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