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