LLVM 24.0.0git
CommandLine.cpp
Go to the documentation of this file.
1//===-- CommandLine.cpp - Command line parser implementation --------------===//
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 could try
14// reading the library documentation located in docs/CommandLine.html
15//
16//===----------------------------------------------------------------------===//
17
19
20#include "DebugOptions.h"
21
22#include "llvm-c/Support.h"
23#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/Twine.h"
31#include "llvm/Config/config.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/Support/Error.h"
40#include "llvm/Support/Path.h"
46#include <cstdlib>
47#include <optional>
48#include <string>
49using namespace llvm;
50using namespace cl;
51
52#define DEBUG_TYPE "commandline"
53
54//===----------------------------------------------------------------------===//
55// Template instantiations and anchors.
56//
57namespace llvm {
58namespace cl {
72
73#if !(defined(LLVM_ENABLE_LLVM_EXPORT_ANNOTATIONS) && defined(_MSC_VER))
74// Only instantiate opt<std::string> when not building a Windows DLL. When
75// exporting opt<std::string>, MSVC implicitly exports symbols for
76// std::basic_string through transitive inheritance via std::string. These
77// symbols may appear in clients, leading to duplicate symbol conflicts.
79#endif
80
85
86} // namespace cl
87} // namespace llvm
88
89// Pin the vtables to this file.
90void GenericOptionValue::anchor() {}
91void OptionValue<boolOrDefault>::anchor() {}
92void OptionValue<std::string>::anchor() {}
93void Option::anchor() {}
97void parser<int>::anchor() {}
104void parser<float>::anchor() {}
106void parser<std::optional<std::string>>::anchor() {}
107void parser<char>::anchor() {}
109
110// These anchor functions instantiate opt<T> and reference its virtual
111// destructor to ensure MSVC exports the corresponding vtable and typeinfo when
112// building a Windows DLL. Without an explicit reference, MSVC may omit the
113// instantiation at link time even if it is marked DLL-export.
114void opt_bool_anchor() { opt<bool> anchor{""}; }
115void opt_char_anchor() { opt<char> anchor{""}; }
116void opt_int_anchor() { opt<int> anchor{""}; }
117void opt_unsigned_anchor() { opt<unsigned> anchor{""}; }
118
119//===----------------------------------------------------------------------===//
120
121const static size_t DefaultPad = 2;
122
123static StringRef ArgPrefix = "-";
126
127static size_t argPlusPrefixesSize(StringRef ArgName, size_t Pad = DefaultPad) {
128 size_t Len = ArgName.size();
129 if (Len == 1)
130 return Len + Pad + ArgPrefix.size() + ArgHelpPrefix.size();
131 return Len + Pad + ArgPrefixLong.size() + ArgHelpPrefix.size();
132}
133
134static SmallString<8> argPrefix(StringRef ArgName, size_t Pad = DefaultPad) {
136 for (size_t I = 0; I < Pad; ++I) {
137 Prefix.push_back(' ');
138 }
139 Prefix.append(ArgName.size() > 1 ? ArgPrefixLong : ArgPrefix);
140 return Prefix;
141}
142
143// Option predicates...
144static inline bool isGrouping(const Option *O) {
145 return O->getMiscFlags() & cl::Grouping;
146}
147static inline bool isPrefixedOrGrouping(const Option *O) {
148 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix ||
149 O->getFormattingFlag() == cl::AlwaysPrefix;
150}
151
153
154namespace {
155
156class PrintArg {
157 StringRef ArgName;
158 size_t Pad;
159public:
160 PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
161 friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
162};
163
164raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
165 OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
166 return OS;
167}
168
169class CommandLineParser {
170public:
171 // Globals for name and overview of program. Program name is not a string to
172 // avoid static ctor/dtor issues.
173 std::string ProgramName;
174 StringRef ProgramOverview;
175
176 // This collects additional help to be printed.
177 std::vector<StringRef> MoreHelp;
178
179 // This collects Options added with the cl::DefaultOption flag. Since they can
180 // be overridden, they are not added to the appropriate SubCommands until
181 // ParseCommandLineOptions actually runs.
182 SmallVector<Option*, 4> DefaultOptions;
183
184 // This collects the different option categories that have been registered.
185 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
186
187 // This collects the different subcommands that have been registered.
188 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
189
190 CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
191
193
194 bool ParseCommandLineOptions(int argc, const char *const *argv,
195 StringRef Overview, raw_ostream *Errs = nullptr,
196 vfs::FileSystem *VFS = nullptr,
197 bool LongOptionsUseDoubleDash = false);
198
199 void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) {
200 if (Opt.Subs.empty()) {
201 Action(SubCommand::getTopLevel());
202 return;
203 }
204 if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) {
205 for (auto *SC : RegisteredSubCommands)
206 Action(*SC);
207 Action(SubCommand::getAll());
208 return;
209 }
210 for (auto *SC : Opt.Subs) {
211 assert(SC != &SubCommand::getAll() &&
212 "SubCommand::getAll() should not be used with other subcommands");
213 Action(*SC);
214 }
215 }
216
217 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
218 if (Opt.hasArgStr())
219 return;
220 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
221 errs() << ProgramName << ": CommandLine Error: Option '" << Name
222 << "' registered more than once!\n";
223 report_fatal_error("inconsistency in registered CommandLine options");
224 }
225 }
226
227 void addLiteralOption(Option &Opt, StringRef Name) {
228 forEachSubCommand(
229 Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
230 }
231
232 void addOption(Option *O, SubCommand *SC) {
233 bool HadErrors = false;
234 if (O->hasArgStr()) {
235 // If it's a DefaultOption, check to make sure it isn't already there.
236 if (O->isDefaultOption() && SC->OptionsMap.contains(O->ArgStr))
237 return;
238
239 // Add argument to the argument map!
240 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
241 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
242 << "' registered more than once!\n";
243 HadErrors = true;
244 }
245 }
246
247 // Remember information about positional options.
248 if (O->getFormattingFlag() == cl::Positional)
249 SC->PositionalOpts.push_back(O);
250 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
251 if (SC->ConsumeAfterOpt) {
252 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
253 HadErrors = true;
254 }
255 SC->ConsumeAfterOpt = O;
256 }
257
258 // Fail hard if there were errors. These are strictly unrecoverable and
259 // indicate serious issues such as conflicting option names or an
260 // incorrectly
261 // linked LLVM distribution.
262 if (HadErrors)
263 report_fatal_error("inconsistency in registered CommandLine options");
264 }
265
266 void addOption(Option *O, bool ProcessDefaultOption = false) {
267 if (!ProcessDefaultOption && O->isDefaultOption()) {
268 DefaultOptions.push_back(O);
269 return;
270 }
271 forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &SC); });
272 }
273
274 void removeOption(Option *O, SubCommand *SC) {
275 SmallVector<StringRef, 16> OptionNames;
276 O->getExtraOptionNames(OptionNames);
277 if (O->hasArgStr())
278 OptionNames.push_back(O->ArgStr);
279
280 SubCommand &Sub = *SC;
281 for (auto Name : OptionNames) {
282 auto I = Sub.OptionsMap.find(Name);
283 // Re-query end() each iteration: a prior erase invalidates iterators
284 // (including a cached end()) under backward-shift deletion.
285 if (I != Sub.OptionsMap.end() && I->second == O)
286 Sub.OptionsMap.erase(I);
287 }
288
289 if (O->getFormattingFlag() == cl::Positional)
290 for (auto *Opt = Sub.PositionalOpts.begin();
291 Opt != Sub.PositionalOpts.end(); ++Opt) {
292 if (*Opt == O) {
293 Sub.PositionalOpts.erase(Opt);
294 break;
295 }
296 }
297 else if (O == Sub.ConsumeAfterOpt)
298 Sub.ConsumeAfterOpt = nullptr;
299 }
300
301 void removeOption(Option *O) {
302 forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &SC); });
303 }
304
305 bool hasOptions(const SubCommand &Sub) const {
306 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
307 nullptr != Sub.ConsumeAfterOpt);
308 }
309
310 bool hasOptions() const {
311 for (const auto *S : RegisteredSubCommands) {
312 if (hasOptions(*S))
313 return true;
314 }
315 return false;
316 }
317
318 bool hasNamedSubCommands() const {
319 for (const auto *S : RegisteredSubCommands)
320 if (!S->getName().empty())
321 return true;
322 return false;
323 }
324
325 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
326
327 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
328 SubCommand &Sub = *SC;
329 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
330 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
331 << "' registered more than once!\n";
332 report_fatal_error("inconsistency in registered CommandLine options");
333 }
334 Sub.OptionsMap.erase(O->ArgStr);
335 }
336
337 void updateArgStr(Option *O, StringRef NewName) {
338 forEachSubCommand(*O,
339 [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
340 }
341
342 void printOptionValues();
343
344 void registerCategory(OptionCategory *cat) {
345 assert(count_if(RegisteredOptionCategories,
346 [cat](const OptionCategory *Category) {
347 return cat->getName() == Category->getName();
348 }) == 0 &&
349 "Duplicate option categories");
350
351 RegisteredOptionCategories.insert(cat);
352 }
353
354 void registerSubCommand(SubCommand *sub) {
355 assert(count_if(RegisteredSubCommands,
356 [sub](const SubCommand *Sub) {
357 return (!sub->getName().empty()) &&
358 (Sub->getName() == sub->getName());
359 }) == 0 &&
360 "Duplicate subcommands");
361 RegisteredSubCommands.insert(sub);
362
363 // For all options that have been registered for all subcommands, add the
364 // option to this subcommand now.
366 "SubCommand::getAll() should not be registered");
367 for (auto &E : SubCommand::getAll().OptionsMap) {
368 Option *O = E.second;
369 if (O->isPositional() || O->isConsumeAfter() || O->hasArgStr())
370 addOption(O, sub);
371 else
372 addLiteralOption(*O, sub, E.first);
373 }
374 }
375
376 void unregisterSubCommand(SubCommand *sub) {
377 RegisteredSubCommands.erase(sub);
378 }
379
382 return make_range(RegisteredSubCommands.begin(),
383 RegisteredSubCommands.end());
384 }
385
386 void reset() {
387 ActiveSubCommand = nullptr;
388 ProgramName.clear();
389 ProgramOverview = StringRef();
390
391 MoreHelp.clear();
392 RegisteredOptionCategories.clear();
393
395 RegisteredSubCommands.clear();
396
399 registerSubCommand(&SubCommand::getTopLevel());
400
401 DefaultOptions.clear();
402 }
403
404private:
405 SubCommand *ActiveSubCommand = nullptr;
406
407 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
408 Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
409 bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
410 Option *Opt = LookupOption(Sub, Arg, Value);
411 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
412 return nullptr;
413 return Opt;
414 }
415 SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
416};
417
418} // namespace
419
420// The global parser is kept as a block-scope static so that option
421// constructors running during dynamic initialization of other translation
422// units never reference a namespace-scope global whose initialization order
423// is unspecified. The ManagedStatic keeps construction lazy and destruction
424// tied to llvm_shutdown().
425static CommandLineParser &globalParser() {
426 static ManagedStatic<CommandLineParser> GlobalParser;
427 return *GlobalParser;
428}
429
430template <typename T, T TrueVal, T FalseVal>
431static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value) {
432 // ProvideOption passes a null Arg for a bare -flag (treated as true) and an
433 // empty one for -flag= (treated as invalid).
434 if (!Arg.data() || Arg == "true" || Arg == "1") {
435 Value = TrueVal;
436 return false;
437 }
438
439 if (Arg == "false" || Arg == "0") {
440 Value = FalseVal;
441 return false;
442 }
443 return O.error("'" + Arg +
444 "' is invalid value for boolean argument! Try 0 or 1");
445}
446
448 globalParser().addLiteralOption(O, Name);
449}
450
452 globalParser().MoreHelp.push_back(Help);
453}
454
456 : NumOccurrences(0), Occurrences(OccurrencesFlag), Value(0),
457 HiddenFlag(Hidden), Formatting(NormalFormatting), Misc(0),
458 FullyInitialized(false), Position(0) {
459 Categories.push_back(&getGeneralCategory());
460}
461
463 globalParser().addOption(this);
464 FullyInitialized = true;
465}
466
467void Option::removeArgument() { globalParser().removeOption(this); }
468
470 if (FullyInitialized)
471 globalParser().updateArgStr(this, S);
472 assert(!S.starts_with("-") && "Option can't start with '-");
473 ArgStr = S;
474 if (ArgStr.size() == 1)
476}
477
479 assert(!Categories.empty() && "Categories cannot be empty.");
480 // Maintain backward compatibility by replacing the default GeneralCategory
481 // if it's still set. Otherwise, just add the new one. The GeneralCategory
482 // must be explicitly added if you want multiple categories that include it.
483 if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
484 Categories[0] = &C;
485 else if (!is_contained(Categories, &C))
486 Categories.push_back(&C);
487}
488
490 NumOccurrences = 0;
491 setDefault();
492 if (isDefaultOption())
494}
495
496void OptionCategory::registerCategory() {
497 globalParser().registerCategory(this);
498}
499
500// A special subcommand representing no subcommand. It is kept as a
501// block-scope static because it is referenced from cl::opt constructors,
502// which run dynamically in an arbitrary order across translation units;
503// block-scope statics are initialized on first use and therefore have no
504// initialization-order hazard.
506 static ManagedStatic<SubCommand> TopLevelSubCommand;
507 return *TopLevelSubCommand;
508}
509
510// A special subcommand that can be used to put an option into all subcommands.
512 static ManagedStatic<SubCommand> AllSubCommands;
513 return *AllSubCommands;
514}
515
517 globalParser().registerSubCommand(this);
518}
519
521 globalParser().unregisterSubCommand(this);
522}
523
525 PositionalOpts.clear();
526 OptionsMap.clear();
527
528 ConsumeAfterOpt = nullptr;
529}
530
531SubCommand::operator bool() const {
532 return (globalParser().getActiveSubCommand() == this);
533}
534
535//===----------------------------------------------------------------------===//
536// Basic, shared command line option processing machinery.
537//
538
539/// LookupOption - Lookup the option specified by the specified option on the
540/// command line. If there is a value specified (after an equal sign) return
541/// that as well. This assumes that leading dashes have already been stripped.
542Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
543 StringRef &Value) {
544 // Reject all dashes.
545 if (Arg.empty())
546 return nullptr;
548
549 size_t EqualPos = Arg.find('=');
550
551 // If we have an equals sign, remember the value.
552 if (EqualPos == StringRef::npos) {
553 // Look up the option.
554 return Sub.OptionsMap.lookup(Arg);
555 }
556
557 // If the argument before the = is a valid option name and the option allows
558 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
559 // failure by returning nullptr.
560 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
561 if (I == Sub.OptionsMap.end())
562 return nullptr;
563
564 auto *O = I->second;
565 if (O->getFormattingFlag() == cl::AlwaysPrefix)
566 return nullptr;
567
568 Value = Arg.substr(EqualPos + 1);
569 Arg = Arg.substr(0, EqualPos);
570 return I->second;
571}
572
573SubCommand *CommandLineParser::LookupSubCommand(StringRef Name,
574 std::string &NearestString) {
575 if (Name.empty())
576 return &SubCommand::getTopLevel();
577 // Find a subcommand with the edit distance == 1.
578 SubCommand *NearestMatch = nullptr;
579 for (auto *S : RegisteredSubCommands) {
580 assert(S != &SubCommand::getAll() &&
581 "SubCommand::getAll() is not expected in RegisteredSubCommands");
582 if (S->getName().empty())
583 continue;
584
585 if (S->getName() == Name)
586 return S;
587
588 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
589 NearestMatch = S;
590 }
591
592 if (NearestMatch)
593 NearestString = NearestMatch->getName();
594
595 return &SubCommand::getTopLevel();
596}
597
598/// LookupNearestOption - Lookup the closest match to the option specified by
599/// the specified option on the command line. If there is a value specified
600/// (after an equal sign) return that as well. This assumes that leading dashes
601/// have already been stripped.
603 const OptionsMapTy &OptionsMap,
604 std::string &NearestString) {
605 // Reject all dashes.
606 if (Arg.empty())
607 return nullptr;
608
609 // Split on any equal sign.
610 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
611 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
612 StringRef &RHS = SplitArg.second;
613
614 // Find the closest match.
615 Option *Best = nullptr;
616 unsigned BestDistance = 0;
617 for (const auto &[_, O] : OptionsMap) {
618 // Do not suggest really hidden options (not shown in any help).
619 if (O->getOptionHiddenFlag() == ReallyHidden)
620 continue;
621
622 SmallVector<StringRef, 16> OptionNames;
623 O->getExtraOptionNames(OptionNames);
624 if (O->hasArgStr())
625 OptionNames.push_back(O->ArgStr);
626
627 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
628 StringRef Flag = PermitValue ? LHS : Arg;
629 for (const auto &Name : OptionNames) {
630 unsigned Distance = StringRef(Name).edit_distance(
631 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
632 if (!Best || Distance < BestDistance) {
633 Best = O;
634 BestDistance = Distance;
635 if (RHS.empty() || !PermitValue)
636 NearestString = std::string(Name);
637 else
638 NearestString = (Twine(Name) + "=" + RHS).str();
639 }
640 }
641 }
642
643 return Best;
644}
645
646/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
647/// that does special handling of cl::CommaSeparated options.
648static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
649 StringRef ArgName, StringRef Value) {
650 // Check to see if this option accepts a comma separated list of values. If
651 // it does, we have to split up the value into multiple values.
652 if (Handler->getMiscFlags() & CommaSeparated) {
653 StringRef Val(Value);
654 StringRef::size_type Pos = Val.find(',');
655
656 while (Pos != StringRef::npos) {
657 // Process the portion before the comma.
658 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos)))
659 return true;
660 // Erase the portion before the comma, AND the comma.
661 Val = Val.substr(Pos + 1);
662 // Check for another comma.
663 Pos = Val.find(',');
664 }
665
666 Value = Val;
667 }
668
669 return Handler->addOccurrence(pos, ArgName, Value);
670}
671
672/// ProvideOption - For Value, this differentiates between an empty value ("")
673/// and a null value (StringRef()). The later is accepted for arguments that
674/// don't allow a value (-foo) the former is rejected (-foo=).
675static inline bool ProvideOption(Option *Handler, StringRef ArgName,
676 StringRef Value, int argc,
677 const char *const *argv, int &i) {
678 // Enforce value requirements
679 switch (Handler->getValueExpectedFlag()) {
680 case ValueRequired:
681 if (!Value.data()) { // No value specified?
682 // If no other argument or the option only supports prefix form, we
683 // cannot look at the next argument.
684 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
685 return Handler->error("requires a value!");
686 // Steal the next argument, like for '-o filename'
687 assert(argv && "null check");
688 Value = StringRef(argv[++i]);
689 }
690 break;
691 case ValueDisallowed:
692 if (Value.data())
693 return Handler->error("does not allow a value! '" + Twine(Value) +
694 "' specified.");
695 break;
696 case ValueOptional:
697 break;
698 }
699
700 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
701}
702
704 int Dummy = i;
705 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
706}
707
708// getOptionPred - Check to see if there are any options that satisfy the
709// specified predicate with names that are the prefixes in Name. This is
710// checked by progressively stripping characters off of the name, checking to
711// see if there options that satisfy the predicate. If we find one, return it,
712// otherwise return null.
713//
714static Option *getOptionPred(StringRef Name, size_t &Length,
715 bool (*Pred)(const Option *),
716 const OptionsMapTy &OptionsMap) {
717 auto OMI = OptionsMap.find(Name);
718 if (OMI != OptionsMap.end() && !Pred(OMI->second))
719 OMI = OptionsMap.end();
720
721 // Loop while we haven't found an option and Name still has at least two
722 // characters in it (so that the next iteration will not be the empty
723 // string.
724 while (OMI == OptionsMap.end() && Name.size() > 1) {
725 Name = Name.drop_back();
726 OMI = OptionsMap.find(Name);
727 if (OMI != OptionsMap.end() && !Pred(OMI->second))
728 OMI = OptionsMap.end();
729 }
730
731 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
732 Length = Name.size();
733 return OMI->second; // Found one!
734 }
735 return nullptr; // No option found!
736}
737
738/// HandlePrefixedOrGroupedOption - The specified argument string (which started
739/// with at least one '-') does not fully match an available option. Check to
740/// see if this is a prefix or grouped option. If so, split arg into output an
741/// Arg/Value pair and return the Option to parse it with.
743 bool &ErrorParsing,
744 const OptionsMapTy &OptionsMap) {
745 if (Arg.size() == 1)
746 return nullptr;
747
748 // Do the lookup!
749 size_t Length = 0;
750 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
751 if (!PGOpt)
752 return nullptr;
753
754 do {
755 StringRef MaybeValue =
756 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
757 Arg = Arg.substr(0, Length);
758 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
759
760 // cl::Prefix options do not preserve '=' when used separately.
761 // The behavior for them with grouped options should be the same.
762 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
763 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
764 Value = MaybeValue;
765 return PGOpt;
766 }
767
768 if (MaybeValue[0] == '=') {
769 Value = MaybeValue.substr(1);
770 return PGOpt;
771 }
772
773 // This must be a grouped option.
774 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
775
776 // Grouping options inside a group can't have values.
777 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
778 ErrorParsing |= PGOpt->error("may not occur within a group!");
779 return nullptr;
780 }
781
782 // Because the value for the option is not required, we don't need to pass
783 // argc/argv in.
784 int Dummy = 0;
785 ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
786
787 // Get the next grouping option.
788 Arg = MaybeValue;
789 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
790 } while (PGOpt);
791
792 // We could not find a grouping option in the remainder of Arg.
793 return nullptr;
794}
795
796static bool RequiresValue(const Option *O) {
797 return O->getNumOccurrencesFlag() == cl::Required ||
798 O->getNumOccurrencesFlag() == cl::OneOrMore;
799}
800
801static bool EatsUnboundedNumberOfValues(const Option *O) {
802 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
803 O->getNumOccurrencesFlag() == cl::OneOrMore;
804}
805
806static bool isWhitespace(char C) {
807 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
808}
809
810static bool isWhitespaceOrNull(char C) {
811 return isWhitespace(C) || C == '\0';
812}
813
814static bool isQuote(char C) { return C == '\"' || C == '\''; }
815
818 bool MarkEOLs) {
819 SmallString<128> Token;
820 bool InToken = false;
821 for (size_t I = 0, E = Src.size(); I != E; ++I) {
822 // Consume runs of whitespace.
823 if (!InToken) {
824 while (I != E && isWhitespace(Src[I])) {
825 // Mark the end of lines in response files.
826 if (MarkEOLs && Src[I] == '\n')
827 NewArgv.push_back(nullptr);
828 ++I;
829 }
830 if (I == E)
831 break;
832 InToken = true;
833 }
834
835 char C = Src[I];
836
837 // Backslash escapes the next character.
838 if (I + 1 < E && C == '\\') {
839 ++I; // Skip the escape.
840 Token.push_back(Src[I]);
841 continue;
842 }
843
844 // Consume a quoted string.
845 if (isQuote(C)) {
846 ++I;
847 while (I != E && Src[I] != C) {
848 // Backslash escapes the next character.
849 if (Src[I] == '\\' && I + 1 != E)
850 ++I;
851 Token.push_back(Src[I]);
852 ++I;
853 }
854 if (I == E)
855 break;
856 continue;
857 }
858
859 // End the token if this is whitespace.
860 if (isWhitespace(C)) {
861 NewArgv.push_back(Saver.save(Token.str()).data());
862 // Mark the end of lines in response files.
863 if (MarkEOLs && C == '\n')
864 NewArgv.push_back(nullptr);
865 Token.clear();
866 InToken = false;
867 continue;
868 }
869
870 // This is a normal character. Append it.
871 Token.push_back(C);
872 }
873
874 // Append the last token after hitting EOF with no whitespace.
875 if (InToken)
876 NewArgv.push_back(Saver.save(Token.str()).data());
877}
878
879/// Backslashes are interpreted in a rather complicated way in the Windows-style
880/// command line, because backslashes are used both to separate path and to
881/// escape double quote. This method consumes runs of backslashes as well as the
882/// following double quote if it's escaped.
883///
884/// * If an even number of backslashes is followed by a double quote, one
885/// backslash is output for every pair of backslashes, and the last double
886/// quote remains unconsumed. The double quote will later be interpreted as
887/// the start or end of a quoted string in the main loop outside of this
888/// function.
889///
890/// * If an odd number of backslashes is followed by a double quote, one
891/// backslash is output for every pair of backslashes, and a double quote is
892/// output for the last pair of backslash-double quote. The double quote is
893/// consumed in this case.
894///
895/// * Otherwise, backslashes are interpreted literally.
896static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
897 size_t E = Src.size();
898 int BackslashCount = 0;
899 // Skip the backslashes.
900 do {
901 ++I;
902 ++BackslashCount;
903 } while (I != E && Src[I] == '\\');
904
905 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
906 if (FollowedByDoubleQuote) {
907 Token.append(BackslashCount / 2, '\\');
908 if (BackslashCount % 2 == 0)
909 return I - 1;
910 Token.push_back('"');
911 return I;
912 }
913 Token.append(BackslashCount, '\\');
914 return I - 1;
915}
916
917// Windows treats whitespace, double quotes, and backslashes specially, except
918// when parsing the first token of a full command line, in which case
919// backslashes are not special.
920static bool isWindowsSpecialChar(char C) {
921 return isWhitespaceOrNull(C) || C == '\\' || C == '\"';
922}
924 return isWhitespaceOrNull(C) || C == '\"';
925}
926
927// Windows tokenization implementation. The implementation is designed to be
928// inlined and specialized for the two user entry points.
930 StringRef Src, StringSaver &Saver, function_ref<void(StringRef)> AddToken,
931 bool AlwaysCopy, function_ref<void()> MarkEOL, bool InitialCommandName) {
932 SmallString<128> Token;
933
934 // Sometimes, this function will be handling a full command line including an
935 // executable pathname at the start. In that situation, the initial pathname
936 // needs different handling from the following arguments, because when
937 // CreateProcess or cmd.exe scans the pathname, it doesn't treat \ as
938 // escaping the quote character, whereas when libc scans the rest of the
939 // command line, it does.
940 bool CommandName = InitialCommandName;
941
942 // Try to do as much work inside the state machine as possible.
943 enum { INIT, UNQUOTED, QUOTED } State = INIT;
944
945 for (size_t I = 0, E = Src.size(); I < E; ++I) {
946 switch (State) {
947 case INIT: {
948 assert(Token.empty() && "token should be empty in initial state");
949 // Eat whitespace before a token.
950 while (I < E && isWhitespaceOrNull(Src[I])) {
951 if (Src[I] == '\n')
952 MarkEOL();
953 ++I;
954 }
955 // Stop if this was trailing whitespace.
956 if (I >= E)
957 break;
958 size_t Start = I;
959 if (CommandName) {
960 while (I < E && !isWindowsSpecialCharInCommandName(Src[I]))
961 ++I;
962 } else {
963 while (I < E && !isWindowsSpecialChar(Src[I]))
964 ++I;
965 }
966 StringRef NormalChars = Src.slice(Start, I);
967 if (I >= E || isWhitespaceOrNull(Src[I])) {
968 // No special characters: slice out the substring and start the next
969 // token. Copy the string if the caller asks us to.
970 AddToken(AlwaysCopy ? Saver.save(NormalChars) : NormalChars);
971 if (I < E && Src[I] == '\n') {
972 MarkEOL();
973 CommandName = InitialCommandName;
974 } else {
975 CommandName = false;
976 }
977 } else if (Src[I] == '\"') {
978 Token += NormalChars;
979 State = QUOTED;
980 } else if (Src[I] == '\\') {
981 assert(!CommandName && "or else we'd have treated it as a normal char");
982 Token += NormalChars;
983 I = parseBackslash(Src, I, Token);
984 State = UNQUOTED;
985 } else {
986 llvm_unreachable("unexpected special character");
987 }
988 break;
989 }
990
991 case UNQUOTED:
992 if (isWhitespaceOrNull(Src[I])) {
993 // Whitespace means the end of the token. If we are in this state, the
994 // token must have contained a special character, so we must copy the
995 // token.
996 AddToken(Saver.save(Token.str()));
997 Token.clear();
998 if (Src[I] == '\n') {
999 CommandName = InitialCommandName;
1000 MarkEOL();
1001 } else {
1002 CommandName = false;
1003 }
1004 State = INIT;
1005 } else if (Src[I] == '\"') {
1006 State = QUOTED;
1007 } else if (Src[I] == '\\' && !CommandName) {
1008 I = parseBackslash(Src, I, Token);
1009 } else {
1010 Token.push_back(Src[I]);
1011 }
1012 break;
1013
1014 case QUOTED:
1015 if (Src[I] == '\"') {
1016 if (I < (E - 1) && Src[I + 1] == '"') {
1017 // Consecutive double-quotes inside a quoted string implies one
1018 // double-quote.
1019 Token.push_back('"');
1020 ++I;
1021 } else {
1022 // Otherwise, end the quoted portion and return to the unquoted state.
1023 State = UNQUOTED;
1024 }
1025 } else if (Src[I] == '\\' && !CommandName) {
1026 I = parseBackslash(Src, I, Token);
1027 } else {
1028 Token.push_back(Src[I]);
1029 }
1030 break;
1031 }
1032 }
1033
1034 if (State != INIT)
1035 AddToken(Saver.save(Token.str()));
1036}
1037
1040 bool MarkEOLs) {
1041 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1042 auto OnEOL = [&]() {
1043 if (MarkEOLs)
1044 NewArgv.push_back(nullptr);
1045 };
1046 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1047 /*AlwaysCopy=*/true, OnEOL, false);
1048}
1049
1051 SmallVectorImpl<StringRef> &NewArgv) {
1052 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok); };
1053 auto OnEOL = []() {};
1054 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken, /*AlwaysCopy=*/false,
1055 OnEOL, false);
1056}
1057
1060 bool MarkEOLs) {
1061 auto AddToken = [&](StringRef Tok) { NewArgv.push_back(Tok.data()); };
1062 auto OnEOL = [&]() {
1063 if (MarkEOLs)
1064 NewArgv.push_back(nullptr);
1065 };
1066 tokenizeWindowsCommandLineImpl(Src, Saver, AddToken,
1067 /*AlwaysCopy=*/true, OnEOL, true);
1068}
1069
1072 bool MarkEOLs) {
1073 for (const char *Cur = Source.begin(); Cur != Source.end();) {
1074 SmallString<128> Line;
1075 // Check for comment line.
1076 if (isWhitespace(*Cur)) {
1077 while (Cur != Source.end() && isWhitespace(*Cur))
1078 ++Cur;
1079 continue;
1080 }
1081 if (*Cur == '#') {
1082 while (Cur != Source.end() && *Cur != '\n')
1083 ++Cur;
1084 continue;
1085 }
1086 // Find end of the current line.
1087 const char *Start = Cur;
1088 for (const char *End = Source.end(); Cur != End; ++Cur) {
1089 if (*Cur == '\\') {
1090 if (Cur + 1 != End) {
1091 ++Cur;
1092 if (*Cur == '\n' ||
1093 (*Cur == '\r' && (Cur + 1 != End) && Cur[1] == '\n')) {
1094 Line.append(Start, Cur - 1);
1095 if (*Cur == '\r')
1096 ++Cur;
1097 Start = Cur + 1;
1098 }
1099 }
1100 } else if (*Cur == '\n')
1101 break;
1102 }
1103 // Tokenize line.
1104 Line.append(Start, Cur);
1105 cl::TokenizeGNUCommandLine(Line, Saver, NewArgv, MarkEOLs);
1106 }
1107}
1108
1109// It is called byte order marker but the UTF-8 BOM is actually not affected
1110// by the host system's endianness.
1112 return (S.size() >= 3 && S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
1113}
1114
1115// Substitute <CFGDIR> with the file's base path.
1116static void ExpandBasePaths(StringRef BasePath, StringSaver &Saver,
1117 const char *&Arg) {
1118 assert(sys::path::is_absolute(BasePath));
1119 constexpr StringLiteral Token("<CFGDIR>");
1120 const StringRef ArgString(Arg);
1121
1122 SmallString<128> ResponseFile;
1123 StringRef::size_type StartPos = 0;
1124 for (StringRef::size_type TokenPos = ArgString.find(Token);
1125 TokenPos != StringRef::npos;
1126 TokenPos = ArgString.find(Token, StartPos)) {
1127 // Token may appear more than once per arg (e.g. comma-separated linker
1128 // args). Support by using path-append on any subsequent appearances.
1129 const StringRef LHS = ArgString.substr(StartPos, TokenPos - StartPos);
1130 if (ResponseFile.empty())
1131 ResponseFile = LHS;
1132 else
1133 llvm::sys::path::append(ResponseFile, LHS);
1134 ResponseFile.append(BasePath);
1135 StartPos = TokenPos + Token.size();
1136 }
1137
1138 if (!ResponseFile.empty()) {
1139 // Path-append the remaining arg substring if at least one token appeared.
1140 const StringRef Remaining = ArgString.substr(StartPos);
1141 if (!Remaining.empty())
1142 llvm::sys::path::append(ResponseFile, Remaining);
1143 Arg = Saver.save(ResponseFile.str()).data();
1144 }
1145}
1146
1147// FName must be an absolute path.
1148Error ExpansionContext::expandResponseFile(
1149 StringRef FName, SmallVectorImpl<const char *> &NewArgv) {
1151 llvm::ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
1152 FS->getBufferForFile(FName);
1153 if (!MemBufOrErr) {
1154 std::error_code EC = MemBufOrErr.getError();
1155 return llvm::createStringError(EC, Twine("cannot not open file '") + FName +
1156 "': " + EC.message());
1157 }
1158 MemoryBuffer &MemBuf = *MemBufOrErr.get();
1159 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
1160
1161 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
1162 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
1163 std::string UTF8Buf;
1164 if (hasUTF16ByteOrderMark(BufRef)) {
1165 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
1166 return llvm::createStringError(std::errc::illegal_byte_sequence,
1167 "Could not convert UTF16 to UTF8");
1168 Str = StringRef(UTF8Buf);
1169 }
1170 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
1171 // these bytes before parsing.
1172 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
1173 else if (hasUTF8ByteOrderMark(BufRef))
1174 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
1175
1176 // Tokenize the contents into NewArgv.
1177 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
1178
1179 // Expanded file content may require additional transformations, like using
1180 // absolute paths instead of relative in '@file' constructs or expanding
1181 // macros.
1182 if (!RelativeNames && !InConfigFile)
1183 return Error::success();
1184
1185 StringRef BasePath = llvm::sys::path::parent_path(FName);
1186 for (const char *&Arg : NewArgv) {
1187 if (!Arg)
1188 continue;
1189
1190 // Substitute <CFGDIR> with the file's base path.
1191 if (InConfigFile)
1192 ExpandBasePaths(BasePath, Saver, Arg);
1193
1194 // Discover the case, when argument should be transformed into '@file' and
1195 // evaluate 'file' for it.
1196 StringRef ArgStr(Arg);
1197 StringRef FileName;
1198 bool ConfigInclusion = false;
1199 if (ArgStr.consume_front("@")) {
1200 FileName = ArgStr;
1201 if (!llvm::sys::path::is_relative(FileName))
1202 continue;
1203 } else if (ArgStr.consume_front("--config=")) {
1204 FileName = ArgStr;
1205 ConfigInclusion = true;
1206 } else {
1207 continue;
1208 }
1209
1210 // Update expansion construct.
1211 SmallString<128> ResponseFile;
1212 ResponseFile.push_back('@');
1213 if (ConfigInclusion && !llvm::sys::path::has_parent_path(FileName)) {
1214 SmallString<128> FilePath;
1215 if (!findConfigFile(FileName, FilePath))
1216 return createStringError(
1217 std::make_error_code(std::errc::no_such_file_or_directory),
1218 "cannot not find configuration file: " + FileName);
1219 ResponseFile.append(FilePath);
1220 } else {
1221 ResponseFile.append(BasePath);
1222 llvm::sys::path::append(ResponseFile, FileName);
1223 }
1224 Arg = Saver.save(ResponseFile.str()).data();
1225 }
1226 return Error::success();
1227}
1228
1229/// Expand response files on a command line recursively using the given
1230/// StringSaver and tokenization strategy.
1233 struct ResponseFileRecord {
1234 std::string File;
1235 size_t End;
1236 };
1237
1238 // To detect recursive response files, we maintain a stack of files and the
1239 // position of the last argument in the file. This position is updated
1240 // dynamically as we recursively expand files.
1242
1243 // Push a dummy entry that represents the initial command line, removing
1244 // the need to check for an empty list.
1245 FileStack.push_back({"", Argv.size()});
1246
1247 // Don't cache Argv.size() because it can change.
1248 for (unsigned I = 0; I != Argv.size();) {
1249 while (I == FileStack.back().End) {
1250 // Passing the end of a file's argument list, so we can remove it from the
1251 // stack.
1252 FileStack.pop_back();
1253 }
1254
1255 const char *Arg = Argv[I];
1256 // Check if it is an EOL marker
1257 if (Arg == nullptr) {
1258 ++I;
1259 continue;
1260 }
1261
1262 if (Arg[0] != '@') {
1263 ++I;
1264 continue;
1265 }
1266
1267 const char *FName = Arg + 1;
1268 // Note that CurrentDir is only used for top-level rsp files, the rest will
1269 // always have an absolute path deduced from the containing file.
1270 SmallString<128> CurrDir;
1271 if (llvm::sys::path::is_relative(FName)) {
1272 if (CurrentDir.empty()) {
1273 if (auto CWD = FS->getCurrentWorkingDirectory()) {
1274 CurrDir = *CWD;
1275 } else {
1276 return createStringError(
1277 CWD.getError(), Twine("cannot get absolute path for: ") + FName);
1278 }
1279 } else {
1280 CurrDir = CurrentDir;
1281 }
1282 llvm::sys::path::append(CurrDir, FName);
1283 FName = CurrDir.c_str();
1284 }
1285
1286 ErrorOr<llvm::vfs::Status> Res = FS->status(FName);
1287 if (!Res || !Res->exists()) {
1288 std::error_code EC = Res.getError();
1289 if (!InConfigFile) {
1290 // If the specified file does not exist, leave '@file' unexpanded, as
1291 // libiberty does.
1292 if (!EC || EC == llvm::errc::no_such_file_or_directory) {
1293 ++I;
1294 continue;
1295 }
1296 }
1297 if (!EC)
1299 return createStringError(EC, Twine("cannot not open file '") + FName +
1300 "': " + EC.message());
1301 }
1302 const llvm::vfs::Status &FileStatus = Res.get();
1303
1304 auto IsEquivalent =
1305 [FileStatus, this](const ResponseFileRecord &RFile) -> ErrorOr<bool> {
1306 ErrorOr<llvm::vfs::Status> RHS = FS->status(RFile.File);
1307 if (!RHS)
1308 return RHS.getError();
1309 return FileStatus.equivalent(*RHS);
1310 };
1311
1312 // Check for recursive response files.
1313 for (const auto &F : drop_begin(FileStack)) {
1314 if (ErrorOr<bool> R = IsEquivalent(F)) {
1315 if (R.get())
1316 return createStringError(
1317 R.getError(), Twine("recursive expansion of: '") + F.File + "'");
1318 } else {
1319 return createStringError(R.getError(),
1320 Twine("cannot open file: ") + F.File);
1321 }
1322 }
1323
1324 // Replace this response file argument with the tokenization of its
1325 // contents. Nested response files are expanded in subsequent iterations.
1326 SmallVector<const char *, 0> ExpandedArgv;
1327 if (Error Err = expandResponseFile(FName, ExpandedArgv))
1328 return Err;
1329
1330 for (ResponseFileRecord &Record : FileStack) {
1331 // Increase the end of all active records by the number of newly expanded
1332 // arguments, minus the response file itself.
1333 Record.End += ExpandedArgv.size() - 1;
1334 }
1335
1336 FileStack.push_back({FName, I + ExpandedArgv.size()});
1337 Argv.erase(Argv.begin() + I);
1338 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
1339 }
1340
1341 // If successful, the top of the file stack will mark the end of the Argv
1342 // stream. A failure here indicates a bug in the stack popping logic above.
1343 // Note that FileStack may have more than one element at this point because we
1344 // don't have a chance to pop the stack when encountering recursive files at
1345 // the end of the stream, so seeing that doesn't indicate a bug.
1346 assert(FileStack.size() > 0 && Argv.size() == FileStack.back().End);
1347 return Error::success();
1348}
1349
1350bool cl::expandResponseFiles(int Argc, const char *const *Argv,
1351 const char *EnvVar, StringSaver &Saver,
1353#ifdef _WIN32
1354 auto Tokenize = cl::TokenizeWindowsCommandLine;
1355#else
1356 auto Tokenize = cl::TokenizeGNUCommandLine;
1357#endif
1358 // The environment variable specifies initial options.
1359 if (EnvVar)
1360 if (std::optional<std::string> EnvValue = sys::Process::GetEnv(EnvVar))
1361 Tokenize(*EnvValue, Saver, NewArgv, /*MarkEOLs=*/false);
1362
1363 // Command line options can override the environment variable.
1364 NewArgv.append(Argv + 1, Argv + Argc);
1365 ExpansionContext ECtx(Saver.getAllocator(), Tokenize);
1366 if (Error Err = ECtx.expandResponseFiles(NewArgv)) {
1367 errs() << toString(std::move(Err)) << '\n';
1368 return false;
1369 }
1370 return true;
1371}
1372
1375 ExpansionContext ECtx(Saver.getAllocator(), Tokenizer);
1376 if (Error Err = ECtx.expandResponseFiles(Argv)) {
1377 errs() << toString(std::move(Err)) << '\n';
1378 return false;
1379 }
1380 return true;
1381}
1382
1384 vfs::FileSystem *FS)
1385 : Saver(A), Tokenizer(T), FS(FS ? FS : vfs::getRealFileSystem().get()) {}
1386
1388 SmallVectorImpl<char> &FilePath) {
1389 SmallString<128> CfgFilePath;
1390 const auto FileExists = [this](SmallString<128> Path) -> bool {
1391 auto Status = FS->status(Path);
1392 return Status &&
1394 };
1395
1396 // If file name contains directory separator, treat it as a path to
1397 // configuration file.
1398 if (llvm::sys::path::has_parent_path(FileName)) {
1399 CfgFilePath = FileName;
1400 if (llvm::sys::path::is_relative(FileName) && FS->makeAbsolute(CfgFilePath))
1401 return false;
1402 if (!FileExists(CfgFilePath))
1403 return false;
1404 FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1405 return true;
1406 }
1407
1408 // Look for the file in search directories.
1409 for (const StringRef &Dir : SearchDirs) {
1410 if (Dir.empty())
1411 continue;
1412 CfgFilePath.assign(Dir);
1413 llvm::sys::path::append(CfgFilePath, FileName);
1414 llvm::sys::path::native(CfgFilePath);
1415 if (FileExists(CfgFilePath)) {
1416 FilePath.assign(CfgFilePath.begin(), CfgFilePath.end());
1417 return true;
1418 }
1419 }
1420
1421 return false;
1422}
1423
1426 SmallString<128> AbsPath;
1427 if (sys::path::is_relative(CfgFile)) {
1428 AbsPath.assign(CfgFile);
1429 if (std::error_code EC = FS->makeAbsolute(AbsPath))
1431 EC, Twine("cannot get absolute path for " + CfgFile));
1432 CfgFile = AbsPath.str();
1433 }
1434 InConfigFile = true;
1435 RelativeNames = true;
1436 if (Error Err = expandResponseFile(CfgFile, Argv))
1437 return Err;
1438 return expandResponseFiles(Argv);
1439}
1440
1441static void initCommonOptions();
1442bool cl::ParseCommandLineOptions(int argc, const char *const *argv,
1443 StringRef Overview, raw_ostream *Errs,
1444 vfs::FileSystem *VFS, const char *EnvVar,
1445 bool LongOptionsUseDoubleDash) {
1449 StringSaver Saver(A);
1450 NewArgv.push_back(argv[0]);
1451
1452 // Parse options from environment variable.
1453 if (EnvVar) {
1454 if (std::optional<std::string> EnvValue =
1456 TokenizeGNUCommandLine(*EnvValue, Saver, NewArgv);
1457 }
1458
1459 // Append options from command line.
1460 for (int I = 1; I < argc; ++I)
1461 NewArgv.push_back(argv[I]);
1462 int NewArgc = static_cast<int>(NewArgv.size());
1463
1464 // Parse all options.
1465 return globalParser().ParseCommandLineOptions(
1466 NewArgc, &NewArgv[0], Overview, Errs, VFS, LongOptionsUseDoubleDash);
1467}
1468
1469/// Reset all options at least once, so that we can parse different options.
1470void CommandLineParser::ResetAllOptionOccurrences() {
1471 // Reset all option values to look like they have never been seen before.
1472 // Options might be reset twice (they can be reference in both OptionsMap
1473 // and one of the other members), but that does not harm.
1474 for (auto *SC : RegisteredSubCommands) {
1475 // reset() removes default options from OptionsMap (via removeArgument), so
1476 // collect the options first to avoid invalidating the map iterator.
1478 Opts.reserve(SC->OptionsMap.size());
1479 for (auto &O : SC->OptionsMap)
1480 Opts.push_back(O.second);
1481 for (Option *O : Opts)
1482 O->reset();
1483 for (Option *O : SC->PositionalOpts)
1484 O->reset();
1485 if (SC->ConsumeAfterOpt)
1486 SC->ConsumeAfterOpt->reset();
1487 }
1488}
1489
1490bool CommandLineParser::ParseCommandLineOptions(
1491 int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs,
1492 vfs::FileSystem *VFS, bool LongOptionsUseDoubleDash) {
1493 assert(hasOptions() && "No options specified!");
1494
1495 ProgramOverview = Overview;
1496 bool IgnoreErrors = Errs;
1497 if (!Errs)
1498 Errs = &errs();
1499 if (!VFS)
1500 VFS = vfs::getRealFileSystem().get();
1501 bool ErrorParsing = false;
1502
1503 // Expand response files.
1504 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1506#ifdef _WIN32
1507 auto Tokenize = cl::TokenizeWindowsCommandLine;
1508#else
1509 auto Tokenize = cl::TokenizeGNUCommandLine;
1510#endif
1511 ExpansionContext ECtx(A, Tokenize, VFS);
1512 if (Error Err = ECtx.expandResponseFiles(newArgv)) {
1513 *Errs << toString(std::move(Err)) << '\n';
1514 return false;
1515 }
1516 argv = &newArgv[0];
1517 argc = static_cast<int>(newArgv.size());
1518
1519 // Copy the program name into ProgName, making sure not to overflow it.
1520 ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1521
1522 // Check out the positional arguments to collect information about them.
1523 unsigned NumPositionalRequired = 0;
1524
1525 // Determine whether or not there are an unlimited number of positionals
1526 bool HasUnlimitedPositionals = false;
1527
1528 int FirstArg = 1;
1529 SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1530 std::string NearestSubCommandString;
1531 bool MaybeNamedSubCommand =
1532 argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands();
1533 if (MaybeNamedSubCommand) {
1534 // If the first argument specifies a valid subcommand, start processing
1535 // options from the second argument.
1536 ChosenSubCommand =
1537 LookupSubCommand(StringRef(argv[FirstArg]), NearestSubCommandString);
1538 if (ChosenSubCommand != &SubCommand::getTopLevel())
1539 FirstArg = 2;
1540 }
1541 globalParser().ActiveSubCommand = ChosenSubCommand;
1542
1543 assert(ChosenSubCommand);
1544 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1545 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1546 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1547
1548 for (auto *O: DefaultOptions) {
1549 addOption(O, true);
1550 }
1551
1552 if (ConsumeAfterOpt) {
1553 assert(PositionalOpts.size() > 0 &&
1554 "Cannot specify cl::ConsumeAfter without a positional argument!");
1555 }
1556 if (!PositionalOpts.empty()) {
1557
1558 // Calculate how many positional values are _required_.
1559 bool UnboundedFound = false;
1560 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1561 Option *Opt = PositionalOpts[i];
1562 if (RequiresValue(Opt))
1563 ++NumPositionalRequired;
1564 else if (ConsumeAfterOpt) {
1565 // ConsumeAfter cannot be combined with "optional" positional options
1566 // unless there is only one positional argument...
1567 if (PositionalOpts.size() > 1) {
1568 if (!IgnoreErrors)
1569 Opt->error("error - this positional option will never be matched, "
1570 "because it does not Require a value, and a "
1571 "cl::ConsumeAfter option is active!");
1572 ErrorParsing = true;
1573 }
1574 } else if (UnboundedFound && !Opt->hasArgStr()) {
1575 // This option does not "require" a value... Make sure this option is
1576 // not specified after an option that eats all extra arguments, or this
1577 // one will never get any!
1578 //
1579 if (!IgnoreErrors)
1580 Opt->error("error - option can never match, because "
1581 "another positional argument will match an "
1582 "unbounded number of values, and this option"
1583 " does not require a value!");
1584 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1585 << "' is all messed up!\n";
1586 *Errs << PositionalOpts.size();
1587 ErrorParsing = true;
1588 }
1589 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1590 }
1591 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1592 }
1593
1594 // PositionalVals - A vector of "positional" arguments we accumulate into
1595 // the process at the end.
1596 //
1598
1599 // If the program has named positional arguments, and the name has been run
1600 // across, keep track of which positional argument was named. Otherwise put
1601 // the positional args into the PositionalVals list...
1602 Option *ActivePositionalArg = nullptr;
1603
1604 // Loop over all of the arguments... processing them.
1605 bool DashDashFound = false; // Have we read '--'?
1606 for (int i = FirstArg; i < argc; ++i) {
1607 Option *Handler = nullptr;
1608 std::string NearestHandlerString;
1609 StringRef Value;
1610 StringRef ArgName = "";
1611 bool HaveDoubleDash = false;
1612
1613 // Check to see if this is a positional argument. This argument is
1614 // considered to be positional if it doesn't start with '-', if it is "-"
1615 // itself, or if we have seen "--" already.
1616 //
1617 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1618 // Positional argument!
1619 if (ActivePositionalArg) {
1620 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1621 continue; // We are done!
1622 }
1623
1624 if (!PositionalOpts.empty()) {
1625 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1626
1627 // All of the positional arguments have been fulfulled, give the rest to
1628 // the consume after option... if it's specified...
1629 //
1630 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1631 for (++i; i < argc; ++i)
1632 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1633 break; // Handle outside of the argument processing loop...
1634 }
1635
1636 // Delay processing positional arguments until the end...
1637 continue;
1638 }
1639 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1640 !DashDashFound) {
1641 DashDashFound = true; // This is the mythical "--"?
1642 continue; // Don't try to process it as an argument itself.
1643 } else if (ActivePositionalArg &&
1644 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1645 // If there is a positional argument eating options, check to see if this
1646 // option is another positional argument. If so, treat it as an argument,
1647 // otherwise feed it to the eating positional.
1648 ArgName = StringRef(argv[i] + 1);
1649 // Eat second dash.
1650 if (ArgName.consume_front("-"))
1651 HaveDoubleDash = true;
1652
1653 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1654 LongOptionsUseDoubleDash, HaveDoubleDash);
1655 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1656 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1657 continue; // We are done!
1658 }
1659 } else { // We start with a '-', must be an argument.
1660 ArgName = StringRef(argv[i] + 1);
1661 // Eat second dash.
1662 if (ArgName.consume_front("-"))
1663 HaveDoubleDash = true;
1664
1665 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1666 LongOptionsUseDoubleDash, HaveDoubleDash);
1667
1668 // If Handler is not found in a specialized subcommand, look up handler
1669 // in the top-level subcommand.
1670 // cl::opt without cl::sub belongs to top-level subcommand.
1671 if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel())
1672 Handler = LookupLongOption(SubCommand::getTopLevel(), ArgName, Value,
1673 LongOptionsUseDoubleDash, HaveDoubleDash);
1674
1675 // Check to see if this "option" is really a prefixed or grouped argument.
1676 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1677 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1678 OptionsMap);
1679
1680 // Otherwise, look for the closest available option to report to the user
1681 // in the upcoming error.
1682 if (!Handler)
1683 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1684 }
1685
1686 if (!Handler) {
1687 auto ReportUnknownArgument = [&](bool IsArg,
1688 StringRef NearestArgumentName) {
1689 *Errs << ProgramName << ": Unknown "
1690 << (IsArg ? "command line argument" : "subcommand") << " '"
1691 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
1692
1693 if (NearestArgumentName.empty())
1694 return;
1695
1696 *Errs << ProgramName << ": Did you mean '";
1697 if (IsArg)
1698 *Errs << PrintArg(NearestArgumentName, 0);
1699 else
1700 *Errs << NearestArgumentName;
1701 *Errs << "'?\n";
1702 };
1703
1704 if (i > 1 || !MaybeNamedSubCommand)
1705 ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString);
1706 else
1707 ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString);
1708
1709 ErrorParsing = true;
1710 continue;
1711 }
1712
1713 // If this is a named positional argument, just remember that it is the
1714 // active one...
1715 if (Handler->getFormattingFlag() == cl::Positional) {
1716 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1717 Handler->error("This argument does not take a value.\n"
1718 "\tInstead, it consumes any positional arguments until "
1719 "the next recognized option.", *Errs);
1720 ErrorParsing = true;
1721 }
1722 ActivePositionalArg = Handler;
1723 }
1724 else
1725 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1726 }
1727
1728 // Check and handle positional arguments now...
1729 if (NumPositionalRequired > PositionalVals.size()) {
1730 *Errs << ProgramName
1731 << ": Not enough positional command line arguments specified!\n"
1732 << "Must specify at least " << NumPositionalRequired
1733 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1734 << ": See: " << argv[0] << " --help\n";
1735
1736 ErrorParsing = true;
1737 } else if (!HasUnlimitedPositionals &&
1738 PositionalVals.size() > PositionalOpts.size()) {
1739 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1740 << "Can specify at most " << PositionalOpts.size()
1741 << " positional arguments: See: " << argv[0] << " --help\n";
1742 ErrorParsing = true;
1743
1744 } else if (!ConsumeAfterOpt) {
1745 // Positional args have already been handled if ConsumeAfter is specified.
1746 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1747 for (Option *Opt : PositionalOpts) {
1748 if (RequiresValue(Opt)) {
1749 ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1750 PositionalVals[ValNo].second);
1751 ValNo++;
1752 --NumPositionalRequired; // We fulfilled our duty...
1753 }
1754
1755 // If we _can_ give this option more arguments, do so now, as long as we
1756 // do not give it values that others need. 'Done' controls whether the
1757 // option even _WANTS_ any more.
1758 //
1759 bool Done = Opt->getNumOccurrencesFlag() == cl::Required;
1760 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1761 switch (Opt->getNumOccurrencesFlag()) {
1762 case cl::Optional:
1763 Done = true; // Optional arguments want _at most_ one value
1764 [[fallthrough]];
1765 case cl::ZeroOrMore: // Zero or more will take all they can get...
1766 case cl::OneOrMore: // One or more will take all they can get...
1767 ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1768 PositionalVals[ValNo].second);
1769 ValNo++;
1770 break;
1771 default:
1772 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1773 "positional argument processing!");
1774 }
1775 }
1776 }
1777 } else {
1778 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1779 unsigned ValNo = 0;
1780 for (Option *Opt : PositionalOpts)
1781 if (RequiresValue(Opt)) {
1782 ErrorParsing |= ProvidePositionalOption(
1783 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1784 ValNo++;
1785 }
1786
1787 // Handle the case where there is just one positional option, and it's
1788 // optional. In this case, we want to give JUST THE FIRST option to the
1789 // positional option and keep the rest for the consume after. The above
1790 // loop would have assigned no values to positional options in this case.
1791 //
1792 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1793 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1794 PositionalVals[ValNo].first,
1795 PositionalVals[ValNo].second);
1796 ValNo++;
1797 }
1798
1799 // Handle over all of the rest of the arguments to the
1800 // cl::ConsumeAfter command line option...
1801 for (; ValNo != PositionalVals.size(); ++ValNo)
1802 ErrorParsing |=
1803 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1804 PositionalVals[ValNo].second);
1805 }
1806
1807 // Loop over args and make sure all required args are specified!
1808 for (const auto &Opt : OptionsMap) {
1809 switch (Opt.second->getNumOccurrencesFlag()) {
1810 case Required:
1811 case OneOrMore:
1812 if (Opt.second->getNumOccurrences() == 0) {
1813 Opt.second->error("must be specified at least once!");
1814 ErrorParsing = true;
1815 }
1816 [[fallthrough]];
1817 default:
1818 break;
1819 }
1820 }
1821
1822 // Now that we know if -debug is specified, we can use it.
1823 // Note that if ReadResponseFiles == true, this must be done before the
1824 // memory allocated for the expanded command line is free()d below.
1825 LLVM_DEBUG(dbgs() << "Args: ";
1826 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1827 dbgs() << '\n';);
1828
1829 // Free all of the memory allocated to the map. Command line options may only
1830 // be processed once!
1831 MoreHelp.clear();
1832
1833 // If we had an error processing our arguments, don't let the program execute
1834 if (ErrorParsing) {
1835 if (!IgnoreErrors)
1836 exit(1);
1837 return false;
1838 }
1839 return true;
1840}
1841
1842//===----------------------------------------------------------------------===//
1843// Option Base class implementation
1844//
1845
1846bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1847 if (!ArgName.data())
1848 ArgName = ArgStr;
1849 if (ArgName.empty())
1850 Errs << HelpStr; // Be nice for positional arguments
1851 else
1852 Errs << globalParser().ProgramName << ": for the " << PrintArg(ArgName, 0);
1853
1854 Errs << " option: " << Message << "\n";
1855 return true;
1856}
1857
1858bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value) {
1859 ++NumOccurrences;
1860 return handleOccurrence(pos, ArgName, Value);
1861}
1862
1863// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1864// has been specified yet.
1865//
1866static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1867 if (O.ValueStr.empty())
1868 return DefaultMsg;
1869 return O.ValueStr;
1870}
1871
1872//===----------------------------------------------------------------------===//
1873// cl::alias class implementation
1874//
1875
1876// Return the width of the option tag for printing...
1877size_t alias::getOptionWidth() const {
1879}
1880
1882 size_t FirstLineIndentedBy) {
1883 assert(Indent >= FirstLineIndentedBy);
1884 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1885 outs().indent(Indent - FirstLineIndentedBy)
1886 << ArgHelpPrefix << Split.first << "\n";
1887 while (!Split.second.empty()) {
1888 Split = Split.second.split('\n');
1889 outs().indent(Indent) << Split.first << "\n";
1890 }
1891}
1892
1894 size_t FirstLineIndentedBy) {
1895 const StringRef ValHelpPrefix = " ";
1896 assert(BaseIndent >= FirstLineIndentedBy);
1897 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1898 outs().indent(BaseIndent - FirstLineIndentedBy)
1899 << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1900 while (!Split.second.empty()) {
1901 Split = Split.second.split('\n');
1902 outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1903 }
1904}
1905
1906// Print out the option for the alias.
1907void alias::printOptionInfo(size_t GlobalWidth) const {
1908 outs() << PrintArg(ArgStr);
1910}
1911
1912//===----------------------------------------------------------------------===//
1913// Parser Implementation code...
1914//
1915
1916// basic_parser implementation
1917//
1918
1919// Return the width of the option tag for printing...
1921 size_t Len = argPlusPrefixesSize(O.ArgStr);
1922 auto ValName = getValueName();
1923 if (!ValName.empty()) {
1924 size_t FormattingLen = 3;
1925 if (O.getMiscFlags() & PositionalEatsArgs)
1926 FormattingLen = 6;
1927 Len += getValueStr(O, ValName).size() + FormattingLen;
1928 }
1929
1930 return Len;
1931}
1932
1933// printOptionInfo - Print out information about this option. The
1934// to-be-maintained width is specified.
1935//
1937 size_t GlobalWidth) const {
1938 outs() << PrintArg(O.ArgStr);
1939
1940 auto ValName = getValueName();
1941 if (!ValName.empty()) {
1942 if (O.getMiscFlags() & PositionalEatsArgs) {
1943 outs() << " <" << getValueStr(O, ValName) << ">...";
1944 } else if (O.getValueExpectedFlag() == ValueOptional)
1945 outs() << "[=<" << getValueStr(O, ValName) << ">]";
1946 else {
1947 outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1948 << '>';
1949 }
1950 }
1951
1952 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1953}
1954
1956 size_t GlobalWidth) const {
1957 outs() << PrintArg(O.ArgStr);
1958 outs().indent(GlobalWidth - O.ArgStr.size());
1959}
1960
1961// parser<bool> implementation
1962//
1963bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1964 bool &Value) {
1965 return parseBool<bool, true, false>(O, ArgName, Arg, Value);
1966}
1967
1968// parser<boolOrDefault> implementation
1969//
1973 boolOrDefault::BOU_FALSE>(O, ArgName, Arg, Value);
1974}
1975
1976// parser<FixedOrScalableQuantity> implementation
1977//
1978template <typename FixedOrScalableQuantityT>
1980 StringRef ValueKind,
1981 FixedOrScalableQuantityT &Value) {
1982 using ScalarTy = typename FixedOrScalableQuantityT::ScalarTy;
1983
1984 Arg = Arg.trim();
1985
1986 ScalarTy MinValue;
1987 if (!Arg.getAsInteger(0, MinValue)) {
1988 Value = FixedOrScalableQuantityT::getFixed(MinValue);
1989 return false;
1990 }
1991
1992 StringRef Remainder = Arg;
1993 if (!Remainder.consume_front("vscale"))
1994 return O.error("'" + Arg + "' value invalid for " + ValueKind +
1995 " argument!");
1996
1997 Remainder = Remainder.ltrim();
1998 if (!Remainder.consume_front('x'))
1999 return O.error("'" + Arg + "' value invalid for " + ValueKind +
2000 " argument!");
2001
2002 Remainder = Remainder.ltrim();
2003 if (Remainder.getAsInteger(0, MinValue))
2004 return O.error("'" + Arg + "' value invalid for " + ValueKind +
2005 " argument!");
2006
2007 Value = FixedOrScalableQuantityT::getScalable(MinValue);
2008 return false;
2009}
2010
2011// parser<int> implementation
2012//
2013bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
2014 int &Value) {
2015 if (Arg.getAsInteger(0, Value))
2016 return O.error("'" + Arg + "' value invalid for integer argument!");
2017 return false;
2018}
2019
2020// parser<long> implementation
2021//
2022bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2023 long &Value) {
2024 if (Arg.getAsInteger(0, Value))
2025 return O.error("'" + Arg + "' value invalid for long argument!");
2026 return false;
2027}
2028
2029// parser<long long> implementation
2030//
2031bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2032 long long &Value) {
2033 if (Arg.getAsInteger(0, Value))
2034 return O.error("'" + Arg + "' value invalid for llong argument!");
2035 return false;
2036}
2037
2038// parser<unsigned> implementation
2039//
2040bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
2041 unsigned &Value) {
2042
2043 if (Arg.getAsInteger(0, Value))
2044 return O.error("'" + Arg + "' value invalid for uint argument!");
2045 return false;
2046}
2047
2048// parser<unsigned long> implementation
2049//
2050bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2051 unsigned long &Value) {
2052
2053 if (Arg.getAsInteger(0, Value))
2054 return O.error("'" + Arg + "' value invalid for ulong argument!");
2055 return false;
2056}
2057
2058// parser<unsigned long long> implementation
2059//
2060bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
2061 StringRef Arg,
2062 unsigned long long &Value) {
2063
2064 if (Arg.getAsInteger(0, Value))
2065 return O.error("'" + Arg + "' value invalid for ullong argument!");
2066 return false;
2067}
2068
2069// parser<ElementCount> implementation
2070//
2071bool parser<ElementCount>::parse(Option &O, StringRef ArgName, StringRef Arg,
2072 ElementCount &Value) {
2073 return parseFixedOrScalableQuantity(O, Arg, getValueName(), Value);
2074}
2075
2076// parser<double>/parser<float> implementation
2077//
2078static bool parseDouble(Option &O, StringRef Arg, double &Value) {
2079 if (to_float(Arg, Value))
2080 return false;
2081 return O.error("'" + Arg + "' value invalid for floating point argument!");
2082}
2083
2084bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
2085 double &Val) {
2086 return parseDouble(O, Arg, Val);
2087}
2088
2089bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
2090 float &Val) {
2091 double dVal;
2092 if (parseDouble(O, Arg, dVal))
2093 return true;
2094 Val = (float)dVal;
2095 return false;
2096}
2097
2098// generic_parser_base implementation
2099//
2100
2101// findOption - Return the option number corresponding to the specified
2102// argument string. If the option is not found, getNumOptions() is returned.
2103//
2105 unsigned e = getNumOptions();
2106
2107 for (unsigned i = 0; i != e; ++i) {
2108 if (getOption(i) == Name)
2109 return i;
2110 }
2111 return e;
2112}
2113
2114static StringRef EqValue = "=<value>";
2115static StringRef EmptyOption = "<empty>";
2117static size_t getOptionPrefixesSize() {
2118 return OptionPrefix.size() + ArgHelpPrefix.size();
2119}
2120
2121static bool shouldPrintOption(StringRef Name, StringRef Description,
2122 const Option &O) {
2123 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2124 !Description.empty();
2125}
2126
2127// Return the width of the option tag for printing...
2129 if (O.hasArgStr()) {
2130 size_t Size =
2131 argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2132 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2133 StringRef Name = getOption(i);
2134 if (!shouldPrintOption(Name, getDescription(i), O))
2135 continue;
2136 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2137 Size = std::max(Size, NameSize + getOptionPrefixesSize());
2138 }
2139 return Size;
2140 } else {
2141 size_t BaseSize = 0;
2142 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2143 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2144 return BaseSize;
2145 }
2146}
2147
2148// printOptionInfo - Print out information about this option. The
2149// to-be-maintained width is specified.
2150//
2152 size_t GlobalWidth) const {
2153 if (O.hasArgStr()) {
2154 // When the value is optional, first print a line just describing the
2155 // option without values.
2156 if (O.getValueExpectedFlag() == ValueOptional) {
2157 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2158 if (getOption(i).empty()) {
2159 outs() << PrintArg(O.ArgStr);
2160 Option::printHelpStr(O.HelpStr, GlobalWidth,
2161 argPlusPrefixesSize(O.ArgStr));
2162 break;
2163 }
2164 }
2165 }
2166
2167 outs() << PrintArg(O.ArgStr) << EqValue;
2168 Option::printHelpStr(O.HelpStr, GlobalWidth,
2169 EqValue.size() +
2170 argPlusPrefixesSize(O.ArgStr));
2171 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2172 StringRef OptionName = getOption(i);
2173 StringRef Description = getDescription(i);
2174 if (!shouldPrintOption(OptionName, Description, O))
2175 continue;
2176 size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2177 outs() << OptionPrefix << OptionName;
2178 if (OptionName.empty()) {
2179 outs() << EmptyOption;
2180 assert(FirstLineIndent >= EmptyOption.size());
2181 FirstLineIndent += EmptyOption.size();
2182 }
2183 if (!Description.empty())
2184 Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2185 else
2186 outs() << '\n';
2187 }
2188 } else {
2189 if (!O.HelpStr.empty())
2190 outs() << " " << O.HelpStr << '\n';
2191 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2193 outs() << " " << PrintArg(Option);
2194 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2195 }
2196 }
2197}
2198
2199static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2200
2201// printGenericOptionDiff - Print the value of this option and it's default.
2202//
2203// "Generic" options have each value mapped to a name.
2205 const Option &O, const GenericOptionValue &Value,
2206 const GenericOptionValue &Default, size_t GlobalWidth) const {
2207 outs() << " " << PrintArg(O.ArgStr);
2208 outs().indent(GlobalWidth - O.ArgStr.size());
2209
2210 unsigned NumOpts = getNumOptions();
2211 for (unsigned i = 0; i != NumOpts; ++i) {
2212 if (!Value.compare(getOptionValue(i)))
2213 continue;
2214
2215 outs() << "= " << getOption(i);
2216 size_t L = getOption(i).size();
2217 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2218 outs().indent(NumSpaces) << " (default: ";
2219 for (unsigned j = 0; j != NumOpts; ++j) {
2220 if (!Default.compare(getOptionValue(j)))
2221 continue;
2222 outs() << getOption(j);
2223 break;
2224 }
2225 outs() << ")\n";
2226 return;
2227 }
2228 outs() << "= *unknown option value*\n";
2229}
2230
2231// printOptionDiff - Specializations for printing basic value types.
2232//
2233namespace llvm {
2234namespace cl {
2236 return OS << static_cast<int>(V);
2237}
2238} // namespace cl
2239} // namespace llvm
2240
2241#define PRINT_OPT_DIFF(T) \
2242 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2243 size_t GlobalWidth) const { \
2244 printOptionName(O, GlobalWidth); \
2245 std::string Str; \
2246 { \
2247 raw_string_ostream SS(Str); \
2248 SS << V; \
2249 } \
2250 outs() << "= " << Str; \
2251 size_t NumSpaces = \
2252 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2253 outs().indent(NumSpaces) << " (default: "; \
2254 if (D.hasValue()) \
2255 outs() << D.getValue(); \
2256 else \
2257 outs() << "*no default*"; \
2258 outs() << ")\n"; \
2259 }
2260
2261PRINT_OPT_DIFF(bool)
2263PRINT_OPT_DIFF(int)
2264PRINT_OPT_DIFF(long)
2265PRINT_OPT_DIFF(long long)
2266PRINT_OPT_DIFF(unsigned)
2267PRINT_OPT_DIFF(unsigned long)
2268PRINT_OPT_DIFF(unsigned long long)
2269PRINT_OPT_DIFF(double)
2270PRINT_OPT_DIFF(float)
2271PRINT_OPT_DIFF(char)
2273
2276 size_t GlobalWidth) const {
2277 printOptionName(O, GlobalWidth);
2278 outs() << "= " << V;
2279 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2280 outs().indent(NumSpaces) << " (default: ";
2281 if (D.hasValue())
2282 outs() << D.getValue();
2283 else
2284 outs() << "*no default*";
2285 outs() << ")\n";
2286}
2287
2288void parser<std::optional<std::string>>::printOptionDiff(
2289 const Option &O, std::optional<StringRef> V,
2290 const OptionValue<std::optional<std::string>> &D,
2291 size_t GlobalWidth) const {
2292 printOptionName(O, GlobalWidth);
2293 outs() << "= " << V;
2294 size_t VSize = V.has_value() ? V.value().size() : 0;
2295 size_t NumSpaces = MaxOptWidth > VSize ? MaxOptWidth - VSize : 0;
2296 outs().indent(NumSpaces) << " (default: ";
2297 if (D.hasValue() && D.getValue().has_value())
2298 outs() << D.getValue();
2299 else
2300 outs() << "*no value*";
2301 outs() << ")\n";
2302}
2303
2304// Print a placeholder for options that don't yet support printOptionDiff().
2306 size_t GlobalWidth) const {
2307 printOptionName(O, GlobalWidth);
2308 outs() << "= *cannot print option value*\n";
2309}
2310
2311//===----------------------------------------------------------------------===//
2312// -help and -help-hidden option implementation
2313//
2314
2315static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2316 const std::pair<const char *, Option *> *RHS) {
2317 return strcmp(LHS->first, RHS->first);
2318}
2319
2320static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2321 const std::pair<const char *, SubCommand *> *RHS) {
2322 return strcmp(LHS->first, RHS->first);
2323}
2324
2325// Copy Options into a vector so we can sort them as we like.
2326static void sortOpts(OptionsMapTy &OptMap,
2327 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2328 bool ShowHidden) {
2329 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2330
2331 for (auto I = OptMap.begin(), E = OptMap.end(); I != E; ++I) {
2332 // Ignore really-hidden options.
2333 if (I->second->getOptionHiddenFlag() == ReallyHidden)
2334 continue;
2335
2336 // Unless showhidden is set, ignore hidden flags.
2337 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2338 continue;
2339
2340 // If we've already seen this option, don't add it to the list again.
2341 if (!OptionSet.insert(I->second).second)
2342 continue;
2343
2344 Opts.push_back(
2345 std::pair<const char *, Option *>(I->first.data(), I->second));
2346 }
2347
2348 // Sort the options list alphabetically.
2349 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2350}
2351
2352static void
2354 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2355 for (auto *S : SubMap) {
2356 if (S->getName().empty())
2357 continue;
2358 Subs.push_back(std::make_pair(S->getName().data(), S));
2359 }
2360 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2361}
2362
2363namespace {
2364
2365class HelpPrinter {
2366protected:
2367 const bool ShowHidden;
2368 using StrOptionPairVector =
2370 using StrSubCommandPairVector =
2372 // Print the options. Opts is assumed to be alphabetically sorted.
2373 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2374 for (const auto &Opt : Opts)
2375 Opt.second->printOptionInfo(MaxArgLen);
2376 }
2377
2378 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2379 for (const auto &S : Subs) {
2380 outs() << " " << S.first;
2381 if (!S.second->getDescription().empty()) {
2382 outs().indent(MaxSubLen - strlen(S.first));
2383 outs() << " - " << S.second->getDescription();
2384 }
2385 outs() << "\n";
2386 }
2387 }
2388
2389public:
2390 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2391 virtual ~HelpPrinter() = default;
2392
2393 // Invoke the printer.
2394 void operator=(bool Value) {
2395 if (!Value)
2396 return;
2397 printHelp();
2398
2399 // Halt the program since help information was printed
2400 exit(0);
2401 }
2402
2403 void printHelp() {
2404 SubCommand *Sub = globalParser().getActiveSubCommand();
2405 auto &OptionsMap = Sub->OptionsMap;
2406 auto &PositionalOpts = Sub->PositionalOpts;
2407 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2408
2409 StrOptionPairVector Opts;
2410 sortOpts(OptionsMap, Opts, ShowHidden);
2411
2412 StrSubCommandPairVector Subs;
2413 sortSubCommands(globalParser().RegisteredSubCommands, Subs);
2414
2415 if (!globalParser().ProgramOverview.empty())
2416 outs() << "OVERVIEW: " << globalParser().ProgramOverview << "\n";
2417
2418 if (Sub == &SubCommand::getTopLevel()) {
2419 outs() << "USAGE: " << globalParser().ProgramName;
2420 if (!Subs.empty())
2421 outs() << " [subcommand]";
2422 outs() << " [options]";
2423 } else {
2424 if (!Sub->getDescription().empty()) {
2425 outs() << "SUBCOMMAND '" << Sub->getName()
2426 << "': " << Sub->getDescription() << "\n\n";
2427 }
2428 outs() << "USAGE: " << globalParser().ProgramName << " " << Sub->getName()
2429 << " [options]";
2430 }
2431
2432 for (auto *Opt : PositionalOpts) {
2433 if (Opt->hasArgStr())
2434 outs() << " --" << Opt->ArgStr;
2435 outs() << " " << Opt->HelpStr;
2436 }
2437
2438 // Print the consume after option info if it exists...
2439 if (ConsumeAfterOpt)
2440 outs() << " " << ConsumeAfterOpt->HelpStr;
2441
2442 if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
2443 // Compute the maximum subcommand length...
2444 size_t MaxSubLen = 0;
2445 for (const auto &Sub : Subs)
2446 MaxSubLen = std::max(MaxSubLen, strlen(Sub.first));
2447
2448 outs() << "\n\n";
2449 outs() << "SUBCOMMANDS:\n\n";
2450 printSubCommands(Subs, MaxSubLen);
2451 outs() << "\n";
2452 outs() << " Type \"" << globalParser().ProgramName
2453 << " <subcommand> --help\" to get more help on a specific "
2454 "subcommand";
2455 }
2456
2457 outs() << "\n\n";
2458
2459 // Compute the maximum argument length...
2460 size_t MaxArgLen = 0;
2461 for (const auto &Opt : Opts)
2462 MaxArgLen = std::max(MaxArgLen, Opt.second->getOptionWidth());
2463
2464 outs() << "OPTIONS:\n";
2465 printOptions(Opts, MaxArgLen);
2466
2467 // Print any extra help the user has declared.
2468 for (const auto &I : globalParser().MoreHelp)
2469 outs() << I;
2470 globalParser().MoreHelp.clear();
2471 }
2472};
2473
2474class CategorizedHelpPrinter : public HelpPrinter {
2475public:
2476 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2477
2478 // Helper function for printOptions().
2479 // It shall return a negative value if A's name should be lexicographically
2480 // ordered before B's name. It returns a value greater than zero if B's name
2481 // should be ordered before A's name, and it returns 0 otherwise.
2482 static int OptionCategoryCompare(OptionCategory *const *A,
2483 OptionCategory *const *B) {
2484 return (*A)->getName().compare((*B)->getName());
2485 }
2486
2487 // Make sure we inherit our base class's operator=()
2488 using HelpPrinter::operator=;
2489
2490protected:
2491 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2492 std::vector<OptionCategory *> SortedCategories;
2493 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2494
2495 // Collect registered option categories into vector in preparation for
2496 // sorting.
2497 llvm::append_range(SortedCategories,
2498 globalParser().RegisteredOptionCategories);
2499
2500 // Sort the different option categories alphabetically.
2501 assert(SortedCategories.size() > 0 && "No option categories registered!");
2502 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2503 OptionCategoryCompare);
2504
2505 // Walk through pre-sorted options and assign into categories.
2506 // Because the options are already alphabetically sorted the
2507 // options within categories will also be alphabetically sorted.
2508 for (const auto &I : Opts) {
2509 Option *Opt = I.second;
2510 for (OptionCategory *Cat : Opt->Categories) {
2511 assert(llvm::is_contained(SortedCategories, Cat) &&
2512 "Option has an unregistered category");
2513 CategorizedOptions[Cat].push_back(Opt);
2514 }
2515 }
2516
2517 // Now do printing.
2518 for (OptionCategory *Category : SortedCategories) {
2519 // Hide empty categories for --help, but show for --help-hidden.
2520 const auto &CategoryOptions = CategorizedOptions[Category];
2521 if (CategoryOptions.empty())
2522 continue;
2523
2524 // Print category information.
2525 outs() << "\n";
2526 outs() << Category->getName() << ":\n";
2527
2528 // Check if description is set.
2529 if (!Category->getDescription().empty())
2530 outs() << Category->getDescription() << "\n\n";
2531 else
2532 outs() << "\n";
2533
2534 // Loop over the options in the category and print.
2535 for (const Option *Opt : CategoryOptions)
2536 Opt->printOptionInfo(MaxArgLen);
2537 }
2538 }
2539};
2540
2541// This wraps the Uncategorizing and Categorizing printers and decides
2542// at run time which should be invoked.
2543class HelpPrinterWrapper {
2544private:
2545 HelpPrinter &UncategorizedPrinter;
2546 CategorizedHelpPrinter &CategorizedPrinter;
2547
2548public:
2549 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2550 CategorizedHelpPrinter &CategorizedPrinter)
2551 : UncategorizedPrinter(UncategorizedPrinter),
2552 CategorizedPrinter(CategorizedPrinter) {}
2553
2554 // Invoke the printer.
2555 void operator=(bool Value);
2556};
2557
2558} // End anonymous namespace
2559
2560#if defined(__GNUC__)
2561// GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2562// enabled.
2563# if defined(__OPTIMIZE__)
2564# define LLVM_IS_DEBUG_BUILD 0
2565# else
2566# define LLVM_IS_DEBUG_BUILD 1
2567# endif
2568#elif defined(_MSC_VER)
2569// MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2570// Use _DEBUG instead. This macro actually corresponds to the choice between
2571// debug and release CRTs, but it is a reasonable proxy.
2572# if defined(_DEBUG)
2573# define LLVM_IS_DEBUG_BUILD 1
2574# else
2575# define LLVM_IS_DEBUG_BUILD 0
2576# endif
2577#else
2578// Otherwise, for an unknown compiler, assume this is an optimized build.
2579# define LLVM_IS_DEBUG_BUILD 0
2580#endif
2581
2582namespace {
2583class VersionPrinter {
2584public:
2585 void print(const std::vector<VersionPrinterTy> &ExtraPrinters) {
2586 raw_ostream &OS = outs();
2587#ifdef PACKAGE_VENDOR
2588 OS << PACKAGE_VENDOR << " ";
2589#else
2590 OS << "LLVM (http://llvm.org/):\n ";
2591#endif
2592 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
2593#if LLVM_IS_DEBUG_BUILD
2594 OS << "DEBUG build";
2595#else
2596 OS << "Optimized build";
2597#endif
2598#ifndef NDEBUG
2599 OS << " with assertions";
2600#endif
2601 OS << ".\n";
2602
2603 // Iterate over any registered extra printers and call them to add further
2604 // information.
2605 if (!ExtraPrinters.empty()) {
2606 for (const auto &I : ExtraPrinters)
2607 I(outs());
2608 }
2609 }
2610 void operator=(bool OptionWasSpecified);
2611};
2612
2613struct CommandLineCommonOptions {
2614 // Declare the four HelpPrinter instances that are used to print out help, or
2615 // help-hidden as an uncategorized list or in categories.
2616 HelpPrinter UncategorizedNormalPrinter{false};
2617 HelpPrinter UncategorizedHiddenPrinter{true};
2618 CategorizedHelpPrinter CategorizedNormalPrinter{false};
2619 CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2620 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2621 // a categorizing help printer
2622 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2623 CategorizedNormalPrinter};
2624 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2625 CategorizedHiddenPrinter};
2626 // Define a category for generic options that all tools should have.
2627 cl::OptionCategory GenericCategory{"Generic Options"};
2628
2629 // Define uncategorized help printers.
2630 // --help-list is hidden by default because if Option categories are being
2631 // used then --help behaves the same as --help-list.
2633 "help-list",
2634 cl::desc(
2635 "Display list of available options (--help-list-hidden for more)"),
2636 cl::location(UncategorizedNormalPrinter),
2637 cl::Hidden,
2639 cl::cat(GenericCategory),
2641
2643 "help-list-hidden",
2644 cl::desc("Display list of all available options"),
2645 cl::location(UncategorizedHiddenPrinter),
2646 cl::Hidden,
2648 cl::cat(GenericCategory),
2650
2651 // Define uncategorized/categorized help printers. These printers change their
2652 // behaviour at runtime depending on whether one or more Option categories
2653 // have been declared.
2655 "help",
2656 cl::desc("Display available options (--help-hidden for more)"),
2657 cl::location(WrappedNormalPrinter),
2659 cl::cat(GenericCategory),
2661
2662 cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2664
2666 "help-hidden",
2667 cl::desc("Display all available options"),
2668 cl::location(WrappedHiddenPrinter),
2669 cl::Hidden,
2671 cl::cat(GenericCategory),
2673
2674 cl::opt<bool> PrintOptions{
2675 "print-options",
2676 cl::desc("Print non-default options after command line parsing"),
2677 cl::Hidden,
2678 cl::init(false),
2679 cl::cat(GenericCategory),
2681
2682 cl::opt<bool> PrintAllOptions{
2683 "print-all-options",
2684 cl::desc("Print all option values after command line parsing"),
2685 cl::Hidden,
2686 cl::init(false),
2687 cl::cat(GenericCategory),
2689
2690 VersionPrinterTy OverrideVersionPrinter = nullptr;
2691
2692 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2693
2694 // Define the --version option that prints out the LLVM version for the tool
2695 VersionPrinter VersionPrinterInstance;
2696
2698 "version", cl::desc("Display the version of this program"),
2699 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2700 cl::cat(GenericCategory)};
2701};
2702} // End anonymous namespace
2703
2704// Lazy-initialized global instance of options controlling the command-line
2705// parser and general handling.
2707
2719
2721 // Initialise the general option category.
2722 static OptionCategory GeneralCategory{"General options"};
2723 return GeneralCategory;
2724}
2725
2726void VersionPrinter::operator=(bool OptionWasSpecified) {
2727 if (!OptionWasSpecified)
2728 return;
2729
2730 if (CommonOptions->OverrideVersionPrinter != nullptr) {
2731 CommonOptions->OverrideVersionPrinter(outs());
2732 exit(0);
2733 }
2734 print(CommonOptions->ExtraVersionPrinters);
2735
2736 exit(0);
2737}
2738
2739void HelpPrinterWrapper::operator=(bool Value) {
2740 if (!Value)
2741 return;
2742
2743 // Decide which printer to invoke. If more than one option category is
2744 // registered then it is useful to show the categorized help instead of
2745 // uncategorized help.
2746 if (globalParser().RegisteredOptionCategories.size() > 1) {
2747 // unhide --help-list option so user can have uncategorized output if they
2748 // want it.
2749 CommonOptions->HLOp.setHiddenFlag(NotHidden);
2750
2751 CategorizedPrinter = true; // Invoke categorized printer
2752 } else {
2753 UncategorizedPrinter = true; // Invoke uncategorized printer
2754 }
2755}
2756
2757// Print the value of each option.
2758void cl::PrintOptionValues() { globalParser().printOptionValues(); }
2759
2760void CommandLineParser::printOptionValues() {
2761 if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2762 return;
2763
2765 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2766
2767 // Compute the maximum argument length...
2768 size_t MaxArgLen = 0;
2769 for (const auto &Opt : Opts)
2770 MaxArgLen = std::max(MaxArgLen, Opt.second->getOptionWidth());
2771
2772 for (const auto &Opt : Opts)
2773 Opt.second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2774}
2775
2776// Utility function for printing the help message.
2777void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2778 if (!Hidden && !Categorized)
2779 CommonOptions->UncategorizedNormalPrinter.printHelp();
2780 else if (!Hidden && Categorized)
2781 CommonOptions->CategorizedNormalPrinter.printHelp();
2782 else if (Hidden && !Categorized)
2783 CommonOptions->UncategorizedHiddenPrinter.printHelp();
2784 else
2785 CommonOptions->CategorizedHiddenPrinter.printHelp();
2786}
2787
2789 static const StringRef Config[] = {
2790 // Placeholder to ensure the array always has elements, since it's an
2791 // error to have a zero-sized array. Slice this off before returning.
2792 "",
2793 // Actual compiler build config feature list:
2794#if LLVM_IS_DEBUG_BUILD
2795 "+unoptimized",
2796#endif
2797#ifndef NDEBUG
2798 "+assertions",
2799#endif
2800#ifdef EXPENSIVE_CHECKS
2801 "+expensive-checks",
2802#endif
2803#if __has_feature(address_sanitizer)
2804 "+asan",
2805#endif
2806#if __has_feature(dataflow_sanitizer)
2807 "+dfsan",
2808#endif
2809#if __has_feature(hwaddress_sanitizer)
2810 "+hwasan",
2811#endif
2812#if __has_feature(memory_sanitizer)
2813 "+msan",
2814#endif
2815#if __has_feature(thread_sanitizer)
2816 "+tsan",
2817#endif
2818#if __has_feature(undefined_behavior_sanitizer)
2819 "+ubsan",
2820#endif
2821#ifdef LLVM_INTEGRATED_CRT_ALLOC
2822 "+alloc:" LLVM_INTEGRATED_CRT_ALLOC,
2823#endif
2824 };
2825 return ArrayRef(Config).drop_front(1);
2826}
2827
2828// Utility function for printing the build config.
2830#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2831 OS << "Build config: ";
2833 OS << '\n';
2834#endif
2835}
2836
2837/// Utility function for printing version number.
2839 CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2840}
2841
2843 CommonOptions->OverrideVersionPrinter = func;
2844}
2845
2847 CommonOptions->ExtraVersionPrinters.push_back(func);
2848}
2849
2852 auto &Subs = globalParser().RegisteredSubCommands;
2853 (void)Subs;
2854 assert(Subs.contains(&Sub));
2855 return Sub.OptionsMap;
2856}
2857
2860 return globalParser().getRegisteredSubcommands();
2861}
2862
2865 for (auto &I : Sub.OptionsMap) {
2866 bool Unrelated = true;
2867 for (auto &Cat : I.second->Categories) {
2868 if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2869 Unrelated = false;
2870 }
2871 if (Unrelated)
2872 I.second->setHiddenFlag(cl::ReallyHidden);
2873 }
2874}
2875
2877 SubCommand &Sub) {
2879 for (auto &I : Sub.OptionsMap) {
2880 bool Unrelated = true;
2881 for (auto &Cat : I.second->Categories) {
2882 if (is_contained(Categories, Cat) ||
2883 Cat == &CommonOptions->GenericCategory)
2884 Unrelated = false;
2885 }
2886 if (Unrelated)
2887 I.second->setHiddenFlag(cl::ReallyHidden);
2888 }
2889}
2890
2893 globalParser().ResetAllOptionOccurrences();
2894}
2895
2896void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2897 const char *Overview) {
2898 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2899 &llvm::nulls());
2900}
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< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
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")
void opt_bool_anchor()
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 bool parseDouble(Option &O, StringRef Arg, double &Value)
static CommandLineParser & globalParser()
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 void ExpandBasePaths(StringRef BasePath, StringSaver &Saver, const char *&Arg)
static Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const OptionsMapTy &OptionsMap)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
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 Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const OptionsMapTy &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
static void initCommonOptions()
void opt_char_anchor()
static void sortOpts(OptionsMapTy &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
DenseMap< StringRef, Option * > OptionsMapTy
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 bool parseFixedOrScalableQuantity(Option &O, StringRef Arg, StringRef ValueKind, FixedOrScalableQuantityT &Value)
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 StringRef EqValue
static const size_t MaxOptWidth
static bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static Option * LookupNearestOption(StringRef Arg, const OptionsMapTy &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
void opt_int_anchor()
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool isGrouping(const Option *O)
static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos, StringRef ArgName, StringRef Value)
CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence() that does special handling ...
#define LLVM_EXPORT_TEMPLATE
Definition Compiler.h:217
#define _
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 I(x, y, z)
Definition MD5.cpp:57
#define T
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.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:258
iterator begin()
Definition DenseMap.h:172
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:254
iterator end()
Definition DenseMap.h:176
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:249
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:319
Represents either an error or a value T.
Definition ErrorOr.h:56
reference get()
Definition ErrorOr.h:149
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
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...
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator end() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
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...
Definition SmallString.h:26
void assign(StringRef RHS)
Assign from a StringRef.
Definition SmallString.h:51
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
const char * c_str()
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)
void reserve(size_type N)
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...
Definition StringRef.h:888
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:736
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:635
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition StringRef.cpp:88
size_t size_type
Definition StringRef.h:62
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:720
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
StringRef ltrim(char Char) const
Return string with consecutive Char characters starting from the the left removed.
Definition StringRef.h:826
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
StringRef trim(char Char) const
Return string with consecutive Char characters starting from the left and right removed.
Definition StringRef.h:850
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:661
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
BumpPtrAllocator & getAllocator() const
Definition StringSaver.h:28
StringRef save(const char *S)
Definition StringSaver.h:31
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
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 getName() const
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
void setMiscFlag(enum MiscFlags M)
enum FormattingFlags getFormattingFlag() const
virtual void printOptionInfo(size_t GlobalWidth) const =0
enum NumOccurrencesFlag getNumOccurrencesFlag() const
virtual bool addOccurrence(unsigned pos, StringRef ArgName, StringRef Value)
SmallVector< OptionCategory *, 1 > Categories
bool error(const Twine &Message, StringRef ArgName=StringRef(), raw_ostream &Errs=llvm::errs())
void setArgStr(StringRef S)
bool hasArgStr() const
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)
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 HelpStr
Option(enum NumOccurrencesFlag OccurrencesFlag, enum OptionHidden Hidden)
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
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 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.
Definition raw_ostream.h:53
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.
constexpr size_t NameSize
Definition XCOFF.h:30
This namespace contains all of the command line option processing machinery.
Definition MCSchedule.h:35
LLVM_ABI iterator_range< SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
LLVM_ABI void PrintVersionMessage()
Utility function for printing version number.
LLVM_ABI bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
LLVM_ABI void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
LLVM_ABI OptionCategory & getGeneralCategory()
@ ValueDisallowed
LLVM_ABI void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
LLVM_ABI void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
LLVM_ABI void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
LLVM_ABI DenseMap< StringRef, Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a map of all registered named options (e.g.
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
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.
static raw_ostream & operator<<(raw_ostream &OS, boolOrDefault V)
LLVM_ABI bool expandResponseFiles(int Argc, const char *const *Argv, const char *EnvVar, SmallVectorImpl< const char * > &NewArgv)
A convenience helper which concatenates the options specified by the environment variable EnvVar and ...
initializer< Ty > init(const Ty &Val)
std::function< void(raw_ostream &)> VersionPrinterTy
Definition CommandLine.h:74
@ PositionalEatsArgs
LLVM_ABI ArrayRef< StringRef > getCompilerBuildConfig()
An array of optional enabled settings in the LLVM build configuration, which may be of interest to co...
LocationClass< Ty > location(Ty &L)
LLVM_ABI void HideUnrelatedOptions(cl::OptionCategory &Category, SubCommand &Sub=SubCommand::getTopLevel())
Mark all options not part of this category as cl::ReallyHidden.
LLVM_ABI void AddExtraVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Add an extra printer to u...
LLVM_ABI void PrintHelpMessage(bool Hidden=false, bool Categorized=false)
This function just prints the help message, exactly the same way as if the -help or -help-hidden opti...
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
LLVM_ABI bool ParseCommandLineOptions(int argc, const char *const *argv, StringRef Overview="", raw_ostream *Errs=nullptr, vfs::FileSystem *VFS=nullptr, const char *EnvVar=nullptr, bool LongOptionsUseDoubleDash=false)
@ NormalFormatting
LLVM_ABI void TokenizeGNUCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a command line that can contain escapes and quotes.
LLVM_ABI StringRef parent_path(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get parent path.
Definition Path.cpp:478
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
Definition Path.cpp:667
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
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.
Definition STLExtras.h:316
@ Length
Definition DWP.cpp:577
void initWithColorOptions()
Definition WithColor.cpp:34
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
@ Done
Definition Threading.h:60
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 initDebugOptions()
Definition Debug.cpp:189
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2329
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.
Definition Error.h:1321
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
Definition Errc.h:65
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.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
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()
Definition Signals.cpp:64
void initStatisticOptions()
Definition Statistic.cpp:49
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.
Definition Error.h:340
void initTimerOptions()
Definition Timer.cpp:569
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...
Definition STLExtras.h:2035
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:390
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
#define INIT(o, n)
Definition regexec.c:71
LLVM_ABI extrahelp(StringRef help)