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