blob: bdebe97d872a27dc571fdd3f1b332872cfcea92c [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
Chris Bienemand1d94302015-01-28 19:00:25 +000086class CommandLineParser {
87public:
88 // Globals for name and overview of program. Program name is not a string to
89 // avoid static ctor/dtor issues.
90 char ProgramName[80] = "<premain>";
91 const char *ProgramOverview = nullptr;
Reid Spencer9501b9b2004-09-01 04:41:28 +000092
Chris Bienemand1d94302015-01-28 19:00:25 +000093 // This collects additional help to be printed.
94 std::vector<const char *> MoreHelp;
95
96 SmallVector<Option *, 4> PositionalOpts;
97 SmallVector<Option *, 4> SinkOpts;
98 StringMap<Option *> OptionsMap;
99
100 Option *ConsumeAfterOpt = nullptr; // The ConsumeAfter option if it exists.
101
102 void ParseCommandLineOptions(int argc, const char *const *argv,
103 const char *Overview);
104
105 void addLiteralOption(Option &Opt, const char *Name) {
106 if (!Opt.hasArgStr()) {
107 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
108 errs() << ProgramName << ": CommandLine Error: Option '" << Name
109 << "' registered more than once!\n";
110 report_fatal_error("inconsistency in registered CommandLine options");
111 }
112 }
113 }
114
115 void addOption(Option *O) {
116 bool HadErrors = false;
117 if (O->ArgStr[0]) {
118 // Add argument to the argument map!
119 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
120 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
121 << "' registered more than once!\n";
122 HadErrors = true;
123 }
124 }
125
126 // Remember information about positional options.
127 if (O->getFormattingFlag() == cl::Positional)
128 PositionalOpts.push_back(O);
129 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
130 SinkOpts.push_back(O);
131 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
132 if (ConsumeAfterOpt) {
133 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
134 HadErrors = true;
135 }
136 ConsumeAfterOpt = O;
137 }
138
139 // Fail hard if there were errors. These are strictly unrecoverable and
140 // indicate serious issues such as conflicting option names or an
141 // incorrectly
142 // linked LLVM distribution.
143 if (HadErrors)
144 report_fatal_error("inconsistency in registered CommandLine options");
145 }
146
147 void removeOption(Option *O) {
148 SmallVector<const char *, 16> OptionNames;
149 O->getExtraOptionNames(OptionNames);
150 if (O->ArgStr[0])
151 OptionNames.push_back(O->ArgStr);
152 for (auto Name : OptionNames)
153 OptionsMap.erase(StringRef(Name));
154
155 if (O->getFormattingFlag() == cl::Positional)
156 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
157 ++Opt) {
158 if (*Opt == O) {
159 PositionalOpts.erase(Opt);
160 break;
161 }
162 }
163 else if (O->getMiscFlags() & cl::Sink)
164 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
165 if (*Opt == O) {
166 SinkOpts.erase(Opt);
167 break;
168 }
169 }
170 else if (O == ConsumeAfterOpt)
171 ConsumeAfterOpt = nullptr;
172 }
173
174 bool hasOptions() {
175 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
176 nullptr != ConsumeAfterOpt);
177 }
178
179 void updateArgStr(Option *O, const char* NewName) {
180 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
181 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
182 << "' registered more than once!\n";
183 report_fatal_error("inconsistency in registered CommandLine options");
184 }
185 OptionsMap.erase(StringRef(O->ArgStr));
186 }
187};
188
189static ManagedStatic<CommandLineParser> GlobalParser;
190
191void cl::AddLiteralOption(Option &O, const char *Name) {
192 GlobalParser->addLiteralOption(O, Name);
193}
Chris Lattner37bcd992004-11-19 17:08:15 +0000194
Chris Bieneman5d232242015-01-13 19:14:20 +0000195extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000196 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000197}
198
Chris Lattner5247f602007-04-06 21:06:55 +0000199void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000200 GlobalParser->addOption(this);
201 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000202}
203
Chris Bienemand1d94302015-01-28 19:00:25 +0000204void Option::removeArgument() { GlobalParser->removeOption(this); }
205
206void Option::setArgStr(const char *S) {
207 if (FullyInitialized)
208 GlobalParser->updateArgStr(this, S);
209 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000210}
211
Andrew Trick0537a982013-05-06 21:56:23 +0000212// This collects the different option categories that have been registered.
Chris Bieneman5d232242015-01-13 19:14:20 +0000213typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
Andrew Trick0537a982013-05-06 21:56:23 +0000214static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
215
216// Initialise the general option category.
217OptionCategory llvm::cl::GeneralCategory("General options");
218
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000219void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000220 assert(std::count_if(RegisteredOptionCategories->begin(),
221 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000222 [this](const OptionCategory *Category) {
223 return getName() == Category->getName();
Chris Bieneman5d232242015-01-13 19:14:20 +0000224 }) == 0 &&
225 "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000226
Andrew Trick0537a982013-05-06 21:56:23 +0000227 RegisteredOptionCategories->insert(this);
228}
Chris Lattneraf039c52007-04-12 00:36:29 +0000229
Chris Lattner5df56c42002-07-22 02:07:59 +0000230//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000231// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000232//
233
Chris Lattner2031b022007-04-05 21:58:17 +0000234/// LookupOption - Lookup the option specified by the specified option on the
235/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000236/// that as well. This assumes that leading dashes have already been stripped.
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000237static Option *LookupOption(StringRef &Arg, StringRef &Value,
Chris Bieneman5d232242015-01-13 19:14:20 +0000238 const StringMap<Option *> &OptionsMap) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000239 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000240 if (Arg.empty())
241 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000242
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000243 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000244
Chris Lattner0a40a972009-09-20 01:53:12 +0000245 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000246 if (EqualPos == StringRef::npos) {
247 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000248 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000249 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000250 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000251
Chris Lattnere7c1e212009-09-20 05:03:30 +0000252 // If the argument before the = is a valid option name, we match. If not,
253 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000254 StringMap<Option *>::const_iterator I =
255 OptionsMap.find(Arg.substr(0, EqualPos));
256 if (I == OptionsMap.end())
257 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000258
Chris Bieneman5d232242015-01-13 19:14:20 +0000259 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000260 Arg = Arg.substr(0, EqualPos);
261 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000262}
263
Daniel Dunbarf4132132011-01-18 01:59:24 +0000264/// LookupNearestOption - Lookup the closest match to the option specified by
265/// the specified option on the command line. If there is a value specified
266/// (after an equal sign) return that as well. This assumes that leading dashes
267/// have already been stripped.
268static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000269 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000270 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000271 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000272 if (Arg.empty())
273 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000274
275 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000276 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000277 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000278 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000279
280 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000281 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000282 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000283 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
284 ie = OptionsMap.end();
285 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000286 Option *O = it->second;
Chris Bieneman5d232242015-01-13 19:14:20 +0000287 SmallVector<const char *, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000288 O->getExtraOptionNames(OptionNames);
289 if (O->ArgStr[0])
290 OptionNames.push_back(O->ArgStr);
291
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000292 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
293 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000294 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
295 StringRef Name = OptionNames[i];
296 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000297 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000298 if (!Best || Distance < BestDistance) {
299 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000300 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000301 if (RHS.empty() || !PermitValue)
302 NearestString = OptionNames[i];
303 else
304 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000305 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000306 }
307 }
308
309 return Best;
310}
311
Alp Tokercb402912014-01-24 17:20:08 +0000312/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
313/// that does special handling of cl::CommaSeparated options.
314static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
315 StringRef ArgName, StringRef Value,
316 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000317 // Check to see if this option accepts a comma separated list of values. If
318 // it does, we have to split up the value into multiple values.
319 if (Handler->getMiscFlags() & CommaSeparated) {
320 StringRef Val(Value);
321 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000322
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000323 while (Pos != StringRef::npos) {
324 // Process the portion before the comma.
325 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
326 return true;
327 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000328 Val = Val.substr(Pos + 1);
329 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000330 // Check for another comma.
331 Pos = Val.find(',');
332 }
333
334 Value = Val;
335 }
336
337 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
338 return true;
339
340 return false;
341}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000342
Chris Lattner40fef802009-09-20 01:49:31 +0000343/// ProvideOption - For Value, this differentiates between an empty value ("")
344/// and a null value (StringRef()). The later is accepted for arguments that
345/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000346static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000347 StringRef Value, int argc,
348 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000349 // Is this a multi-argument option?
350 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
351
Chris Lattnere81c4092001-10-27 05:54:17 +0000352 // Enforce value requirements
353 switch (Handler->getValueExpectedFlag()) {
354 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000355 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000356 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000357 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000358 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000359 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000360 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000361 }
362 break;
363 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000364 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000365 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000366 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000367
Chris Lattner40fef802009-09-20 01:49:31 +0000368 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000369 return Handler->error("does not allow a value! '" + Twine(Value) +
370 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000371 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000372 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000373 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000374 }
375
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000376 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000377 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000378 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000379
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000380 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000381 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000382
Chris Lattner40fef802009-09-20 01:49:31 +0000383 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000384 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000385 return true;
386 --NumAdditionalVals;
387 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000388 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000389
390 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000391 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000392 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000393 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000394 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000395
Alp Tokercb402912014-01-24 17:20:08 +0000396 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000397 return true;
398 MultiArg = true;
399 --NumAdditionalVals;
400 }
401 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000402}
403
Chris Lattnerca2552d2009-09-20 00:07:40 +0000404static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000405 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000406 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000407}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000408
Chris Lattner5df56c42002-07-22 02:07:59 +0000409// Option predicates...
410static inline bool isGrouping(const Option *O) {
411 return O->getFormattingFlag() == cl::Grouping;
412}
413static inline bool isPrefixedOrGrouping(const Option *O) {
414 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
415}
416
417// getOptionPred - Check to see if there are any options that satisfy the
418// specified predicate with names that are the prefixes in Name. This is
419// checked by progressively stripping characters off of the name, checking to
420// see if there options that satisfy the predicate. If we find one, return it,
421// otherwise return null.
422//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000423static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000424 bool (*Pred)(const Option *),
425 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000426
Chris Bieneman5d232242015-01-13 19:14:20 +0000427 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000428
Chris Lattnere7c1e212009-09-20 05:03:30 +0000429 // Loop while we haven't found an option and Name still has at least two
430 // characters in it (so that the next iteration will not be the empty
431 // string.
432 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000433 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000434 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000435 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000436
Chris Lattner5247f602007-04-06 21:06:55 +0000437 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000438 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000439 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000440 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000441 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000442}
443
Chris Lattnere7c1e212009-09-20 05:03:30 +0000444/// HandlePrefixedOrGroupedOption - The specified argument string (which started
445/// with at least one '-') does not fully match an available option. Check to
446/// see if this is a prefix or grouped option. If so, split arg into output an
447/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000448static Option *
449HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
450 bool &ErrorParsing,
451 const StringMap<Option *> &OptionsMap) {
452 if (Arg.size() == 1)
453 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000454
455 // Do the lookup!
456 size_t Length = 0;
457 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000458 if (!PGOpt)
459 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000460
Chris Lattnere7c1e212009-09-20 05:03:30 +0000461 // If the option is a prefixed option, then the value is simply the
462 // rest of the name... so fall through to later processing, by
463 // setting up the argument name flags and value fields.
464 if (PGOpt->getFormattingFlag() == cl::Prefix) {
465 Value = Arg.substr(Length);
466 Arg = Arg.substr(0, Length);
467 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
468 return PGOpt;
469 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000470
Chris Lattnere7c1e212009-09-20 05:03:30 +0000471 // This must be a grouped option... handle them now. Grouping options can't
472 // have values.
473 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000474
Chris Lattnere7c1e212009-09-20 05:03:30 +0000475 do {
476 // Move current arg name out of Arg into OneArgName.
477 StringRef OneArgName = Arg.substr(0, Length);
478 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000479
Chris Lattnere7c1e212009-09-20 05:03:30 +0000480 // Because ValueRequired is an invalid flag for grouped arguments,
481 // we don't need to pass argc/argv in.
482 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
483 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000484 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000485 ErrorParsing |=
486 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000487
Chris Lattnere7c1e212009-09-20 05:03:30 +0000488 // Get the next grouping option.
489 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
490 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000491
Chris Lattnere7c1e212009-09-20 05:03:30 +0000492 // Return the last option with Arg cut down to just the last one.
493 return PGOpt;
494}
495
Chris Lattner5df56c42002-07-22 02:07:59 +0000496static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000497 return O->getNumOccurrencesFlag() == cl::Required ||
498 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000499}
500
501static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000502 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
503 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000504}
Chris Lattnere81c4092001-10-27 05:54:17 +0000505
Chris Bieneman5d232242015-01-13 19:14:20 +0000506static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000507
Chris Bieneman5d232242015-01-13 19:14:20 +0000508static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000509
Chris Bieneman5d232242015-01-13 19:14:20 +0000510static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
Reid Klecknera73c7782013-07-18 16:52:05 +0000511
512void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000513 SmallVectorImpl<const char *> &NewArgv,
514 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000515 SmallString<128> Token;
516 for (size_t I = 0, E = Src.size(); I != E; ++I) {
517 // Consume runs of whitespace.
518 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000519 while (I != E && isWhitespace(Src[I])) {
520 // Mark the end of lines in response files
521 if (MarkEOLs && Src[I] == '\n')
522 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000523 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000524 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000525 if (I == E)
526 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000527 }
528
529 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
530 // they are literal. This makes it much easier to read Windows file paths.
531 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000532 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000533 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000534 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000535 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000536
Reid Klecknera73c7782013-07-18 16:52:05 +0000537 // Consume a quoted string.
538 if (isQuote(Src[I])) {
539 char Quote = Src[I++];
540 while (I != E && Src[I] != Quote) {
541 // Backslashes are literal, unless they escape a special character.
542 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
543 ++I;
544 Token.push_back(Src[I]);
545 ++I;
546 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000547 if (I == E)
548 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000549 continue;
550 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000551
Reid Klecknera73c7782013-07-18 16:52:05 +0000552 // End the token if this is whitespace.
553 if (isWhitespace(Src[I])) {
554 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000555 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000556 Token.clear();
557 continue;
558 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000559
Reid Klecknera73c7782013-07-18 16:52:05 +0000560 // This is a normal character. Append it.
561 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000562 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000563
564 // Append the last token after hitting EOF with no whitespace.
565 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000566 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000567 // Mark the end of response files
568 if (MarkEOLs)
569 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000570}
571
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000572/// Backslashes are interpreted in a rather complicated way in the Windows-style
573/// command line, because backslashes are used both to separate path and to
574/// escape double quote. This method consumes runs of backslashes as well as the
575/// following double quote if it's escaped.
576///
577/// * If an even number of backslashes is followed by a double quote, one
578/// backslash is output for every pair of backslashes, and the last double
579/// quote remains unconsumed. The double quote will later be interpreted as
580/// the start or end of a quoted string in the main loop outside of this
581/// function.
582///
583/// * If an odd number of backslashes is followed by a double quote, one
584/// backslash is output for every pair of backslashes, and a double quote is
585/// output for the last pair of backslash-double quote. The double quote is
586/// consumed in this case.
587///
588/// * Otherwise, backslashes are interpreted literally.
589static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
590 size_t E = Src.size();
591 int BackslashCount = 0;
592 // Skip the backslashes.
593 do {
594 ++I;
595 ++BackslashCount;
596 } while (I != E && Src[I] == '\\');
597
598 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
599 if (FollowedByDoubleQuote) {
600 Token.append(BackslashCount / 2, '\\');
601 if (BackslashCount % 2 == 0)
602 return I - 1;
603 Token.push_back('"');
604 return I;
605 }
606 Token.append(BackslashCount, '\\');
607 return I - 1;
608}
609
Reid Klecknera73c7782013-07-18 16:52:05 +0000610void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000611 SmallVectorImpl<const char *> &NewArgv,
612 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000613 SmallString<128> Token;
614
615 // This is a small state machine to consume characters until it reaches the
616 // end of the source string.
617 enum { INIT, UNQUOTED, QUOTED } State = INIT;
618 for (size_t I = 0, E = Src.size(); I != E; ++I) {
619 // INIT state indicates that the current input index is at the start of
620 // the string or between tokens.
621 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000622 if (isWhitespace(Src[I])) {
623 // Mark the end of lines in response files
624 if (MarkEOLs && Src[I] == '\n')
625 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000626 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000627 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000628 if (Src[I] == '"') {
629 State = QUOTED;
630 continue;
631 }
632 if (Src[I] == '\\') {
633 I = parseBackslash(Src, I, Token);
634 State = UNQUOTED;
635 continue;
636 }
637 Token.push_back(Src[I]);
638 State = UNQUOTED;
639 continue;
640 }
641
642 // UNQUOTED state means that it's reading a token not quoted by double
643 // quotes.
644 if (State == UNQUOTED) {
645 // Whitespace means the end of the token.
646 if (isWhitespace(Src[I])) {
Sean Silvadb794842014-08-15 23:39:01 +0000647 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000648 Token.clear();
649 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000650 // Mark the end of lines in response files
651 if (MarkEOLs && Src[I] == '\n')
652 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000653 continue;
654 }
655 if (Src[I] == '"') {
656 State = QUOTED;
657 continue;
658 }
659 if (Src[I] == '\\') {
660 I = parseBackslash(Src, I, Token);
661 continue;
662 }
663 Token.push_back(Src[I]);
664 continue;
665 }
666
667 // QUOTED state means that it's reading a token quoted by double quotes.
668 if (State == QUOTED) {
669 if (Src[I] == '"') {
670 State = UNQUOTED;
671 continue;
672 }
673 if (Src[I] == '\\') {
674 I = parseBackslash(Src, I, Token);
675 continue;
676 }
677 Token.push_back(Src[I]);
678 }
679 }
680 // Append the last token after hitting EOF with no whitespace.
681 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000682 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000683 // Mark the end of response files
684 if (MarkEOLs)
685 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000686}
687
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000688// It is called byte order marker but the UTF-8 BOM is actually not affected
689// by the host system's endianness.
690static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
691 return (S.size() >= 3 &&
692 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
693}
694
Reid Klecknera73c7782013-07-18 16:52:05 +0000695static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
696 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000697 SmallVectorImpl<const char *> &NewArgv,
698 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000699 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
700 MemoryBuffer::getFile(FName);
701 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000702 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000703 MemoryBuffer &MemBuf = *MemBufOrErr.get();
704 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000705
706 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000707 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000708 std::string UTF8Buf;
709 if (hasUTF16ByteOrderMark(BufRef)) {
710 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
711 return false;
712 Str = StringRef(UTF8Buf);
713 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000714 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
715 // these bytes before parsing.
716 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
717 else if (hasUTF8ByteOrderMark(BufRef))
718 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000719
720 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000721 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000722
723 return true;
724}
725
726/// \brief Expand response files on a command line recursively using the given
727/// StringSaver and tokenization strategy.
728bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000729 SmallVectorImpl<const char *> &Argv,
730 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000731 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000732 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000733
734 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000735 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000736 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000737 // Check if it is an EOL marker
738 if (Arg == nullptr) {
739 ++I;
740 continue;
741 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000742 if (Arg[0] != '@') {
743 ++I;
744 continue;
745 }
746
747 // If we have too many response files, leave some unexpanded. This avoids
748 // crashing on self-referential response files.
749 if (RspFiles++ > 20)
750 return false;
751
752 // Replace this response file argument with the tokenization of its
753 // contents. Nested response files are expanded in subsequent iterations.
754 // FIXME: If a nested response file uses a relative path, is it relative to
755 // the cwd of the process or the response file?
756 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000757 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
758 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000759 // We couldn't read this file, so we leave it in the argument stream and
760 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000761 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000762 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000763 continue;
764 }
765 Argv.erase(Argv.begin() + I);
766 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
767 }
768 return AllExpanded;
769}
770
Sean Silvadb794842014-08-15 23:39:01 +0000771namespace {
Chris Bieneman5d232242015-01-13 19:14:20 +0000772class StrDupSaver : public StringSaver {
773 std::vector<char *> Dups;
774
775public:
776 ~StrDupSaver() {
777 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
778 ++I) {
779 char *Dup = *I;
780 free(Dup);
Sean Silvadb794842014-08-15 23:39:01 +0000781 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000782 }
783 const char *SaveString(const char *Str) override {
784 char *Dup = strdup(Str);
785 Dups.push_back(Dup);
786 return Dup;
787 }
788};
Sean Silvadb794842014-08-15 23:39:01 +0000789}
790
Brian Gaekeca782d92003-08-14 22:00:59 +0000791/// ParseEnvironmentOptions - An alternative entry point to the
792/// CommandLine library, which allows you to read the program's name
793/// from the caller (as PROGNAME) and its command-line arguments from
794/// an environment variable (whose name is given in ENVVAR).
795///
Chris Lattnera60f3552004-05-06 22:04:31 +0000796void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000797 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000798 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000799 assert(progName && "Program name not specified");
800 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000801
Brian Gaeke497216d2003-08-15 21:05:57 +0000802 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000803 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000804 if (!envValue)
805 return;
806
Brian Gaekeca782d92003-08-14 22:00:59 +0000807 // Get program's "name", which we wouldn't know without the caller
808 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000809 SmallVector<const char *, 20> newArgv;
Sean Silvadb794842014-08-15 23:39:01 +0000810 StrDupSaver Saver;
811 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000812
813 // Parse the value of the environment variable into a "command line"
814 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000815 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000816 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000817 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000818}
819
Chris Bieneman5d232242015-01-13 19:14:20 +0000820void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000821 const char *Overview) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000822 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
823}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000824
Chris Bienemand1d94302015-01-28 19:00:25 +0000825void CommandLineParser::ParseCommandLineOptions(int argc,
826 const char *const *argv,
827 const char *Overview) {
828 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000829
830 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000831 SmallVector<const char *, 20> newArgv;
832 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000833 newArgv.push_back(argv[i]);
Sean Silvadb794842014-08-15 23:39:01 +0000834 StrDupSaver Saver;
Reid Klecknera73c7782013-07-18 16:52:05 +0000835 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000836 argv = &newArgv[0];
837 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000838
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000839 // Copy the program name into ProgName, making sure not to overflow it.
NAKAMURA Takumic2c66492014-04-23 14:51:23 +0000840 StringRef ProgName = sys::path::filename(argv[0]);
Benjamin Kramer29063ea2010-01-28 18:04:38 +0000841 size_t Len = std::min(ProgName.size(), size_t(79));
842 memcpy(ProgramName, ProgName.data(), Len);
843 ProgramName[Len] = '\0';
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000844
Chris Lattner36a57d32001-07-23 17:17:47 +0000845 ProgramOverview = Overview;
846 bool ErrorParsing = false;
847
Chris Lattner5df56c42002-07-22 02:07:59 +0000848 // Check out the positional arguments to collect information about them.
849 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000850
Chris Lattnerd380d842005-08-08 17:25:38 +0000851 // Determine whether or not there are an unlimited number of positionals
852 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000853
Chris Bienemand1d94302015-01-28 19:00:25 +0000854 if (ConsumeAfterOpt) {
855 assert(PositionalOpts.size() > 0 &&
856 "Cannot specify cl::ConsumeAfter without a positional argument!");
857 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000858 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000859
860 // Calculate how many positional values are _required_.
861 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +0000862 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000863 Option *Opt = PositionalOpts[i];
864 if (RequiresValue(Opt))
865 ++NumPositionalRequired;
866 else if (ConsumeAfterOpt) {
867 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000868 // unless there is only one positional argument...
Chris Bienemand1d94302015-01-28 19:00:25 +0000869 if (PositionalOpts.size() > 1)
Chris Bieneman5d232242015-01-13 19:14:20 +0000870 ErrorParsing |= Opt->error(
871 "error - this positional option will never be matched, "
872 "because it does not Require a value, and a "
873 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000874 } else if (UnboundedFound && !Opt->ArgStr[0]) {
875 // This option does not "require" a value... Make sure this option is
876 // not specified after an option that eats all extra arguments, or this
877 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000878 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000879 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000880 "another positional argument will match an "
881 "unbounded number of values, and this option"
882 " does not require a value!");
Chris Bienemand1d94302015-01-28 19:00:25 +0000883 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
884 << "' is all messed up!\n";
885 errs() << PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000886 }
887 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
888 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000889 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000890 }
891
Reid Spencer2027a6f2004-08-13 19:47:30 +0000892 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000893 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000894 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000895 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000896
Chris Lattner2da046f2003-07-30 17:34:02 +0000897 // If the program has named positional arguments, and the name has been run
898 // across, keep track of which positional argument was named. Otherwise put
899 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000900 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000901
Chris Lattner36a57d32001-07-23 17:17:47 +0000902 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000903 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000904 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000905 Option *Handler = nullptr;
906 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000907 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000908 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000909 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000910
911 // Check to see if this is a positional argument. This argument is
912 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000913 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000914 //
915 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
916 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000917 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000918 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000919 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000920 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000921
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000922 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000923 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000924
925 // All of the positional arguments have been fulfulled, give the rest to
926 // the consume after option... if it's specified...
927 //
Craig Topper8d399f82014-04-09 04:20:00 +0000928 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000929 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000930 PositionalVals.push_back(std::make_pair(argv[i], i));
931 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000932 }
933
934 // Delay processing positional arguments until the end...
935 continue;
936 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000937 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
938 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000939 DashDashFound = true; // This is the mythical "--"?
940 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000941 } else if (ActivePositionalArg &&
942 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
943 // If there is a positional argument eating options, check to see if this
944 // option is another positional argument. If so, treat it as an argument,
945 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000946 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000947 // Eat leading dashes.
948 while (!ArgName.empty() && ArgName[0] == '-')
949 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000950
Chris Bienemand1d94302015-01-28 19:00:25 +0000951 Handler = LookupOption(ArgName, Value, OptionsMap);
Chris Lattnera60f3552004-05-06 22:04:31 +0000952 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000953 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000954 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000955 }
956
Chris Bieneman5d232242015-01-13 19:14:20 +0000957 } else { // We start with a '-', must be an argument.
958 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000959 // Eat leading dashes.
960 while (!ArgName.empty() && ArgName[0] == '-')
961 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000962
Chris Bienemand1d94302015-01-28 19:00:25 +0000963 Handler = LookupOption(ArgName, Value, OptionsMap);
Chris Lattner36a57d32001-07-23 17:17:47 +0000964
Chris Lattnera60f3552004-05-06 22:04:31 +0000965 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000966 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +0000967 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
968 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000969
970 // Otherwise, look for the closest available option to report to the user
971 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000972 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000973 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +0000974 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000975 }
976
Craig Topper8d399f82014-04-09 04:20:00 +0000977 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000978 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000979 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
980 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000981
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000982 if (NearestHandler) {
983 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000984 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
985 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000986 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000987
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000988 ErrorParsing = true;
989 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000990 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
991 E = SinkOpts.end();
992 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000993 (*I)->addOccurrence(i, "", argv[i]);
994 }
Chris Lattner36a57d32001-07-23 17:17:47 +0000995 continue;
996 }
997
Chris Lattner2da046f2003-07-30 17:34:02 +0000998 // If this is a named positional argument, just remember that it is the
999 // active one...
1000 if (Handler->getFormattingFlag() == cl::Positional)
1001 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001002 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001003 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001004 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001005
Chris Lattner5df56c42002-07-22 02:07:59 +00001006 // Check and handle positional arguments now...
1007 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001008 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +00001009 << ": Not enough positional command line arguments specified!\n"
1010 << "Must specify at least " << NumPositionalRequired
1011 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001012
Chris Lattner5df56c42002-07-22 02:07:59 +00001013 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001014 } else if (!HasUnlimitedPositionals &&
1015 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001016 errs() << ProgramName << ": Too many positional arguments specified!\n"
1017 << "Can specify at most " << PositionalOpts.size()
1018 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001019 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001020
Craig Topper8d399f82014-04-09 04:20:00 +00001021 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001022 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001023 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1024 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001025 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001026 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001027 PositionalVals[ValNo].second);
1028 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001029 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001030 }
1031
1032 // If we _can_ give this option more arguments, do so now, as long as we
1033 // do not give it values that others need. 'Done' controls whether the
1034 // option even _WANTS_ any more.
1035 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001036 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001037 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001038 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001039 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001040 Done = true; // Optional arguments want _at most_ one value
1041 // FALL THROUGH
1042 case cl::ZeroOrMore: // Zero or more will take all they can get...
1043 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001044 ProvidePositionalOption(PositionalOpts[i],
1045 PositionalVals[ValNo].first,
1046 PositionalVals[ValNo].second);
1047 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001048 break;
1049 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001050 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001051 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001052 }
1053 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001054 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001055 } else {
1056 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1057 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001058 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001059 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001060 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001061 PositionalVals[ValNo].first,
1062 PositionalVals[ValNo].second);
1063 ValNo++;
1064 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001065
1066 // Handle the case where there is just one positional option, and it's
1067 // optional. In this case, we want to give JUST THE FIRST option to the
1068 // positional option and keep the rest for the consume after. The above
1069 // loop would have assigned no values to positional options in this case.
1070 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001071 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1072 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001073 PositionalVals[ValNo].first,
1074 PositionalVals[ValNo].second);
1075 ValNo++;
1076 }
Misha Brukman10468d82005-04-21 22:55:34 +00001077
Chris Lattner5df56c42002-07-22 02:07:59 +00001078 // Handle over all of the rest of the arguments to the
1079 // cl::ConsumeAfter command line option...
1080 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001081 ErrorParsing |=
1082 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1083 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001084 }
1085
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001086 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001087 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001088 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001089 case Required:
1090 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001091 if (Opt.second->getNumOccurrences() == 0) {
1092 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001093 ErrorParsing = true;
1094 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001095 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001096 default:
1097 break;
1098 }
1099 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001100
Rafael Espindolacf14a382010-11-19 21:14:29 +00001101 // Now that we know if -debug is specified, we can use it.
1102 // Note that if ReadResponseFiles == true, this must be done before the
1103 // memory allocated for the expanded command line is free()d below.
1104 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001105 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1106 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001107
Chris Lattner5df56c42002-07-22 02:07:59 +00001108 // Free all of the memory allocated to the map. Command line options may only
1109 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001110 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001111
1112 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001113 if (ErrorParsing)
1114 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001115}
1116
1117//===----------------------------------------------------------------------===//
1118// Option Base class implementation
1119//
Chris Lattner36a57d32001-07-23 17:17:47 +00001120
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001121bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001122 if (!ArgName.data())
1123 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001124 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001125 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001126 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001127 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001128
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001129 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001130 return true;
1131}
1132
Chris Bieneman5d232242015-01-13 19:14:20 +00001133bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1134 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001135 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001136 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001137
Misha Brukman069e6b52003-07-10 16:49:51 +00001138 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001139 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001140 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001141 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001142 break;
1143 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001144 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001145 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001146 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001147 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001148 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001149 case ConsumeAfter:
1150 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001151 }
1152
Reid Spencer2027a6f2004-08-13 19:47:30 +00001153 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001154}
1155
Chris Lattner5df56c42002-07-22 02:07:59 +00001156// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1157// has been specified yet.
1158//
1159static const char *getValueStr(const Option &O, const char *DefaultMsg) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001160 if (O.ValueStr[0] == 0)
1161 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001162 return O.ValueStr;
1163}
1164
1165//===----------------------------------------------------------------------===//
1166// cl::alias class implementation
1167//
1168
Chris Lattner36a57d32001-07-23 17:17:47 +00001169// Return the width of the option tag for printing...
Chris Bieneman5d232242015-01-13 19:14:20 +00001170size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001171
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001172static void printHelpStr(StringRef HelpStr, size_t Indent,
1173 size_t FirstLineIndentedBy) {
1174 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1175 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1176 while (!Split.second.empty()) {
1177 Split = Split.second.split('\n');
1178 outs().indent(Indent) << Split.first << "\n";
1179 }
1180}
1181
Chris Lattner1b7a5152006-04-28 05:36:25 +00001182// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001183void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001184 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001185 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001186}
1187
Chris Lattner36a57d32001-07-23 17:17:47 +00001188//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001189// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001190//
1191
Chris Lattnerb4101b12002-08-07 18:36:37 +00001192// basic_parser implementation
1193//
1194
1195// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001196size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1197 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001198 if (const char *ValName = getValueName())
Chris Bieneman5d232242015-01-13 19:14:20 +00001199 Len += std::strlen(getValueStr(O, ValName)) + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001200
1201 return Len + 6;
1202}
1203
Misha Brukman10468d82005-04-21 22:55:34 +00001204// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001205// to-be-maintained width is specified.
1206//
1207void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001208 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001209 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001210
1211 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001212 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001213
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001214 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001215}
1216
Andrew Trick12004012011-04-05 18:54:36 +00001217void basic_parser_impl::printOptionName(const Option &O,
1218 size_t GlobalWidth) const {
1219 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001220 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001221}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001222
Chris Lattner5df56c42002-07-22 02:07:59 +00001223// parser<bool> implementation
1224//
Chris Bieneman5d232242015-01-13 19:14:20 +00001225bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1226 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001227 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001228 Arg == "1") {
1229 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001230 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001231 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001232
Chris Lattneraecd74d2009-09-19 18:55:05 +00001233 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1234 Value = false;
1235 return false;
1236 }
1237 return O.error("'" + Arg +
1238 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001239}
1240
Dale Johannesen82810c82007-05-22 17:14:46 +00001241// parser<boolOrDefault> implementation
1242//
Chris Bieneman5d232242015-01-13 19:14:20 +00001243bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1244 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001245 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1246 Arg == "1") {
1247 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001248 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001249 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001250 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1251 Value = BOU_FALSE;
1252 return false;
1253 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001254
Chris Lattneraecd74d2009-09-19 18:55:05 +00001255 return O.error("'" + Arg +
1256 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001257}
1258
Chris Lattner5df56c42002-07-22 02:07:59 +00001259// parser<int> implementation
1260//
Chris Bieneman5d232242015-01-13 19:14:20 +00001261bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1262 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001263 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001264 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001265 return false;
1266}
1267
Chris Lattner719c7152003-06-28 15:47:20 +00001268// parser<unsigned> implementation
1269//
Chris Bieneman5d232242015-01-13 19:14:20 +00001270bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1271 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001272
1273 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001274 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001275 return false;
1276}
1277
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001278// parser<unsigned long long> implementation
1279//
1280bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001281 StringRef Arg,
1282 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001283
1284 if (Arg.getAsInteger(0, Value))
1285 return O.error("'" + Arg + "' value invalid for uint argument!");
1286 return false;
1287}
1288
Chris Lattnerb4101b12002-08-07 18:36:37 +00001289// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001290//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001291static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001292 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1293 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001294 char *End;
1295 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001296 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001297 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001298 return false;
1299}
1300
Chris Bieneman5d232242015-01-13 19:14:20 +00001301bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1302 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001303 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001304}
1305
Chris Bieneman5d232242015-01-13 19:14:20 +00001306bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1307 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001308 double dVal;
1309 if (parseDouble(O, Arg, dVal))
1310 return true;
1311 Val = (float)dVal;
1312 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001313}
1314
Chris Lattner5df56c42002-07-22 02:07:59 +00001315// generic_parser_base implementation
1316//
1317
Chris Lattner494c0b02002-07-23 17:15:12 +00001318// findOption - Return the option number corresponding to the specified
1319// argument string. If the option is not found, getNumOptions() is returned.
1320//
1321unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001322 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001323
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001324 for (unsigned i = 0; i != e; ++i) {
1325 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001326 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001327 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001328 return e;
1329}
1330
Chris Lattner5df56c42002-07-22 02:07:59 +00001331// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001332size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001333 if (O.hasArgStr()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001334 size_t Size = std::strlen(O.ArgStr) + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001335 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001336 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001337 return Size;
1338 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001339 size_t BaseSize = 0;
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 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001342 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001343 }
1344}
1345
Misha Brukman10468d82005-04-21 22:55:34 +00001346// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001347// to-be-maintained width is specified.
1348//
1349void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001350 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001351 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001352 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001353 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001354
Chris Lattner5df56c42002-07-22 02:07:59 +00001355 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001356 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001357 outs() << " =" << getOption(i);
1358 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001359 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001360 } else {
1361 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001362 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001363 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001364 const char *Option = getOption(i);
1365 outs() << " -" << Option;
1366 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001367 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001368 }
1369}
1370
Andrew Trick12004012011-04-05 18:54:36 +00001371static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1372
1373// printGenericOptionDiff - Print the value of this option and it's default.
1374//
1375// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001376void generic_parser_base::printGenericOptionDiff(
1377 const Option &O, const GenericOptionValue &Value,
1378 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001379 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001380 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001381
1382 unsigned NumOpts = getNumOptions();
1383 for (unsigned i = 0; i != NumOpts; ++i) {
1384 if (Value.compare(getOptionValue(i)))
1385 continue;
1386
1387 outs() << "= " << getOption(i);
1388 size_t L = std::strlen(getOption(i));
1389 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1390 outs().indent(NumSpaces) << " (default: ";
1391 for (unsigned j = 0; j != NumOpts; ++j) {
1392 if (Default.compare(getOptionValue(j)))
1393 continue;
1394 outs() << getOption(j);
1395 break;
1396 }
1397 outs() << ")\n";
1398 return;
1399 }
1400 outs() << "= *unknown option value*\n";
1401}
1402
1403// printOptionDiff - Specializations for printing basic value types.
1404//
Chris Bieneman5d232242015-01-13 19:14:20 +00001405#define PRINT_OPT_DIFF(T) \
1406 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1407 size_t GlobalWidth) const { \
1408 printOptionName(O, GlobalWidth); \
1409 std::string Str; \
1410 { \
1411 raw_string_ostream SS(Str); \
1412 SS << V; \
1413 } \
1414 outs() << "= " << Str; \
1415 size_t NumSpaces = \
1416 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1417 outs().indent(NumSpaces) << " (default: "; \
1418 if (D.hasValue()) \
1419 outs() << D.getValue(); \
1420 else \
1421 outs() << "*no default*"; \
1422 outs() << ")\n"; \
1423 }
Andrew Trick12004012011-04-05 18:54:36 +00001424
Frits van Bommel87e33672011-04-06 12:29:56 +00001425PRINT_OPT_DIFF(bool)
1426PRINT_OPT_DIFF(boolOrDefault)
1427PRINT_OPT_DIFF(int)
1428PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001429PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001430PRINT_OPT_DIFF(double)
1431PRINT_OPT_DIFF(float)
1432PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001433
Chris Bieneman5d232242015-01-13 19:14:20 +00001434void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1435 OptionValue<std::string> D,
1436 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001437 printOptionName(O, GlobalWidth);
1438 outs() << "= " << V;
1439 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1440 outs().indent(NumSpaces) << " (default: ";
1441 if (D.hasValue())
1442 outs() << D.getValue();
1443 else
1444 outs() << "*no default*";
1445 outs() << ")\n";
1446}
1447
1448// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001449void basic_parser_impl::printOptionNoValue(const Option &O,
1450 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001451 printOptionName(O, GlobalWidth);
1452 outs() << "= *cannot print option value*\n";
1453}
Chris Lattner36a57d32001-07-23 17:17:47 +00001454
1455//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001456// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001457//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001458
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001459static int OptNameCompare(const void *LHS, const void *RHS) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001460 typedef std::pair<const char *, Option *> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001461
Chris Bieneman5d232242015-01-13 19:14:20 +00001462 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001463}
1464
Andrew Trick12004012011-04-05 18:54:36 +00001465// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001466static void sortOpts(StringMap<Option *> &OptMap,
1467 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1468 bool ShowHidden) {
1469 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001470
Chris Bieneman5d232242015-01-13 19:14:20 +00001471 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001472 I != E; ++I) {
1473 // Ignore really-hidden options.
1474 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1475 continue;
1476
1477 // Unless showhidden is set, ignore hidden flags.
1478 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1479 continue;
1480
1481 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001482 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001483 continue;
1484
Chris Bieneman5d232242015-01-13 19:14:20 +00001485 Opts.push_back(
1486 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001487 }
1488
1489 // Sort the options list alphabetically.
1490 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1491}
1492
Chris Lattner36a57d32001-07-23 17:17:47 +00001493namespace {
1494
Chris Lattner5df56c42002-07-22 02:07:59 +00001495class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001496protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001497 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001498 typedef SmallVector<std::pair<const char *, Option *>, 128>
1499 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001500 // Print the options. Opts is assumed to be alphabetically sorted.
1501 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1502 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1503 Opts[i].second->printOptionInfo(MaxArgLen);
1504 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001505
Chris Lattner5df56c42002-07-22 02:07:59 +00001506public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001507 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001508 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001509
Andrew Trick0537a982013-05-06 21:56:23 +00001510 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001511 void operator=(bool Value) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001512 if (Value == false)
1513 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001514
Andrew Trick0537a982013-05-06 21:56:23 +00001515 StrOptionPairVector Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001516 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001517
Chris Bienemand1d94302015-01-28 19:00:25 +00001518 if (GlobalParser->ProgramOverview)
1519 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001520
Chris Bienemand1d94302015-01-28 19:00:25 +00001521 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001522
Chris Bienemand1d94302015-01-28 19:00:25 +00001523 for (auto Opt : GlobalParser->PositionalOpts) {
1524 if (Opt->ArgStr[0])
1525 outs() << " --" << Opt->ArgStr;
1526 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001527 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001528
1529 // Print the consume after option info if it exists...
Chris Bienemand1d94302015-01-28 19:00:25 +00001530 if (GlobalParser->ConsumeAfterOpt)
1531 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001532
Chris Lattner471ba482009-08-23 08:43:55 +00001533 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001534
1535 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001536 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001537 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001538 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001539
Chris Lattner471ba482009-08-23 08:43:55 +00001540 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001541 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001542
Chris Lattner37bcd992004-11-19 17:08:15 +00001543 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001544 for (auto I : GlobalParser->MoreHelp)
1545 outs() << I;
1546 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001547
Reid Spencer5e554702004-11-16 06:11:52 +00001548 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001549 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001550 }
1551};
Andrew Trick0537a982013-05-06 21:56:23 +00001552
1553class CategorizedHelpPrinter : public HelpPrinter {
1554public:
1555 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1556
1557 // Helper function for printOptions().
1558 // It shall return true if A's name should be lexographically
1559 // ordered before B's name. It returns false otherwise.
1560 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001561 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001562 }
1563
1564 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001565 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001566
1567protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001568 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001569 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001570 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001571
Alp Tokercb402912014-01-24 17:20:08 +00001572 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001573 // sorting.
1574 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1575 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001576 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001577 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001578 }
Andrew Trick0537a982013-05-06 21:56:23 +00001579
1580 // Sort the different option categories alphabetically.
1581 assert(SortedCategories.size() > 0 && "No option categories registered!");
1582 std::sort(SortedCategories.begin(), SortedCategories.end(),
1583 OptionCategoryCompare);
1584
1585 // Create map to empty vectors.
1586 for (std::vector<OptionCategory *>::const_iterator
1587 I = SortedCategories.begin(),
1588 E = SortedCategories.end();
1589 I != E; ++I)
1590 CategorizedOptions[*I] = std::vector<Option *>();
1591
1592 // Walk through pre-sorted options and assign into categories.
1593 // Because the options are already alphabetically sorted the
1594 // options within categories will also be alphabetically sorted.
1595 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1596 Option *Opt = Opts[I].second;
1597 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1598 "Option has an unregistered category");
1599 CategorizedOptions[Opt->Category].push_back(Opt);
1600 }
1601
1602 // Now do printing.
1603 for (std::vector<OptionCategory *>::const_iterator
1604 Category = SortedCategories.begin(),
1605 E = SortedCategories.end();
1606 Category != E; ++Category) {
1607 // Hide empty categories for -help, but show for -help-hidden.
1608 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1609 if (!ShowHidden && IsEmptyCategory)
1610 continue;
1611
1612 // Print category information.
1613 outs() << "\n";
1614 outs() << (*Category)->getName() << ":\n";
1615
1616 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001617 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001618 outs() << (*Category)->getDescription() << "\n\n";
1619 else
1620 outs() << "\n";
1621
1622 // When using -help-hidden explicitly state if the category has no
1623 // options associated with it.
1624 if (IsEmptyCategory) {
1625 outs() << " This option category has no options.\n";
1626 continue;
1627 }
1628 // Loop over the options in the category and print.
1629 for (std::vector<Option *>::const_iterator
1630 Opt = CategorizedOptions[*Category].begin(),
1631 E = CategorizedOptions[*Category].end();
1632 Opt != E; ++Opt)
1633 (*Opt)->printOptionInfo(MaxArgLen);
1634 }
1635 }
1636};
1637
1638// This wraps the Uncategorizing and Categorizing printers and decides
1639// at run time which should be invoked.
1640class HelpPrinterWrapper {
1641private:
1642 HelpPrinter &UncategorizedPrinter;
1643 CategorizedHelpPrinter &CategorizedPrinter;
1644
1645public:
1646 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001647 CategorizedHelpPrinter &CategorizedPrinter)
1648 : UncategorizedPrinter(UncategorizedPrinter),
1649 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001650
1651 // Invoke the printer.
1652 void operator=(bool Value);
1653};
1654
Chris Lattneradb19d62006-10-12 22:09:17 +00001655} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001656
Andrew Trick0537a982013-05-06 21:56:23 +00001657// Declare the four HelpPrinter instances that are used to print out help, or
1658// help-hidden as an uncategorized list or in categories.
1659static HelpPrinter UncategorizedNormalPrinter(false);
1660static HelpPrinter UncategorizedHiddenPrinter(true);
1661static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1662static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1663
Andrew Trick0537a982013-05-06 21:56:23 +00001664// Declare HelpPrinter wrappers that will decide whether or not to invoke
1665// a categorizing help printer
1666static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1667 CategorizedNormalPrinter);
1668static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1669 CategorizedHiddenPrinter);
1670
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001671// Define a category for generic options that all tools should have.
1672static cl::OptionCategory GenericCategory("Generic Options");
1673
Andrew Trick0537a982013-05-06 21:56:23 +00001674// Define uncategorized help printers.
1675// -help-list is hidden by default because if Option categories are being used
1676// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001677static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1678 "help-list",
1679 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001680 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1681 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001682
Chris Bieneman5d232242015-01-13 19:14:20 +00001683static cl::opt<HelpPrinter, true, parser<bool>>
1684 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1685 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001686 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001687
1688// Define uncategorized/categorized help printers. These printers change their
1689// behaviour at runtime depending on whether one or more Option categories have
1690// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001691static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1692 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001693 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1694 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001695
Chris Bieneman5d232242015-01-13 19:14:20 +00001696static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1697 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001698 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1699 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001700
Chris Bieneman5d232242015-01-13 19:14:20 +00001701static cl::opt<bool> PrintOptions(
1702 "print-options",
1703 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001704 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001705
Chris Bieneman5d232242015-01-13 19:14:20 +00001706static cl::opt<bool> PrintAllOptions(
1707 "print-all-options",
1708 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001709 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001710
Andrew Trick0537a982013-05-06 21:56:23 +00001711void HelpPrinterWrapper::operator=(bool Value) {
1712 if (Value == false)
1713 return;
1714
1715 // Decide which printer to invoke. If more than one option category is
1716 // registered then it is useful to show the categorized help instead of
1717 // uncategorized help.
1718 if (RegisteredOptionCategories->size() > 1) {
1719 // unhide -help-list option so user can have uncategorized output if they
1720 // want it.
1721 HLOp.setHiddenFlag(NotHidden);
1722
1723 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001724 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001725 UncategorizedPrinter = true; // Invoke uncategorized printer
1726}
1727
Andrew Trick12004012011-04-05 18:54:36 +00001728// Print the value of each option.
1729void cl::PrintOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001730 if (!PrintOptions && !PrintAllOptions)
1731 return;
Andrew Trick12004012011-04-05 18:54:36 +00001732
Chris Bieneman5d232242015-01-13 19:14:20 +00001733 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001734 sortOpts(GlobalParser->OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001735
1736 // Compute the maximum argument length...
1737 size_t MaxArgLen = 0;
1738 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1739 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1740
1741 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1742 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1743}
1744
Craig Topperc10719f2014-04-07 04:17:22 +00001745static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001746
Chris Bieneman5d232242015-01-13 19:14:20 +00001747static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001748
Chris Lattneradb19d62006-10-12 22:09:17 +00001749namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001750class VersionPrinter {
1751public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001752 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001753 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001754 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001755 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001756#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001757 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001758#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001759 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001760#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001761 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001762#else
Chris Lattner131dca92009-09-20 06:18:38 +00001763 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001764#endif
1765#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001766 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001767#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001768 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001769 if (CPU == "generic")
1770 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001771 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001772#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001773 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001774#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001775 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001776 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001777 }
1778 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001779 if (!OptionWasSpecified)
1780 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001781
Craig Topperc10719f2014-04-07 04:17:22 +00001782 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001783 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001784 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001785 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001786 print();
1787
1788 // Iterate over any registered extra printers and call them to add further
1789 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001790 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001791 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001792 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1793 E = ExtraVersionPrinters->end();
1794 I != E; ++I)
1795 (*I)();
1796 }
1797
Justin Bogner02b95842014-02-28 19:08:01 +00001798 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001799 }
1800};
Chris Lattneradb19d62006-10-12 22:09:17 +00001801} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001802
Reid Spencerff6cc122004-08-04 00:36:06 +00001803// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001804static VersionPrinter VersionPrinterInstance;
1805
Chris Bieneman5d232242015-01-13 19:14:20 +00001806static cl::opt<VersionPrinter, true, parser<bool>>
1807 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001808 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1809 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001810
Reid Spencer5e554702004-11-16 06:11:52 +00001811// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001812void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1813 // This looks weird, but it actually prints the help message. The Printers are
1814 // types of HelpPrinter and the help gets printed when its operator= is
1815 // invoked. That's because the "normal" usages of the help printer is to be
1816 // assigned true/false depending on whether -help or -help-hidden was given or
1817 // not. Since we're circumventing that we have to make it look like -help or
1818 // -help-hidden were given, so we assign true.
1819
1820 if (!Hidden && !Categorized)
1821 UncategorizedNormalPrinter = true;
1822 else if (!Hidden && Categorized)
1823 CategorizedNormalPrinter = true;
1824 else if (Hidden && !Categorized)
1825 UncategorizedHiddenPrinter = true;
1826 else
1827 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001828}
Reid Spencerb3171672006-06-05 16:22:56 +00001829
Devang Patel9eb2caae2007-02-01 01:43:37 +00001830/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001831void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001832
Chris Bieneman5d232242015-01-13 19:14:20 +00001833void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001834
1835void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001836 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001837 ExtraVersionPrinters = new std::vector<void (*)()>;
1838
1839 ExtraVersionPrinters->push_back(func);
1840}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001841
Chris Bienemand1d94302015-01-28 19:00:25 +00001842StringMap<Option *> &cl::getRegisteredOptions() {
1843 return GlobalParser->OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00001844}
Peter Collingbournee1863192014-10-16 22:47:52 +00001845
Chris Bieneman9e13af72015-01-21 22:45:52 +00001846void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001847 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001848 if (I.second->Category != &Category &&
1849 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001850 I.second->setHiddenFlag(cl::ReallyHidden);
1851 }
1852}
1853
Chris Bieneman68169362015-01-27 22:21:06 +00001854void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
Chris Bieneman01043252015-01-26 21:57:29 +00001855 auto CategoriesBegin = Categories.begin();
1856 auto CategoriesEnd = Categories.end();
Chris Bienemand1d94302015-01-28 19:00:25 +00001857 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00001858 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1859 CategoriesEnd &&
1860 I.second->Category != &GenericCategory)
1861 I.second->setHiddenFlag(cl::ReallyHidden);
1862 }
1863}
1864
Peter Collingbournee1863192014-10-16 22:47:52 +00001865void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1866 const char *Overview) {
1867 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1868}