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