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