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/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/config.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/StringSaver.h"
36 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "commandline"
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
49 template class basic_parser<bool>;
50 template class basic_parser<boolOrDefault>;
51 template class basic_parser<int>;
52 template class basic_parser<unsigned>;
53 template class basic_parser<unsigned long long>;
54 template class basic_parser<double>;
55 template class basic_parser<float>;
56 template class basic_parser<std::string>;
57 template class basic_parser<char>;
59 template class opt<unsigned>;
60 template class opt<int>;
61 template class opt<std::string>;
62 template class opt<char>;
63 template 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() {}
83 //===----------------------------------------------------------------------===//
87 class CommandLineParser {
89 // Globals for name and overview of program. Program name is not a string to
90 // avoid static ctor/dtor issues.
91 std::string ProgramName;
92 const char *ProgramOverview;
94 // This collects additional help to be printed.
95 std::vector<const char *> MoreHelp;
97 SmallVector<Option *, 4> PositionalOpts;
98 SmallVector<Option *, 4> SinkOpts;
99 StringMap<Option *> OptionsMap;
101 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
103 // This collects the different option categories that have been registered.
104 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
106 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
108 void ParseCommandLineOptions(int argc, const char *const *argv,
109 const char *Overview);
111 void addLiteralOption(Option &Opt, const char *Name) {
112 if (!Opt.hasArgStr()) {
113 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
114 errs() << ProgramName << ": CommandLine Error: Option '" << Name
115 << "' registered more than once!\n";
116 report_fatal_error("inconsistency in registered CommandLine options");
121 void addOption(Option *O) {
122 bool HadErrors = false;
123 if (O->hasArgStr()) {
124 // Add argument to the argument map!
125 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
126 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
127 << "' registered more than once!\n";
132 // Remember information about positional options.
133 if (O->getFormattingFlag() == cl::Positional)
134 PositionalOpts.push_back(O);
135 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
136 SinkOpts.push_back(O);
137 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
138 if (ConsumeAfterOpt) {
139 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
145 // Fail hard if there were errors. These are strictly unrecoverable and
146 // indicate serious issues such as conflicting option names or an
148 // linked LLVM distribution.
150 report_fatal_error("inconsistency in registered CommandLine options");
153 void removeOption(Option *O) {
154 SmallVector<StringRef, 16> OptionNames;
155 O->getExtraOptionNames(OptionNames);
157 OptionNames.push_back(O->ArgStr);
158 for (auto Name : OptionNames)
159 OptionsMap.erase(Name);
161 if (O->getFormattingFlag() == cl::Positional)
162 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
165 PositionalOpts.erase(Opt);
169 else if (O->getMiscFlags() & cl::Sink)
170 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
176 else if (O == ConsumeAfterOpt)
177 ConsumeAfterOpt = nullptr;
181 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
182 nullptr != ConsumeAfterOpt);
185 void updateArgStr(Option *O, StringRef NewName) {
186 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
187 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
188 << "' registered more than once!\n";
189 report_fatal_error("inconsistency in registered CommandLine options");
191 OptionsMap.erase(O->ArgStr);
194 void printOptionValues();
196 void registerCategory(OptionCategory *cat) {
197 assert(std::count_if(RegisteredOptionCategories.begin(),
198 RegisteredOptionCategories.end(),
199 [cat](const OptionCategory *Category) {
200 return cat->getName() == Category->getName();
202 "Duplicate option categories");
204 RegisteredOptionCategories.insert(cat);
208 Option *LookupOption(StringRef &Arg, StringRef &Value);
213 static ManagedStatic<CommandLineParser> GlobalParser;
215 void cl::AddLiteralOption(Option &O, const char *Name) {
216 GlobalParser->addLiteralOption(O, Name);
219 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
220 GlobalParser->MoreHelp.push_back(Help);
223 void Option::addArgument() {
224 GlobalParser->addOption(this);
225 FullyInitialized = true;
228 void Option::removeArgument() { GlobalParser->removeOption(this); }
230 void Option::setArgStr(StringRef S) {
231 if (FullyInitialized)
232 GlobalParser->updateArgStr(this, S);
236 // Initialise the general option category.
237 OptionCategory llvm::cl::GeneralCategory("General options");
239 void OptionCategory::registerCategory() {
240 GlobalParser->registerCategory(this);
243 //===----------------------------------------------------------------------===//
244 // Basic, shared command line option processing machinery.
247 /// LookupOption - Lookup the option specified by the specified option on the
248 /// command line. If there is a value specified (after an equal sign) return
249 /// that as well. This assumes that leading dashes have already been stripped.
250 Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
251 // Reject all dashes.
255 size_t EqualPos = Arg.find('=');
257 // If we have an equals sign, remember the value.
258 if (EqualPos == StringRef::npos) {
259 // Look up the option.
260 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
261 return I != OptionsMap.end() ? I->second : nullptr;
264 // If the argument before the = is a valid option name, we match. If not,
265 // return Arg unmolested.
266 StringMap<Option *>::const_iterator I =
267 OptionsMap.find(Arg.substr(0, EqualPos));
268 if (I == OptionsMap.end())
271 Value = Arg.substr(EqualPos + 1);
272 Arg = Arg.substr(0, EqualPos);
276 /// LookupNearestOption - Lookup the closest match to the option specified by
277 /// the specified option on the command line. If there is a value specified
278 /// (after an equal sign) return that as well. This assumes that leading dashes
279 /// have already been stripped.
280 static Option *LookupNearestOption(StringRef Arg,
281 const StringMap<Option *> &OptionsMap,
282 std::string &NearestString) {
283 // Reject all dashes.
287 // Split on any equal sign.
288 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
289 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
290 StringRef &RHS = SplitArg.second;
292 // Find the closest match.
293 Option *Best = nullptr;
294 unsigned BestDistance = 0;
295 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
296 ie = OptionsMap.end();
298 Option *O = it->second;
299 SmallVector<StringRef, 16> OptionNames;
300 O->getExtraOptionNames(OptionNames);
302 OptionNames.push_back(O->ArgStr);
304 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
305 StringRef Flag = PermitValue ? LHS : Arg;
306 for (auto Name : OptionNames) {
307 unsigned Distance = StringRef(Name).edit_distance(
308 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
309 if (!Best || Distance < BestDistance) {
311 BestDistance = Distance;
312 if (RHS.empty() || !PermitValue)
313 NearestString = Name;
315 NearestString = (Twine(Name) + "=" + RHS).str();
323 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
324 /// that does special handling of cl::CommaSeparated options.
325 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
326 StringRef ArgName, StringRef Value,
327 bool MultiArg = false) {
328 // Check to see if this option accepts a comma separated list of values. If
329 // it does, we have to split up the value into multiple values.
330 if (Handler->getMiscFlags() & CommaSeparated) {
331 StringRef Val(Value);
332 StringRef::size_type Pos = Val.find(',');
334 while (Pos != StringRef::npos) {
335 // Process the portion before the comma.
336 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
338 // Erase the portion before the comma, AND the comma.
339 Val = Val.substr(Pos + 1);
340 Value.substr(Pos + 1); // Increment the original value pointer as well.
341 // Check for another comma.
348 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
351 /// ProvideOption - For Value, this differentiates between an empty value ("")
352 /// and a null value (StringRef()). The later is accepted for arguments that
353 /// don't allow a value (-foo) the former is rejected (-foo=).
354 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
355 StringRef Value, int argc,
356 const char *const *argv, int &i) {
357 // Is this a multi-argument option?
358 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
360 // Enforce value requirements
361 switch (Handler->getValueExpectedFlag()) {
363 if (!Value.data()) { // No value specified?
365 return Handler->error("requires a value!");
366 // Steal the next argument, like for '-o filename'
367 assert(argv && "null check");
371 case ValueDisallowed:
372 if (NumAdditionalVals > 0)
373 return Handler->error("multi-valued option specified"
374 " with ValueDisallowed modifier!");
377 return Handler->error("does not allow a value! '" + Twine(Value) +
384 // If this isn't a multi-arg option, just run the handler.
385 if (NumAdditionalVals == 0)
386 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
388 // If it is, run the handle several times.
389 bool MultiArg = false;
392 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
398 while (NumAdditionalVals > 0) {
400 return Handler->error("not enough values!");
401 assert(argv && "null check");
404 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
412 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
414 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
417 // Option predicates...
418 static inline bool isGrouping(const Option *O) {
419 return O->getFormattingFlag() == cl::Grouping;
421 static inline bool isPrefixedOrGrouping(const Option *O) {
422 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
425 // getOptionPred - Check to see if there are any options that satisfy the
426 // specified predicate with names that are the prefixes in Name. This is
427 // checked by progressively stripping characters off of the name, checking to
428 // see if there options that satisfy the predicate. If we find one, return it,
429 // otherwise return null.
431 static Option *getOptionPred(StringRef Name, size_t &Length,
432 bool (*Pred)(const Option *),
433 const StringMap<Option *> &OptionsMap) {
435 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
437 // Loop while we haven't found an option and Name still has at least two
438 // characters in it (so that the next iteration will not be the empty
440 while (OMI == OptionsMap.end() && Name.size() > 1) {
441 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
442 OMI = OptionsMap.find(Name);
445 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
446 Length = Name.size();
447 return OMI->second; // Found one!
449 return nullptr; // No option found!
452 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
453 /// with at least one '-') does not fully match an available option. Check to
454 /// see if this is a prefix or grouped option. If so, split arg into output an
455 /// Arg/Value pair and return the Option to parse it with.
457 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
459 const StringMap<Option *> &OptionsMap) {
465 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
469 // If the option is a prefixed option, then the value is simply the
470 // rest of the name... so fall through to later processing, by
471 // setting up the argument name flags and value fields.
472 if (PGOpt->getFormattingFlag() == cl::Prefix) {
473 Value = Arg.substr(Length);
474 Arg = Arg.substr(0, Length);
475 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
479 // This must be a grouped option... handle them now. Grouping options can't
481 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
484 // Move current arg name out of Arg into OneArgName.
485 StringRef OneArgName = Arg.substr(0, Length);
486 Arg = Arg.substr(Length);
488 // Because ValueRequired is an invalid flag for grouped arguments,
489 // we don't need to pass argc/argv in.
490 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
491 "Option can not be cl::Grouping AND cl::ValueRequired!");
494 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
496 // Get the next grouping option.
497 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
498 } while (PGOpt && Length != Arg.size());
500 // Return the last option with Arg cut down to just the last one.
504 static bool RequiresValue(const Option *O) {
505 return O->getNumOccurrencesFlag() == cl::Required ||
506 O->getNumOccurrencesFlag() == cl::OneOrMore;
509 static bool EatsUnboundedNumberOfValues(const Option *O) {
510 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
511 O->getNumOccurrencesFlag() == cl::OneOrMore;
514 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
516 static bool isQuote(char C) { return C == '\"' || C == '\''; }
518 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
520 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
521 SmallVectorImpl<const char *> &NewArgv,
523 SmallString<128> Token;
524 for (size_t I = 0, E = Src.size(); I != E; ++I) {
525 // Consume runs of whitespace.
527 while (I != E && isWhitespace(Src[I])) {
528 // Mark the end of lines in response files
529 if (MarkEOLs && Src[I] == '\n')
530 NewArgv.push_back(nullptr);
537 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
538 // they are literal. This makes it much easier to read Windows file paths.
539 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
540 ++I; // Skip the escape.
541 Token.push_back(Src[I]);
545 // Consume a quoted string.
546 if (isQuote(Src[I])) {
547 char Quote = Src[I++];
548 while (I != E && Src[I] != Quote) {
549 // Backslashes are literal, unless they escape a special character.
550 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
552 Token.push_back(Src[I]);
560 // End the token if this is whitespace.
561 if (isWhitespace(Src[I])) {
563 NewArgv.push_back(Saver.save(Token.c_str()));
568 // This is a normal character. Append it.
569 Token.push_back(Src[I]);
572 // Append the last token after hitting EOF with no whitespace.
574 NewArgv.push_back(Saver.save(Token.c_str()));
575 // Mark the end of response files
577 NewArgv.push_back(nullptr);
580 /// Backslashes are interpreted in a rather complicated way in the Windows-style
581 /// command line, because backslashes are used both to separate path and to
582 /// escape double quote. This method consumes runs of backslashes as well as the
583 /// following double quote if it's escaped.
585 /// * If an even number of backslashes is followed by a double quote, one
586 /// backslash is output for every pair of backslashes, and the last double
587 /// quote remains unconsumed. The double quote will later be interpreted as
588 /// the start or end of a quoted string in the main loop outside of this
591 /// * If an odd number of backslashes is followed by a double quote, one
592 /// backslash is output for every pair of backslashes, and a double quote is
593 /// output for the last pair of backslash-double quote. The double quote is
594 /// consumed in this case.
596 /// * Otherwise, backslashes are interpreted literally.
597 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
598 size_t E = Src.size();
599 int BackslashCount = 0;
600 // Skip the backslashes.
604 } while (I != E && Src[I] == '\\');
606 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
607 if (FollowedByDoubleQuote) {
608 Token.append(BackslashCount / 2, '\\');
609 if (BackslashCount % 2 == 0)
611 Token.push_back('"');
614 Token.append(BackslashCount, '\\');
618 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
619 SmallVectorImpl<const char *> &NewArgv,
621 SmallString<128> Token;
623 // This is a small state machine to consume characters until it reaches the
624 // end of the source string.
625 enum { INIT, UNQUOTED, QUOTED } State = INIT;
626 for (size_t I = 0, E = Src.size(); I != E; ++I) {
627 // INIT state indicates that the current input index is at the start of
628 // the string or between tokens.
630 if (isWhitespace(Src[I])) {
631 // Mark the end of lines in response files
632 if (MarkEOLs && Src[I] == '\n')
633 NewArgv.push_back(nullptr);
640 if (Src[I] == '\\') {
641 I = parseBackslash(Src, I, Token);
645 Token.push_back(Src[I]);
650 // UNQUOTED state means that it's reading a token not quoted by double
652 if (State == UNQUOTED) {
653 // Whitespace means the end of the token.
654 if (isWhitespace(Src[I])) {
655 NewArgv.push_back(Saver.save(Token.c_str()));
658 // Mark the end of lines in response files
659 if (MarkEOLs && Src[I] == '\n')
660 NewArgv.push_back(nullptr);
667 if (Src[I] == '\\') {
668 I = parseBackslash(Src, I, Token);
671 Token.push_back(Src[I]);
675 // QUOTED state means that it's reading a token quoted by double quotes.
676 if (State == QUOTED) {
681 if (Src[I] == '\\') {
682 I = parseBackslash(Src, I, Token);
685 Token.push_back(Src[I]);
688 // Append the last token after hitting EOF with no whitespace.
690 NewArgv.push_back(Saver.save(Token.c_str()));
691 // Mark the end of response files
693 NewArgv.push_back(nullptr);
696 // It is called byte order marker but the UTF-8 BOM is actually not affected
697 // by the host system's endianness.
698 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
699 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
702 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
703 TokenizerCallback Tokenizer,
704 SmallVectorImpl<const char *> &NewArgv,
705 bool MarkEOLs = false) {
706 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
707 MemoryBuffer::getFile(FName);
710 MemoryBuffer &MemBuf = *MemBufOrErr.get();
711 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
713 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
714 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
716 if (hasUTF16ByteOrderMark(BufRef)) {
717 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
719 Str = StringRef(UTF8Buf);
721 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
722 // these bytes before parsing.
723 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
724 else if (hasUTF8ByteOrderMark(BufRef))
725 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
727 // Tokenize the contents into NewArgv.
728 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
733 /// \brief Expand response files on a command line recursively using the given
734 /// StringSaver and tokenization strategy.
735 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
736 SmallVectorImpl<const char *> &Argv,
738 unsigned RspFiles = 0;
739 bool AllExpanded = true;
741 // Don't cache Argv.size() because it can change.
742 for (unsigned I = 0; I != Argv.size();) {
743 const char *Arg = Argv[I];
744 // Check if it is an EOL marker
745 if (Arg == nullptr) {
754 // If we have too many response files, leave some unexpanded. This avoids
755 // crashing on self-referential response files.
759 // Replace this response file argument with the tokenization of its
760 // contents. Nested response files are expanded in subsequent iterations.
761 // FIXME: If a nested response file uses a relative path, is it relative to
762 // the cwd of the process or the response file?
763 SmallVector<const char *, 0> ExpandedArgv;
764 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
766 // We couldn't read this file, so we leave it in the argument stream and
772 Argv.erase(Argv.begin() + I);
773 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
778 /// ParseEnvironmentOptions - An alternative entry point to the
779 /// CommandLine library, which allows you to read the program's name
780 /// from the caller (as PROGNAME) and its command-line arguments from
781 /// an environment variable (whose name is given in ENVVAR).
783 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
784 const char *Overview) {
786 assert(progName && "Program name not specified");
787 assert(envVar && "Environment variable name missing");
789 // Get the environment variable they want us to parse options out of.
790 const char *envValue = getenv(envVar);
794 // Get program's "name", which we wouldn't know without the caller
796 SmallVector<const char *, 20> newArgv;
798 StringSaver Saver(A);
799 newArgv.push_back(Saver.save(progName));
801 // Parse the value of the environment variable into a "command line"
802 // and hand it off to ParseCommandLineOptions().
803 TokenizeGNUCommandLine(envValue, Saver, newArgv);
804 int newArgc = static_cast<int>(newArgv.size());
805 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
808 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
809 const char *Overview) {
810 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
813 void CommandLineParser::ParseCommandLineOptions(int argc,
814 const char *const *argv,
815 const char *Overview) {
816 assert(hasOptions() && "No options specified!");
818 // Expand response files.
819 SmallVector<const char *, 20> newArgv(argv, argv + argc);
821 StringSaver Saver(A);
822 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
824 argc = static_cast<int>(newArgv.size());
826 // Copy the program name into ProgName, making sure not to overflow it.
827 ProgramName = sys::path::filename(argv[0]);
829 ProgramOverview = Overview;
830 bool ErrorParsing = false;
832 // Check out the positional arguments to collect information about them.
833 unsigned NumPositionalRequired = 0;
835 // Determine whether or not there are an unlimited number of positionals
836 bool HasUnlimitedPositionals = false;
838 if (ConsumeAfterOpt) {
839 assert(PositionalOpts.size() > 0 &&
840 "Cannot specify cl::ConsumeAfter without a positional argument!");
842 if (!PositionalOpts.empty()) {
844 // Calculate how many positional values are _required_.
845 bool UnboundedFound = false;
846 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
847 Option *Opt = PositionalOpts[i];
848 if (RequiresValue(Opt))
849 ++NumPositionalRequired;
850 else if (ConsumeAfterOpt) {
851 // ConsumeAfter cannot be combined with "optional" positional options
852 // unless there is only one positional argument...
853 if (PositionalOpts.size() > 1)
854 ErrorParsing |= Opt->error(
855 "error - this positional option will never be matched, "
856 "because it does not Require a value, and a "
857 "cl::ConsumeAfter option is active!");
858 } else if (UnboundedFound && !Opt->hasArgStr()) {
859 // This option does not "require" a value... Make sure this option is
860 // not specified after an option that eats all extra arguments, or this
861 // one will never get any!
863 ErrorParsing |= Opt->error("error - option can never match, because "
864 "another positional argument will match an "
865 "unbounded number of values, and this option"
866 " does not require a value!");
867 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
868 << "' is all messed up!\n";
869 errs() << PositionalOpts.size();
871 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
873 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
876 // PositionalVals - A vector of "positional" arguments we accumulate into
877 // the process at the end.
879 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
881 // If the program has named positional arguments, and the name has been run
882 // across, keep track of which positional argument was named. Otherwise put
883 // the positional args into the PositionalVals list...
884 Option *ActivePositionalArg = nullptr;
886 // Loop over all of the arguments... processing them.
887 bool DashDashFound = false; // Have we read '--'?
888 for (int i = 1; i < argc; ++i) {
889 Option *Handler = nullptr;
890 Option *NearestHandler = nullptr;
891 std::string NearestHandlerString;
893 StringRef ArgName = "";
895 // Check to see if this is a positional argument. This argument is
896 // considered to be positional if it doesn't start with '-', if it is "-"
897 // itself, or if we have seen "--" already.
899 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
900 // Positional argument!
901 if (ActivePositionalArg) {
902 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
903 continue; // We are done!
906 if (!PositionalOpts.empty()) {
907 PositionalVals.push_back(std::make_pair(argv[i], i));
909 // All of the positional arguments have been fulfulled, give the rest to
910 // the consume after option... if it's specified...
912 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
913 for (++i; i < argc; ++i)
914 PositionalVals.push_back(std::make_pair(argv[i], i));
915 break; // Handle outside of the argument processing loop...
918 // Delay processing positional arguments until the end...
921 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
923 DashDashFound = true; // This is the mythical "--"?
924 continue; // Don't try to process it as an argument itself.
925 } else if (ActivePositionalArg &&
926 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
927 // If there is a positional argument eating options, check to see if this
928 // option is another positional argument. If so, treat it as an argument,
929 // otherwise feed it to the eating positional.
930 ArgName = argv[i] + 1;
931 // Eat leading dashes.
932 while (!ArgName.empty() && ArgName[0] == '-')
933 ArgName = ArgName.substr(1);
935 Handler = LookupOption(ArgName, Value);
936 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
937 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
938 continue; // We are done!
941 } else { // We start with a '-', must be an argument.
942 ArgName = argv[i] + 1;
943 // Eat leading dashes.
944 while (!ArgName.empty() && ArgName[0] == '-')
945 ArgName = ArgName.substr(1);
947 Handler = LookupOption(ArgName, Value);
949 // Check to see if this "option" is really a prefixed or grouped argument.
951 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
954 // Otherwise, look for the closest available option to report to the user
955 // in the upcoming error.
956 if (!Handler && SinkOpts.empty())
958 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
962 if (SinkOpts.empty()) {
963 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
964 << "'. Try: '" << argv[0] << " -help'\n";
966 if (NearestHandler) {
967 // If we know a near match, report it as well.
968 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
974 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
977 (*I)->addOccurrence(i, "", argv[i]);
982 // If this is a named positional argument, just remember that it is the
984 if (Handler->getFormattingFlag() == cl::Positional)
985 ActivePositionalArg = Handler;
987 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
990 // Check and handle positional arguments now...
991 if (NumPositionalRequired > PositionalVals.size()) {
992 errs() << ProgramName
993 << ": Not enough positional command line arguments specified!\n"
994 << "Must specify at least " << NumPositionalRequired
995 << " positional arguments: See: " << argv[0] << " -help\n";
998 } else if (!HasUnlimitedPositionals &&
999 PositionalVals.size() > PositionalOpts.size()) {
1000 errs() << ProgramName << ": Too many positional arguments specified!\n"
1001 << "Can specify at most " << PositionalOpts.size()
1002 << " positional arguments: See: " << argv[0] << " -help\n";
1003 ErrorParsing = true;
1005 } else if (!ConsumeAfterOpt) {
1006 // Positional args have already been handled if ConsumeAfter is specified.
1007 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1008 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1009 if (RequiresValue(PositionalOpts[i])) {
1010 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1011 PositionalVals[ValNo].second);
1013 --NumPositionalRequired; // We fulfilled our duty...
1016 // If we _can_ give this option more arguments, do so now, as long as we
1017 // do not give it values that others need. 'Done' controls whether the
1018 // option even _WANTS_ any more.
1020 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1021 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1022 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1024 Done = true; // Optional arguments want _at most_ one value
1026 case cl::ZeroOrMore: // Zero or more will take all they can get...
1027 case cl::OneOrMore: // One or more will take all they can get...
1028 ProvidePositionalOption(PositionalOpts[i],
1029 PositionalVals[ValNo].first,
1030 PositionalVals[ValNo].second);
1034 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1035 "positional argument processing!");
1040 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1042 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1043 if (RequiresValue(PositionalOpts[j])) {
1044 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1045 PositionalVals[ValNo].first,
1046 PositionalVals[ValNo].second);
1050 // Handle the case where there is just one positional option, and it's
1051 // optional. In this case, we want to give JUST THE FIRST option to the
1052 // positional option and keep the rest for the consume after. The above
1053 // loop would have assigned no values to positional options in this case.
1055 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1056 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1057 PositionalVals[ValNo].first,
1058 PositionalVals[ValNo].second);
1062 // Handle over all of the rest of the arguments to the
1063 // cl::ConsumeAfter command line option...
1064 for (; ValNo != PositionalVals.size(); ++ValNo)
1066 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1067 PositionalVals[ValNo].second);
1070 // Loop over args and make sure all required args are specified!
1071 for (const auto &Opt : OptionsMap) {
1072 switch (Opt.second->getNumOccurrencesFlag()) {
1075 if (Opt.second->getNumOccurrences() == 0) {
1076 Opt.second->error("must be specified at least once!");
1077 ErrorParsing = true;
1085 // Now that we know if -debug is specified, we can use it.
1086 // Note that if ReadResponseFiles == true, this must be done before the
1087 // memory allocated for the expanded command line is free()d below.
1088 DEBUG(dbgs() << "Args: ";
1089 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1092 // Free all of the memory allocated to the map. Command line options may only
1093 // be processed once!
1096 // If we had an error processing our arguments, don't let the program execute
1101 //===----------------------------------------------------------------------===//
1102 // Option Base class implementation
1105 bool Option::error(const Twine &Message, StringRef ArgName) {
1106 if (!ArgName.data())
1108 if (ArgName.empty())
1109 errs() << HelpStr; // Be nice for positional arguments
1111 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1113 errs() << " option: " << Message << "\n";
1117 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1120 NumOccurrences++; // Increment the number of times we have been seen
1122 switch (getNumOccurrencesFlag()) {
1124 if (NumOccurrences > 1)
1125 return error("may only occur zero or one times!", ArgName);
1128 if (NumOccurrences > 1)
1129 return error("must occur exactly one time!", ArgName);
1137 return handleOccurrence(pos, ArgName, Value);
1140 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1141 // has been specified yet.
1143 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1144 if (O.ValueStr.empty())
1149 //===----------------------------------------------------------------------===//
1150 // cl::alias class implementation
1153 // Return the width of the option tag for printing...
1154 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1156 static void printHelpStr(StringRef HelpStr, size_t Indent,
1157 size_t FirstLineIndentedBy) {
1158 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1159 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1160 while (!Split.second.empty()) {
1161 Split = Split.second.split('\n');
1162 outs().indent(Indent) << Split.first << "\n";
1166 // Print out the option for the alias.
1167 void alias::printOptionInfo(size_t GlobalWidth) const {
1168 outs() << " -" << ArgStr;
1169 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1172 //===----------------------------------------------------------------------===//
1173 // Parser Implementation code...
1176 // basic_parser implementation
1179 // Return the width of the option tag for printing...
1180 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1181 size_t Len = O.ArgStr.size();
1182 if (const char *ValName = getValueName())
1183 Len += getValueStr(O, ValName).size() + 3;
1188 // printOptionInfo - Print out information about this option. The
1189 // to-be-maintained width is specified.
1191 void basic_parser_impl::printOptionInfo(const Option &O,
1192 size_t GlobalWidth) const {
1193 outs() << " -" << O.ArgStr;
1195 if (const char *ValName = getValueName())
1196 outs() << "=<" << getValueStr(O, ValName) << '>';
1198 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1201 void basic_parser_impl::printOptionName(const Option &O,
1202 size_t GlobalWidth) const {
1203 outs() << " -" << O.ArgStr;
1204 outs().indent(GlobalWidth - O.ArgStr.size());
1207 // parser<bool> implementation
1209 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1211 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1217 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1221 return O.error("'" + Arg +
1222 "' is invalid value for boolean argument! Try 0 or 1");
1225 // parser<boolOrDefault> implementation
1227 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1228 boolOrDefault &Value) {
1229 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1234 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1239 return O.error("'" + Arg +
1240 "' is invalid value for boolean argument! Try 0 or 1");
1243 // parser<int> implementation
1245 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1247 if (Arg.getAsInteger(0, Value))
1248 return O.error("'" + Arg + "' value invalid for integer argument!");
1252 // parser<unsigned> implementation
1254 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1257 if (Arg.getAsInteger(0, Value))
1258 return O.error("'" + Arg + "' value invalid for uint argument!");
1262 // parser<unsigned long long> implementation
1264 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1266 unsigned long long &Value) {
1268 if (Arg.getAsInteger(0, Value))
1269 return O.error("'" + Arg + "' value invalid for uint argument!");
1273 // parser<double>/parser<float> implementation
1275 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1276 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1277 const char *ArgStart = TmpStr.c_str();
1279 Value = strtod(ArgStart, &End);
1281 return O.error("'" + Arg + "' value invalid for floating point argument!");
1285 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1287 return parseDouble(O, Arg, Val);
1290 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1293 if (parseDouble(O, Arg, dVal))
1299 // generic_parser_base implementation
1302 // findOption - Return the option number corresponding to the specified
1303 // argument string. If the option is not found, getNumOptions() is returned.
1305 unsigned generic_parser_base::findOption(const char *Name) {
1306 unsigned e = getNumOptions();
1308 for (unsigned i = 0; i != e; ++i) {
1309 if (strcmp(getOption(i), Name) == 0)
1315 // Return the width of the option tag for printing...
1316 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1317 if (O.hasArgStr()) {
1318 size_t Size = O.ArgStr.size() + 6;
1319 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1320 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1323 size_t BaseSize = 0;
1324 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1325 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1330 // printOptionInfo - Print out information about this option. The
1331 // to-be-maintained width is specified.
1333 void generic_parser_base::printOptionInfo(const Option &O,
1334 size_t GlobalWidth) const {
1335 if (O.hasArgStr()) {
1336 outs() << " -" << O.ArgStr;
1337 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1339 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1340 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1341 outs() << " =" << getOption(i);
1342 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1345 if (!O.HelpStr.empty())
1346 outs() << " " << O.HelpStr << '\n';
1347 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1348 const char *Option = getOption(i);
1349 outs() << " -" << Option;
1350 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1355 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1357 // printGenericOptionDiff - Print the value of this option and it's default.
1359 // "Generic" options have each value mapped to a name.
1360 void generic_parser_base::printGenericOptionDiff(
1361 const Option &O, const GenericOptionValue &Value,
1362 const GenericOptionValue &Default, size_t GlobalWidth) const {
1363 outs() << " -" << O.ArgStr;
1364 outs().indent(GlobalWidth - O.ArgStr.size());
1366 unsigned NumOpts = getNumOptions();
1367 for (unsigned i = 0; i != NumOpts; ++i) {
1368 if (Value.compare(getOptionValue(i)))
1371 outs() << "= " << getOption(i);
1372 size_t L = std::strlen(getOption(i));
1373 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1374 outs().indent(NumSpaces) << " (default: ";
1375 for (unsigned j = 0; j != NumOpts; ++j) {
1376 if (Default.compare(getOptionValue(j)))
1378 outs() << getOption(j);
1384 outs() << "= *unknown option value*\n";
1387 // printOptionDiff - Specializations for printing basic value types.
1389 #define PRINT_OPT_DIFF(T) \
1390 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1391 size_t GlobalWidth) const { \
1392 printOptionName(O, GlobalWidth); \
1395 raw_string_ostream SS(Str); \
1398 outs() << "= " << Str; \
1399 size_t NumSpaces = \
1400 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1401 outs().indent(NumSpaces) << " (default: "; \
1403 outs() << D.getValue(); \
1405 outs() << "*no default*"; \
1409 PRINT_OPT_DIFF(bool)
1410 PRINT_OPT_DIFF(boolOrDefault)
1412 PRINT_OPT_DIFF(unsigned)
1413 PRINT_OPT_DIFF(unsigned long long)
1414 PRINT_OPT_DIFF(double)
1415 PRINT_OPT_DIFF(float)
1416 PRINT_OPT_DIFF(char)
1418 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1419 OptionValue<std::string> D,
1420 size_t GlobalWidth) const {
1421 printOptionName(O, GlobalWidth);
1422 outs() << "= " << V;
1423 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1424 outs().indent(NumSpaces) << " (default: ";
1426 outs() << D.getValue();
1428 outs() << "*no default*";
1432 // Print a placeholder for options that don't yet support printOptionDiff().
1433 void basic_parser_impl::printOptionNoValue(const Option &O,
1434 size_t GlobalWidth) const {
1435 printOptionName(O, GlobalWidth);
1436 outs() << "= *cannot print option value*\n";
1439 //===----------------------------------------------------------------------===//
1440 // -help and -help-hidden option implementation
1443 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1444 const std::pair<const char *, Option *> *RHS) {
1445 return strcmp(LHS->first, RHS->first);
1448 // Copy Options into a vector so we can sort them as we like.
1449 static void sortOpts(StringMap<Option *> &OptMap,
1450 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1452 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1454 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1456 // Ignore really-hidden options.
1457 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1460 // Unless showhidden is set, ignore hidden flags.
1461 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1464 // If we've already seen this option, don't add it to the list again.
1465 if (!OptionSet.insert(I->second).second)
1469 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1472 // Sort the options list alphabetically.
1473 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1480 const bool ShowHidden;
1481 typedef SmallVector<std::pair<const char *, Option *>, 128>
1482 StrOptionPairVector;
1483 // Print the options. Opts is assumed to be alphabetically sorted.
1484 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1485 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1486 Opts[i].second->printOptionInfo(MaxArgLen);
1490 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1491 virtual ~HelpPrinter() {}
1493 // Invoke the printer.
1494 void operator=(bool Value) {
1498 StrOptionPairVector Opts;
1499 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1501 if (GlobalParser->ProgramOverview)
1502 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1504 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1506 for (auto Opt : GlobalParser->PositionalOpts) {
1507 if (Opt->hasArgStr())
1508 outs() << " --" << Opt->ArgStr;
1509 outs() << " " << Opt->HelpStr;
1512 // Print the consume after option info if it exists...
1513 if (GlobalParser->ConsumeAfterOpt)
1514 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1518 // Compute the maximum argument length...
1519 size_t MaxArgLen = 0;
1520 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1521 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1523 outs() << "OPTIONS:\n";
1524 printOptions(Opts, MaxArgLen);
1526 // Print any extra help the user has declared.
1527 for (auto I : GlobalParser->MoreHelp)
1529 GlobalParser->MoreHelp.clear();
1531 // Halt the program since help information was printed
1536 class CategorizedHelpPrinter : public HelpPrinter {
1538 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1540 // Helper function for printOptions().
1541 // It shall return a negative value if A's name should be lexicographically
1542 // ordered before B's name. It returns a value greater equal zero otherwise.
1543 static int OptionCategoryCompare(OptionCategory *const *A,
1544 OptionCategory *const *B) {
1545 return strcmp((*A)->getName(), (*B)->getName());
1548 // Make sure we inherit our base class's operator=()
1549 using HelpPrinter::operator=;
1552 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1553 std::vector<OptionCategory *> SortedCategories;
1554 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1556 // Collect registered option categories into vector in preparation for
1558 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1559 E = GlobalParser->RegisteredOptionCategories.end();
1561 SortedCategories.push_back(*I);
1564 // Sort the different option categories alphabetically.
1565 assert(SortedCategories.size() > 0 && "No option categories registered!");
1566 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1567 OptionCategoryCompare);
1569 // Create map to empty vectors.
1570 for (std::vector<OptionCategory *>::const_iterator
1571 I = SortedCategories.begin(),
1572 E = SortedCategories.end();
1574 CategorizedOptions[*I] = std::vector<Option *>();
1576 // Walk through pre-sorted options and assign into categories.
1577 // Because the options are already alphabetically sorted the
1578 // options within categories will also be alphabetically sorted.
1579 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1580 Option *Opt = Opts[I].second;
1581 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1582 "Option has an unregistered category");
1583 CategorizedOptions[Opt->Category].push_back(Opt);
1587 for (std::vector<OptionCategory *>::const_iterator
1588 Category = SortedCategories.begin(),
1589 E = SortedCategories.end();
1590 Category != E; ++Category) {
1591 // Hide empty categories for -help, but show for -help-hidden.
1592 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1593 if (!ShowHidden && IsEmptyCategory)
1596 // Print category information.
1598 outs() << (*Category)->getName() << ":\n";
1600 // Check if description is set.
1601 if ((*Category)->getDescription() != nullptr)
1602 outs() << (*Category)->getDescription() << "\n\n";
1606 // When using -help-hidden explicitly state if the category has no
1607 // options associated with it.
1608 if (IsEmptyCategory) {
1609 outs() << " This option category has no options.\n";
1612 // Loop over the options in the category and print.
1613 for (std::vector<Option *>::const_iterator
1614 Opt = CategorizedOptions[*Category].begin(),
1615 E = CategorizedOptions[*Category].end();
1617 (*Opt)->printOptionInfo(MaxArgLen);
1622 // This wraps the Uncategorizing and Categorizing printers and decides
1623 // at run time which should be invoked.
1624 class HelpPrinterWrapper {
1626 HelpPrinter &UncategorizedPrinter;
1627 CategorizedHelpPrinter &CategorizedPrinter;
1630 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1631 CategorizedHelpPrinter &CategorizedPrinter)
1632 : UncategorizedPrinter(UncategorizedPrinter),
1633 CategorizedPrinter(CategorizedPrinter) {}
1635 // Invoke the printer.
1636 void operator=(bool Value);
1639 } // End anonymous namespace
1641 // Declare the four HelpPrinter instances that are used to print out help, or
1642 // help-hidden as an uncategorized list or in categories.
1643 static HelpPrinter UncategorizedNormalPrinter(false);
1644 static HelpPrinter UncategorizedHiddenPrinter(true);
1645 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1646 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1648 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1649 // a categorizing help printer
1650 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1651 CategorizedNormalPrinter);
1652 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1653 CategorizedHiddenPrinter);
1655 // Define a category for generic options that all tools should have.
1656 static cl::OptionCategory GenericCategory("Generic Options");
1658 // Define uncategorized help printers.
1659 // -help-list is hidden by default because if Option categories are being used
1660 // then -help behaves the same as -help-list.
1661 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1663 cl::desc("Display list of available options (-help-list-hidden for more)"),
1664 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1665 cl::cat(GenericCategory));
1667 static cl::opt<HelpPrinter, true, parser<bool>>
1668 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1669 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1670 cl::ValueDisallowed, cl::cat(GenericCategory));
1672 // Define uncategorized/categorized help printers. These printers change their
1673 // behaviour at runtime depending on whether one or more Option categories have
1675 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1676 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1677 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1678 cl::cat(GenericCategory));
1680 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1681 HHOp("help-hidden", cl::desc("Display all available options"),
1682 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1683 cl::cat(GenericCategory));
1685 static cl::opt<bool> PrintOptions(
1687 cl::desc("Print non-default options after command line parsing"),
1688 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1690 static cl::opt<bool> PrintAllOptions(
1691 "print-all-options",
1692 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1693 cl::init(false), cl::cat(GenericCategory));
1695 void HelpPrinterWrapper::operator=(bool Value) {
1699 // Decide which printer to invoke. If more than one option category is
1700 // registered then it is useful to show the categorized help instead of
1701 // uncategorized help.
1702 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1703 // unhide -help-list option so user can have uncategorized output if they
1705 HLOp.setHiddenFlag(NotHidden);
1707 CategorizedPrinter = true; // Invoke categorized printer
1709 UncategorizedPrinter = true; // Invoke uncategorized printer
1712 // Print the value of each option.
1713 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1715 void CommandLineParser::printOptionValues() {
1716 if (!PrintOptions && !PrintAllOptions)
1719 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1720 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1722 // Compute the maximum argument length...
1723 size_t MaxArgLen = 0;
1724 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1725 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1727 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1728 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1731 static void (*OverrideVersionPrinter)() = nullptr;
1733 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1736 class VersionPrinter {
1739 raw_ostream &OS = outs();
1740 OS << "LLVM (http://llvm.org/):\n"
1741 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1742 #ifdef LLVM_VERSION_INFO
1743 OS << " " << LLVM_VERSION_INFO;
1746 #ifndef __OPTIMIZE__
1747 OS << "DEBUG build";
1749 OS << "Optimized build";
1752 OS << " with assertions";
1754 std::string CPU = sys::getHostCPUName();
1755 if (CPU == "generic")
1758 #if (ENABLE_TIMESTAMPS == 1)
1759 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1761 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1762 << " Host CPU: " << CPU << '\n';
1764 void operator=(bool OptionWasSpecified) {
1765 if (!OptionWasSpecified)
1768 if (OverrideVersionPrinter != nullptr) {
1769 (*OverrideVersionPrinter)();
1774 // Iterate over any registered extra printers and call them to add further
1776 if (ExtraVersionPrinters != nullptr) {
1778 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1779 E = ExtraVersionPrinters->end();
1787 } // End anonymous namespace
1789 // Define the --version option that prints out the LLVM version for the tool
1790 static VersionPrinter VersionPrinterInstance;
1792 static cl::opt<VersionPrinter, true, parser<bool>>
1793 VersOp("version", cl::desc("Display the version of this program"),
1794 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1795 cl::cat(GenericCategory));
1797 // Utility function for printing the help message.
1798 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1799 // This looks weird, but it actually prints the help message. The Printers are
1800 // types of HelpPrinter and the help gets printed when its operator= is
1801 // invoked. That's because the "normal" usages of the help printer is to be
1802 // assigned true/false depending on whether -help or -help-hidden was given or
1803 // not. Since we're circumventing that we have to make it look like -help or
1804 // -help-hidden were given, so we assign true.
1806 if (!Hidden && !Categorized)
1807 UncategorizedNormalPrinter = true;
1808 else if (!Hidden && Categorized)
1809 CategorizedNormalPrinter = true;
1810 else if (Hidden && !Categorized)
1811 UncategorizedHiddenPrinter = true;
1813 CategorizedHiddenPrinter = true;
1816 /// Utility function for printing version number.
1817 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1819 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1821 void cl::AddExtraVersionPrinter(void (*func)()) {
1822 if (!ExtraVersionPrinters)
1823 ExtraVersionPrinters = new std::vector<void (*)()>;
1825 ExtraVersionPrinters->push_back(func);
1828 StringMap<Option *> &cl::getRegisteredOptions() {
1829 return GlobalParser->OptionsMap;
1832 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1833 for (auto &I : GlobalParser->OptionsMap) {
1834 if (I.second->Category != &Category &&
1835 I.second->Category != &GenericCategory)
1836 I.second->setHiddenFlag(cl::ReallyHidden);
1840 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1841 auto CategoriesBegin = Categories.begin();
1842 auto CategoriesEnd = Categories.end();
1843 for (auto &I : GlobalParser->OptionsMap) {
1844 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1846 I.second->Category != &GenericCategory)
1847 I.second->setHiddenFlag(cl::ReallyHidden);
1851 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1852 const char *Overview) {
1853 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);