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