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