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