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