Switch all uses of LLVM_OVERRIDE to just use 'override' directly.
[oota-llvm.git] / include / llvm / Support / CommandLine.h
1 //===- llvm/Support/CommandLine.h - Command line handler --------*- C++ -*-===//
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 should
15 // read the library documentation located in docs/CommandLine.html or looks at
16 // the many example usages in tools/*/*.cpp
17 //
18 //===----------------------------------------------------------------------===//
19
20 #ifndef LLVM_SUPPORT_COMMANDLINE_H
21 #define LLVM_SUPPORT_COMMANDLINE_H
22
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/type_traits.h"
28 #include <cassert>
29 #include <climits>
30 #include <cstdarg>
31 #include <utility>
32 #include <vector>
33
34 namespace llvm {
35
36 /// cl Namespace - This namespace contains all of the command line option
37 /// processing machinery.  It is intentionally a short name to make qualified
38 /// usage concise.
39 namespace cl {
40
41 //===----------------------------------------------------------------------===//
42 // ParseCommandLineOptions - Command line option processing entry point.
43 //
44 void ParseCommandLineOptions(int argc, const char * const *argv,
45                              const char *Overview = 0);
46
47 //===----------------------------------------------------------------------===//
48 // ParseEnvironmentOptions - Environment variable option processing alternate
49 //                           entry point.
50 //
51 void ParseEnvironmentOptions(const char *progName, const char *envvar,
52                              const char *Overview = 0);
53
54 ///===---------------------------------------------------------------------===//
55 /// SetVersionPrinter - Override the default (LLVM specific) version printer
56 ///                     used to print out the version when --version is given
57 ///                     on the command line. This allows other systems using the
58 ///                     CommandLine utilities to print their own version string.
59 void SetVersionPrinter(void (*func)());
60
61 ///===---------------------------------------------------------------------===//
62 /// AddExtraVersionPrinter - Add an extra printer to use in addition to the
63 ///                          default one. This can be called multiple times,
64 ///                          and each time it adds a new function to the list
65 ///                          which will be called after the basic LLVM version
66 ///                          printing is complete. Each can then add additional
67 ///                          information specific to the tool.
68 void AddExtraVersionPrinter(void (*func)());
69
70
71 // PrintOptionValues - Print option values.
72 // With -print-options print the difference between option values and defaults.
73 // With -print-all-options print all option values.
74 // (Currently not perfect, but best-effort.)
75 void PrintOptionValues();
76
77 // MarkOptionsChanged - Internal helper function.
78 void MarkOptionsChanged();
79
80 //===----------------------------------------------------------------------===//
81 // Flags permitted to be passed to command line arguments
82 //
83
84 enum NumOccurrencesFlag {      // Flags for the number of occurrences allowed
85   Optional        = 0x00,      // Zero or One occurrence
86   ZeroOrMore      = 0x01,      // Zero or more occurrences allowed
87   Required        = 0x02,      // One occurrence required
88   OneOrMore       = 0x03,      // One or more occurrences required
89
90   // ConsumeAfter - Indicates that this option is fed anything that follows the
91   // last positional argument required by the application (it is an error if
92   // there are zero positional arguments, and a ConsumeAfter option is used).
93   // Thus, for example, all arguments to LLI are processed until a filename is
94   // found.  Once a filename is found, all of the succeeding arguments are
95   // passed, unprocessed, to the ConsumeAfter option.
96   //
97   ConsumeAfter    = 0x04
98 };
99
100 enum ValueExpected {           // Is a value required for the option?
101   // zero reserved for the unspecified value
102   ValueOptional   = 0x01,      // The value can appear... or not
103   ValueRequired   = 0x02,      // The value is required to appear!
104   ValueDisallowed = 0x03       // A value may not be specified (for flags)
105 };
106
107 enum OptionHidden {            // Control whether -help shows this option
108   NotHidden       = 0x00,      // Option included in -help & -help-hidden
109   Hidden          = 0x01,      // -help doesn't, but -help-hidden does
110   ReallyHidden    = 0x02       // Neither -help nor -help-hidden show this arg
111 };
112
113 // Formatting flags - This controls special features that the option might have
114 // that cause it to be parsed differently...
115 //
116 // Prefix - This option allows arguments that are otherwise unrecognized to be
117 // matched by options that are a prefix of the actual value.  This is useful for
118 // cases like a linker, where options are typically of the form '-lfoo' or
119 // '-L../../include' where -l or -L are the actual flags.  When prefix is
120 // enabled, and used, the value for the flag comes from the suffix of the
121 // argument.
122 //
123 // Grouping - With this option enabled, multiple letter options are allowed to
124 // bunch together with only a single hyphen for the whole group.  This allows
125 // emulation of the behavior that ls uses for example: ls -la === ls -l -a
126 //
127
128 enum FormattingFlags {
129   NormalFormatting = 0x00,     // Nothing special
130   Positional       = 0x01,     // Is a positional argument, no '-' required
131   Prefix           = 0x02,     // Can this option directly prefix its value?
132   Grouping         = 0x03      // Can this option group with other options?
133 };
134
135 enum MiscFlags {               // Miscellaneous flags to adjust argument
136   CommaSeparated     = 0x01,  // Should this cl::list split between commas?
137   PositionalEatsArgs = 0x02,  // Should this positional cl::list eat -args?
138   Sink               = 0x04   // Should this cl::list eat all unknown options?
139 };
140
141 //===----------------------------------------------------------------------===//
142 // Option Category class
143 //
144 class OptionCategory {
145 private:
146   const char *const Name;
147   const char *const Description;
148   void registerCategory();
149 public:
150   OptionCategory(const char *const Name, const char *const Description = 0)
151       : Name(Name), Description(Description) { registerCategory(); }
152   const char *getName() const { return Name; }
153   const char *getDescription() const { return Description; }
154 };
155
156 // The general Option Category (used as default category).
157 extern OptionCategory GeneralCategory;
158
159 //===----------------------------------------------------------------------===//
160 // Option Base class
161 //
162 class alias;
163 class Option {
164   friend class alias;
165
166   // handleOccurrences - Overriden by subclasses to handle the value passed into
167   // an argument.  Should return true if there was an error processing the
168   // argument and the program should exit.
169   //
170   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
171                                 StringRef Arg) = 0;
172
173   virtual enum ValueExpected getValueExpectedFlagDefault() const {
174     return ValueOptional;
175   }
176
177   // Out of line virtual function to provide home for the class.
178   virtual void anchor();
179
180   int NumOccurrences;     // The number of times specified
181   // Occurrences, HiddenFlag, and Formatting are all enum types but to avoid
182   // problems with signed enums in bitfields.
183   unsigned Occurrences : 3; // enum NumOccurrencesFlag
184   // not using the enum type for 'Value' because zero is an implementation
185   // detail representing the non-value
186   unsigned Value : 2;
187   unsigned HiddenFlag : 2; // enum OptionHidden
188   unsigned Formatting : 2; // enum FormattingFlags
189   unsigned Misc : 3;
190   unsigned Position;      // Position of last occurrence of the option
191   unsigned AdditionalVals;// Greater than 0 for multi-valued option.
192   Option *NextRegistered; // Singly linked list of registered options.
193
194 public:
195   const char *ArgStr;   // The argument string itself (ex: "help", "o")
196   const char *HelpStr;  // The descriptive text message for -help
197   const char *ValueStr; // String describing what the value of this option is
198   OptionCategory *Category; // The Category this option belongs to
199
200   inline enum NumOccurrencesFlag getNumOccurrencesFlag() const {
201     return (enum NumOccurrencesFlag)Occurrences;
202   }
203   inline enum ValueExpected getValueExpectedFlag() const {
204     return Value ? ((enum ValueExpected)Value)
205               : getValueExpectedFlagDefault();
206   }
207   inline enum OptionHidden getOptionHiddenFlag() const {
208     return (enum OptionHidden)HiddenFlag;
209   }
210   inline enum FormattingFlags getFormattingFlag() const {
211     return (enum FormattingFlags)Formatting;
212   }
213   inline unsigned getMiscFlags() const {
214     return Misc;
215   }
216   inline unsigned getPosition() const { return Position; }
217   inline unsigned getNumAdditionalVals() const { return AdditionalVals; }
218
219   // hasArgStr - Return true if the argstr != ""
220   bool hasArgStr() const { return ArgStr[0] != 0; }
221
222   //-------------------------------------------------------------------------===
223   // Accessor functions set by OptionModifiers
224   //
225   void setArgStr(const char *S) { ArgStr = S; }
226   void setDescription(const char *S) { HelpStr = S; }
227   void setValueStr(const char *S) { ValueStr = S; }
228   void setNumOccurrencesFlag(enum NumOccurrencesFlag Val) {
229     Occurrences = Val;
230   }
231   void setValueExpectedFlag(enum ValueExpected Val) { Value = Val; }
232   void setHiddenFlag(enum OptionHidden Val) { HiddenFlag = Val; }
233   void setFormattingFlag(enum FormattingFlags V) { Formatting = V; }
234   void setMiscFlag(enum MiscFlags M) { Misc |= M; }
235   void setPosition(unsigned pos) { Position = pos; }
236   void setCategory(OptionCategory &C) { Category = &C; }
237 protected:
238   explicit Option(enum NumOccurrencesFlag OccurrencesFlag,
239                   enum OptionHidden Hidden)
240     : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
241       HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
242       Position(0), AdditionalVals(0), NextRegistered(0),
243       ArgStr(""), HelpStr(""), ValueStr(""), Category(&GeneralCategory) {
244   }
245
246   inline void setNumAdditionalVals(unsigned n) { AdditionalVals = n; }
247 public:
248   // addArgument - Register this argument with the commandline system.
249   //
250   void addArgument();
251
252   /// Unregisters this option from the CommandLine system.
253   ///
254   /// This option must have been the last option registered.
255   /// For testing purposes only.
256   void removeArgument();
257
258   Option *getNextRegisteredOption() const { return NextRegistered; }
259
260   // Return the width of the option tag for printing...
261   virtual size_t getOptionWidth() const = 0;
262
263   // printOptionInfo - Print out information about this option.  The
264   // to-be-maintained width is specified.
265   //
266   virtual void printOptionInfo(size_t GlobalWidth) const = 0;
267
268   virtual void printOptionValue(size_t GlobalWidth, bool Force) const = 0;
269
270   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
271
272   // addOccurrence - Wrapper around handleOccurrence that enforces Flags.
273   //
274   bool addOccurrence(unsigned pos, StringRef ArgName,
275                      StringRef Value, bool MultiArg = false);
276
277   // Prints option name followed by message.  Always returns true.
278   bool error(const Twine &Message, StringRef ArgName = StringRef());
279
280 public:
281   inline int getNumOccurrences() const { return NumOccurrences; }
282   virtual ~Option() {}
283 };
284
285
286 //===----------------------------------------------------------------------===//
287 // Command line option modifiers that can be used to modify the behavior of
288 // command line option parsers...
289 //
290
291 // desc - Modifier to set the description shown in the -help output...
292 struct desc {
293   const char *Desc;
294   desc(const char *Str) : Desc(Str) {}
295   void apply(Option &O) const { O.setDescription(Desc); }
296 };
297
298 // value_desc - Modifier to set the value description shown in the -help
299 // output...
300 struct value_desc {
301   const char *Desc;
302   value_desc(const char *Str) : Desc(Str) {}
303   void apply(Option &O) const { O.setValueStr(Desc); }
304 };
305
306 // init - Specify a default (initial) value for the command line argument, if
307 // the default constructor for the argument type does not give you what you
308 // want.  This is only valid on "opt" arguments, not on "list" arguments.
309 //
310 template<class Ty>
311 struct initializer {
312   const Ty &Init;
313   initializer(const Ty &Val) : Init(Val) {}
314
315   template<class Opt>
316   void apply(Opt &O) const { O.setInitialValue(Init); }
317 };
318
319 template<class Ty>
320 initializer<Ty> init(const Ty &Val) {
321   return initializer<Ty>(Val);
322 }
323
324
325 // location - Allow the user to specify which external variable they want to
326 // store the results of the command line argument processing into, if they don't
327 // want to store it in the option itself.
328 //
329 template<class Ty>
330 struct LocationClass {
331   Ty &Loc;
332   LocationClass(Ty &L) : Loc(L) {}
333
334   template<class Opt>
335   void apply(Opt &O) const { O.setLocation(O, Loc); }
336 };
337
338 template<class Ty>
339 LocationClass<Ty> location(Ty &L) { return LocationClass<Ty>(L); }
340
341 // cat - Specifiy the Option category for the command line argument to belong
342 // to.
343 struct cat {
344   OptionCategory &Category;
345   cat(OptionCategory &c) : Category(c) {}
346
347   template<class Opt>
348   void apply(Opt &O) const { O.setCategory(Category); }
349 };
350
351
352 //===----------------------------------------------------------------------===//
353 // OptionValue class
354
355 // Support value comparison outside the template.
356 struct GenericOptionValue {
357   virtual ~GenericOptionValue() {}
358   virtual bool compare(const GenericOptionValue &V) const = 0;
359
360 private:
361   virtual void anchor();
362 };
363
364 template<class DataType> struct OptionValue;
365
366 // The default value safely does nothing. Option value printing is only
367 // best-effort.
368 template<class DataType, bool isClass>
369 struct OptionValueBase : public GenericOptionValue {
370   // Temporary storage for argument passing.
371   typedef OptionValue<DataType> WrapperType;
372
373   bool hasValue() const { return false; }
374
375   const DataType &getValue() const { llvm_unreachable("no default value"); }
376
377   // Some options may take their value from a different data type.
378   template<class DT>
379   void setValue(const DT& /*V*/) {}
380
381   bool compare(const DataType &/*V*/) const { return false; }
382
383   virtual bool compare(const GenericOptionValue& /*V*/) const { return false; }
384 };
385
386 // Simple copy of the option value.
387 template<class DataType>
388 class OptionValueCopy : public GenericOptionValue {
389   DataType Value;
390   bool Valid;
391 public:
392   OptionValueCopy() : Valid(false) {}
393
394   bool hasValue() const { return Valid; }
395
396   const DataType &getValue() const {
397     assert(Valid && "invalid option value");
398     return Value;
399   }
400
401   void setValue(const DataType &V) { Valid = true; Value = V; }
402
403   bool compare(const DataType &V) const {
404     return Valid && (Value != V);
405   }
406
407   virtual bool compare(const GenericOptionValue &V) const {
408     const OptionValueCopy<DataType> &VC =
409       static_cast< const OptionValueCopy<DataType>& >(V);
410     if (!VC.hasValue()) return false;
411     return compare(VC.getValue());
412   }
413 };
414
415 // Non-class option values.
416 template<class DataType>
417 struct OptionValueBase<DataType, false> : OptionValueCopy<DataType> {
418   typedef DataType WrapperType;
419 };
420
421 // Top-level option class.
422 template<class DataType>
423 struct OptionValue : OptionValueBase<DataType, is_class<DataType>::value> {
424   OptionValue() {}
425
426   OptionValue(const DataType& V) {
427     this->setValue(V);
428   }
429   // Some options may take their value from a different data type.
430   template<class DT>
431   OptionValue<DataType> &operator=(const DT& V) {
432     this->setValue(V);
433     return *this;
434   }
435 };
436
437 // Other safe-to-copy-by-value common option types.
438 enum boolOrDefault { BOU_UNSET, BOU_TRUE, BOU_FALSE };
439 template<>
440 struct OptionValue<cl::boolOrDefault> : OptionValueCopy<cl::boolOrDefault> {
441   typedef cl::boolOrDefault WrapperType;
442
443   OptionValue() {}
444
445   OptionValue(const cl::boolOrDefault& V) {
446     this->setValue(V);
447   }
448   OptionValue<cl::boolOrDefault> &operator=(const cl::boolOrDefault& V) {
449     setValue(V);
450     return *this;
451   }
452 private:
453   virtual void anchor();
454 };
455
456 template<>
457 struct OptionValue<std::string> : OptionValueCopy<std::string> {
458   typedef StringRef WrapperType;
459
460   OptionValue() {}
461
462   OptionValue(const std::string& V) {
463     this->setValue(V);
464   }
465   OptionValue<std::string> &operator=(const std::string& V) {
466     setValue(V);
467     return *this;
468   }
469 private:
470   virtual void anchor();
471 };
472
473 //===----------------------------------------------------------------------===//
474 // Enum valued command line option
475 //
476 #define clEnumVal(ENUMVAL, DESC) #ENUMVAL, int(ENUMVAL), DESC
477 #define clEnumValN(ENUMVAL, FLAGNAME, DESC) FLAGNAME, int(ENUMVAL), DESC
478 #define clEnumValEnd (reinterpret_cast<void*>(0))
479
480 // values - For custom data types, allow specifying a group of values together
481 // as the values that go into the mapping that the option handler uses.  Note
482 // that the values list must always have a 0 at the end of the list to indicate
483 // that the list has ended.
484 //
485 template<class DataType>
486 class ValuesClass {
487   // Use a vector instead of a map, because the lists should be short,
488   // the overhead is less, and most importantly, it keeps them in the order
489   // inserted so we can print our option out nicely.
490   SmallVector<std::pair<const char *, std::pair<int, const char *> >,4> Values;
491   void processValues(va_list Vals);
492 public:
493   ValuesClass(const char *EnumName, DataType Val, const char *Desc,
494               va_list ValueArgs) {
495     // Insert the first value, which is required.
496     Values.push_back(std::make_pair(EnumName, std::make_pair(Val, Desc)));
497
498     // Process the varargs portion of the values...
499     while (const char *enumName = va_arg(ValueArgs, const char *)) {
500       DataType EnumVal = static_cast<DataType>(va_arg(ValueArgs, int));
501       const char *EnumDesc = va_arg(ValueArgs, const char *);
502       Values.push_back(std::make_pair(enumName,      // Add value to value map
503                                       std::make_pair(EnumVal, EnumDesc)));
504     }
505   }
506
507   template<class Opt>
508   void apply(Opt &O) const {
509     for (size_t i = 0, e = Values.size(); i != e; ++i)
510       O.getParser().addLiteralOption(Values[i].first, Values[i].second.first,
511                                      Values[i].second.second);
512   }
513 };
514
515 template<class DataType>
516 ValuesClass<DataType> END_WITH_NULL values(const char *Arg, DataType Val,
517                                            const char *Desc, ...) {
518     va_list ValueArgs;
519     va_start(ValueArgs, Desc);
520     ValuesClass<DataType> Vals(Arg, Val, Desc, ValueArgs);
521     va_end(ValueArgs);
522     return Vals;
523 }
524
525 //===----------------------------------------------------------------------===//
526 // parser class - Parameterizable parser for different data types.  By default,
527 // known data types (string, int, bool) have specialized parsers, that do what
528 // you would expect.  The default parser, used for data types that are not
529 // built-in, uses a mapping table to map specific options to values, which is
530 // used, among other things, to handle enum types.
531
532 //--------------------------------------------------
533 // generic_parser_base - This class holds all the non-generic code that we do
534 // not need replicated for every instance of the generic parser.  This also
535 // allows us to put stuff into CommandLine.cpp
536 //
537 class generic_parser_base {
538 protected:
539   class GenericOptionInfo {
540   public:
541     GenericOptionInfo(const char *name, const char *helpStr) :
542       Name(name), HelpStr(helpStr) {}
543     const char *Name;
544     const char *HelpStr;
545   };
546 public:
547   virtual ~generic_parser_base() {}  // Base class should have virtual-dtor
548
549   // getNumOptions - Virtual function implemented by generic subclass to
550   // indicate how many entries are in Values.
551   //
552   virtual unsigned getNumOptions() const = 0;
553
554   // getOption - Return option name N.
555   virtual const char *getOption(unsigned N) const = 0;
556
557   // getDescription - Return description N
558   virtual const char *getDescription(unsigned N) const = 0;
559
560   // Return the width of the option tag for printing...
561   virtual size_t getOptionWidth(const Option &O) const;
562
563   virtual const GenericOptionValue &getOptionValue(unsigned N) const = 0;
564
565   // printOptionInfo - Print out information about this option.  The
566   // to-be-maintained width is specified.
567   //
568   virtual void printOptionInfo(const Option &O, size_t GlobalWidth) const;
569
570   void printGenericOptionDiff(const Option &O, const GenericOptionValue &V,
571                               const GenericOptionValue &Default,
572                               size_t GlobalWidth) const;
573
574   // printOptionDiff - print the value of an option and it's default.
575   //
576   // Template definition ensures that the option and default have the same
577   // DataType (via the same AnyOptionValue).
578   template<class AnyOptionValue>
579   void printOptionDiff(const Option &O, const AnyOptionValue &V,
580                        const AnyOptionValue &Default,
581                        size_t GlobalWidth) const {
582     printGenericOptionDiff(O, V, Default, GlobalWidth);
583   }
584
585   void initialize(Option &O) {
586     // All of the modifiers for the option have been processed by now, so the
587     // argstr field should be stable, copy it down now.
588     //
589     hasArgStr = O.hasArgStr();
590   }
591
592   void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
593     // If there has been no argstr specified, that means that we need to add an
594     // argument for every possible option.  This ensures that our options are
595     // vectored to us.
596     if (!hasArgStr)
597       for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
598         OptionNames.push_back(getOption(i));
599   }
600
601
602   enum ValueExpected getValueExpectedFlagDefault() const {
603     // If there is an ArgStr specified, then we are of the form:
604     //
605     //    -opt=O2   or   -opt O2  or  -optO2
606     //
607     // In which case, the value is required.  Otherwise if an arg str has not
608     // been specified, we are of the form:
609     //
610     //    -O2 or O2 or -la (where -l and -a are separate options)
611     //
612     // If this is the case, we cannot allow a value.
613     //
614     if (hasArgStr)
615       return ValueRequired;
616     else
617       return ValueDisallowed;
618   }
619
620   // findOption - Return the option number corresponding to the specified
621   // argument string.  If the option is not found, getNumOptions() is returned.
622   //
623   unsigned findOption(const char *Name);
624
625 protected:
626   bool hasArgStr;
627 };
628
629 // Default parser implementation - This implementation depends on having a
630 // mapping of recognized options to values of some sort.  In addition to this,
631 // each entry in the mapping also tracks a help message that is printed with the
632 // command line option for -help.  Because this is a simple mapping parser, the
633 // data type can be any unsupported type.
634 //
635 template <class DataType>
636 class parser : public generic_parser_base {
637 protected:
638   class OptionInfo : public GenericOptionInfo {
639   public:
640     OptionInfo(const char *name, DataType v, const char *helpStr) :
641       GenericOptionInfo(name, helpStr), V(v) {}
642     OptionValue<DataType> V;
643   };
644   SmallVector<OptionInfo, 8> Values;
645 public:
646   typedef DataType parser_data_type;
647
648   // Implement virtual functions needed by generic_parser_base
649   unsigned getNumOptions() const { return unsigned(Values.size()); }
650   const char *getOption(unsigned N) const { return Values[N].Name; }
651   const char *getDescription(unsigned N) const {
652     return Values[N].HelpStr;
653   }
654
655   // getOptionValue - Return the value of option name N.
656   virtual const GenericOptionValue &getOptionValue(unsigned N) const {
657     return Values[N].V;
658   }
659
660   // parse - Return true on error.
661   bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V) {
662     StringRef ArgVal;
663     if (hasArgStr)
664       ArgVal = Arg;
665     else
666       ArgVal = ArgName;
667
668     for (size_t i = 0, e = Values.size(); i != e; ++i)
669       if (Values[i].Name == ArgVal) {
670         V = Values[i].V.getValue();
671         return false;
672       }
673
674     return O.error("Cannot find option named '" + ArgVal + "'!");
675   }
676
677   /// addLiteralOption - Add an entry to the mapping table.
678   ///
679   template <class DT>
680   void addLiteralOption(const char *Name, const DT &V, const char *HelpStr) {
681     assert(findOption(Name) == Values.size() && "Option already exists!");
682     OptionInfo X(Name, static_cast<DataType>(V), HelpStr);
683     Values.push_back(X);
684     MarkOptionsChanged();
685   }
686
687   /// removeLiteralOption - Remove the specified option.
688   ///
689   void removeLiteralOption(const char *Name) {
690     unsigned N = findOption(Name);
691     assert(N != Values.size() && "Option not found!");
692     Values.erase(Values.begin()+N);
693   }
694 };
695
696 //--------------------------------------------------
697 // basic_parser - Super class of parsers to provide boilerplate code
698 //
699 class basic_parser_impl {  // non-template implementation of basic_parser<t>
700 public:
701   virtual ~basic_parser_impl() {}
702
703   enum ValueExpected getValueExpectedFlagDefault() const {
704     return ValueRequired;
705   }
706
707   void getExtraOptionNames(SmallVectorImpl<const char*> &) {}
708
709   void initialize(Option &) {}
710
711   // Return the width of the option tag for printing...
712   size_t getOptionWidth(const Option &O) const;
713
714   // printOptionInfo - Print out information about this option.  The
715   // to-be-maintained width is specified.
716   //
717   void printOptionInfo(const Option &O, size_t GlobalWidth) const;
718
719   // printOptionNoValue - Print a placeholder for options that don't yet support
720   // printOptionDiff().
721   void printOptionNoValue(const Option &O, size_t GlobalWidth) const;
722
723   // getValueName - Overload in subclass to provide a better default value.
724   virtual const char *getValueName() const { return "value"; }
725
726   // An out-of-line virtual method to provide a 'home' for this class.
727   virtual void anchor();
728
729 protected:
730   // A helper for basic_parser::printOptionDiff.
731   void printOptionName(const Option &O, size_t GlobalWidth) const;
732 };
733
734 // basic_parser - The real basic parser is just a template wrapper that provides
735 // a typedef for the provided data type.
736 //
737 template<class DataType>
738 class basic_parser : public basic_parser_impl {
739 public:
740   typedef DataType parser_data_type;
741   typedef OptionValue<DataType> OptVal;
742 };
743
744 //--------------------------------------------------
745 // parser<bool>
746 //
747 template<>
748 class parser<bool> : public basic_parser<bool> {
749   const char *ArgStr;
750 public:
751
752   // parse - Return true on error.
753   bool parse(Option &O, StringRef ArgName, StringRef Arg, bool &Val);
754
755   template <class Opt>
756   void initialize(Opt &O) {
757     ArgStr = O.ArgStr;
758   }
759
760   enum ValueExpected getValueExpectedFlagDefault() const {
761     return ValueOptional;
762   }
763
764   // getValueName - Do not print =<value> at all.
765   virtual const char *getValueName() const { return 0; }
766
767   void printOptionDiff(const Option &O, bool V, OptVal Default,
768                        size_t GlobalWidth) const;
769
770   // An out-of-line virtual method to provide a 'home' for this class.
771   virtual void anchor();
772 };
773
774 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<bool>);
775
776 //--------------------------------------------------
777 // parser<boolOrDefault>
778 template<>
779 class parser<boolOrDefault> : public basic_parser<boolOrDefault> {
780 public:
781   // parse - Return true on error.
782   bool parse(Option &O, StringRef ArgName, StringRef Arg, boolOrDefault &Val);
783
784   enum ValueExpected getValueExpectedFlagDefault() const {
785     return ValueOptional;
786   }
787
788   // getValueName - Do not print =<value> at all.
789   virtual const char *getValueName() const { return 0; }
790
791   void printOptionDiff(const Option &O, boolOrDefault V, OptVal Default,
792                        size_t GlobalWidth) const;
793
794   // An out-of-line virtual method to provide a 'home' for this class.
795   virtual void anchor();
796 };
797
798 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
799
800 //--------------------------------------------------
801 // parser<int>
802 //
803 template<>
804 class parser<int> : public basic_parser<int> {
805 public:
806   // parse - Return true on error.
807   bool parse(Option &O, StringRef ArgName, StringRef Arg, int &Val);
808
809   // getValueName - Overload in subclass to provide a better default value.
810   virtual const char *getValueName() const { return "int"; }
811
812   void printOptionDiff(const Option &O, int V, OptVal Default,
813                        size_t GlobalWidth) const;
814
815   // An out-of-line virtual method to provide a 'home' for this class.
816   virtual void anchor();
817 };
818
819 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<int>);
820
821
822 //--------------------------------------------------
823 // parser<unsigned>
824 //
825 template<>
826 class parser<unsigned> : public basic_parser<unsigned> {
827 public:
828   // parse - Return true on error.
829   bool parse(Option &O, StringRef ArgName, StringRef Arg, unsigned &Val);
830
831   // getValueName - Overload in subclass to provide a better default value.
832   virtual const char *getValueName() const { return "uint"; }
833
834   void printOptionDiff(const Option &O, unsigned V, OptVal Default,
835                        size_t GlobalWidth) const;
836
837   // An out-of-line virtual method to provide a 'home' for this class.
838   virtual void anchor();
839 };
840
841 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
842
843 //--------------------------------------------------
844 // parser<unsigned long long>
845 //
846 template<>
847 class parser<unsigned long long> : public basic_parser<unsigned long long> {
848 public:
849   // parse - Return true on error.
850   bool parse(Option &O, StringRef ArgName, StringRef Arg,
851              unsigned long long &Val);
852
853   // getValueName - Overload in subclass to provide a better default value.
854   virtual const char *getValueName() const { return "uint"; }
855
856   void printOptionDiff(const Option &O, unsigned long long V, OptVal Default,
857                        size_t GlobalWidth) const;
858
859   // An out-of-line virtual method to provide a 'home' for this class.
860   virtual void anchor();
861 };
862
863 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
864
865 //--------------------------------------------------
866 // parser<double>
867 //
868 template<>
869 class parser<double> : public basic_parser<double> {
870 public:
871   // parse - Return true on error.
872   bool parse(Option &O, StringRef ArgName, StringRef Arg, double &Val);
873
874   // getValueName - Overload in subclass to provide a better default value.
875   virtual const char *getValueName() const { return "number"; }
876
877   void printOptionDiff(const Option &O, double V, OptVal Default,
878                        size_t GlobalWidth) const;
879
880   // An out-of-line virtual method to provide a 'home' for this class.
881   virtual void anchor();
882 };
883
884 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<double>);
885
886 //--------------------------------------------------
887 // parser<float>
888 //
889 template<>
890 class parser<float> : public basic_parser<float> {
891 public:
892   // parse - Return true on error.
893   bool parse(Option &O, StringRef ArgName, StringRef Arg, float &Val);
894
895   // getValueName - Overload in subclass to provide a better default value.
896   virtual const char *getValueName() const { return "number"; }
897
898   void printOptionDiff(const Option &O, float V, OptVal Default,
899                        size_t GlobalWidth) const;
900
901   // An out-of-line virtual method to provide a 'home' for this class.
902   virtual void anchor();
903 };
904
905 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<float>);
906
907 //--------------------------------------------------
908 // parser<std::string>
909 //
910 template<>
911 class parser<std::string> : public basic_parser<std::string> {
912 public:
913   // parse - Return true on error.
914   bool parse(Option &, StringRef, StringRef Arg, std::string &Value) {
915     Value = Arg.str();
916     return false;
917   }
918
919   // getValueName - Overload in subclass to provide a better default value.
920   virtual const char *getValueName() const { return "string"; }
921
922   void printOptionDiff(const Option &O, StringRef V, OptVal Default,
923                        size_t GlobalWidth) const;
924
925   // An out-of-line virtual method to provide a 'home' for this class.
926   virtual void anchor();
927 };
928
929 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
930
931 //--------------------------------------------------
932 // parser<char>
933 //
934 template<>
935 class parser<char> : public basic_parser<char> {
936 public:
937   // parse - Return true on error.
938   bool parse(Option &, StringRef, StringRef Arg, char &Value) {
939     Value = Arg[0];
940     return false;
941   }
942
943   // getValueName - Overload in subclass to provide a better default value.
944   virtual const char *getValueName() const { return "char"; }
945
946   void printOptionDiff(const Option &O, char V, OptVal Default,
947                        size_t GlobalWidth) const;
948
949   // An out-of-line virtual method to provide a 'home' for this class.
950   virtual void anchor();
951 };
952
953 EXTERN_TEMPLATE_INSTANTIATION(class basic_parser<char>);
954
955 //--------------------------------------------------
956 // PrintOptionDiff
957 //
958 // This collection of wrappers is the intermediary between class opt and class
959 // parser to handle all the template nastiness.
960
961 // This overloaded function is selected by the generic parser.
962 template<class ParserClass, class DT>
963 void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V,
964                      const OptionValue<DT> &Default, size_t GlobalWidth) {
965   OptionValue<DT> OV = V;
966   P.printOptionDiff(O, OV, Default, GlobalWidth);
967 }
968
969 // This is instantiated for basic parsers when the parsed value has a different
970 // type than the option value. e.g. HelpPrinter.
971 template<class ParserDT, class ValDT>
972 struct OptionDiffPrinter {
973   void print(const Option &O, const parser<ParserDT> P, const ValDT &/*V*/,
974              const OptionValue<ValDT> &/*Default*/, size_t GlobalWidth) {
975     P.printOptionNoValue(O, GlobalWidth);
976   }
977 };
978
979 // This is instantiated for basic parsers when the parsed value has the same
980 // type as the option value.
981 template<class DT>
982 struct OptionDiffPrinter<DT, DT> {
983   void print(const Option &O, const parser<DT> P, const DT &V,
984              const OptionValue<DT> &Default, size_t GlobalWidth) {
985     P.printOptionDiff(O, V, Default, GlobalWidth);
986   }
987 };
988
989 // This overloaded function is selected by the basic parser, which may parse a
990 // different type than the option type.
991 template<class ParserClass, class ValDT>
992 void printOptionDiff(
993   const Option &O,
994   const basic_parser<typename ParserClass::parser_data_type> &P,
995   const ValDT &V, const OptionValue<ValDT> &Default,
996   size_t GlobalWidth) {
997
998   OptionDiffPrinter<typename ParserClass::parser_data_type, ValDT> printer;
999   printer.print(O, static_cast<const ParserClass&>(P), V, Default,
1000                 GlobalWidth);
1001 }
1002
1003 //===----------------------------------------------------------------------===//
1004 // applicator class - This class is used because we must use partial
1005 // specialization to handle literal string arguments specially (const char* does
1006 // not correctly respond to the apply method).  Because the syntax to use this
1007 // is a pain, we have the 'apply' method below to handle the nastiness...
1008 //
1009 template<class Mod> struct applicator {
1010   template<class Opt>
1011   static void opt(const Mod &M, Opt &O) { M.apply(O); }
1012 };
1013
1014 // Handle const char* as a special case...
1015 template<unsigned n> struct applicator<char[n]> {
1016   template<class Opt>
1017   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1018 };
1019 template<unsigned n> struct applicator<const char[n]> {
1020   template<class Opt>
1021   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1022 };
1023 template<> struct applicator<const char*> {
1024   template<class Opt>
1025   static void opt(const char *Str, Opt &O) { O.setArgStr(Str); }
1026 };
1027
1028 template<> struct applicator<NumOccurrencesFlag> {
1029   static void opt(NumOccurrencesFlag N, Option &O) {
1030     O.setNumOccurrencesFlag(N);
1031   }
1032 };
1033 template<> struct applicator<ValueExpected> {
1034   static void opt(ValueExpected VE, Option &O) { O.setValueExpectedFlag(VE); }
1035 };
1036 template<> struct applicator<OptionHidden> {
1037   static void opt(OptionHidden OH, Option &O) { O.setHiddenFlag(OH); }
1038 };
1039 template<> struct applicator<FormattingFlags> {
1040   static void opt(FormattingFlags FF, Option &O) { O.setFormattingFlag(FF); }
1041 };
1042 template<> struct applicator<MiscFlags> {
1043   static void opt(MiscFlags MF, Option &O) { O.setMiscFlag(MF); }
1044 };
1045
1046 // apply method - Apply a modifier to an option in a type safe way.
1047 template<class Mod, class Opt>
1048 void apply(const Mod &M, Opt *O) {
1049   applicator<Mod>::opt(M, *O);
1050 }
1051
1052 //===----------------------------------------------------------------------===//
1053 // opt_storage class
1054
1055 // Default storage class definition: external storage.  This implementation
1056 // assumes the user will specify a variable to store the data into with the
1057 // cl::location(x) modifier.
1058 //
1059 template<class DataType, bool ExternalStorage, bool isClass>
1060 class opt_storage {
1061   DataType *Location;   // Where to store the object...
1062   OptionValue<DataType> Default;
1063
1064   void check_location() const {
1065     assert(Location != 0 && "cl::location(...) not specified for a command "
1066            "line option with external storage, "
1067            "or cl::init specified before cl::location()!!");
1068   }
1069 public:
1070   opt_storage() : Location(0) {}
1071
1072   bool setLocation(Option &O, DataType &L) {
1073     if (Location)
1074       return O.error("cl::location(x) specified more than once!");
1075     Location = &L;
1076     Default = L;
1077     return false;
1078   }
1079
1080   template<class T>
1081   void setValue(const T &V, bool initial = false) {
1082     check_location();
1083     *Location = V;
1084     if (initial)
1085       Default = V;
1086   }
1087
1088   DataType &getValue() { check_location(); return *Location; }
1089   const DataType &getValue() const { check_location(); return *Location; }
1090
1091   operator DataType() const { return this->getValue(); }
1092
1093   const OptionValue<DataType> &getDefault() const { return Default; }
1094 };
1095
1096 // Define how to hold a class type object, such as a string.  Since we can
1097 // inherit from a class, we do so.  This makes us exactly compatible with the
1098 // object in all cases that it is used.
1099 //
1100 template<class DataType>
1101 class opt_storage<DataType,false,true> : public DataType {
1102 public:
1103   OptionValue<DataType> Default;
1104
1105   template<class T>
1106   void setValue(const T &V, bool initial = false) {
1107     DataType::operator=(V);
1108     if (initial)
1109       Default = V;
1110   }
1111
1112   DataType &getValue() { return *this; }
1113   const DataType &getValue() const { return *this; }
1114
1115   const OptionValue<DataType> &getDefault() const { return Default; }
1116 };
1117
1118 // Define a partial specialization to handle things we cannot inherit from.  In
1119 // this case, we store an instance through containment, and overload operators
1120 // to get at the value.
1121 //
1122 template<class DataType>
1123 class opt_storage<DataType, false, false> {
1124 public:
1125   DataType Value;
1126   OptionValue<DataType> Default;
1127
1128   // Make sure we initialize the value with the default constructor for the
1129   // type.
1130   opt_storage() : Value(DataType()), Default(DataType()) {}
1131
1132   template<class T>
1133   void setValue(const T &V, bool initial = false) {
1134     Value = V;
1135     if (initial)
1136       Default = V;
1137   }
1138   DataType &getValue() { return Value; }
1139   DataType getValue() const { return Value; }
1140
1141   const OptionValue<DataType> &getDefault() const { return Default; }
1142
1143   operator DataType() const { return getValue(); }
1144
1145   // If the datatype is a pointer, support -> on it.
1146   DataType operator->() const { return Value; }
1147 };
1148
1149
1150 //===----------------------------------------------------------------------===//
1151 // opt - A scalar command line option.
1152 //
1153 template <class DataType, bool ExternalStorage = false,
1154           class ParserClass = parser<DataType> >
1155 class opt : public Option,
1156             public opt_storage<DataType, ExternalStorage,
1157                                is_class<DataType>::value> {
1158   ParserClass Parser;
1159
1160   virtual bool handleOccurrence(unsigned pos, StringRef ArgName,
1161                                 StringRef Arg) {
1162     typename ParserClass::parser_data_type Val =
1163        typename ParserClass::parser_data_type();
1164     if (Parser.parse(*this, ArgName, Arg, Val))
1165       return true;                            // Parse error!
1166     this->setValue(Val);
1167     this->setPosition(pos);
1168     return false;
1169   }
1170
1171   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1172     return Parser.getValueExpectedFlagDefault();
1173   }
1174   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1175     return Parser.getExtraOptionNames(OptionNames);
1176   }
1177
1178   // Forward printing stuff to the parser...
1179   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1180   virtual void printOptionInfo(size_t GlobalWidth) const {
1181     Parser.printOptionInfo(*this, GlobalWidth);
1182   }
1183
1184   virtual void printOptionValue(size_t GlobalWidth, bool Force) const {
1185     if (Force || this->getDefault().compare(this->getValue())) {
1186       cl::printOptionDiff<ParserClass>(
1187         *this, Parser, this->getValue(), this->getDefault(), GlobalWidth);
1188     }
1189   }
1190
1191   void done() {
1192     addArgument();
1193     Parser.initialize(*this);
1194   }
1195 public:
1196   // setInitialValue - Used by the cl::init modifier...
1197   void setInitialValue(const DataType &V) { this->setValue(V, true); }
1198
1199   ParserClass &getParser() { return Parser; }
1200
1201   template<class T>
1202   DataType &operator=(const T &Val) {
1203     this->setValue(Val);
1204     return this->getValue();
1205   }
1206
1207   // One option...
1208   template<class M0t>
1209   explicit opt(const M0t &M0) : Option(Optional, NotHidden) {
1210     apply(M0, this);
1211     done();
1212   }
1213
1214   // Two options...
1215   template<class M0t, class M1t>
1216   opt(const M0t &M0, const M1t &M1) : Option(Optional, NotHidden) {
1217     apply(M0, this); apply(M1, this);
1218     done();
1219   }
1220
1221   // Three options...
1222   template<class M0t, class M1t, class M2t>
1223   opt(const M0t &M0, const M1t &M1,
1224       const M2t &M2) : Option(Optional, NotHidden) {
1225     apply(M0, this); apply(M1, this); apply(M2, this);
1226     done();
1227   }
1228   // Four options...
1229   template<class M0t, class M1t, class M2t, class M3t>
1230   opt(const M0t &M0, const M1t &M1, const M2t &M2,
1231       const M3t &M3) : Option(Optional, NotHidden) {
1232     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1233     done();
1234   }
1235   // Five options...
1236   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1237   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1238       const M4t &M4) : Option(Optional, NotHidden) {
1239     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1240     apply(M4, this);
1241     done();
1242   }
1243   // Six options...
1244   template<class M0t, class M1t, class M2t, class M3t,
1245            class M4t, class M5t>
1246   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1247       const M4t &M4, const M5t &M5) : Option(Optional, NotHidden) {
1248     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1249     apply(M4, this); apply(M5, this);
1250     done();
1251   }
1252   // Seven options...
1253   template<class M0t, class M1t, class M2t, class M3t,
1254            class M4t, class M5t, class M6t>
1255   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1256       const M4t &M4, const M5t &M5,
1257       const M6t &M6) : Option(Optional, NotHidden) {
1258     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1259     apply(M4, this); apply(M5, this); apply(M6, this);
1260     done();
1261   }
1262   // Eight options...
1263   template<class M0t, class M1t, class M2t, class M3t,
1264            class M4t, class M5t, class M6t, class M7t>
1265   opt(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1266       const M4t &M4, const M5t &M5, const M6t &M6,
1267       const M7t &M7) : Option(Optional, NotHidden) {
1268     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1269     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1270     done();
1271   }
1272 };
1273
1274 EXTERN_TEMPLATE_INSTANTIATION(class opt<unsigned>);
1275 EXTERN_TEMPLATE_INSTANTIATION(class opt<int>);
1276 EXTERN_TEMPLATE_INSTANTIATION(class opt<std::string>);
1277 EXTERN_TEMPLATE_INSTANTIATION(class opt<char>);
1278 EXTERN_TEMPLATE_INSTANTIATION(class opt<bool>);
1279
1280 //===----------------------------------------------------------------------===//
1281 // list_storage class
1282
1283 // Default storage class definition: external storage.  This implementation
1284 // assumes the user will specify a variable to store the data into with the
1285 // cl::location(x) modifier.
1286 //
1287 template<class DataType, class StorageClass>
1288 class list_storage {
1289   StorageClass *Location;   // Where to store the object...
1290
1291 public:
1292   list_storage() : Location(0) {}
1293
1294   bool setLocation(Option &O, StorageClass &L) {
1295     if (Location)
1296       return O.error("cl::location(x) specified more than once!");
1297     Location = &L;
1298     return false;
1299   }
1300
1301   template<class T>
1302   void addValue(const T &V) {
1303     assert(Location != 0 && "cl::location(...) not specified for a command "
1304            "line option with external storage!");
1305     Location->push_back(V);
1306   }
1307 };
1308
1309
1310 // Define how to hold a class type object, such as a string.  Since we can
1311 // inherit from a class, we do so.  This makes us exactly compatible with the
1312 // object in all cases that it is used.
1313 //
1314 template<class DataType>
1315 class list_storage<DataType, bool> : public std::vector<DataType> {
1316 public:
1317   template<class T>
1318   void addValue(const T &V) { std::vector<DataType>::push_back(V); }
1319 };
1320
1321
1322 //===----------------------------------------------------------------------===//
1323 // list - A list of command line options.
1324 //
1325 template <class DataType, class Storage = bool,
1326           class ParserClass = parser<DataType> >
1327 class list : public Option, public list_storage<DataType, Storage> {
1328   std::vector<unsigned> Positions;
1329   ParserClass Parser;
1330
1331   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1332     return Parser.getValueExpectedFlagDefault();
1333   }
1334   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1335     return Parser.getExtraOptionNames(OptionNames);
1336   }
1337
1338   virtual bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg){
1339     typename ParserClass::parser_data_type Val =
1340       typename ParserClass::parser_data_type();
1341     if (Parser.parse(*this, ArgName, Arg, Val))
1342       return true;  // Parse Error!
1343     list_storage<DataType, Storage>::addValue(Val);
1344     setPosition(pos);
1345     Positions.push_back(pos);
1346     return false;
1347   }
1348
1349   // Forward printing stuff to the parser...
1350   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1351   virtual void printOptionInfo(size_t GlobalWidth) const {
1352     Parser.printOptionInfo(*this, GlobalWidth);
1353   }
1354
1355   // Unimplemented: list options don't currently store their default value.
1356   virtual void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const {}
1357
1358   void done() {
1359     addArgument();
1360     Parser.initialize(*this);
1361   }
1362 public:
1363   ParserClass &getParser() { return Parser; }
1364
1365   unsigned getPosition(unsigned optnum) const {
1366     assert(optnum < this->size() && "Invalid option index");
1367     return Positions[optnum];
1368   }
1369
1370   void setNumAdditionalVals(unsigned n) {
1371     Option::setNumAdditionalVals(n);
1372   }
1373
1374   // One option...
1375   template<class M0t>
1376   explicit list(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1377     apply(M0, this);
1378     done();
1379   }
1380   // Two options...
1381   template<class M0t, class M1t>
1382   list(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1383     apply(M0, this); apply(M1, this);
1384     done();
1385   }
1386   // Three options...
1387   template<class M0t, class M1t, class M2t>
1388   list(const M0t &M0, const M1t &M1, const M2t &M2)
1389     : Option(ZeroOrMore, NotHidden) {
1390     apply(M0, this); apply(M1, this); apply(M2, this);
1391     done();
1392   }
1393   // Four options...
1394   template<class M0t, class M1t, class M2t, class M3t>
1395   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1396     : Option(ZeroOrMore, NotHidden) {
1397     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1398     done();
1399   }
1400   // Five options...
1401   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1402   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1403        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1404     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1405     apply(M4, this);
1406     done();
1407   }
1408   // Six options...
1409   template<class M0t, class M1t, class M2t, class M3t,
1410            class M4t, class M5t>
1411   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1412        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1413     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1414     apply(M4, this); apply(M5, this);
1415     done();
1416   }
1417   // Seven options...
1418   template<class M0t, class M1t, class M2t, class M3t,
1419            class M4t, class M5t, class M6t>
1420   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1421        const M4t &M4, const M5t &M5, const M6t &M6)
1422     : Option(ZeroOrMore, NotHidden) {
1423     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1424     apply(M4, this); apply(M5, this); apply(M6, this);
1425     done();
1426   }
1427   // Eight options...
1428   template<class M0t, class M1t, class M2t, class M3t,
1429            class M4t, class M5t, class M6t, class M7t>
1430   list(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1431        const M4t &M4, const M5t &M5, const M6t &M6,
1432        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1433     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1434     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1435     done();
1436   }
1437 };
1438
1439 // multi_val - Modifier to set the number of additional values.
1440 struct multi_val {
1441   unsigned AdditionalVals;
1442   explicit multi_val(unsigned N) : AdditionalVals(N) {}
1443
1444   template <typename D, typename S, typename P>
1445   void apply(list<D, S, P> &L) const { L.setNumAdditionalVals(AdditionalVals); }
1446 };
1447
1448
1449 //===----------------------------------------------------------------------===//
1450 // bits_storage class
1451
1452 // Default storage class definition: external storage.  This implementation
1453 // assumes the user will specify a variable to store the data into with the
1454 // cl::location(x) modifier.
1455 //
1456 template<class DataType, class StorageClass>
1457 class bits_storage {
1458   unsigned *Location;   // Where to store the bits...
1459
1460   template<class T>
1461   static unsigned Bit(const T &V) {
1462     unsigned BitPos = reinterpret_cast<unsigned>(V);
1463     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1464           "enum exceeds width of bit vector!");
1465     return 1 << BitPos;
1466   }
1467
1468 public:
1469   bits_storage() : Location(0) {}
1470
1471   bool setLocation(Option &O, unsigned &L) {
1472     if (Location)
1473       return O.error("cl::location(x) specified more than once!");
1474     Location = &L;
1475     return false;
1476   }
1477
1478   template<class T>
1479   void addValue(const T &V) {
1480     assert(Location != 0 && "cl::location(...) not specified for a command "
1481            "line option with external storage!");
1482     *Location |= Bit(V);
1483   }
1484
1485   unsigned getBits() { return *Location; }
1486
1487   template<class T>
1488   bool isSet(const T &V) {
1489     return (*Location & Bit(V)) != 0;
1490   }
1491 };
1492
1493
1494 // Define how to hold bits.  Since we can inherit from a class, we do so.
1495 // This makes us exactly compatible with the bits in all cases that it is used.
1496 //
1497 template<class DataType>
1498 class bits_storage<DataType, bool> {
1499   unsigned Bits;   // Where to store the bits...
1500
1501   template<class T>
1502   static unsigned Bit(const T &V) {
1503     unsigned BitPos = (unsigned)V;
1504     assert(BitPos < sizeof(unsigned) * CHAR_BIT &&
1505           "enum exceeds width of bit vector!");
1506     return 1 << BitPos;
1507   }
1508
1509 public:
1510   template<class T>
1511   void addValue(const T &V) {
1512     Bits |=  Bit(V);
1513   }
1514
1515   unsigned getBits() { return Bits; }
1516
1517   template<class T>
1518   bool isSet(const T &V) {
1519     return (Bits & Bit(V)) != 0;
1520   }
1521 };
1522
1523
1524 //===----------------------------------------------------------------------===//
1525 // bits - A bit vector of command options.
1526 //
1527 template <class DataType, class Storage = bool,
1528           class ParserClass = parser<DataType> >
1529 class bits : public Option, public bits_storage<DataType, Storage> {
1530   std::vector<unsigned> Positions;
1531   ParserClass Parser;
1532
1533   virtual enum ValueExpected getValueExpectedFlagDefault() const {
1534     return Parser.getValueExpectedFlagDefault();
1535   }
1536   virtual void getExtraOptionNames(SmallVectorImpl<const char*> &OptionNames) {
1537     return Parser.getExtraOptionNames(OptionNames);
1538   }
1539
1540   virtual bool handleOccurrence(unsigned pos, StringRef ArgName, StringRef Arg){
1541     typename ParserClass::parser_data_type Val =
1542       typename ParserClass::parser_data_type();
1543     if (Parser.parse(*this, ArgName, Arg, Val))
1544       return true;  // Parse Error!
1545     this->addValue(Val);
1546     setPosition(pos);
1547     Positions.push_back(pos);
1548     return false;
1549   }
1550
1551   // Forward printing stuff to the parser...
1552   virtual size_t getOptionWidth() const {return Parser.getOptionWidth(*this);}
1553   virtual void printOptionInfo(size_t GlobalWidth) const {
1554     Parser.printOptionInfo(*this, GlobalWidth);
1555   }
1556
1557   // Unimplemented: bits options don't currently store their default values.
1558   virtual void printOptionValue(size_t /*GlobalWidth*/, bool /*Force*/) const {}
1559
1560   void done() {
1561     addArgument();
1562     Parser.initialize(*this);
1563   }
1564 public:
1565   ParserClass &getParser() { return Parser; }
1566
1567   unsigned getPosition(unsigned optnum) const {
1568     assert(optnum < this->size() && "Invalid option index");
1569     return Positions[optnum];
1570   }
1571
1572   // One option...
1573   template<class M0t>
1574   explicit bits(const M0t &M0) : Option(ZeroOrMore, NotHidden) {
1575     apply(M0, this);
1576     done();
1577   }
1578   // Two options...
1579   template<class M0t, class M1t>
1580   bits(const M0t &M0, const M1t &M1) : Option(ZeroOrMore, NotHidden) {
1581     apply(M0, this); apply(M1, this);
1582     done();
1583   }
1584   // Three options...
1585   template<class M0t, class M1t, class M2t>
1586   bits(const M0t &M0, const M1t &M1, const M2t &M2)
1587     : Option(ZeroOrMore, NotHidden) {
1588     apply(M0, this); apply(M1, this); apply(M2, this);
1589     done();
1590   }
1591   // Four options...
1592   template<class M0t, class M1t, class M2t, class M3t>
1593   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1594     : Option(ZeroOrMore, NotHidden) {
1595     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1596     done();
1597   }
1598   // Five options...
1599   template<class M0t, class M1t, class M2t, class M3t, class M4t>
1600   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1601        const M4t &M4) : Option(ZeroOrMore, NotHidden) {
1602     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1603     apply(M4, this);
1604     done();
1605   }
1606   // Six options...
1607   template<class M0t, class M1t, class M2t, class M3t,
1608            class M4t, class M5t>
1609   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1610        const M4t &M4, const M5t &M5) : Option(ZeroOrMore, NotHidden) {
1611     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1612     apply(M4, this); apply(M5, this);
1613     done();
1614   }
1615   // Seven options...
1616   template<class M0t, class M1t, class M2t, class M3t,
1617            class M4t, class M5t, class M6t>
1618   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1619        const M4t &M4, const M5t &M5, const M6t &M6)
1620     : Option(ZeroOrMore, NotHidden) {
1621     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1622     apply(M4, this); apply(M5, this); apply(M6, this);
1623     done();
1624   }
1625   // Eight options...
1626   template<class M0t, class M1t, class M2t, class M3t,
1627            class M4t, class M5t, class M6t, class M7t>
1628   bits(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3,
1629        const M4t &M4, const M5t &M5, const M6t &M6,
1630        const M7t &M7) : Option(ZeroOrMore, NotHidden) {
1631     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1632     apply(M4, this); apply(M5, this); apply(M6, this); apply(M7, this);
1633     done();
1634   }
1635 };
1636
1637 //===----------------------------------------------------------------------===//
1638 // Aliased command line option (alias this name to a preexisting name)
1639 //
1640
1641 class alias : public Option {
1642   Option *AliasFor;
1643   virtual bool handleOccurrence(unsigned pos, StringRef /*ArgName*/,
1644                                 StringRef Arg) override {
1645     return AliasFor->handleOccurrence(pos, AliasFor->ArgStr, Arg);
1646   }
1647   // Handle printing stuff...
1648   virtual size_t getOptionWidth() const override;
1649   virtual void printOptionInfo(size_t GlobalWidth) const override;
1650
1651   // Aliases do not need to print their values.
1652   virtual void printOptionValue(size_t /*GlobalWidth*/,
1653                                 bool /*Force*/) const override {}
1654
1655   virtual ValueExpected getValueExpectedFlagDefault() const override {
1656     return AliasFor->getValueExpectedFlag();
1657   }
1658
1659   void done() {
1660     if (!hasArgStr())
1661       error("cl::alias must have argument name specified!");
1662     if (AliasFor == 0)
1663       error("cl::alias must have an cl::aliasopt(option) specified!");
1664       addArgument();
1665   }
1666 public:
1667   void setAliasFor(Option &O) {
1668     if (AliasFor)
1669       error("cl::alias must only have one cl::aliasopt(...) specified!");
1670     AliasFor = &O;
1671   }
1672
1673   // One option...
1674   template<class M0t>
1675   explicit alias(const M0t &M0) : Option(Optional, Hidden), AliasFor(0) {
1676     apply(M0, this);
1677     done();
1678   }
1679   // Two options...
1680   template<class M0t, class M1t>
1681   alias(const M0t &M0, const M1t &M1) : Option(Optional, Hidden), AliasFor(0) {
1682     apply(M0, this); apply(M1, this);
1683     done();
1684   }
1685   // Three options...
1686   template<class M0t, class M1t, class M2t>
1687   alias(const M0t &M0, const M1t &M1, const M2t &M2)
1688     : Option(Optional, Hidden), AliasFor(0) {
1689     apply(M0, this); apply(M1, this); apply(M2, this);
1690     done();
1691   }
1692   // Four options...
1693   template<class M0t, class M1t, class M2t, class M3t>
1694   alias(const M0t &M0, const M1t &M1, const M2t &M2, const M3t &M3)
1695     : Option(Optional, Hidden), AliasFor(0) {
1696     apply(M0, this); apply(M1, this); apply(M2, this); apply(M3, this);
1697     done();
1698   }
1699 };
1700
1701 // aliasfor - Modifier to set the option an alias aliases.
1702 struct aliasopt {
1703   Option &Opt;
1704   explicit aliasopt(Option &O) : Opt(O) {}
1705   void apply(alias &A) const { A.setAliasFor(Opt); }
1706 };
1707
1708 // extrahelp - provide additional help at the end of the normal help
1709 // output. All occurrences of cl::extrahelp will be accumulated and
1710 // printed to stderr at the end of the regular help, just before
1711 // exit is called.
1712 struct extrahelp {
1713   const char * morehelp;
1714   explicit extrahelp(const char* help);
1715 };
1716
1717 void PrintVersionMessage();
1718
1719 /// This function just prints the help message, exactly the same way as if the
1720 /// -help or -help-hidden option had been given on the command line.
1721 ///
1722 /// NOTE: THIS FUNCTION TERMINATES THE PROGRAM!
1723 ///
1724 /// \param Hidden if true will print hidden options
1725 /// \param Categorized if true print options in categories
1726 void PrintHelpMessage(bool Hidden=false, bool Categorized=false);
1727
1728
1729 //===----------------------------------------------------------------------===//
1730 // Public interface for accessing registered options.
1731 //
1732
1733 /// \brief Use this to get a StringMap to all registered named options
1734 /// (e.g. -help). Note \p Map Should be an empty StringMap.
1735 ///
1736 /// \param [out] Map will be filled with mappings where the key is the
1737 /// Option argument string (e.g. "help") and value is the corresponding
1738 /// Option*.
1739 ///
1740 /// Access to unnamed arguments (i.e. positional) are not provided because
1741 /// it is expected that the client already has access to these.
1742 ///
1743 /// Typical usage:
1744 /// \code
1745 /// main(int argc,char* argv[]) {
1746 /// StringMap<llvm::cl::Option*> opts;
1747 /// llvm::cl::getRegisteredOptions(opts);
1748 /// assert(opts.count("help") == 1)
1749 /// opts["help"]->setDescription("Show alphabetical help information")
1750 /// // More code
1751 /// llvm::cl::ParseCommandLineOptions(argc,argv);
1752 /// //More code
1753 /// }
1754 /// \endcode
1755 ///
1756 /// This interface is useful for modifying options in libraries that are out of
1757 /// the control of the client. The options should be modified before calling
1758 /// llvm::cl::ParseCommandLineOptions().
1759 void getRegisteredOptions(StringMap<Option*> &Map);
1760
1761 //===----------------------------------------------------------------------===//
1762 // Standalone command line processing utilities.
1763 //
1764
1765 /// \brief Saves strings in the inheritor's stable storage and returns a stable
1766 /// raw character pointer.
1767 class StringSaver {
1768   virtual void anchor();
1769 public:
1770   virtual const char *SaveString(const char *Str) = 0;
1771   virtual ~StringSaver() {};  // Pacify -Wnon-virtual-dtor.
1772 };
1773
1774 /// \brief Tokenizes a command line that can contain escapes and quotes.
1775 //
1776 /// The quoting rules match those used by GCC and other tools that use
1777 /// libiberty's buildargv() or expandargv() utilities, and do not match bash.
1778 /// They differ from buildargv() on treatment of backslashes that do not escape
1779 /// a special character to make it possible to accept most Windows file paths.
1780 ///
1781 /// \param [in] Source The string to be split on whitespace with quotes.
1782 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1783 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1784 void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver,
1785                             SmallVectorImpl<const char *> &NewArgv);
1786
1787 /// \brief Tokenizes a Windows command line which may contain quotes and escaped
1788 /// quotes.
1789 ///
1790 /// See MSDN docs for CommandLineToArgvW for information on the quoting rules.
1791 /// http://msdn.microsoft.com/en-us/library/windows/desktop/17w5ykft(v=vs.85).aspx
1792 ///
1793 /// \param [in] Source The string to be split on whitespace with quotes.
1794 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1795 /// \param [out] NewArgv All parsed strings are appended to NewArgv.
1796 void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver,
1797                                 SmallVectorImpl<const char *> &NewArgv);
1798
1799 /// \brief String tokenization function type.  Should be compatible with either
1800 /// Windows or Unix command line tokenizers.
1801 typedef void (*TokenizerCallback)(StringRef Source, StringSaver &Saver,
1802                                   SmallVectorImpl<const char *> &NewArgv);
1803
1804 /// \brief Expand response files on a command line recursively using the given
1805 /// StringSaver and tokenization strategy.  Argv should contain the command line
1806 /// before expansion and will be modified in place.
1807 ///
1808 /// \param [in] Saver Delegates back to the caller for saving parsed strings.
1809 /// \param [in] Tokenizer Tokenization strategy. Typically Unix or Windows.
1810 /// \param [in,out] Argv Command line into which to expand response files.
1811 /// \return true if all @files were expanded successfully or there were none.
1812 bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
1813                          SmallVectorImpl<const char *> &Argv);
1814
1815 } // End namespace cl
1816
1817 } // End namespace llvm
1818
1819 #endif