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 std::string ProgramName;
91 const char *ProgramOverview;
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; // The ConsumeAfter option if it exists.
102 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
104 void ParseCommandLineOptions(int argc, const char *const *argv,
105 const char *Overview);
107 void addLiteralOption(Option &Opt, const char *Name) {
108 if (!Opt.hasArgStr()) {
109 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
110 errs() << ProgramName << ": CommandLine Error: Option '" << Name
111 << "' registered more than once!\n";
112 report_fatal_error("inconsistency in registered CommandLine options");
117 void addOption(Option *O) {
118 bool HadErrors = false;
120 // Add argument to the argument map!
121 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
122 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
123 << "' registered more than once!\n";
128 // Remember information about positional options.
129 if (O->getFormattingFlag() == cl::Positional)
130 PositionalOpts.push_back(O);
131 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
132 SinkOpts.push_back(O);
133 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
134 if (ConsumeAfterOpt) {
135 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
141 // Fail hard if there were errors. These are strictly unrecoverable and
142 // indicate serious issues such as conflicting option names or an
144 // linked LLVM distribution.
146 report_fatal_error("inconsistency in registered CommandLine options");
149 void removeOption(Option *O) {
150 SmallVector<const char *, 16> OptionNames;
151 O->getExtraOptionNames(OptionNames);
153 OptionNames.push_back(O->ArgStr);
154 for (auto Name : OptionNames)
155 OptionsMap.erase(StringRef(Name));
157 if (O->getFormattingFlag() == cl::Positional)
158 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
161 PositionalOpts.erase(Opt);
165 else if (O->getMiscFlags() & cl::Sink)
166 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
172 else if (O == ConsumeAfterOpt)
173 ConsumeAfterOpt = nullptr;
177 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
178 nullptr != ConsumeAfterOpt);
181 void updateArgStr(Option *O, const char* NewName) {
182 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
183 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
184 << "' registered more than once!\n";
185 report_fatal_error("inconsistency in registered CommandLine options");
187 OptionsMap.erase(StringRef(O->ArgStr));
191 static ManagedStatic<CommandLineParser> GlobalParser;
193 void cl::AddLiteralOption(Option &O, const char *Name) {
194 GlobalParser->addLiteralOption(O, Name);
197 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
198 GlobalParser->MoreHelp.push_back(Help);
201 void Option::addArgument() {
202 GlobalParser->addOption(this);
203 FullyInitialized = true;
206 void Option::removeArgument() { GlobalParser->removeOption(this); }
208 void Option::setArgStr(const char *S) {
209 if (FullyInitialized)
210 GlobalParser->updateArgStr(this, S);
214 // This collects the different option categories that have been registered.
215 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
216 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
218 // Initialise the general option category.
219 OptionCategory llvm::cl::GeneralCategory("General options");
221 void OptionCategory::registerCategory() {
222 assert(std::count_if(RegisteredOptionCategories->begin(),
223 RegisteredOptionCategories->end(),
224 [this](const OptionCategory *Category) {
225 return getName() == Category->getName();
227 "Duplicate option categories");
229 RegisteredOptionCategories->insert(this);
232 //===----------------------------------------------------------------------===//
233 // Basic, shared command line option processing machinery.
236 /// LookupOption - Lookup the option specified by the specified option on the
237 /// command line. If there is a value specified (after an equal sign) return
238 /// that as well. This assumes that leading dashes have already been stripped.
239 static Option *LookupOption(StringRef &Arg, StringRef &Value,
240 const StringMap<Option *> &OptionsMap) {
241 // Reject all dashes.
245 size_t EqualPos = Arg.find('=');
247 // If we have an equals sign, remember the value.
248 if (EqualPos == StringRef::npos) {
249 // Look up the option.
250 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
251 return I != OptionsMap.end() ? I->second : nullptr;
254 // If the argument before the = is a valid option name, we match. If not,
255 // return Arg unmolested.
256 StringMap<Option *>::const_iterator I =
257 OptionsMap.find(Arg.substr(0, EqualPos));
258 if (I == OptionsMap.end())
261 Value = Arg.substr(EqualPos + 1);
262 Arg = Arg.substr(0, EqualPos);
266 /// LookupNearestOption - Lookup the closest match to the option specified by
267 /// the specified option on the command line. If there is a value specified
268 /// (after an equal sign) return that as well. This assumes that leading dashes
269 /// have already been stripped.
270 static Option *LookupNearestOption(StringRef Arg,
271 const StringMap<Option *> &OptionsMap,
272 std::string &NearestString) {
273 // Reject all dashes.
277 // Split on any equal sign.
278 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
279 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
280 StringRef &RHS = SplitArg.second;
282 // Find the closest match.
283 Option *Best = nullptr;
284 unsigned BestDistance = 0;
285 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
286 ie = OptionsMap.end();
288 Option *O = it->second;
289 SmallVector<const char *, 16> OptionNames;
290 O->getExtraOptionNames(OptionNames);
292 OptionNames.push_back(O->ArgStr);
294 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
295 StringRef Flag = PermitValue ? LHS : Arg;
296 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
297 StringRef Name = OptionNames[i];
298 unsigned Distance = StringRef(Name).edit_distance(
299 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
300 if (!Best || Distance < BestDistance) {
302 BestDistance = Distance;
303 if (RHS.empty() || !PermitValue)
304 NearestString = OptionNames[i];
306 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
314 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
315 /// that does special handling of cl::CommaSeparated options.
316 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
317 StringRef ArgName, StringRef Value,
318 bool MultiArg = false) {
319 // Check to see if this option accepts a comma separated list of values. If
320 // it does, we have to split up the value into multiple values.
321 if (Handler->getMiscFlags() & CommaSeparated) {
322 StringRef Val(Value);
323 StringRef::size_type Pos = Val.find(',');
325 while (Pos != StringRef::npos) {
326 // Process the portion before the comma.
327 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
329 // Erase the portion before the comma, AND the comma.
330 Val = Val.substr(Pos + 1);
331 Value.substr(Pos + 1); // Increment the original value pointer as well.
332 // Check for another comma.
339 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
345 /// ProvideOption - For Value, this differentiates between an empty value ("")
346 /// and a null value (StringRef()). The later is accepted for arguments that
347 /// don't allow a value (-foo) the former is rejected (-foo=).
348 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
349 StringRef Value, int argc,
350 const char *const *argv, int &i) {
351 // Is this a multi-argument option?
352 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
354 // Enforce value requirements
355 switch (Handler->getValueExpectedFlag()) {
357 if (!Value.data()) { // No value specified?
359 return Handler->error("requires a value!");
360 // Steal the next argument, like for '-o filename'
361 assert(argv && "null check");
365 case ValueDisallowed:
366 if (NumAdditionalVals > 0)
367 return Handler->error("multi-valued option specified"
368 " with ValueDisallowed modifier!");
371 return Handler->error("does not allow a value! '" + Twine(Value) +
378 // If this isn't a multi-arg option, just run the handler.
379 if (NumAdditionalVals == 0)
380 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
382 // If it is, run the handle several times.
383 bool MultiArg = false;
386 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
392 while (NumAdditionalVals > 0) {
394 return Handler->error("not enough values!");
395 assert(argv && "null check");
398 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
406 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
408 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
411 // Option predicates...
412 static inline bool isGrouping(const Option *O) {
413 return O->getFormattingFlag() == cl::Grouping;
415 static inline bool isPrefixedOrGrouping(const Option *O) {
416 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
419 // getOptionPred - Check to see if there are any options that satisfy the
420 // specified predicate with names that are the prefixes in Name. This is
421 // checked by progressively stripping characters off of the name, checking to
422 // see if there options that satisfy the predicate. If we find one, return it,
423 // otherwise return null.
425 static Option *getOptionPred(StringRef Name, size_t &Length,
426 bool (*Pred)(const Option *),
427 const StringMap<Option *> &OptionsMap) {
429 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
431 // Loop while we haven't found an option and Name still has at least two
432 // characters in it (so that the next iteration will not be the empty
434 while (OMI == OptionsMap.end() && Name.size() > 1) {
435 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
436 OMI = OptionsMap.find(Name);
439 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
440 Length = Name.size();
441 return OMI->second; // Found one!
443 return nullptr; // No option found!
446 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
447 /// with at least one '-') does not fully match an available option. Check to
448 /// see if this is a prefix or grouped option. If so, split arg into output an
449 /// Arg/Value pair and return the Option to parse it with.
451 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
453 const StringMap<Option *> &OptionsMap) {
459 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
463 // If the option is a prefixed option, then the value is simply the
464 // rest of the name... so fall through to later processing, by
465 // setting up the argument name flags and value fields.
466 if (PGOpt->getFormattingFlag() == cl::Prefix) {
467 Value = Arg.substr(Length);
468 Arg = Arg.substr(0, Length);
469 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
473 // This must be a grouped option... handle them now. Grouping options can't
475 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
478 // Move current arg name out of Arg into OneArgName.
479 StringRef OneArgName = Arg.substr(0, Length);
480 Arg = Arg.substr(Length);
482 // Because ValueRequired is an invalid flag for grouped arguments,
483 // we don't need to pass argc/argv in.
484 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
485 "Option can not be cl::Grouping AND cl::ValueRequired!");
488 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
490 // Get the next grouping option.
491 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
492 } while (PGOpt && Length != Arg.size());
494 // Return the last option with Arg cut down to just the last one.
498 static bool RequiresValue(const Option *O) {
499 return O->getNumOccurrencesFlag() == cl::Required ||
500 O->getNumOccurrencesFlag() == cl::OneOrMore;
503 static bool EatsUnboundedNumberOfValues(const Option *O) {
504 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
505 O->getNumOccurrencesFlag() == cl::OneOrMore;
508 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
510 static bool isQuote(char C) { return C == '\"' || C == '\''; }
512 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
514 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
515 SmallVectorImpl<const char *> &NewArgv,
517 SmallString<128> Token;
518 for (size_t I = 0, E = Src.size(); I != E; ++I) {
519 // Consume runs of whitespace.
521 while (I != E && isWhitespace(Src[I])) {
522 // Mark the end of lines in response files
523 if (MarkEOLs && Src[I] == '\n')
524 NewArgv.push_back(nullptr);
531 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
532 // they are literal. This makes it much easier to read Windows file paths.
533 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
534 ++I; // Skip the escape.
535 Token.push_back(Src[I]);
539 // Consume a quoted string.
540 if (isQuote(Src[I])) {
541 char Quote = Src[I++];
542 while (I != E && Src[I] != Quote) {
543 // Backslashes are literal, unless they escape a special character.
544 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
546 Token.push_back(Src[I]);
554 // End the token if this is whitespace.
555 if (isWhitespace(Src[I])) {
557 NewArgv.push_back(Saver.SaveString(Token.c_str()));
562 // This is a normal character. Append it.
563 Token.push_back(Src[I]);
566 // Append the last token after hitting EOF with no whitespace.
568 NewArgv.push_back(Saver.SaveString(Token.c_str()));
569 // Mark the end of response files
571 NewArgv.push_back(nullptr);
574 /// Backslashes are interpreted in a rather complicated way in the Windows-style
575 /// command line, because backslashes are used both to separate path and to
576 /// escape double quote. This method consumes runs of backslashes as well as the
577 /// following double quote if it's escaped.
579 /// * If an even number of backslashes is followed by a double quote, one
580 /// backslash is output for every pair of backslashes, and the last double
581 /// quote remains unconsumed. The double quote will later be interpreted as
582 /// the start or end of a quoted string in the main loop outside of this
585 /// * If an odd number of backslashes is followed by a double quote, one
586 /// backslash is output for every pair of backslashes, and a double quote is
587 /// output for the last pair of backslash-double quote. The double quote is
588 /// consumed in this case.
590 /// * Otherwise, backslashes are interpreted literally.
591 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
592 size_t E = Src.size();
593 int BackslashCount = 0;
594 // Skip the backslashes.
598 } while (I != E && Src[I] == '\\');
600 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
601 if (FollowedByDoubleQuote) {
602 Token.append(BackslashCount / 2, '\\');
603 if (BackslashCount % 2 == 0)
605 Token.push_back('"');
608 Token.append(BackslashCount, '\\');
612 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
613 SmallVectorImpl<const char *> &NewArgv,
615 SmallString<128> Token;
617 // This is a small state machine to consume characters until it reaches the
618 // end of the source string.
619 enum { INIT, UNQUOTED, QUOTED } State = INIT;
620 for (size_t I = 0, E = Src.size(); I != E; ++I) {
621 // INIT state indicates that the current input index is at the start of
622 // the string or between tokens.
624 if (isWhitespace(Src[I])) {
625 // Mark the end of lines in response files
626 if (MarkEOLs && Src[I] == '\n')
627 NewArgv.push_back(nullptr);
634 if (Src[I] == '\\') {
635 I = parseBackslash(Src, I, Token);
639 Token.push_back(Src[I]);
644 // UNQUOTED state means that it's reading a token not quoted by double
646 if (State == UNQUOTED) {
647 // Whitespace means the end of the token.
648 if (isWhitespace(Src[I])) {
649 NewArgv.push_back(Saver.SaveString(Token.c_str()));
652 // Mark the end of lines in response files
653 if (MarkEOLs && Src[I] == '\n')
654 NewArgv.push_back(nullptr);
661 if (Src[I] == '\\') {
662 I = parseBackslash(Src, I, Token);
665 Token.push_back(Src[I]);
669 // QUOTED state means that it's reading a token quoted by double quotes.
670 if (State == QUOTED) {
675 if (Src[I] == '\\') {
676 I = parseBackslash(Src, I, Token);
679 Token.push_back(Src[I]);
682 // Append the last token after hitting EOF with no whitespace.
684 NewArgv.push_back(Saver.SaveString(Token.c_str()));
685 // Mark the end of response files
687 NewArgv.push_back(nullptr);
690 // It is called byte order marker but the UTF-8 BOM is actually not affected
691 // by the host system's endianness.
692 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
693 return (S.size() >= 3 &&
694 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
697 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
698 TokenizerCallback Tokenizer,
699 SmallVectorImpl<const char *> &NewArgv,
700 bool MarkEOLs = false) {
701 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
702 MemoryBuffer::getFile(FName);
705 MemoryBuffer &MemBuf = *MemBufOrErr.get();
706 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
708 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
709 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
711 if (hasUTF16ByteOrderMark(BufRef)) {
712 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
714 Str = StringRef(UTF8Buf);
716 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
717 // these bytes before parsing.
718 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
719 else if (hasUTF8ByteOrderMark(BufRef))
720 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
722 // Tokenize the contents into NewArgv.
723 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
728 /// \brief Expand response files on a command line recursively using the given
729 /// StringSaver and tokenization strategy.
730 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
731 SmallVectorImpl<const char *> &Argv,
733 unsigned RspFiles = 0;
734 bool AllExpanded = true;
736 // Don't cache Argv.size() because it can change.
737 for (unsigned I = 0; I != Argv.size();) {
738 const char *Arg = Argv[I];
739 // Check if it is an EOL marker
740 if (Arg == nullptr) {
749 // If we have too many response files, leave some unexpanded. This avoids
750 // crashing on self-referential response files.
754 // Replace this response file argument with the tokenization of its
755 // contents. Nested response files are expanded in subsequent iterations.
756 // FIXME: If a nested response file uses a relative path, is it relative to
757 // the cwd of the process or the response file?
758 SmallVector<const char *, 0> ExpandedArgv;
759 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
761 // We couldn't read this file, so we leave it in the argument stream and
767 Argv.erase(Argv.begin() + I);
768 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
774 class StrDupSaver : public StringSaver {
775 std::vector<char *> Dups;
779 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
785 const char *SaveString(const char *Str) override {
786 char *Dup = strdup(Str);
793 /// ParseEnvironmentOptions - An alternative entry point to the
794 /// CommandLine library, which allows you to read the program's name
795 /// from the caller (as PROGNAME) and its command-line arguments from
796 /// an environment variable (whose name is given in ENVVAR).
798 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
799 const char *Overview) {
801 assert(progName && "Program name not specified");
802 assert(envVar && "Environment variable name missing");
804 // Get the environment variable they want us to parse options out of.
805 const char *envValue = getenv(envVar);
809 // Get program's "name", which we wouldn't know without the caller
811 SmallVector<const char *, 20> newArgv;
813 newArgv.push_back(Saver.SaveString(progName));
815 // Parse the value of the environment variable into a "command line"
816 // and hand it off to ParseCommandLineOptions().
817 TokenizeGNUCommandLine(envValue, Saver, newArgv);
818 int newArgc = static_cast<int>(newArgv.size());
819 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
822 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
823 const char *Overview) {
824 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
827 void CommandLineParser::ParseCommandLineOptions(int argc,
828 const char *const *argv,
829 const char *Overview) {
830 assert(hasOptions() && "No options specified!");
832 // Expand response files.
833 SmallVector<const char *, 20> newArgv;
834 for (int i = 0; i != argc; ++i)
835 newArgv.push_back(argv[i]);
837 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
839 argc = static_cast<int>(newArgv.size());
841 // Copy the program name into ProgName, making sure not to overflow it.
842 ProgramName = sys::path::filename(argv[0]);
844 ProgramOverview = Overview;
845 bool ErrorParsing = false;
847 // Check out the positional arguments to collect information about them.
848 unsigned NumPositionalRequired = 0;
850 // Determine whether or not there are an unlimited number of positionals
851 bool HasUnlimitedPositionals = false;
853 if (ConsumeAfterOpt) {
854 assert(PositionalOpts.size() > 0 &&
855 "Cannot specify cl::ConsumeAfter without a positional argument!");
857 if (!PositionalOpts.empty()) {
859 // Calculate how many positional values are _required_.
860 bool UnboundedFound = false;
861 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
862 Option *Opt = PositionalOpts[i];
863 if (RequiresValue(Opt))
864 ++NumPositionalRequired;
865 else if (ConsumeAfterOpt) {
866 // ConsumeAfter cannot be combined with "optional" positional options
867 // unless there is only one positional argument...
868 if (PositionalOpts.size() > 1)
869 ErrorParsing |= Opt->error(
870 "error - this positional option will never be matched, "
871 "because it does not Require a value, and a "
872 "cl::ConsumeAfter option is active!");
873 } else if (UnboundedFound && !Opt->ArgStr[0]) {
874 // This option does not "require" a value... Make sure this option is
875 // not specified after an option that eats all extra arguments, or this
876 // one will never get any!
878 ErrorParsing |= Opt->error("error - option can never match, because "
879 "another positional argument will match an "
880 "unbounded number of values, and this option"
881 " does not require a value!");
882 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
883 << "' is all messed up!\n";
884 errs() << PositionalOpts.size();
886 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
888 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
891 // PositionalVals - A vector of "positional" arguments we accumulate into
892 // the process at the end.
894 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
896 // If the program has named positional arguments, and the name has been run
897 // across, keep track of which positional argument was named. Otherwise put
898 // the positional args into the PositionalVals list...
899 Option *ActivePositionalArg = nullptr;
901 // Loop over all of the arguments... processing them.
902 bool DashDashFound = false; // Have we read '--'?
903 for (int i = 1; i < argc; ++i) {
904 Option *Handler = nullptr;
905 Option *NearestHandler = nullptr;
906 std::string NearestHandlerString;
908 StringRef ArgName = "";
910 // Check to see if this is a positional argument. This argument is
911 // considered to be positional if it doesn't start with '-', if it is "-"
912 // itself, or if we have seen "--" already.
914 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
915 // Positional argument!
916 if (ActivePositionalArg) {
917 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
918 continue; // We are done!
921 if (!PositionalOpts.empty()) {
922 PositionalVals.push_back(std::make_pair(argv[i], i));
924 // All of the positional arguments have been fulfulled, give the rest to
925 // the consume after option... if it's specified...
927 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
928 for (++i; i < argc; ++i)
929 PositionalVals.push_back(std::make_pair(argv[i], i));
930 break; // Handle outside of the argument processing loop...
933 // Delay processing positional arguments until the end...
936 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
938 DashDashFound = true; // This is the mythical "--"?
939 continue; // Don't try to process it as an argument itself.
940 } else if (ActivePositionalArg &&
941 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
942 // If there is a positional argument eating options, check to see if this
943 // option is another positional argument. If so, treat it as an argument,
944 // otherwise feed it to the eating positional.
945 ArgName = argv[i] + 1;
946 // Eat leading dashes.
947 while (!ArgName.empty() && ArgName[0] == '-')
948 ArgName = ArgName.substr(1);
950 Handler = LookupOption(ArgName, Value, OptionsMap);
951 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
952 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
953 continue; // We are done!
956 } else { // We start with a '-', must be an argument.
957 ArgName = argv[i] + 1;
958 // Eat leading dashes.
959 while (!ArgName.empty() && ArgName[0] == '-')
960 ArgName = ArgName.substr(1);
962 Handler = LookupOption(ArgName, Value, OptionsMap);
964 // Check to see if this "option" is really a prefixed or grouped argument.
966 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
969 // Otherwise, look for the closest available option to report to the user
970 // in the upcoming error.
971 if (!Handler && SinkOpts.empty())
973 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
977 if (SinkOpts.empty()) {
978 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
979 << "'. Try: '" << argv[0] << " -help'\n";
981 if (NearestHandler) {
982 // If we know a near match, report it as well.
983 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
989 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
992 (*I)->addOccurrence(i, "", argv[i]);
997 // If this is a named positional argument, just remember that it is the
999 if (Handler->getFormattingFlag() == cl::Positional)
1000 ActivePositionalArg = Handler;
1002 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1005 // Check and handle positional arguments now...
1006 if (NumPositionalRequired > PositionalVals.size()) {
1007 errs() << ProgramName
1008 << ": Not enough positional command line arguments specified!\n"
1009 << "Must specify at least " << NumPositionalRequired
1010 << " positional arguments: See: " << argv[0] << " -help\n";
1012 ErrorParsing = true;
1013 } else if (!HasUnlimitedPositionals &&
1014 PositionalVals.size() > PositionalOpts.size()) {
1015 errs() << ProgramName << ": Too many positional arguments specified!\n"
1016 << "Can specify at most " << PositionalOpts.size()
1017 << " positional arguments: See: " << argv[0] << " -help\n";
1018 ErrorParsing = true;
1020 } else if (!ConsumeAfterOpt) {
1021 // Positional args have already been handled if ConsumeAfter is specified.
1022 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1023 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1024 if (RequiresValue(PositionalOpts[i])) {
1025 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1026 PositionalVals[ValNo].second);
1028 --NumPositionalRequired; // We fulfilled our duty...
1031 // If we _can_ give this option more arguments, do so now, as long as we
1032 // do not give it values that others need. 'Done' controls whether the
1033 // option even _WANTS_ any more.
1035 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1036 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1037 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1039 Done = true; // Optional arguments want _at most_ one value
1041 case cl::ZeroOrMore: // Zero or more will take all they can get...
1042 case cl::OneOrMore: // One or more will take all they can get...
1043 ProvidePositionalOption(PositionalOpts[i],
1044 PositionalVals[ValNo].first,
1045 PositionalVals[ValNo].second);
1049 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1050 "positional argument processing!");
1055 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1057 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1058 if (RequiresValue(PositionalOpts[j])) {
1059 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1060 PositionalVals[ValNo].first,
1061 PositionalVals[ValNo].second);
1065 // Handle the case where there is just one positional option, and it's
1066 // optional. In this case, we want to give JUST THE FIRST option to the
1067 // positional option and keep the rest for the consume after. The above
1068 // loop would have assigned no values to positional options in this case.
1070 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1071 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1072 PositionalVals[ValNo].first,
1073 PositionalVals[ValNo].second);
1077 // Handle over all of the rest of the arguments to the
1078 // cl::ConsumeAfter command line option...
1079 for (; ValNo != PositionalVals.size(); ++ValNo)
1081 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1082 PositionalVals[ValNo].second);
1085 // Loop over args and make sure all required args are specified!
1086 for (const auto &Opt : OptionsMap) {
1087 switch (Opt.second->getNumOccurrencesFlag()) {
1090 if (Opt.second->getNumOccurrences() == 0) {
1091 Opt.second->error("must be specified at least once!");
1092 ErrorParsing = true;
1100 // Now that we know if -debug is specified, we can use it.
1101 // Note that if ReadResponseFiles == true, this must be done before the
1102 // memory allocated for the expanded command line is free()d below.
1103 DEBUG(dbgs() << "Args: ";
1104 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1107 // Free all of the memory allocated to the map. Command line options may only
1108 // be processed once!
1111 // If we had an error processing our arguments, don't let the program execute
1116 //===----------------------------------------------------------------------===//
1117 // Option Base class implementation
1120 bool Option::error(const Twine &Message, StringRef ArgName) {
1121 if (!ArgName.data())
1123 if (ArgName.empty())
1124 errs() << HelpStr; // Be nice for positional arguments
1126 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1128 errs() << " option: " << Message << "\n";
1132 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1135 NumOccurrences++; // Increment the number of times we have been seen
1137 switch (getNumOccurrencesFlag()) {
1139 if (NumOccurrences > 1)
1140 return error("may only occur zero or one times!", ArgName);
1143 if (NumOccurrences > 1)
1144 return error("must occur exactly one time!", ArgName);
1152 return handleOccurrence(pos, ArgName, Value);
1155 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1156 // has been specified yet.
1158 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1159 if (O.ValueStr[0] == 0)
1164 //===----------------------------------------------------------------------===//
1165 // cl::alias class implementation
1168 // Return the width of the option tag for printing...
1169 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1171 static void printHelpStr(StringRef HelpStr, size_t Indent,
1172 size_t FirstLineIndentedBy) {
1173 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1174 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1175 while (!Split.second.empty()) {
1176 Split = Split.second.split('\n');
1177 outs().indent(Indent) << Split.first << "\n";
1181 // Print out the option for the alias.
1182 void alias::printOptionInfo(size_t GlobalWidth) const {
1183 outs() << " -" << ArgStr;
1184 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1187 //===----------------------------------------------------------------------===//
1188 // Parser Implementation code...
1191 // basic_parser implementation
1194 // Return the width of the option tag for printing...
1195 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1196 size_t Len = std::strlen(O.ArgStr);
1197 if (const char *ValName = getValueName())
1198 Len += std::strlen(getValueStr(O, ValName)) + 3;
1203 // printOptionInfo - Print out information about this option. The
1204 // to-be-maintained width is specified.
1206 void basic_parser_impl::printOptionInfo(const Option &O,
1207 size_t GlobalWidth) const {
1208 outs() << " -" << O.ArgStr;
1210 if (const char *ValName = getValueName())
1211 outs() << "=<" << getValueStr(O, ValName) << '>';
1213 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1216 void basic_parser_impl::printOptionName(const Option &O,
1217 size_t GlobalWidth) const {
1218 outs() << " -" << O.ArgStr;
1219 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1222 // parser<bool> implementation
1224 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1226 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1232 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1236 return O.error("'" + Arg +
1237 "' is invalid value for boolean argument! Try 0 or 1");
1240 // parser<boolOrDefault> implementation
1242 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1243 boolOrDefault &Value) {
1244 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1249 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1254 return O.error("'" + Arg +
1255 "' is invalid value for boolean argument! Try 0 or 1");
1258 // parser<int> implementation
1260 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1262 if (Arg.getAsInteger(0, Value))
1263 return O.error("'" + Arg + "' value invalid for integer argument!");
1267 // parser<unsigned> implementation
1269 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1272 if (Arg.getAsInteger(0, Value))
1273 return O.error("'" + Arg + "' value invalid for uint argument!");
1277 // parser<unsigned long long> implementation
1279 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1281 unsigned long long &Value) {
1283 if (Arg.getAsInteger(0, Value))
1284 return O.error("'" + Arg + "' value invalid for uint argument!");
1288 // parser<double>/parser<float> implementation
1290 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1291 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1292 const char *ArgStart = TmpStr.c_str();
1294 Value = strtod(ArgStart, &End);
1296 return O.error("'" + Arg + "' value invalid for floating point argument!");
1300 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1302 return parseDouble(O, Arg, Val);
1305 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1308 if (parseDouble(O, Arg, dVal))
1314 // generic_parser_base implementation
1317 // findOption - Return the option number corresponding to the specified
1318 // argument string. If the option is not found, getNumOptions() is returned.
1320 unsigned generic_parser_base::findOption(const char *Name) {
1321 unsigned e = getNumOptions();
1323 for (unsigned i = 0; i != e; ++i) {
1324 if (strcmp(getOption(i), Name) == 0)
1330 // Return the width of the option tag for printing...
1331 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1332 if (O.hasArgStr()) {
1333 size_t Size = std::strlen(O.ArgStr) + 6;
1334 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1335 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1338 size_t BaseSize = 0;
1339 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1340 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1345 // printOptionInfo - Print out information about this option. The
1346 // to-be-maintained width is specified.
1348 void generic_parser_base::printOptionInfo(const Option &O,
1349 size_t GlobalWidth) const {
1350 if (O.hasArgStr()) {
1351 outs() << " -" << O.ArgStr;
1352 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1354 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1355 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1356 outs() << " =" << getOption(i);
1357 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1361 outs() << " " << O.HelpStr << '\n';
1362 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1363 const char *Option = getOption(i);
1364 outs() << " -" << Option;
1365 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1370 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1372 // printGenericOptionDiff - Print the value of this option and it's default.
1374 // "Generic" options have each value mapped to a name.
1375 void generic_parser_base::printGenericOptionDiff(
1376 const Option &O, const GenericOptionValue &Value,
1377 const GenericOptionValue &Default, size_t GlobalWidth) const {
1378 outs() << " -" << O.ArgStr;
1379 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1381 unsigned NumOpts = getNumOptions();
1382 for (unsigned i = 0; i != NumOpts; ++i) {
1383 if (Value.compare(getOptionValue(i)))
1386 outs() << "= " << getOption(i);
1387 size_t L = std::strlen(getOption(i));
1388 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1389 outs().indent(NumSpaces) << " (default: ";
1390 for (unsigned j = 0; j != NumOpts; ++j) {
1391 if (Default.compare(getOptionValue(j)))
1393 outs() << getOption(j);
1399 outs() << "= *unknown option value*\n";
1402 // printOptionDiff - Specializations for printing basic value types.
1404 #define PRINT_OPT_DIFF(T) \
1405 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1406 size_t GlobalWidth) const { \
1407 printOptionName(O, GlobalWidth); \
1410 raw_string_ostream SS(Str); \
1413 outs() << "= " << Str; \
1414 size_t NumSpaces = \
1415 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1416 outs().indent(NumSpaces) << " (default: "; \
1418 outs() << D.getValue(); \
1420 outs() << "*no default*"; \
1424 PRINT_OPT_DIFF(bool)
1425 PRINT_OPT_DIFF(boolOrDefault)
1427 PRINT_OPT_DIFF(unsigned)
1428 PRINT_OPT_DIFF(unsigned long long)
1429 PRINT_OPT_DIFF(double)
1430 PRINT_OPT_DIFF(float)
1431 PRINT_OPT_DIFF(char)
1433 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1434 OptionValue<std::string> D,
1435 size_t GlobalWidth) const {
1436 printOptionName(O, GlobalWidth);
1437 outs() << "= " << V;
1438 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1439 outs().indent(NumSpaces) << " (default: ";
1441 outs() << D.getValue();
1443 outs() << "*no default*";
1447 // Print a placeholder for options that don't yet support printOptionDiff().
1448 void basic_parser_impl::printOptionNoValue(const Option &O,
1449 size_t GlobalWidth) const {
1450 printOptionName(O, GlobalWidth);
1451 outs() << "= *cannot print option value*\n";
1454 //===----------------------------------------------------------------------===//
1455 // -help and -help-hidden option implementation
1458 static int OptNameCompare(const void *LHS, const void *RHS) {
1459 typedef std::pair<const char *, Option *> pair_ty;
1461 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1464 // Copy Options into a vector so we can sort them as we like.
1465 static void sortOpts(StringMap<Option *> &OptMap,
1466 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1468 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1470 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1472 // Ignore really-hidden options.
1473 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1476 // Unless showhidden is set, ignore hidden flags.
1477 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1480 // If we've already seen this option, don't add it to the list again.
1481 if (!OptionSet.insert(I->second).second)
1485 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1488 // Sort the options list alphabetically.
1489 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1496 const bool ShowHidden;
1497 typedef SmallVector<std::pair<const char *, Option *>, 128>
1498 StrOptionPairVector;
1499 // Print the options. Opts is assumed to be alphabetically sorted.
1500 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1501 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1502 Opts[i].second->printOptionInfo(MaxArgLen);
1506 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1507 virtual ~HelpPrinter() {}
1509 // Invoke the printer.
1510 void operator=(bool Value) {
1514 StrOptionPairVector Opts;
1515 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1517 if (GlobalParser->ProgramOverview)
1518 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1520 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1522 for (auto Opt : GlobalParser->PositionalOpts) {
1524 outs() << " --" << Opt->ArgStr;
1525 outs() << " " << Opt->HelpStr;
1528 // Print the consume after option info if it exists...
1529 if (GlobalParser->ConsumeAfterOpt)
1530 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1534 // Compute the maximum argument length...
1535 size_t MaxArgLen = 0;
1536 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1537 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1539 outs() << "OPTIONS:\n";
1540 printOptions(Opts, MaxArgLen);
1542 // Print any extra help the user has declared.
1543 for (auto I : GlobalParser->MoreHelp)
1545 GlobalParser->MoreHelp.clear();
1547 // Halt the program since help information was printed
1552 class CategorizedHelpPrinter : public HelpPrinter {
1554 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1556 // Helper function for printOptions().
1557 // It shall return true if A's name should be lexographically
1558 // ordered before B's name. It returns false otherwise.
1559 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1560 return strcmp(A->getName(), B->getName()) < 0;
1563 // Make sure we inherit our base class's operator=()
1564 using HelpPrinter::operator=;
1567 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1568 std::vector<OptionCategory *> SortedCategories;
1569 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1571 // Collect registered option categories into vector in preparation for
1573 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1574 E = RegisteredOptionCategories->end();
1576 SortedCategories.push_back(*I);
1579 // Sort the different option categories alphabetically.
1580 assert(SortedCategories.size() > 0 && "No option categories registered!");
1581 std::sort(SortedCategories.begin(), SortedCategories.end(),
1582 OptionCategoryCompare);
1584 // Create map to empty vectors.
1585 for (std::vector<OptionCategory *>::const_iterator
1586 I = SortedCategories.begin(),
1587 E = SortedCategories.end();
1589 CategorizedOptions[*I] = std::vector<Option *>();
1591 // Walk through pre-sorted options and assign into categories.
1592 // Because the options are already alphabetically sorted the
1593 // options within categories will also be alphabetically sorted.
1594 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1595 Option *Opt = Opts[I].second;
1596 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1597 "Option has an unregistered category");
1598 CategorizedOptions[Opt->Category].push_back(Opt);
1602 for (std::vector<OptionCategory *>::const_iterator
1603 Category = SortedCategories.begin(),
1604 E = SortedCategories.end();
1605 Category != E; ++Category) {
1606 // Hide empty categories for -help, but show for -help-hidden.
1607 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1608 if (!ShowHidden && IsEmptyCategory)
1611 // Print category information.
1613 outs() << (*Category)->getName() << ":\n";
1615 // Check if description is set.
1616 if ((*Category)->getDescription() != nullptr)
1617 outs() << (*Category)->getDescription() << "\n\n";
1621 // When using -help-hidden explicitly state if the category has no
1622 // options associated with it.
1623 if (IsEmptyCategory) {
1624 outs() << " This option category has no options.\n";
1627 // Loop over the options in the category and print.
1628 for (std::vector<Option *>::const_iterator
1629 Opt = CategorizedOptions[*Category].begin(),
1630 E = CategorizedOptions[*Category].end();
1632 (*Opt)->printOptionInfo(MaxArgLen);
1637 // This wraps the Uncategorizing and Categorizing printers and decides
1638 // at run time which should be invoked.
1639 class HelpPrinterWrapper {
1641 HelpPrinter &UncategorizedPrinter;
1642 CategorizedHelpPrinter &CategorizedPrinter;
1645 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1646 CategorizedHelpPrinter &CategorizedPrinter)
1647 : UncategorizedPrinter(UncategorizedPrinter),
1648 CategorizedPrinter(CategorizedPrinter) {}
1650 // Invoke the printer.
1651 void operator=(bool Value);
1654 } // End anonymous namespace
1656 // Declare the four HelpPrinter instances that are used to print out help, or
1657 // help-hidden as an uncategorized list or in categories.
1658 static HelpPrinter UncategorizedNormalPrinter(false);
1659 static HelpPrinter UncategorizedHiddenPrinter(true);
1660 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1661 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1663 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1664 // a categorizing help printer
1665 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1666 CategorizedNormalPrinter);
1667 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1668 CategorizedHiddenPrinter);
1670 // Define a category for generic options that all tools should have.
1671 static cl::OptionCategory GenericCategory("Generic Options");
1673 // Define uncategorized help printers.
1674 // -help-list is hidden by default because if Option categories are being used
1675 // then -help behaves the same as -help-list.
1676 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1678 cl::desc("Display list of available options (-help-list-hidden for more)"),
1679 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1680 cl::cat(GenericCategory));
1682 static cl::opt<HelpPrinter, true, parser<bool>>
1683 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1684 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1685 cl::ValueDisallowed, cl::cat(GenericCategory));
1687 // Define uncategorized/categorized help printers. These printers change their
1688 // behaviour at runtime depending on whether one or more Option categories have
1690 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1691 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1692 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1693 cl::cat(GenericCategory));
1695 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1696 HHOp("help-hidden", cl::desc("Display all available options"),
1697 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1698 cl::cat(GenericCategory));
1700 static cl::opt<bool> PrintOptions(
1702 cl::desc("Print non-default options after command line parsing"),
1703 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1705 static cl::opt<bool> PrintAllOptions(
1706 "print-all-options",
1707 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1708 cl::init(false), cl::cat(GenericCategory));
1710 void HelpPrinterWrapper::operator=(bool Value) {
1714 // Decide which printer to invoke. If more than one option category is
1715 // registered then it is useful to show the categorized help instead of
1716 // uncategorized help.
1717 if (RegisteredOptionCategories->size() > 1) {
1718 // unhide -help-list option so user can have uncategorized output if they
1720 HLOp.setHiddenFlag(NotHidden);
1722 CategorizedPrinter = true; // Invoke categorized printer
1724 UncategorizedPrinter = true; // Invoke uncategorized printer
1727 // Print the value of each option.
1728 void cl::PrintOptionValues() {
1729 if (!PrintOptions && !PrintAllOptions)
1732 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1733 sortOpts(GlobalParser->OptionsMap, Opts, /*ShowHidden*/ true);
1735 // Compute the maximum argument length...
1736 size_t MaxArgLen = 0;
1737 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1738 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1740 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1741 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1744 static void (*OverrideVersionPrinter)() = nullptr;
1746 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1749 class VersionPrinter {
1752 raw_ostream &OS = outs();
1753 OS << "LLVM (http://llvm.org/):\n"
1754 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1755 #ifdef LLVM_VERSION_INFO
1756 OS << " " << LLVM_VERSION_INFO;
1759 #ifndef __OPTIMIZE__
1760 OS << "DEBUG build";
1762 OS << "Optimized build";
1765 OS << " with assertions";
1767 std::string CPU = sys::getHostCPUName();
1768 if (CPU == "generic")
1771 #if (ENABLE_TIMESTAMPS == 1)
1772 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1774 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1775 << " Host CPU: " << CPU << '\n';
1777 void operator=(bool OptionWasSpecified) {
1778 if (!OptionWasSpecified)
1781 if (OverrideVersionPrinter != nullptr) {
1782 (*OverrideVersionPrinter)();
1787 // Iterate over any registered extra printers and call them to add further
1789 if (ExtraVersionPrinters != nullptr) {
1791 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1792 E = ExtraVersionPrinters->end();
1800 } // End anonymous namespace
1802 // Define the --version option that prints out the LLVM version for the tool
1803 static VersionPrinter VersionPrinterInstance;
1805 static cl::opt<VersionPrinter, true, parser<bool>>
1806 VersOp("version", cl::desc("Display the version of this program"),
1807 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1808 cl::cat(GenericCategory));
1810 // Utility function for printing the help message.
1811 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1812 // This looks weird, but it actually prints the help message. The Printers are
1813 // types of HelpPrinter and the help gets printed when its operator= is
1814 // invoked. That's because the "normal" usages of the help printer is to be
1815 // assigned true/false depending on whether -help or -help-hidden was given or
1816 // not. Since we're circumventing that we have to make it look like -help or
1817 // -help-hidden were given, so we assign true.
1819 if (!Hidden && !Categorized)
1820 UncategorizedNormalPrinter = true;
1821 else if (!Hidden && Categorized)
1822 CategorizedNormalPrinter = true;
1823 else if (Hidden && !Categorized)
1824 UncategorizedHiddenPrinter = true;
1826 CategorizedHiddenPrinter = true;
1829 /// Utility function for printing version number.
1830 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1832 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1834 void cl::AddExtraVersionPrinter(void (*func)()) {
1835 if (!ExtraVersionPrinters)
1836 ExtraVersionPrinters = new std::vector<void (*)()>;
1838 ExtraVersionPrinters->push_back(func);
1841 StringMap<Option *> &cl::getRegisteredOptions() {
1842 return GlobalParser->OptionsMap;
1845 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1846 for (auto &I : GlobalParser->OptionsMap) {
1847 if (I.second->Category != &Category &&
1848 I.second->Category != &GenericCategory)
1849 I.second->setHiddenFlag(cl::ReallyHidden);
1853 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1854 auto CategoriesBegin = Categories.begin();
1855 auto CategoriesEnd = Categories.end();
1856 for (auto &I : GlobalParser->OptionsMap) {
1857 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1859 I.second->Category != &GenericCategory)
1860 I.second->setHiddenFlag(cl::ReallyHidden);
1864 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1865 const char *Overview) {
1866 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);