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