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