CommandLine.cpp revision 239462
1193323Sed//===-- CommandLine.cpp - Command line parser implementation --------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This class implements a command line argument processor that is useful when
11193323Sed// creating a tool.  It provides a simple, minimalistic interface that is easily
12193323Sed// extensible and supports nonlocal (library) command line options.
13193323Sed//
14193323Sed// Note that rather than trying to figure out what this code does, you could try
15193323Sed// reading the library documentation located in docs/CommandLine.html
16193323Sed//
17193323Sed//===----------------------------------------------------------------------===//
18193323Sed
19193323Sed#include "llvm/Support/CommandLine.h"
20199481Srdivacky#include "llvm/Support/Debug.h"
21198090Srdivacky#include "llvm/Support/ErrorHandling.h"
22193323Sed#include "llvm/Support/MemoryBuffer.h"
23193323Sed#include "llvm/Support/ManagedStatic.h"
24198090Srdivacky#include "llvm/Support/raw_ostream.h"
25218893Sdim#include "llvm/Support/system_error.h"
26218893Sdim#include "llvm/Support/Host.h"
27218893Sdim#include "llvm/Support/Path.h"
28198090Srdivacky#include "llvm/ADT/OwningPtr.h"
29198090Srdivacky#include "llvm/ADT/SmallPtrSet.h"
30198090Srdivacky#include "llvm/ADT/SmallString.h"
31198090Srdivacky#include "llvm/ADT/StringMap.h"
32198090Srdivacky#include "llvm/ADT/Twine.h"
33198090Srdivacky#include "llvm/Config/config.h"
34198090Srdivacky#include <cerrno>
35193323Sed#include <cstdlib>
36193323Sedusing namespace llvm;
37193323Sedusing namespace cl;
38193323Sed
39193323Sed//===----------------------------------------------------------------------===//
40193323Sed// Template instantiations and anchors.
41193323Sed//
42199989Srdivackynamespace llvm { namespace cl {
43193323SedTEMPLATE_INSTANTIATION(class basic_parser<bool>);
44193323SedTEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
45193323SedTEMPLATE_INSTANTIATION(class basic_parser<int>);
46193323SedTEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
47226633SdimTEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
48193323SedTEMPLATE_INSTANTIATION(class basic_parser<double>);
49193323SedTEMPLATE_INSTANTIATION(class basic_parser<float>);
50193323SedTEMPLATE_INSTANTIATION(class basic_parser<std::string>);
51193323SedTEMPLATE_INSTANTIATION(class basic_parser<char>);
52193323Sed
53193323SedTEMPLATE_INSTANTIATION(class opt<unsigned>);
54193323SedTEMPLATE_INSTANTIATION(class opt<int>);
55193323SedTEMPLATE_INSTANTIATION(class opt<std::string>);
56193323SedTEMPLATE_INSTANTIATION(class opt<char>);
57193323SedTEMPLATE_INSTANTIATION(class opt<bool>);
58199989Srdivacky} } // end namespace llvm::cl
59193323Sed
60234353Sdimvoid GenericOptionValue::anchor() {}
61234353Sdimvoid OptionValue<boolOrDefault>::anchor() {}
62234353Sdimvoid OptionValue<std::string>::anchor() {}
63193323Sedvoid Option::anchor() {}
64193323Sedvoid basic_parser_impl::anchor() {}
65193323Sedvoid parser<bool>::anchor() {}
66193323Sedvoid parser<boolOrDefault>::anchor() {}
67193323Sedvoid parser<int>::anchor() {}
68193323Sedvoid parser<unsigned>::anchor() {}
69226633Sdimvoid parser<unsigned long long>::anchor() {}
70193323Sedvoid parser<double>::anchor() {}
71193323Sedvoid parser<float>::anchor() {}
72193323Sedvoid parser<std::string>::anchor() {}
73193323Sedvoid parser<char>::anchor() {}
74193323Sed
75193323Sed//===----------------------------------------------------------------------===//
76193323Sed
77193323Sed// Globals for name and overview of program.  Program name is not a string to
78193323Sed// avoid static ctor/dtor issues.
79193323Sedstatic char ProgramName[80] = "<premain>";
80193323Sedstatic const char *ProgramOverview = 0;
81193323Sed
82193323Sed// This collects additional help to be printed.
83193323Sedstatic ManagedStatic<std::vector<const char*> > MoreHelp;
84193323Sed
85193323Sedextrahelp::extrahelp(const char *Help)
86193323Sed  : morehelp(Help) {
87193323Sed  MoreHelp->push_back(Help);
88193323Sed}
89193323Sed
90193323Sedstatic bool OptionListChanged = false;
91193323Sed
92193323Sed// MarkOptionsChanged - Internal helper function.
93193323Sedvoid cl::MarkOptionsChanged() {
94193323Sed  OptionListChanged = true;
95193323Sed}
96193323Sed
97193323Sed/// RegisteredOptionList - This is the list of the command line options that
98193323Sed/// have statically constructed themselves.
99193323Sedstatic Option *RegisteredOptionList = 0;
100193323Sed
101193323Sedvoid Option::addArgument() {
102193323Sed  assert(NextRegistered == 0 && "argument multiply registered!");
103193323Sed
104193323Sed  NextRegistered = RegisteredOptionList;
105193323Sed  RegisteredOptionList = this;
106193323Sed  MarkOptionsChanged();
107193323Sed}
108193323Sed
109193323Sed
110193323Sed//===----------------------------------------------------------------------===//
111193323Sed// Basic, shared command line option processing machinery.
112193323Sed//
113193323Sed
114193323Sed/// GetOptionInfo - Scan the list of registered options, turning them into data
115193323Sed/// structures that are easier to handle.
116198090Srdivackystatic void GetOptionInfo(SmallVectorImpl<Option*> &PositionalOpts,
117198090Srdivacky                          SmallVectorImpl<Option*> &SinkOpts,
118198090Srdivacky                          StringMap<Option*> &OptionsMap) {
119198090Srdivacky  SmallVector<const char*, 16> OptionNames;
120193323Sed  Option *CAOpt = 0;  // The ConsumeAfter option if it exists.
121193323Sed  for (Option *O = RegisteredOptionList; O; O = O->getNextRegisteredOption()) {
122193323Sed    // If this option wants to handle multiple option names, get the full set.
123193323Sed    // This handles enum options like "-O1 -O2" etc.
124193323Sed    O->getExtraOptionNames(OptionNames);
125193323Sed    if (O->ArgStr[0])
126193323Sed      OptionNames.push_back(O->ArgStr);
127193323Sed
128193323Sed    // Handle named options.
129193323Sed    for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
130193323Sed      // Add argument to the argument map!
131198090Srdivacky      if (OptionsMap.GetOrCreateValue(OptionNames[i], O).second != O) {
132198090Srdivacky        errs() << ProgramName << ": CommandLine Error: Argument '"
133193323Sed             << OptionNames[i] << "' defined more than once!\n";
134193323Sed      }
135193323Sed    }
136193323Sed
137193323Sed    OptionNames.clear();
138193323Sed
139193323Sed    // Remember information about positional options.
140193323Sed    if (O->getFormattingFlag() == cl::Positional)
141193323Sed      PositionalOpts.push_back(O);
142193323Sed    else if (O->getMiscFlags() & cl::Sink) // Remember sink options
143193323Sed      SinkOpts.push_back(O);
144193323Sed    else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
145193323Sed      if (CAOpt)
146193323Sed        O->error("Cannot specify more than one option with cl::ConsumeAfter!");
147193323Sed      CAOpt = O;
148193323Sed    }
149193323Sed  }
150193323Sed
151193323Sed  if (CAOpt)
152193323Sed    PositionalOpts.push_back(CAOpt);
153193323Sed
154193323Sed  // Make sure that they are in order of registration not backwards.
155193323Sed  std::reverse(PositionalOpts.begin(), PositionalOpts.end());
156193323Sed}
157193323Sed
158193323Sed
159193323Sed/// LookupOption - Lookup the option specified by the specified option on the
160193323Sed/// command line.  If there is a value specified (after an equal sign) return
161198090Srdivacky/// that as well.  This assumes that leading dashes have already been stripped.
162198090Srdivackystatic Option *LookupOption(StringRef &Arg, StringRef &Value,
163198090Srdivacky                            const StringMap<Option*> &OptionsMap) {
164198090Srdivacky  // Reject all dashes.
165198090Srdivacky  if (Arg.empty()) return 0;
166199989Srdivacky
167198090Srdivacky  size_t EqualPos = Arg.find('=');
168199989Srdivacky
169198090Srdivacky  // If we have an equals sign, remember the value.
170198090Srdivacky  if (EqualPos == StringRef::npos) {
171198090Srdivacky    // Look up the option.
172198090Srdivacky    StringMap<Option*>::const_iterator I = OptionsMap.find(Arg);
173198090Srdivacky    return I != OptionsMap.end() ? I->second : 0;
174198090Srdivacky  }
175193323Sed
176198090Srdivacky  // If the argument before the = is a valid option name, we match.  If not,
177198090Srdivacky  // return Arg unmolested.
178198090Srdivacky  StringMap<Option*>::const_iterator I =
179198090Srdivacky    OptionsMap.find(Arg.substr(0, EqualPos));
180198090Srdivacky  if (I == OptionsMap.end()) return 0;
181199989Srdivacky
182198090Srdivacky  Value = Arg.substr(EqualPos+1);
183198090Srdivacky  Arg = Arg.substr(0, EqualPos);
184198090Srdivacky  return I->second;
185198090Srdivacky}
186193323Sed
187218893Sdim/// LookupNearestOption - Lookup the closest match to the option specified by
188218893Sdim/// the specified option on the command line.  If there is a value specified
189218893Sdim/// (after an equal sign) return that as well.  This assumes that leading dashes
190218893Sdim/// have already been stripped.
191218893Sdimstatic Option *LookupNearestOption(StringRef Arg,
192218893Sdim                                   const StringMap<Option*> &OptionsMap,
193221345Sdim                                   std::string &NearestString) {
194218893Sdim  // Reject all dashes.
195218893Sdim  if (Arg.empty()) return 0;
196218893Sdim
197218893Sdim  // Split on any equal sign.
198221345Sdim  std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
199221345Sdim  StringRef &LHS = SplitArg.first;  // LHS == Arg when no '=' is present.
200221345Sdim  StringRef &RHS = SplitArg.second;
201218893Sdim
202218893Sdim  // Find the closest match.
203218893Sdim  Option *Best = 0;
204218893Sdim  unsigned BestDistance = 0;
205218893Sdim  for (StringMap<Option*>::const_iterator it = OptionsMap.begin(),
206218893Sdim         ie = OptionsMap.end(); it != ie; ++it) {
207218893Sdim    Option *O = it->second;
208218893Sdim    SmallVector<const char*, 16> OptionNames;
209218893Sdim    O->getExtraOptionNames(OptionNames);
210218893Sdim    if (O->ArgStr[0])
211218893Sdim      OptionNames.push_back(O->ArgStr);
212218893Sdim
213221345Sdim    bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
214221345Sdim    StringRef Flag = PermitValue ? LHS : Arg;
215218893Sdim    for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
216218893Sdim      StringRef Name = OptionNames[i];
217218893Sdim      unsigned Distance = StringRef(Name).edit_distance(
218221345Sdim        Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
219218893Sdim      if (!Best || Distance < BestDistance) {
220218893Sdim        Best = O;
221218893Sdim        BestDistance = Distance;
222239462Sdim        if (RHS.empty() || !PermitValue)
223239462Sdim          NearestString = OptionNames[i];
224239462Sdim        else
225239462Sdim          NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
226218893Sdim      }
227218893Sdim    }
228218893Sdim  }
229218893Sdim
230218893Sdim  return Best;
231218893Sdim}
232218893Sdim
233199989Srdivacky/// CommaSeparateAndAddOccurence - A wrapper around Handler->addOccurence() that
234199989Srdivacky/// does special handling of cl::CommaSeparated options.
235199989Srdivackystatic bool CommaSeparateAndAddOccurence(Option *Handler, unsigned pos,
236199989Srdivacky                                         StringRef ArgName,
237199989Srdivacky                                         StringRef Value, bool MultiArg = false)
238199989Srdivacky{
239199989Srdivacky  // Check to see if this option accepts a comma separated list of values.  If
240199989Srdivacky  // it does, we have to split up the value into multiple values.
241199989Srdivacky  if (Handler->getMiscFlags() & CommaSeparated) {
242199989Srdivacky    StringRef Val(Value);
243199989Srdivacky    StringRef::size_type Pos = Val.find(',');
244193323Sed
245199989Srdivacky    while (Pos != StringRef::npos) {
246199989Srdivacky      // Process the portion before the comma.
247199989Srdivacky      if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
248199989Srdivacky        return true;
249199989Srdivacky      // Erase the portion before the comma, AND the comma.
250199989Srdivacky      Val = Val.substr(Pos+1);
251199989Srdivacky      Value.substr(Pos+1);  // Increment the original value pointer as well.
252199989Srdivacky      // Check for another comma.
253199989Srdivacky      Pos = Val.find(',');
254199989Srdivacky    }
255193323Sed
256199989Srdivacky    Value = Val;
257199989Srdivacky  }
258199989Srdivacky
259199989Srdivacky  if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
260199989Srdivacky    return true;
261199989Srdivacky
262199989Srdivacky  return false;
263199989Srdivacky}
264199989Srdivacky
265198090Srdivacky/// ProvideOption - For Value, this differentiates between an empty value ("")
266198090Srdivacky/// and a null value (StringRef()).  The later is accepted for arguments that
267198090Srdivacky/// don't allow a value (-foo) the former is rejected (-foo=).
268198090Srdivackystatic inline bool ProvideOption(Option *Handler, StringRef ArgName,
269234353Sdim                                 StringRef Value, int argc,
270234353Sdim                                 const char *const *argv, int &i) {
271193323Sed  // Is this a multi-argument option?
272193323Sed  unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
273193323Sed
274193323Sed  // Enforce value requirements
275193323Sed  switch (Handler->getValueExpectedFlag()) {
276193323Sed  case ValueRequired:
277198090Srdivacky    if (Value.data() == 0) {       // No value specified?
278198090Srdivacky      if (i+1 >= argc)
279198090Srdivacky        return Handler->error("requires a value!");
280198090Srdivacky      // Steal the next argument, like for '-o filename'
281198090Srdivacky      Value = argv[++i];
282193323Sed    }
283193323Sed    break;
284193323Sed  case ValueDisallowed:
285193323Sed    if (NumAdditionalVals > 0)
286198090Srdivacky      return Handler->error("multi-valued option specified"
287198090Srdivacky                            " with ValueDisallowed modifier!");
288193323Sed
289198090Srdivacky    if (Value.data())
290198090Srdivacky      return Handler->error("does not allow a value! '" +
291198090Srdivacky                            Twine(Value) + "' specified.");
292193323Sed    break;
293193323Sed  case ValueOptional:
294193323Sed    break;
295193323Sed  }
296193323Sed
297193323Sed  // If this isn't a multi-arg option, just run the handler.
298198090Srdivacky  if (NumAdditionalVals == 0)
299199989Srdivacky    return CommaSeparateAndAddOccurence(Handler, i, ArgName, Value);
300198090Srdivacky
301193323Sed  // If it is, run the handle several times.
302198090Srdivacky  bool MultiArg = false;
303193323Sed
304198090Srdivacky  if (Value.data()) {
305199989Srdivacky    if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
306198090Srdivacky      return true;
307198090Srdivacky    --NumAdditionalVals;
308198090Srdivacky    MultiArg = true;
309198090Srdivacky  }
310193323Sed
311198090Srdivacky  while (NumAdditionalVals > 0) {
312198090Srdivacky    if (i+1 >= argc)
313198090Srdivacky      return Handler->error("not enough values!");
314198090Srdivacky    Value = argv[++i];
315199989Srdivacky
316199989Srdivacky    if (CommaSeparateAndAddOccurence(Handler, i, ArgName, Value, MultiArg))
317198090Srdivacky      return true;
318198090Srdivacky    MultiArg = true;
319198090Srdivacky    --NumAdditionalVals;
320193323Sed  }
321198090Srdivacky  return false;
322193323Sed}
323193323Sed
324198090Srdivackystatic bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
325193323Sed  int Dummy = i;
326198090Srdivacky  return ProvideOption(Handler, Handler->ArgStr, Arg, 0, 0, Dummy);
327193323Sed}
328193323Sed
329193323Sed
330193323Sed// Option predicates...
331193323Sedstatic inline bool isGrouping(const Option *O) {
332193323Sed  return O->getFormattingFlag() == cl::Grouping;
333193323Sed}
334193323Sedstatic inline bool isPrefixedOrGrouping(const Option *O) {
335193323Sed  return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
336193323Sed}
337193323Sed
338193323Sed// getOptionPred - Check to see if there are any options that satisfy the
339193323Sed// specified predicate with names that are the prefixes in Name.  This is
340193323Sed// checked by progressively stripping characters off of the name, checking to
341193323Sed// see if there options that satisfy the predicate.  If we find one, return it,
342193323Sed// otherwise return null.
343193323Sed//
344198090Srdivackystatic Option *getOptionPred(StringRef Name, size_t &Length,
345193323Sed                             bool (*Pred)(const Option*),
346198090Srdivacky                             const StringMap<Option*> &OptionsMap) {
347193323Sed
348198090Srdivacky  StringMap<Option*>::const_iterator OMI = OptionsMap.find(Name);
349193323Sed
350198090Srdivacky  // Loop while we haven't found an option and Name still has at least two
351198090Srdivacky  // characters in it (so that the next iteration will not be the empty
352198090Srdivacky  // string.
353198090Srdivacky  while (OMI == OptionsMap.end() && Name.size() > 1) {
354198090Srdivacky    Name = Name.substr(0, Name.size()-1);   // Chop off the last character.
355193323Sed    OMI = OptionsMap.find(Name);
356198090Srdivacky  }
357193323Sed
358193323Sed  if (OMI != OptionsMap.end() && Pred(OMI->second)) {
359198090Srdivacky    Length = Name.size();
360193323Sed    return OMI->second;    // Found one!
361193323Sed  }
362193323Sed  return 0;                // No option found!
363193323Sed}
364193323Sed
365198090Srdivacky/// HandlePrefixedOrGroupedOption - The specified argument string (which started
366198090Srdivacky/// with at least one '-') does not fully match an available option.  Check to
367198090Srdivacky/// see if this is a prefix or grouped option.  If so, split arg into output an
368198090Srdivacky/// Arg/Value pair and return the Option to parse it with.
369198090Srdivackystatic Option *HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
370198090Srdivacky                                             bool &ErrorParsing,
371198090Srdivacky                                         const StringMap<Option*> &OptionsMap) {
372198090Srdivacky  if (Arg.size() == 1) return 0;
373198090Srdivacky
374198090Srdivacky  // Do the lookup!
375198090Srdivacky  size_t Length = 0;
376198090Srdivacky  Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
377198090Srdivacky  if (PGOpt == 0) return 0;
378199989Srdivacky
379198090Srdivacky  // If the option is a prefixed option, then the value is simply the
380198090Srdivacky  // rest of the name...  so fall through to later processing, by
381198090Srdivacky  // setting up the argument name flags and value fields.
382198090Srdivacky  if (PGOpt->getFormattingFlag() == cl::Prefix) {
383198090Srdivacky    Value = Arg.substr(Length);
384198090Srdivacky    Arg = Arg.substr(0, Length);
385198090Srdivacky    assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
386198090Srdivacky    return PGOpt;
387198090Srdivacky  }
388199989Srdivacky
389198090Srdivacky  // This must be a grouped option... handle them now.  Grouping options can't
390198090Srdivacky  // have values.
391198090Srdivacky  assert(isGrouping(PGOpt) && "Broken getOptionPred!");
392199989Srdivacky
393198090Srdivacky  do {
394198090Srdivacky    // Move current arg name out of Arg into OneArgName.
395198090Srdivacky    StringRef OneArgName = Arg.substr(0, Length);
396198090Srdivacky    Arg = Arg.substr(Length);
397199989Srdivacky
398198090Srdivacky    // Because ValueRequired is an invalid flag for grouped arguments,
399198090Srdivacky    // we don't need to pass argc/argv in.
400198090Srdivacky    assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
401198090Srdivacky           "Option can not be cl::Grouping AND cl::ValueRequired!");
402202375Srdivacky    int Dummy = 0;
403198090Srdivacky    ErrorParsing |= ProvideOption(PGOpt, OneArgName,
404198090Srdivacky                                  StringRef(), 0, 0, Dummy);
405199989Srdivacky
406198090Srdivacky    // Get the next grouping option.
407198090Srdivacky    PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
408198090Srdivacky  } while (PGOpt && Length != Arg.size());
409199989Srdivacky
410198090Srdivacky  // Return the last option with Arg cut down to just the last one.
411198090Srdivacky  return PGOpt;
412198090Srdivacky}
413198090Srdivacky
414198090Srdivacky
415198090Srdivacky
416193323Sedstatic bool RequiresValue(const Option *O) {
417193323Sed  return O->getNumOccurrencesFlag() == cl::Required ||
418193323Sed         O->getNumOccurrencesFlag() == cl::OneOrMore;
419193323Sed}
420193323Sed
421193323Sedstatic bool EatsUnboundedNumberOfValues(const Option *O) {
422193323Sed  return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
423193323Sed         O->getNumOccurrencesFlag() == cl::OneOrMore;
424193323Sed}
425193323Sed
426193323Sed/// ParseCStringVector - Break INPUT up wherever one or more
427193323Sed/// whitespace characters are found, and store the resulting tokens in
428193323Sed/// OUTPUT. The tokens stored in OUTPUT are dynamically allocated
429198090Srdivacky/// using strdup(), so it is the caller's responsibility to free()
430193323Sed/// them later.
431193323Sed///
432198090Srdivackystatic void ParseCStringVector(std::vector<char *> &OutputVector,
433198090Srdivacky                               const char *Input) {
434193323Sed  // Characters which will be treated as token separators:
435198090Srdivacky  StringRef Delims = " \v\f\t\r\n";
436193323Sed
437198090Srdivacky  StringRef WorkStr(Input);
438198090Srdivacky  while (!WorkStr.empty()) {
439198090Srdivacky    // If the first character is a delimiter, strip them off.
440198090Srdivacky    if (Delims.find(WorkStr[0]) != StringRef::npos) {
441198090Srdivacky      size_t Pos = WorkStr.find_first_not_of(Delims);
442198090Srdivacky      if (Pos == StringRef::npos) Pos = WorkStr.size();
443198090Srdivacky      WorkStr = WorkStr.substr(Pos);
444198090Srdivacky      continue;
445193323Sed    }
446199989Srdivacky
447198090Srdivacky    // Find position of first delimiter.
448198090Srdivacky    size_t Pos = WorkStr.find_first_of(Delims);
449198090Srdivacky    if (Pos == StringRef::npos) Pos = WorkStr.size();
450199989Srdivacky
451198090Srdivacky    // Everything from 0 to Pos is the next word to copy.
452198090Srdivacky    char *NewStr = (char*)malloc(Pos+1);
453198090Srdivacky    memcpy(NewStr, WorkStr.data(), Pos);
454198090Srdivacky    NewStr[Pos] = 0;
455198090Srdivacky    OutputVector.push_back(NewStr);
456199989Srdivacky
457198090Srdivacky    WorkStr = WorkStr.substr(Pos);
458193323Sed  }
459193323Sed}
460193323Sed
461193323Sed/// ParseEnvironmentOptions - An alternative entry point to the
462193323Sed/// CommandLine library, which allows you to read the program's name
463193323Sed/// from the caller (as PROGNAME) and its command-line arguments from
464193323Sed/// an environment variable (whose name is given in ENVVAR).
465193323Sed///
466193323Sedvoid cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
467193323Sed                                 const char *Overview, bool ReadResponseFiles) {
468193323Sed  // Check args.
469193323Sed  assert(progName && "Program name not specified");
470193323Sed  assert(envVar && "Environment variable name missing");
471193323Sed
472193323Sed  // Get the environment variable they want us to parse options out of.
473193323Sed  const char *envValue = getenv(envVar);
474193323Sed  if (!envValue)
475193323Sed    return;
476193323Sed
477193323Sed  // Get program's "name", which we wouldn't know without the caller
478193323Sed  // telling us.
479193323Sed  std::vector<char*> newArgv;
480193323Sed  newArgv.push_back(strdup(progName));
481193323Sed
482193323Sed  // Parse the value of the environment variable into a "command line"
483193323Sed  // and hand it off to ParseCommandLineOptions().
484193323Sed  ParseCStringVector(newArgv, envValue);
485193323Sed  int newArgc = static_cast<int>(newArgv.size());
486193323Sed  ParseCommandLineOptions(newArgc, &newArgv[0], Overview, ReadResponseFiles);
487193323Sed
488193323Sed  // Free all the strdup()ed strings.
489193323Sed  for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
490193323Sed       i != e; ++i)
491198090Srdivacky    free(*i);
492193323Sed}
493193323Sed
494193323Sed
495193323Sed/// ExpandResponseFiles - Copy the contents of argv into newArgv,
496193323Sed/// substituting the contents of the response files for the arguments
497193323Sed/// of type @file.
498234353Sdimstatic void ExpandResponseFiles(unsigned argc, const char*const* argv,
499193323Sed                                std::vector<char*>& newArgv) {
500198090Srdivacky  for (unsigned i = 1; i != argc; ++i) {
501234353Sdim    const char *arg = argv[i];
502193323Sed
503193323Sed    if (arg[0] == '@') {
504193323Sed      sys::PathWithStatus respFile(++arg);
505193323Sed
506193323Sed      // Check that the response file is not empty (mmap'ing empty
507193323Sed      // files can be problematic).
508193323Sed      const sys::FileStatus *FileStat = respFile.getFileStatus();
509193323Sed      if (FileStat && FileStat->getSize() != 0) {
510193323Sed
511193323Sed        // If we could open the file, parse its contents, otherwise
512193323Sed        // pass the @file option verbatim.
513193323Sed
514193323Sed        // TODO: we should also support recursive loading of response files,
515193323Sed        // since this is how gcc behaves. (From their man page: "The file may
516193323Sed        // itself contain additional @file options; any such options will be
517193323Sed        // processed recursively.")
518193323Sed
519218893Sdim        // Mmap the response file into memory.
520218893Sdim        OwningPtr<MemoryBuffer> respFilePtr;
521218893Sdim        if (!MemoryBuffer::getFile(respFile.c_str(), respFilePtr)) {
522193323Sed          ParseCStringVector(newArgv, respFilePtr->getBufferStart());
523193323Sed          continue;
524193323Sed        }
525193323Sed      }
526193323Sed    }
527193323Sed    newArgv.push_back(strdup(arg));
528193323Sed  }
529193323Sed}
530193323Sed
531234353Sdimvoid cl::ParseCommandLineOptions(int argc, const char * const *argv,
532193323Sed                                 const char *Overview, bool ReadResponseFiles) {
533193323Sed  // Process all registered options.
534198090Srdivacky  SmallVector<Option*, 4> PositionalOpts;
535198090Srdivacky  SmallVector<Option*, 4> SinkOpts;
536198090Srdivacky  StringMap<Option*> Opts;
537193323Sed  GetOptionInfo(PositionalOpts, SinkOpts, Opts);
538193323Sed
539193323Sed  assert((!Opts.empty() || !PositionalOpts.empty()) &&
540193323Sed         "No options specified!");
541193323Sed
542193323Sed  // Expand response files.
543193323Sed  std::vector<char*> newArgv;
544193323Sed  if (ReadResponseFiles) {
545193323Sed    newArgv.push_back(strdup(argv[0]));
546193323Sed    ExpandResponseFiles(argc, argv, newArgv);
547193323Sed    argv = &newArgv[0];
548193323Sed    argc = static_cast<int>(newArgv.size());
549193323Sed  }
550193323Sed
551193323Sed  // Copy the program name into ProgName, making sure not to overflow it.
552218893Sdim  std::string ProgName = sys::path::filename(argv[0]);
553203954Srdivacky  size_t Len = std::min(ProgName.size(), size_t(79));
554203954Srdivacky  memcpy(ProgramName, ProgName.data(), Len);
555203954Srdivacky  ProgramName[Len] = '\0';
556193323Sed
557193323Sed  ProgramOverview = Overview;
558193323Sed  bool ErrorParsing = false;
559193323Sed
560193323Sed  // Check out the positional arguments to collect information about them.
561193323Sed  unsigned NumPositionalRequired = 0;
562193323Sed
563193323Sed  // Determine whether or not there are an unlimited number of positionals
564193323Sed  bool HasUnlimitedPositionals = false;
565193323Sed
566193323Sed  Option *ConsumeAfterOpt = 0;
567193323Sed  if (!PositionalOpts.empty()) {
568193323Sed    if (PositionalOpts[0]->getNumOccurrencesFlag() == cl::ConsumeAfter) {
569193323Sed      assert(PositionalOpts.size() > 1 &&
570193323Sed             "Cannot specify cl::ConsumeAfter without a positional argument!");
571193323Sed      ConsumeAfterOpt = PositionalOpts[0];
572193323Sed    }
573193323Sed
574193323Sed    // Calculate how many positional values are _required_.
575193323Sed    bool UnboundedFound = false;
576193323Sed    for (size_t i = ConsumeAfterOpt != 0, e = PositionalOpts.size();
577193323Sed         i != e; ++i) {
578193323Sed      Option *Opt = PositionalOpts[i];
579193323Sed      if (RequiresValue(Opt))
580193323Sed        ++NumPositionalRequired;
581193323Sed      else if (ConsumeAfterOpt) {
582193323Sed        // ConsumeAfter cannot be combined with "optional" positional options
583193323Sed        // unless there is only one positional argument...
584193323Sed        if (PositionalOpts.size() > 2)
585193323Sed          ErrorParsing |=
586198090Srdivacky            Opt->error("error - this positional option will never be matched, "
587193323Sed                       "because it does not Require a value, and a "
588193323Sed                       "cl::ConsumeAfter option is active!");
589193323Sed      } else if (UnboundedFound && !Opt->ArgStr[0]) {
590193323Sed        // This option does not "require" a value...  Make sure this option is
591193323Sed        // not specified after an option that eats all extra arguments, or this
592193323Sed        // one will never get any!
593193323Sed        //
594198090Srdivacky        ErrorParsing |= Opt->error("error - option can never match, because "
595193323Sed                                   "another positional argument will match an "
596193323Sed                                   "unbounded number of values, and this option"
597193323Sed                                   " does not require a value!");
598193323Sed      }
599193323Sed      UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
600193323Sed    }
601193323Sed    HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
602193323Sed  }
603193323Sed
604193323Sed  // PositionalVals - A vector of "positional" arguments we accumulate into
605198090Srdivacky  // the process at the end.
606193323Sed  //
607198090Srdivacky  SmallVector<std::pair<StringRef,unsigned>, 4> PositionalVals;
608193323Sed
609193323Sed  // If the program has named positional arguments, and the name has been run
610193323Sed  // across, keep track of which positional argument was named.  Otherwise put
611193323Sed  // the positional args into the PositionalVals list...
612193323Sed  Option *ActivePositionalArg = 0;
613193323Sed
614193323Sed  // Loop over all of the arguments... processing them.
615193323Sed  bool DashDashFound = false;  // Have we read '--'?
616193323Sed  for (int i = 1; i < argc; ++i) {
617193323Sed    Option *Handler = 0;
618218893Sdim    Option *NearestHandler = 0;
619221345Sdim    std::string NearestHandlerString;
620198090Srdivacky    StringRef Value;
621198090Srdivacky    StringRef ArgName = "";
622193323Sed
623193323Sed    // If the option list changed, this means that some command line
624193323Sed    // option has just been registered or deregistered.  This can occur in
625193323Sed    // response to things like -load, etc.  If this happens, rescan the options.
626193323Sed    if (OptionListChanged) {
627193323Sed      PositionalOpts.clear();
628193323Sed      SinkOpts.clear();
629193323Sed      Opts.clear();
630193323Sed      GetOptionInfo(PositionalOpts, SinkOpts, Opts);
631193323Sed      OptionListChanged = false;
632193323Sed    }
633193323Sed
634193323Sed    // Check to see if this is a positional argument.  This argument is
635193323Sed    // considered to be positional if it doesn't start with '-', if it is "-"
636193323Sed    // itself, or if we have seen "--" already.
637193323Sed    //
638193323Sed    if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
639193323Sed      // Positional argument!
640193323Sed      if (ActivePositionalArg) {
641193323Sed        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
642193323Sed        continue;  // We are done!
643198090Srdivacky      }
644199989Srdivacky
645198090Srdivacky      if (!PositionalOpts.empty()) {
646193323Sed        PositionalVals.push_back(std::make_pair(argv[i],i));
647193323Sed
648193323Sed        // All of the positional arguments have been fulfulled, give the rest to
649193323Sed        // the consume after option... if it's specified...
650193323Sed        //
651193323Sed        if (PositionalVals.size() >= NumPositionalRequired &&
652193323Sed            ConsumeAfterOpt != 0) {
653193323Sed          for (++i; i < argc; ++i)
654193323Sed            PositionalVals.push_back(std::make_pair(argv[i],i));
655193323Sed          break;   // Handle outside of the argument processing loop...
656193323Sed        }
657193323Sed
658193323Sed        // Delay processing positional arguments until the end...
659193323Sed        continue;
660193323Sed      }
661193323Sed    } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
662193323Sed               !DashDashFound) {
663193323Sed      DashDashFound = true;  // This is the mythical "--"?
664193323Sed      continue;              // Don't try to process it as an argument itself.
665193323Sed    } else if (ActivePositionalArg &&
666193323Sed               (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
667193323Sed      // If there is a positional argument eating options, check to see if this
668193323Sed      // option is another positional argument.  If so, treat it as an argument,
669193323Sed      // otherwise feed it to the eating positional.
670193323Sed      ArgName = argv[i]+1;
671198090Srdivacky      // Eat leading dashes.
672198090Srdivacky      while (!ArgName.empty() && ArgName[0] == '-')
673198090Srdivacky        ArgName = ArgName.substr(1);
674199989Srdivacky
675193323Sed      Handler = LookupOption(ArgName, Value, Opts);
676193323Sed      if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
677193323Sed        ProvidePositionalOption(ActivePositionalArg, argv[i], i);
678193323Sed        continue;  // We are done!
679193323Sed      }
680193323Sed
681198090Srdivacky    } else {     // We start with a '-', must be an argument.
682193323Sed      ArgName = argv[i]+1;
683198090Srdivacky      // Eat leading dashes.
684198090Srdivacky      while (!ArgName.empty() && ArgName[0] == '-')
685198090Srdivacky        ArgName = ArgName.substr(1);
686199989Srdivacky
687193323Sed      Handler = LookupOption(ArgName, Value, Opts);
688193323Sed
689193323Sed      // Check to see if this "option" is really a prefixed or grouped argument.
690198090Srdivacky      if (Handler == 0)
691198090Srdivacky        Handler = HandlePrefixedOrGroupedOption(ArgName, Value,
692198090Srdivacky                                                ErrorParsing, Opts);
693218893Sdim
694218893Sdim      // Otherwise, look for the closest available option to report to the user
695218893Sdim      // in the upcoming error.
696218893Sdim      if (Handler == 0 && SinkOpts.empty())
697218893Sdim        NearestHandler = LookupNearestOption(ArgName, Opts,
698218893Sdim                                             NearestHandlerString);
699193323Sed    }
700193323Sed
701193323Sed    if (Handler == 0) {
702193323Sed      if (SinkOpts.empty()) {
703198090Srdivacky        errs() << ProgramName << ": Unknown command line argument '"
704204642Srdivacky             << argv[i] << "'.  Try: '" << argv[0] << " -help'\n";
705218893Sdim
706218893Sdim        if (NearestHandler) {
707218893Sdim          // If we know a near match, report it as well.
708218893Sdim          errs() << ProgramName << ": Did you mean '-"
709218893Sdim                 << NearestHandlerString << "'?\n";
710218893Sdim        }
711218893Sdim
712193323Sed        ErrorParsing = true;
713193323Sed      } else {
714198090Srdivacky        for (SmallVectorImpl<Option*>::iterator I = SinkOpts.begin(),
715193323Sed               E = SinkOpts.end(); I != E ; ++I)
716193323Sed          (*I)->addOccurrence(i, "", argv[i]);
717193323Sed      }
718193323Sed      continue;
719193323Sed    }
720193323Sed
721193323Sed    // If this is a named positional argument, just remember that it is the
722193323Sed    // active one...
723193323Sed    if (Handler->getFormattingFlag() == cl::Positional)
724193323Sed      ActivePositionalArg = Handler;
725193323Sed    else
726193323Sed      ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
727193323Sed  }
728193323Sed
729193323Sed  // Check and handle positional arguments now...
730193323Sed  if (NumPositionalRequired > PositionalVals.size()) {
731198090Srdivacky    errs() << ProgramName
732193323Sed         << ": Not enough positional command line arguments specified!\n"
733193323Sed         << "Must specify at least " << NumPositionalRequired
734204642Srdivacky         << " positional arguments: See: " << argv[0] << " -help\n";
735193323Sed
736193323Sed    ErrorParsing = true;
737206083Srdivacky  } else if (!HasUnlimitedPositionals &&
738206083Srdivacky             PositionalVals.size() > PositionalOpts.size()) {
739198090Srdivacky    errs() << ProgramName
740193323Sed         << ": Too many positional arguments specified!\n"
741193323Sed         << "Can specify at most " << PositionalOpts.size()
742204642Srdivacky         << " positional arguments: See: " << argv[0] << " -help\n";
743193323Sed    ErrorParsing = true;
744193323Sed
745193323Sed  } else if (ConsumeAfterOpt == 0) {
746198090Srdivacky    // Positional args have already been handled if ConsumeAfter is specified.
747193323Sed    unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
748193323Sed    for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
749193323Sed      if (RequiresValue(PositionalOpts[i])) {
750193323Sed        ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
751193323Sed                                PositionalVals[ValNo].second);
752193323Sed        ValNo++;
753193323Sed        --NumPositionalRequired;  // We fulfilled our duty...
754193323Sed      }
755193323Sed
756193323Sed      // If we _can_ give this option more arguments, do so now, as long as we
757193323Sed      // do not give it values that others need.  'Done' controls whether the
758193323Sed      // option even _WANTS_ any more.
759193323Sed      //
760193323Sed      bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
761193323Sed      while (NumVals-ValNo > NumPositionalRequired && !Done) {
762193323Sed        switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
763193323Sed        case cl::Optional:
764193323Sed          Done = true;          // Optional arguments want _at most_ one value
765193323Sed          // FALL THROUGH
766193323Sed        case cl::ZeroOrMore:    // Zero or more will take all they can get...
767193323Sed        case cl::OneOrMore:     // One or more will take all they can get...
768193323Sed          ProvidePositionalOption(PositionalOpts[i],
769193323Sed                                  PositionalVals[ValNo].first,
770193323Sed                                  PositionalVals[ValNo].second);
771193323Sed          ValNo++;
772193323Sed          break;
773193323Sed        default:
774198090Srdivacky          llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
775193323Sed                 "positional argument processing!");
776193323Sed        }
777193323Sed      }
778193323Sed    }
779193323Sed  } else {
780193323Sed    assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
781193323Sed    unsigned ValNo = 0;
782193323Sed    for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
783193323Sed      if (RequiresValue(PositionalOpts[j])) {
784193323Sed        ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
785193323Sed                                                PositionalVals[ValNo].first,
786193323Sed                                                PositionalVals[ValNo].second);
787193323Sed        ValNo++;
788193323Sed      }
789193323Sed
790193323Sed    // Handle the case where there is just one positional option, and it's
791193323Sed    // optional.  In this case, we want to give JUST THE FIRST option to the
792193323Sed    // positional option and keep the rest for the consume after.  The above
793193323Sed    // loop would have assigned no values to positional options in this case.
794193323Sed    //
795193323Sed    if (PositionalOpts.size() == 2 && ValNo == 0 && !PositionalVals.empty()) {
796193323Sed      ErrorParsing |= ProvidePositionalOption(PositionalOpts[1],
797193323Sed                                              PositionalVals[ValNo].first,
798193323Sed                                              PositionalVals[ValNo].second);
799193323Sed      ValNo++;
800193323Sed    }
801193323Sed
802193323Sed    // Handle over all of the rest of the arguments to the
803193323Sed    // cl::ConsumeAfter command line option...
804193323Sed    for (; ValNo != PositionalVals.size(); ++ValNo)
805193323Sed      ErrorParsing |= ProvidePositionalOption(ConsumeAfterOpt,
806193323Sed                                              PositionalVals[ValNo].first,
807193323Sed                                              PositionalVals[ValNo].second);
808193323Sed  }
809193323Sed
810193323Sed  // Loop over args and make sure all required args are specified!
811198090Srdivacky  for (StringMap<Option*>::iterator I = Opts.begin(),
812193323Sed         E = Opts.end(); I != E; ++I) {
813193323Sed    switch (I->second->getNumOccurrencesFlag()) {
814193323Sed    case Required:
815193323Sed    case OneOrMore:
816193323Sed      if (I->second->getNumOccurrences() == 0) {
817198090Srdivacky        I->second->error("must be specified at least once!");
818193323Sed        ErrorParsing = true;
819193323Sed      }
820193323Sed      // Fall through
821193323Sed    default:
822193323Sed      break;
823193323Sed    }
824193323Sed  }
825193323Sed
826218893Sdim  // Now that we know if -debug is specified, we can use it.
827218893Sdim  // Note that if ReadResponseFiles == true, this must be done before the
828218893Sdim  // memory allocated for the expanded command line is free()d below.
829218893Sdim  DEBUG(dbgs() << "Args: ";
830218893Sdim        for (int i = 0; i < argc; ++i)
831218893Sdim          dbgs() << argv[i] << ' ';
832218893Sdim        dbgs() << '\n';
833218893Sdim       );
834218893Sdim
835193323Sed  // Free all of the memory allocated to the map.  Command line options may only
836193323Sed  // be processed once!
837193323Sed  Opts.clear();
838193323Sed  PositionalOpts.clear();
839193323Sed  MoreHelp->clear();
840193323Sed
841193323Sed  // Free the memory allocated by ExpandResponseFiles.
842193323Sed  if (ReadResponseFiles) {
843193323Sed    // Free all the strdup()ed strings.
844193323Sed    for (std::vector<char*>::iterator i = newArgv.begin(), e = newArgv.end();
845193323Sed         i != e; ++i)
846198090Srdivacky      free(*i);
847193323Sed  }
848193323Sed
849193323Sed  // If we had an error processing our arguments, don't let the program execute
850193323Sed  if (ErrorParsing) exit(1);
851193323Sed}
852193323Sed
853193323Sed//===----------------------------------------------------------------------===//
854193323Sed// Option Base class implementation
855193323Sed//
856193323Sed
857198090Srdivackybool Option::error(const Twine &Message, StringRef ArgName) {
858198090Srdivacky  if (ArgName.data() == 0) ArgName = ArgStr;
859198090Srdivacky  if (ArgName.empty())
860198090Srdivacky    errs() << HelpStr;  // Be nice for positional arguments
861193323Sed  else
862198090Srdivacky    errs() << ProgramName << ": for the -" << ArgName;
863193323Sed
864198090Srdivacky  errs() << " option: " << Message << "\n";
865193323Sed  return true;
866193323Sed}
867193323Sed
868198090Srdivackybool Option::addOccurrence(unsigned pos, StringRef ArgName,
869198090Srdivacky                           StringRef Value, bool MultiArg) {
870193323Sed  if (!MultiArg)
871193323Sed    NumOccurrences++;   // Increment the number of times we have been seen
872193323Sed
873193323Sed  switch (getNumOccurrencesFlag()) {
874193323Sed  case Optional:
875193323Sed    if (NumOccurrences > 1)
876198090Srdivacky      return error("may only occur zero or one times!", ArgName);
877193323Sed    break;
878193323Sed  case Required:
879193323Sed    if (NumOccurrences > 1)
880198090Srdivacky      return error("must occur exactly one time!", ArgName);
881193323Sed    // Fall through
882193323Sed  case OneOrMore:
883193323Sed  case ZeroOrMore:
884193323Sed  case ConsumeAfter: break;
885193323Sed  }
886193323Sed
887193323Sed  return handleOccurrence(pos, ArgName, Value);
888193323Sed}
889193323Sed
890193323Sed
891193323Sed// getValueStr - Get the value description string, using "DefaultMsg" if nothing
892193323Sed// has been specified yet.
893193323Sed//
894193323Sedstatic const char *getValueStr(const Option &O, const char *DefaultMsg) {
895193323Sed  if (O.ValueStr[0] == 0) return DefaultMsg;
896193323Sed  return O.ValueStr;
897193323Sed}
898193323Sed
899193323Sed//===----------------------------------------------------------------------===//
900193323Sed// cl::alias class implementation
901193323Sed//
902193323Sed
903193323Sed// Return the width of the option tag for printing...
904193323Sedsize_t alias::getOptionWidth() const {
905193323Sed  return std::strlen(ArgStr)+6;
906193323Sed}
907193323Sed
908193323Sed// Print out the option for the alias.
909193323Sedvoid alias::printOptionInfo(size_t GlobalWidth) const {
910193323Sed  size_t L = std::strlen(ArgStr);
911224145Sdim  outs() << "  -" << ArgStr;
912224145Sdim  outs().indent(GlobalWidth-L-6) << " - " << HelpStr << "\n";
913193323Sed}
914193323Sed
915193323Sed//===----------------------------------------------------------------------===//
916193323Sed// Parser Implementation code...
917193323Sed//
918193323Sed
919193323Sed// basic_parser implementation
920193323Sed//
921193323Sed
922193323Sed// Return the width of the option tag for printing...
923193323Sedsize_t basic_parser_impl::getOptionWidth(const Option &O) const {
924193323Sed  size_t Len = std::strlen(O.ArgStr);
925193323Sed  if (const char *ValName = getValueName())
926193323Sed    Len += std::strlen(getValueStr(O, ValName))+3;
927193323Sed
928193323Sed  return Len + 6;
929193323Sed}
930193323Sed
931193323Sed// printOptionInfo - Print out information about this option.  The
932193323Sed// to-be-maintained width is specified.
933193323Sed//
934193323Sedvoid basic_parser_impl::printOptionInfo(const Option &O,
935193323Sed                                        size_t GlobalWidth) const {
936198090Srdivacky  outs() << "  -" << O.ArgStr;
937193323Sed
938193323Sed  if (const char *ValName = getValueName())
939198090Srdivacky    outs() << "=<" << getValueStr(O, ValName) << '>';
940193323Sed
941198090Srdivacky  outs().indent(GlobalWidth-getOptionWidth(O)) << " - " << O.HelpStr << '\n';
942193323Sed}
943193323Sed
944221345Sdimvoid basic_parser_impl::printOptionName(const Option &O,
945221345Sdim                                        size_t GlobalWidth) const {
946221345Sdim  outs() << "  -" << O.ArgStr;
947221345Sdim  outs().indent(GlobalWidth-std::strlen(O.ArgStr));
948221345Sdim}
949193323Sed
950193323Sed
951193323Sed// parser<bool> implementation
952193323Sed//
953198090Srdivackybool parser<bool>::parse(Option &O, StringRef ArgName,
954198090Srdivacky                         StringRef Arg, bool &Value) {
955193323Sed  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
956193323Sed      Arg == "1") {
957193323Sed    Value = true;
958198090Srdivacky    return false;
959198090Srdivacky  }
960199989Srdivacky
961198090Srdivacky  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
962193323Sed    Value = false;
963198090Srdivacky    return false;
964193323Sed  }
965198090Srdivacky  return O.error("'" + Arg +
966198090Srdivacky                 "' is invalid value for boolean argument! Try 0 or 1");
967193323Sed}
968193323Sed
969193323Sed// parser<boolOrDefault> implementation
970193323Sed//
971198090Srdivackybool parser<boolOrDefault>::parse(Option &O, StringRef ArgName,
972198090Srdivacky                                  StringRef Arg, boolOrDefault &Value) {
973193323Sed  if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
974193323Sed      Arg == "1") {
975193323Sed    Value = BOU_TRUE;
976198090Srdivacky    return false;
977198090Srdivacky  }
978198090Srdivacky  if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
979193323Sed    Value = BOU_FALSE;
980198090Srdivacky    return false;
981193323Sed  }
982199989Srdivacky
983198090Srdivacky  return O.error("'" + Arg +
984198090Srdivacky                 "' is invalid value for boolean argument! Try 0 or 1");
985193323Sed}
986193323Sed
987193323Sed// parser<int> implementation
988193323Sed//
989198090Srdivackybool parser<int>::parse(Option &O, StringRef ArgName,
990198090Srdivacky                        StringRef Arg, int &Value) {
991198090Srdivacky  if (Arg.getAsInteger(0, Value))
992198090Srdivacky    return O.error("'" + Arg + "' value invalid for integer argument!");
993193323Sed  return false;
994193323Sed}
995193323Sed
996193323Sed// parser<unsigned> implementation
997193323Sed//
998198090Srdivackybool parser<unsigned>::parse(Option &O, StringRef ArgName,
999198090Srdivacky                             StringRef Arg, unsigned &Value) {
1000198090Srdivacky
1001198090Srdivacky  if (Arg.getAsInteger(0, Value))
1002198090Srdivacky    return O.error("'" + Arg + "' value invalid for uint argument!");
1003193323Sed  return false;
1004193323Sed}
1005193323Sed
1006226633Sdim// parser<unsigned long long> implementation
1007226633Sdim//
1008226633Sdimbool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
1009226633Sdim                                      StringRef Arg, unsigned long long &Value){
1010226633Sdim
1011226633Sdim  if (Arg.getAsInteger(0, Value))
1012226633Sdim    return O.error("'" + Arg + "' value invalid for uint argument!");
1013226633Sdim  return false;
1014226633Sdim}
1015226633Sdim
1016193323Sed// parser<double>/parser<float> implementation
1017193323Sed//
1018198090Srdivackystatic bool parseDouble(Option &O, StringRef Arg, double &Value) {
1019198090Srdivacky  SmallString<32> TmpStr(Arg.begin(), Arg.end());
1020198090Srdivacky  const char *ArgStart = TmpStr.c_str();
1021193323Sed  char *End;
1022193323Sed  Value = strtod(ArgStart, &End);
1023193323Sed  if (*End != 0)
1024198090Srdivacky    return O.error("'" + Arg + "' value invalid for floating point argument!");
1025193323Sed  return false;
1026193323Sed}
1027193323Sed
1028198090Srdivackybool parser<double>::parse(Option &O, StringRef ArgName,
1029198090Srdivacky                           StringRef Arg, double &Val) {
1030193323Sed  return parseDouble(O, Arg, Val);
1031193323Sed}
1032193323Sed
1033198090Srdivackybool parser<float>::parse(Option &O, StringRef ArgName,
1034198090Srdivacky                          StringRef Arg, float &Val) {
1035193323Sed  double dVal;
1036193323Sed  if (parseDouble(O, Arg, dVal))
1037193323Sed    return true;
1038193323Sed  Val = (float)dVal;
1039193323Sed  return false;
1040193323Sed}
1041193323Sed
1042193323Sed
1043193323Sed
1044193323Sed// generic_parser_base implementation
1045193323Sed//
1046193323Sed
1047193323Sed// findOption - Return the option number corresponding to the specified
1048193323Sed// argument string.  If the option is not found, getNumOptions() is returned.
1049193323Sed//
1050193323Sedunsigned generic_parser_base::findOption(const char *Name) {
1051198090Srdivacky  unsigned e = getNumOptions();
1052193323Sed
1053198090Srdivacky  for (unsigned i = 0; i != e; ++i) {
1054198090Srdivacky    if (strcmp(getOption(i), Name) == 0)
1055193323Sed      return i;
1056198090Srdivacky  }
1057193323Sed  return e;
1058193323Sed}
1059193323Sed
1060193323Sed
1061193323Sed// Return the width of the option tag for printing...
1062193323Sedsize_t generic_parser_base::getOptionWidth(const Option &O) const {
1063193323Sed  if (O.hasArgStr()) {
1064193323Sed    size_t Size = std::strlen(O.ArgStr)+6;
1065193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1066193323Sed      Size = std::max(Size, std::strlen(getOption(i))+8);
1067193323Sed    return Size;
1068193323Sed  } else {
1069193323Sed    size_t BaseSize = 0;
1070193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
1071193323Sed      BaseSize = std::max(BaseSize, std::strlen(getOption(i))+8);
1072193323Sed    return BaseSize;
1073193323Sed  }
1074193323Sed}
1075193323Sed
1076193323Sed// printOptionInfo - Print out information about this option.  The
1077193323Sed// to-be-maintained width is specified.
1078193323Sed//
1079193323Sedvoid generic_parser_base::printOptionInfo(const Option &O,
1080193323Sed                                          size_t GlobalWidth) const {
1081193323Sed  if (O.hasArgStr()) {
1082193323Sed    size_t L = std::strlen(O.ArgStr);
1083198090Srdivacky    outs() << "  -" << O.ArgStr;
1084198090Srdivacky    outs().indent(GlobalWidth-L-6) << " - " << O.HelpStr << '\n';
1085193323Sed
1086193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1087193323Sed      size_t NumSpaces = GlobalWidth-strlen(getOption(i))-8;
1088198090Srdivacky      outs() << "    =" << getOption(i);
1089198090Srdivacky      outs().indent(NumSpaces) << " -   " << getDescription(i) << '\n';
1090193323Sed    }
1091193323Sed  } else {
1092193323Sed    if (O.HelpStr[0])
1093198090Srdivacky      outs() << "  " << O.HelpStr << '\n';
1094193323Sed    for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
1095193323Sed      size_t L = std::strlen(getOption(i));
1096198090Srdivacky      outs() << "    -" << getOption(i);
1097198090Srdivacky      outs().indent(GlobalWidth-L-8) << " - " << getDescription(i) << '\n';
1098193323Sed    }
1099193323Sed  }
1100193323Sed}
1101193323Sed
1102221345Sdimstatic const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1103193323Sed
1104221345Sdim// printGenericOptionDiff - Print the value of this option and it's default.
1105221345Sdim//
1106221345Sdim// "Generic" options have each value mapped to a name.
1107221345Sdimvoid generic_parser_base::
1108221345SdimprintGenericOptionDiff(const Option &O, const GenericOptionValue &Value,
1109221345Sdim                       const GenericOptionValue &Default,
1110221345Sdim                       size_t GlobalWidth) const {
1111221345Sdim  outs() << "  -" << O.ArgStr;
1112221345Sdim  outs().indent(GlobalWidth-std::strlen(O.ArgStr));
1113221345Sdim
1114221345Sdim  unsigned NumOpts = getNumOptions();
1115221345Sdim  for (unsigned i = 0; i != NumOpts; ++i) {
1116221345Sdim    if (Value.compare(getOptionValue(i)))
1117221345Sdim      continue;
1118221345Sdim
1119221345Sdim    outs() << "= " << getOption(i);
1120221345Sdim    size_t L = std::strlen(getOption(i));
1121221345Sdim    size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1122221345Sdim    outs().indent(NumSpaces) << " (default: ";
1123221345Sdim    for (unsigned j = 0; j != NumOpts; ++j) {
1124221345Sdim      if (Default.compare(getOptionValue(j)))
1125221345Sdim        continue;
1126221345Sdim      outs() << getOption(j);
1127221345Sdim      break;
1128221345Sdim    }
1129221345Sdim    outs() << ")\n";
1130221345Sdim    return;
1131221345Sdim  }
1132221345Sdim  outs() << "= *unknown option value*\n";
1133221345Sdim}
1134221345Sdim
1135221345Sdim// printOptionDiff - Specializations for printing basic value types.
1136221345Sdim//
1137221345Sdim#define PRINT_OPT_DIFF(T)                                               \
1138221345Sdim  void parser<T>::                                                      \
1139221345Sdim  printOptionDiff(const Option &O, T V, OptionValue<T> D,               \
1140221345Sdim                  size_t GlobalWidth) const {                           \
1141221345Sdim    printOptionName(O, GlobalWidth);                                    \
1142221345Sdim    std::string Str;                                                    \
1143221345Sdim    {                                                                   \
1144221345Sdim      raw_string_ostream SS(Str);                                       \
1145221345Sdim      SS << V;                                                          \
1146221345Sdim    }                                                                   \
1147221345Sdim    outs() << "= " << Str;                                              \
1148221345Sdim    size_t NumSpaces = MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0;\
1149221345Sdim    outs().indent(NumSpaces) << " (default: ";                          \
1150221345Sdim    if (D.hasValue())                                                   \
1151221345Sdim      outs() << D.getValue();                                           \
1152221345Sdim    else                                                                \
1153221345Sdim      outs() << "*no default*";                                         \
1154221345Sdim    outs() << ")\n";                                                    \
1155221345Sdim  }                                                                     \
1156221345Sdim
1157221345SdimPRINT_OPT_DIFF(bool)
1158221345SdimPRINT_OPT_DIFF(boolOrDefault)
1159221345SdimPRINT_OPT_DIFF(int)
1160221345SdimPRINT_OPT_DIFF(unsigned)
1161226633SdimPRINT_OPT_DIFF(unsigned long long)
1162221345SdimPRINT_OPT_DIFF(double)
1163221345SdimPRINT_OPT_DIFF(float)
1164221345SdimPRINT_OPT_DIFF(char)
1165221345Sdim
1166221345Sdimvoid parser<std::string>::
1167221345SdimprintOptionDiff(const Option &O, StringRef V, OptionValue<std::string> D,
1168221345Sdim                size_t GlobalWidth) const {
1169221345Sdim  printOptionName(O, GlobalWidth);
1170221345Sdim  outs() << "= " << V;
1171221345Sdim  size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1172221345Sdim  outs().indent(NumSpaces) << " (default: ";
1173221345Sdim  if (D.hasValue())
1174221345Sdim    outs() << D.getValue();
1175221345Sdim  else
1176221345Sdim    outs() << "*no default*";
1177221345Sdim  outs() << ")\n";
1178221345Sdim}
1179221345Sdim
1180221345Sdim// Print a placeholder for options that don't yet support printOptionDiff().
1181221345Sdimvoid basic_parser_impl::
1182221345SdimprintOptionNoValue(const Option &O, size_t GlobalWidth) const {
1183221345Sdim  printOptionName(O, GlobalWidth);
1184221345Sdim  outs() << "= *cannot print option value*\n";
1185221345Sdim}
1186221345Sdim
1187193323Sed//===----------------------------------------------------------------------===//
1188204642Srdivacky// -help and -help-hidden option implementation
1189193323Sed//
1190193323Sed
1191198090Srdivackystatic int OptNameCompare(const void *LHS, const void *RHS) {
1192198090Srdivacky  typedef std::pair<const char *, Option*> pair_ty;
1193199989Srdivacky
1194234353Sdim  return strcmp(((const pair_ty*)LHS)->first, ((const pair_ty*)RHS)->first);
1195198090Srdivacky}
1196198090Srdivacky
1197221345Sdim// Copy Options into a vector so we can sort them as we like.
1198221345Sdimstatic void
1199221345SdimsortOpts(StringMap<Option*> &OptMap,
1200221345Sdim         SmallVectorImpl< std::pair<const char *, Option*> > &Opts,
1201221345Sdim         bool ShowHidden) {
1202221345Sdim  SmallPtrSet<Option*, 128> OptionSet;  // Duplicate option detection.
1203221345Sdim
1204221345Sdim  for (StringMap<Option*>::iterator I = OptMap.begin(), E = OptMap.end();
1205221345Sdim       I != E; ++I) {
1206221345Sdim    // Ignore really-hidden options.
1207221345Sdim    if (I->second->getOptionHiddenFlag() == ReallyHidden)
1208221345Sdim      continue;
1209221345Sdim
1210221345Sdim    // Unless showhidden is set, ignore hidden flags.
1211221345Sdim    if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1212221345Sdim      continue;
1213221345Sdim
1214221345Sdim    // If we've already seen this option, don't add it to the list again.
1215221345Sdim    if (!OptionSet.insert(I->second))
1216221345Sdim      continue;
1217221345Sdim
1218221345Sdim    Opts.push_back(std::pair<const char *, Option*>(I->getKey().data(),
1219221345Sdim                                                    I->second));
1220221345Sdim  }
1221221345Sdim
1222221345Sdim  // Sort the options list alphabetically.
1223221345Sdim  qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1224221345Sdim}
1225221345Sdim
1226193323Sednamespace {
1227193323Sed
1228193323Sedclass HelpPrinter {
1229193323Sed  size_t MaxArgLen;
1230193323Sed  const Option *EmptyArg;
1231193323Sed  const bool ShowHidden;
1232193323Sed
1233193323Sedpublic:
1234193323Sed  explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {
1235193323Sed    EmptyArg = 0;
1236193323Sed  }
1237193323Sed
1238193323Sed  void operator=(bool Value) {
1239193323Sed    if (Value == false) return;
1240193323Sed
1241193323Sed    // Get all the options.
1242198090Srdivacky    SmallVector<Option*, 4> PositionalOpts;
1243198090Srdivacky    SmallVector<Option*, 4> SinkOpts;
1244198090Srdivacky    StringMap<Option*> OptMap;
1245193323Sed    GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1246193323Sed
1247198090Srdivacky    SmallVector<std::pair<const char *, Option*>, 128> Opts;
1248221345Sdim    sortOpts(OptMap, Opts, ShowHidden);
1249193323Sed
1250193323Sed    if (ProgramOverview)
1251198090Srdivacky      outs() << "OVERVIEW: " << ProgramOverview << "\n";
1252193323Sed
1253198090Srdivacky    outs() << "USAGE: " << ProgramName << " [options]";
1254193323Sed
1255193323Sed    // Print out the positional options.
1256193323Sed    Option *CAOpt = 0;   // The cl::ConsumeAfter option, if it exists...
1257193323Sed    if (!PositionalOpts.empty() &&
1258193323Sed        PositionalOpts[0]->getNumOccurrencesFlag() == ConsumeAfter)
1259193323Sed      CAOpt = PositionalOpts[0];
1260193323Sed
1261193323Sed    for (size_t i = CAOpt != 0, e = PositionalOpts.size(); i != e; ++i) {
1262193323Sed      if (PositionalOpts[i]->ArgStr[0])
1263198090Srdivacky        outs() << " --" << PositionalOpts[i]->ArgStr;
1264198090Srdivacky      outs() << " " << PositionalOpts[i]->HelpStr;
1265193323Sed    }
1266193323Sed
1267193323Sed    // Print the consume after option info if it exists...
1268198090Srdivacky    if (CAOpt) outs() << " " << CAOpt->HelpStr;
1269193323Sed
1270198090Srdivacky    outs() << "\n\n";
1271193323Sed
1272193323Sed    // Compute the maximum argument length...
1273193323Sed    MaxArgLen = 0;
1274193323Sed    for (size_t i = 0, e = Opts.size(); i != e; ++i)
1275193323Sed      MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1276193323Sed
1277198090Srdivacky    outs() << "OPTIONS:\n";
1278193323Sed    for (size_t i = 0, e = Opts.size(); i != e; ++i)
1279193323Sed      Opts[i].second->printOptionInfo(MaxArgLen);
1280193323Sed
1281193323Sed    // Print any extra help the user has declared.
1282193323Sed    for (std::vector<const char *>::iterator I = MoreHelp->begin(),
1283193323Sed          E = MoreHelp->end(); I != E; ++I)
1284198090Srdivacky      outs() << *I;
1285193323Sed    MoreHelp->clear();
1286193323Sed
1287193323Sed    // Halt the program since help information was printed
1288193323Sed    exit(1);
1289193323Sed  }
1290193323Sed};
1291193323Sed} // End anonymous namespace
1292193323Sed
1293193323Sed// Define the two HelpPrinter instances that are used to print out help, or
1294193323Sed// help-hidden...
1295193323Sed//
1296193323Sedstatic HelpPrinter NormalPrinter(false);
1297193323Sedstatic HelpPrinter HiddenPrinter(true);
1298193323Sed
1299193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> >
1300204642SrdivackyHOp("help", cl::desc("Display available options (-help-hidden for more)"),
1301193323Sed    cl::location(NormalPrinter), cl::ValueDisallowed);
1302193323Sed
1303193323Sedstatic cl::opt<HelpPrinter, true, parser<bool> >
1304193323SedHHOp("help-hidden", cl::desc("Display all available options"),
1305193323Sed     cl::location(HiddenPrinter), cl::Hidden, cl::ValueDisallowed);
1306193323Sed
1307221345Sdimstatic cl::opt<bool>
1308221345SdimPrintOptions("print-options",
1309221345Sdim             cl::desc("Print non-default options after command line parsing"),
1310221345Sdim             cl::Hidden, cl::init(false));
1311221345Sdim
1312221345Sdimstatic cl::opt<bool>
1313221345SdimPrintAllOptions("print-all-options",
1314221345Sdim                cl::desc("Print all option values after command line parsing"),
1315221345Sdim                cl::Hidden, cl::init(false));
1316221345Sdim
1317221345Sdim// Print the value of each option.
1318221345Sdimvoid cl::PrintOptionValues() {
1319221345Sdim  if (!PrintOptions && !PrintAllOptions) return;
1320221345Sdim
1321221345Sdim  // Get all the options.
1322221345Sdim  SmallVector<Option*, 4> PositionalOpts;
1323221345Sdim  SmallVector<Option*, 4> SinkOpts;
1324221345Sdim  StringMap<Option*> OptMap;
1325221345Sdim  GetOptionInfo(PositionalOpts, SinkOpts, OptMap);
1326221345Sdim
1327221345Sdim  SmallVector<std::pair<const char *, Option*>, 128> Opts;
1328221345Sdim  sortOpts(OptMap, Opts, /*ShowHidden*/true);
1329221345Sdim
1330221345Sdim  // Compute the maximum argument length...
1331221345Sdim  size_t MaxArgLen = 0;
1332221345Sdim  for (size_t i = 0, e = Opts.size(); i != e; ++i)
1333221345Sdim    MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1334221345Sdim
1335221345Sdim  for (size_t i = 0, e = Opts.size(); i != e; ++i)
1336221345Sdim    Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1337221345Sdim}
1338221345Sdim
1339193323Sedstatic void (*OverrideVersionPrinter)() = 0;
1340193323Sed
1341226633Sdimstatic std::vector<void (*)()>* ExtraVersionPrinters = 0;
1342198090Srdivacky
1343193323Sednamespace {
1344193323Sedclass VersionPrinter {
1345193323Sedpublic:
1346193323Sed  void print() {
1347198090Srdivacky    raw_ostream &OS = outs();
1348234353Sdim    OS << "LLVM (http://llvm.org/):\n"
1349198090Srdivacky       << "  " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
1350193323Sed#ifdef LLVM_VERSION_INFO
1351198090Srdivacky    OS << LLVM_VERSION_INFO;
1352193323Sed#endif
1353198090Srdivacky    OS << "\n  ";
1354193323Sed#ifndef __OPTIMIZE__
1355198090Srdivacky    OS << "DEBUG build";
1356193323Sed#else
1357198090Srdivacky    OS << "Optimized build";
1358193323Sed#endif
1359193323Sed#ifndef NDEBUG
1360198090Srdivacky    OS << " with assertions";
1361193323Sed#endif
1362199481Srdivacky    std::string CPU = sys::getHostCPUName();
1363199481Srdivacky    if (CPU == "generic") CPU = "(unknown)";
1364198090Srdivacky    OS << ".\n"
1365226633Sdim#if (ENABLE_TIMESTAMPS == 1)
1366198090Srdivacky       << "  Built " << __DATE__ << " (" << __TIME__ << ").\n"
1367208599Srdivacky#endif
1368234353Sdim       << "  Default target: " << sys::getDefaultTargetTriple() << '\n'
1369226633Sdim       << "  Host CPU: " << CPU << '\n';
1370193323Sed  }
1371193323Sed  void operator=(bool OptionWasSpecified) {
1372198090Srdivacky    if (!OptionWasSpecified) return;
1373199989Srdivacky
1374226633Sdim    if (OverrideVersionPrinter != 0) {
1375226633Sdim      (*OverrideVersionPrinter)();
1376198090Srdivacky      exit(1);
1377193323Sed    }
1378226633Sdim    print();
1379226633Sdim
1380226633Sdim    // Iterate over any registered extra printers and call them to add further
1381226633Sdim    // information.
1382226633Sdim    if (ExtraVersionPrinters != 0) {
1383226633Sdim      outs() << '\n';
1384226633Sdim      for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1385226633Sdim                                             E = ExtraVersionPrinters->end();
1386226633Sdim           I != E; ++I)
1387226633Sdim        (*I)();
1388226633Sdim    }
1389226633Sdim
1390198090Srdivacky    exit(1);
1391193323Sed  }
1392193323Sed};
1393193323Sed} // End anonymous namespace
1394193323Sed
1395193323Sed
1396193323Sed// Define the --version option that prints out the LLVM version for the tool
1397193323Sedstatic VersionPrinter VersionPrinterInstance;
1398193323Sed
1399193323Sedstatic cl::opt<VersionPrinter, true, parser<bool> >
1400193323SedVersOp("version", cl::desc("Display the version of this program"),
1401193323Sed    cl::location(VersionPrinterInstance), cl::ValueDisallowed);
1402193323Sed
1403193323Sed// Utility function for printing the help message.
1404193323Sedvoid cl::PrintHelpMessage() {
1405193323Sed  // This looks weird, but it actually prints the help message. The
1406193323Sed  // NormalPrinter variable is a HelpPrinter and the help gets printed when
1407193323Sed  // its operator= is invoked. That's because the "normal" usages of the
1408193323Sed  // help printer is to be assigned true/false depending on whether the
1409204642Srdivacky  // -help option was given or not. Since we're circumventing that we have
1410204642Srdivacky  // to make it look like -help was given, so we assign true.
1411193323Sed  NormalPrinter = true;
1412193323Sed}
1413193323Sed
1414193323Sed/// Utility function for printing version number.
1415193323Sedvoid cl::PrintVersionMessage() {
1416193323Sed  VersionPrinterInstance.print();
1417193323Sed}
1418193323Sed
1419193323Sedvoid cl::SetVersionPrinter(void (*func)()) {
1420193323Sed  OverrideVersionPrinter = func;
1421193323Sed}
1422226633Sdim
1423226633Sdimvoid cl::AddExtraVersionPrinter(void (*func)()) {
1424226633Sdim  if (ExtraVersionPrinters == 0)
1425226633Sdim    ExtraVersionPrinters = new std::vector<void (*)()>;
1426226633Sdim
1427226633Sdim  ExtraVersionPrinters->push_back(func);
1428226633Sdim}
1429