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