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