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