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