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