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