LLVM 22.0.0git
ArgList.cpp
Go to the documentation of this file.
1//===- ArgList.cpp - Argument List Management -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/Config/llvm-config.h"
15#include "llvm/Option/Arg.h"
18#include "llvm/Option/Option.h"
20#include "llvm/Support/Debug.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <memory>
26#include <string>
27#include <utility>
28#include <vector>
29
30using namespace llvm;
31using namespace llvm::opt;
32
34 Args.push_back(A);
35
36 // Update ranges for the option and all of its groups.
37 for (Option O = A->getOption().getUnaliasedOption(); O.isValid();
38 O = O.getGroup()) {
39 auto &R =
40 OptRanges.insert(std::make_pair(O.getID(), emptyRange())).first->second;
41 R.first = std::min<unsigned>(R.first, Args.size() - 1);
42 R.second = Args.size();
43 }
44}
45
47 // Zero out the removed entries but keep them around so that we don't
48 // need to invalidate OptRanges.
49 for (Arg *const &A : filtered(Id)) {
50 // Avoid the need for a non-const filtered iterator variant.
51 Arg **ArgsBegin = Args.data();
52 ArgsBegin[&A - ArgsBegin] = nullptr;
53 }
54 OptRanges.erase(Id.getID());
55}
56
57ArgList::OptRange
58ArgList::getRange(std::initializer_list<OptSpecifier> Ids) const {
59 OptRange R = emptyRange();
60 for (auto Id : Ids) {
61 auto I = OptRanges.find(Id.getID());
62 if (I != OptRanges.end()) {
63 R.first = std::min(R.first, I->second.first);
64 R.second = std::max(R.second, I->second.second);
65 }
66 }
67 // Map an empty {-1, 0} range to {0, 0} so it can be used to form iterators.
68 if (R.first == -1u)
69 R.first = 0;
70 return R;
71}
72
74 if (Arg *A = getLastArg(Pos, Neg))
75 return A->getOption().matches(Pos);
76 return Default;
77}
78
80 bool Default) const {
81 if (Arg *A = getLastArgNoClaim(Pos, Neg))
82 return A->getOption().matches(Pos);
83 return Default;
84}
85
87 bool Default) const {
88 if (Arg *A = getLastArg(Pos, PosAlias, Neg))
89 return A->getOption().matches(Pos) || A->getOption().matches(PosAlias);
90 return Default;
91}
92
94 if (Arg *A = getLastArg(Id))
95 return A->getValue();
96 return Default;
97}
98
99std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const {
101 AddAllArgValues(Values, Id);
102 return std::vector<std::string>(Values.begin(), Values.end());
103}
104
106 OptSpecifier Neg) const {
107 if (Arg *A = getLastArg(Pos, Neg))
108 if (A->getOption().matches(Pos))
109 A->render(*this, Output);
110}
111
114 ArrayRef<OptSpecifier> ExcludeIds) const {
115 for (const Arg *Arg : *this) {
116 bool Excluded = false;
117 for (OptSpecifier Id : ExcludeIds) {
118 if (Arg->getOption().matches(Id)) {
119 Excluded = true;
120 break;
121 }
122 }
123 if (!Excluded) {
124 for (OptSpecifier Id : Ids) {
125 if (Arg->getOption().matches(Id)) {
126 Arg->claim();
127 Arg->render(*this, Output);
128 break;
129 }
130 }
131 }
132 }
133}
134
135/// This is a nicer interface when you don't have a list of Ids to exclude.
137 ArrayRef<OptSpecifier> Ids) const {
138 ArrayRef<OptSpecifier> Exclude = {};
139 AddAllArgsExcept(Output, Ids, Exclude);
140}
141
143 for (auto *Arg : filtered(Id0)) {
144 Arg->claim();
145 Arg->render(*this, Output);
146 }
147}
148
150 OptSpecifier Id1, OptSpecifier Id2) const {
151 for (auto *Arg : filtered(Id0, Id1, Id2)) {
152 Arg->claim();
153 const auto &Values = Arg->getValues();
154 Output.append(Values.begin(), Values.end());
155 }
156}
157
159 const char *Translation,
160 bool Joined) const {
161 for (auto *Arg : filtered(Id0)) {
162 Arg->claim();
163
164 if (Joined) {
165 Output.push_back(MakeArgString(StringRef(Translation) +
166 Arg->getValue(0)));
167 } else {
168 Output.push_back(Translation);
169 Output.push_back(Arg->getValue(0));
170 }
171 }
172}
173
175 for (auto *Arg : filtered(Id0))
176 Arg->claim();
177}
178
180 for (auto *Arg : *this)
181 if (!Arg->isClaimed())
182 Arg->claim();
183}
184
185const char *ArgList::GetOrMakeJoinedArgString(unsigned Index,
186 StringRef LHS,
187 StringRef RHS) const {
188 StringRef Cur = getArgString(Index);
189 if (Cur.size() == LHS.size() + RHS.size() && Cur.starts_with(LHS) &&
190 Cur.ends_with(RHS))
191 return Cur.data();
192
193 return MakeArgString(LHS + RHS);
194}
195
197 for (Arg *A : *this) {
198 O << "* ";
199 A->print(O);
200 }
201}
202
203#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
205#endif
206
209 std::function<void(ArrayRef<StringRef>)> HandleMultipleSubcommands,
210 std::function<void(ArrayRef<StringRef>)> HandleOtherPositionals) const {
211
212 SmallVector<StringRef, 4> SubCommands;
213 SmallVector<StringRef, 4> OtherPositionals;
214 for (const Arg *A : *this) {
215 if (A->getOption().getKind() != Option::InputClass)
216 continue;
217
218 size_t OldSize = SubCommands.size();
219 for (const OptTable::SubCommand &CMD : AllSubCommands) {
220 if (StringRef(CMD.Name) == A->getValue())
221 SubCommands.push_back(A->getValue());
222 }
223
224 if (SubCommands.size() == OldSize)
225 OtherPositionals.push_back(A->getValue());
226 }
227
228 // Invoke callbacks if necessary.
229 if (SubCommands.size() > 1) {
230 HandleMultipleSubcommands(SubCommands);
231 return {};
232 }
233 if (!OtherPositionals.empty()) {
234 HandleOtherPositionals(OtherPositionals);
235 return {};
236 }
237
238 if (SubCommands.size() == 1)
239 return SubCommands.front();
240 return {}; // No valid usage of subcommand found.
241}
242
243void InputArgList::releaseMemory() {
244 // An InputArgList always owns its arguments.
245 for (Arg *A : *this)
246 delete A;
247}
248
249InputArgList::InputArgList(const char* const *ArgBegin,
250 const char* const *ArgEnd)
251 : NumInputArgStrings(ArgEnd - ArgBegin) {
252 ArgStrings.append(ArgBegin, ArgEnd);
253}
254
255unsigned InputArgList::MakeIndex(StringRef String0) const {
256 unsigned Index = ArgStrings.size();
257
258 // Tuck away so we have a reliable const char *.
259 SynthesizedStrings.push_back(std::string(String0));
260 ArgStrings.push_back(SynthesizedStrings.back().c_str());
261
262 return Index;
263}
264
266 StringRef String1) const {
267 unsigned Index0 = MakeIndex(String0);
268 unsigned Index1 = MakeIndex(String1);
269 assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!");
270 (void) Index1;
271 return Index0;
272}
273
275 return getArgString(MakeIndex(Str));
276}
277
279 : BaseArgs(BaseArgs) {}
280
282 return BaseArgs.MakeArgString(Str);
283}
284
286 SynthesizedArgs.push_back(std::unique_ptr<Arg>(A));
287}
288
289Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option Opt) const {
290 SynthesizedArgs.push_back(
291 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
292 BaseArgs.MakeIndex(Opt.getName()), BaseArg));
293 return SynthesizedArgs.back().get();
294}
295
297 StringRef Value) const {
298 unsigned Index = BaseArgs.MakeIndex(Value);
299 SynthesizedArgs.push_back(
300 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
301 Index, BaseArgs.getArgString(Index), BaseArg));
302 return SynthesizedArgs.back().get();
303}
304
306 StringRef Value) const {
307 unsigned Index = BaseArgs.MakeIndex(Opt.getName(), Value);
308 SynthesizedArgs.push_back(
309 std::make_unique<Arg>(Opt, MakeArgString(Opt.getPrefix() + Opt.getName()),
310 Index, BaseArgs.getArgString(Index + 1), BaseArg));
311 return SynthesizedArgs.back().get();
312}
313
314Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option Opt,
315 StringRef Value) const {
316 unsigned Index = BaseArgs.MakeIndex((Opt.getName() + Value).str());
317 SynthesizedArgs.push_back(std::make_unique<Arg>(
318 Opt, MakeArgString(Opt.getPrefix() + Opt.getName()), Index,
319 BaseArgs.getArgString(Index) + Opt.getName().size(), BaseArg));
320 return SynthesizedArgs.back().get();
321}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Defines the llvm::Arg class for parsed arguments.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static ManagedStatic< SubCommand > AllSubCommands
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:638
#define I(x, y, z)
Definition MD5.cpp:58
This file defines the SmallVector class.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:41
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:167
iterator end()
Definition DenseMap.h:81
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:261
constexpr size_t size() const
size - Get the string size.
Definition StringRef.h:146
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition StringRef.h:140
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:273
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void eraseArg(OptSpecifier Id)
eraseArg - Remove any option matching Id.
Definition ArgList.cpp:46
virtual const char * getArgString(unsigned Index) const =0
getArgString - Return the input argument string at Index.
LLVM_ABI void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0, OptSpecifier Id1=0U, OptSpecifier Id2=0U) const
AddAllArgValues - Render the argument values of all arguments matching the given ids.
Definition ArgList.cpp:149
LLVM_ABI void print(raw_ostream &O) const
Definition ArgList.cpp:196
LLVM_ABI const char * GetOrMakeJoinedArgString(unsigned Index, StringRef LHS, StringRef RHS) const
Create an arg string for (LHS + RHS), reusing the string at Index if possible.
Definition ArgList.cpp:185
LLVM_ABI void addOptInFlag(ArgStringList &Output, OptSpecifier Pos, OptSpecifier Neg) const
Given an option Pos and its negative form Neg, render the option if Pos is present.
Definition ArgList.cpp:105
LLVM_ABI bool hasFlagNoClaim(OptSpecifier Pos, OptSpecifier Neg, bool Default) const
Definition ArgList.cpp:79
LLVM_ABI void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0, const char *Translation, bool Joined=false) const
AddAllArgsTranslated - Render all the arguments matching the given ids, but forced to separate args a...
Definition ArgList.cpp:158
LLVM_ABI void AddAllArgs(ArgStringList &Output, OptSpecifier Id0) const
AddAllArgs - Render all arguments matching the given ids.
Definition ArgList.cpp:142
const char * MakeArgString(const Twine &Str) const
Definition ArgList.h:400
StringRef getSubCommand(ArrayRef< OptTable::SubCommand > AllSubCommands, std::function< void(ArrayRef< StringRef >)> HandleMultipleSubcommands, std::function< void(ArrayRef< StringRef >)> HandleOtherPositionals) const
getSubCommand - Find subcommand from the arguments if the usage is valid.
Definition ArgList.cpp:207
LLVM_ABI void append(Arg *A)
append - Append A to the arg list.
Definition ArgList.cpp:33
LLVM_ABI void addAllArgs(ArgStringList &Output, ArrayRef< OptSpecifier > Ids) const
Render all arguments matching any of the given ids.
Definition ArgList.cpp:136
LLVM_ABI void ClaimAllArgs() const
ClaimAllArgs - Claim all arguments.
Definition ArgList.cpp:179
LLVM_ATTRIBUTE_NOINLINE Arg * getLastArgNoClaim(OptSpecifiers... Ids) const
Return the last argument matching Id, or null.
Definition ArgList.h:270
LLVM_ABI void dump() const
Definition ArgList.cpp:204
LLVM_ABI void AddAllArgsExcept(ArgStringList &Output, ArrayRef< OptSpecifier > Ids, ArrayRef< OptSpecifier > ExcludeIds) const
AddAllArgsExcept - Render all arguments matching any of the given ids and not matching any of the exc...
Definition ArgList.cpp:112
LLVM_ATTRIBUTE_NOINLINE Arg * getLastArg(OptSpecifiers... Ids) const
Return the last argument matching Id, or null.
Definition ArgList.h:258
LLVM_ABI std::vector< std::string > getAllArgValues(OptSpecifier Id) const
getAllArgValues - Get the values of all instances of the given argument as strings.
Definition ArgList.cpp:99
LLVM_ABI StringRef getLastArgValue(OptSpecifier Id, StringRef Default="") const
getLastArgValue - Return the value of the last argument, or a default.
Definition ArgList.cpp:93
iterator_range< filtered_iterator< sizeof...(OptSpecifiers)> > filtered(OptSpecifiers ...Ids) const
Definition ArgList.h:207
LLVM_ABI bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const
hasFlag - Given an option Pos and its negative form Neg, return true if the option is present,...
Definition ArgList.cpp:73
A concrete instance of a particular driver option.
Definition Arg.h:35
LLVM_ABI void render(const ArgList &Args, ArgStringList &Output) const
Append the argument onto the given array as strings.
Definition Arg.cpp:89
SmallVectorImpl< const char * > & getValues()
Definition Arg.h:131
const Option & getOption() const
Definition Arg.h:85
bool isClaimed() const
Definition Arg.h:115
const char * getValue(unsigned N=0) const
Definition Arg.h:127
void claim() const
Definition Arg.h:116
const char * MakeArgStringRef(StringRef Str) const override
Construct a constant string pointer whose lifetime will match that of the ArgList.
Definition ArgList.cpp:281
Arg * MakeSeparateArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakeSeparateArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:305
void AddSynthesizedArg(Arg *A)
AddSynthesizedArg - Add a argument to the list of synthesized arguments (to be freed).
Definition ArgList.cpp:285
Arg * MakeJoinedArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakeJoinedArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:314
DerivedArgList(const InputArgList &BaseArgs)
Construct a new derived arg list from BaseArgs.
Definition ArgList.cpp:278
const char * MakeArgString(const Twine &Str) const
Definition ArgList.h:400
Arg * MakePositionalArg(const Arg *BaseArg, const Option Opt, StringRef Value) const
MakePositionalArg - Construct a new Positional arg for the given option Id, with the provided Value.
Definition ArgList.cpp:296
Arg * MakeFlagArg(const Arg *BaseArg, const Option Opt) const
MakeFlagArg - Construct a new FlagArg for the given option Id.
Definition ArgList.cpp:289
const char * getArgString(unsigned Index) const override
getArgString - Return the input argument string at Index.
Definition ArgList.h:461
unsigned MakeIndex(StringRef String0) const
MakeIndex - Get an index for the given string(s).
Definition ArgList.cpp:255
const char * MakeArgStringRef(StringRef Str) const override
Construct a constant string pointer whose lifetime will match that of the ArgList.
Definition ArgList.cpp:274
OptSpecifier - Wrapper class for abstracting references to option IDs.
Option - Abstract representation for a single form of driver argument.
Definition Option.h:55
LLVM_ABI bool matches(OptSpecifier ID) const
matches - Predicate for whether this option is part of the given option (which may be a group).
Definition Option.cpp:96
StringRef getPrefix() const
Get the default prefix for this option.
Definition Option.h:131
StringRef getName() const
Get the name of this option without any prefix.
Definition Option.h:102
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
SmallVector< const char *, 16 > ArgStringList
ArgStringList - Type used for constructing argv lists for subprocesses.
Definition Option.h:30
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
@ Default
The result values are uniform if and only if all operands are uniform.
Definition Uniformity.h:20
Represents a subcommand and its options in the option table.
Definition OptTable.h:57