1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
38 #include <system_error>
42 #define DEBUG_TYPE "commandline"
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
49 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
50 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
51 TEMPLATE_INSTANTIATION(class basic_parser<int>);
52 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
53 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
54 TEMPLATE_INSTANTIATION(class basic_parser<double>);
55 TEMPLATE_INSTANTIATION(class basic_parser<float>);
56 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
57 TEMPLATE_INSTANTIATION(class basic_parser<char>);
59 TEMPLATE_INSTANTIATION(class opt<unsigned>);
60 TEMPLATE_INSTANTIATION(class opt<int>);
61 TEMPLATE_INSTANTIATION(class opt<std::string>);
62 TEMPLATE_INSTANTIATION(class opt<char>);
63 TEMPLATE_INSTANTIATION(class opt<bool>);
65 } // end namespace llvm::cl
67 // Pin the vtables to this file.
68 void GenericOptionValue::anchor() {}
69 void OptionValue<boolOrDefault>::anchor() {}
70 void OptionValue<std::string>::anchor() {}
71 void Option::anchor() {}
72 void basic_parser_impl::anchor() {}
73 void parser<bool>::anchor() {}
74 void parser<boolOrDefault>::anchor() {}
75 void parser<int>::anchor() {}
76 void parser<unsigned>::anchor() {}
77 void parser<unsigned long long>::anchor() {}
78 void parser<double>::anchor() {}
79 void parser<float>::anchor() {}
80 void parser<std::string>::anchor() {}
81 void parser<char>::anchor() {}
82 void StringSaver::anchor() {}
84 //===----------------------------------------------------------------------===//
86 class CommandLineParser {
88 // Globals for name and overview of program. Program name is not a string to
89 // avoid static ctor/dtor issues.
90 char ProgramName[80] = "<premain>";
91 const char *ProgramOverview = nullptr;
93 // This collects additional help to be printed.
94 std::vector<const char *> MoreHelp;
96 SmallVector<Option *, 4> PositionalOpts;
97 SmallVector<Option *, 4> SinkOpts;
98 StringMap<Option *> OptionsMap;
100 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
102 void ParseCommandLineOptions(int argc, const char *const *argv,
103 const char *Overview);
105 void addLiteralOption(Option &Opt, const char *Name) {
106 if (!Opt.hasArgStr()) {
107 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
108 errs() << ProgramName << ": CommandLine Error: Option '" << Name
109 << "' registered more than once!\n";
110 report_fatal_error("inconsistency in registered CommandLine options");
115 void addOption(Option *O) {
116 bool HadErrors = false;
118 // Add argument to the argument map!
119 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
120 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
121 << "' registered more than once!\n";
126 // Remember information about positional options.
127 if (O->getFormattingFlag() == cl::Positional)
128 PositionalOpts.push_back(O);
129 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
130 SinkOpts.push_back(O);
131 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
132 if (ConsumeAfterOpt) {
133 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
139 // Fail hard if there were errors. These are strictly unrecoverable and
140 // indicate serious issues such as conflicting option names or an
142 // linked LLVM distribution.
144 report_fatal_error("inconsistency in registered CommandLine options");
147 void removeOption(Option *O) {
148 SmallVector<const char *, 16> OptionNames;
149 O->getExtraOptionNames(OptionNames);
151 OptionNames.push_back(O->ArgStr);
152 for (auto Name : OptionNames)
153 OptionsMap.erase(StringRef(Name));
155 if (O->getFormattingFlag() == cl::Positional)
156 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
159 PositionalOpts.erase(Opt);
163 else if (O->getMiscFlags() & cl::Sink)
164 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
170 else if (O == ConsumeAfterOpt)
171 ConsumeAfterOpt = nullptr;
175 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
176 nullptr != ConsumeAfterOpt);
179 void updateArgStr(Option *O, const char* NewName) {
180 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
181 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
182 << "' registered more than once!\n";
183 report_fatal_error("inconsistency in registered CommandLine options");
185 OptionsMap.erase(StringRef(O->ArgStr));
189 static ManagedStatic<CommandLineParser> GlobalParser;
191 void cl::AddLiteralOption(Option &O, const char *Name) {
192 GlobalParser->addLiteralOption(O, Name);
195 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
196 GlobalParser->MoreHelp.push_back(Help);
199 void Option::addArgument() {
200 GlobalParser->addOption(this);
201 FullyInitialized = true;
204 void Option::removeArgument() { GlobalParser->removeOption(this); }
206 void Option::setArgStr(const char *S) {
207 if (FullyInitialized)
208 GlobalParser->updateArgStr(this, S);
212 // This collects the different option categories that have been registered.
213 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
214 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
216 // Initialise the general option category.
217 OptionCategory llvm::cl::GeneralCategory("General options");
219 void OptionCategory::registerCategory() {
220 assert(std::count_if(RegisteredOptionCategories->begin(),
221 RegisteredOptionCategories->end(),
222 [this](const OptionCategory *Category) {
223 return getName() == Category->getName();
225 "Duplicate option categories");
227 RegisteredOptionCategories->insert(this);
230 //===----------------------------------------------------------------------===//
231 // Basic, shared command line option processing machinery.
234 /// LookupOption - Lookup the option specified by the specified option on the
235 /// command line. If there is a value specified (after an equal sign) return
236 /// that as well. This assumes that leading dashes have already been stripped.
237 static Option *LookupOption(StringRef &Arg, StringRef &Value,
238 const StringMap<Option *> &OptionsMap) {
239 // Reject all dashes.
243 size_t EqualPos = Arg.find('=');
245 // If we have an equals sign, remember the value.
246 if (EqualPos == StringRef::npos) {
247 // Look up the option.
248 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
249 return I != OptionsMap.end() ? I->second : nullptr;
252 // If the argument before the = is a valid option name, we match. If not,
253 // return Arg unmolested.
254 StringMap<Option *>::const_iterator I =
255 OptionsMap.find(Arg.substr(0, EqualPos));
256 if (I == OptionsMap.end())
259 Value = Arg.substr(EqualPos + 1);
260 Arg = Arg.substr(0, EqualPos);
264 /// LookupNearestOption - Lookup the closest match to the option specified by
265 /// the specified option on the command line. If there is a value specified
266 /// (after an equal sign) return that as well. This assumes that leading dashes
267 /// have already been stripped.
268 static Option *LookupNearestOption(StringRef Arg,
269 const StringMap<Option *> &OptionsMap,
270 std::string &NearestString) {
271 // Reject all dashes.
275 // Split on any equal sign.
276 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
277 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
278 StringRef &RHS = SplitArg.second;
280 // Find the closest match.
281 Option *Best = nullptr;
282 unsigned BestDistance = 0;
283 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
284 ie = OptionsMap.end();
286 Option *O = it->second;
287 SmallVector<const char *, 16> OptionNames;
288 O->getExtraOptionNames(OptionNames);
290 OptionNames.push_back(O->ArgStr);
292 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
293 StringRef Flag = PermitValue ? LHS : Arg;
294 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
295 StringRef Name = OptionNames[i];
296 unsigned Distance = StringRef(Name).edit_distance(
297 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
298 if (!Best || Distance < BestDistance) {
300 BestDistance = Distance;
301 if (RHS.empty() || !PermitValue)
302 NearestString = OptionNames[i];
304 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
312 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
313 /// that does special handling of cl::CommaSeparated options.
314 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
315 StringRef ArgName, StringRef Value,
316 bool MultiArg = false) {
317 // Check to see if this option accepts a comma separated list of values. If
318 // it does, we have to split up the value into multiple values.
319 if (Handler->getMiscFlags() & CommaSeparated) {
320 StringRef Val(Value);
321 StringRef::size_type Pos = Val.find(',');
323 while (Pos != StringRef::npos) {
324 // Process the portion before the comma.
325 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
327 // Erase the portion before the comma, AND the comma.
328 Val = Val.substr(Pos + 1);
329 Value.substr(Pos + 1); // Increment the original value pointer as well.
330 // Check for another comma.
337 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
343 /// ProvideOption - For Value, this differentiates between an empty value ("")
344 /// and a null value (StringRef()). The later is accepted for arguments that
345 /// don't allow a value (-foo) the former is rejected (-foo=).
346 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
347 StringRef Value, int argc,
348 const char *const *argv, int &i) {
349 // Is this a multi-argument option?
350 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
352 // Enforce value requirements
353 switch (Handler->getValueExpectedFlag()) {
355 if (!Value.data()) { // No value specified?
357 return Handler->error("requires a value!");
358 // Steal the next argument, like for '-o filename'
359 assert(argv && "null check");
363 case ValueDisallowed:
364 if (NumAdditionalVals > 0)
365 return Handler->error("multi-valued option specified"
366 " with ValueDisallowed modifier!");
369 return Handler->error("does not allow a value! '" + Twine(Value) +
376 // If this isn't a multi-arg option, just run the handler.
377 if (NumAdditionalVals == 0)
378 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
380 // If it is, run the handle several times.
381 bool MultiArg = false;
384 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
390 while (NumAdditionalVals > 0) {
392 return Handler->error("not enough values!");
393 assert(argv && "null check");
396 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
404 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
406 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
409 // Option predicates...
410 static inline bool isGrouping(const Option *O) {
411 return O->getFormattingFlag() == cl::Grouping;
413 static inline bool isPrefixedOrGrouping(const Option *O) {
414 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
417 // getOptionPred - Check to see if there are any options that satisfy the
418 // specified predicate with names that are the prefixes in Name. This is
419 // checked by progressively stripping characters off of the name, checking to
420 // see if there options that satisfy the predicate. If we find one, return it,
421 // otherwise return null.
423 static Option *getOptionPred(StringRef Name, size_t &Length,
424 bool (*Pred)(const Option *),
425 const StringMap<Option *> &OptionsMap) {
427 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
429 // Loop while we haven't found an option and Name still has at least two
430 // characters in it (so that the next iteration will not be the empty
432 while (OMI == OptionsMap.end() && Name.size() > 1) {
433 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
434 OMI = OptionsMap.find(Name);
437 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
438 Length = Name.size();
439 return OMI->second; // Found one!
441 return nullptr; // No option found!
444 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
445 /// with at least one '-') does not fully match an available option. Check to
446 /// see if this is a prefix or grouped option. If so, split arg into output an
447 /// Arg/Value pair and return the Option to parse it with.
449 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
451 const StringMap<Option *> &OptionsMap) {
457 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
461 // If the option is a prefixed option, then the value is simply the
462 // rest of the name... so fall through to later processing, by
463 // setting up the argument name flags and value fields.
464 if (PGOpt->getFormattingFlag() == cl::Prefix) {
465 Value = Arg.substr(Length);
466 Arg = Arg.substr(0, Length);
467 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
471 // This must be a grouped option... handle them now. Grouping options can't
473 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
476 // Move current arg name out of Arg into OneArgName.
477 StringRef OneArgName = Arg.substr(0, Length);
478 Arg = Arg.substr(Length);
480 // Because ValueRequired is an invalid flag for grouped arguments,
481 // we don't need to pass argc/argv in.
482 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
483 "Option can not be cl::Grouping AND cl::ValueRequired!");
486 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
488 // Get the next grouping option.
489 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
490 } while (PGOpt && Length != Arg.size());
492 // Return the last option with Arg cut down to just the last one.
496 static bool RequiresValue(const Option *O) {
497 return O->getNumOccurrencesFlag() == cl::Required ||
498 O->getNumOccurrencesFlag() == cl::OneOrMore;
501 static bool EatsUnboundedNumberOfValues(const Option *O) {
502 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
503 O->getNumOccurrencesFlag() == cl::OneOrMore;
506 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
508 static bool isQuote(char C) { return C == '\"' || C == '\''; }
510 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
512 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
513 SmallVectorImpl<const char *> &NewArgv,
515 SmallString<128> Token;
516 for (size_t I = 0, E = Src.size(); I != E; ++I) {
517 // Consume runs of whitespace.
519 while (I != E && isWhitespace(Src[I])) {
520 // Mark the end of lines in response files
521 if (MarkEOLs && Src[I] == '\n')
522 NewArgv.push_back(nullptr);
529 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
530 // they are literal. This makes it much easier to read Windows file paths.
531 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
532 ++I; // Skip the escape.
533 Token.push_back(Src[I]);
537 // Consume a quoted string.
538 if (isQuote(Src[I])) {
539 char Quote = Src[I++];
540 while (I != E && Src[I] != Quote) {
541 // Backslashes are literal, unless they escape a special character.
542 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
544 Token.push_back(Src[I]);
552 // End the token if this is whitespace.
553 if (isWhitespace(Src[I])) {
555 NewArgv.push_back(Saver.SaveString(Token.c_str()));
560 // This is a normal character. Append it.
561 Token.push_back(Src[I]);
564 // Append the last token after hitting EOF with no whitespace.
566 NewArgv.push_back(Saver.SaveString(Token.c_str()));
567 // Mark the end of response files
569 NewArgv.push_back(nullptr);
572 /// Backslashes are interpreted in a rather complicated way in the Windows-style
573 /// command line, because backslashes are used both to separate path and to
574 /// escape double quote. This method consumes runs of backslashes as well as the
575 /// following double quote if it's escaped.
577 /// * If an even number of backslashes is followed by a double quote, one
578 /// backslash is output for every pair of backslashes, and the last double
579 /// quote remains unconsumed. The double quote will later be interpreted as
580 /// the start or end of a quoted string in the main loop outside of this
583 /// * If an odd number of backslashes is followed by a double quote, one
584 /// backslash is output for every pair of backslashes, and a double quote is
585 /// output for the last pair of backslash-double quote. The double quote is
586 /// consumed in this case.
588 /// * Otherwise, backslashes are interpreted literally.
589 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
590 size_t E = Src.size();
591 int BackslashCount = 0;
592 // Skip the backslashes.
596 } while (I != E && Src[I] == '\\');
598 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
599 if (FollowedByDoubleQuote) {
600 Token.append(BackslashCount / 2, '\\');
601 if (BackslashCount % 2 == 0)
603 Token.push_back('"');
606 Token.append(BackslashCount, '\\');
610 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
611 SmallVectorImpl<const char *> &NewArgv,
613 SmallString<128> Token;
615 // This is a small state machine to consume characters until it reaches the
616 // end of the source string.
617 enum { INIT, UNQUOTED, QUOTED } State = INIT;
618 for (size_t I = 0, E = Src.size(); I != E; ++I) {
619 // INIT state indicates that the current input index is at the start of
620 // the string or between tokens.
622 if (isWhitespace(Src[I])) {
623 // Mark the end of lines in response files
624 if (MarkEOLs && Src[I] == '\n')
625 NewArgv.push_back(nullptr);
632 if (Src[I] == '\\') {
633 I = parseBackslash(Src, I, Token);
637 Token.push_back(Src[I]);
642 // UNQUOTED state means that it's reading a token not quoted by double
644 if (State == UNQUOTED) {
645 // Whitespace means the end of the token.
646 if (isWhitespace(Src[I])) {
647 NewArgv.push_back(Saver.SaveString(Token.c_str()));
650 // Mark the end of lines in response files
651 if (MarkEOLs && Src[I] == '\n')
652 NewArgv.push_back(nullptr);
659 if (Src[I] == '\\') {
660 I = parseBackslash(Src, I, Token);
663 Token.push_back(Src[I]);
667 // QUOTED state means that it's reading a token quoted by double quotes.
668 if (State == QUOTED) {
673 if (Src[I] == '\\') {
674 I = parseBackslash(Src, I, Token);
677 Token.push_back(Src[I]);
680 // Append the last token after hitting EOF with no whitespace.
682 NewArgv.push_back(Saver.SaveString(Token.c_str()));
683 // Mark the end of response files
685 NewArgv.push_back(nullptr);
688 // It is called byte order marker but the UTF-8 BOM is actually not affected
689 // by the host system's endianness.
690 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
691 return (S.size() >= 3 &&
692 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
695 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
696 TokenizerCallback Tokenizer,
697 SmallVectorImpl<const char *> &NewArgv,
698 bool MarkEOLs = false) {
699 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
700 MemoryBuffer::getFile(FName);
703 MemoryBuffer &MemBuf = *MemBufOrErr.get();
704 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
706 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
707 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
709 if (hasUTF16ByteOrderMark(BufRef)) {
710 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
712 Str = StringRef(UTF8Buf);
714 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
715 // these bytes before parsing.
716 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
717 else if (hasUTF8ByteOrderMark(BufRef))
718 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
720 // Tokenize the contents into NewArgv.
721 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
726 /// \brief Expand response files on a command line recursively using the given
727 /// StringSaver and tokenization strategy.
728 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
729 SmallVectorImpl<const char *> &Argv,
731 unsigned RspFiles = 0;
732 bool AllExpanded = true;
734 // Don't cache Argv.size() because it can change.
735 for (unsigned I = 0; I != Argv.size();) {
736 const char *Arg = Argv[I];
737 // Check if it is an EOL marker
738 if (Arg == nullptr) {
747 // If we have too many response files, leave some unexpanded. This avoids
748 // crashing on self-referential response files.
752 // Replace this response file argument with the tokenization of its
753 // contents. Nested response files are expanded in subsequent iterations.
754 // FIXME: If a nested response file uses a relative path, is it relative to
755 // the cwd of the process or the response file?
756 SmallVector<const char *, 0> ExpandedArgv;
757 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
759 // We couldn't read this file, so we leave it in the argument stream and
765 Argv.erase(Argv.begin() + I);
766 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
772 class StrDupSaver : public StringSaver {
773 std::vector<char *> Dups;
777 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
783 const char *SaveString(const char *Str) override {
784 char *Dup = strdup(Str);
791 /// ParseEnvironmentOptions - An alternative entry point to the
792 /// CommandLine library, which allows you to read the program's name
793 /// from the caller (as PROGNAME) and its command-line arguments from
794 /// an environment variable (whose name is given in ENVVAR).
796 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
797 const char *Overview) {
799 assert(progName && "Program name not specified");
800 assert(envVar && "Environment variable name missing");
802 // Get the environment variable they want us to parse options out of.
803 const char *envValue = getenv(envVar);
807 // Get program's "name", which we wouldn't know without the caller
809 SmallVector<const char *, 20> newArgv;
811 newArgv.push_back(Saver.SaveString(progName));
813 // Parse the value of the environment variable into a "command line"
814 // and hand it off to ParseCommandLineOptions().
815 TokenizeGNUCommandLine(envValue, Saver, newArgv);
816 int newArgc = static_cast<int>(newArgv.size());
817 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
820 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
821 const char *Overview) {
822 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
825 void CommandLineParser::ParseCommandLineOptions(int argc,
826 const char *const *argv,
827 const char *Overview) {
828 assert(hasOptions() && "No options specified!");
830 // Expand response files.
831 SmallVector<const char *, 20> newArgv;
832 for (int i = 0; i != argc; ++i)
833 newArgv.push_back(argv[i]);
835 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
837 argc = static_cast<int>(newArgv.size());
839 // Copy the program name into ProgName, making sure not to overflow it.
840 StringRef ProgName = sys::path::filename(argv[0]);
841 size_t Len = std::min(ProgName.size(), size_t(79));
842 memcpy(ProgramName, ProgName.data(), Len);
843 ProgramName[Len] = '\0';
845 ProgramOverview = Overview;
846 bool ErrorParsing = false;
848 // Check out the positional arguments to collect information about them.
849 unsigned NumPositionalRequired = 0;
851 // Determine whether or not there are an unlimited number of positionals
852 bool HasUnlimitedPositionals = false;
854 if (ConsumeAfterOpt) {
855 assert(PositionalOpts.size() > 0 &&
856 "Cannot specify cl::ConsumeAfter without a positional argument!");
858 if (!PositionalOpts.empty()) {
860 // Calculate how many positional values are _required_.
861 bool UnboundedFound = false;
862 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
863 Option *Opt = PositionalOpts[i];
864 if (RequiresValue(Opt))
865 ++NumPositionalRequired;
866 else if (ConsumeAfterOpt) {
867 // ConsumeAfter cannot be combined with "optional" positional options
868 // unless there is only one positional argument...
869 if (PositionalOpts.size() > 1)
870 ErrorParsing |= Opt->error(
871 "error - this positional option will never be matched, "
872 "because it does not Require a value, and a "
873 "cl::ConsumeAfter option is active!");
874 } else if (UnboundedFound && !Opt->ArgStr[0]) {
875 // This option does not "require" a value... Make sure this option is
876 // not specified after an option that eats all extra arguments, or this
877 // one will never get any!
879 ErrorParsing |= Opt->error("error - option can never match, because "
880 "another positional argument will match an "
881 "unbounded number of values, and this option"
882 " does not require a value!");
883 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
884 << "' is all messed up!\n";
885 errs() << PositionalOpts.size();
887 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
889 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
892 // PositionalVals - A vector of "positional" arguments we accumulate into
893 // the process at the end.
895 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
897 // If the program has named positional arguments, and the name has been run
898 // across, keep track of which positional argument was named. Otherwise put
899 // the positional args into the PositionalVals list...
900 Option *ActivePositionalArg = nullptr;
902 // Loop over all of the arguments... processing them.
903 bool DashDashFound = false; // Have we read '--'?
904 for (int i = 1; i < argc; ++i) {
905 Option *Handler = nullptr;
906 Option *NearestHandler = nullptr;
907 std::string NearestHandlerString;
909 StringRef ArgName = "";
911 // Check to see if this is a positional argument. This argument is
912 // considered to be positional if it doesn't start with '-', if it is "-"
913 // itself, or if we have seen "--" already.
915 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
916 // Positional argument!
917 if (ActivePositionalArg) {
918 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
919 continue; // We are done!
922 if (!PositionalOpts.empty()) {
923 PositionalVals.push_back(std::make_pair(argv[i], i));
925 // All of the positional arguments have been fulfulled, give the rest to
926 // the consume after option... if it's specified...
928 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
929 for (++i; i < argc; ++i)
930 PositionalVals.push_back(std::make_pair(argv[i], i));
931 break; // Handle outside of the argument processing loop...
934 // Delay processing positional arguments until the end...
937 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
939 DashDashFound = true; // This is the mythical "--"?
940 continue; // Don't try to process it as an argument itself.
941 } else if (ActivePositionalArg &&
942 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
943 // If there is a positional argument eating options, check to see if this
944 // option is another positional argument. If so, treat it as an argument,
945 // otherwise feed it to the eating positional.
946 ArgName = argv[i] + 1;
947 // Eat leading dashes.
948 while (!ArgName.empty() && ArgName[0] == '-')
949 ArgName = ArgName.substr(1);
951 Handler = LookupOption(ArgName, Value, OptionsMap);
952 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
953 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
954 continue; // We are done!
957 } else { // We start with a '-', must be an argument.
958 ArgName = argv[i] + 1;
959 // Eat leading dashes.
960 while (!ArgName.empty() && ArgName[0] == '-')
961 ArgName = ArgName.substr(1);
963 Handler = LookupOption(ArgName, Value, OptionsMap);
965 // Check to see if this "option" is really a prefixed or grouped argument.
967 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
970 // Otherwise, look for the closest available option to report to the user
971 // in the upcoming error.
972 if (!Handler && SinkOpts.empty())
974 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
978 if (SinkOpts.empty()) {
979 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
980 << "'. Try: '" << argv[0] << " -help'\n";
982 if (NearestHandler) {
983 // If we know a near match, report it as well.
984 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
990 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
993 (*I)->addOccurrence(i, "", argv[i]);
998 // If this is a named positional argument, just remember that it is the
1000 if (Handler->getFormattingFlag() == cl::Positional)
1001 ActivePositionalArg = Handler;
1003 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1006 // Check and handle positional arguments now...
1007 if (NumPositionalRequired > PositionalVals.size()) {
1008 errs() << ProgramName
1009 << ": Not enough positional command line arguments specified!\n"
1010 << "Must specify at least " << NumPositionalRequired
1011 << " positional arguments: See: " << argv[0] << " -help\n";
1013 ErrorParsing = true;
1014 } else if (!HasUnlimitedPositionals &&
1015 PositionalVals.size() > PositionalOpts.size()) {
1016 errs() << ProgramName << ": Too many positional arguments specified!\n"
1017 << "Can specify at most " << PositionalOpts.size()
1018 << " positional arguments: See: " << argv[0] << " -help\n";
1019 ErrorParsing = true;
1021 } else if (!ConsumeAfterOpt) {
1022 // Positional args have already been handled if ConsumeAfter is specified.
1023 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1024 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1025 if (RequiresValue(PositionalOpts[i])) {
1026 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1027 PositionalVals[ValNo].second);
1029 --NumPositionalRequired; // We fulfilled our duty...
1032 // If we _can_ give this option more arguments, do so now, as long as we
1033 // do not give it values that others need. 'Done' controls whether the
1034 // option even _WANTS_ any more.
1036 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1037 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1038 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1040 Done = true; // Optional arguments want _at most_ one value
1042 case cl::ZeroOrMore: // Zero or more will take all they can get...
1043 case cl::OneOrMore: // One or more will take all they can get...
1044 ProvidePositionalOption(PositionalOpts[i],
1045 PositionalVals[ValNo].first,
1046 PositionalVals[ValNo].second);
1050 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1051 "positional argument processing!");
1056 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1058 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1059 if (RequiresValue(PositionalOpts[j])) {
1060 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1061 PositionalVals[ValNo].first,
1062 PositionalVals[ValNo].second);
1066 // Handle the case where there is just one positional option, and it's
1067 // optional. In this case, we want to give JUST THE FIRST option to the
1068 // positional option and keep the rest for the consume after. The above
1069 // loop would have assigned no values to positional options in this case.
1071 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1072 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1073 PositionalVals[ValNo].first,
1074 PositionalVals[ValNo].second);
1078 // Handle over all of the rest of the arguments to the
1079 // cl::ConsumeAfter command line option...
1080 for (; ValNo != PositionalVals.size(); ++ValNo)
1082 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1083 PositionalVals[ValNo].second);
1086 // Loop over args and make sure all required args are specified!
1087 for (const auto &Opt : OptionsMap) {
1088 switch (Opt.second->getNumOccurrencesFlag()) {
1091 if (Opt.second->getNumOccurrences() == 0) {
1092 Opt.second->error("must be specified at least once!");
1093 ErrorParsing = true;
1101 // Now that we know if -debug is specified, we can use it.
1102 // Note that if ReadResponseFiles == true, this must be done before the
1103 // memory allocated for the expanded command line is free()d below.
1104 DEBUG(dbgs() << "Args: ";
1105 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1108 // Free all of the memory allocated to the map. Command line options may only
1109 // be processed once!
1112 // If we had an error processing our arguments, don't let the program execute
1117 //===----------------------------------------------------------------------===//
1118 // Option Base class implementation
1121 bool Option::error(const Twine &Message, StringRef ArgName) {
1122 if (!ArgName.data())
1124 if (ArgName.empty())
1125 errs() << HelpStr; // Be nice for positional arguments
1127 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1129 errs() << " option: " << Message << "\n";
1133 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1136 NumOccurrences++; // Increment the number of times we have been seen
1138 switch (getNumOccurrencesFlag()) {
1140 if (NumOccurrences > 1)
1141 return error("may only occur zero or one times!", ArgName);
1144 if (NumOccurrences > 1)
1145 return error("must occur exactly one time!", ArgName);
1153 return handleOccurrence(pos, ArgName, Value);
1156 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1157 // has been specified yet.
1159 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1160 if (O.ValueStr[0] == 0)
1165 //===----------------------------------------------------------------------===//
1166 // cl::alias class implementation
1169 // Return the width of the option tag for printing...
1170 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1172 static void printHelpStr(StringRef HelpStr, size_t Indent,
1173 size_t FirstLineIndentedBy) {
1174 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1175 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1176 while (!Split.second.empty()) {
1177 Split = Split.second.split('\n');
1178 outs().indent(Indent) << Split.first << "\n";
1182 // Print out the option for the alias.
1183 void alias::printOptionInfo(size_t GlobalWidth) const {
1184 outs() << " -" << ArgStr;
1185 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1188 //===----------------------------------------------------------------------===//
1189 // Parser Implementation code...
1192 // basic_parser implementation
1195 // Return the width of the option tag for printing...
1196 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1197 size_t Len = std::strlen(O.ArgStr);
1198 if (const char *ValName = getValueName())
1199 Len += std::strlen(getValueStr(O, ValName)) + 3;
1204 // printOptionInfo - Print out information about this option. The
1205 // to-be-maintained width is specified.
1207 void basic_parser_impl::printOptionInfo(const Option &O,
1208 size_t GlobalWidth) const {
1209 outs() << " -" << O.ArgStr;
1211 if (const char *ValName = getValueName())
1212 outs() << "=<" << getValueStr(O, ValName) << '>';
1214 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1217 void basic_parser_impl::printOptionName(const Option &O,
1218 size_t GlobalWidth) const {
1219 outs() << " -" << O.ArgStr;
1220 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1223 // parser<bool> implementation
1225 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1227 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1233 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1237 return O.error("'" + Arg +
1238 "' is invalid value for boolean argument! Try 0 or 1");
1241 // parser<boolOrDefault> implementation
1243 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1244 boolOrDefault &Value) {
1245 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1250 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1255 return O.error("'" + Arg +
1256 "' is invalid value for boolean argument! Try 0 or 1");
1259 // parser<int> implementation
1261 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1263 if (Arg.getAsInteger(0, Value))
1264 return O.error("'" + Arg + "' value invalid for integer argument!");
1268 // parser<unsigned> implementation
1270 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1273 if (Arg.getAsInteger(0, Value))
1274 return O.error("'" + Arg + "' value invalid for uint argument!");
1278 // parser<unsigned long long> implementation
1280 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1282 unsigned long long &Value) {
1284 if (Arg.getAsInteger(0, Value))
1285 return O.error("'" + Arg + "' value invalid for uint argument!");
1289 // parser<double>/parser<float> implementation
1291 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1292 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1293 const char *ArgStart = TmpStr.c_str();
1295 Value = strtod(ArgStart, &End);
1297 return O.error("'" + Arg + "' value invalid for floating point argument!");
1301 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1303 return parseDouble(O, Arg, Val);
1306 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1309 if (parseDouble(O, Arg, dVal))
1315 // generic_parser_base implementation
1318 // findOption - Return the option number corresponding to the specified
1319 // argument string. If the option is not found, getNumOptions() is returned.
1321 unsigned generic_parser_base::findOption(const char *Name) {
1322 unsigned e = getNumOptions();
1324 for (unsigned i = 0; i != e; ++i) {
1325 if (strcmp(getOption(i), Name) == 0)
1331 // Return the width of the option tag for printing...
1332 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1333 if (O.hasArgStr()) {
1334 size_t Size = std::strlen(O.ArgStr) + 6;
1335 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1336 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1339 size_t BaseSize = 0;
1340 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1341 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1346 // printOptionInfo - Print out information about this option. The
1347 // to-be-maintained width is specified.
1349 void generic_parser_base::printOptionInfo(const Option &O,
1350 size_t GlobalWidth) const {
1351 if (O.hasArgStr()) {
1352 outs() << " -" << O.ArgStr;
1353 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1355 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1356 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1357 outs() << " =" << getOption(i);
1358 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1362 outs() << " " << O.HelpStr << '\n';
1363 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1364 const char *Option = getOption(i);
1365 outs() << " -" << Option;
1366 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1371 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1373 // printGenericOptionDiff - Print the value of this option and it's default.
1375 // "Generic" options have each value mapped to a name.
1376 void generic_parser_base::printGenericOptionDiff(
1377 const Option &O, const GenericOptionValue &Value,
1378 const GenericOptionValue &Default, size_t GlobalWidth) const {
1379 outs() << " -" << O.ArgStr;
1380 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1382 unsigned NumOpts = getNumOptions();
1383 for (unsigned i = 0; i != NumOpts; ++i) {
1384 if (Value.compare(getOptionValue(i)))
1387 outs() << "= " << getOption(i);
1388 size_t L = std::strlen(getOption(i));
1389 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1390 outs().indent(NumSpaces) << " (default: ";
1391 for (unsigned j = 0; j != NumOpts; ++j) {
1392 if (Default.compare(getOptionValue(j)))
1394 outs() << getOption(j);
1400 outs() << "= *unknown option value*\n";
1403 // printOptionDiff - Specializations for printing basic value types.
1405 #define PRINT_OPT_DIFF(T) \
1406 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1407 size_t GlobalWidth) const { \
1408 printOptionName(O, GlobalWidth); \
1411 raw_string_ostream SS(Str); \
1414 outs() << "= " << Str; \
1415 size_t NumSpaces = \
1416 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1417 outs().indent(NumSpaces) << " (default: "; \
1419 outs() << D.getValue(); \
1421 outs() << "*no default*"; \
1425 PRINT_OPT_DIFF(bool)
1426 PRINT_OPT_DIFF(boolOrDefault)
1428 PRINT_OPT_DIFF(unsigned)
1429 PRINT_OPT_DIFF(unsigned long long)
1430 PRINT_OPT_DIFF(double)
1431 PRINT_OPT_DIFF(float)
1432 PRINT_OPT_DIFF(char)
1434 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1435 OptionValue<std::string> D,
1436 size_t GlobalWidth) const {
1437 printOptionName(O, GlobalWidth);
1438 outs() << "= " << V;
1439 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1440 outs().indent(NumSpaces) << " (default: ";
1442 outs() << D.getValue();
1444 outs() << "*no default*";
1448 // Print a placeholder for options that don't yet support printOptionDiff().
1449 void basic_parser_impl::printOptionNoValue(const Option &O,
1450 size_t GlobalWidth) const {
1451 printOptionName(O, GlobalWidth);
1452 outs() << "= *cannot print option value*\n";
1455 //===----------------------------------------------------------------------===//
1456 // -help and -help-hidden option implementation
1459 static int OptNameCompare(const void *LHS, const void *RHS) {
1460 typedef std::pair<const char *, Option *> pair_ty;
1462 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1465 // Copy Options into a vector so we can sort them as we like.
1466 static void sortOpts(StringMap<Option *> &OptMap,
1467 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1469 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1471 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1473 // Ignore really-hidden options.
1474 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1477 // Unless showhidden is set, ignore hidden flags.
1478 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1481 // If we've already seen this option, don't add it to the list again.
1482 if (!OptionSet.insert(I->second).second)
1486 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1489 // Sort the options list alphabetically.
1490 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1497 const bool ShowHidden;
1498 typedef SmallVector<std::pair<const char *, Option *>, 128>
1499 StrOptionPairVector;
1500 // Print the options. Opts is assumed to be alphabetically sorted.
1501 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1502 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1503 Opts[i].second->printOptionInfo(MaxArgLen);
1507 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1508 virtual ~HelpPrinter() {}
1510 // Invoke the printer.
1511 void operator=(bool Value) {
1515 StrOptionPairVector Opts;
1516 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1518 if (GlobalParser->ProgramOverview)
1519 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1521 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1523 for (auto Opt : GlobalParser->PositionalOpts) {
1525 outs() << " --" << Opt->ArgStr;
1526 outs() << " " << Opt->HelpStr;
1529 // Print the consume after option info if it exists...
1530 if (GlobalParser->ConsumeAfterOpt)
1531 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1535 // Compute the maximum argument length...
1536 size_t MaxArgLen = 0;
1537 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1538 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1540 outs() << "OPTIONS:\n";
1541 printOptions(Opts, MaxArgLen);
1543 // Print any extra help the user has declared.
1544 for (auto I : GlobalParser->MoreHelp)
1546 GlobalParser->MoreHelp.clear();
1548 // Halt the program since help information was printed
1553 class CategorizedHelpPrinter : public HelpPrinter {
1555 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1557 // Helper function for printOptions().
1558 // It shall return true if A's name should be lexographically
1559 // ordered before B's name. It returns false otherwise.
1560 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1561 return strcmp(A->getName(), B->getName()) < 0;
1564 // Make sure we inherit our base class's operator=()
1565 using HelpPrinter::operator=;
1568 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1569 std::vector<OptionCategory *> SortedCategories;
1570 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1572 // Collect registered option categories into vector in preparation for
1574 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1575 E = RegisteredOptionCategories->end();
1577 SortedCategories.push_back(*I);
1580 // Sort the different option categories alphabetically.
1581 assert(SortedCategories.size() > 0 && "No option categories registered!");
1582 std::sort(SortedCategories.begin(), SortedCategories.end(),
1583 OptionCategoryCompare);
1585 // Create map to empty vectors.
1586 for (std::vector<OptionCategory *>::const_iterator
1587 I = SortedCategories.begin(),
1588 E = SortedCategories.end();
1590 CategorizedOptions[*I] = std::vector<Option *>();
1592 // Walk through pre-sorted options and assign into categories.
1593 // Because the options are already alphabetically sorted the
1594 // options within categories will also be alphabetically sorted.
1595 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1596 Option *Opt = Opts[I].second;
1597 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1598 "Option has an unregistered category");
1599 CategorizedOptions[Opt->Category].push_back(Opt);
1603 for (std::vector<OptionCategory *>::const_iterator
1604 Category = SortedCategories.begin(),
1605 E = SortedCategories.end();
1606 Category != E; ++Category) {
1607 // Hide empty categories for -help, but show for -help-hidden.
1608 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1609 if (!ShowHidden && IsEmptyCategory)
1612 // Print category information.
1614 outs() << (*Category)->getName() << ":\n";
1616 // Check if description is set.
1617 if ((*Category)->getDescription() != nullptr)
1618 outs() << (*Category)->getDescription() << "\n\n";
1622 // When using -help-hidden explicitly state if the category has no
1623 // options associated with it.
1624 if (IsEmptyCategory) {
1625 outs() << " This option category has no options.\n";
1628 // Loop over the options in the category and print.
1629 for (std::vector<Option *>::const_iterator
1630 Opt = CategorizedOptions[*Category].begin(),
1631 E = CategorizedOptions[*Category].end();
1633 (*Opt)->printOptionInfo(MaxArgLen);
1638 // This wraps the Uncategorizing and Categorizing printers and decides
1639 // at run time which should be invoked.
1640 class HelpPrinterWrapper {
1642 HelpPrinter &UncategorizedPrinter;
1643 CategorizedHelpPrinter &CategorizedPrinter;
1646 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1647 CategorizedHelpPrinter &CategorizedPrinter)
1648 : UncategorizedPrinter(UncategorizedPrinter),
1649 CategorizedPrinter(CategorizedPrinter) {}
1651 // Invoke the printer.
1652 void operator=(bool Value);
1655 } // End anonymous namespace
1657 // Declare the four HelpPrinter instances that are used to print out help, or
1658 // help-hidden as an uncategorized list or in categories.
1659 static HelpPrinter UncategorizedNormalPrinter(false);
1660 static HelpPrinter UncategorizedHiddenPrinter(true);
1661 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1662 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1664 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1665 // a categorizing help printer
1666 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1667 CategorizedNormalPrinter);
1668 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1669 CategorizedHiddenPrinter);
1671 // Define a category for generic options that all tools should have.
1672 static cl::OptionCategory GenericCategory("Generic Options");
1674 // Define uncategorized help printers.
1675 // -help-list is hidden by default because if Option categories are being used
1676 // then -help behaves the same as -help-list.
1677 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1679 cl::desc("Display list of available options (-help-list-hidden for more)"),
1680 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1681 cl::cat(GenericCategory));
1683 static cl::opt<HelpPrinter, true, parser<bool>>
1684 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1685 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1686 cl::ValueDisallowed, cl::cat(GenericCategory));
1688 // Define uncategorized/categorized help printers. These printers change their
1689 // behaviour at runtime depending on whether one or more Option categories have
1691 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1692 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1693 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1694 cl::cat(GenericCategory));
1696 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1697 HHOp("help-hidden", cl::desc("Display all available options"),
1698 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1699 cl::cat(GenericCategory));
1701 static cl::opt<bool> PrintOptions(
1703 cl::desc("Print non-default options after command line parsing"),
1704 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1706 static cl::opt<bool> PrintAllOptions(
1707 "print-all-options",
1708 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1709 cl::init(false), cl::cat(GenericCategory));
1711 void HelpPrinterWrapper::operator=(bool Value) {
1715 // Decide which printer to invoke. If more than one option category is
1716 // registered then it is useful to show the categorized help instead of
1717 // uncategorized help.
1718 if (RegisteredOptionCategories->size() > 1) {
1719 // unhide -help-list option so user can have uncategorized output if they
1721 HLOp.setHiddenFlag(NotHidden);
1723 CategorizedPrinter = true; // Invoke categorized printer
1725 UncategorizedPrinter = true; // Invoke uncategorized printer
1728 // Print the value of each option.
1729 void cl::PrintOptionValues() {
1730 if (!PrintOptions && !PrintAllOptions)
1733 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1734 sortOpts(GlobalParser->OptionsMap, Opts, /*ShowHidden*/ true);
1736 // Compute the maximum argument length...
1737 size_t MaxArgLen = 0;
1738 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1739 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1741 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1745 static void (*OverrideVersionPrinter)() = nullptr;
1747 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1750 class VersionPrinter {
1753 raw_ostream &OS = outs();
1754 OS << "LLVM (http://llvm.org/):\n"
1755 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1756 #ifdef LLVM_VERSION_INFO
1757 OS << " " << LLVM_VERSION_INFO;
1760 #ifndef __OPTIMIZE__
1761 OS << "DEBUG build";
1763 OS << "Optimized build";
1766 OS << " with assertions";
1768 std::string CPU = sys::getHostCPUName();
1769 if (CPU == "generic")
1772 #if (ENABLE_TIMESTAMPS == 1)
1773 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1775 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1776 << " Host CPU: " << CPU << '\n';
1778 void operator=(bool OptionWasSpecified) {
1779 if (!OptionWasSpecified)
1782 if (OverrideVersionPrinter != nullptr) {
1783 (*OverrideVersionPrinter)();
1788 // Iterate over any registered extra printers and call them to add further
1790 if (ExtraVersionPrinters != nullptr) {
1792 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1793 E = ExtraVersionPrinters->end();
1801 } // End anonymous namespace
1803 // Define the --version option that prints out the LLVM version for the tool
1804 static VersionPrinter VersionPrinterInstance;
1806 static cl::opt<VersionPrinter, true, parser<bool>>
1807 VersOp("version", cl::desc("Display the version of this program"),
1808 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1809 cl::cat(GenericCategory));
1811 // Utility function for printing the help message.
1812 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1813 // This looks weird, but it actually prints the help message. The Printers are
1814 // types of HelpPrinter and the help gets printed when its operator= is
1815 // invoked. That's because the "normal" usages of the help printer is to be
1816 // assigned true/false depending on whether -help or -help-hidden was given or
1817 // not. Since we're circumventing that we have to make it look like -help or
1818 // -help-hidden were given, so we assign true.
1820 if (!Hidden && !Categorized)
1821 UncategorizedNormalPrinter = true;
1822 else if (!Hidden && Categorized)
1823 CategorizedNormalPrinter = true;
1824 else if (Hidden && !Categorized)
1825 UncategorizedHiddenPrinter = true;
1827 CategorizedHiddenPrinter = true;
1830 /// Utility function for printing version number.
1831 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1833 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1835 void cl::AddExtraVersionPrinter(void (*func)()) {
1836 if (!ExtraVersionPrinters)
1837 ExtraVersionPrinters = new std::vector<void (*)()>;
1839 ExtraVersionPrinters->push_back(func);
1842 StringMap<Option *> &cl::getRegisteredOptions() {
1843 return GlobalParser->OptionsMap;
1846 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1847 for (auto &I : GlobalParser->OptionsMap) {
1848 if (I.second->Category != &Category &&
1849 I.second->Category != &GenericCategory)
1850 I.second->setHiddenFlag(cl::ReallyHidden);
1854 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1855 auto CategoriesBegin = Categories.begin();
1856 auto CategoriesEnd = Categories.end();
1857 for (auto &I : GlobalParser->OptionsMap) {
1858 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1860 I.second->Category != &GenericCategory)
1861 I.second->setHiddenFlag(cl::ReallyHidden);
1865 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1866 const char *Overview) {
1867 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);