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"
34 #include "llvm/Support/system_error.h"
41 //===----------------------------------------------------------------------===//
42 // Template instantiations and anchors.
44 namespace llvm { namespace cl {
45 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
46 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
47 TEMPLATE_INSTANTIATION(class basic_parser<int>);
48 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
49 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
50 TEMPLATE_INSTANTIATION(class basic_parser<double>);
51 TEMPLATE_INSTANTIATION(class basic_parser<float>);
52 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
53 TEMPLATE_INSTANTIATION(class basic_parser<char>);
55 TEMPLATE_INSTANTIATION(class opt<unsigned>);
56 TEMPLATE_INSTANTIATION(class opt<int>);
57 TEMPLATE_INSTANTIATION(class opt<std::string>);
58 TEMPLATE_INSTANTIATION(class opt<char>);
59 TEMPLATE_INSTANTIATION(class opt<bool>);
60 } } // end namespace llvm::cl
62 // Pin the vtables to this file.
63 void GenericOptionValue::anchor() {}
64 void OptionValue<boolOrDefault>::anchor() {}
65 void OptionValue<std::string>::anchor() {}
66 void Option::anchor() {}
67 void basic_parser_impl::anchor() {}
68 void parser<bool>::anchor() {}
69 void parser<boolOrDefault>::anchor() {}
70 void parser<int>::anchor() {}
71 void parser<unsigned>::anchor() {}
72 void parser<unsigned long long>::anchor() {}
73 void parser<double>::anchor() {}
74 void parser<float>::anchor() {}
75 void parser<std::string>::anchor() {}
76 void parser<char>::anchor() {}
77 void StringSaver::anchor() {}
79 //===----------------------------------------------------------------------===//
81 // Globals for name and overview of program. Program name is not a string to
82 // avoid static ctor/dtor issues.
83 static char ProgramName[80] = "<premain>";
84 static const char *ProgramOverview = nullptr;
86 // This collects additional help to be printed.
87 static ManagedStatic<std::vector<const char*> > MoreHelp;
89 extrahelp::extrahelp(const char *Help)
91 MoreHelp->push_back(Help);
94 static bool OptionListChanged = false;
96 // MarkOptionsChanged - Internal helper function.
97 void cl::MarkOptionsChanged() {
98 OptionListChanged = true;
101 /// RegisteredOptionList - This is the list of the command line options that
102 /// have statically constructed themselves.
103 static Option *RegisteredOptionList = nullptr;
105 void Option::addArgument() {
106 assert(NextRegistered == 0 && "argument multiply registered!");
108 NextRegistered = RegisteredOptionList;
109 RegisteredOptionList = this;
110 MarkOptionsChanged();
113 void Option::removeArgument() {
114 assert(NextRegistered != 0 && "argument never registered");
115 assert(RegisteredOptionList == this && "argument is not the last registered");
116 RegisteredOptionList = NextRegistered;
117 MarkOptionsChanged();
120 // This collects the different option categories that have been registered.
121 typedef SmallPtrSet<OptionCategory*,16> OptionCatSet;
122 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
124 // Initialise the general option category.
125 OptionCategory llvm::cl::GeneralCategory("General options");
127 void OptionCategory::registerCategory() {
128 assert(std::count_if(RegisteredOptionCategories->begin(),
129 RegisteredOptionCategories->end(),
130 [this](const OptionCategory *Category) {
131 return getName() == Category->getName();
132 }) == 0 && "Duplicate option categories");
134 RegisteredOptionCategories->insert(this);
137 //===----------------------------------------------------------------------===//
138 // Basic, shared command line option processing machinery.
141 /// GetOptionInfo - Scan the list of registered options, turning them into data
142 /// structures that are easier to handle.
143 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
144 SmallVectorImpl<Option*> &SinkOpts,
145 StringMap<Option*> &OptionsMap) {
146 SmallVector<const char*, 16> OptionNames;
147 Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
148 for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
149 // If this option wants to handle multiple option names, get the full set.
150 // This handles enum options like "-O1 -O2" etc.
151 O->getExtraOptionNames(OptionNames);
153 OptionNames.push_back(O->ArgStr);
155 // Handle named options.
156 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
157 // Add argument to the argument map!
158 if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
159 errs() << ProgramName << ": CommandLine Error: Argument '"
160 << OptionNames[i] << "' defined more than once!\n";
166 // Remember information about positional options.
167 if (O->getFormattingFlag() == cl::Positional)
168 PositionalOpts.push_back(O);
169 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
170 SinkOpts.push_back(O);
171 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
173 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
179 PositionalOpts.push_back(CAOpt);
181 // Make sure that they are in order of registration not backwards.
182 std::reverse(PositionalOpts.begin(), PositionalOpts.end());
186 /// LookupOption - Lookup the option specified by the specified option on the
187 /// command line. If there is a value specified (after an equal sign) return
188 /// that as well. This assumes that leading dashes have already been stripped.
189 static Option *LookupOption(StringRef &Arg, StringRef &Value,
190 const StringMap<Option*> &OptionsMap) {
191 // Reject all dashes.
192 if (Arg.empty()) return nullptr;
194 size_t EqualPos = Arg.find('=');
196 // If we have an equals sign, remember the value.
197 if (EqualPos == StringRef::npos) {
198 // Look up the option.
199 StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
200 return I != OptionsMap.end() ? I->second : nullptr;
203 // If the argument before the = is a valid option name, we match. If not,
204 // return Arg unmolested.
205 StringMap<Option*>::const_iterator I =
206 OptionsMap.find(Arg.substr(0, EqualPos));
207 if (I == OptionsMap.end()) return nullptr;
209 Value = Arg.substr(EqualPos+1);
210 Arg = Arg.substr(0, EqualPos);
214 /// LookupNearestOption - Lookup the closest match to the option specified by
215 /// the specified option on the command line. If there is a value specified
216 /// (after an equal sign) return that as well. This assumes that leading dashes
217 /// have already been stripped.
218 static Option *LookupNearestOption(StringRef Arg,
219 const StringMap<Option*> &OptionsMap,
220 std::string &NearestString) {
221 // Reject all dashes.
222 if (Arg.empty()) return nullptr;
224 // Split on any equal sign.
225 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
226 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
227 StringRef &RHS = SplitArg.second;
229 // Find the closest match.
230 Option *Best = nullptr;
231 unsigned BestDistance = 0;
232 for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
233 ie = OptionsMap.end(); it != ie; ++it) {
234 Option *O = it->second;
235 SmallVector<const char*, 16> OptionNames;
236 O->getExtraOptionNames(OptionNames);
238 OptionNames.push_back(O->ArgStr);
240 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
241 StringRef Flag = PermitValue ? LHS : Arg;
242 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
243 StringRef Name = OptionNames[i];
244 unsigned Distance = StringRef(Name).edit_distance(
245 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
246 if (!Best || Distance < BestDistance) {
248 BestDistance = Distance;
249 if (RHS.empty() || !PermitValue)
250 NearestString = OptionNames[i];
252 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
260 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
261 /// that does special handling of cl::CommaSeparated options.
262 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
263 StringRef ArgName, StringRef Value,
264 bool MultiArg = false) {
265 // Check to see if this option accepts a comma separated list of values. If
266 // it does, we have to split up the value into multiple values.
267 if (Handler->getMiscFlags() & CommaSeparated) {
268 StringRef Val(Value);
269 StringRef::size_type Pos = Val.find(',');
271 while (Pos != StringRef::npos) {
272 // Process the portion before the comma.
273 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
275 // Erase the portion before the comma, AND the comma.
276 Val = Val.substr(Pos+1);
277 Value.substr(Pos+1); // Increment the original value pointer as well.
278 // Check for another comma.
285 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
291 /// ProvideOption - For Value, this differentiates between an empty value ("")
292 /// and a null value (StringRef()). The later is accepted for arguments that
293 /// don't allow a value (-foo) the former is rejected (-foo=).
294 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
295 StringRef Value, int argc,
296 const char *const *argv, int &i) {
297 // Is this a multi-argument option?
298 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
300 // Enforce value requirements
301 switch (Handler->getValueExpectedFlag()) {
303 if (!Value.data()) { // No value specified?
305 return Handler->error("requires a value!");
306 // Steal the next argument, like for '-o filename'
310 case ValueDisallowed:
311 if (NumAdditionalVals > 0)
312 return Handler->error("multi-valued option specified"
313 " with ValueDisallowed modifier!");
316 return Handler->error("does not allow a value! '" +
317 Twine(Value) + "' specified.");
323 // If this isn't a multi-arg option, just run the handler.
324 if (NumAdditionalVals == 0)
325 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
327 // If it is, run the handle several times.
328 bool MultiArg = false;
331 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
337 while (NumAdditionalVals > 0) {
339 return Handler->error("not enough values!");
342 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
350 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
352 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
356 // Option predicates...
357 static inline bool isGrouping(const Option *O) {
358 return O->getFormattingFlag() == cl::Grouping;
360 static inline bool isPrefixedOrGrouping(const Option *O) {
361 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
364 // getOptionPred - Check to see if there are any options that satisfy the
365 // specified predicate with names that are the prefixes in Name. This is
366 // checked by progressively stripping characters off of the name, checking to
367 // see if there options that satisfy the predicate. If we find one, return it,
368 // otherwise return null.
370 static Option *getOptionPred(StringRef Name, size_t &Length,
371 bool (*Pred)(const Option*),
372 const StringMap<Option*> &OptionsMap) {
374 StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
376 // Loop while we haven't found an option and Name still has at least two
377 // characters in it (so that the next iteration will not be the empty
379 while (OMI == OptionsMap.end() && Name.size() > 1) {
380 Name = Name.substr(0, Name.size()-1); // Chop off the last character.
381 OMI = OptionsMap.find(Name);
384 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
385 Length = Name.size();
386 return OMI->second; // Found one!
388 return nullptr; // No option found!
391 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
392 /// with at least one '-') does not fully match an available option. Check to
393 /// see if this is a prefix or grouped option. If so, split arg into output an
394 /// Arg/Value pair and return the Option to parse it with.
395 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
397 const StringMap<Option*> &OptionsMap) {
398 if (Arg.size() == 1) return nullptr;
402 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
403 if (!PGOpt) return nullptr;
405 // If the option is a prefixed option, then the value is simply the
406 // rest of the name... so fall through to later processing, by
407 // setting up the argument name flags and value fields.
408 if (PGOpt->getFormattingFlag() == cl::Prefix) {
409 Value = Arg.substr(Length);
410 Arg = Arg.substr(0, Length);
411 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
415 // This must be a grouped option... handle them now. Grouping options can't
417 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
420 // Move current arg name out of Arg into OneArgName.
421 StringRef OneArgName = Arg.substr(0, Length);
422 Arg = Arg.substr(Length);
424 // Because ValueRequired is an invalid flag for grouped arguments,
425 // we don't need to pass argc/argv in.
426 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
427 "Option can not be cl::Grouping AND cl::ValueRequired!");
429 ErrorParsing |= ProvideOption(PGOpt, OneArgName,
430 StringRef(), 0, nullptr, Dummy);
432 // Get the next grouping option.
433 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
434 } while (PGOpt && Length != Arg.size());
436 // Return the last option with Arg cut down to just the last one.
442 static bool RequiresValue(const Option *O) {
443 return O->getNumOccurrencesFlag() == cl::Required ||
444 O->getNumOccurrencesFlag() == cl::OneOrMore;
447 static bool EatsUnboundedNumberOfValues(const Option *O) {
448 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
449 O->getNumOccurrencesFlag() == cl::OneOrMore;
452 static bool isWhitespace(char C) {
453 return strchr(" \t\n\r\f\v", C);
456 static bool isQuote(char C) {
457 return C == '\"' || C == '\'';
460 static bool isGNUSpecial(char C) {
461 return strchr("\\\"\' ", C);
464 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
465 SmallVectorImpl<const char *> &NewArgv) {
466 SmallString<128> Token;
467 for (size_t I = 0, E = Src.size(); I != E; ++I) {
468 // Consume runs of whitespace.
470 while (I != E && isWhitespace(Src[I]))
475 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
476 // they are literal. This makes it much easier to read Windows file paths.
477 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
478 ++I; // Skip the escape.
479 Token.push_back(Src[I]);
483 // Consume a quoted string.
484 if (isQuote(Src[I])) {
485 char Quote = Src[I++];
486 while (I != E && Src[I] != Quote) {
487 // Backslashes are literal, unless they escape a special character.
488 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
490 Token.push_back(Src[I]);
497 // End the token if this is whitespace.
498 if (isWhitespace(Src[I])) {
500 NewArgv.push_back(Saver.SaveString(Token.c_str()));
505 // This is a normal character. Append it.
506 Token.push_back(Src[I]);
509 // Append the last token after hitting EOF with no whitespace.
511 NewArgv.push_back(Saver.SaveString(Token.c_str()));
514 /// Backslashes are interpreted in a rather complicated way in the Windows-style
515 /// command line, because backslashes are used both to separate path and to
516 /// escape double quote. This method consumes runs of backslashes as well as the
517 /// following double quote if it's escaped.
519 /// * If an even number of backslashes is followed by a double quote, one
520 /// backslash is output for every pair of backslashes, and the last double
521 /// quote remains unconsumed. The double quote will later be interpreted as
522 /// the start or end of a quoted string in the main loop outside of this
525 /// * If an odd number of backslashes is followed by a double quote, one
526 /// backslash is output for every pair of backslashes, and a double quote is
527 /// output for the last pair of backslash-double quote. The double quote is
528 /// consumed in this case.
530 /// * Otherwise, backslashes are interpreted literally.
531 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
532 size_t E = Src.size();
533 int BackslashCount = 0;
534 // Skip the backslashes.
538 } while (I != E && Src[I] == '\\');
540 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
541 if (FollowedByDoubleQuote) {
542 Token.append(BackslashCount / 2, '\\');
543 if (BackslashCount % 2 == 0)
545 Token.push_back('"');
548 Token.append(BackslashCount, '\\');
552 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
553 SmallVectorImpl<const char *> &NewArgv) {
554 SmallString<128> Token;
556 // This is a small state machine to consume characters until it reaches the
557 // end of the source string.
558 enum { INIT, UNQUOTED, QUOTED } State = INIT;
559 for (size_t I = 0, E = Src.size(); I != E; ++I) {
560 // INIT state indicates that the current input index is at the start of
561 // the string or between tokens.
563 if (isWhitespace(Src[I]))
569 if (Src[I] == '\\') {
570 I = parseBackslash(Src, I, Token);
574 Token.push_back(Src[I]);
579 // UNQUOTED state means that it's reading a token not quoted by double
581 if (State == UNQUOTED) {
582 // Whitespace means the end of the token.
583 if (isWhitespace(Src[I])) {
584 NewArgv.push_back(Saver.SaveString(Token.c_str()));
593 if (Src[I] == '\\') {
594 I = parseBackslash(Src, I, Token);
597 Token.push_back(Src[I]);
601 // QUOTED state means that it's reading a token quoted by double quotes.
602 if (State == QUOTED) {
607 if (Src[I] == '\\') {
608 I = parseBackslash(Src, I, Token);
611 Token.push_back(Src[I]);
614 // Append the last token after hitting EOF with no whitespace.
616 NewArgv.push_back(Saver.SaveString(Token.c_str()));
619 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
620 TokenizerCallback Tokenizer,
621 SmallVectorImpl<const char *> &NewArgv) {
622 std::unique_ptr<MemoryBuffer> MemBuf;
623 if (MemoryBuffer::getFile(FName, MemBuf))
625 StringRef Str(MemBuf->getBufferStart(), MemBuf->getBufferSize());
627 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
628 ArrayRef<char> BufRef(MemBuf->getBufferStart(), MemBuf->getBufferEnd());
630 if (hasUTF16ByteOrderMark(BufRef)) {
631 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
633 Str = StringRef(UTF8Buf);
636 // Tokenize the contents into NewArgv.
637 Tokenizer(Str, Saver, NewArgv);
642 /// \brief Expand response files on a command line recursively using the given
643 /// StringSaver and tokenization strategy.
644 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
645 SmallVectorImpl<const char *> &Argv) {
646 unsigned RspFiles = 0;
647 bool AllExpanded = true;
649 // Don't cache Argv.size() because it can change.
650 for (unsigned I = 0; I != Argv.size(); ) {
651 const char *Arg = Argv[I];
657 // If we have too many response files, leave some unexpanded. This avoids
658 // crashing on self-referential response files.
662 // Replace this response file argument with the tokenization of its
663 // contents. Nested response files are expanded in subsequent iterations.
664 // FIXME: If a nested response file uses a relative path, is it relative to
665 // the cwd of the process or the response file?
666 SmallVector<const char *, 0> ExpandedArgv;
667 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv)) {
668 // We couldn't read this file, so we leave it in the argument stream and
674 Argv.erase(Argv.begin() + I);
675 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
681 class StrDupSaver : public StringSaver {
682 std::vector<char*> Dups;
685 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end();
691 const char *SaveString(const char *Str) override {
692 char *Dup = strdup(Str);
699 /// ParseEnvironmentOptions - An alternative entry point to the
700 /// CommandLine library, which allows you to read the program's name
701 /// from the caller (as PROGNAME) and its command-line arguments from
702 /// an environment variable (whose name is given in ENVVAR).
704 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
705 const char *Overview) {
707 assert(progName && "Program name not specified");
708 assert(envVar && "Environment variable name missing");
710 // Get the environment variable they want us to parse options out of.
711 const char *envValue = getenv(envVar);
715 // Get program's "name", which we wouldn't know without the caller
717 SmallVector<const char *, 20> newArgv;
719 newArgv.push_back(Saver.SaveString(progName));
721 // Parse the value of the environment variable into a "command line"
722 // and hand it off to ParseCommandLineOptions().
723 TokenizeGNUCommandLine(envValue, Saver, newArgv);
724 int newArgc = static_cast<int>(newArgv.size());
725 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
728 void cl::ParseCommandLineOptions(int argc, const char * const *argv,
729 const char *Overview) {
730 // Process all registered options.
731 SmallVector<Option*, 4> PositionalOpts;
732 SmallVector<Option*, 4> SinkOpts;
733 StringMap<Option*> Opts;
734 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
736 assert((!Opts.empty() || !PositionalOpts.empty()) &&
737 "No options specified!");
739 // Expand response files.
740 SmallVector<const char *, 20> newArgv;
741 for (int i = 0; i != argc; ++i)
742 newArgv.push_back(argv[i]);
744 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
746 argc = static_cast<int>(newArgv.size());
748 // Copy the program name into ProgName, making sure not to overflow it.
749 std::string ProgName = sys::path::filename(argv[0]);
750 size_t Len = std::min(ProgName.size(), size_t(79));
751 memcpy(ProgramName, ProgName.data(), Len);
752 ProgramName[Len] = '\0';
754 ProgramOverview = Overview;
755 bool ErrorParsing = false;
757 // Check out the positional arguments to collect information about them.
758 unsigned NumPositionalRequired = 0;
760 // Determine whether or not there are an unlimited number of positionals
761 bool HasUnlimitedPositionals = false;
763 Option *ConsumeAfterOpt = nullptr;
764 if (!PositionalOpts.empty()) {
765 if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
766 assert(PositionalOpts.size() > 1 &&
767 "Cannot specify cl::ConsumeAfter without a positional argument!");
768 ConsumeAfterOpt = PositionalOpts[0];
771 // Calculate how many positional values are _required_.
772 bool UnboundedFound = false;
773 for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size();
775 Option *Opt = PositionalOpts[i];
776 if (RequiresValue(Opt))
777 ++NumPositionalRequired;
778 else if (ConsumeAfterOpt) {
779 // ConsumeAfter cannot be combined with "optional" positional options
780 // unless there is only one positional argument...
781 if (PositionalOpts.size() > 2)
783 Opt->error("error - this positional option will never be matched, "
784 "because it does not Require a value, and a "
785 "cl::ConsumeAfter option is active!");
786 } else if (UnboundedFound && !Opt->ArgStr[0]) {
787 // This option does not "require" a value... Make sure this option is
788 // not specified after an option that eats all extra arguments, or this
789 // one will never get any!
791 ErrorParsing |= Opt->error("error - option can never match, because "
792 "another positional argument will match an "
793 "unbounded number of values, and this option"
794 " does not require a value!");
796 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
798 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
801 // PositionalVals - A vector of "positional" arguments we accumulate into
802 // the process at the end.
804 SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
806 // If the program has named positional arguments, and the name has been run
807 // across, keep track of which positional argument was named. Otherwise put
808 // the positional args into the PositionalVals list...
809 Option *ActivePositionalArg = nullptr;
811 // Loop over all of the arguments... processing them.
812 bool DashDashFound = false; // Have we read '--'?
813 for (int i = 1; i < argc; ++i) {
814 Option *Handler = nullptr;
815 Option *NearestHandler = nullptr;
816 std::string NearestHandlerString;
818 StringRef ArgName = "";
820 // If the option list changed, this means that some command line
821 // option has just been registered or deregistered. This can occur in
822 // response to things like -load, etc. If this happens, rescan the options.
823 if (OptionListChanged) {
824 PositionalOpts.clear();
827 GetOptionInfo(PositionalOpts, SinkOpts, Opts);
828 OptionListChanged = false;
831 // Check to see if this is a positional argument. This argument is
832 // considered to be positional if it doesn't start with '-', if it is "-"
833 // itself, or if we have seen "--" already.
835 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
836 // Positional argument!
837 if (ActivePositionalArg) {
838 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
839 continue; // We are done!
842 if (!PositionalOpts.empty()) {
843 PositionalVals.push_back(std::make_pair(argv[i],i));
845 // All of the positional arguments have been fulfulled, give the rest to
846 // the consume after option... if it's specified...
848 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
849 for (++i; i < argc; ++i)
850 PositionalVals.push_back(std::make_pair(argv[i],i));
851 break; // Handle outside of the argument processing loop...
854 // Delay processing positional arguments until the end...
857 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
859 DashDashFound = true; // This is the mythical "--"?
860 continue; // Don't try to process it as an argument itself.
861 } else if (ActivePositionalArg &&
862 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
863 // If there is a positional argument eating options, check to see if this
864 // option is another positional argument. If so, treat it as an argument,
865 // otherwise feed it to the eating positional.
867 // Eat leading dashes.
868 while (!ArgName.empty() && ArgName[0] == '-')
869 ArgName = ArgName.substr(1);
871 Handler = LookupOption(ArgName, Value, Opts);
872 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
873 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
874 continue; // We are done!
877 } else { // We start with a '-', must be an argument.
879 // Eat leading dashes.
880 while (!ArgName.empty() && ArgName[0] == '-')
881 ArgName = ArgName.substr(1);
883 Handler = LookupOption(ArgName, Value, Opts);
885 // Check to see if this "option" is really a prefixed or grouped argument.
887 Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
890 // Otherwise, look for the closest available option to report to the user
891 // in the upcoming error.
892 if (!Handler && SinkOpts.empty())
893 NearestHandler = LookupNearestOption(ArgName, Opts,
894 NearestHandlerString);
898 if (SinkOpts.empty()) {
899 errs() << ProgramName << ": Unknown command line argument '"
900 << argv[i] << "'. Try: '" << argv[0] << " -help'\n";
902 if (NearestHandler) {
903 // If we know a near match, report it as well.
904 errs() << ProgramName << ": Did you mean '-"
905 << NearestHandlerString << "'?\n";
910 for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
911 E = SinkOpts.end(); I != E ; ++I)
912 (*I)->addOccurrence(i, "", argv[i]);
917 // If this is a named positional argument, just remember that it is the
919 if (Handler->getFormattingFlag() == cl::Positional)
920 ActivePositionalArg = Handler;
922 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
925 // Check and handle positional arguments now...
926 if (NumPositionalRequired > PositionalVals.size()) {
927 errs() << ProgramName
928 << ": Not enough positional command line arguments specified!\n"
929 << "Must specify at least " << NumPositionalRequired
930 << " positional arguments: See: " << argv[0] << " -help\n";
933 } else if (!HasUnlimitedPositionals &&
934 PositionalVals.size() > PositionalOpts.size()) {
935 errs() << ProgramName
936 << ": Too many positional arguments specified!\n"
937 << "Can specify at most " << PositionalOpts.size()
938 << " positional arguments: See: " << argv[0] << " -help\n";
941 } else if (!ConsumeAfterOpt) {
942 // Positional args have already been handled if ConsumeAfter is specified.
943 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
944 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
945 if (RequiresValue(PositionalOpts[i])) {
946 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
947 PositionalVals[ValNo].second);
949 --NumPositionalRequired; // We fulfilled our duty...
952 // If we _can_ give this option more arguments, do so now, as long as we
953 // do not give it values that others need. 'Done' controls whether the
954 // option even _WANTS_ any more.
956 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
957 while (NumVals-ValNo > NumPositionalRequired && !Done) {
958 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
960 Done = true; // Optional arguments want _at most_ one value
962 case cl::ZeroOrMore: // Zero or more will take all they can get...
963 case cl::OneOrMore: // One or more will take all they can get...
964 ProvidePositionalOption(PositionalOpts[i],
965 PositionalVals[ValNo].first,
966 PositionalVals[ValNo].second);
970 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
971 "positional argument processing!");
976 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
978 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
979 if (RequiresValue(PositionalOpts[j])) {
980 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
981 PositionalVals[ValNo].first,
982 PositionalVals[ValNo].second);
986 // Handle the case where there is just one positional option, and it's
987 // optional. In this case, we want to give JUST THE FIRST option to the
988 // positional option and keep the rest for the consume after. The above
989 // loop would have assigned no values to positional options in this case.
991 if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
992 ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
993 PositionalVals[ValNo].first,
994 PositionalVals[ValNo].second);
998 // Handle over all of the rest of the arguments to the
999 // cl::ConsumeAfter command line option...
1000 for (; ValNo != PositionalVals.size(); ++ValNo)
1001 ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
1002 PositionalVals[ValNo].first,
1003 PositionalVals[ValNo].second);
1006 // Loop over args and make sure all required args are specified!
1007 for (StringMap<Option*>::iterator I = Opts.begin(),
1008 E = Opts.end(); I != E; ++I) {
1009 switch (I->second->getNumOccurrencesFlag()) {
1012 if (I->second->getNumOccurrences() == 0) {
1013 I->second->error("must be specified at least once!");
1014 ErrorParsing = true;
1022 // Now that we know if -debug is specified, we can use it.
1023 // Note that if ReadResponseFiles == true, this must be done before the
1024 // memory allocated for the expanded command line is free()d below.
1025 DEBUG(dbgs() << "Args: ";
1026 for (int i = 0; i < argc; ++i)
1027 dbgs() << argv[i] << ' ';
1031 // Free all of the memory allocated to the map. Command line options may only
1032 // be processed once!
1034 PositionalOpts.clear();
1037 // If we had an error processing our arguments, don't let the program execute
1038 if (ErrorParsing) exit(1);
1041 //===----------------------------------------------------------------------===//
1042 // Option Base class implementation
1045 bool Option::error(const Twine &Message, StringRef ArgName) {
1046 if (!ArgName.data()) ArgName = ArgStr;
1047 if (ArgName.empty())
1048 errs() << HelpStr; // Be nice for positional arguments
1050 errs() << ProgramName << ": for the -" << ArgName;
1052 errs() << " option: " << Message << "\n";
1056 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
1057 StringRef Value, bool MultiArg) {
1059 NumOccurrences++; // Increment the number of times we have been seen
1061 switch (getNumOccurrencesFlag()) {
1063 if (NumOccurrences > 1)
1064 return error("may only occur zero or one times!", ArgName);
1067 if (NumOccurrences > 1)
1068 return error("must occur exactly one time!", ArgName);
1072 case ConsumeAfter: break;
1075 return handleOccurrence(pos, ArgName, Value);
1079 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1080 // has been specified yet.
1082 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1083 if (O.ValueStr[0] == 0) return DefaultMsg;
1087 //===----------------------------------------------------------------------===//
1088 // cl::alias class implementation
1091 // Return the width of the option tag for printing...
1092 size_t alias::getOptionWidth() const {
1093 return std::strlen(ArgStr)+6;
1096 static void printHelpStr(StringRef HelpStr, size_t Indent,
1097 size_t FirstLineIndentedBy) {
1098 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1099 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1100 while (!Split.second.empty()) {
1101 Split = Split.second.split('\n');
1102 outs().indent(Indent) << Split.first << "\n";
1106 // Print out the option for the alias.
1107 void alias::printOptionInfo(size_t GlobalWidth) const {
1108 outs() << " -" << ArgStr;
1109 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1112 //===----------------------------------------------------------------------===//
1113 // Parser Implementation code...
1116 // basic_parser implementation
1119 // Return the width of the option tag for printing...
1120 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1121 size_t Len = std::strlen(O.ArgStr);
1122 if (const char *ValName = getValueName())
1123 Len += std::strlen(getValueStr(O, ValName))+3;
1128 // printOptionInfo - Print out information about this option. The
1129 // to-be-maintained width is specified.
1131 void basic_parser_impl::printOptionInfo(const Option &O,
1132 size_t GlobalWidth) const {
1133 outs() << " -" << O.ArgStr;
1135 if (const char *ValName = getValueName())
1136 outs() << "=<" << getValueStr(O, ValName) << '>';
1138 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1141 void basic_parser_impl::printOptionName(const Option &O,
1142 size_t GlobalWidth) const {
1143 outs() << " -" << O.ArgStr;
1144 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1148 // parser<bool> implementation
1150 bool parser<bool>::parse(Option &O, StringRef ArgName,
1151 StringRef Arg, bool &Value) {
1152 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1158 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1162 return O.error("'" + Arg +
1163 "' is invalid value for boolean argument! Try 0 or 1");
1166 // parser<boolOrDefault> implementation
1168 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
1169 StringRef Arg, boolOrDefault &Value) {
1170 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1175 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1180 return O.error("'" + Arg +
1181 "' is invalid value for boolean argument! Try 0 or 1");
1184 // parser<int> implementation
1186 bool parser<int>::parse(Option &O, StringRef ArgName,
1187 StringRef Arg, int &Value) {
1188 if (Arg.getAsInteger(0, Value))
1189 return O.error("'" + Arg + "' value invalid for integer argument!");
1193 // parser<unsigned> implementation
1195 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1196 StringRef Arg, unsigned &Value) {
1198 if (Arg.getAsInteger(0, Value))
1199 return O.error("'" + Arg + "' value invalid for uint argument!");
1203 // parser<unsigned long long> implementation
1205 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1206 StringRef Arg, unsigned long long &Value){
1208 if (Arg.getAsInteger(0, Value))
1209 return O.error("'" + Arg + "' value invalid for uint argument!");
1213 // parser<double>/parser<float> implementation
1215 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1216 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1217 const char *ArgStart = TmpStr.c_str();
1219 Value = strtod(ArgStart, &End);
1221 return O.error("'" + Arg + "' value invalid for floating point argument!");
1225 bool parser<double>::parse(Option &O, StringRef ArgName,
1226 StringRef Arg, double &Val) {
1227 return parseDouble(O, Arg, Val);
1230 bool parser<float>::parse(Option &O, StringRef ArgName,
1231 StringRef Arg, float &Val) {
1233 if (parseDouble(O, Arg, dVal))
1241 // generic_parser_base implementation
1244 // findOption - Return the option number corresponding to the specified
1245 // argument string. If the option is not found, getNumOptions() is returned.
1247 unsigned generic_parser_base::findOption(const char *Name) {
1248 unsigned e = getNumOptions();
1250 for (unsigned i = 0; i != e; ++i) {
1251 if (strcmp(getOption(i), Name) == 0)
1258 // Return the width of the option tag for printing...
1259 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1260 if (O.hasArgStr()) {
1261 size_t Size = std::strlen(O.ArgStr)+6;
1262 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1263 Size = std::max(Size, std::strlen(getOption(i))+8);
1266 size_t BaseSize = 0;
1267 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1268 BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1273 // printOptionInfo - Print out information about this option. The
1274 // to-be-maintained width is specified.
1276 void generic_parser_base::printOptionInfo(const Option &O,
1277 size_t GlobalWidth) const {
1278 if (O.hasArgStr()) {
1279 outs() << " -" << O.ArgStr;
1280 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1282 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1283 size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1284 outs() << " =" << getOption(i);
1285 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1289 outs() << " " << O.HelpStr << '\n';
1290 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1291 const char *Option = getOption(i);
1292 outs() << " -" << Option;
1293 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1298 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1300 // printGenericOptionDiff - Print the value of this option and it's default.
1302 // "Generic" options have each value mapped to a name.
1303 void generic_parser_base::
1304 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1305 const GenericOptionValue &Default,
1306 size_t GlobalWidth) const {
1307 outs() << " -" << O.ArgStr;
1308 outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1310 unsigned NumOpts = getNumOptions();
1311 for (unsigned i = 0; i != NumOpts; ++i) {
1312 if (Value.compare(getOptionValue(i)))
1315 outs() << "= " << getOption(i);
1316 size_t L = std::strlen(getOption(i));
1317 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1318 outs().indent(NumSpaces) << " (default: ";
1319 for (unsigned j = 0; j != NumOpts; ++j) {
1320 if (Default.compare(getOptionValue(j)))
1322 outs() << getOption(j);
1328 outs() << "= *unknown option value*\n";
1331 // printOptionDiff - Specializations for printing basic value types.
1333 #define PRINT_OPT_DIFF(T) \
1335 printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1336 size_t GlobalWidth) const { \
1337 printOptionName(O, GlobalWidth); \
1340 raw_string_ostream SS(Str); \
1343 outs() << "= " << Str; \
1344 size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1345 outs().indent(NumSpaces) << " (default: "; \
1347 outs() << D.getValue(); \
1349 outs() << "*no default*"; \
1353 PRINT_OPT_DIFF(bool)
1354 PRINT_OPT_DIFF(boolOrDefault)
1356 PRINT_OPT_DIFF(unsigned)
1357 PRINT_OPT_DIFF(unsigned long long)
1358 PRINT_OPT_DIFF(double)
1359 PRINT_OPT_DIFF(float)
1360 PRINT_OPT_DIFF(char)
1362 void parser<std::string>::
1363 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1364 size_t GlobalWidth) const {
1365 printOptionName(O, GlobalWidth);
1366 outs() << "= " << V;
1367 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1368 outs().indent(NumSpaces) << " (default: ";
1370 outs() << D.getValue();
1372 outs() << "*no default*";
1376 // Print a placeholder for options that don't yet support printOptionDiff().
1377 void basic_parser_impl::
1378 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1379 printOptionName(O, GlobalWidth);
1380 outs() << "= *cannot print option value*\n";
1383 //===----------------------------------------------------------------------===//
1384 // -help and -help-hidden option implementation
1387 static int OptNameCompare(const void *LHS, const void *RHS) {
1388 typedef std::pair<const char *, Option*> pair_ty;
1390 return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1393 // Copy Options into a vector so we can sort them as we like.
1395 sortOpts(StringMap<Option*> &OptMap,
1396 SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1398 SmallPtrSet<Option*, 128> OptionSet; // Duplicate option detection.
1400 for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1402 // Ignore really-hidden options.
1403 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1406 // Unless showhidden is set, ignore hidden flags.
1407 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1410 // If we've already seen this option, don't add it to the list again.
1411 if (!OptionSet.insert(I->second))
1414 Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1418 // Sort the options list alphabetically.
1419 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1426 const bool ShowHidden;
1427 typedef SmallVector<std::pair<const char *, Option*>,128> StrOptionPairVector;
1428 // Print the options. Opts is assumed to be alphabetically sorted.
1429 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1430 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1431 Opts[i].second->printOptionInfo(MaxArgLen);
1435 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1436 virtual ~HelpPrinter() {}
1438 // Invoke the printer.
1439 void operator=(bool Value) {
1440 if (Value == false) return;
1442 // Get all the options.
1443 SmallVector<Option*, 4> PositionalOpts;
1444 SmallVector<Option*, 4> SinkOpts;
1445 StringMap<Option*> OptMap;
1446 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1448 StrOptionPairVector Opts;
1449 sortOpts(OptMap, Opts, ShowHidden);
1451 if (ProgramOverview)
1452 outs() << "OVERVIEW: " << ProgramOverview << "\n";
1454 outs() << "USAGE: " << ProgramName << " [options]";
1456 // Print out the positional options.
1457 Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1458 if (!PositionalOpts.empty() &&
1459 PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1460 CAOpt = PositionalOpts[0];
1462 for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1463 if (PositionalOpts[i]->ArgStr[0])
1464 outs() << " --" << PositionalOpts[i]->ArgStr;
1465 outs() << " " << PositionalOpts[i]->HelpStr;
1468 // Print the consume after option info if it exists...
1469 if (CAOpt) outs() << " " << CAOpt->HelpStr;
1473 // Compute the maximum argument length...
1474 size_t MaxArgLen = 0;
1475 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1476 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1478 outs() << "OPTIONS:\n";
1479 printOptions(Opts, MaxArgLen);
1481 // Print any extra help the user has declared.
1482 for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1483 E = MoreHelp->end();
1488 // Halt the program since help information was printed
1493 class CategorizedHelpPrinter : public HelpPrinter {
1495 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1497 // Helper function for printOptions().
1498 // It shall return true if A's name should be lexographically
1499 // ordered before B's name. It returns false otherwise.
1500 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1501 return strcmp(A->getName(), B->getName()) < 0;
1504 // Make sure we inherit our base class's operator=()
1505 using HelpPrinter::operator= ;
1508 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1509 std::vector<OptionCategory *> SortedCategories;
1510 std::map<OptionCategory *, std::vector<Option *> > CategorizedOptions;
1512 // Collect registered option categories into vector in preparation for
1514 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1515 E = RegisteredOptionCategories->end();
1517 SortedCategories.push_back(*I);
1520 // Sort the different option categories alphabetically.
1521 assert(SortedCategories.size() > 0 && "No option categories registered!");
1522 std::sort(SortedCategories.begin(), SortedCategories.end(),
1523 OptionCategoryCompare);
1525 // Create map to empty vectors.
1526 for (std::vector<OptionCategory *>::const_iterator
1527 I = SortedCategories.begin(),
1528 E = SortedCategories.end();
1530 CategorizedOptions[*I] = std::vector<Option *>();
1532 // Walk through pre-sorted options and assign into categories.
1533 // Because the options are already alphabetically sorted the
1534 // options within categories will also be alphabetically sorted.
1535 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1536 Option *Opt = Opts[I].second;
1537 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1538 "Option has an unregistered category");
1539 CategorizedOptions[Opt->Category].push_back(Opt);
1543 for (std::vector<OptionCategory *>::const_iterator
1544 Category = SortedCategories.begin(),
1545 E = SortedCategories.end();
1546 Category != E; ++Category) {
1547 // Hide empty categories for -help, but show for -help-hidden.
1548 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1549 if (!ShowHidden && IsEmptyCategory)
1552 // Print category information.
1554 outs() << (*Category)->getName() << ":\n";
1556 // Check if description is set.
1557 if ((*Category)->getDescription() != nullptr)
1558 outs() << (*Category)->getDescription() << "\n\n";
1562 // When using -help-hidden explicitly state if the category has no
1563 // options associated with it.
1564 if (IsEmptyCategory) {
1565 outs() << " This option category has no options.\n";
1568 // Loop over the options in the category and print.
1569 for (std::vector<Option *>::const_iterator
1570 Opt = CategorizedOptions[*Category].begin(),
1571 E = CategorizedOptions[*Category].end();
1573 (*Opt)->printOptionInfo(MaxArgLen);
1578 // This wraps the Uncategorizing and Categorizing printers and decides
1579 // at run time which should be invoked.
1580 class HelpPrinterWrapper {
1582 HelpPrinter &UncategorizedPrinter;
1583 CategorizedHelpPrinter &CategorizedPrinter;
1586 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1587 CategorizedHelpPrinter &CategorizedPrinter) :
1588 UncategorizedPrinter(UncategorizedPrinter),
1589 CategorizedPrinter(CategorizedPrinter) { }
1591 // Invoke the printer.
1592 void operator=(bool Value);
1595 } // End anonymous namespace
1597 // Declare the four HelpPrinter instances that are used to print out help, or
1598 // help-hidden as an uncategorized list or in categories.
1599 static HelpPrinter UncategorizedNormalPrinter(false);
1600 static HelpPrinter UncategorizedHiddenPrinter(true);
1601 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1602 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1605 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1606 // a categorizing help printer
1607 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1608 CategorizedNormalPrinter);
1609 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1610 CategorizedHiddenPrinter);
1612 // Define uncategorized help printers.
1613 // -help-list is hidden by default because if Option categories are being used
1614 // then -help behaves the same as -help-list.
1615 static cl::opt<HelpPrinter, true, parser<bool> >
1617 cl::desc("Display list of available options (-help-list-hidden for more)"),
1618 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed);
1620 static cl::opt<HelpPrinter, true, parser<bool> >
1621 HLHOp("help-list-hidden",
1622 cl::desc("Display list of all available options"),
1623 cl::location(UncategorizedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1625 // Define uncategorized/categorized help printers. These printers change their
1626 // behaviour at runtime depending on whether one or more Option categories have
1628 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1629 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1630 cl::location(WrappedNormalPrinter), cl::ValueDisallowed);
1632 static cl::opt<HelpPrinterWrapper, true, parser<bool> >
1633 HHOp("help-hidden", cl::desc("Display all available options"),
1634 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1638 static cl::opt<bool>
1639 PrintOptions("print-options",
1640 cl::desc("Print non-default options after command line parsing"),
1641 cl::Hidden, cl::init(false));
1643 static cl::opt<bool>
1644 PrintAllOptions("print-all-options",
1645 cl::desc("Print all option values after command line parsing"),
1646 cl::Hidden, cl::init(false));
1648 void HelpPrinterWrapper::operator=(bool Value) {
1652 // Decide which printer to invoke. If more than one option category is
1653 // registered then it is useful to show the categorized help instead of
1654 // uncategorized help.
1655 if (RegisteredOptionCategories->size() > 1) {
1656 // unhide -help-list option so user can have uncategorized output if they
1658 HLOp.setHiddenFlag(NotHidden);
1660 CategorizedPrinter = true; // Invoke categorized printer
1663 UncategorizedPrinter = true; // Invoke uncategorized printer
1666 // Print the value of each option.
1667 void cl::PrintOptionValues() {
1668 if (!PrintOptions && !PrintAllOptions) return;
1670 // Get all the options.
1671 SmallVector<Option*, 4> PositionalOpts;
1672 SmallVector<Option*, 4> SinkOpts;
1673 StringMap<Option*> OptMap;
1674 GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1676 SmallVector<std::pair<const char *, Option*>, 128> Opts;
1677 sortOpts(OptMap, Opts, /*ShowHidden*/true);
1679 // Compute the maximum argument length...
1680 size_t MaxArgLen = 0;
1681 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1682 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1684 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1685 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1688 static void (*OverrideVersionPrinter)() = nullptr;
1690 static std::vector<void (*)()>* ExtraVersionPrinters = nullptr;
1693 class VersionPrinter {
1696 raw_ostream &OS = outs();
1697 OS << "LLVM (http://llvm.org/):\n"
1698 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1699 #ifdef LLVM_VERSION_INFO
1700 OS << LLVM_VERSION_INFO;
1703 #ifndef __OPTIMIZE__
1704 OS << "DEBUG build";
1706 OS << "Optimized build";
1709 OS << " with assertions";
1711 std::string CPU = sys::getHostCPUName();
1712 if (CPU == "generic") CPU = "(unknown)";
1714 #if (ENABLE_TIMESTAMPS == 1)
1715 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1717 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1718 << " Host CPU: " << CPU << '\n';
1720 void operator=(bool OptionWasSpecified) {
1721 if (!OptionWasSpecified) return;
1723 if (OverrideVersionPrinter != nullptr) {
1724 (*OverrideVersionPrinter)();
1729 // Iterate over any registered extra printers and call them to add further
1731 if (ExtraVersionPrinters != nullptr) {
1733 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1734 E = ExtraVersionPrinters->end();
1742 } // End anonymous namespace
1745 // Define the --version option that prints out the LLVM version for the tool
1746 static VersionPrinter VersionPrinterInstance;
1748 static cl::opt<VersionPrinter, true, parser<bool> >
1749 VersOp("version", cl::desc("Display the version of this program"),
1750 cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1752 // Utility function for printing the help message.
1753 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1754 // This looks weird, but it actually prints the help message. The Printers are
1755 // types of HelpPrinter and the help gets printed when its operator= is
1756 // invoked. That's because the "normal" usages of the help printer is to be
1757 // assigned true/false depending on whether -help or -help-hidden was given or
1758 // not. Since we're circumventing that we have to make it look like -help or
1759 // -help-hidden were given, so we assign true.
1761 if (!Hidden && !Categorized)
1762 UncategorizedNormalPrinter = true;
1763 else if (!Hidden && Categorized)
1764 CategorizedNormalPrinter = true;
1765 else if (Hidden && !Categorized)
1766 UncategorizedHiddenPrinter = true;
1768 CategorizedHiddenPrinter = true;
1771 /// Utility function for printing version number.
1772 void cl::PrintVersionMessage() {
1773 VersionPrinterInstance.print();
1776 void cl::SetVersionPrinter(void (*func)()) {
1777 OverrideVersionPrinter = func;
1780 void cl::AddExtraVersionPrinter(void (*func)()) {
1781 if (!ExtraVersionPrinters)
1782 ExtraVersionPrinters = new std::vector<void (*)()>;
1784 ExtraVersionPrinters->push_back(func);
1787 void cl::getRegisteredOptions(StringMap<Option*> &Map)
1789 // Get all the options.
1790 SmallVector<Option*, 4> PositionalOpts; //NOT USED
1791 SmallVector<Option*, 4> SinkOpts; //NOT USED
1792 assert(Map.size() == 0 && "StringMap must be empty");
1793 GetOptionInfo(PositionalOpts, SinkOpts, Map);