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