10b57cec5SDimitry Andric //===-- CommandLine.cpp - Command line parser implementation --------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This class implements a command line argument processor that is useful when
100b57cec5SDimitry Andric // creating a tool.  It provides a simple, minimalistic interface that is easily
110b57cec5SDimitry Andric // extensible and supports nonlocal (library) command line options.
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // Note that rather than trying to figure out what this code does, you could try
140b57cec5SDimitry Andric // reading the library documentation located in docs/CommandLine.html
150b57cec5SDimitry Andric //
160b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
170b57cec5SDimitry Andric 
180b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
19fe6060f1SDimitry Andric 
20fe6060f1SDimitry Andric #include "DebugOptions.h"
21fe6060f1SDimitry Andric 
220b57cec5SDimitry Andric #include "llvm-c/Support.h"
230b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
2404eeddc0SDimitry Andric #include "llvm/ADT/STLFunctionalExtras.h"
250b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
260b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
270b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
280b57cec5SDimitry Andric #include "llvm/ADT/StringMap.h"
29480093f4SDimitry Andric #include "llvm/ADT/StringRef.h"
300b57cec5SDimitry Andric #include "llvm/ADT/Twine.h"
310b57cec5SDimitry Andric #include "llvm/Config/config.h"
320b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
330b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
34480093f4SDimitry Andric #include "llvm/Support/Error.h"
350b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
360b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
370b57cec5SDimitry Andric #include "llvm/Support/ManagedStatic.h"
380b57cec5SDimitry Andric #include "llvm/Support/MemoryBuffer.h"
390b57cec5SDimitry Andric #include "llvm/Support/Path.h"
400b57cec5SDimitry Andric #include "llvm/Support/Process.h"
410b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h"
42480093f4SDimitry Andric #include "llvm/Support/VirtualFileSystem.h"
430b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
440b57cec5SDimitry Andric #include <cstdlib>
45bdd1243dSDimitry Andric #include <optional>
46480093f4SDimitry Andric #include <string>
470b57cec5SDimitry Andric using namespace llvm;
480b57cec5SDimitry Andric using namespace cl;
490b57cec5SDimitry Andric 
500b57cec5SDimitry Andric #define DEBUG_TYPE "commandline"
510b57cec5SDimitry Andric 
520b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
530b57cec5SDimitry Andric // Template instantiations and anchors.
540b57cec5SDimitry Andric //
550b57cec5SDimitry Andric namespace llvm {
560b57cec5SDimitry Andric namespace cl {
570b57cec5SDimitry Andric template class basic_parser<bool>;
580b57cec5SDimitry Andric template class basic_parser<boolOrDefault>;
590b57cec5SDimitry Andric template class basic_parser<int>;
60480093f4SDimitry Andric template class basic_parser<long>;
61480093f4SDimitry Andric template class basic_parser<long long>;
620b57cec5SDimitry Andric template class basic_parser<unsigned>;
630b57cec5SDimitry Andric template class basic_parser<unsigned long>;
640b57cec5SDimitry Andric template class basic_parser<unsigned long long>;
650b57cec5SDimitry Andric template class basic_parser<double>;
660b57cec5SDimitry Andric template class basic_parser<float>;
670b57cec5SDimitry Andric template class basic_parser<std::string>;
680b57cec5SDimitry Andric template class basic_parser<char>;
690b57cec5SDimitry Andric 
700b57cec5SDimitry Andric template class opt<unsigned>;
710b57cec5SDimitry Andric template class opt<int>;
720b57cec5SDimitry Andric template class opt<std::string>;
730b57cec5SDimitry Andric template class opt<char>;
740b57cec5SDimitry Andric template class opt<bool>;
75fe6060f1SDimitry Andric } // namespace cl
76fe6060f1SDimitry Andric } // namespace llvm
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric // Pin the vtables to this file.
anchor()790b57cec5SDimitry Andric void GenericOptionValue::anchor() {}
anchor()800b57cec5SDimitry Andric void OptionValue<boolOrDefault>::anchor() {}
anchor()810b57cec5SDimitry Andric void OptionValue<std::string>::anchor() {}
anchor()820b57cec5SDimitry Andric void Option::anchor() {}
anchor()830b57cec5SDimitry Andric void basic_parser_impl::anchor() {}
anchor()840b57cec5SDimitry Andric void parser<bool>::anchor() {}
anchor()850b57cec5SDimitry Andric void parser<boolOrDefault>::anchor() {}
anchor()860b57cec5SDimitry Andric void parser<int>::anchor() {}
anchor()87480093f4SDimitry Andric void parser<long>::anchor() {}
anchor()88480093f4SDimitry Andric void parser<long long>::anchor() {}
anchor()890b57cec5SDimitry Andric void parser<unsigned>::anchor() {}
anchor()900b57cec5SDimitry Andric void parser<unsigned long>::anchor() {}
anchor()910b57cec5SDimitry Andric void parser<unsigned long long>::anchor() {}
anchor()920b57cec5SDimitry Andric void parser<double>::anchor() {}
anchor()930b57cec5SDimitry Andric void parser<float>::anchor() {}
anchor()940b57cec5SDimitry Andric void parser<std::string>::anchor() {}
anchor()950b57cec5SDimitry Andric void parser<char>::anchor() {}
960b57cec5SDimitry Andric 
970b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
980b57cec5SDimitry Andric 
99480093f4SDimitry Andric const static size_t DefaultPad = 2;
100480093f4SDimitry Andric 
1010b57cec5SDimitry Andric static StringRef ArgPrefix = "-";
1020b57cec5SDimitry Andric static StringRef ArgPrefixLong = "--";
1030b57cec5SDimitry Andric static StringRef ArgHelpPrefix = " - ";
1040b57cec5SDimitry Andric 
argPlusPrefixesSize(StringRef ArgName,size_t Pad=DefaultPad)105480093f4SDimitry Andric static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
1060b57cec5SDimitry Andric   size_t Len = ArgName.size();
1070b57cec5SDimitry Andric   if (Len == 1)
108480093f4SDimitry Andric     return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
109480093f4SDimitry Andric   return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
1100b57cec5SDimitry Andric }
1110b57cec5SDimitry Andric 
argPrefix(StringRef ArgName,size_t Pad=DefaultPad)112480093f4SDimitry Andric static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
113480093f4SDimitry Andric   SmallString<8> Prefix;
114480093f4SDimitry Andric   for (size_t I = 0; I < Pad; ++I) {
115480093f4SDimitry Andric     Prefix.push_back(' ');
116480093f4SDimitry Andric   }
117480093f4SDimitry Andric   Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
118480093f4SDimitry Andric   return Prefix;
1190b57cec5SDimitry Andric }
1200b57cec5SDimitry Andric 
1210b57cec5SDimitry Andric // Option predicates...
isGrouping(const Option * O)1220b57cec5SDimitry Andric static inline bool isGrouping(const Option *O) {
1230b57cec5SDimitry Andric   return O->getMiscFlags() & cl::Grouping;
1240b57cec5SDimitry Andric }
isPrefixedOrGrouping(const Option * O)1250b57cec5SDimitry Andric static inline bool isPrefixedOrGrouping(const Option *O) {
1260b57cec5SDimitry Andric   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
1270b57cec5SDimitry Andric          O->getFormattingFlag() == cl::AlwaysPrefix;
1280b57cec5SDimitry Andric }
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric 
1310b57cec5SDimitry Andric namespace {
1320b57cec5SDimitry Andric 
1330b57cec5SDimitry Andric class PrintArg {
1340b57cec5SDimitry Andric   StringRef ArgName;
135480093f4SDimitry Andric   size_t Pad;
1360b57cec5SDimitry Andric public:
PrintArg(StringRef ArgName,size_t Pad=DefaultPad)137480093f4SDimitry Andric   PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
1380b57cec5SDimitry Andric   friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
1390b57cec5SDimitry Andric };
1400b57cec5SDimitry Andric 
operator <<(raw_ostream & OS,const PrintArg & Arg)1410b57cec5SDimitry Andric raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
142480093f4SDimitry Andric   OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
1430b57cec5SDimitry Andric   return OS;
1440b57cec5SDimitry Andric }
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric class CommandLineParser {
1470b57cec5SDimitry Andric public:
1480b57cec5SDimitry Andric   // Globals for name and overview of program.  Program name is not a string to
1490b57cec5SDimitry Andric   // avoid static ctor/dtor issues.
1500b57cec5SDimitry Andric   std::string ProgramName;
1510b57cec5SDimitry Andric   StringRef ProgramOverview;
1520b57cec5SDimitry Andric 
1530b57cec5SDimitry Andric   // This collects additional help to be printed.
1540b57cec5SDimitry Andric   std::vector<StringRef> MoreHelp;
1550b57cec5SDimitry Andric 
1560b57cec5SDimitry Andric   // This collects Options added with the cl::DefaultOption flag. Since they can
1570b57cec5SDimitry Andric   // be overridden, they are not added to the appropriate SubCommands until
1580b57cec5SDimitry Andric   // ParseCommandLineOptions actually runs.
1590b57cec5SDimitry Andric   SmallVector<Option*, 4> DefaultOptions;
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   // This collects the different option categories that have been registered.
1620b57cec5SDimitry Andric   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric   // This collects the different subcommands that have been registered.
1650b57cec5SDimitry Andric   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
1660b57cec5SDimitry Andric 
CommandLineParser()1677a6dacacSDimitry Andric   CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   void ResetAllOptionOccurrences();
1700b57cec5SDimitry Andric 
1710b57cec5SDimitry Andric   bool ParseCommandLineOptions(int argc, const char *const *argv,
1720b57cec5SDimitry Andric                                StringRef Overview, raw_ostream *Errs = nullptr,
1730b57cec5SDimitry Andric                                bool LongOptionsUseDoubleDash = false);
1740b57cec5SDimitry Andric 
forEachSubCommand(Option & Opt,function_ref<void (SubCommand &)> Action)175cb14a3feSDimitry Andric   void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) {
176cb14a3feSDimitry Andric     if (Opt.Subs.empty()) {
177cb14a3feSDimitry Andric       Action(SubCommand::getTopLevel());
178cb14a3feSDimitry Andric       return;
179cb14a3feSDimitry Andric     }
180cb14a3feSDimitry Andric     if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) {
181cb14a3feSDimitry Andric       for (auto *SC : RegisteredSubCommands)
182cb14a3feSDimitry Andric         Action(*SC);
1837a6dacacSDimitry Andric       Action(SubCommand::getAll());
184cb14a3feSDimitry Andric       return;
185cb14a3feSDimitry Andric     }
186cb14a3feSDimitry Andric     for (auto *SC : Opt.Subs) {
187cb14a3feSDimitry Andric       assert(SC != &SubCommand::getAll() &&
188cb14a3feSDimitry Andric              "SubCommand::getAll() should not be used with other subcommands");
189cb14a3feSDimitry Andric       Action(*SC);
190cb14a3feSDimitry Andric     }
191cb14a3feSDimitry Andric   }
192cb14a3feSDimitry Andric 
addLiteralOption(Option & Opt,SubCommand * SC,StringRef Name)1930b57cec5SDimitry Andric   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
1940b57cec5SDimitry Andric     if (Opt.hasArgStr())
1950b57cec5SDimitry Andric       return;
1960b57cec5SDimitry Andric     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
1970b57cec5SDimitry Andric       errs() << ProgramName << ": CommandLine Error: Option '" << Name
1980b57cec5SDimitry Andric              << "' registered more than once!\n";
1990b57cec5SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
2000b57cec5SDimitry Andric     }
2010b57cec5SDimitry Andric   }
2020b57cec5SDimitry Andric 
addLiteralOption(Option & Opt,StringRef Name)2030b57cec5SDimitry Andric   void addLiteralOption(Option &Opt, StringRef Name) {
204cb14a3feSDimitry Andric     forEachSubCommand(
205cb14a3feSDimitry Andric         Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
2060b57cec5SDimitry Andric   }
2070b57cec5SDimitry Andric 
addOption(Option * O,SubCommand * SC)2080b57cec5SDimitry Andric   void addOption(Option *O, SubCommand *SC) {
2090b57cec5SDimitry Andric     bool HadErrors = false;
2100b57cec5SDimitry Andric     if (O->hasArgStr()) {
2110b57cec5SDimitry Andric       // If it's a DefaultOption, check to make sure it isn't already there.
21206c3fb27SDimitry Andric       if (O->isDefaultOption() && SC->OptionsMap.contains(O->ArgStr))
2130b57cec5SDimitry Andric         return;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric       // Add argument to the argument map!
2160b57cec5SDimitry Andric       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
2170b57cec5SDimitry Andric         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
2180b57cec5SDimitry Andric                << "' registered more than once!\n";
2190b57cec5SDimitry Andric         HadErrors = true;
2200b57cec5SDimitry Andric       }
2210b57cec5SDimitry Andric     }
2220b57cec5SDimitry Andric 
2230b57cec5SDimitry Andric     // Remember information about positional options.
2240b57cec5SDimitry Andric     if (O->getFormattingFlag() == cl::Positional)
2250b57cec5SDimitry Andric       SC->PositionalOpts.push_back(O);
2260b57cec5SDimitry Andric     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
2270b57cec5SDimitry Andric       SC->SinkOpts.push_back(O);
2280b57cec5SDimitry Andric     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
2290b57cec5SDimitry Andric       if (SC->ConsumeAfterOpt) {
2300b57cec5SDimitry Andric         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
2310b57cec5SDimitry Andric         HadErrors = true;
2320b57cec5SDimitry Andric       }
2330b57cec5SDimitry Andric       SC->ConsumeAfterOpt = O;
2340b57cec5SDimitry Andric     }
2350b57cec5SDimitry Andric 
2360b57cec5SDimitry Andric     // Fail hard if there were errors. These are strictly unrecoverable and
2370b57cec5SDimitry Andric     // indicate serious issues such as conflicting option names or an
2380b57cec5SDimitry Andric     // incorrectly
2390b57cec5SDimitry Andric     // linked LLVM distribution.
2400b57cec5SDimitry Andric     if (HadErrors)
2410b57cec5SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
2420b57cec5SDimitry Andric   }
2430b57cec5SDimitry Andric 
addOption(Option * O,bool ProcessDefaultOption=false)2440b57cec5SDimitry Andric   void addOption(Option *O, bool ProcessDefaultOption = false) {
2450b57cec5SDimitry Andric     if (!ProcessDefaultOption && O->isDefaultOption()) {
2460b57cec5SDimitry Andric       DefaultOptions.push_back(O);
2470b57cec5SDimitry Andric       return;
2480b57cec5SDimitry Andric     }
249cb14a3feSDimitry Andric     forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &SC); });
2500b57cec5SDimitry Andric   }
2510b57cec5SDimitry Andric 
removeOption(Option * O,SubCommand * SC)2520b57cec5SDimitry Andric   void removeOption(Option *O, SubCommand *SC) {
2530b57cec5SDimitry Andric     SmallVector<StringRef, 16> OptionNames;
2540b57cec5SDimitry Andric     O->getExtraOptionNames(OptionNames);
2550b57cec5SDimitry Andric     if (O->hasArgStr())
2560b57cec5SDimitry Andric       OptionNames.push_back(O->ArgStr);
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric     SubCommand &Sub = *SC;
2590b57cec5SDimitry Andric     auto End = Sub.OptionsMap.end();
2600b57cec5SDimitry Andric     for (auto Name : OptionNames) {
2610b57cec5SDimitry Andric       auto I = Sub.OptionsMap.find(Name);
2620b57cec5SDimitry Andric       if (I != End && I->getValue() == O)
2630b57cec5SDimitry Andric         Sub.OptionsMap.erase(I);
2640b57cec5SDimitry Andric     }
2650b57cec5SDimitry Andric 
2660b57cec5SDimitry Andric     if (O->getFormattingFlag() == cl::Positional)
267fe6060f1SDimitry Andric       for (auto *Opt = Sub.PositionalOpts.begin();
2680b57cec5SDimitry Andric            Opt != Sub.PositionalOpts.end(); ++Opt) {
2690b57cec5SDimitry Andric         if (*Opt == O) {
2700b57cec5SDimitry Andric           Sub.PositionalOpts.erase(Opt);
2710b57cec5SDimitry Andric           break;
2720b57cec5SDimitry Andric         }
2730b57cec5SDimitry Andric       }
2740b57cec5SDimitry Andric     else if (O->getMiscFlags() & cl::Sink)
275fe6060f1SDimitry Andric       for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
2760b57cec5SDimitry Andric         if (*Opt == O) {
2770b57cec5SDimitry Andric           Sub.SinkOpts.erase(Opt);
2780b57cec5SDimitry Andric           break;
2790b57cec5SDimitry Andric         }
2800b57cec5SDimitry Andric       }
2810b57cec5SDimitry Andric     else if (O == Sub.ConsumeAfterOpt)
2820b57cec5SDimitry Andric       Sub.ConsumeAfterOpt = nullptr;
2830b57cec5SDimitry Andric   }
2840b57cec5SDimitry Andric 
removeOption(Option * O)2850b57cec5SDimitry Andric   void removeOption(Option *O) {
286cb14a3feSDimitry Andric     forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &SC); });
2870b57cec5SDimitry Andric   }
2880b57cec5SDimitry Andric 
hasOptions(const SubCommand & Sub) const2890b57cec5SDimitry Andric   bool hasOptions(const SubCommand &Sub) const {
2900b57cec5SDimitry Andric     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
2910b57cec5SDimitry Andric             nullptr != Sub.ConsumeAfterOpt);
2920b57cec5SDimitry Andric   }
2930b57cec5SDimitry Andric 
hasOptions() const2940b57cec5SDimitry Andric   bool hasOptions() const {
295480093f4SDimitry Andric     for (const auto *S : RegisteredSubCommands) {
2960b57cec5SDimitry Andric       if (hasOptions(*S))
2970b57cec5SDimitry Andric         return true;
2980b57cec5SDimitry Andric     }
2990b57cec5SDimitry Andric     return false;
3000b57cec5SDimitry Andric   }
3010b57cec5SDimitry Andric 
hasNamedSubCommands() const3025f757f3fSDimitry Andric   bool hasNamedSubCommands() const {
3035f757f3fSDimitry Andric     for (const auto *S : RegisteredSubCommands)
3045f757f3fSDimitry Andric       if (!S->getName().empty())
3055f757f3fSDimitry Andric         return true;
3065f757f3fSDimitry Andric     return false;
3075f757f3fSDimitry Andric   }
3085f757f3fSDimitry Andric 
getActiveSubCommand()3090b57cec5SDimitry Andric   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
3100b57cec5SDimitry Andric 
updateArgStr(Option * O,StringRef NewName,SubCommand * SC)3110b57cec5SDimitry Andric   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
3120b57cec5SDimitry Andric     SubCommand &Sub = *SC;
3130b57cec5SDimitry Andric     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
3140b57cec5SDimitry Andric       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
3150b57cec5SDimitry Andric              << "' registered more than once!\n";
3160b57cec5SDimitry Andric       report_fatal_error("inconsistency in registered CommandLine options");
3170b57cec5SDimitry Andric     }
3180b57cec5SDimitry Andric     Sub.OptionsMap.erase(O->ArgStr);
3190b57cec5SDimitry Andric   }
3200b57cec5SDimitry Andric 
updateArgStr(Option * O,StringRef NewName)3210b57cec5SDimitry Andric   void updateArgStr(Option *O, StringRef NewName) {
322cb14a3feSDimitry Andric     forEachSubCommand(*O,
323cb14a3feSDimitry Andric                       [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
3240b57cec5SDimitry Andric   }
3250b57cec5SDimitry Andric 
3260b57cec5SDimitry Andric   void printOptionValues();
3270b57cec5SDimitry Andric 
registerCategory(OptionCategory * cat)3280b57cec5SDimitry Andric   void registerCategory(OptionCategory *cat) {
3290b57cec5SDimitry Andric     assert(count_if(RegisteredOptionCategories,
3300b57cec5SDimitry Andric                     [cat](const OptionCategory *Category) {
3310b57cec5SDimitry Andric              return cat->getName() == Category->getName();
3320b57cec5SDimitry Andric            }) == 0 &&
3330b57cec5SDimitry Andric            "Duplicate option categories");
3340b57cec5SDimitry Andric 
3350b57cec5SDimitry Andric     RegisteredOptionCategories.insert(cat);
3360b57cec5SDimitry Andric   }
3370b57cec5SDimitry Andric 
registerSubCommand(SubCommand * sub)3380b57cec5SDimitry Andric   void registerSubCommand(SubCommand *sub) {
3390b57cec5SDimitry Andric     assert(count_if(RegisteredSubCommands,
3400b57cec5SDimitry Andric                     [sub](const SubCommand *Sub) {
3410b57cec5SDimitry Andric                       return (!sub->getName().empty()) &&
3420b57cec5SDimitry Andric                              (Sub->getName() == sub->getName());
3430b57cec5SDimitry Andric                     }) == 0 &&
3440b57cec5SDimitry Andric            "Duplicate subcommands");
3450b57cec5SDimitry Andric     RegisteredSubCommands.insert(sub);
3460b57cec5SDimitry Andric 
3470b57cec5SDimitry Andric     // For all options that have been registered for all subcommands, add the
3480b57cec5SDimitry Andric     // option to this subcommand now.
3497a6dacacSDimitry Andric     assert(sub != &SubCommand::getAll() &&
3507a6dacacSDimitry Andric            "SubCommand::getAll() should not be registered");
351bdd1243dSDimitry Andric     for (auto &E : SubCommand::getAll().OptionsMap) {
3520b57cec5SDimitry Andric       Option *O = E.second;
3530b57cec5SDimitry Andric       if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
3540b57cec5SDimitry Andric           O->hasArgStr())
3550b57cec5SDimitry Andric         addOption(O, sub);
3560b57cec5SDimitry Andric       else
3570b57cec5SDimitry Andric         addLiteralOption(*O, sub, E.first());
3580b57cec5SDimitry Andric     }
3590b57cec5SDimitry Andric   }
3600b57cec5SDimitry Andric 
unregisterSubCommand(SubCommand * sub)3610b57cec5SDimitry Andric   void unregisterSubCommand(SubCommand *sub) {
3620b57cec5SDimitry Andric     RegisteredSubCommands.erase(sub);
3630b57cec5SDimitry Andric   }
3640b57cec5SDimitry Andric 
3650b57cec5SDimitry Andric   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()3660b57cec5SDimitry Andric   getRegisteredSubcommands() {
3670b57cec5SDimitry Andric     return make_range(RegisteredSubCommands.begin(),
3680b57cec5SDimitry Andric                       RegisteredSubCommands.end());
3690b57cec5SDimitry Andric   }
3700b57cec5SDimitry Andric 
reset()3710b57cec5SDimitry Andric   void reset() {
3720b57cec5SDimitry Andric     ActiveSubCommand = nullptr;
3730b57cec5SDimitry Andric     ProgramName.clear();
3740b57cec5SDimitry Andric     ProgramOverview = StringRef();
3750b57cec5SDimitry Andric 
3760b57cec5SDimitry Andric     MoreHelp.clear();
3770b57cec5SDimitry Andric     RegisteredOptionCategories.clear();
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric     ResetAllOptionOccurrences();
3800b57cec5SDimitry Andric     RegisteredSubCommands.clear();
3810b57cec5SDimitry Andric 
382bdd1243dSDimitry Andric     SubCommand::getTopLevel().reset();
383bdd1243dSDimitry Andric     SubCommand::getAll().reset();
384bdd1243dSDimitry Andric     registerSubCommand(&SubCommand::getTopLevel());
3850b57cec5SDimitry Andric 
3860b57cec5SDimitry Andric     DefaultOptions.clear();
3870b57cec5SDimitry Andric   }
3880b57cec5SDimitry Andric 
3890b57cec5SDimitry Andric private:
39081ad6265SDimitry Andric   SubCommand *ActiveSubCommand = nullptr;
3910b57cec5SDimitry Andric 
3920b57cec5SDimitry Andric   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
LookupLongOption(SubCommand & Sub,StringRef & Arg,StringRef & Value,bool LongOptionsUseDoubleDash,bool HaveDoubleDash)3930b57cec5SDimitry Andric   Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
3940b57cec5SDimitry Andric                            bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
3950b57cec5SDimitry Andric     Option *Opt = LookupOption(Sub, Arg, Value);
3960b57cec5SDimitry Andric     if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
3970b57cec5SDimitry Andric       return nullptr;
3980b57cec5SDimitry Andric     return Opt;
3990b57cec5SDimitry Andric   }
4005f757f3fSDimitry Andric   SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
4010b57cec5SDimitry Andric };
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric } // namespace
4040b57cec5SDimitry Andric 
4050b57cec5SDimitry Andric static ManagedStatic<CommandLineParser> GlobalParser;
4060b57cec5SDimitry Andric 
AddLiteralOption(Option & O,StringRef Name)4070b57cec5SDimitry Andric void cl::AddLiteralOption(Option &O, StringRef Name) {
4080b57cec5SDimitry Andric   GlobalParser->addLiteralOption(O, Name);
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
extrahelp(StringRef Help)4110b57cec5SDimitry Andric extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
4120b57cec5SDimitry Andric   GlobalParser->MoreHelp.push_back(Help);
4130b57cec5SDimitry Andric }
4140b57cec5SDimitry Andric 
addArgument()4150b57cec5SDimitry Andric void Option::addArgument() {
4160b57cec5SDimitry Andric   GlobalParser->addOption(this);
4170b57cec5SDimitry Andric   FullyInitialized = true;
4180b57cec5SDimitry Andric }
4190b57cec5SDimitry Andric 
removeArgument()4200b57cec5SDimitry Andric void Option::removeArgument() { GlobalParser->removeOption(this); }
4210b57cec5SDimitry Andric 
setArgStr(StringRef S)4220b57cec5SDimitry Andric void Option::setArgStr(StringRef S) {
4230b57cec5SDimitry Andric   if (FullyInitialized)
4240b57cec5SDimitry Andric     GlobalParser->updateArgStr(this, S);
4250b57cec5SDimitry Andric   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
4260b57cec5SDimitry Andric   ArgStr = S;
4270b57cec5SDimitry Andric   if (ArgStr.size() == 1)
4280b57cec5SDimitry Andric     setMiscFlag(Grouping);
4290b57cec5SDimitry Andric }
4300b57cec5SDimitry Andric 
addCategory(OptionCategory & C)4310b57cec5SDimitry Andric void Option::addCategory(OptionCategory &C) {
4320b57cec5SDimitry Andric   assert(!Categories.empty() && "Categories cannot be empty.");
4330b57cec5SDimitry Andric   // Maintain backward compatibility by replacing the default GeneralCategory
4340b57cec5SDimitry Andric   // if it's still set.  Otherwise, just add the new one.  The GeneralCategory
4350b57cec5SDimitry Andric   // must be explicitly added if you want multiple categories that include it.
436fe6060f1SDimitry Andric   if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
4370b57cec5SDimitry Andric     Categories[0] = &C;
438e8d8bef9SDimitry Andric   else if (!is_contained(Categories, &C))
4390b57cec5SDimitry Andric     Categories.push_back(&C);
4400b57cec5SDimitry Andric }
4410b57cec5SDimitry Andric 
reset()4420b57cec5SDimitry Andric void Option::reset() {
4430b57cec5SDimitry Andric   NumOccurrences = 0;
4440b57cec5SDimitry Andric   setDefault();
4450b57cec5SDimitry Andric   if (isDefaultOption())
4460b57cec5SDimitry Andric     removeArgument();
4470b57cec5SDimitry Andric }
4480b57cec5SDimitry Andric 
registerCategory()4490b57cec5SDimitry Andric void OptionCategory::registerCategory() {
4500b57cec5SDimitry Andric   GlobalParser->registerCategory(this);
4510b57cec5SDimitry Andric }
4520b57cec5SDimitry Andric 
4530b57cec5SDimitry Andric // A special subcommand representing no subcommand. It is particularly important
4540b57cec5SDimitry Andric // that this ManagedStatic uses constant initailization and not dynamic
4550b57cec5SDimitry Andric // initialization because it is referenced from cl::opt constructors, which run
4560b57cec5SDimitry Andric // dynamically in an arbitrary order.
4570b57cec5SDimitry Andric LLVM_REQUIRE_CONSTANT_INITIALIZATION
4580b57cec5SDimitry Andric ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
4590b57cec5SDimitry Andric 
4600b57cec5SDimitry Andric // A special subcommand that can be used to put an option into all subcommands.
4610b57cec5SDimitry Andric ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
4620b57cec5SDimitry Andric 
getTopLevel()463bdd1243dSDimitry Andric SubCommand &SubCommand::getTopLevel() { return *TopLevelSubCommand; }
464bdd1243dSDimitry Andric 
getAll()465bdd1243dSDimitry Andric SubCommand &SubCommand::getAll() { return *AllSubCommands; }
466bdd1243dSDimitry Andric 
registerSubCommand()4670b57cec5SDimitry Andric void SubCommand::registerSubCommand() {
4680b57cec5SDimitry Andric   GlobalParser->registerSubCommand(this);
4690b57cec5SDimitry Andric }
4700b57cec5SDimitry Andric 
unregisterSubCommand()4710b57cec5SDimitry Andric void SubCommand::unregisterSubCommand() {
4720b57cec5SDimitry Andric   GlobalParser->unregisterSubCommand(this);
4730b57cec5SDimitry Andric }
4740b57cec5SDimitry Andric 
reset()4750b57cec5SDimitry Andric void SubCommand::reset() {
4760b57cec5SDimitry Andric   PositionalOpts.clear();
4770b57cec5SDimitry Andric   SinkOpts.clear();
4780b57cec5SDimitry Andric   OptionsMap.clear();
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   ConsumeAfterOpt = nullptr;
4810b57cec5SDimitry Andric }
4820b57cec5SDimitry Andric 
operator bool() const4830b57cec5SDimitry Andric SubCommand::operator bool() const {
4840b57cec5SDimitry Andric   return (GlobalParser->getActiveSubCommand() == this);
4850b57cec5SDimitry Andric }
4860b57cec5SDimitry Andric 
4870b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
4880b57cec5SDimitry Andric // Basic, shared command line option processing machinery.
4890b57cec5SDimitry Andric //
4900b57cec5SDimitry Andric 
4910b57cec5SDimitry Andric /// LookupOption - Lookup the option specified by the specified option on the
4920b57cec5SDimitry Andric /// command line.  If there is a value specified (after an equal sign) return
4930b57cec5SDimitry Andric /// that as well.  This assumes that leading dashes have already been stripped.
LookupOption(SubCommand & Sub,StringRef & Arg,StringRef & Value)4940b57cec5SDimitry Andric Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
4950b57cec5SDimitry Andric                                         StringRef &Value) {
4960b57cec5SDimitry Andric   // Reject all dashes.
4970b57cec5SDimitry Andric   if (Arg.empty())
4980b57cec5SDimitry Andric     return nullptr;
499bdd1243dSDimitry Andric   assert(&Sub != &SubCommand::getAll());
5000b57cec5SDimitry Andric 
5010b57cec5SDimitry Andric   size_t EqualPos = Arg.find('=');
5020b57cec5SDimitry Andric 
5030b57cec5SDimitry Andric   // If we have an equals sign, remember the value.
5040b57cec5SDimitry Andric   if (EqualPos == StringRef::npos) {
5050b57cec5SDimitry Andric     // Look up the option.
506e8d8bef9SDimitry Andric     return Sub.OptionsMap.lookup(Arg);
5070b57cec5SDimitry Andric   }
5080b57cec5SDimitry Andric 
5090b57cec5SDimitry Andric   // If the argument before the = is a valid option name and the option allows
5100b57cec5SDimitry Andric   // non-prefix form (ie is not AlwaysPrefix), we match.  If not, signal match
5110b57cec5SDimitry Andric   // failure by returning nullptr.
5120b57cec5SDimitry Andric   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
5130b57cec5SDimitry Andric   if (I == Sub.OptionsMap.end())
5140b57cec5SDimitry Andric     return nullptr;
5150b57cec5SDimitry Andric 
516fe6060f1SDimitry Andric   auto *O = I->second;
5170b57cec5SDimitry Andric   if (O->getFormattingFlag() == cl::AlwaysPrefix)
5180b57cec5SDimitry Andric     return nullptr;
5190b57cec5SDimitry Andric 
5200b57cec5SDimitry Andric   Value = Arg.substr(EqualPos + 1);
5210b57cec5SDimitry Andric   Arg = Arg.substr(0, EqualPos);
5220b57cec5SDimitry Andric   return I->second;
5230b57cec5SDimitry Andric }
5240b57cec5SDimitry Andric 
LookupSubCommand(StringRef Name,std::string & NearestString)5255f757f3fSDimitry Andric SubCommand *CommandLineParser::LookupSubCommand(StringRef Name,
5265f757f3fSDimitry Andric                                                 std::string &NearestString) {
5270b57cec5SDimitry Andric   if (Name.empty())
528bdd1243dSDimitry Andric     return &SubCommand::getTopLevel();
5295f757f3fSDimitry Andric   // Find a subcommand with the edit distance == 1.
5305f757f3fSDimitry Andric   SubCommand *NearestMatch = nullptr;
531fe6060f1SDimitry Andric   for (auto *S : RegisteredSubCommands) {
5327a6dacacSDimitry Andric     assert(S != &SubCommand::getAll() &&
5337a6dacacSDimitry Andric            "SubCommand::getAll() is not expected in RegisteredSubCommands");
5340b57cec5SDimitry Andric     if (S->getName().empty())
5350b57cec5SDimitry Andric       continue;
5360b57cec5SDimitry Andric 
5370b57cec5SDimitry Andric     if (StringRef(S->getName()) == StringRef(Name))
5380b57cec5SDimitry Andric       return S;
5395f757f3fSDimitry Andric 
5405f757f3fSDimitry Andric     if (!NearestMatch && S->getName().edit_distance(Name) < 2)
5415f757f3fSDimitry Andric       NearestMatch = S;
5420b57cec5SDimitry Andric   }
5435f757f3fSDimitry Andric 
5445f757f3fSDimitry Andric   if (NearestMatch)
5455f757f3fSDimitry Andric     NearestString = NearestMatch->getName();
5465f757f3fSDimitry Andric 
547bdd1243dSDimitry Andric   return &SubCommand::getTopLevel();
5480b57cec5SDimitry Andric }
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric /// LookupNearestOption - Lookup the closest match to the option specified by
5510b57cec5SDimitry Andric /// the specified option on the command line.  If there is a value specified
5520b57cec5SDimitry Andric /// (after an equal sign) return that as well.  This assumes that leading dashes
5530b57cec5SDimitry Andric /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)5540b57cec5SDimitry Andric static Option *LookupNearestOption(StringRef Arg,
5550b57cec5SDimitry Andric                                    const StringMap<Option *> &OptionsMap,
5560b57cec5SDimitry Andric                                    std::string &NearestString) {
5570b57cec5SDimitry Andric   // Reject all dashes.
5580b57cec5SDimitry Andric   if (Arg.empty())
5590b57cec5SDimitry Andric     return nullptr;
5600b57cec5SDimitry Andric 
5610b57cec5SDimitry Andric   // Split on any equal sign.
5620b57cec5SDimitry Andric   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
5630b57cec5SDimitry Andric   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
5640b57cec5SDimitry Andric   StringRef &RHS = SplitArg.second;
5650b57cec5SDimitry Andric 
5660b57cec5SDimitry Andric   // Find the closest match.
5670b57cec5SDimitry Andric   Option *Best = nullptr;
5680b57cec5SDimitry Andric   unsigned BestDistance = 0;
5690b57cec5SDimitry Andric   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
5700b57cec5SDimitry Andric                                            ie = OptionsMap.end();
5710b57cec5SDimitry Andric        it != ie; ++it) {
5720b57cec5SDimitry Andric     Option *O = it->second;
5735ffd83dbSDimitry Andric     // Do not suggest really hidden options (not shown in any help).
5745ffd83dbSDimitry Andric     if (O->getOptionHiddenFlag() == ReallyHidden)
5755ffd83dbSDimitry Andric       continue;
5765ffd83dbSDimitry Andric 
5770b57cec5SDimitry Andric     SmallVector<StringRef, 16> OptionNames;
5780b57cec5SDimitry Andric     O->getExtraOptionNames(OptionNames);
5790b57cec5SDimitry Andric     if (O->hasArgStr())
5800b57cec5SDimitry Andric       OptionNames.push_back(O->ArgStr);
5810b57cec5SDimitry Andric 
5820b57cec5SDimitry Andric     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
5830b57cec5SDimitry Andric     StringRef Flag = PermitValue ? LHS : Arg;
584fe6060f1SDimitry Andric     for (const auto &Name : OptionNames) {
5850b57cec5SDimitry Andric       unsigned Distance = StringRef(Name).edit_distance(
5860b57cec5SDimitry Andric           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
5870b57cec5SDimitry Andric       if (!Best || Distance < BestDistance) {
5880b57cec5SDimitry Andric         Best = O;
5890b57cec5SDimitry Andric         BestDistance = Distance;
5900b57cec5SDimitry Andric         if (RHS.empty() || !PermitValue)
5915ffd83dbSDimitry Andric           NearestString = std::string(Name);
5920b57cec5SDimitry Andric         else
5930b57cec5SDimitry Andric           NearestString = (Twine(Name) + "=" + RHS).str();
5940b57cec5SDimitry Andric       }
5950b57cec5SDimitry Andric     }
5960b57cec5SDimitry Andric   }
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric   return Best;
5990b57cec5SDimitry Andric }
6000b57cec5SDimitry Andric 
6010b57cec5SDimitry Andric /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
6020b57cec5SDimitry Andric /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)6030b57cec5SDimitry Andric static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
6040b57cec5SDimitry Andric                                           StringRef ArgName, StringRef Value,
6050b57cec5SDimitry Andric                                           bool MultiArg = false) {
6060b57cec5SDimitry Andric   // Check to see if this option accepts a comma separated list of values.  If
6070b57cec5SDimitry Andric   // it does, we have to split up the value into multiple values.
6080b57cec5SDimitry Andric   if (Handler->getMiscFlags() & CommaSeparated) {
6090b57cec5SDimitry Andric     StringRef Val(Value);
6100b57cec5SDimitry Andric     StringRef::size_type Pos = Val.find(',');
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric     while (Pos != StringRef::npos) {
6130b57cec5SDimitry Andric       // Process the portion before the comma.
6140b57cec5SDimitry Andric       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
6150b57cec5SDimitry Andric         return true;
6160b57cec5SDimitry Andric       // Erase the portion before the comma, AND the comma.
6170b57cec5SDimitry Andric       Val = Val.substr(Pos + 1);
6180b57cec5SDimitry Andric       // Check for another comma.
6190b57cec5SDimitry Andric       Pos = Val.find(',');
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric     Value = Val;
6230b57cec5SDimitry Andric   }
6240b57cec5SDimitry Andric 
6250b57cec5SDimitry Andric   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
6260b57cec5SDimitry Andric }
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric /// ProvideOption - For Value, this differentiates between an empty value ("")
6290b57cec5SDimitry Andric /// and a null value (StringRef()).  The later is accepted for arguments that
6300b57cec5SDimitry Andric /// don't allow a value (-foo) the former is rejected (-foo=).
ProvideOption(Option * Handler,StringRef ArgName,StringRef Value,int argc,const char * const * argv,int & i)6310b57cec5SDimitry Andric static inline bool ProvideOption(Option *Handler, StringRef ArgName,
6320b57cec5SDimitry Andric                                  StringRef Value, int argc,
6330b57cec5SDimitry Andric                                  const char *const *argv, int &i) {
6340b57cec5SDimitry Andric   // Is this a multi-argument option?
6350b57cec5SDimitry Andric   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
6360b57cec5SDimitry Andric 
6370b57cec5SDimitry Andric   // Enforce value requirements
6380b57cec5SDimitry Andric   switch (Handler->getValueExpectedFlag()) {
6390b57cec5SDimitry Andric   case ValueRequired:
6400b57cec5SDimitry Andric     if (!Value.data()) { // No value specified?
6410b57cec5SDimitry Andric       // If no other argument or the option only supports prefix form, we
6420b57cec5SDimitry Andric       // cannot look at the next argument.
6430b57cec5SDimitry Andric       if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
6440b57cec5SDimitry Andric         return Handler->error("requires a value!");
6450b57cec5SDimitry Andric       // Steal the next argument, like for '-o filename'
6460b57cec5SDimitry Andric       assert(argv && "null check");
6470b57cec5SDimitry Andric       Value = StringRef(argv[++i]);
6480b57cec5SDimitry Andric     }
6490b57cec5SDimitry Andric     break;
6500b57cec5SDimitry Andric   case ValueDisallowed:
6510b57cec5SDimitry Andric     if (NumAdditionalVals > 0)
6520b57cec5SDimitry Andric       return Handler->error("multi-valued option specified"
6530b57cec5SDimitry Andric                             " with ValueDisallowed modifier!");
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric     if (Value.data())
6560b57cec5SDimitry Andric       return Handler->error("does not allow a value! '" + Twine(Value) +
6570b57cec5SDimitry Andric                             "' specified.");
6580b57cec5SDimitry Andric     break;
6590b57cec5SDimitry Andric   case ValueOptional:
6600b57cec5SDimitry Andric     break;
6610b57cec5SDimitry Andric   }
6620b57cec5SDimitry Andric 
6630b57cec5SDimitry Andric   // If this isn't a multi-arg option, just run the handler.
6640b57cec5SDimitry Andric   if (NumAdditionalVals == 0)
6650b57cec5SDimitry Andric     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
6660b57cec5SDimitry Andric 
6670b57cec5SDimitry Andric   // If it is, run the handle several times.
6680b57cec5SDimitry Andric   bool MultiArg = false;
6690b57cec5SDimitry Andric 
6700b57cec5SDimitry Andric   if (Value.data()) {
6710b57cec5SDimitry Andric     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
6720b57cec5SDimitry Andric       return true;
6730b57cec5SDimitry Andric     --NumAdditionalVals;
6740b57cec5SDimitry Andric     MultiArg = true;
6750b57cec5SDimitry Andric   }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric   while (NumAdditionalVals > 0) {
6780b57cec5SDimitry Andric     if (i + 1 >= argc)
6790b57cec5SDimitry Andric       return Handler->error("not enough values!");
6800b57cec5SDimitry Andric     assert(argv && "null check");
6810b57cec5SDimitry Andric     Value = StringRef(argv[++i]);
6820b57cec5SDimitry Andric 
6830b57cec5SDimitry Andric     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
6840b57cec5SDimitry Andric       return true;
6850b57cec5SDimitry Andric     MultiArg = true;
6860b57cec5SDimitry Andric     --NumAdditionalVals;
6870b57cec5SDimitry Andric   }
6880b57cec5SDimitry Andric   return false;
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric 
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)6918bcb0991SDimitry Andric bool llvm::cl::ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
6920b57cec5SDimitry Andric   int Dummy = i;
6930b57cec5SDimitry Andric   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
6940b57cec5SDimitry Andric }
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric // getOptionPred - Check to see if there are any options that satisfy the
6970b57cec5SDimitry Andric // specified predicate with names that are the prefixes in Name.  This is
6980b57cec5SDimitry Andric // checked by progressively stripping characters off of the name, checking to
6990b57cec5SDimitry Andric // see if there options that satisfy the predicate.  If we find one, return it,
7000b57cec5SDimitry Andric // otherwise return null.
7010b57cec5SDimitry Andric //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)7020b57cec5SDimitry Andric static Option *getOptionPred(StringRef Name, size_t &Length,
7030b57cec5SDimitry Andric                              bool (*Pred)(const Option *),
7040b57cec5SDimitry Andric                              const StringMap<Option *> &OptionsMap) {
7050b57cec5SDimitry Andric   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
7060b57cec5SDimitry Andric   if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
7070b57cec5SDimitry Andric     OMI = OptionsMap.end();
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   // Loop while we haven't found an option and Name still has at least two
7100b57cec5SDimitry Andric   // characters in it (so that the next iteration will not be the empty
7110b57cec5SDimitry Andric   // string.
7120b57cec5SDimitry Andric   while (OMI == OptionsMap.end() && Name.size() > 1) {
7130b57cec5SDimitry Andric     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
7140b57cec5SDimitry Andric     OMI = OptionsMap.find(Name);
7150b57cec5SDimitry Andric     if (OMI != OptionsMap.end() && !Pred(OMI->getValue()))
7160b57cec5SDimitry Andric       OMI = OptionsMap.end();
7170b57cec5SDimitry Andric   }
7180b57cec5SDimitry Andric 
7190b57cec5SDimitry Andric   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
7200b57cec5SDimitry Andric     Length = Name.size();
7210b57cec5SDimitry Andric     return OMI->second; // Found one!
7220b57cec5SDimitry Andric   }
7230b57cec5SDimitry Andric   return nullptr; // No option found!
7240b57cec5SDimitry Andric }
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric /// HandlePrefixedOrGroupedOption - The specified argument string (which started
7270b57cec5SDimitry Andric /// with at least one '-') does not fully match an available option.  Check to
7280b57cec5SDimitry Andric /// see if this is a prefix or grouped option.  If so, split arg into output an
7290b57cec5SDimitry Andric /// Arg/Value pair and return the Option to parse it with.
7300b57cec5SDimitry Andric static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)7310b57cec5SDimitry Andric HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
7320b57cec5SDimitry Andric                               bool &ErrorParsing,
7330b57cec5SDimitry Andric                               const StringMap<Option *> &OptionsMap) {
7340b57cec5SDimitry Andric   if (Arg.size() == 1)
7350b57cec5SDimitry Andric     return nullptr;
7360b57cec5SDimitry Andric 
7370b57cec5SDimitry Andric   // Do the lookup!
7380b57cec5SDimitry Andric   size_t Length = 0;
7390b57cec5SDimitry Andric   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
7400b57cec5SDimitry Andric   if (!PGOpt)
7410b57cec5SDimitry Andric     return nullptr;
7420b57cec5SDimitry Andric 
7430b57cec5SDimitry Andric   do {
7440b57cec5SDimitry Andric     StringRef MaybeValue =
7450b57cec5SDimitry Andric         (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
7460b57cec5SDimitry Andric     Arg = Arg.substr(0, Length);
7470b57cec5SDimitry Andric     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
7480b57cec5SDimitry Andric 
7490b57cec5SDimitry Andric     // cl::Prefix options do not preserve '=' when used separately.
7500b57cec5SDimitry Andric     // The behavior for them with grouped options should be the same.
7510b57cec5SDimitry Andric     if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
7520b57cec5SDimitry Andric         (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
7530b57cec5SDimitry Andric       Value = MaybeValue;
7540b57cec5SDimitry Andric       return PGOpt;
7550b57cec5SDimitry Andric     }
7560b57cec5SDimitry Andric 
7570b57cec5SDimitry Andric     if (MaybeValue[0] == '=') {
7580b57cec5SDimitry Andric       Value = MaybeValue.substr(1);
7590b57cec5SDimitry Andric       return PGOpt;
7600b57cec5SDimitry Andric     }
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric     // This must be a grouped option.
7630b57cec5SDimitry Andric     assert(isGrouping(PGOpt) && "Broken getOptionPred!");
7640b57cec5SDimitry Andric 
7650b57cec5SDimitry Andric     // Grouping options inside a group can't have values.
7660b57cec5SDimitry Andric     if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
7670b57cec5SDimitry Andric       ErrorParsing |= PGOpt->error("may not occur within a group!");
7680b57cec5SDimitry Andric       return nullptr;
7690b57cec5SDimitry Andric     }
7700b57cec5SDimitry Andric 
7710b57cec5SDimitry Andric     // Because the value for the option is not required, we don't need to pass
7720b57cec5SDimitry Andric     // argc/argv in.
7730b57cec5SDimitry Andric     int Dummy = 0;
7740b57cec5SDimitry Andric     ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric     // Get the next grouping option.
7770b57cec5SDimitry Andric     Arg = MaybeValue;
7780b57cec5SDimitry Andric     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
7790b57cec5SDimitry Andric   } while (PGOpt);
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   // We could not find a grouping option in the remainder of Arg.
7820b57cec5SDimitry Andric   return nullptr;
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric 
RequiresValue(const Option * O)7850b57cec5SDimitry Andric static bool RequiresValue(const Option *O) {
7860b57cec5SDimitry Andric   return O->getNumOccurrencesFlag() == cl::Required ||
7870b57cec5SDimitry Andric          O->getNumOccurrencesFlag() == cl::OneOrMore;
7880b57cec5SDimitry Andric }
7890b57cec5SDimitry Andric 
EatsUnboundedNumberOfValues(const Option * O)7900b57cec5SDimitry Andric static bool EatsUnboundedNumberOfValues(const Option *O) {
7910b57cec5SDimitry Andric   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
7920b57cec5SDimitry Andric          O->getNumOccurrencesFlag() == cl::OneOrMore;
7930b57cec5SDimitry Andric }
7940b57cec5SDimitry Andric 
isWhitespace(char C)7950b57cec5SDimitry Andric static bool isWhitespace(char C) {
7960b57cec5SDimitry Andric   return C == ' ' || C == '\t' || C == '\r' || C == '\n';
7970b57cec5SDimitry Andric }
7980b57cec5SDimitry Andric 
isWhitespaceOrNull(char C)7990b57cec5SDimitry Andric static bool isWhitespaceOrNull(char C) {
8000b57cec5SDimitry Andric   return isWhitespace(C) || C == '\0';
8010b57cec5SDimitry Andric }
8020b57cec5SDimitry Andric 
isQuote(char C)8030b57cec5SDimitry Andric static bool isQuote(char C) { return C == '\"' || C == '\''; }
8040b57cec5SDimitry Andric 
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)8050b57cec5SDimitry Andric void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
8060b57cec5SDimitry Andric                                 SmallVectorImpl<const char *> &NewArgv,
8070b57cec5SDimitry Andric                                 bool MarkEOLs) {
8080b57cec5SDimitry Andric   SmallString<128> Token;
8090b57cec5SDimitry Andric   for (size_t I = 0, E = Src.size(); I != E; ++I) {
8100b57cec5SDimitry Andric     // Consume runs of whitespace.
8110b57cec5SDimitry Andric     if (Token.empty()) {
8120b57cec5SDimitry Andric       while (I != E && isWhitespace(Src[I])) {
813e8d8bef9SDimitry Andric         // Mark the end of lines in response files.
8140b57cec5SDimitry Andric         if (MarkEOLs && Src[I] == '\n')
8150b57cec5SDimitry Andric           NewArgv.push_back(nullptr);
8160b57cec5SDimitry Andric         ++I;
8170b57cec5SDimitry Andric       }
8180b57cec5SDimitry Andric       if (I == E)
8190b57cec5SDimitry Andric         break;
8200b57cec5SDimitry Andric     }
8210b57cec5SDimitry Andric 
8220b57cec5SDimitry Andric     char C = Src[I];
8230b57cec5SDimitry Andric 
8240b57cec5SDimitry Andric     // Backslash escapes the next character.
8250b57cec5SDimitry Andric     if (I + 1 < E && C == '\\') {
8260b57cec5SDimitry Andric       ++I; // Skip the escape.
8270b57cec5SDimitry Andric       Token.push_back(Src[I]);
8280b57cec5SDimitry Andric       continue;
8290b57cec5SDimitry Andric     }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric     // Consume a quoted string.
8320b57cec5SDimitry Andric     if (isQuote(C)) {
8330b57cec5SDimitry Andric       ++I;
8340b57cec5SDimitry Andric       while (I != E && Src[I] != C) {
8350b57cec5SDimitry Andric         // Backslash escapes the next character.
8360b57cec5SDimitry Andric         if (Src[I] == '\\' && I + 1 != E)
8370b57cec5SDimitry Andric           ++I;
8380b57cec5SDimitry Andric         Token.push_back(Src[I]);
8390b57cec5SDimitry Andric         ++I;
8400b57cec5SDimitry Andric       }
8410b57cec5SDimitry Andric       if (I == E)
8420b57cec5SDimitry Andric         break;
8430b57cec5SDimitry Andric       continue;
8440b57cec5SDimitry Andric     }
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric     // End the token if this is whitespace.
8470b57cec5SDimitry Andric     if (isWhitespace(C)) {
8480b57cec5SDimitry Andric       if (!Token.empty())
849fe6060f1SDimitry Andric         NewArgv.push_back(Saver.save(Token.str()).data());
850e8d8bef9SDimitry Andric       // Mark the end of lines in response files.
851e8d8bef9SDimitry Andric       if (MarkEOLs && C == '\n')
852e8d8bef9SDimitry Andric         NewArgv.push_back(nullptr);
8530b57cec5SDimitry Andric       Token.clear();
8540b57cec5SDimitry Andric       continue;
8550b57cec5SDimitry Andric     }
8560b57cec5SDimitry Andric 
8570b57cec5SDimitry Andric     // This is a normal character.  Append it.
8580b57cec5SDimitry Andric     Token.push_back(C);
8590b57cec5SDimitry Andric   }
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   // Append the last token after hitting EOF with no whitespace.
8620b57cec5SDimitry Andric   if (!Token.empty())
863fe6060f1SDimitry Andric     NewArgv.push_back(Saver.save(Token.str()).data());
8640b57cec5SDimitry Andric }
8650b57cec5SDimitry Andric 
8660b57cec5SDimitry Andric /// Backslashes are interpreted in a rather complicated way in the Windows-style
8670b57cec5SDimitry Andric /// command line, because backslashes are used both to separate path and to
8680b57cec5SDimitry Andric /// escape double quote. This method consumes runs of backslashes as well as the
8690b57cec5SDimitry Andric /// following double quote if it's escaped.
8700b57cec5SDimitry Andric ///
8710b57cec5SDimitry Andric ///  * If an even number of backslashes is followed by a double quote, one
8720b57cec5SDimitry Andric ///    backslash is output for every pair of backslashes, and the last double
8730b57cec5SDimitry Andric ///    quote remains unconsumed. The double quote will later be interpreted as
8740b57cec5SDimitry Andric ///    the start or end of a quoted string in the main loop outside of this
8750b57cec5SDimitry Andric ///    function.
8760b57cec5SDimitry Andric ///
8770b57cec5SDimitry Andric ///  * If an odd number of backslashes is followed by a double quote, one
8780b57cec5SDimitry Andric ///    backslash is output for every pair of backslashes, and a double quote is
8790b57cec5SDimitry Andric ///    output for the last pair of backslash-double quote. The double quote is
8800b57cec5SDimitry Andric ///    consumed in this case.
8810b57cec5SDimitry Andric ///
8820b57cec5SDimitry Andric ///  * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)8830b57cec5SDimitry Andric static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
8840b57cec5SDimitry Andric   size_t E = Src.size();
8850b57cec5SDimitry Andric   int BackslashCount = 0;
8860b57cec5SDimitry Andric   // Skip the backslashes.
8870b57cec5SDimitry Andric   do {
8880b57cec5SDimitry Andric     ++I;
8890b57cec5SDimitry Andric     ++BackslashCount;
8900b57cec5SDimitry Andric   } while (I != E && Src[I] == '\\');
8910b57cec5SDimitry Andric 
8920b57cec5SDimitry Andric   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
8930b57cec5SDimitry Andric   if (FollowedByDoubleQuote) {
8940b57cec5SDimitry Andric     Token.append(BackslashCount / 2, '\\');
8950b57cec5SDimitry Andric     if (BackslashCount % 2 == 0)
8960b57cec5SDimitry Andric       return I - 1;
8970b57cec5SDimitry Andric     Token.push_back('"');
8980b57cec5SDimitry Andric     return I;
8990b57cec5SDimitry Andric   }
9000b57cec5SDimitry Andric   Token.append(BackslashCount, '\\');
9010b57cec5SDimitry Andric   return I - 1;
9020b57cec5SDimitry Andric }
9030b57cec5SDimitry Andric 
90481ad6265SDimitry Andric // Windows treats whitespace, double quotes, and backslashes specially, except
90581ad6265SDimitry Andric // when parsing the first token of a full command line, in which case
90681ad6265SDimitry Andric // backslashes are not special.
isWindowsSpecialChar(char C)9075ffd83dbSDimitry Andric static bool isWindowsSpecialChar(char C) {
9085ffd83dbSDimitry Andric   return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
9095ffd83dbSDimitry Andric }
isWindowsSpecialCharInCommandName(char C)91081ad6265SDimitry Andric static bool isWindowsSpecialCharInCommandName(char C) {
91181ad6265SDimitry Andric   return isWhitespaceOrNull(C) || C == '\"';
91281ad6265SDimitry Andric }
9135ffd83dbSDimitry Andric 
9145ffd83dbSDimitry Andric // Windows tokenization implementation. The implementation is designed to be
9155ffd83dbSDimitry Andric // inlined and specialized for the two user entry points.
tokenizeWindowsCommandLineImpl(StringRef Src,StringSaver & Saver,function_ref<void (StringRef)> AddToken,bool AlwaysCopy,function_ref<void ()> MarkEOL,bool InitialCommandName)91681ad6265SDimitry Andric static inline void tokenizeWindowsCommandLineImpl(
91781ad6265SDimitry Andric     StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
91881ad6265SDimitry Andric     bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
9190b57cec5SDimitry Andric   SmallString<128> Token;
9200b57cec5SDimitry Andric 
92181ad6265SDimitry Andric   // Sometimes, this function will be handling a full command line including an
92281ad6265SDimitry Andric   // executable pathname at the start. In that situation, the initial pathname
92381ad6265SDimitry Andric   // needs different handling from the following arguments, because when
92481ad6265SDimitry Andric   // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
92581ad6265SDimitry Andric   // escaping the quote character, whereas when libc scans the rest of the
92681ad6265SDimitry Andric   // command line, it does.
92781ad6265SDimitry Andric   bool CommandName = InitialCommandName;
92881ad6265SDimitry Andric 
9295ffd83dbSDimitry Andric   // Try to do as much work inside the state machine as possible.
9300b57cec5SDimitry Andric   enum { INIT, UNQUOTED, QUOTED } State = INIT;
93181ad6265SDimitry Andric 
9325ffd83dbSDimitry Andric   for (size_t I = 0, E = Src.size(); I < E; ++I) {
9335ffd83dbSDimitry Andric     switch (State) {
9345ffd83dbSDimitry Andric     case INIT: {
9355ffd83dbSDimitry Andric       assert(Token.empty() && "token should be empty in initial state");
9365ffd83dbSDimitry Andric       // Eat whitespace before a token.
9375ffd83dbSDimitry Andric       while (I < E && isWhitespaceOrNull(Src[I])) {
9385ffd83dbSDimitry Andric         if (Src[I] == '\n')
9395ffd83dbSDimitry Andric           MarkEOL();
9405ffd83dbSDimitry Andric         ++I;
9410b57cec5SDimitry Andric       }
9425ffd83dbSDimitry Andric       // Stop if this was trailing whitespace.
9435ffd83dbSDimitry Andric       if (I >= E)
9445ffd83dbSDimitry Andric         break;
9455ffd83dbSDimitry Andric       size_t Start = I;
94681ad6265SDimitry Andric       if (CommandName) {
94781ad6265SDimitry Andric         while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
94881ad6265SDimitry Andric           ++I;
94981ad6265SDimitry Andric       } else {
9505ffd83dbSDimitry Andric         while (I < E && !isWindowsSpecialChar(Src[I]))
9515ffd83dbSDimitry Andric           ++I;
95281ad6265SDimitry Andric       }
9535ffd83dbSDimitry Andric       StringRef NormalChars = Src.slice(Start, I);
9545ffd83dbSDimitry Andric       if (I >= E || isWhitespaceOrNull(Src[I])) {
9555ffd83dbSDimitry Andric         // No special characters: slice out the substring and start the next
9565ffd83dbSDimitry Andric         // token. Copy the string if the caller asks us to.
9575ffd83dbSDimitry Andric         AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
95881ad6265SDimitry Andric         if (I < E && Src[I] == '\n') {
959e8d8bef9SDimitry Andric           MarkEOL();
96081ad6265SDimitry Andric           CommandName = InitialCommandName;
96181ad6265SDimitry Andric         } else {
96281ad6265SDimitry Andric           CommandName = false;
96381ad6265SDimitry Andric         }
9645ffd83dbSDimitry Andric       } else if (Src[I] == '\"') {
9655ffd83dbSDimitry Andric         Token += NormalChars;
9660b57cec5SDimitry Andric         State = QUOTED;
9675ffd83dbSDimitry Andric       } else if (Src[I] == '\\') {
96881ad6265SDimitry Andric         assert(!CommandName && "or else we'd have treated it as a normal char");
9695ffd83dbSDimitry Andric         Token += NormalChars;
9700b57cec5SDimitry Andric         I = parseBackslash(Src, I, Token);
9710b57cec5SDimitry Andric         State = UNQUOTED;
9725ffd83dbSDimitry Andric       } else {
9735ffd83dbSDimitry Andric         llvm_unreachable("unexpected special character");
9740b57cec5SDimitry Andric       }
9755ffd83dbSDimitry Andric       break;
9760b57cec5SDimitry Andric     }
9770b57cec5SDimitry Andric 
9785ffd83dbSDimitry Andric     case UNQUOTED:
9795ffd83dbSDimitry Andric       if (isWhitespaceOrNull(Src[I])) {
9805ffd83dbSDimitry Andric         // Whitespace means the end of the token. If we are in this state, the
9815ffd83dbSDimitry Andric         // token must have contained a special character, so we must copy the
9825ffd83dbSDimitry Andric         // token.
9835ffd83dbSDimitry Andric         AddToken(Saver.save(Token.str()));
9840b57cec5SDimitry Andric         Token.clear();
98581ad6265SDimitry Andric         if (Src[I] == '\n') {
98681ad6265SDimitry Andric           CommandName = InitialCommandName;
9875ffd83dbSDimitry Andric           MarkEOL();
98881ad6265SDimitry Andric         } else {
98981ad6265SDimitry Andric           CommandName = false;
99081ad6265SDimitry Andric         }
9910b57cec5SDimitry Andric         State = INIT;
9925ffd83dbSDimitry Andric       } else if (Src[I] == '\"') {
9930b57cec5SDimitry Andric         State = QUOTED;
99481ad6265SDimitry Andric       } else if (Src[I] == '\\' && !CommandName) {
9950b57cec5SDimitry Andric         I = parseBackslash(Src, I, Token);
9965ffd83dbSDimitry Andric       } else {
9975ffd83dbSDimitry Andric         Token.push_back(Src[I]);
9980b57cec5SDimitry Andric       }
9995ffd83dbSDimitry Andric       break;
10000b57cec5SDimitry Andric 
10015ffd83dbSDimitry Andric     case QUOTED:
10025ffd83dbSDimitry Andric       if (Src[I] == '\"') {
10030b57cec5SDimitry Andric         if (I < (E - 1) && Src[I + 1] == '"') {
10040b57cec5SDimitry Andric           // Consecutive double-quotes inside a quoted string implies one
10050b57cec5SDimitry Andric           // double-quote.
10060b57cec5SDimitry Andric           Token.push_back('"');
10075ffd83dbSDimitry Andric           ++I;
10085ffd83dbSDimitry Andric         } else {
10095ffd83dbSDimitry Andric           // Otherwise, end the quoted portion and return to the unquoted state.
10100b57cec5SDimitry Andric           State = UNQUOTED;
10110b57cec5SDimitry Andric         }
101281ad6265SDimitry Andric       } else if (Src[I] == '\\' && !CommandName) {
10130b57cec5SDimitry Andric         I = parseBackslash(Src, I, Token);
10145ffd83dbSDimitry Andric       } else {
10155ffd83dbSDimitry Andric         Token.push_back(Src[I]);
10160b57cec5SDimitry Andric       }
10175ffd83dbSDimitry Andric       break;
10180b57cec5SDimitry Andric     }
10190b57cec5SDimitry Andric   }
10205ffd83dbSDimitry Andric 
102181ad6265SDimitry Andric   if (State != INIT)
10225ffd83dbSDimitry Andric     AddToken(Saver.save(Token.str()));
10235ffd83dbSDimitry Andric }
10245ffd83dbSDimitry Andric 
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)10255ffd83dbSDimitry Andric void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
10265ffd83dbSDimitry Andric                                     SmallVectorImpl<const char *> &NewArgv,
10275ffd83dbSDimitry Andric                                     bool MarkEOLs) {
10285ffd83dbSDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
10295ffd83dbSDimitry Andric   auto OnEOL = [&]() {
10300b57cec5SDimitry Andric     if (MarkEOLs)
10310b57cec5SDimitry Andric       NewArgv.push_back(nullptr);
10325ffd83dbSDimitry Andric   };
10335ffd83dbSDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
103481ad6265SDimitry Andric                                  /*AlwaysCopy=*/true, OnEOL, false);
10355ffd83dbSDimitry Andric }
10365ffd83dbSDimitry Andric 
TokenizeWindowsCommandLineNoCopy(StringRef Src,StringSaver & Saver,SmallVectorImpl<StringRef> & NewArgv)10375ffd83dbSDimitry Andric void cl::TokenizeWindowsCommandLineNoCopy(StringRef Src, StringSaver &Saver,
10385ffd83dbSDimitry Andric                                           SmallVectorImpl<StringRef> &NewArgv) {
10395ffd83dbSDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
10405ffd83dbSDimitry Andric   auto OnEOL = []() {};
10415ffd83dbSDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
104281ad6265SDimitry Andric                                  OnEOL, false);
104381ad6265SDimitry Andric }
104481ad6265SDimitry Andric 
TokenizeWindowsCommandLineFull(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)104581ad6265SDimitry Andric void cl::TokenizeWindowsCommandLineFull(StringRef Src, StringSaver &Saver,
104681ad6265SDimitry Andric                                         SmallVectorImpl<const char *> &NewArgv,
104781ad6265SDimitry Andric                                         bool MarkEOLs) {
104881ad6265SDimitry Andric   auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
104981ad6265SDimitry Andric   auto OnEOL = [&]() {
105081ad6265SDimitry Andric     if (MarkEOLs)
105181ad6265SDimitry Andric       NewArgv.push_back(nullptr);
105281ad6265SDimitry Andric   };
105381ad6265SDimitry Andric   tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
105481ad6265SDimitry Andric                                  /*AlwaysCopy=*/true, OnEOL, true);
10550b57cec5SDimitry Andric }
10560b57cec5SDimitry Andric 
tokenizeConfigFile(StringRef Source,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)10570b57cec5SDimitry Andric void cl::tokenizeConfigFile(StringRef Source, StringSaver &Saver,
10580b57cec5SDimitry Andric                             SmallVectorImpl<const char *> &NewArgv,
10590b57cec5SDimitry Andric                             bool MarkEOLs) {
10600b57cec5SDimitry Andric   for (const char *Cur = Source.begin(); Cur != Source.end();) {
10610b57cec5SDimitry Andric     SmallString<128> Line;
10620b57cec5SDimitry Andric     // Check for comment line.
10630b57cec5SDimitry Andric     if (isWhitespace(*Cur)) {
10640b57cec5SDimitry Andric       while (Cur != Source.end() && isWhitespace(*Cur))
10650b57cec5SDimitry Andric         ++Cur;
10660b57cec5SDimitry Andric       continue;
10670b57cec5SDimitry Andric     }
10680b57cec5SDimitry Andric     if (*Cur == '#') {
10690b57cec5SDimitry Andric       while (Cur != Source.end() && *Cur != '\n')
10700b57cec5SDimitry Andric         ++Cur;
10710b57cec5SDimitry Andric       continue;
10720b57cec5SDimitry Andric     }
10730b57cec5SDimitry Andric     // Find end of the current line.
10740b57cec5SDimitry Andric     const char *Start = Cur;
10750b57cec5SDimitry Andric     for (const char *End = Source.end(); Cur != End; ++Cur) {
10760b57cec5SDimitry Andric       if (*Cur == '\\') {
10770b57cec5SDimitry Andric         if (Cur + 1 != End) {
10780b57cec5SDimitry Andric           ++Cur;
10790b57cec5SDimitry Andric           if (*Cur == '\n' ||
10800b57cec5SDimitry Andric               (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
10810b57cec5SDimitry Andric             Line.append(Start, Cur - 1);
10820b57cec5SDimitry Andric             if (*Cur == '\r')
10830b57cec5SDimitry Andric               ++Cur;
10840b57cec5SDimitry Andric             Start = Cur + 1;
10850b57cec5SDimitry Andric           }
10860b57cec5SDimitry Andric         }
10870b57cec5SDimitry Andric       } else if (*Cur == '\n')
10880b57cec5SDimitry Andric         break;
10890b57cec5SDimitry Andric     }
10900b57cec5SDimitry Andric     // Tokenize line.
10910b57cec5SDimitry Andric     Line.append(Start, Cur);
10920b57cec5SDimitry Andric     cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
10930b57cec5SDimitry Andric   }
10940b57cec5SDimitry Andric }
10950b57cec5SDimitry Andric 
10960b57cec5SDimitry Andric // It is called byte order marker but the UTF-8 BOM is actually not affected
10970b57cec5SDimitry Andric // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)10980b57cec5SDimitry Andric static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
10990b57cec5SDimitry Andric   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
11000b57cec5SDimitry Andric }
11010b57cec5SDimitry Andric 
110204eeddc0SDimitry Andric // Substitute <CFGDIR> with the file's base path.
ExpandBasePaths(StringRef BasePath,StringSaver & Saver,const char * & Arg)110304eeddc0SDimitry Andric static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
110404eeddc0SDimitry Andric                             const char *&Arg) {
110504eeddc0SDimitry Andric   assert(sys::path::is_absolute(BasePath));
110604eeddc0SDimitry Andric   constexpr StringLiteral Token("<CFGDIR>");
110704eeddc0SDimitry Andric   const StringRef ArgString(Arg);
110804eeddc0SDimitry Andric 
110904eeddc0SDimitry Andric   SmallString<128> ResponseFile;
111004eeddc0SDimitry Andric   StringRef::size_type StartPos = 0;
111104eeddc0SDimitry Andric   for (StringRef::size_type TokenPos = ArgString.find(Token);
111204eeddc0SDimitry Andric        TokenPos != StringRef::npos;
111304eeddc0SDimitry Andric        TokenPos = ArgString.find(Token, StartPos)) {
111404eeddc0SDimitry Andric     // Token may appear more than once per arg (e.g. comma-separated linker
111504eeddc0SDimitry Andric     // args). Support by using path-append on any subsequent appearances.
111604eeddc0SDimitry Andric     const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
111704eeddc0SDimitry Andric     if (ResponseFile.empty())
111804eeddc0SDimitry Andric       ResponseFile = LHS;
111904eeddc0SDimitry Andric     else
112004eeddc0SDimitry Andric       llvm::sys::path::append(ResponseFile, LHS);
112104eeddc0SDimitry Andric     ResponseFile.append(BasePath);
112204eeddc0SDimitry Andric     StartPos = TokenPos + Token.size();
112304eeddc0SDimitry Andric   }
112404eeddc0SDimitry Andric 
112504eeddc0SDimitry Andric   if (!ResponseFile.empty()) {
112604eeddc0SDimitry Andric     // Path-append the remaining arg substring if at least one token appeared.
112704eeddc0SDimitry Andric     const StringRef Remaining = ArgString.substr(StartPos);
112804eeddc0SDimitry Andric     if (!Remaining.empty())
112904eeddc0SDimitry Andric       llvm::sys::path::append(ResponseFile, Remaining);
113004eeddc0SDimitry Andric     Arg = Saver.save(ResponseFile.str()).data();
113104eeddc0SDimitry Andric   }
113204eeddc0SDimitry Andric }
113304eeddc0SDimitry Andric 
1134480093f4SDimitry Andric // FName must be an absolute path.
expandResponseFile(StringRef FName,SmallVectorImpl<const char * > & NewArgv)1135bdd1243dSDimitry Andric Error ExpansionContext::expandResponseFile(
1136bdd1243dSDimitry Andric     StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1137480093f4SDimitry Andric   assert(sys::path::is_absolute(FName));
1138480093f4SDimitry Andric   llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1139bdd1243dSDimitry Andric       FS->getBufferForFile(FName);
1140bdd1243dSDimitry Andric   if (!MemBufOrErr) {
1141bdd1243dSDimitry Andric     std::error_code EC = MemBufOrErr.getError();
1142bdd1243dSDimitry Andric     return llvm::createStringError(EC, Twine("cannot not open file '") + FName +
1143bdd1243dSDimitry Andric                                            "': " + EC.message());
1144bdd1243dSDimitry Andric   }
11450b57cec5SDimitry Andric   MemoryBuffer &MemBuf = *MemBufOrErr.get();
11460b57cec5SDimitry Andric   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
11490b57cec5SDimitry Andric   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
11500b57cec5SDimitry Andric   std::string UTF8Buf;
11510b57cec5SDimitry Andric   if (hasUTF16ByteOrderMark(BufRef)) {
11520b57cec5SDimitry Andric     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1153480093f4SDimitry Andric       return llvm::createStringError(std::errc::illegal_byte_sequence,
1154480093f4SDimitry Andric                                      "Could not convert UTF16 to UTF8");
11550b57cec5SDimitry Andric     Str = StringRef(UTF8Buf);
11560b57cec5SDimitry Andric   }
11570b57cec5SDimitry Andric   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
11580b57cec5SDimitry Andric   // these bytes before parsing.
11590b57cec5SDimitry Andric   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
11600b57cec5SDimitry Andric   else if (hasUTF8ByteOrderMark(BufRef))
11610b57cec5SDimitry Andric     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
11620b57cec5SDimitry Andric 
11630b57cec5SDimitry Andric   // Tokenize the contents into NewArgv.
11640b57cec5SDimitry Andric   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
11650b57cec5SDimitry Andric 
1166bdd1243dSDimitry Andric   // Expanded file content may require additional transformations, like using
1167bdd1243dSDimitry Andric   // absolute paths instead of relative in '@file' constructs or expanding
1168bdd1243dSDimitry Andric   // macros.
1169bdd1243dSDimitry Andric   if (!RelativeNames && !InConfigFile)
1170480093f4SDimitry Andric     return Error::success();
1171bdd1243dSDimitry Andric 
1172bdd1243dSDimitry Andric   StringRef BasePath = llvm::sys::path::parent_path(FName);
1173bdd1243dSDimitry Andric   for (const char *&Arg : NewArgv) {
117404eeddc0SDimitry Andric     if (!Arg)
117504eeddc0SDimitry Andric       continue;
117604eeddc0SDimitry Andric 
117704eeddc0SDimitry Andric     // Substitute <CFGDIR> with the file's base path.
1178bdd1243dSDimitry Andric     if (InConfigFile)
117904eeddc0SDimitry Andric       ExpandBasePaths(BasePath, Saver, Arg);
118004eeddc0SDimitry Andric 
1181bdd1243dSDimitry Andric     // Discover the case, when argument should be transformed into '@file' and
1182bdd1243dSDimitry Andric     // evaluate 'file' for it.
1183bdd1243dSDimitry Andric     StringRef ArgStr(Arg);
1184bdd1243dSDimitry Andric     StringRef FileName;
1185bdd1243dSDimitry Andric     bool ConfigInclusion = false;
1186bdd1243dSDimitry Andric     if (ArgStr.consume_front("@")) {
1187bdd1243dSDimitry Andric       FileName = ArgStr;
1188480093f4SDimitry Andric       if (!llvm::sys::path::is_relative(FileName))
1189480093f4SDimitry Andric         continue;
1190bdd1243dSDimitry Andric     } else if (ArgStr.consume_front("--config=")) {
1191bdd1243dSDimitry Andric       FileName = ArgStr;
1192bdd1243dSDimitry Andric       ConfigInclusion = true;
1193bdd1243dSDimitry Andric     } else {
1194bdd1243dSDimitry Andric       continue;
1195bdd1243dSDimitry Andric     }
1196480093f4SDimitry Andric 
1197bdd1243dSDimitry Andric     // Update expansion construct.
1198480093f4SDimitry Andric     SmallString<128> ResponseFile;
1199480093f4SDimitry Andric     ResponseFile.push_back('@');
1200bdd1243dSDimitry Andric     if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
1201bdd1243dSDimitry Andric       SmallString<128> FilePath;
1202bdd1243dSDimitry Andric       if (!findConfigFile(FileName, FilePath))
1203bdd1243dSDimitry Andric         return createStringError(
1204bdd1243dSDimitry Andric             std::make_error_code(std::errc::no_such_file_or_directory),
1205bdd1243dSDimitry Andric             "cannot not find configuration file: " + FileName);
1206bdd1243dSDimitry Andric       ResponseFile.append(FilePath);
1207bdd1243dSDimitry Andric     } else {
1208480093f4SDimitry Andric       ResponseFile.append(BasePath);
1209480093f4SDimitry Andric       llvm::sys::path::append(ResponseFile, FileName);
1210bdd1243dSDimitry Andric     }
121104eeddc0SDimitry Andric     Arg = Saver.save(ResponseFile.str()).data();
1212480093f4SDimitry Andric   }
1213480093f4SDimitry Andric   return Error::success();
12140b57cec5SDimitry Andric }
12150b57cec5SDimitry Andric 
12160b57cec5SDimitry Andric /// Expand response files on a command line recursively using the given
12170b57cec5SDimitry Andric /// StringSaver and tokenization strategy.
expandResponseFiles(SmallVectorImpl<const char * > & Argv)1218bdd1243dSDimitry Andric Error ExpansionContext::expandResponseFiles(
1219bdd1243dSDimitry Andric     SmallVectorImpl<const char *> &Argv) {
12200b57cec5SDimitry Andric   struct ResponseFileRecord {
1221480093f4SDimitry Andric     std::string File;
12220b57cec5SDimitry Andric     size_t End;
12230b57cec5SDimitry Andric   };
12240b57cec5SDimitry Andric 
12250b57cec5SDimitry Andric   // To detect recursive response files, we maintain a stack of files and the
12260b57cec5SDimitry Andric   // position of the last argument in the file. This position is updated
12270b57cec5SDimitry Andric   // dynamically as we recursively expand files.
12280b57cec5SDimitry Andric   SmallVector<ResponseFileRecord, 3> FileStack;
12290b57cec5SDimitry Andric 
12300b57cec5SDimitry Andric   // Push a dummy entry that represents the initial command line, removing
12310b57cec5SDimitry Andric   // the need to check for an empty list.
12320b57cec5SDimitry Andric   FileStack.push_back({"", Argv.size()});
12330b57cec5SDimitry Andric 
12340b57cec5SDimitry Andric   // Don't cache Argv.size() because it can change.
12350b57cec5SDimitry Andric   for (unsigned I = 0; I != Argv.size();) {
12360b57cec5SDimitry Andric     while (I == FileStack.back().End) {
12370b57cec5SDimitry Andric       // Passing the end of a file's argument list, so we can remove it from the
12380b57cec5SDimitry Andric       // stack.
12390b57cec5SDimitry Andric       FileStack.pop_back();
12400b57cec5SDimitry Andric     }
12410b57cec5SDimitry Andric 
12420b57cec5SDimitry Andric     const char *Arg = Argv[I];
12430b57cec5SDimitry Andric     // Check if it is an EOL marker
12440b57cec5SDimitry Andric     if (Arg == nullptr) {
12450b57cec5SDimitry Andric       ++I;
12460b57cec5SDimitry Andric       continue;
12470b57cec5SDimitry Andric     }
12480b57cec5SDimitry Andric 
12490b57cec5SDimitry Andric     if (Arg[0] != '@') {
12500b57cec5SDimitry Andric       ++I;
12510b57cec5SDimitry Andric       continue;
12520b57cec5SDimitry Andric     }
12530b57cec5SDimitry Andric 
12540b57cec5SDimitry Andric     const char *FName = Arg + 1;
1255480093f4SDimitry Andric     // Note that CurrentDir is only used for top-level rsp files, the rest will
1256480093f4SDimitry Andric     // always have an absolute path deduced from the containing file.
1257480093f4SDimitry Andric     SmallString<128> CurrDir;
1258480093f4SDimitry Andric     if (llvm::sys::path::is_relative(FName)) {
1259bdd1243dSDimitry Andric       if (CurrentDir.empty()) {
1260bdd1243dSDimitry Andric         if (auto CWD = FS->getCurrentWorkingDirectory()) {
1261bdd1243dSDimitry Andric           CurrDir = *CWD;
1262bdd1243dSDimitry Andric         } else {
1263bdd1243dSDimitry Andric           return createStringError(
1264bdd1243dSDimitry Andric               CWD.getError(), Twine("cannot get absolute path for: ") + FName);
1265bdd1243dSDimitry Andric         }
1266bdd1243dSDimitry Andric       } else {
1267bdd1243dSDimitry Andric         CurrDir = CurrentDir;
1268bdd1243dSDimitry Andric       }
1269480093f4SDimitry Andric       llvm::sys::path::append(CurrDir, FName);
1270480093f4SDimitry Andric       FName = CurrDir.c_str();
1271480093f4SDimitry Andric     }
1272bdd1243dSDimitry Andric 
1273bdd1243dSDimitry Andric     ErrorOr<llvm::vfs::Status> Res = FS->status(FName);
1274bdd1243dSDimitry Andric     if (!Res || !Res->exists()) {
1275bdd1243dSDimitry Andric       std::error_code EC = Res.getError();
1276bdd1243dSDimitry Andric       if (!InConfigFile) {
1277bdd1243dSDimitry Andric         // If the specified file does not exist, leave '@file' unexpanded, as
1278bdd1243dSDimitry Andric         // libiberty does.
1279bdd1243dSDimitry Andric         if (!EC || EC == llvm::errc::no_such_file_or_directory) {
1280bdd1243dSDimitry Andric           ++I;
1281bdd1243dSDimitry Andric           continue;
1282480093f4SDimitry Andric         }
1283480093f4SDimitry Andric       }
1284bdd1243dSDimitry Andric       if (!EC)
1285bdd1243dSDimitry Andric         EC = llvm::errc::no_such_file_or_directory;
1286bdd1243dSDimitry Andric       return createStringError(EC, Twine("cannot not open file '") + FName +
1287bdd1243dSDimitry Andric                                        "': " + EC.message());
1288bdd1243dSDimitry Andric     }
1289bdd1243dSDimitry Andric     const llvm::vfs::Status &FileStatus = Res.get();
1290bdd1243dSDimitry Andric 
1291bdd1243dSDimitry Andric     auto IsEquivalent =
1292bdd1243dSDimitry Andric         [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
1293bdd1243dSDimitry Andric       ErrorOr<llvm::vfs::Status> RHS = FS->status(RFile.File);
1294bdd1243dSDimitry Andric       if (!RHS)
1295bdd1243dSDimitry Andric         return RHS.getError();
1296bdd1243dSDimitry Andric       return FileStatus.equivalent(*RHS);
12970b57cec5SDimitry Andric     };
12980b57cec5SDimitry Andric 
12990b57cec5SDimitry Andric     // Check for recursive response files.
1300bdd1243dSDimitry Andric     for (const auto &F : drop_begin(FileStack)) {
1301bdd1243dSDimitry Andric       if (ErrorOr<bool> R = IsEquivalent(F)) {
1302bdd1243dSDimitry Andric         if (R.get())
1303bdd1243dSDimitry Andric           return createStringError(
1304bdd1243dSDimitry Andric               R.getError(), Twine("recursive expansion of: '") + F.File + "'");
1305bdd1243dSDimitry Andric       } else {
1306bdd1243dSDimitry Andric         return createStringError(R.getError(),
1307bdd1243dSDimitry Andric                                  Twine("cannot open file: ") + F.File);
1308bdd1243dSDimitry Andric       }
13090b57cec5SDimitry Andric     }
13100b57cec5SDimitry Andric 
13110b57cec5SDimitry Andric     // Replace this response file argument with the tokenization of its
13120b57cec5SDimitry Andric     // contents.  Nested response files are expanded in subsequent iterations.
13130b57cec5SDimitry Andric     SmallVector<const char *, 0> ExpandedArgv;
1314bdd1243dSDimitry Andric     if (Error Err = expandResponseFile(FName, ExpandedArgv))
1315bdd1243dSDimitry Andric       return Err;
13160b57cec5SDimitry Andric 
13170b57cec5SDimitry Andric     for (ResponseFileRecord &Record : FileStack) {
13180b57cec5SDimitry Andric       // Increase the end of all active records by the number of newly expanded
13190b57cec5SDimitry Andric       // arguments, minus the response file itself.
13200b57cec5SDimitry Andric       Record.End += ExpandedArgv.size() - 1;
13210b57cec5SDimitry Andric     }
13220b57cec5SDimitry Andric 
13230b57cec5SDimitry Andric     FileStack.push_back({FName, I + ExpandedArgv.size()});
13240b57cec5SDimitry Andric     Argv.erase(Argv.begin() + I);
13250b57cec5SDimitry Andric     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
13260b57cec5SDimitry Andric   }
13270b57cec5SDimitry Andric 
13280b57cec5SDimitry Andric   // If successful, the top of the file stack will mark the end of the Argv
13290b57cec5SDimitry Andric   // stream. A failure here indicates a bug in the stack popping logic above.
13300b57cec5SDimitry Andric   // Note that FileStack may have more than one element at this point because we
13310b57cec5SDimitry Andric   // don't have a chance to pop the stack when encountering recursive files at
13320b57cec5SDimitry Andric   // the end of the stream, so seeing that doesn't indicate a bug.
13330b57cec5SDimitry Andric   assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1334bdd1243dSDimitry Andric   return Error::success();
1335fe6060f1SDimitry Andric }
1336fe6060f1SDimitry Andric 
expandResponseFiles(int Argc,const char * const * Argv,const char * EnvVar,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv)1337e8d8bef9SDimitry Andric bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1338e8d8bef9SDimitry Andric                              const char *EnvVar, StringSaver &Saver,
1339e8d8bef9SDimitry Andric                              SmallVectorImpl<const char *> &NewArgv) {
1340bdd1243dSDimitry Andric #ifdef _WIN32
1341bdd1243dSDimitry Andric   auto Tokenize = cl::TokenizeWindowsCommandLine;
1342bdd1243dSDimitry Andric #else
1343bdd1243dSDimitry Andric   auto Tokenize = cl::TokenizeGNUCommandLine;
1344bdd1243dSDimitry Andric #endif
1345e8d8bef9SDimitry Andric   // The environment variable specifies initial options.
1346e8d8bef9SDimitry Andric   if (EnvVar)
1347bdd1243dSDimitry Andric     if (std::optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1348e8d8bef9SDimitry Andric       Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1349e8d8bef9SDimitry Andric 
1350e8d8bef9SDimitry Andric   // Command line options can override the environment variable.
1351e8d8bef9SDimitry Andric   NewArgv.append(Argv + 1, Argv + Argc);
1352bdd1243dSDimitry Andric   ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1353bdd1243dSDimitry Andric   if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
1354bdd1243dSDimitry Andric     errs() << toString(std::move(Err)) << '\n';
1355bdd1243dSDimitry Andric     return false;
1356bdd1243dSDimitry Andric   }
1357bdd1243dSDimitry Andric   return true;
1358e8d8bef9SDimitry Andric }
1359e8d8bef9SDimitry Andric 
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv)1360bdd1243dSDimitry Andric bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1361bdd1243dSDimitry Andric                              SmallVectorImpl<const char *> &Argv) {
1362bdd1243dSDimitry Andric   ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1363bdd1243dSDimitry Andric   if (Error Err = ECtx.expandResponseFiles(Argv)) {
1364bdd1243dSDimitry Andric     errs() << toString(std::move(Err)) << '\n';
1365bdd1243dSDimitry Andric     return false;
1366bdd1243dSDimitry Andric   }
1367bdd1243dSDimitry Andric   return true;
1368bdd1243dSDimitry Andric }
1369bdd1243dSDimitry Andric 
ExpansionContext(BumpPtrAllocator & A,TokenizerCallback T)1370bdd1243dSDimitry Andric ExpansionContext::ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T)
1371bdd1243dSDimitry Andric     : Saver(A), Tokenizer(T), FS(vfs::getRealFileSystem().get()) {}
1372bdd1243dSDimitry Andric 
findConfigFile(StringRef FileName,SmallVectorImpl<char> & FilePath)1373bdd1243dSDimitry Andric bool ExpansionContext::findConfigFile(StringRef FileName,
1374bdd1243dSDimitry Andric                                       SmallVectorImpl<char> &FilePath) {
1375bdd1243dSDimitry Andric   SmallString<128> CfgFilePath;
1376bdd1243dSDimitry Andric   const auto FileExists = [this](SmallString<128> Path) -> bool {
1377bdd1243dSDimitry Andric     auto Status = FS->status(Path);
1378bdd1243dSDimitry Andric     return Status &&
1379bdd1243dSDimitry Andric            Status->getType() == llvm::sys::fs::file_type::regular_file;
1380bdd1243dSDimitry Andric   };
1381bdd1243dSDimitry Andric 
1382bdd1243dSDimitry Andric   // If file name contains directory separator, treat it as a path to
1383bdd1243dSDimitry Andric   // configuration file.
1384bdd1243dSDimitry Andric   if (llvm::sys::path::has_parent_path(FileName)) {
1385bdd1243dSDimitry Andric     CfgFilePath = FileName;
1386bdd1243dSDimitry Andric     if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
1387bdd1243dSDimitry Andric       return false;
1388bdd1243dSDimitry Andric     if (!FileExists(CfgFilePath))
1389bdd1243dSDimitry Andric       return false;
1390bdd1243dSDimitry Andric     FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1391bdd1243dSDimitry Andric     return true;
1392bdd1243dSDimitry Andric   }
1393bdd1243dSDimitry Andric 
1394bdd1243dSDimitry Andric   // Look for the file in search directories.
1395bdd1243dSDimitry Andric   for (const StringRef &Dir : SearchDirs) {
1396bdd1243dSDimitry Andric     if (Dir.empty())
1397bdd1243dSDimitry Andric       continue;
1398bdd1243dSDimitry Andric     CfgFilePath.assign(Dir);
1399bdd1243dSDimitry Andric     llvm::sys::path::append(CfgFilePath, FileName);
1400bdd1243dSDimitry Andric     llvm::sys::path::native(CfgFilePath);
1401bdd1243dSDimitry Andric     if (FileExists(CfgFilePath)) {
1402bdd1243dSDimitry Andric       FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1403bdd1243dSDimitry Andric       return true;
1404bdd1243dSDimitry Andric     }
1405bdd1243dSDimitry Andric   }
1406bdd1243dSDimitry Andric 
1407bdd1243dSDimitry Andric   return false;
1408bdd1243dSDimitry Andric }
1409bdd1243dSDimitry Andric 
readConfigFile(StringRef CfgFile,SmallVectorImpl<const char * > & Argv)1410bdd1243dSDimitry Andric Error ExpansionContext::readConfigFile(StringRef CfgFile,
14110b57cec5SDimitry Andric                                        SmallVectorImpl<const char *> &Argv) {
1412480093f4SDimitry Andric   SmallString<128> AbsPath;
1413480093f4SDimitry Andric   if (sys::path::is_relative(CfgFile)) {
1414bdd1243dSDimitry Andric     AbsPath.assign(CfgFile);
1415bdd1243dSDimitry Andric     if (std::error_code EC = FS->makeAbsolute(AbsPath))
1416bdd1243dSDimitry Andric       return make_error<StringError>(
1417bdd1243dSDimitry Andric           EC, Twine("cannot get absolute path for " + CfgFile));
1418480093f4SDimitry Andric     CfgFile = AbsPath.str();
1419480093f4SDimitry Andric   }
1420bdd1243dSDimitry Andric   InConfigFile = true;
1421bdd1243dSDimitry Andric   RelativeNames = true;
1422bdd1243dSDimitry Andric   if (Error Err = expandResponseFile(CfgFile, Argv))
1423bdd1243dSDimitry Andric     return Err;
1424bdd1243dSDimitry Andric   return expandResponseFiles(Argv);
14250b57cec5SDimitry Andric }
14260b57cec5SDimitry Andric 
1427fe6060f1SDimitry Andric static void initCommonOptions();
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,const char * EnvVar,bool LongOptionsUseDoubleDash)14280b57cec5SDimitry Andric bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
14290b57cec5SDimitry Andric                                  StringRef Overview, raw_ostream *Errs,
14300b57cec5SDimitry Andric                                  const char *EnvVar,
14310b57cec5SDimitry Andric                                  bool LongOptionsUseDoubleDash) {
1432fe6060f1SDimitry Andric   initCommonOptions();
14330b57cec5SDimitry Andric   SmallVector<const char *, 20> NewArgv;
14340b57cec5SDimitry Andric   BumpPtrAllocator A;
14350b57cec5SDimitry Andric   StringSaver Saver(A);
14360b57cec5SDimitry Andric   NewArgv.push_back(argv[0]);
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric   // Parse options from environment variable.
14390b57cec5SDimitry Andric   if (EnvVar) {
1440bdd1243dSDimitry Andric     if (std::optional<std::string> EnvValue =
14410b57cec5SDimitry Andric             sys::Process::GetEnv(StringRef(EnvVar)))
14420b57cec5SDimitry Andric       TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
14430b57cec5SDimitry Andric   }
14440b57cec5SDimitry Andric 
14450b57cec5SDimitry Andric   // Append options from command line.
14460b57cec5SDimitry Andric   for (int I = 1; I < argc; ++I)
14470b57cec5SDimitry Andric     NewArgv.push_back(argv[I]);
14480b57cec5SDimitry Andric   int NewArgc = static_cast<int>(NewArgv.size());
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric   // Parse all options.
14510b57cec5SDimitry Andric   return GlobalParser->ParseCommandLineOptions(NewArgc, &NewArgv[0], Overview,
14520b57cec5SDimitry Andric                                                Errs, LongOptionsUseDoubleDash);
14530b57cec5SDimitry Andric }
14540b57cec5SDimitry Andric 
1455349cc55cSDimitry Andric /// Reset all options at least once, so that we can parse different options.
ResetAllOptionOccurrences()14560b57cec5SDimitry Andric void CommandLineParser::ResetAllOptionOccurrences() {
1457349cc55cSDimitry Andric   // Reset all option values to look like they have never been seen before.
1458349cc55cSDimitry Andric   // Options might be reset twice (they can be reference in both OptionsMap
1459349cc55cSDimitry Andric   // and one of the other members), but that does not harm.
1460fe6060f1SDimitry Andric   for (auto *SC : RegisteredSubCommands) {
14610b57cec5SDimitry Andric     for (auto &O : SC->OptionsMap)
14620b57cec5SDimitry Andric       O.second->reset();
1463349cc55cSDimitry Andric     for (Option *O : SC->PositionalOpts)
1464349cc55cSDimitry Andric       O->reset();
1465349cc55cSDimitry Andric     for (Option *O : SC->SinkOpts)
1466349cc55cSDimitry Andric       O->reset();
1467349cc55cSDimitry Andric     if (SC->ConsumeAfterOpt)
1468349cc55cSDimitry Andric       SC->ConsumeAfterOpt->reset();
14690b57cec5SDimitry Andric   }
14700b57cec5SDimitry Andric }
14710b57cec5SDimitry Andric 
ParseCommandLineOptions(int argc,const char * const * argv,StringRef Overview,raw_ostream * Errs,bool LongOptionsUseDoubleDash)14720b57cec5SDimitry Andric bool CommandLineParser::ParseCommandLineOptions(int argc,
14730b57cec5SDimitry Andric                                                 const char *const *argv,
14740b57cec5SDimitry Andric                                                 StringRef Overview,
14750b57cec5SDimitry Andric                                                 raw_ostream *Errs,
14760b57cec5SDimitry Andric                                                 bool LongOptionsUseDoubleDash) {
14770b57cec5SDimitry Andric   assert(hasOptions() && "No options specified!");
14780b57cec5SDimitry Andric 
14790b57cec5SDimitry Andric   ProgramOverview = Overview;
14800b57cec5SDimitry Andric   bool IgnoreErrors = Errs;
14810b57cec5SDimitry Andric   if (!Errs)
14820b57cec5SDimitry Andric     Errs = &errs();
14830b57cec5SDimitry Andric   bool ErrorParsing = false;
14840b57cec5SDimitry Andric 
1485bdd1243dSDimitry Andric   // Expand response files.
1486bdd1243dSDimitry Andric   SmallVector<const char *, 20> newArgv(argv, argv + argc);
1487bdd1243dSDimitry Andric   BumpPtrAllocator A;
1488bdd1243dSDimitry Andric #ifdef _WIN32
1489bdd1243dSDimitry Andric   auto Tokenize = cl::TokenizeWindowsCommandLine;
1490bdd1243dSDimitry Andric #else
1491bdd1243dSDimitry Andric   auto Tokenize = cl::TokenizeGNUCommandLine;
1492bdd1243dSDimitry Andric #endif
1493bdd1243dSDimitry Andric   ExpansionContext ECtx(A, Tokenize);
1494bdd1243dSDimitry Andric   if (Error Err = ECtx.expandResponseFiles(newArgv)) {
1495bdd1243dSDimitry Andric     *Errs << toString(std::move(Err)) << '\n';
1496bdd1243dSDimitry Andric     return false;
1497bdd1243dSDimitry Andric   }
1498bdd1243dSDimitry Andric   argv = &newArgv[0];
1499bdd1243dSDimitry Andric   argc = static_cast<int>(newArgv.size());
1500bdd1243dSDimitry Andric 
1501bdd1243dSDimitry Andric   // Copy the program name into ProgName, making sure not to overflow it.
1502bdd1243dSDimitry Andric   ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1503bdd1243dSDimitry Andric 
15040b57cec5SDimitry Andric   // Check out the positional arguments to collect information about them.
15050b57cec5SDimitry Andric   unsigned NumPositionalRequired = 0;
15060b57cec5SDimitry Andric 
15070b57cec5SDimitry Andric   // Determine whether or not there are an unlimited number of positionals
15080b57cec5SDimitry Andric   bool HasUnlimitedPositionals = false;
15090b57cec5SDimitry Andric 
15100b57cec5SDimitry Andric   int FirstArg = 1;
1511bdd1243dSDimitry Andric   SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
15125f757f3fSDimitry Andric   std::string NearestSubCommandString;
15135f757f3fSDimitry Andric   bool MaybeNamedSubCommand =
15145f757f3fSDimitry Andric       argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands();
15155f757f3fSDimitry Andric   if (MaybeNamedSubCommand) {
15160b57cec5SDimitry Andric     // If the first argument specifies a valid subcommand, start processing
15170b57cec5SDimitry Andric     // options from the second argument.
15185f757f3fSDimitry Andric     ChosenSubCommand =
15195f757f3fSDimitry Andric         LookupSubCommand(StringRef(argv[FirstArg]), NearestSubCommandString);
1520bdd1243dSDimitry Andric     if (ChosenSubCommand != &SubCommand::getTopLevel())
15210b57cec5SDimitry Andric       FirstArg = 2;
15220b57cec5SDimitry Andric   }
15230b57cec5SDimitry Andric   GlobalParser->ActiveSubCommand = ChosenSubCommand;
15240b57cec5SDimitry Andric 
15250b57cec5SDimitry Andric   assert(ChosenSubCommand);
15260b57cec5SDimitry Andric   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
15270b57cec5SDimitry Andric   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
15280b57cec5SDimitry Andric   auto &SinkOpts = ChosenSubCommand->SinkOpts;
15290b57cec5SDimitry Andric   auto &OptionsMap = ChosenSubCommand->OptionsMap;
15300b57cec5SDimitry Andric 
1531fe6060f1SDimitry Andric   for (auto *O: DefaultOptions) {
15320b57cec5SDimitry Andric     addOption(O, true);
15330b57cec5SDimitry Andric   }
15340b57cec5SDimitry Andric 
15350b57cec5SDimitry Andric   if (ConsumeAfterOpt) {
15360b57cec5SDimitry Andric     assert(PositionalOpts.size() > 0 &&
15370b57cec5SDimitry Andric            "Cannot specify cl::ConsumeAfter without a positional argument!");
15380b57cec5SDimitry Andric   }
15390b57cec5SDimitry Andric   if (!PositionalOpts.empty()) {
15400b57cec5SDimitry Andric 
15410b57cec5SDimitry Andric     // Calculate how many positional values are _required_.
15420b57cec5SDimitry Andric     bool UnboundedFound = false;
15430b57cec5SDimitry Andric     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
15440b57cec5SDimitry Andric       Option *Opt = PositionalOpts[i];
15450b57cec5SDimitry Andric       if (RequiresValue(Opt))
15460b57cec5SDimitry Andric         ++NumPositionalRequired;
15470b57cec5SDimitry Andric       else if (ConsumeAfterOpt) {
15480b57cec5SDimitry Andric         // ConsumeAfter cannot be combined with "optional" positional options
15490b57cec5SDimitry Andric         // unless there is only one positional argument...
15500b57cec5SDimitry Andric         if (PositionalOpts.size() > 1) {
15510b57cec5SDimitry Andric           if (!IgnoreErrors)
15520b57cec5SDimitry Andric             Opt->error("error - this positional option will never be matched, "
15530b57cec5SDimitry Andric                        "because it does not Require a value, and a "
15540b57cec5SDimitry Andric                        "cl::ConsumeAfter option is active!");
15550b57cec5SDimitry Andric           ErrorParsing = true;
15560b57cec5SDimitry Andric         }
15570b57cec5SDimitry Andric       } else if (UnboundedFound && !Opt->hasArgStr()) {
15580b57cec5SDimitry Andric         // This option does not "require" a value...  Make sure this option is
15590b57cec5SDimitry Andric         // not specified after an option that eats all extra arguments, or this
15600b57cec5SDimitry Andric         // one will never get any!
15610b57cec5SDimitry Andric         //
15620b57cec5SDimitry Andric         if (!IgnoreErrors)
15630b57cec5SDimitry Andric           Opt->error("error - option can never match, because "
15640b57cec5SDimitry Andric                      "another positional argument will match an "
15650b57cec5SDimitry Andric                      "unbounded number of values, and this option"
15660b57cec5SDimitry Andric                      " does not require a value!");
15670b57cec5SDimitry Andric         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
15680b57cec5SDimitry Andric               << "' is all messed up!\n";
15690b57cec5SDimitry Andric         *Errs << PositionalOpts.size();
15700b57cec5SDimitry Andric         ErrorParsing = true;
15710b57cec5SDimitry Andric       }
15720b57cec5SDimitry Andric       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
15730b57cec5SDimitry Andric     }
15740b57cec5SDimitry Andric     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
15750b57cec5SDimitry Andric   }
15760b57cec5SDimitry Andric 
15770b57cec5SDimitry Andric   // PositionalVals - A vector of "positional" arguments we accumulate into
15780b57cec5SDimitry Andric   // the process at the end.
15790b57cec5SDimitry Andric   //
15800b57cec5SDimitry Andric   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric   // If the program has named positional arguments, and the name has been run
15830b57cec5SDimitry Andric   // across, keep track of which positional argument was named.  Otherwise put
15840b57cec5SDimitry Andric   // the positional args into the PositionalVals list...
15850b57cec5SDimitry Andric   Option *ActivePositionalArg = nullptr;
15860b57cec5SDimitry Andric 
15870b57cec5SDimitry Andric   // Loop over all of the arguments... processing them.
15880b57cec5SDimitry Andric   bool DashDashFound = false; // Have we read '--'?
15890b57cec5SDimitry Andric   for (int i = FirstArg; i < argc; ++i) {
15900b57cec5SDimitry Andric     Option *Handler = nullptr;
15910b57cec5SDimitry Andric     std::string NearestHandlerString;
15920b57cec5SDimitry Andric     StringRef Value;
15930b57cec5SDimitry Andric     StringRef ArgName = "";
15940b57cec5SDimitry Andric     bool HaveDoubleDash = false;
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric     // Check to see if this is a positional argument.  This argument is
15970b57cec5SDimitry Andric     // considered to be positional if it doesn't start with '-', if it is "-"
15980b57cec5SDimitry Andric     // itself, or if we have seen "--" already.
15990b57cec5SDimitry Andric     //
16000b57cec5SDimitry Andric     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
16010b57cec5SDimitry Andric       // Positional argument!
16020b57cec5SDimitry Andric       if (ActivePositionalArg) {
16030b57cec5SDimitry Andric         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
16040b57cec5SDimitry Andric         continue; // We are done!
16050b57cec5SDimitry Andric       }
16060b57cec5SDimitry Andric 
16070b57cec5SDimitry Andric       if (!PositionalOpts.empty()) {
16080b57cec5SDimitry Andric         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
16090b57cec5SDimitry Andric 
16100b57cec5SDimitry Andric         // All of the positional arguments have been fulfulled, give the rest to
16110b57cec5SDimitry Andric         // the consume after option... if it's specified...
16120b57cec5SDimitry Andric         //
16130b57cec5SDimitry Andric         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
16140b57cec5SDimitry Andric           for (++i; i < argc; ++i)
16150b57cec5SDimitry Andric             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
16160b57cec5SDimitry Andric           break; // Handle outside of the argument processing loop...
16170b57cec5SDimitry Andric         }
16180b57cec5SDimitry Andric 
16190b57cec5SDimitry Andric         // Delay processing positional arguments until the end...
16200b57cec5SDimitry Andric         continue;
16210b57cec5SDimitry Andric       }
16220b57cec5SDimitry Andric     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
16230b57cec5SDimitry Andric                !DashDashFound) {
16240b57cec5SDimitry Andric       DashDashFound = true; // This is the mythical "--"?
16250b57cec5SDimitry Andric       continue;             // Don't try to process it as an argument itself.
16260b57cec5SDimitry Andric     } else if (ActivePositionalArg &&
16270b57cec5SDimitry Andric                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
16280b57cec5SDimitry Andric       // If there is a positional argument eating options, check to see if this
16290b57cec5SDimitry Andric       // option is another positional argument.  If so, treat it as an argument,
16300b57cec5SDimitry Andric       // otherwise feed it to the eating positional.
16310b57cec5SDimitry Andric       ArgName = StringRef(argv[i] + 1);
16320b57cec5SDimitry Andric       // Eat second dash.
16337a6dacacSDimitry Andric       if (ArgName.consume_front("-"))
16340b57cec5SDimitry Andric         HaveDoubleDash = true;
16350b57cec5SDimitry Andric 
16360b57cec5SDimitry Andric       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
16370b57cec5SDimitry Andric                                  LongOptionsUseDoubleDash, HaveDoubleDash);
16380b57cec5SDimitry Andric       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
16390b57cec5SDimitry Andric         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
16400b57cec5SDimitry Andric         continue; // We are done!
16410b57cec5SDimitry Andric       }
16420b57cec5SDimitry Andric     } else { // We start with a '-', must be an argument.
16430b57cec5SDimitry Andric       ArgName = StringRef(argv[i] + 1);
16440b57cec5SDimitry Andric       // Eat second dash.
16457a6dacacSDimitry Andric       if (ArgName.consume_front("-"))
16460b57cec5SDimitry Andric         HaveDoubleDash = true;
16470b57cec5SDimitry Andric 
16480b57cec5SDimitry Andric       Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
16490b57cec5SDimitry Andric                                  LongOptionsUseDoubleDash, HaveDoubleDash);
16500b57cec5SDimitry Andric 
16515f757f3fSDimitry Andric       // If Handler is not found in a specialized subcommand, look up handler
16525f757f3fSDimitry Andric       // in the top-level subcommand.
16535f757f3fSDimitry Andric       // cl::opt without cl::sub belongs to top-level subcommand.
16545f757f3fSDimitry Andric       if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel())
16555f757f3fSDimitry Andric         Handler = LookupLongOption(SubCommand::getTopLevel(), ArgName, Value,
16565f757f3fSDimitry Andric                                    LongOptionsUseDoubleDash, HaveDoubleDash);
16575f757f3fSDimitry Andric 
16580b57cec5SDimitry Andric       // Check to see if this "option" is really a prefixed or grouped argument.
16590b57cec5SDimitry Andric       if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
16600b57cec5SDimitry Andric         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
16610b57cec5SDimitry Andric                                                 OptionsMap);
16620b57cec5SDimitry Andric 
16630b57cec5SDimitry Andric       // Otherwise, look for the closest available option to report to the user
16640b57cec5SDimitry Andric       // in the upcoming error.
16650b57cec5SDimitry Andric       if (!Handler && SinkOpts.empty())
16660b57cec5SDimitry Andric         LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
16670b57cec5SDimitry Andric     }
16680b57cec5SDimitry Andric 
16690b57cec5SDimitry Andric     if (!Handler) {
16705f757f3fSDimitry Andric       if (!SinkOpts.empty()) {
16710eae32dcSDimitry Andric         for (Option *SinkOpt : SinkOpts)
16720eae32dcSDimitry Andric           SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
16735f757f3fSDimitry Andric         continue;
16740b57cec5SDimitry Andric       }
16755f757f3fSDimitry Andric 
16765f757f3fSDimitry Andric       auto ReportUnknownArgument = [&](bool IsArg,
16775f757f3fSDimitry Andric                                        StringRef NearestArgumentName) {
16785f757f3fSDimitry Andric         *Errs << ProgramName << ": Unknown "
16795f757f3fSDimitry Andric               << (IsArg ? "command line argument" : "subcommand") << " '"
16805f757f3fSDimitry Andric               << argv[i] << "'.  Try: '" << argv[0] << " --help'\n";
16815f757f3fSDimitry Andric 
16825f757f3fSDimitry Andric         if (NearestArgumentName.empty())
16835f757f3fSDimitry Andric           return;
16845f757f3fSDimitry Andric 
16855f757f3fSDimitry Andric         *Errs << ProgramName << ": Did you mean '";
16865f757f3fSDimitry Andric         if (IsArg)
16875f757f3fSDimitry Andric           *Errs << PrintArg(NearestArgumentName, 0);
16885f757f3fSDimitry Andric         else
16895f757f3fSDimitry Andric           *Errs << NearestArgumentName;
16905f757f3fSDimitry Andric         *Errs << "'?\n";
16915f757f3fSDimitry Andric       };
16925f757f3fSDimitry Andric 
16935f757f3fSDimitry Andric       if (i > 1 || !MaybeNamedSubCommand)
16945f757f3fSDimitry Andric         ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString);
16955f757f3fSDimitry Andric       else
16965f757f3fSDimitry Andric         ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString);
16975f757f3fSDimitry Andric 
16985f757f3fSDimitry Andric       ErrorParsing = true;
16990b57cec5SDimitry Andric       continue;
17000b57cec5SDimitry Andric     }
17010b57cec5SDimitry Andric 
17020b57cec5SDimitry Andric     // If this is a named positional argument, just remember that it is the
17030b57cec5SDimitry Andric     // active one...
17040b57cec5SDimitry Andric     if (Handler->getFormattingFlag() == cl::Positional) {
17050b57cec5SDimitry Andric       if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
17060b57cec5SDimitry Andric         Handler->error("This argument does not take a value.\n"
17070b57cec5SDimitry Andric                        "\tInstead, it consumes any positional arguments until "
17080b57cec5SDimitry Andric                        "the next recognized option.", *Errs);
17090b57cec5SDimitry Andric         ErrorParsing = true;
17100b57cec5SDimitry Andric       }
17110b57cec5SDimitry Andric       ActivePositionalArg = Handler;
17120b57cec5SDimitry Andric     }
17130b57cec5SDimitry Andric     else
17140b57cec5SDimitry Andric       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
17150b57cec5SDimitry Andric   }
17160b57cec5SDimitry Andric 
17170b57cec5SDimitry Andric   // Check and handle positional arguments now...
17180b57cec5SDimitry Andric   if (NumPositionalRequired > PositionalVals.size()) {
17190b57cec5SDimitry Andric       *Errs << ProgramName
17200b57cec5SDimitry Andric              << ": Not enough positional command line arguments specified!\n"
17210b57cec5SDimitry Andric              << "Must specify at least " << NumPositionalRequired
17220b57cec5SDimitry Andric              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
17230b57cec5SDimitry Andric              << ": See: " << argv[0] << " --help\n";
17240b57cec5SDimitry Andric 
17250b57cec5SDimitry Andric     ErrorParsing = true;
17260b57cec5SDimitry Andric   } else if (!HasUnlimitedPositionals &&
17270b57cec5SDimitry Andric              PositionalVals.size() > PositionalOpts.size()) {
17280b57cec5SDimitry Andric     *Errs << ProgramName << ": Too many positional arguments specified!\n"
17290b57cec5SDimitry Andric           << "Can specify at most " << PositionalOpts.size()
17300b57cec5SDimitry Andric           << " positional arguments: See: " << argv[0] << " --help\n";
17310b57cec5SDimitry Andric     ErrorParsing = true;
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   } else if (!ConsumeAfterOpt) {
17340b57cec5SDimitry Andric     // Positional args have already been handled if ConsumeAfter is specified.
17350b57cec5SDimitry Andric     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
17360b57cec5SDimitry Andric     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
17370b57cec5SDimitry Andric       if (RequiresValue(PositionalOpts[i])) {
17380b57cec5SDimitry Andric         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
17390b57cec5SDimitry Andric                                 PositionalVals[ValNo].second);
17400b57cec5SDimitry Andric         ValNo++;
17410b57cec5SDimitry Andric         --NumPositionalRequired; // We fulfilled our duty...
17420b57cec5SDimitry Andric       }
17430b57cec5SDimitry Andric 
17440b57cec5SDimitry Andric       // If we _can_ give this option more arguments, do so now, as long as we
17450b57cec5SDimitry Andric       // do not give it values that others need.  'Done' controls whether the
17460b57cec5SDimitry Andric       // option even _WANTS_ any more.
17470b57cec5SDimitry Andric       //
17480b57cec5SDimitry Andric       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
17490b57cec5SDimitry Andric       while (NumVals - ValNo > NumPositionalRequired && !Done) {
17500b57cec5SDimitry Andric         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
17510b57cec5SDimitry Andric         case cl::Optional:
17520b57cec5SDimitry Andric           Done = true; // Optional arguments want _at most_ one value
1753bdd1243dSDimitry Andric           [[fallthrough]];
17540b57cec5SDimitry Andric         case cl::ZeroOrMore: // Zero or more will take all they can get...
17550b57cec5SDimitry Andric         case cl::OneOrMore:  // One or more will take all they can get...
17560b57cec5SDimitry Andric           ProvidePositionalOption(PositionalOpts[i],
17570b57cec5SDimitry Andric                                   PositionalVals[ValNo].first,
17580b57cec5SDimitry Andric                                   PositionalVals[ValNo].second);
17590b57cec5SDimitry Andric           ValNo++;
17600b57cec5SDimitry Andric           break;
17610b57cec5SDimitry Andric         default:
17620b57cec5SDimitry Andric           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
17630b57cec5SDimitry Andric                            "positional argument processing!");
17640b57cec5SDimitry Andric         }
17650b57cec5SDimitry Andric       }
17660b57cec5SDimitry Andric     }
17670b57cec5SDimitry Andric   } else {
17680b57cec5SDimitry Andric     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
17690b57cec5SDimitry Andric     unsigned ValNo = 0;
17705ffd83dbSDimitry Andric     for (size_t J = 0, E = PositionalOpts.size(); J != E; ++J)
17715ffd83dbSDimitry Andric       if (RequiresValue(PositionalOpts[J])) {
17725ffd83dbSDimitry Andric         ErrorParsing |= ProvidePositionalOption(PositionalOpts[J],
17730b57cec5SDimitry Andric                                                 PositionalVals[ValNo].first,
17740b57cec5SDimitry Andric                                                 PositionalVals[ValNo].second);
17750b57cec5SDimitry Andric         ValNo++;
17760b57cec5SDimitry Andric       }
17770b57cec5SDimitry Andric 
17780b57cec5SDimitry Andric     // Handle the case where there is just one positional option, and it's
17790b57cec5SDimitry Andric     // optional.  In this case, we want to give JUST THE FIRST option to the
17800b57cec5SDimitry Andric     // positional option and keep the rest for the consume after.  The above
17810b57cec5SDimitry Andric     // loop would have assigned no values to positional options in this case.
17820b57cec5SDimitry Andric     //
17830b57cec5SDimitry Andric     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
17840b57cec5SDimitry Andric       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
17850b57cec5SDimitry Andric                                               PositionalVals[ValNo].first,
17860b57cec5SDimitry Andric                                               PositionalVals[ValNo].second);
17870b57cec5SDimitry Andric       ValNo++;
17880b57cec5SDimitry Andric     }
17890b57cec5SDimitry Andric 
17900b57cec5SDimitry Andric     // Handle over all of the rest of the arguments to the
17910b57cec5SDimitry Andric     // cl::ConsumeAfter command line option...
17920b57cec5SDimitry Andric     for (; ValNo != PositionalVals.size(); ++ValNo)
17930b57cec5SDimitry Andric       ErrorParsing |=
17940b57cec5SDimitry Andric           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
17950b57cec5SDimitry Andric                                   PositionalVals[ValNo].second);
17960b57cec5SDimitry Andric   }
17970b57cec5SDimitry Andric 
17980b57cec5SDimitry Andric   // Loop over args and make sure all required args are specified!
17990b57cec5SDimitry Andric   for (const auto &Opt : OptionsMap) {
18000b57cec5SDimitry Andric     switch (Opt.second->getNumOccurrencesFlag()) {
18010b57cec5SDimitry Andric     case Required:
18020b57cec5SDimitry Andric     case OneOrMore:
18030b57cec5SDimitry Andric       if (Opt.second->getNumOccurrences() == 0) {
18040b57cec5SDimitry Andric         Opt.second->error("must be specified at least once!");
18050b57cec5SDimitry Andric         ErrorParsing = true;
18060b57cec5SDimitry Andric       }
1807bdd1243dSDimitry Andric       [[fallthrough]];
18080b57cec5SDimitry Andric     default:
18090b57cec5SDimitry Andric       break;
18100b57cec5SDimitry Andric     }
18110b57cec5SDimitry Andric   }
18120b57cec5SDimitry Andric 
18130b57cec5SDimitry Andric   // Now that we know if -debug is specified, we can use it.
18140b57cec5SDimitry Andric   // Note that if ReadResponseFiles == true, this must be done before the
18150b57cec5SDimitry Andric   // memory allocated for the expanded command line is free()d below.
18160b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Args: ";
18170b57cec5SDimitry Andric              for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
18180b57cec5SDimitry Andric              dbgs() << '\n';);
18190b57cec5SDimitry Andric 
18200b57cec5SDimitry Andric   // Free all of the memory allocated to the map.  Command line options may only
18210b57cec5SDimitry Andric   // be processed once!
18220b57cec5SDimitry Andric   MoreHelp.clear();
18230b57cec5SDimitry Andric 
18240b57cec5SDimitry Andric   // If we had an error processing our arguments, don't let the program execute
18250b57cec5SDimitry Andric   if (ErrorParsing) {
18260b57cec5SDimitry Andric     if (!IgnoreErrors)
18270b57cec5SDimitry Andric       exit(1);
18280b57cec5SDimitry Andric     return false;
18290b57cec5SDimitry Andric   }
18300b57cec5SDimitry Andric   return true;
18310b57cec5SDimitry Andric }
18320b57cec5SDimitry Andric 
18330b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18340b57cec5SDimitry Andric // Option Base class implementation
18350b57cec5SDimitry Andric //
18360b57cec5SDimitry Andric 
error(const Twine & Message,StringRef ArgName,raw_ostream & Errs)18370b57cec5SDimitry Andric bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
18380b57cec5SDimitry Andric   if (!ArgName.data())
18390b57cec5SDimitry Andric     ArgName = ArgStr;
18400b57cec5SDimitry Andric   if (ArgName.empty())
18410b57cec5SDimitry Andric     Errs << HelpStr; // Be nice for positional arguments
18420b57cec5SDimitry Andric   else
1843480093f4SDimitry Andric     Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
18440b57cec5SDimitry Andric 
18450b57cec5SDimitry Andric   Errs << " option: " << Message << "\n";
18460b57cec5SDimitry Andric   return true;
18470b57cec5SDimitry Andric }
18480b57cec5SDimitry Andric 
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)18490b57cec5SDimitry Andric bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
18500b57cec5SDimitry Andric                            bool MultiArg) {
18510b57cec5SDimitry Andric   if (!MultiArg)
18520b57cec5SDimitry Andric     NumOccurrences++; // Increment the number of times we have been seen
18530b57cec5SDimitry Andric 
18540b57cec5SDimitry Andric   return handleOccurrence(pos, ArgName, Value);
18550b57cec5SDimitry Andric }
18560b57cec5SDimitry Andric 
18570b57cec5SDimitry Andric // getValueStr - Get the value description string, using "DefaultMsg" if nothing
18580b57cec5SDimitry Andric // has been specified yet.
18590b57cec5SDimitry Andric //
getValueStr(const Option & O,StringRef DefaultMsg)18600b57cec5SDimitry Andric static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
18610b57cec5SDimitry Andric   if (O.ValueStr.empty())
18620b57cec5SDimitry Andric     return DefaultMsg;
18630b57cec5SDimitry Andric   return O.ValueStr;
18640b57cec5SDimitry Andric }
18650b57cec5SDimitry Andric 
18660b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
18670b57cec5SDimitry Andric // cl::alias class implementation
18680b57cec5SDimitry Andric //
18690b57cec5SDimitry Andric 
18700b57cec5SDimitry Andric // Return the width of the option tag for printing...
getOptionWidth() const18710b57cec5SDimitry Andric size_t alias::getOptionWidth() const {
18720b57cec5SDimitry Andric   return argPlusPrefixesSize(ArgStr);
18730b57cec5SDimitry Andric }
18740b57cec5SDimitry Andric 
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)18750b57cec5SDimitry Andric void Option::printHelpStr(StringRef HelpStr, size_t Indent,
18760b57cec5SDimitry Andric                           size_t FirstLineIndentedBy) {
18770b57cec5SDimitry Andric   assert(Indent >= FirstLineIndentedBy);
18780b57cec5SDimitry Andric   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
18790b57cec5SDimitry Andric   outs().indent(Indent - FirstLineIndentedBy)
18800b57cec5SDimitry Andric       << ArgHelpPrefix << Split.first << "\n";
18810b57cec5SDimitry Andric   while (!Split.second.empty()) {
18820b57cec5SDimitry Andric     Split = Split.second.split('\n');
18830b57cec5SDimitry Andric     outs().indent(Indent) << Split.first << "\n";
18840b57cec5SDimitry Andric   }
18850b57cec5SDimitry Andric }
18860b57cec5SDimitry Andric 
printEnumValHelpStr(StringRef HelpStr,size_t BaseIndent,size_t FirstLineIndentedBy)1887d409305fSDimitry Andric void Option::printEnumValHelpStr(StringRef HelpStr, size_t BaseIndent,
1888d409305fSDimitry Andric                                  size_t FirstLineIndentedBy) {
1889d409305fSDimitry Andric   const StringRef ValHelpPrefix = "  ";
189023408297SDimitry Andric   assert(BaseIndent >= FirstLineIndentedBy);
1891d409305fSDimitry Andric   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1892d409305fSDimitry Andric   outs().indent(BaseIndent - FirstLineIndentedBy)
1893d409305fSDimitry Andric       << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1894d409305fSDimitry Andric   while (!Split.second.empty()) {
1895d409305fSDimitry Andric     Split = Split.second.split('\n');
1896d409305fSDimitry Andric     outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1897d409305fSDimitry Andric   }
1898d409305fSDimitry Andric }
1899d409305fSDimitry Andric 
19000b57cec5SDimitry Andric // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const19010b57cec5SDimitry Andric void alias::printOptionInfo(size_t GlobalWidth) const {
19020b57cec5SDimitry Andric   outs() << PrintArg(ArgStr);
19030b57cec5SDimitry Andric   printHelpStr(HelpStr, GlobalWidth, argPlusPrefixesSize(ArgStr));
19040b57cec5SDimitry Andric }
19050b57cec5SDimitry Andric 
19060b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19070b57cec5SDimitry Andric // Parser Implementation code...
19080b57cec5SDimitry Andric //
19090b57cec5SDimitry Andric 
19100b57cec5SDimitry Andric // basic_parser implementation
19110b57cec5SDimitry Andric //
19120b57cec5SDimitry Andric 
19130b57cec5SDimitry Andric // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const19140b57cec5SDimitry Andric size_t basic_parser_impl::getOptionWidth(const Option &O) const {
19150b57cec5SDimitry Andric   size_t Len = argPlusPrefixesSize(O.ArgStr);
19160b57cec5SDimitry Andric   auto ValName = getValueName();
19170b57cec5SDimitry Andric   if (!ValName.empty()) {
19180b57cec5SDimitry Andric     size_t FormattingLen = 3;
19190b57cec5SDimitry Andric     if (O.getMiscFlags() & PositionalEatsArgs)
19200b57cec5SDimitry Andric       FormattingLen = 6;
19210b57cec5SDimitry Andric     Len += getValueStr(O, ValName).size() + FormattingLen;
19220b57cec5SDimitry Andric   }
19230b57cec5SDimitry Andric 
19240b57cec5SDimitry Andric   return Len;
19250b57cec5SDimitry Andric }
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric // printOptionInfo - Print out information about this option.  The
19280b57cec5SDimitry Andric // to-be-maintained width is specified.
19290b57cec5SDimitry Andric //
printOptionInfo(const Option & O,size_t GlobalWidth) const19300b57cec5SDimitry Andric void basic_parser_impl::printOptionInfo(const Option &O,
19310b57cec5SDimitry Andric                                         size_t GlobalWidth) const {
19320b57cec5SDimitry Andric   outs() << PrintArg(O.ArgStr);
19330b57cec5SDimitry Andric 
19340b57cec5SDimitry Andric   auto ValName = getValueName();
19350b57cec5SDimitry Andric   if (!ValName.empty()) {
19360b57cec5SDimitry Andric     if (O.getMiscFlags() & PositionalEatsArgs) {
19370b57cec5SDimitry Andric       outs() << " <" << getValueStr(O, ValName) << ">...";
19385ffd83dbSDimitry Andric     } else if (O.getValueExpectedFlag() == ValueOptional)
19395ffd83dbSDimitry Andric       outs() << "[=<" << getValueStr(O, ValName) << ">]";
1940753f127fSDimitry Andric     else {
1941753f127fSDimitry Andric       outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1942753f127fSDimitry Andric              << '>';
1943753f127fSDimitry Andric     }
19440b57cec5SDimitry Andric   }
19450b57cec5SDimitry Andric 
19460b57cec5SDimitry Andric   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
19470b57cec5SDimitry Andric }
19480b57cec5SDimitry Andric 
printOptionName(const Option & O,size_t GlobalWidth) const19490b57cec5SDimitry Andric void basic_parser_impl::printOptionName(const Option &O,
19500b57cec5SDimitry Andric                                         size_t GlobalWidth) const {
19510b57cec5SDimitry Andric   outs() << PrintArg(O.ArgStr);
19520b57cec5SDimitry Andric   outs().indent(GlobalWidth - O.ArgStr.size());
19530b57cec5SDimitry Andric }
19540b57cec5SDimitry Andric 
19550b57cec5SDimitry Andric // parser<bool> implementation
19560b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)19570b57cec5SDimitry Andric bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
19580b57cec5SDimitry Andric                          bool &Value) {
19590b57cec5SDimitry Andric   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
19600b57cec5SDimitry Andric       Arg == "1") {
19610b57cec5SDimitry Andric     Value = true;
19620b57cec5SDimitry Andric     return false;
19630b57cec5SDimitry Andric   }
19640b57cec5SDimitry Andric 
19650b57cec5SDimitry Andric   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
19660b57cec5SDimitry Andric     Value = false;
19670b57cec5SDimitry Andric     return false;
19680b57cec5SDimitry Andric   }
19690b57cec5SDimitry Andric   return O.error("'" + Arg +
19700b57cec5SDimitry Andric                  "' is invalid value for boolean argument! Try 0 or 1");
19710b57cec5SDimitry Andric }
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric // parser<boolOrDefault> implementation
19740b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)19750b57cec5SDimitry Andric bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
19760b57cec5SDimitry Andric                                   boolOrDefault &Value) {
19770b57cec5SDimitry Andric   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
19780b57cec5SDimitry Andric       Arg == "1") {
19790b57cec5SDimitry Andric     Value = BOU_TRUE;
19800b57cec5SDimitry Andric     return false;
19810b57cec5SDimitry Andric   }
19820b57cec5SDimitry Andric   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
19830b57cec5SDimitry Andric     Value = BOU_FALSE;
19840b57cec5SDimitry Andric     return false;
19850b57cec5SDimitry Andric   }
19860b57cec5SDimitry Andric 
19870b57cec5SDimitry Andric   return O.error("'" + Arg +
19880b57cec5SDimitry Andric                  "' is invalid value for boolean argument! Try 0 or 1");
19890b57cec5SDimitry Andric }
19900b57cec5SDimitry Andric 
19910b57cec5SDimitry Andric // parser<int> implementation
19920b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)19930b57cec5SDimitry Andric bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
19940b57cec5SDimitry Andric                         int &Value) {
19950b57cec5SDimitry Andric   if (Arg.getAsInteger(0, Value))
19960b57cec5SDimitry Andric     return O.error("'" + Arg + "' value invalid for integer argument!");
19970b57cec5SDimitry Andric   return false;
19980b57cec5SDimitry Andric }
19990b57cec5SDimitry Andric 
2000480093f4SDimitry Andric // parser<long> implementation
2001480093f4SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,long & Value)2002480093f4SDimitry Andric bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2003480093f4SDimitry Andric                          long &Value) {
2004480093f4SDimitry Andric   if (Arg.getAsInteger(0, Value))
2005480093f4SDimitry Andric     return O.error("'" + Arg + "' value invalid for long argument!");
2006480093f4SDimitry Andric   return false;
2007480093f4SDimitry Andric }
2008480093f4SDimitry Andric 
2009480093f4SDimitry Andric // parser<long long> implementation
2010480093f4SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,long long & Value)2011480093f4SDimitry Andric bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2012480093f4SDimitry Andric                               long long &Value) {
2013480093f4SDimitry Andric   if (Arg.getAsInteger(0, Value))
2014480093f4SDimitry Andric     return O.error("'" + Arg + "' value invalid for llong argument!");
2015480093f4SDimitry Andric   return false;
2016480093f4SDimitry Andric }
2017480093f4SDimitry Andric 
20180b57cec5SDimitry Andric // parser<unsigned> implementation
20190b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)20200b57cec5SDimitry Andric bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
20210b57cec5SDimitry Andric                              unsigned &Value) {
20220b57cec5SDimitry Andric 
20230b57cec5SDimitry Andric   if (Arg.getAsInteger(0, Value))
20240b57cec5SDimitry Andric     return O.error("'" + Arg + "' value invalid for uint argument!");
20250b57cec5SDimitry Andric   return false;
20260b57cec5SDimitry Andric }
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric // parser<unsigned long> implementation
20290b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long & Value)20300b57cec5SDimitry Andric bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
20310b57cec5SDimitry Andric                                   unsigned long &Value) {
20320b57cec5SDimitry Andric 
20330b57cec5SDimitry Andric   if (Arg.getAsInteger(0, Value))
20340b57cec5SDimitry Andric     return O.error("'" + Arg + "' value invalid for ulong argument!");
20350b57cec5SDimitry Andric   return false;
20360b57cec5SDimitry Andric }
20370b57cec5SDimitry Andric 
20380b57cec5SDimitry Andric // parser<unsigned long long> implementation
20390b57cec5SDimitry Andric //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)20400b57cec5SDimitry Andric bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
20410b57cec5SDimitry Andric                                        StringRef Arg,
20420b57cec5SDimitry Andric                                        unsigned long long &Value) {
20430b57cec5SDimitry Andric 
20440b57cec5SDimitry Andric   if (Arg.getAsInteger(0, Value))
20450b57cec5SDimitry Andric     return O.error("'" + Arg + "' value invalid for ullong argument!");
20460b57cec5SDimitry Andric   return false;
20470b57cec5SDimitry Andric }
20480b57cec5SDimitry Andric 
20490b57cec5SDimitry Andric // parser<double>/parser<float> implementation
20500b57cec5SDimitry Andric //
parseDouble(Option & O,StringRef Arg,double & Value)20510b57cec5SDimitry Andric static bool parseDouble(Option &O, StringRef Arg, double &Value) {
20520b57cec5SDimitry Andric   if (to_float(Arg, Value))
20530b57cec5SDimitry Andric     return false;
20540b57cec5SDimitry Andric   return O.error("'" + Arg + "' value invalid for floating point argument!");
20550b57cec5SDimitry Andric }
20560b57cec5SDimitry Andric 
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)20570b57cec5SDimitry Andric bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
20580b57cec5SDimitry Andric                            double &Val) {
20590b57cec5SDimitry Andric   return parseDouble(O, Arg, Val);
20600b57cec5SDimitry Andric }
20610b57cec5SDimitry Andric 
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)20620b57cec5SDimitry Andric bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
20630b57cec5SDimitry Andric                           float &Val) {
20640b57cec5SDimitry Andric   double dVal;
20650b57cec5SDimitry Andric   if (parseDouble(O, Arg, dVal))
20660b57cec5SDimitry Andric     return true;
20670b57cec5SDimitry Andric   Val = (float)dVal;
20680b57cec5SDimitry Andric   return false;
20690b57cec5SDimitry Andric }
20700b57cec5SDimitry Andric 
20710b57cec5SDimitry Andric // generic_parser_base implementation
20720b57cec5SDimitry Andric //
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric // findOption - Return the option number corresponding to the specified
20750b57cec5SDimitry Andric // argument string.  If the option is not found, getNumOptions() is returned.
20760b57cec5SDimitry Andric //
findOption(StringRef Name)20770b57cec5SDimitry Andric unsigned generic_parser_base::findOption(StringRef Name) {
20780b57cec5SDimitry Andric   unsigned e = getNumOptions();
20790b57cec5SDimitry Andric 
20800b57cec5SDimitry Andric   for (unsigned i = 0; i != e; ++i) {
20810b57cec5SDimitry Andric     if (getOption(i) == Name)
20820b57cec5SDimitry Andric       return i;
20830b57cec5SDimitry Andric   }
20840b57cec5SDimitry Andric   return e;
20850b57cec5SDimitry Andric }
20860b57cec5SDimitry Andric 
20870b57cec5SDimitry Andric static StringRef EqValue = "=<value>";
20880b57cec5SDimitry Andric static StringRef EmptyOption = "<empty>";
20890b57cec5SDimitry Andric static StringRef OptionPrefix = "    =";
getOptionPrefixesSize()2090fe6060f1SDimitry Andric static size_t getOptionPrefixesSize() {
2091fe6060f1SDimitry Andric   return OptionPrefix.size() + ArgHelpPrefix.size();
2092fe6060f1SDimitry Andric }
20930b57cec5SDimitry Andric 
shouldPrintOption(StringRef Name,StringRef Description,const Option & O)20940b57cec5SDimitry Andric static bool shouldPrintOption(StringRef Name, StringRef Description,
20950b57cec5SDimitry Andric                               const Option &O) {
20960b57cec5SDimitry Andric   return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
20970b57cec5SDimitry Andric          !Description.empty();
20980b57cec5SDimitry Andric }
20990b57cec5SDimitry Andric 
21000b57cec5SDimitry Andric // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const21010b57cec5SDimitry Andric size_t generic_parser_base::getOptionWidth(const Option &O) const {
21020b57cec5SDimitry Andric   if (O.hasArgStr()) {
21030b57cec5SDimitry Andric     size_t Size =
21040b57cec5SDimitry Andric         argPlusPrefixesSize(O.ArgStr) + EqValue.size();
21050b57cec5SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
21060b57cec5SDimitry Andric       StringRef Name = getOption(i);
21070b57cec5SDimitry Andric       if (!shouldPrintOption(Name, getDescription(i), O))
21080b57cec5SDimitry Andric         continue;
21090b57cec5SDimitry Andric       size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2110fe6060f1SDimitry Andric       Size = std::max(Size, NameSize + getOptionPrefixesSize());
21110b57cec5SDimitry Andric     }
21120b57cec5SDimitry Andric     return Size;
21130b57cec5SDimitry Andric   } else {
21140b57cec5SDimitry Andric     size_t BaseSize = 0;
21150b57cec5SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
21160b57cec5SDimitry Andric       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
21170b57cec5SDimitry Andric     return BaseSize;
21180b57cec5SDimitry Andric   }
21190b57cec5SDimitry Andric }
21200b57cec5SDimitry Andric 
21210b57cec5SDimitry Andric // printOptionInfo - Print out information about this option.  The
21220b57cec5SDimitry Andric // to-be-maintained width is specified.
21230b57cec5SDimitry Andric //
printOptionInfo(const Option & O,size_t GlobalWidth) const21240b57cec5SDimitry Andric void generic_parser_base::printOptionInfo(const Option &O,
21250b57cec5SDimitry Andric                                           size_t GlobalWidth) const {
21260b57cec5SDimitry Andric   if (O.hasArgStr()) {
21270b57cec5SDimitry Andric     // When the value is optional, first print a line just describing the
21280b57cec5SDimitry Andric     // option without values.
21290b57cec5SDimitry Andric     if (O.getValueExpectedFlag() == ValueOptional) {
21300b57cec5SDimitry Andric       for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
21310b57cec5SDimitry Andric         if (getOption(i).empty()) {
21320b57cec5SDimitry Andric           outs() << PrintArg(O.ArgStr);
21330b57cec5SDimitry Andric           Option::printHelpStr(O.HelpStr, GlobalWidth,
21340b57cec5SDimitry Andric                                argPlusPrefixesSize(O.ArgStr));
21350b57cec5SDimitry Andric           break;
21360b57cec5SDimitry Andric         }
21370b57cec5SDimitry Andric       }
21380b57cec5SDimitry Andric     }
21390b57cec5SDimitry Andric 
21400b57cec5SDimitry Andric     outs() << PrintArg(O.ArgStr) << EqValue;
21410b57cec5SDimitry Andric     Option::printHelpStr(O.HelpStr, GlobalWidth,
21420b57cec5SDimitry Andric                          EqValue.size() +
21430b57cec5SDimitry Andric                              argPlusPrefixesSize(O.ArgStr));
21440b57cec5SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
21450b57cec5SDimitry Andric       StringRef OptionName = getOption(i);
21460b57cec5SDimitry Andric       StringRef Description = getDescription(i);
21470b57cec5SDimitry Andric       if (!shouldPrintOption(OptionName, Description, O))
21480b57cec5SDimitry Andric         continue;
2149fe6060f1SDimitry Andric       size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
21500b57cec5SDimitry Andric       outs() << OptionPrefix << OptionName;
21510b57cec5SDimitry Andric       if (OptionName.empty()) {
21520b57cec5SDimitry Andric         outs() << EmptyOption;
2153d409305fSDimitry Andric         assert(FirstLineIndent >= EmptyOption.size());
2154d409305fSDimitry Andric         FirstLineIndent += EmptyOption.size();
21550b57cec5SDimitry Andric       }
21560b57cec5SDimitry Andric       if (!Description.empty())
2157d409305fSDimitry Andric         Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2158d409305fSDimitry Andric       else
21590b57cec5SDimitry Andric         outs() << '\n';
21600b57cec5SDimitry Andric     }
21610b57cec5SDimitry Andric   } else {
21620b57cec5SDimitry Andric     if (!O.HelpStr.empty())
21630b57cec5SDimitry Andric       outs() << "  " << O.HelpStr << '\n';
21640b57cec5SDimitry Andric     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
21650b57cec5SDimitry Andric       StringRef Option = getOption(i);
21660b57cec5SDimitry Andric       outs() << "    " << PrintArg(Option);
21670b57cec5SDimitry Andric       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
21680b57cec5SDimitry Andric     }
21690b57cec5SDimitry Andric   }
21700b57cec5SDimitry Andric }
21710b57cec5SDimitry Andric 
21720b57cec5SDimitry Andric static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
21730b57cec5SDimitry Andric 
21740b57cec5SDimitry Andric // printGenericOptionDiff - Print the value of this option and it's default.
21750b57cec5SDimitry Andric //
21760b57cec5SDimitry Andric // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const21770b57cec5SDimitry Andric void generic_parser_base::printGenericOptionDiff(
21780b57cec5SDimitry Andric     const Option &O, const GenericOptionValue &Value,
21790b57cec5SDimitry Andric     const GenericOptionValue &Default, size_t GlobalWidth) const {
21800b57cec5SDimitry Andric   outs() << "  " << PrintArg(O.ArgStr);
21810b57cec5SDimitry Andric   outs().indent(GlobalWidth - O.ArgStr.size());
21820b57cec5SDimitry Andric 
21830b57cec5SDimitry Andric   unsigned NumOpts = getNumOptions();
21840b57cec5SDimitry Andric   for (unsigned i = 0; i != NumOpts; ++i) {
21855f757f3fSDimitry Andric     if (!Value.compare(getOptionValue(i)))
21860b57cec5SDimitry Andric       continue;
21870b57cec5SDimitry Andric 
21880b57cec5SDimitry Andric     outs() << "= " << getOption(i);
21890b57cec5SDimitry Andric     size_t L = getOption(i).size();
21900b57cec5SDimitry Andric     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
21910b57cec5SDimitry Andric     outs().indent(NumSpaces) << " (default: ";
21920b57cec5SDimitry Andric     for (unsigned j = 0; j != NumOpts; ++j) {
21935f757f3fSDimitry Andric       if (!Default.compare(getOptionValue(j)))
21940b57cec5SDimitry Andric         continue;
21950b57cec5SDimitry Andric       outs() << getOption(j);
21960b57cec5SDimitry Andric       break;
21970b57cec5SDimitry Andric     }
21980b57cec5SDimitry Andric     outs() << ")\n";
21990b57cec5SDimitry Andric     return;
22000b57cec5SDimitry Andric   }
22010b57cec5SDimitry Andric   outs() << "= *unknown option value*\n";
22020b57cec5SDimitry Andric }
22030b57cec5SDimitry Andric 
22040b57cec5SDimitry Andric // printOptionDiff - Specializations for printing basic value types.
22050b57cec5SDimitry Andric //
22060b57cec5SDimitry Andric #define PRINT_OPT_DIFF(T)                                                      \
22070b57cec5SDimitry Andric   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
22080b57cec5SDimitry Andric                                   size_t GlobalWidth) const {                  \
22090b57cec5SDimitry Andric     printOptionName(O, GlobalWidth);                                           \
22100b57cec5SDimitry Andric     std::string Str;                                                           \
22110b57cec5SDimitry Andric     {                                                                          \
22120b57cec5SDimitry Andric       raw_string_ostream SS(Str);                                              \
22130b57cec5SDimitry Andric       SS << V;                                                                 \
22140b57cec5SDimitry Andric     }                                                                          \
22150b57cec5SDimitry Andric     outs() << "= " << Str;                                                     \
22160b57cec5SDimitry Andric     size_t NumSpaces =                                                         \
22170b57cec5SDimitry Andric         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
22180b57cec5SDimitry Andric     outs().indent(NumSpaces) << " (default: ";                                 \
22190b57cec5SDimitry Andric     if (D.hasValue())                                                          \
22200b57cec5SDimitry Andric       outs() << D.getValue();                                                  \
22210b57cec5SDimitry Andric     else                                                                       \
22220b57cec5SDimitry Andric       outs() << "*no default*";                                                \
22230b57cec5SDimitry Andric     outs() << ")\n";                                                           \
22240b57cec5SDimitry Andric   }
22250b57cec5SDimitry Andric 
22260b57cec5SDimitry Andric PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)22270b57cec5SDimitry Andric PRINT_OPT_DIFF(boolOrDefault)
22280b57cec5SDimitry Andric PRINT_OPT_DIFF(int)
2229480093f4SDimitry Andric PRINT_OPT_DIFF(long)
2230480093f4SDimitry Andric PRINT_OPT_DIFF(long long)
22310b57cec5SDimitry Andric PRINT_OPT_DIFF(unsigned)
22320b57cec5SDimitry Andric PRINT_OPT_DIFF(unsigned long)
22330b57cec5SDimitry Andric PRINT_OPT_DIFF(unsigned long long)
22340b57cec5SDimitry Andric PRINT_OPT_DIFF(double)
22350b57cec5SDimitry Andric PRINT_OPT_DIFF(float)
22360b57cec5SDimitry Andric PRINT_OPT_DIFF(char)
22370b57cec5SDimitry Andric 
22380b57cec5SDimitry Andric void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
22390b57cec5SDimitry Andric                                           const OptionValue<std::string> &D,
22400b57cec5SDimitry Andric                                           size_t GlobalWidth) const {
22410b57cec5SDimitry Andric   printOptionName(O, GlobalWidth);
22420b57cec5SDimitry Andric   outs() << "= " << V;
22430b57cec5SDimitry Andric   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
22440b57cec5SDimitry Andric   outs().indent(NumSpaces) << " (default: ";
22450b57cec5SDimitry Andric   if (D.hasValue())
22460b57cec5SDimitry Andric     outs() << D.getValue();
22470b57cec5SDimitry Andric   else
22480b57cec5SDimitry Andric     outs() << "*no default*";
22490b57cec5SDimitry Andric   outs() << ")\n";
22500b57cec5SDimitry Andric }
22510b57cec5SDimitry Andric 
22520b57cec5SDimitry Andric // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const22530b57cec5SDimitry Andric void basic_parser_impl::printOptionNoValue(const Option &O,
22540b57cec5SDimitry Andric                                            size_t GlobalWidth) const {
22550b57cec5SDimitry Andric   printOptionName(O, GlobalWidth);
22560b57cec5SDimitry Andric   outs() << "= *cannot print option value*\n";
22570b57cec5SDimitry Andric }
22580b57cec5SDimitry Andric 
22590b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
22600b57cec5SDimitry Andric // -help and -help-hidden option implementation
22610b57cec5SDimitry Andric //
22620b57cec5SDimitry Andric 
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)22630b57cec5SDimitry Andric static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
22640b57cec5SDimitry Andric                           const std::pair<const char *, Option *> *RHS) {
22650b57cec5SDimitry Andric   return strcmp(LHS->first, RHS->first);
22660b57cec5SDimitry Andric }
22670b57cec5SDimitry Andric 
SubNameCompare(const std::pair<const char *,SubCommand * > * LHS,const std::pair<const char *,SubCommand * > * RHS)22680b57cec5SDimitry Andric static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
22690b57cec5SDimitry Andric                           const std::pair<const char *, SubCommand *> *RHS) {
22700b57cec5SDimitry Andric   return strcmp(LHS->first, RHS->first);
22710b57cec5SDimitry Andric }
22720b57cec5SDimitry Andric 
22730b57cec5SDimitry Andric // Copy Options into a vector so we can sort them as we like.
sortOpts(StringMap<Option * > & OptMap,SmallVectorImpl<std::pair<const char *,Option * >> & Opts,bool ShowHidden)22740b57cec5SDimitry Andric static void sortOpts(StringMap<Option *> &OptMap,
22750b57cec5SDimitry Andric                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
22760b57cec5SDimitry Andric                      bool ShowHidden) {
22770b57cec5SDimitry Andric   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
22780b57cec5SDimitry Andric 
22790b57cec5SDimitry Andric   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
22800b57cec5SDimitry Andric        I != E; ++I) {
22810b57cec5SDimitry Andric     // Ignore really-hidden options.
22820b57cec5SDimitry Andric     if (I->second->getOptionHiddenFlag() == ReallyHidden)
22830b57cec5SDimitry Andric       continue;
22840b57cec5SDimitry Andric 
22850b57cec5SDimitry Andric     // Unless showhidden is set, ignore hidden flags.
22860b57cec5SDimitry Andric     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
22870b57cec5SDimitry Andric       continue;
22880b57cec5SDimitry Andric 
22890b57cec5SDimitry Andric     // If we've already seen this option, don't add it to the list again.
22900b57cec5SDimitry Andric     if (!OptionSet.insert(I->second).second)
22910b57cec5SDimitry Andric       continue;
22920b57cec5SDimitry Andric 
22930b57cec5SDimitry Andric     Opts.push_back(
22940b57cec5SDimitry Andric         std::pair<const char *, Option *>(I->getKey().data(), I->second));
22950b57cec5SDimitry Andric   }
22960b57cec5SDimitry Andric 
22970b57cec5SDimitry Andric   // Sort the options list alphabetically.
22980b57cec5SDimitry Andric   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
22990b57cec5SDimitry Andric }
23000b57cec5SDimitry Andric 
23010b57cec5SDimitry Andric static void
sortSubCommands(const SmallPtrSetImpl<SubCommand * > & SubMap,SmallVectorImpl<std::pair<const char *,SubCommand * >> & Subs)23020b57cec5SDimitry Andric sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
23030b57cec5SDimitry Andric                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2304480093f4SDimitry Andric   for (auto *S : SubMap) {
23050b57cec5SDimitry Andric     if (S->getName().empty())
23060b57cec5SDimitry Andric       continue;
23070b57cec5SDimitry Andric     Subs.push_back(std::make_pair(S->getName().data(), S));
23080b57cec5SDimitry Andric   }
23090b57cec5SDimitry Andric   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
23100b57cec5SDimitry Andric }
23110b57cec5SDimitry Andric 
23120b57cec5SDimitry Andric namespace {
23130b57cec5SDimitry Andric 
23140b57cec5SDimitry Andric class HelpPrinter {
23150b57cec5SDimitry Andric protected:
23160b57cec5SDimitry Andric   const bool ShowHidden;
23170b57cec5SDimitry Andric   typedef SmallVector<std::pair<const char *, Option *>, 128>
23180b57cec5SDimitry Andric       StrOptionPairVector;
23190b57cec5SDimitry Andric   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
23200b57cec5SDimitry Andric       StrSubCommandPairVector;
23210b57cec5SDimitry Andric   // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)23220b57cec5SDimitry Andric   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
23230b57cec5SDimitry Andric     for (size_t i = 0, e = Opts.size(); i != e; ++i)
23240b57cec5SDimitry Andric       Opts[i].second->printOptionInfo(MaxArgLen);
23250b57cec5SDimitry Andric   }
23260b57cec5SDimitry Andric 
printSubCommands(StrSubCommandPairVector & Subs,size_t MaxSubLen)23270b57cec5SDimitry Andric   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
23280b57cec5SDimitry Andric     for (const auto &S : Subs) {
23290b57cec5SDimitry Andric       outs() << "  " << S.first;
23300b57cec5SDimitry Andric       if (!S.second->getDescription().empty()) {
23310b57cec5SDimitry Andric         outs().indent(MaxSubLen - strlen(S.first));
23320b57cec5SDimitry Andric         outs() << " - " << S.second->getDescription();
23330b57cec5SDimitry Andric       }
23340b57cec5SDimitry Andric       outs() << "\n";
23350b57cec5SDimitry Andric     }
23360b57cec5SDimitry Andric   }
23370b57cec5SDimitry Andric 
23380b57cec5SDimitry Andric public:
HelpPrinter(bool showHidden)23390b57cec5SDimitry Andric   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
234081ad6265SDimitry Andric   virtual ~HelpPrinter() = default;
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric   // Invoke the printer.
operator =(bool Value)23430b57cec5SDimitry Andric   void operator=(bool Value) {
23440b57cec5SDimitry Andric     if (!Value)
23450b57cec5SDimitry Andric       return;
23460b57cec5SDimitry Andric     printHelp();
23470b57cec5SDimitry Andric 
23480b57cec5SDimitry Andric     // Halt the program since help information was printed
23490b57cec5SDimitry Andric     exit(0);
23500b57cec5SDimitry Andric   }
23510b57cec5SDimitry Andric 
printHelp()23520b57cec5SDimitry Andric   void printHelp() {
23530b57cec5SDimitry Andric     SubCommand *Sub = GlobalParser->getActiveSubCommand();
23540b57cec5SDimitry Andric     auto &OptionsMap = Sub->OptionsMap;
23550b57cec5SDimitry Andric     auto &PositionalOpts = Sub->PositionalOpts;
23560b57cec5SDimitry Andric     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
23570b57cec5SDimitry Andric 
23580b57cec5SDimitry Andric     StrOptionPairVector Opts;
23590b57cec5SDimitry Andric     sortOpts(OptionsMap, Opts, ShowHidden);
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric     StrSubCommandPairVector Subs;
23620b57cec5SDimitry Andric     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric     if (!GlobalParser->ProgramOverview.empty())
23650b57cec5SDimitry Andric       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
23660b57cec5SDimitry Andric 
2367bdd1243dSDimitry Andric     if (Sub == &SubCommand::getTopLevel()) {
23680b57cec5SDimitry Andric       outs() << "USAGE: " << GlobalParser->ProgramName;
23695f757f3fSDimitry Andric       if (!Subs.empty())
23700b57cec5SDimitry Andric         outs() << " [subcommand]";
23710b57cec5SDimitry Andric       outs() << " [options]";
23720b57cec5SDimitry Andric     } else {
23730b57cec5SDimitry Andric       if (!Sub->getDescription().empty()) {
23740b57cec5SDimitry Andric         outs() << "SUBCOMMAND '" << Sub->getName()
23750b57cec5SDimitry Andric                << "': " << Sub->getDescription() << "\n\n";
23760b57cec5SDimitry Andric       }
23770b57cec5SDimitry Andric       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
23780b57cec5SDimitry Andric              << " [options]";
23790b57cec5SDimitry Andric     }
23800b57cec5SDimitry Andric 
2381fe6060f1SDimitry Andric     for (auto *Opt : PositionalOpts) {
23820b57cec5SDimitry Andric       if (Opt->hasArgStr())
23830b57cec5SDimitry Andric         outs() << " --" << Opt->ArgStr;
23840b57cec5SDimitry Andric       outs() << " " << Opt->HelpStr;
23850b57cec5SDimitry Andric     }
23860b57cec5SDimitry Andric 
23870b57cec5SDimitry Andric     // Print the consume after option info if it exists...
23880b57cec5SDimitry Andric     if (ConsumeAfterOpt)
23890b57cec5SDimitry Andric       outs() << " " << ConsumeAfterOpt->HelpStr;
23900b57cec5SDimitry Andric 
2391bdd1243dSDimitry Andric     if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
23920b57cec5SDimitry Andric       // Compute the maximum subcommand length...
23930b57cec5SDimitry Andric       size_t MaxSubLen = 0;
23940b57cec5SDimitry Andric       for (size_t i = 0, e = Subs.size(); i != e; ++i)
23950b57cec5SDimitry Andric         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
23960b57cec5SDimitry Andric 
23970b57cec5SDimitry Andric       outs() << "\n\n";
23980b57cec5SDimitry Andric       outs() << "SUBCOMMANDS:\n\n";
23990b57cec5SDimitry Andric       printSubCommands(Subs, MaxSubLen);
24000b57cec5SDimitry Andric       outs() << "\n";
24010b57cec5SDimitry Andric       outs() << "  Type \"" << GlobalParser->ProgramName
24020b57cec5SDimitry Andric              << " <subcommand> --help\" to get more help on a specific "
24030b57cec5SDimitry Andric                 "subcommand";
24040b57cec5SDimitry Andric     }
24050b57cec5SDimitry Andric 
24060b57cec5SDimitry Andric     outs() << "\n\n";
24070b57cec5SDimitry Andric 
24080b57cec5SDimitry Andric     // Compute the maximum argument length...
24090b57cec5SDimitry Andric     size_t MaxArgLen = 0;
24100b57cec5SDimitry Andric     for (size_t i = 0, e = Opts.size(); i != e; ++i)
24110b57cec5SDimitry Andric       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
24120b57cec5SDimitry Andric 
24130b57cec5SDimitry Andric     outs() << "OPTIONS:\n";
24140b57cec5SDimitry Andric     printOptions(Opts, MaxArgLen);
24150b57cec5SDimitry Andric 
24160b57cec5SDimitry Andric     // Print any extra help the user has declared.
2417fe6060f1SDimitry Andric     for (const auto &I : GlobalParser->MoreHelp)
24180b57cec5SDimitry Andric       outs() << I;
24190b57cec5SDimitry Andric     GlobalParser->MoreHelp.clear();
24200b57cec5SDimitry Andric   }
24210b57cec5SDimitry Andric };
24220b57cec5SDimitry Andric 
24230b57cec5SDimitry Andric class CategorizedHelpPrinter : public HelpPrinter {
24240b57cec5SDimitry Andric public:
CategorizedHelpPrinter(bool showHidden)24250b57cec5SDimitry Andric   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
24260b57cec5SDimitry Andric 
24270b57cec5SDimitry Andric   // Helper function for printOptions().
24280b57cec5SDimitry Andric   // It shall return a negative value if A's name should be lexicographically
24290b57cec5SDimitry Andric   // ordered before B's name. It returns a value greater than zero if B's name
24300b57cec5SDimitry Andric   // should be ordered before A's name, and it returns 0 otherwise.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)24310b57cec5SDimitry Andric   static int OptionCategoryCompare(OptionCategory *const *A,
24320b57cec5SDimitry Andric                                    OptionCategory *const *B) {
24330b57cec5SDimitry Andric     return (*A)->getName().compare((*B)->getName());
24340b57cec5SDimitry Andric   }
24350b57cec5SDimitry Andric 
24360b57cec5SDimitry Andric   // Make sure we inherit our base class's operator=()
24370b57cec5SDimitry Andric   using HelpPrinter::operator=;
24380b57cec5SDimitry Andric 
24390b57cec5SDimitry Andric protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)24400b57cec5SDimitry Andric   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
24410b57cec5SDimitry Andric     std::vector<OptionCategory *> SortedCategories;
244204eeddc0SDimitry Andric     DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric     // Collect registered option categories into vector in preparation for
24450b57cec5SDimitry Andric     // sorting.
24460eae32dcSDimitry Andric     for (OptionCategory *Category : GlobalParser->RegisteredOptionCategories)
24470eae32dcSDimitry Andric       SortedCategories.push_back(Category);
24480b57cec5SDimitry Andric 
24490b57cec5SDimitry Andric     // Sort the different option categories alphabetically.
24500b57cec5SDimitry Andric     assert(SortedCategories.size() > 0 && "No option categories registered!");
24510b57cec5SDimitry Andric     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
24520b57cec5SDimitry Andric                    OptionCategoryCompare);
24530b57cec5SDimitry Andric 
24540b57cec5SDimitry Andric     // Walk through pre-sorted options and assign into categories.
24550b57cec5SDimitry Andric     // Because the options are already alphabetically sorted the
24560b57cec5SDimitry Andric     // options within categories will also be alphabetically sorted.
24570b57cec5SDimitry Andric     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
24580b57cec5SDimitry Andric       Option *Opt = Opts[I].second;
24590b57cec5SDimitry Andric       for (auto &Cat : Opt->Categories) {
2460fcaf7f86SDimitry Andric         assert(llvm::is_contained(SortedCategories, Cat) &&
24610b57cec5SDimitry Andric                "Option has an unregistered category");
24620b57cec5SDimitry Andric         CategorizedOptions[Cat].push_back(Opt);
24630b57cec5SDimitry Andric       }
24640b57cec5SDimitry Andric     }
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric     // Now do printing.
24670eae32dcSDimitry Andric     for (OptionCategory *Category : SortedCategories) {
24680b57cec5SDimitry Andric       // Hide empty categories for --help, but show for --help-hidden.
24690eae32dcSDimitry Andric       const auto &CategoryOptions = CategorizedOptions[Category];
24701db9f3b2SDimitry Andric       if (CategoryOptions.empty())
24710b57cec5SDimitry Andric         continue;
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric       // Print category information.
24740b57cec5SDimitry Andric       outs() << "\n";
24750eae32dcSDimitry Andric       outs() << Category->getName() << ":\n";
24760b57cec5SDimitry Andric 
24770b57cec5SDimitry Andric       // Check if description is set.
24780eae32dcSDimitry Andric       if (!Category->getDescription().empty())
24790eae32dcSDimitry Andric         outs() << Category->getDescription() << "\n\n";
24800b57cec5SDimitry Andric       else
24810b57cec5SDimitry Andric         outs() << "\n";
24820b57cec5SDimitry Andric 
24830b57cec5SDimitry Andric       // Loop over the options in the category and print.
24840b57cec5SDimitry Andric       for (const Option *Opt : CategoryOptions)
24850b57cec5SDimitry Andric         Opt->printOptionInfo(MaxArgLen);
24860b57cec5SDimitry Andric     }
24870b57cec5SDimitry Andric   }
24880b57cec5SDimitry Andric };
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric // This wraps the Uncategorizing and Categorizing printers and decides
24910b57cec5SDimitry Andric // at run time which should be invoked.
24920b57cec5SDimitry Andric class HelpPrinterWrapper {
24930b57cec5SDimitry Andric private:
24940b57cec5SDimitry Andric   HelpPrinter &UncategorizedPrinter;
24950b57cec5SDimitry Andric   CategorizedHelpPrinter &CategorizedPrinter;
24960b57cec5SDimitry Andric 
24970b57cec5SDimitry Andric public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)24980b57cec5SDimitry Andric   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
24990b57cec5SDimitry Andric                               CategorizedHelpPrinter &CategorizedPrinter)
25000b57cec5SDimitry Andric       : UncategorizedPrinter(UncategorizedPrinter),
25010b57cec5SDimitry Andric         CategorizedPrinter(CategorizedPrinter) {}
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric   // Invoke the printer.
25040b57cec5SDimitry Andric   void operator=(bool Value);
25050b57cec5SDimitry Andric };
25060b57cec5SDimitry Andric 
25070b57cec5SDimitry Andric } // End anonymous namespace
25080b57cec5SDimitry Andric 
2509480093f4SDimitry Andric #if defined(__GNUC__)
2510480093f4SDimitry Andric // GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2511480093f4SDimitry Andric // enabled.
2512480093f4SDimitry Andric # if defined(__OPTIMIZE__)
2513480093f4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 0
2514480093f4SDimitry Andric # else
2515480093f4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 1
2516480093f4SDimitry Andric # endif
2517480093f4SDimitry Andric #elif defined(_MSC_VER)
2518480093f4SDimitry Andric // MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2519480093f4SDimitry Andric // Use _DEBUG instead. This macro actually corresponds to the choice between
2520480093f4SDimitry Andric // debug and release CRTs, but it is a reasonable proxy.
2521480093f4SDimitry Andric # if defined(_DEBUG)
2522480093f4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 1
2523480093f4SDimitry Andric # else
2524480093f4SDimitry Andric #  define LLVM_IS_DEBUG_BUILD 0
2525480093f4SDimitry Andric # endif
2526480093f4SDimitry Andric #else
2527480093f4SDimitry Andric // Otherwise, for an unknown compiler, assume this is an optimized build.
2528480093f4SDimitry Andric # define LLVM_IS_DEBUG_BUILD 0
2529480093f4SDimitry Andric #endif
2530480093f4SDimitry Andric 
25310b57cec5SDimitry Andric namespace {
25320b57cec5SDimitry Andric class VersionPrinter {
25330b57cec5SDimitry Andric public:
print(std::vector<VersionPrinterTy> ExtraPrinters={})2534bdd1243dSDimitry Andric   void print(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
25350b57cec5SDimitry Andric     raw_ostream &OS = outs();
25360b57cec5SDimitry Andric #ifdef PACKAGE_VENDOR
25370b57cec5SDimitry Andric     OS << PACKAGE_VENDOR << " ";
25380b57cec5SDimitry Andric #else
25390b57cec5SDimitry Andric     OS << "LLVM (http://llvm.org/):\n  ";
25400b57cec5SDimitry Andric #endif
254181ad6265SDimitry Andric     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n  ";
2542480093f4SDimitry Andric #if LLVM_IS_DEBUG_BUILD
25430b57cec5SDimitry Andric     OS << "DEBUG build";
25440b57cec5SDimitry Andric #else
25450b57cec5SDimitry Andric     OS << "Optimized build";
25460b57cec5SDimitry Andric #endif
25470b57cec5SDimitry Andric #ifndef NDEBUG
25480b57cec5SDimitry Andric     OS << " with assertions";
25490b57cec5SDimitry Andric #endif
2550bdd1243dSDimitry Andric     OS << ".\n";
2551bdd1243dSDimitry Andric 
2552bdd1243dSDimitry Andric     // Iterate over any registered extra printers and call them to add further
2553bdd1243dSDimitry Andric     // information.
2554bdd1243dSDimitry Andric     if (!ExtraPrinters.empty()) {
2555bdd1243dSDimitry Andric       for (const auto &I : ExtraPrinters)
2556bdd1243dSDimitry Andric         I(outs());
2557bdd1243dSDimitry Andric     }
25580b57cec5SDimitry Andric   }
2559fe6060f1SDimitry Andric   void operator=(bool OptionWasSpecified);
2560fe6060f1SDimitry Andric };
2561fe6060f1SDimitry Andric 
2562fe6060f1SDimitry Andric struct CommandLineCommonOptions {
2563fe6060f1SDimitry Andric   // Declare the four HelpPrinter instances that are used to print out help, or
2564fe6060f1SDimitry Andric   // help-hidden as an uncategorized list or in categories.
2565fe6060f1SDimitry Andric   HelpPrinter UncategorizedNormalPrinter{false};
2566fe6060f1SDimitry Andric   HelpPrinter UncategorizedHiddenPrinter{true};
2567fe6060f1SDimitry Andric   CategorizedHelpPrinter CategorizedNormalPrinter{false};
2568fe6060f1SDimitry Andric   CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2569fe6060f1SDimitry Andric   // Declare HelpPrinter wrappers that will decide whether or not to invoke
2570fe6060f1SDimitry Andric   // a categorizing help printer
2571fe6060f1SDimitry Andric   HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2572fe6060f1SDimitry Andric                                           CategorizedNormalPrinter};
2573fe6060f1SDimitry Andric   HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2574fe6060f1SDimitry Andric                                           CategorizedHiddenPrinter};
2575fe6060f1SDimitry Andric   // Define a category for generic options that all tools should have.
2576fe6060f1SDimitry Andric   cl::OptionCategory GenericCategory{"Generic Options"};
2577fe6060f1SDimitry Andric 
2578fe6060f1SDimitry Andric   // Define uncategorized help printers.
2579fe6060f1SDimitry Andric   // --help-list is hidden by default because if Option categories are being
2580fe6060f1SDimitry Andric   // used then --help behaves the same as --help-list.
2581fe6060f1SDimitry Andric   cl::opt<HelpPrinter, true, parser<bool>> HLOp{
2582fe6060f1SDimitry Andric       "help-list",
2583fe6060f1SDimitry Andric       cl::desc(
2584fe6060f1SDimitry Andric           "Display list of available options (--help-list-hidden for more)"),
2585fe6060f1SDimitry Andric       cl::location(UncategorizedNormalPrinter),
2586fe6060f1SDimitry Andric       cl::Hidden,
2587fe6060f1SDimitry Andric       cl::ValueDisallowed,
2588fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2589bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2590fe6060f1SDimitry Andric 
2591fe6060f1SDimitry Andric   cl::opt<HelpPrinter, true, parser<bool>> HLHOp{
2592fe6060f1SDimitry Andric       "help-list-hidden",
2593fe6060f1SDimitry Andric       cl::desc("Display list of all available options"),
2594fe6060f1SDimitry Andric       cl::location(UncategorizedHiddenPrinter),
2595fe6060f1SDimitry Andric       cl::Hidden,
2596fe6060f1SDimitry Andric       cl::ValueDisallowed,
2597fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2598bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2599fe6060f1SDimitry Andric 
2600fe6060f1SDimitry Andric   // Define uncategorized/categorized help printers. These printers change their
2601fe6060f1SDimitry Andric   // behaviour at runtime depending on whether one or more Option categories
2602fe6060f1SDimitry Andric   // have been declared.
2603fe6060f1SDimitry Andric   cl::opt<HelpPrinterWrapper, true, parser<bool>> HOp{
2604fe6060f1SDimitry Andric       "help",
2605fe6060f1SDimitry Andric       cl::desc("Display available options (--help-hidden for more)"),
2606fe6060f1SDimitry Andric       cl::location(WrappedNormalPrinter),
2607fe6060f1SDimitry Andric       cl::ValueDisallowed,
2608fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2609bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2610fe6060f1SDimitry Andric 
2611fe6060f1SDimitry Andric   cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2612fe6060f1SDimitry Andric                  cl::DefaultOption};
2613fe6060f1SDimitry Andric 
2614fe6060f1SDimitry Andric   cl::opt<HelpPrinterWrapper, true, parser<bool>> HHOp{
2615fe6060f1SDimitry Andric       "help-hidden",
2616fe6060f1SDimitry Andric       cl::desc("Display all available options"),
2617fe6060f1SDimitry Andric       cl::location(WrappedHiddenPrinter),
2618fe6060f1SDimitry Andric       cl::Hidden,
2619fe6060f1SDimitry Andric       cl::ValueDisallowed,
2620fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2621bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2622fe6060f1SDimitry Andric 
2623fe6060f1SDimitry Andric   cl::opt<bool> PrintOptions{
2624fe6060f1SDimitry Andric       "print-options",
2625fe6060f1SDimitry Andric       cl::desc("Print non-default options after command line parsing"),
2626fe6060f1SDimitry Andric       cl::Hidden,
2627fe6060f1SDimitry Andric       cl::init(false),
2628fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2629bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2630fe6060f1SDimitry Andric 
2631fe6060f1SDimitry Andric   cl::opt<bool> PrintAllOptions{
2632fe6060f1SDimitry Andric       "print-all-options",
2633fe6060f1SDimitry Andric       cl::desc("Print all option values after command line parsing"),
2634fe6060f1SDimitry Andric       cl::Hidden,
2635fe6060f1SDimitry Andric       cl::init(false),
2636fe6060f1SDimitry Andric       cl::cat(GenericCategory),
2637bdd1243dSDimitry Andric       cl::sub(SubCommand::getAll())};
2638fe6060f1SDimitry Andric 
2639fe6060f1SDimitry Andric   VersionPrinterTy OverrideVersionPrinter = nullptr;
2640fe6060f1SDimitry Andric 
2641fe6060f1SDimitry Andric   std::vector<VersionPrinterTy> ExtraVersionPrinters;
2642fe6060f1SDimitry Andric 
2643fe6060f1SDimitry Andric   // Define the --version option that prints out the LLVM version for the tool
2644fe6060f1SDimitry Andric   VersionPrinter VersionPrinterInstance;
2645fe6060f1SDimitry Andric 
2646fe6060f1SDimitry Andric   cl::opt<VersionPrinter, true, parser<bool>> VersOp{
2647fe6060f1SDimitry Andric       "version", cl::desc("Display the version of this program"),
2648fe6060f1SDimitry Andric       cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2649fe6060f1SDimitry Andric       cl::cat(GenericCategory)};
2650fe6060f1SDimitry Andric };
2651fe6060f1SDimitry Andric } // End anonymous namespace
2652fe6060f1SDimitry Andric 
2653fe6060f1SDimitry Andric // Lazy-initialized global instance of options controlling the command-line
2654fe6060f1SDimitry Andric // parser and general handling.
2655fe6060f1SDimitry Andric static ManagedStatic<CommandLineCommonOptions> CommonOptions;
2656fe6060f1SDimitry Andric 
initCommonOptions()2657fe6060f1SDimitry Andric static void initCommonOptions() {
2658fe6060f1SDimitry Andric   *CommonOptions;
2659fe6060f1SDimitry Andric   initDebugCounterOptions();
2660fe6060f1SDimitry Andric   initGraphWriterOptions();
2661fe6060f1SDimitry Andric   initSignalsOptions();
2662fe6060f1SDimitry Andric   initStatisticOptions();
2663fe6060f1SDimitry Andric   initTimerOptions();
2664fe6060f1SDimitry Andric   initTypeSizeOptions();
2665fe6060f1SDimitry Andric   initWithColorOptions();
2666fe6060f1SDimitry Andric   initDebugOptions();
2667fe6060f1SDimitry Andric   initRandomSeedOptions();
2668fe6060f1SDimitry Andric }
2669fe6060f1SDimitry Andric 
getGeneralCategory()2670fe6060f1SDimitry Andric OptionCategory &cl::getGeneralCategory() {
2671fe6060f1SDimitry Andric   // Initialise the general option category.
2672fe6060f1SDimitry Andric   static OptionCategory GeneralCategory{"General options"};
2673fe6060f1SDimitry Andric   return GeneralCategory;
2674fe6060f1SDimitry Andric }
2675fe6060f1SDimitry Andric 
operator =(bool OptionWasSpecified)2676fe6060f1SDimitry Andric void VersionPrinter::operator=(bool OptionWasSpecified) {
26770b57cec5SDimitry Andric   if (!OptionWasSpecified)
26780b57cec5SDimitry Andric     return;
26790b57cec5SDimitry Andric 
2680fe6060f1SDimitry Andric   if (CommonOptions->OverrideVersionPrinter != nullptr) {
2681fe6060f1SDimitry Andric     CommonOptions->OverrideVersionPrinter(outs());
26820b57cec5SDimitry Andric     exit(0);
26830b57cec5SDimitry Andric   }
2684bdd1243dSDimitry Andric   print(CommonOptions->ExtraVersionPrinters);
26850b57cec5SDimitry Andric 
26860b57cec5SDimitry Andric   exit(0);
26870b57cec5SDimitry Andric }
26880b57cec5SDimitry Andric 
operator =(bool Value)2689fe6060f1SDimitry Andric void HelpPrinterWrapper::operator=(bool Value) {
2690fe6060f1SDimitry Andric   if (!Value)
2691fe6060f1SDimitry Andric     return;
26920b57cec5SDimitry Andric 
2693fe6060f1SDimitry Andric   // Decide which printer to invoke. If more than one option category is
2694fe6060f1SDimitry Andric   // registered then it is useful to show the categorized help instead of
2695fe6060f1SDimitry Andric   // uncategorized help.
2696fe6060f1SDimitry Andric   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2697fe6060f1SDimitry Andric     // unhide --help-list option so user can have uncategorized output if they
2698fe6060f1SDimitry Andric     // want it.
2699fe6060f1SDimitry Andric     CommonOptions->HLOp.setHiddenFlag(NotHidden);
2700fe6060f1SDimitry Andric 
2701fe6060f1SDimitry Andric     CategorizedPrinter = true; // Invoke categorized printer
2702fe6060f1SDimitry Andric   } else
2703fe6060f1SDimitry Andric     UncategorizedPrinter = true; // Invoke uncategorized printer
2704fe6060f1SDimitry Andric }
2705fe6060f1SDimitry Andric 
2706fe6060f1SDimitry Andric // Print the value of each option.
PrintOptionValues()2707fe6060f1SDimitry Andric void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2708fe6060f1SDimitry Andric 
printOptionValues()2709fe6060f1SDimitry Andric void CommandLineParser::printOptionValues() {
2710fe6060f1SDimitry Andric   if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2711fe6060f1SDimitry Andric     return;
2712fe6060f1SDimitry Andric 
2713fe6060f1SDimitry Andric   SmallVector<std::pair<const char *, Option *>, 128> Opts;
2714fe6060f1SDimitry Andric   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2715fe6060f1SDimitry Andric 
2716fe6060f1SDimitry Andric   // Compute the maximum argument length...
2717fe6060f1SDimitry Andric   size_t MaxArgLen = 0;
2718fe6060f1SDimitry Andric   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2719fe6060f1SDimitry Andric     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
2720fe6060f1SDimitry Andric 
2721fe6060f1SDimitry Andric   for (size_t i = 0, e = Opts.size(); i != e; ++i)
2722fe6060f1SDimitry Andric     Opts[i].second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2723fe6060f1SDimitry Andric }
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)27260b57cec5SDimitry Andric void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
27270b57cec5SDimitry Andric   if (!Hidden && !Categorized)
2728fe6060f1SDimitry Andric     CommonOptions->UncategorizedNormalPrinter.printHelp();
27290b57cec5SDimitry Andric   else if (!Hidden && Categorized)
2730fe6060f1SDimitry Andric     CommonOptions->CategorizedNormalPrinter.printHelp();
27310b57cec5SDimitry Andric   else if (Hidden && !Categorized)
2732fe6060f1SDimitry Andric     CommonOptions->UncategorizedHiddenPrinter.printHelp();
27330b57cec5SDimitry Andric   else
2734fe6060f1SDimitry Andric     CommonOptions->CategorizedHiddenPrinter.printHelp();
27350b57cec5SDimitry Andric }
27360b57cec5SDimitry Andric 
27370b57cec5SDimitry Andric /// Utility function for printing version number.
PrintVersionMessage()2738fe6060f1SDimitry Andric void cl::PrintVersionMessage() {
2739bdd1243dSDimitry Andric   CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2740fe6060f1SDimitry Andric }
27410b57cec5SDimitry Andric 
SetVersionPrinter(VersionPrinterTy func)2742fe6060f1SDimitry Andric void cl::SetVersionPrinter(VersionPrinterTy func) {
2743fe6060f1SDimitry Andric   CommonOptions->OverrideVersionPrinter = func;
2744fe6060f1SDimitry Andric }
27450b57cec5SDimitry Andric 
AddExtraVersionPrinter(VersionPrinterTy func)27460b57cec5SDimitry Andric void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
2747fe6060f1SDimitry Andric   CommonOptions->ExtraVersionPrinters.push_back(func);
27480b57cec5SDimitry Andric }
27490b57cec5SDimitry Andric 
getRegisteredOptions(SubCommand & Sub)27500b57cec5SDimitry Andric StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
2751349cc55cSDimitry Andric   initCommonOptions();
27520b57cec5SDimitry Andric   auto &Subs = GlobalParser->RegisteredSubCommands;
27530b57cec5SDimitry Andric   (void)Subs;
275406c3fb27SDimitry Andric   assert(Subs.contains(&Sub));
27550b57cec5SDimitry Andric   return Sub.OptionsMap;
27560b57cec5SDimitry Andric }
27570b57cec5SDimitry Andric 
27580b57cec5SDimitry Andric iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
getRegisteredSubcommands()27590b57cec5SDimitry Andric cl::getRegisteredSubcommands() {
27600b57cec5SDimitry Andric   return GlobalParser->getRegisteredSubcommands();
27610b57cec5SDimitry Andric }
27620b57cec5SDimitry Andric 
HideUnrelatedOptions(cl::OptionCategory & Category,SubCommand & Sub)27630b57cec5SDimitry Andric void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
2764fe6060f1SDimitry Andric   initCommonOptions();
27650b57cec5SDimitry Andric   for (auto &I : Sub.OptionsMap) {
27664824e7fdSDimitry Andric     bool Unrelated = true;
27670b57cec5SDimitry Andric     for (auto &Cat : I.second->Categories) {
27684824e7fdSDimitry Andric       if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
27694824e7fdSDimitry Andric         Unrelated = false;
27700b57cec5SDimitry Andric     }
27714824e7fdSDimitry Andric     if (Unrelated)
27724824e7fdSDimitry Andric       I.second->setHiddenFlag(cl::ReallyHidden);
27730b57cec5SDimitry Andric   }
27740b57cec5SDimitry Andric }
27750b57cec5SDimitry Andric 
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories,SubCommand & Sub)27760b57cec5SDimitry Andric void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
27770b57cec5SDimitry Andric                               SubCommand &Sub) {
2778fe6060f1SDimitry Andric   initCommonOptions();
27790b57cec5SDimitry Andric   for (auto &I : Sub.OptionsMap) {
27804824e7fdSDimitry Andric     bool Unrelated = true;
27810b57cec5SDimitry Andric     for (auto &Cat : I.second->Categories) {
27824824e7fdSDimitry Andric       if (is_contained(Categories, Cat) ||
27834824e7fdSDimitry Andric           Cat == &CommonOptions->GenericCategory)
27844824e7fdSDimitry Andric         Unrelated = false;
27850b57cec5SDimitry Andric     }
27864824e7fdSDimitry Andric     if (Unrelated)
27874824e7fdSDimitry Andric       I.second->setHiddenFlag(cl::ReallyHidden);
27880b57cec5SDimitry Andric   }
27890b57cec5SDimitry Andric }
27900b57cec5SDimitry Andric 
ResetCommandLineParser()27910b57cec5SDimitry Andric void cl::ResetCommandLineParser() { GlobalParser->reset(); }
ResetAllOptionOccurrences()27920b57cec5SDimitry Andric void cl::ResetAllOptionOccurrences() {
27930b57cec5SDimitry Andric   GlobalParser->ResetAllOptionOccurrences();
27940b57cec5SDimitry Andric }
27950b57cec5SDimitry Andric 
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)27960b57cec5SDimitry Andric void LLVMParseCommandLineOptions(int argc, const char *const *argv,
27970b57cec5SDimitry Andric                                  const char *Overview) {
27980b57cec5SDimitry Andric   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
27990b57cec5SDimitry Andric                                     &llvm::nulls());
28000b57cec5SDimitry Andric }
2801