CommandLine.cpp revision a962b40f0bcaee07296836e175112602c58e439f
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/Support/Debug.h" 21#include "llvm/Support/ErrorHandling.h" 22#include "llvm/Support/MemoryBuffer.h" 23#include "llvm/Support/ManagedStatic.h" 24#include "llvm/Support/raw_ostream.h" 25#include "llvm/Target/TargetRegistry.h" 26#include "llvm/System/Host.h" 27#include "llvm/System/Path.h" 28#include "llvm/ADT/OwningPtr.h" 29#include "llvm/ADT/SmallPtrSet.h" 30#include "llvm/ADT/SmallString.h" 31#include "llvm/ADT/StringMap.h" 32#include "llvm/ADT/Twine.h" 33#include "llvm/Config/config.h" 34#include <cerrno> 35#include <cstdlib> 36using namespace llvm; 37using namespace cl; 38 39//===----------------------------------------------------------------------===// 40// Template instantiations and anchors. 41// 42namespace llvm { namespace cl { 43TEMPLATE_INSTANTIATION(class basic_parser<bool>); 44TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>); 45TEMPLATE_INSTANTIATION(class basic_parser<int>); 46TEMPLATE_INSTANTIATION(class basic_parser<unsigned>); 47TEMPLATE_INSTANTIATION(class basic_parser<double>); 48TEMPLATE_INSTANTIATION(class basic_parser<float>); 49TEMPLATE_INSTANTIATION(class basic_parser<std::string>); 50TEMPLATE_INSTANTIATION(class basic_parser<char>); 51 52TEMPLATE_INSTANTIATION(class opt<unsigned>); 53TEMPLATE_INSTANTIATION(class opt<int>); 54TEMPLATE_INSTANTIATION(class opt<std::string>); 55TEMPLATE_INSTANTIATION(class opt<char>); 56TEMPLATE_INSTANTIATION(class opt<bool>); 57} } // end namespace llvm::cl 58 59void Option::anchor() {} 60void basic_parser_impl::anchor() {} 61void parser<bool>::anchor() {} 62void parser<boolOrDefault>::anchor() {} 63void parser<int>::anchor() {} 64void parser<unsigned>::anchor() {} 65void parser<double>::anchor() {} 66void parser<float>::anchor() {} 67void parser<std::string>::anchor() {} 68void parser<char>::anchor() {} 69 70//===----------------------------------------------------------------------===// 71 72// Globals for name and overview of program. Program name is not a string to 73// avoid static ctor/dtor issues. 74static char ProgramName[80] = "<premain>"; 75static const char *ProgramOverview = 0; 76 77// This collects additional help to be printed. 78static ManagedStatic<std::vector<const char*> > MoreHelp; 79 80extrahelp::extrahelp(const char *Help) 81 : morehelp(Help) { 82 MoreHelp->push_back(Help); 83} 84 85static bool OptionListChanged = false; 86 87// MarkOptionsChanged - Internal helper function. 88void cl::MarkOptionsChanged() { 89 OptionListChanged = true; 90} 91 92/// RegisteredOptionList - This is the list of the command line options that 93/// have statically constructed themselves. 94static Option *RegisteredOptionList = 0; 95 96void Option::addArgument() { 97 assert(NextRegistered == 0 && "argument multiply registered!"); 98 99 NextRegistered = RegisteredOptionList; 100 RegisteredOptionList = this; 101 MarkOptionsChanged(); 102} 103 104 105//===----------------------------------------------------------------------===// 106// Basic, shared command line option processing machinery. 107// 108 109/// GetOptionInfo - Scan the list of registered options, turning them into data 110/// structures that are easier to handle. 111static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts, 112 SmallVectorImpl<Option*> &SinkOpts, 113 StringMap<Option*> &OptionsMap) { 114 SmallVector<const char*, 16> OptionNames; 115 Option *CAOpt = 0; // The ConsumeAfter option if it exists. 116 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) { 117 // If this option wants to handle multiple option names, get the full set. 118 // This handles enum options like "-O1 -O2" etc. 119 O->getExtraOptionNames(OptionNames); 120 if (O->ArgStr[0]) 121 OptionNames.push_back(O->ArgStr); 122 123 // Handle named options. 124 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) { 125 // Add argument to the argument map! 126 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) { 127 errs() << ProgramName << ": CommandLine Error: Argument '" 128 << OptionNames[i] << "' defined more than once!\n"; 129 } 130 } 131 132 OptionNames.clear(); 133 134 // Remember information about positional options. 135 if (O->getFormattingFlag() == cl::Positional) 136 PositionalOpts.push_back(O); 137 else if (O->getMiscFlags() & cl::Sink) // Remember sink options 138 SinkOpts.push_back(O); 139 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) { 140 if (CAOpt) 141 O->error("Cannot specify more than one option with cl::ConsumeAfter!"); 142 CAOpt = O; 143 } 144 } 145 146 if (CAOpt) 147 PositionalOpts.push_back(CAOpt); 148 149 // Make sure that they are in order of registration not backwards. 150 std::reverse(PositionalOpts.begin(), PositionalOpts.end()); 151} 152 153 154/// LookupOption - Lookup the option specified by the specified option on the 155/// command line. If there is a value specified (after an equal sign) return 156/// that as well. This assumes that leading dashes have already been stripped. 157static Option *LookupOption(StringRef &Arg, StringRef &Value, 158 const StringMap<Option*> &OptionsMap) { 159 // Reject all dashes. 160 if (Arg.empty()) return 0; 161 162 size_t EqualPos = Arg.find('='); 163 164 // If we have an equals sign, remember the value. 165 if (EqualPos == StringRef::npos) { 166 // Look up the option. 167 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg); 168 return I != OptionsMap.end() ? I->second : 0; 169 } 170 171 // If the argument before the = is a valid option name, we match. If not, 172 // return Arg unmolested. 173 StringMap<Option*>::const_iterator I = 174 OptionsMap.find(Arg.substr(0, EqualPos)); 175 if (I == OptionsMap.end()) return 0; 176 177 Value = Arg.substr(EqualPos+1); 178 Arg = Arg.substr(0, EqualPos); 179 return I->second; 180} 181 182/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that 183/// does special handling of cl::CommaSeparated options. 184static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos, 185 StringRef ArgName, 186 StringRef Value, bool MultiArg = false) 187{ 188 // Check to see if this option accepts a comma separated list of values. If 189 // it does, we have to split up the value into multiple values. 190 if (Handler->getMiscFlags() & CommaSeparated) { 191 StringRef Val(Value); 192 StringRef::size_type Pos = Val.find(','); 193 194 while (Pos != StringRef::npos) { 195 // Process the portion before the comma. 196 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg)) 197 return true; 198 // Erase the portion before the comma, AND the comma. 199 Val = Val.substr(Pos+1); 200 Value.substr(Pos+1); // Increment the original value pointer as well. 201 // Check for another comma. 202 Pos = Val.find(','); 203 } 204 205 Value = Val; 206 } 207 208 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg)) 209 return true; 210 211 return false; 212} 213 214/// ProvideOption - For Value, this differentiates between an empty value ("") 215/// and a null value (StringRef()). The later is accepted for arguments that 216/// don't allow a value (-foo) the former is rejected (-foo=). 217static inline bool ProvideOption(Option *Handler, StringRef ArgName, 218 StringRef Value, int argc, char **argv, 219 int &i) { 220 // Is this a multi-argument option? 221 unsigned NumAdditionalVals = Handler->getNumAdditionalVals(); 222 223 // Enforce value requirements 224 switch (Handler->getValueExpectedFlag()) { 225 case ValueRequired: 226 if (Value.data() == 0) { // No value specified? 227 if (i+1 >= argc) 228 return Handler->error("requires a value!"); 229 // Steal the next argument, like for '-o filename' 230 Value = argv[++i]; 231 } 232 break; 233 case ValueDisallowed: 234 if (NumAdditionalVals > 0) 235 return Handler->error("multi-valued option specified" 236 " with ValueDisallowed modifier!"); 237 238 if (Value.data()) 239 return Handler->error("does not allow a value! '" + 240 Twine(Value) + "' specified."); 241 break; 242 case ValueOptional: 243 break; 244 245 default: 246 errs() << ProgramName 247 << ": Bad ValueMask flag! CommandLine usage error:" 248 << Handler->getValueExpectedFlag() << "\n"; 249 llvm_unreachable(0); 250 } 251 252 // If this isn't a multi-arg option, just run the handler. 253 if (NumAdditionalVals == 0) 254 return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value); 255 256 // If it is, run the handle several times. 257 bool MultiArg = false; 258 259 if (Value.data()) { 260 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 261 return true; 262 --NumAdditionalVals; 263 MultiArg = true; 264 } 265 266 while (NumAdditionalVals > 0) { 267 if (i+1 >= argc) 268 return Handler->error("not enough values!"); 269 Value = argv[++i]; 270 271 if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg)) 272 return true; 273 MultiArg = true; 274 --NumAdditionalVals; 275 } 276 return false; 277} 278 279static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) { 280 int Dummy = i; 281 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy); 282} 283 284 285// Option predicates... 286static inline bool isGrouping(const Option *O) { 287 return O->getFormattingFlag() == cl::Grouping; 288} 289static inline bool isPrefixedOrGrouping(const Option *O) { 290 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix; 291} 292 293// getOptionPred - Check to see if there are any options that satisfy the 294// specified predicate with names that are the prefixes in Name. This is 295// checked by progressively stripping characters off of the name, checking to 296// see if there options that satisfy the predicate. If we find one, return it, 297// otherwise return null. 298// 299static Option *getOptionPred(StringRef Name, size_t &Length, 300 bool (*Pred)(const Option*), 301 const StringMap<Option*> &OptionsMap) { 302 303 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name); 304 305 // Loop while we haven't found an option and Name still has at least two 306 // characters in it (so that the next iteration will not be the empty 307 // string. 308 while (OMI == OptionsMap.end() && Name.size() > 1) { 309 Name = Name.substr(0, Name.size()-1); // Chop off the last character. 310 OMI = OptionsMap.find(Name); 311 } 312 313 if (OMI != OptionsMap.end() && Pred(OMI->second)) { 314 Length = Name.size(); 315 return OMI->second; // Found one! 316 } 317 return 0; // No option found! 318} 319 320/// HandlePrefixedOrGroupedOption - The specified argument string (which started 321/// with at least one '-') does not fully match an available option. Check to 322/// see if this is a prefix or grouped option. If so, split arg into output an 323/// Arg/Value pair and return the Option to parse it with. 324static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, 325 bool &ErrorParsing, 326 const StringMap<Option*> &OptionsMap) { 327 if (Arg.size() == 1) return 0; 328 329 // Do the lookup! 330 size_t Length = 0; 331 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap); 332 if (PGOpt == 0) return 0; 333 334 // If the option is a prefixed option, then the value is simply the 335 // rest of the name... so fall through to later processing, by 336 // setting up the argument name flags and value fields. 337 if (PGOpt->getFormattingFlag() == cl::Prefix) { 338 Value = Arg.substr(Length); 339 Arg = Arg.substr(0, Length); 340 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt); 341 return PGOpt; 342 } 343 344 // This must be a grouped option... handle them now. Grouping options can't 345 // have values. 346 assert(isGrouping(PGOpt) && "Broken getOptionPred!"); 347 348 do { 349 // Move current arg name out of Arg into OneArgName. 350 StringRef OneArgName = Arg.substr(0, Length); 351 Arg = Arg.substr(Length); 352 353 // Because ValueRequired is an invalid flag for grouped arguments, 354 // we don't need to pass argc/argv in. 355 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired && 356 "Option can not be cl::Grouping AND cl::ValueRequired!"); 357 int Dummy = 0; 358 ErrorParsing |= ProvideOption(PGOpt, OneArgName, 359 StringRef(), 0, 0, Dummy); 360 361 // Get the next grouping option. 362 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap); 363 } while (PGOpt && Length != Arg.size()); 364 365 // Return the last option with Arg cut down to just the last one. 366 return PGOpt; 367} 368 369 370 371static bool RequiresValue(const Option *O) { 372 return O->getNumOccurrencesFlag() == cl::Required || 373 O->getNumOccurrencesFlag() == cl::OneOrMore; 374} 375 376static bool EatsUnboundedNumberOfValues(const Option *O) { 377 return O->getNumOccurrencesFlag() == cl::ZeroOrMore || 378 O->getNumOccurrencesFlag() == cl::OneOrMore; 379} 380 381/// ParseCStringVector - Break INPUT up wherever one or more 382/// whitespace characters are found, and store the resulting tokens in 383/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated 384/// using strdup(), so it is the caller's responsibility to free() 385/// them later. 386/// 387static void ParseCStringVector(std::vector<char *> &OutputVector, 388 const char *Input) { 389 // Characters which will be treated as token separators: 390 StringRef Delims = " \v\f\t\r\n"; 391 392 StringRef WorkStr(Input); 393 while (!WorkStr.empty()) { 394 // If the first character is a delimiter, strip them off. 395 if (Delims.find(WorkStr[0]) != StringRef::npos) { 396 size_t Pos = WorkStr.find_first_not_of(Delims); 397 if (Pos == StringRef::npos) Pos = WorkStr.size(); 398 WorkStr = WorkStr.substr(Pos); 399 continue; 400 } 401 402 // Find position of first delimiter. 403 size_t Pos = WorkStr.find_first_of(Delims); 404 if (Pos == StringRef::npos) Pos = WorkStr.size(); 405 406 // Everything from 0 to Pos is the next word to copy. 407 char *NewStr = (char*)malloc(Pos+1); 408 memcpy(NewStr, WorkStr.data(), Pos); 409 NewStr[Pos] = 0; 410 OutputVector.push_back(NewStr); 411 412 WorkStr = WorkStr.substr(Pos); 413 } 414} 415 416/// ParseEnvironmentOptions - An alternative entry point to the 417/// CommandLine library, which allows you to read the program's name 418/// from the caller (as PROGNAME) and its command-line arguments from 419/// an environment variable (whose name is given in ENVVAR). 420/// 421void cl::ParseEnvironmentOptions(const char *progName, const char *envVar, 422 const char *Overview, bool ReadResponseFiles) { 423 // Check args. 424 assert(progName && "Program name not specified"); 425 assert(envVar && "Environment variable name missing"); 426 427 // Get the environment variable they want us to parse options out of. 428 const char *envValue = getenv(envVar); 429 if (!envValue) 430 return; 431 432 // Get program's "name", which we wouldn't know without the caller 433 // telling us. 434 std::vector<char*> newArgv; 435 newArgv.push_back(strdup(progName)); 436 437 // Parse the value of the environment variable into a "command line" 438 // and hand it off to ParseCommandLineOptions(). 439 ParseCStringVector(newArgv, envValue); 440 int newArgc = static_cast<int>(newArgv.size()); 441 ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles); 442 443 // Free all the strdup()ed strings. 444 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 445 i != e; ++i) 446 free(*i); 447} 448 449 450/// ExpandResponseFiles - Copy the contents of argv into newArgv, 451/// substituting the contents of the response files for the arguments 452/// of type @file. 453static void ExpandResponseFiles(unsigned argc, char** argv, 454 std::vector<char*>& newArgv) { 455 for (unsigned i = 1; i != argc; ++i) { 456 char *arg = argv[i]; 457 458 if (arg[0] == '@') { 459 sys::PathWithStatus respFile(++arg); 460 461 // Check that the response file is not empty (mmap'ing empty 462 // files can be problematic). 463 const sys::FileStatus *FileStat = respFile.getFileStatus(); 464 if (FileStat && FileStat->getSize() != 0) { 465 466 // Mmap the response file into memory. 467 OwningPtr<MemoryBuffer> 468 respFilePtr(MemoryBuffer::getFile(respFile.c_str())); 469 470 // If we could open the file, parse its contents, otherwise 471 // pass the @file option verbatim. 472 473 // TODO: we should also support recursive loading of response files, 474 // since this is how gcc behaves. (From their man page: "The file may 475 // itself contain additional @file options; any such options will be 476 // processed recursively.") 477 478 if (respFilePtr != 0) { 479 ParseCStringVector(newArgv, respFilePtr->getBufferStart()); 480 continue; 481 } 482 } 483 } 484 newArgv.push_back(strdup(arg)); 485 } 486} 487 488void cl::ParseCommandLineOptions(int argc, char **argv, 489 const char *Overview, bool ReadResponseFiles) { 490 // Process all registered options. 491 SmallVector<Option*, 4> PositionalOpts; 492 SmallVector<Option*, 4> SinkOpts; 493 StringMap<Option*> Opts; 494 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 495 496 assert((!Opts.empty() || !PositionalOpts.empty()) && 497 "No options specified!"); 498 499 // Expand response files. 500 std::vector<char*> newArgv; 501 if (ReadResponseFiles) { 502 newArgv.push_back(strdup(argv[0])); 503 ExpandResponseFiles(argc, argv, newArgv); 504 argv = &newArgv[0]; 505 argc = static_cast<int>(newArgv.size()); 506 } 507 508 // Copy the program name into ProgName, making sure not to overflow it. 509 std::string ProgName = sys::Path(argv[0]).getLast(); 510 size_t Len = std::min(ProgName.size(), size_t(79)); 511 memcpy(ProgramName, ProgName.data(), Len); 512 ProgramName[Len] = '\0'; 513 514 ProgramOverview = Overview; 515 bool ErrorParsing = false; 516 517 // Check out the positional arguments to collect information about them. 518 unsigned NumPositionalRequired = 0; 519 520 // Determine whether or not there are an unlimited number of positionals 521 bool HasUnlimitedPositionals = false; 522 523 Option *ConsumeAfterOpt = 0; 524 if (!PositionalOpts.empty()) { 525 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) { 526 assert(PositionalOpts.size() > 1 && 527 "Cannot specify cl::ConsumeAfter without a positional argument!"); 528 ConsumeAfterOpt = PositionalOpts[0]; 529 } 530 531 // Calculate how many positional values are _required_. 532 bool UnboundedFound = false; 533 for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size(); 534 i != e; ++i) { 535 Option *Opt = PositionalOpts[i]; 536 if (RequiresValue(Opt)) 537 ++NumPositionalRequired; 538 else if (ConsumeAfterOpt) { 539 // ConsumeAfter cannot be combined with "optional" positional options 540 // unless there is only one positional argument... 541 if (PositionalOpts.size() > 2) 542 ErrorParsing |= 543 Opt->error("error - this positional option will never be matched, " 544 "because it does not Require a value, and a " 545 "cl::ConsumeAfter option is active!"); 546 } else if (UnboundedFound && !Opt->ArgStr[0]) { 547 // This option does not "require" a value... Make sure this option is 548 // not specified after an option that eats all extra arguments, or this 549 // one will never get any! 550 // 551 ErrorParsing |= Opt->error("error - option can never match, because " 552 "another positional argument will match an " 553 "unbounded number of values, and this option" 554 " does not require a value!"); 555 } 556 UnboundedFound |= EatsUnboundedNumberOfValues(Opt); 557 } 558 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt; 559 } 560 561 // PositionalVals - A vector of "positional" arguments we accumulate into 562 // the process at the end. 563 // 564 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals; 565 566 // If the program has named positional arguments, and the name has been run 567 // across, keep track of which positional argument was named. Otherwise put 568 // the positional args into the PositionalVals list... 569 Option *ActivePositionalArg = 0; 570 571 // Loop over all of the arguments... processing them. 572 bool DashDashFound = false; // Have we read '--'? 573 for (int i = 1; i < argc; ++i) { 574 Option *Handler = 0; 575 StringRef Value; 576 StringRef ArgName = ""; 577 578 // If the option list changed, this means that some command line 579 // option has just been registered or deregistered. This can occur in 580 // response to things like -load, etc. If this happens, rescan the options. 581 if (OptionListChanged) { 582 PositionalOpts.clear(); 583 SinkOpts.clear(); 584 Opts.clear(); 585 GetOptionInfo(PositionalOpts, SinkOpts, Opts); 586 OptionListChanged = false; 587 } 588 589 // Check to see if this is a positional argument. This argument is 590 // considered to be positional if it doesn't start with '-', if it is "-" 591 // itself, or if we have seen "--" already. 592 // 593 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) { 594 // Positional argument! 595 if (ActivePositionalArg) { 596 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 597 continue; // We are done! 598 } 599 600 if (!PositionalOpts.empty()) { 601 PositionalVals.push_back(std::make_pair(argv[i],i)); 602 603 // All of the positional arguments have been fulfulled, give the rest to 604 // the consume after option... if it's specified... 605 // 606 if (PositionalVals.size() >= NumPositionalRequired && 607 ConsumeAfterOpt != 0) { 608 for (++i; i < argc; ++i) 609 PositionalVals.push_back(std::make_pair(argv[i],i)); 610 break; // Handle outside of the argument processing loop... 611 } 612 613 // Delay processing positional arguments until the end... 614 continue; 615 } 616 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 && 617 !DashDashFound) { 618 DashDashFound = true; // This is the mythical "--"? 619 continue; // Don't try to process it as an argument itself. 620 } else if (ActivePositionalArg && 621 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) { 622 // If there is a positional argument eating options, check to see if this 623 // option is another positional argument. If so, treat it as an argument, 624 // otherwise feed it to the eating positional. 625 ArgName = argv[i]+1; 626 // Eat leading dashes. 627 while (!ArgName.empty() && ArgName[0] == '-') 628 ArgName = ArgName.substr(1); 629 630 Handler = LookupOption(ArgName, Value, Opts); 631 if (!Handler || Handler->getFormattingFlag() != cl::Positional) { 632 ProvidePositionalOption(ActivePositionalArg, argv[i], i); 633 continue; // We are done! 634 } 635 636 } else { // We start with a '-', must be an argument. 637 ArgName = argv[i]+1; 638 // Eat leading dashes. 639 while (!ArgName.empty() && ArgName[0] == '-') 640 ArgName = ArgName.substr(1); 641 642 Handler = LookupOption(ArgName, Value, Opts); 643 644 // Check to see if this "option" is really a prefixed or grouped argument. 645 if (Handler == 0) 646 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, 647 ErrorParsing, Opts); 648 } 649 650 if (Handler == 0) { 651 if (SinkOpts.empty()) { 652 errs() << ProgramName << ": Unknown command line argument '" 653 << argv[i] << "'. Try: '" << argv[0] << " -help'\n"; 654 ErrorParsing = true; 655 } else { 656 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(), 657 E = SinkOpts.end(); I != E ; ++I) 658 (*I)->addOccurrence(i, "", argv[i]); 659 } 660 continue; 661 } 662 663 // If this is a named positional argument, just remember that it is the 664 // active one... 665 if (Handler->getFormattingFlag() == cl::Positional) 666 ActivePositionalArg = Handler; 667 else 668 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i); 669 } 670 671 // Check and handle positional arguments now... 672 if (NumPositionalRequired > PositionalVals.size()) { 673 errs() << ProgramName 674 << ": Not enough positional command line arguments specified!\n" 675 << "Must specify at least " << NumPositionalRequired 676 << " positional arguments: See: " << argv[0] << " -help\n"; 677 678 ErrorParsing = true; 679 } else if (!HasUnlimitedPositionals && 680 PositionalVals.size() > PositionalOpts.size()) { 681 errs() << ProgramName 682 << ": Too many positional arguments specified!\n" 683 << "Can specify at most " << PositionalOpts.size() 684 << " positional arguments: See: " << argv[0] << " -help\n"; 685 ErrorParsing = true; 686 687 } else if (ConsumeAfterOpt == 0) { 688 // Positional args have already been handled if ConsumeAfter is specified. 689 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size()); 690 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) { 691 if (RequiresValue(PositionalOpts[i])) { 692 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first, 693 PositionalVals[ValNo].second); 694 ValNo++; 695 --NumPositionalRequired; // We fulfilled our duty... 696 } 697 698 // If we _can_ give this option more arguments, do so now, as long as we 699 // do not give it values that others need. 'Done' controls whether the 700 // option even _WANTS_ any more. 701 // 702 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required; 703 while (NumVals-ValNo > NumPositionalRequired && !Done) { 704 switch (PositionalOpts[i]->getNumOccurrencesFlag()) { 705 case cl::Optional: 706 Done = true; // Optional arguments want _at most_ one value 707 // FALL THROUGH 708 case cl::ZeroOrMore: // Zero or more will take all they can get... 709 case cl::OneOrMore: // One or more will take all they can get... 710 ProvidePositionalOption(PositionalOpts[i], 711 PositionalVals[ValNo].first, 712 PositionalVals[ValNo].second); 713 ValNo++; 714 break; 715 default: 716 llvm_unreachable("Internal error, unexpected NumOccurrences flag in " 717 "positional argument processing!"); 718 } 719 } 720 } 721 } else { 722 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size()); 723 unsigned ValNo = 0; 724 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j) 725 if (RequiresValue(PositionalOpts[j])) { 726 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j], 727 PositionalVals[ValNo].first, 728 PositionalVals[ValNo].second); 729 ValNo++; 730 } 731 732 // Handle the case where there is just one positional option, and it's 733 // optional. In this case, we want to give JUST THE FIRST option to the 734 // positional option and keep the rest for the consume after. The above 735 // loop would have assigned no values to positional options in this case. 736 // 737 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) { 738 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1], 739 PositionalVals[ValNo].first, 740 PositionalVals[ValNo].second); 741 ValNo++; 742 } 743 744 // Handle over all of the rest of the arguments to the 745 // cl::ConsumeAfter command line option... 746 for (; ValNo != PositionalVals.size(); ++ValNo) 747 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt, 748 PositionalVals[ValNo].first, 749 PositionalVals[ValNo].second); 750 } 751 752 // Loop over args and make sure all required args are specified! 753 for (StringMap<Option*>::iterator I = Opts.begin(), 754 E = Opts.end(); I != E; ++I) { 755 switch (I->second->getNumOccurrencesFlag()) { 756 case Required: 757 case OneOrMore: 758 if (I->second->getNumOccurrences() == 0) { 759 I->second->error("must be specified at least once!"); 760 ErrorParsing = true; 761 } 762 // Fall through 763 default: 764 break; 765 } 766 } 767 768 // Now that we know if -debug is specified, we can use it. 769 // Note that if ReadResponseFiles == true, this must be done before the 770 // memory allocated for the expanded command line is free()d below. 771 DEBUG(dbgs() << "Args: "; 772 for (int i = 0; i < argc; ++i) 773 dbgs() << argv[i] << ' '; 774 dbgs() << '\n'; 775 ); 776 777 // Free all of the memory allocated to the map. Command line options may only 778 // be processed once! 779 Opts.clear(); 780 PositionalOpts.clear(); 781 MoreHelp->clear(); 782 783 // Free the memory allocated by ExpandResponseFiles. 784 if (ReadResponseFiles) { 785 // Free all the strdup()ed strings. 786 for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end(); 787 i != e; ++i) 788 free(*i); 789 } 790 791 // If we had an error processing our arguments, don't let the program execute 792 if (ErrorParsing) exit(1); 793} 794 795//===----------------------------------------------------------------------===// 796// Option Base class implementation 797// 798 799bool Option::error(const Twine &Message, StringRef ArgName) { 800 if (ArgName.data() == 0) ArgName = ArgStr; 801 if (ArgName.empty()) 802 errs() << HelpStr; // Be nice for positional arguments 803 else 804 errs() << ProgramName << ": for the -" << ArgName; 805 806 errs() << " option: " << Message << "\n"; 807 return true; 808} 809 810bool Option::addOccurrence(unsigned pos, StringRef ArgName, 811 StringRef Value, bool MultiArg) { 812 if (!MultiArg) 813 NumOccurrences++; // Increment the number of times we have been seen 814 815 switch (getNumOccurrencesFlag()) { 816 case Optional: 817 if (NumOccurrences > 1) 818 return error("may only occur zero or one times!", ArgName); 819 break; 820 case Required: 821 if (NumOccurrences > 1) 822 return error("must occur exactly one time!", ArgName); 823 // Fall through 824 case OneOrMore: 825 case ZeroOrMore: 826 case ConsumeAfter: break; 827 default: return error("bad num occurrences flag value!"); 828 } 829 830 return handleOccurrence(pos, ArgName, Value); 831} 832 833 834// getValueStr - Get the value description string, using "DefaultMsg" if nothing 835// has been specified yet. 836// 837static const char *getValueStr(const Option &O, const char *DefaultMsg) { 838 if (O.ValueStr[0] == 0) return DefaultMsg; 839 return O.ValueStr; 840} 841 842//===----------------------------------------------------------------------===// 843// cl::alias class implementation 844// 845 846// Return the width of the option tag for printing... 847size_t alias::getOptionWidth() const { 848 return std::strlen(ArgStr)+6; 849} 850 851// Print out the option for the alias. 852void alias::printOptionInfo(size_t GlobalWidth) const { 853 size_t L = std::strlen(ArgStr); 854 errs() << " -" << ArgStr; 855 errs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n"; 856} 857 858 859 860//===----------------------------------------------------------------------===// 861// Parser Implementation code... 862// 863 864// basic_parser implementation 865// 866 867// Return the width of the option tag for printing... 868size_t basic_parser_impl::getOptionWidth(const Option &O) const { 869 size_t Len = std::strlen(O.ArgStr); 870 if (const char *ValName = getValueName()) 871 Len += std::strlen(getValueStr(O, ValName))+3; 872 873 return Len + 6; 874} 875 876// printOptionInfo - Print out information about this option. The 877// to-be-maintained width is specified. 878// 879void basic_parser_impl::printOptionInfo(const Option &O, 880 size_t GlobalWidth) const { 881 outs() << " -" << O.ArgStr; 882 883 if (const char *ValName = getValueName()) 884 outs() << "=<" << getValueStr(O, ValName) << '>'; 885 886 outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n'; 887} 888 889 890 891 892// parser<bool> implementation 893// 894bool parser<bool>::parse(Option &O, StringRef ArgName, 895 StringRef Arg, bool &Value) { 896 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 897 Arg == "1") { 898 Value = true; 899 return false; 900 } 901 902 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 903 Value = false; 904 return false; 905 } 906 return O.error("'" + Arg + 907 "' is invalid value for boolean argument! Try 0 or 1"); 908} 909 910// parser<boolOrDefault> implementation 911// 912bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, 913 StringRef Arg, boolOrDefault &Value) { 914 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" || 915 Arg == "1") { 916 Value = BOU_TRUE; 917 return false; 918 } 919 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") { 920 Value = BOU_FALSE; 921 return false; 922 } 923 924 return O.error("'" + Arg + 925 "' is invalid value for boolean argument! Try 0 or 1"); 926} 927 928// parser<int> implementation 929// 930bool parser<int>::parse(Option &O, StringRef ArgName, 931 StringRef Arg, int &Value) { 932 if (Arg.getAsInteger(0, Value)) 933 return O.error("'" + Arg + "' value invalid for integer argument!"); 934 return false; 935} 936 937// parser<unsigned> implementation 938// 939bool parser<unsigned>::parse(Option &O, StringRef ArgName, 940 StringRef Arg, unsigned &Value) { 941 942 if (Arg.getAsInteger(0, Value)) 943 return O.error("'" + Arg + "' value invalid for uint argument!"); 944 return false; 945} 946 947// parser<double>/parser<float> implementation 948// 949static bool parseDouble(Option &O, StringRef Arg, double &Value) { 950 SmallString<32> TmpStr(Arg.begin(), Arg.end()); 951 const char *ArgStart = TmpStr.c_str(); 952 char *End; 953 Value = strtod(ArgStart, &End); 954 if (*End != 0) 955 return O.error("'" + Arg + "' value invalid for floating point argument!"); 956 return false; 957} 958 959bool parser<double>::parse(Option &O, StringRef ArgName, 960 StringRef Arg, double &Val) { 961 return parseDouble(O, Arg, Val); 962} 963 964bool parser<float>::parse(Option &O, StringRef ArgName, 965 StringRef Arg, float &Val) { 966 double dVal; 967 if (parseDouble(O, Arg, dVal)) 968 return true; 969 Val = (float)dVal; 970 return false; 971} 972 973 974 975// generic_parser_base implementation 976// 977 978// findOption - Return the option number corresponding to the specified 979// argument string. If the option is not found, getNumOptions() is returned. 980// 981unsigned generic_parser_base::findOption(const char *Name) { 982 unsigned e = getNumOptions(); 983 984 for (unsigned i = 0; i != e; ++i) { 985 if (strcmp(getOption(i), Name) == 0) 986 return i; 987 } 988 return e; 989} 990 991 992// Return the width of the option tag for printing... 993size_t generic_parser_base::getOptionWidth(const Option &O) const { 994 if (O.hasArgStr()) { 995 size_t Size = std::strlen(O.ArgStr)+6; 996 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 997 Size = std::max(Size, std::strlen(getOption(i))+8); 998 return Size; 999 } else { 1000 size_t BaseSize = 0; 1001 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) 1002 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8); 1003 return BaseSize; 1004 } 1005} 1006 1007// printOptionInfo - Print out information about this option. The 1008// to-be-maintained width is specified. 1009// 1010void generic_parser_base::printOptionInfo(const Option &O, 1011 size_t GlobalWidth) const { 1012 if (O.hasArgStr()) { 1013 size_t L = std::strlen(O.ArgStr); 1014 outs() << " -" << O.ArgStr; 1015 outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n'; 1016 1017 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1018 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8; 1019 outs() << " =" << getOption(i); 1020 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n'; 1021 } 1022 } else { 1023 if (O.HelpStr[0]) 1024 outs() << " " << O.HelpStr << '\n'; 1025 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { 1026 size_t L = std::strlen(getOption(i)); 1027 outs() << " -" << getOption(i); 1028 outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n'; 1029 } 1030 } 1031} 1032 1033 1034//===----------------------------------------------------------------------===// 1035// -help and -help-hidden option implementation 1036// 1037 1038static int OptNameCompare(const void *LHS, const void *RHS) { 1039 typedef std::pair<const char *, Option*> pair_ty; 1040 1041 return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first); 1042} 1043 1044namespace { 1045 1046class HelpPrinter { 1047 size_t MaxArgLen; 1048 const Option *EmptyArg; 1049 const bool ShowHidden; 1050 1051public: 1052 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) { 1053 EmptyArg = 0; 1054 } 1055 1056 void operator=(bool Value) { 1057 if (Value == false) return; 1058 1059 // Get all the options. 1060 SmallVector<Option*, 4> PositionalOpts; 1061 SmallVector<Option*, 4> SinkOpts; 1062 StringMap<Option*> OptMap; 1063 GetOptionInfo(PositionalOpts, SinkOpts, OptMap); 1064 1065 // Copy Options into a vector so we can sort them as we like. 1066 SmallVector<std::pair<const char *, Option*>, 128> Opts; 1067 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection. 1068 1069 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end(); 1070 I != E; ++I) { 1071 // Ignore really-hidden options. 1072 if (I->second->getOptionHiddenFlag() == ReallyHidden) 1073 continue; 1074 1075 // Unless showhidden is set, ignore hidden flags. 1076 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden) 1077 continue; 1078 1079 // If we've already seen this option, don't add it to the list again. 1080 if (!OptionSet.insert(I->second)) 1081 continue; 1082 1083 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(), 1084 I->second)); 1085 } 1086 1087 // Sort the options list alphabetically. 1088 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare); 1089 1090 if (ProgramOverview) 1091 outs() << "OVERVIEW: " << ProgramOverview << "\n"; 1092 1093 outs() << "USAGE: " << ProgramName << " [options]"; 1094 1095 // Print out the positional options. 1096 Option *CAOpt = 0; // The cl::ConsumeAfter option, if it exists... 1097 if (!PositionalOpts.empty() && 1098 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter) 1099 CAOpt = PositionalOpts[0]; 1100 1101 for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) { 1102 if (PositionalOpts[i]->ArgStr[0]) 1103 outs() << " --" << PositionalOpts[i]->ArgStr; 1104 outs() << " " << PositionalOpts[i]->HelpStr; 1105 } 1106 1107 // Print the consume after option info if it exists... 1108 if (CAOpt) outs() << " " << CAOpt->HelpStr; 1109 1110 outs() << "\n\n"; 1111 1112 // Compute the maximum argument length... 1113 MaxArgLen = 0; 1114 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1115 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth()); 1116 1117 outs() << "OPTIONS:\n"; 1118 for (size_t i = 0, e = Opts.size(); i != e; ++i) 1119 Opts[i].second->printOptionInfo(MaxArgLen); 1120 1121 // Print any extra help the user has declared. 1122 for (std::vector<const char *>::iterator I = MoreHelp->begin(), 1123 E = MoreHelp->end(); I != E; ++I) 1124 outs() << *I; 1125 MoreHelp->clear(); 1126 1127 // Halt the program since help information was printed 1128 exit(1); 1129 } 1130}; 1131} // End anonymous namespace 1132 1133// Define the two HelpPrinter instances that are used to print out help, or 1134// help-hidden... 1135// 1136static HelpPrinter NormalPrinter(false); 1137static HelpPrinter HiddenPrinter(true); 1138 1139static cl::opt<HelpPrinter, true, parser<bool> > 1140HOp("help", cl::desc("Display available options (-help-hidden for more)"), 1141 cl::location(NormalPrinter), cl::ValueDisallowed); 1142 1143static cl::opt<HelpPrinter, true, parser<bool> > 1144HHOp("help-hidden", cl::desc("Display all available options"), 1145 cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed); 1146 1147static void (*OverrideVersionPrinter)() = 0; 1148 1149static int TargetArraySortFn(const void *LHS, const void *RHS) { 1150 typedef std::pair<const char *, const Target*> pair_ty; 1151 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first); 1152} 1153 1154namespace { 1155class VersionPrinter { 1156public: 1157 void print() { 1158 raw_ostream &OS = outs(); 1159 OS << "Low Level Virtual Machine (http://llvm.org/):\n" 1160 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION; 1161#ifdef LLVM_VERSION_INFO 1162 OS << LLVM_VERSION_INFO; 1163#endif 1164 OS << "\n "; 1165#ifndef __OPTIMIZE__ 1166 OS << "DEBUG build"; 1167#else 1168 OS << "Optimized build"; 1169#endif 1170#ifndef NDEBUG 1171 OS << " with assertions"; 1172#endif 1173 std::string CPU = sys::getHostCPUName(); 1174 if (CPU == "generic") CPU = "(unknown)"; 1175 OS << ".\n" 1176#if (ENABLE_TIMESTAMPS == 1) 1177 << " Built " << __DATE__ << " (" << __TIME__ << ").\n" 1178#endif 1179 << " Host: " << sys::getHostTriple() << '\n' 1180 << " Host CPU: " << CPU << '\n' 1181 << '\n' 1182 << " Registered Targets:\n"; 1183 1184 std::vector<std::pair<const char *, const Target*> > Targets; 1185 size_t Width = 0; 1186 for (TargetRegistry::iterator it = TargetRegistry::begin(), 1187 ie = TargetRegistry::end(); it != ie; ++it) { 1188 Targets.push_back(std::make_pair(it->getName(), &*it)); 1189 Width = std::max(Width, strlen(Targets.back().first)); 1190 } 1191 if (!Targets.empty()) 1192 qsort(&Targets[0], Targets.size(), sizeof(Targets[0]), 1193 TargetArraySortFn); 1194 1195 for (unsigned i = 0, e = Targets.size(); i != e; ++i) { 1196 OS << " " << Targets[i].first; 1197 OS.indent(Width - strlen(Targets[i].first)) << " - " 1198 << Targets[i].second->getShortDescription() << '\n'; 1199 } 1200 if (Targets.empty()) 1201 OS << " (none)\n"; 1202 } 1203 void operator=(bool OptionWasSpecified) { 1204 if (!OptionWasSpecified) return; 1205 1206 if (OverrideVersionPrinter == 0) { 1207 print(); 1208 exit(1); 1209 } 1210 (*OverrideVersionPrinter)(); 1211 exit(1); 1212 } 1213}; 1214} // End anonymous namespace 1215 1216 1217// Define the --version option that prints out the LLVM version for the tool 1218static VersionPrinter VersionPrinterInstance; 1219 1220static cl::opt<VersionPrinter, true, parser<bool> > 1221VersOp("version", cl::desc("Display the version of this program"), 1222 cl::location(VersionPrinterInstance), cl::ValueDisallowed); 1223 1224// Utility function for printing the help message. 1225void cl::PrintHelpMessage() { 1226 // This looks weird, but it actually prints the help message. The 1227 // NormalPrinter variable is a HelpPrinter and the help gets printed when 1228 // its operator= is invoked. That's because the "normal" usages of the 1229 // help printer is to be assigned true/false depending on whether the 1230 // -help option was given or not. Since we're circumventing that we have 1231 // to make it look like -help was given, so we assign true. 1232 NormalPrinter = true; 1233} 1234 1235/// Utility function for printing version number. 1236void cl::PrintVersionMessage() { 1237 VersionPrinterInstance.print(); 1238} 1239 1240void cl::SetVersionPrinter(void (*func)()) { 1241 OverrideVersionPrinter = func; 1242} 1243