blob: 9a1e8831064df7fcc601257c00f3a99568dee7f8 [file] [log] [blame]
Chris Lattner36a57d32001-07-23 17:17:47 +00001//===-- CommandLine.cpp - Command line parser implementation --------------===//
Misha Brukman10468d82005-04-21 22:55:34 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman10468d82005-04-21 22:55:34 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner36a57d32001-07-23 17:17:47 +00009//
10// This class implements a command line argument processor that is useful when
11// creating a tool. It provides a simple, minimalistic interface that is easily
12// extensible and supports nonlocal (library) command line options.
13//
Chris Lattner81cc83d2001-07-23 23:04:07 +000014// Note that rather than trying to figure out what this code does, you could try
15// reading the library documentation located in docs/CommandLine.html
16//
Chris Lattner36a57d32001-07-23 17:17:47 +000017//===----------------------------------------------------------------------===//
18
Reid Spencer7c16caa2004-09-01 22:55:40 +000019#include "llvm/Support/CommandLine.h"
Peter Collingbournee1863192014-10-16 22:47:52 +000020#include "llvm-c/Support.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000021#include "llvm/ADT/ArrayRef.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000022#include "llvm/ADT/SmallPtrSet.h"
Chris Lattnerfa9c6f42009-09-19 23:59:02 +000023#include "llvm/ADT/SmallString.h"
Chris Lattner41f8b0b2009-09-20 05:12:14 +000024#include "llvm/ADT/StringMap.h"
Chris Lattneraecd74d2009-09-19 18:55:05 +000025#include "llvm/ADT/Twine.h"
Chris Lattner36b3caf2009-08-23 18:09:02 +000026#include "llvm/Config/config.h"
Reid Klecknera73c7782013-07-18 16:52:05 +000027#include "llvm/Support/ConvertUTF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/Host.h"
31#include "llvm/Support/ManagedStatic.h"
32#include "llvm/Support/MemoryBuffer.h"
33#include "llvm/Support/Path.h"
34#include "llvm/Support/raw_ostream.h"
Brian Gaekee5e53222003-10-10 17:01:36 +000035#include <cerrno>
Chris Lattner36b3caf2009-08-23 18:09:02 +000036#include <cstdlib>
Andrew Trick0537a982013-05-06 21:56:23 +000037#include <map>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000038#include <system_error>
Chris Lattnerc9499b62003-12-14 21:35:53 +000039using namespace llvm;
Chris Lattner36a57d32001-07-23 17:17:47 +000040using namespace cl;
41
Chandler Carruthe96dd892014-04-21 22:55:11 +000042#define DEBUG_TYPE "commandline"
43
Chris Lattner3e5d60f2006-08-27 12:45:47 +000044//===----------------------------------------------------------------------===//
45// Template instantiations and anchors.
46//
Chris Bieneman5d232242015-01-13 19:14:20 +000047namespace llvm {
48namespace cl {
Chris Lattner3e5d60f2006-08-27 12:45:47 +000049TEMPLATE_INSTANTIATION(class basic_parser<bool>);
Dale Johannesen82810c82007-05-22 17:14:46 +000050TEMPLATE_INSTANTIATION(class basic_parser<boolOrDefault>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000051TEMPLATE_INSTANTIATION(class basic_parser<int>);
52TEMPLATE_INSTANTIATION(class basic_parser<unsigned>);
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000053TEMPLATE_INSTANTIATION(class basic_parser<unsigned long long>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000054TEMPLATE_INSTANTIATION(class basic_parser<double>);
55TEMPLATE_INSTANTIATION(class basic_parser<float>);
56TEMPLATE_INSTANTIATION(class basic_parser<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000057TEMPLATE_INSTANTIATION(class basic_parser<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000058
59TEMPLATE_INSTANTIATION(class opt<unsigned>);
60TEMPLATE_INSTANTIATION(class opt<int>);
61TEMPLATE_INSTANTIATION(class opt<std::string>);
Bill Wendlingdb59fda2009-04-29 23:26:16 +000062TEMPLATE_INSTANTIATION(class opt<char>);
Chris Lattner3e5d60f2006-08-27 12:45:47 +000063TEMPLATE_INSTANTIATION(class opt<bool>);
Chris Bieneman5d232242015-01-13 19:14:20 +000064}
65} // end namespace llvm::cl
Chris Lattner3e5d60f2006-08-27 12:45:47 +000066
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +000067// Pin the vtables to this file.
68void GenericOptionValue::anchor() {}
David Blaikie3a15e142011-12-01 08:00:17 +000069void OptionValue<boolOrDefault>::anchor() {}
70void OptionValue<std::string>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000071void Option::anchor() {}
72void basic_parser_impl::anchor() {}
73void parser<bool>::anchor() {}
Dale Johannesen82810c82007-05-22 17:14:46 +000074void parser<boolOrDefault>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000075void parser<int>::anchor() {}
76void parser<unsigned>::anchor() {}
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +000077void parser<unsigned long long>::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000078void parser<double>::anchor() {}
79void parser<float>::anchor() {}
80void parser<std::string>::anchor() {}
Bill Wendlingdb59fda2009-04-29 23:26:16 +000081void parser<char>::anchor() {}
Sean Silvadb794842014-08-15 23:39:01 +000082void StringSaver::anchor() {}
Chris Lattner3e5d60f2006-08-27 12:45:47 +000083
84//===----------------------------------------------------------------------===//
85
Benjamin Kramer970eac42015-02-06 17:51:54 +000086namespace {
87
Chris Bienemand1d94302015-01-28 19:00:25 +000088class CommandLineParser {
89public:
90 // Globals for name and overview of program. Program name is not a string to
91 // avoid static ctor/dtor issues.
Chris Bienemanb6866422015-01-28 22:25:00 +000092 std::string ProgramName;
NAKAMURA Takumi81828182015-01-29 11:06:59 +000093 const char *ProgramOverview;
Reid Spencer9501b9b2004-09-01 04:41:28 +000094
Chris Bienemand1d94302015-01-28 19:00:25 +000095 // This collects additional help to be printed.
96 std::vector<const char *> MoreHelp;
97
98 SmallVector<Option *, 4> PositionalOpts;
99 SmallVector<Option *, 4> SinkOpts;
100 StringMap<Option *> OptionsMap;
101
NAKAMURA Takumi81828182015-01-29 11:06:59 +0000102 Option *ConsumeAfterOpt; // The ConsumeAfter option if it exists.
103
104 CommandLineParser() : ProgramOverview(nullptr), ConsumeAfterOpt(nullptr) {}
Chris Bienemand1d94302015-01-28 19:00:25 +0000105
106 void ParseCommandLineOptions(int argc, const char *const *argv,
107 const char *Overview);
108
109 void addLiteralOption(Option &Opt, const char *Name) {
110 if (!Opt.hasArgStr()) {
111 if (!OptionsMap.insert(std::make_pair(Name, &Opt)).second) {
112 errs() << ProgramName << ": CommandLine Error: Option '" << Name
113 << "' registered more than once!\n";
114 report_fatal_error("inconsistency in registered CommandLine options");
115 }
116 }
117 }
118
119 void addOption(Option *O) {
120 bool HadErrors = false;
121 if (O->ArgStr[0]) {
122 // Add argument to the argument map!
123 if (!OptionsMap.insert(std::make_pair(O->ArgStr, O)).second) {
124 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
125 << "' registered more than once!\n";
126 HadErrors = true;
127 }
128 }
129
130 // Remember information about positional options.
131 if (O->getFormattingFlag() == cl::Positional)
132 PositionalOpts.push_back(O);
133 else if (O->getMiscFlags() & cl::Sink) // Remember sink options
134 SinkOpts.push_back(O);
135 else if (O->getNumOccurrencesFlag() == cl::ConsumeAfter) {
136 if (ConsumeAfterOpt) {
137 O->error("Cannot specify more than one option with cl::ConsumeAfter!");
138 HadErrors = true;
139 }
140 ConsumeAfterOpt = O;
141 }
142
143 // Fail hard if there were errors. These are strictly unrecoverable and
144 // indicate serious issues such as conflicting option names or an
145 // incorrectly
146 // linked LLVM distribution.
147 if (HadErrors)
148 report_fatal_error("inconsistency in registered CommandLine options");
149 }
150
151 void removeOption(Option *O) {
152 SmallVector<const char *, 16> OptionNames;
153 O->getExtraOptionNames(OptionNames);
154 if (O->ArgStr[0])
155 OptionNames.push_back(O->ArgStr);
156 for (auto Name : OptionNames)
157 OptionsMap.erase(StringRef(Name));
158
159 if (O->getFormattingFlag() == cl::Positional)
160 for (auto Opt = PositionalOpts.begin(); Opt != PositionalOpts.end();
161 ++Opt) {
162 if (*Opt == O) {
163 PositionalOpts.erase(Opt);
164 break;
165 }
166 }
167 else if (O->getMiscFlags() & cl::Sink)
168 for (auto Opt = SinkOpts.begin(); Opt != SinkOpts.end(); ++Opt) {
169 if (*Opt == O) {
170 SinkOpts.erase(Opt);
171 break;
172 }
173 }
174 else if (O == ConsumeAfterOpt)
175 ConsumeAfterOpt = nullptr;
176 }
177
178 bool hasOptions() {
179 return (!OptionsMap.empty() || !PositionalOpts.empty() ||
180 nullptr != ConsumeAfterOpt);
181 }
182
Chris Bienemand77bbab2015-01-30 22:16:01 +0000183 void updateArgStr(Option *O, const char *NewName) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000184 if (!OptionsMap.insert(std::make_pair(NewName, O)).second) {
185 errs() << ProgramName << ": CommandLine Error: Option '" << O->ArgStr
186 << "' registered more than once!\n";
187 report_fatal_error("inconsistency in registered CommandLine options");
188 }
189 OptionsMap.erase(StringRef(O->ArgStr));
190 }
Chris Bienemand77bbab2015-01-30 22:16:01 +0000191
192 void printOptionValues();
Chris Bieneman542f56a2015-02-13 22:54:27 +0000193
194private:
195 Option *LookupOption(StringRef &Arg, StringRef &Value);
Chris Bienemand1d94302015-01-28 19:00:25 +0000196};
197
Benjamin Kramer970eac42015-02-06 17:51:54 +0000198} // namespace
199
Chris Bienemand1d94302015-01-28 19:00:25 +0000200static ManagedStatic<CommandLineParser> GlobalParser;
201
202void cl::AddLiteralOption(Option &O, const char *Name) {
203 GlobalParser->addLiteralOption(O, Name);
204}
Chris Lattner37bcd992004-11-19 17:08:15 +0000205
Chris Bieneman5d232242015-01-13 19:14:20 +0000206extrahelp::extrahelp(const char *Help) : morehelp(Help) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000207 GlobalParser->MoreHelp.push_back(Help);
Chris Lattner37bcd992004-11-19 17:08:15 +0000208}
209
Chris Lattner5247f602007-04-06 21:06:55 +0000210void Option::addArgument() {
Chris Bienemand1d94302015-01-28 19:00:25 +0000211 GlobalParser->addOption(this);
212 FullyInitialized = true;
Chris Lattner5247f602007-04-06 21:06:55 +0000213}
214
Chris Bienemand1d94302015-01-28 19:00:25 +0000215void Option::removeArgument() { GlobalParser->removeOption(this); }
216
217void Option::setArgStr(const char *S) {
218 if (FullyInitialized)
219 GlobalParser->updateArgStr(this, S);
220 ArgStr = S;
Jordan Rosec25b0c72014-01-29 18:54:17 +0000221}
222
Andrew Trick0537a982013-05-06 21:56:23 +0000223// This collects the different option categories that have been registered.
Chris Bieneman5d232242015-01-13 19:14:20 +0000224typedef SmallPtrSet<OptionCategory *, 16> OptionCatSet;
Andrew Trick0537a982013-05-06 21:56:23 +0000225static ManagedStatic<OptionCatSet> RegisteredOptionCategories;
226
227// Initialise the general option category.
228OptionCategory llvm::cl::GeneralCategory("General options");
229
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000230void OptionCategory::registerCategory() {
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000231 assert(std::count_if(RegisteredOptionCategories->begin(),
232 RegisteredOptionCategories->end(),
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000233 [this](const OptionCategory *Category) {
234 return getName() == Category->getName();
Chris Bieneman5d232242015-01-13 19:14:20 +0000235 }) == 0 &&
236 "Duplicate option categories");
Alexander Kornienko52a07b82014-02-27 14:47:37 +0000237
Andrew Trick0537a982013-05-06 21:56:23 +0000238 RegisteredOptionCategories->insert(this);
239}
Chris Lattneraf039c52007-04-12 00:36:29 +0000240
Chris Lattner5df56c42002-07-22 02:07:59 +0000241//===----------------------------------------------------------------------===//
Chris Lattner3e5d60f2006-08-27 12:45:47 +0000242// Basic, shared command line option processing machinery.
Chris Lattner5df56c42002-07-22 02:07:59 +0000243//
244
Chris Lattner2031b022007-04-05 21:58:17 +0000245/// LookupOption - Lookup the option specified by the specified option on the
246/// command line. If there is a value specified (after an equal sign) return
Chris Lattnere7c1e212009-09-20 05:03:30 +0000247/// that as well. This assumes that leading dashes have already been stripped.
Chris Bieneman542f56a2015-02-13 22:54:27 +0000248Option *CommandLineParser::LookupOption(StringRef &Arg, StringRef &Value) {
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000249 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000250 if (Arg.empty())
251 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000252
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000253 size_t EqualPos = Arg.find('=');
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000254
Chris Lattner0a40a972009-09-20 01:53:12 +0000255 // If we have an equals sign, remember the value.
Chris Lattnere7c1e212009-09-20 05:03:30 +0000256 if (EqualPos == StringRef::npos) {
257 // Look up the option.
Chris Bieneman5d232242015-01-13 19:14:20 +0000258 StringMap<Option *>::const_iterator I = OptionsMap.find(Arg);
Craig Topperc10719f2014-04-07 04:17:22 +0000259 return I != OptionsMap.end() ? I->second : nullptr;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000260 }
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000261
Chris Lattnere7c1e212009-09-20 05:03:30 +0000262 // If the argument before the = is a valid option name, we match. If not,
263 // return Arg unmolested.
Chris Bieneman5d232242015-01-13 19:14:20 +0000264 StringMap<Option *>::const_iterator I =
265 OptionsMap.find(Arg.substr(0, EqualPos));
266 if (I == OptionsMap.end())
267 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000268
Chris Bieneman5d232242015-01-13 19:14:20 +0000269 Value = Arg.substr(EqualPos + 1);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000270 Arg = Arg.substr(0, EqualPos);
271 return I->second;
Chris Lattner36a57d32001-07-23 17:17:47 +0000272}
273
Daniel Dunbarf4132132011-01-18 01:59:24 +0000274/// LookupNearestOption - Lookup the closest match to the option specified by
275/// the specified option on the command line. If there is a value specified
276/// (after an equal sign) return that as well. This assumes that leading dashes
277/// have already been stripped.
278static Option *LookupNearestOption(StringRef Arg,
Chris Bieneman5d232242015-01-13 19:14:20 +0000279 const StringMap<Option *> &OptionsMap,
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000280 std::string &NearestString) {
Daniel Dunbarf4132132011-01-18 01:59:24 +0000281 // Reject all dashes.
Chris Bieneman5d232242015-01-13 19:14:20 +0000282 if (Arg.empty())
283 return nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000284
285 // Split on any equal sign.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000286 std::pair<StringRef, StringRef> SplitArg = Arg.split('=');
Chris Bieneman5d232242015-01-13 19:14:20 +0000287 StringRef &LHS = SplitArg.first; // LHS == Arg when no '=' is present.
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000288 StringRef &RHS = SplitArg.second;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000289
290 // Find the closest match.
Craig Topperc10719f2014-04-07 04:17:22 +0000291 Option *Best = nullptr;
Daniel Dunbarf4132132011-01-18 01:59:24 +0000292 unsigned BestDistance = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000293 for (StringMap<Option *>::const_iterator it = OptionsMap.begin(),
294 ie = OptionsMap.end();
295 it != ie; ++it) {
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000296 Option *O = it->second;
Chris Bieneman5d232242015-01-13 19:14:20 +0000297 SmallVector<const char *, 16> OptionNames;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000298 O->getExtraOptionNames(OptionNames);
299 if (O->ArgStr[0])
300 OptionNames.push_back(O->ArgStr);
301
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000302 bool PermitValue = O->getValueExpectedFlag() != cl::ValueDisallowed;
303 StringRef Flag = PermitValue ? LHS : Arg;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000304 for (size_t i = 0, e = OptionNames.size(); i != e; ++i) {
305 StringRef Name = OptionNames[i];
306 unsigned Distance = StringRef(Name).edit_distance(
Chris Bieneman5d232242015-01-13 19:14:20 +0000307 Flag, /*AllowReplacements=*/true, /*MaxEditDistance=*/BestDistance);
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000308 if (!Best || Distance < BestDistance) {
309 Best = O;
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000310 BestDistance = Distance;
Bill Wendling318f03f2012-07-19 00:15:11 +0000311 if (RHS.empty() || !PermitValue)
312 NearestString = OptionNames[i];
313 else
314 NearestString = std::string(OptionNames[i]) + "=" + RHS.str();
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000315 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000316 }
317 }
318
319 return Best;
320}
321
Alp Tokercb402912014-01-24 17:20:08 +0000322/// CommaSeparateAndAddOccurrence - A wrapper around Handler->addOccurrence()
323/// that does special handling of cl::CommaSeparated options.
324static bool CommaSeparateAndAddOccurrence(Option *Handler, unsigned pos,
325 StringRef ArgName, StringRef Value,
326 bool MultiArg = false) {
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000327 // Check to see if this option accepts a comma separated list of values. If
328 // it does, we have to split up the value into multiple values.
329 if (Handler->getMiscFlags() & CommaSeparated) {
330 StringRef Val(Value);
331 StringRef::size_type Pos = Val.find(',');
Chris Lattnere7c1e212009-09-20 05:03:30 +0000332
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000333 while (Pos != StringRef::npos) {
334 // Process the portion before the comma.
335 if (Handler->addOccurrence(pos, ArgName, Val.substr(0, Pos), MultiArg))
336 return true;
337 // Erase the portion before the comma, AND the comma.
Chris Bieneman5d232242015-01-13 19:14:20 +0000338 Val = Val.substr(Pos + 1);
339 Value.substr(Pos + 1); // Increment the original value pointer as well.
Mikhail Glushenkov5551c202009-11-20 17:23:17 +0000340 // Check for another comma.
341 Pos = Val.find(',');
342 }
343
344 Value = Val;
345 }
346
347 if (Handler->addOccurrence(pos, ArgName, Value, MultiArg))
348 return true;
349
350 return false;
351}
Chris Lattnere7c1e212009-09-20 05:03:30 +0000352
Chris Lattner40fef802009-09-20 01:49:31 +0000353/// ProvideOption - For Value, this differentiates between an empty value ("")
354/// and a null value (StringRef()). The later is accepted for arguments that
355/// don't allow a value (-foo) the former is rejected (-foo=).
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000356static inline bool ProvideOption(Option *Handler, StringRef ArgName,
David Blaikie0210e972012-02-07 19:36:01 +0000357 StringRef Value, int argc,
358 const char *const *argv, int &i) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000359 // Is this a multi-argument option?
360 unsigned NumAdditionalVals = Handler->getNumAdditionalVals();
361
Chris Lattnere81c4092001-10-27 05:54:17 +0000362 // Enforce value requirements
363 switch (Handler->getValueExpectedFlag()) {
364 case ValueRequired:
Craig Topper8d399f82014-04-09 04:20:00 +0000365 if (!Value.data()) { // No value specified?
Chris Bieneman5d232242015-01-13 19:14:20 +0000366 if (i + 1 >= argc)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000367 return Handler->error("requires a value!");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000368 // Steal the next argument, like for '-o filename'
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000369 assert(argv && "null check");
Chris Lattnerca2552d2009-09-20 00:07:40 +0000370 Value = argv[++i];
Chris Lattnere81c4092001-10-27 05:54:17 +0000371 }
372 break;
373 case ValueDisallowed:
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000374 if (NumAdditionalVals > 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000375 return Handler->error("multi-valued option specified"
Chris Lattnerca2552d2009-09-20 00:07:40 +0000376 " with ValueDisallowed modifier!");
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000377
Chris Lattner40fef802009-09-20 01:49:31 +0000378 if (Value.data())
Chris Bieneman5d232242015-01-13 19:14:20 +0000379 return Handler->error("does not allow a value! '" + Twine(Value) +
380 "' specified.");
Chris Lattnere81c4092001-10-27 05:54:17 +0000381 break;
Misha Brukman10468d82005-04-21 22:55:34 +0000382 case ValueOptional:
Reid Spencer9501b9b2004-09-01 04:41:28 +0000383 break;
Chris Lattnere81c4092001-10-27 05:54:17 +0000384 }
385
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000386 // If this isn't a multi-arg option, just run the handler.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000387 if (NumAdditionalVals == 0)
Alp Tokercb402912014-01-24 17:20:08 +0000388 return CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value);
Chris Lattneraecd74d2009-09-19 18:55:05 +0000389
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000390 // If it is, run the handle several times.
Chris Lattneraecd74d2009-09-19 18:55:05 +0000391 bool MultiArg = false;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000392
Chris Lattner40fef802009-09-20 01:49:31 +0000393 if (Value.data()) {
Alp Tokercb402912014-01-24 17:20:08 +0000394 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000395 return true;
396 --NumAdditionalVals;
397 MultiArg = true;
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +0000398 }
Chris Lattneraecd74d2009-09-19 18:55:05 +0000399
400 while (NumAdditionalVals > 0) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000401 if (i + 1 >= argc)
Chris Lattneraecd74d2009-09-19 18:55:05 +0000402 return Handler->error("not enough values!");
Michael Ilseman4e654cd2014-12-11 19:46:38 +0000403 assert(argv && "null check");
Chris Lattneraecd74d2009-09-19 18:55:05 +0000404 Value = argv[++i];
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000405
Alp Tokercb402912014-01-24 17:20:08 +0000406 if (CommaSeparateAndAddOccurrence(Handler, i, ArgName, Value, MultiArg))
Chris Lattneraecd74d2009-09-19 18:55:05 +0000407 return true;
408 MultiArg = true;
409 --NumAdditionalVals;
410 }
411 return false;
Chris Lattnere81c4092001-10-27 05:54:17 +0000412}
413
Chris Lattnerca2552d2009-09-20 00:07:40 +0000414static bool ProvidePositionalOption(Option *Handler, StringRef Arg, int i) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000415 int Dummy = i;
Craig Topperc10719f2014-04-07 04:17:22 +0000416 return ProvideOption(Handler, Handler->ArgStr, Arg, 0, nullptr, Dummy);
Chris Lattner5df56c42002-07-22 02:07:59 +0000417}
Chris Lattnerf0f91052001-11-26 18:58:34 +0000418
Chris Lattner5df56c42002-07-22 02:07:59 +0000419// Option predicates...
420static inline bool isGrouping(const Option *O) {
421 return O->getFormattingFlag() == cl::Grouping;
422}
423static inline bool isPrefixedOrGrouping(const Option *O) {
424 return isGrouping(O) || O->getFormattingFlag() == cl::Prefix;
425}
426
427// getOptionPred - Check to see if there are any options that satisfy the
428// specified predicate with names that are the prefixes in Name. This is
429// checked by progressively stripping characters off of the name, checking to
430// see if there options that satisfy the predicate. If we find one, return it,
431// otherwise return null.
432//
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000433static Option *getOptionPred(StringRef Name, size_t &Length,
Chris Bieneman5d232242015-01-13 19:14:20 +0000434 bool (*Pred)(const Option *),
435 const StringMap<Option *> &OptionsMap) {
Misha Brukman10468d82005-04-21 22:55:34 +0000436
Chris Bieneman5d232242015-01-13 19:14:20 +0000437 StringMap<Option *>::const_iterator OMI = OptionsMap.find(Name);
Chris Lattnerf0f91052001-11-26 18:58:34 +0000438
Chris Lattnere7c1e212009-09-20 05:03:30 +0000439 // Loop while we haven't found an option and Name still has at least two
440 // characters in it (so that the next iteration will not be the empty
441 // string.
442 while (OMI == OptionsMap.end() && Name.size() > 1) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000443 Name = Name.substr(0, Name.size() - 1); // Chop off the last character.
Chris Lattner5247f602007-04-06 21:06:55 +0000444 OMI = OptionsMap.find(Name);
Chris Lattnere7c1e212009-09-20 05:03:30 +0000445 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000446
Chris Lattner5247f602007-04-06 21:06:55 +0000447 if (OMI != OptionsMap.end() && Pred(OMI->second)) {
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000448 Length = Name.size();
Chris Bieneman5d232242015-01-13 19:14:20 +0000449 return OMI->second; // Found one!
Chris Lattner5df56c42002-07-22 02:07:59 +0000450 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000451 return nullptr; // No option found!
Chris Lattner5df56c42002-07-22 02:07:59 +0000452}
453
Chris Lattnere7c1e212009-09-20 05:03:30 +0000454/// HandlePrefixedOrGroupedOption - The specified argument string (which started
455/// with at least one '-') does not fully match an available option. Check to
456/// see if this is a prefix or grouped option. If so, split arg into output an
457/// Arg/Value pair and return the Option to parse it with.
Chris Bieneman5d232242015-01-13 19:14:20 +0000458static Option *
459HandlePrefixedOrGroupedOption(StringRef &Arg, StringRef &Value,
460 bool &ErrorParsing,
461 const StringMap<Option *> &OptionsMap) {
462 if (Arg.size() == 1)
463 return nullptr;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000464
465 // Do the lookup!
466 size_t Length = 0;
467 Option *PGOpt = getOptionPred(Arg, Length, isPrefixedOrGrouping, OptionsMap);
Chris Bieneman5d232242015-01-13 19:14:20 +0000468 if (!PGOpt)
469 return nullptr;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000470
Chris Lattnere7c1e212009-09-20 05:03:30 +0000471 // If the option is a prefixed option, then the value is simply the
472 // rest of the name... so fall through to later processing, by
473 // setting up the argument name flags and value fields.
474 if (PGOpt->getFormattingFlag() == cl::Prefix) {
475 Value = Arg.substr(Length);
476 Arg = Arg.substr(0, Length);
477 assert(OptionsMap.count(Arg) && OptionsMap.find(Arg)->second == PGOpt);
478 return PGOpt;
479 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000480
Chris Lattnere7c1e212009-09-20 05:03:30 +0000481 // This must be a grouped option... handle them now. Grouping options can't
482 // have values.
483 assert(isGrouping(PGOpt) && "Broken getOptionPred!");
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000484
Chris Lattnere7c1e212009-09-20 05:03:30 +0000485 do {
486 // Move current arg name out of Arg into OneArgName.
487 StringRef OneArgName = Arg.substr(0, Length);
488 Arg = Arg.substr(Length);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000489
Chris Lattnere7c1e212009-09-20 05:03:30 +0000490 // Because ValueRequired is an invalid flag for grouped arguments,
491 // we don't need to pass argc/argv in.
492 assert(PGOpt->getValueExpectedFlag() != cl::ValueRequired &&
493 "Option can not be cl::Grouping AND cl::ValueRequired!");
Duncan Sandsa2305522010-01-09 08:30:33 +0000494 int Dummy = 0;
Chris Bieneman5d232242015-01-13 19:14:20 +0000495 ErrorParsing |=
496 ProvideOption(PGOpt, OneArgName, StringRef(), 0, nullptr, Dummy);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000497
Chris Lattnere7c1e212009-09-20 05:03:30 +0000498 // Get the next grouping option.
499 PGOpt = getOptionPred(Arg, Length, isGrouping, OptionsMap);
500 } while (PGOpt && Length != Arg.size());
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000501
Chris Lattnere7c1e212009-09-20 05:03:30 +0000502 // Return the last option with Arg cut down to just the last one.
503 return PGOpt;
504}
505
Chris Lattner5df56c42002-07-22 02:07:59 +0000506static bool RequiresValue(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000507 return O->getNumOccurrencesFlag() == cl::Required ||
508 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattner5df56c42002-07-22 02:07:59 +0000509}
510
511static bool EatsUnboundedNumberOfValues(const Option *O) {
Misha Brukman069e6b52003-07-10 16:49:51 +0000512 return O->getNumOccurrencesFlag() == cl::ZeroOrMore ||
513 O->getNumOccurrencesFlag() == cl::OneOrMore;
Chris Lattnerf0f91052001-11-26 18:58:34 +0000514}
Chris Lattnere81c4092001-10-27 05:54:17 +0000515
Chris Bieneman5d232242015-01-13 19:14:20 +0000516static bool isWhitespace(char C) { return strchr(" \t\n\r\f\v", C); }
Brian Gaeke497216d2003-08-15 21:05:57 +0000517
Chris Bieneman5d232242015-01-13 19:14:20 +0000518static bool isQuote(char C) { return C == '\"' || C == '\''; }
Reid Klecknera73c7782013-07-18 16:52:05 +0000519
Chris Bieneman5d232242015-01-13 19:14:20 +0000520static bool isGNUSpecial(char C) { return strchr("\\\"\' ", C); }
Reid Klecknera73c7782013-07-18 16:52:05 +0000521
522void cl::TokenizeGNUCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000523 SmallVectorImpl<const char *> &NewArgv,
524 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000525 SmallString<128> Token;
526 for (size_t I = 0, E = Src.size(); I != E; ++I) {
527 // Consume runs of whitespace.
528 if (Token.empty()) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000529 while (I != E && isWhitespace(Src[I])) {
530 // Mark the end of lines in response files
531 if (MarkEOLs && Src[I] == '\n')
532 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000533 ++I;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000534 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000535 if (I == E)
536 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000537 }
538
539 // Backslashes can escape backslashes, spaces, and other quotes. Otherwise
540 // they are literal. This makes it much easier to read Windows file paths.
541 if (I + 1 < E && Src[I] == '\\' && isGNUSpecial(Src[I + 1])) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000542 ++I; // Skip the escape.
Reid Klecknera73c7782013-07-18 16:52:05 +0000543 Token.push_back(Src[I]);
Chris Lattner4e37f872009-09-24 05:38:36 +0000544 continue;
Brian Gaeke497216d2003-08-15 21:05:57 +0000545 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000546
Reid Klecknera73c7782013-07-18 16:52:05 +0000547 // Consume a quoted string.
548 if (isQuote(Src[I])) {
549 char Quote = Src[I++];
550 while (I != E && Src[I] != Quote) {
551 // Backslashes are literal, unless they escape a special character.
552 if (Src[I] == '\\' && I + 1 != E && isGNUSpecial(Src[I + 1]))
553 ++I;
554 Token.push_back(Src[I]);
555 ++I;
556 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000557 if (I == E)
558 break;
Reid Klecknera73c7782013-07-18 16:52:05 +0000559 continue;
560 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000561
Reid Klecknera73c7782013-07-18 16:52:05 +0000562 // End the token if this is whitespace.
563 if (isWhitespace(Src[I])) {
564 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000565 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknera73c7782013-07-18 16:52:05 +0000566 Token.clear();
567 continue;
568 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000569
Reid Klecknera73c7782013-07-18 16:52:05 +0000570 // This is a normal character. Append it.
571 Token.push_back(Src[I]);
Brian Gaeke497216d2003-08-15 21:05:57 +0000572 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000573
574 // Append the last token after hitting EOF with no whitespace.
575 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000576 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000577 // Mark the end of response files
578 if (MarkEOLs)
579 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000580}
581
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000582/// Backslashes are interpreted in a rather complicated way in the Windows-style
583/// command line, because backslashes are used both to separate path and to
584/// escape double quote. This method consumes runs of backslashes as well as the
585/// following double quote if it's escaped.
586///
587/// * If an even number of backslashes is followed by a double quote, one
588/// backslash is output for every pair of backslashes, and the last double
589/// quote remains unconsumed. The double quote will later be interpreted as
590/// the start or end of a quoted string in the main loop outside of this
591/// function.
592///
593/// * If an odd number of backslashes is followed by a double quote, one
594/// backslash is output for every pair of backslashes, and a double quote is
595/// output for the last pair of backslash-double quote. The double quote is
596/// consumed in this case.
597///
598/// * Otherwise, backslashes are interpreted literally.
599static size_t parseBackslash(StringRef Src, size_t I, SmallString<128> &Token) {
600 size_t E = Src.size();
601 int BackslashCount = 0;
602 // Skip the backslashes.
603 do {
604 ++I;
605 ++BackslashCount;
606 } while (I != E && Src[I] == '\\');
607
608 bool FollowedByDoubleQuote = (I != E && Src[I] == '"');
609 if (FollowedByDoubleQuote) {
610 Token.append(BackslashCount / 2, '\\');
611 if (BackslashCount % 2 == 0)
612 return I - 1;
613 Token.push_back('"');
614 return I;
615 }
616 Token.append(BackslashCount, '\\');
617 return I - 1;
618}
619
Reid Klecknera73c7782013-07-18 16:52:05 +0000620void cl::TokenizeWindowsCommandLine(StringRef Src, StringSaver &Saver,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000621 SmallVectorImpl<const char *> &NewArgv,
622 bool MarkEOLs) {
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000623 SmallString<128> Token;
624
625 // This is a small state machine to consume characters until it reaches the
626 // end of the source string.
627 enum { INIT, UNQUOTED, QUOTED } State = INIT;
628 for (size_t I = 0, E = Src.size(); I != E; ++I) {
629 // INIT state indicates that the current input index is at the start of
630 // the string or between tokens.
631 if (State == INIT) {
Reid Klecknere3f146d2014-08-22 19:29:17 +0000632 if (isWhitespace(Src[I])) {
633 // Mark the end of lines in response files
634 if (MarkEOLs && Src[I] == '\n')
635 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000636 continue;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000637 }
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000638 if (Src[I] == '"') {
639 State = QUOTED;
640 continue;
641 }
642 if (Src[I] == '\\') {
643 I = parseBackslash(Src, I, Token);
644 State = UNQUOTED;
645 continue;
646 }
647 Token.push_back(Src[I]);
648 State = UNQUOTED;
649 continue;
650 }
651
652 // UNQUOTED state means that it's reading a token not quoted by double
653 // quotes.
654 if (State == UNQUOTED) {
655 // Whitespace means the end of the token.
656 if (isWhitespace(Src[I])) {
Sean Silvadb794842014-08-15 23:39:01 +0000657 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000658 Token.clear();
659 State = INIT;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000660 // Mark the end of lines in response files
661 if (MarkEOLs && Src[I] == '\n')
662 NewArgv.push_back(nullptr);
Rui Ueyamaa2222b52013-07-30 19:03:20 +0000663 continue;
664 }
665 if (Src[I] == '"') {
666 State = QUOTED;
667 continue;
668 }
669 if (Src[I] == '\\') {
670 I = parseBackslash(Src, I, Token);
671 continue;
672 }
673 Token.push_back(Src[I]);
674 continue;
675 }
676
677 // QUOTED state means that it's reading a token quoted by double quotes.
678 if (State == QUOTED) {
679 if (Src[I] == '"') {
680 State = UNQUOTED;
681 continue;
682 }
683 if (Src[I] == '\\') {
684 I = parseBackslash(Src, I, Token);
685 continue;
686 }
687 Token.push_back(Src[I]);
688 }
689 }
690 // Append the last token after hitting EOF with no whitespace.
691 if (!Token.empty())
Sean Silvadb794842014-08-15 23:39:01 +0000692 NewArgv.push_back(Saver.SaveString(Token.c_str()));
Reid Klecknere3f146d2014-08-22 19:29:17 +0000693 // Mark the end of response files
694 if (MarkEOLs)
695 NewArgv.push_back(nullptr);
Reid Klecknera73c7782013-07-18 16:52:05 +0000696}
697
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000698// It is called byte order marker but the UTF-8 BOM is actually not affected
699// by the host system's endianness.
700static bool hasUTF8ByteOrderMark(ArrayRef<char> S) {
701 return (S.size() >= 3 &&
702 S[0] == '\xef' && S[1] == '\xbb' && S[2] == '\xbf');
703}
704
Reid Klecknera73c7782013-07-18 16:52:05 +0000705static bool ExpandResponseFile(const char *FName, StringSaver &Saver,
706 TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000707 SmallVectorImpl<const char *> &NewArgv,
708 bool MarkEOLs = false) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000709 ErrorOr<std::unique_ptr<MemoryBuffer>> MemBufOrErr =
710 MemoryBuffer::getFile(FName);
711 if (!MemBufOrErr)
Reid Klecknera73c7782013-07-18 16:52:05 +0000712 return false;
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000713 MemoryBuffer &MemBuf = *MemBufOrErr.get();
714 StringRef Str(MemBuf.getBufferStart(), MemBuf.getBufferSize());
Reid Klecknera73c7782013-07-18 16:52:05 +0000715
716 // If we have a UTF-16 byte order mark, convert to UTF-8 for parsing.
Rafael Espindola3f6481d2014-08-01 14:31:55 +0000717 ArrayRef<char> BufRef(MemBuf.getBufferStart(), MemBuf.getBufferEnd());
Reid Klecknera73c7782013-07-18 16:52:05 +0000718 std::string UTF8Buf;
719 if (hasUTF16ByteOrderMark(BufRef)) {
720 if (!convertUTF16ToUTF8String(BufRef, UTF8Buf))
721 return false;
722 Str = StringRef(UTF8Buf);
723 }
Yunzhong Gaoa8cf4952015-01-24 04:23:08 +0000724 // If we see UTF-8 BOM sequence at the beginning of a file, we shall remove
725 // these bytes before parsing.
726 // Reference: http://en.wikipedia.org/wiki/UTF-8#Byte_order_mark
727 else if (hasUTF8ByteOrderMark(BufRef))
728 Str = StringRef(BufRef.data() + 3, BufRef.size() - 3);
Reid Klecknera73c7782013-07-18 16:52:05 +0000729
730 // Tokenize the contents into NewArgv.
Reid Klecknere3f146d2014-08-22 19:29:17 +0000731 Tokenizer(Str, Saver, NewArgv, MarkEOLs);
Reid Klecknera73c7782013-07-18 16:52:05 +0000732
733 return true;
734}
735
736/// \brief Expand response files on a command line recursively using the given
737/// StringSaver and tokenization strategy.
738bool cl::ExpandResponseFiles(StringSaver &Saver, TokenizerCallback Tokenizer,
Reid Klecknere3f146d2014-08-22 19:29:17 +0000739 SmallVectorImpl<const char *> &Argv,
740 bool MarkEOLs) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000741 unsigned RspFiles = 0;
Reid Kleckner7c5fdaf2013-12-03 19:13:18 +0000742 bool AllExpanded = true;
Reid Klecknera73c7782013-07-18 16:52:05 +0000743
744 // Don't cache Argv.size() because it can change.
Chris Bieneman5d232242015-01-13 19:14:20 +0000745 for (unsigned I = 0; I != Argv.size();) {
Reid Klecknera73c7782013-07-18 16:52:05 +0000746 const char *Arg = Argv[I];
Reid Klecknere3f146d2014-08-22 19:29:17 +0000747 // Check if it is an EOL marker
748 if (Arg == nullptr) {
749 ++I;
750 continue;
751 }
Reid Klecknera73c7782013-07-18 16:52:05 +0000752 if (Arg[0] != '@') {
753 ++I;
754 continue;
755 }
756
757 // If we have too many response files, leave some unexpanded. This avoids
758 // crashing on self-referential response files.
759 if (RspFiles++ > 20)
760 return false;
761
762 // Replace this response file argument with the tokenization of its
763 // contents. Nested response files are expanded in subsequent iterations.
764 // FIXME: If a nested response file uses a relative path, is it relative to
765 // the cwd of the process or the response file?
766 SmallVector<const char *, 0> ExpandedArgv;
Reid Klecknere3f146d2014-08-22 19:29:17 +0000767 if (!ExpandResponseFile(Arg + 1, Saver, Tokenizer, ExpandedArgv,
768 MarkEOLs)) {
Justin Bogner67ae9912013-12-06 22:56:19 +0000769 // We couldn't read this file, so we leave it in the argument stream and
770 // move on.
Reid Klecknera73c7782013-07-18 16:52:05 +0000771 AllExpanded = false;
Justin Bogner67ae9912013-12-06 22:56:19 +0000772 ++I;
Reid Klecknera73c7782013-07-18 16:52:05 +0000773 continue;
774 }
775 Argv.erase(Argv.begin() + I);
776 Argv.insert(Argv.begin() + I, ExpandedArgv.begin(), ExpandedArgv.end());
777 }
778 return AllExpanded;
779}
780
Sean Silvadb794842014-08-15 23:39:01 +0000781namespace {
Chris Bieneman5d232242015-01-13 19:14:20 +0000782class StrDupSaver : public StringSaver {
783 std::vector<char *> Dups;
784
785public:
786 ~StrDupSaver() {
787 for (std::vector<char *>::iterator I = Dups.begin(), E = Dups.end(); I != E;
788 ++I) {
789 char *Dup = *I;
790 free(Dup);
Sean Silvadb794842014-08-15 23:39:01 +0000791 }
Chris Bieneman5d232242015-01-13 19:14:20 +0000792 }
793 const char *SaveString(const char *Str) override {
794 char *Dup = strdup(Str);
795 Dups.push_back(Dup);
796 return Dup;
797 }
798};
Sean Silvadb794842014-08-15 23:39:01 +0000799}
800
Brian Gaekeca782d92003-08-14 22:00:59 +0000801/// ParseEnvironmentOptions - An alternative entry point to the
802/// CommandLine library, which allows you to read the program's name
803/// from the caller (as PROGNAME) and its command-line arguments from
804/// an environment variable (whose name is given in ENVVAR).
805///
Chris Lattnera60f3552004-05-06 22:04:31 +0000806void cl::ParseEnvironmentOptions(const char *progName, const char *envVar,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000807 const char *Overview) {
Brian Gaeke497216d2003-08-15 21:05:57 +0000808 // Check args.
Chris Lattnera60f3552004-05-06 22:04:31 +0000809 assert(progName && "Program name not specified");
810 assert(envVar && "Environment variable name missing");
Misha Brukman10468d82005-04-21 22:55:34 +0000811
Brian Gaeke497216d2003-08-15 21:05:57 +0000812 // Get the environment variable they want us to parse options out of.
Chris Lattner2de6e332006-08-27 22:10:29 +0000813 const char *envValue = getenv(envVar);
Brian Gaeke497216d2003-08-15 21:05:57 +0000814 if (!envValue)
815 return;
816
Brian Gaekeca782d92003-08-14 22:00:59 +0000817 // Get program's "name", which we wouldn't know without the caller
818 // telling us.
Reid Klecknera73c7782013-07-18 16:52:05 +0000819 SmallVector<const char *, 20> newArgv;
Sean Silvadb794842014-08-15 23:39:01 +0000820 StrDupSaver Saver;
821 newArgv.push_back(Saver.SaveString(progName));
Brian Gaekeca782d92003-08-14 22:00:59 +0000822
823 // Parse the value of the environment variable into a "command line"
824 // and hand it off to ParseCommandLineOptions().
Reid Klecknera73c7782013-07-18 16:52:05 +0000825 TokenizeGNUCommandLine(envValue, Saver, newArgv);
Evan Cheng86cb3182008-05-05 18:30:58 +0000826 int newArgc = static_cast<int>(newArgv.size());
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000827 ParseCommandLineOptions(newArgc, &newArgv[0], Overview);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000828}
829
Chris Bieneman5d232242015-01-13 19:14:20 +0000830void cl::ParseCommandLineOptions(int argc, const char *const *argv,
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000831 const char *Overview) {
Chris Bienemand1d94302015-01-28 19:00:25 +0000832 GlobalParser->ParseCommandLineOptions(argc, argv, Overview);
833}
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000834
Chris Bienemand1d94302015-01-28 19:00:25 +0000835void CommandLineParser::ParseCommandLineOptions(int argc,
836 const char *const *argv,
837 const char *Overview) {
838 assert(hasOptions() && "No options specified!");
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000839
840 // Expand response files.
Reid Klecknera73c7782013-07-18 16:52:05 +0000841 SmallVector<const char *, 20> newArgv;
842 for (int i = 0; i != argc; ++i)
Rafael Espindolaa8e7c262013-07-24 14:32:01 +0000843 newArgv.push_back(argv[i]);
Sean Silvadb794842014-08-15 23:39:01 +0000844 StrDupSaver Saver;
Reid Klecknera73c7782013-07-18 16:52:05 +0000845 ExpandResponseFiles(Saver, TokenizeGNUCommandLine, newArgv);
Rafael Espindolabe5613c2012-10-09 19:52:10 +0000846 argv = &newArgv[0];
847 argc = static_cast<int>(newArgv.size());
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000848
Chris Lattner5af1cbc2006-10-13 00:06:24 +0000849 // Copy the program name into ProgName, making sure not to overflow it.
Chris Bienemanb6866422015-01-28 22:25:00 +0000850 ProgramName = sys::path::filename(argv[0]);
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000851
Chris Lattner36a57d32001-07-23 17:17:47 +0000852 ProgramOverview = Overview;
853 bool ErrorParsing = false;
854
Chris Lattner5df56c42002-07-22 02:07:59 +0000855 // Check out the positional arguments to collect information about them.
856 unsigned NumPositionalRequired = 0;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000857
Chris Lattnerd380d842005-08-08 17:25:38 +0000858 // Determine whether or not there are an unlimited number of positionals
859 bool HasUnlimitedPositionals = false;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +0000860
Chris Bienemand1d94302015-01-28 19:00:25 +0000861 if (ConsumeAfterOpt) {
862 assert(PositionalOpts.size() > 0 &&
863 "Cannot specify cl::ConsumeAfter without a positional argument!");
864 }
Chris Lattner5df56c42002-07-22 02:07:59 +0000865 if (!PositionalOpts.empty()) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000866
867 // Calculate how many positional values are _required_.
868 bool UnboundedFound = false;
Chris Bienemand1d94302015-01-28 19:00:25 +0000869 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000870 Option *Opt = PositionalOpts[i];
871 if (RequiresValue(Opt))
872 ++NumPositionalRequired;
873 else if (ConsumeAfterOpt) {
874 // ConsumeAfter cannot be combined with "optional" positional options
Chris Lattnerd49ea882002-07-22 02:21:57 +0000875 // unless there is only one positional argument...
Chris Bienemand1d94302015-01-28 19:00:25 +0000876 if (PositionalOpts.size() > 1)
Chris Bieneman5d232242015-01-13 19:14:20 +0000877 ErrorParsing |= Opt->error(
878 "error - this positional option will never be matched, "
879 "because it does not Require a value, and a "
880 "cl::ConsumeAfter option is active!");
Chris Lattner2da046f2003-07-30 17:34:02 +0000881 } else if (UnboundedFound && !Opt->ArgStr[0]) {
882 // This option does not "require" a value... Make sure this option is
883 // not specified after an option that eats all extra arguments, or this
884 // one will never get any!
Chris Lattner5df56c42002-07-22 02:07:59 +0000885 //
Benjamin Kramer666cf9d2009-08-02 12:13:02 +0000886 ErrorParsing |= Opt->error("error - option can never match, because "
Chris Lattner5df56c42002-07-22 02:07:59 +0000887 "another positional argument will match an "
888 "unbounded number of values, and this option"
889 " does not require a value!");
Chris Bienemand1d94302015-01-28 19:00:25 +0000890 errs() << ProgramName << ": CommandLine Error: Option '" << Opt->ArgStr
891 << "' is all messed up!\n";
892 errs() << PositionalOpts.size();
Chris Lattner5df56c42002-07-22 02:07:59 +0000893 }
894 UnboundedFound |= EatsUnboundedNumberOfValues(Opt);
895 }
Chris Lattnerd09a9a72005-08-08 21:57:27 +0000896 HasUnlimitedPositionals = UnboundedFound || ConsumeAfterOpt;
Chris Lattner5df56c42002-07-22 02:07:59 +0000897 }
898
Reid Spencer2027a6f2004-08-13 19:47:30 +0000899 // PositionalVals - A vector of "positional" arguments we accumulate into
Chris Lattnerca2552d2009-09-20 00:07:40 +0000900 // the process at the end.
Chris Lattner5df56c42002-07-22 02:07:59 +0000901 //
Chris Bieneman5d232242015-01-13 19:14:20 +0000902 SmallVector<std::pair<StringRef, unsigned>, 4> PositionalVals;
Chris Lattner5df56c42002-07-22 02:07:59 +0000903
Chris Lattner2da046f2003-07-30 17:34:02 +0000904 // If the program has named positional arguments, and the name has been run
905 // across, keep track of which positional argument was named. Otherwise put
906 // the positional args into the PositionalVals list...
Craig Topperc10719f2014-04-07 04:17:22 +0000907 Option *ActivePositionalArg = nullptr;
Chris Lattner2da046f2003-07-30 17:34:02 +0000908
Chris Lattner36a57d32001-07-23 17:17:47 +0000909 // Loop over all of the arguments... processing them.
Chris Bieneman5d232242015-01-13 19:14:20 +0000910 bool DashDashFound = false; // Have we read '--'?
Chris Lattner36a57d32001-07-23 17:17:47 +0000911 for (int i = 1; i < argc; ++i) {
Craig Topperc10719f2014-04-07 04:17:22 +0000912 Option *Handler = nullptr;
913 Option *NearestHandler = nullptr;
Nick Lewyckye75ffa12011-05-02 05:24:47 +0000914 std::string NearestHandlerString;
Chris Lattner0a40a972009-09-20 01:53:12 +0000915 StringRef Value;
Chris Lattner5a3fa4e2009-09-20 02:02:24 +0000916 StringRef ArgName = "";
Chris Lattner5df56c42002-07-22 02:07:59 +0000917
918 // Check to see if this is a positional argument. This argument is
919 // considered to be positional if it doesn't start with '-', if it is "-"
Misha Brukman5258e592003-07-10 21:38:28 +0000920 // itself, or if we have seen "--" already.
Chris Lattner5df56c42002-07-22 02:07:59 +0000921 //
922 if (argv[i][0] != '-' || argv[i][1] == 0 || DashDashFound) {
923 // Positional argument!
Chris Lattner2da046f2003-07-30 17:34:02 +0000924 if (ActivePositionalArg) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000925 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000926 continue; // We are done!
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000927 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000928
Chris Lattner3b8adaf2009-09-20 00:40:49 +0000929 if (!PositionalOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000930 PositionalVals.push_back(std::make_pair(argv[i], i));
Chris Lattner5df56c42002-07-22 02:07:59 +0000931
932 // All of the positional arguments have been fulfulled, give the rest to
933 // the consume after option... if it's specified...
934 //
Craig Topper8d399f82014-04-09 04:20:00 +0000935 if (PositionalVals.size() >= NumPositionalRequired && ConsumeAfterOpt) {
Chris Lattner5df56c42002-07-22 02:07:59 +0000936 for (++i; i < argc; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +0000937 PositionalVals.push_back(std::make_pair(argv[i], i));
938 break; // Handle outside of the argument processing loop...
Chris Lattner5df56c42002-07-22 02:07:59 +0000939 }
940
941 // Delay processing positional arguments until the end...
942 continue;
943 }
Chris Lattnera60f3552004-05-06 22:04:31 +0000944 } else if (argv[i][0] == '-' && argv[i][1] == '-' && argv[i][2] == 0 &&
945 !DashDashFound) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000946 DashDashFound = true; // This is the mythical "--"?
947 continue; // Don't try to process it as an argument itself.
Chris Lattnera60f3552004-05-06 22:04:31 +0000948 } else if (ActivePositionalArg &&
949 (ActivePositionalArg->getMiscFlags() & PositionalEatsArgs)) {
950 // If there is a positional argument eating options, check to see if this
951 // option is another positional argument. If so, treat it as an argument,
952 // otherwise feed it to the eating positional.
Chris Bieneman5d232242015-01-13 19:14:20 +0000953 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000954 // Eat leading dashes.
955 while (!ArgName.empty() && ArgName[0] == '-')
956 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000957
Chris Bieneman542f56a2015-02-13 22:54:27 +0000958 Handler = LookupOption(ArgName, Value);
Chris Lattnera60f3552004-05-06 22:04:31 +0000959 if (!Handler || Handler->getFormattingFlag() != cl::Positional) {
Reid Spencer2027a6f2004-08-13 19:47:30 +0000960 ProvidePositionalOption(ActivePositionalArg, argv[i], i);
Chris Bieneman5d232242015-01-13 19:14:20 +0000961 continue; // We are done!
Chris Lattner5df56c42002-07-22 02:07:59 +0000962 }
963
Chris Bieneman5d232242015-01-13 19:14:20 +0000964 } else { // We start with a '-', must be an argument.
965 ArgName = argv[i] + 1;
Chris Lattnere7c1e212009-09-20 05:03:30 +0000966 // Eat leading dashes.
967 while (!ArgName.empty() && ArgName[0] == '-')
968 ArgName = ArgName.substr(1);
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +0000969
Chris Bieneman542f56a2015-02-13 22:54:27 +0000970 Handler = LookupOption(ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +0000971
Chris Lattnera60f3552004-05-06 22:04:31 +0000972 // Check to see if this "option" is really a prefixed or grouped argument.
Craig Topper8d399f82014-04-09 04:20:00 +0000973 if (!Handler)
Chris Bienemand1d94302015-01-28 19:00:25 +0000974 Handler = HandlePrefixedOrGroupedOption(ArgName, Value, ErrorParsing,
975 OptionsMap);
Daniel Dunbarf4132132011-01-18 01:59:24 +0000976
977 // Otherwise, look for the closest available option to report to the user
978 // in the upcoming error.
Craig Topper8d399f82014-04-09 04:20:00 +0000979 if (!Handler && SinkOpts.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +0000980 NearestHandler =
Chris Bienemand1d94302015-01-28 19:00:25 +0000981 LookupNearestOption(ArgName, OptionsMap, NearestHandlerString);
Chris Lattner36a57d32001-07-23 17:17:47 +0000982 }
983
Craig Topper8d399f82014-04-09 04:20:00 +0000984 if (!Handler) {
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000985 if (SinkOpts.empty()) {
Chris Bieneman5d232242015-01-13 19:14:20 +0000986 errs() << ProgramName << ": Unknown command line argument '" << argv[i]
987 << "'. Try: '" << argv[0] << " -help'\n";
Daniel Dunbarf4132132011-01-18 01:59:24 +0000988
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000989 if (NearestHandler) {
990 // If we know a near match, report it as well.
Chris Bieneman5d232242015-01-13 19:14:20 +0000991 errs() << ProgramName << ": Did you mean '-" << NearestHandlerString
992 << "'?\n";
Daniel Dunbar72d523b2011-01-24 17:27:17 +0000993 }
Daniel Dunbarf4132132011-01-18 01:59:24 +0000994
Anton Korobeynikovf275a492008-02-20 12:38:07 +0000995 ErrorParsing = true;
996 } else {
Chris Bieneman5d232242015-01-13 19:14:20 +0000997 for (SmallVectorImpl<Option *>::iterator I = SinkOpts.begin(),
998 E = SinkOpts.end();
999 I != E; ++I)
Anton Korobeynikovf275a492008-02-20 12:38:07 +00001000 (*I)->addOccurrence(i, "", argv[i]);
1001 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001002 continue;
1003 }
1004
Chris Lattner2da046f2003-07-30 17:34:02 +00001005 // If this is a named positional argument, just remember that it is the
1006 // active one...
1007 if (Handler->getFormattingFlag() == cl::Positional)
1008 ActivePositionalArg = Handler;
Chris Lattner40fef802009-09-20 01:49:31 +00001009 else
Chris Lattner0a40a972009-09-20 01:53:12 +00001010 ErrorParsing |= ProvideOption(Handler, ArgName, Value, argc, argv, i);
Chris Lattner5df56c42002-07-22 02:07:59 +00001011 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001012
Chris Lattner5df56c42002-07-22 02:07:59 +00001013 // Check and handle positional arguments now...
1014 if (NumPositionalRequired > PositionalVals.size()) {
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001015 errs() << ProgramName
Chris Bieneman5d232242015-01-13 19:14:20 +00001016 << ": Not enough positional command line arguments specified!\n"
1017 << "Must specify at least " << NumPositionalRequired
1018 << " positional arguments: See: " << argv[0] << " -help\n";
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001019
Chris Lattner5df56c42002-07-22 02:07:59 +00001020 ErrorParsing = true;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001021 } else if (!HasUnlimitedPositionals &&
1022 PositionalVals.size() > PositionalOpts.size()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001023 errs() << ProgramName << ": Too many positional arguments specified!\n"
1024 << "Can specify at most " << PositionalOpts.size()
1025 << " positional arguments: See: " << argv[0] << " -help\n";
Chris Lattnerd380d842005-08-08 17:25:38 +00001026 ErrorParsing = true;
Chris Lattner5df56c42002-07-22 02:07:59 +00001027
Craig Topper8d399f82014-04-09 04:20:00 +00001028 } else if (!ConsumeAfterOpt) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001029 // Positional args have already been handled if ConsumeAfter is specified.
Evan Cheng86cb3182008-05-05 18:30:58 +00001030 unsigned ValNo = 0, NumVals = static_cast<unsigned>(PositionalVals.size());
1031 for (size_t i = 0, e = PositionalOpts.size(); i != e; ++i) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001032 if (RequiresValue(PositionalOpts[i])) {
Misha Brukman10468d82005-04-21 22:55:34 +00001033 ProvidePositionalOption(PositionalOpts[i], PositionalVals[ValNo].first,
Reid Spencer2027a6f2004-08-13 19:47:30 +00001034 PositionalVals[ValNo].second);
1035 ValNo++;
Chris Bieneman5d232242015-01-13 19:14:20 +00001036 --NumPositionalRequired; // We fulfilled our duty...
Chris Lattner5df56c42002-07-22 02:07:59 +00001037 }
1038
1039 // If we _can_ give this option more arguments, do so now, as long as we
1040 // do not give it values that others need. 'Done' controls whether the
1041 // option even _WANTS_ any more.
1042 //
Misha Brukman069e6b52003-07-10 16:49:51 +00001043 bool Done = PositionalOpts[i]->getNumOccurrencesFlag() == cl::Required;
Chris Bieneman5d232242015-01-13 19:14:20 +00001044 while (NumVals - ValNo > NumPositionalRequired && !Done) {
Misha Brukman069e6b52003-07-10 16:49:51 +00001045 switch (PositionalOpts[i]->getNumOccurrencesFlag()) {
Chris Lattner5df56c42002-07-22 02:07:59 +00001046 case cl::Optional:
Chris Bieneman5d232242015-01-13 19:14:20 +00001047 Done = true; // Optional arguments want _at most_ one value
1048 // FALL THROUGH
1049 case cl::ZeroOrMore: // Zero or more will take all they can get...
1050 case cl::OneOrMore: // One or more will take all they can get...
Reid Spencer2027a6f2004-08-13 19:47:30 +00001051 ProvidePositionalOption(PositionalOpts[i],
1052 PositionalVals[ValNo].first,
1053 PositionalVals[ValNo].second);
1054 ValNo++;
Chris Lattner5df56c42002-07-22 02:07:59 +00001055 break;
1056 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001057 llvm_unreachable("Internal error, unexpected NumOccurrences flag in "
Chris Bieneman5d232242015-01-13 19:14:20 +00001058 "positional argument processing!");
Chris Lattner5df56c42002-07-22 02:07:59 +00001059 }
1060 }
Chris Lattnere81c4092001-10-27 05:54:17 +00001061 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001062 } else {
1063 assert(ConsumeAfterOpt && NumPositionalRequired <= PositionalVals.size());
1064 unsigned ValNo = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001065 for (size_t j = 1, e = PositionalOpts.size(); j != e; ++j)
Reid Spencer2027a6f2004-08-13 19:47:30 +00001066 if (RequiresValue(PositionalOpts[j])) {
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001067 ErrorParsing |= ProvidePositionalOption(PositionalOpts[j],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001068 PositionalVals[ValNo].first,
1069 PositionalVals[ValNo].second);
1070 ValNo++;
1071 }
Chris Lattnerca0e79e2002-07-24 20:15:13 +00001072
1073 // Handle the case where there is just one positional option, and it's
1074 // optional. In this case, we want to give JUST THE FIRST option to the
1075 // positional option and keep the rest for the consume after. The above
1076 // loop would have assigned no values to positional options in this case.
1077 //
Chris Bienemand1d94302015-01-28 19:00:25 +00001078 if (PositionalOpts.size() == 1 && ValNo == 0 && !PositionalVals.empty()) {
1079 ErrorParsing |= ProvidePositionalOption(PositionalOpts[0],
Reid Spencer2027a6f2004-08-13 19:47:30 +00001080 PositionalVals[ValNo].first,
1081 PositionalVals[ValNo].second);
1082 ValNo++;
1083 }
Misha Brukman10468d82005-04-21 22:55:34 +00001084
Chris Lattner5df56c42002-07-22 02:07:59 +00001085 // Handle over all of the rest of the arguments to the
1086 // cl::ConsumeAfter command line option...
1087 for (; ValNo != PositionalVals.size(); ++ValNo)
Chris Bieneman5d232242015-01-13 19:14:20 +00001088 ErrorParsing |=
1089 ProvidePositionalOption(ConsumeAfterOpt, PositionalVals[ValNo].first,
1090 PositionalVals[ValNo].second);
Chris Lattner36a57d32001-07-23 17:17:47 +00001091 }
1092
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001093 // Loop over args and make sure all required args are specified!
Chris Bienemand1d94302015-01-28 19:00:25 +00001094 for (const auto &Opt : OptionsMap) {
Justin Bogner973b2ff2014-07-14 19:24:13 +00001095 switch (Opt.second->getNumOccurrencesFlag()) {
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001096 case Required:
1097 case OneOrMore:
Justin Bogner973b2ff2014-07-14 19:24:13 +00001098 if (Opt.second->getNumOccurrences() == 0) {
1099 Opt.second->error("must be specified at least once!");
Chris Lattnerd4617cd2001-10-24 06:21:56 +00001100 ErrorParsing = true;
1101 }
Chris Bieneman5d232242015-01-13 19:14:20 +00001102 // Fall through
Chris Lattner4fdde2c2001-07-23 23:02:45 +00001103 default:
1104 break;
1105 }
1106 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001107
Rafael Espindolacf14a382010-11-19 21:14:29 +00001108 // Now that we know if -debug is specified, we can use it.
1109 // Note that if ReadResponseFiles == true, this must be done before the
1110 // memory allocated for the expanded command line is free()d below.
1111 DEBUG(dbgs() << "Args: ";
Chris Bieneman5d232242015-01-13 19:14:20 +00001112 for (int i = 0; i < argc; ++i) dbgs() << argv[i] << ' ';
1113 dbgs() << '\n';);
Rafael Espindolacf14a382010-11-19 21:14:29 +00001114
Chris Lattner5df56c42002-07-22 02:07:59 +00001115 // Free all of the memory allocated to the map. Command line options may only
1116 // be processed once!
Chris Bienemand1d94302015-01-28 19:00:25 +00001117 MoreHelp.clear();
Chris Lattner36a57d32001-07-23 17:17:47 +00001118
1119 // If we had an error processing our arguments, don't let the program execute
Chris Bieneman5d232242015-01-13 19:14:20 +00001120 if (ErrorParsing)
1121 exit(1);
Chris Lattner36a57d32001-07-23 17:17:47 +00001122}
1123
1124//===----------------------------------------------------------------------===//
1125// Option Base class implementation
1126//
Chris Lattner36a57d32001-07-23 17:17:47 +00001127
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001128bool Option::error(const Twine &Message, StringRef ArgName) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001129 if (!ArgName.data())
1130 ArgName = ArgStr;
Chris Lattner3b8adaf2009-09-20 00:40:49 +00001131 if (ArgName.empty())
Chris Bieneman5d232242015-01-13 19:14:20 +00001132 errs() << HelpStr; // Be nice for positional arguments
Chris Lattner5df56c42002-07-22 02:07:59 +00001133 else
Chris Bienemand1d94302015-01-28 19:00:25 +00001134 errs() << GlobalParser->ProgramName << ": for the -" << ArgName;
Mikhail Glushenkov5653d3b2008-04-28 16:44:25 +00001135
Benjamin Kramerc9aa4802009-08-23 10:01:13 +00001136 errs() << " option: " << Message << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001137 return true;
1138}
1139
Chris Bieneman5d232242015-01-13 19:14:20 +00001140bool Option::addOccurrence(unsigned pos, StringRef ArgName, StringRef Value,
1141 bool MultiArg) {
Mikhail Glushenkovcbc26fd2009-01-16 22:54:19 +00001142 if (!MultiArg)
Chris Bieneman5d232242015-01-13 19:14:20 +00001143 NumOccurrences++; // Increment the number of times we have been seen
Chris Lattner36a57d32001-07-23 17:17:47 +00001144
Misha Brukman069e6b52003-07-10 16:49:51 +00001145 switch (getNumOccurrencesFlag()) {
Chris Lattner36a57d32001-07-23 17:17:47 +00001146 case Optional:
Misha Brukman069e6b52003-07-10 16:49:51 +00001147 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001148 return error("may only occur zero or one times!", ArgName);
Chris Lattner36a57d32001-07-23 17:17:47 +00001149 break;
1150 case Required:
Misha Brukman069e6b52003-07-10 16:49:51 +00001151 if (NumOccurrences > 1)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001152 return error("must occur exactly one time!", ArgName);
Chris Bieneman5d232242015-01-13 19:14:20 +00001153 // Fall through
Chris Lattner36a57d32001-07-23 17:17:47 +00001154 case OneOrMore:
Chris Lattnere81c4092001-10-27 05:54:17 +00001155 case ZeroOrMore:
Chris Bieneman5d232242015-01-13 19:14:20 +00001156 case ConsumeAfter:
1157 break;
Chris Lattner36a57d32001-07-23 17:17:47 +00001158 }
1159
Reid Spencer2027a6f2004-08-13 19:47:30 +00001160 return handleOccurrence(pos, ArgName, Value);
Chris Lattner36a57d32001-07-23 17:17:47 +00001161}
1162
Chris Lattner5df56c42002-07-22 02:07:59 +00001163// getValueStr - Get the value description string, using "DefaultMsg" if nothing
1164// has been specified yet.
1165//
1166static const char *getValueStr(const Option &O, const char *DefaultMsg) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001167 if (O.ValueStr[0] == 0)
1168 return DefaultMsg;
Chris Lattner5df56c42002-07-22 02:07:59 +00001169 return O.ValueStr;
1170}
1171
1172//===----------------------------------------------------------------------===//
1173// cl::alias class implementation
1174//
1175
Chris Lattner36a57d32001-07-23 17:17:47 +00001176// Return the width of the option tag for printing...
Chris Bieneman5d232242015-01-13 19:14:20 +00001177size_t alias::getOptionWidth() const { return std::strlen(ArgStr) + 6; }
Chris Lattner36a57d32001-07-23 17:17:47 +00001178
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001179static void printHelpStr(StringRef HelpStr, size_t Indent,
1180 size_t FirstLineIndentedBy) {
1181 std::pair<StringRef, StringRef> Split = HelpStr.split('\n');
1182 outs().indent(Indent - FirstLineIndentedBy) << " - " << Split.first << "\n";
1183 while (!Split.second.empty()) {
1184 Split = Split.second.split('\n');
1185 outs().indent(Indent) << Split.first << "\n";
1186 }
1187}
1188
Chris Lattner1b7a5152006-04-28 05:36:25 +00001189// Print out the option for the alias.
Evan Cheng86cb3182008-05-05 18:30:58 +00001190void alias::printOptionInfo(size_t GlobalWidth) const {
Evan Cheng871b7122011-06-13 20:45:54 +00001191 outs() << " -" << ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001192 printHelpStr(HelpStr, GlobalWidth, std::strlen(ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001193}
1194
Chris Lattner36a57d32001-07-23 17:17:47 +00001195//===----------------------------------------------------------------------===//
Chris Lattner5df56c42002-07-22 02:07:59 +00001196// Parser Implementation code...
Chris Lattner36a57d32001-07-23 17:17:47 +00001197//
1198
Chris Lattnerb4101b12002-08-07 18:36:37 +00001199// basic_parser implementation
1200//
1201
1202// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001203size_t basic_parser_impl::getOptionWidth(const Option &O) const {
1204 size_t Len = std::strlen(O.ArgStr);
Chris Lattnerb4101b12002-08-07 18:36:37 +00001205 if (const char *ValName = getValueName())
Chris Bieneman5d232242015-01-13 19:14:20 +00001206 Len += std::strlen(getValueStr(O, ValName)) + 3;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001207
1208 return Len + 6;
1209}
1210
Misha Brukman10468d82005-04-21 22:55:34 +00001211// printOptionInfo - Print out information about this option. The
Chris Lattnerb4101b12002-08-07 18:36:37 +00001212// to-be-maintained width is specified.
1213//
1214void basic_parser_impl::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001215 size_t GlobalWidth) const {
Chris Lattner471ba482009-08-23 08:43:55 +00001216 outs() << " -" << O.ArgStr;
Chris Lattnerb4101b12002-08-07 18:36:37 +00001217
1218 if (const char *ValName = getValueName())
Chris Lattner471ba482009-08-23 08:43:55 +00001219 outs() << "=<" << getValueStr(O, ValName) << '>';
Chris Lattnerb4101b12002-08-07 18:36:37 +00001220
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001221 printHelpStr(O.HelpStr, GlobalWidth, getOptionWidth(O));
Chris Lattnerb4101b12002-08-07 18:36:37 +00001222}
1223
Andrew Trick12004012011-04-05 18:54:36 +00001224void basic_parser_impl::printOptionName(const Option &O,
1225 size_t GlobalWidth) const {
1226 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001227 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001228}
Chris Lattnerb4101b12002-08-07 18:36:37 +00001229
Chris Lattner5df56c42002-07-22 02:07:59 +00001230// parser<bool> implementation
1231//
Chris Bieneman5d232242015-01-13 19:14:20 +00001232bool parser<bool>::parse(Option &O, StringRef ArgName, StringRef Arg,
1233 bool &Value) {
Misha Brukman10468d82005-04-21 22:55:34 +00001234 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
Chris Lattner36a57d32001-07-23 17:17:47 +00001235 Arg == "1") {
1236 Value = true;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001237 return false;
Chris Lattner36a57d32001-07-23 17:17:47 +00001238 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001239
Chris Lattneraecd74d2009-09-19 18:55:05 +00001240 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1241 Value = false;
1242 return false;
1243 }
1244 return O.error("'" + Arg +
1245 "' is invalid value for boolean argument! Try 0 or 1");
Chris Lattner36a57d32001-07-23 17:17:47 +00001246}
1247
Dale Johannesen82810c82007-05-22 17:14:46 +00001248// parser<boolOrDefault> implementation
1249//
Chris Bieneman5d232242015-01-13 19:14:20 +00001250bool parser<boolOrDefault>::parse(Option &O, StringRef ArgName, StringRef Arg,
1251 boolOrDefault &Value) {
Dale Johannesen82810c82007-05-22 17:14:46 +00001252 if (Arg == "" || Arg == "true" || Arg == "TRUE" || Arg == "True" ||
1253 Arg == "1") {
1254 Value = BOU_TRUE;
Chris Lattneraecd74d2009-09-19 18:55:05 +00001255 return false;
Dale Johannesen82810c82007-05-22 17:14:46 +00001256 }
Chris Lattneraecd74d2009-09-19 18:55:05 +00001257 if (Arg == "false" || Arg == "FALSE" || Arg == "False" || Arg == "0") {
1258 Value = BOU_FALSE;
1259 return false;
1260 }
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001261
Chris Lattneraecd74d2009-09-19 18:55:05 +00001262 return O.error("'" + Arg +
1263 "' is invalid value for boolean argument! Try 0 or 1");
Dale Johannesen82810c82007-05-22 17:14:46 +00001264}
1265
Chris Lattner5df56c42002-07-22 02:07:59 +00001266// parser<int> implementation
1267//
Chris Bieneman5d232242015-01-13 19:14:20 +00001268bool parser<int>::parse(Option &O, StringRef ArgName, StringRef Arg,
1269 int &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001270 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001271 return O.error("'" + Arg + "' value invalid for integer argument!");
Chris Lattner36a57d32001-07-23 17:17:47 +00001272 return false;
1273}
1274
Chris Lattner719c7152003-06-28 15:47:20 +00001275// parser<unsigned> implementation
1276//
Chris Bieneman5d232242015-01-13 19:14:20 +00001277bool parser<unsigned>::parse(Option &O, StringRef ArgName, StringRef Arg,
1278 unsigned &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001279
1280 if (Arg.getAsInteger(0, Value))
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001281 return O.error("'" + Arg + "' value invalid for uint argument!");
Chris Lattner719c7152003-06-28 15:47:20 +00001282 return false;
1283}
1284
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001285// parser<unsigned long long> implementation
1286//
1287bool parser<unsigned long long>::parse(Option &O, StringRef ArgName,
Chris Bieneman5d232242015-01-13 19:14:20 +00001288 StringRef Arg,
1289 unsigned long long &Value) {
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001290
1291 if (Arg.getAsInteger(0, Value))
1292 return O.error("'" + Arg + "' value invalid for uint argument!");
1293 return false;
1294}
1295
Chris Lattnerb4101b12002-08-07 18:36:37 +00001296// parser<double>/parser<float> implementation
Chris Lattner675db8d2001-10-13 06:53:19 +00001297//
Chris Lattneraecd74d2009-09-19 18:55:05 +00001298static bool parseDouble(Option &O, StringRef Arg, double &Value) {
Chris Lattnerfa9c6f42009-09-19 23:59:02 +00001299 SmallString<32> TmpStr(Arg.begin(), Arg.end());
1300 const char *ArgStart = TmpStr.c_str();
Chris Lattner5df56c42002-07-22 02:07:59 +00001301 char *End;
1302 Value = strtod(ArgStart, &End);
Misha Brukman10468d82005-04-21 22:55:34 +00001303 if (*End != 0)
Benjamin Kramer666cf9d2009-08-02 12:13:02 +00001304 return O.error("'" + Arg + "' value invalid for floating point argument!");
Chris Lattner675db8d2001-10-13 06:53:19 +00001305 return false;
1306}
1307
Chris Bieneman5d232242015-01-13 19:14:20 +00001308bool parser<double>::parse(Option &O, StringRef ArgName, StringRef Arg,
1309 double &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001310 return parseDouble(O, Arg, Val);
Chris Lattner5df56c42002-07-22 02:07:59 +00001311}
1312
Chris Bieneman5d232242015-01-13 19:14:20 +00001313bool parser<float>::parse(Option &O, StringRef ArgName, StringRef Arg,
1314 float &Val) {
Chris Lattnerb4101b12002-08-07 18:36:37 +00001315 double dVal;
1316 if (parseDouble(O, Arg, dVal))
1317 return true;
1318 Val = (float)dVal;
1319 return false;
Chris Lattner5df56c42002-07-22 02:07:59 +00001320}
1321
Chris Lattner5df56c42002-07-22 02:07:59 +00001322// generic_parser_base implementation
1323//
1324
Chris Lattner494c0b02002-07-23 17:15:12 +00001325// findOption - Return the option number corresponding to the specified
1326// argument string. If the option is not found, getNumOptions() is returned.
1327//
1328unsigned generic_parser_base::findOption(const char *Name) {
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001329 unsigned e = getNumOptions();
Chris Lattner494c0b02002-07-23 17:15:12 +00001330
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001331 for (unsigned i = 0; i != e; ++i) {
1332 if (strcmp(getOption(i), Name) == 0)
Chris Lattner494c0b02002-07-23 17:15:12 +00001333 return i;
Benjamin Kramer543d9b22009-09-19 10:01:45 +00001334 }
Chris Lattner494c0b02002-07-23 17:15:12 +00001335 return e;
1336}
1337
Chris Lattner5df56c42002-07-22 02:07:59 +00001338// Return the width of the option tag for printing...
Evan Cheng86cb3182008-05-05 18:30:58 +00001339size_t generic_parser_base::getOptionWidth(const Option &O) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001340 if (O.hasArgStr()) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001341 size_t Size = std::strlen(O.ArgStr) + 6;
Chris Lattner5df56c42002-07-22 02:07:59 +00001342 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001343 Size = std::max(Size, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001344 return Size;
1345 } else {
Evan Cheng86cb3182008-05-05 18:30:58 +00001346 size_t BaseSize = 0;
Chris Lattner5df56c42002-07-22 02:07:59 +00001347 for (unsigned i = 0, e = getNumOptions(); i != e; ++i)
Chris Bieneman5d232242015-01-13 19:14:20 +00001348 BaseSize = std::max(BaseSize, std::strlen(getOption(i)) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001349 return BaseSize;
Chris Lattner36a57d32001-07-23 17:17:47 +00001350 }
1351}
1352
Misha Brukman10468d82005-04-21 22:55:34 +00001353// printOptionInfo - Print out information about this option. The
Chris Lattner5df56c42002-07-22 02:07:59 +00001354// to-be-maintained width is specified.
1355//
1356void generic_parser_base::printOptionInfo(const Option &O,
Evan Cheng86cb3182008-05-05 18:30:58 +00001357 size_t GlobalWidth) const {
Chris Lattner5df56c42002-07-22 02:07:59 +00001358 if (O.hasArgStr()) {
Chris Lattnere7c1e212009-09-20 05:03:30 +00001359 outs() << " -" << O.ArgStr;
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001360 printHelpStr(O.HelpStr, GlobalWidth, std::strlen(O.ArgStr) + 6);
Chris Lattner36a57d32001-07-23 17:17:47 +00001361
Chris Lattner5df56c42002-07-22 02:07:59 +00001362 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001363 size_t NumSpaces = GlobalWidth - strlen(getOption(i)) - 8;
Chris Lattnere7c1e212009-09-20 05:03:30 +00001364 outs() << " =" << getOption(i);
1365 outs().indent(NumSpaces) << " - " << getDescription(i) << '\n';
Chris Lattnerc2ef08c2002-01-31 00:42:56 +00001366 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001367 } else {
1368 if (O.HelpStr[0])
Chris Lattnere7c1e212009-09-20 05:03:30 +00001369 outs() << " " << O.HelpStr << '\n';
Chris Lattner5df56c42002-07-22 02:07:59 +00001370 for (unsigned i = 0, e = getNumOptions(); i != e; ++i) {
Alexander Kornienko72a196a2013-05-10 17:15:51 +00001371 const char *Option = getOption(i);
1372 outs() << " -" << Option;
1373 printHelpStr(getDescription(i), GlobalWidth, std::strlen(Option) + 8);
Chris Lattner5df56c42002-07-22 02:07:59 +00001374 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001375 }
1376}
1377
Andrew Trick12004012011-04-05 18:54:36 +00001378static const size_t MaxOptWidth = 8; // arbitrary spacing for printOptionDiff
1379
1380// printGenericOptionDiff - Print the value of this option and it's default.
1381//
1382// "Generic" options have each value mapped to a name.
Chris Bieneman5d232242015-01-13 19:14:20 +00001383void generic_parser_base::printGenericOptionDiff(
1384 const Option &O, const GenericOptionValue &Value,
1385 const GenericOptionValue &Default, size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001386 outs() << " -" << O.ArgStr;
Chris Bieneman5d232242015-01-13 19:14:20 +00001387 outs().indent(GlobalWidth - std::strlen(O.ArgStr));
Andrew Trick12004012011-04-05 18:54:36 +00001388
1389 unsigned NumOpts = getNumOptions();
1390 for (unsigned i = 0; i != NumOpts; ++i) {
1391 if (Value.compare(getOptionValue(i)))
1392 continue;
1393
1394 outs() << "= " << getOption(i);
1395 size_t L = std::strlen(getOption(i));
1396 size_t NumSpaces = MaxOptWidth > L ? MaxOptWidth - L : 0;
1397 outs().indent(NumSpaces) << " (default: ";
1398 for (unsigned j = 0; j != NumOpts; ++j) {
1399 if (Default.compare(getOptionValue(j)))
1400 continue;
1401 outs() << getOption(j);
1402 break;
1403 }
1404 outs() << ")\n";
1405 return;
1406 }
1407 outs() << "= *unknown option value*\n";
1408}
1409
1410// printOptionDiff - Specializations for printing basic value types.
1411//
Chris Bieneman5d232242015-01-13 19:14:20 +00001412#define PRINT_OPT_DIFF(T) \
1413 void parser<T>::printOptionDiff(const Option &O, T V, OptionValue<T> D, \
1414 size_t GlobalWidth) const { \
1415 printOptionName(O, GlobalWidth); \
1416 std::string Str; \
1417 { \
1418 raw_string_ostream SS(Str); \
1419 SS << V; \
1420 } \
1421 outs() << "= " << Str; \
1422 size_t NumSpaces = \
1423 MaxOptWidth > Str.size() ? MaxOptWidth - Str.size() : 0; \
1424 outs().indent(NumSpaces) << " (default: "; \
1425 if (D.hasValue()) \
1426 outs() << D.getValue(); \
1427 else \
1428 outs() << "*no default*"; \
1429 outs() << ")\n"; \
1430 }
Andrew Trick12004012011-04-05 18:54:36 +00001431
Frits van Bommel87e33672011-04-06 12:29:56 +00001432PRINT_OPT_DIFF(bool)
1433PRINT_OPT_DIFF(boolOrDefault)
1434PRINT_OPT_DIFF(int)
1435PRINT_OPT_DIFF(unsigned)
Benjamin Kramer49fc9dd2011-09-15 21:17:37 +00001436PRINT_OPT_DIFF(unsigned long long)
Frits van Bommel87e33672011-04-06 12:29:56 +00001437PRINT_OPT_DIFF(double)
1438PRINT_OPT_DIFF(float)
1439PRINT_OPT_DIFF(char)
Andrew Trick12004012011-04-05 18:54:36 +00001440
Chris Bieneman5d232242015-01-13 19:14:20 +00001441void parser<std::string>::printOptionDiff(const Option &O, StringRef V,
1442 OptionValue<std::string> D,
1443 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001444 printOptionName(O, GlobalWidth);
1445 outs() << "= " << V;
1446 size_t NumSpaces = MaxOptWidth > V.size() ? MaxOptWidth - V.size() : 0;
1447 outs().indent(NumSpaces) << " (default: ";
1448 if (D.hasValue())
1449 outs() << D.getValue();
1450 else
1451 outs() << "*no default*";
1452 outs() << ")\n";
1453}
1454
1455// Print a placeholder for options that don't yet support printOptionDiff().
Chris Bieneman5d232242015-01-13 19:14:20 +00001456void basic_parser_impl::printOptionNoValue(const Option &O,
1457 size_t GlobalWidth) const {
Andrew Trick12004012011-04-05 18:54:36 +00001458 printOptionName(O, GlobalWidth);
1459 outs() << "= *cannot print option value*\n";
1460}
Chris Lattner36a57d32001-07-23 17:17:47 +00001461
1462//===----------------------------------------------------------------------===//
Duncan Sands142b9ed2010-02-18 14:08:13 +00001463// -help and -help-hidden option implementation
Chris Lattner36a57d32001-07-23 17:17:47 +00001464//
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001465
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001466static int OptNameCompare(const void *LHS, const void *RHS) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001467 typedef std::pair<const char *, Option *> pair_ty;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001468
Chris Bieneman5d232242015-01-13 19:14:20 +00001469 return strcmp(((const pair_ty *)LHS)->first, ((const pair_ty *)RHS)->first);
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001470}
1471
Andrew Trick12004012011-04-05 18:54:36 +00001472// Copy Options into a vector so we can sort them as we like.
Chris Bieneman5d232242015-01-13 19:14:20 +00001473static void sortOpts(StringMap<Option *> &OptMap,
1474 SmallVectorImpl<std::pair<const char *, Option *>> &Opts,
1475 bool ShowHidden) {
1476 SmallPtrSet<Option *, 128> OptionSet; // Duplicate option detection.
Andrew Trick12004012011-04-05 18:54:36 +00001477
Chris Bieneman5d232242015-01-13 19:14:20 +00001478 for (StringMap<Option *>::iterator I = OptMap.begin(), E = OptMap.end();
Andrew Trick12004012011-04-05 18:54:36 +00001479 I != E; ++I) {
1480 // Ignore really-hidden options.
1481 if (I->second->getOptionHiddenFlag() == ReallyHidden)
1482 continue;
1483
1484 // Unless showhidden is set, ignore hidden flags.
1485 if (I->second->getOptionHiddenFlag() == Hidden && !ShowHidden)
1486 continue;
1487
1488 // If we've already seen this option, don't add it to the list again.
David Blaikie70573dc2014-11-19 07:49:26 +00001489 if (!OptionSet.insert(I->second).second)
Andrew Trick12004012011-04-05 18:54:36 +00001490 continue;
1491
Chris Bieneman5d232242015-01-13 19:14:20 +00001492 Opts.push_back(
1493 std::pair<const char *, Option *>(I->getKey().data(), I->second));
Andrew Trick12004012011-04-05 18:54:36 +00001494 }
1495
1496 // Sort the options list alphabetically.
1497 qsort(Opts.data(), Opts.size(), sizeof(Opts[0]), OptNameCompare);
1498}
1499
Chris Lattner36a57d32001-07-23 17:17:47 +00001500namespace {
1501
Chris Lattner5df56c42002-07-22 02:07:59 +00001502class HelpPrinter {
Andrew Trick0537a982013-05-06 21:56:23 +00001503protected:
Chris Lattner36a57d32001-07-23 17:17:47 +00001504 const bool ShowHidden;
Chris Bieneman5d232242015-01-13 19:14:20 +00001505 typedef SmallVector<std::pair<const char *, Option *>, 128>
1506 StrOptionPairVector;
Andrew Trick0537a982013-05-06 21:56:23 +00001507 // Print the options. Opts is assumed to be alphabetically sorted.
1508 virtual void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) {
1509 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1510 Opts[i].second->printOptionInfo(MaxArgLen);
1511 }
Chris Lattner36a57d32001-07-23 17:17:47 +00001512
Chris Lattner5df56c42002-07-22 02:07:59 +00001513public:
Craig Topperfa9888f2013-03-09 23:29:37 +00001514 explicit HelpPrinter(bool showHidden) : ShowHidden(showHidden) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001515 virtual ~HelpPrinter() {}
Chris Lattner5df56c42002-07-22 02:07:59 +00001516
Andrew Trick0537a982013-05-06 21:56:23 +00001517 // Invoke the printer.
Chris Lattner5df56c42002-07-22 02:07:59 +00001518 void operator=(bool Value) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001519 if (Value == false)
1520 return;
Chris Lattner5df56c42002-07-22 02:07:59 +00001521
Andrew Trick0537a982013-05-06 21:56:23 +00001522 StrOptionPairVector Opts;
Chris Bienemand1d94302015-01-28 19:00:25 +00001523 sortOpts(GlobalParser->OptionsMap, Opts, ShowHidden);
Chris Lattner36a57d32001-07-23 17:17:47 +00001524
Chris Bienemand1d94302015-01-28 19:00:25 +00001525 if (GlobalParser->ProgramOverview)
1526 outs() << "OVERVIEW: " << GlobalParser->ProgramOverview << "\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001527
Chris Bienemand1d94302015-01-28 19:00:25 +00001528 outs() << "USAGE: " << GlobalParser->ProgramName << " [options]";
Chris Lattner5df56c42002-07-22 02:07:59 +00001529
Chris Bienemand1d94302015-01-28 19:00:25 +00001530 for (auto Opt : GlobalParser->PositionalOpts) {
1531 if (Opt->ArgStr[0])
1532 outs() << " --" << Opt->ArgStr;
1533 outs() << " " << Opt->HelpStr;
Chris Lattner2da046f2003-07-30 17:34:02 +00001534 }
Chris Lattner5df56c42002-07-22 02:07:59 +00001535
1536 // Print the consume after option info if it exists...
Chris Bienemand1d94302015-01-28 19:00:25 +00001537 if (GlobalParser->ConsumeAfterOpt)
1538 outs() << " " << GlobalParser->ConsumeAfterOpt->HelpStr;
Chris Lattner5df56c42002-07-22 02:07:59 +00001539
Chris Lattner471ba482009-08-23 08:43:55 +00001540 outs() << "\n\n";
Chris Lattner36a57d32001-07-23 17:17:47 +00001541
1542 // Compute the maximum argument length...
Craig Topperfa9888f2013-03-09 23:29:37 +00001543 size_t MaxArgLen = 0;
Evan Cheng86cb3182008-05-05 18:30:58 +00001544 for (size_t i = 0, e = Opts.size(); i != e; ++i)
Chris Lattner6ec8caf2009-09-20 05:37:24 +00001545 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
Chris Lattner36a57d32001-07-23 17:17:47 +00001546
Chris Lattner471ba482009-08-23 08:43:55 +00001547 outs() << "OPTIONS:\n";
Andrew Trick0537a982013-05-06 21:56:23 +00001548 printOptions(Opts, MaxArgLen);
Chris Lattner36a57d32001-07-23 17:17:47 +00001549
Chris Lattner37bcd992004-11-19 17:08:15 +00001550 // Print any extra help the user has declared.
Chris Bienemand1d94302015-01-28 19:00:25 +00001551 for (auto I : GlobalParser->MoreHelp)
1552 outs() << I;
1553 GlobalParser->MoreHelp.clear();
Reid Spencer1f4ab8b2004-11-14 22:04:00 +00001554
Reid Spencer5e554702004-11-16 06:11:52 +00001555 // Halt the program since help information was printed
Justin Bogner02b95842014-02-28 19:08:01 +00001556 exit(0);
Chris Lattner36a57d32001-07-23 17:17:47 +00001557 }
1558};
Andrew Trick0537a982013-05-06 21:56:23 +00001559
1560class CategorizedHelpPrinter : public HelpPrinter {
1561public:
1562 explicit CategorizedHelpPrinter(bool showHidden) : HelpPrinter(showHidden) {}
1563
1564 // Helper function for printOptions().
1565 // It shall return true if A's name should be lexographically
1566 // ordered before B's name. It returns false otherwise.
1567 static bool OptionCategoryCompare(OptionCategory *A, OptionCategory *B) {
Alexander Kornienkod772d722014-02-07 17:42:30 +00001568 return strcmp(A->getName(), B->getName()) < 0;
Andrew Trick0537a982013-05-06 21:56:23 +00001569 }
1570
1571 // Make sure we inherit our base class's operator=()
Chris Bieneman5d232242015-01-13 19:14:20 +00001572 using HelpPrinter::operator=;
Andrew Trick0537a982013-05-06 21:56:23 +00001573
1574protected:
Craig Topper32ea8262014-03-04 06:24:11 +00001575 void printOptions(StrOptionPairVector &Opts, size_t MaxArgLen) override {
Andrew Trick0537a982013-05-06 21:56:23 +00001576 std::vector<OptionCategory *> SortedCategories;
Chris Bieneman5d232242015-01-13 19:14:20 +00001577 std::map<OptionCategory *, std::vector<Option *>> CategorizedOptions;
Andrew Trick0537a982013-05-06 21:56:23 +00001578
Alp Tokercb402912014-01-24 17:20:08 +00001579 // Collect registered option categories into vector in preparation for
Andrew Trick0537a982013-05-06 21:56:23 +00001580 // sorting.
1581 for (OptionCatSet::const_iterator I = RegisteredOptionCategories->begin(),
1582 E = RegisteredOptionCategories->end();
Alexander Kornienkod772d722014-02-07 17:42:30 +00001583 I != E; ++I) {
Andrew Trick0537a982013-05-06 21:56:23 +00001584 SortedCategories.push_back(*I);
Alexander Kornienkod772d722014-02-07 17:42:30 +00001585 }
Andrew Trick0537a982013-05-06 21:56:23 +00001586
1587 // Sort the different option categories alphabetically.
1588 assert(SortedCategories.size() > 0 && "No option categories registered!");
1589 std::sort(SortedCategories.begin(), SortedCategories.end(),
1590 OptionCategoryCompare);
1591
1592 // Create map to empty vectors.
1593 for (std::vector<OptionCategory *>::const_iterator
1594 I = SortedCategories.begin(),
1595 E = SortedCategories.end();
1596 I != E; ++I)
1597 CategorizedOptions[*I] = std::vector<Option *>();
1598
1599 // Walk through pre-sorted options and assign into categories.
1600 // Because the options are already alphabetically sorted the
1601 // options within categories will also be alphabetically sorted.
1602 for (size_t I = 0, E = Opts.size(); I != E; ++I) {
1603 Option *Opt = Opts[I].second;
1604 assert(CategorizedOptions.count(Opt->Category) > 0 &&
1605 "Option has an unregistered category");
1606 CategorizedOptions[Opt->Category].push_back(Opt);
1607 }
1608
1609 // Now do printing.
1610 for (std::vector<OptionCategory *>::const_iterator
1611 Category = SortedCategories.begin(),
1612 E = SortedCategories.end();
1613 Category != E; ++Category) {
1614 // Hide empty categories for -help, but show for -help-hidden.
1615 bool IsEmptyCategory = CategorizedOptions[*Category].size() == 0;
1616 if (!ShowHidden && IsEmptyCategory)
1617 continue;
1618
1619 // Print category information.
1620 outs() << "\n";
1621 outs() << (*Category)->getName() << ":\n";
1622
1623 // Check if description is set.
Craig Topperc10719f2014-04-07 04:17:22 +00001624 if ((*Category)->getDescription() != nullptr)
Andrew Trick0537a982013-05-06 21:56:23 +00001625 outs() << (*Category)->getDescription() << "\n\n";
1626 else
1627 outs() << "\n";
1628
1629 // When using -help-hidden explicitly state if the category has no
1630 // options associated with it.
1631 if (IsEmptyCategory) {
1632 outs() << " This option category has no options.\n";
1633 continue;
1634 }
1635 // Loop over the options in the category and print.
1636 for (std::vector<Option *>::const_iterator
1637 Opt = CategorizedOptions[*Category].begin(),
1638 E = CategorizedOptions[*Category].end();
1639 Opt != E; ++Opt)
1640 (*Opt)->printOptionInfo(MaxArgLen);
1641 }
1642 }
1643};
1644
1645// This wraps the Uncategorizing and Categorizing printers and decides
1646// at run time which should be invoked.
1647class HelpPrinterWrapper {
1648private:
1649 HelpPrinter &UncategorizedPrinter;
1650 CategorizedHelpPrinter &CategorizedPrinter;
1651
1652public:
1653 explicit HelpPrinterWrapper(HelpPrinter &UncategorizedPrinter,
Chris Bieneman5d232242015-01-13 19:14:20 +00001654 CategorizedHelpPrinter &CategorizedPrinter)
1655 : UncategorizedPrinter(UncategorizedPrinter),
1656 CategorizedPrinter(CategorizedPrinter) {}
Andrew Trick0537a982013-05-06 21:56:23 +00001657
1658 // Invoke the printer.
1659 void operator=(bool Value);
1660};
1661
Chris Lattneradb19d62006-10-12 22:09:17 +00001662} // End anonymous namespace
Chris Lattner36a57d32001-07-23 17:17:47 +00001663
Andrew Trick0537a982013-05-06 21:56:23 +00001664// Declare the four HelpPrinter instances that are used to print out help, or
1665// help-hidden as an uncategorized list or in categories.
1666static HelpPrinter UncategorizedNormalPrinter(false);
1667static HelpPrinter UncategorizedHiddenPrinter(true);
1668static CategorizedHelpPrinter CategorizedNormalPrinter(false);
1669static CategorizedHelpPrinter CategorizedHiddenPrinter(true);
1670
Andrew Trick0537a982013-05-06 21:56:23 +00001671// Declare HelpPrinter wrappers that will decide whether or not to invoke
1672// a categorizing help printer
1673static HelpPrinterWrapper WrappedNormalPrinter(UncategorizedNormalPrinter,
1674 CategorizedNormalPrinter);
1675static HelpPrinterWrapper WrappedHiddenPrinter(UncategorizedHiddenPrinter,
1676 CategorizedHiddenPrinter);
1677
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001678// Define a category for generic options that all tools should have.
1679static cl::OptionCategory GenericCategory("Generic Options");
1680
Andrew Trick0537a982013-05-06 21:56:23 +00001681// Define uncategorized help printers.
1682// -help-list is hidden by default because if Option categories are being used
1683// then -help behaves the same as -help-list.
Chris Bieneman5d232242015-01-13 19:14:20 +00001684static cl::opt<HelpPrinter, true, parser<bool>> HLOp(
1685 "help-list",
1686 cl::desc("Display list of available options (-help-list-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001687 cl::location(UncategorizedNormalPrinter), cl::Hidden, cl::ValueDisallowed,
1688 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001689
Chris Bieneman5d232242015-01-13 19:14:20 +00001690static cl::opt<HelpPrinter, true, parser<bool>>
1691 HLHOp("help-list-hidden", cl::desc("Display list of all available options"),
1692 cl::location(UncategorizedHiddenPrinter), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001693 cl::ValueDisallowed, cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001694
1695// Define uncategorized/categorized help printers. These printers change their
1696// behaviour at runtime depending on whether one or more Option categories have
1697// been declared.
Chris Bieneman5d232242015-01-13 19:14:20 +00001698static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1699 HOp("help", cl::desc("Display available options (-help-hidden for more)"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001700 cl::location(WrappedNormalPrinter), cl::ValueDisallowed,
1701 cl::cat(GenericCategory));
Chris Lattner5df56c42002-07-22 02:07:59 +00001702
Chris Bieneman5d232242015-01-13 19:14:20 +00001703static cl::opt<HelpPrinterWrapper, true, parser<bool>>
1704 HHOp("help-hidden", cl::desc("Display all available options"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001705 cl::location(WrappedHiddenPrinter), cl::Hidden, cl::ValueDisallowed,
1706 cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001707
Chris Bieneman5d232242015-01-13 19:14:20 +00001708static cl::opt<bool> PrintOptions(
1709 "print-options",
1710 cl::desc("Print non-default options after command line parsing"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001711 cl::Hidden, cl::init(false), cl::cat(GenericCategory));
Andrew Trick0537a982013-05-06 21:56:23 +00001712
Chris Bieneman5d232242015-01-13 19:14:20 +00001713static cl::opt<bool> PrintAllOptions(
1714 "print-all-options",
1715 cl::desc("Print all option values after command line parsing"), cl::Hidden,
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001716 cl::init(false), cl::cat(GenericCategory));
Andrew Trick12004012011-04-05 18:54:36 +00001717
Andrew Trick0537a982013-05-06 21:56:23 +00001718void HelpPrinterWrapper::operator=(bool Value) {
1719 if (Value == false)
1720 return;
1721
1722 // Decide which printer to invoke. If more than one option category is
1723 // registered then it is useful to show the categorized help instead of
1724 // uncategorized help.
1725 if (RegisteredOptionCategories->size() > 1) {
1726 // unhide -help-list option so user can have uncategorized output if they
1727 // want it.
1728 HLOp.setHiddenFlag(NotHidden);
1729
1730 CategorizedPrinter = true; // Invoke categorized printer
Chris Bieneman5d232242015-01-13 19:14:20 +00001731 } else
Andrew Trick0537a982013-05-06 21:56:23 +00001732 UncategorizedPrinter = true; // Invoke uncategorized printer
1733}
1734
Andrew Trick12004012011-04-05 18:54:36 +00001735// Print the value of each option.
Chris Bienemand77bbab2015-01-30 22:16:01 +00001736void cl::PrintOptionValues() { GlobalParser->printOptionValues(); }
1737
1738void CommandLineParser::printOptionValues() {
Chris Bieneman5d232242015-01-13 19:14:20 +00001739 if (!PrintOptions && !PrintAllOptions)
1740 return;
Andrew Trick12004012011-04-05 18:54:36 +00001741
Chris Bieneman5d232242015-01-13 19:14:20 +00001742 SmallVector<std::pair<const char *, Option *>, 128> Opts;
Chris Bienemand77bbab2015-01-30 22:16:01 +00001743 sortOpts(OptionsMap, Opts, /*ShowHidden*/ true);
Andrew Trick12004012011-04-05 18:54:36 +00001744
1745 // Compute the maximum argument length...
1746 size_t MaxArgLen = 0;
1747 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1748 MaxArgLen = std::max(MaxArgLen, Opts[i].second->getOptionWidth());
1749
1750 for (size_t i = 0, e = Opts.size(); i != e; ++i)
1751 Opts[i].second->printOptionValue(MaxArgLen, PrintAllOptions);
1752}
1753
Craig Topperc10719f2014-04-07 04:17:22 +00001754static void (*OverrideVersionPrinter)() = nullptr;
Reid Spencerb3171672006-06-05 16:22:56 +00001755
Chris Bieneman5d232242015-01-13 19:14:20 +00001756static std::vector<void (*)()> *ExtraVersionPrinters = nullptr;
Chandler Carruthea7e5522011-07-22 07:50:40 +00001757
Chris Lattneradb19d62006-10-12 22:09:17 +00001758namespace {
Reid Spencerb3171672006-06-05 16:22:56 +00001759class VersionPrinter {
1760public:
Devang Patel9eb2caae2007-02-01 01:43:37 +00001761 void print() {
Chris Lattner131dca92009-09-20 06:18:38 +00001762 raw_ostream &OS = outs();
Jim Grosbach65e24652012-01-25 22:00:23 +00001763 OS << "LLVM (http://llvm.org/):\n"
Chris Lattner131dca92009-09-20 06:18:38 +00001764 << " " << PACKAGE_NAME << " version " << PACKAGE_VERSION;
Chris Lattner8ac22e72006-07-06 18:33:03 +00001765#ifdef LLVM_VERSION_INFO
Justin Bogner581b5922014-06-17 06:52:41 +00001766 OS << " " << LLVM_VERSION_INFO;
Reid Spencerb3171672006-06-05 16:22:56 +00001767#endif
Chris Lattner131dca92009-09-20 06:18:38 +00001768 OS << "\n ";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001769#ifndef __OPTIMIZE__
Chris Lattner131dca92009-09-20 06:18:38 +00001770 OS << "DEBUG build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001771#else
Chris Lattner131dca92009-09-20 06:18:38 +00001772 OS << "Optimized build";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001773#endif
1774#ifndef NDEBUG
Chris Lattner131dca92009-09-20 06:18:38 +00001775 OS << " with assertions";
Chris Lattner8ac22e72006-07-06 18:33:03 +00001776#endif
Daniel Dunbard90a9a02009-11-14 21:36:07 +00001777 std::string CPU = sys::getHostCPUName();
Chris Bieneman5d232242015-01-13 19:14:20 +00001778 if (CPU == "generic")
1779 CPU = "(unknown)";
Chris Lattner131dca92009-09-20 06:18:38 +00001780 OS << ".\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001781#if (ENABLE_TIMESTAMPS == 1)
Chris Lattner131dca92009-09-20 06:18:38 +00001782 << " Built " << __DATE__ << " (" << __TIME__ << ").\n"
Daniel Dunbardac18242010-05-10 20:11:56 +00001783#endif
Sebastian Pop94441fb2011-11-01 21:32:20 +00001784 << " Default target: " << sys::getDefaultTargetTriple() << '\n'
Chandler Carruth2d71c422011-07-22 07:50:48 +00001785 << " Host CPU: " << CPU << '\n';
Devang Patel9eb2caae2007-02-01 01:43:37 +00001786 }
1787 void operator=(bool OptionWasSpecified) {
Chris Bieneman5d232242015-01-13 19:14:20 +00001788 if (!OptionWasSpecified)
1789 return;
Mikhail Glushenkov1d9f1fe2009-11-19 17:29:36 +00001790
Craig Topperc10719f2014-04-07 04:17:22 +00001791 if (OverrideVersionPrinter != nullptr) {
Chandler Carruthea7e5522011-07-22 07:50:40 +00001792 (*OverrideVersionPrinter)();
Justin Bogner02b95842014-02-28 19:08:01 +00001793 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001794 }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001795 print();
1796
1797 // Iterate over any registered extra printers and call them to add further
1798 // information.
Craig Topperc10719f2014-04-07 04:17:22 +00001799 if (ExtraVersionPrinters != nullptr) {
Chandler Carruth2d71c422011-07-22 07:50:48 +00001800 outs() << '\n';
Chandler Carruthea7e5522011-07-22 07:50:40 +00001801 for (std::vector<void (*)()>::iterator I = ExtraVersionPrinters->begin(),
1802 E = ExtraVersionPrinters->end();
1803 I != E; ++I)
1804 (*I)();
1805 }
1806
Justin Bogner02b95842014-02-28 19:08:01 +00001807 exit(0);
Reid Spencerb3171672006-06-05 16:22:56 +00001808 }
1809};
Chris Lattneradb19d62006-10-12 22:09:17 +00001810} // End anonymous namespace
Reid Spencerb3171672006-06-05 16:22:56 +00001811
Reid Spencerff6cc122004-08-04 00:36:06 +00001812// Define the --version option that prints out the LLVM version for the tool
Chris Lattneradb19d62006-10-12 22:09:17 +00001813static VersionPrinter VersionPrinterInstance;
1814
Chris Bieneman5d232242015-01-13 19:14:20 +00001815static cl::opt<VersionPrinter, true, parser<bool>>
1816 VersOp("version", cl::desc("Display the version of this program"),
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001817 cl::location(VersionPrinterInstance), cl::ValueDisallowed,
1818 cl::cat(GenericCategory));
Reid Spencerff6cc122004-08-04 00:36:06 +00001819
Reid Spencer5e554702004-11-16 06:11:52 +00001820// Utility function for printing the help message.
Andrew Trick0537a982013-05-06 21:56:23 +00001821void cl::PrintHelpMessage(bool Hidden, bool Categorized) {
1822 // This looks weird, but it actually prints the help message. The Printers are
1823 // types of HelpPrinter and the help gets printed when its operator= is
1824 // invoked. That's because the "normal" usages of the help printer is to be
1825 // assigned true/false depending on whether -help or -help-hidden was given or
1826 // not. Since we're circumventing that we have to make it look like -help or
1827 // -help-hidden were given, so we assign true.
1828
1829 if (!Hidden && !Categorized)
1830 UncategorizedNormalPrinter = true;
1831 else if (!Hidden && Categorized)
1832 CategorizedNormalPrinter = true;
1833 else if (Hidden && !Categorized)
1834 UncategorizedHiddenPrinter = true;
1835 else
1836 CategorizedHiddenPrinter = true;
Reid Spencer5e554702004-11-16 06:11:52 +00001837}
Reid Spencerb3171672006-06-05 16:22:56 +00001838
Devang Patel9eb2caae2007-02-01 01:43:37 +00001839/// Utility function for printing version number.
Chris Bieneman5d232242015-01-13 19:14:20 +00001840void cl::PrintVersionMessage() { VersionPrinterInstance.print(); }
Devang Patel9eb2caae2007-02-01 01:43:37 +00001841
Chris Bieneman5d232242015-01-13 19:14:20 +00001842void cl::SetVersionPrinter(void (*func)()) { OverrideVersionPrinter = func; }
Chandler Carruthea7e5522011-07-22 07:50:40 +00001843
1844void cl::AddExtraVersionPrinter(void (*func)()) {
Craig Topper8d399f82014-04-09 04:20:00 +00001845 if (!ExtraVersionPrinters)
Chandler Carruthea7e5522011-07-22 07:50:40 +00001846 ExtraVersionPrinters = new std::vector<void (*)()>;
1847
1848 ExtraVersionPrinters->push_back(func);
1849}
Andrew Trick7cb710d2013-05-06 21:56:35 +00001850
Chris Bienemand1d94302015-01-28 19:00:25 +00001851StringMap<Option *> &cl::getRegisteredOptions() {
1852 return GlobalParser->OptionsMap;
Andrew Trick7cb710d2013-05-06 21:56:35 +00001853}
Peter Collingbournee1863192014-10-16 22:47:52 +00001854
Chris Bieneman9e13af72015-01-21 22:45:52 +00001855void cl::HideUnrelatedOptions(cl::OptionCategory &Category) {
Chris Bienemand1d94302015-01-28 19:00:25 +00001856 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman831fc5e2015-01-26 16:56:00 +00001857 if (I.second->Category != &Category &&
1858 I.second->Category != &GenericCategory)
Chris Bieneman9e13af72015-01-21 22:45:52 +00001859 I.second->setHiddenFlag(cl::ReallyHidden);
1860 }
1861}
1862
Chris Bieneman68169362015-01-27 22:21:06 +00001863void cl::HideUnrelatedOptions(ArrayRef<const cl::OptionCategory *> Categories) {
Chris Bieneman01043252015-01-26 21:57:29 +00001864 auto CategoriesBegin = Categories.begin();
1865 auto CategoriesEnd = Categories.end();
Chris Bienemand1d94302015-01-28 19:00:25 +00001866 for (auto &I : GlobalParser->OptionsMap) {
Chris Bieneman01043252015-01-26 21:57:29 +00001867 if (std::find(CategoriesBegin, CategoriesEnd, I.second->Category) ==
1868 CategoriesEnd &&
1869 I.second->Category != &GenericCategory)
1870 I.second->setHiddenFlag(cl::ReallyHidden);
1871 }
1872}
1873
Peter Collingbournee1863192014-10-16 22:47:52 +00001874void LLVMParseCommandLineOptions(int argc, const char *const *argv,
1875 const char *Overview) {
1876 llvm::cl::ParseCommandLineOptions(argc, argv, Overview);
1877}