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