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