CommandLine: Add support for 64 bit unsigned integer options.
[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/Support/Debug.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Support/system_error.h"
26 #include "llvm/Support/Host.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Config/config.h"
34 #include <cerrno>
35 #include <cstdlib>
36 using namespace llvm;
37 using namespace cl;
38
39 //===----------------------------------------------------------------------===//
40 // Template instantiations and anchors.
41 //
42 namespace llvm { namespace cl {
43 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
44 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45 TEMPLATE_INSTANTIATION(class basic_parser<int>);
46 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
48 TEMPLATE_INSTANTIATION(class basic_parser<double>);
49 TEMPLATE_INSTANTIATION(class basic_parser<float>);
50 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
51 TEMPLATE_INSTANTIATION(class basic_parser<char>);
52
53 TEMPLATE_INSTANTIATION(class opt<unsigned>);
54 TEMPLATE_INSTANTIATION(class opt<int>);
55 TEMPLATE_INSTANTIATION(class opt<std::string>);
56 TEMPLATE_INSTANTIATION(class opt<char>);
57 TEMPLATE_INSTANTIATION(class opt<bool>);
58 } } // end namespace llvm::cl
59
60 void Option::anchor() {}
61 void basic_parser_impl::anchor() {}
62 void parser<bool>::anchor() {}
63 void parser<boolOrDefault>::anchor() {}
64 void parser<int>::anchor() {}
65 void parser<unsigned>::anchor() {}
66 void parser<unsigned long long>::anchor() {}
67 void parser<double>::anchor() {}
68 void parser<float>::anchor() {}
69 void parser<std::string>::anchor() {}
70 void parser<char>::anchor() {}
71
72 //===----------------------------------------------------------------------===//
73
74 // Globals for name and overview of program.  Program name is not a string to
75 // avoid static ctor/dtor issues.
76 static char ProgramName[80] = "<premain>";
77 static const char *ProgramOverview = 0;
78
79 // This collects additional help to be printed.
80 static ManagedStatic<std::vector<const char*> > MoreHelp;
81
82 extrahelp::extrahelp(const char *Help)
83   : morehelp(Help) {
84   MoreHelp->push_back(Help);
85 }
86
87 static bool OptionListChanged = false;
88
89 // MarkOptionsChanged - Internal helper function.
90 void cl::MarkOptionsChanged() {
91   OptionListChanged = true;
92 }
93
94 /// RegisteredOptionList - This is the list of the command line options that
95 /// have statically constructed themselves.
96 static Option *RegisteredOptionList = 0;
97
98 void Option::addArgument() {
99   assert(NextRegistered == 0 && "argument multiply registered!");
100
101   NextRegistered = RegisteredOptionList;
102   RegisteredOptionList = this;
103   MarkOptionsChanged();
104 }
105
106
107 //===----------------------------------------------------------------------===//
108 // Basic, shared command line option processing machinery.
109 //
110
111 /// GetOptionInfo - Scan the list of registered options, turning them into data
112 /// structures that are easier to handle.
113 static void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
114                           SmallVectorImpl<Option*> &SinkOpts,
115                           StringMap<Option*> &OptionsMap) {
116   SmallVector<const char*, 16> OptionNames;
117   Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
118   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
119     // If this option wants to handle multiple option names, get the full set.
120     // This handles enum options like "-O1 -O2" etc.
121     O->getExtraOptionNames(OptionNames);
122     if (O->ArgStr[0])
123       OptionNames.push_back(O->ArgStr);
124
125     // Handle named options.
126     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
127       // Add argument to the argument map!
128       if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
129         errs() << ProgramName << ": CommandLine Error: Argument '"
130              << OptionNames[i] << "' defined more than once!\n";
131       }
132     }
133
134     OptionNames.clear();
135
136     // Remember information about positional options.
137     if (O->getFormattingFlag() == cl::Positional)
138       PositionalOpts.push_back(O);
139     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
140       SinkOpts.push_back(O);
141     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
142       if (CAOpt)
143         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
144       CAOpt = O;
145     }
146   }
147
148   if (CAOpt)
149     PositionalOpts.push_back(CAOpt);
150
151   // Make sure that they are in order of registration not backwards.
152   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
153 }
154
155
156 /// LookupOption - Lookup the option specified by the specified option on the
157 /// command line.  If there is a value specified (after an equal sign) return
158 /// that as well.  This assumes that leading dashes have already been stripped.
159 static Option *LookupOption(StringRef &Arg, StringRef &Value,
160                             const StringMap<Option*> &OptionsMap) {
161   // Reject all dashes.
162   if (Arg.empty()) return 0;
163
164   size_t EqualPos = Arg.find('=');
165
166   // If we have an equals sign, remember the value.
167   if (EqualPos == StringRef::npos) {
168     // Look up the option.
169     StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
170     return I != OptionsMap.end() ? I->second : 0;
171   }
172
173   // If the argument before the = is a valid option name, we match.  If not,
174   // return Arg unmolested.
175   StringMap<Option*>::const_iterator I =
176     OptionsMap.find(Arg.substr(0, EqualPos));
177   if (I == OptionsMap.end()) return 0;
178
179   Value = Arg.substr(EqualPos+1);
180   Arg = Arg.substr(0, EqualPos);
181   return I->second;
182 }
183
184 /// LookupNearestOption - Lookup the closest match to the option specified by
185 /// the specified option on the command line.  If there is a value specified
186 /// (after an equal sign) return that as well.  This assumes that leading dashes
187 /// have already been stripped.
188 static Option *LookupNearestOption(StringRef Arg,
189                                    const StringMap<Option*> &OptionsMap,
190                                    std::string &NearestString) {
191   // Reject all dashes.
192   if (Arg.empty()) return 0;
193
194   // Split on any equal sign.
195   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
196   StringRef &LHS = SplitArg.first;  // LHS == Arg when no '=' is present.
197   StringRef &RHS = SplitArg.second;
198
199   // Find the closest match.
200   Option *Best = 0;
201   unsigned BestDistance = 0;
202   for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
203          ie = OptionsMap.end(); it != ie; ++it) {
204     Option *O = it->second;
205     SmallVector<const char*, 16> OptionNames;
206     O->getExtraOptionNames(OptionNames);
207     if (O->ArgStr[0])
208       OptionNames.push_back(O->ArgStr);
209
210     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
211     StringRef Flag = PermitValue ? LHS : Arg;
212     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
213       StringRef Name = OptionNames[i];
214       unsigned Distance = StringRef(Name).edit_distance(
215         Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
216       if (!Best || Distance < BestDistance) {
217         Best = O;
218         BestDistance = Distance;
219         if (RHS.empty() || !PermitValue)
220           NearestString = OptionNames[i];
221         else
222           NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
223       }
224     }
225   }
226
227   return Best;
228 }
229
230 /// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
231 /// does special handling of cl::CommaSeparated options.
232 static bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
233                                          StringRef ArgName,
234                                          StringRef Value, bool MultiArg = false)
235 {
236   // Check to see if this option accepts a comma separated list of values.  If
237   // it does, we have to split up the value into multiple values.
238   if (Handler->getMiscFlags() & CommaSeparated) {
239     StringRef Val(Value);
240     StringRef::size_type Pos = Val.find(',');
241
242     while (Pos != StringRef::npos) {
243       // Process the portion before the comma.
244       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
245         return true;
246       // Erase the portion before the comma, AND the comma.
247       Val = Val.substr(Pos+1);
248       Value.substr(Pos+1);  // Increment the original value pointer as well.
249       // Check for another comma.
250       Pos = Val.find(',');
251     }
252
253     Value = Val;
254   }
255
256   if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
257     return true;
258
259   return false;
260 }
261
262 /// ProvideOption - For Value, this differentiates between an empty value ("")
263 /// and a null value (StringRef()).  The later is accepted for arguments that
264 /// don't allow a value (-foo) the former is rejected (-foo=).
265 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
266                                  StringRef Value, int argc, char **argv,
267                                  int &i) {
268   // Is this a multi-argument option?
269   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
270
271   // Enforce value requirements
272   switch (Handler->getValueExpectedFlag()) {
273   case ValueRequired:
274     if (Value.data() == 0) {       // No value specified?
275       if (i+1 >= argc)
276         return Handler->error("requires a value!");
277       // Steal the next argument, like for '-o filename'
278       Value = argv[++i];
279     }
280     break;
281   case ValueDisallowed:
282     if (NumAdditionalVals > 0)
283       return Handler->error("multi-valued option specified"
284                             " with ValueDisallowed modifier!");
285
286     if (Value.data())
287       return Handler->error("does not allow a value! '" +
288                             Twine(Value) + "' specified.");
289     break;
290   case ValueOptional:
291     break;
292
293   default:
294     errs() << ProgramName
295          << ": Bad ValueMask flag! CommandLine usage error:"
296          << Handler->getValueExpectedFlag() << "\n";
297     llvm_unreachable(0);
298   }
299
300   // If this isn't a multi-arg option, just run the handler.
301   if (NumAdditionalVals == 0)
302     return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
303
304   // If it is, run the handle several times.
305   bool MultiArg = false;
306
307   if (Value.data()) {
308     if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
309       return true;
310     --NumAdditionalVals;
311     MultiArg = true;
312   }
313
314   while (NumAdditionalVals > 0) {
315     if (i+1 >= argc)
316       return Handler->error("not enough values!");
317     Value = argv[++i];
318
319     if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
320       return true;
321     MultiArg = true;
322     --NumAdditionalVals;
323   }
324   return false;
325 }
326
327 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
328   int Dummy = i;
329   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
330 }
331
332
333 // Option predicates...
334 static inline bool isGrouping(const Option *O) {
335   return O->getFormattingFlag() == cl::Grouping;
336 }
337 static inline bool isPrefixedOrGrouping(const Option *O) {
338   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
339 }
340
341 // getOptionPred - Check to see if there are any options that satisfy the
342 // specified predicate with names that are the prefixes in Name.  This is
343 // checked by progressively stripping characters off of the name, checking to
344 // see if there options that satisfy the predicate.  If we find one, return it,
345 // otherwise return null.
346 //
347 static Option *getOptionPred(StringRef Name, size_t &Length,
348                              bool (*Pred)(const Option*),
349                              const StringMap<Option*> &OptionsMap) {
350
351   StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
352
353   // Loop while we haven't found an option and Name still has at least two
354   // characters in it (so that the next iteration will not be the empty
355   // string.
356   while (OMI == OptionsMap.end() && Name.size() > 1) {
357     Name = Name.substr(0, Name.size()-1);   // Chop off the last character.
358     OMI = OptionsMap.find(Name);
359   }
360
361   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
362     Length = Name.size();
363     return OMI->second;    // Found one!
364   }
365   return 0;                // No option found!
366 }
367
368 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
369 /// with at least one '-') does not fully match an available option.  Check to
370 /// see if this is a prefix or grouped option.  If so, split arg into output an
371 /// Arg/Value pair and return the Option to parse it with.
372 static Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
373                                              bool &ErrorParsing,
374                                          const StringMap<Option*> &OptionsMap) {
375   if (Arg.size() == 1) return 0;
376
377   // Do the lookup!
378   size_t Length = 0;
379   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
380   if (PGOpt == 0) return 0;
381
382   // If the option is a prefixed option, then the value is simply the
383   // rest of the name...  so fall through to later processing, by
384   // setting up the argument name flags and value fields.
385   if (PGOpt->getFormattingFlag() == cl::Prefix) {
386     Value = Arg.substr(Length);
387     Arg = Arg.substr(0, Length);
388     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
389     return PGOpt;
390   }
391
392   // This must be a grouped option... handle them now.  Grouping options can't
393   // have values.
394   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
395
396   do {
397     // Move current arg name out of Arg into OneArgName.
398     StringRef OneArgName = Arg.substr(0, Length);
399     Arg = Arg.substr(Length);
400
401     // Because ValueRequired is an invalid flag for grouped arguments,
402     // we don't need to pass argc/argv in.
403     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
404            "Option can not be cl::Grouping AND cl::ValueRequired!");
405     int Dummy = 0;
406     ErrorParsing |= ProvideOption(PGOpt, OneArgName,
407                                   StringRef(), 0, 0, Dummy);
408
409     // Get the next grouping option.
410     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
411   } while (PGOpt && Length != Arg.size());
412
413   // Return the last option with Arg cut down to just the last one.
414   return PGOpt;
415 }
416
417
418
419 static bool RequiresValue(const Option *O) {
420   return O->getNumOccurrencesFlag() == cl::Required ||
421          O->getNumOccurrencesFlag() == cl::OneOrMore;
422 }
423
424 static bool EatsUnboundedNumberOfValues(const Option *O) {
425   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
426          O->getNumOccurrencesFlag() == cl::OneOrMore;
427 }
428
429 /// ParseCStringVector - Break INPUT up wherever one or more
430 /// whitespace characters are found, and store the resulting tokens in
431 /// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
432 /// using strdup(), so it is the caller's responsibility to free()
433 /// them later.
434 ///
435 static void ParseCStringVector(std::vector<char *> &OutputVector,
436                                const char *Input) {
437   // Characters which will be treated as token separators:
438   StringRef Delims = " \v\f\t\r\n";
439
440   StringRef WorkStr(Input);
441   while (!WorkStr.empty()) {
442     // If the first character is a delimiter, strip them off.
443     if (Delims.find(WorkStr[0]) != StringRef::npos) {
444       size_t Pos = WorkStr.find_first_not_of(Delims);
445       if (Pos == StringRef::npos) Pos = WorkStr.size();
446       WorkStr = WorkStr.substr(Pos);
447       continue;
448     }
449
450     // Find position of first delimiter.
451     size_t Pos = WorkStr.find_first_of(Delims);
452     if (Pos == StringRef::npos) Pos = WorkStr.size();
453
454     // Everything from 0 to Pos is the next word to copy.
455     char *NewStr = (char*)malloc(Pos+1);
456     memcpy(NewStr, WorkStr.data(), Pos);
457     NewStr[Pos] = 0;
458     OutputVector.push_back(NewStr);
459
460     WorkStr = WorkStr.substr(Pos);
461   }
462 }
463
464 /// ParseEnvironmentOptions - An alternative entry point to the
465 /// CommandLine library, which allows you to read the program's name
466 /// from the caller (as PROGNAME) and its command-line arguments from
467 /// an environment variable (whose name is given in ENVVAR).
468 ///
469 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
470                                  const char *Overview, bool ReadResponseFiles) {
471   // Check args.
472   assert(progName && "Program name not specified");
473   assert(envVar && "Environment variable name missing");
474
475   // Get the environment variable they want us to parse options out of.
476   const char *envValue = getenv(envVar);
477   if (!envValue)
478     return;
479
480   // Get program's "name", which we wouldn't know without the caller
481   // telling us.
482   std::vector<char*> newArgv;
483   newArgv.push_back(strdup(progName));
484
485   // Parse the value of the environment variable into a "command line"
486   // and hand it off to ParseCommandLineOptions().
487   ParseCStringVector(newArgv, envValue);
488   int newArgc = static_cast<int>(newArgv.size());
489   ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
490
491   // Free all the strdup()ed strings.
492   for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
493        i != e; ++i)
494     free(*i);
495 }
496
497
498 /// ExpandResponseFiles - Copy the contents of argv into newArgv,
499 /// substituting the contents of the response files for the arguments
500 /// of type @file.
501 static void ExpandResponseFiles(unsigned argc, char** argv,
502                                 std::vector<char*>& newArgv) {
503   for (unsigned i = 1; i != argc; ++i) {
504     char *arg = argv[i];
505
506     if (arg[0] == '@') {
507       sys::PathWithStatus respFile(++arg);
508
509       // Check that the response file is not empty (mmap'ing empty
510       // files can be problematic).
511       const sys::FileStatus *FileStat = respFile.getFileStatus();
512       if (FileStat && FileStat->getSize() != 0) {
513
514         // If we could open the file, parse its contents, otherwise
515         // pass the @file option verbatim.
516
517         // TODO: we should also support recursive loading of response files,
518         // since this is how gcc behaves. (From their man page: "The file may
519         // itself contain additional @file options; any such options will be
520         // processed recursively.")
521
522         // Mmap the response file into memory.
523         OwningPtr<MemoryBuffer> respFilePtr;
524         if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
525           ParseCStringVector(newArgv, respFilePtr->getBufferStart());
526           continue;
527         }
528       }
529     }
530     newArgv.push_back(strdup(arg));
531   }
532 }
533
534 void cl::ParseCommandLineOptions(int argc, char **argv,
535                                  const char *Overview, bool ReadResponseFiles) {
536   // Process all registered options.
537   SmallVector<Option*, 4> PositionalOpts;
538   SmallVector<Option*, 4> SinkOpts;
539   StringMap<Option*> Opts;
540   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
541
542   assert((!Opts.empty() || !PositionalOpts.empty()) &&
543          "No options specified!");
544
545   // Expand response files.
546   std::vector<char*> newArgv;
547   if (ReadResponseFiles) {
548     newArgv.push_back(strdup(argv[0]));
549     ExpandResponseFiles(argc, argv, newArgv);
550     argv = &newArgv[0];
551     argc = static_cast<int>(newArgv.size());
552   }
553
554   // Copy the program name into ProgName, making sure not to overflow it.
555   std::string ProgName = sys::path::filename(argv[0]);
556   size_t Len = std::min(ProgName.size(), size_t(79));
557   memcpy(ProgramName, ProgName.data(), Len);
558   ProgramName[Len] = '\0';
559
560   ProgramOverview = Overview;
561   bool ErrorParsing = false;
562
563   // Check out the positional arguments to collect information about them.
564   unsigned NumPositionalRequired = 0;
565
566   // Determine whether or not there are an unlimited number of positionals
567   bool HasUnlimitedPositionals = false;
568
569   Option *ConsumeAfterOpt = 0;
570   if (!PositionalOpts.empty()) {
571     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
572       assert(PositionalOpts.size() > 1 &&
573              "Cannot specify cl::ConsumeAfter without a positional argument!");
574       ConsumeAfterOpt = PositionalOpts[0];
575     }
576
577     // Calculate how many positional values are _required_.
578     bool UnboundedFound = false;
579     for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
580          i != e; ++i) {
581       Option *Opt = PositionalOpts[i];
582       if (RequiresValue(Opt))
583         ++NumPositionalRequired;
584       else if (ConsumeAfterOpt) {
585         // ConsumeAfter cannot be combined with "optional" positional options
586         // unless there is only one positional argument...
587         if (PositionalOpts.size() > 2)
588           ErrorParsing |=
589             Opt->error("error - this positional option will never be matched, "
590                        "because it does not Require a value, and a "
591                        "cl::ConsumeAfter option is active!");
592       } else if (UnboundedFound && !Opt->ArgStr[0]) {
593         // This option does not "require" a value...  Make sure this option is
594         // not specified after an option that eats all extra arguments, or this
595         // one will never get any!
596         //
597         ErrorParsing |= Opt->error("error - option can never match, because "
598                                    "another positional argument will match an "
599                                    "unbounded number of values, and this option"
600                                    " does not require a value!");
601       }
602       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
603     }
604     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
605   }
606
607   // PositionalVals - A vector of "positional" arguments we accumulate into
608   // the process at the end.
609   //
610   SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
611
612   // If the program has named positional arguments, and the name has been run
613   // across, keep track of which positional argument was named.  Otherwise put
614   // the positional args into the PositionalVals list...
615   Option *ActivePositionalArg = 0;
616
617   // Loop over all of the arguments... processing them.
618   bool DashDashFound = false;  // Have we read '--'?
619   for (int i = 1; i < argc; ++i) {
620     Option *Handler = 0;
621     Option *NearestHandler = 0;
622     std::string NearestHandlerString;
623     StringRef Value;
624     StringRef ArgName = "";
625
626     // If the option list changed, this means that some command line
627     // option has just been registered or deregistered.  This can occur in
628     // response to things like -load, etc.  If this happens, rescan the options.
629     if (OptionListChanged) {
630       PositionalOpts.clear();
631       SinkOpts.clear();
632       Opts.clear();
633       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
634       OptionListChanged = false;
635     }
636
637     // Check to see if this is a positional argument.  This argument is
638     // considered to be positional if it doesn't start with '-', if it is "-"
639     // itself, or if we have seen "--" already.
640     //
641     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
642       // Positional argument!
643       if (ActivePositionalArg) {
644         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
645         continue;  // We are done!
646       }
647
648       if (!PositionalOpts.empty()) {
649         PositionalVals.push_back(std::make_pair(argv[i],i));
650
651         // All of the positional arguments have been fulfulled, give the rest to
652         // the consume after option... if it's specified...
653         //
654         if (PositionalVals.size() >= NumPositionalRequired &&
655             ConsumeAfterOpt != 0) {
656           for (++i; i < argc; ++i)
657             PositionalVals.push_back(std::make_pair(argv[i],i));
658           break;   // Handle outside of the argument processing loop...
659         }
660
661         // Delay processing positional arguments until the end...
662         continue;
663       }
664     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
665                !DashDashFound) {
666       DashDashFound = true;  // This is the mythical "--"?
667       continue;              // Don't try to process it as an argument itself.
668     } else if (ActivePositionalArg &&
669                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
670       // If there is a positional argument eating options, check to see if this
671       // option is another positional argument.  If so, treat it as an argument,
672       // otherwise feed it to the eating positional.
673       ArgName = argv[i]+1;
674       // Eat leading dashes.
675       while (!ArgName.empty() && ArgName[0] == '-')
676         ArgName = ArgName.substr(1);
677
678       Handler = LookupOption(ArgName, Value, Opts);
679       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
680         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
681         continue;  // We are done!
682       }
683
684     } else {     // We start with a '-', must be an argument.
685       ArgName = argv[i]+1;
686       // Eat leading dashes.
687       while (!ArgName.empty() && ArgName[0] == '-')
688         ArgName = ArgName.substr(1);
689
690       Handler = LookupOption(ArgName, Value, Opts);
691
692       // Check to see if this "option" is really a prefixed or grouped argument.
693       if (Handler == 0)
694         Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
695                                                 ErrorParsing, Opts);
696
697       // Otherwise, look for the closest available option to report to the user
698       // in the upcoming error.
699       if (Handler == 0 && SinkOpts.empty())
700         NearestHandler = LookupNearestOption(ArgName, Opts,
701                                              NearestHandlerString);
702     }
703
704     if (Handler == 0) {
705       if (SinkOpts.empty()) {
706         errs() << ProgramName << ": Unknown command line argument '"
707              << argv[i] << "'.  Try: '" << argv[0] << " -help'\n";
708
709         if (NearestHandler) {
710           // If we know a near match, report it as well.
711           errs() << ProgramName << ": Did you mean '-"
712                  << NearestHandlerString << "'?\n";
713         }
714
715         ErrorParsing = true;
716       } else {
717         for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
718                E = SinkOpts.end(); I != E ; ++I)
719           (*I)->addOccurrence(i, "", argv[i]);
720       }
721       continue;
722     }
723
724     // If this is a named positional argument, just remember that it is the
725     // active one...
726     if (Handler->getFormattingFlag() == cl::Positional)
727       ActivePositionalArg = Handler;
728     else
729       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
730   }
731
732   // Check and handle positional arguments now...
733   if (NumPositionalRequired > PositionalVals.size()) {
734     errs() << ProgramName
735          << ": Not enough positional command line arguments specified!\n"
736          << "Must specify at least " << NumPositionalRequired
737          << " positional arguments: See: " << argv[0] << " -help\n";
738
739     ErrorParsing = true;
740   } else if (!HasUnlimitedPositionals &&
741              PositionalVals.size() > PositionalOpts.size()) {
742     errs() << ProgramName
743          << ": Too many positional arguments specified!\n"
744          << "Can specify at most " << PositionalOpts.size()
745          << " positional arguments: See: " << argv[0] << " -help\n";
746     ErrorParsing = true;
747
748   } else if (ConsumeAfterOpt == 0) {
749     // Positional args have already been handled if ConsumeAfter is specified.
750     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
751     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
752       if (RequiresValue(PositionalOpts[i])) {
753         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
754                                 PositionalVals[ValNo].second);
755         ValNo++;
756         --NumPositionalRequired;  // We fulfilled our duty...
757       }
758
759       // If we _can_ give this option more arguments, do so now, as long as we
760       // do not give it values that others need.  'Done' controls whether the
761       // option even _WANTS_ any more.
762       //
763       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
764       while (NumVals-ValNo > NumPositionalRequired && !Done) {
765         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
766         case cl::Optional:
767           Done = true;          // Optional arguments want _at most_ one value
768           // FALL THROUGH
769         case cl::ZeroOrMore:    // Zero or more will take all they can get...
770         case cl::OneOrMore:     // One or more will take all they can get...
771           ProvidePositionalOption(PositionalOpts[i],
772                                   PositionalVals[ValNo].first,
773                                   PositionalVals[ValNo].second);
774           ValNo++;
775           break;
776         default:
777           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
778                  "positional argument processing!");
779         }
780       }
781     }
782   } else {
783     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
784     unsigned ValNo = 0;
785     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
786       if (RequiresValue(PositionalOpts[j])) {
787         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
788                                                 PositionalVals[ValNo].first,
789                                                 PositionalVals[ValNo].second);
790         ValNo++;
791       }
792
793     // Handle the case where there is just one positional option, and it's
794     // optional.  In this case, we want to give JUST THE FIRST option to the
795     // positional option and keep the rest for the consume after.  The above
796     // loop would have assigned no values to positional options in this case.
797     //
798     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
799       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
800                                               PositionalVals[ValNo].first,
801                                               PositionalVals[ValNo].second);
802       ValNo++;
803     }
804
805     // Handle over all of the rest of the arguments to the
806     // cl::ConsumeAfter command line option...
807     for (; ValNo != PositionalVals.size(); ++ValNo)
808       ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
809                                               PositionalVals[ValNo].first,
810                                               PositionalVals[ValNo].second);
811   }
812
813   // Loop over args and make sure all required args are specified!
814   for (StringMap<Option*>::iterator I = Opts.begin(),
815          E = Opts.end(); I != E; ++I) {
816     switch (I->second->getNumOccurrencesFlag()) {
817     case Required:
818     case OneOrMore:
819       if (I->second->getNumOccurrences() == 0) {
820         I->second->error("must be specified at least once!");
821         ErrorParsing = true;
822       }
823       // Fall through
824     default:
825       break;
826     }
827   }
828
829   // Now that we know if -debug is specified, we can use it.
830   // Note that if ReadResponseFiles == true, this must be done before the
831   // memory allocated for the expanded command line is free()d below.
832   DEBUG(dbgs() << "Args: ";
833         for (int i = 0; i < argc; ++i)
834           dbgs() << argv[i] << ' ';
835         dbgs() << '\n';
836        );
837
838   // Free all of the memory allocated to the map.  Command line options may only
839   // be processed once!
840   Opts.clear();
841   PositionalOpts.clear();
842   MoreHelp->clear();
843
844   // Free the memory allocated by ExpandResponseFiles.
845   if (ReadResponseFiles) {
846     // Free all the strdup()ed strings.
847     for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
848          i != e; ++i)
849       free(*i);
850   }
851
852   // If we had an error processing our arguments, don't let the program execute
853   if (ErrorParsing) exit(1);
854 }
855
856 //===----------------------------------------------------------------------===//
857 // Option Base class implementation
858 //
859
860 bool Option::error(const Twine &Message, StringRef ArgName) {
861   if (ArgName.data() == 0) ArgName = ArgStr;
862   if (ArgName.empty())
863     errs() << HelpStr;  // Be nice for positional arguments
864   else
865     errs() << ProgramName << ": for the -" << ArgName;
866
867   errs() << " option: " << Message << "\n";
868   return true;
869 }
870
871 bool Option::addOccurrence(unsigned pos, StringRef ArgName,
872                            StringRef Value, bool MultiArg) {
873   if (!MultiArg)
874     NumOccurrences++;   // Increment the number of times we have been seen
875
876   switch (getNumOccurrencesFlag()) {
877   case Optional:
878     if (NumOccurrences > 1)
879       return error("may only occur zero or one times!", ArgName);
880     break;
881   case Required:
882     if (NumOccurrences > 1)
883       return error("must occur exactly one time!", ArgName);
884     // Fall through
885   case OneOrMore:
886   case ZeroOrMore:
887   case ConsumeAfter: break;
888   default: return error("bad num occurrences flag value!");
889   }
890
891   return handleOccurrence(pos, ArgName, Value);
892 }
893
894
895 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
896 // has been specified yet.
897 //
898 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
899   if (O.ValueStr[0] == 0) return DefaultMsg;
900   return O.ValueStr;
901 }
902
903 //===----------------------------------------------------------------------===//
904 // cl::alias class implementation
905 //
906
907 // Return the width of the option tag for printing...
908 size_t alias::getOptionWidth() const {
909   return std::strlen(ArgStr)+6;
910 }
911
912 // Print out the option for the alias.
913 void alias::printOptionInfo(size_t GlobalWidth) const {
914   size_t L = std::strlen(ArgStr);
915   outs() << "  -" << ArgStr;
916   outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
917 }
918
919 //===----------------------------------------------------------------------===//
920 // Parser Implementation code...
921 //
922
923 // basic_parser implementation
924 //
925
926 // Return the width of the option tag for printing...
927 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
928   size_t Len = std::strlen(O.ArgStr);
929   if (const char *ValName = getValueName())
930     Len += std::strlen(getValueStr(O, ValName))+3;
931
932   return Len + 6;
933 }
934
935 // printOptionInfo - Print out information about this option.  The
936 // to-be-maintained width is specified.
937 //
938 void basic_parser_impl::printOptionInfo(const Option &O,
939                                         size_t GlobalWidth) const {
940   outs() << "  -" << O.ArgStr;
941
942   if (const char *ValName = getValueName())
943     outs() << "=<" << getValueStr(O, ValName) << '>';
944
945   outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
946 }
947
948 void basic_parser_impl::printOptionName(const Option &O,
949                                         size_t GlobalWidth) const {
950   outs() << "  -" << O.ArgStr;
951   outs().indent(GlobalWidth-std::strlen(O.ArgStr));
952 }
953
954
955 // parser<bool> implementation
956 //
957 bool parser<bool>::parse(Option &O, StringRef ArgName,
958                          StringRef Arg, bool &Value) {
959   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
960       Arg == "1") {
961     Value = true;
962     return false;
963   }
964
965   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
966     Value = false;
967     return false;
968   }
969   return O.error("'" + Arg +
970                  "' is invalid value for boolean argument! Try 0 or 1");
971 }
972
973 // parser<boolOrDefault> implementation
974 //
975 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
976                                   StringRef Arg, boolOrDefault &Value) {
977   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
978       Arg == "1") {
979     Value = BOU_TRUE;
980     return false;
981   }
982   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
983     Value = BOU_FALSE;
984     return false;
985   }
986
987   return O.error("'" + Arg +
988                  "' is invalid value for boolean argument! Try 0 or 1");
989 }
990
991 // parser<int> implementation
992 //
993 bool parser<int>::parse(Option &O, StringRef ArgName,
994                         StringRef Arg, int &Value) {
995   if (Arg.getAsInteger(0, Value))
996     return O.error("'" + Arg + "' value invalid for integer argument!");
997   return false;
998 }
999
1000 // parser<unsigned> implementation
1001 //
1002 bool parser<unsigned>::parse(Option &O, StringRef ArgName,
1003                              StringRef Arg, unsigned &Value) {
1004
1005   if (Arg.getAsInteger(0, Value))
1006     return O.error("'" + Arg + "' value invalid for uint argument!");
1007   return false;
1008 }
1009
1010 // parser<unsigned long long> implementation
1011 //
1012 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1013                                       StringRef Arg, unsigned long long &Value){
1014
1015   if (Arg.getAsInteger(0, Value))
1016     return O.error("'" + Arg + "' value invalid for uint argument!");
1017   return false;
1018 }
1019
1020 // parser<double>/parser<float> implementation
1021 //
1022 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1023   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1024   const char *ArgStart = TmpStr.c_str();
1025   char *End;
1026   Value = strtod(ArgStart, &End);
1027   if (*End != 0)
1028     return O.error("'" + Arg + "' value invalid for floating point argument!");
1029   return false;
1030 }
1031
1032 bool parser<double>::parse(Option &O, StringRef ArgName,
1033                            StringRef Arg, double &Val) {
1034   return parseDouble(O, Arg, Val);
1035 }
1036
1037 bool parser<float>::parse(Option &O, StringRef ArgName,
1038                           StringRef Arg, float &Val) {
1039   double dVal;
1040   if (parseDouble(O, Arg, dVal))
1041     return true;
1042   Val = (float)dVal;
1043   return false;
1044 }
1045
1046
1047
1048 // generic_parser_base implementation
1049 //
1050
1051 // findOption - Return the option number corresponding to the specified
1052 // argument string.  If the option is not found, getNumOptions() is returned.
1053 //
1054 unsigned generic_parser_base::findOption(const char *Name) {
1055   unsigned e = getNumOptions();
1056
1057   for (unsigned i = 0; i != e; ++i) {
1058     if (strcmp(getOption(i), Name) == 0)
1059       return i;
1060   }
1061   return e;
1062 }
1063
1064
1065 // Return the width of the option tag for printing...
1066 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1067   if (O.hasArgStr()) {
1068     size_t Size = std::strlen(O.ArgStr)+6;
1069     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1070       Size = std::max(Size, std::strlen(getOption(i))+8);
1071     return Size;
1072   } else {
1073     size_t BaseSize = 0;
1074     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1075       BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1076     return BaseSize;
1077   }
1078 }
1079
1080 // printOptionInfo - Print out information about this option.  The
1081 // to-be-maintained width is specified.
1082 //
1083 void generic_parser_base::printOptionInfo(const Option &O,
1084                                           size_t GlobalWidth) const {
1085   if (O.hasArgStr()) {
1086     size_t L = std::strlen(O.ArgStr);
1087     outs() << "  -" << O.ArgStr;
1088     outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1089
1090     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1091       size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1092       outs() << "    =" << getOption(i);
1093       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1094     }
1095   } else {
1096     if (O.HelpStr[0])
1097       outs() << "  " << O.HelpStr << '\n';
1098     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1099       size_t L = std::strlen(getOption(i));
1100       outs() << "    -" << getOption(i);
1101       outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1102     }
1103   }
1104 }
1105
1106 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1107
1108 // printGenericOptionDiff - Print the value of this option and it's default.
1109 //
1110 // "Generic" options have each value mapped to a name.
1111 void generic_parser_base::
1112 printGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1113                        const GenericOptionValue &Default,
1114                        size_t GlobalWidth) const {
1115   outs() << "  -" << O.ArgStr;
1116   outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1117
1118   unsigned NumOpts = getNumOptions();
1119   for (unsigned i = 0; i != NumOpts; ++i) {
1120     if (Value.compare(getOptionValue(i)))
1121       continue;
1122
1123     outs() << "= " << getOption(i);
1124     size_t L = std::strlen(getOption(i));
1125     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1126     outs().indent(NumSpaces) << " (default: ";
1127     for (unsigned j = 0; j != NumOpts; ++j) {
1128       if (Default.compare(getOptionValue(j)))
1129         continue;
1130       outs() << getOption(j);
1131       break;
1132     }
1133     outs() << ")\n";
1134     return;
1135   }
1136   outs() << "= *unknown option value*\n";
1137 }
1138
1139 // printOptionDiff - Specializations for printing basic value types.
1140 //
1141 #define PRINT_OPT_DIFF(T)                                               \
1142   void parser<T>::                                                      \
1143   printOptionDiff(const Option &O, T V, OptionValue<T> D,               \
1144                   size_t GlobalWidth) const {                           \
1145     printOptionName(O, GlobalWidth);                                    \
1146     std::string Str;                                                    \
1147     {                                                                   \
1148       raw_string_ostream SS(Str);                                       \
1149       SS << V;                                                          \
1150     }                                                                   \
1151     outs() << "= " << Str;                                              \
1152     size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1153     outs().indent(NumSpaces) << " (default: ";                          \
1154     if (D.hasValue())                                                   \
1155       outs() << D.getValue();                                           \
1156     else                                                                \
1157       outs() << "*no default*";                                         \
1158     outs() << ")\n";                                                    \
1159   }                                                                     \
1160
1161 PRINT_OPT_DIFF(bool)
1162 PRINT_OPT_DIFF(boolOrDefault)
1163 PRINT_OPT_DIFF(int)
1164 PRINT_OPT_DIFF(unsigned)
1165 PRINT_OPT_DIFF(unsigned long long)
1166 PRINT_OPT_DIFF(double)
1167 PRINT_OPT_DIFF(float)
1168 PRINT_OPT_DIFF(char)
1169
1170 void parser<std::string>::
1171 printOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1172                 size_t GlobalWidth) const {
1173   printOptionName(O, GlobalWidth);
1174   outs() << "= " << V;
1175   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1176   outs().indent(NumSpaces) << " (default: ";
1177   if (D.hasValue())
1178     outs() << D.getValue();
1179   else
1180     outs() << "*no default*";
1181   outs() << ")\n";
1182 }
1183
1184 // Print a placeholder for options that don't yet support printOptionDiff().
1185 void basic_parser_impl::
1186 printOptionNoValue(const Option &O, size_t GlobalWidth) const {
1187   printOptionName(O, GlobalWidth);
1188   outs() << "= *cannot print option value*\n";
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 // -help and -help-hidden option implementation
1193 //
1194
1195 static int OptNameCompare(const void *LHS, const void *RHS) {
1196   typedef std::pair<const char *, Option*> pair_ty;
1197
1198   return strcmp(((pair_ty*)LHS)->first, ((pair_ty*)RHS)->first);
1199 }
1200
1201 // Copy Options into a vector so we can sort them as we like.
1202 static void
1203 sortOpts(StringMap<Option*> &OptMap,
1204          SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1205          bool ShowHidden) {
1206   SmallPtrSet<Option*, 128> OptionSet;  // Duplicate option detection.
1207
1208   for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1209        I != E; ++I) {
1210     // Ignore really-hidden options.
1211     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1212       continue;
1213
1214     // Unless showhidden is set, ignore hidden flags.
1215     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1216       continue;
1217
1218     // If we've already seen this option, don't add it to the list again.
1219     if (!OptionSet.insert(I->second))
1220       continue;
1221
1222     Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1223                                                     I->second));
1224   }
1225
1226   // Sort the options list alphabetically.
1227   qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1228 }
1229
1230 namespace {
1231
1232 class HelpPrinter {
1233   size_t MaxArgLen;
1234   const Option *EmptyArg;
1235   const bool ShowHidden;
1236
1237 public:
1238   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1239     EmptyArg = 0;
1240   }
1241
1242   void operator=(bool Value) {
1243     if (Value == false) return;
1244
1245     // Get all the options.
1246     SmallVector<Option*, 4> PositionalOpts;
1247     SmallVector<Option*, 4> SinkOpts;
1248     StringMap<Option*> OptMap;
1249     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1250
1251     SmallVector<std::pair<const char *, Option*>, 128> Opts;
1252     sortOpts(OptMap, Opts, ShowHidden);
1253
1254     if (ProgramOverview)
1255       outs() << "OVERVIEW: " << ProgramOverview << "\n";
1256
1257     outs() << "USAGE: " << ProgramName << " [options]";
1258
1259     // Print out the positional options.
1260     Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
1261     if (!PositionalOpts.empty() &&
1262         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1263       CAOpt = PositionalOpts[0];
1264
1265     for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1266       if (PositionalOpts[i]->ArgStr[0])
1267         outs() << " --" << PositionalOpts[i]->ArgStr;
1268       outs() << " " << PositionalOpts[i]->HelpStr;
1269     }
1270
1271     // Print the consume after option info if it exists...
1272     if (CAOpt) outs() << " " << CAOpt->HelpStr;
1273
1274     outs() << "\n\n";
1275
1276     // Compute the maximum argument length...
1277     MaxArgLen = 0;
1278     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1279       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1280
1281     outs() << "OPTIONS:\n";
1282     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1283       Opts[i].second->printOptionInfo(MaxArgLen);
1284
1285     // Print any extra help the user has declared.
1286     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1287           E = MoreHelp->end(); I != E; ++I)
1288       outs() << *I;
1289     MoreHelp->clear();
1290
1291     // Halt the program since help information was printed
1292     exit(1);
1293   }
1294 };
1295 } // End anonymous namespace
1296
1297 // Define the two HelpPrinter instances that are used to print out help, or
1298 // help-hidden...
1299 //
1300 static HelpPrinter NormalPrinter(false);
1301 static HelpPrinter HiddenPrinter(true);
1302
1303 static cl::opt<HelpPrinter, true, parser<bool> >
1304 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1305     cl::location(NormalPrinter), cl::ValueDisallowed);
1306
1307 static cl::opt<HelpPrinter, true, parser<bool> >
1308 HHOp("help-hidden", cl::desc("Display all available options"),
1309      cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1310
1311 static cl::opt<bool>
1312 PrintOptions("print-options",
1313              cl::desc("Print non-default options after command line parsing"),
1314              cl::Hidden, cl::init(false));
1315
1316 static cl::opt<bool>
1317 PrintAllOptions("print-all-options",
1318                 cl::desc("Print all option values after command line parsing"),
1319                 cl::Hidden, cl::init(false));
1320
1321 // Print the value of each option.
1322 void cl::PrintOptionValues() {
1323   if (!PrintOptions && !PrintAllOptions) return;
1324
1325   // Get all the options.
1326   SmallVector<Option*, 4> PositionalOpts;
1327   SmallVector<Option*, 4> SinkOpts;
1328   StringMap<Option*> OptMap;
1329   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1330
1331   SmallVector<std::pair<const char *, Option*>, 128> Opts;
1332   sortOpts(OptMap, Opts, /*ShowHidden*/true);
1333
1334   // Compute the maximum argument length...
1335   size_t MaxArgLen = 0;
1336   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1337     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1338
1339   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1340     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1341 }
1342
1343 static void (*OverrideVersionPrinter)() = 0;
1344
1345 static std::vector<void (*)()>* ExtraVersionPrinters = 0;
1346
1347 namespace {
1348 class VersionPrinter {
1349 public:
1350   void print() {
1351     raw_ostream &OS = outs();
1352     OS << "Low Level Virtual Machine (http://llvm.org/):\n"
1353        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1354 #ifdef LLVM_VERSION_INFO
1355     OS << LLVM_VERSION_INFO;
1356 #endif
1357     OS << "\n  ";
1358 #ifndef __OPTIMIZE__
1359     OS << "DEBUG build";
1360 #else
1361     OS << "Optimized build";
1362 #endif
1363 #ifndef NDEBUG
1364     OS << " with assertions";
1365 #endif
1366     std::string CPU = sys::getHostCPUName();
1367     if (CPU == "generic") CPU = "(unknown)";
1368     OS << ".\n"
1369 #if (ENABLE_TIMESTAMPS == 1)
1370        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1371 #endif
1372        << "  Host: " << sys::getHostTriple() << '\n'
1373        << "  Host CPU: " << CPU << '\n';
1374   }
1375   void operator=(bool OptionWasSpecified) {
1376     if (!OptionWasSpecified) return;
1377
1378     if (OverrideVersionPrinter != 0) {
1379       (*OverrideVersionPrinter)();
1380       exit(1);
1381     }
1382     print();
1383
1384     // Iterate over any registered extra printers and call them to add further
1385     // information.
1386     if (ExtraVersionPrinters != 0) {
1387       outs() << '\n';
1388       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1389                                              E = ExtraVersionPrinters->end();
1390            I != E; ++I)
1391         (*I)();
1392     }
1393
1394     exit(1);
1395   }
1396 };
1397 } // End anonymous namespace
1398
1399
1400 // Define the --version option that prints out the LLVM version for the tool
1401 static VersionPrinter VersionPrinterInstance;
1402
1403 static cl::opt<VersionPrinter, true, parser<bool> >
1404 VersOp("version", cl::desc("Display the version of this program"),
1405     cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1406
1407 // Utility function for printing the help message.
1408 void cl::PrintHelpMessage() {
1409   // This looks weird, but it actually prints the help message. The
1410   // NormalPrinter variable is a HelpPrinter and the help gets printed when
1411   // its operator= is invoked. That's because the "normal" usages of the
1412   // help printer is to be assigned true/false depending on whether the
1413   // -help option was given or not. Since we're circumventing that we have
1414   // to make it look like -help was given, so we assign true.
1415   NormalPrinter = true;
1416 }
1417
1418 /// Utility function for printing version number.
1419 void cl::PrintVersionMessage() {
1420   VersionPrinterInstance.print();
1421 }
1422
1423 void cl::SetVersionPrinter(void (*func)()) {
1424   OverrideVersionPrinter = func;
1425 }
1426
1427 void cl::AddExtraVersionPrinter(void (*func)()) {
1428   if (ExtraVersionPrinters == 0)
1429     ExtraVersionPrinters = new std::vector<void (*)()>;
1430
1431   ExtraVersionPrinters->push_back(func);
1432 }