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