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