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