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