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