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 // Globals for name and overview of program. Program name is not a string to
87 // avoid static ctor/dtor issues.
88 static char ProgramName[80] = "<premain>";
89 static const char *ProgramOverview = nullptr;
91 // This collects additional help to be printed.
92 static ManagedStatic<std::vector<const char *>> MoreHelp;
94 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
95 MoreHelp->push_back(Help);
98 static bool OptionListChanged = false;
100 // MarkOptionsChanged - Internal helper function.
101 void cl::MarkOptionsChanged() { OptionListChanged = true; }
103 /// RegisteredOptionList - This is the list of the command line options that
104 /// have statically constructed themselves.
105 static Option *RegisteredOptionList = nullptr;
107 void Option::addArgument() {
108 assert(!NextRegistered && "argument multiply registered!");
110 NextRegistered = RegisteredOptionList;
111 RegisteredOptionList = this;
112 MarkOptionsChanged();
115 void Option::removeArgument() {
116 if (RegisteredOptionList == this) {
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
121 Option *O = RegisteredOptionList;
122 for (; O->NextRegistered != this; O = O->NextRegistered)
124 O->NextRegistered = NextRegistered;
125 MarkOptionsChanged();
128 // This collects the different option categories that have been registered.
129 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
130 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
132 // Initialise the general option category.
133 OptionCategory llvm::cl::GeneralCategory("General options");
135 void OptionCategory::registerCategory() {
136 assert(std::count_if(RegisteredOptionCategories->begin(),
137 RegisteredOptionCategories->end(),
138 [this](const OptionCategory *Category) {
139 return getName() == Category->getName();
141 "Duplicate option categories");
143 RegisteredOptionCategories->insert(this);
146 //===----------------------------------------------------------------------===//
147 // Basic, shared command line option processing machinery.
150 /// GetOptionInfo - Scan the list of registered options, turning them into data
151 /// structures that are easier to handle.
152 static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
153 SmallVectorImpl<Option *> &SinkOpts,
154 StringMap<Option *> &OptionsMap) {
155 bool HadErrors = false;
156 SmallVector<const char *, 16> OptionNames;
157 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
158 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159 // If this option wants to handle multiple option names, get the full set.
160 // This handles enum options like "-O1 -O2" etc.
161 O->getExtraOptionNames(OptionNames);
163 OptionNames.push_back(O->ArgStr);
165 // Handle named options.
166 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
167 // Add argument to the argument map!
168 if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
169 errs() << ProgramName << ": CommandLine Error: Option '"
170 << OptionNames[i] << "' registered more than once!\n";
177 // Remember information about positional options.
178 if (O->getFormattingFlag() == cl::Positional)
179 PositionalOpts.push_back(O);
180 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
181 SinkOpts.push_back(O);
182 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
184 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
192 PositionalOpts.push_back(CAOpt);
194 // Make sure that they are in order of registration not backwards.
195 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
197 // Fail hard if there were errors. These are strictly unrecoverable and
198 // indicate serious issues such as conflicting option names or an incorrectly
199 // linked LLVM distribution.
201 report_fatal_error("inconsistency in registered CommandLine options");
204 /// LookupOption - Lookup the option specified by the specified option on the
205 /// command line. If there is a value specified (after an equal sign) return
206 /// that as well. This assumes that leading dashes have already been stripped.
207 static Option *LookupOption(StringRef &Arg, StringRef &Value,
208 const StringMap<Option *> &OptionsMap) {
209 // Reject all dashes.
213 size_t EqualPos = Arg.find('=');
215 // If we have an equals sign, remember the value.
216 if (EqualPos == StringRef::npos) {
217 // Look up the option.
218 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
219 return I != OptionsMap.end() ? I->second : nullptr;
222 // If the argument before the = is a valid option name, we match. If not,
223 // return Arg unmolested.
224 StringMap<Option *>::const_iterator I =
225 OptionsMap.find(Arg.substr(0, EqualPos));
226 if (I == OptionsMap.end())
229 Value = Arg.substr(EqualPos + 1);
230 Arg = Arg.substr(0, EqualPos);
234 /// LookupNearestOption - Lookup the closest match to the option specified by
235 /// the specified option on the command line. If there is a value specified
236 /// (after an equal sign) return that as well. This assumes that leading dashes
237 /// have already been stripped.
238 static Option *LookupNearestOption(StringRef Arg,
239 const StringMap<Option *> &OptionsMap,
240 std::string &NearestString) {
241 // Reject all dashes.
245 // Split on any equal sign.
246 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
247 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
248 StringRef &RHS = SplitArg.second;
250 // Find the closest match.
251 Option *Best = nullptr;
252 unsigned BestDistance = 0;
253 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
254 ie = OptionsMap.end();
256 Option *O = it->second;
257 SmallVector<const char *, 16> OptionNames;
258 O->getExtraOptionNames(OptionNames);
260 OptionNames.push_back(O->ArgStr);
262 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
263 StringRef Flag = PermitValue ? LHS : Arg;
264 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
265 StringRef Name = OptionNames[i];
266 unsigned Distance = StringRef(Name).edit_distance(
267 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
268 if (!Best || Distance < BestDistance) {
270 BestDistance = Distance;
271 if (RHS.empty() || !PermitValue)
272 NearestString = OptionNames[i];
274 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
282 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
283 /// that does special handling of cl::CommaSeparated options.
284 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
285 StringRef ArgName, StringRef Value,
286 bool MultiArg = false) {
287 // Check to see if this option accepts a comma separated list of values. If
288 // it does, we have to split up the value into multiple values.
289 if (Handler->getMiscFlags() & CommaSeparated) {
290 StringRef Val(Value);
291 StringRef::size_type Pos = Val.find(',');
293 while (Pos != StringRef::npos) {
294 // Process the portion before the comma.
295 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
297 // Erase the portion before the comma, AND the comma.
298 Val = Val.substr(Pos + 1);
299 Value.substr(Pos + 1); // Increment the original value pointer as well.
300 // Check for another comma.
307 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
313 /// ProvideOption - For Value, this differentiates between an empty value ("")
314 /// and a null value (StringRef()). The later is accepted for arguments that
315 /// don't allow a value (-foo) the former is rejected (-foo=).
316 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
317 StringRef Value, int argc,
318 const char *const *argv, int &i) {
319 // Is this a multi-argument option?
320 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
322 // Enforce value requirements
323 switch (Handler->getValueExpectedFlag()) {
325 if (!Value.data()) { // No value specified?
327 return Handler->error("requires a value!");
328 // Steal the next argument, like for '-o filename'
329 assert(argv && "null check");
333 case ValueDisallowed:
334 if (NumAdditionalVals > 0)
335 return Handler->error("multi-valued option specified"
336 " with ValueDisallowed modifier!");
339 return Handler->error("does not allow a value! '" + Twine(Value) +
346 // If this isn't a multi-arg option, just run the handler.
347 if (NumAdditionalVals == 0)
348 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
350 // If it is, run the handle several times.
351 bool MultiArg = false;
354 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
360 while (NumAdditionalVals > 0) {
362 return Handler->error("not enough values!");
363 assert(argv && "null check");
366 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
374 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
376 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
379 // Option predicates...
380 static inline bool isGrouping(const Option *O) {
381 return O->getFormattingFlag() == cl::Grouping;
383 static inline bool isPrefixedOrGrouping(const Option *O) {
384 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
387 // getOptionPred - Check to see if there are any options that satisfy the
388 // specified predicate with names that are the prefixes in Name. This is
389 // checked by progressively stripping characters off of the name, checking to
390 // see if there options that satisfy the predicate. If we find one, return it,
391 // otherwise return null.
393 static Option *getOptionPred(StringRef Name, size_t &Length,
394 bool (*Pred)(const Option *),
395 const StringMap<Option *> &OptionsMap) {
397 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
399 // Loop while we haven't found an option and Name still has at least two
400 // characters in it (so that the next iteration will not be the empty
402 while (OMI == OptionsMap.end() && Name.size() > 1) {
403 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
404 OMI = OptionsMap.find(Name);
407 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
408 Length = Name.size();
409 return OMI->second; // Found one!
411 return nullptr; // No option found!
414 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
415 /// with at least one '-') does not fully match an available option. Check to
416 /// see if this is a prefix or grouped option. If so, split arg into output an
417 /// Arg/Value pair and return the Option to parse it with.
419 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
421 const StringMap<Option *> &OptionsMap) {
427 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
431 // If the option is a prefixed option, then the value is simply the
432 // rest of the name... so fall through to later processing, by
433 // setting up the argument name flags and value fields.
434 if (PGOpt->getFormattingFlag() == cl::Prefix) {
435 Value = Arg.substr(Length);
436 Arg = Arg.substr(0, Length);
437 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
441 // This must be a grouped option... handle them now. Grouping options can't
443 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
446 // Move current arg name out of Arg into OneArgName.
447 StringRef OneArgName = Arg.substr(0, Length);
448 Arg = Arg.substr(Length);
450 // Because ValueRequired is an invalid flag for grouped arguments,
451 // we don't need to pass argc/argv in.
452 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
453 "Option can not be cl::Grouping AND cl::ValueRequired!");
456 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
458 // Get the next grouping option.
459 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
460 } while (PGOpt && Length != Arg.size());
462 // Return the last option with Arg cut down to just the last one.
466 static bool RequiresValue(const Option *O) {
467 return O->getNumOccurrencesFlag() == cl::Required ||
468 O->getNumOccurrencesFlag() == cl::OneOrMore;
471 static bool EatsUnboundedNumberOfValues(const Option *O) {
472 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
473 O->getNumOccurrencesFlag() == cl::OneOrMore;
476 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
478 static bool isQuote(char C) { return C == '\"' || C == '\''; }
480 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
482 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
483 SmallVectorImpl<const char *> &NewArgv,
485 SmallString<128> Token;
486 for (size_t I = 0, E = Src.size(); I != E; ++I) {
487 // Consume runs of whitespace.
489 while (I != E && isWhitespace(Src[I])) {
490 // Mark the end of lines in response files
491 if (MarkEOLs && Src[I] == '\n')
492 NewArgv.push_back(nullptr);
499 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
500 // they are literal. This makes it much easier to read Windows file paths.
501 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
502 ++I; // Skip the escape.
503 Token.push_back(Src[I]);
507 // Consume a quoted string.
508 if (isQuote(Src[I])) {
509 char Quote = Src[I++];
510 while (I != E && Src[I] != Quote) {
511 // Backslashes are literal, unless they escape a special character.
512 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
514 Token.push_back(Src[I]);
522 // End the token if this is whitespace.
523 if (isWhitespace(Src[I])) {
525 NewArgv.push_back(Saver.SaveString(Token.c_str()));
530 // This is a normal character. Append it.
531 Token.push_back(Src[I]);
534 // Append the last token after hitting EOF with no whitespace.
536 NewArgv.push_back(Saver.SaveString(Token.c_str()));
537 // Mark the end of response files
539 NewArgv.push_back(nullptr);
542 /// Backslashes are interpreted in a rather complicated way in the Windows-style
543 /// command line, because backslashes are used both to separate path and to
544 /// escape double quote. This method consumes runs of backslashes as well as the
545 /// following double quote if it's escaped.
547 /// * If an even number of backslashes is followed by a double quote, one
548 /// backslash is output for every pair of backslashes, and the last double
549 /// quote remains unconsumed. The double quote will later be interpreted as
550 /// the start or end of a quoted string in the main loop outside of this
553 /// * If an odd number of backslashes is followed by a double quote, one
554 /// backslash is output for every pair of backslashes, and a double quote is
555 /// output for the last pair of backslash-double quote. The double quote is
556 /// consumed in this case.
558 /// * Otherwise, backslashes are interpreted literally.
559 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
560 size_t E = Src.size();
561 int BackslashCount = 0;
562 // Skip the backslashes.
566 } while (I != E && Src[I] == '\\');
568 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
569 if (FollowedByDoubleQuote) {
570 Token.append(BackslashCount / 2, '\\');
571 if (BackslashCount % 2 == 0)
573 Token.push_back('"');
576 Token.append(BackslashCount, '\\');
580 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
581 SmallVectorImpl<const char *> &NewArgv,
583 SmallString<128> Token;
585 // This is a small state machine to consume characters until it reaches the
586 // end of the source string.
587 enum { INIT, UNQUOTED, QUOTED } State = INIT;
588 for (size_t I = 0, E = Src.size(); I != E; ++I) {
589 // INIT state indicates that the current input index is at the start of
590 // the string or between tokens.
592 if (isWhitespace(Src[I])) {
593 // Mark the end of lines in response files
594 if (MarkEOLs && Src[I] == '\n')
595 NewArgv.push_back(nullptr);
602 if (Src[I] == '\\') {
603 I = parseBackslash(Src, I, Token);
607 Token.push_back(Src[I]);
612 // UNQUOTED state means that it's reading a token not quoted by double
614 if (State == UNQUOTED) {
615 // Whitespace means the end of the token.
616 if (isWhitespace(Src[I])) {
617 NewArgv.push_back(Saver.SaveString(Token.c_str()));
620 // Mark the end of lines in response files
621 if (MarkEOLs && Src[I] == '\n')
622 NewArgv.push_back(nullptr);
629 if (Src[I] == '\\') {
630 I = parseBackslash(Src, I, Token);
633 Token.push_back(Src[I]);
637 // QUOTED state means that it's reading a token quoted by double quotes.
638 if (State == QUOTED) {
643 if (Src[I] == '\\') {
644 I = parseBackslash(Src, I, Token);
647 Token.push_back(Src[I]);
650 // Append the last token after hitting EOF with no whitespace.
652 NewArgv.push_back(Saver.SaveString(Token.c_str()));
653 // Mark the end of response files
655 NewArgv.push_back(nullptr);
658 // It is called byte order marker but the UTF-8 BOM is actually not affected
659 // by the host system's endianness.
660 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
661 return (S.size() >= 3 &&
662 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
665 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
666 TokenizerCallback Tokenizer,
667 SmallVectorImpl<const char *> &NewArgv,
668 bool MarkEOLs = false) {
669 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
670 MemoryBuffer::getFile(FName);
673 MemoryBuffer &MemBuf = *MemBufOrErr.get();
674 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
676 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
677 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
679 if (hasUTF16ByteOrderMark(BufRef)) {
680 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
682 Str = StringRef(UTF8Buf);
684 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
685 // these bytes before parsing.
686 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
687 else if (hasUTF8ByteOrderMark(BufRef))
688 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
690 // Tokenize the contents into NewArgv.
691 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
696 /// \brief Expand response files on a command line recursively using the given
697 /// StringSaver and tokenization strategy.
698 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
699 SmallVectorImpl<const char *> &Argv,
701 unsigned RspFiles = 0;
702 bool AllExpanded = true;
704 // Don't cache Argv.size() because it can change.
705 for (unsigned I = 0; I != Argv.size();) {
706 const char *Arg = Argv[I];
707 // Check if it is an EOL marker
708 if (Arg == nullptr) {
717 // If we have too many response files, leave some unexpanded. This avoids
718 // crashing on self-referential response files.
722 // Replace this response file argument with the tokenization of its
723 // contents. Nested response files are expanded in subsequent iterations.
724 // FIXME: If a nested response file uses a relative path, is it relative to
725 // the cwd of the process or the response file?
726 SmallVector<const char *, 0> ExpandedArgv;
727 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
729 // We couldn't read this file, so we leave it in the argument stream and
735 Argv.erase(Argv.begin() + I);
736 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
742 class StrDupSaver : public StringSaver {
743 std::vector<char *> Dups;
747 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
753 const char *SaveString(const char *Str) override {
754 char *Dup = strdup(Str);
761 /// ParseEnvironmentOptions - An alternative entry point to the
762 /// CommandLine library, which allows you to read the program's name
763 /// from the caller (as PROGNAME) and its command-line arguments from
764 /// an environment variable (whose name is given in ENVVAR).
766 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
767 const char *Overview) {
769 assert(progName && "Program name not specified");
770 assert(envVar && "Environment variable name missing");
772 // Get the environment variable they want us to parse options out of.
773 const char *envValue = getenv(envVar);
777 // Get program's "name", which we wouldn't know without the caller
779 SmallVector<const char *, 20> newArgv;
781 newArgv.push_back(Saver.SaveString(progName));
783 // Parse the value of the environment variable into a "command line"
784 // and hand it off to ParseCommandLineOptions().
785 TokenizeGNUCommandLine(envValue, Saver, newArgv);
786 int newArgc = static_cast<int>(newArgv.size());
787 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
790 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
791 const char *Overview) {
792 // Process all registered options.
793 SmallVector<Option *, 4> PositionalOpts;
794 SmallVector<Option *, 4> SinkOpts;
795 StringMap<Option *> Opts;
796 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
798 assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
800 // Expand response files.
801 SmallVector<const char *, 20> newArgv;
802 for (int i = 0; i != argc; ++i)
803 newArgv.push_back(argv[i]);
805 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
807 argc = static_cast<int>(newArgv.size());
809 // Copy the program name into ProgName, making sure not to overflow it.
810 StringRef ProgName = sys::path::filename(argv[0]);
811 size_t Len = std::min(ProgName.size(), size_t(79));
812 memcpy(ProgramName, ProgName.data(), Len);
813 ProgramName[Len] = '\0';
815 ProgramOverview = Overview;
816 bool ErrorParsing = false;
818 // Check out the positional arguments to collect information about them.
819 unsigned NumPositionalRequired = 0;
821 // Determine whether or not there are an unlimited number of positionals
822 bool HasUnlimitedPositionals = false;
824 Option *ConsumeAfterOpt = nullptr;
825 if (!PositionalOpts.empty()) {
826 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
827 assert(PositionalOpts.size() > 1 &&
828 "Cannot specify cl::ConsumeAfter without a positional argument!");
829 ConsumeAfterOpt = PositionalOpts[0];
832 // Calculate how many positional values are _required_.
833 bool UnboundedFound = false;
834 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
836 Option *Opt = PositionalOpts[i];
837 if (RequiresValue(Opt))
838 ++NumPositionalRequired;
839 else if (ConsumeAfterOpt) {
840 // ConsumeAfter cannot be combined with "optional" positional options
841 // unless there is only one positional argument...
842 if (PositionalOpts.size() > 2)
843 ErrorParsing |= Opt->error(
844 "error - this positional option will never be matched, "
845 "because it does not Require a value, and a "
846 "cl::ConsumeAfter option is active!");
847 } else if (UnboundedFound && !Opt->ArgStr[0]) {
848 // This option does not "require" a value... Make sure this option is
849 // not specified after an option that eats all extra arguments, or this
850 // one will never get any!
852 ErrorParsing |= Opt->error("error - option can never match, because "
853 "another positional argument will match an "
854 "unbounded number of values, and this option"
855 " does not require a value!");
857 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
859 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
862 // PositionalVals - A vector of "positional" arguments we accumulate into
863 // the process at the end.
865 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
867 // If the program has named positional arguments, and the name has been run
868 // across, keep track of which positional argument was named. Otherwise put
869 // the positional args into the PositionalVals list...
870 Option *ActivePositionalArg = nullptr;
872 // Loop over all of the arguments... processing them.
873 bool DashDashFound = false; // Have we read '--'?
874 for (int i = 1; i < argc; ++i) {
875 Option *Handler = nullptr;
876 Option *NearestHandler = nullptr;
877 std::string NearestHandlerString;
879 StringRef ArgName = "";
881 // If the option list changed, this means that some command line
882 // option has just been registered or deregistered. This can occur in
883 // response to things like -load, etc. If this happens, rescan the options.
884 if (OptionListChanged) {
885 PositionalOpts.clear();
888 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
889 OptionListChanged = false;
892 // Check to see if this is a positional argument. This argument is
893 // considered to be positional if it doesn't start with '-', if it is "-"
894 // itself, or if we have seen "--" already.
896 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
897 // Positional argument!
898 if (ActivePositionalArg) {
899 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
900 continue; // We are done!
903 if (!PositionalOpts.empty()) {
904 PositionalVals.push_back(std::make_pair(argv[i], i));
906 // All of the positional arguments have been fulfulled, give the rest to
907 // the consume after option... if it's specified...
909 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
910 for (++i; i < argc; ++i)
911 PositionalVals.push_back(std::make_pair(argv[i], i));
912 break; // Handle outside of the argument processing loop...
915 // Delay processing positional arguments until the end...
918 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
920 DashDashFound = true; // This is the mythical "--"?
921 continue; // Don't try to process it as an argument itself.
922 } else if (ActivePositionalArg &&
923 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
924 // If there is a positional argument eating options, check to see if this
925 // option is another positional argument. If so, treat it as an argument,
926 // otherwise feed it to the eating positional.
927 ArgName = argv[i] + 1;
928 // Eat leading dashes.
929 while (!ArgName.empty() && ArgName[0] == '-')
930 ArgName = ArgName.substr(1);
932 Handler = LookupOption(ArgName, Value, Opts);
933 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
934 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
935 continue; // We are done!
938 } else { // We start with a '-', must be an argument.
939 ArgName = argv[i] + 1;
940 // Eat leading dashes.
941 while (!ArgName.empty() && ArgName[0] == '-')
942 ArgName = ArgName.substr(1);
944 Handler = LookupOption(ArgName, Value, Opts);
946 // Check to see if this "option" is really a prefixed or grouped argument.
949 HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
951 // Otherwise, look for the closest available option to report to the user
952 // in the upcoming error.
953 if (!Handler && SinkOpts.empty())
955 LookupNearestOption(ArgName, Opts, NearestHandlerString);
959 if (SinkOpts.empty()) {
960 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
961 << "'. Try: '" << argv[0] << " -help'\n";
963 if (NearestHandler) {
964 // If we know a near match, report it as well.
965 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
971 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
974 (*I)->addOccurrence(i, "", argv[i]);
979 // If this is a named positional argument, just remember that it is the
981 if (Handler->getFormattingFlag() == cl::Positional)
982 ActivePositionalArg = Handler;
984 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
987 // Check and handle positional arguments now...
988 if (NumPositionalRequired > PositionalVals.size()) {
989 errs() << ProgramName
990 << ": Not enough positional command line arguments specified!\n"
991 << "Must specify at least " << NumPositionalRequired
992 << " positional arguments: See: " << argv[0] << " -help\n";
995 } else if (!HasUnlimitedPositionals &&
996 PositionalVals.size() > PositionalOpts.size()) {
997 errs() << ProgramName << ": Too many positional arguments specified!\n"
998 << "Can specify at most " << PositionalOpts.size()
999 << " positional arguments: See: " << argv[0] << " -help\n";
1000 ErrorParsing = true;
1002 } else if (!ConsumeAfterOpt) {
1003 // Positional args have already been handled if ConsumeAfter is specified.
1004 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1005 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1006 if (RequiresValue(PositionalOpts[i])) {
1007 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1008 PositionalVals[ValNo].second);
1010 --NumPositionalRequired; // We fulfilled our duty...
1013 // If we _can_ give this option more arguments, do so now, as long as we
1014 // do not give it values that others need. 'Done' controls whether the
1015 // option even _WANTS_ any more.
1017 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1018 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1019 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1021 Done = true; // Optional arguments want _at most_ one value
1023 case cl::ZeroOrMore: // Zero or more will take all they can get...
1024 case cl::OneOrMore: // One or more will take all they can get...
1025 ProvidePositionalOption(PositionalOpts[i],
1026 PositionalVals[ValNo].first,
1027 PositionalVals[ValNo].second);
1031 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1032 "positional argument processing!");
1037 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1039 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1040 if (RequiresValue(PositionalOpts[j])) {
1041 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1042 PositionalVals[ValNo].first,
1043 PositionalVals[ValNo].second);
1047 // Handle the case where there is just one positional option, and it's
1048 // optional. In this case, we want to give JUST THE FIRST option to the
1049 // positional option and keep the rest for the consume after. The above
1050 // loop would have assigned no values to positional options in this case.
1052 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1053 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1054 PositionalVals[ValNo].first,
1055 PositionalVals[ValNo].second);
1059 // Handle over all of the rest of the arguments to the
1060 // cl::ConsumeAfter command line option...
1061 for (; ValNo != PositionalVals.size(); ++ValNo)
1063 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1064 PositionalVals[ValNo].second);
1067 // Loop over args and make sure all required args are specified!
1068 for (const auto &Opt : Opts) {
1069 switch (Opt.second->getNumOccurrencesFlag()) {
1072 if (Opt.second->getNumOccurrences() == 0) {
1073 Opt.second->error("must be specified at least once!");
1074 ErrorParsing = true;
1082 // Now that we know if -debug is specified, we can use it.
1083 // Note that if ReadResponseFiles == true, this must be done before the
1084 // memory allocated for the expanded command line is free()d below.
1085 DEBUG(dbgs() << "Args: ";
1086 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1089 // Free all of the memory allocated to the map. Command line options may only
1090 // be processed once!
1092 PositionalOpts.clear();
1095 // If we had an error processing our arguments, don't let the program execute
1100 //===----------------------------------------------------------------------===//
1101 // Option Base class implementation
1104 bool Option::error(const Twine &Message, StringRef ArgName) {
1105 if (!ArgName.data())
1107 if (ArgName.empty())
1108 errs() << HelpStr; // Be nice for positional arguments
1110 errs() << ProgramName << ": for the -" << ArgName;
1112 errs() << " option: " << Message << "\n";
1116 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1119 NumOccurrences++; // Increment the number of times we have been seen
1121 switch (getNumOccurrencesFlag()) {
1123 if (NumOccurrences > 1)
1124 return error("may only occur zero or one times!", ArgName);
1127 if (NumOccurrences > 1)
1128 return error("must occur exactly one time!", ArgName);
1136 return handleOccurrence(pos, ArgName, Value);
1139 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1140 // has been specified yet.
1142 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1143 if (O.ValueStr[0] == 0)
1148 //===----------------------------------------------------------------------===//
1149 // cl::alias class implementation
1152 // Return the width of the option tag for printing...
1153 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1155 static void printHelpStr(StringRef HelpStr, size_t Indent,
1156 size_t FirstLineIndentedBy) {
1157 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1158 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1159 while (!Split.second.empty()) {
1160 Split = Split.second.split('\n');
1161 outs().indent(Indent) << Split.first << "\n";
1165 // Print out the option for the alias.
1166 void alias::printOptionInfo(size_t GlobalWidth) const {
1167 outs() << " -" << ArgStr;
1168 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1171 //===----------------------------------------------------------------------===//
1172 // Parser Implementation code...
1175 // basic_parser implementation
1178 // Return the width of the option tag for printing...
1179 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1180 size_t Len = std::strlen(O.ArgStr);
1181 if (const char *ValName = getValueName())
1182 Len += std::strlen(getValueStr(O, ValName)) + 3;
1187 // printOptionInfo - Print out information about this option. The
1188 // to-be-maintained width is specified.
1190 void basic_parser_impl::printOptionInfo(const Option &O,
1191 size_t GlobalWidth) const {
1192 outs() << " -" << O.ArgStr;
1194 if (const char *ValName = getValueName())
1195 outs() << "=<" << getValueStr(O, ValName) << '>';
1197 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1200 void basic_parser_impl::printOptionName(const Option &O,
1201 size_t GlobalWidth) const {
1202 outs() << " -" << O.ArgStr;
1203 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1206 // parser<bool> implementation
1208 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1210 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1216 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1220 return O.error("'" + Arg +
1221 "' is invalid value for boolean argument! Try 0 or 1");
1224 // parser<boolOrDefault> implementation
1226 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1227 boolOrDefault &Value) {
1228 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1233 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1238 return O.error("'" + Arg +
1239 "' is invalid value for boolean argument! Try 0 or 1");
1242 // parser<int> implementation
1244 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1246 if (Arg.getAsInteger(0, Value))
1247 return O.error("'" + Arg + "' value invalid for integer argument!");
1251 // parser<unsigned> implementation
1253 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1256 if (Arg.getAsInteger(0, Value))
1257 return O.error("'" + Arg + "' value invalid for uint argument!");
1261 // parser<unsigned long long> implementation
1263 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1265 unsigned long long &Value) {
1267 if (Arg.getAsInteger(0, Value))
1268 return O.error("'" + Arg + "' value invalid for uint argument!");
1272 // parser<double>/parser<float> implementation
1274 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1275 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1276 const char *ArgStart = TmpStr.c_str();
1278 Value = strtod(ArgStart, &End);
1280 return O.error("'" + Arg + "' value invalid for floating point argument!");
1284 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1286 return parseDouble(O, Arg, Val);
1289 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1292 if (parseDouble(O, Arg, dVal))
1298 // generic_parser_base implementation
1301 // findOption - Return the option number corresponding to the specified
1302 // argument string. If the option is not found, getNumOptions() is returned.
1304 unsigned generic_parser_base::findOption(const char *Name) {
1305 unsigned e = getNumOptions();
1307 for (unsigned i = 0; i != e; ++i) {
1308 if (strcmp(getOption(i), Name) == 0)
1314 // Return the width of the option tag for printing...
1315 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1316 if (O.hasArgStr()) {
1317 size_t Size = std::strlen(O.ArgStr) + 6;
1318 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1319 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1322 size_t BaseSize = 0;
1323 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1324 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1329 // printOptionInfo - Print out information about this option. The
1330 // to-be-maintained width is specified.
1332 void generic_parser_base::printOptionInfo(const Option &O,
1333 size_t GlobalWidth) const {
1334 if (O.hasArgStr()) {
1335 outs() << " -" << O.ArgStr;
1336 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1338 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1339 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1340 outs() << " =" << getOption(i);
1341 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1345 outs() << " " << O.HelpStr << '\n';
1346 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1347 const char *Option = getOption(i);
1348 outs() << " -" << Option;
1349 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1354 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1356 // printGenericOptionDiff - Print the value of this option and it's default.
1358 // "Generic" options have each value mapped to a name.
1359 void generic_parser_base::printGenericOptionDiff(
1360 const Option &O, const GenericOptionValue &Value,
1361 const GenericOptionValue &Default, size_t GlobalWidth) const {
1362 outs() << " -" << O.ArgStr;
1363 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1365 unsigned NumOpts = getNumOptions();
1366 for (unsigned i = 0; i != NumOpts; ++i) {
1367 if (Value.compare(getOptionValue(i)))
1370 outs() << "= " << getOption(i);
1371 size_t L = std::strlen(getOption(i));
1372 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1373 outs().indent(NumSpaces) << " (default: ";
1374 for (unsigned j = 0; j != NumOpts; ++j) {
1375 if (Default.compare(getOptionValue(j)))
1377 outs() << getOption(j);
1383 outs() << "= *unknown option value*\n";
1386 // printOptionDiff - Specializations for printing basic value types.
1388 #define PRINT_OPT_DIFF(T) \
1389 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1390 size_t GlobalWidth) const { \
1391 printOptionName(O, GlobalWidth); \
1394 raw_string_ostream SS(Str); \
1397 outs() << "= " << Str; \
1398 size_t NumSpaces = \
1399 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1400 outs().indent(NumSpaces) << " (default: "; \
1402 outs() << D.getValue(); \
1404 outs() << "*no default*"; \
1408 PRINT_OPT_DIFF(bool)
1409 PRINT_OPT_DIFF(boolOrDefault)
1411 PRINT_OPT_DIFF(unsigned)
1412 PRINT_OPT_DIFF(unsigned long long)
1413 PRINT_OPT_DIFF(double)
1414 PRINT_OPT_DIFF(float)
1415 PRINT_OPT_DIFF(char)
1417 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1418 OptionValue<std::string> D,
1419 size_t GlobalWidth) const {
1420 printOptionName(O, GlobalWidth);
1421 outs() << "= " << V;
1422 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1423 outs().indent(NumSpaces) << " (default: ";
1425 outs() << D.getValue();
1427 outs() << "*no default*";
1431 // Print a placeholder for options that don't yet support printOptionDiff().
1432 void basic_parser_impl::printOptionNoValue(const Option &O,
1433 size_t GlobalWidth) const {
1434 printOptionName(O, GlobalWidth);
1435 outs() << "= *cannot print option value*\n";
1438 //===----------------------------------------------------------------------===//
1439 // -help and -help-hidden option implementation
1442 static int OptNameCompare(const void *LHS, const void *RHS) {
1443 typedef std::pair<const char *, Option *> pair_ty;
1445 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)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 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), 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 // Get all the options.
1499 SmallVector<Option *, 4> PositionalOpts;
1500 SmallVector<Option *, 4> SinkOpts;
1501 StringMap<Option *> OptMap;
1502 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1504 StrOptionPairVector Opts;
1505 sortOpts(OptMap, Opts, ShowHidden);
1507 if (ProgramOverview)
1508 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1510 outs() << "USAGE: " << ProgramName << " [options]";
1512 // Print out the positional options.
1513 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1514 if (!PositionalOpts.empty() &&
1515 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1516 CAOpt = PositionalOpts[0];
1518 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1519 if (PositionalOpts[i]->ArgStr[0])
1520 outs() << " --" << PositionalOpts[i]->ArgStr;
1521 outs() << " " << PositionalOpts[i]->HelpStr;
1524 // Print the consume after option info if it exists...
1526 outs() << " " << CAOpt->HelpStr;
1530 // Compute the maximum argument length...
1531 size_t MaxArgLen = 0;
1532 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1533 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1535 outs() << "OPTIONS:\n";
1536 printOptions(Opts, MaxArgLen);
1538 // Print any extra help the user has declared.
1539 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1540 E = MoreHelp->end();
1545 // Halt the program since help information was printed
1550 class CategorizedHelpPrinter : public HelpPrinter {
1552 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1554 // Helper function for printOptions().
1555 // It shall return true if A's name should be lexographically
1556 // ordered before B's name. It returns false otherwise.
1557 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1558 return strcmp(A->getName(), B->getName()) < 0;
1561 // Make sure we inherit our base class's operator=()
1562 using HelpPrinter::operator=;
1565 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1566 std::vector<OptionCategory *> SortedCategories;
1567 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1569 // Collect registered option categories into vector in preparation for
1571 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1572 E = RegisteredOptionCategories->end();
1574 SortedCategories.push_back(*I);
1577 // Sort the different option categories alphabetically.
1578 assert(SortedCategories.size() > 0 && "No option categories registered!");
1579 std::sort(SortedCategories.begin(), SortedCategories.end(),
1580 OptionCategoryCompare);
1582 // Create map to empty vectors.
1583 for (std::vector<OptionCategory *>::const_iterator
1584 I = SortedCategories.begin(),
1585 E = SortedCategories.end();
1587 CategorizedOptions[*I] = std::vector<Option *>();
1589 // Walk through pre-sorted options and assign into categories.
1590 // Because the options are already alphabetically sorted the
1591 // options within categories will also be alphabetically sorted.
1592 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1593 Option *Opt = Opts[I].second;
1594 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1595 "Option has an unregistered category");
1596 CategorizedOptions[Opt->Category].push_back(Opt);
1600 for (std::vector<OptionCategory *>::const_iterator
1601 Category = SortedCategories.begin(),
1602 E = SortedCategories.end();
1603 Category != E; ++Category) {
1604 // Hide empty categories for -help, but show for -help-hidden.
1605 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1606 if (!ShowHidden && IsEmptyCategory)
1609 // Print category information.
1611 outs() << (*Category)->getName() << ":\n";
1613 // Check if description is set.
1614 if ((*Category)->getDescription() != nullptr)
1615 outs() << (*Category)->getDescription() << "\n\n";
1619 // When using -help-hidden explicitly state if the category has no
1620 // options associated with it.
1621 if (IsEmptyCategory) {
1622 outs() << " This option category has no options.\n";
1625 // Loop over the options in the category and print.
1626 for (std::vector<Option *>::const_iterator
1627 Opt = CategorizedOptions[*Category].begin(),
1628 E = CategorizedOptions[*Category].end();
1630 (*Opt)->printOptionInfo(MaxArgLen);
1635 // This wraps the Uncategorizing and Categorizing printers and decides
1636 // at run time which should be invoked.
1637 class HelpPrinterWrapper {
1639 HelpPrinter &UncategorizedPrinter;
1640 CategorizedHelpPrinter &CategorizedPrinter;
1643 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1644 CategorizedHelpPrinter &CategorizedPrinter)
1645 : UncategorizedPrinter(UncategorizedPrinter),
1646 CategorizedPrinter(CategorizedPrinter) {}
1648 // Invoke the printer.
1649 void operator=(bool Value);
1652 } // End anonymous namespace
1654 // Declare the four HelpPrinter instances that are used to print out help, or
1655 // help-hidden as an uncategorized list or in categories.
1656 static HelpPrinter UncategorizedNormalPrinter(false);
1657 static HelpPrinter UncategorizedHiddenPrinter(true);
1658 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1659 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1661 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1662 // a categorizing help printer
1663 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1664 CategorizedNormalPrinter);
1665 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1666 CategorizedHiddenPrinter);
1668 // Define a category for generic options that all tools should have.
1669 static cl::OptionCategory GenericCategory("Generic Options");
1671 // Define uncategorized help printers.
1672 // -help-list is hidden by default because if Option categories are being used
1673 // then -help behaves the same as -help-list.
1674 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1676 cl::desc("Display list of available options (-help-list-hidden for more)"),
1677 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1678 cl::cat(GenericCategory));
1680 static cl::opt<HelpPrinter, true, parser<bool>>
1681 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1682 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1683 cl::ValueDisallowed, cl::cat(GenericCategory));
1685 // Define uncategorized/categorized help printers. These printers change their
1686 // behaviour at runtime depending on whether one or more Option categories have
1688 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1689 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1690 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1691 cl::cat(GenericCategory));
1693 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1694 HHOp("help-hidden", cl::desc("Display all available options"),
1695 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1696 cl::cat(GenericCategory));
1698 static cl::opt<bool> PrintOptions(
1700 cl::desc("Print non-default options after command line parsing"),
1701 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1703 static cl::opt<bool> PrintAllOptions(
1704 "print-all-options",
1705 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1706 cl::init(false), cl::cat(GenericCategory));
1708 void HelpPrinterWrapper::operator=(bool Value) {
1712 // Decide which printer to invoke. If more than one option category is
1713 // registered then it is useful to show the categorized help instead of
1714 // uncategorized help.
1715 if (RegisteredOptionCategories->size() > 1) {
1716 // unhide -help-list option so user can have uncategorized output if they
1718 HLOp.setHiddenFlag(NotHidden);
1720 CategorizedPrinter = true; // Invoke categorized printer
1722 UncategorizedPrinter = true; // Invoke uncategorized printer
1725 // Print the value of each option.
1726 void cl::PrintOptionValues() {
1727 if (!PrintOptions && !PrintAllOptions)
1730 // Get all the options.
1731 SmallVector<Option *, 4> PositionalOpts;
1732 SmallVector<Option *, 4> SinkOpts;
1733 StringMap<Option *> OptMap;
1734 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1736 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1737 sortOpts(OptMap, Opts, /*ShowHidden*/ true);
1739 // Compute the maximum argument length...
1740 size_t MaxArgLen = 0;
1741 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1744 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1745 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1748 static void (*OverrideVersionPrinter)() = nullptr;
1750 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1753 class VersionPrinter {
1756 raw_ostream &OS = outs();
1757 OS << "LLVM (http://llvm.org/):\n"
1758 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1759 #ifdef LLVM_VERSION_INFO
1760 OS << " " << LLVM_VERSION_INFO;
1763 #ifndef __OPTIMIZE__
1764 OS << "DEBUG build";
1766 OS << "Optimized build";
1769 OS << " with assertions";
1771 std::string CPU = sys::getHostCPUName();
1772 if (CPU == "generic")
1775 #if (ENABLE_TIMESTAMPS == 1)
1776 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1778 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1779 << " Host CPU: " << CPU << '\n';
1781 void operator=(bool OptionWasSpecified) {
1782 if (!OptionWasSpecified)
1785 if (OverrideVersionPrinter != nullptr) {
1786 (*OverrideVersionPrinter)();
1791 // Iterate over any registered extra printers and call them to add further
1793 if (ExtraVersionPrinters != nullptr) {
1795 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1796 E = ExtraVersionPrinters->end();
1804 } // End anonymous namespace
1806 // Define the --version option that prints out the LLVM version for the tool
1807 static VersionPrinter VersionPrinterInstance;
1809 static cl::opt<VersionPrinter, true, parser<bool>>
1810 VersOp("version", cl::desc("Display the version of this program"),
1811 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1812 cl::cat(GenericCategory));
1814 // Utility function for printing the help message.
1815 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1816 // This looks weird, but it actually prints the help message. The Printers are
1817 // types of HelpPrinter and the help gets printed when its operator= is
1818 // invoked. That's because the "normal" usages of the help printer is to be
1819 // assigned true/false depending on whether -help or -help-hidden was given or
1820 // not. Since we're circumventing that we have to make it look like -help or
1821 // -help-hidden were given, so we assign true.
1823 if (!Hidden && !Categorized)
1824 UncategorizedNormalPrinter = true;
1825 else if (!Hidden && Categorized)
1826 CategorizedNormalPrinter = true;
1827 else if (Hidden && !Categorized)
1828 UncategorizedHiddenPrinter = true;
1830 CategorizedHiddenPrinter = true;
1833 /// Utility function for printing version number.
1834 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1836 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1838 void cl::AddExtraVersionPrinter(void (*func)()) {
1839 if (!ExtraVersionPrinters)
1840 ExtraVersionPrinters = new std::vector<void (*)()>;
1842 ExtraVersionPrinters->push_back(func);
1845 void cl::getRegisteredOptions(StringMap<Option *> &Map) {
1846 // Get all the options.
1847 SmallVector<Option *, 4> PositionalOpts; // NOT USED
1848 SmallVector<Option *, 4> SinkOpts; // NOT USED
1849 assert(Map.size() == 0 && "StringMap must be empty");
1850 GetOptionInfo(PositionalOpts, SinkOpts, Map);
1854 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1855 StringMap<cl::Option *> Options;
1856 cl::getRegisteredOptions(Options);
1857 for (auto &I : Options) {
1858 if (I.second->Category != &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);