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