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