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/ADT/ArrayRef.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Config/config.h"
26 #include "llvm/Support/ConvertUTF.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/MemoryBuffer.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/raw_ostream.h"
37 #include <system_error>
41 #define DEBUG_TYPE "commandline"
43 //===----------------------------------------------------------------------===//
44 // Template instantiations and anchors.
46 namespace llvm { namespace cl {
47 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
48 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
49 TEMPLATE_INSTANTIATION(class basic_parser<int>);
50 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
51 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
52 TEMPLATE_INSTANTIATION(class basic_parser<double>);
53 TEMPLATE_INSTANTIATION(class basic_parser<float>);
54 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
55 TEMPLATE_INSTANTIATION(class basic_parser<char>);
57 TEMPLATE_INSTANTIATION(class opt<unsigned>);
58 TEMPLATE_INSTANTIATION(class opt<int>);
59 TEMPLATE_INSTANTIATION(class opt<std::string>);
60 TEMPLATE_INSTANTIATION(class opt<char>);
61 TEMPLATE_INSTANTIATION(class opt<bool>);
62 } } // end namespace llvm::cl
64 // Pin the vtables to this file.
65 void GenericOptionValue::anchor() {}
66 void OptionValue<boolOrDefault>::anchor() {}
67 void OptionValue<std::string>::anchor() {}
68 void Option::anchor() {}
69 void basic_parser_impl::anchor() {}
70 void parser<bool>::anchor() {}
71 void parser<boolOrDefault>::anchor() {}
72 void parser<int>::anchor() {}
73 void parser<unsigned>::anchor() {}
74 void parser<unsigned long long>::anchor() {}
75 void parser<double>::anchor() {}
76 void parser<float>::anchor() {}
77 void parser<std::string>::anchor() {}
78 void parser<char>::anchor() {}
80 //===----------------------------------------------------------------------===//
82 // Globals for name and overview of program. Program name is not a string to
83 // avoid static ctor/dtor issues.
84 static char ProgramName[80] = "<premain>";
85 static const char *ProgramOverview = nullptr;
87 // This collects additional help to be printed.
88 static ManagedStatic<std::vector<const char*> > MoreHelp;
90 extrahelp::extrahelp(const char *Help)
92 MoreHelp->push_back(Help);
95 static bool OptionListChanged = false;
97 // MarkOptionsChanged - Internal helper function.
98 void cl::MarkOptionsChanged() {
99 OptionListChanged = true;
102 /// RegisteredOptionList - This is the list of the command line options that
103 /// have statically constructed themselves.
104 static Option *RegisteredOptionList = nullptr;
106 void Option::addArgument() {
107 assert(!NextRegistered && "argument multiply registered!");
109 NextRegistered = RegisteredOptionList;
110 RegisteredOptionList = this;
111 MarkOptionsChanged();
114 void Option::removeArgument() {
115 assert(NextRegistered && "argument never registered");
116 assert(RegisteredOptionList == this && "argument is not the last registered");
117 RegisteredOptionList = NextRegistered;
118 MarkOptionsChanged();
121 // This collects the different option categories that have been registered.
122 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
123 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
125 // Initialise the general option category.
126 OptionCategory llvm::cl::GeneralCategory("General options");
128 void OptionCategory::registerCategory() {
129 assert(std::count_if(RegisteredOptionCategories->begin(),
130 RegisteredOptionCategories->end(),
131 [this](const OptionCategory *Category) {
132 return getName() == Category->getName();
133 }) == 0 && "Duplicate option categories");
135 RegisteredOptionCategories->insert(this);
138 //===----------------------------------------------------------------------===//
139 // Basic, shared command line option processing machinery.
142 /// GetOptionInfo - Scan the list of registered options, turning them into data
143 /// structures that are easier to handle.
144 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
145 SmallVectorImpl<Option*> &SinkOpts,
146 StringMap<Option*> &OptionsMap) {
147 bool HadErrors = false;
148 SmallVector<const char*, 16> OptionNames;
149 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
150 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
151 // If this option wants to handle multiple option names, get the full set.
152 // This handles enum options like "-O1 -O2" etc.
153 O->getExtraOptionNames(OptionNames);
155 OptionNames.push_back(O->ArgStr);
157 // Handle named options.
158 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
159 // Add argument to the argument map!
160 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
161 errs() << ProgramName << ": CommandLine Error: Option '"
162 << OptionNames[i] << "' registered more than once!\n";
169 // Remember information about positional options.
170 if (O->getFormattingFlag() == cl::Positional)
171 PositionalOpts.push_back(O);
172 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
173 SinkOpts.push_back(O);
174 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
176 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
184 PositionalOpts.push_back(CAOpt);
186 // Make sure that they are in order of registration not backwards.
187 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
189 // Fail hard if there were errors. These are strictly unrecoverable and
190 // indicate serious issues such as conflicting option names or an incorrectly
191 // linked LLVM distribution.
193 report_fatal_error("inconsistency in registered CommandLine options");
197 /// LookupOption - Lookup the option specified by the specified option on the
198 /// command line. If there is a value specified (after an equal sign) return
199 /// that as well. This assumes that leading dashes have already been stripped.
200 static Option *LookupOption(StringRef &Arg, StringRef &Value,
201 const StringMap<Option*> &OptionsMap) {
202 // Reject all dashes.
203 if (Arg.empty()) return nullptr;
205 size_t EqualPos = Arg.find('=');
207 // If we have an equals sign, remember the value.
208 if (EqualPos == StringRef::npos) {
209 // Look up the option.
210 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
211 return I != OptionsMap.end() ? I->second : nullptr;
214 // If the argument before the = is a valid option name, we match. If not,
215 // return Arg unmolested.
216 StringMap<Option*>::const_iterator I =
217 OptionsMap.find(Arg.substr(0, EqualPos));
218 if (I == OptionsMap.end()) return nullptr;
220 Value = Arg.substr(EqualPos+1);
221 Arg = Arg.substr(0, EqualPos);
225 /// LookupNearestOption - Lookup the closest match to the option specified by
226 /// the specified option on the command line. If there is a value specified
227 /// (after an equal sign) return that as well. This assumes that leading dashes
228 /// have already been stripped.
229 static Option *LookupNearestOption(StringRef Arg,
230 const StringMap<Option*> &OptionsMap,
231 std::string &NearestString) {
232 // Reject all dashes.
233 if (Arg.empty()) return nullptr;
235 // Split on any equal sign.
236 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
237 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
238 StringRef &RHS = SplitArg.second;
240 // Find the closest match.
241 Option *Best = nullptr;
242 unsigned BestDistance = 0;
243 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
244 ie = OptionsMap.end(); it != ie; ++it) {
245 Option *O = it->second;
246 SmallVector<const char*, 16> OptionNames;
247 O->getExtraOptionNames(OptionNames);
249 OptionNames.push_back(O->ArgStr);
251 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
252 StringRef Flag = PermitValue ? LHS : Arg;
253 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
254 StringRef Name = OptionNames[i];
255 unsigned Distance = StringRef(Name).edit_distance(
256 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
257 if (!Best || Distance < BestDistance) {
259 BestDistance = Distance;
260 if (RHS.empty() || !PermitValue)
261 NearestString = OptionNames[i];
263 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
271 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
272 /// that does special handling of cl::CommaSeparated options.
273 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
274 StringRef ArgName, StringRef Value,
275 bool MultiArg = false) {
276 // Check to see if this option accepts a comma separated list of values. If
277 // it does, we have to split up the value into multiple values.
278 if (Handler->getMiscFlags() & CommaSeparated) {
279 StringRef Val(Value);
280 StringRef::size_type Pos = Val.find(',');
282 while (Pos != StringRef::npos) {
283 // Process the portion before the comma.
284 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
286 // Erase the portion before the comma, AND the comma.
287 Val = Val.substr(Pos+1);
288 Value.substr(Pos+1); // Increment the original value pointer as well.
289 // Check for another comma.
296 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
302 /// ProvideOption - For Value, this differentiates between an empty value ("")
303 /// and a null value (StringRef()). The later is accepted for arguments that
304 /// don't allow a value (-foo) the former is rejected (-foo=).
305 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
306 StringRef Value, int argc,
307 const char *const *argv, int &i) {
308 // Is this a multi-argument option?
309 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
311 // Enforce value requirements
312 switch (Handler->getValueExpectedFlag()) {
314 if (!Value.data()) { // No value specified?
316 return Handler->error("requires a value!");
317 // Steal the next argument, like for '-o filename'
321 case ValueDisallowed:
322 if (NumAdditionalVals > 0)
323 return Handler->error("multi-valued option specified"
324 " with ValueDisallowed modifier!");
327 return Handler->error("does not allow a value! '" +
328 Twine(Value) + "' specified.");
334 // If this isn't a multi-arg option, just run the handler.
335 if (NumAdditionalVals == 0)
336 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
338 // If it is, run the handle several times.
339 bool MultiArg = false;
342 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
348 while (NumAdditionalVals > 0) {
350 return Handler->error("not enough values!");
353 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
361 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
363 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
367 // Option predicates...
368 static inline bool isGrouping(const Option *O) {
369 return O->getFormattingFlag() == cl::Grouping;
371 static inline bool isPrefixedOrGrouping(const Option *O) {
372 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
375 // getOptionPred - Check to see if there are any options that satisfy the
376 // specified predicate with names that are the prefixes in Name. This is
377 // checked by progressively stripping characters off of the name, checking to
378 // see if there options that satisfy the predicate. If we find one, return it,
379 // otherwise return null.
381 static Option *getOptionPred(StringRef Name, size_t &Length,
382 bool (*Pred)(const Option*),
383 const StringMap<Option*> &OptionsMap) {
385 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
387 // Loop while we haven't found an option and Name still has at least two
388 // characters in it (so that the next iteration will not be the empty
390 while (OMI == OptionsMap.end() && Name.size() > 1) {
391 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
392 OMI = OptionsMap.find(Name);
395 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
396 Length = Name.size();
397 return OMI->second; // Found one!
399 return nullptr; // No option found!
402 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
403 /// with at least one '-') does not fully match an available option. Check to
404 /// see if this is a prefix or grouped option. If so, split arg into output an
405 /// Arg/Value pair and return the Option to parse it with.
406 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
408 const StringMap<Option*> &OptionsMap) {
409 if (Arg.size() == 1) return nullptr;
413 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
414 if (!PGOpt) return nullptr;
416 // If the option is a prefixed option, then the value is simply the
417 // rest of the name... so fall through to later processing, by
418 // setting up the argument name flags and value fields.
419 if (PGOpt->getFormattingFlag() == cl::Prefix) {
420 Value = Arg.substr(Length);
421 Arg = Arg.substr(0, Length);
422 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
426 // This must be a grouped option... handle them now. Grouping options can't
428 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
431 // Move current arg name out of Arg into OneArgName.
432 StringRef OneArgName = Arg.substr(0, Length);
433 Arg = Arg.substr(Length);
435 // Because ValueRequired is an invalid flag for grouped arguments,
436 // we don't need to pass argc/argv in.
437 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
438 "Option can not be cl::Grouping AND cl::ValueRequired!");
440 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
441 StringRef(), 0, nullptr, Dummy);
443 // Get the next grouping option.
444 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
445 } while (PGOpt && Length != Arg.size());
447 // Return the last option with Arg cut down to just the last one.
453 static bool RequiresValue(const Option *O) {
454 return O->getNumOccurrencesFlag() == cl::Required ||
455 O->getNumOccurrencesFlag() == cl::OneOrMore;
458 static bool EatsUnboundedNumberOfValues(const Option *O) {
459 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
460 O->getNumOccurrencesFlag() == cl::OneOrMore;
463 static bool isWhitespace(char C) {
464 return strchr(" \t\n\r\f\v", C);
467 static bool isQuote(char C) {
468 return C == '\"' || C == '\'';
471 static bool isGNUSpecial(char C) {
472 return strchr("\\\"\' ", C);
475 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
476 SmallVectorImpl<const char *> &NewArgv) {
477 SmallString<128> Token;
478 for (size_t I = 0, E = Src.size(); I != E; ++I) {
479 // Consume runs of whitespace.
481 while (I != E && isWhitespace(Src[I]))
486 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
487 // they are literal. This makes it much easier to read Windows file paths.
488 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
489 ++I; // Skip the escape.
490 Token.push_back(Src[I]);
494 // Consume a quoted string.
495 if (isQuote(Src[I])) {
496 char Quote = Src[I++];
497 while (I != E && Src[I] != Quote) {
498 // Backslashes are literal, unless they escape a special character.
499 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
501 Token.push_back(Src[I]);
508 // End the token if this is whitespace.
509 if (isWhitespace(Src[I])) {
511 NewArgv.push_back(Saver.saveCStr(Token.c_str()));
516 // This is a normal character. Append it.
517 Token.push_back(Src[I]);
520 // Append the last token after hitting EOF with no whitespace.
522 NewArgv.push_back(Saver.saveCStr(Token.c_str()));
525 /// Backslashes are interpreted in a rather complicated way in the Windows-style
526 /// command line, because backslashes are used both to separate path and to
527 /// escape double quote. This method consumes runs of backslashes as well as the
528 /// following double quote if it's escaped.
530 /// * If an even number of backslashes is followed by a double quote, one
531 /// backslash is output for every pair of backslashes, and the last double
532 /// quote remains unconsumed. The double quote will later be interpreted as
533 /// the start or end of a quoted string in the main loop outside of this
536 /// * If an odd number of backslashes is followed by a double quote, one
537 /// backslash is output for every pair of backslashes, and a double quote is
538 /// output for the last pair of backslash-double quote. The double quote is
539 /// consumed in this case.
541 /// * Otherwise, backslashes are interpreted literally.
542 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
543 size_t E = Src.size();
544 int BackslashCount = 0;
545 // Skip the backslashes.
549 } while (I != E && Src[I] == '\\');
551 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
552 if (FollowedByDoubleQuote) {
553 Token.append(BackslashCount / 2, '\\');
554 if (BackslashCount % 2 == 0)
556 Token.push_back('"');
559 Token.append(BackslashCount, '\\');
563 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
564 SmallVectorImpl<const char *> &NewArgv) {
565 SmallString<128> Token;
567 // This is a small state machine to consume characters until it reaches the
568 // end of the source string.
569 enum { INIT, UNQUOTED, QUOTED } State = INIT;
570 for (size_t I = 0, E = Src.size(); I != E; ++I) {
571 // INIT state indicates that the current input index is at the start of
572 // the string or between tokens.
574 if (isWhitespace(Src[I]))
580 if (Src[I] == '\\') {
581 I = parseBackslash(Src, I, Token);
585 Token.push_back(Src[I]);
590 // UNQUOTED state means that it's reading a token not quoted by double
592 if (State == UNQUOTED) {
593 // Whitespace means the end of the token.
594 if (isWhitespace(Src[I])) {
595 NewArgv.push_back(Saver.saveCStr(Token.c_str()));
604 if (Src[I] == '\\') {
605 I = parseBackslash(Src, I, Token);
608 Token.push_back(Src[I]);
612 // QUOTED state means that it's reading a token quoted by double quotes.
613 if (State == QUOTED) {
618 if (Src[I] == '\\') {
619 I = parseBackslash(Src, I, Token);
622 Token.push_back(Src[I]);
625 // Append the last token after hitting EOF with no whitespace.
627 NewArgv.push_back(Saver.saveCStr(Token.c_str()));
630 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
631 TokenizerCallback Tokenizer,
632 SmallVectorImpl<const char *> &NewArgv) {
633 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
634 MemoryBuffer::getFile(FName);
637 MemoryBuffer &MemBuf = *MemBufOrErr.get();
638 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
640 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
641 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
643 if (hasUTF16ByteOrderMark(BufRef)) {
644 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
646 Str = StringRef(UTF8Buf);
649 // Tokenize the contents into NewArgv.
650 Tokenizer(Str, Saver, NewArgv);
655 /// \brief Expand response files on a command line recursively using the given
656 /// StringSaver and tokenization strategy.
657 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
658 SmallVectorImpl<const char *> &Argv) {
659 unsigned RspFiles = 0;
660 bool AllExpanded = true;
662 // Don't cache Argv.size() because it can change.
663 for (unsigned I = 0; I != Argv.size(); ) {
664 const char *Arg = Argv[I];
670 // If we have too many response files, leave some unexpanded. This avoids
671 // crashing on self-referential response files.
675 // Replace this response file argument with the tokenization of its
676 // contents. Nested response files are expanded in subsequent iterations.
677 // FIXME: If a nested response file uses a relative path, is it relative to
678 // the cwd of the process or the response file?
679 SmallVector<const char *, 0> ExpandedArgv;
680 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
681 // We couldn't read this file, so we leave it in the argument stream and
687 Argv.erase(Argv.begin() + I);
688 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
693 /// ParseEnvironmentOptions - An alternative entry point to the
694 /// CommandLine library, which allows you to read the program's name
695 /// from the caller (as PROGNAME) and its command-line arguments from
696 /// an environment variable (whose name is given in ENVVAR).
698 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
699 const char *Overview) {
701 assert(progName && "Program name not specified");
702 assert(envVar && "Environment variable name missing");
704 // Get the environment variable they want us to parse options out of.
705 const char *envValue = getenv(envVar);
709 // Get program's "name", which we wouldn't know without the caller
711 SmallVector<const char *, 20> newArgv;
713 newArgv.push_back(Saver.saveCStr(progName));
715 // Parse the value of the environment variable into a "command line"
716 // and hand it off to ParseCommandLineOptions().
717 TokenizeGNUCommandLine(envValue, Saver, newArgv);
718 int newArgc = static_cast<int>(newArgv.size());
719 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
722 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
723 const char *Overview) {
724 // Process all registered options.
725 SmallVector<Option*, 4> PositionalOpts;
726 SmallVector<Option*, 4> SinkOpts;
727 StringMap<Option*> Opts;
728 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
730 assert((!Opts.empty() || !PositionalOpts.empty()) &&
731 "No options specified!");
733 // Expand response files.
734 SmallVector<const char *, 20> newArgv;
735 for (int i = 0; i != argc; ++i)
736 newArgv.push_back(argv[i]);
738 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
740 argc = static_cast<int>(newArgv.size());
742 // Copy the program name into ProgName, making sure not to overflow it.
743 StringRef ProgName = sys::path::filename(argv[0]);
744 size_t Len = std::min(ProgName.size(), size_t(79));
745 memcpy(ProgramName, ProgName.data(), Len);
746 ProgramName[Len] = '\0';
748 ProgramOverview = Overview;
749 bool ErrorParsing = false;
751 // Check out the positional arguments to collect information about them.
752 unsigned NumPositionalRequired = 0;
754 // Determine whether or not there are an unlimited number of positionals
755 bool HasUnlimitedPositionals = false;
757 Option *ConsumeAfterOpt = nullptr;
758 if (!PositionalOpts.empty()) {
759 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
760 assert(PositionalOpts.size() > 1 &&
761 "Cannot specify cl::ConsumeAfter without a positional argument!");
762 ConsumeAfterOpt = PositionalOpts[0];
765 // Calculate how many positional values are _required_.
766 bool UnboundedFound = false;
767 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
769 Option *Opt = PositionalOpts[i];
770 if (RequiresValue(Opt))
771 ++NumPositionalRequired;
772 else if (ConsumeAfterOpt) {
773 // ConsumeAfter cannot be combined with "optional" positional options
774 // unless there is only one positional argument...
775 if (PositionalOpts.size() > 2)
777 Opt->error("error - this positional option will never be matched, "
778 "because it does not Require a value, and a "
779 "cl::ConsumeAfter option is active!");
780 } else if (UnboundedFound && !Opt->ArgStr[0]) {
781 // This option does not "require" a value... Make sure this option is
782 // not specified after an option that eats all extra arguments, or this
783 // one will never get any!
785 ErrorParsing |= Opt->error("error - option can never match, because "
786 "another positional argument will match an "
787 "unbounded number of values, and this option"
788 " does not require a value!");
790 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
792 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
795 // PositionalVals - A vector of "positional" arguments we accumulate into
796 // the process at the end.
798 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
800 // If the program has named positional arguments, and the name has been run
801 // across, keep track of which positional argument was named. Otherwise put
802 // the positional args into the PositionalVals list...
803 Option *ActivePositionalArg = nullptr;
805 // Loop over all of the arguments... processing them.
806 bool DashDashFound = false; // Have we read '--'?
807 for (int i = 1; i < argc; ++i) {
808 Option *Handler = nullptr;
809 Option *NearestHandler = nullptr;
810 std::string NearestHandlerString;
812 StringRef ArgName = "";
814 // If the option list changed, this means that some command line
815 // option has just been registered or deregistered. This can occur in
816 // response to things like -load, etc. If this happens, rescan the options.
817 if (OptionListChanged) {
818 PositionalOpts.clear();
821 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
822 OptionListChanged = false;
825 // Check to see if this is a positional argument. This argument is
826 // considered to be positional if it doesn't start with '-', if it is "-"
827 // itself, or if we have seen "--" already.
829 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
830 // Positional argument!
831 if (ActivePositionalArg) {
832 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
833 continue; // We are done!
836 if (!PositionalOpts.empty()) {
837 PositionalVals.push_back(std::make_pair(argv[i],i));
839 // All of the positional arguments have been fulfulled, give the rest to
840 // the consume after option... if it's specified...
842 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
843 for (++i; i < argc; ++i)
844 PositionalVals.push_back(std::make_pair(argv[i],i));
845 break; // Handle outside of the argument processing loop...
848 // Delay processing positional arguments until the end...
851 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
853 DashDashFound = true; // This is the mythical "--"?
854 continue; // Don't try to process it as an argument itself.
855 } else if (ActivePositionalArg &&
856 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
857 // If there is a positional argument eating options, check to see if this
858 // option is another positional argument. If so, treat it as an argument,
859 // otherwise feed it to the eating positional.
861 // Eat leading dashes.
862 while (!ArgName.empty() && ArgName[0] == '-')
863 ArgName = ArgName.substr(1);
865 Handler = LookupOption(ArgName, Value, Opts);
866 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
867 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
868 continue; // We are done!
871 } else { // We start with a '-', must be an argument.
873 // Eat leading dashes.
874 while (!ArgName.empty() && ArgName[0] == '-')
875 ArgName = ArgName.substr(1);
877 Handler = LookupOption(ArgName, Value, Opts);
879 // Check to see if this "option" is really a prefixed or grouped argument.
881 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
884 // Otherwise, look for the closest available option to report to the user
885 // in the upcoming error.
886 if (!Handler && SinkOpts.empty())
887 NearestHandler = LookupNearestOption(ArgName, Opts,
888 NearestHandlerString);
892 if (SinkOpts.empty()) {
893 errs() << ProgramName << ": Unknown command line argument '"
894 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
896 if (NearestHandler) {
897 // If we know a near match, report it as well.
898 errs() << ProgramName << ": Did you mean '-"
899 << NearestHandlerString << "'?\n";
904 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
905 E = SinkOpts.end(); I != E ; ++I)
906 (*I)->addOccurrence(i, "", argv[i]);
911 // If this is a named positional argument, just remember that it is the
913 if (Handler->getFormattingFlag() == cl::Positional)
914 ActivePositionalArg = Handler;
916 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
919 // Check and handle positional arguments now...
920 if (NumPositionalRequired > PositionalVals.size()) {
921 errs() << ProgramName
922 << ": Not enough positional command line arguments specified!\n"
923 << "Must specify at least " << NumPositionalRequired
924 << " positional arguments: See: " << argv[0] << " -help\n";
927 } else if (!HasUnlimitedPositionals &&
928 PositionalVals.size() > PositionalOpts.size()) {
929 errs() << ProgramName
930 << ": Too many positional arguments specified!\n"
931 << "Can specify at most " << PositionalOpts.size()
932 << " positional arguments: See: " << argv[0] << " -help\n";
935 } else if (!ConsumeAfterOpt) {
936 // Positional args have already been handled if ConsumeAfter is specified.
937 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
938 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
939 if (RequiresValue(PositionalOpts[i])) {
940 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
941 PositionalVals[ValNo].second);
943 --NumPositionalRequired; // We fulfilled our duty...
946 // If we _can_ give this option more arguments, do so now, as long as we
947 // do not give it values that others need. 'Done' controls whether the
948 // option even _WANTS_ any more.
950 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
951 while (NumVals-ValNo > NumPositionalRequired && !Done) {
952 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
954 Done = true; // Optional arguments want _at most_ one value
956 case cl::ZeroOrMore: // Zero or more will take all they can get...
957 case cl::OneOrMore: // One or more will take all they can get...
958 ProvidePositionalOption(PositionalOpts[i],
959 PositionalVals[ValNo].first,
960 PositionalVals[ValNo].second);
964 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
965 "positional argument processing!");
970 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
972 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
973 if (RequiresValue(PositionalOpts[j])) {
974 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
975 PositionalVals[ValNo].first,
976 PositionalVals[ValNo].second);
980 // Handle the case where there is just one positional option, and it's
981 // optional. In this case, we want to give JUST THE FIRST option to the
982 // positional option and keep the rest for the consume after. The above
983 // loop would have assigned no values to positional options in this case.
985 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
986 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
987 PositionalVals[ValNo].first,
988 PositionalVals[ValNo].second);
992 // Handle over all of the rest of the arguments to the
993 // cl::ConsumeAfter command line option...
994 for (; ValNo != PositionalVals.size(); ++ValNo)
995 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
996 PositionalVals[ValNo].first,
997 PositionalVals[ValNo].second);
1000 // Loop over args and make sure all required args are specified!
1001 for (const auto &Opt : Opts) {
1002 switch (Opt.second->getNumOccurrencesFlag()) {
1005 if (Opt.second->getNumOccurrences() == 0) {
1006 Opt.second->error("must be specified at least once!");
1007 ErrorParsing = true;
1015 // Now that we know if -debug is specified, we can use it.
1016 // Note that if ReadResponseFiles == true, this must be done before the
1017 // memory allocated for the expanded command line is free()d below.
1018 DEBUG(dbgs() << "Args: ";
1019 for (int i = 0; i < argc; ++i)
1020 dbgs() << argv[i] << ' ';
1024 // Free all of the memory allocated to the map. Command line options may only
1025 // be processed once!
1027 PositionalOpts.clear();
1030 // If we had an error processing our arguments, don't let the program execute
1031 if (ErrorParsing) exit(1);
1034 //===----------------------------------------------------------------------===//
1035 // Option Base class implementation
1038 bool Option::error(const Twine &Message, StringRef ArgName) {
1039 if (!ArgName.data()) ArgName = ArgStr;
1040 if (ArgName.empty())
1041 errs() << HelpStr; // Be nice for positional arguments
1043 errs() << ProgramName << ": for the -" << ArgName;
1045 errs() << " option: " << Message << "\n";
1049 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1050 StringRef Value, bool MultiArg) {
1052 NumOccurrences++; // Increment the number of times we have been seen
1054 switch (getNumOccurrencesFlag()) {
1056 if (NumOccurrences > 1)
1057 return error("may only occur zero or one times!", ArgName);
1060 if (NumOccurrences > 1)
1061 return error("must occur exactly one time!", ArgName);
1065 case ConsumeAfter: break;
1068 return handleOccurrence(pos, ArgName, Value);
1072 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1073 // has been specified yet.
1075 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1076 if (O.ValueStr[0] == 0) return DefaultMsg;
1080 //===----------------------------------------------------------------------===//
1081 // cl::alias class implementation
1084 // Return the width of the option tag for printing...
1085 size_t alias::getOptionWidth() const {
1086 return std::strlen(ArgStr)+6;
1089 static void printHelpStr(StringRef HelpStr, size_t Indent,
1090 size_t FirstLineIndentedBy) {
1091 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1092 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1093 while (!Split.second.empty()) {
1094 Split = Split.second.split('\n');
1095 outs().indent(Indent) << Split.first << "\n";
1099 // Print out the option for the alias.
1100 void alias::printOptionInfo(size_t GlobalWidth) const {
1101 outs() << " -" << ArgStr;
1102 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1105 //===----------------------------------------------------------------------===//
1106 // Parser Implementation code...
1109 // basic_parser implementation
1112 // Return the width of the option tag for printing...
1113 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1114 size_t Len = std::strlen(O.ArgStr);
1115 if (const char *ValName = getValueName())
1116 Len += std::strlen(getValueStr(O, ValName))+3;
1121 // printOptionInfo - Print out information about this option. The
1122 // to-be-maintained width is specified.
1124 void basic_parser_impl::printOptionInfo(const Option &O,
1125 size_t GlobalWidth) const {
1126 outs() << " -" << O.ArgStr;
1128 if (const char *ValName = getValueName())
1129 outs() << "=<" << getValueStr(O, ValName) << '>';
1131 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1134 void basic_parser_impl::printOptionName(const Option &O,
1135 size_t GlobalWidth) const {
1136 outs() << " -" << O.ArgStr;
1137 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1141 // parser<bool> implementation
1143 bool parser<bool>::parse(Option &O, StringRef ArgName,
1144 StringRef Arg, bool &Value) {
1145 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1151 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1155 return O.error("'" + Arg +
1156 "' is invalid value for boolean argument! Try 0 or 1");
1159 // parser<boolOrDefault> implementation
1161 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1162 StringRef Arg, boolOrDefault &Value) {
1163 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1168 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1173 return O.error("'" + Arg +
1174 "' is invalid value for boolean argument! Try 0 or 1");
1177 // parser<int> implementation
1179 bool parser<int>::parse(Option &O, StringRef ArgName,
1180 StringRef Arg, int &Value) {
1181 if (Arg.getAsInteger(0, Value))
1182 return O.error("'" + Arg + "' value invalid for integer argument!");
1186 // parser<unsigned> implementation
1188 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1189 StringRef Arg, unsigned &Value) {
1191 if (Arg.getAsInteger(0, Value))
1192 return O.error("'" + Arg + "' value invalid for uint argument!");
1196 // parser<unsigned long long> implementation
1198 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1199 StringRef Arg, unsigned long long &Value){
1201 if (Arg.getAsInteger(0, Value))
1202 return O.error("'" + Arg + "' value invalid for uint argument!");
1206 // parser<double>/parser<float> implementation
1208 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1209 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1210 const char *ArgStart = TmpStr.c_str();
1212 Value = strtod(ArgStart, &End);
1214 return O.error("'" + Arg + "' value invalid for floating point argument!");
1218 bool parser<double>::parse(Option &O, StringRef ArgName,
1219 StringRef Arg, double &Val) {
1220 return parseDouble(O, Arg, Val);
1223 bool parser<float>::parse(Option &O, StringRef ArgName,
1224 StringRef Arg, float &Val) {
1226 if (parseDouble(O, Arg, dVal))
1234 // generic_parser_base implementation
1237 // findOption - Return the option number corresponding to the specified
1238 // argument string. If the option is not found, getNumOptions() is returned.
1240 unsigned generic_parser_base::findOption(const char *Name) {
1241 unsigned e = getNumOptions();
1243 for (unsigned i = 0; i != e; ++i) {
1244 if (strcmp(getOption(i), Name) == 0)
1251 // Return the width of the option tag for printing...
1252 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1253 if (O.hasArgStr()) {
1254 size_t Size = std::strlen(O.ArgStr)+6;
1255 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1256 Size = std::max(Size, std::strlen(getOption(i))+8);
1259 size_t BaseSize = 0;
1260 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1261 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1266 // printOptionInfo - Print out information about this option. The
1267 // to-be-maintained width is specified.
1269 void generic_parser_base::printOptionInfo(const Option &O,
1270 size_t GlobalWidth) const {
1271 if (O.hasArgStr()) {
1272 outs() << " -" << O.ArgStr;
1273 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1275 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1276 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1277 outs() << " =" << getOption(i);
1278 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1282 outs() << " " << O.HelpStr << '\n';
1283 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1284 const char *Option = getOption(i);
1285 outs() << " -" << Option;
1286 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1291 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1293 // printGenericOptionDiff - Print the value of this option and it's default.
1295 // "Generic" options have each value mapped to a name.
1296 void generic_parser_base::
1297 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1298 const GenericOptionValue &Default,
1299 size_t GlobalWidth) const {
1300 outs() << " -" << O.ArgStr;
1301 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1303 unsigned NumOpts = getNumOptions();
1304 for (unsigned i = 0; i != NumOpts; ++i) {
1305 if (Value.compare(getOptionValue(i)))
1308 outs() << "= " << getOption(i);
1309 size_t L = std::strlen(getOption(i));
1310 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1311 outs().indent(NumSpaces) << " (default: ";
1312 for (unsigned j = 0; j != NumOpts; ++j) {
1313 if (Default.compare(getOptionValue(j)))
1315 outs() << getOption(j);
1321 outs() << "= *unknown option value*\n";
1324 // printOptionDiff - Specializations for printing basic value types.
1326 #define PRINT_OPT_DIFF(T) \
1328 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1329 size_t GlobalWidth) const { \
1330 printOptionName(O, GlobalWidth); \
1333 raw_string_ostream SS(Str); \
1336 outs() << "= " << Str; \
1337 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1338 outs().indent(NumSpaces) << " (default: "; \
1340 outs() << D.getValue(); \
1342 outs() << "*no default*"; \
1346 PRINT_OPT_DIFF(bool)
1347 PRINT_OPT_DIFF(boolOrDefault)
1349 PRINT_OPT_DIFF(unsigned)
1350 PRINT_OPT_DIFF(unsigned long long)
1351 PRINT_OPT_DIFF(double)
1352 PRINT_OPT_DIFF(float)
1353 PRINT_OPT_DIFF(char)
1355 void parser<std::string>::
1356 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1357 size_t GlobalWidth) const {
1358 printOptionName(O, GlobalWidth);
1359 outs() << "= " << V;
1360 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1361 outs().indent(NumSpaces) << " (default: ";
1363 outs() << D.getValue();
1365 outs() << "*no default*";
1369 // Print a placeholder for options that don't yet support printOptionDiff().
1370 void basic_parser_impl::
1371 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1372 printOptionName(O, GlobalWidth);
1373 outs() << "= *cannot print option value*\n";
1376 //===----------------------------------------------------------------------===//
1377 // -help and -help-hidden option implementation
1380 static int OptNameCompare(const void *LHS, const void *RHS) {
1381 typedef std::pair<const char *, Option*> pair_ty;
1383 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1386 // Copy Options into a vector so we can sort them as we like.
1388 sortOpts(StringMap<Option*> &OptMap,
1389 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1391 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1393 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1395 // Ignore really-hidden options.
1396 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1399 // Unless showhidden is set, ignore hidden flags.
1400 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1403 // If we've already seen this option, don't add it to the list again.
1404 if (!OptionSet.insert(I->second))
1407 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1411 // Sort the options list alphabetically.
1412 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1419 const bool ShowHidden;
1420 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1421 // Print the options. Opts is assumed to be alphabetically sorted.
1422 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1423 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1424 Opts[i].second->printOptionInfo(MaxArgLen);
1428 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1429 virtual ~HelpPrinter() {}
1431 // Invoke the printer.
1432 void operator=(bool Value) {
1433 if (Value == false) return;
1435 // Get all the options.
1436 SmallVector<Option*, 4> PositionalOpts;
1437 SmallVector<Option*, 4> SinkOpts;
1438 StringMap<Option*> OptMap;
1439 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1441 StrOptionPairVector Opts;
1442 sortOpts(OptMap, Opts, ShowHidden);
1444 if (ProgramOverview)
1445 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1447 outs() << "USAGE: " << ProgramName << " [options]";
1449 // Print out the positional options.
1450 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1451 if (!PositionalOpts.empty() &&
1452 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1453 CAOpt = PositionalOpts[0];
1455 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1456 if (PositionalOpts[i]->ArgStr[0])
1457 outs() << " --" << PositionalOpts[i]->ArgStr;
1458 outs() << " " << PositionalOpts[i]->HelpStr;
1461 // Print the consume after option info if it exists...
1462 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1466 // Compute the maximum argument length...
1467 size_t MaxArgLen = 0;
1468 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1469 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1471 outs() << "OPTIONS:\n";
1472 printOptions(Opts, MaxArgLen);
1474 // Print any extra help the user has declared.
1475 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1476 E = MoreHelp->end();
1481 // Halt the program since help information was printed
1486 class CategorizedHelpPrinter : public HelpPrinter {
1488 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1490 // Helper function for printOptions().
1491 // It shall return true if A's name should be lexographically
1492 // ordered before B's name. It returns false otherwise.
1493 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1494 return strcmp(A->getName(), B->getName()) < 0;
1497 // Make sure we inherit our base class's operator=()
1498 using HelpPrinter::operator= ;
1501 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1502 std::vector<OptionCategory *> SortedCategories;
1503 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1505 // Collect registered option categories into vector in preparation for
1507 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1508 E = RegisteredOptionCategories->end();
1510 SortedCategories.push_back(*I);
1513 // Sort the different option categories alphabetically.
1514 assert(SortedCategories.size() > 0 && "No option categories registered!");
1515 std::sort(SortedCategories.begin(), SortedCategories.end(),
1516 OptionCategoryCompare);
1518 // Create map to empty vectors.
1519 for (std::vector<OptionCategory *>::const_iterator
1520 I = SortedCategories.begin(),
1521 E = SortedCategories.end();
1523 CategorizedOptions[*I] = std::vector<Option *>();
1525 // Walk through pre-sorted options and assign into categories.
1526 // Because the options are already alphabetically sorted the
1527 // options within categories will also be alphabetically sorted.
1528 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1529 Option *Opt = Opts[I].second;
1530 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1531 "Option has an unregistered category");
1532 CategorizedOptions[Opt->Category].push_back(Opt);
1536 for (std::vector<OptionCategory *>::const_iterator
1537 Category = SortedCategories.begin(),
1538 E = SortedCategories.end();
1539 Category != E; ++Category) {
1540 // Hide empty categories for -help, but show for -help-hidden.
1541 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1542 if (!ShowHidden && IsEmptyCategory)
1545 // Print category information.
1547 outs() << (*Category)->getName() << ":\n";
1549 // Check if description is set.
1550 if ((*Category)->getDescription() != nullptr)
1551 outs() << (*Category)->getDescription() << "\n\n";
1555 // When using -help-hidden explicitly state if the category has no
1556 // options associated with it.
1557 if (IsEmptyCategory) {
1558 outs() << " This option category has no options.\n";
1561 // Loop over the options in the category and print.
1562 for (std::vector<Option *>::const_iterator
1563 Opt = CategorizedOptions[*Category].begin(),
1564 E = CategorizedOptions[*Category].end();
1566 (*Opt)->printOptionInfo(MaxArgLen);
1571 // This wraps the Uncategorizing and Categorizing printers and decides
1572 // at run time which should be invoked.
1573 class HelpPrinterWrapper {
1575 HelpPrinter &UncategorizedPrinter;
1576 CategorizedHelpPrinter &CategorizedPrinter;
1579 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1580 CategorizedHelpPrinter &CategorizedPrinter) :
1581 UncategorizedPrinter(UncategorizedPrinter),
1582 CategorizedPrinter(CategorizedPrinter) { }
1584 // Invoke the printer.
1585 void operator=(bool Value);
1588 } // End anonymous namespace
1590 // Declare the four HelpPrinter instances that are used to print out help, or
1591 // help-hidden as an uncategorized list or in categories.
1592 static HelpPrinter UncategorizedNormalPrinter(false);
1593 static HelpPrinter UncategorizedHiddenPrinter(true);
1594 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1595 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1598 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1599 // a categorizing help printer
1600 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1601 CategorizedNormalPrinter);
1602 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1603 CategorizedHiddenPrinter);
1605 // Define uncategorized help printers.
1606 // -help-list is hidden by default because if Option categories are being used
1607 // then -help behaves the same as -help-list.
1608 static cl::opt<HelpPrinter, true, parser<bool> >
1610 cl::desc("Display list of available options (-help-list-hidden for more)"),
1611 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1613 static cl::opt<HelpPrinter, true, parser<bool> >
1614 HLHOp("help-list-hidden",
1615 cl::desc("Display list of all available options"),
1616 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1618 // Define uncategorized/categorized help printers. These printers change their
1619 // behaviour at runtime depending on whether one or more Option categories have
1621 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1622 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1623 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1625 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1626 HHOp("help-hidden", cl::desc("Display all available options"),
1627 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1631 static cl::opt<bool>
1632 PrintOptions("print-options",
1633 cl::desc("Print non-default options after command line parsing"),
1634 cl::Hidden, cl::init(false));
1636 static cl::opt<bool>
1637 PrintAllOptions("print-all-options",
1638 cl::desc("Print all option values after command line parsing"),
1639 cl::Hidden, cl::init(false));
1641 void HelpPrinterWrapper::operator=(bool Value) {
1645 // Decide which printer to invoke. If more than one option category is
1646 // registered then it is useful to show the categorized help instead of
1647 // uncategorized help.
1648 if (RegisteredOptionCategories->size() > 1) {
1649 // unhide -help-list option so user can have uncategorized output if they
1651 HLOp.setHiddenFlag(NotHidden);
1653 CategorizedPrinter = true; // Invoke categorized printer
1656 UncategorizedPrinter = true; // Invoke uncategorized printer
1659 // Print the value of each option.
1660 void cl::PrintOptionValues() {
1661 if (!PrintOptions && !PrintAllOptions) return;
1663 // Get all the options.
1664 SmallVector<Option*, 4> PositionalOpts;
1665 SmallVector<Option*, 4> SinkOpts;
1666 StringMap<Option*> OptMap;
1667 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1669 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1670 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1672 // Compute the maximum argument length...
1673 size_t MaxArgLen = 0;
1674 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1675 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1677 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1678 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1681 static void (*OverrideVersionPrinter)() = nullptr;
1683 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
1686 class VersionPrinter {
1689 raw_ostream &OS = outs();
1690 OS << "LLVM (http://llvm.org/):\n"
1691 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1692 #ifdef LLVM_VERSION_INFO
1693 OS << " " << LLVM_VERSION_INFO;
1696 #ifndef __OPTIMIZE__
1697 OS << "DEBUG build";
1699 OS << "Optimized build";
1702 OS << " with assertions";
1704 std::string CPU = sys::getHostCPUName();
1705 if (CPU == "generic") CPU = "(unknown)";
1707 #if (ENABLE_TIMESTAMPS == 1)
1708 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1710 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1711 << " Host CPU: " << CPU << '\n';
1713 void operator=(bool OptionWasSpecified) {
1714 if (!OptionWasSpecified) return;
1716 if (OverrideVersionPrinter != nullptr) {
1717 (*OverrideVersionPrinter)();
1722 // Iterate over any registered extra printers and call them to add further
1724 if (ExtraVersionPrinters != nullptr) {
1726 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1727 E = ExtraVersionPrinters->end();
1735 } // End anonymous namespace
1738 // Define the --version option that prints out the LLVM version for the tool
1739 static VersionPrinter VersionPrinterInstance;
1741 static cl::opt<VersionPrinter, true, parser<bool> >
1742 VersOp("version", cl::desc("Display the version of this program"),
1743 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1745 // Utility function for printing the help message.
1746 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1747 // This looks weird, but it actually prints the help message. The Printers are
1748 // types of HelpPrinter and the help gets printed when its operator= is
1749 // invoked. That's because the "normal" usages of the help printer is to be
1750 // assigned true/false depending on whether -help or -help-hidden was given or
1751 // not. Since we're circumventing that we have to make it look like -help or
1752 // -help-hidden were given, so we assign true.
1754 if (!Hidden && !Categorized)
1755 UncategorizedNormalPrinter = true;
1756 else if (!Hidden && Categorized)
1757 CategorizedNormalPrinter = true;
1758 else if (Hidden && !Categorized)
1759 UncategorizedHiddenPrinter = true;
1761 CategorizedHiddenPrinter = true;
1764 /// Utility function for printing version number.
1765 void cl::PrintVersionMessage() {
1766 VersionPrinterInstance.print();
1769 void cl::SetVersionPrinter(void (*func)()) {
1770 OverrideVersionPrinter = func;
1773 void cl::AddExtraVersionPrinter(void (*func)()) {
1774 if (!ExtraVersionPrinters)
1775 ExtraVersionPrinters = new std::vector<void (*)()>;
1777 ExtraVersionPrinters->push_back(func);
1780 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1782 // Get all the options.
1783 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1784 SmallVector<Option*, 4> SinkOpts; //NOT USED
1785 assert(Map.size() == 0 && "StringMap must be empty");
1786 GetOptionInfo(PositionalOpts, SinkOpts, Map);