blob: 7d9f3b7930a484229871f5fca87c42085d5234ce [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
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//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// 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//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Peter Collingbournee1863192014-10-16 22:47:52 +000020#include "llvm-c/Support.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000021#include "llvm/ADT/ArrayRef.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#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"
Brian Gaekee5e53222003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000037#include <map>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000038#include <system_error>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "commandline"
43
Chris Lattner3e5d60f2006-08-27 12:45:47 +000044//===----------------------------------------------------------------------===//
45// Template instantiations and anchors.
46//
Chris Bieneman5d232242015-01-13 19:14:20 +000047namespace llvm {
48namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000050TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000051TEMPLATE_INSTANTIATION(class basic_parser<int>);
52TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000053TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000054TEMPLATE_INSTANTIATION(class basic_parser<double>);
55TEMPLATE_INSTANTIATION(class basic_parser<float>);
56TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000057TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000058
59TEMPLATE_INSTANTIATION(class opt<unsigned>);
60TEMPLATE_INSTANTIATION(class opt<int>);
61TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000062TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000063TEMPLATE_INSTANTIATION(class opt<bool>);
Chris Bieneman5d232242015-01-13 19:14:20 +000064}
65} // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000066
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000067// Pin the vtables to this file.
68void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000069void OptionValue<boolOrDefault>::anchor() {}
70void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000071void Option::anchor() {}
72void basic_parser_impl::anchor() {}
73void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000074void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000075void parser<int>::anchor() {}
76void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000077void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000078void parser<double>::anchor() {}
79void parser<float>::anchor() {}
80void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000081void parser<char>::anchor() {}
Sean Silvadb794842014-08-15 23:39:01 +000082void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000083
84//===----------------------------------------------------------------------===//
85
Benjamin Kramer970eac42015-02-06 17:51:54 +000086namespace {
87
Chris Bienemand1d94302015-01-28 19:00:25 +000088class CommandLineParser {
89public:
90 // Globals for name and overview of program. Program name is not a string to
91 // avoid static ctor/dtor issues.
Chris Bienemanb6866422015-01-28 22:25:00 +000092 std::string ProgramName;
NAKAMURA Takumi81828182015-01-29 11:06:59 +000093 const char *ProgramOverview;
Reid Spencer9501b9b2004-09-01 04:41:28 +000094
Chris Bienemand1d94302015-01-28 19:00:25 +000095 // This collects additional help to be printed.
96 std::vector<const char *> MoreHelp;
97
98 SmallVector<Option *, 4> PositionalOpts;
99 SmallVector<Option *, 4> SinkOpts;
100 StringMap<Option *> OptionsMap;
101
NAKAMURA Takumi81828182015-01-29 11:06:59 +0000102 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
103
104 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
Chris Bienemand1d94302015-01-28 19:00:25 +0000105
106 void ParseCommandLineOptions(int argc, const char *const *argv,
107 const char *Overview);
108
109 void addLiteralOption(Option &Opt, const char *Name) {
110 if (!Opt.hasArgStr()) {
111 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
112 errs() << ProgramName << ": CommandLine Error: Option '" << Name
113 << "' registered more than once!\n";
114 report_fatal_error("inconsistency in registered CommandLine options");
115 }
116 }
117 }
118
119 void addOption(Option *O) {
120 bool HadErrors = false;
121 if (O->ArgStr[0]) {
122 // Add argument to the argument map!
123 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
124 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
125 << "' registered more than once!\n";
126 HadErrors = true;
127 }
128 }
129
130 // Remember information about positional options.
131 if (O->getFormattingFlag() == cl::Positional)
132 PositionalOpts.push_back(O);
133 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
134 SinkOpts.push_back(O);
135 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
136 if (ConsumeAfterOpt) {
137 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
138 HadErrors = true;
139 }
140 ConsumeAfterOpt = O;
141 }
142
143 // Fail hard if there were errors. These are strictly unrecoverable and
144 // indicate serious issues such as conflicting option names or an
145 // incorrectly
146 // linked LLVM distribution.
147 if (HadErrors)
148 report_fatal_error("inconsistency in registered CommandLine options");
149 }
150
151 void removeOption(Option *O) {
152 SmallVector<const char *, 16> OptionNames;
153 O->getExtraOptionNames(OptionNames);
154 if (O->ArgStr[0])
155 OptionNames.push_back(O->ArgStr);
156 for (auto Name : OptionNames)
157 OptionsMap.erase(StringRef(Name));
158
159 if (O->getFormattingFlag() == cl::Positional)
160 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
161 ++Opt) {
162 if (*Opt == O) {
163 PositionalOpts.erase(Opt);
164 break;
165 }
166 }
167 else if (O->getMiscFlags() & cl::Sink)
168 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
169 if (*Opt == O) {
170 SinkOpts.erase(Opt);
171 break;
172 }
173 }
174 else if (O == ConsumeAfterOpt)
175 ConsumeAfterOpt = nullptr;
176 }
177
178 bool hasOptions() {
179 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
180 nullptr != ConsumeAfterOpt);
181 }
182
Chris Bienemand77bbab2015-01-30 22:16:01 +0000183 void updateArgStr(Option *O, const char *NewName) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000184 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
185 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
186 << "' registered more than once!\n";
187 report_fatal_error("inconsistency in registered CommandLine options");
188 }
189 OptionsMap.erase(StringRef(O->ArgStr));
190 }
Chris Bienemand77bbab2015-01-30 22:16:01 +0000191
192 void printOptionValues();
Chris Bienemand1d94302015-01-28 19:00:25 +0000193};
194
Benjamin Kramer970eac42015-02-06 17:51:54 +0000195} // namespace
196
Chris Bienemand1d94302015-01-28 19:00:25 +0000197static ManagedStatic<CommandLineParser> GlobalParser;
198
199void cl::AddLiteralOption(Option &O, const char *Name) {
200 GlobalParser->addLiteralOption(O, Name);
201}
Chris Lattner37bcd992004-11-19 17:08:15 +0000202
Chris Bieneman5d232242015-01-13 19:14:20 +0000203extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000204 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000205}
206
Chris Lattner5247f602007-04-06 21:06:55 +0000207void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000208 GlobalParser->addOption(this);
209 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000210}
211
Chris Bienemand1d94302015-01-28 19:00:25 +0000212void Option::removeArgument() { GlobalParser->removeOption(this); }
213
214void Option::setArgStr(const char *S) {
215 if (FullyInitialized)
216 GlobalParser->updateArgStr(this, S);
217 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000218}
219
Andrew Trick0537a982013-05-06 21:56:23 +0000220// This collects the different option categories that have been registered.
Chris Bieneman5d232242015-01-13 19:14:20 +0000221typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
Andrew Trick0537a982013-05-06 21:56:23 +0000222static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
223
224// Initialise the general option category.
225OptionCategory llvm::cl::GeneralCategory("General options");
226
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000227void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000228 assert(std::count_if(RegisteredOptionCategories->begin(),
229 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000230 [this](const OptionCategory *Category) {
231 return getName() == Category->getName();
Chris Bieneman5d232242015-01-13 19:14:20 +0000232 }) == 0 &&
233 "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000234
Andrew Trick0537a982013-05-06 21:56:23 +0000235 RegisteredOptionCategories->insert(this);
236}
Chris Lattneraf039c52007-04-12 00:36:29 +0000237
Chris Lattner5df56c42002-07-22 02:07:59 +0000238//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000239// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000240//
241
Chris Lattner2031b022007-04-05 21:58:17 +0000242/// LookupOption - Lookup the option specified by the specified option on the
243/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000244/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000245static Option *LookupOption(StringRef &Arg, StringRef &Value,
Chris Bieneman5d232242015-01-13 19:14:20 +0000246 const StringMap<Option *> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000247 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000248 if (Arg.empty())
249 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000250
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000251 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000252
Chris Lattner0a40a972009-09-20 01:53:12 +0000253 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000254 if (EqualPos == StringRef::npos) {
255 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000256 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000257 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000258 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000259
Chris Lattnere7c1e212009-09-20 05:03:30 +0000260 // If the argument before the = is a valid option name, we match. If not,
261 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000262 StringMap<Option *>::const_iterator I =
263 OptionsMap.find(Arg.substr(0, EqualPos));
264 if (I == OptionsMap.end())
265 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000266
Chris Bieneman5d232242015-01-13 19:14:20 +0000267 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000268 Arg = Arg.substr(0, EqualPos);
269 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000270}
271
Daniel Dunbarf4132132011-01-18 01:59:24 +0000272/// LookupNearestOption - Lookup the closest match to the option specified by
273/// the specified option on the command line. If there is a value specified
274/// (after an equal sign) return that as well. This assumes that leading dashes
275/// have already been stripped.
276static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000277 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000278 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000279 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000280 if (Arg.empty())
281 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000282
283 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000284 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000285 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000286 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000287
288 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000289 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000290 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000291 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
292 ie = OptionsMap.end();
293 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000294 Option *O = it->second;
Chris Bieneman5d232242015-01-13 19:14:20 +0000295 SmallVector<const char *, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000296 O->getExtraOptionNames(OptionNames);
297 if (O->ArgStr[0])
298 OptionNames.push_back(O->ArgStr);
299
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000300 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
301 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000302 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
303 StringRef Name = OptionNames[i];
304 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000305 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000306 if (!Best || Distance < BestDistance) {
307 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000308 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000309 if (RHS.empty() || !PermitValue)
310 NearestString = OptionNames[i];
311 else
312 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000313 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000314 }
315 }
316
317 return Best;
318}
319
Alp Tokercb402912014-01-24 17:20:08 +0000320/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
321/// that does special handling of cl::CommaSeparated options.
322static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
323 StringRef ArgName, StringRef Value,
324 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000325 // Check to see if this option accepts a comma separated list of values. If
326 // it does, we have to split up the value into multiple values.
327 if (Handler->getMiscFlags() & CommaSeparated) {
328 StringRef Val(Value);
329 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000330
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000331 while (Pos != StringRef::npos) {
332 // Process the portion before the comma.
333 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
334 return true;
335 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000336 Val = Val.substr(Pos + 1);
337 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000338 // Check for another comma.
339 Pos = Val.find(',');
340 }
341
342 Value = Val;
343 }
344
345 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
346 return true;
347
348 return false;
349}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000350
Chris Lattner40fef802009-09-20 01:49:31 +0000351/// ProvideOption - For Value, this differentiates between an empty value ("")
352/// and a null value (StringRef()). The later is accepted for arguments that
353/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000354static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000355 StringRef Value, int argc,
356 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000357 // Is this a multi-argument option?
358 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
359
Chris Lattnere81c4092001-10-27 05:54:17 +0000360 // Enforce value requirements
361 switch (Handler->getValueExpectedFlag()) {
362 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000363 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000364 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000365 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000366 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000367 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000368 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000369 }
370 break;
371 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000372 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000373 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000374 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000375
Chris Lattner40fef802009-09-20 01:49:31 +0000376 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000377 return Handler->error("does not allow a value! '" + Twine(Value) +
378 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000379 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000380 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000381 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000382 }
383
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000384 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000385 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000386 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000387
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000388 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000389 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000390
Chris Lattner40fef802009-09-20 01:49:31 +0000391 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000392 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000393 return true;
394 --NumAdditionalVals;
395 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000396 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000397
398 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000399 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000400 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000401 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000402 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000403
Alp Tokercb402912014-01-24 17:20:08 +0000404 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000405 return true;
406 MultiArg = true;
407 --NumAdditionalVals;
408 }
409 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000410}
411
Chris Lattnerca2552d2009-09-20 00:07:40 +0000412static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000413 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000414 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000415}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000416
Chris Lattner5df56c42002-07-22 02:07:59 +0000417// Option predicates...
418static inline bool isGrouping(const Option *O) {
419 return O->getFormattingFlag() == cl::Grouping;
420}
421static inline bool isPrefixedOrGrouping(const Option *O) {
422 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
423}
424
425// getOptionPred - Check to see if there are any options that satisfy the
426// specified predicate with names that are the prefixes in Name. This is
427// checked by progressively stripping characters off of the name, checking to
428// see if there options that satisfy the predicate. If we find one, return it,
429// otherwise return null.
430//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000431static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000432 bool (*Pred)(const Option *),
433 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000434
Chris Bieneman5d232242015-01-13 19:14:20 +0000435 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000436
Chris Lattnere7c1e212009-09-20 05:03:30 +0000437 // Loop while we haven't found an option and Name still has at least two
438 // characters in it (so that the next iteration will not be the empty
439 // string.
440 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000441 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000442 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000443 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000444
Chris Lattner5247f602007-04-06 21:06:55 +0000445 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000446 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000447 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000448 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000449 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000450}
451
Chris Lattnere7c1e212009-09-20 05:03:30 +0000452/// HandlePrefixedOrGroupedOption - The specified argument string (which started
453/// with at least one '-') does not fully match an available option. Check to
454/// see if this is a prefix or grouped option. If so, split arg into output an
455/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000456static Option *
457HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
458 bool &ErrorParsing,
459 const StringMap<Option *> &OptionsMap) {
460 if (Arg.size() == 1)
461 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000462
463 // Do the lookup!
464 size_t Length = 0;
465 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000466 if (!PGOpt)
467 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000468
Chris Lattnere7c1e212009-09-20 05:03:30 +0000469 // If the option is a prefixed option, then the value is simply the
470 // rest of the name... so fall through to later processing, by
471 // setting up the argument name flags and value fields.
472 if (PGOpt->getFormattingFlag() == cl::Prefix) {
473 Value = Arg.substr(Length);
474 Arg = Arg.substr(0, Length);
475 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
476 return PGOpt;
477 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000478
Chris Lattnere7c1e212009-09-20 05:03:30 +0000479 // This must be a grouped option... handle them now. Grouping options can't
480 // have values.
481 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000482
Chris Lattnere7c1e212009-09-20 05:03:30 +0000483 do {
484 // Move current arg name out of Arg into OneArgName.
485 StringRef OneArgName = Arg.substr(0, Length);
486 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000487
Chris Lattnere7c1e212009-09-20 05:03:30 +0000488 // Because ValueRequired is an invalid flag for grouped arguments,
489 // we don't need to pass argc/argv in.
490 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
491 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000492 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000493 ErrorParsing |=
494 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000495
Chris Lattnere7c1e212009-09-20 05:03:30 +0000496 // Get the next grouping option.
497 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
498 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000499
Chris Lattnere7c1e212009-09-20 05:03:30 +0000500 // Return the last option with Arg cut down to just the last one.
501 return PGOpt;
502}
503
Chris Lattner5df56c42002-07-22 02:07:59 +0000504static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000505 return O->getNumOccurrencesFlag() == cl::Required ||
506 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000507}
508
509static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000510 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
511 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000512}
Chris Lattnere81c4092001-10-27 05:54:17 +0000513
Chris Bieneman5d232242015-01-13 19:14:20 +0000514static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000515
Chris Bieneman5d232242015-01-13 19:14:20 +0000516static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000517
Chris Bieneman5d232242015-01-13 19:14:20 +0000518static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
Reid Klecknera73c7782013-07-18 16:52:05 +0000519
520void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000521 SmallVectorImpl<const char *> &NewArgv,
522 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000523 SmallString<128> Token;
524 for (size_t I = 0, E = Src.size(); I != E; ++I) {
525 // Consume runs of whitespace.
526 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000527 while (I != E && isWhitespace(Src[I])) {
528 // Mark the end of lines in response files
529 if (MarkEOLs && Src[I] == '\n')
530 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000531 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000532 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000533 if (I == E)
534 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000535 }
536
537 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
538 // they are literal. This makes it much easier to read Windows file paths.
539 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000540 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000541 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000542 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000543 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000544
Reid Klecknera73c7782013-07-18 16:52:05 +0000545 // Consume a quoted string.
546 if (isQuote(Src[I])) {
547 char Quote = Src[I++];
548 while (I != E && Src[I] != Quote) {
549 // Backslashes are literal, unless they escape a special character.
550 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
551 ++I;
552 Token.push_back(Src[I]);
553 ++I;
554 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000555 if (I == E)
556 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000557 continue;
558 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000559
Reid Klecknera73c7782013-07-18 16:52:05 +0000560 // End the token if this is whitespace.
561 if (isWhitespace(Src[I])) {
562 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000563 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000564 Token.clear();
565 continue;
566 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000567
Reid Klecknera73c7782013-07-18 16:52:05 +0000568 // This is a normal character. Append it.
569 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000570 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000571
572 // Append the last token after hitting EOF with no whitespace.
573 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000574 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000575 // Mark the end of response files
576 if (MarkEOLs)
577 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000578}
579
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000580/// Backslashes are interpreted in a rather complicated way in the Windows-style
581/// command line, because backslashes are used both to separate path and to
582/// escape double quote. This method consumes runs of backslashes as well as the
583/// following double quote if it's escaped.
584///
585/// * If an even number of backslashes is followed by a double quote, one
586/// backslash is output for every pair of backslashes, and the last double
587/// quote remains unconsumed. The double quote will later be interpreted as
588/// the start or end of a quoted string in the main loop outside of this
589/// function.
590///
591/// * If an odd number of backslashes is followed by a double quote, one
592/// backslash is output for every pair of backslashes, and a double quote is
593/// output for the last pair of backslash-double quote. The double quote is
594/// consumed in this case.
595///
596/// * Otherwise, backslashes are interpreted literally.
597static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
598 size_t E = Src.size();
599 int BackslashCount = 0;
600 // Skip the backslashes.
601 do {
602 ++I;
603 ++BackslashCount;
604 } while (I != E && Src[I] == '\\');
605
606 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
607 if (FollowedByDoubleQuote) {
608 Token.append(BackslashCount / 2, '\\');
609 if (BackslashCount % 2 == 0)
610 return I - 1;
611 Token.push_back('"');
612 return I;
613 }
614 Token.append(BackslashCount, '\\');
615 return I - 1;
616}
617
Reid Klecknera73c7782013-07-18 16:52:05 +0000618void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000619 SmallVectorImpl<const char *> &NewArgv,
620 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000621 SmallString<128> Token;
622
623 // This is a small state machine to consume characters until it reaches the
624 // end of the source string.
625 enum { INIT, UNQUOTED, QUOTED } State = INIT;
626 for (size_t I = 0, E = Src.size(); I != E; ++I) {
627 // INIT state indicates that the current input index is at the start of
628 // the string or between tokens.
629 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000630 if (isWhitespace(Src[I])) {
631 // Mark the end of lines in response files
632 if (MarkEOLs && Src[I] == '\n')
633 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000634 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000635 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000636 if (Src[I] == '"') {
637 State = QUOTED;
638 continue;
639 }
640 if (Src[I] == '\\') {
641 I = parseBackslash(Src, I, Token);
642 State = UNQUOTED;
643 continue;
644 }
645 Token.push_back(Src[I]);
646 State = UNQUOTED;
647 continue;
648 }
649
650 // UNQUOTED state means that it's reading a token not quoted by double
651 // quotes.
652 if (State == UNQUOTED) {
653 // Whitespace means the end of the token.
654 if (isWhitespace(Src[I])) {
Sean Silvadb794842014-08-15 23:39:01 +0000655 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000656 Token.clear();
657 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000658 // Mark the end of lines in response files
659 if (MarkEOLs && Src[I] == '\n')
660 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000661 continue;
662 }
663 if (Src[I] == '"') {
664 State = QUOTED;
665 continue;
666 }
667 if (Src[I] == '\\') {
668 I = parseBackslash(Src, I, Token);
669 continue;
670 }
671 Token.push_back(Src[I]);
672 continue;
673 }
674
675 // QUOTED state means that it's reading a token quoted by double quotes.
676 if (State == QUOTED) {
677 if (Src[I] == '"') {
678 State = UNQUOTED;
679 continue;
680 }
681 if (Src[I] == '\\') {
682 I = parseBackslash(Src, I, Token);
683 continue;
684 }
685 Token.push_back(Src[I]);
686 }
687 }
688 // Append the last token after hitting EOF with no whitespace.
689 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000690 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000691 // Mark the end of response files
692 if (MarkEOLs)
693 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000694}
695
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000696// It is called byte order marker but the UTF-8 BOM is actually not affected
697// by the host system's endianness.
698static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
699 return (S.size() >= 3 &&
700 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
701}
702
Reid Klecknera73c7782013-07-18 16:52:05 +0000703static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
704 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000705 SmallVectorImpl<const char *> &NewArgv,
706 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000707 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
708 MemoryBuffer::getFile(FName);
709 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000710 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000711 MemoryBuffer &MemBuf = *MemBufOrErr.get();
712 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000713
714 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000715 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000716 std::string UTF8Buf;
717 if (hasUTF16ByteOrderMark(BufRef)) {
718 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
719 return false;
720 Str = StringRef(UTF8Buf);
721 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000722 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
723 // these bytes before parsing.
724 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
725 else if (hasUTF8ByteOrderMark(BufRef))
726 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000727
728 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000729 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000730
731 return true;
732}
733
734/// \brief Expand response files on a command line recursively using the given
735/// StringSaver and tokenization strategy.
736bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000737 SmallVectorImpl<const char *> &Argv,
738 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000739 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000740 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000741
742 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000743 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000744 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000745 // Check if it is an EOL marker
746 if (Arg == nullptr) {
747 ++I;
748 continue;
749 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000750 if (Arg[0] != '@') {
751 ++I;
752 continue;
753 }
754
755 // If we have too many response files, leave some unexpanded. This avoids
756 // crashing on self-referential response files.
757 if (RspFiles++ > 20)
758 return false;
759
760 // Replace this response file argument with the tokenization of its
761 // contents. Nested response files are expanded in subsequent iterations.
762 // FIXME: If a nested response file uses a relative path, is it relative to
763 // the cwd of the process or the response file?
764 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000765 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
766 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000767 // We couldn't read this file, so we leave it in the argument stream and
768 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000769 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000770 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000771 continue;
772 }
773 Argv.erase(Argv.begin() + I);
774 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
775 }
776 return AllExpanded;
777}
778
Sean Silvadb794842014-08-15 23:39:01 +0000779namespace {
Chris Bieneman5d232242015-01-13 19:14:20 +0000780class StrDupSaver : public StringSaver {
781 std::vector<char *> Dups;
782
783public:
784 ~StrDupSaver() {
785 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
786 ++I) {
787 char *Dup = *I;
788 free(Dup);
Sean Silvadb794842014-08-15 23:39:01 +0000789 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000790 }
791 const char *SaveString(const char *Str) override {
792 char *Dup = strdup(Str);
793 Dups.push_back(Dup);
794 return Dup;
795 }
796};
Sean Silvadb794842014-08-15 23:39:01 +0000797}
798
Brian Gaekeca782d92003-08-14 22:00:59 +0000799/// ParseEnvironmentOptions - An alternative entry point to the
800/// CommandLine library, which allows you to read the program's name
801/// from the caller (as PROGNAME) and its command-line arguments from
802/// an environment variable (whose name is given in ENVVAR).
803///
Chris Lattnera60f3552004-05-06 22:04:31 +0000804void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000805 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000806 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000807 assert(progName && "Program name not specified");
808 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000809
Brian Gaeke497216d2003-08-15 21:05:57 +0000810 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000811 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000812 if (!envValue)
813 return;
814
Brian Gaekeca782d92003-08-14 22:00:59 +0000815 // Get program's "name", which we wouldn't know without the caller
816 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000817 SmallVector<const char *, 20> newArgv;
Sean Silvadb794842014-08-15 23:39:01 +0000818 StrDupSaver Saver;
819 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000820
821 // Parse the value of the environment variable into a "command line"
822 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000823 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000824 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000825 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000826}
827
Chris Bieneman5d232242015-01-13 19:14:20 +0000828void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000829 const char *Overview) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000830 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
831}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000832
Chris Bienemand1d94302015-01-28 19:00:25 +0000833void CommandLineParser::ParseCommandLineOptions(int argc,
834 const char *const *argv,
835 const char *Overview) {
836 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000837
838 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000839 SmallVector<const char *, 20> newArgv;
840 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000841 newArgv.push_back(argv[i]);
Sean Silvadb794842014-08-15 23:39:01 +0000842 StrDupSaver Saver;
Reid Klecknera73c7782013-07-18 16:52:05 +0000843 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000844 argv = &newArgv[0];
845 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000846
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000847 // Copy the program name into ProgName, making sure not to overflow it.
Chris Bienemanb6866422015-01-28 22:25:00 +0000848 ProgramName = sys::path::filename(argv[0]);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000849
Chris Lattner36a57d32001-07-23 17:17:47 +0000850 ProgramOverview = Overview;
851 bool ErrorParsing = false;
852
Chris Lattner5df56c42002-07-22 02:07:59 +0000853 // Check out the positional arguments to collect information about them.
854 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000855
Chris Lattnerd380d842005-08-08 17:25:38 +0000856 // Determine whether or not there are an unlimited number of positionals
857 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000858
Chris Bienemand1d94302015-01-28 19:00:25 +0000859 if (ConsumeAfterOpt) {
860 assert(PositionalOpts.size() > 0 &&
861 "Cannot specify cl::ConsumeAfter without a positional argument!");
862 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000863 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000864
865 // Calculate how many positional values are _required_.
866 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +0000867 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000868 Option *Opt = PositionalOpts[i];
869 if (RequiresValue(Opt))
870 ++NumPositionalRequired;
871 else if (ConsumeAfterOpt) {
872 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000873 // unless there is only one positional argument...
Chris Bienemand1d94302015-01-28 19:00:25 +0000874 if (PositionalOpts.size() > 1)
Chris Bieneman5d232242015-01-13 19:14:20 +0000875 ErrorParsing |= Opt->error(
876 "error - this positional option will never be matched, "
877 "because it does not Require a value, and a "
878 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000879 } else if (UnboundedFound && !Opt->ArgStr[0]) {
880 // This option does not "require" a value... Make sure this option is
881 // not specified after an option that eats all extra arguments, or this
882 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000883 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000884 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000885 "another positional argument will match an "
886 "unbounded number of values, and this option"
887 " does not require a value!");
Chris Bienemand1d94302015-01-28 19:00:25 +0000888 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
889 << "' is all messed up!\n";
890 errs() << PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000891 }
892 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
893 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000894 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000895 }
896
Reid Spencer2027a6f2004-08-13 19:47:30 +0000897 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000898 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000899 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000900 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000901
Chris Lattner2da046f2003-07-30 17:34:02 +0000902 // If the program has named positional arguments, and the name has been run
903 // across, keep track of which positional argument was named. Otherwise put
904 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000905 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000906
Chris Lattner36a57d32001-07-23 17:17:47 +0000907 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000908 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000909 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000910 Option *Handler = nullptr;
911 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000912 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000913 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000914 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000915
916 // Check to see if this is a positional argument. This argument is
917 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000918 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000919 //
920 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
921 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000922 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000923 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000924 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000925 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000926
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000927 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000928 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000929
930 // All of the positional arguments have been fulfulled, give the rest to
931 // the consume after option... if it's specified...
932 //
Craig Topper8d399f82014-04-09 04:20:00 +0000933 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000934 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000935 PositionalVals.push_back(std::make_pair(argv[i], i));
936 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000937 }
938
939 // Delay processing positional arguments until the end...
940 continue;
941 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000942 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
943 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000944 DashDashFound = true; // This is the mythical "--"?
945 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000946 } else if (ActivePositionalArg &&
947 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
948 // If there is a positional argument eating options, check to see if this
949 // option is another positional argument. If so, treat it as an argument,
950 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000951 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000952 // Eat leading dashes.
953 while (!ArgName.empty() && ArgName[0] == '-')
954 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000955
Chris Bienemand1d94302015-01-28 19:00:25 +0000956 Handler = LookupOption(ArgName, Value, OptionsMap);
Chris Lattnera60f3552004-05-06 22:04:31 +0000957 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000958 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000959 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000960 }
961
Chris Bieneman5d232242015-01-13 19:14:20 +0000962 } else { // We start with a '-', must be an argument.
963 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000964 // Eat leading dashes.
965 while (!ArgName.empty() && ArgName[0] == '-')
966 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000967
Chris Bienemand1d94302015-01-28 19:00:25 +0000968 Handler = LookupOption(ArgName, Value, OptionsMap);
Chris Lattner36a57d32001-07-23 17:17:47 +0000969
Chris Lattnera60f3552004-05-06 22:04:31 +0000970 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000971 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +0000972 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
973 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000974
975 // Otherwise, look for the closest available option to report to the user
976 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000977 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000978 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +0000979 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000980 }
981
Craig Topper8d399f82014-04-09 04:20:00 +0000982 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000983 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000984 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
985 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000986
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000987 if (NearestHandler) {
988 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000989 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
990 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000991 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000992
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000993 ErrorParsing = true;
994 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000995 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
996 E = SinkOpts.end();
997 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000998 (*I)->addOccurrence(i, "", argv[i]);
999 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001000 continue;
1001 }
1002
Chris Lattner2da046f2003-07-30 17:34:02 +00001003 // If this is a named positional argument, just remember that it is the
1004 // active one...
1005 if (Handler->getFormattingFlag() == cl::Positional)
1006 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001007 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001008 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001009 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001010
Chris Lattner5df56c42002-07-22 02:07:59 +00001011 // Check and handle positional arguments now...
1012 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001013 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +00001014 << ": Not enough positional command line arguments specified!\n"
1015 << "Must specify at least " << NumPositionalRequired
1016 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001017
Chris Lattner5df56c42002-07-22 02:07:59 +00001018 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001019 } else if (!HasUnlimitedPositionals &&
1020 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001021 errs() << ProgramName << ": Too many positional arguments specified!\n"
1022 << "Can specify at most " << PositionalOpts.size()
1023 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001024 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001025
Craig Topper8d399f82014-04-09 04:20:00 +00001026 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001027 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001028 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1029 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001030 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001031 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001032 PositionalVals[ValNo].second);
1033 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001034 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001035 }
1036
1037 // If we _can_ give this option more arguments, do so now, as long as we
1038 // do not give it values that others need. 'Done' controls whether the
1039 // option even _WANTS_ any more.
1040 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001041 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001042 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001043 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001044 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001045 Done = true; // Optional arguments want _at most_ one value
1046 // FALL THROUGH
1047 case cl::ZeroOrMore: // Zero or more will take all they can get...
1048 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001049 ProvidePositionalOption(PositionalOpts[i],
1050 PositionalVals[ValNo].first,
1051 PositionalVals[ValNo].second);
1052 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001053 break;
1054 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001055 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001056 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001057 }
1058 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001059 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001060 } else {
1061 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1062 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001063 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001064 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001065 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001066 PositionalVals[ValNo].first,
1067 PositionalVals[ValNo].second);
1068 ValNo++;
1069 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001070
1071 // Handle the case where there is just one positional option, and it's
1072 // optional. In this case, we want to give JUST THE FIRST option to the
1073 // positional option and keep the rest for the consume after. The above
1074 // loop would have assigned no values to positional options in this case.
1075 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001076 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1077 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001078 PositionalVals[ValNo].first,
1079 PositionalVals[ValNo].second);
1080 ValNo++;
1081 }
Misha Brukman10468d82005-04-21 22:55:34 +00001082
Chris Lattner5df56c42002-07-22 02:07:59 +00001083 // Handle over all of the rest of the arguments to the
1084 // cl::ConsumeAfter command line option...
1085 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001086 ErrorParsing |=
1087 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1088 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001089 }
1090
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001091 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001092 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001093 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001094 case Required:
1095 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001096 if (Opt.second->getNumOccurrences() == 0) {
1097 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001098 ErrorParsing = true;
1099 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001100 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001101 default:
1102 break;
1103 }
1104 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001105
Rafael Espindolacf14a382010-11-19 21:14:29 +00001106 // Now that we know if -debug is specified, we can use it.
1107 // Note that if ReadResponseFiles == true, this must be done before the
1108 // memory allocated for the expanded command line is free()d below.
1109 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001110 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1111 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001112
Chris Lattner5df56c42002-07-22 02:07:59 +00001113 // Free all of the memory allocated to the map. Command line options may only
1114 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001115 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001116
1117 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001118 if (ErrorParsing)
1119 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001120}
1121
1122//===----------------------------------------------------------------------===//
1123// Option Base class implementation
1124//
Chris Lattner36a57d32001-07-23 17:17:47 +00001125
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001126bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001127 if (!ArgName.data())
1128 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001129 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001130 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001131 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001132 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001133
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001134 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001135 return true;
1136}
1137
Chris Bieneman5d232242015-01-13 19:14:20 +00001138bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1139 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001140 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001141 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001142
Misha Brukman069e6b52003-07-10 16:49:51 +00001143 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001144 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001145 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001146 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001147 break;
1148 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001149 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001150 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001151 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001152 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001153 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001154 case ConsumeAfter:
1155 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001156 }
1157
Reid Spencer2027a6f2004-08-13 19:47:30 +00001158 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001159}
1160
Chris Lattner5df56c42002-07-22 02:07:59 +00001161// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1162// has been specified yet.
1163//
1164static const char *getValueStr(const Option &O, const char *DefaultMsg) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001165 if (O.ValueStr[0] == 0)
1166 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001167 return O.ValueStr;
1168}
1169
1170//===----------------------------------------------------------------------===//
1171// cl::alias class implementation
1172//
1173
Chris Lattner36a57d32001-07-23 17:17:47 +00001174// Return the width of the option tag for printing...
Chris Bieneman5d232242015-01-13 19:14:20 +00001175size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001176
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001177static void printHelpStr(StringRef HelpStr, size_t Indent,
1178 size_t FirstLineIndentedBy) {
1179 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1180 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1181 while (!Split.second.empty()) {
1182 Split = Split.second.split('\n');
1183 outs().indent(Indent) << Split.first << "\n";
1184 }
1185}
1186
Chris Lattner1b7a5152006-04-28 05:36:25 +00001187// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001188void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001189 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001190 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001191}
1192
Chris Lattner36a57d32001-07-23 17:17:47 +00001193//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001194// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001195//
1196
Chris Lattnerb4101b12002-08-07 18:36:37 +00001197// basic_parser implementation
1198//
1199
1200// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001201size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1202 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001203 if (const char *ValName = getValueName())
Chris Bieneman5d232242015-01-13 19:14:20 +00001204 Len += std::strlen(getValueStr(O, ValName)) + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001205
1206 return Len + 6;
1207}
1208
Misha Brukman10468d82005-04-21 22:55:34 +00001209// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001210// to-be-maintained width is specified.
1211//
1212void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001213 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001214 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001215
1216 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001217 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001218
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001219 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001220}
1221
Andrew Trick12004012011-04-05 18:54:36 +00001222void basic_parser_impl::printOptionName(const Option &O,
1223 size_t GlobalWidth) const {
1224 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001225 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001226}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001227
Chris Lattner5df56c42002-07-22 02:07:59 +00001228// parser<bool> implementation
1229//
Chris Bieneman5d232242015-01-13 19:14:20 +00001230bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1231 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001232 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001233 Arg == "1") {
1234 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001235 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001236 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001237
Chris Lattneraecd74d2009-09-19 18:55:05 +00001238 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1239 Value = false;
1240 return false;
1241 }
1242 return O.error("'" + Arg +
1243 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001244}
1245
Dale Johannesen82810c82007-05-22 17:14:46 +00001246// parser<boolOrDefault> implementation
1247//
Chris Bieneman5d232242015-01-13 19:14:20 +00001248bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1249 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001250 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1251 Arg == "1") {
1252 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001253 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001254 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001255 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1256 Value = BOU_FALSE;
1257 return false;
1258 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001259
Chris Lattneraecd74d2009-09-19 18:55:05 +00001260 return O.error("'" + Arg +
1261 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001262}
1263
Chris Lattner5df56c42002-07-22 02:07:59 +00001264// parser<int> implementation
1265//
Chris Bieneman5d232242015-01-13 19:14:20 +00001266bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1267 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001268 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001269 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001270 return false;
1271}
1272
Chris Lattner719c7152003-06-28 15:47:20 +00001273// parser<unsigned> implementation
1274//
Chris Bieneman5d232242015-01-13 19:14:20 +00001275bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1276 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001277
1278 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001279 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001280 return false;
1281}
1282
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001283// parser<unsigned long long> implementation
1284//
1285bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001286 StringRef Arg,
1287 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001288
1289 if (Arg.getAsInteger(0, Value))
1290 return O.error("'" + Arg + "' value invalid for uint argument!");
1291 return false;
1292}
1293
Chris Lattnerb4101b12002-08-07 18:36:37 +00001294// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001295//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001296static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001297 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1298 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001299 char *End;
1300 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001301 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001302 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001303 return false;
1304}
1305
Chris Bieneman5d232242015-01-13 19:14:20 +00001306bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1307 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001308 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001309}
1310
Chris Bieneman5d232242015-01-13 19:14:20 +00001311bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1312 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001313 double dVal;
1314 if (parseDouble(O, Arg, dVal))
1315 return true;
1316 Val = (float)dVal;
1317 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001318}
1319
Chris Lattner5df56c42002-07-22 02:07:59 +00001320// generic_parser_base implementation
1321//
1322
Chris Lattner494c0b02002-07-23 17:15:12 +00001323// findOption - Return the option number corresponding to the specified
1324// argument string. If the option is not found, getNumOptions() is returned.
1325//
1326unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001327 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001328
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001329 for (unsigned i = 0; i != e; ++i) {
1330 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001331 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001332 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001333 return e;
1334}
1335
Chris Lattner5df56c42002-07-22 02:07:59 +00001336// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001337size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001338 if (O.hasArgStr()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001339 size_t Size = std::strlen(O.ArgStr) + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001340 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001341 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001342 return Size;
1343 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001344 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001345 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001346 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001347 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001348 }
1349}
1350
Misha Brukman10468d82005-04-21 22:55:34 +00001351// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001352// to-be-maintained width is specified.
1353//
1354void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001355 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001356 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001357 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001358 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001359
Chris Lattner5df56c42002-07-22 02:07:59 +00001360 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001361 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001362 outs() << " =" << getOption(i);
1363 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001364 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001365 } else {
1366 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001367 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001368 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001369 const char *Option = getOption(i);
1370 outs() << " -" << Option;
1371 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001372 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001373 }
1374}
1375
Andrew Trick12004012011-04-05 18:54:36 +00001376static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1377
1378// printGenericOptionDiff - Print the value of this option and it's default.
1379//
1380// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001381void generic_parser_base::printGenericOptionDiff(
1382 const Option &O, const GenericOptionValue &Value,
1383 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001384 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001385 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001386
1387 unsigned NumOpts = getNumOptions();
1388 for (unsigned i = 0; i != NumOpts; ++i) {
1389 if (Value.compare(getOptionValue(i)))
1390 continue;
1391
1392 outs() << "= " << getOption(i);
1393 size_t L = std::strlen(getOption(i));
1394 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1395 outs().indent(NumSpaces) << " (default: ";
1396 for (unsigned j = 0; j != NumOpts; ++j) {
1397 if (Default.compare(getOptionValue(j)))
1398 continue;
1399 outs() << getOption(j);
1400 break;
1401 }
1402 outs() << ")\n";
1403 return;
1404 }
1405 outs() << "= *unknown option value*\n";
1406}
1407
1408// printOptionDiff - Specializations for printing basic value types.
1409//
Chris Bieneman5d232242015-01-13 19:14:20 +00001410#define PRINT_OPT_DIFF(T) \
1411 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1412 size_t GlobalWidth) const { \
1413 printOptionName(O, GlobalWidth); \
1414 std::string Str; \
1415 { \
1416 raw_string_ostream SS(Str); \
1417 SS << V; \
1418 } \
1419 outs() << "= " << Str; \
1420 size_t NumSpaces = \
1421 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1422 outs().indent(NumSpaces) << " (default: "; \
1423 if (D.hasValue()) \
1424 outs() << D.getValue(); \
1425 else \
1426 outs() << "*no default*"; \
1427 outs() << ")\n"; \
1428 }
Andrew Trick12004012011-04-05 18:54:36 +00001429
Frits van Bommel87e33672011-04-06 12:29:56 +00001430PRINT_OPT_DIFF(bool)
1431PRINT_OPT_DIFF(boolOrDefault)
1432PRINT_OPT_DIFF(int)
1433PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001434PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001435PRINT_OPT_DIFF(double)
1436PRINT_OPT_DIFF(float)
1437PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001438
Chris Bieneman5d232242015-01-13 19:14:20 +00001439void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1440 OptionValue<std::string> D,
1441 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001442 printOptionName(O, GlobalWidth);
1443 outs() << "= " << V;
1444 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1445 outs().indent(NumSpaces) << " (default: ";
1446 if (D.hasValue())
1447 outs() << D.getValue();
1448 else
1449 outs() << "*no default*";
1450 outs() << ")\n";
1451}
1452
1453// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001454void basic_parser_impl::printOptionNoValue(const Option &O,
1455 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001456 printOptionName(O, GlobalWidth);
1457 outs() << "= *cannot print option value*\n";
1458}
Chris Lattner36a57d32001-07-23 17:17:47 +00001459
1460//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001461// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001462//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001463
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001464static int OptNameCompare(const void *LHS, const void *RHS) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001465 typedef std::pair<const char *, Option *> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001466
Chris Bieneman5d232242015-01-13 19:14:20 +00001467 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001468}
1469
Andrew Trick12004012011-04-05 18:54:36 +00001470// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001471static void sortOpts(StringMap<Option *> &OptMap,
1472 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1473 bool ShowHidden) {
1474 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001475
Chris Bieneman5d232242015-01-13 19:14:20 +00001476 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001477 I != E; ++I) {
1478 // Ignore really-hidden options.
1479 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1480 continue;
1481
1482 // Unless showhidden is set, ignore hidden flags.
1483 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1484 continue;
1485
1486 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001487 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001488 continue;
1489
Chris Bieneman5d232242015-01-13 19:14:20 +00001490 Opts.push_back(
1491 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001492 }
1493
1494 // Sort the options list alphabetically.
1495 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1496}
1497
Chris Lattner36a57d32001-07-23 17:17:47 +00001498namespace {
1499
Chris Lattner5df56c42002-07-22 02:07:59 +00001500class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001501protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001502 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001503 typedef SmallVector<std::pair<const char *, Option *>, 128>
1504 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001505 // Print the options. Opts is assumed to be alphabetically sorted.
1506 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1507 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1508 Opts[i].second->printOptionInfo(MaxArgLen);
1509 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001510
Chris Lattner5df56c42002-07-22 02:07:59 +00001511public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001512 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001513 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001514
Andrew Trick0537a982013-05-06 21:56:23 +00001515 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001516 void operator=(bool Value) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001517 if (Value == false)
1518 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001519
Andrew Trick0537a982013-05-06 21:56:23 +00001520 StrOptionPairVector Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001521 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001522
Chris Bienemand1d94302015-01-28 19:00:25 +00001523 if (GlobalParser->ProgramOverview)
1524 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001525
Chris Bienemand1d94302015-01-28 19:00:25 +00001526 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001527
Chris Bienemand1d94302015-01-28 19:00:25 +00001528 for (auto Opt : GlobalParser->PositionalOpts) {
1529 if (Opt->ArgStr[0])
1530 outs() << " --" << Opt->ArgStr;
1531 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001532 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001533
1534 // Print the consume after option info if it exists...
Chris Bienemand1d94302015-01-28 19:00:25 +00001535 if (GlobalParser->ConsumeAfterOpt)
1536 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001537
Chris Lattner471ba482009-08-23 08:43:55 +00001538 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001539
1540 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001541 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001542 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001543 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001544
Chris Lattner471ba482009-08-23 08:43:55 +00001545 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001546 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001547
Chris Lattner37bcd992004-11-19 17:08:15 +00001548 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001549 for (auto I : GlobalParser->MoreHelp)
1550 outs() << I;
1551 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001552
Reid Spencer5e554702004-11-16 06:11:52 +00001553 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001554 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001555 }
1556};
Andrew Trick0537a982013-05-06 21:56:23 +00001557
1558class CategorizedHelpPrinter : public HelpPrinter {
1559public:
1560 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1561
1562 // Helper function for printOptions().
1563 // It shall return true if A's name should be lexographically
1564 // ordered before B's name. It returns false otherwise.
1565 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001566 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001567 }
1568
1569 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001570 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001571
1572protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001573 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001574 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001575 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001576
Alp Tokercb402912014-01-24 17:20:08 +00001577 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001578 // sorting.
1579 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1580 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001581 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001582 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001583 }
Andrew Trick0537a982013-05-06 21:56:23 +00001584
1585 // Sort the different option categories alphabetically.
1586 assert(SortedCategories.size() > 0 && "No option categories registered!");
1587 std::sort(SortedCategories.begin(), SortedCategories.end(),
1588 OptionCategoryCompare);
1589
1590 // Create map to empty vectors.
1591 for (std::vector<OptionCategory *>::const_iterator
1592 I = SortedCategories.begin(),
1593 E = SortedCategories.end();
1594 I != E; ++I)
1595 CategorizedOptions[*I] = std::vector<Option *>();
1596
1597 // Walk through pre-sorted options and assign into categories.
1598 // Because the options are already alphabetically sorted the
1599 // options within categories will also be alphabetically sorted.
1600 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1601 Option *Opt = Opts[I].second;
1602 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1603 "Option has an unregistered category");
1604 CategorizedOptions[Opt->Category].push_back(Opt);
1605 }
1606
1607 // Now do printing.
1608 for (std::vector<OptionCategory *>::const_iterator
1609 Category = SortedCategories.begin(),
1610 E = SortedCategories.end();
1611 Category != E; ++Category) {
1612 // Hide empty categories for -help, but show for -help-hidden.
1613 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1614 if (!ShowHidden && IsEmptyCategory)
1615 continue;
1616
1617 // Print category information.
1618 outs() << "\n";
1619 outs() << (*Category)->getName() << ":\n";
1620
1621 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001622 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001623 outs() << (*Category)->getDescription() << "\n\n";
1624 else
1625 outs() << "\n";
1626
1627 // When using -help-hidden explicitly state if the category has no
1628 // options associated with it.
1629 if (IsEmptyCategory) {
1630 outs() << " This option category has no options.\n";
1631 continue;
1632 }
1633 // Loop over the options in the category and print.
1634 for (std::vector<Option *>::const_iterator
1635 Opt = CategorizedOptions[*Category].begin(),
1636 E = CategorizedOptions[*Category].end();
1637 Opt != E; ++Opt)
1638 (*Opt)->printOptionInfo(MaxArgLen);
1639 }
1640 }
1641};
1642
1643// This wraps the Uncategorizing and Categorizing printers and decides
1644// at run time which should be invoked.
1645class HelpPrinterWrapper {
1646private:
1647 HelpPrinter &UncategorizedPrinter;
1648 CategorizedHelpPrinter &CategorizedPrinter;
1649
1650public:
1651 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001652 CategorizedHelpPrinter &CategorizedPrinter)
1653 : UncategorizedPrinter(UncategorizedPrinter),
1654 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001655
1656 // Invoke the printer.
1657 void operator=(bool Value);
1658};
1659
Chris Lattneradb19d62006-10-12 22:09:17 +00001660} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001661
Andrew Trick0537a982013-05-06 21:56:23 +00001662// Declare the four HelpPrinter instances that are used to print out help, or
1663// help-hidden as an uncategorized list or in categories.
1664static HelpPrinter UncategorizedNormalPrinter(false);
1665static HelpPrinter UncategorizedHiddenPrinter(true);
1666static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1667static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1668
Andrew Trick0537a982013-05-06 21:56:23 +00001669// Declare HelpPrinter wrappers that will decide whether or not to invoke
1670// a categorizing help printer
1671static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1672 CategorizedNormalPrinter);
1673static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1674 CategorizedHiddenPrinter);
1675
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001676// Define a category for generic options that all tools should have.
1677static cl::OptionCategory GenericCategory("Generic Options");
1678
Andrew Trick0537a982013-05-06 21:56:23 +00001679// Define uncategorized help printers.
1680// -help-list is hidden by default because if Option categories are being used
1681// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001682static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1683 "help-list",
1684 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001685 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1686 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001687
Chris Bieneman5d232242015-01-13 19:14:20 +00001688static cl::opt<HelpPrinter, true, parser<bool>>
1689 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1690 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001691 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001692
1693// Define uncategorized/categorized help printers. These printers change their
1694// behaviour at runtime depending on whether one or more Option categories have
1695// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001696static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1697 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001698 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1699 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001700
Chris Bieneman5d232242015-01-13 19:14:20 +00001701static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1702 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001703 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1704 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001705
Chris Bieneman5d232242015-01-13 19:14:20 +00001706static cl::opt<bool> PrintOptions(
1707 "print-options",
1708 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001709 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001710
Chris Bieneman5d232242015-01-13 19:14:20 +00001711static cl::opt<bool> PrintAllOptions(
1712 "print-all-options",
1713 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001714 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001715
Andrew Trick0537a982013-05-06 21:56:23 +00001716void HelpPrinterWrapper::operator=(bool Value) {
1717 if (Value == false)
1718 return;
1719
1720 // Decide which printer to invoke. If more than one option category is
1721 // registered then it is useful to show the categorized help instead of
1722 // uncategorized help.
1723 if (RegisteredOptionCategories->size() > 1) {
1724 // unhide -help-list option so user can have uncategorized output if they
1725 // want it.
1726 HLOp.setHiddenFlag(NotHidden);
1727
1728 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001729 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001730 UncategorizedPrinter = true; // Invoke uncategorized printer
1731}
1732
Andrew Trick12004012011-04-05 18:54:36 +00001733// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00001734void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1735
1736void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001737 if (!PrintOptions && !PrintAllOptions)
1738 return;
Andrew Trick12004012011-04-05 18:54:36 +00001739
Chris Bieneman5d232242015-01-13 19:14:20 +00001740 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Chris Bienemand77bbab2015-01-30 22:16:01 +00001741 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001742
1743 // Compute the maximum argument length...
1744 size_t MaxArgLen = 0;
1745 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1746 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1747
1748 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1749 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1750}
1751
Craig Topperc10719f2014-04-07 04:17:22 +00001752static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001753
Chris Bieneman5d232242015-01-13 19:14:20 +00001754static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001755
Chris Lattneradb19d62006-10-12 22:09:17 +00001756namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001757class VersionPrinter {
1758public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001759 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001760 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001761 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001762 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001763#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001764 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001765#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001766 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001767#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001768 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001769#else
Chris Lattner131dca92009-09-20 06:18:38 +00001770 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001771#endif
1772#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001773 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001774#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001775 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001776 if (CPU == "generic")
1777 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001778 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001779#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001780 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001781#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001782 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001783 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001784 }
1785 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001786 if (!OptionWasSpecified)
1787 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001788
Craig Topperc10719f2014-04-07 04:17:22 +00001789 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001790 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001791 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001792 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001793 print();
1794
1795 // Iterate over any registered extra printers and call them to add further
1796 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001797 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001798 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001799 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1800 E = ExtraVersionPrinters->end();
1801 I != E; ++I)
1802 (*I)();
1803 }
1804
Justin Bogner02b95842014-02-28 19:08:01 +00001805 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001806 }
1807};
Chris Lattneradb19d62006-10-12 22:09:17 +00001808} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001809
Reid Spencerff6cc122004-08-04 00:36:06 +00001810// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001811static VersionPrinter VersionPrinterInstance;
1812
Chris Bieneman5d232242015-01-13 19:14:20 +00001813static cl::opt<VersionPrinter, true, parser<bool>>
1814 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001815 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1816 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001817
Reid Spencer5e554702004-11-16 06:11:52 +00001818// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001819void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1820 // This looks weird, but it actually prints the help message. The Printers are
1821 // types of HelpPrinter and the help gets printed when its operator= is
1822 // invoked. That's because the "normal" usages of the help printer is to be
1823 // assigned true/false depending on whether -help or -help-hidden was given or
1824 // not. Since we're circumventing that we have to make it look like -help or
1825 // -help-hidden were given, so we assign true.
1826
1827 if (!Hidden && !Categorized)
1828 UncategorizedNormalPrinter = true;
1829 else if (!Hidden && Categorized)
1830 CategorizedNormalPrinter = true;
1831 else if (Hidden && !Categorized)
1832 UncategorizedHiddenPrinter = true;
1833 else
1834 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001835}
Reid Spencerb3171672006-06-05 16:22:56 +00001836
Devang Patel9eb2caae2007-02-01 01:43:37 +00001837/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001838void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001839
Chris Bieneman5d232242015-01-13 19:14:20 +00001840void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001841
1842void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001843 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001844 ExtraVersionPrinters = new std::vector<void (*)()>;
1845
1846 ExtraVersionPrinters->push_back(func);
1847}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001848
Chris Bienemand1d94302015-01-28 19:00:25 +00001849StringMap<Option *> &cl::getRegisteredOptions() {
1850 return GlobalParser->OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00001851}
Peter Collingbournee1863192014-10-16 22:47:52 +00001852
Chris Bieneman9e13af72015-01-21 22:45:52 +00001853void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001854 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001855 if (I.second->Category != &Category &&
1856 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001857 I.second->setHiddenFlag(cl::ReallyHidden);
1858 }
1859}
1860
Chris Bieneman68169362015-01-27 22:21:06 +00001861void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
Chris Bieneman01043252015-01-26 21:57:29 +00001862 auto CategoriesBegin = Categories.begin();
1863 auto CategoriesEnd = Categories.end();
Chris Bienemand1d94302015-01-28 19:00:25 +00001864 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00001865 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1866 CategoriesEnd &&
1867 I.second->Category != &GenericCategory)
1868 I.second->setHiddenFlag(cl::ReallyHidden);
1869 }
1870}
1871
Peter Collingbournee1863192014-10-16 22:47:52 +00001872void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1873 const char *Overview) {
1874 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1875}