OSDN Git Service

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