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