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