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