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