LCOV - code coverage report
Current view: top level - lib/Support - CommandLine.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 831 1018 81.6 %
Date: 2017-09-14 15:23:50 Functions: 87 116 75.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===-- CommandLine.cpp - Command line parser implementation --------------===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This class implements a command line argument processor that is useful when
      11             : // creating a tool.  It provides a simple, minimalistic interface that is easily
      12             : // extensible and supports nonlocal (library) command line options.
      13             : //
      14             : // Note that rather than trying to figure out what this code does, you could try
      15             : // reading the library documentation located in docs/CommandLine.html
      16             : //
      17             : //===----------------------------------------------------------------------===//
      18             : 
      19             : #include "llvm/Support/CommandLine.h"
      20             : #include "llvm-c/Support.h"
      21             : #include "llvm/ADT/ArrayRef.h"
      22             : #include "llvm/ADT/DenseMap.h"
      23             : #include "llvm/ADT/Optional.h"
      24             : #include "llvm/ADT/STLExtras.h"
      25             : #include "llvm/ADT/SmallPtrSet.h"
      26             : #include "llvm/ADT/SmallString.h"
      27             : #include "llvm/ADT/StringExtras.h"
      28             : #include "llvm/ADT/StringMap.h"
      29             : #include "llvm/ADT/Twine.h"
      30             : #include "llvm/Config/config.h"
      31             : #include "llvm/Support/ConvertUTF.h"
      32             : #include "llvm/Support/Debug.h"
      33             : #include "llvm/Support/ErrorHandling.h"
      34             : #include "llvm/Support/FileSystem.h"
      35             : #include "llvm/Support/Host.h"
      36             : #include "llvm/Support/ManagedStatic.h"
      37             : #include "llvm/Support/MemoryBuffer.h"
      38             : #include "llvm/Support/Path.h"
      39             : #include "llvm/Support/Process.h"
      40             : #include "llvm/Support/StringSaver.h"
      41             : #include "llvm/Support/raw_ostream.h"
      42             : #include <cstdlib>
      43             : #include <map>
      44             : using namespace llvm;
      45             : using namespace cl;
      46             : 
      47             : #define DEBUG_TYPE "commandline"
      48             : 
      49             : //===----------------------------------------------------------------------===//
      50             : // Template instantiations and anchors.
      51             : //
      52             : namespace llvm {
      53             : namespace cl {
      54             : template class basic_parser<bool>;
      55             : template class basic_parser<boolOrDefault>;
      56             : template class basic_parser<int>;
      57             : template class basic_parser<unsigned>;
      58             : template class basic_parser<unsigned long long>;
      59             : template class basic_parser<double>;
      60             : template class basic_parser<float>;
      61             : template class basic_parser<std::string>;
      62             : template class basic_parser<char>;
      63             : 
      64             : template class opt<unsigned>;
      65             : template class opt<int>;
      66             : template class opt<std::string>;
      67             : template class opt<char>;
      68             : template class opt<bool>;
      69             : }
      70             : } // end namespace llvm::cl
      71             : 
      72             : // Pin the vtables to this file.
      73           0 : void GenericOptionValue::anchor() {}
      74           0 : void OptionValue<boolOrDefault>::anchor() {}
      75           0 : void OptionValue<std::string>::anchor() {}
      76           0 : void Option::anchor() {}
      77           0 : void basic_parser_impl::anchor() {}
      78           0 : void parser<bool>::anchor() {}
      79           0 : void parser<boolOrDefault>::anchor() {}
      80           0 : void parser<int>::anchor() {}
      81           0 : void parser<unsigned>::anchor() {}
      82           0 : void parser<unsigned long long>::anchor() {}
      83           0 : void parser<double>::anchor() {}
      84           0 : void parser<float>::anchor() {}
      85           0 : void parser<std::string>::anchor() {}
      86           0 : void parser<char>::anchor() {}
      87             : 
      88             : //===----------------------------------------------------------------------===//
      89             : 
      90             : namespace {
      91             : 
      92      311830 : class CommandLineParser {
      93             : public:
      94             :   // Globals for name and overview of program.  Program name is not a string to
      95             :   // avoid static ctor/dtor issues.
      96             :   std::string ProgramName;
      97             :   StringRef ProgramOverview;
      98             : 
      99             :   // This collects additional help to be printed.
     100             :   std::vector<StringRef> MoreHelp;
     101             : 
     102             :   // This collects the different option categories that have been registered.
     103             :   SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
     104             : 
     105             :   // This collects the different subcommands that have been registered.
     106             :   SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
     107             : 
     108      728070 :   CommandLineParser() : ActiveSubCommand(nullptr) {
     109      121345 :     registerSubCommand(&*TopLevelSubCommand);
     110      121345 :     registerSubCommand(&*AllSubCommands);
     111      121345 :   }
     112             : 
     113             :   void ResetAllOptionOccurrences();
     114             : 
     115             :   bool ParseCommandLineOptions(int argc, const char *const *argv,
     116             :                                StringRef Overview, raw_ostream *Errs = nullptr);
     117             : 
     118    37210020 :   void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
     119    37210020 :     if (Opt.hasArgStr())
     120             :       return;
     121    11481123 :     if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
     122           0 :       errs() << ProgramName << ": CommandLine Error: Option '" << Name
     123           0 :              << "' registered more than once!\n";
     124           0 :       report_fatal_error("inconsistency in registered CommandLine options");
     125             :     }
     126             : 
     127             :     // If we're adding this to all sub-commands, add it to the ones that have
     128             :     // already been registered.
     129     3827041 :     if (SC == &*AllSubCommands) {
     130           0 :       for (const auto &Sub : RegisteredSubCommands) {
     131           0 :         if (SC == Sub)
     132           0 :           continue;
     133           0 :         addLiteralOption(Opt, Sub, Name);
     134             :       }
     135             :     }
     136             :   }
     137             : 
     138    37210020 :   void addLiteralOption(Option &Opt, StringRef Name) {
     139    74420040 :     if (Opt.Subs.empty())
     140    37204892 :       addLiteralOption(Opt, &*TopLevelSubCommand, Name);
     141             :     else {
     142       10256 :       for (auto SC : Opt.Subs)
     143        5128 :         addLiteralOption(Opt, SC, Name);
     144             :     }
     145    37210020 :   }
     146             : 
     147    84189588 :   void addOption(Option *O, SubCommand *SC) {
     148    84189588 :     bool HadErrors = false;
     149   168379176 :     if (O->hasArgStr()) {
     150             :       // Add argument to the argument map!
     151   251827944 :       if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
     152          20 :         errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
     153          10 :                << "' registered more than once!\n";
     154          10 :         HadErrors = true;
     155             :       }
     156             :     }
     157             : 
     158             :     // Remember information about positional options.
     159   168379176 :     if (O->getFormattingFlag() == cl::Positional)
     160       86873 :       SC->PositionalOpts.push_back(O);
     161   168205430 :     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
     162           0 :       SC->SinkOpts.push_back(O);
     163   168205430 :     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
     164         217 :       if (SC->ConsumeAfterOpt) {
     165           0 :         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
     166           0 :         HadErrors = true;
     167             :       }
     168         217 :       SC->ConsumeAfterOpt = O;
     169             :     }
     170             : 
     171             :     // Fail hard if there were errors. These are strictly unrecoverable and
     172             :     // indicate serious issues such as conflicting option names or an
     173             :     // incorrectly
     174             :     // linked LLVM distribution.
     175    84189588 :     if (HadErrors)
     176          10 :       report_fatal_error("inconsistency in registered CommandLine options");
     177             : 
     178             :     // If we're adding this to all sub-commands, add it to the ones that have
     179             :     // already been registered.
     180    84189578 :     if (SC == &*AllSubCommands) {
     181     2184224 :       for (const auto &Sub : RegisteredSubCommands) {
     182     1456151 :         if (SC == Sub)
     183      728073 :           continue;
     184      728078 :         addOption(O, Sub);
     185             :       }
     186             :     }
     187    84189578 :   }
     188             : 
     189    83453733 :   void addOption(Option *O) {
     190   166907466 :     if (O->Subs.empty()) {
     191    82707175 :       addOption(O, &*TopLevelSubCommand);
     192             :     } else {
     193     1493116 :       for (auto SC : O->Subs)
     194      746558 :         addOption(O, SC);
     195             :     }
     196    83453723 :   }
     197             : 
     198          60 :   void removeOption(Option *O, SubCommand *SC) {
     199         120 :     SmallVector<StringRef, 16> OptionNames;
     200          60 :     O->getExtraOptionNames(OptionNames);
     201          60 :     if (O->hasArgStr())
     202          56 :       OptionNames.push_back(O->ArgStr);
     203             : 
     204          60 :     SubCommand &Sub = *SC;
     205         236 :     for (auto Name : OptionNames)
     206          56 :       Sub.OptionsMap.erase(Name);
     207             : 
     208          60 :     if (O->getFormattingFlag() == cl::Positional)
     209           8 :       for (auto Opt = Sub.PositionalOpts.begin();
     210           8 :            Opt != Sub.PositionalOpts.end(); ++Opt) {
     211           4 :         if (*Opt == O) {
     212           4 :           Sub.PositionalOpts.erase(Opt);
     213             :           break;
     214             :         }
     215             :       }
     216          56 :     else if (O->getMiscFlags() & cl::Sink)
     217           0 :       for (auto Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
     218           0 :         if (*Opt == O) {
     219           0 :           Sub.SinkOpts.erase(Opt);
     220             :           break;
     221             :         }
     222             :       }
     223          56 :     else if (O == Sub.ConsumeAfterOpt)
     224           0 :       Sub.ConsumeAfterOpt = nullptr;
     225          60 :   }
     226             : 
     227          49 :   void removeOption(Option *O) {
     228          98 :     if (O->Subs.empty())
     229          32 :       removeOption(O, &*TopLevelSubCommand);
     230             :     else {
     231          17 :       if (O->isInAllSubCommands()) {
     232          19 :         for (auto SC : RegisteredSubCommands)
     233          15 :           removeOption(O, SC);
     234             :       } else {
     235          26 :         for (auto SC : O->Subs)
     236          13 :           removeOption(O, SC);
     237             :       }
     238             :     }
     239          49 :   }
     240             : 
     241             :   bool hasOptions(const SubCommand &Sub) const {
     242             :     return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
     243             :             nullptr != Sub.ConsumeAfterOpt);
     244             :   }
     245             : 
     246             :   bool hasOptions() const {
     247             :     for (const auto &S : RegisteredSubCommands) {
     248             :       if (hasOptions(*S))
     249             :         return true;
     250             :     }
     251             :     return false;
     252             :   }
     253             : 
     254             :   SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
     255             : 
     256           1 :   void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
     257           1 :     SubCommand &Sub = *SC;
     258           3 :     if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
     259           0 :       errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
     260           0 :              << "' registered more than once!\n";
     261           0 :       report_fatal_error("inconsistency in registered CommandLine options");
     262             :     }
     263           1 :     Sub.OptionsMap.erase(O->ArgStr);
     264           1 :   }
     265             : 
     266           1 :   void updateArgStr(Option *O, StringRef NewName) {
     267           2 :     if (O->Subs.empty())
     268           1 :       updateArgStr(O, NewName, &*TopLevelSubCommand);
     269             :     else {
     270           0 :       for (auto SC : O->Subs)
     271           0 :         updateArgStr(O, NewName, SC);
     272             :     }
     273           1 :   }
     274             : 
     275             :   void printOptionValues();
     276             : 
     277             :   void registerCategory(OptionCategory *cat) {
     278             :     assert(count_if(RegisteredOptionCategories,
     279             :                     [cat](const OptionCategory *Category) {
     280             :              return cat->getName() == Category->getName();
     281             :            }) == 0 &&
     282             :            "Duplicate option categories");
     283             : 
     284      281038 :     RegisteredOptionCategories.insert(cat);
     285             :   }
     286             : 
     287      244015 :   void registerSubCommand(SubCommand *sub) {
     288             :     assert(count_if(RegisteredSubCommands,
     289             :                     [sub](const SubCommand *Sub) {
     290             :                       return (!sub->getName().empty()) &&
     291             :                              (Sub->getName() == sub->getName());
     292             :                     }) == 0 &&
     293             :            "Duplicate subcommands");
     294      244015 :     RegisteredSubCommands.insert(sub);
     295             : 
     296             :     // For all options that have been registered for all subcommands, add the
     297             :     // option to this subcommand now.
     298      244015 :     if (sub != &*AllSubCommands) {
     299      506198 :       for (auto &E : AllSubCommands->OptionsMap) {
     300        7777 :         Option *O = E.second;
     301       31108 :         if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
     302        7777 :             O->hasArgStr())
     303        7777 :           addOption(O, sub);
     304             :         else
     305           0 :           addLiteralOption(*O, sub, E.first());
     306             :       }
     307             :     }
     308      244015 :   }
     309             : 
     310             :   void unregisterSubCommand(SubCommand *sub) {
     311          22 :     RegisteredSubCommands.erase(sub);
     312             :   }
     313             : 
     314             :   iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
     315          66 :   getRegisteredSubcommands() {
     316             :     return make_range(RegisteredSubCommands.begin(),
     317         132 :                       RegisteredSubCommands.end());
     318             :   }
     319             : 
     320           9 :   void reset() {
     321           9 :     ActiveSubCommand = nullptr;
     322          18 :     ProgramName.clear();
     323           9 :     ProgramOverview = StringRef();
     324             : 
     325          18 :     MoreHelp.clear();
     326           9 :     RegisteredOptionCategories.clear();
     327             : 
     328           9 :     ResetAllOptionOccurrences();
     329           9 :     RegisteredSubCommands.clear();
     330             : 
     331           9 :     TopLevelSubCommand->reset();
     332           9 :     AllSubCommands->reset();
     333           9 :     registerSubCommand(&*TopLevelSubCommand);
     334           9 :     registerSubCommand(&*AllSubCommands);
     335           9 :   }
     336             : 
     337             : private:
     338             :   SubCommand *ActiveSubCommand;
     339             : 
     340             :   Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
     341             :   SubCommand *LookupSubCommand(StringRef Name);
     342             : };
     343             : 
     344             : } // namespace
     345             : 
     346             : static ManagedStatic<CommandLineParser> GlobalParser;
     347             : 
     348    37210020 : void cl::AddLiteralOption(Option &O, StringRef Name) {
     349    37210020 :   GlobalParser->addLiteralOption(O, Name);
     350    37210020 : }
     351             : 
     352        1973 : extrahelp::extrahelp(StringRef Help) : morehelp(Help) {
     353        1973 :   GlobalParser->MoreHelp.push_back(Help);
     354        1973 : }
     355             : 
     356    83453733 : void Option::addArgument() {
     357    83453733 :   GlobalParser->addOption(this);
     358    83453723 :   FullyInitialized = true;
     359    83453723 : }
     360             : 
     361          98 : void Option::removeArgument() { GlobalParser->removeOption(this); }
     362             : 
     363    83206794 : void Option::setArgStr(StringRef S) {
     364    83206794 :   if (FullyInitialized)
     365           1 :     GlobalParser->updateArgStr(this, S);
     366             :   assert((S.empty() || S[0] != '-') && "Option can't start with '-");
     367    83206794 :   ArgStr = S;
     368    83206794 : }
     369             : 
     370             : // Initialise the general option category.
     371      242710 : OptionCategory llvm::cl::GeneralCategory("General options");
     372             : 
     373      281038 : void OptionCategory::registerCategory() {
     374      562076 :   GlobalParser->registerCategory(this);
     375      281038 : }
     376             : 
     377             : // A special subcommand representing no subcommand
     378             : ManagedStatic<SubCommand> llvm::cl::TopLevelSubCommand;
     379             : 
     380             : // A special subcommand that can be used to put an option into all subcommands.
     381             : ManagedStatic<SubCommand> llvm::cl::AllSubCommands;
     382             : 
     383        1307 : void SubCommand::registerSubCommand() {
     384        1307 :   GlobalParser->registerSubCommand(this);
     385        1307 : }
     386             : 
     387          11 : void SubCommand::unregisterSubCommand() {
     388          22 :   GlobalParser->unregisterSubCommand(this);
     389          11 : }
     390             : 
     391          18 : void SubCommand::reset() {
     392          36 :   PositionalOpts.clear();
     393          36 :   SinkOpts.clear();
     394          18 :   OptionsMap.clear();
     395             : 
     396          18 :   ConsumeAfterOpt = nullptr;
     397          18 : }
     398             : 
     399        1252 : SubCommand::operator bool() const {
     400        1252 :   return (GlobalParser->getActiveSubCommand() == this);
     401             : }
     402             : 
     403             : //===----------------------------------------------------------------------===//
     404             : // Basic, shared command line option processing machinery.
     405             : //
     406             : 
     407             : /// LookupOption - Lookup the option specified by the specified option on the
     408             : /// command line.  If there is a value specified (after an equal sign) return
     409             : /// that as well.  This assumes that leading dashes have already been stripped.
     410      140803 : Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
     411             :                                         StringRef &Value) {
     412             :   // Reject all dashes.
     413      140803 :   if (Arg.empty())
     414             :     return nullptr;
     415             :   assert(&Sub != &*AllSubCommands);
     416             : 
     417       75820 :   size_t EqualPos = Arg.find('=');
     418             : 
     419             :   // If we have an equals sign, remember the value.
     420       75820 :   if (EqualPos == StringRef::npos) {
     421             :     // Look up the option.
     422       64983 :     auto I = Sub.OptionsMap.find(Arg);
     423      129966 :     if (I == Sub.OptionsMap.end())
     424             :       return nullptr;
     425             : 
     426      252452 :     return I != Sub.OptionsMap.end() ? I->second : nullptr;
     427             :   }
     428             : 
     429             :   // If the argument before the = is a valid option name, we match.  If not,
     430             :   // return Arg unmolested.
     431      151640 :   auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
     432      151640 :   if (I == Sub.OptionsMap.end())
     433             :     return nullptr;
     434             : 
     435      151640 :   Value = Arg.substr(EqualPos + 1);
     436       75820 :   Arg = Arg.substr(0, EqualPos);
     437       75820 :   return I->second;
     438             : }
     439             : 
     440       35220 : SubCommand *CommandLineParser::LookupSubCommand(StringRef Name) {
     441       35220 :   if (Name.empty())
     442           0 :     return &*TopLevelSubCommand;
     443      106292 :   for (auto S : RegisteredSubCommands) {
     444       71072 :     if (S == &*AllSubCommands)
     445       35143 :       continue;
     446       35929 :     if (S->getName().empty())
     447       35131 :       continue;
     448             : 
     449         190 :     if (StringRef(S->getName()) == StringRef(Name))
     450         190 :       return S;
     451             :   }
     452       35030 :   return &*TopLevelSubCommand;
     453             : }
     454             : 
     455             : /// LookupNearestOption - Lookup the closest match to the option specified by
     456             : /// the specified option on the command line.  If there is a value specified
     457             : /// (after an equal sign) return that as well.  This assumes that leading dashes
     458             : /// have already been stripped.
     459          11 : static Option *LookupNearestOption(StringRef Arg,
     460             :                                    const StringMap<Option *> &OptionsMap,
     461             :                                    std::string &NearestString) {
     462             :   // Reject all dashes.
     463          11 :   if (Arg.empty())
     464             :     return nullptr;
     465             : 
     466             :   // Split on any equal sign.
     467          11 :   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
     468          11 :   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
     469          11 :   StringRef &RHS = SplitArg.second;
     470             : 
     471             :   // Find the closest match.
     472          11 :   Option *Best = nullptr;
     473          11 :   unsigned BestDistance = 0;
     474          22 :   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
     475          22 :                                            ie = OptionsMap.end();
     476        6707 :        it != ie; ++it) {
     477        6696 :     Option *O = it->second;
     478       13392 :     SmallVector<StringRef, 16> OptionNames;
     479        6696 :     O->getExtraOptionNames(OptionNames);
     480        6696 :     if (O->hasArgStr())
     481        5961 :       OptionNames.push_back(O->ArgStr);
     482             : 
     483        6696 :     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
     484        6696 :     StringRef Flag = PermitValue ? LHS : Arg;
     485      278164 :     for (auto Name : OptionNames) {
     486      516152 :       unsigned Distance = StringRef(Name).edit_distance(
     487      258076 :           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
     488      258076 :       if (!Best || Distance < BestDistance) {
     489          37 :         Best = O;
     490          37 :         BestDistance = Distance;
     491          37 :         if (RHS.empty() || !PermitValue)
     492          74 :           NearestString = Name;
     493             :         else
     494           0 :           NearestString = (Twine(Name) + "=" + RHS).str();
     495             :       }
     496             :     }
     497             :   }
     498             : 
     499             :   return Best;
     500             : }
     501             : 
     502             : /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
     503             : /// that does special handling of cl::CommaSeparated options.
     504      201461 : static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
     505             :                                           StringRef ArgName, StringRef Value,
     506             :                                           bool MultiArg = false) {
     507             :   // Check to see if this option accepts a comma separated list of values.  If
     508             :   // it does, we have to split up the value into multiple values.
     509      201461 :   if (Handler->getMiscFlags() & CommaSeparated) {
     510        6998 :     StringRef Val(Value);
     511             :     StringRef::size_type Pos = Val.find(',');
     512             : 
     513        9460 :     while (Pos != StringRef::npos) {
     514             :       // Process the portion before the comma.
     515        7500 :       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
     516           0 :         return true;
     517             :       // Erase the portion before the comma, AND the comma.
     518        7500 :       Val = Val.substr(Pos + 1);
     519             :       // Check for another comma.
     520        1231 :       Pos = Val.find(',');
     521             :     }
     522             : 
     523        6998 :     Value = Val;
     524             :   }
     525             : 
     526      201461 :   return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
     527             : }
     528             : 
     529             : /// ProvideOption - For Value, this differentiates between an empty value ("")
     530             : /// and a null value (StringRef()).  The later is accepted for arguments that
     531             : /// don't allow a value (-foo) the former is rejected (-foo=).
     532      201461 : static inline bool ProvideOption(Option *Handler, StringRef ArgName,
     533             :                                  StringRef Value, int argc,
     534             :                                  const char *const *argv, int &i) {
     535             :   // Is this a multi-argument option?
     536      201461 :   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
     537             : 
     538             :   // Enforce value requirements
     539      201461 :   switch (Handler->getValueExpectedFlag()) {
     540      152723 :   case ValueRequired:
     541      152723 :     if (!Value.data()) { // No value specified?
     542       16486 :       if (i + 1 >= argc)
     543           0 :         return Handler->error("requires a value!");
     544             :       // Steal the next argument, like for '-o filename'
     545             :       assert(argv && "null check");
     546       32972 :       Value = StringRef(argv[++i]);
     547             :     }
     548             :     break;
     549       11164 :   case ValueDisallowed:
     550       11164 :     if (NumAdditionalVals > 0)
     551           0 :       return Handler->error("multi-valued option specified"
     552           0 :                             " with ValueDisallowed modifier!");
     553             : 
     554       11164 :     if (Value.data())
     555           0 :       return Handler->error("does not allow a value! '" + Twine(Value) +
     556           0 :                             "' specified.");
     557             :     break;
     558             :   case ValueOptional:
     559             :     break;
     560             :   }
     561             : 
     562             :   // If this isn't a multi-arg option, just run the handler.
     563      201461 :   if (NumAdditionalVals == 0)
     564      201461 :     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
     565             : 
     566             :   // If it is, run the handle several times.
     567           0 :   bool MultiArg = false;
     568             : 
     569           0 :   if (Value.data()) {
     570           0 :     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
     571             :       return true;
     572           0 :     --NumAdditionalVals;
     573           0 :     MultiArg = true;
     574             :   }
     575             : 
     576           0 :   while (NumAdditionalVals > 0) {
     577           0 :     if (i + 1 >= argc)
     578           0 :       return Handler->error("not enough values!");
     579             :     assert(argv && "null check");
     580           0 :     Value = StringRef(argv[++i]);
     581             : 
     582           0 :     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
     583             :       return true;
     584           0 :     MultiArg = true;
     585           0 :     --NumAdditionalVals;
     586             :   }
     587             :   return false;
     588             : }
     589             : 
     590             : static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
     591       60663 :   int Dummy = i;
     592       60663 :   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
     593             : }
     594             : 
     595             : // Option predicates...
     596           8 : static inline bool isGrouping(const Option *O) {
     597        1868 :   return O->getFormattingFlag() == cl::Grouping;
     598             : }
     599        1860 : static inline bool isPrefixedOrGrouping(const Option *O) {
     600        3715 :   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
     601             : }
     602             : 
     603             : // getOptionPred - Check to see if there are any options that satisfy the
     604             : // specified predicate with names that are the prefixes in Name.  This is
     605             : // checked by progressively stripping characters off of the name, checking to
     606             : // see if there options that satisfy the predicate.  If we find one, return it,
     607             : // otherwise return null.
     608             : //
     609        1877 : static Option *getOptionPred(StringRef Name, size_t &Length,
     610             :                              bool (*Pred)(const Option *),
     611             :                              const StringMap<Option *> &OptionsMap) {
     612             : 
     613        1877 :   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
     614             : 
     615             :   // Loop while we haven't found an option and Name still has at least two
     616             :   // characters in it (so that the next iteration will not be the empty
     617             :   // string.
     618       12479 :   while (OMI == OptionsMap.end() && Name.size() > 1) {
     619        4358 :     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
     620        2179 :     OMI = OptionsMap.find(Name);
     621             :   }
     622             : 
     623        7499 :   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
     624        1867 :     Length = Name.size();
     625        1867 :     return OMI->second; // Found one!
     626             :   }
     627             :   return nullptr; // No option found!
     628             : }
     629             : 
     630             : /// HandlePrefixedOrGroupedOption - The specified argument string (which started
     631             : /// with at least one '-') does not fully match an available option.  Check to
     632             : /// see if this is a prefix or grouped option.  If so, split arg into output an
     633             : /// Arg/Value pair and return the Option to parse it with.
     634             : static Option *
     635        1870 : HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
     636             :                               bool &ErrorParsing,
     637             :                               const StringMap<Option *> &OptionsMap) {
     638        1870 :   if (Arg.size() == 1)
     639             :     return nullptr;
     640             : 
     641             :   // Do the lookup!
     642        1869 :   size_t Length = 0;
     643        1869 :   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
     644        1869 :   if (!PGOpt)
     645             :     return nullptr;
     646             : 
     647             :   // If the option is a prefixed option, then the value is simply the
     648             :   // rest of the name...  so fall through to later processing, by
     649             :   // setting up the argument name flags and value fields.
     650        1859 :   if (PGOpt->getFormattingFlag() == cl::Prefix) {
     651        3708 :     Value = Arg.substr(Length);
     652        3708 :     Arg = Arg.substr(0, Length);
     653             :     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
     654        1854 :     return PGOpt;
     655             :   }
     656             : 
     657             :   // This must be a grouped option... handle them now.  Grouping options can't
     658             :   // have values.
     659             :   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
     660             : 
     661             :   do {
     662             :     // Move current arg name out of Arg into OneArgName.
     663          16 :     StringRef OneArgName = Arg.substr(0, Length);
     664          16 :     Arg = Arg.substr(Length);
     665             : 
     666             :     // Because ValueRequired is an invalid flag for grouped arguments,
     667             :     // we don't need to pass argc/argv in.
     668             :     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
     669             :            "Option can not be cl::Grouping AND cl::ValueRequired!");
     670           8 :     int Dummy = 0;
     671           8 :     ErrorParsing |=
     672          16 :         ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
     673             : 
     674             :     // Get the next grouping option.
     675           8 :     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
     676          16 :   } while (PGOpt && Length != Arg.size());
     677             : 
     678             :   // Return the last option with Arg cut down to just the last one.
     679             :   return PGOpt;
     680             : }
     681             : 
     682             : static bool RequiresValue(const Option *O) {
     683      252150 :   return O->getNumOccurrencesFlag() == cl::Required ||
     684       81261 :          O->getNumOccurrencesFlag() == cl::OneOrMore;
     685             : }
     686             : 
     687             : static bool EatsUnboundedNumberOfValues(const Option *O) {
     688      165187 :   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
     689       79630 :          O->getNumOccurrencesFlag() == cl::OneOrMore;
     690             : }
     691             : 
     692     7207670 : static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
     693             : 
     694     3301208 : static bool isQuote(char C) { return C == '\"' || C == '\''; }
     695             : 
     696          19 : void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
     697             :                                 SmallVectorImpl<const char *> &NewArgv,
     698             :                                 bool MarkEOLs) {
     699          38 :   SmallString<128> Token;
     700     3301261 :   for (size_t I = 0, E = Src.size(); I != E; ++I) {
     701             :     // Consume runs of whitespace.
     702     3301225 :     if (Token.empty()) {
     703     2700423 :       while (I != E && isWhitespace(Src[I])) {
     704             :         // Mark the end of lines in response files
     705          19 :         if (MarkEOLs && Src[I] == '\n')
     706           0 :           NewArgv.push_back(nullptr);
     707          19 :         ++I;
     708             :       }
     709      900117 :       if (I == E)
     710             :         break;
     711             :     }
     712             : 
     713             :     // Backslash escapes the next character.
     714     6602445 :     if (I + 1 < E && Src[I] == '\\') {
     715          15 :       ++I; // Skip the escape.
     716          30 :       Token.push_back(Src[I]);
     717          15 :       continue;
     718             :     }
     719             : 
     720             :     // Consume a quoted string.
     721     9903624 :     if (isQuote(Src[I])) {
     722             :       char Quote = Src[I++];
     723     6603603 :       while (I != E && Src[I] != Quote) {
     724             :         // Backslash escapes the next character.
     725     1801153 :         if (Src[I] == '\\' && I + 1 != E)
     726           9 :           ++I;
     727     3602306 :         Token.push_back(Src[I]);
     728     1801153 :         ++I;
     729             :       }
     730      600072 :       if (I == E)
     731             :         break;
     732      600072 :       continue;
     733             :     }
     734             : 
     735             :     // End the token if this is whitespace.
     736     6302384 :     if (isWhitespace(Src[I])) {
     737      900112 :       if (!Token.empty())
     738     2700336 :         NewArgv.push_back(Saver.save(StringRef(Token)).data());
     739      900112 :       Token.clear();
     740      900112 :       continue;
     741             :     }
     742             : 
     743             :     // This is a normal character.  Append it.
     744     1801024 :     Token.push_back(Src[I]);
     745             :   }
     746             : 
     747             :   // Append the last token after hitting EOF with no whitespace.
     748          19 :   if (!Token.empty())
     749           9 :     NewArgv.push_back(Saver.save(StringRef(Token)).data());
     750             :   // Mark the end of response files
     751          19 :   if (MarkEOLs)
     752           0 :     NewArgv.push_back(nullptr);
     753          19 : }
     754             : 
     755             : /// Backslashes are interpreted in a rather complicated way in the Windows-style
     756             : /// command line, because backslashes are used both to separate path and to
     757             : /// escape double quote. This method consumes runs of backslashes as well as the
     758             : /// following double quote if it's escaped.
     759             : ///
     760             : ///  * If an even number of backslashes is followed by a double quote, one
     761             : ///    backslash is output for every pair of backslashes, and the last double
     762             : ///    quote remains unconsumed. The double quote will later be interpreted as
     763             : ///    the start or end of a quoted string in the main loop outside of this
     764             : ///    function.
     765             : ///
     766             : ///  * If an odd number of backslashes is followed by a double quote, one
     767             : ///    backslash is output for every pair of backslashes, and a double quote is
     768             : ///    output for the last pair of backslash-double quote. The double quote is
     769             : ///    consumed in this case.
     770             : ///
     771             : ///  * Otherwise, backslashes are interpreted literally.
     772          19 : static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
     773          19 :   size_t E = Src.size();
     774          19 :   int BackslashCount = 0;
     775             :   // Skip the backslashes.
     776             :   do {
     777          23 :     ++I;
     778          23 :     ++BackslashCount;
     779          46 :   } while (I != E && Src[I] == '\\');
     780             : 
     781          44 :   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
     782             :   if (FollowedByDoubleQuote) {
     783          12 :     Token.append(BackslashCount / 2, '\\');
     784           6 :     if (BackslashCount % 2 == 0)
     785             :       return I - 1;
     786           5 :     Token.push_back('"');
     787           5 :     return I;
     788             :   }
     789          26 :   Token.append(BackslashCount, '\\');
     790          13 :   return I - 1;
     791             : }
     792             : 
     793          89 : void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
     794             :                                     SmallVectorImpl<const char *> &NewArgv,
     795             :                                     bool MarkEOLs) {
     796         178 :   SmallString<128> Token;
     797             : 
     798             :   // This is a small state machine to consume characters until it reaches the
     799             :   // end of the source string.
     800          89 :   enum { INIT, UNQUOTED, QUOTED } State = INIT;
     801        3302 :   for (size_t I = 0, E = Src.size(); I != E; ++I) {
     802             :     // INIT state indicates that the current input index is at the start of
     803             :     // the string or between tokens.
     804        3269 :     if (State == INIT) {
     805         454 :       if (isWhitespace(Src[I])) {
     806             :         // Mark the end of lines in response files
     807           1 :         if (MarkEOLs && Src[I] == '\n')
     808           0 :           NewArgv.push_back(nullptr);
     809           1 :         continue;
     810             :       }
     811         154 :       if (Src[I] == '"') {
     812           4 :         State = QUOTED;
     813           4 :         continue;
     814             :       }
     815         147 :       if (Src[I] == '\\') {
     816           1 :         I = parseBackslash(Src, I, Token);
     817           1 :         State = UNQUOTED;
     818           1 :         continue;
     819             :       }
     820         145 :       Token.push_back(Src[I]);
     821         145 :       State = UNQUOTED;
     822         145 :       continue;
     823             :     }
     824             : 
     825             :     // UNQUOTED state means that it's reading a token not quoted by double
     826             :     // quotes.
     827        5207 :     if (State == UNQUOTED) {
     828             :       // Whitespace means the end of the token.
     829        7341 :       if (isWhitespace(Src[I])) {
     830         297 :         NewArgv.push_back(Saver.save(StringRef(Token)).data());
     831          99 :         Token.clear();
     832          99 :         State = INIT;
     833             :         // Mark the end of lines in response files
     834         104 :         if (MarkEOLs && Src[I] == '\n')
     835           2 :           NewArgv.push_back(nullptr);
     836          99 :         continue;
     837             :       }
     838        2379 :       if (Src[I] == '"') {
     839          64 :         State = QUOTED;
     840          64 :         continue;
     841             :       }
     842        2268 :       if (Src[I] == '\\') {
     843          17 :         I = parseBackslash(Src, I, Token);
     844          17 :         continue;
     845             :       }
     846        2234 :       Token.push_back(Src[I]);
     847        2234 :       continue;
     848             :     }
     849             : 
     850             :     // QUOTED state means that it's reading a token quoted by double quotes.
     851         559 :     if (State == QUOTED) {
     852        1186 :       if (Src[I] == '"') {
     853          68 :         State = UNQUOTED;
     854          68 :         continue;
     855             :       }
     856         492 :       if (Src[I] == '\\') {
     857           1 :         I = parseBackslash(Src, I, Token);
     858           1 :         continue;
     859             :       }
     860         490 :       Token.push_back(Src[I]);
     861             :     }
     862             :   }
     863             :   // Append the last token after hitting EOF with no whitespace.
     864          89 :   if (!Token.empty())
     865         153 :     NewArgv.push_back(Saver.save(StringRef(Token)).data());
     866             :   // Mark the end of response files
     867          89 :   if (MarkEOLs)
     868           2 :     NewArgv.push_back(nullptr);
     869          89 : }
     870             : 
     871             : // It is called byte order marker but the UTF-8 BOM is actually not affected
     872             : // by the host system's endianness.
     873             : static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
     874          21 :   return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
     875             : }
     876             : 
     877          23 : static bool ExpandResponseFile(StringRef FName, StringSaver &Saver,
     878             :                                TokenizerCallback Tokenizer,
     879             :                                SmallVectorImpl<const char *> &NewArgv,
     880             :                                bool MarkEOLs, bool RelativeNames) {
     881             :   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
     882          46 :       MemoryBuffer::getFile(FName);
     883          23 :   if (!MemBufOrErr)
     884             :     return false;
     885          44 :   MemoryBuffer &MemBuf = *MemBufOrErr.get();
     886          44 :   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
     887             : 
     888             :   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
     889          44 :   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
     890          22 :   std::string UTF8Buf;
     891          22 :   if (hasUTF16ByteOrderMark(BufRef)) {
     892           1 :     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
     893             :       return false;
     894           1 :     Str = StringRef(UTF8Buf);
     895             :   }
     896             :   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
     897             :   // these bytes before parsing.
     898             :   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
     899           1 :   else if (hasUTF8ByteOrderMark(BufRef))
     900           1 :     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
     901             : 
     902             :   // Tokenize the contents into NewArgv.
     903          22 :   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
     904             : 
     905             :   // If names of nested response files should be resolved relative to including
     906             :   // file, replace the included response file names with their full paths
     907             :   // obtained by required resolution.
     908          22 :   if (RelativeNames)
     909          25 :     for (unsigned I = 0; I < NewArgv.size(); ++I)
     910          14 :       if (NewArgv[I]) {
     911          21 :         StringRef Arg = NewArgv[I];
     912          14 :         if (Arg.front() == '@') {
     913           1 :           StringRef FileName = Arg.drop_front();
     914           1 :           if (llvm::sys::path::is_relative(FileName)) {
     915           2 :             SmallString<128> ResponseFile;
     916           1 :             ResponseFile.append(1, '@');
     917           1 :             if (llvm::sys::path::is_relative(FName)) {
     918           0 :               SmallString<128> curr_dir;
     919           0 :               llvm::sys::fs::current_path(curr_dir);
     920           0 :               ResponseFile.append(curr_dir.str());
     921             :             }
     922           5 :             llvm::sys::path::append(
     923           2 :                 ResponseFile, llvm::sys::path::parent_path(FName), FileName);
     924           3 :             NewArgv[I] = Saver.save(ResponseFile.c_str()).data();
     925             :           }
     926             :         }
     927             :       }
     928             : 
     929             :   return true;
     930             : }
     931             : 
     932             : /// \brief Expand response files on a command line recursively using the given
     933             : /// StringSaver and tokenization strategy.
     934      121513 : bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
     935             :                              SmallVectorImpl<const char *> &Argv,
     936             :                              bool MarkEOLs, bool RelativeNames) {
     937      121513 :   unsigned RspFiles = 0;
     938      121513 :   bool AllExpanded = true;
     939             : 
     940             :   // Don't cache Argv.size() because it can change.
     941     1755899 :   for (unsigned I = 0; I != Argv.size();) {
     942     3025746 :     const char *Arg = Argv[I];
     943             :     // Check if it is an EOL marker
     944     1512877 :     if (Arg == nullptr) {
     945           4 :       ++I;
     946     1512855 :       continue;
     947             :     }
     948     3025715 :     if (Arg[0] != '@') {
     949     1512846 :       ++I;
     950     1512846 :       continue;
     951             :     }
     952             : 
     953             :     // If we have too many response files, leave some unexpanded.  This avoids
     954             :     // crashing on self-referential response files.
     955          23 :     if (RspFiles++ > 20)
     956           0 :       return false;
     957             : 
     958             :     // Replace this response file argument with the tokenization of its
     959             :     // contents.  Nested response files are expanded in subsequent iterations.
     960          45 :     SmallVector<const char *, 0> ExpandedArgv;
     961          47 :     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
     962             :                             MarkEOLs, RelativeNames)) {
     963             :       // We couldn't read this file, so we leave it in the argument stream and
     964             :       // move on.
     965           1 :       AllExpanded = false;
     966           1 :       ++I;
     967             :       continue;
     968             :     }
     969          44 :     Argv.erase(Argv.begin() + I);
     970          66 :     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
     971             :   }
     972             :   return AllExpanded;
     973             : }
     974             : 
     975             : /// ParseEnvironmentOptions - An alternative entry point to the
     976             : /// CommandLine library, which allows you to read the program's name
     977             : /// from the caller (as PROGNAME) and its command-line arguments from
     978             : /// an environment variable (whose name is given in ENVVAR).
     979             : ///
     980           2 : void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
     981             :                                  const char *Overview) {
     982             :   // Check args.
     983             :   assert(progName && "Program name not specified");
     984             :   assert(envVar && "Environment variable name missing");
     985             : 
     986             :   // Get the environment variable they want us to parse options out of.
     987           4 :   llvm::Optional<std::string> envValue = sys::Process::GetEnv(StringRef(envVar));
     988           2 :   if (!envValue)
     989           0 :     return;
     990             : 
     991             :   // Get program's "name", which we wouldn't know without the caller
     992             :   // telling us.
     993           4 :   SmallVector<const char *, 20> newArgv;
     994           4 :   BumpPtrAllocator A;
     995           2 :   StringSaver Saver(A);
     996           4 :   newArgv.push_back(Saver.save(progName).data());
     997             : 
     998             :   // Parse the value of the environment variable into a "command line"
     999             :   // and hand it off to ParseCommandLineOptions().
    1000           4 :   TokenizeGNUCommandLine(*envValue, Saver, newArgv);
    1001           2 :   int newArgc = static_cast<int>(newArgv.size());
    1002           4 :   ParseCommandLineOptions(newArgc, &newArgv[0], StringRef(Overview));
    1003             : }
    1004             : 
    1005       97587 : bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
    1006             :                                  StringRef Overview, raw_ostream *Errs) {
    1007       97587 :   return GlobalParser->ParseCommandLineOptions(argc, argv, Overview,
    1008       97587 :                                                Errs);
    1009             : }
    1010             : 
    1011          23 : void CommandLineParser::ResetAllOptionOccurrences() {
    1012             :   // So that we can parse different command lines multiple times in succession
    1013             :   // we reset all option values to look like they have never been seen before.
    1014          90 :   for (auto SC : RegisteredSubCommands) {
    1015       19486 :     for (auto &O : SC->OptionsMap)
    1016       19218 :       O.second->reset();
    1017             :   }
    1018          23 : }
    1019             : 
    1020       97587 : bool CommandLineParser::ParseCommandLineOptions(int argc,
    1021             :                                                 const char *const *argv,
    1022             :                                                 StringRef Overview,
    1023             :                                                 raw_ostream *Errs) {
    1024             :   assert(hasOptions() && "No options specified!");
    1025             : 
    1026             :   // Expand response files.
    1027      292746 :   SmallVector<const char *, 20> newArgv(argv, argv + argc);
    1028      195159 :   BumpPtrAllocator A;
    1029       97587 :   StringSaver Saver(A);
    1030       97587 :   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
    1031       97587 :   argv = &newArgv[0];
    1032       97587 :   argc = static_cast<int>(newArgv.size());
    1033             : 
    1034             :   // Copy the program name into ProgName, making sure not to overflow it.
    1035      390348 :   ProgramName = sys::path::filename(StringRef(argv[0]));
    1036             : 
    1037       97587 :   ProgramOverview = Overview;
    1038       97587 :   bool IgnoreErrors = Errs;
    1039       97587 :   if (!Errs)
    1040       97565 :     Errs = &errs();
    1041       97587 :   bool ErrorParsing = false;
    1042             : 
    1043             :   // Check out the positional arguments to collect information about them.
    1044       97587 :   unsigned NumPositionalRequired = 0;
    1045             : 
    1046             :   // Determine whether or not there are an unlimited number of positionals
    1047       97587 :   bool HasUnlimitedPositionals = false;
    1048             : 
    1049       97587 :   int FirstArg = 1;
    1050       97587 :   SubCommand *ChosenSubCommand = &*TopLevelSubCommand;
    1051       97587 :   if (argc >= 2 && argv[FirstArg][0] != '-') {
    1052             :     // If the first argument specifies a valid subcommand, start processing
    1053             :     // options from the second argument.
    1054       70440 :     ChosenSubCommand = LookupSubCommand(StringRef(argv[FirstArg]));
    1055       35220 :     if (ChosenSubCommand != &*TopLevelSubCommand)
    1056         190 :       FirstArg = 2;
    1057             :   }
    1058       97587 :   GlobalParser->ActiveSubCommand = ChosenSubCommand;
    1059             : 
    1060             :   assert(ChosenSubCommand);
    1061       97587 :   auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
    1062       97587 :   auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
    1063       97587 :   auto &SinkOpts = ChosenSubCommand->SinkOpts;
    1064       97587 :   auto &OptionsMap = ChosenSubCommand->OptionsMap;
    1065             : 
    1066             :   if (ConsumeAfterOpt) {
    1067             :     assert(PositionalOpts.size() > 0 &&
    1068             :            "Cannot specify cl::ConsumeAfter without a positional argument!");
    1069             :   }
    1070       97587 :   if (!PositionalOpts.empty()) {
    1071             : 
    1072             :     // Calculate how many positional values are _required_.
    1073       85089 :     bool UnboundedFound = false;
    1074      255735 :     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
    1075      171114 :       Option *Opt = PositionalOpts[i];
    1076       39812 :       if (RequiresValue(Opt))
    1077       45745 :         ++NumPositionalRequired;
    1078       39812 :       else if (ConsumeAfterOpt) {
    1079             :         // ConsumeAfter cannot be combined with "optional" positional options
    1080             :         // unless there is only one positional argument...
    1081         418 :         if (PositionalOpts.size() > 1) {
    1082           0 :           if (!IgnoreErrors)
    1083           0 :             Opt->error("error - this positional option will never be matched, "
    1084             :                        "because it does not Require a value, and a "
    1085           0 :                        "cl::ConsumeAfter option is active!");
    1086           0 :           ErrorParsing = true;
    1087             :         }
    1088       39940 :       } else if (UnboundedFound && !Opt->hasArgStr()) {
    1089             :         // This option does not "require" a value...  Make sure this option is
    1090             :         // not specified after an option that eats all extra arguments, or this
    1091             :         // one will never get any!
    1092             :         //
    1093           0 :         if (!IgnoreErrors)
    1094           0 :           Opt->error("error - option can never match, because "
    1095             :                      "another positional argument will match an "
    1096             :                      "unbounded number of values, and this option"
    1097           0 :                      " does not require a value!");
    1098           0 :         *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
    1099           0 :               << "' is all messed up!\n";
    1100           0 :         *Errs << PositionalOpts.size();
    1101           0 :         ErrorParsing = true;
    1102             :       }
    1103       85557 :       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
    1104             :     }
    1105       85089 :     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
    1106             :   }
    1107             : 
    1108             :   // PositionalVals - A vector of "positional" arguments we accumulate into
    1109             :   // the process at the end.
    1110             :   //
    1111      195159 :   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
    1112             : 
    1113             :   // If the program has named positional arguments, and the name has been run
    1114             :   // across, keep track of which positional argument was named.  Otherwise put
    1115             :   // the positional args into the PositionalVals list...
    1116       97587 :   Option *ActivePositionalArg = nullptr;
    1117             : 
    1118             :   // Loop over all of the arguments... processing them.
    1119       97587 :   bool DashDashFound = false; // Have we read '--'?
    1120      298764 :   for (int i = FirstArg; i < argc; ++i) {
    1121      201399 :     Option *Handler = nullptr;
    1122      201399 :     Option *NearestHandler = nullptr;
    1123      342182 :     std::string NearestHandlerString;
    1124      201399 :     StringRef Value;
    1125      201399 :     StringRef ArgName = "";
    1126             : 
    1127             :     // Check to see if this is a positional argument.  This argument is
    1128             :     // considered to be positional if it doesn't start with '-', if it is "-"
    1129             :     // itself, or if we have seen "--" already.
    1130             :     //
    1131      201399 :     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
    1132             :       // Positional argument!
    1133       60599 :       if (ActivePositionalArg) {
    1134           9 :         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
    1135       60397 :         continue; // We are done!
    1136             :       }
    1137             : 
    1138      120973 :       if (!PositionalOpts.empty()) {
    1139      242372 :         PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
    1140             : 
    1141             :         // All of the positional arguments have been fulfulled, give the rest to
    1142             :         // the consume after option... if it's specified...
    1143             :         //
    1144       60593 :         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
    1145         280 :           for (++i; i < argc; ++i)
    1146         268 :             PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
    1147         213 :           break; // Handle outside of the argument processing loop...
    1148             :         }
    1149             : 
    1150             :         // Delay processing positional arguments until the end...
    1151       60380 :         continue;
    1152             :       }
    1153      140803 :     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
    1154             :                !DashDashFound) {
    1155           0 :       DashDashFound = true; // This is the mythical "--"?
    1156           0 :       continue;             // Don't try to process it as an argument itself.
    1157      140803 :     } else if (ActivePositionalArg &&
    1158           0 :                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
    1159             :       // If there is a positional argument eating options, check to see if this
    1160             :       // option is another positional argument.  If so, treat it as an argument,
    1161             :       // otherwise feed it to the eating positional.
    1162           0 :       ArgName = StringRef(argv[i] + 1);
    1163             :       // Eat leading dashes.
    1164           0 :       while (!ArgName.empty() && ArgName[0] == '-')
    1165           0 :         ArgName = ArgName.substr(1);
    1166             : 
    1167           0 :       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
    1168           0 :       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
    1169           0 :         ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
    1170           0 :         continue; // We are done!
    1171             :       }
    1172             : 
    1173             :     } else { // We start with a '-', must be an argument.
    1174      281606 :       ArgName = StringRef(argv[i] + 1);
    1175             :       // Eat leading dashes.
    1176      332408 :       while (!ArgName.empty() && ArgName[0] == '-')
    1177       16934 :         ArgName = ArgName.substr(1);
    1178             : 
    1179      140803 :       Handler = LookupOption(*ChosenSubCommand, ArgName, Value);
    1180             : 
    1181             :       // Check to see if this "option" is really a prefixed or grouped argument.
    1182      140803 :       if (!Handler)
    1183        1870 :         Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
    1184             :                                                 OptionsMap);
    1185             : 
    1186             :       // Otherwise, look for the closest available option to report to the user
    1187             :       // in the upcoming error.
    1188      140803 :       if (!Handler && SinkOpts.empty())
    1189          11 :         NearestHandler =
    1190             :             LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
    1191             :     }
    1192             : 
    1193      140803 :     if (!Handler) {
    1194          11 :       if (SinkOpts.empty()) {
    1195          22 :         *Errs << ProgramName << ": Unknown command line argument '" << argv[i]
    1196          11 :               << "'.  Try: '" << argv[0] << " -help'\n";
    1197             : 
    1198          11 :         if (NearestHandler) {
    1199             :           // If we know a near match, report it as well.
    1200          33 :           *Errs << ProgramName << ": Did you mean '-" << NearestHandlerString
    1201          11 :                  << "'?\n";
    1202             :         }
    1203             : 
    1204          11 :         ErrorParsing = true;
    1205             :       } else {
    1206           0 :         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
    1207             :                                                  E = SinkOpts.end();
    1208           0 :              I != E; ++I)
    1209           0 :           (*I)->addOccurrence(i, "", StringRef(argv[i]));
    1210             :       }
    1211          11 :       continue;
    1212             :     }
    1213             : 
    1214             :     // If this is a named positional argument, just remember that it is the
    1215             :     // active one...
    1216      140792 :     if (Handler->getFormattingFlag() == cl::Positional)
    1217             :       ActivePositionalArg = Handler;
    1218             :     else
    1219      140790 :       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
    1220             :   }
    1221             : 
    1222             :   // Check and handle positional arguments now...
    1223      195156 :   if (NumPositionalRequired > PositionalVals.size()) {
    1224           0 :       *Errs << ProgramName
    1225           0 :              << ": Not enough positional command line arguments specified!\n"
    1226           0 :              << "Must specify at least " << NumPositionalRequired
    1227           0 :              << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
    1228           0 :              << ": See: " << argv[0] << " -help\n";
    1229             : 
    1230           0 :     ErrorParsing = true;
    1231      188461 :   } else if (!HasUnlimitedPositionals &&
    1232      181766 :              PositionalVals.size() > PositionalOpts.size()) {
    1233           0 :     *Errs << ProgramName << ": Too many positional arguments specified!\n"
    1234           0 :           << "Can specify at most " << PositionalOpts.size()
    1235           0 :           << " positional arguments: See: " << argv[0] << " -help\n";
    1236           0 :     ErrorParsing = true;
    1237             : 
    1238       97578 :   } else if (!ConsumeAfterOpt) {
    1239             :     // Positional args have already been handled if ConsumeAfter is specified.
    1240      194722 :     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
    1241      280054 :     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
    1242      170664 :       if (RequiresValue(PositionalOpts[i])) {
    1243      182948 :         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
    1244       91474 :                                 PositionalVals[ValNo].second);
    1245       45737 :         ValNo++;
    1246       45737 :         --NumPositionalRequired; // We fulfilled our duty...
    1247             :       }
    1248             : 
    1249             :       // If we _can_ give this option more arguments, do so now, as long as we
    1250             :       // do not give it values that others need.  'Done' controls whether the
    1251             :       // option even _WANTS_ any more.
    1252             :       //
    1253      255996 :       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
    1254      114618 :       while (NumVals - ValNo > NumPositionalRequired && !Done) {
    1255       43929 :         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
    1256        8988 :         case cl::Optional:
    1257        8988 :           Done = true; // Optional arguments want _at most_ one value
    1258             :           LLVM_FALLTHROUGH;
    1259       14643 :         case cl::ZeroOrMore: // Zero or more will take all they can get...
    1260             :         case cl::OneOrMore:  // One or more will take all they can get...
    1261       58572 :           ProvidePositionalOption(PositionalOpts[i],
    1262       29286 :                                   PositionalVals[ValNo].first,
    1263       29286 :                                   PositionalVals[ValNo].second);
    1264       14643 :           ValNo++;
    1265             :           break;
    1266           0 :         default:
    1267           0 :           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
    1268             :                            "positional argument processing!");
    1269             :         }
    1270             :       }
    1271             :     }
    1272             :   } else {
    1273             :     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
    1274         217 :     unsigned ValNo = 0;
    1275         434 :     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
    1276           0 :       if (RequiresValue(PositionalOpts[j])) {
    1277           0 :         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
    1278           0 :                                                 PositionalVals[ValNo].first,
    1279           0 :                                                 PositionalVals[ValNo].second);
    1280           0 :         ValNo++;
    1281             :       }
    1282             : 
    1283             :     // Handle the case where there is just one positional option, and it's
    1284             :     // optional.  In this case, we want to give JUST THE FIRST option to the
    1285             :     // positional option and keep the rest for the consume after.  The above
    1286             :     // loop would have assigned no values to positional options in this case.
    1287             :     //
    1288         434 :     if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
    1289         852 :       ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
    1290         426 :                                               PositionalVals[ValNo].first,
    1291         426 :                                               PositionalVals[ValNo].second);
    1292         213 :       ValNo++;
    1293             :     }
    1294             : 
    1295             :     // Handle over all of the rest of the arguments to the
    1296             :     // cl::ConsumeAfter command line option...
    1297         635 :     for (; ValNo != PositionalVals.size(); ++ValNo)
    1298          67 :       ErrorParsing |=
    1299         201 :           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
    1300         134 :                                   PositionalVals[ValNo].second);
    1301             :   }
    1302             : 
    1303             :   // Loop over args and make sure all required args are specified!
    1304   127568838 :   for (const auto &Opt : OptionsMap) {
    1305   127178526 :     switch (Opt.second->getNumOccurrencesFlag()) {
    1306         821 :     case Required:
    1307             :     case OneOrMore:
    1308         821 :       if (Opt.second->getNumOccurrences() == 0) {
    1309           8 :         Opt.second->error("must be specified at least once!");
    1310           4 :         ErrorParsing = true;
    1311             :       }
    1312             :       LLVM_FALLTHROUGH;
    1313             :     default:
    1314             :       break;
    1315             :     }
    1316             :   }
    1317             : 
    1318             :   // Now that we know if -debug is specified, we can use it.
    1319             :   // Note that if ReadResponseFiles == true, this must be done before the
    1320             :   // memory allocated for the expanded command line is free()d below.
    1321             :   DEBUG(dbgs() << "Args: ";
    1322             :         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
    1323             :         dbgs() << '\n';);
    1324             : 
    1325             :   // Free all of the memory allocated to the map.  Command line options may only
    1326             :   // be processed once!
    1327      195156 :   MoreHelp.clear();
    1328             : 
    1329             :   // If we had an error processing our arguments, don't let the program execute
    1330       97578 :   if (ErrorParsing) {
    1331          12 :     if (!IgnoreErrors)
    1332           6 :       exit(1);
    1333             :     return false;
    1334             :   }
    1335             :   return true;
    1336             : }
    1337             : 
    1338             : //===----------------------------------------------------------------------===//
    1339             : // Option Base class implementation
    1340             : //
    1341             : 
    1342           4 : bool Option::error(const Twine &Message, StringRef ArgName) {
    1343           4 :   if (!ArgName.data())
    1344           4 :     ArgName = ArgStr;
    1345           4 :   if (ArgName.empty())
    1346           0 :     errs() << HelpStr; // Be nice for positional arguments
    1347             :   else
    1348          12 :     errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
    1349             : 
    1350           8 :   errs() << " option: " << Message << "\n";
    1351           4 :   return true;
    1352             : }
    1353             : 
    1354      205211 : bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
    1355             :                            bool MultiArg) {
    1356      205211 :   if (!MultiArg)
    1357      205211 :     NumOccurrences++; // Increment the number of times we have been seen
    1358             : 
    1359      205211 :   switch (getNumOccurrencesFlag()) {
    1360       85162 :   case Optional:
    1361       85162 :     if (NumOccurrences > 1)
    1362           0 :       return error("may only occur zero or one times!", ArgName);
    1363             :     break;
    1364       45354 :   case Required:
    1365       45354 :     if (NumOccurrences > 1)
    1366           0 :       return error("must occur exactly one time!", ArgName);
    1367             :     LLVM_FALLTHROUGH;
    1368             :   case OneOrMore:
    1369             :   case ZeroOrMore:
    1370             :   case ConsumeAfter:
    1371             :     break;
    1372             :   }
    1373             : 
    1374      205211 :   return handleOccurrence(pos, ArgName, Value);
    1375             : }
    1376             : 
    1377             : // getValueStr - Get the value description string, using "DefaultMsg" if nothing
    1378             : // has been specified yet.
    1379             : //
    1380             : static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
    1381        6550 :   if (O.ValueStr.empty())
    1382             :     return DefaultMsg;
    1383         349 :   return O.ValueStr;
    1384             : }
    1385             : 
    1386             : //===----------------------------------------------------------------------===//
    1387             : // cl::alias class implementation
    1388             : //
    1389             : 
    1390             : // Return the width of the option tag for printing...
    1391           2 : size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
    1392             : 
    1393        3543 : void Option::printHelpStr(StringRef HelpStr, size_t Indent,
    1394             :                                  size_t FirstLineIndentedBy) {
    1395        3543 :   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
    1396        3543 :   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
    1397        3723 :   while (!Split.second.empty()) {
    1398         180 :     Split = Split.second.split('\n');
    1399          90 :     outs().indent(Indent) << Split.first << "\n";
    1400             :   }
    1401        3543 : }
    1402             : 
    1403             : // Print out the option for the alias.
    1404           1 : void alias::printOptionInfo(size_t GlobalWidth) const {
    1405           1 :   outs() << "  -" << ArgStr;
    1406           2 :   printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
    1407           1 : }
    1408             : 
    1409             : //===----------------------------------------------------------------------===//
    1410             : // Parser Implementation code...
    1411             : //
    1412             : 
    1413             : // basic_parser implementation
    1414             : //
    1415             : 
    1416             : // Return the width of the option tag for printing...
    1417        6669 : size_t basic_parser_impl::getOptionWidth(const Option &O) const {
    1418       13338 :   size_t Len = O.ArgStr.size();
    1419        6669 :   auto ValName = getValueName();
    1420        6669 :   if (!ValName.empty())
    1421        2191 :     Len += getValueStr(O, ValName).size() + 3;
    1422             : 
    1423        6669 :   return Len + 6;
    1424             : }
    1425             : 
    1426             : // printOptionInfo - Print out information about this option.  The
    1427             : // to-be-maintained width is specified.
    1428             : //
    1429        3323 : void basic_parser_impl::printOptionInfo(const Option &O,
    1430             :                                         size_t GlobalWidth) const {
    1431        3323 :   outs() << "  -" << O.ArgStr;
    1432             : 
    1433        3323 :   auto ValName = getValueName();
    1434        3323 :   if (!ValName.empty())
    1435        2168 :     outs() << "=<" << getValueStr(O, ValName) << '>';
    1436             : 
    1437        3323 :   Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
    1438        3323 : }
    1439             : 
    1440           0 : void basic_parser_impl::printOptionName(const Option &O,
    1441             :                                         size_t GlobalWidth) const {
    1442           0 :   outs() << "  -" << O.ArgStr;
    1443           0 :   outs().indent(GlobalWidth - O.ArgStr.size());
    1444           0 : }
    1445             : 
    1446             : // parser<bool> implementation
    1447             : //
    1448       36744 : bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1449             :                          bool &Value) {
    1450       41225 :   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
    1451        1283 :       Arg == "1") {
    1452       35599 :     Value = true;
    1453       35599 :     return false;
    1454             :   }
    1455             : 
    1456        2246 :   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
    1457        1145 :     Value = false;
    1458        1145 :     return false;
    1459             :   }
    1460           0 :   return O.error("'" + Arg +
    1461           0 :                  "' is invalid value for boolean argument! Try 0 or 1");
    1462             : }
    1463             : 
    1464             : // parser<boolOrDefault> implementation
    1465             : //
    1466         800 : bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1467             :                                   boolOrDefault &Value) {
    1468        1180 :   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
    1469         112 :       Arg == "1") {
    1470         692 :     Value = BOU_TRUE;
    1471         692 :     return false;
    1472             :   }
    1473         246 :   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
    1474         108 :     Value = BOU_FALSE;
    1475         108 :     return false;
    1476             :   }
    1477             : 
    1478           0 :   return O.error("'" + Arg +
    1479           0 :                  "' is invalid value for boolean argument! Try 0 or 1");
    1480             : }
    1481             : 
    1482             : // parser<int> implementation
    1483             : //
    1484         849 : bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1485             :                         int &Value) {
    1486         849 :   if (Arg.getAsInteger(0, Value))
    1487           0 :     return O.error("'" + Arg + "' value invalid for integer argument!");
    1488             :   return false;
    1489             : }
    1490             : 
    1491             : // parser<unsigned> implementation
    1492             : //
    1493         936 : bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1494             :                              unsigned &Value) {
    1495             : 
    1496         936 :   if (Arg.getAsInteger(0, Value))
    1497           0 :     return O.error("'" + Arg + "' value invalid for uint argument!");
    1498             :   return false;
    1499             : }
    1500             : 
    1501             : // parser<unsigned long long> implementation
    1502             : //
    1503           8 : bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
    1504             :                                        StringRef Arg,
    1505             :                                        unsigned long long &Value) {
    1506             : 
    1507           8 :   if (Arg.getAsInteger(0, Value))
    1508           0 :     return O.error("'" + Arg + "' value invalid for uint argument!");
    1509             :   return false;
    1510             : }
    1511             : 
    1512             : // parser<double>/parser<float> implementation
    1513             : //
    1514          19 : static bool parseDouble(Option &O, StringRef Arg, double &Value) {
    1515          38 :   if (to_float(Arg, Value))
    1516             :     return false;
    1517           0 :   return O.error("'" + Arg + "' value invalid for floating point argument!");
    1518             : }
    1519             : 
    1520           2 : bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1521             :                            double &Val) {
    1522           2 :   return parseDouble(O, Arg, Val);
    1523             : }
    1524             : 
    1525          17 : bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
    1526             :                           float &Val) {
    1527             :   double dVal;
    1528          17 :   if (parseDouble(O, Arg, dVal))
    1529             :     return true;
    1530          17 :   Val = (float)dVal;
    1531          17 :   return false;
    1532             : }
    1533             : 
    1534             : // generic_parser_base implementation
    1535             : //
    1536             : 
    1537             : // findOption - Return the option number corresponding to the specified
    1538             : // argument string.  If the option is not found, getNumOptions() is returned.
    1539             : //
    1540    28585287 : unsigned generic_parser_base::findOption(StringRef Name) {
    1541    28585287 :   unsigned e = getNumOptions();
    1542             : 
    1543  3934950313 :   for (unsigned i = 0; i != e; ++i) {
    1544  3907232578 :     if (getOption(i) == Name)
    1545             :       return i;
    1546             :   }
    1547             :   return e;
    1548             : }
    1549             : 
    1550             : // Return the width of the option tag for printing...
    1551         193 : size_t generic_parser_base::getOptionWidth(const Option &O) const {
    1552         193 :   if (O.hasArgStr()) {
    1553         191 :     size_t Size = O.ArgStr.size() + 6;
    1554        1394 :     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
    1555        3609 :       Size = std::max(Size, getOption(i).size() + 8);
    1556         191 :     return Size;
    1557             :   } else {
    1558           2 :     size_t BaseSize = 0;
    1559           7 :     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
    1560          15 :       BaseSize = std::max(BaseSize, getOption(i).size() + 8);
    1561           2 :     return BaseSize;
    1562             :   }
    1563             : }
    1564             : 
    1565             : // printOptionInfo - Print out information about this option.  The
    1566             : // to-be-maintained width is specified.
    1567             : //
    1568         193 : void generic_parser_base::printOptionInfo(const Option &O,
    1569             :                                           size_t GlobalWidth) const {
    1570         193 :   if (O.hasArgStr()) {
    1571         191 :     outs() << "  -" << O.ArgStr;
    1572         382 :     Option::printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
    1573             : 
    1574        1394 :     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
    1575        2406 :       size_t NumSpaces = GlobalWidth - getOption(i).size() - 8;
    1576        1203 :       outs() << "    =" << getOption(i);
    1577        2406 :       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
    1578             :     }
    1579             :   } else {
    1580           4 :     if (!O.HelpStr.empty())
    1581           2 :       outs() << "  " << O.HelpStr << '\n';
    1582           7 :     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
    1583           5 :       auto Option = getOption(i);
    1584           5 :       outs() << "    -" << Option;
    1585           5 :       Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
    1586             :     }
    1587             :   }
    1588         193 : }
    1589             : 
    1590             : static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
    1591             : 
    1592             : // printGenericOptionDiff - Print the value of this option and it's default.
    1593             : //
    1594             : // "Generic" options have each value mapped to a name.
    1595           0 : void generic_parser_base::printGenericOptionDiff(
    1596             :     const Option &O, const GenericOptionValue &Value,
    1597             :     const GenericOptionValue &Default, size_t GlobalWidth) const {
    1598           0 :   outs() << "  -" << O.ArgStr;
    1599           0 :   outs().indent(GlobalWidth - O.ArgStr.size());
    1600             : 
    1601           0 :   unsigned NumOpts = getNumOptions();
    1602           0 :   for (unsigned i = 0; i != NumOpts; ++i) {
    1603           0 :     if (Value.compare(getOptionValue(i)))
    1604             :       continue;
    1605             : 
    1606           0 :     outs() << "= " << getOption(i);
    1607           0 :     size_t L = getOption(i).size();
    1608           0 :     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
    1609           0 :     outs().indent(NumSpaces) << " (default: ";
    1610           0 :     for (unsigned j = 0; j != NumOpts; ++j) {
    1611           0 :       if (Default.compare(getOptionValue(j)))
    1612             :         continue;
    1613           0 :       outs() << getOption(j);
    1614           0 :       break;
    1615             :     }
    1616           0 :     outs() << ")\n";
    1617           0 :     return;
    1618             :   }
    1619           0 :   outs() << "= *unknown option value*\n";
    1620             : }
    1621             : 
    1622             : // printOptionDiff - Specializations for printing basic value types.
    1623             : //
    1624             : #define PRINT_OPT_DIFF(T)                                                      \
    1625             :   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
    1626             :                                   size_t GlobalWidth) const {                  \
    1627             :     printOptionName(O, GlobalWidth);                                           \
    1628             :     std::string Str;                                                           \
    1629             :     {                                                                          \
    1630             :       raw_string_ostream SS(Str);                                              \
    1631             :       SS << V;                                                                 \
    1632             :     }                                                                          \
    1633             :     outs() << "= " << Str;                                                     \
    1634             :     size_t NumSpaces =                                                         \
    1635             :         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
    1636             :     outs().indent(NumSpaces) << " (default: ";                                 \
    1637             :     if (D.hasValue())                                                          \
    1638             :       outs() << D.getValue();                                                  \
    1639             :     else                                                                       \
    1640             :       outs() << "*no default*";                                                \
    1641             :     outs() << ")\n";                                                           \
    1642             :   }
    1643             : 
    1644           0 : PRINT_OPT_DIFF(bool)
    1645           0 : PRINT_OPT_DIFF(boolOrDefault)
    1646           0 : PRINT_OPT_DIFF(int)
    1647           0 : PRINT_OPT_DIFF(unsigned)
    1648           0 : PRINT_OPT_DIFF(unsigned long long)
    1649           0 : PRINT_OPT_DIFF(double)
    1650           0 : PRINT_OPT_DIFF(float)
    1651           0 : PRINT_OPT_DIFF(char)
    1652             : 
    1653           0 : void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
    1654             :                                           const OptionValue<std::string> &D,
    1655             :                                           size_t GlobalWidth) const {
    1656           0 :   printOptionName(O, GlobalWidth);
    1657           0 :   outs() << "= " << V;
    1658           0 :   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
    1659           0 :   outs().indent(NumSpaces) << " (default: ";
    1660           0 :   if (D.hasValue())
    1661           0 :     outs() << D.getValue();
    1662             :   else
    1663           0 :     outs() << "*no default*";
    1664           0 :   outs() << ")\n";
    1665           0 : }
    1666             : 
    1667             : // Print a placeholder for options that don't yet support printOptionDiff().
    1668           0 : void basic_parser_impl::printOptionNoValue(const Option &O,
    1669             :                                            size_t GlobalWidth) const {
    1670           0 :   printOptionName(O, GlobalWidth);
    1671           0 :   outs() << "= *cannot print option value*\n";
    1672           0 : }
    1673             : 
    1674             : //===----------------------------------------------------------------------===//
    1675             : // -help and -help-hidden option implementation
    1676             : //
    1677             : 
    1678       22788 : static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
    1679             :                           const std::pair<const char *, Option *> *RHS) {
    1680       22788 :   return strcmp(LHS->first, RHS->first);
    1681             : }
    1682             : 
    1683           9 : static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
    1684             :                           const std::pair<const char *, SubCommand *> *RHS) {
    1685           9 :   return strcmp(LHS->first, RHS->first);
    1686             : }
    1687             : 
    1688             : // Copy Options into a vector so we can sort them as we like.
    1689          27 : static void sortOpts(StringMap<Option *> &OptMap,
    1690             :                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
    1691             :                      bool ShowHidden) {
    1692          54 :   SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
    1693             : 
    1694          81 :   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
    1695       28707 :        I != E; ++I) {
    1696             :     // Ignore really-hidden options.
    1697       57360 :     if (I->second->getOptionHiddenFlag() == ReallyHidden)
    1698        4629 :       continue;
    1699             : 
    1700             :     // Unless showhidden is set, ignore hidden flags.
    1701       24051 :     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
    1702       20508 :       continue;
    1703             : 
    1704             :     // If we've already seen this option, don't add it to the list again.
    1705        3543 :     if (!OptionSet.insert(I->second).second)
    1706           3 :       continue;
    1707             : 
    1708        7080 :     Opts.push_back(
    1709       17700 :         std::pair<const char *, Option *>(I->getKey().data(), I->second));
    1710             :   }
    1711             : 
    1712             :   // Sort the options list alphabetically.
    1713         108 :   array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
    1714          27 : }
    1715             : 
    1716             : static void
    1717          27 : sortSubCommands(const SmallPtrSetImpl<SubCommand *> &SubMap,
    1718             :                 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
    1719          87 :   for (const auto &S : SubMap) {
    1720          60 :     if (S->getName().empty())
    1721          54 :       continue;
    1722          12 :     Subs.push_back(std::make_pair(S->getName().data(), S));
    1723             :   }
    1724         108 :   array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
    1725          27 : }
    1726             : 
    1727             : namespace {
    1728             : 
    1729             : class HelpPrinter {
    1730             : protected:
    1731             :   const bool ShowHidden;
    1732             :   typedef SmallVector<std::pair<const char *, Option *>, 128>
    1733             :       StrOptionPairVector;
    1734             :   typedef SmallVector<std::pair<const char *, SubCommand *>, 128>
    1735             :       StrSubCommandPairVector;
    1736             :   // Print the options. Opts is assumed to be alphabetically sorted.
    1737          19 :   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
    1738        2058 :     for (size_t i = 0, e = Opts.size(); i != e; ++i)
    1739        4040 :       Opts[i].second->printOptionInfo(MaxArgLen);
    1740          19 :   }
    1741             : 
    1742           1 :   void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
    1743           9 :     for (const auto &S : Subs) {
    1744           6 :       outs() << "  " << S.first;
    1745           6 :       if (!S.second->getDescription().empty()) {
    1746           6 :         outs().indent(MaxSubLen - strlen(S.first));
    1747           6 :         outs() << " - " << S.second->getDescription();
    1748             :       }
    1749           6 :       outs() << "\n";
    1750             :     }
    1751           1 :   }
    1752             : 
    1753             : public:
    1754      485420 :   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
    1755      242710 :   virtual ~HelpPrinter() {}
    1756             : 
    1757             :   // Invoke the printer.
    1758             :   void operator=(bool Value) {
    1759           0 :     if (!Value)
    1760             :       return;
    1761           5 :     printHelp();
    1762             : 
    1763             :     // Halt the program since help information was printed
    1764           5 :     exit(0);
    1765             :   }
    1766             : 
    1767          27 :   void printHelp() {
    1768          27 :     SubCommand *Sub = GlobalParser->getActiveSubCommand();
    1769          27 :     auto &OptionsMap = Sub->OptionsMap;
    1770          27 :     auto &PositionalOpts = Sub->PositionalOpts;
    1771          27 :     auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
    1772             : 
    1773          54 :     StrOptionPairVector Opts;
    1774          27 :     sortOpts(OptionsMap, Opts, ShowHidden);
    1775             : 
    1776          54 :     StrSubCommandPairVector Subs;
    1777          27 :     sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
    1778             : 
    1779          54 :     if (!GlobalParser->ProgramOverview.empty())
    1780          52 :       outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
    1781             : 
    1782          27 :     if (Sub == &*TopLevelSubCommand) {
    1783          81 :       outs() << "USAGE: " << GlobalParser->ProgramName;
    1784          27 :       if (Subs.size() > 2)
    1785           1 :         outs() << " [subcommand]";
    1786          27 :       outs() << " [options]";
    1787             :     } else {
    1788           0 :       if (!Sub->getDescription().empty()) {
    1789           0 :         outs() << "SUBCOMMAND '" << Sub->getName()
    1790           0 :                << "': " << Sub->getDescription() << "\n\n";
    1791             :       }
    1792           0 :       outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
    1793           0 :              << " [options]";
    1794             :     }
    1795             : 
    1796         106 :     for (auto Opt : PositionalOpts) {
    1797          25 :       if (Opt->hasArgStr())
    1798           0 :         outs() << " --" << Opt->ArgStr;
    1799          25 :       outs() << " " << Opt->HelpStr;
    1800             :     }
    1801             : 
    1802             :     // Print the consume after option info if it exists...
    1803          27 :     if (ConsumeAfterOpt)
    1804           1 :       outs() << " " << ConsumeAfterOpt->HelpStr;
    1805             : 
    1806          27 :     if (Sub == &*TopLevelSubCommand && !Subs.empty()) {
    1807             :       // Compute the maximum subcommand length...
    1808           1 :       size_t MaxSubLen = 0;
    1809           8 :       for (size_t i = 0, e = Subs.size(); i != e; ++i)
    1810          12 :         MaxSubLen = std::max(MaxSubLen, strlen(Subs[i].first));
    1811             : 
    1812           1 :       outs() << "\n\n";
    1813           1 :       outs() << "SUBCOMMANDS:\n\n";
    1814           1 :       printSubCommands(Subs, MaxSubLen);
    1815           1 :       outs() << "\n";
    1816           3 :       outs() << "  Type \"" << GlobalParser->ProgramName
    1817           1 :              << " <subcommand> -help\" to get more help on a specific "
    1818             :                 "subcommand";
    1819             :     }
    1820             : 
    1821          27 :     outs() << "\n\n";
    1822             : 
    1823             :     // Compute the maximum argument length...
    1824          27 :     size_t MaxArgLen = 0;
    1825        3594 :     for (size_t i = 0, e = Opts.size(); i != e; ++i)
    1826        7080 :       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
    1827             : 
    1828          27 :     outs() << "OPTIONS:\n";
    1829          27 :     printOptions(Opts, MaxArgLen);
    1830             : 
    1831             :     // Print any extra help the user has declared.
    1832         108 :     for (auto I : GlobalParser->MoreHelp)
    1833           0 :       outs() << I;
    1834          54 :     GlobalParser->MoreHelp.clear();
    1835          27 :   }
    1836             : };
    1837             : 
    1838      242710 : class CategorizedHelpPrinter : public HelpPrinter {
    1839             : public:
    1840      485420 :   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
    1841             : 
    1842             :   // Helper function for printOptions().
    1843             :   // It shall return a negative value if A's name should be lexicographically
    1844             :   // ordered before B's name. It returns a value greater than zero if B's name
    1845             :   // should be ordered before A's name, and it returns 0 otherwise.
    1846          16 :   static int OptionCategoryCompare(OptionCategory *const *A,
    1847             :                                    OptionCategory *const *B) {
    1848          32 :     return (*A)->getName().compare((*B)->getName());
    1849             :   }
    1850             : 
    1851             :   // Make sure we inherit our base class's operator=()
    1852             :   using HelpPrinter::operator=;
    1853             : 
    1854             : protected:
    1855           8 :   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
    1856          16 :     std::vector<OptionCategory *> SortedCategories;
    1857          16 :     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
    1858             : 
    1859             :     // Collect registered option categories into vector in preparation for
    1860             :     // sorting.
    1861           8 :     for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
    1862           8 :               E = GlobalParser->RegisteredOptionCategories.end();
    1863          30 :          I != E; ++I) {
    1864          66 :       SortedCategories.push_back(*I);
    1865             :     }
    1866             : 
    1867             :     // Sort the different option categories alphabetically.
    1868             :     assert(SortedCategories.size() > 0 && "No option categories registered!");
    1869          24 :     array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
    1870             :                    OptionCategoryCompare);
    1871             : 
    1872             :     // Create map to empty vectors.
    1873             :     for (std::vector<OptionCategory *>::const_iterator
    1874          16 :              I = SortedCategories.begin(),
    1875          16 :              E = SortedCategories.end();
    1876          30 :          I != E; ++I)
    1877          66 :       CategorizedOptions[*I] = std::vector<Option *>();
    1878             : 
    1879             :     // Walk through pre-sorted options and assign into categories.
    1880             :     // Because the options are already alphabetically sorted the
    1881             :     // options within categories will also be alphabetically sorted.
    1882        1536 :     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
    1883        3040 :       Option *Opt = Opts[I].second;
    1884             :       assert(CategorizedOptions.count(Opt->Category) > 0 &&
    1885             :              "Option has an unregistered category");
    1886        1520 :       CategorizedOptions[Opt->Category].push_back(Opt);
    1887             :     }
    1888             : 
    1889             :     // Now do printing.
    1890             :     for (std::vector<OptionCategory *>::const_iterator
    1891          16 :              Category = SortedCategories.begin(),
    1892          16 :              E = SortedCategories.end();
    1893          30 :          Category != E; ++Category) {
    1894             :       // Hide empty categories for -help, but show for -help-hidden.
    1895          22 :       const auto &CategoryOptions = CategorizedOptions[*Category];
    1896          22 :       bool IsEmptyCategory = CategoryOptions.empty();
    1897          22 :       if (!ShowHidden && IsEmptyCategory)
    1898           4 :         continue;
    1899             : 
    1900             :       // Print category information.
    1901          18 :       outs() << "\n";
    1902          18 :       outs() << (*Category)->getName() << ":\n";
    1903             : 
    1904             :       // Check if description is set.
    1905          18 :       if (!(*Category)->getDescription().empty())
    1906           2 :         outs() << (*Category)->getDescription() << "\n\n";
    1907             :       else
    1908          16 :         outs() << "\n";
    1909             : 
    1910             :       // When using -help-hidden explicitly state if the category has no
    1911             :       // options associated with it.
    1912          18 :       if (IsEmptyCategory) {
    1913           0 :         outs() << "  This option category has no options.\n";
    1914           0 :         continue;
    1915             :       }
    1916             :       // Loop over the options in the category and print.
    1917        1592 :       for (const Option *Opt : CategoryOptions)
    1918        1520 :         Opt->printOptionInfo(MaxArgLen);
    1919             :     }
    1920           8 :   }
    1921             : };
    1922             : 
    1923             : // This wraps the Uncategorizing and Categorizing printers and decides
    1924             : // at run time which should be invoked.
    1925             : class HelpPrinterWrapper {
    1926             : private:
    1927             :   HelpPrinter &UncategorizedPrinter;
    1928             :   CategorizedHelpPrinter &CategorizedPrinter;
    1929             : 
    1930             : public:
    1931             :   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
    1932             :                               CategorizedHelpPrinter &CategorizedPrinter)
    1933      242710 :       : UncategorizedPrinter(UncategorizedPrinter),
    1934      242710 :         CategorizedPrinter(CategorizedPrinter) {}
    1935             : 
    1936             :   // Invoke the printer.
    1937             :   void operator=(bool Value);
    1938             : };
    1939             : 
    1940             : } // End anonymous namespace
    1941             : 
    1942             : // Declare the four HelpPrinter instances that are used to print out help, or
    1943             : // help-hidden as an uncategorized list or in categories.
    1944      121355 : static HelpPrinter UncategorizedNormalPrinter(false);
    1945      121355 : static HelpPrinter UncategorizedHiddenPrinter(true);
    1946      121355 : static CategorizedHelpPrinter CategorizedNormalPrinter(false);
    1947      121355 : static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
    1948             : 
    1949             : // Declare HelpPrinter wrappers that will decide whether or not to invoke
    1950             : // a categorizing help printer
    1951             : static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
    1952      121355 :                                                CategorizedNormalPrinter);
    1953             : static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
    1954      121355 :                                                CategorizedHiddenPrinter);
    1955             : 
    1956             : // Define a category for generic options that all tools should have.
    1957      242710 : static cl::OptionCategory GenericCategory("Generic Options");
    1958             : 
    1959             : // Define uncategorized help printers.
    1960             : // -help-list is hidden by default because if Option categories are being used
    1961             : // then -help behaves the same as -help-list.
    1962      121345 : static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
    1963             :     "help-list",
    1964      364055 :     cl::desc("Display list of available options (-help-list-hidden for more)"),
    1965      242700 :     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
    1966      606765 :     cl::cat(GenericCategory), cl::sub(*AllSubCommands));
    1967             : 
    1968             : static cl::opt<HelpPrinter, true, parser<bool>>
    1969      485380 :     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
    1970      242690 :           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
    1971      242690 :           cl::ValueDisallowed, cl::cat(GenericCategory),
    1972      728070 :           cl::sub(*AllSubCommands));
    1973             : 
    1974             : // Define uncategorized/categorized help printers. These printers change their
    1975             : // behaviour at runtime depending on whether one or more Option categories have
    1976             : // been declared.
    1977             : static cl::opt<HelpPrinterWrapper, true, parser<bool>>
    1978      485380 :     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
    1979      242690 :         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
    1980      606725 :         cl::cat(GenericCategory), cl::sub(*AllSubCommands));
    1981             : 
    1982             : static cl::opt<HelpPrinterWrapper, true, parser<bool>>
    1983      485380 :     HHOp("help-hidden", cl::desc("Display all available options"),
    1984      242690 :          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
    1985      606725 :          cl::cat(GenericCategory), cl::sub(*AllSubCommands));
    1986             : 
    1987      121345 : static cl::opt<bool> PrintOptions(
    1988             :     "print-options",
    1989      364035 :     cl::desc("Print non-default options after command line parsing"),
    1990      364035 :     cl::Hidden, cl::init(false), cl::cat(GenericCategory),
    1991      728070 :     cl::sub(*AllSubCommands));
    1992             : 
    1993      121345 : static cl::opt<bool> PrintAllOptions(
    1994             :     "print-all-options",
    1995      364035 :     cl::desc("Print all option values after command line parsing"), cl::Hidden,
    1996      728070 :     cl::init(false), cl::cat(GenericCategory), cl::sub(*AllSubCommands));
    1997             : 
    1998           5 : void HelpPrinterWrapper::operator=(bool Value) {
    1999           5 :   if (!Value)
    2000             :     return;
    2001             : 
    2002             :   // Decide which printer to invoke. If more than one option category is
    2003             :   // registered then it is useful to show the categorized help instead of
    2004             :   // uncategorized help.
    2005          10 :   if (GlobalParser->RegisteredOptionCategories.size() > 1) {
    2006             :     // unhide -help-list option so user can have uncategorized output if they
    2007             :     // want it.
    2008           5 :     HLOp.setHiddenFlag(NotHidden);
    2009             : 
    2010           5 :     CategorizedPrinter = true; // Invoke categorized printer
    2011             :   } else
    2012           0 :     UncategorizedPrinter = true; // Invoke uncategorized printer
    2013             : }
    2014             : 
    2015             : // Print the value of each option.
    2016       62748 : void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
    2017             : 
    2018       31374 : void CommandLineParser::printOptionValues() {
    2019       62748 :   if (!PrintOptions && !PrintAllOptions)
    2020       31374 :     return;
    2021             : 
    2022           0 :   SmallVector<std::pair<const char *, Option *>, 128> Opts;
    2023           0 :   sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
    2024             : 
    2025             :   // Compute the maximum argument length...
    2026           0 :   size_t MaxArgLen = 0;
    2027           0 :   for (size_t i = 0, e = Opts.size(); i != e; ++i)
    2028           0 :     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
    2029             : 
    2030           0 :   for (size_t i = 0, e = Opts.size(); i != e; ++i)
    2031           0 :     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
    2032             : }
    2033             : 
    2034      121345 : static VersionPrinterTy OverrideVersionPrinter = nullptr;
    2035             : 
    2036             : static std::vector<VersionPrinterTy> *ExtraVersionPrinters = nullptr;
    2037             : 
    2038             : namespace {
    2039             : class VersionPrinter {
    2040             : public:
    2041           4 :   void print() {
    2042           4 :     raw_ostream &OS = outs();
    2043             : #ifdef PACKAGE_VENDOR
    2044             :     OS << PACKAGE_VENDOR << " ";
    2045             : #else
    2046           4 :     OS << "LLVM (http://llvm.org/):\n  ";
    2047             : #endif
    2048           4 :     OS << PACKAGE_NAME << " version " << PACKAGE_VERSION;
    2049             : #ifdef LLVM_VERSION_INFO
    2050             :     OS << " " << LLVM_VERSION_INFO;
    2051             : #endif
    2052           4 :     OS << "\n  ";
    2053             : #ifdef LLVM_DEBIAN_INFO
    2054             :     OS << LLVM_DEBIAN_INFO;
    2055             : #endif
    2056           4 :     OS << "\n  ";
    2057             : #ifndef __OPTIMIZE__
    2058             :     OS << "DEBUG build";
    2059             : #else
    2060           4 :     OS << "Optimized build";
    2061             : #endif
    2062             : #ifndef NDEBUG
    2063             :     OS << " with assertions";
    2064             : #endif
    2065             : #if LLVM_VERSION_PRINTER_SHOW_HOST_TARGET_INFO
    2066          12 :     std::string CPU = sys::getHostCPUName();
    2067           4 :     if (CPU == "generic")
    2068             :       CPU = "(unknown)";
    2069           4 :     OS << ".\n"
    2070          16 :        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
    2071           8 :        << "  Host CPU: " << CPU;
    2072             : #endif
    2073           4 :     OS << '\n';
    2074           4 :   }
    2075           3 :   void operator=(bool OptionWasSpecified) {
    2076           3 :     if (!OptionWasSpecified)
    2077           0 :       return;
    2078             : 
    2079           6 :     if (OverrideVersionPrinter != nullptr) {
    2080           0 :       OverrideVersionPrinter(outs());
    2081           0 :       exit(0);
    2082             :     }
    2083           3 :     print();
    2084             : 
    2085             :     // Iterate over any registered extra printers and call them to add further
    2086             :     // information.
    2087           3 :     if (ExtraVersionPrinters != nullptr) {
    2088           0 :       outs() << '\n';
    2089           0 :       for (auto I : *ExtraVersionPrinters)
    2090           0 :         I(outs());
    2091             :     }
    2092             : 
    2093           3 :     exit(0);
    2094             :   }
    2095             : };
    2096             : } // End anonymous namespace
    2097             : 
    2098             : // Define the --version option that prints out the LLVM version for the tool
    2099             : static VersionPrinter VersionPrinterInstance;
    2100             : 
    2101             : static cl::opt<VersionPrinter, true, parser<bool>>
    2102      485380 :     VersOp("version", cl::desc("Display the version of this program"),
    2103      242690 :            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
    2104      364035 :            cl::cat(GenericCategory));
    2105             : 
    2106             : // Utility function for printing the help message.
    2107          22 : void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
    2108          22 :   if (!Hidden && !Categorized)
    2109          19 :     UncategorizedNormalPrinter.printHelp();
    2110           3 :   else if (!Hidden && Categorized)
    2111           3 :     CategorizedNormalPrinter.printHelp();
    2112           0 :   else if (Hidden && !Categorized)
    2113           0 :     UncategorizedHiddenPrinter.printHelp();
    2114             :   else
    2115           0 :     CategorizedHiddenPrinter.printHelp();
    2116          22 : }
    2117             : 
    2118             : /// Utility function for printing version number.
    2119           1 : void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
    2120             : 
    2121         282 : void cl::SetVersionPrinter(VersionPrinterTy func) { OverrideVersionPrinter = func; }
    2122             : 
    2123       24898 : void cl::AddExtraVersionPrinter(VersionPrinterTy func) {
    2124       24898 :   if (!ExtraVersionPrinters)
    2125       49796 :     ExtraVersionPrinters = new std::vector<VersionPrinterTy>;
    2126             : 
    2127       24898 :   ExtraVersionPrinters->push_back(func);
    2128       24898 : }
    2129             : 
    2130           4 : StringMap<Option *> &cl::getRegisteredOptions(SubCommand &Sub) {
    2131           4 :   auto &Subs = GlobalParser->RegisteredSubCommands;
    2132             :   (void)Subs;
    2133             :   assert(is_contained(Subs, &Sub));
    2134           4 :   return Sub.OptionsMap;
    2135             : }
    2136             : 
    2137             : iterator_range<typename SmallPtrSet<SubCommand *, 4>::iterator>
    2138          66 : cl::getRegisteredSubcommands() {
    2139          66 :   return GlobalParser->getRegisteredSubcommands();
    2140             : }
    2141             : 
    2142         872 : void cl::HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub) {
    2143     1867638 :   for (auto &I : Sub.OptionsMap) {
    2144      932075 :     if (I.second->Category != &Category &&
    2145             :         I.second->Category != &GenericCategory)
    2146      914097 :       I.second->setHiddenFlag(cl::ReallyHidden);
    2147             :   }
    2148         872 : }
    2149             : 
    2150         492 : void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories,
    2151             :                               SubCommand &Sub) {
    2152         492 :   auto CategoriesBegin = Categories.begin();
    2153         492 :   auto CategoriesEnd = Categories.end();
    2154     1075870 :   for (auto &I : Sub.OptionsMap) {
    2155     1073902 :     if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
    2156     1056480 :             CategoriesEnd &&
    2157      519529 :         I.second->Category != &GenericCategory)
    2158      516085 :       I.second->setHiddenFlag(cl::ReallyHidden);
    2159             :   }
    2160         492 : }
    2161             : 
    2162          18 : void cl::ResetCommandLineParser() { GlobalParser->reset(); }
    2163          14 : void cl::ResetAllOptionOccurrences() {
    2164          14 :   GlobalParser->ResetAllOptionOccurrences();
    2165          14 : }
    2166             : 
    2167           0 : void LLVMParseCommandLineOptions(int argc, const char *const *argv,
    2168             :                                  const char *Overview) {
    2169           0 :   llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
    2170           0 :                                     &llvm::nulls());
    2171      364055 : }

Generated by: LCOV version 1.13