Putting all the standard tool options into a "Generic" category.
[oota-llvm.git] / lib / Support / CommandLine.cpp
1 //===-- CommandLine.cpp - Command line parser implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This class implements a command line argument processor that is useful when
11 // creating a tool.  It provides a simple, minimalistic interface that is easily
12 // extensible and supports nonlocal (library) command line options.
13 //
14 // Note that rather than trying to figure out what this code does, you could try
15 // reading the library documentation located in docs/CommandLine.html
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm-c/Support.h"
21 #include "llvm/ADT/ArrayRef.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/Twine.h"
26 #include "llvm/Config/config.h"
27 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include <cerrno>
36 #include <cstdlib>
37 #include <map>
38 #include <system_error>
39 using namespace llvm;
40 using namespace cl;
41
42 #define DEBUG_TYPE "commandline"
43
44 //===----------------------------------------------------------------------===//
45 // Template instantiations and anchors.
46 //
47 namespace llvm {
48 namespace cl {
49 TEMPLATE_INSTANTIATION(class basic_parser<bool>);
50 TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
51 TEMPLATE_INSTANTIATION(class basic_parser<int>);
52 TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
53 TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
54 TEMPLATE_INSTANTIATION(class basic_parser<double>);
55 TEMPLATE_INSTANTIATION(class basic_parser<float>);
56 TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
57 TEMPLATE_INSTANTIATION(class basic_parser<char>);
58
59 TEMPLATE_INSTANTIATION(class opt<unsigned>);
60 TEMPLATE_INSTANTIATION(class opt<int>);
61 TEMPLATE_INSTANTIATION(class opt<std::string>);
62 TEMPLATE_INSTANTIATION(class opt<char>);
63 TEMPLATE_INSTANTIATION(class opt<bool>);
64 }
65 } // end namespace llvm::cl
66
67 // Pin the vtables to this file.
68 void GenericOptionValue::anchor() {}
69 void OptionValue<boolOrDefault>::anchor() {}
70 void OptionValue<std::string>::anchor() {}
71 void Option::anchor() {}
72 void basic_parser_impl::anchor() {}
73 void parser<bool>::anchor() {}
74 void parser<boolOrDefault>::anchor() {}
75 void parser<int>::anchor() {}
76 void parser<unsigned>::anchor() {}
77 void parser<unsigned long long>::anchor() {}
78 void parser<double>::anchor() {}
79 void parser<float>::anchor() {}
80 void parser<std::string>::anchor() {}
81 void parser<char>::anchor() {}
82 void StringSaver::anchor() {}
83
84 //===----------------------------------------------------------------------===//
85
86 // Globals for name and overview of program.  Program name is not a string to
87 // avoid static ctor/dtor issues.
88 static char ProgramName[80] = "<premain>";
89 static const char *ProgramOverview = nullptr;
90
91 // This collects additional help to be printed.
92 static ManagedStatic<std::vector<const char *>> MoreHelp;
93
94 extrahelp::extrahelp(const char *Help) : morehelp(Help) {
95   MoreHelp->push_back(Help);
96 }
97
98 static bool OptionListChanged = false;
99
100 // MarkOptionsChanged - Internal helper function.
101 void cl::MarkOptionsChanged() { OptionListChanged = true; }
102
103 /// RegisteredOptionList - This is the list of the command line options that
104 /// have statically constructed themselves.
105 static Option *RegisteredOptionList = nullptr;
106
107 void Option::addArgument() {
108   assert(!NextRegistered && "argument multiply registered!");
109
110   NextRegistered = RegisteredOptionList;
111   RegisteredOptionList = this;
112   MarkOptionsChanged();
113 }
114
115 void Option::removeArgument() {
116   if (RegisteredOptionList == this) {
117     RegisteredOptionList = NextRegistered;
118     MarkOptionsChanged();
119     return;
120   }
121   Option *O = RegisteredOptionList;
122   for (; O->NextRegistered != this; O = O->NextRegistered)
123     ;
124   O->NextRegistered = NextRegistered;
125   MarkOptionsChanged();
126 }
127
128 // This collects the different option categories that have been registered.
129 typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
130 static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
131
132 // Initialise the general option category.
133 OptionCategory llvm::cl::GeneralCategory("General options");
134
135 void OptionCategory::registerCategory() {
136   assert(std::count_if(RegisteredOptionCategories->begin(),
137                        RegisteredOptionCategories->end(),
138                        [this](const OptionCategory *Category) {
139                          return getName() == Category->getName();
140                        }) == 0 &&
141          "Duplicate option categories");
142
143   RegisteredOptionCategories->insert(this);
144 }
145
146 //===----------------------------------------------------------------------===//
147 // Basic, shared command line option processing machinery.
148 //
149
150 /// GetOptionInfo - Scan the list of registered options, turning them into data
151 /// structures that are easier to handle.
152 static void GetOptionInfo(SmallVectorImpl<Option *> &PositionalOpts,
153                           SmallVectorImpl<Option *> &SinkOpts,
154                           StringMap<Option *> &OptionsMap) {
155   bool HadErrors = false;
156   SmallVector<const char *, 16> OptionNames;
157   Option *CAOpt = nullptr; // The ConsumeAfter option if it exists.
158   for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
159     // If this option wants to handle multiple option names, get the full set.
160     // This handles enum options like "-O1 -O2" etc.
161     O->getExtraOptionNames(OptionNames);
162     if (O->ArgStr[0])
163       OptionNames.push_back(O->ArgStr);
164
165     // Handle named options.
166     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
167       // Add argument to the argument map!
168       if (!OptionsMap.insert(std::make_pair(OptionNames[i], O)).second) {
169         errs() << ProgramName << ": CommandLine Error: Option '"
170                << OptionNames[i] << "' registered more than once!\n";
171         HadErrors = true;
172       }
173     }
174
175     OptionNames.clear();
176
177     // Remember information about positional options.
178     if (O->getFormattingFlag() == cl::Positional)
179       PositionalOpts.push_back(O);
180     else if (O->getMiscFlags() & cl::Sink) // Remember sink options
181       SinkOpts.push_back(O);
182     else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
183       if (CAOpt) {
184         O->error("Cannot specify more than one option with cl::ConsumeAfter!");
185         HadErrors = true;
186       }
187       CAOpt = O;
188     }
189   }
190
191   if (CAOpt)
192     PositionalOpts.push_back(CAOpt);
193
194   // Make sure that they are in order of registration not backwards.
195   std::reverse(PositionalOpts.begin(), PositionalOpts.end());
196
197   // Fail hard if there were errors. These are strictly unrecoverable and
198   // indicate serious issues such as conflicting option names or an incorrectly
199   // linked LLVM distribution.
200   if (HadErrors)
201     report_fatal_error("inconsistency in registered CommandLine options");
202 }
203
204 /// LookupOption - Lookup the option specified by the specified option on the
205 /// command line.  If there is a value specified (after an equal sign) return
206 /// that as well.  This assumes that leading dashes have already been stripped.
207 static Option *LookupOption(StringRef &Arg, StringRef &Value,
208                             const StringMap<Option *> &OptionsMap) {
209   // Reject all dashes.
210   if (Arg.empty())
211     return nullptr;
212
213   size_t EqualPos = Arg.find('=');
214
215   // If we have an equals sign, remember the value.
216   if (EqualPos == StringRef::npos) {
217     // Look up the option.
218     StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
219     return I != OptionsMap.end() ? I->second : nullptr;
220   }
221
222   // If the argument before the = is a valid option name, we match.  If not,
223   // return Arg unmolested.
224   StringMap<Option *>::const_iterator I =
225       OptionsMap.find(Arg.substr(0, EqualPos));
226   if (I == OptionsMap.end())
227     return nullptr;
228
229   Value = Arg.substr(EqualPos + 1);
230   Arg = Arg.substr(0, EqualPos);
231   return I->second;
232 }
233
234 /// LookupNearestOption - Lookup the closest match to the option specified by
235 /// the specified option on the command line.  If there is a value specified
236 /// (after an equal sign) return that as well.  This assumes that leading dashes
237 /// have already been stripped.
238 static Option *LookupNearestOption(StringRef Arg,
239                                    const StringMap<Option *> &OptionsMap,
240                                    std::string &NearestString) {
241   // Reject all dashes.
242   if (Arg.empty())
243     return nullptr;
244
245   // Split on any equal sign.
246   std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
247   StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
248   StringRef &RHS = SplitArg.second;
249
250   // Find the closest match.
251   Option *Best = nullptr;
252   unsigned BestDistance = 0;
253   for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
254                                            ie = OptionsMap.end();
255        it != ie; ++it) {
256     Option *O = it->second;
257     SmallVector<const char *, 16> OptionNames;
258     O->getExtraOptionNames(OptionNames);
259     if (O->ArgStr[0])
260       OptionNames.push_back(O->ArgStr);
261
262     bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
263     StringRef Flag = PermitValue ? LHS : Arg;
264     for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
265       StringRef Name = OptionNames[i];
266       unsigned Distance = StringRef(Name).edit_distance(
267           Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
268       if (!Best || Distance < BestDistance) {
269         Best = O;
270         BestDistance = Distance;
271         if (RHS.empty() || !PermitValue)
272           NearestString = OptionNames[i];
273         else
274           NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
275       }
276     }
277   }
278
279   return Best;
280 }
281
282 /// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
283 /// that does special handling of cl::CommaSeparated options.
284 static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
285                                           StringRef ArgName, StringRef Value,
286                                           bool MultiArg = false) {
287   // Check to see if this option accepts a comma separated list of values.  If
288   // it does, we have to split up the value into multiple values.
289   if (Handler->getMiscFlags() & CommaSeparated) {
290     StringRef Val(Value);
291     StringRef::size_type Pos = Val.find(',');
292
293     while (Pos != StringRef::npos) {
294       // Process the portion before the comma.
295       if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
296         return true;
297       // Erase the portion before the comma, AND the comma.
298       Val = Val.substr(Pos + 1);
299       Value.substr(Pos + 1); // Increment the original value pointer as well.
300       // Check for another comma.
301       Pos = Val.find(',');
302     }
303
304     Value = Val;
305   }
306
307   if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
308     return true;
309
310   return false;
311 }
312
313 /// ProvideOption - For Value, this differentiates between an empty value ("")
314 /// and a null value (StringRef()).  The later is accepted for arguments that
315 /// don't allow a value (-foo) the former is rejected (-foo=).
316 static inline bool ProvideOption(Option *Handler, StringRef ArgName,
317                                  StringRef Value, int argc,
318                                  const char *const *argv, int &i) {
319   // Is this a multi-argument option?
320   unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
321
322   // Enforce value requirements
323   switch (Handler->getValueExpectedFlag()) {
324   case ValueRequired:
325     if (!Value.data()) { // No value specified?
326       if (i + 1 >= argc)
327         return Handler->error("requires a value!");
328       // Steal the next argument, like for '-o filename'
329       assert(argv && "null check");
330       Value = argv[++i];
331     }
332     break;
333   case ValueDisallowed:
334     if (NumAdditionalVals > 0)
335       return Handler->error("multi-valued option specified"
336                             " with ValueDisallowed modifier!");
337
338     if (Value.data())
339       return Handler->error("does not allow a value! '" + Twine(Value) +
340                             "' specified.");
341     break;
342   case ValueOptional:
343     break;
344   }
345
346   // If this isn't a multi-arg option, just run the handler.
347   if (NumAdditionalVals == 0)
348     return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
349
350   // If it is, run the handle several times.
351   bool MultiArg = false;
352
353   if (Value.data()) {
354     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
355       return true;
356     --NumAdditionalVals;
357     MultiArg = true;
358   }
359
360   while (NumAdditionalVals > 0) {
361     if (i + 1 >= argc)
362       return Handler->error("not enough values!");
363     assert(argv && "null check");
364     Value = argv[++i];
365
366     if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
367       return true;
368     MultiArg = true;
369     --NumAdditionalVals;
370   }
371   return false;
372 }
373
374 static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
375   int Dummy = i;
376   return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
377 }
378
379 // Option predicates...
380 static inline bool isGrouping(const Option *O) {
381   return O->getFormattingFlag() == cl::Grouping;
382 }
383 static inline bool isPrefixedOrGrouping(const Option *O) {
384   return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
385 }
386
387 // getOptionPred - Check to see if there are any options that satisfy the
388 // specified predicate with names that are the prefixes in Name.  This is
389 // checked by progressively stripping characters off of the name, checking to
390 // see if there options that satisfy the predicate.  If we find one, return it,
391 // otherwise return null.
392 //
393 static Option *getOptionPred(StringRef Name, size_t &Length,
394                              bool (*Pred)(const Option *),
395                              const StringMap<Option *> &OptionsMap) {
396
397   StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
398
399   // Loop while we haven't found an option and Name still has at least two
400   // characters in it (so that the next iteration will not be the empty
401   // string.
402   while (OMI == OptionsMap.end() && Name.size() > 1) {
403     Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
404     OMI = OptionsMap.find(Name);
405   }
406
407   if (OMI != OptionsMap.end() && Pred(OMI->second)) {
408     Length = Name.size();
409     return OMI->second; // Found one!
410   }
411   return nullptr; // No option found!
412 }
413
414 /// HandlePrefixedOrGroupedOption - The specified argument string (which started
415 /// with at least one '-') does not fully match an available option.  Check to
416 /// see if this is a prefix or grouped option.  If so, split arg into output an
417 /// Arg/Value pair and return the Option to parse it with.
418 static Option *
419 HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
420                               bool &ErrorParsing,
421                               const StringMap<Option *> &OptionsMap) {
422   if (Arg.size() == 1)
423     return nullptr;
424
425   // Do the lookup!
426   size_t Length = 0;
427   Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
428   if (!PGOpt)
429     return nullptr;
430
431   // If the option is a prefixed option, then the value is simply the
432   // rest of the name...  so fall through to later processing, by
433   // setting up the argument name flags and value fields.
434   if (PGOpt->getFormattingFlag() == cl::Prefix) {
435     Value = Arg.substr(Length);
436     Arg = Arg.substr(0, Length);
437     assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
438     return PGOpt;
439   }
440
441   // This must be a grouped option... handle them now.  Grouping options can't
442   // have values.
443   assert(isGrouping(PGOpt) && "Broken getOptionPred!");
444
445   do {
446     // Move current arg name out of Arg into OneArgName.
447     StringRef OneArgName = Arg.substr(0, Length);
448     Arg = Arg.substr(Length);
449
450     // Because ValueRequired is an invalid flag for grouped arguments,
451     // we don't need to pass argc/argv in.
452     assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
453            "Option can not be cl::Grouping AND cl::ValueRequired!");
454     int Dummy = 0;
455     ErrorParsing |=
456         ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
457
458     // Get the next grouping option.
459     PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
460   } while (PGOpt && Length != Arg.size());
461
462   // Return the last option with Arg cut down to just the last one.
463   return PGOpt;
464 }
465
466 static bool RequiresValue(const Option *O) {
467   return O->getNumOccurrencesFlag() == cl::Required ||
468          O->getNumOccurrencesFlag() == cl::OneOrMore;
469 }
470
471 static bool EatsUnboundedNumberOfValues(const Option *O) {
472   return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
473          O->getNumOccurrencesFlag() == cl::OneOrMore;
474 }
475
476 static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
477
478 static bool isQuote(char C) { return C == '\"' || C == '\''; }
479
480 static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
481
482 void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
483                                 SmallVectorImpl<const char *> &NewArgv,
484                                 bool MarkEOLs) {
485   SmallString<128> Token;
486   for (size_t I = 0, E = Src.size(); I != E; ++I) {
487     // Consume runs of whitespace.
488     if (Token.empty()) {
489       while (I != E && isWhitespace(Src[I])) {
490         // Mark the end of lines in response files
491         if (MarkEOLs && Src[I] == '\n')
492           NewArgv.push_back(nullptr);
493         ++I;
494       }
495       if (I == E)
496         break;
497     }
498
499     // Backslashes can escape backslashes, spaces, and other quotes.  Otherwise
500     // they are literal.  This makes it much easier to read Windows file paths.
501     if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
502       ++I; // Skip the escape.
503       Token.push_back(Src[I]);
504       continue;
505     }
506
507     // Consume a quoted string.
508     if (isQuote(Src[I])) {
509       char Quote = Src[I++];
510       while (I != E && Src[I] != Quote) {
511         // Backslashes are literal, unless they escape a special character.
512         if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
513           ++I;
514         Token.push_back(Src[I]);
515         ++I;
516       }
517       if (I == E)
518         break;
519       continue;
520     }
521
522     // End the token if this is whitespace.
523     if (isWhitespace(Src[I])) {
524       if (!Token.empty())
525         NewArgv.push_back(Saver.SaveString(Token.c_str()));
526       Token.clear();
527       continue;
528     }
529
530     // This is a normal character.  Append it.
531     Token.push_back(Src[I]);
532   }
533
534   // Append the last token after hitting EOF with no whitespace.
535   if (!Token.empty())
536     NewArgv.push_back(Saver.SaveString(Token.c_str()));
537   // Mark the end of response files
538   if (MarkEOLs)
539     NewArgv.push_back(nullptr);
540 }
541
542 /// Backslashes are interpreted in a rather complicated way in the Windows-style
543 /// command line, because backslashes are used both to separate path and to
544 /// escape double quote. This method consumes runs of backslashes as well as the
545 /// following double quote if it's escaped.
546 ///
547 ///  * If an even number of backslashes is followed by a double quote, one
548 ///    backslash is output for every pair of backslashes, and the last double
549 ///    quote remains unconsumed. The double quote will later be interpreted as
550 ///    the start or end of a quoted string in the main loop outside of this
551 ///    function.
552 ///
553 ///  * If an odd number of backslashes is followed by a double quote, one
554 ///    backslash is output for every pair of backslashes, and a double quote is
555 ///    output for the last pair of backslash-double quote. The double quote is
556 ///    consumed in this case.
557 ///
558 ///  * Otherwise, backslashes are interpreted literally.
559 static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
560   size_t E = Src.size();
561   int BackslashCount = 0;
562   // Skip the backslashes.
563   do {
564     ++I;
565     ++BackslashCount;
566   } while (I != E && Src[I] == '\\');
567
568   bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
569   if (FollowedByDoubleQuote) {
570     Token.append(BackslashCount / 2, '\\');
571     if (BackslashCount % 2 == 0)
572       return I - 1;
573     Token.push_back('"');
574     return I;
575   }
576   Token.append(BackslashCount, '\\');
577   return I - 1;
578 }
579
580 void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
581                                     SmallVectorImpl<const char *> &NewArgv,
582                                     bool MarkEOLs) {
583   SmallString<128> Token;
584
585   // This is a small state machine to consume characters until it reaches the
586   // end of the source string.
587   enum { INIT, UNQUOTED, QUOTED } State = INIT;
588   for (size_t I = 0, E = Src.size(); I != E; ++I) {
589     // INIT state indicates that the current input index is at the start of
590     // the string or between tokens.
591     if (State == INIT) {
592       if (isWhitespace(Src[I])) {
593         // Mark the end of lines in response files
594         if (MarkEOLs && Src[I] == '\n')
595           NewArgv.push_back(nullptr);
596         continue;
597       }
598       if (Src[I] == '"') {
599         State = QUOTED;
600         continue;
601       }
602       if (Src[I] == '\\') {
603         I = parseBackslash(Src, I, Token);
604         State = UNQUOTED;
605         continue;
606       }
607       Token.push_back(Src[I]);
608       State = UNQUOTED;
609       continue;
610     }
611
612     // UNQUOTED state means that it's reading a token not quoted by double
613     // quotes.
614     if (State == UNQUOTED) {
615       // Whitespace means the end of the token.
616       if (isWhitespace(Src[I])) {
617         NewArgv.push_back(Saver.SaveString(Token.c_str()));
618         Token.clear();
619         State = INIT;
620         // Mark the end of lines in response files
621         if (MarkEOLs && Src[I] == '\n')
622           NewArgv.push_back(nullptr);
623         continue;
624       }
625       if (Src[I] == '"') {
626         State = QUOTED;
627         continue;
628       }
629       if (Src[I] == '\\') {
630         I = parseBackslash(Src, I, Token);
631         continue;
632       }
633       Token.push_back(Src[I]);
634       continue;
635     }
636
637     // QUOTED state means that it's reading a token quoted by double quotes.
638     if (State == QUOTED) {
639       if (Src[I] == '"') {
640         State = UNQUOTED;
641         continue;
642       }
643       if (Src[I] == '\\') {
644         I = parseBackslash(Src, I, Token);
645         continue;
646       }
647       Token.push_back(Src[I]);
648     }
649   }
650   // Append the last token after hitting EOF with no whitespace.
651   if (!Token.empty())
652     NewArgv.push_back(Saver.SaveString(Token.c_str()));
653   // Mark the end of response files
654   if (MarkEOLs)
655     NewArgv.push_back(nullptr);
656 }
657
658 // It is called byte order marker but the UTF-8 BOM is actually not affected
659 // by the host system's endianness.
660 static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
661   return (S.size() >= 3 &&
662           S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
663 }
664
665 static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
666                                TokenizerCallback Tokenizer,
667                                SmallVectorImpl<const char *> &NewArgv,
668                                bool MarkEOLs = false) {
669   ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
670       MemoryBuffer::getFile(FName);
671   if (!MemBufOrErr)
672     return false;
673   MemoryBuffer &MemBuf = *MemBufOrErr.get();
674   StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
675
676   // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
677   ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
678   std::string UTF8Buf;
679   if (hasUTF16ByteOrderMark(BufRef)) {
680     if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
681       return false;
682     Str = StringRef(UTF8Buf);
683   }
684   // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
685   // these bytes before parsing.
686   // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
687   else if (hasUTF8ByteOrderMark(BufRef))
688     Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
689
690   // Tokenize the contents into NewArgv.
691   Tokenizer(Str, Saver, NewArgv, MarkEOLs);
692
693   return true;
694 }
695
696 /// \brief Expand response files on a command line recursively using the given
697 /// StringSaver and tokenization strategy.
698 bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
699                              SmallVectorImpl<const char *> &Argv,
700                              bool MarkEOLs) {
701   unsigned RspFiles = 0;
702   bool AllExpanded = true;
703
704   // Don't cache Argv.size() because it can change.
705   for (unsigned I = 0; I != Argv.size();) {
706     const char *Arg = Argv[I];
707     // Check if it is an EOL marker
708     if (Arg == nullptr) {
709       ++I;
710       continue;
711     }
712     if (Arg[0] != '@') {
713       ++I;
714       continue;
715     }
716
717     // If we have too many response files, leave some unexpanded.  This avoids
718     // crashing on self-referential response files.
719     if (RspFiles++ > 20)
720       return false;
721
722     // Replace this response file argument with the tokenization of its
723     // contents.  Nested response files are expanded in subsequent iterations.
724     // FIXME: If a nested response file uses a relative path, is it relative to
725     // the cwd of the process or the response file?
726     SmallVector<const char *, 0> ExpandedArgv;
727     if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
728                             MarkEOLs)) {
729       // We couldn't read this file, so we leave it in the argument stream and
730       // move on.
731       AllExpanded = false;
732       ++I;
733       continue;
734     }
735     Argv.erase(Argv.begin() + I);
736     Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
737   }
738   return AllExpanded;
739 }
740
741 namespace {
742 class StrDupSaver : public StringSaver {
743   std::vector<char *> Dups;
744
745 public:
746   ~StrDupSaver() {
747     for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
748          ++I) {
749       char *Dup = *I;
750       free(Dup);
751     }
752   }
753   const char *SaveString(const char *Str) override {
754     char *Dup = strdup(Str);
755     Dups.push_back(Dup);
756     return Dup;
757   }
758 };
759 }
760
761 /// ParseEnvironmentOptions - An alternative entry point to the
762 /// CommandLine library, which allows you to read the program's name
763 /// from the caller (as PROGNAME) and its command-line arguments from
764 /// an environment variable (whose name is given in ENVVAR).
765 ///
766 void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
767                                  const char *Overview) {
768   // Check args.
769   assert(progName && "Program name not specified");
770   assert(envVar && "Environment variable name missing");
771
772   // Get the environment variable they want us to parse options out of.
773   const char *envValue = getenv(envVar);
774   if (!envValue)
775     return;
776
777   // Get program's "name", which we wouldn't know without the caller
778   // telling us.
779   SmallVector<const char *, 20> newArgv;
780   StrDupSaver Saver;
781   newArgv.push_back(Saver.SaveString(progName));
782
783   // Parse the value of the environment variable into a "command line"
784   // and hand it off to ParseCommandLineOptions().
785   TokenizeGNUCommandLine(envValue, Saver, newArgv);
786   int newArgc = static_cast<int>(newArgv.size());
787   ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
788 }
789
790 void cl::ParseCommandLineOptions(int argc, const char *const *argv,
791                                  const char *Overview) {
792   // Process all registered options.
793   SmallVector<Option *, 4> PositionalOpts;
794   SmallVector<Option *, 4> SinkOpts;
795   StringMap<Option *> Opts;
796   GetOptionInfo(PositionalOpts, SinkOpts, Opts);
797
798   assert((!Opts.empty() || !PositionalOpts.empty()) && "No options specified!");
799
800   // Expand response files.
801   SmallVector<const char *, 20> newArgv;
802   for (int i = 0; i != argc; ++i)
803     newArgv.push_back(argv[i]);
804   StrDupSaver Saver;
805   ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
806   argv = &newArgv[0];
807   argc = static_cast<int>(newArgv.size());
808
809   // Copy the program name into ProgName, making sure not to overflow it.
810   StringRef ProgName = sys::path::filename(argv[0]);
811   size_t Len = std::min(ProgName.size(), size_t(79));
812   memcpy(ProgramName, ProgName.data(), Len);
813   ProgramName[Len] = '\0';
814
815   ProgramOverview = Overview;
816   bool ErrorParsing = false;
817
818   // Check out the positional arguments to collect information about them.
819   unsigned NumPositionalRequired = 0;
820
821   // Determine whether or not there are an unlimited number of positionals
822   bool HasUnlimitedPositionals = false;
823
824   Option *ConsumeAfterOpt = nullptr;
825   if (!PositionalOpts.empty()) {
826     if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
827       assert(PositionalOpts.size() > 1 &&
828              "Cannot specify cl::ConsumeAfter without a positional argument!");
829       ConsumeAfterOpt = PositionalOpts[0];
830     }
831
832     // Calculate how many positional values are _required_.
833     bool UnboundedFound = false;
834     for (size_t i = ConsumeAfterOpt ? 1 : 0, e = PositionalOpts.size(); i != e;
835          ++i) {
836       Option *Opt = PositionalOpts[i];
837       if (RequiresValue(Opt))
838         ++NumPositionalRequired;
839       else if (ConsumeAfterOpt) {
840         // ConsumeAfter cannot be combined with "optional" positional options
841         // unless there is only one positional argument...
842         if (PositionalOpts.size() > 2)
843           ErrorParsing |= Opt->error(
844               "error - this positional option will never be matched, "
845               "because it does not Require a value, and a "
846               "cl::ConsumeAfter option is active!");
847       } else if (UnboundedFound && !Opt->ArgStr[0]) {
848         // This option does not "require" a value...  Make sure this option is
849         // not specified after an option that eats all extra arguments, or this
850         // one will never get any!
851         //
852         ErrorParsing |= Opt->error("error - option can never match, because "
853                                    "another positional argument will match an "
854                                    "unbounded number of values, and this option"
855                                    " does not require a value!");
856       }
857       UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
858     }
859     HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
860   }
861
862   // PositionalVals - A vector of "positional" arguments we accumulate into
863   // the process at the end.
864   //
865   SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
866
867   // If the program has named positional arguments, and the name has been run
868   // across, keep track of which positional argument was named.  Otherwise put
869   // the positional args into the PositionalVals list...
870   Option *ActivePositionalArg = nullptr;
871
872   // Loop over all of the arguments... processing them.
873   bool DashDashFound = false; // Have we read '--'?
874   for (int i = 1; i < argc; ++i) {
875     Option *Handler = nullptr;
876     Option *NearestHandler = nullptr;
877     std::string NearestHandlerString;
878     StringRef Value;
879     StringRef ArgName = "";
880
881     // If the option list changed, this means that some command line
882     // option has just been registered or deregistered.  This can occur in
883     // response to things like -load, etc.  If this happens, rescan the options.
884     if (OptionListChanged) {
885       PositionalOpts.clear();
886       SinkOpts.clear();
887       Opts.clear();
888       GetOptionInfo(PositionalOpts, SinkOpts, Opts);
889       OptionListChanged = false;
890     }
891
892     // Check to see if this is a positional argument.  This argument is
893     // considered to be positional if it doesn't start with '-', if it is "-"
894     // itself, or if we have seen "--" already.
895     //
896     if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
897       // Positional argument!
898       if (ActivePositionalArg) {
899         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
900         continue; // We are done!
901       }
902
903       if (!PositionalOpts.empty()) {
904         PositionalVals.push_back(std::make_pair(argv[i], i));
905
906         // All of the positional arguments have been fulfulled, give the rest to
907         // the consume after option... if it's specified...
908         //
909         if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
910           for (++i; i < argc; ++i)
911             PositionalVals.push_back(std::make_pair(argv[i], i));
912           break; // Handle outside of the argument processing loop...
913         }
914
915         // Delay processing positional arguments until the end...
916         continue;
917       }
918     } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
919                !DashDashFound) {
920       DashDashFound = true; // This is the mythical "--"?
921       continue;             // Don't try to process it as an argument itself.
922     } else if (ActivePositionalArg &&
923                (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
924       // If there is a positional argument eating options, check to see if this
925       // option is another positional argument.  If so, treat it as an argument,
926       // otherwise feed it to the eating positional.
927       ArgName = argv[i] + 1;
928       // Eat leading dashes.
929       while (!ArgName.empty() && ArgName[0] == '-')
930         ArgName = ArgName.substr(1);
931
932       Handler = LookupOption(ArgName, Value, Opts);
933       if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
934         ProvidePositionalOption(ActivePositionalArg, argv[i], i);
935         continue; // We are done!
936       }
937
938     } else { // We start with a '-', must be an argument.
939       ArgName = argv[i] + 1;
940       // Eat leading dashes.
941       while (!ArgName.empty() && ArgName[0] == '-')
942         ArgName = ArgName.substr(1);
943
944       Handler = LookupOption(ArgName, Value, Opts);
945
946       // Check to see if this "option" is really a prefixed or grouped argument.
947       if (!Handler)
948         Handler =
949             HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing, Opts);
950
951       // Otherwise, look for the closest available option to report to the user
952       // in the upcoming error.
953       if (!Handler && SinkOpts.empty())
954         NearestHandler =
955             LookupNearestOption(ArgName, Opts, NearestHandlerString);
956     }
957
958     if (!Handler) {
959       if (SinkOpts.empty()) {
960         errs() << ProgramName << ": Unknown command line argument '" << argv[i]
961                << "'.  Try: '" << argv[0] << " -help'\n";
962
963         if (NearestHandler) {
964           // If we know a near match, report it as well.
965           errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
966                  << "'?\n";
967         }
968
969         ErrorParsing = true;
970       } else {
971         for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
972                                                  E = SinkOpts.end();
973              I != E; ++I)
974           (*I)->addOccurrence(i, "", argv[i]);
975       }
976       continue;
977     }
978
979     // If this is a named positional argument, just remember that it is the
980     // active one...
981     if (Handler->getFormattingFlag() == cl::Positional)
982       ActivePositionalArg = Handler;
983     else
984       ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
985   }
986
987   // Check and handle positional arguments now...
988   if (NumPositionalRequired > PositionalVals.size()) {
989     errs() << ProgramName
990            << ": Not enough positional command line arguments specified!\n"
991            << "Must specify at least " << NumPositionalRequired
992            << " positional arguments: See: " << argv[0] << " -help\n";
993
994     ErrorParsing = true;
995   } else if (!HasUnlimitedPositionals &&
996              PositionalVals.size() > PositionalOpts.size()) {
997     errs() << ProgramName << ": Too many positional arguments specified!\n"
998            << "Can specify at most " << PositionalOpts.size()
999            << " positional arguments: See: " << argv[0] << " -help\n";
1000     ErrorParsing = true;
1001
1002   } else if (!ConsumeAfterOpt) {
1003     // Positional args have already been handled if ConsumeAfter is specified.
1004     unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1005     for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
1006       if (RequiresValue(PositionalOpts[i])) {
1007         ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
1008                                 PositionalVals[ValNo].second);
1009         ValNo++;
1010         --NumPositionalRequired; // We fulfilled our duty...
1011       }
1012
1013       // If we _can_ give this option more arguments, do so now, as long as we
1014       // do not give it values that others need.  'Done' controls whether the
1015       // option even _WANTS_ any more.
1016       //
1017       bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
1018       while (NumVals - ValNo > NumPositionalRequired && !Done) {
1019         switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
1020         case cl::Optional:
1021           Done = true; // Optional arguments want _at most_ one value
1022         // FALL THROUGH
1023         case cl::ZeroOrMore: // Zero or more will take all they can get...
1024         case cl::OneOrMore:  // One or more will take all they can get...
1025           ProvidePositionalOption(PositionalOpts[i],
1026                                   PositionalVals[ValNo].first,
1027                                   PositionalVals[ValNo].second);
1028           ValNo++;
1029           break;
1030         default:
1031           llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
1032                            "positional argument processing!");
1033         }
1034       }
1035     }
1036   } else {
1037     assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1038     unsigned ValNo = 0;
1039     for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
1040       if (RequiresValue(PositionalOpts[j])) {
1041         ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
1042                                                 PositionalVals[ValNo].first,
1043                                                 PositionalVals[ValNo].second);
1044         ValNo++;
1045       }
1046
1047     // Handle the case where there is just one positional option, and it's
1048     // optional.  In this case, we want to give JUST THE FIRST option to the
1049     // positional option and keep the rest for the consume after.  The above
1050     // loop would have assigned no values to positional options in this case.
1051     //
1052     if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
1053       ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
1054                                               PositionalVals[ValNo].first,
1055                                               PositionalVals[ValNo].second);
1056       ValNo++;
1057     }
1058
1059     // Handle over all of the rest of the arguments to the
1060     // cl::ConsumeAfter command line option...
1061     for (; ValNo != PositionalVals.size(); ++ValNo)
1062       ErrorParsing |=
1063           ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1064                                   PositionalVals[ValNo].second);
1065   }
1066
1067   // Loop over args and make sure all required args are specified!
1068   for (const auto &Opt : Opts) {
1069     switch (Opt.second->getNumOccurrencesFlag()) {
1070     case Required:
1071     case OneOrMore:
1072       if (Opt.second->getNumOccurrences() == 0) {
1073         Opt.second->error("must be specified at least once!");
1074         ErrorParsing = true;
1075       }
1076     // Fall through
1077     default:
1078       break;
1079     }
1080   }
1081
1082   // Now that we know if -debug is specified, we can use it.
1083   // Note that if ReadResponseFiles == true, this must be done before the
1084   // memory allocated for the expanded command line is free()d below.
1085   DEBUG(dbgs() << "Args: ";
1086         for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1087         dbgs() << '\n';);
1088
1089   // Free all of the memory allocated to the map.  Command line options may only
1090   // be processed once!
1091   Opts.clear();
1092   PositionalOpts.clear();
1093   MoreHelp->clear();
1094
1095   // If we had an error processing our arguments, don't let the program execute
1096   if (ErrorParsing)
1097     exit(1);
1098 }
1099
1100 //===----------------------------------------------------------------------===//
1101 // Option Base class implementation
1102 //
1103
1104 bool Option::error(const Twine &Message, StringRef ArgName) {
1105   if (!ArgName.data())
1106     ArgName = ArgStr;
1107   if (ArgName.empty())
1108     errs() << HelpStr; // Be nice for positional arguments
1109   else
1110     errs() << ProgramName << ": for the -" << ArgName;
1111
1112   errs() << " option: " << Message << "\n";
1113   return true;
1114 }
1115
1116 bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1117                            bool MultiArg) {
1118   if (!MultiArg)
1119     NumOccurrences++; // Increment the number of times we have been seen
1120
1121   switch (getNumOccurrencesFlag()) {
1122   case Optional:
1123     if (NumOccurrences > 1)
1124       return error("may only occur zero or one times!", ArgName);
1125     break;
1126   case Required:
1127     if (NumOccurrences > 1)
1128       return error("must occur exactly one time!", ArgName);
1129   // Fall through
1130   case OneOrMore:
1131   case ZeroOrMore:
1132   case ConsumeAfter:
1133     break;
1134   }
1135
1136   return handleOccurrence(pos, ArgName, Value);
1137 }
1138
1139 // getValueStr - Get the value description string, using "DefaultMsg" if nothing
1140 // has been specified yet.
1141 //
1142 static const char *getValueStr(const Option &O, const char *DefaultMsg) {
1143   if (O.ValueStr[0] == 0)
1144     return DefaultMsg;
1145   return O.ValueStr;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 // cl::alias class implementation
1150 //
1151
1152 // Return the width of the option tag for printing...
1153 size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
1154
1155 static void printHelpStr(StringRef HelpStr, size_t Indent,
1156                          size_t FirstLineIndentedBy) {
1157   std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1158   outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1159   while (!Split.second.empty()) {
1160     Split = Split.second.split('\n');
1161     outs().indent(Indent) << Split.first << "\n";
1162   }
1163 }
1164
1165 // Print out the option for the alias.
1166 void alias::printOptionInfo(size_t GlobalWidth) const {
1167   outs() << "  -" << ArgStr;
1168   printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
1169 }
1170
1171 //===----------------------------------------------------------------------===//
1172 // Parser Implementation code...
1173 //
1174
1175 // basic_parser implementation
1176 //
1177
1178 // Return the width of the option tag for printing...
1179 size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1180   size_t Len = std::strlen(O.ArgStr);
1181   if (const char *ValName = getValueName())
1182     Len += std::strlen(getValueStr(O, ValName)) + 3;
1183
1184   return Len + 6;
1185 }
1186
1187 // printOptionInfo - Print out information about this option.  The
1188 // to-be-maintained width is specified.
1189 //
1190 void basic_parser_impl::printOptionInfo(const Option &O,
1191                                         size_t GlobalWidth) const {
1192   outs() << "  -" << O.ArgStr;
1193
1194   if (const char *ValName = getValueName())
1195     outs() << "=<" << getValueStr(O, ValName) << '>';
1196
1197   printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
1198 }
1199
1200 void basic_parser_impl::printOptionName(const Option &O,
1201                                         size_t GlobalWidth) const {
1202   outs() << "  -" << O.ArgStr;
1203   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1204 }
1205
1206 // parser<bool> implementation
1207 //
1208 bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1209                          bool &Value) {
1210   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1211       Arg == "1") {
1212     Value = true;
1213     return false;
1214   }
1215
1216   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1217     Value = false;
1218     return false;
1219   }
1220   return O.error("'" + Arg +
1221                  "' is invalid value for boolean argument! Try 0 or 1");
1222 }
1223
1224 // parser<boolOrDefault> implementation
1225 //
1226 bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1227                                   boolOrDefault &Value) {
1228   if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1229       Arg == "1") {
1230     Value = BOU_TRUE;
1231     return false;
1232   }
1233   if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1234     Value = BOU_FALSE;
1235     return false;
1236   }
1237
1238   return O.error("'" + Arg +
1239                  "' is invalid value for boolean argument! Try 0 or 1");
1240 }
1241
1242 // parser<int> implementation
1243 //
1244 bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1245                         int &Value) {
1246   if (Arg.getAsInteger(0, Value))
1247     return O.error("'" + Arg + "' value invalid for integer argument!");
1248   return false;
1249 }
1250
1251 // parser<unsigned> implementation
1252 //
1253 bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1254                              unsigned &Value) {
1255
1256   if (Arg.getAsInteger(0, Value))
1257     return O.error("'" + Arg + "' value invalid for uint argument!");
1258   return false;
1259 }
1260
1261 // parser<unsigned long long> implementation
1262 //
1263 bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1264                                        StringRef Arg,
1265                                        unsigned long long &Value) {
1266
1267   if (Arg.getAsInteger(0, Value))
1268     return O.error("'" + Arg + "' value invalid for uint argument!");
1269   return false;
1270 }
1271
1272 // parser<double>/parser<float> implementation
1273 //
1274 static bool parseDouble(Option &O, StringRef Arg, double &Value) {
1275   SmallString<32> TmpStr(Arg.begin(), Arg.end());
1276   const char *ArgStart = TmpStr.c_str();
1277   char *End;
1278   Value = strtod(ArgStart, &End);
1279   if (*End != 0)
1280     return O.error("'" + Arg + "' value invalid for floating point argument!");
1281   return false;
1282 }
1283
1284 bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1285                            double &Val) {
1286   return parseDouble(O, Arg, Val);
1287 }
1288
1289 bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1290                           float &Val) {
1291   double dVal;
1292   if (parseDouble(O, Arg, dVal))
1293     return true;
1294   Val = (float)dVal;
1295   return false;
1296 }
1297
1298 // generic_parser_base implementation
1299 //
1300
1301 // findOption - Return the option number corresponding to the specified
1302 // argument string.  If the option is not found, getNumOptions() is returned.
1303 //
1304 unsigned generic_parser_base::findOption(const char *Name) {
1305   unsigned e = getNumOptions();
1306
1307   for (unsigned i = 0; i != e; ++i) {
1308     if (strcmp(getOption(i), Name) == 0)
1309       return i;
1310   }
1311   return e;
1312 }
1313
1314 // Return the width of the option tag for printing...
1315 size_t generic_parser_base::getOptionWidth(const Option &O) const {
1316   if (O.hasArgStr()) {
1317     size_t Size = std::strlen(O.ArgStr) + 6;
1318     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1319       Size = std::max(Size, std::strlen(getOption(i)) + 8);
1320     return Size;
1321   } else {
1322     size_t BaseSize = 0;
1323     for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1324       BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
1325     return BaseSize;
1326   }
1327 }
1328
1329 // printOptionInfo - Print out information about this option.  The
1330 // to-be-maintained width is specified.
1331 //
1332 void generic_parser_base::printOptionInfo(const Option &O,
1333                                           size_t GlobalWidth) const {
1334   if (O.hasArgStr()) {
1335     outs() << "  -" << O.ArgStr;
1336     printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
1337
1338     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1339       size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
1340       outs() << "    =" << getOption(i);
1341       outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1342     }
1343   } else {
1344     if (O.HelpStr[0])
1345       outs() << "  " << O.HelpStr << '\n';
1346     for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1347       const char *Option = getOption(i);
1348       outs() << "    -" << Option;
1349       printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
1350     }
1351   }
1352 }
1353
1354 static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1355
1356 // printGenericOptionDiff - Print the value of this option and it's default.
1357 //
1358 // "Generic" options have each value mapped to a name.
1359 void generic_parser_base::printGenericOptionDiff(
1360     const Option &O, const GenericOptionValue &Value,
1361     const GenericOptionValue &Default, size_t GlobalWidth) const {
1362   outs() << "  -" << O.ArgStr;
1363   outs().indent(GlobalWidth - std::strlen(O.ArgStr));
1364
1365   unsigned NumOpts = getNumOptions();
1366   for (unsigned i = 0; i != NumOpts; ++i) {
1367     if (Value.compare(getOptionValue(i)))
1368       continue;
1369
1370     outs() << "= " << getOption(i);
1371     size_t L = std::strlen(getOption(i));
1372     size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1373     outs().indent(NumSpaces) << " (default: ";
1374     for (unsigned j = 0; j != NumOpts; ++j) {
1375       if (Default.compare(getOptionValue(j)))
1376         continue;
1377       outs() << getOption(j);
1378       break;
1379     }
1380     outs() << ")\n";
1381     return;
1382   }
1383   outs() << "= *unknown option value*\n";
1384 }
1385
1386 // printOptionDiff - Specializations for printing basic value types.
1387 //
1388 #define PRINT_OPT_DIFF(T)                                                      \
1389   void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D,      \
1390                                   size_t GlobalWidth) const {                  \
1391     printOptionName(O, GlobalWidth);                                           \
1392     std::string Str;                                                           \
1393     {                                                                          \
1394       raw_string_ostream SS(Str);                                              \
1395       SS << V;                                                                 \
1396     }                                                                          \
1397     outs() << "= " << Str;                                                     \
1398     size_t NumSpaces =                                                         \
1399         MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;               \
1400     outs().indent(NumSpaces) << " (default: ";                                 \
1401     if (D.hasValue())                                                          \
1402       outs() << D.getValue();                                                  \
1403     else                                                                       \
1404       outs() << "*no default*";                                                \
1405     outs() << ")\n";                                                           \
1406   }
1407
1408 PRINT_OPT_DIFF(bool)
1409 PRINT_OPT_DIFF(boolOrDefault)
1410 PRINT_OPT_DIFF(int)
1411 PRINT_OPT_DIFF(unsigned)
1412 PRINT_OPT_DIFF(unsigned long long)
1413 PRINT_OPT_DIFF(double)
1414 PRINT_OPT_DIFF(float)
1415 PRINT_OPT_DIFF(char)
1416
1417 void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1418                                           OptionValue<std::string> D,
1419                                           size_t GlobalWidth) const {
1420   printOptionName(O, GlobalWidth);
1421   outs() << "= " << V;
1422   size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1423   outs().indent(NumSpaces) << " (default: ";
1424   if (D.hasValue())
1425     outs() << D.getValue();
1426   else
1427     outs() << "*no default*";
1428   outs() << ")\n";
1429 }
1430
1431 // Print a placeholder for options that don't yet support printOptionDiff().
1432 void basic_parser_impl::printOptionNoValue(const Option &O,
1433                                            size_t GlobalWidth) const {
1434   printOptionName(O, GlobalWidth);
1435   outs() << "= *cannot print option value*\n";
1436 }
1437
1438 //===----------------------------------------------------------------------===//
1439 // -help and -help-hidden option implementation
1440 //
1441
1442 static int OptNameCompare(const void *LHS, const void *RHS) {
1443   typedef std::pair<const char *, Option *> pair_ty;
1444
1445   return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
1446 }
1447
1448 // Copy Options into a vector so we can sort them as we like.
1449 static void sortOpts(StringMap<Option *> &OptMap,
1450                      SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1451                      bool ShowHidden) {
1452   SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
1453
1454   for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
1455        I != E; ++I) {
1456     // Ignore really-hidden options.
1457     if (I->second->getOptionHiddenFlag() == ReallyHidden)
1458       continue;
1459
1460     // Unless showhidden is set, ignore hidden flags.
1461     if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1462       continue;
1463
1464     // If we've already seen this option, don't add it to the list again.
1465     if (!OptionSet.insert(I->second).second)
1466       continue;
1467
1468     Opts.push_back(
1469         std::pair<const char *, Option *>(I->getKey().data(), I->second));
1470   }
1471
1472   // Sort the options list alphabetically.
1473   qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1474 }
1475
1476 namespace {
1477
1478 class HelpPrinter {
1479 protected:
1480   const bool ShowHidden;
1481   typedef SmallVector<std::pair<const char *, Option *>, 128>
1482       StrOptionPairVector;
1483   // Print the options. Opts is assumed to be alphabetically sorted.
1484   virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1485     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1486       Opts[i].second->printOptionInfo(MaxArgLen);
1487   }
1488
1489 public:
1490   explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
1491   virtual ~HelpPrinter() {}
1492
1493   // Invoke the printer.
1494   void operator=(bool Value) {
1495     if (Value == false)
1496       return;
1497
1498     // Get all the options.
1499     SmallVector<Option *, 4> PositionalOpts;
1500     SmallVector<Option *, 4> SinkOpts;
1501     StringMap<Option *> OptMap;
1502     GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1503
1504     StrOptionPairVector Opts;
1505     sortOpts(OptMap, Opts, ShowHidden);
1506
1507     if (ProgramOverview)
1508       outs() << "OVERVIEW: " << ProgramOverview << "\n";
1509
1510     outs() << "USAGE: " << ProgramName << " [options]";
1511
1512     // Print out the positional options.
1513     Option *CAOpt = nullptr; // The cl::ConsumeAfter option, if it exists...
1514     if (!PositionalOpts.empty() &&
1515         PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1516       CAOpt = PositionalOpts[0];
1517
1518     for (size_t i = CAOpt != nullptr, e = PositionalOpts.size(); i != e; ++i) {
1519       if (PositionalOpts[i]->ArgStr[0])
1520         outs() << " --" << PositionalOpts[i]->ArgStr;
1521       outs() << " " << PositionalOpts[i]->HelpStr;
1522     }
1523
1524     // Print the consume after option info if it exists...
1525     if (CAOpt)
1526       outs() << " " << CAOpt->HelpStr;
1527
1528     outs() << "\n\n";
1529
1530     // Compute the maximum argument length...
1531     size_t MaxArgLen = 0;
1532     for (size_t i = 0, e = Opts.size(); i != e; ++i)
1533       MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1534
1535     outs() << "OPTIONS:\n";
1536     printOptions(Opts, MaxArgLen);
1537
1538     // Print any extra help the user has declared.
1539     for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1540                                              E = MoreHelp->end();
1541          I != E; ++I)
1542       outs() << *I;
1543     MoreHelp->clear();
1544
1545     // Halt the program since help information was printed
1546     exit(0);
1547   }
1548 };
1549
1550 class CategorizedHelpPrinter : public HelpPrinter {
1551 public:
1552   explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1553
1554   // Helper function for printOptions().
1555   // It shall return true if A's name should be lexographically
1556   // ordered before B's name. It returns false otherwise.
1557   static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
1558     return strcmp(A->getName(), B->getName()) < 0;
1559   }
1560
1561   // Make sure we inherit our base class's operator=()
1562   using HelpPrinter::operator=;
1563
1564 protected:
1565   void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
1566     std::vector<OptionCategory *> SortedCategories;
1567     std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
1568
1569     // Collect registered option categories into vector in preparation for
1570     // sorting.
1571     for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1572                                       E = RegisteredOptionCategories->end();
1573          I != E; ++I) {
1574       SortedCategories.push_back(*I);
1575     }
1576
1577     // Sort the different option categories alphabetically.
1578     assert(SortedCategories.size() > 0 && "No option categories registered!");
1579     std::sort(SortedCategories.begin(), SortedCategories.end(),
1580               OptionCategoryCompare);
1581
1582     // Create map to empty vectors.
1583     for (std::vector<OptionCategory *>::const_iterator
1584              I = SortedCategories.begin(),
1585              E = SortedCategories.end();
1586          I != E; ++I)
1587       CategorizedOptions[*I] = std::vector<Option *>();
1588
1589     // Walk through pre-sorted options and assign into categories.
1590     // Because the options are already alphabetically sorted the
1591     // options within categories will also be alphabetically sorted.
1592     for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1593       Option *Opt = Opts[I].second;
1594       assert(CategorizedOptions.count(Opt->Category) > 0 &&
1595              "Option has an unregistered category");
1596       CategorizedOptions[Opt->Category].push_back(Opt);
1597     }
1598
1599     // Now do printing.
1600     for (std::vector<OptionCategory *>::const_iterator
1601              Category = SortedCategories.begin(),
1602              E = SortedCategories.end();
1603          Category != E; ++Category) {
1604       // Hide empty categories for -help, but show for -help-hidden.
1605       bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1606       if (!ShowHidden && IsEmptyCategory)
1607         continue;
1608
1609       // Print category information.
1610       outs() << "\n";
1611       outs() << (*Category)->getName() << ":\n";
1612
1613       // Check if description is set.
1614       if ((*Category)->getDescription() != nullptr)
1615         outs() << (*Category)->getDescription() << "\n\n";
1616       else
1617         outs() << "\n";
1618
1619       // When using -help-hidden explicitly state if the category has no
1620       // options associated with it.
1621       if (IsEmptyCategory) {
1622         outs() << "  This option category has no options.\n";
1623         continue;
1624       }
1625       // Loop over the options in the category and print.
1626       for (std::vector<Option *>::const_iterator
1627                Opt = CategorizedOptions[*Category].begin(),
1628                E = CategorizedOptions[*Category].end();
1629            Opt != E; ++Opt)
1630         (*Opt)->printOptionInfo(MaxArgLen);
1631     }
1632   }
1633 };
1634
1635 // This wraps the Uncategorizing and Categorizing printers and decides
1636 // at run time which should be invoked.
1637 class HelpPrinterWrapper {
1638 private:
1639   HelpPrinter &UncategorizedPrinter;
1640   CategorizedHelpPrinter &CategorizedPrinter;
1641
1642 public:
1643   explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
1644                               CategorizedHelpPrinter &CategorizedPrinter)
1645       : UncategorizedPrinter(UncategorizedPrinter),
1646         CategorizedPrinter(CategorizedPrinter) {}
1647
1648   // Invoke the printer.
1649   void operator=(bool Value);
1650 };
1651
1652 } // End anonymous namespace
1653
1654 // Declare the four HelpPrinter instances that are used to print out help, or
1655 // help-hidden as an uncategorized list or in categories.
1656 static HelpPrinter UncategorizedNormalPrinter(false);
1657 static HelpPrinter UncategorizedHiddenPrinter(true);
1658 static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1659 static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1660
1661 // Declare HelpPrinter wrappers that will decide whether or not to invoke
1662 // a categorizing help printer
1663 static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1664                                                CategorizedNormalPrinter);
1665 static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1666                                                CategorizedHiddenPrinter);
1667
1668 // Define a category for generic options that all tools should have.
1669 static cl::OptionCategory GenericCategory("Generic Options");
1670
1671 // Define uncategorized help printers.
1672 // -help-list is hidden by default because if Option categories are being used
1673 // then -help behaves the same as -help-list.
1674 static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1675     "help-list",
1676     cl::desc("Display list of available options (-help-list-hidden for more)"),
1677     cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1678     cl::cat(GenericCategory));
1679
1680 static cl::opt<HelpPrinter, true, parser<bool>>
1681     HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1682           cl::location(UncategorizedHiddenPrinter), cl::Hidden,
1683           cl::ValueDisallowed, cl::cat(GenericCategory));
1684
1685 // Define uncategorized/categorized help printers. These printers change their
1686 // behaviour at runtime depending on whether one or more Option categories have
1687 // been declared.
1688 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1689     HOp("help", cl::desc("Display available options (-help-hidden for more)"),
1690         cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1691         cl::cat(GenericCategory));
1692
1693 static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1694     HHOp("help-hidden", cl::desc("Display all available options"),
1695          cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1696          cl::cat(GenericCategory));
1697
1698 static cl::opt<bool> PrintOptions(
1699     "print-options",
1700     cl::desc("Print non-default options after command line parsing"),
1701     cl::Hidden, cl::init(false), cl::cat(GenericCategory));
1702
1703 static cl::opt<bool> PrintAllOptions(
1704     "print-all-options",
1705     cl::desc("Print all option values after command line parsing"), cl::Hidden,
1706     cl::init(false), cl::cat(GenericCategory));
1707
1708 void HelpPrinterWrapper::operator=(bool Value) {
1709   if (Value == false)
1710     return;
1711
1712   // Decide which printer to invoke. If more than one option category is
1713   // registered then it is useful to show the categorized help instead of
1714   // uncategorized help.
1715   if (RegisteredOptionCategories->size() > 1) {
1716     // unhide -help-list option so user can have uncategorized output if they
1717     // want it.
1718     HLOp.setHiddenFlag(NotHidden);
1719
1720     CategorizedPrinter = true; // Invoke categorized printer
1721   } else
1722     UncategorizedPrinter = true; // Invoke uncategorized printer
1723 }
1724
1725 // Print the value of each option.
1726 void cl::PrintOptionValues() {
1727   if (!PrintOptions && !PrintAllOptions)
1728     return;
1729
1730   // Get all the options.
1731   SmallVector<Option *, 4> PositionalOpts;
1732   SmallVector<Option *, 4> SinkOpts;
1733   StringMap<Option *> OptMap;
1734   GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1735
1736   SmallVector<std::pair<const char *, Option *>, 128> Opts;
1737   sortOpts(OptMap, Opts, /*ShowHidden*/ true);
1738
1739   // Compute the maximum argument length...
1740   size_t MaxArgLen = 0;
1741   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742     MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1743
1744   for (size_t i = 0, e = Opts.size(); i != e; ++i)
1745     Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1746 }
1747
1748 static void (*OverrideVersionPrinter)() = nullptr;
1749
1750 static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
1751
1752 namespace {
1753 class VersionPrinter {
1754 public:
1755   void print() {
1756     raw_ostream &OS = outs();
1757     OS << "LLVM (http://llvm.org/):\n"
1758        << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1759 #ifdef LLVM_VERSION_INFO
1760     OS << " " << LLVM_VERSION_INFO;
1761 #endif
1762     OS << "\n  ";
1763 #ifndef __OPTIMIZE__
1764     OS << "DEBUG build";
1765 #else
1766     OS << "Optimized build";
1767 #endif
1768 #ifndef NDEBUG
1769     OS << " with assertions";
1770 #endif
1771     std::string CPU = sys::getHostCPUName();
1772     if (CPU == "generic")
1773       CPU = "(unknown)";
1774     OS << ".\n"
1775 #if (ENABLE_TIMESTAMPS == 1)
1776        << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1777 #endif
1778        << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
1779        << "  Host CPU: " << CPU << '\n';
1780   }
1781   void operator=(bool OptionWasSpecified) {
1782     if (!OptionWasSpecified)
1783       return;
1784
1785     if (OverrideVersionPrinter != nullptr) {
1786       (*OverrideVersionPrinter)();
1787       exit(0);
1788     }
1789     print();
1790
1791     // Iterate over any registered extra printers and call them to add further
1792     // information.
1793     if (ExtraVersionPrinters != nullptr) {
1794       outs() << '\n';
1795       for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1796                                              E = ExtraVersionPrinters->end();
1797            I != E; ++I)
1798         (*I)();
1799     }
1800
1801     exit(0);
1802   }
1803 };
1804 } // End anonymous namespace
1805
1806 // Define the --version option that prints out the LLVM version for the tool
1807 static VersionPrinter VersionPrinterInstance;
1808
1809 static cl::opt<VersionPrinter, true, parser<bool>>
1810     VersOp("version", cl::desc("Display the version of this program"),
1811            cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1812            cl::cat(GenericCategory));
1813
1814 // Utility function for printing the help message.
1815 void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1816   // This looks weird, but it actually prints the help message. The Printers are
1817   // types of HelpPrinter and the help gets printed when its operator= is
1818   // invoked. That's because the "normal" usages of the help printer is to be
1819   // assigned true/false depending on whether -help or -help-hidden was given or
1820   // not.  Since we're circumventing that we have to make it look like -help or
1821   // -help-hidden were given, so we assign true.
1822
1823   if (!Hidden && !Categorized)
1824     UncategorizedNormalPrinter = true;
1825   else if (!Hidden && Categorized)
1826     CategorizedNormalPrinter = true;
1827   else if (Hidden && !Categorized)
1828     UncategorizedHiddenPrinter = true;
1829   else
1830     CategorizedHiddenPrinter = true;
1831 }
1832
1833 /// Utility function for printing version number.
1834 void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
1835
1836 void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
1837
1838 void cl::AddExtraVersionPrinter(void (*func)()) {
1839   if (!ExtraVersionPrinters)
1840     ExtraVersionPrinters = new std::vector<void (*)()>;
1841
1842   ExtraVersionPrinters->push_back(func);
1843 }
1844
1845 void cl::getRegisteredOptions(StringMap<Option *> &Map) {
1846   // Get all the options.
1847   SmallVector<Option *, 4> PositionalOpts; // NOT USED
1848   SmallVector<Option *, 4> SinkOpts;       // NOT USED
1849   assert(Map.size() == 0 && "StringMap must be empty");
1850   GetOptionInfo(PositionalOpts, SinkOpts, Map);
1851   return;
1852 }
1853
1854 void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
1855   StringMap<cl::Option *> Options;
1856   cl::getRegisteredOptions(Options);
1857   for (auto &I : Options) {
1858     if (I.second->Category != &Category &&
1859         I.second->Category != &GenericCategory)
1860       I.second->setHiddenFlag(cl::ReallyHidden);
1861   }
1862 }
1863
1864 void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1865                                  const char *Overview) {
1866   llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1867 }