1//===-- CommandLine.cpp - Command line parser implementation --------------===//
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
7//===----------------------------------------------------------------------===//
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.
13// Note that rather than trying to figure out what this code does, you could try
14// reading the library documentation located in docs/CommandLine.html
16//===----------------------------------------------------------------------===//
31#include "llvm/Config/config.h"
51 #define DEBUG_TYPE "commandline"
53//===----------------------------------------------------------------------===//
54// Template instantiations and anchors.
71#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
72// Only instantiate opt<std::string> when not building a Windows DLL. When
73// exporting opt<std::string>, MSVC implicitly exports symbols for
74// std::basic_string through transitive inheritance via std::string. These
75// symbols may appear in clients, leading to duplicate symbol conflicts.
87// Pin the vtables to this file.
88void GenericOptionValue::anchor() {}
89void OptionValue<boolOrDefault>::anchor() {}
90void OptionValue<std::string>::anchor() {}
91void Option::anchor() {}
107// These anchor functions instantiate opt<T> and reference its virtual
108// destructor to ensure MSVC exports the corresponding vtable and typeinfo when
109// building a Windows DLL. Without an explicit reference, MSVC may omit the
110// instantiation at link time even if it is marked DLL-export.
116//===----------------------------------------------------------------------===//
125 size_t Len = ArgName.
size();
133 for (
size_t I = 0;
I < Pad; ++
I) {
140// Option predicates...
156 PrintArg(StringRef ArgName,
size_t Pad =
DefaultPad) : ArgName(ArgName), Pad(Pad) {}
157 friend raw_ostream &
operator<<(raw_ostream &OS,
const PrintArg &);
160raw_ostream &
operator<<(raw_ostream &OS,
const PrintArg& Arg) {
161 OS <<
argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
165class CommandLineParser {
167 // Globals for name and overview of program. Program name is not a string to
168 // avoid static ctor/dtor issues.
169 std::string ProgramName;
170 StringRef ProgramOverview;
172 // This collects additional help to be printed.
173 std::vector<StringRef> MoreHelp;
175 // This collects Options added with the cl::DefaultOption flag. Since they can
176 // be overridden, they are not added to the appropriate SubCommands until
177 // ParseCommandLineOptions actually runs.
180 // This collects the different option categories that have been registered.
181 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
183 // This collects the different subcommands that have been registered.
184 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
191 StringRef Overview, raw_ostream *Errs =
nullptr,
192 vfs::FileSystem *VFS =
nullptr,
193 bool LongOptionsUseDoubleDash =
false);
195 void forEachSubCommand(Option &Opt, function_ref<
void(SubCommand &)> Action) {
196 if (Opt.
Subs.empty()) {
201 for (
auto *SC : RegisteredSubCommands)
206 for (
auto *SC : Opt.
Subs) {
208 "SubCommand::getAll() should not be used with other subcommands");
213 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
216 if (!SC->
OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
217 errs() << ProgramName <<
": CommandLine Error: Option '" <<
Name
218 <<
"' registered more than once!\n";
223 void addLiteralOption(Option &Opt, StringRef Name) {
225 Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
228 void addOption(Option *O, SubCommand *SC) {
229 bool HadErrors =
false;
230 if (
O->hasArgStr()) {
231 // If it's a DefaultOption, check to make sure it isn't already there.
232 if (
O->isDefaultOption() && SC->
OptionsMap.contains(
O->ArgStr))
235 // Add argument to the argument map!
236 if (!SC->
OptionsMap.insert(std::make_pair(
O->ArgStr, O)).second) {
237 errs() << ProgramName <<
": CommandLine Error: Option '" <<
O->ArgStr
238 <<
"' registered more than once!\n";
243 // Remember information about positional options.
246 else if (
O->getMiscFlags() &
cl::Sink)
// Remember sink options
250 O->error(
"Cannot specify more than one option with cl::ConsumeAfter!");
256 // Fail hard if there were errors. These are strictly unrecoverable and
257 // indicate serious issues such as conflicting option names or an
259 // linked LLVM distribution.
264 void addOption(Option *O,
bool ProcessDefaultOption =
false) {
265 if (!ProcessDefaultOption &&
O->isDefaultOption()) {
269 forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &SC); });
272 void removeOption(Option *O, SubCommand *SC) {
273 SmallVector<StringRef, 16> OptionNames;
274 O->getExtraOptionNames(OptionNames);
278 SubCommand &
Sub = *SC;
280 for (
auto Name : OptionNames) {
281 auto I =
Sub.OptionsMap.find(Name);
282 if (
I != End &&
I->getValue() == O)
283 Sub.OptionsMap.erase(
I);
287 for (
auto *Opt =
Sub.PositionalOpts.begin();
288 Opt !=
Sub.PositionalOpts.end(); ++Opt) {
290 Sub.PositionalOpts.erase(Opt);
295 for (
auto *Opt =
Sub.SinkOpts.begin(); Opt !=
Sub.SinkOpts.end(); ++Opt) {
297 Sub.SinkOpts.erase(Opt);
301 else if (O ==
Sub.ConsumeAfterOpt)
302 Sub.ConsumeAfterOpt =
nullptr;
305 void removeOption(Option *O) {
306 forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &SC); });
309 bool hasOptions(
const SubCommand &
Sub)
const {
310 return (!
Sub.OptionsMap.empty() || !
Sub.PositionalOpts.empty() ||
311 nullptr !=
Sub.ConsumeAfterOpt);
314 bool hasOptions()
const {
315 for (
const auto *S : RegisteredSubCommands) {
322 bool hasNamedSubCommands()
const {
323 for (
const auto *S : RegisteredSubCommands)
324 if (!S->getName().empty())
329 SubCommand *getActiveSubCommand() {
return ActiveSubCommand; }
331 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
332 SubCommand &
Sub = *SC;
333 if (!
Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
334 errs() << ProgramName <<
": CommandLine Error: Option '" <<
O->ArgStr
335 <<
"' registered more than once!\n";
341 void updateArgStr(Option *O, StringRef NewName) {
342 forEachSubCommand(*O,
343 [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
346 void printOptionValues();
348 void registerCategory(OptionCategory *cat) {
350 [cat](
const OptionCategory *Category) {
353 "Duplicate option categories");
355 RegisteredOptionCategories.
insert(cat);
358 void registerSubCommand(SubCommand *sub) {
360 [sub](
const SubCommand *
Sub) {
361 return (!
sub->getName().empty()) &&
362 (
Sub->getName() ==
sub->getName());
364 "Duplicate subcommands");
365 RegisteredSubCommands.insert(sub);
367 // For all options that have been registered for all subcommands, add the
368 // option to this subcommand now.
370 "SubCommand::getAll() should not be registered");
373 if ((
O->isPositional() ||
O->isSink() ||
O->isConsumeAfter()) ||
377 addLiteralOption(*O, sub,
E.first());
381 void unregisterSubCommand(SubCommand *sub) {
382 RegisteredSubCommands.erase(sub);
385 iterator_range<SmallPtrSet<SubCommand *, 4>::iterator>
387 return make_range(RegisteredSubCommands.begin(),
388 RegisteredSubCommands.end());
392 ActiveSubCommand =
nullptr;
394 ProgramOverview = StringRef();
397 RegisteredOptionCategories.
clear();
400 RegisteredSubCommands.clear();
406 DefaultOptions.
clear();
410 SubCommand *ActiveSubCommand =
nullptr;
412 Option *LookupOption(SubCommand &
Sub, StringRef &Arg, StringRef &
Value);
413 Option *LookupLongOption(SubCommand &
Sub, StringRef &Arg, StringRef &
Value,
414 bool LongOptionsUseDoubleDash,
bool HaveDoubleDash) {
416 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !
isGrouping(Opt))
420 SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
427template <
typename T, T TrueVal, T FalseVal>
429 if (Arg ==
"" || Arg ==
"true" || Arg ==
"TRUE" || Arg ==
"True" ||
435 if (Arg ==
"false" || Arg ==
"FALSE" || Arg ==
"False" || Arg ==
"0") {
439 return O.error(
"'" + Arg +
440 "' is invalid value for boolean argument! Try 0 or 1");
453 FullyInitialized =
true;
459 if (FullyInitialized)
469 // Maintain backward compatibility by replacing the default GeneralCategory
470 // if it's still set. Otherwise, just add the new one. The GeneralCategory
471 // must be explicitly added if you want multiple categories that include it.
485void OptionCategory::registerCategory() {
489// A special subcommand representing no subcommand. It is particularly important
490// that this ManagedStatic uses constant initailization and not dynamic
491// initialization because it is referenced from cl::opt constructors, which run
492// dynamically in an arbitrary order.
496// A special subcommand that can be used to put an option into all subcommands.
519 SubCommand::operator
bool()
const {
523//===----------------------------------------------------------------------===//
524// Basic, shared command line option processing machinery.
527/// LookupOption - Lookup the option specified by the specified option on the
528/// command line. If there is a value specified (after an equal sign) return
529/// that as well. This assumes that leading dashes have already been stripped.
532 // Reject all dashes.
537 size_t EqualPos = Arg.
find(
'=');
539 // If we have an equals sign, remember the value.
541 // Look up the option.
542 return Sub.OptionsMap.lookup(Arg);
545 // If the argument before the = is a valid option name and the option allows
546 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
547 // failure by returning nullptr.
548 auto I =
Sub.OptionsMap.find(Arg.
substr(0, EqualPos));
549 if (
I ==
Sub.OptionsMap.end())
557 Arg = Arg.
substr(0, EqualPos);
562 std::string &NearestString) {
565 // Find a subcommand with the edit distance == 1.
567 for (
auto *S : RegisteredSubCommands) {
569 "SubCommand::getAll() is not expected in RegisteredSubCommands");
570 if (S->getName().empty())
573 if (S->getName() == Name)
576 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
581 NearestString = NearestMatch->
getName();
586/// LookupNearestOption - Lookup the closest match to the option specified by
587/// the specified option on the command line. If there is a value specified
588/// (after an equal sign) return that as well. This assumes that leading dashes
589/// have already been stripped.
592 std::string &NearestString) {
593 // Reject all dashes.
597 // Split on any equal sign.
598 std::pair<StringRef, StringRef> SplitArg = Arg.
split(
'=');
599 StringRef &
LHS = SplitArg.first;
// LHS == Arg when no '=' is present.
602 // Find the closest match.
604 unsigned BestDistance = 0;
606 ie = OptionsMap.
end();
609 // Do not suggest really hidden options (not shown in any help).
614 O->getExtraOptionNames(OptionNames);
620 for (
const auto &Name : OptionNames) {
622 Flag,
/*AllowReplacements=*/true,
/*MaxEditDistance=*/BestDistance);
623 if (!Best || Distance < BestDistance) {
625 BestDistance = Distance;
626 if (
RHS.empty() || !PermitValue)
627 NearestString = std::string(Name);
629 NearestString = (
Twine(Name) +
"=" +
RHS).str();
637/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
638/// that does special handling of cl::CommaSeparated options.
641 bool MultiArg =
false) {
642 // Check to see if this option accepts a comma separated list of values. If
643 // it does, we have to split up the value into multiple values.
649 // Process the portion before the comma.
652 // Erase the portion before the comma, AND the comma.
653 Val = Val.
substr(Pos + 1);
654 // Check for another comma.
664/// ProvideOption - For Value, this differentiates between an empty value ("")
665/// and a null value (StringRef()). The later is accepted for arguments that
666/// don't allow a value (-foo) the former is rejected (-foo=).
669 const char *
const *argv,
int &i) {
670 // Is this a multi-argument option?
673 // Enforce value requirements
676 if (!
Value.data()) {
// No value specified?
677 // If no other argument or the option only supports prefix form, we
678 // cannot look at the next argument.
680 return Handler->
error(
"requires a value!");
681 // Steal the next argument, like for '-o filename'
682 assert(argv &&
"null check");
687 if (NumAdditionalVals > 0)
688 return Handler->
error(
"multi-valued option specified"
689 " with ValueDisallowed modifier!");
699 // If this isn't a multi-arg option, just run the handler.
700 if (NumAdditionalVals == 0)
703 // If it is, run the handle several times.
704 bool MultiArg =
false;
713 while (NumAdditionalVals > 0) {
715 return Handler->
error(
"not enough values!");
716 assert(argv &&
"null check");
732// getOptionPred - Check to see if there are any options that satisfy the
733// specified predicate with names that are the prefixes in Name. This is
734// checked by progressively stripping characters off of the name, checking to
735// see if there options that satisfy the predicate. If we find one, return it,
736// otherwise return null.
739 bool (*Pred)(
const Option *),
742 if (OMI != OptionsMap.
end() && !Pred(OMI->getValue()))
743 OMI = OptionsMap.
end();
745 // Loop while we haven't found an option and Name still has at least two
746 // characters in it (so that the next iteration will not be the empty
748 while (OMI == OptionsMap.
end() && Name.size() > 1) {
749 Name = Name.drop_back();
750 OMI = OptionsMap.
find(Name);
751 if (OMI != OptionsMap.
end() && !Pred(OMI->getValue()))
752 OMI = OptionsMap.
end();
755 if (OMI != OptionsMap.
end() && Pred(OMI->second)) {
757 return OMI->second;
// Found one!
759 return nullptr;
// No option found!
762/// HandlePrefixedOrGroupedOption - The specified argument string (which started
763/// with at least one '-') does not fully match an available option. Check to
764/// see if this is a prefix or grouped option. If so, split arg into output an
765/// Arg/Value pair and return the Option to parse it with.
783 assert(OptionsMap.
count(Arg) && OptionsMap.
find(Arg)->second == PGOpt);
785 // cl::Prefix options do not preserve '=' when used separately.
786 // The behavior for them with grouped options should be the same.
793 if (MaybeValue[0] ==
'=') {
798 // This must be a grouped option.
801 // Grouping options inside a group can't have values.
803 ErrorParsing |= PGOpt->
error(
"may not occur within a group!");
807 // Because the value for the option is not required, we don't need to pass
812 // Get the next grouping option.
817 // We could not find a grouping option in the remainder of Arg.
832 return C ==
' ' ||
C ==
'\t' ||
C ==
'\r' ||
C ==
'\n';
839 static bool isQuote(
char C) {
return C ==
'\"' ||
C ==
'\''; }
845 for (
size_t I = 0, E = Src.size();
I != E; ++
I) {
846 // Consume runs of whitespace.
849 // Mark the end of lines in response files.
850 if (MarkEOLs && Src[
I] ==
'\n')
860 // Backslash escapes the next character.
861 if (
I + 1 < E &&
C ==
'\\') {
862 ++
I;
// Skip the escape.
867 // Consume a quoted string.
870 while (
I != E && Src[
I] !=
C) {
871 // Backslash escapes the next character.
872 if (Src[
I] ==
'\\' &&
I + 1 != E)
882 // End the token if this is whitespace.
886 // Mark the end of lines in response files.
887 if (MarkEOLs &&
C ==
'\n')
893 // This is a normal character. Append it.
897 // Append the last token after hitting EOF with no whitespace.
902/// Backslashes are interpreted in a rather complicated way in the Windows-style
903/// command line, because backslashes are used both to separate path and to
904/// escape double quote. This method consumes runs of backslashes as well as the
905/// following double quote if it's escaped.
907/// * If an even number of backslashes is followed by a double quote, one
908/// backslash is output for every pair of backslashes, and the last double
909/// quote remains unconsumed. The double quote will later be interpreted as
910/// the start or end of a quoted string in the main loop outside of this
913/// * If an odd number of backslashes is followed by a double quote, one
914/// backslash is output for every pair of backslashes, and a double quote is
915/// output for the last pair of backslash-double quote. The double quote is
916/// consumed in this case.
918/// * Otherwise, backslashes are interpreted literally.
920 size_t E = Src.size();
921 int BackslashCount = 0;
922 // Skip the backslashes.
926 }
while (
I !=
E && Src[
I] ==
'\\');
928 bool FollowedByDoubleQuote = (
I !=
E && Src[
I] ==
'"');
929 if (FollowedByDoubleQuote) {
930 Token.
append(BackslashCount / 2,
'\\');
931 if (BackslashCount % 2 == 0)
936 Token.
append(BackslashCount,
'\\');
940// Windows treats whitespace, double quotes, and backslashes specially, except
941// when parsing the first token of a full command line, in which case
942// backslashes are not special.
950// Windows tokenization implementation. The implementation is designed to be
951// inlined and specialized for the two user entry points.
954 bool AlwaysCopy,
function_ref<
void()> MarkEOL,
bool InitialCommandName) {
957 // Sometimes, this function will be handling a full command line including an
958 // executable pathname at the start. In that situation, the initial pathname
959 // needs different handling from the following arguments, because when
960 // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
961 // escaping the quote character, whereas when libc scans the rest of the
962 // command line, it does.
963 bool CommandName = InitialCommandName;
965 // Try to do as much work inside the state machine as possible.
966 enum {
INIT, UNQUOTED, QUOTED } State =
INIT;
968 for (
size_t I = 0,
E = Src.size();
I <
E; ++
I) {
971 assert(Token.
empty() &&
"token should be empty in initial state");
972 // Eat whitespace before a token.
978 // Stop if this was trailing whitespace.
991 // No special characters: slice out the substring and start the next
992 // token. Copy the string if the caller asks us to.
993 AddToken(AlwaysCopy ? Saver.
save(NormalChars) : NormalChars);
994 if (
I <
E && Src[
I] ==
'\n') {
996 CommandName = InitialCommandName;
1000 }
else if (Src[
I] ==
'\"') {
1001 Token += NormalChars;
1003 }
else if (Src[
I] ==
'\\') {
1004 assert(!CommandName &&
"or else we'd have treated it as a normal char");
1005 Token += NormalChars;
1016 // Whitespace means the end of the token. If we are in this state, the
1017 // token must have contained a special character, so we must copy the
1019 AddToken(Saver.
save(Token.
str()));
1021 if (Src[
I] ==
'\n') {
1022 CommandName = InitialCommandName;
1025 CommandName =
false;
1028 }
else if (Src[
I] ==
'\"') {
1030 }
else if (Src[
I] ==
'\\' && !CommandName) {
1038 if (Src[
I] ==
'\"') {
1039 if (
I < (
E - 1) && Src[
I + 1] ==
'"') {
1040 // Consecutive double-quotes inside a quoted string implies one
1045 // Otherwise, end the quoted portion and return to the unquoted state.
1048 }
else if (Src[
I] ==
'\\' && !CommandName) {
1058 AddToken(Saver.
save(Token.
str()));
1065 auto OnEOL = [&]() {
1070 /*AlwaysCopy=*/true, OnEOL,
false);
1076 auto OnEOL = []() {};
1085 auto OnEOL = [&]() {
1090 /*AlwaysCopy=*/true, OnEOL,
true);
1096 for (
const char *Cur = Source.begin(); Cur != Source.end();) {
1098 // Check for comment line.
1105 while (Cur != Source.end() && *Cur !=
'\n')
1109 // Find end of the current line.
1110 const char *Start = Cur;
1111 for (
const char *End = Source.end(); Cur != End; ++Cur) {
1113 if (Cur + 1 != End) {
1116 (*Cur ==
'\r' && (Cur + 1 != End) && Cur[1] ==
'\n')) {
1117 Line.append(Start, Cur - 1);
1123 }
else if (*Cur ==
'\n')
1127 Line.append(Start, Cur);
1132// It is called byte order marker but the UTF-8 BOM is actually not affected
1133// by the host system's endianness.
1135 return (S.
size() >= 3 && S[0] ==
'\xef' && S[1] ==
'\xbb' && S[2] ==
'\xbf');
1138// Substitute <CFGDIR> with the file's base path.
1149 TokenPos = ArgString.
find(Token, StartPos)) {
1150 // Token may appear more than once per arg (e.g. comma-separated linker
1151 // args). Support by using path-append on any subsequent appearances.
1153 if (ResponseFile.
empty())
1157 ResponseFile.
append(BasePath);
1158 StartPos = TokenPos + Token.
size();
1161 if (!ResponseFile.
empty()) {
1162 // Path-append the remaining arg substring if at least one token appeared.
1164 if (!Remaining.
empty())
1170// FName must be an absolute path.
1171Error ExpansionContext::expandResponseFile(
1172 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1174 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1175 FS->getBufferForFile(FName);
1179 "': " +
EC.message());
1181 MemoryBuffer &MemBuf = *MemBufOrErr.
get();
1184 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1186 std::string UTF8Buf;
1190 "Could not convert UTF16 to UTF8");
1191 Str = StringRef(UTF8Buf);
1193 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1194 // these bytes before parsing.
1195 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1197 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1199 // Tokenize the contents into NewArgv.
1200 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1202 // Expanded file content may require additional transformations, like using
1203 // absolute paths instead of relative in '@file' constructs or expanding
1205 if (!RelativeNames && !InConfigFile)
1209 for (
const char *&Arg : NewArgv) {
1213 // Substitute <CFGDIR> with the file's base path.
1217 // Discover the case, when argument should be transformed into '@file' and
1218 // evaluate 'file' for it.
1219 StringRef ArgStr(Arg);
1221 bool ConfigInclusion =
false;
1222 if (ArgStr.consume_front(
"@")) {
1226 }
else if (ArgStr.consume_front(
"--config=")) {
1228 ConfigInclusion =
true;
1233 // Update expansion construct.
1234 SmallString<128> ResponseFile;
1237 SmallString<128> FilePath;
1240 std::make_error_code(std::errc::no_such_file_or_directory),
1241 "cannot not find configuration file: " + FileName);
1242 ResponseFile.
append(FilePath);
1244 ResponseFile.
append(BasePath);
1247 Arg = Saver.save(ResponseFile.
str()).
data();
1252/// Expand response files on a command line recursively using the given
1253/// StringSaver and tokenization strategy.
1256 struct ResponseFileRecord {
1261 // To detect recursive response files, we maintain a stack of files and the
1262 // position of the last argument in the file. This position is updated
1263 // dynamically as we recursively expand files.
1266 // Push a dummy entry that represents the initial command line, removing
1267 // the need to check for an empty list.
1270 // Don't cache Argv.size() because it can change.
1271 for (
unsigned I = 0;
I != Argv.
size();) {
1272 while (
I == FileStack.
back().End) {
1273 // Passing the end of a file's argument list, so we can remove it from the
1278 const char *Arg = Argv[
I];
1279 // Check if it is an EOL marker
1280 if (Arg ==
nullptr) {
1285 if (Arg[0] !=
'@') {
1290 const char *FName = Arg + 1;
1291 // Note that CurrentDir is only used for top-level rsp files, the rest will
1292 // always have an absolute path deduced from the containing file.
1295 if (CurrentDir.empty()) {
1296 if (
auto CWD = FS->getCurrentWorkingDirectory()) {
1300 CWD.getError(),
Twine(
"cannot get absolute path for: ") + FName);
1303 CurrDir = CurrentDir;
1306 FName = CurrDir.
c_str();
1310 if (!Res || !Res->exists()) {
1311 std::error_code EC = Res.
getError();
1312 if (!InConfigFile) {
1313 // If the specified file does not exist, leave '@file' unexpanded, as
1323 "': " + EC.message());
1328 [FileStatus,
this](
const ResponseFileRecord &RFile) ->
ErrorOr<bool> {
1335 // Check for recursive response files.
1340 R.getError(),
Twine(
"recursive expansion of: '") +
F.File +
"'");
1343 Twine(
"cannot open file: ") +
F.File);
1347 // Replace this response file argument with the tokenization of its
1348 // contents. Nested response files are expanded in subsequent iterations.
1350 if (
Error Err = expandResponseFile(FName, ExpandedArgv))
1353 for (ResponseFileRecord &
Record : FileStack) {
1354 // Increase the end of all active records by the number of newly expanded
1355 // arguments, minus the response file itself.
1364 // If successful, the top of the file stack will mark the end of the Argv
1365 // stream. A failure here indicates a bug in the stack popping logic above.
1366 // Note that FileStack may have more than one element at this point because we
1367 // don't have a chance to pop the stack when encountering recursive files at
1368 // the end of the stream, so seeing that doesn't indicate a bug.
1381 // The environment variable specifies initial options.
1384 Tokenize(*EnvValue, Saver, NewArgv,
/*MarkEOLs=*/false);
1386 // Command line options can override the environment variable.
1387 NewArgv.
append(Argv + 1, Argv + Argc);
1408 : Saver(
A), Tokenizer(
T), FS(FS ? FS :
vfs::getRealFileSystem().
get()) {}
1414 auto Status = FS->status(Path);
1419 // If file name contains directory separator, treat it as a path to
1420 // configuration file.
1422 CfgFilePath = FileName;
1425 if (!FileExists(CfgFilePath))
1431 // Look for the file in search directories.
1432 for (
const StringRef &Dir : SearchDirs) {
1438 if (FileExists(CfgFilePath)) {
1452 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1454 EC,
Twine(
"cannot get absolute path for " + CfgFile));
1455 CfgFile = AbsPath.
str();
1457 InConfigFile =
true;
1458 RelativeNames =
true;
1459 if (
Error Err = expandResponseFile(CfgFile, Argv))
1468 bool LongOptionsUseDoubleDash) {
1475 // Parse options from environment variable.
1477 if (std::optional<std::string> EnvValue =
1482 // Append options from command line.
1483 for (
int I = 1;
I < argc; ++
I)
1485 int NewArgc =
static_cast<int>(NewArgv.
size());
1487 // Parse all options.
1489 NewArgc, &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash);
1492/// Reset all options at least once, so that we can parse different options.
1493 void CommandLineParser::ResetAllOptionOccurrences() {
1494 // Reset all option values to look like they have never been seen before.
1495 // Options might be reset twice (they can be reference in both OptionsMap
1496 // and one of the other members), but that does not harm.
1497 for (
auto *SC : RegisteredSubCommands) {
1509bool CommandLineParser::ParseCommandLineOptions(
1512 assert(hasOptions() &&
"No options specified!");
1514 ProgramOverview = Overview;
1515 bool IgnoreErrors = Errs;
1520 bool ErrorParsing =
false;
1522 // Expand response files.
1531 if (
Error Err = ECtx.expandResponseFiles(newArgv)) {
1532 *Errs <<
toString(std::move(Err)) <<
'\n';
1536 argc =
static_cast<int>(newArgv.size());
1538 // Copy the program name into ProgName, making sure not to overflow it.
1541 // Check out the positional arguments to collect information about them.
1542 unsigned NumPositionalRequired = 0;
1544 // Determine whether or not there are an unlimited number of positionals
1545 bool HasUnlimitedPositionals =
false;
1549 std::string NearestSubCommandString;
1550 bool MaybeNamedSubCommand =
1551 argc >= 2 && argv[FirstArg][0] !=
'-' && hasNamedSubCommands();
1552 if (MaybeNamedSubCommand) {
1553 // If the first argument specifies a valid subcommand, start processing
1554 // options from the second argument.
1556 LookupSubCommand(
StringRef(argv[FirstArg]), NearestSubCommandString);
1562 assert(ChosenSubCommand);
1565 auto &SinkOpts = ChosenSubCommand->
SinkOpts;
1566 auto &OptionsMap = ChosenSubCommand->
OptionsMap;
1568 for (
auto *O: DefaultOptions) {
1572 if (ConsumeAfterOpt) {
1573 assert(PositionalOpts.size() > 0 &&
1574 "Cannot specify cl::ConsumeAfter without a positional argument!");
1576 if (!PositionalOpts.empty()) {
1578 // Calculate how many positional values are _required_.
1579 bool UnboundedFound =
false;
1580 for (
size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1581 Option *Opt = PositionalOpts[i];
1583 ++NumPositionalRequired;
1584 else if (ConsumeAfterOpt) {
1585 // ConsumeAfter cannot be combined with "optional" positional options
1586 // unless there is only one positional argument...
1587 if (PositionalOpts.size() > 1) {
1589 Opt->
error(
"error - this positional option will never be matched, "
1590 "because it does not Require a value, and a "
1591 "cl::ConsumeAfter option is active!");
1592 ErrorParsing =
true;
1594 }
else if (UnboundedFound && !Opt->
hasArgStr()) {
1595 // This option does not "require" a value... Make sure this option is
1596 // not specified after an option that eats all extra arguments, or this
1597 // one will never get any!
1600 Opt->
error(
"error - option can never match, because "
1601 "another positional argument will match an "
1602 "unbounded number of values, and this option"
1603 " does not require a value!");
1604 *Errs << ProgramName <<
": CommandLine Error: Option '" << Opt->
ArgStr
1605 <<
"' is all messed up!\n";
1606 *Errs << PositionalOpts.size();
1607 ErrorParsing =
true;
1611 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1614 // PositionalVals - A vector of "positional" arguments we accumulate into
1615 // the process at the end.
1619 // If the program has named positional arguments, and the name has been run
1620 // across, keep track of which positional argument was named. Otherwise put
1621 // the positional args into the PositionalVals list...
1622 Option *ActivePositionalArg =
nullptr;
1624 // Loop over all of the arguments... processing them.
1625 bool DashDashFound =
false;
// Have we read '--'?
1626 for (
int i = FirstArg; i < argc; ++i) {
1627 Option *Handler =
nullptr;
1628 std::string NearestHandlerString;
1630 StringRef ArgName =
"";
1631 bool HaveDoubleDash =
false;
1633 // Check to see if this is a positional argument. This argument is
1634 // considered to be positional if it doesn't start with '-', if it is "-"
1635 // itself, or if we have seen "--" already.
1637 if (argv[i][0] !=
'-' || argv[i][1] == 0 || DashDashFound) {
1638 // Positional argument!
1639 if (ActivePositionalArg) {
1641 continue;
// We are done!
1644 if (!PositionalOpts.empty()) {
1645 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1647 // All of the positional arguments have been fulfulled, give the rest to
1648 // the consume after option... if it's specified...
1650 if (PositionalVals.
size() >= NumPositionalRequired && ConsumeAfterOpt) {
1651 for (++i; i < argc; ++i)
1652 PositionalVals.
push_back(std::make_pair(StringRef(argv[i]), i));
1653 break;
// Handle outside of the argument processing loop...
1656 // Delay processing positional arguments until the end...
1659 }
else if (argv[i][0] ==
'-' && argv[i][1] ==
'-' && argv[i][2] == 0 &&
1661 DashDashFound =
true;
// This is the mythical "--"?
1662 continue;
// Don't try to process it as an argument itself.
1663 }
else if (ActivePositionalArg &&
1665 // If there is a positional argument eating options, check to see if this
1666 // option is another positional argument. If so, treat it as an argument,
1667 // otherwise feed it to the eating positional.
1668 ArgName = StringRef(argv[i] + 1);
1671 HaveDoubleDash =
true;
1673 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1674 LongOptionsUseDoubleDash, HaveDoubleDash);
1677 continue;
// We are done!
1679 }
else {
// We start with a '-', must be an argument.
1680 ArgName = StringRef(argv[i] + 1);
1683 HaveDoubleDash =
true;
1685 Handler = LookupLongOption(*ChosenSubCommand, ArgName,
Value,
1686 LongOptionsUseDoubleDash, HaveDoubleDash);
1688 // If Handler is not found in a specialized subcommand, look up handler
1689 // in the top-level subcommand.
1690 // cl::opt without cl::sub belongs to top-level subcommand.
1693 LongOptionsUseDoubleDash, HaveDoubleDash);
1695 // Check to see if this "option" is really a prefixed or grouped argument.
1696 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1700 // Otherwise, look for the closest available option to report to the user
1701 // in the upcoming error.
1702 if (!Handler && SinkOpts.empty())
1707 if (!SinkOpts.empty()) {
1708 for (
Option *SinkOpt : SinkOpts)
1709 SinkOpt->addOccurrence(i,
"", StringRef(argv[i]));
1713 auto ReportUnknownArgument = [&](
bool IsArg,
1714 StringRef NearestArgumentName) {
1715 *Errs << ProgramName <<
": Unknown "
1716 << (IsArg ?
"command line argument" :
"subcommand") <<
" '"
1717 << argv[i] <<
"'. Try: '" << argv[0] <<
" --help'\n";
1719 if (NearestArgumentName.empty())
1722 *Errs << ProgramName <<
": Did you mean '";
1724 *Errs << PrintArg(NearestArgumentName, 0);
1726 *Errs << NearestArgumentName;
1730 if (i > 1 || !MaybeNamedSubCommand)
1731 ReportUnknownArgument(
/*IsArg=*/true, NearestHandlerString);
1733 ReportUnknownArgument(
/*IsArg=*/false, NearestSubCommandString);
1735 ErrorParsing =
true;
1739 // If this is a named positional argument, just remember that it is the
1743 Handler->
error(
"This argument does not take a value.\n"
1744 "\tInstead, it consumes any positional arguments until "
1745 "the next recognized option.", *Errs);
1746 ErrorParsing =
true;
1748 ActivePositionalArg = Handler;
1754 // Check and handle positional arguments now...
1755 if (NumPositionalRequired > PositionalVals.
size()) {
1756 *Errs << ProgramName
1757 <<
": Not enough positional command line arguments specified!\n"
1758 <<
"Must specify at least " << NumPositionalRequired
1759 <<
" positional argument" << (NumPositionalRequired > 1 ?
"s" :
"")
1760 <<
": See: " << argv[0] <<
" --help\n";
1762 ErrorParsing =
true;
1763 }
else if (!HasUnlimitedPositionals &&
1764 PositionalVals.
size() > PositionalOpts.size()) {
1765 *Errs << ProgramName <<
": Too many positional arguments specified!\n"
1766 <<
"Can specify at most " << PositionalOpts.size()
1767 <<
" positional arguments: See: " << argv[0] <<
" --help\n";
1768 ErrorParsing =
true;
1770 }
else if (!ConsumeAfterOpt) {
1771 // Positional args have already been handled if ConsumeAfter is specified.
1772 unsigned ValNo = 0, NumVals =
static_cast<unsigned>(PositionalVals.
size());
1773 for (
Option *Opt : PositionalOpts) {
1776 PositionalVals[ValNo].second);
1778 --NumPositionalRequired;
// We fulfilled our duty...
1781 // If we _can_ give this option more arguments, do so now, as long as we
1782 // do not give it values that others need. 'Done' controls whether the
1783 // option even _WANTS_ any more.
1786 while (NumVals - ValNo > NumPositionalRequired && !
Done) {
1789 Done =
true;
// Optional arguments want _at most_ one value
1791 case cl::ZeroOrMore:
// Zero or more will take all they can get...
1792 case cl::OneOrMore:
// One or more will take all they can get...
1794 PositionalVals[ValNo].second);
1799 "positional argument processing!");
1804 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.
size());
1806 for (
Option *Opt : PositionalOpts)
1809 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1813 // Handle the case where there is just one positional option, and it's
1814 // optional. In this case, we want to give JUST THE FIRST option to the
1815 // positional option and keep the rest for the consume after. The above
1816 // loop would have assigned no values to positional options in this case.
1818 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.
empty()) {
1820 PositionalVals[ValNo].first,
1821 PositionalVals[ValNo].second);
1825 // Handle over all of the rest of the arguments to the
1826 // cl::ConsumeAfter command line option...
1827 for (; ValNo != PositionalVals.
size(); ++ValNo)
1830 PositionalVals[ValNo].second);
1833 // Loop over args and make sure all required args are specified!
1834 for (
const auto &Opt : OptionsMap) {
1839 Opt.second->
error(
"must be specified at least once!");
1840 ErrorParsing =
true;
1848 // Now that we know if -debug is specified, we can use it.
1849 // Note that if ReadResponseFiles == true, this must be done before the
1850 // memory allocated for the expanded command line is free()d below.
1852 for (
int i = 0; i < argc; ++i)
dbgs() << argv[i] <<
' ';
1855 // Free all of the memory allocated to the map. Command line options may only
1856 // be processed once!
1859 // If we had an error processing our arguments, don't let the program execute
1868//===----------------------------------------------------------------------===//
1869// Option Base class implementation
1873 if (!ArgName.
data())
1875 if (ArgName.
empty())
1876 Errs <<
HelpStr;
// Be nice for positional arguments
1878 Errs <<
GlobalParser->ProgramName <<
": for the " << PrintArg(ArgName, 0);
1880 Errs <<
" option: " << Message <<
"\n";
1887 NumOccurrences++;
// Increment the number of times we have been seen
1889 return handleOccurrence(pos, ArgName, Value);
1892// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1893// has been specified yet.
1896 if (O.ValueStr.empty())
1901//===----------------------------------------------------------------------===//
1902// cl::alias class implementation
1905// Return the width of the option tag for printing...
1911 size_t FirstLineIndentedBy) {
1912 assert(Indent >= FirstLineIndentedBy);
1913 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1916 while (!Split.second.empty()) {
1917 Split = Split.second.split(
'\n');
1918 outs().
indent(Indent) << Split.first <<
"\n";
1923 size_t FirstLineIndentedBy) {
1925 assert(BaseIndent >= FirstLineIndentedBy);
1926 std::pair<StringRef, StringRef> Split =
HelpStr.split(
'\n');
1927 outs().
indent(BaseIndent - FirstLineIndentedBy)
1929 while (!Split.second.empty()) {
1930 Split = Split.second.split(
'\n');
1931 outs().
indent(BaseIndent + ValHelpPrefix.
size()) << Split.first <<
"\n";
1935// Print out the option for the alias.
1936void alias::printOptionInfo(
size_t GlobalWidth)
const {
1941//===----------------------------------------------------------------------===//
1942// Parser Implementation code...
1945// basic_parser implementation
1948// Return the width of the option tag for printing...
1952 if (!ValName.empty()) {
1953 size_t FormattingLen = 3;
1962// printOptionInfo - Print out information about this option. The
1963// to-be-maintained width is specified.
1966 size_t GlobalWidth)
const {
1967 outs() << PrintArg(O.ArgStr);
1970 if (!ValName.empty()) {
1976 outs() << (O.ArgStr.size() == 1 ?
" <" :
"=<") <<
getValueStr(O, ValName)
1985 size_t GlobalWidth)
const {
1986 outs() << PrintArg(O.ArgStr);
1987 outs().
indent(GlobalWidth - O.ArgStr.size());
1990// parser<bool> implementation
1997// parser<boolOrDefault> implementation
2004// parser<int> implementation
2009 return O.error(
"'" + Arg +
"' value invalid for integer argument!");
2013// parser<long> implementation
2018 return O.error(
"'" + Arg +
"' value invalid for long argument!");
2022// parser<long long> implementation
2027 return O.error(
"'" + Arg +
"' value invalid for llong argument!");
2031// parser<unsigned> implementation
2037 return O.error(
"'" + Arg +
"' value invalid for uint argument!");
2041// parser<unsigned long> implementation
2044 unsigned long &
Value) {
2047 return O.error(
"'" + Arg +
"' value invalid for ulong argument!");
2051// parser<unsigned long long> implementation
2055 unsigned long long &
Value) {
2058 return O.error(
"'" + Arg +
"' value invalid for ullong argument!");
2062// parser<double>/parser<float> implementation
2067 return O.error(
"'" + Arg +
"' value invalid for floating point argument!");
2084// generic_parser_base implementation
2087// findOption - Return the option number corresponding to the specified
2088// argument string. If the option is not found, getNumOptions() is returned.
2093 for (
unsigned i = 0; i != e; ++i) {
2109 return O.getValueExpectedFlag() !=
ValueOptional || !Name.empty() ||
2110 !Description.
empty();
2113// Return the width of the option tag for printing...
2115 if (O.hasArgStr()) {
2127 size_t BaseSize = 0;
2134// printOptionInfo - Print out information about this option. The
2135// to-be-maintained width is specified.
2138 size_t GlobalWidth)
const {
2139 if (O.hasArgStr()) {
2140 // When the value is optional, first print a line just describing the
2141 // option without values.
2145 outs() << PrintArg(O.ArgStr);
2164 if (OptionName.
empty()) {
2169 if (!Description.
empty())
2175 if (!O.HelpStr.empty())
2176 outs() <<
" " << O.HelpStr <<
'\n';
2185 static const size_t MaxOptWidth = 8;
// arbitrary spacing for printOptionDiff
2187// printGenericOptionDiff - Print the value of this option and it's default.
2189// "Generic" options have each value mapped to a name.
2193 outs() <<
" " << PrintArg(O.ArgStr);
2194 outs().
indent(GlobalWidth - O.ArgStr.size());
2197 for (
unsigned i = 0; i != NumOpts; ++i) {
2205 for (
unsigned j = 0; j != NumOpts; ++j) {
2214 outs() <<
"= *unknown option value*\n";
2217// printOptionDiff - Specializations for printing basic value types.
2219 #define PRINT_OPT_DIFF(T) \
2220 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2221 size_t GlobalWidth) const { \
2222 printOptionName(O, GlobalWidth); \
2225 raw_string_ostream SS(Str); \
2228 outs() << "= " << Str; \
2229 size_t NumSpaces = \
2230 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2231 outs().indent(NumSpaces) << " (default: "; \
2233 outs() << D.getValue(); \
2235 outs() << "*no default*"; \
2253 size_t GlobalWidth)
const {
2254 printOptionName(O, GlobalWidth);
2255 outs() <<
"= " << V;
2259 outs() <<
D.getValue();
2261 outs() <<
"*no default*";
2266 const Option &O, std::optional<StringRef> V,
2268 size_t GlobalWidth)
const {
2269 printOptionName(O, GlobalWidth);
2270 outs() <<
"= " <<
V;
2271 size_t VSize =
V.has_value() ?
V.value().size() : 0;
2274 if (
D.hasValue() &&
D.getValue().has_value())
2275 outs() <<
D.getValue();
2277 outs() <<
"*no value*";
2281// Print a placeholder for options that don't yet support printOptionDiff().
2283 size_t GlobalWidth)
const {
2285 outs() <<
"= *cannot print option value*\n";
2288//===----------------------------------------------------------------------===//
2289// -help and -help-hidden option implementation
2293 const std::pair<const char *, Option *> *
RHS) {
2294 return strcmp(
LHS->first,
RHS->first);
2298 const std::pair<const char *, SubCommand *> *
RHS) {
2299 return strcmp(
LHS->first,
RHS->first);
2302// Copy Options into a vector so we can sort them as we like.
2310 // Ignore really-hidden options.
2314 // Unless showhidden is set, ignore hidden flags.
2315 if (
I->second->getOptionHiddenFlag() ==
Hidden && !ShowHidden)
2318 // If we've already seen this option, don't add it to the list again.
2319 if (!OptionSet.
insert(
I->second).second)
2323 std::pair<const char *, Option *>(
I->getKey().data(),
I->second));
2326 // Sort the options list alphabetically.
2333 for (
auto *S : SubMap) {
2334 if (S->getName().empty())
2336 Subs.push_back(std::make_pair(S->getName().data(), S));
2345 const bool ShowHidden;
2346 using StrOptionPairVector =
2348 using StrSubCommandPairVector =
2350 // Print the options. Opts is assumed to be alphabetically sorted.
2351 virtual void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen) {
2352 for (
const auto &Opt : Opts)
2356 void printSubCommands(StrSubCommandPairVector &Subs,
size_t MaxSubLen) {
2357 for (
const auto &S : Subs) {
2358 outs() <<
" " << S.first;
2359 if (!S.second->getDescription().empty()) {
2361 outs() <<
" - " << S.second->getDescription();
2368 explicit HelpPrinter(
bool showHidden) : ShowHidden(showHidden) {}
2369 virtual ~HelpPrinter() =
default;
2371 // Invoke the printer.
2372 void operator=(
bool Value) {
2377 // Halt the program since help information was printed
2383 auto &OptionsMap =
Sub->OptionsMap;
2384 auto &PositionalOpts =
Sub->PositionalOpts;
2385 auto &ConsumeAfterOpt =
Sub->ConsumeAfterOpt;
2387 StrOptionPairVector Opts;
2388 sortOpts(OptionsMap, Opts, ShowHidden);
2390 StrSubCommandPairVector Subs;
2399 outs() <<
" [subcommand]";
2400 outs() <<
" [options]";
2402 if (!
Sub->getDescription().empty()) {
2403 outs() <<
"SUBCOMMAND '" <<
Sub->getName()
2404 <<
"': " <<
Sub->getDescription() <<
"\n\n";
2410 for (
auto *Opt : PositionalOpts) {
2416 // Print the consume after option info if it exists...
2417 if (ConsumeAfterOpt)
2418 outs() <<
" " << ConsumeAfterOpt->HelpStr;
2421 // Compute the maximum subcommand length...
2422 size_t MaxSubLen = 0;
2423 for (
const auto &
Sub : Subs)
2424 MaxSubLen = std::max(MaxSubLen, strlen(
Sub.first));
2427 outs() <<
"SUBCOMMANDS:\n\n";
2428 printSubCommands(Subs, MaxSubLen);
2431 <<
" <subcommand> --help\" to get more help on a specific "
2437 // Compute the maximum argument length...
2438 size_t MaxArgLen = 0;
2439 for (
const auto &Opt : Opts)
2442 outs() <<
"OPTIONS:\n";
2443 printOptions(Opts, MaxArgLen);
2445 // Print any extra help the user has declared.
2452class CategorizedHelpPrinter :
public HelpPrinter {
2454 explicit CategorizedHelpPrinter(
bool showHidden) : HelpPrinter(showHidden) {}
2456 // Helper function for printOptions().
2457 // It shall return a negative value if A's name should be lexicographically
2458 // ordered before B's name. It returns a value greater than zero if B's name
2459 // should be ordered before A's name, and it returns 0 otherwise.
2460 static int OptionCategoryCompare(OptionCategory *
const *
A,
2461 OptionCategory *
const *
B) {
2462 return (*A)->getName().compare((*B)->getName());
2465 // Make sure we inherit our base class's operator=()
2466 using HelpPrinter::operator=;
2469 void printOptions(StrOptionPairVector &Opts,
size_t MaxArgLen)
override {
2470 std::vector<OptionCategory *> SortedCategories;
2471 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2473 // Collect registered option categories into vector in preparation for
2478 // Sort the different option categories alphabetically.
2479 assert(SortedCategories.size() > 0 &&
"No option categories registered!");
2481 OptionCategoryCompare);
2483 // Walk through pre-sorted options and assign into categories.
2484 // Because the options are already alphabetically sorted the
2485 // options within categories will also be alphabetically sorted.
2486 for (
const auto &
I : Opts) {
2488 for (OptionCategory *Cat : Opt->
Categories) {
2490 "Option has an unregistered category");
2491 CategorizedOptions[Cat].push_back(Opt);
2496 for (OptionCategory *Category : SortedCategories) {
2497 // Hide empty categories for --help, but show for --help-hidden.
2498 const auto &CategoryOptions = CategorizedOptions[Category];
2499 if (CategoryOptions.empty())
2502 // Print category information.
2506 // Check if description is set.
2512 // Loop over the options in the category and print.
2513 for (
const Option *Opt : CategoryOptions)
2519// This wraps the Uncategorizing and Categorizing printers and decides
2520// at run time which should be invoked.
2521class HelpPrinterWrapper {
2523 HelpPrinter &UncategorizedPrinter;
2524 CategorizedHelpPrinter &CategorizedPrinter;
2527 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2528 CategorizedHelpPrinter &CategorizedPrinter)
2529 : UncategorizedPrinter(UncategorizedPrinter),
2530 CategorizedPrinter(CategorizedPrinter) {}
2532 // Invoke the printer.
2533 void operator=(
bool Value);
2536}
// End anonymous namespace
2538#if defined(__GNUC__)
2539// GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2541# if defined(__OPTIMIZE__)
2542# define LLVM_IS_DEBUG_BUILD 0
2544# define LLVM_IS_DEBUG_BUILD 1
2546#elif defined(_MSC_VER)
2547// MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2548// Use _DEBUG instead. This macro actually corresponds to the choice between
2549// debug and release CRTs, but it is a reasonable proxy.
2551# define LLVM_IS_DEBUG_BUILD 1
2553# define LLVM_IS_DEBUG_BUILD 0
2556// Otherwise, for an unknown compiler, assume this is an optimized build.
2557 # define LLVM_IS_DEBUG_BUILD 0
2561class VersionPrinter {
2563 void print(std::vector<VersionPrinterTy> ExtraPrinters = {}) {
2565#ifdef PACKAGE_VENDOR
2566 OS << PACKAGE_VENDOR <<
" ";
2568 OS <<
"LLVM (http://llvm.org/):\n ";
2570 OS << PACKAGE_NAME <<
" version " << PACKAGE_VERSION <<
"\n ";
2571#if LLVM_IS_DEBUG_BUILD
2572 OS <<
"DEBUG build";
2574 OS <<
"Optimized build";
2577 OS <<
" with assertions";
2581 // Iterate over any registered extra printers and call them to add further
2583 if (!ExtraPrinters.empty()) {
2584 for (
const auto &
I : ExtraPrinters)
2588 void operator=(
bool OptionWasSpecified);
2591struct CommandLineCommonOptions {
2592 // Declare the four HelpPrinter instances that are used to print out help, or
2593 // help-hidden as an uncategorized list or in categories.
2594 HelpPrinter UncategorizedNormalPrinter{
false};
2595 HelpPrinter UncategorizedHiddenPrinter{
true};
2596 CategorizedHelpPrinter CategorizedNormalPrinter{
false};
2597 CategorizedHelpPrinter CategorizedHiddenPrinter{
true};
2598 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2599 // a categorizing help printer
2600 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2601 CategorizedNormalPrinter};
2602 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2603 CategorizedHiddenPrinter};
2604 // Define a category for generic options that all tools should have.
2607 // Define uncategorized help printers.
2608 // --help-list is hidden by default because if Option categories are being
2609 // used then --help behaves the same as --help-list.
2613 "Display list of available options (--help-list-hidden for more)"),
2622 cl::desc(
"Display list of all available options"),
2629 // Define uncategorized/categorized help printers. These printers change their
2630 // behaviour at runtime depending on whether one or more Option categories
2631 // have been declared.
2634 cl::desc(
"Display available options (--help-hidden for more)"),
2645 cl::desc(
"Display all available options"),
2654 cl::desc(
"Print non-default options after command line parsing"),
2661 "print-all-options",
2662 cl::desc(
"Print all option values after command line parsing"),
2670 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2672 // Define the --version option that prints out the LLVM version for the tool
2673 VersionPrinter VersionPrinterInstance;
2676 "version",
cl::desc(
"Display the version of this program"),
2680}
// End anonymous namespace
2682// Lazy-initialized global instance of options controlling the command-line
2683// parser and general handling.
2699 // Initialise the general option category.
2701 return GeneralCategory;
2704void VersionPrinter::operator=(
bool OptionWasSpecified) {
2705 if (!OptionWasSpecified)
2717void HelpPrinterWrapper::operator=(
bool Value) {
2721 // Decide which printer to invoke. If more than one option category is
2722 // registered then it is useful to show the categorized help instead of
2723 // uncategorized help.
2724 if (
GlobalParser->RegisteredOptionCategories.size() > 1) {
2725 // unhide --help-list option so user can have uncategorized output if they
2729 CategorizedPrinter =
true;
// Invoke categorized printer
2731 UncategorizedPrinter =
true;
// Invoke uncategorized printer
2735// Print the value of each option.
2738void CommandLineParser::printOptionValues() {
2745 // Compute the maximum argument length...
2746 size_t MaxArgLen = 0;
2747 for (
const auto &Opt : Opts)
2750 for (
const auto &Opt : Opts)
2754// Utility function for printing the help message.
2756 if (!
Hidden && !Categorized)
2758 else if (!
Hidden && Categorized)
2760 else if (
Hidden && !Categorized)
2768 // Placeholder to ensure the array always has elements, since it's an
2769 // error to have a zero-sized array. Slice this off before returning.
2771 // Actual compiler build config feature list:
2772#if LLVM_IS_DEBUG_BUILD
2778#ifdef EXPENSIVE_CHECKS
2779 "+expensive-checks",
2781#if __has_feature(address_sanitizer)
2784#if __has_feature(dataflow_sanitizer)
2787#if __has_feature(hwaddress_sanitizer)
2790#if __has_feature(memory_sanitizer)
2793#if __has_feature(thread_sanitizer)
2796#if __has_feature(undefined_behavior_sanitizer)
2803// Utility function for printing the build config.
2805#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2806 OS <<
"Build config: ";
2812/// Utility function for printing version number.
2830 return Sub.OptionsMap;
2840 for (
auto &
I :
Sub.OptionsMap) {
2841 bool Unrelated =
true;
2842 for (
auto &Cat :
I.second->Categories) {
2843 if (Cat == &Category || Cat == &
CommonOptions->GenericCategory)
2854 for (
auto &
I :
Sub.OptionsMap) {
2855 bool Unrelated =
true;
2856 for (
auto &Cat :
I.second->Categories) {
2872 const char *Overview) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the StringMap class.
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
static StringRef OptionPrefix
static bool RequiresValue(const Option *O)
static int SubNameCompare(const std::pair< const char *, SubCommand * > *LHS, const std::pair< const char *, SubCommand * > *RHS)
static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad=DefaultPad)
static bool isPrefixedOrGrouping(const Option *O)
static bool shouldPrintOption(StringRef Name, StringRef Description, const Option &O)
static ManagedStatic< SubCommand > AllSubCommands
static Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const StringMap< Option * > &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
static bool parseDouble(Option &O, StringRef Arg, double &Value)
static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value)
static const size_t DefaultPad
static StringRef EmptyOption
static bool hasUTF8ByteOrderMark(ArrayRef< char > S)
static ManagedStatic< CommandLineParser > GlobalParser
static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const StringMap< Option * > &OptionsMap)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static size_t getOptionPrefixesSize()
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
static bool isQuote(char C)
static ManagedStatic< CommandLineCommonOptions > CommonOptions
static void initCommonOptions()
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static bool isWhitespace(char C)
static LLVM_REQUIRE_CONSTANT_INITIALIZATION ManagedStatic< SubCommand > TopLevelSubCommand
static size_t parseBackslash(StringRef Src, size_t I, SmallString< 128 > &Token)
Backslashes are interpreted in a rather complicated way in the Windows-style command line,...
static StringRef ArgPrefixLong
static void sortSubCommands(const SmallPtrSetImpl< SubCommand * > &SubMap, SmallVectorImpl< std::pair< const char *, SubCommand * > > &Subs)
#define PRINT_OPT_DIFF(T)
static bool isWhitespaceOrNull(char C)
static const size_t MaxOptWidth
static Option * LookupNearestOption(StringRef Arg, const StringMap< Option * > &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static void sortOpts(StringMap< Option * > &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool isGrouping(const Option *O)
#define LLVM_REQUIRE_CONSTANT_INITIALIZATION
LLVM_REQUIRE_CONSTANT_INITIALIZATION - Apply this to globals to ensure that they are constant initial...
#define LLVM_EXPORT_TEMPLATE
static void Help(ArrayRef< StringRef > CPUNames, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the SmallPtrSet class.
This file defines the SmallString class.
Defines the virtual file system interface vfs::FileSystem.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
size_t size() const
size - Get the array size.
Represents either an error or a value T.
std::error_code getError() const
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
size_t getBufferSize() const
const char * getBufferEnd() const
const char * getBufferStart() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
void assign(StringRef RHS)
Assign from a StringRef.
void append(StringRef RHS)
Append from a StringRef.
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
iterator find(StringRef Key)
StringMapIterBase< ValueTy, false > iterator
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
StringMapIterBase< ValueTy, true > const_iterator
StringRef - Represent a constant reference to a string, i.e.
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
static constexpr size_t npos
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr bool empty() const
empty - Check if the string is empty.
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
BumpPtrAllocator & getAllocator() const
StringRef save(const char *S)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM Value Representation.
Contains options that control response file expansion.
LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, vfs::FileSystem *FS=nullptr)
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.
StringRef getDescription() const
StringRef getName() const
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value, bool MultiArg=false)
void setMiscFlag(enum MiscFlags M)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
bool isDefaultOption() const
unsigned getMiscFlags() const
virtual void setDefault()=0
virtual void printOptionValue(size_t GlobalWidth, bool Force) const =0
static void printEnumValHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
unsigned getNumAdditionalVals() const
void removeArgument()
Unregisters this option from the CommandLine system.
static void printHelpStr(StringRef HelpStr, size_t Indent, size_t FirstLineIndentedBy)
virtual size_t getOptionWidth() const =0
StringRef getName() const
SubCommand(StringRef Name, StringRef Description="")
SmallVector< Option *, 4 > SinkOpts
static LLVM_ABI SubCommand & getTopLevel()
LLVM_ABI void unregisterSubCommand()
static LLVM_ABI SubCommand & getAll()
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
StringMap< Option * > OptionsMap
void printOptionInfo(const Option &O, size_t GlobalWidth) const
virtual StringRef getValueName() const
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
size_t getOptionWidth(const Option &O) const
void printOptionName(const Option &O, size_t GlobalWidth) const
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)
bool parse(Option &O, StringRef ArgName, StringRef Arg, DataType &V)
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.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
The virtual file system interface.
The result of a status operation.
LLVM_ABI bool equivalent(const Status &Other) const
LLVM_C_ABI void LLVMParseCommandLineOptions(int argc, const char *const *argv, const char *Overview)
This function parses the given arguments using the LLVM command line parser.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
constexpr size_t NameSize
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 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.
LLVM_ABI OptionCategory & getGeneralCategory()
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 StringMap< Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a StringMap to all registered named options (e.g.
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
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.
LLVM_ABI void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
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 void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
LLVM_ABI void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
LLVM_ABI void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
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.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
FunctionAddr VTableAddr Value
void initWithColorOptions()
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
LLVM_ABI bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
void initDebugCounterOptions()
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
LLVM_ABI bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
void initSignalsOptions()
void initStatisticOptions()
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void initRandomSeedOptions()
@ Sub
Subtraction of integers.
void initGraphWriterOptions()
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
@ Default
The result values are uniform if and only if all operands are uniform.