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