1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
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
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "llvm/ADT/StringMap.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Config/config.h"
28 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/Path.h"
35 #include "llvm/Support/StringSaver.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <cstdlib>
38 #include <map>
39 using namespace llvm;
40 using namespace cl;
41
42 #define DEBUG_TYPE "commandline"
43
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
46 //
47 namespace llvm {
48 namespace cl {
49 template class basic_parser<bool>;
50 template class basic_parser<boolOrDefault>;
51 template class basic_parser<int>;
52 template class basic_parser<unsigned>;
53 template class basic_parser<unsigned long long>;
54 template class basic_parser<double>;
55 template class basic_parser<float>;
56 template class basic_parser<std::string>;
57 template class basic_parser<char>;
58
59 template class opt<unsigned>;
60 template class opt<int>;
61 template class opt<std::string>;
62 template class opt<char>;
63 template class opt<bool>;
64 }
65 } // end namespace llvm::cl
66
67 // Pin the vtables to this file.
anchor()68 void GenericOptionValue::anchor() {}
anchor()69 void OptionValue<boolOrDefault>::anchor() {}
anchor()70 void OptionValue<std::string>::anchor() {}
anchor()71 void Option::anchor() {}
anchor()72 void basic_parser_impl::anchor() {}
anchor()73 void parser<bool>::anchor() {}
anchor()74 void parser<boolOrDefault>::anchor() {}
anchor()75 void parser<int>::anchor() {}
anchor()76 void parser<unsigned>::anchor() {}
anchor()77 void parser<unsigned long long>::anchor() {}
anchor()78 void parser<double>::anchor() {}
anchor()79 void parser<float>::anchor() {}
anchor()80 void parser<std::string>::anchor() {}
anchor()81 void parser<char>::anchor() {}
82
83 //===----------------------------------------------------------------------===//
84
85 namespace {
86
87 class CommandLineParser {
88 public:
89 // Globals for name and overview of program. Program name is not a string to
90 // avoid static ctor/dtor issues.
91 std::string ProgramName;
92 const char *ProgramOverview;
93
94 // This collects additional help to be printed.
95 std::vector<const char *> MoreHelp;
96
97 SmallVector<Option *, 4> PositionalOpts;
98 SmallVector<Option *, 4> SinkOpts;
99 StringMap<Option *> OptionsMap;
100
101 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
102
103 // This collects the different option categories that have been registered.
104 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
105
CommandLineParser()106 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
107
108 void ParseCommandLineOptions(int argc, const char *const *argv,
109 const char *Overview);
110
addLiteralOption(Option & Opt,const char * Name)111 void addLiteralOption(Option &Opt, const char *Name) {
112 if (!Opt.hasArgStr()) {
113 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
114 errs() << ProgramName << ": CommandLine Error: Option '" << Name
115 << "' registered more than once!\n";
116 report_fatal_error("inconsistency in registered CommandLine options");
117 }
118 }
119 }
120
addOption(Option * O)121 void addOption(Option *O) {
122 bool HadErrors = false;
123 if (O->hasArgStr()) {
124 // Add argument to the argument map!
125 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
126 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
127 << "' registered more than once!\n";
128 HadErrors = true;
129 }
130 }
131
132 // Remember information about positional options.
133 if (O->getFormattingFlag() == cl::Positional)
134 PositionalOpts.push_back(O);
135 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
136 SinkOpts.push_back(O);
137 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
138 if (ConsumeAfterOpt) {
139 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
140 HadErrors = true;
141 }
142 ConsumeAfterOpt = O;
143 }
144
145 // Fail hard if there were errors. These are strictly unrecoverable and
146 // indicate serious issues such as conflicting option names or an
147 // incorrectly
148 // linked LLVM distribution.
149 if (HadErrors)
150 report_fatal_error("inconsistency in registered CommandLine options");
151 }
152
removeOption(Option * O)153 void removeOption(Option *O) {
154 SmallVector<StringRef, 16> OptionNames;
155 O->getExtraOptionNames(OptionNames);
156 if (O->hasArgStr())
157 OptionNames.push_back(O->ArgStr);
158 for (auto Name : OptionNames)
159 OptionsMap.erase(Name);
160
161 if (O->getFormattingFlag() == cl::Positional)
162 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
163 ++Opt) {
164 if (*Opt == O) {
165 PositionalOpts.erase(Opt);
166 break;
167 }
168 }
169 else if (O->getMiscFlags() & cl::Sink)
170 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
171 if (*Opt == O) {
172 SinkOpts.erase(Opt);
173 break;
174 }
175 }
176 else if (O == ConsumeAfterOpt)
177 ConsumeAfterOpt = nullptr;
178 }
179
hasOptions()180 bool hasOptions() {
181 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
182 nullptr != ConsumeAfterOpt);
183 }
184
updateArgStr(Option * O,StringRef NewName)185 void updateArgStr(Option *O, StringRef NewName) {
186 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
187 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
188 << "' registered more than once!\n";
189 report_fatal_error("inconsistency in registered CommandLine options");
190 }
191 OptionsMap.erase(O->ArgStr);
192 }
193
194 void printOptionValues();
195
registerCategory(OptionCategory * cat)196 void registerCategory(OptionCategory *cat) {
197 assert(std::count_if(RegisteredOptionCategories.begin(),
198 RegisteredOptionCategories.end(),
199 [cat](const OptionCategory *Category) {
200 return cat->getName() == Category->getName();
201 }) == 0 &&
202 "Duplicate option categories");
203
204 RegisteredOptionCategories.insert(cat);
205 }
206
207 private:
208 Option *LookupOption(StringRef &Arg, StringRef &Value);
209 };
210
211 } // namespace
212
213 static ManagedStatic<CommandLineParser> GlobalParser;
214
AddLiteralOption(Option & O,const char * Name)215 void cl::AddLiteralOption(Option &O, const char *Name) {
216 GlobalParser->addLiteralOption(O, Name);
217 }
218
extrahelp(const char * Help)219 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
220 GlobalParser->MoreHelp.push_back(Help);
221 }
222
addArgument()223 void Option::addArgument() {
224 GlobalParser->addOption(this);
225 FullyInitialized = true;
226 }
227
removeArgument()228 void Option::removeArgument() { GlobalParser->removeOption(this); }
229
setArgStr(StringRef S)230 void Option::setArgStr(StringRef S) {
231 if (FullyInitialized)
232 GlobalParser->updateArgStr(this, S);
233 ArgStr = S;
234 }
235
236 // Initialise the general option category.
237 OptionCategory llvm::cl::GeneralCategory("General options");
238
registerCategory()239 void OptionCategory::registerCategory() {
240 GlobalParser->registerCategory(this);
241 }
242
243 //===----------------------------------------------------------------------===//
244 // Basic, shared command line option processing machinery.
245 //
246
247 /// LookupOption - Lookup the option specified by the specified option on the
248 /// command line. If there is a value specified (after an equal sign) return
249 /// that as well. This assumes that leading dashes have already been stripped.
LookupOption(StringRef & Arg,StringRef & Value)250 Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
251 // Reject all dashes.
252 if (Arg.empty())
253 return nullptr;
254
255 size_t EqualPos = Arg.find('=');
256
257 // If we have an equals sign, remember the value.
258 if (EqualPos == StringRef::npos) {
259 // Look up the option.
260 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
261 return I != OptionsMap.end() ? I->second : nullptr;
262 }
263
264 // If the argument before the = is a valid option name, we match. If not,
265 // return Arg unmolested.
266 StringMap<Option *>::const_iterator I =
267 OptionsMap.find(Arg.substr(0, EqualPos));
268 if (I == OptionsMap.end())
269 return nullptr;
270
271 Value = Arg.substr(EqualPos + 1);
272 Arg = Arg.substr(0, EqualPos);
273 return I->second;
274 }
275
276 /// LookupNearestOption - Lookup the closest match to the option specified by
277 /// the specified option on the command line. If there is a value specified
278 /// (after an equal sign) return that as well. This assumes that leading dashes
279 /// have already been stripped.
LookupNearestOption(StringRef Arg,const StringMap<Option * > & OptionsMap,std::string & NearestString)280 static Option *LookupNearestOption(StringRef Arg,
281 const StringMap<Option *> &OptionsMap,
282 std::string &NearestString) {
283 // Reject all dashes.
284 if (Arg.empty())
285 return nullptr;
286
287 // Split on any equal sign.
288 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
289 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
290 StringRef &RHS = SplitArg.second;
291
292 // Find the closest match.
293 Option *Best = nullptr;
294 unsigned BestDistance = 0;
295 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
296 ie = OptionsMap.end();
297 it != ie; ++it) {
298 Option *O = it->second;
299 SmallVector<StringRef, 16> OptionNames;
300 O->getExtraOptionNames(OptionNames);
301 if (O->hasArgStr())
302 OptionNames.push_back(O->ArgStr);
303
304 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
305 StringRef Flag = PermitValue ? LHS : Arg;
306 for (auto Name : OptionNames) {
307 unsigned Distance = StringRef(Name).edit_distance(
308 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
309 if (!Best || Distance < BestDistance) {
310 Best = O;
311 BestDistance = Distance;
312 if (RHS.empty() || !PermitValue)
313 NearestString = Name;
314 else
315 NearestString = (Twine(Name) + "=" + RHS).str();
316 }
317 }
318 }
319
320 return Best;
321 }
322
323 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
324 /// that does special handling of cl::CommaSeparated options.
CommaSeparateAndAddOccurrence(Option * Handler,unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg=false)325 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
326 StringRef ArgName, StringRef Value,
327 bool MultiArg = false) {
328 // Check to see if this option accepts a comma separated list of values. If
329 // it does, we have to split up the value into multiple values.
330 if (Handler->getMiscFlags() & CommaSeparated) {
331 StringRef Val(Value);
332 StringRef::size_type Pos = Val.find(',');
333
334 while (Pos != StringRef::npos) {
335 // Process the portion before the comma.
336 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
337 return true;
338 // Erase the portion before the comma, AND the comma.
339 Val = Val.substr(Pos + 1);
340 Value.substr(Pos + 1); // Increment the original value pointer as well.
341 // Check for another comma.
342 Pos = Val.find(',');
343 }
344
345 Value = Val;
346 }
347
348 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
349 return true;
350
351 return false;
352 }
353
354 /// ProvideOption - For Value, this differentiates between an empty value ("")
355 /// and a null value (StringRef()). The later is accepted for arguments that
356 /// don't allow a value (-foo) the former is rejected (-foo=).
ProvideOption(Option * Handler,StringRef ArgName,StringRef Value,int argc,const char * const * argv,int & i)357 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
358 StringRef Value, int argc,
359 const char *const *argv, int &i) {
360 // Is this a multi-argument option?
361 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
362
363 // Enforce value requirements
364 switch (Handler->getValueExpectedFlag()) {
365 case ValueRequired:
366 if (!Value.data()) { // No value specified?
367 if (i + 1 >= argc)
368 return Handler->error("requires a value!");
369 // Steal the next argument, like for '-o filename'
370 assert(argv && "null check");
371 Value = argv[++i];
372 }
373 break;
374 case ValueDisallowed:
375 if (NumAdditionalVals > 0)
376 return Handler->error("multi-valued option specified"
377 " with ValueDisallowed modifier!");
378
379 if (Value.data())
380 return Handler->error("does not allow a value! '" + Twine(Value) +
381 "' specified.");
382 break;
383 case ValueOptional:
384 break;
385 }
386
387 // If this isn't a multi-arg option, just run the handler.
388 if (NumAdditionalVals == 0)
389 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
390
391 // If it is, run the handle several times.
392 bool MultiArg = false;
393
394 if (Value.data()) {
395 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
396 return true;
397 --NumAdditionalVals;
398 MultiArg = true;
399 }
400
401 while (NumAdditionalVals > 0) {
402 if (i + 1 >= argc)
403 return Handler->error("not enough values!");
404 assert(argv && "null check");
405 Value = argv[++i];
406
407 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
408 return true;
409 MultiArg = true;
410 --NumAdditionalVals;
411 }
412 return false;
413 }
414
ProvidePositionalOption(Option * Handler,StringRef Arg,int i)415 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
416 int Dummy = i;
417 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
418 }
419
420 // Option predicates...
isGrouping(const Option * O)421 static inline bool isGrouping(const Option *O) {
422 return O->getFormattingFlag() == cl::Grouping;
423 }
isPrefixedOrGrouping(const Option * O)424 static inline bool isPrefixedOrGrouping(const Option *O) {
425 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
426 }
427
428 // getOptionPred - Check to see if there are any options that satisfy the
429 // specified predicate with names that are the prefixes in Name. This is
430 // checked by progressively stripping characters off of the name, checking to
431 // see if there options that satisfy the predicate. If we find one, return it,
432 // otherwise return null.
433 //
getOptionPred(StringRef Name,size_t & Length,bool (* Pred)(const Option *),const StringMap<Option * > & OptionsMap)434 static Option *getOptionPred(StringRef Name, size_t &Length,
435 bool (*Pred)(const Option *),
436 const StringMap<Option *> &OptionsMap) {
437
438 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
439
440 // Loop while we haven't found an option and Name still has at least two
441 // characters in it (so that the next iteration will not be the empty
442 // string.
443 while (OMI == OptionsMap.end() && Name.size() > 1) {
444 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
445 OMI = OptionsMap.find(Name);
446 }
447
448 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
449 Length = Name.size();
450 return OMI->second; // Found one!
451 }
452 return nullptr; // No option found!
453 }
454
455 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
456 /// with at least one '-') does not fully match an available option. Check to
457 /// see if this is a prefix or grouped option. If so, split arg into output an
458 /// Arg/Value pair and return the Option to parse it with.
459 static Option *
HandlePrefixedOrGroupedOption(StringRef & Arg,StringRef & Value,bool & ErrorParsing,const StringMap<Option * > & OptionsMap)460 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
461 bool &ErrorParsing,
462 const StringMap<Option *> &OptionsMap) {
463 if (Arg.size() == 1)
464 return nullptr;
465
466 // Do the lookup!
467 size_t Length = 0;
468 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
469 if (!PGOpt)
470 return nullptr;
471
472 // If the option is a prefixed option, then the value is simply the
473 // rest of the name... so fall through to later processing, by
474 // setting up the argument name flags and value fields.
475 if (PGOpt->getFormattingFlag() == cl::Prefix) {
476 Value = Arg.substr(Length);
477 Arg = Arg.substr(0, Length);
478 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
479 return PGOpt;
480 }
481
482 // This must be a grouped option... handle them now. Grouping options can't
483 // have values.
484 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
485
486 do {
487 // Move current arg name out of Arg into OneArgName.
488 StringRef OneArgName = Arg.substr(0, Length);
489 Arg = Arg.substr(Length);
490
491 // Because ValueRequired is an invalid flag for grouped arguments,
492 // we don't need to pass argc/argv in.
493 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
494 "Option can not be cl::Grouping AND cl::ValueRequired!");
495 int Dummy = 0;
496 ErrorParsing |=
497 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
498
499 // Get the next grouping option.
500 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
501 } while (PGOpt && Length != Arg.size());
502
503 // Return the last option with Arg cut down to just the last one.
504 return PGOpt;
505 }
506
RequiresValue(const Option * O)507 static bool RequiresValue(const Option *O) {
508 return O->getNumOccurrencesFlag() == cl::Required ||
509 O->getNumOccurrencesFlag() == cl::OneOrMore;
510 }
511
EatsUnboundedNumberOfValues(const Option * O)512 static bool EatsUnboundedNumberOfValues(const Option *O) {
513 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
514 O->getNumOccurrencesFlag() == cl::OneOrMore;
515 }
516
isWhitespace(char C)517 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
518
isQuote(char C)519 static bool isQuote(char C) { return C == '\"' || C == '\''; }
520
isGNUSpecial(char C)521 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
522
TokenizeGNUCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)523 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
524 SmallVectorImpl<const char *> &NewArgv,
525 bool MarkEOLs) {
526 SmallString<128> Token;
527 for (size_t I = 0, E = Src.size(); I != E; ++I) {
528 // Consume runs of whitespace.
529 if (Token.empty()) {
530 while (I != E && isWhitespace(Src[I])) {
531 // Mark the end of lines in response files
532 if (MarkEOLs && Src[I] == '\n')
533 NewArgv.push_back(nullptr);
534 ++I;
535 }
536 if (I == E)
537 break;
538 }
539
540 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
541 // they are literal. This makes it much easier to read Windows file paths.
542 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
543 ++I; // Skip the escape.
544 Token.push_back(Src[I]);
545 continue;
546 }
547
548 // Consume a quoted string.
549 if (isQuote(Src[I])) {
550 char Quote = Src[I++];
551 while (I != E && Src[I] != Quote) {
552 // Backslashes are literal, unless they escape a special character.
553 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
554 ++I;
555 Token.push_back(Src[I]);
556 ++I;
557 }
558 if (I == E)
559 break;
560 continue;
561 }
562
563 // End the token if this is whitespace.
564 if (isWhitespace(Src[I])) {
565 if (!Token.empty())
566 NewArgv.push_back(Saver.save(Token.c_str()));
567 Token.clear();
568 continue;
569 }
570
571 // This is a normal character. Append it.
572 Token.push_back(Src[I]);
573 }
574
575 // Append the last token after hitting EOF with no whitespace.
576 if (!Token.empty())
577 NewArgv.push_back(Saver.save(Token.c_str()));
578 // Mark the end of response files
579 if (MarkEOLs)
580 NewArgv.push_back(nullptr);
581 }
582
583 /// Backslashes are interpreted in a rather complicated way in the Windows-style
584 /// command line, because backslashes are used both to separate path and to
585 /// escape double quote. This method consumes runs of backslashes as well as the
586 /// following double quote if it's escaped.
587 ///
588 /// * If an even number of backslashes is followed by a double quote, one
589 /// backslash is output for every pair of backslashes, and the last double
590 /// quote remains unconsumed. The double quote will later be interpreted as
591 /// the start or end of a quoted string in the main loop outside of this
592 /// function.
593 ///
594 /// * If an odd number of backslashes is followed by a double quote, one
595 /// backslash is output for every pair of backslashes, and a double quote is
596 /// output for the last pair of backslash-double quote. The double quote is
597 /// consumed in this case.
598 ///
599 /// * Otherwise, backslashes are interpreted literally.
parseBackslash(StringRef Src,size_t I,SmallString<128> & Token)600 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
601 size_t E = Src.size();
602 int BackslashCount = 0;
603 // Skip the backslashes.
604 do {
605 ++I;
606 ++BackslashCount;
607 } while (I != E && Src[I] == '\\');
608
609 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
610 if (FollowedByDoubleQuote) {
611 Token.append(BackslashCount / 2, '\\');
612 if (BackslashCount % 2 == 0)
613 return I - 1;
614 Token.push_back('"');
615 return I;
616 }
617 Token.append(BackslashCount, '\\');
618 return I - 1;
619 }
620
TokenizeWindowsCommandLine(StringRef Src,StringSaver & Saver,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs)621 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
622 SmallVectorImpl<const char *> &NewArgv,
623 bool MarkEOLs) {
624 SmallString<128> Token;
625
626 // This is a small state machine to consume characters until it reaches the
627 // end of the source string.
628 enum { INIT, UNQUOTED, QUOTED } State = INIT;
629 for (size_t I = 0, E = Src.size(); I != E; ++I) {
630 // INIT state indicates that the current input index is at the start of
631 // the string or between tokens.
632 if (State == INIT) {
633 if (isWhitespace(Src[I])) {
634 // Mark the end of lines in response files
635 if (MarkEOLs && Src[I] == '\n')
636 NewArgv.push_back(nullptr);
637 continue;
638 }
639 if (Src[I] == '"') {
640 State = QUOTED;
641 continue;
642 }
643 if (Src[I] == '\\') {
644 I = parseBackslash(Src, I, Token);
645 State = UNQUOTED;
646 continue;
647 }
648 Token.push_back(Src[I]);
649 State = UNQUOTED;
650 continue;
651 }
652
653 // UNQUOTED state means that it's reading a token not quoted by double
654 // quotes.
655 if (State == UNQUOTED) {
656 // Whitespace means the end of the token.
657 if (isWhitespace(Src[I])) {
658 NewArgv.push_back(Saver.save(Token.c_str()));
659 Token.clear();
660 State = INIT;
661 // Mark the end of lines in response files
662 if (MarkEOLs && Src[I] == '\n')
663 NewArgv.push_back(nullptr);
664 continue;
665 }
666 if (Src[I] == '"') {
667 State = QUOTED;
668 continue;
669 }
670 if (Src[I] == '\\') {
671 I = parseBackslash(Src, I, Token);
672 continue;
673 }
674 Token.push_back(Src[I]);
675 continue;
676 }
677
678 // QUOTED state means that it's reading a token quoted by double quotes.
679 if (State == QUOTED) {
680 if (Src[I] == '"') {
681 State = UNQUOTED;
682 continue;
683 }
684 if (Src[I] == '\\') {
685 I = parseBackslash(Src, I, Token);
686 continue;
687 }
688 Token.push_back(Src[I]);
689 }
690 }
691 // Append the last token after hitting EOF with no whitespace.
692 if (!Token.empty())
693 NewArgv.push_back(Saver.save(Token.c_str()));
694 // Mark the end of response files
695 if (MarkEOLs)
696 NewArgv.push_back(nullptr);
697 }
698
699 // It is called byte order marker but the UTF-8 BOM is actually not affected
700 // by the host system's endianness.
hasUTF8ByteOrderMark(ArrayRef<char> S)701 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
702 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
703 }
704
ExpandResponseFile(const char * FName,StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & NewArgv,bool MarkEOLs=false)705 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
706 TokenizerCallback Tokenizer,
707 SmallVectorImpl<const char *> &NewArgv,
708 bool MarkEOLs = false) {
709 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
710 MemoryBuffer::getFile(FName);
711 if (!MemBufOrErr)
712 return false;
713 MemoryBuffer &MemBuf = *MemBufOrErr.get();
714 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
715
716 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
717 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
718 std::string UTF8Buf;
719 if (hasUTF16ByteOrderMark(BufRef)) {
720 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
721 return false;
722 Str = StringRef(UTF8Buf);
723 }
724 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
725 // these bytes before parsing.
726 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
727 else if (hasUTF8ByteOrderMark(BufRef))
728 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
729
730 // Tokenize the contents into NewArgv.
731 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
732
733 return true;
734 }
735
736 /// \brief Expand response files on a command line recursively using the given
737 /// StringSaver and tokenization strategy.
ExpandResponseFiles(StringSaver & Saver,TokenizerCallback Tokenizer,SmallVectorImpl<const char * > & Argv,bool MarkEOLs)738 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
739 SmallVectorImpl<const char *> &Argv,
740 bool MarkEOLs) {
741 unsigned RspFiles = 0;
742 bool AllExpanded = true;
743
744 // Don't cache Argv.size() because it can change.
745 for (unsigned I = 0; I != Argv.size();) {
746 const char *Arg = Argv[I];
747 // Check if it is an EOL marker
748 if (Arg == nullptr) {
749 ++I;
750 continue;
751 }
752 if (Arg[0] != '@') {
753 ++I;
754 continue;
755 }
756
757 // If we have too many response files, leave some unexpanded. This avoids
758 // crashing on self-referential response files.
759 if (RspFiles++ > 20)
760 return false;
761
762 // Replace this response file argument with the tokenization of its
763 // contents. Nested response files are expanded in subsequent iterations.
764 // FIXME: If a nested response file uses a relative path, is it relative to
765 // the cwd of the process or the response file?
766 SmallVector<const char *, 0> ExpandedArgv;
767 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
768 MarkEOLs)) {
769 // We couldn't read this file, so we leave it in the argument stream and
770 // move on.
771 AllExpanded = false;
772 ++I;
773 continue;
774 }
775 Argv.erase(Argv.begin() + I);
776 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
777 }
778 return AllExpanded;
779 }
780
781 /// ParseEnvironmentOptions - An alternative entry point to the
782 /// CommandLine library, which allows you to read the program's name
783 /// from the caller (as PROGNAME) and its command-line arguments from
784 /// an environment variable (whose name is given in ENVVAR).
785 ///
ParseEnvironmentOptions(const char * progName,const char * envVar,const char * Overview)786 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
787 const char *Overview) {
788 // Check args.
789 assert(progName && "Program name not specified");
790 assert(envVar && "Environment variable name missing");
791
792 // Get the environment variable they want us to parse options out of.
793 const char *envValue = getenv(envVar);
794 if (!envValue)
795 return;
796
797 // Get program's "name", which we wouldn't know without the caller
798 // telling us.
799 SmallVector<const char *, 20> newArgv;
800 BumpPtrAllocator A;
801 StringSaver Saver(A);
802 newArgv.push_back(Saver.save(progName));
803
804 // Parse the value of the environment variable into a "command line"
805 // and hand it off to ParseCommandLineOptions().
806 TokenizeGNUCommandLine(envValue, Saver, newArgv);
807 int newArgc = static_cast<int>(newArgv.size());
808 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
809 }
810
ParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)811 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
812 const char *Overview) {
813 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
814 }
815
ParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)816 void CommandLineParser::ParseCommandLineOptions(int argc,
817 const char *const *argv,
818 const char *Overview) {
819 assert(hasOptions() && "No options specified!");
820
821 // Expand response files.
822 SmallVector<const char *, 20> newArgv(argv, argv + argc);
823 BumpPtrAllocator A;
824 StringSaver Saver(A);
825 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
826 argv = &newArgv[0];
827 argc = static_cast<int>(newArgv.size());
828
829 // Copy the program name into ProgName, making sure not to overflow it.
830 ProgramName = sys::path::filename(argv[0]);
831
832 ProgramOverview = Overview;
833 bool ErrorParsing = false;
834
835 // Check out the positional arguments to collect information about them.
836 unsigned NumPositionalRequired = 0;
837
838 // Determine whether or not there are an unlimited number of positionals
839 bool HasUnlimitedPositionals = false;
840
841 if (ConsumeAfterOpt) {
842 assert(PositionalOpts.size() > 0 &&
843 "Cannot specify cl::ConsumeAfter without a positional argument!");
844 }
845 if (!PositionalOpts.empty()) {
846
847 // Calculate how many positional values are _required_.
848 bool UnboundedFound = false;
849 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
850 Option *Opt = PositionalOpts[i];
851 if (RequiresValue(Opt))
852 ++NumPositionalRequired;
853 else if (ConsumeAfterOpt) {
854 // ConsumeAfter cannot be combined with "optional" positional options
855 // unless there is only one positional argument...
856 if (PositionalOpts.size() > 1)
857 ErrorParsing |= Opt->error(
858 "error - this positional option will never be matched, "
859 "because it does not Require a value, and a "
860 "cl::ConsumeAfter option is active!");
861 } else if (UnboundedFound && !Opt->hasArgStr()) {
862 // This option does not "require" a value... Make sure this option is
863 // not specified after an option that eats all extra arguments, or this
864 // one will never get any!
865 //
866 ErrorParsing |= Opt->error("error - option can never match, because "
867 "another positional argument will match an "
868 "unbounded number of values, and this option"
869 " does not require a value!");
870 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
871 << "' is all messed up!\n";
872 errs() << PositionalOpts.size();
873 }
874 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
875 }
876 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
877 }
878
879 // PositionalVals - A vector of "positional" arguments we accumulate into
880 // the process at the end.
881 //
882 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
883
884 // If the program has named positional arguments, and the name has been run
885 // across, keep track of which positional argument was named. Otherwise put
886 // the positional args into the PositionalVals list...
887 Option *ActivePositionalArg = nullptr;
888
889 // Loop over all of the arguments... processing them.
890 bool DashDashFound = false; // Have we read '--'?
891 for (int i = 1; i < argc; ++i) {
892 Option *Handler = nullptr;
893 Option *NearestHandler = nullptr;
894 std::string NearestHandlerString;
895 StringRef Value;
896 StringRef ArgName = "";
897
898 // Check to see if this is a positional argument. This argument is
899 // considered to be positional if it doesn't start with '-', if it is "-"
900 // itself, or if we have seen "--" already.
901 //
902 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
903 // Positional argument!
904 if (ActivePositionalArg) {
905 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
906 continue; // We are done!
907 }
908
909 if (!PositionalOpts.empty()) {
910 PositionalVals.push_back(std::make_pair(argv[i], i));
911
912 // All of the positional arguments have been fulfulled, give the rest to
913 // the consume after option... if it's specified...
914 //
915 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
916 for (++i; i < argc; ++i)
917 PositionalVals.push_back(std::make_pair(argv[i], i));
918 break; // Handle outside of the argument processing loop...
919 }
920
921 // Delay processing positional arguments until the end...
922 continue;
923 }
924 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
925 !DashDashFound) {
926 DashDashFound = true; // This is the mythical "--"?
927 continue; // Don't try to process it as an argument itself.
928 } else if (ActivePositionalArg &&
929 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
930 // If there is a positional argument eating options, check to see if this
931 // option is another positional argument. If so, treat it as an argument,
932 // otherwise feed it to the eating positional.
933 ArgName = argv[i] + 1;
934 // Eat leading dashes.
935 while (!ArgName.empty() && ArgName[0] == '-')
936 ArgName = ArgName.substr(1);
937
938 Handler = LookupOption(ArgName, Value);
939 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
940 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
941 continue; // We are done!
942 }
943
944 } else { // We start with a '-', must be an argument.
945 ArgName = argv[i] + 1;
946 // Eat leading dashes.
947 while (!ArgName.empty() && ArgName[0] == '-')
948 ArgName = ArgName.substr(1);
949
950 Handler = LookupOption(ArgName, Value);
951
952 // Check to see if this "option" is really a prefixed or grouped argument.
953 if (!Handler)
954 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
955 OptionsMap);
956
957 // Otherwise, look for the closest available option to report to the user
958 // in the upcoming error.
959 if (!Handler && SinkOpts.empty())
960 NearestHandler =
961 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
962 }
963
964 if (!Handler) {
965 if (SinkOpts.empty()) {
966 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
967 << "'. Try: '" << argv[0] << " -help'\n";
968
969 if (NearestHandler) {
970 // If we know a near match, report it as well.
971 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
972 << "'?\n";
973 }
974
975 ErrorParsing = true;
976 } else {
977 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
978 E = SinkOpts.end();
979 I != E; ++I)
980 (*I)->addOccurrence(i, "", argv[i]);
981 }
982 continue;
983 }
984
985 // If this is a named positional argument, just remember that it is the
986 // active one...
987 if (Handler->getFormattingFlag() == cl::Positional)
988 ActivePositionalArg = Handler;
989 else
990 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
991 }
992
993 // Check and handle positional arguments now...
994 if (NumPositionalRequired > PositionalVals.size()) {
995 errs() << ProgramName
996 << ": Not enough positional command line arguments specified!\n"
997 << "Must specify at least " << NumPositionalRequired
998 << " positional arguments: See: " << argv[0] << " -help\n";
999
1000 ErrorParsing = true;
1001 } else if (!HasUnlimitedPositionals &&
1002 PositionalVals.size() > PositionalOpts.size()) {
1003 errs() << ProgramName << ": Too many positional arguments specified!\n"
1004 << "Can specify at most " << PositionalOpts.size()
1005 << " positional arguments: See: " << argv[0] << " -help\n";
1006 ErrorParsing = true;
1007
1008 } else if (!ConsumeAfterOpt) {
1009 // Positional args have already been handled if ConsumeAfter is specified.
1010 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1011 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1012 if (RequiresValue(PositionalOpts[i])) {
1013 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1014 PositionalVals[ValNo].second);
1015 ValNo++;
1016 --NumPositionalRequired; // We fulfilled our duty...
1017 }
1018
1019 // If we _can_ give this option more arguments, do so now, as long as we
1020 // do not give it values that others need. 'Done' controls whether the
1021 // option even _WANTS_ any more.
1022 //
1023 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1024 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1025 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1026 case cl::Optional:
1027 Done = true; // Optional arguments want _at most_ one value
1028 // FALL THROUGH
1029 case cl::ZeroOrMore: // Zero or more will take all they can get...
1030 case cl::OneOrMore: // One or more will take all they can get...
1031 ProvidePositionalOption(PositionalOpts[i],
1032 PositionalVals[ValNo].first,
1033 PositionalVals[ValNo].second);
1034 ValNo++;
1035 break;
1036 default:
1037 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1038 "positional argument processing!");
1039 }
1040 }
1041 }
1042 } else {
1043 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1044 unsigned ValNo = 0;
1045 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1046 if (RequiresValue(PositionalOpts[j])) {
1047 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1048 PositionalVals[ValNo].first,
1049 PositionalVals[ValNo].second);
1050 ValNo++;
1051 }
1052
1053 // Handle the case where there is just one positional option, and it's
1054 // optional. In this case, we want to give JUST THE FIRST option to the
1055 // positional option and keep the rest for the consume after. The above
1056 // loop would have assigned no values to positional options in this case.
1057 //
1058 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1059 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1060 PositionalVals[ValNo].first,
1061 PositionalVals[ValNo].second);
1062 ValNo++;
1063 }
1064
1065 // Handle over all of the rest of the arguments to the
1066 // cl::ConsumeAfter command line option...
1067 for (; ValNo != PositionalVals.size(); ++ValNo)
1068 ErrorParsing |=
1069 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1070 PositionalVals[ValNo].second);
1071 }
1072
1073 // Loop over args and make sure all required args are specified!
1074 for (const auto &Opt : OptionsMap) {
1075 switch (Opt.second->getNumOccurrencesFlag()) {
1076 case Required:
1077 case OneOrMore:
1078 if (Opt.second->getNumOccurrences() == 0) {
1079 Opt.second->error("must be specified at least once!");
1080 ErrorParsing = true;
1081 }
1082 // Fall through
1083 default:
1084 break;
1085 }
1086 }
1087
1088 // Now that we know if -debug is specified, we can use it.
1089 // Note that if ReadResponseFiles == true, this must be done before the
1090 // memory allocated for the expanded command line is free()d below.
1091 DEBUG(dbgs() << "Args: ";
1092 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1093 dbgs() << '\n';);
1094
1095 // Free all of the memory allocated to the map. Command line options may only
1096 // be processed once!
1097 MoreHelp.clear();
1098
1099 // If we had an error processing our arguments, don't let the program execute
1100 if (ErrorParsing)
1101 exit(1);
1102 }
1103
1104 //===----------------------------------------------------------------------===//
1105 // Option Base class implementation
1106 //
1107
error(const Twine & Message,StringRef ArgName)1108 bool Option::error(const Twine &Message, StringRef ArgName) {
1109 if (!ArgName.data())
1110 ArgName = ArgStr;
1111 if (ArgName.empty())
1112 errs() << HelpStr; // Be nice for positional arguments
1113 else
1114 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
1115
1116 errs() << " option: " << Message << "\n";
1117 return true;
1118 }
1119
addOccurrence(unsigned pos,StringRef ArgName,StringRef Value,bool MultiArg)1120 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1121 bool MultiArg) {
1122 if (!MultiArg)
1123 NumOccurrences++; // Increment the number of times we have been seen
1124
1125 switch (getNumOccurrencesFlag()) {
1126 case Optional:
1127 if (NumOccurrences > 1)
1128 return error("may only occur zero or one times!", ArgName);
1129 break;
1130 case Required:
1131 if (NumOccurrences > 1)
1132 return error("must occur exactly one time!", ArgName);
1133 // Fall through
1134 case OneOrMore:
1135 case ZeroOrMore:
1136 case ConsumeAfter:
1137 break;
1138 }
1139
1140 return handleOccurrence(pos, ArgName, Value);
1141 }
1142
1143 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1144 // has been specified yet.
1145 //
getValueStr(const Option & O,StringRef DefaultMsg)1146 static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1147 if (O.ValueStr.empty())
1148 return DefaultMsg;
1149 return O.ValueStr;
1150 }
1151
1152 //===----------------------------------------------------------------------===//
1153 // cl::alias class implementation
1154 //
1155
1156 // Return the width of the option tag for printing...
getOptionWidth() const1157 size_t alias::getOptionWidth() const { return ArgStr.size() + 6; }
1158
printHelpStr(StringRef HelpStr,size_t Indent,size_t FirstLineIndentedBy)1159 static void printHelpStr(StringRef HelpStr, size_t Indent,
1160 size_t FirstLineIndentedBy) {
1161 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1162 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1163 while (!Split.second.empty()) {
1164 Split = Split.second.split('\n');
1165 outs().indent(Indent) << Split.first << "\n";
1166 }
1167 }
1168
1169 // Print out the option for the alias.
printOptionInfo(size_t GlobalWidth) const1170 void alias::printOptionInfo(size_t GlobalWidth) const {
1171 outs() << " -" << ArgStr;
1172 printHelpStr(HelpStr, GlobalWidth, ArgStr.size() + 6);
1173 }
1174
1175 //===----------------------------------------------------------------------===//
1176 // Parser Implementation code...
1177 //
1178
1179 // basic_parser implementation
1180 //
1181
1182 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1183 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1184 size_t Len = O.ArgStr.size();
1185 if (const char *ValName = getValueName())
1186 Len += getValueStr(O, ValName).size() + 3;
1187
1188 return Len + 6;
1189 }
1190
1191 // printOptionInfo - Print out information about this option. The
1192 // to-be-maintained width is specified.
1193 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1194 void basic_parser_impl::printOptionInfo(const Option &O,
1195 size_t GlobalWidth) const {
1196 outs() << " -" << O.ArgStr;
1197
1198 if (const char *ValName = getValueName())
1199 outs() << "=<" << getValueStr(O, ValName) << '>';
1200
1201 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1202 }
1203
printOptionName(const Option & O,size_t GlobalWidth) const1204 void basic_parser_impl::printOptionName(const Option &O,
1205 size_t GlobalWidth) const {
1206 outs() << " -" << O.ArgStr;
1207 outs().indent(GlobalWidth - O.ArgStr.size());
1208 }
1209
1210 // parser<bool> implementation
1211 //
parse(Option & O,StringRef ArgName,StringRef Arg,bool & Value)1212 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1213 bool &Value) {
1214 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1215 Arg == "1") {
1216 Value = true;
1217 return false;
1218 }
1219
1220 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1221 Value = false;
1222 return false;
1223 }
1224 return O.error("'" + Arg +
1225 "' is invalid value for boolean argument! Try 0 or 1");
1226 }
1227
1228 // parser<boolOrDefault> implementation
1229 //
parse(Option & O,StringRef ArgName,StringRef Arg,boolOrDefault & Value)1230 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1231 boolOrDefault &Value) {
1232 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1233 Arg == "1") {
1234 Value = BOU_TRUE;
1235 return false;
1236 }
1237 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1238 Value = BOU_FALSE;
1239 return false;
1240 }
1241
1242 return O.error("'" + Arg +
1243 "' is invalid value for boolean argument! Try 0 or 1");
1244 }
1245
1246 // parser<int> implementation
1247 //
parse(Option & O,StringRef ArgName,StringRef Arg,int & Value)1248 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1249 int &Value) {
1250 if (Arg.getAsInteger(0, Value))
1251 return O.error("'" + Arg + "' value invalid for integer argument!");
1252 return false;
1253 }
1254
1255 // parser<unsigned> implementation
1256 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned & Value)1257 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1258 unsigned &Value) {
1259
1260 if (Arg.getAsInteger(0, Value))
1261 return O.error("'" + Arg + "' value invalid for uint argument!");
1262 return false;
1263 }
1264
1265 // parser<unsigned long long> implementation
1266 //
parse(Option & O,StringRef ArgName,StringRef Arg,unsigned long long & Value)1267 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1268 StringRef Arg,
1269 unsigned long long &Value) {
1270
1271 if (Arg.getAsInteger(0, Value))
1272 return O.error("'" + Arg + "' value invalid for uint argument!");
1273 return false;
1274 }
1275
1276 // parser<double>/parser<float> implementation
1277 //
parseDouble(Option & O,StringRef Arg,double & Value)1278 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1279 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1280 const char *ArgStart = TmpStr.c_str();
1281 char *End;
1282 Value = strtod(ArgStart, &End);
1283 if (*End != 0)
1284 return O.error("'" + Arg + "' value invalid for floating point argument!");
1285 return false;
1286 }
1287
parse(Option & O,StringRef ArgName,StringRef Arg,double & Val)1288 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1289 double &Val) {
1290 return parseDouble(O, Arg, Val);
1291 }
1292
parse(Option & O,StringRef ArgName,StringRef Arg,float & Val)1293 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1294 float &Val) {
1295 double dVal;
1296 if (parseDouble(O, Arg, dVal))
1297 return true;
1298 Val = (float)dVal;
1299 return false;
1300 }
1301
1302 // generic_parser_base implementation
1303 //
1304
1305 // findOption - Return the option number corresponding to the specified
1306 // argument string. If the option is not found, getNumOptions() is returned.
1307 //
findOption(const char * Name)1308 unsigned generic_parser_base::findOption(const char *Name) {
1309 unsigned e = getNumOptions();
1310
1311 for (unsigned i = 0; i != e; ++i) {
1312 if (strcmp(getOption(i), Name) == 0)
1313 return i;
1314 }
1315 return e;
1316 }
1317
1318 // Return the width of the option tag for printing...
getOptionWidth(const Option & O) const1319 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1320 if (O.hasArgStr()) {
1321 size_t Size = O.ArgStr.size() + 6;
1322 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1323 Size = std::max(Size, std::strlen(getOption(i)) + 8);
1324 return Size;
1325 } else {
1326 size_t BaseSize = 0;
1327 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1328 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1329 return BaseSize;
1330 }
1331 }
1332
1333 // printOptionInfo - Print out information about this option. The
1334 // to-be-maintained width is specified.
1335 //
printOptionInfo(const Option & O,size_t GlobalWidth) const1336 void generic_parser_base::printOptionInfo(const Option &O,
1337 size_t GlobalWidth) const {
1338 if (O.hasArgStr()) {
1339 outs() << " -" << O.ArgStr;
1340 printHelpStr(O.HelpStr, GlobalWidth, O.ArgStr.size() + 6);
1341
1342 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1343 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1344 outs() << " =" << getOption(i);
1345 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
1346 }
1347 } else {
1348 if (!O.HelpStr.empty())
1349 outs() << " " << O.HelpStr << '\n';
1350 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1351 const char *Option = getOption(i);
1352 outs() << " -" << Option;
1353 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1354 }
1355 }
1356 }
1357
1358 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1359
1360 // printGenericOptionDiff - Print the value of this option and it's default.
1361 //
1362 // "Generic" options have each value mapped to a name.
printGenericOptionDiff(const Option & O,const GenericOptionValue & Value,const GenericOptionValue & Default,size_t GlobalWidth) const1363 void generic_parser_base::printGenericOptionDiff(
1364 const Option &O, const GenericOptionValue &Value,
1365 const GenericOptionValue &Default, size_t GlobalWidth) const {
1366 outs() << " -" << O.ArgStr;
1367 outs().indent(GlobalWidth - O.ArgStr.size());
1368
1369 unsigned NumOpts = getNumOptions();
1370 for (unsigned i = 0; i != NumOpts; ++i) {
1371 if (Value.compare(getOptionValue(i)))
1372 continue;
1373
1374 outs() << "= " << getOption(i);
1375 size_t L = std::strlen(getOption(i));
1376 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1377 outs().indent(NumSpaces) << " (default: ";
1378 for (unsigned j = 0; j != NumOpts; ++j) {
1379 if (Default.compare(getOptionValue(j)))
1380 continue;
1381 outs() << getOption(j);
1382 break;
1383 }
1384 outs() << ")\n";
1385 return;
1386 }
1387 outs() << "= *unknown option value*\n";
1388 }
1389
1390 // printOptionDiff - Specializations for printing basic value types.
1391 //
1392 #define PRINT_OPT_DIFF(T) \
1393 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1394 size_t GlobalWidth) const { \
1395 printOptionName(O, GlobalWidth); \
1396 std::string Str; \
1397 { \
1398 raw_string_ostream SS(Str); \
1399 SS << V; \
1400 } \
1401 outs() << "= " << Str; \
1402 size_t NumSpaces = \
1403 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1404 outs().indent(NumSpaces) << " (default: "; \
1405 if (D.hasValue()) \
1406 outs() << D.getValue(); \
1407 else \
1408 outs() << "*no default*"; \
1409 outs() << ")\n"; \
1410 }
1411
1412 PRINT_OPT_DIFF(bool)
PRINT_OPT_DIFF(boolOrDefault)1413 PRINT_OPT_DIFF(boolOrDefault)
1414 PRINT_OPT_DIFF(int)
1415 PRINT_OPT_DIFF(unsigned)
1416 PRINT_OPT_DIFF(unsigned long long)
1417 PRINT_OPT_DIFF(double)
1418 PRINT_OPT_DIFF(float)
1419 PRINT_OPT_DIFF(char)
1420
1421 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1422 OptionValue<std::string> D,
1423 size_t GlobalWidth) const {
1424 printOptionName(O, GlobalWidth);
1425 outs() << "= " << V;
1426 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1427 outs().indent(NumSpaces) << " (default: ";
1428 if (D.hasValue())
1429 outs() << D.getValue();
1430 else
1431 outs() << "*no default*";
1432 outs() << ")\n";
1433 }
1434
1435 // Print a placeholder for options that don't yet support printOptionDiff().
printOptionNoValue(const Option & O,size_t GlobalWidth) const1436 void basic_parser_impl::printOptionNoValue(const Option &O,
1437 size_t GlobalWidth) const {
1438 printOptionName(O, GlobalWidth);
1439 outs() << "= *cannot print option value*\n";
1440 }
1441
1442 //===----------------------------------------------------------------------===//
1443 // -help and -help-hidden option implementation
1444 //
1445
OptNameCompare(const std::pair<const char *,Option * > * LHS,const std::pair<const char *,Option * > * RHS)1446 static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
1447 const std::pair<const char *, Option *> *RHS) {
1448 return strcmp(LHS->first, RHS->first);
1449 }
1450
1451 // Copy Options into a vector so we can sort them as we like.
sortOpts(StringMap<Option * > & OptMap,SmallVectorImpl<std::pair<const char *,Option * >> & Opts,bool ShowHidden)1452 static void sortOpts(StringMap<Option *> &OptMap,
1453 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1454 bool ShowHidden) {
1455 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1456
1457 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1458 I != E; ++I) {
1459 // Ignore really-hidden options.
1460 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1461 continue;
1462
1463 // Unless showhidden is set, ignore hidden flags.
1464 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1465 continue;
1466
1467 // If we've already seen this option, don't add it to the list again.
1468 if (!OptionSet.insert(I->second).second)
1469 continue;
1470
1471 Opts.push_back(
1472 std::pair<const char *, Option *>(I->getKey().data(), I->second));
1473 }
1474
1475 // Sort the options list alphabetically.
1476 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
1477 }
1478
1479 namespace {
1480
1481 class HelpPrinter {
1482 protected:
1483 const bool ShowHidden;
1484 typedef SmallVector<std::pair<const char *, Option *>, 128>
1485 StrOptionPairVector;
1486 // Print the options. Opts is assumed to be alphabetically sorted.
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1487 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1488 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1489 Opts[i].second->printOptionInfo(MaxArgLen);
1490 }
1491
1492 public:
HelpPrinter(bool showHidden)1493 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
~HelpPrinter()1494 virtual ~HelpPrinter() {}
1495
1496 // Invoke the printer.
operator =(bool Value)1497 void operator=(bool Value) {
1498 if (!Value)
1499 return;
1500
1501 StrOptionPairVector Opts;
1502 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
1503
1504 if (GlobalParser->ProgramOverview)
1505 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
1506
1507 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
1508
1509 for (auto Opt : GlobalParser->PositionalOpts) {
1510 if (Opt->hasArgStr())
1511 outs() << " --" << Opt->ArgStr;
1512 outs() << " " << Opt->HelpStr;
1513 }
1514
1515 // Print the consume after option info if it exists...
1516 if (GlobalParser->ConsumeAfterOpt)
1517 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
1518
1519 outs() << "\n\n";
1520
1521 // Compute the maximum argument length...
1522 size_t MaxArgLen = 0;
1523 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1524 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1525
1526 outs() << "OPTIONS:\n";
1527 printOptions(Opts, MaxArgLen);
1528
1529 // Print any extra help the user has declared.
1530 for (auto I : GlobalParser->MoreHelp)
1531 outs() << I;
1532 GlobalParser->MoreHelp.clear();
1533
1534 // Halt the program since help information was printed
1535 exit(0);
1536 }
1537 };
1538
1539 class CategorizedHelpPrinter : public HelpPrinter {
1540 public:
CategorizedHelpPrinter(bool showHidden)1541 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1542
1543 // Helper function for printOptions().
1544 // It shall return a negative value if A's name should be lexicographically
1545 // ordered before B's name. It returns a value greater equal zero otherwise.
OptionCategoryCompare(OptionCategory * const * A,OptionCategory * const * B)1546 static int OptionCategoryCompare(OptionCategory *const *A,
1547 OptionCategory *const *B) {
1548 return strcmp((*A)->getName(), (*B)->getName());
1549 }
1550
1551 // Make sure we inherit our base class's operator=()
1552 using HelpPrinter::operator=;
1553
1554 protected:
printOptions(StrOptionPairVector & Opts,size_t MaxArgLen)1555 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1556 std::vector<OptionCategory *> SortedCategories;
1557 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1558
1559 // Collect registered option categories into vector in preparation for
1560 // sorting.
1561 for (auto I = GlobalParser->RegisteredOptionCategories.begin(),
1562 E = GlobalParser->RegisteredOptionCategories.end();
1563 I != E; ++I) {
1564 SortedCategories.push_back(*I);
1565 }
1566
1567 // Sort the different option categories alphabetically.
1568 assert(SortedCategories.size() > 0 && "No option categories registered!");
1569 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
1570 OptionCategoryCompare);
1571
1572 // Create map to empty vectors.
1573 for (std::vector<OptionCategory *>::const_iterator
1574 I = SortedCategories.begin(),
1575 E = SortedCategories.end();
1576 I != E; ++I)
1577 CategorizedOptions[*I] = std::vector<Option *>();
1578
1579 // Walk through pre-sorted options and assign into categories.
1580 // Because the options are already alphabetically sorted the
1581 // options within categories will also be alphabetically sorted.
1582 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1583 Option *Opt = Opts[I].second;
1584 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1585 "Option has an unregistered category");
1586 CategorizedOptions[Opt->Category].push_back(Opt);
1587 }
1588
1589 // Now do printing.
1590 for (std::vector<OptionCategory *>::const_iterator
1591 Category = SortedCategories.begin(),
1592 E = SortedCategories.end();
1593 Category != E; ++Category) {
1594 // Hide empty categories for -help, but show for -help-hidden.
1595 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1596 if (!ShowHidden && IsEmptyCategory)
1597 continue;
1598
1599 // Print category information.
1600 outs() << "\n";
1601 outs() << (*Category)->getName() << ":\n";
1602
1603 // Check if description is set.
1604 if ((*Category)->getDescription() != nullptr)
1605 outs() << (*Category)->getDescription() << "\n\n";
1606 else
1607 outs() << "\n";
1608
1609 // When using -help-hidden explicitly state if the category has no
1610 // options associated with it.
1611 if (IsEmptyCategory) {
1612 outs() << " This option category has no options.\n";
1613 continue;
1614 }
1615 // Loop over the options in the category and print.
1616 for (std::vector<Option *>::const_iterator
1617 Opt = CategorizedOptions[*Category].begin(),
1618 E = CategorizedOptions[*Category].end();
1619 Opt != E; ++Opt)
1620 (*Opt)->printOptionInfo(MaxArgLen);
1621 }
1622 }
1623 };
1624
1625 // This wraps the Uncategorizing and Categorizing printers and decides
1626 // at run time which should be invoked.
1627 class HelpPrinterWrapper {
1628 private:
1629 HelpPrinter &UncategorizedPrinter;
1630 CategorizedHelpPrinter &CategorizedPrinter;
1631
1632 public:
HelpPrinterWrapper(HelpPrinter & UncategorizedPrinter,CategorizedHelpPrinter & CategorizedPrinter)1633 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1634 CategorizedHelpPrinter &CategorizedPrinter)
1635 : UncategorizedPrinter(UncategorizedPrinter),
1636 CategorizedPrinter(CategorizedPrinter) {}
1637
1638 // Invoke the printer.
1639 void operator=(bool Value);
1640 };
1641
1642 } // End anonymous namespace
1643
1644 // Declare the four HelpPrinter instances that are used to print out help, or
1645 // help-hidden as an uncategorized list or in categories.
1646 static HelpPrinter UncategorizedNormalPrinter(false);
1647 static HelpPrinter UncategorizedHiddenPrinter(true);
1648 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1649 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1650
1651 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1652 // a categorizing help printer
1653 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1654 CategorizedNormalPrinter);
1655 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1656 CategorizedHiddenPrinter);
1657
1658 // Define a category for generic options that all tools should have.
1659 static cl::OptionCategory GenericCategory("Generic Options");
1660
1661 // Define uncategorized help printers.
1662 // -help-list is hidden by default because if Option categories are being used
1663 // then -help behaves the same as -help-list.
1664 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1665 "help-list",
1666 cl::desc("Display list of available options (-help-list-hidden for more)"),
1667 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1668 cl::cat(GenericCategory));
1669
1670 static cl::opt<HelpPrinter, true, parser<bool>>
1671 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1672 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1673 cl::ValueDisallowed, cl::cat(GenericCategory));
1674
1675 // Define uncategorized/categorized help printers. These printers change their
1676 // behaviour at runtime depending on whether one or more Option categories have
1677 // been declared.
1678 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1679 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1680 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1681 cl::cat(GenericCategory));
1682
1683 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1684 HHOp("help-hidden", cl::desc("Display all available options"),
1685 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1686 cl::cat(GenericCategory));
1687
1688 static cl::opt<bool> PrintOptions(
1689 "print-options",
1690 cl::desc("Print non-default options after command line parsing"),
1691 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1692
1693 static cl::opt<bool> PrintAllOptions(
1694 "print-all-options",
1695 cl::desc("Print all option values after command line parsing"), cl::Hidden,
1696 cl::init(false), cl::cat(GenericCategory));
1697
operator =(bool Value)1698 void HelpPrinterWrapper::operator=(bool Value) {
1699 if (!Value)
1700 return;
1701
1702 // Decide which printer to invoke. If more than one option category is
1703 // registered then it is useful to show the categorized help instead of
1704 // uncategorized help.
1705 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
1706 // unhide -help-list option so user can have uncategorized output if they
1707 // want it.
1708 HLOp.setHiddenFlag(NotHidden);
1709
1710 CategorizedPrinter = true; // Invoke categorized printer
1711 } else
1712 UncategorizedPrinter = true; // Invoke uncategorized printer
1713 }
1714
1715 // Print the value of each option.
PrintOptionValues()1716 void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1717
printOptionValues()1718 void CommandLineParser::printOptionValues() {
1719 if (!PrintOptions && !PrintAllOptions)
1720 return;
1721
1722 SmallVector<std::pair<const char *, Option *>, 128> Opts;
1723 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
1724
1725 // Compute the maximum argument length...
1726 size_t MaxArgLen = 0;
1727 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1728 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1729
1730 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1731 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1732 }
1733
1734 static void (*OverrideVersionPrinter)() = nullptr;
1735
1736 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1737
1738 namespace {
1739 class VersionPrinter {
1740 public:
print()1741 void print() {
1742 raw_ostream &OS = outs();
1743 OS << "LLVM (http://llvm.org/):\n"
1744 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1745 #ifdef LLVM_VERSION_INFO
1746 OS << " " << LLVM_VERSION_INFO;
1747 #endif
1748 OS << "\n ";
1749 #ifndef __OPTIMIZE__
1750 OS << "DEBUG build";
1751 #else
1752 OS << "Optimized build";
1753 #endif
1754 #ifndef NDEBUG
1755 OS << " with assertions";
1756 #endif
1757 std::string CPU = sys::getHostCPUName();
1758 if (CPU == "generic")
1759 CPU = "(unknown)";
1760 OS << ".\n"
1761 #if (ENABLE_TIMESTAMPS == 1)
1762 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
1763 #endif
1764 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
1765 << " Host CPU: " << CPU << '\n';
1766 }
operator =(bool OptionWasSpecified)1767 void operator=(bool OptionWasSpecified) {
1768 if (!OptionWasSpecified)
1769 return;
1770
1771 if (OverrideVersionPrinter != nullptr) {
1772 (*OverrideVersionPrinter)();
1773 exit(0);
1774 }
1775 print();
1776
1777 // Iterate over any registered extra printers and call them to add further
1778 // information.
1779 if (ExtraVersionPrinters != nullptr) {
1780 outs() << '\n';
1781 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1782 E = ExtraVersionPrinters->end();
1783 I != E; ++I)
1784 (*I)();
1785 }
1786
1787 exit(0);
1788 }
1789 };
1790 } // End anonymous namespace
1791
1792 // Define the --version option that prints out the LLVM version for the tool
1793 static VersionPrinter VersionPrinterInstance;
1794
1795 static cl::opt<VersionPrinter, true, parser<bool>>
1796 VersOp("version", cl::desc("Display the version of this program"),
1797 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1798 cl::cat(GenericCategory));
1799
1800 // Utility function for printing the help message.
PrintHelpMessage(bool Hidden,bool Categorized)1801 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1802 // This looks weird, but it actually prints the help message. The Printers are
1803 // types of HelpPrinter and the help gets printed when its operator= is
1804 // invoked. That's because the "normal" usages of the help printer is to be
1805 // assigned true/false depending on whether -help or -help-hidden was given or
1806 // not. Since we're circumventing that we have to make it look like -help or
1807 // -help-hidden were given, so we assign true.
1808
1809 if (!Hidden && !Categorized)
1810 UncategorizedNormalPrinter = true;
1811 else if (!Hidden && Categorized)
1812 CategorizedNormalPrinter = true;
1813 else if (Hidden && !Categorized)
1814 UncategorizedHiddenPrinter = true;
1815 else
1816 CategorizedHiddenPrinter = true;
1817 }
1818
1819 /// Utility function for printing version number.
PrintVersionMessage()1820 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1821
SetVersionPrinter(void (* func)())1822 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1823
AddExtraVersionPrinter(void (* func)())1824 void cl::AddExtraVersionPrinter(void (*func)()) {
1825 if (!ExtraVersionPrinters)
1826 ExtraVersionPrinters = new std::vector<void (*)()>;
1827
1828 ExtraVersionPrinters->push_back(func);
1829 }
1830
getRegisteredOptions()1831 StringMap<Option *> &cl::getRegisteredOptions() {
1832 return GlobalParser->OptionsMap;
1833 }
1834
HideUnrelatedOptions(cl::OptionCategory & Category)1835 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1836 for (auto &I : GlobalParser->OptionsMap) {
1837 if (I.second->Category != &Category &&
1838 I.second->Category != &GenericCategory)
1839 I.second->setHiddenFlag(cl::ReallyHidden);
1840 }
1841 }
1842
HideUnrelatedOptions(ArrayRef<const cl::OptionCategory * > Categories)1843 void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
1844 auto CategoriesBegin = Categories.begin();
1845 auto CategoriesEnd = Categories.end();
1846 for (auto &I : GlobalParser->OptionsMap) {
1847 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1848 CategoriesEnd &&
1849 I.second->Category != &GenericCategory)
1850 I.second->setHiddenFlag(cl::ReallyHidden);
1851 }
1852 }
1853
LLVMParseCommandLineOptions(int argc,const char * const * argv,const char * Overview)1854 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1855 const char *Overview) {
1856 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1857 }
1858