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