LLVM 23.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
150
151namespace {
152
153class PrintArg {
154 StringRef ArgName;
155 size_t Pad;
156public:
157 PrintArg(StringRef ArgName, size_t Pad = DefaultPad) : ArgName(ArgName), Pad(Pad) {}
158 friend raw_ostream &operator<<(raw_ostream &OS, const PrintArg &);
159};
160
161raw_ostream &operator<<(raw_ostream &OS, const PrintArg& Arg) {
162 OS << argPrefix(Arg.ArgName, Arg.Pad) << Arg.ArgName;
163 return OS;
164}
165
166class CommandLineParser {
167public:
168 // Globals for name and overview of program. Program name is not a string to
169 // avoid static ctor/dtor issues.
170 std::string ProgramName;
171 StringRef ProgramOverview;
172
173 // This collects additional help to be printed.
174 std::vector<StringRef> MoreHelp;
175
176 // This collects Options added with the cl::DefaultOption flag. Since they can
177 // be overridden, they are not added to the appropriate SubCommands until
178 // ParseCommandLineOptions actually runs.
179 SmallVector<Option*, 4> DefaultOptions;
180
181 // This collects the different option categories that have been registered.
182 SmallPtrSet<OptionCategory *, 16> RegisteredOptionCategories;
183
184 // This collects the different subcommands that have been registered.
185 SmallPtrSet<SubCommand *, 4> RegisteredSubCommands;
186
187 CommandLineParser() { registerSubCommand(&SubCommand::getTopLevel()); }
188
190
191 bool ParseCommandLineOptions(int argc, const char *const *argv,
192 StringRef Overview, raw_ostream *Errs = nullptr,
193 vfs::FileSystem *VFS = nullptr,
194 bool LongOptionsUseDoubleDash = false);
195
196 void forEachSubCommand(Option &Opt, function_ref<void(SubCommand &)> Action) {
197 if (Opt.Subs.empty()) {
198 Action(SubCommand::getTopLevel());
199 return;
200 }
201 if (Opt.Subs.size() == 1 && *Opt.Subs.begin() == &SubCommand::getAll()) {
202 for (auto *SC : RegisteredSubCommands)
203 Action(*SC);
204 Action(SubCommand::getAll());
205 return;
206 }
207 for (auto *SC : Opt.Subs) {
208 assert(SC != &SubCommand::getAll() &&
209 "SubCommand::getAll() should not be used with other subcommands");
210 Action(*SC);
211 }
212 }
213
214 void addLiteralOption(Option &Opt, SubCommand *SC, StringRef Name) {
215 if (Opt.hasArgStr())
216 return;
217 if (!SC->OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
218 errs() << ProgramName << ": CommandLine Error: Option '" << Name
219 << "' registered more than once!\n";
220 report_fatal_error("inconsistency in registered CommandLine options");
221 }
222 }
223
224 void addLiteralOption(Option &Opt, StringRef Name) {
225 forEachSubCommand(
226 Opt, [&](SubCommand &SC) { addLiteralOption(Opt, &SC, Name); });
227 }
228
229 void addOption(Option *O, SubCommand *SC) {
230 bool HadErrors = false;
231 if (O->hasArgStr()) {
232 // If it's a DefaultOption, check to make sure it isn't already there.
233 if (O->isDefaultOption() && SC->OptionsMap.contains(O->ArgStr))
234 return;
235
236 // Add argument to the argument map!
237 if (!SC->OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
238 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
239 << "' registered more than once!\n";
240 HadErrors = true;
241 }
242 }
243
244 // Remember information about positional options.
245 if (O->getFormattingFlag() == cl::Positional)
246 SC->PositionalOpts.push_back(O);
247 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
248 SC->SinkOpts.push_back(O);
249 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
250 if (SC->ConsumeAfterOpt) {
251 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
252 HadErrors = true;
253 }
254 SC->ConsumeAfterOpt = O;
255 }
256
257 // Fail hard if there were errors. These are strictly unrecoverable and
258 // indicate serious issues such as conflicting option names or an
259 // incorrectly
260 // linked LLVM distribution.
261 if (HadErrors)
262 report_fatal_error("inconsistency in registered CommandLine options");
263 }
264
265 void addOption(Option *O, bool ProcessDefaultOption = false) {
266 if (!ProcessDefaultOption && O->isDefaultOption()) {
267 DefaultOptions.push_back(O);
268 return;
269 }
270 forEachSubCommand(*O, [&](SubCommand &SC) { addOption(O, &SC); });
271 }
272
273 void removeOption(Option *O, SubCommand *SC) {
274 SmallVector<StringRef, 16> OptionNames;
275 O->getExtraOptionNames(OptionNames);
276 if (O->hasArgStr())
277 OptionNames.push_back(O->ArgStr);
278
279 SubCommand &Sub = *SC;
280 for (auto Name : OptionNames) {
281 auto I = Sub.OptionsMap.find(Name);
282 // Re-query end() each iteration: a prior erase invalidates iterators
283 // (including a cached end()) under backward-shift deletion.
284 if (I != Sub.OptionsMap.end() && I->second == O)
285 Sub.OptionsMap.erase(I);
286 }
287
288 if (O->getFormattingFlag() == cl::Positional)
289 for (auto *Opt = Sub.PositionalOpts.begin();
290 Opt != Sub.PositionalOpts.end(); ++Opt) {
291 if (*Opt == O) {
292 Sub.PositionalOpts.erase(Opt);
293 break;
294 }
295 }
296 else if (O->getMiscFlags() & cl::Sink)
297 for (auto *Opt = Sub.SinkOpts.begin(); Opt != Sub.SinkOpts.end(); ++Opt) {
298 if (*Opt == O) {
299 Sub.SinkOpts.erase(Opt);
300 break;
301 }
302 }
303 else if (O == Sub.ConsumeAfterOpt)
304 Sub.ConsumeAfterOpt = nullptr;
305 }
306
307 void removeOption(Option *O) {
308 forEachSubCommand(*O, [&](SubCommand &SC) { removeOption(O, &SC); });
309 }
310
311 bool hasOptions(const SubCommand &Sub) const {
312 return (!Sub.OptionsMap.empty() || !Sub.PositionalOpts.empty() ||
313 nullptr != Sub.ConsumeAfterOpt);
314 }
315
316 bool hasOptions() const {
317 for (const auto *S : RegisteredSubCommands) {
318 if (hasOptions(*S))
319 return true;
320 }
321 return false;
322 }
323
324 bool hasNamedSubCommands() const {
325 for (const auto *S : RegisteredSubCommands)
326 if (!S->getName().empty())
327 return true;
328 return false;
329 }
330
331 SubCommand *getActiveSubCommand() { return ActiveSubCommand; }
332
333 void updateArgStr(Option *O, StringRef NewName, SubCommand *SC) {
334 SubCommand &Sub = *SC;
335 if (!Sub.OptionsMap.insert(std::make_pair(NewName, O)).second) {
336 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
337 << "' registered more than once!\n";
338 report_fatal_error("inconsistency in registered CommandLine options");
339 }
340 Sub.OptionsMap.erase(O->ArgStr);
341 }
342
343 void updateArgStr(Option *O, StringRef NewName) {
344 forEachSubCommand(*O,
345 [&](SubCommand &SC) { updateArgStr(O, NewName, &SC); });
346 }
347
348 void printOptionValues();
349
350 void registerCategory(OptionCategory *cat) {
351 assert(count_if(RegisteredOptionCategories,
352 [cat](const OptionCategory *Category) {
353 return cat->getName() == Category->getName();
354 }) == 0 &&
355 "Duplicate option categories");
356
357 RegisteredOptionCategories.insert(cat);
358 }
359
360 void registerSubCommand(SubCommand *sub) {
361 assert(count_if(RegisteredSubCommands,
362 [sub](const SubCommand *Sub) {
363 return (!sub->getName().empty()) &&
364 (Sub->getName() == sub->getName());
365 }) == 0 &&
366 "Duplicate subcommands");
367 RegisteredSubCommands.insert(sub);
368
369 // For all options that have been registered for all subcommands, add the
370 // option to this subcommand now.
372 "SubCommand::getAll() should not be registered");
373 for (auto &E : SubCommand::getAll().OptionsMap) {
374 Option *O = E.second;
375 if ((O->isPositional() || O->isSink() || O->isConsumeAfter()) ||
376 O->hasArgStr())
377 addOption(O, sub);
378 else
379 addLiteralOption(*O, sub, E.first);
380 }
381 }
382
383 void unregisterSubCommand(SubCommand *sub) {
384 RegisteredSubCommands.erase(sub);
385 }
386
389 return make_range(RegisteredSubCommands.begin(),
390 RegisteredSubCommands.end());
391 }
392
393 void reset() {
394 ActiveSubCommand = nullptr;
395 ProgramName.clear();
396 ProgramOverview = StringRef();
397
398 MoreHelp.clear();
399 RegisteredOptionCategories.clear();
400
402 RegisteredSubCommands.clear();
403
406 registerSubCommand(&SubCommand::getTopLevel());
407
408 DefaultOptions.clear();
409 }
410
411private:
412 SubCommand *ActiveSubCommand = nullptr;
413
414 Option *LookupOption(SubCommand &Sub, StringRef &Arg, StringRef &Value);
415 Option *LookupLongOption(SubCommand &Sub, StringRef &Arg, StringRef &Value,
416 bool LongOptionsUseDoubleDash, bool HaveDoubleDash) {
417 Option *Opt = LookupOption(Sub, Arg, Value);
418 if (Opt && LongOptionsUseDoubleDash && !HaveDoubleDash && !isGrouping(Opt))
419 return nullptr;
420 return Opt;
421 }
422 SubCommand *LookupSubCommand(StringRef Name, std::string &NearestString);
423};
424
425} // namespace
426
428
429template <typename T, T TrueVal, T FalseVal>
430static bool parseBool(Option &O, StringRef ArgName, StringRef Arg, T &Value) {
431 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
432 Arg == "1") {
433 Value = TrueVal;
434 return false;
435 }
436
437 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
438 Value = FalseVal;
439 return false;
440 }
441 return O.error("'" + Arg +
442 "' is invalid value for boolean argument! Try 0 or 1");
443}
444
446 GlobalParser->addLiteralOption(O, Name);
447}
448
450 GlobalParser->MoreHelp.push_back(Help);
451}
452
454 GlobalParser->addOption(this);
455 FullyInitialized = true;
456}
457
458void Option::removeArgument() { GlobalParser->removeOption(this); }
459
461 if (FullyInitialized)
462 GlobalParser->updateArgStr(this, S);
463 assert(!S.starts_with("-") && "Option can't start with '-");
464 ArgStr = S;
465 if (ArgStr.size() == 1)
467}
468
470 assert(!Categories.empty() && "Categories cannot be empty.");
471 // Maintain backward compatibility by replacing the default GeneralCategory
472 // if it's still set. Otherwise, just add the new one. The GeneralCategory
473 // must be explicitly added if you want multiple categories that include it.
474 if (&C != &getGeneralCategory() && Categories[0] == &getGeneralCategory())
475 Categories[0] = &C;
476 else if (!is_contained(Categories, &C))
477 Categories.push_back(&C);
478}
479
481 NumOccurrences = 0;
482 setDefault();
483 if (isDefaultOption())
485}
486
487void OptionCategory::registerCategory() {
488 GlobalParser->registerCategory(this);
489}
490
491// A special subcommand representing no subcommand. It is particularly important
492// that this ManagedStatic uses constant initailization and not dynamic
493// initialization because it is referenced from cl::opt constructors, which run
494// dynamically in an arbitrary order.
497
498// A special subcommand that can be used to put an option into all subcommands.
500
502
504
506 GlobalParser->registerSubCommand(this);
507}
508
510 GlobalParser->unregisterSubCommand(this);
511}
512
514 PositionalOpts.clear();
515 SinkOpts.clear();
516 OptionsMap.clear();
517
518 ConsumeAfterOpt = nullptr;
519}
520
521SubCommand::operator bool() const {
522 return (GlobalParser->getActiveSubCommand() == this);
523}
524
525//===----------------------------------------------------------------------===//
526// Basic, shared command line option processing machinery.
527//
528
529/// LookupOption - Lookup the option specified by the specified option on the
530/// command line. If there is a value specified (after an equal sign) return
531/// that as well. This assumes that leading dashes have already been stripped.
532Option *CommandLineParser::LookupOption(SubCommand &Sub, StringRef &Arg,
533 StringRef &Value) {
534 // Reject all dashes.
535 if (Arg.empty())
536 return nullptr;
538
539 size_t EqualPos = Arg.find('=');
540
541 // If we have an equals sign, remember the value.
542 if (EqualPos == StringRef::npos) {
543 // Look up the option.
544 return Sub.OptionsMap.lookup(Arg);
545 }
546
547 // If the argument before the = is a valid option name and the option allows
548 // non-prefix form (ie is not AlwaysPrefix), we match. If not, signal match
549 // failure by returning nullptr.
550 auto I = Sub.OptionsMap.find(Arg.substr(0, EqualPos));
551 if (I == Sub.OptionsMap.end())
552 return nullptr;
553
554 auto *O = I->second;
555 if (O->getFormattingFlag() == cl::AlwaysPrefix)
556 return nullptr;
557
558 Value = Arg.substr(EqualPos + 1);
559 Arg = Arg.substr(0, EqualPos);
560 return I->second;
561}
562
563SubCommand *CommandLineParser::LookupSubCommand(StringRef Name,
564 std::string &NearestString) {
565 if (Name.empty())
566 return &SubCommand::getTopLevel();
567 // Find a subcommand with the edit distance == 1.
568 SubCommand *NearestMatch = nullptr;
569 for (auto *S : RegisteredSubCommands) {
570 assert(S != &SubCommand::getAll() &&
571 "SubCommand::getAll() is not expected in RegisteredSubCommands");
572 if (S->getName().empty())
573 continue;
574
575 if (S->getName() == Name)
576 return S;
577
578 if (!NearestMatch && S->getName().edit_distance(Name) < 2)
579 NearestMatch = S;
580 }
581
582 if (NearestMatch)
583 NearestString = NearestMatch->getName();
584
585 return &SubCommand::getTopLevel();
586}
587
588/// LookupNearestOption - Lookup the closest match to the option specified by
589/// the specified option on the command line. If there is a value specified
590/// (after an equal sign) return that as well. This assumes that leading dashes
591/// have already been stripped.
593 const OptionsMapTy &OptionsMap,
594 std::string &NearestString) {
595 // Reject all dashes.
596 if (Arg.empty())
597 return nullptr;
598
599 // Split on any equal sign.
600 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
601 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
602 StringRef &RHS = SplitArg.second;
603
604 // Find the closest match.
605 Option *Best = nullptr;
606 unsigned BestDistance = 0;
607 for (const auto &[_, O] : OptionsMap) {
608 // Do not suggest really hidden options (not shown in any help).
609 if (O->getOptionHiddenFlag() == ReallyHidden)
610 continue;
611
612 SmallVector<StringRef, 16> OptionNames;
613 O->getExtraOptionNames(OptionNames);
614 if (O->hasArgStr())
615 OptionNames.push_back(O->ArgStr);
616
617 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
618 StringRef Flag = PermitValue ? LHS : Arg;
619 for (const auto &Name : OptionNames) {
620 unsigned Distance = StringRef(Name).edit_distance(
621 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
622 if (!Best || Distance < BestDistance) {
623 Best = O;
624 BestDistance = Distance;
625 if (RHS.empty() || !PermitValue)
626 NearestString = std::string(Name);
627 else
628 NearestString = (Twine(Name) + "=" + RHS).str();
629 }
630 }
631 }
632
633 return Best;
634}
635
636/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
637/// that does special handling of cl::CommaSeparated options.
638static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
639 StringRef ArgName, StringRef Value,
640 bool MultiArg = false) {
641 // Check to see if this option accepts a comma separated list of values. If
642 // it does, we have to split up the value into multiple values.
643 if (Handler->getMiscFlags() & CommaSeparated) {
644 StringRef Val(Value);
645 StringRef::size_type Pos = Val.find(',');
646
647 while (Pos != StringRef::npos) {
648 // Process the portion before the comma.
649 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
650 return true;
651 // Erase the portion before the comma, AND the comma.
652 Val = Val.substr(Pos + 1);
653 // Check for another comma.
654 Pos = Val.find(',');
655 }
656
657 Value = Val;
658 }
659
660 return Handler->addOccurrence(pos, ArgName, Value, MultiArg);
661}
662
663/// ProvideOption - For Value, this differentiates between an empty value ("")
664/// and a null value (StringRef()). The later is accepted for arguments that
665/// don't allow a value (-foo) the former is rejected (-foo=).
666static inline bool ProvideOption(Option *Handler, StringRef ArgName,
667 StringRef Value, int argc,
668 const char *const *argv, int &i) {
669 // Is this a multi-argument option?
670 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
671
672 // Enforce value requirements
673 switch (Handler->getValueExpectedFlag()) {
674 case ValueRequired:
675 if (!Value.data()) { // No value specified?
676 // If no other argument or the option only supports prefix form, we
677 // cannot look at the next argument.
678 if (i + 1 >= argc || Handler->getFormattingFlag() == cl::AlwaysPrefix)
679 return Handler->error("requires a value!");
680 // Steal the next argument, like for '-o filename'
681 assert(argv && "null check");
682 Value = StringRef(argv[++i]);
683 }
684 break;
685 case ValueDisallowed:
686 if (NumAdditionalVals > 0)
687 return Handler->error("multi-valued option specified"
688 " with ValueDisallowed modifier!");
689
690 if (Value.data())
691 return Handler->error("does not allow a value! '" + Twine(Value) +
692 "' specified.");
693 break;
694 case ValueOptional:
695 break;
696 }
697
698 // If this isn't a multi-arg option, just run the handler.
699 if (NumAdditionalVals == 0)
700 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
701
702 // If it is, run the handle several times.
703 bool MultiArg = false;
704
705 if (Value.data()) {
706 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
707 return true;
708 --NumAdditionalVals;
709 MultiArg = true;
710 }
711
712 while (NumAdditionalVals > 0) {
713 if (i + 1 >= argc)
714 return Handler->error("not enough values!");
715 assert(argv && "null check");
716 Value = StringRef(argv[++i]);
717
718 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
719 return true;
720 MultiArg = true;
721 --NumAdditionalVals;
722 }
723 return false;
724}
725
727 int Dummy = i;
728 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
729}
730
731// getOptionPred - Check to see if there are any options that satisfy the
732// specified predicate with names that are the prefixes in Name. This is
733// checked by progressively stripping characters off of the name, checking to
734// see if there options that satisfy the predicate. If we find one, return it,
735// otherwise return null.
736//
737static Option *getOptionPred(StringRef Name, size_t &Length,
738 bool (*Pred)(const Option *),
739 const OptionsMapTy &OptionsMap) {
740 auto OMI = OptionsMap.find(Name);
741 if (OMI != OptionsMap.end() && !Pred(OMI->second))
742 OMI = OptionsMap.end();
743
744 // Loop while we haven't found an option and Name still has at least two
745 // characters in it (so that the next iteration will not be the empty
746 // string.
747 while (OMI == OptionsMap.end() && Name.size() > 1) {
748 Name = Name.drop_back();
749 OMI = OptionsMap.find(Name);
750 if (OMI != OptionsMap.end() && !Pred(OMI->second))
751 OMI = OptionsMap.end();
752 }
753
754 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
755 Length = Name.size();
756 return OMI->second; // Found one!
757 }
758 return nullptr; // No option found!
759}
760
761/// HandlePrefixedOrGroupedOption - The specified argument string (which started
762/// with at least one '-') does not fully match an available option. Check to
763/// see if this is a prefix or grouped option. If so, split arg into output an
764/// Arg/Value pair and return the Option to parse it with.
766 bool &ErrorParsing,
767 const OptionsMapTy &OptionsMap) {
768 if (Arg.size() == 1)
769 return nullptr;
770
771 // Do the lookup!
772 size_t Length = 0;
773 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
774 if (!PGOpt)
775 return nullptr;
776
777 do {
778 StringRef MaybeValue =
779 (Length < Arg.size()) ? Arg.substr(Length) : StringRef();
780 Arg = Arg.substr(0, Length);
781 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
782
783 // cl::Prefix options do not preserve '=' when used separately.
784 // The behavior for them with grouped options should be the same.
785 if (MaybeValue.empty() || PGOpt->getFormattingFlag() == cl::AlwaysPrefix ||
786 (PGOpt->getFormattingFlag() == cl::Prefix && MaybeValue[0] != '=')) {
787 Value = MaybeValue;
788 return PGOpt;
789 }
790
791 if (MaybeValue[0] == '=') {
792 Value = MaybeValue.substr(1);
793 return PGOpt;
794 }
795
796 // This must be a grouped option.
797 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
798
799 // Grouping options inside a group can't have values.
800 if (PGOpt->getValueExpectedFlag() == cl::ValueRequired) {
801 ErrorParsing |= PGOpt->error("may not occur within a group!");
802 return nullptr;
803 }
804
805 // Because the value for the option is not required, we don't need to pass
806 // argc/argv in.
807 int Dummy = 0;
808 ErrorParsing |= ProvideOption(PGOpt, Arg, StringRef(), 0, nullptr, Dummy);
809
810 // Get the next grouping option.
811 Arg = MaybeValue;
812 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
813 } while (PGOpt);
814
815 // We could not find a grouping option in the remainder of Arg.
816 return nullptr;
817}
818
819static bool RequiresValue(const Option *O) {
820 return O->getNumOccurrencesFlag() == cl::Required ||
821 O->getNumOccurrencesFlag() == cl::OneOrMore;
822}
823
824static bool EatsUnboundedNumberOfValues(const Option *O) {
825 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
826 O->getNumOccurrencesFlag() == cl::OneOrMore;
827}
828
829static bool isWhitespace(char C) {
830 return C == ' ' || C == '\t' || C == '\r' || C == '\n';
831}
832
833static bool isWhitespaceOrNull(char C) {
834 return isWhitespace(C) || C == '\0';
835}
836
837static bool isQuote(char C) { return C == '\"' || C == '\''; }
838
841 bool MarkEOLs) {
842 SmallString<128> Token;
843 bool InToken = false;
844 for (size_t I = 0, E = Src.size(); I != E; ++I) {
845 // Consume runs of whitespace.
846 if (!InToken) {
847 while (I != E && isWhitespace(Src[I])) {
848 // Mark the end of lines in response files.
849 if (MarkEOLs && Src[I] == '\n')
850 NewArgv.push_back(nullptr);
851 ++I;
852 }
853 if (I == E)
854 break;
855 InToken = true;
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 NewArgv.push_back(Saver.save(Token.str()).data());
885 // Mark the end of lines in response files.
886 if (MarkEOLs && C == '\n')
887 NewArgv.push_back(nullptr);
888 Token.clear();
889 InToken = false;
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 (InToken)
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 // reset() removes default options from OptionsMap (via removeArgument), so
1499 // collect the options first to avoid invalidating the map iterator.
1501 Opts.reserve(SC->OptionsMap.size());
1502 for (auto &O : SC->OptionsMap)
1503 Opts.push_back(O.second);
1504 for (Option *O : Opts)
1505 O->reset();
1506 for (Option *O : SC->PositionalOpts)
1507 O->reset();
1508 for (Option *O : SC->SinkOpts)
1509 O->reset();
1510 if (SC->ConsumeAfterOpt)
1511 SC->ConsumeAfterOpt->reset();
1512 }
1513}
1514
1515bool CommandLineParser::ParseCommandLineOptions(
1516 int argc, const char *const *argv, StringRef Overview, raw_ostream *Errs,
1517 vfs::FileSystem *VFS, bool LongOptionsUseDoubleDash) {
1518 assert(hasOptions() && "No options specified!");
1519
1520 ProgramOverview = Overview;
1521 bool IgnoreErrors = Errs;
1522 if (!Errs)
1523 Errs = &errs();
1524 if (!VFS)
1525 VFS = vfs::getRealFileSystem().get();
1526 bool ErrorParsing = false;
1527
1528 // Expand response files.
1529 SmallVector<const char *, 20> newArgv(argv, argv + argc);
1531#ifdef _WIN32
1532 auto Tokenize = cl::TokenizeWindowsCommandLine;
1533#else
1534 auto Tokenize = cl::TokenizeGNUCommandLine;
1535#endif
1536 ExpansionContext ECtx(A, Tokenize, VFS);
1537 if (Error Err = ECtx.expandResponseFiles(newArgv)) {
1538 *Errs << toString(std::move(Err)) << '\n';
1539 return false;
1540 }
1541 argv = &newArgv[0];
1542 argc = static_cast<int>(newArgv.size());
1543
1544 // Copy the program name into ProgName, making sure not to overflow it.
1545 ProgramName = std::string(sys::path::filename(StringRef(argv[0])));
1546
1547 // Check out the positional arguments to collect information about them.
1548 unsigned NumPositionalRequired = 0;
1549
1550 // Determine whether or not there are an unlimited number of positionals
1551 bool HasUnlimitedPositionals = false;
1552
1553 int FirstArg = 1;
1554 SubCommand *ChosenSubCommand = &SubCommand::getTopLevel();
1555 std::string NearestSubCommandString;
1556 bool MaybeNamedSubCommand =
1557 argc >= 2 && argv[FirstArg][0] != '-' && hasNamedSubCommands();
1558 if (MaybeNamedSubCommand) {
1559 // If the first argument specifies a valid subcommand, start processing
1560 // options from the second argument.
1561 ChosenSubCommand =
1562 LookupSubCommand(StringRef(argv[FirstArg]), NearestSubCommandString);
1563 if (ChosenSubCommand != &SubCommand::getTopLevel())
1564 FirstArg = 2;
1565 }
1566 GlobalParser->ActiveSubCommand = ChosenSubCommand;
1567
1568 assert(ChosenSubCommand);
1569 auto &ConsumeAfterOpt = ChosenSubCommand->ConsumeAfterOpt;
1570 auto &PositionalOpts = ChosenSubCommand->PositionalOpts;
1571 auto &SinkOpts = ChosenSubCommand->SinkOpts;
1572 auto &OptionsMap = ChosenSubCommand->OptionsMap;
1573
1574 for (auto *O: DefaultOptions) {
1575 addOption(O, true);
1576 }
1577
1578 if (ConsumeAfterOpt) {
1579 assert(PositionalOpts.size() > 0 &&
1580 "Cannot specify cl::ConsumeAfter without a positional argument!");
1581 }
1582 if (!PositionalOpts.empty()) {
1583
1584 // Calculate how many positional values are _required_.
1585 bool UnboundedFound = false;
1586 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1587 Option *Opt = PositionalOpts[i];
1588 if (RequiresValue(Opt))
1589 ++NumPositionalRequired;
1590 else if (ConsumeAfterOpt) {
1591 // ConsumeAfter cannot be combined with "optional" positional options
1592 // unless there is only one positional argument...
1593 if (PositionalOpts.size() > 1) {
1594 if (!IgnoreErrors)
1595 Opt->error("error - this positional option will never be matched, "
1596 "because it does not Require a value, and a "
1597 "cl::ConsumeAfter option is active!");
1598 ErrorParsing = true;
1599 }
1600 } else if (UnboundedFound && !Opt->hasArgStr()) {
1601 // This option does not "require" a value... Make sure this option is
1602 // not specified after an option that eats all extra arguments, or this
1603 // one will never get any!
1604 //
1605 if (!IgnoreErrors)
1606 Opt->error("error - option can never match, because "
1607 "another positional argument will match an "
1608 "unbounded number of values, and this option"
1609 " does not require a value!");
1610 *Errs << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
1611 << "' is all messed up!\n";
1612 *Errs << PositionalOpts.size();
1613 ErrorParsing = true;
1614 }
1615 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
1616 }
1617 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
1618 }
1619
1620 // PositionalVals - A vector of "positional" arguments we accumulate into
1621 // the process at the end.
1622 //
1624
1625 // If the program has named positional arguments, and the name has been run
1626 // across, keep track of which positional argument was named. Otherwise put
1627 // the positional args into the PositionalVals list...
1628 Option *ActivePositionalArg = nullptr;
1629
1630 // Loop over all of the arguments... processing them.
1631 bool DashDashFound = false; // Have we read '--'?
1632 for (int i = FirstArg; i < argc; ++i) {
1633 Option *Handler = nullptr;
1634 std::string NearestHandlerString;
1635 StringRef Value;
1636 StringRef ArgName = "";
1637 bool HaveDoubleDash = false;
1638
1639 // Check to see if this is a positional argument. This argument is
1640 // considered to be positional if it doesn't start with '-', if it is "-"
1641 // itself, or if we have seen "--" already.
1642 //
1643 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
1644 // Positional argument!
1645 if (ActivePositionalArg) {
1646 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1647 continue; // We are done!
1648 }
1649
1650 if (!PositionalOpts.empty()) {
1651 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1652
1653 // All of the positional arguments have been fulfulled, give the rest to
1654 // the consume after option... if it's specified...
1655 //
1656 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
1657 for (++i; i < argc; ++i)
1658 PositionalVals.push_back(std::make_pair(StringRef(argv[i]), i));
1659 break; // Handle outside of the argument processing loop...
1660 }
1661
1662 // Delay processing positional arguments until the end...
1663 continue;
1664 }
1665 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
1666 !DashDashFound) {
1667 DashDashFound = true; // This is the mythical "--"?
1668 continue; // Don't try to process it as an argument itself.
1669 } else if (ActivePositionalArg &&
1670 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
1671 // If there is a positional argument eating options, check to see if this
1672 // option is another positional argument. If so, treat it as an argument,
1673 // otherwise feed it to the eating positional.
1674 ArgName = StringRef(argv[i] + 1);
1675 // Eat second dash.
1676 if (ArgName.consume_front("-"))
1677 HaveDoubleDash = true;
1678
1679 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1680 LongOptionsUseDoubleDash, HaveDoubleDash);
1681 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
1682 ProvidePositionalOption(ActivePositionalArg, StringRef(argv[i]), i);
1683 continue; // We are done!
1684 }
1685 } else { // We start with a '-', must be an argument.
1686 ArgName = StringRef(argv[i] + 1);
1687 // Eat second dash.
1688 if (ArgName.consume_front("-"))
1689 HaveDoubleDash = true;
1690
1691 Handler = LookupLongOption(*ChosenSubCommand, ArgName, Value,
1692 LongOptionsUseDoubleDash, HaveDoubleDash);
1693
1694 // If Handler is not found in a specialized subcommand, look up handler
1695 // in the top-level subcommand.
1696 // cl::opt without cl::sub belongs to top-level subcommand.
1697 if (!Handler && ChosenSubCommand != &SubCommand::getTopLevel())
1698 Handler = LookupLongOption(SubCommand::getTopLevel(), ArgName, Value,
1699 LongOptionsUseDoubleDash, HaveDoubleDash);
1700
1701 // Check to see if this "option" is really a prefixed or grouped argument.
1702 if (!Handler && !(LongOptionsUseDoubleDash && HaveDoubleDash))
1703 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
1704 OptionsMap);
1705
1706 // Otherwise, look for the closest available option to report to the user
1707 // in the upcoming error.
1708 if (!Handler && SinkOpts.empty())
1709 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
1710 }
1711
1712 if (!Handler) {
1713 if (!SinkOpts.empty()) {
1714 for (Option *SinkOpt : SinkOpts)
1715 SinkOpt->addOccurrence(i, "", StringRef(argv[i]));
1716 continue;
1717 }
1718
1719 auto ReportUnknownArgument = [&](bool IsArg,
1720 StringRef NearestArgumentName) {
1721 *Errs << ProgramName << ": Unknown "
1722 << (IsArg ? "command line argument" : "subcommand") << " '"
1723 << argv[i] << "'. Try: '" << argv[0] << " --help'\n";
1724
1725 if (NearestArgumentName.empty())
1726 return;
1727
1728 *Errs << ProgramName << ": Did you mean '";
1729 if (IsArg)
1730 *Errs << PrintArg(NearestArgumentName, 0);
1731 else
1732 *Errs << NearestArgumentName;
1733 *Errs << "'?\n";
1734 };
1735
1736 if (i > 1 || !MaybeNamedSubCommand)
1737 ReportUnknownArgument(/*IsArg=*/true, NearestHandlerString);
1738 else
1739 ReportUnknownArgument(/*IsArg=*/false, NearestSubCommandString);
1740
1741 ErrorParsing = true;
1742 continue;
1743 }
1744
1745 // If this is a named positional argument, just remember that it is the
1746 // active one...
1747 if (Handler->getFormattingFlag() == cl::Positional) {
1748 if ((Handler->getMiscFlags() & PositionalEatsArgs) && !Value.empty()) {
1749 Handler->error("This argument does not take a value.\n"
1750 "\tInstead, it consumes any positional arguments until "
1751 "the next recognized option.", *Errs);
1752 ErrorParsing = true;
1753 }
1754 ActivePositionalArg = Handler;
1755 }
1756 else
1757 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
1758 }
1759
1760 // Check and handle positional arguments now...
1761 if (NumPositionalRequired > PositionalVals.size()) {
1762 *Errs << ProgramName
1763 << ": Not enough positional command line arguments specified!\n"
1764 << "Must specify at least " << NumPositionalRequired
1765 << " positional argument" << (NumPositionalRequired > 1 ? "s" : "")
1766 << ": See: " << argv[0] << " --help\n";
1767
1768 ErrorParsing = true;
1769 } else if (!HasUnlimitedPositionals &&
1770 PositionalVals.size() > PositionalOpts.size()) {
1771 *Errs << ProgramName << ": Too many positional arguments specified!\n"
1772 << "Can specify at most " << PositionalOpts.size()
1773 << " positional arguments: See: " << argv[0] << " --help\n";
1774 ErrorParsing = true;
1775
1776 } else if (!ConsumeAfterOpt) {
1777 // Positional args have already been handled if ConsumeAfter is specified.
1778 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1779 for (Option *Opt : PositionalOpts) {
1780 if (RequiresValue(Opt)) {
1781 ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1782 PositionalVals[ValNo].second);
1783 ValNo++;
1784 --NumPositionalRequired; // We fulfilled our duty...
1785 }
1786
1787 // If we _can_ give this option more arguments, do so now, as long as we
1788 // do not give it values that others need. 'Done' controls whether the
1789 // option even _WANTS_ any more.
1790 //
1791 bool Done = Opt->getNumOccurrencesFlag() == cl::Required;
1792 while (NumVals - ValNo > NumPositionalRequired && !Done) {
1793 switch (Opt->getNumOccurrencesFlag()) {
1794 case cl::Optional:
1795 Done = true; // Optional arguments want _at most_ one value
1796 [[fallthrough]];
1797 case cl::ZeroOrMore: // Zero or more will take all they can get...
1798 case cl::OneOrMore: // One or more will take all they can get...
1799 ProvidePositionalOption(Opt, PositionalVals[ValNo].first,
1800 PositionalVals[ValNo].second);
1801 ValNo++;
1802 break;
1803 default:
1804 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1805 "positional argument processing!");
1806 }
1807 }
1808 }
1809 } else {
1810 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1811 unsigned ValNo = 0;
1812 for (Option *Opt : PositionalOpts)
1813 if (RequiresValue(Opt)) {
1814 ErrorParsing |= ProvidePositionalOption(
1815 Opt, PositionalVals[ValNo].first, PositionalVals[ValNo].second);
1816 ValNo++;
1817 }
1818
1819 // Handle the case where there is just one positional option, and it's
1820 // optional. In this case, we want to give JUST THE FIRST option to the
1821 // positional option and keep the rest for the consume after. The above
1822 // loop would have assigned no values to positional options in this case.
1823 //
1824 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1825 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
1826 PositionalVals[ValNo].first,
1827 PositionalVals[ValNo].second);
1828 ValNo++;
1829 }
1830
1831 // Handle over all of the rest of the arguments to the
1832 // cl::ConsumeAfter command line option...
1833 for (; ValNo != PositionalVals.size(); ++ValNo)
1834 ErrorParsing |=
1835 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1836 PositionalVals[ValNo].second);
1837 }
1838
1839 // Loop over args and make sure all required args are specified!
1840 for (const auto &Opt : OptionsMap) {
1841 switch (Opt.second->getNumOccurrencesFlag()) {
1842 case Required:
1843 case OneOrMore:
1844 if (Opt.second->getNumOccurrences() == 0) {
1845 Opt.second->error("must be specified at least once!");
1846 ErrorParsing = true;
1847 }
1848 [[fallthrough]];
1849 default:
1850 break;
1851 }
1852 }
1853
1854 // Now that we know if -debug is specified, we can use it.
1855 // Note that if ReadResponseFiles == true, this must be done before the
1856 // memory allocated for the expanded command line is free()d below.
1857 LLVM_DEBUG(dbgs() << "Args: ";
1858 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1859 dbgs() << '\n';);
1860
1861 // Free all of the memory allocated to the map. Command line options may only
1862 // be processed once!
1863 MoreHelp.clear();
1864
1865 // If we had an error processing our arguments, don't let the program execute
1866 if (ErrorParsing) {
1867 if (!IgnoreErrors)
1868 exit(1);
1869 return false;
1870 }
1871 return true;
1872}
1873
1874//===----------------------------------------------------------------------===//
1875// Option Base class implementation
1876//
1877
1878bool Option::error(const Twine &Message, StringRef ArgName, raw_ostream &Errs) {
1879 if (!ArgName.data())
1880 ArgName = ArgStr;
1881 if (ArgName.empty())
1882 Errs << HelpStr; // Be nice for positional arguments
1883 else
1884 Errs << GlobalParser->ProgramName << ": for the " << PrintArg(ArgName, 0);
1885
1886 Errs << " option: " << Message << "\n";
1887 return true;
1888}
1889
1890bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1891 bool MultiArg) {
1892 if (!MultiArg)
1893 NumOccurrences++; // Increment the number of times we have been seen
1894
1895 return handleOccurrence(pos, ArgName, Value);
1896}
1897
1898// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1899// has been specified yet.
1900//
1901static StringRef getValueStr(const Option &O, StringRef DefaultMsg) {
1902 if (O.ValueStr.empty())
1903 return DefaultMsg;
1904 return O.ValueStr;
1905}
1906
1907//===----------------------------------------------------------------------===//
1908// cl::alias class implementation
1909//
1910
1911// Return the width of the option tag for printing...
1912size_t alias::getOptionWidth() const {
1914}
1915
1917 size_t FirstLineIndentedBy) {
1918 assert(Indent >= FirstLineIndentedBy);
1919 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1920 outs().indent(Indent - FirstLineIndentedBy)
1921 << ArgHelpPrefix << Split.first << "\n";
1922 while (!Split.second.empty()) {
1923 Split = Split.second.split('\n');
1924 outs().indent(Indent) << Split.first << "\n";
1925 }
1926}
1927
1929 size_t FirstLineIndentedBy) {
1930 const StringRef ValHelpPrefix = " ";
1931 assert(BaseIndent >= FirstLineIndentedBy);
1932 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1933 outs().indent(BaseIndent - FirstLineIndentedBy)
1934 << ArgHelpPrefix << ValHelpPrefix << Split.first << "\n";
1935 while (!Split.second.empty()) {
1936 Split = Split.second.split('\n');
1937 outs().indent(BaseIndent + ValHelpPrefix.size()) << Split.first << "\n";
1938 }
1939}
1940
1941// Print out the option for the alias.
1942void alias::printOptionInfo(size_t GlobalWidth) const {
1943 outs() << PrintArg(ArgStr);
1945}
1946
1947//===----------------------------------------------------------------------===//
1948// Parser Implementation code...
1949//
1950
1951// basic_parser implementation
1952//
1953
1954// Return the width of the option tag for printing...
1956 size_t Len = argPlusPrefixesSize(O.ArgStr);
1957 auto ValName = getValueName();
1958 if (!ValName.empty()) {
1959 size_t FormattingLen = 3;
1960 if (O.getMiscFlags() & PositionalEatsArgs)
1961 FormattingLen = 6;
1962 Len += getValueStr(O, ValName).size() + FormattingLen;
1963 }
1964
1965 return Len;
1966}
1967
1968// printOptionInfo - Print out information about this option. The
1969// to-be-maintained width is specified.
1970//
1972 size_t GlobalWidth) const {
1973 outs() << PrintArg(O.ArgStr);
1974
1975 auto ValName = getValueName();
1976 if (!ValName.empty()) {
1977 if (O.getMiscFlags() & PositionalEatsArgs) {
1978 outs() << " <" << getValueStr(O, ValName) << ">...";
1979 } else if (O.getValueExpectedFlag() == ValueOptional)
1980 outs() << "[=<" << getValueStr(O, ValName) << ">]";
1981 else {
1982 outs() << (O.ArgStr.size() == 1 ? " <" : "=<") << getValueStr(O, ValName)
1983 << '>';
1984 }
1985 }
1986
1987 Option::printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1988}
1989
1991 size_t GlobalWidth) const {
1992 outs() << PrintArg(O.ArgStr);
1993 outs().indent(GlobalWidth - O.ArgStr.size());
1994}
1995
1996// parser<bool> implementation
1997//
1998bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1999 bool &Value) {
2000 return parseBool<bool, true, false>(O, ArgName, Arg, Value);
2001}
2002
2003// parser<boolOrDefault> implementation
2004//
2008}
2009
2010// parser<int> implementation
2011//
2012bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
2013 int &Value) {
2014 if (Arg.getAsInteger(0, Value))
2015 return O.error("'" + Arg + "' value invalid for integer argument!");
2016 return false;
2017}
2018
2019// parser<long> implementation
2020//
2021bool parser<long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2022 long &Value) {
2023 if (Arg.getAsInteger(0, Value))
2024 return O.error("'" + Arg + "' value invalid for long argument!");
2025 return false;
2026}
2027
2028// parser<long long> implementation
2029//
2030bool parser<long long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2031 long long &Value) {
2032 if (Arg.getAsInteger(0, Value))
2033 return O.error("'" + Arg + "' value invalid for llong argument!");
2034 return false;
2035}
2036
2037// parser<unsigned> implementation
2038//
2039bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
2040 unsigned &Value) {
2041
2042 if (Arg.getAsInteger(0, Value))
2043 return O.error("'" + Arg + "' value invalid for uint argument!");
2044 return false;
2045}
2046
2047// parser<unsigned long> implementation
2048//
2049bool parser<unsigned long>::parse(Option &O, StringRef ArgName, StringRef Arg,
2050 unsigned long &Value) {
2051
2052 if (Arg.getAsInteger(0, Value))
2053 return O.error("'" + Arg + "' value invalid for ulong argument!");
2054 return false;
2055}
2056
2057// parser<unsigned long long> implementation
2058//
2059bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
2060 StringRef Arg,
2061 unsigned long long &Value) {
2062
2063 if (Arg.getAsInteger(0, Value))
2064 return O.error("'" + Arg + "' value invalid for ullong argument!");
2065 return false;
2066}
2067
2068// parser<double>/parser<float> implementation
2069//
2070static bool parseDouble(Option &O, StringRef Arg, double &Value) {
2071 if (to_float(Arg, Value))
2072 return false;
2073 return O.error("'" + Arg + "' value invalid for floating point argument!");
2074}
2075
2076bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
2077 double &Val) {
2078 return parseDouble(O, Arg, Val);
2079}
2080
2081bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
2082 float &Val) {
2083 double dVal;
2084 if (parseDouble(O, Arg, dVal))
2085 return true;
2086 Val = (float)dVal;
2087 return false;
2088}
2089
2090// generic_parser_base implementation
2091//
2092
2093// findOption - Return the option number corresponding to the specified
2094// argument string. If the option is not found, getNumOptions() is returned.
2095//
2097 unsigned e = getNumOptions();
2098
2099 for (unsigned i = 0; i != e; ++i) {
2100 if (getOption(i) == Name)
2101 return i;
2102 }
2103 return e;
2104}
2105
2106static StringRef EqValue = "=<value>";
2107static StringRef EmptyOption = "<empty>";
2109static size_t getOptionPrefixesSize() {
2110 return OptionPrefix.size() + ArgHelpPrefix.size();
2111}
2112
2113static bool shouldPrintOption(StringRef Name, StringRef Description,
2114 const Option &O) {
2115 return O.getValueExpectedFlag() != ValueOptional || !Name.empty() ||
2116 !Description.empty();
2117}
2118
2119// Return the width of the option tag for printing...
2121 if (O.hasArgStr()) {
2122 size_t Size =
2123 argPlusPrefixesSize(O.ArgStr) + EqValue.size();
2124 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2125 StringRef Name = getOption(i);
2126 if (!shouldPrintOption(Name, getDescription(i), O))
2127 continue;
2128 size_t NameSize = Name.empty() ? EmptyOption.size() : Name.size();
2129 Size = std::max(Size, NameSize + getOptionPrefixesSize());
2130 }
2131 return Size;
2132 } else {
2133 size_t BaseSize = 0;
2134 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
2135 BaseSize = std::max(BaseSize, getOption(i).size() + 8);
2136 return BaseSize;
2137 }
2138}
2139
2140// printOptionInfo - Print out information about this option. The
2141// to-be-maintained width is specified.
2142//
2144 size_t GlobalWidth) const {
2145 if (O.hasArgStr()) {
2146 // When the value is optional, first print a line just describing the
2147 // option without values.
2148 if (O.getValueExpectedFlag() == ValueOptional) {
2149 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2150 if (getOption(i).empty()) {
2151 outs() << PrintArg(O.ArgStr);
2152 Option::printHelpStr(O.HelpStr, GlobalWidth,
2153 argPlusPrefixesSize(O.ArgStr));
2154 break;
2155 }
2156 }
2157 }
2158
2159 outs() << PrintArg(O.ArgStr) << EqValue;
2160 Option::printHelpStr(O.HelpStr, GlobalWidth,
2161 EqValue.size() +
2162 argPlusPrefixesSize(O.ArgStr));
2163 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2164 StringRef OptionName = getOption(i);
2165 StringRef Description = getDescription(i);
2166 if (!shouldPrintOption(OptionName, Description, O))
2167 continue;
2168 size_t FirstLineIndent = OptionName.size() + getOptionPrefixesSize();
2169 outs() << OptionPrefix << OptionName;
2170 if (OptionName.empty()) {
2171 outs() << EmptyOption;
2172 assert(FirstLineIndent >= EmptyOption.size());
2173 FirstLineIndent += EmptyOption.size();
2174 }
2175 if (!Description.empty())
2176 Option::printEnumValHelpStr(Description, GlobalWidth, FirstLineIndent);
2177 else
2178 outs() << '\n';
2179 }
2180 } else {
2181 if (!O.HelpStr.empty())
2182 outs() << " " << O.HelpStr << '\n';
2183 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
2185 outs() << " " << PrintArg(Option);
2186 Option::printHelpStr(getDescription(i), GlobalWidth, Option.size() + 8);
2187 }
2188 }
2189}
2190
2191static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
2192
2193// printGenericOptionDiff - Print the value of this option and it's default.
2194//
2195// "Generic" options have each value mapped to a name.
2197 const Option &O, const GenericOptionValue &Value,
2198 const GenericOptionValue &Default, size_t GlobalWidth) const {
2199 outs() << " " << PrintArg(O.ArgStr);
2200 outs().indent(GlobalWidth - O.ArgStr.size());
2201
2202 unsigned NumOpts = getNumOptions();
2203 for (unsigned i = 0; i != NumOpts; ++i) {
2204 if (!Value.compare(getOptionValue(i)))
2205 continue;
2206
2207 outs() << "= " << getOption(i);
2208 size_t L = getOption(i).size();
2209 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
2210 outs().indent(NumSpaces) << " (default: ";
2211 for (unsigned j = 0; j != NumOpts; ++j) {
2212 if (!Default.compare(getOptionValue(j)))
2213 continue;
2214 outs() << getOption(j);
2215 break;
2216 }
2217 outs() << ")\n";
2218 return;
2219 }
2220 outs() << "= *unknown option value*\n";
2221}
2222
2223// printOptionDiff - Specializations for printing basic value types.
2224//
2225#define PRINT_OPT_DIFF(T) \
2226 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
2227 size_t GlobalWidth) const { \
2228 printOptionName(O, GlobalWidth); \
2229 std::string Str; \
2230 { \
2231 raw_string_ostream SS(Str); \
2232 SS << V; \
2233 } \
2234 outs() << "= " << Str; \
2235 size_t NumSpaces = \
2236 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
2237 outs().indent(NumSpaces) << " (default: "; \
2238 if (D.hasValue()) \
2239 outs() << D.getValue(); \
2240 else \
2241 outs() << "*no default*"; \
2242 outs() << ")\n"; \
2243 }
2244
2245PRINT_OPT_DIFF(bool)
2247PRINT_OPT_DIFF(int)
2248PRINT_OPT_DIFF(long)
2249PRINT_OPT_DIFF(long long)
2250PRINT_OPT_DIFF(unsigned)
2251PRINT_OPT_DIFF(unsigned long)
2252PRINT_OPT_DIFF(unsigned long long)
2253PRINT_OPT_DIFF(double)
2254PRINT_OPT_DIFF(float)
2255PRINT_OPT_DIFF(char)
2256
2259 size_t GlobalWidth) const {
2260 printOptionName(O, GlobalWidth);
2261 outs() << "= " << V;
2262 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
2263 outs().indent(NumSpaces) << " (default: ";
2264 if (D.hasValue())
2265 outs() << D.getValue();
2266 else
2267 outs() << "*no default*";
2268 outs() << ")\n";
2269}
2270
2272 const Option &O, std::optional<StringRef> V,
2273 const OptionValue<std::optional<std::string>> &D,
2274 size_t GlobalWidth) const {
2275 printOptionName(O, GlobalWidth);
2276 outs() << "= " << V;
2277 size_t VSize = V.has_value() ? V.value().size() : 0;
2278 size_t NumSpaces = MaxOptWidth > VSize ? MaxOptWidth - VSize : 0;
2279 outs().indent(NumSpaces) << " (default: ";
2280 if (D.hasValue() && D.getValue().has_value())
2281 outs() << D.getValue();
2282 else
2283 outs() << "*no value*";
2284 outs() << ")\n";
2285}
2286
2287// Print a placeholder for options that don't yet support printOptionDiff().
2289 size_t GlobalWidth) const {
2290 printOptionName(O, GlobalWidth);
2291 outs() << "= *cannot print option value*\n";
2292}
2293
2294//===----------------------------------------------------------------------===//
2295// -help and -help-hidden option implementation
2296//
2297
2298static int OptNameCompare(const std::pair<const char *, Option *> *LHS,
2299 const std::pair<const char *, Option *> *RHS) {
2300 return strcmp(LHS->first, RHS->first);
2301}
2302
2303static int SubNameCompare(const std::pair<const char *, SubCommand *> *LHS,
2304 const std::pair<const char *, SubCommand *> *RHS) {
2305 return strcmp(LHS->first, RHS->first);
2306}
2307
2308// Copy Options into a vector so we can sort them as we like.
2309static void sortOpts(OptionsMapTy &OptMap,
2310 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
2311 bool ShowHidden) {
2312 SmallPtrSet<Option *, 32> OptionSet; // Duplicate option detection.
2313
2314 for (auto I = OptMap.begin(), E = OptMap.end(); I != E; ++I) {
2315 // Ignore really-hidden options.
2316 if (I->second->getOptionHiddenFlag() == ReallyHidden)
2317 continue;
2318
2319 // Unless showhidden is set, ignore hidden flags.
2320 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
2321 continue;
2322
2323 // If we've already seen this option, don't add it to the list again.
2324 if (!OptionSet.insert(I->second).second)
2325 continue;
2326
2327 Opts.push_back(
2328 std::pair<const char *, Option *>(I->first.data(), I->second));
2329 }
2330
2331 // Sort the options list alphabetically.
2332 array_pod_sort(Opts.begin(), Opts.end(), OptNameCompare);
2333}
2334
2335static void
2337 SmallVectorImpl<std::pair<const char *, SubCommand *>> &Subs) {
2338 for (auto *S : SubMap) {
2339 if (S->getName().empty())
2340 continue;
2341 Subs.push_back(std::make_pair(S->getName().data(), S));
2342 }
2343 array_pod_sort(Subs.begin(), Subs.end(), SubNameCompare);
2344}
2345
2346namespace {
2347
2348class HelpPrinter {
2349protected:
2350 const bool ShowHidden;
2351 using StrOptionPairVector =
2353 using StrSubCommandPairVector =
2355 // Print the options. Opts is assumed to be alphabetically sorted.
2356 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
2357 for (const auto &Opt : Opts)
2358 Opt.second->printOptionInfo(MaxArgLen);
2359 }
2360
2361 void printSubCommands(StrSubCommandPairVector &Subs, size_t MaxSubLen) {
2362 for (const auto &S : Subs) {
2363 outs() << " " << S.first;
2364 if (!S.second->getDescription().empty()) {
2365 outs().indent(MaxSubLen - strlen(S.first));
2366 outs() << " - " << S.second->getDescription();
2367 }
2368 outs() << "\n";
2369 }
2370 }
2371
2372public:
2373 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
2374 virtual ~HelpPrinter() = default;
2375
2376 // Invoke the printer.
2377 void operator=(bool Value) {
2378 if (!Value)
2379 return;
2380 printHelp();
2381
2382 // Halt the program since help information was printed
2383 exit(0);
2384 }
2385
2386 void printHelp() {
2387 SubCommand *Sub = GlobalParser->getActiveSubCommand();
2388 auto &OptionsMap = Sub->OptionsMap;
2389 auto &PositionalOpts = Sub->PositionalOpts;
2390 auto &ConsumeAfterOpt = Sub->ConsumeAfterOpt;
2391
2392 StrOptionPairVector Opts;
2393 sortOpts(OptionsMap, Opts, ShowHidden);
2394
2395 StrSubCommandPairVector Subs;
2396 sortSubCommands(GlobalParser->RegisteredSubCommands, Subs);
2397
2398 if (!GlobalParser->ProgramOverview.empty())
2399 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
2400
2401 if (Sub == &SubCommand::getTopLevel()) {
2402 outs() << "USAGE: " << GlobalParser->ProgramName;
2403 if (!Subs.empty())
2404 outs() << " [subcommand]";
2405 outs() << " [options]";
2406 } else {
2407 if (!Sub->getDescription().empty()) {
2408 outs() << "SUBCOMMAND '" << Sub->getName()
2409 << "': " << Sub->getDescription() << "\n\n";
2410 }
2411 outs() << "USAGE: " << GlobalParser->ProgramName << " " << Sub->getName()
2412 << " [options]";
2413 }
2414
2415 for (auto *Opt : PositionalOpts) {
2416 if (Opt->hasArgStr())
2417 outs() << " --" << Opt->ArgStr;
2418 outs() << " " << Opt->HelpStr;
2419 }
2420
2421 // Print the consume after option info if it exists...
2422 if (ConsumeAfterOpt)
2423 outs() << " " << ConsumeAfterOpt->HelpStr;
2424
2425 if (Sub == &SubCommand::getTopLevel() && !Subs.empty()) {
2426 // Compute the maximum subcommand length...
2427 size_t MaxSubLen = 0;
2428 for (const auto &Sub : Subs)
2429 MaxSubLen = std::max(MaxSubLen, strlen(Sub.first));
2430
2431 outs() << "\n\n";
2432 outs() << "SUBCOMMANDS:\n\n";
2433 printSubCommands(Subs, MaxSubLen);
2434 outs() << "\n";
2435 outs() << " Type \"" << GlobalParser->ProgramName
2436 << " <subcommand> --help\" to get more help on a specific "
2437 "subcommand";
2438 }
2439
2440 outs() << "\n\n";
2441
2442 // Compute the maximum argument length...
2443 size_t MaxArgLen = 0;
2444 for (const auto &Opt : Opts)
2445 MaxArgLen = std::max(MaxArgLen, Opt.second->getOptionWidth());
2446
2447 outs() << "OPTIONS:\n";
2448 printOptions(Opts, MaxArgLen);
2449
2450 // Print any extra help the user has declared.
2451 for (const auto &I : GlobalParser->MoreHelp)
2452 outs() << I;
2453 GlobalParser->MoreHelp.clear();
2454 }
2455};
2456
2457class CategorizedHelpPrinter : public HelpPrinter {
2458public:
2459 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
2460
2461 // Helper function for printOptions().
2462 // It shall return a negative value if A's name should be lexicographically
2463 // ordered before B's name. It returns a value greater than zero if B's name
2464 // should be ordered before A's name, and it returns 0 otherwise.
2465 static int OptionCategoryCompare(OptionCategory *const *A,
2466 OptionCategory *const *B) {
2467 return (*A)->getName().compare((*B)->getName());
2468 }
2469
2470 // Make sure we inherit our base class's operator=()
2471 using HelpPrinter::operator=;
2472
2473protected:
2474 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
2475 std::vector<OptionCategory *> SortedCategories;
2476 DenseMap<OptionCategory *, std::vector<Option *>> CategorizedOptions;
2477
2478 // Collect registered option categories into vector in preparation for
2479 // sorting.
2480 llvm::append_range(SortedCategories,
2481 GlobalParser->RegisteredOptionCategories);
2482
2483 // Sort the different option categories alphabetically.
2484 assert(SortedCategories.size() > 0 && "No option categories registered!");
2485 array_pod_sort(SortedCategories.begin(), SortedCategories.end(),
2486 OptionCategoryCompare);
2487
2488 // Walk through pre-sorted options and assign into categories.
2489 // Because the options are already alphabetically sorted the
2490 // options within categories will also be alphabetically sorted.
2491 for (const auto &I : Opts) {
2492 Option *Opt = I.second;
2493 for (OptionCategory *Cat : Opt->Categories) {
2494 assert(llvm::is_contained(SortedCategories, Cat) &&
2495 "Option has an unregistered category");
2496 CategorizedOptions[Cat].push_back(Opt);
2497 }
2498 }
2499
2500 // Now do printing.
2501 for (OptionCategory *Category : SortedCategories) {
2502 // Hide empty categories for --help, but show for --help-hidden.
2503 const auto &CategoryOptions = CategorizedOptions[Category];
2504 if (CategoryOptions.empty())
2505 continue;
2506
2507 // Print category information.
2508 outs() << "\n";
2509 outs() << Category->getName() << ":\n";
2510
2511 // Check if description is set.
2512 if (!Category->getDescription().empty())
2513 outs() << Category->getDescription() << "\n\n";
2514 else
2515 outs() << "\n";
2516
2517 // Loop over the options in the category and print.
2518 for (const Option *Opt : CategoryOptions)
2519 Opt->printOptionInfo(MaxArgLen);
2520 }
2521 }
2522};
2523
2524// This wraps the Uncategorizing and Categorizing printers and decides
2525// at run time which should be invoked.
2526class HelpPrinterWrapper {
2527private:
2528 HelpPrinter &UncategorizedPrinter;
2529 CategorizedHelpPrinter &CategorizedPrinter;
2530
2531public:
2532 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
2533 CategorizedHelpPrinter &CategorizedPrinter)
2534 : UncategorizedPrinter(UncategorizedPrinter),
2535 CategorizedPrinter(CategorizedPrinter) {}
2536
2537 // Invoke the printer.
2538 void operator=(bool Value);
2539};
2540
2541} // End anonymous namespace
2542
2543#if defined(__GNUC__)
2544// GCC and GCC-compatible compilers define __OPTIMIZE__ when optimizations are
2545// enabled.
2546# if defined(__OPTIMIZE__)
2547# define LLVM_IS_DEBUG_BUILD 0
2548# else
2549# define LLVM_IS_DEBUG_BUILD 1
2550# endif
2551#elif defined(_MSC_VER)
2552// MSVC doesn't have a predefined macro indicating if optimizations are enabled.
2553// Use _DEBUG instead. This macro actually corresponds to the choice between
2554// debug and release CRTs, but it is a reasonable proxy.
2555# if defined(_DEBUG)
2556# define LLVM_IS_DEBUG_BUILD 1
2557# else
2558# define LLVM_IS_DEBUG_BUILD 0
2559# endif
2560#else
2561// Otherwise, for an unknown compiler, assume this is an optimized build.
2562# define LLVM_IS_DEBUG_BUILD 0
2563#endif
2564
2565namespace {
2566class VersionPrinter {
2567public:
2568 void print(const std::vector<VersionPrinterTy> &ExtraPrinters) {
2569 raw_ostream &OS = outs();
2570#ifdef PACKAGE_VENDOR
2571 OS << PACKAGE_VENDOR << " ";
2572#else
2573 OS << "LLVM (http://llvm.org/):\n ";
2574#endif
2575 OS << PACKAGE_NAME << " version " << PACKAGE_VERSION << "\n ";
2576#if LLVM_IS_DEBUG_BUILD
2577 OS << "DEBUG build";
2578#else
2579 OS << "Optimized build";
2580#endif
2581#ifndef NDEBUG
2582 OS << " with assertions";
2583#endif
2584 OS << ".\n";
2585
2586 // Iterate over any registered extra printers and call them to add further
2587 // information.
2588 if (!ExtraPrinters.empty()) {
2589 for (const auto &I : ExtraPrinters)
2590 I(outs());
2591 }
2592 }
2593 void operator=(bool OptionWasSpecified);
2594};
2595
2596struct CommandLineCommonOptions {
2597 // Declare the four HelpPrinter instances that are used to print out help, or
2598 // help-hidden as an uncategorized list or in categories.
2599 HelpPrinter UncategorizedNormalPrinter{false};
2600 HelpPrinter UncategorizedHiddenPrinter{true};
2601 CategorizedHelpPrinter CategorizedNormalPrinter{false};
2602 CategorizedHelpPrinter CategorizedHiddenPrinter{true};
2603 // Declare HelpPrinter wrappers that will decide whether or not to invoke
2604 // a categorizing help printer
2605 HelpPrinterWrapper WrappedNormalPrinter{UncategorizedNormalPrinter,
2606 CategorizedNormalPrinter};
2607 HelpPrinterWrapper WrappedHiddenPrinter{UncategorizedHiddenPrinter,
2608 CategorizedHiddenPrinter};
2609 // Define a category for generic options that all tools should have.
2610 cl::OptionCategory GenericCategory{"Generic Options"};
2611
2612 // Define uncategorized help printers.
2613 // --help-list is hidden by default because if Option categories are being
2614 // used then --help behaves the same as --help-list.
2616 "help-list",
2617 cl::desc(
2618 "Display list of available options (--help-list-hidden for more)"),
2619 cl::location(UncategorizedNormalPrinter),
2620 cl::Hidden,
2622 cl::cat(GenericCategory),
2624
2626 "help-list-hidden",
2627 cl::desc("Display list of all available options"),
2628 cl::location(UncategorizedHiddenPrinter),
2629 cl::Hidden,
2631 cl::cat(GenericCategory),
2633
2634 // Define uncategorized/categorized help printers. These printers change their
2635 // behaviour at runtime depending on whether one or more Option categories
2636 // have been declared.
2638 "help",
2639 cl::desc("Display available options (--help-hidden for more)"),
2640 cl::location(WrappedNormalPrinter),
2642 cl::cat(GenericCategory),
2644
2645 cl::alias HOpA{"h", cl::desc("Alias for --help"), cl::aliasopt(HOp),
2647
2649 "help-hidden",
2650 cl::desc("Display all available options"),
2651 cl::location(WrappedHiddenPrinter),
2652 cl::Hidden,
2654 cl::cat(GenericCategory),
2656
2657 cl::opt<bool> PrintOptions{
2658 "print-options",
2659 cl::desc("Print non-default options after command line parsing"),
2660 cl::Hidden,
2661 cl::init(false),
2662 cl::cat(GenericCategory),
2664
2665 cl::opt<bool> PrintAllOptions{
2666 "print-all-options",
2667 cl::desc("Print all option values after command line parsing"),
2668 cl::Hidden,
2669 cl::init(false),
2670 cl::cat(GenericCategory),
2672
2673 VersionPrinterTy OverrideVersionPrinter = nullptr;
2674
2675 std::vector<VersionPrinterTy> ExtraVersionPrinters;
2676
2677 // Define the --version option that prints out the LLVM version for the tool
2678 VersionPrinter VersionPrinterInstance;
2679
2681 "version", cl::desc("Display the version of this program"),
2682 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
2683 cl::cat(GenericCategory)};
2684};
2685} // End anonymous namespace
2686
2687// Lazy-initialized global instance of options controlling the command-line
2688// parser and general handling.
2690
2702
2704 // Initialise the general option category.
2705 static OptionCategory GeneralCategory{"General options"};
2706 return GeneralCategory;
2707}
2708
2709void VersionPrinter::operator=(bool OptionWasSpecified) {
2710 if (!OptionWasSpecified)
2711 return;
2712
2713 if (CommonOptions->OverrideVersionPrinter != nullptr) {
2714 CommonOptions->OverrideVersionPrinter(outs());
2715 exit(0);
2716 }
2717 print(CommonOptions->ExtraVersionPrinters);
2718
2719 exit(0);
2720}
2721
2722void HelpPrinterWrapper::operator=(bool Value) {
2723 if (!Value)
2724 return;
2725
2726 // Decide which printer to invoke. If more than one option category is
2727 // registered then it is useful to show the categorized help instead of
2728 // uncategorized help.
2729 if (GlobalParser->RegisteredOptionCategories.size() > 1) {
2730 // unhide --help-list option so user can have uncategorized output if they
2731 // want it.
2732 CommonOptions->HLOp.setHiddenFlag(NotHidden);
2733
2734 CategorizedPrinter = true; // Invoke categorized printer
2735 } else {
2736 UncategorizedPrinter = true; // Invoke uncategorized printer
2737 }
2738}
2739
2740// Print the value of each option.
2741void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
2742
2743void CommandLineParser::printOptionValues() {
2744 if (!CommonOptions->PrintOptions && !CommonOptions->PrintAllOptions)
2745 return;
2746
2748 sortOpts(ActiveSubCommand->OptionsMap, Opts, /*ShowHidden*/ true);
2749
2750 // Compute the maximum argument length...
2751 size_t MaxArgLen = 0;
2752 for (const auto &Opt : Opts)
2753 MaxArgLen = std::max(MaxArgLen, Opt.second->getOptionWidth());
2754
2755 for (const auto &Opt : Opts)
2756 Opt.second->printOptionValue(MaxArgLen, CommonOptions->PrintAllOptions);
2757}
2758
2759// Utility function for printing the help message.
2760void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
2761 if (!Hidden && !Categorized)
2762 CommonOptions->UncategorizedNormalPrinter.printHelp();
2763 else if (!Hidden && Categorized)
2764 CommonOptions->CategorizedNormalPrinter.printHelp();
2765 else if (Hidden && !Categorized)
2766 CommonOptions->UncategorizedHiddenPrinter.printHelp();
2767 else
2768 CommonOptions->CategorizedHiddenPrinter.printHelp();
2769}
2770
2772 static const StringRef Config[] = {
2773 // Placeholder to ensure the array always has elements, since it's an
2774 // error to have a zero-sized array. Slice this off before returning.
2775 "",
2776 // Actual compiler build config feature list:
2777#if LLVM_IS_DEBUG_BUILD
2778 "+unoptimized",
2779#endif
2780#ifndef NDEBUG
2781 "+assertions",
2782#endif
2783#ifdef EXPENSIVE_CHECKS
2784 "+expensive-checks",
2785#endif
2786#if __has_feature(address_sanitizer)
2787 "+asan",
2788#endif
2789#if __has_feature(dataflow_sanitizer)
2790 "+dfsan",
2791#endif
2792#if __has_feature(hwaddress_sanitizer)
2793 "+hwasan",
2794#endif
2795#if __has_feature(memory_sanitizer)
2796 "+msan",
2797#endif
2798#if __has_feature(thread_sanitizer)
2799 "+tsan",
2800#endif
2801#if __has_feature(undefined_behavior_sanitizer)
2802 "+ubsan",
2803#endif
2804 };
2805 return ArrayRef(Config).drop_front(1);
2806}
2807
2808// Utility function for printing the build config.
2810#if LLVM_VERSION_PRINTER_SHOW_BUILD_CONFIG
2811 OS << "Build config: ";
2813 OS << '\n';
2814#endif
2815}
2816
2817/// Utility function for printing version number.
2819 CommonOptions->VersionPrinterInstance.print(CommonOptions->ExtraVersionPrinters);
2820}
2821
2823 CommonOptions->OverrideVersionPrinter = func;
2824}
2825
2827 CommonOptions->ExtraVersionPrinters.push_back(func);
2828}
2829
2832 auto &Subs = GlobalParser->RegisteredSubCommands;
2833 (void)Subs;
2834 assert(Subs.contains(&Sub));
2835 return Sub.OptionsMap;
2836}
2837
2840 return GlobalParser->getRegisteredSubcommands();
2841}
2842
2845 for (auto &I : Sub.OptionsMap) {
2846 bool Unrelated = true;
2847 for (auto &Cat : I.second->Categories) {
2848 if (Cat == &Category || Cat == &CommonOptions->GenericCategory)
2849 Unrelated = false;
2850 }
2851 if (Unrelated)
2852 I.second->setHiddenFlag(cl::ReallyHidden);
2853 }
2854}
2855
2857 SubCommand &Sub) {
2859 for (auto &I : Sub.OptionsMap) {
2860 bool Unrelated = true;
2861 for (auto &Cat : I.second->Categories) {
2862 if (is_contained(Categories, Cat) ||
2863 Cat == &CommonOptions->GenericCategory)
2864 Unrelated = false;
2865 }
2866 if (Unrelated)
2867 I.second->setHiddenFlag(cl::ReallyHidden);
2868 }
2869}
2870
2873 GlobalParser->ResetAllOptionOccurrences();
2874}
2875
2876void LLVMParseCommandLineOptions(int argc, const char *const *argv,
2877 const char *Overview) {
2878 llvm::cl::ParseCommandLineOptions(argc, argv, StringRef(Overview),
2879 &llvm::nulls());
2880}
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 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 Option * getOptionPred(StringRef Name, size_t &Length, bool(*Pred)(const Option *), const OptionsMapTy &OptionsMap)
static SmallString< 8 > argPrefix(StringRef ArgName, size_t Pad=DefaultPad)
static StringRef ArgHelpPrefix
void opt_unsigned_anchor()
static bool isWindowsSpecialCharInCommandName(char C)
static StringRef getValueStr(const Option &O, StringRef DefaultMsg)
static size_t getOptionPrefixesSize()
static bool ProvideOption(Option *Handler, StringRef ArgName, StringRef Value, int argc, const char *const *argv, int &i)
ProvideOption - For Value, this differentiates between an empty value ("") and a null value (StringRe...
static bool isQuote(char C)
static ManagedStatic< CommandLineCommonOptions > CommonOptions
static Option * HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value, bool &ErrorParsing, const OptionsMapTy &OptionsMap)
HandlePrefixedOrGroupedOption - The specified argument string (which started with at least one '-') d...
static void initCommonOptions()
void opt_char_anchor()
static void sortOpts(OptionsMapTy &OptMap, SmallVectorImpl< std::pair< const char *, Option * > > &Opts, bool ShowHidden)
DenseMap< StringRef, Option * > OptionsMapTy
static void tokenizeWindowsCommandLineImpl(StringRef Src, StringSaver &Saver, function_ref< void(StringRef)> AddToken, bool AlwaysCopy, function_ref< void()> MarkEOL, bool InitialCommandName)
static bool isWhitespace(char C)
static 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 bool EatsUnboundedNumberOfValues(const Option *O)
static int OptNameCompare(const std::pair< const char *, Option * > *LHS, const std::pair< const char *, Option * > *RHS)
static Option * LookupNearestOption(StringRef Arg, const OptionsMapTy &OptionsMap, std::string &NearestString)
LookupNearestOption - Lookup the closest match to the option specified by the specified option on the...
void opt_int_anchor()
static StringRef ArgPrefix
static bool isWindowsSpecialChar(char C)
static bool isGrouping(const Option *O)
#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
#define _
static void Help(ArrayRef< StringRef > CPUNames, ArrayRef< SubtargetFeatureKV > FeatTable)
Display help for feature and mcpu choices.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
Provides a library for accessing information about this process and other processes on the operating ...
This file defines the SmallPtrSet class.
This file defines the SmallString class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:178
iterator begin()
Definition DenseMap.h:82
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition DenseMap.h:174
iterator end()
Definition DenseMap.h:85
bool contains(const_arg_type_t< KeyT > Val) const
Return true if the specified key is in the map, false otherwise.
Definition DenseMap.h:169
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:239
Represents either an error or a value T.
Definition ErrorOr.h:56
reference get()
Definition ErrorOr.h:149
std::error_code getError() const
Definition ErrorOr.h:152
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
ManagedStatic - This transparently changes the behavior of global statics to be lazily constructed on...
size_t getBufferSize() const
const char * getBufferEnd() const
const char * getBufferStart() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool erase(PtrType Ptr)
Remove pointer from the set.
iterator end() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
iterator begin() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
void assign(StringRef RHS)
Assign from a StringRef.
Definition SmallString.h:51
void append(StringRef RHS)
Append from a StringRef.
Definition SmallString.h:68
const char * c_str()
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
void reserve(size_type N)
iterator erase(const_iterator CI)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
iterator insert(iterator I, T &&Elt)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition StringRef.h:882
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition StringRef.h:730
static constexpr size_t npos
Definition StringRef.h:58
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:591
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition StringRef.h:629
LLVM_ABI unsigned edit_distance(StringRef Other, bool AllowReplacements=true, unsigned MaxEditDistance=0) const
Determine the edit distance between this string and another string.
Definition StringRef.cpp:88
size_t size_type
Definition StringRef.h:62
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition StringRef.h:714
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
constexpr const char * data() const
Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:138
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition StringRef.h:290
bool consume_front(char Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition StringRef.h:655
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
Definition StringSaver.h:22
BumpPtrAllocator & getAllocator() const
Definition StringSaver.h:28
StringRef save(const char *S)
Definition StringSaver.h:31
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
Contains options that control response file expansion.
LLVM_ABI ExpansionContext(BumpPtrAllocator &A, TokenizerCallback T, vfs::FileSystem *FS=nullptr)
LLVM_ABI bool findConfigFile(StringRef FileName, SmallVectorImpl< char > &FilePath)
Looks for the specified configuration file.
LLVM_ABI Error expandResponseFiles(SmallVectorImpl< const char * > &Argv)
Expands constructs "@file" in the provided array of arguments recursively.
LLVM_ABI Error readConfigFile(StringRef CfgFile, SmallVectorImpl< const char * > &Argv)
Reads command line options from the given configuration file.
StringRef getName() const
SmallPtrSet< SubCommand *, 1 > Subs
int getNumOccurrences() const
enum ValueExpected getValueExpectedFlag() const
void addCategory(OptionCategory &C)
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()
DenseMap< StringRef, Option * > OptionsMap
LLVM_ABI void registerSubCommand()
SmallVector< Option *, 4 > PositionalOpts
void printOptionInfo(const Option &O, size_t GlobalWidth) const
virtual StringRef getValueName() const
void printOptionNoValue(const Option &O, size_t GlobalWidth) const
size_t getOptionWidth(const Option &O) const
void printOptionName(const Option &O, size_t GlobalWidth) const
virtual size_t getOptionWidth(const Option &O) const
virtual StringRef getDescription(unsigned N) const =0
virtual const GenericOptionValue & getOptionValue(unsigned N) const =0
virtual unsigned getNumOptions() const =0
virtual StringRef getOption(unsigned N) const =0
void 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 MCSchedule.h:35
LLVM_ABI iterator_range< SmallPtrSet< SubCommand *, 4 >::iterator > getRegisteredSubcommands()
Use this to get all registered SubCommands from the provided parser.
LLVM_ABI void PrintVersionMessage()
Utility function for printing version number.
LLVM_ABI bool ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer, SmallVectorImpl< const char * > &Argv)
A convenience helper which supports the typical use case of expansion function call.
LLVM_ABI void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a string of Windows command line arguments, which may contain quotes and escaped quotes.
LLVM_ABI OptionCategory & getGeneralCategory()
@ ValueDisallowed
LLVM_ABI void ResetAllOptionOccurrences()
Reset all command line options to a state that looks as if they have never appeared on the command li...
LLVM_ABI void SetVersionPrinter(VersionPrinterTy func)
===------------------------------------------------------------------—===// Override the default (LLV...
LLVM_ABI void tokenizeConfigFile(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes content of configuration file.
LLVM_ABI DenseMap< StringRef, Option * > & getRegisteredOptions(SubCommand &Sub=SubCommand::getTopLevel())
Use this to get a map of all registered named options (e.g.
LLVM_ABI void ResetCommandLineParser()
Reset the command line parser back to its initial state.
LLVM_ABI void PrintOptionValues()
LLVM_ABI void AddLiteralOption(Option &O, StringRef Name)
Adds a new option for parsing and provides the option it refers to.
void printOptionDiff(const Option &O, const generic_parser_base &P, const DT &V, const OptionValue< DT > &Default, size_t GlobalWidth)
LLVM_ABI void TokenizeWindowsCommandLineNoCopy(StringRef Source, StringSaver &Saver, SmallVectorImpl< StringRef > &NewArgv)
Tokenizes a Windows command line while attempting to avoid copies.
LLVM_ABI void printBuildConfig(raw_ostream &OS)
Prints the compiler build configuration.
void(*)(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs) TokenizerCallback
String tokenization function type.
LLVM_ABI bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i)
Parses Arg into the option handler Handler.
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:76
@ 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:478
LLVM_ABI bool has_parent_path(const Twine &path, Style style=Style::native)
Has parent path?
Definition Path.cpp:667
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:716
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
LLVM_ABI bool is_absolute(const Twine &path, Style style=Style::native)
Is path absolute?
Definition Path.cpp:688
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:315
@ Length
Definition DWP.cpp:558
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:1668
@ 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:2207
void interleaveComma(const Container &c, StreamT &os, UnaryFunctor each_fn)
Definition STLExtras.h:2312
LLVM_ABI bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark.
void initDebugCounterOptions()
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
bool to_float(const Twine &T, float &Num)
@ no_such_file_or_directory
Definition Errc.h:65
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
void initSignalsOptions()
Definition Signals.cpp:64
void initStatisticOptions()
Definition Statistic.cpp:49
LLVM_ABI raw_ostream & nulls()
This returns a reference to a raw_ostream which simply discards output.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
void initTimerOptions()
Definition Timer.cpp:569
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
void initRandomSeedOptions()
@ Sub
Subtraction of integers.
void initGraphWriterOptions()
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ArrayRef(const T &OneElt) -> ArrayRef< T >
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2018
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
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:1595
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
@ Default
The result value is uniform if and only if all operands are uniform.
Definition Uniformity.h:20
#define INIT(o, n)
Definition regexec.c:71
LLVM_ABI extrahelp(StringRef help)