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