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