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