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