ArgList.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ArgList.h - Argument List Management ---------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_OPTION_ARGLIST_H
  14. #define LLVM_OPTION_ARGLIST_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringRef.h"
  21. #include "llvm/ADT/Twine.h"
  22. #include "llvm/Option/Arg.h"
  23. #include "llvm/Option/OptSpecifier.h"
  24. #include "llvm/Option/Option.h"
  25. #include <algorithm>
  26. #include <cstddef>
  27. #include <initializer_list>
  28. #include <iterator>
  29. #include <list>
  30. #include <memory>
  31. #include <string>
  32. #include <utility>
  33. #include <vector>
  34. namespace llvm {
  35. class raw_ostream;
  36. namespace opt {
  37. /// arg_iterator - Iterates through arguments stored inside an ArgList.
  38. template<typename BaseIter, unsigned NumOptSpecifiers = 0>
  39. class arg_iterator {
  40. /// The current argument and the end of the sequence we're iterating.
  41. BaseIter Current, End;
  42. /// Optional filters on the arguments which will be match. To avoid a
  43. /// zero-sized array, we store one specifier even if we're asked for none.
  44. OptSpecifier Ids[NumOptSpecifiers ? NumOptSpecifiers : 1];
  45. void SkipToNextArg() {
  46. for (; Current != End; ++Current) {
  47. // Skip erased elements.
  48. if (!*Current)
  49. continue;
  50. // Done if there are no filters.
  51. if (!NumOptSpecifiers)
  52. return;
  53. // Otherwise require a match.
  54. const Option &O = (*Current)->getOption();
  55. for (auto Id : Ids) {
  56. if (!Id.isValid())
  57. break;
  58. if (O.matches(Id))
  59. return;
  60. }
  61. }
  62. }
  63. using Traits = std::iterator_traits<BaseIter>;
  64. public:
  65. using value_type = typename Traits::value_type;
  66. using reference = typename Traits::reference;
  67. using pointer = typename Traits::pointer;
  68. using iterator_category = std::forward_iterator_tag;
  69. using difference_type = std::ptrdiff_t;
  70. arg_iterator(
  71. BaseIter Current, BaseIter End,
  72. const OptSpecifier (&Ids)[NumOptSpecifiers ? NumOptSpecifiers : 1] = {})
  73. : Current(Current), End(End) {
  74. for (unsigned I = 0; I != NumOptSpecifiers; ++I)
  75. this->Ids[I] = Ids[I];
  76. SkipToNextArg();
  77. }
  78. reference operator*() const { return *Current; }
  79. pointer operator->() const { return Current; }
  80. arg_iterator &operator++() {
  81. ++Current;
  82. SkipToNextArg();
  83. return *this;
  84. }
  85. arg_iterator operator++(int) {
  86. arg_iterator tmp(*this);
  87. ++(*this);
  88. return tmp;
  89. }
  90. friend bool operator==(arg_iterator LHS, arg_iterator RHS) {
  91. return LHS.Current == RHS.Current;
  92. }
  93. friend bool operator!=(arg_iterator LHS, arg_iterator RHS) {
  94. return !(LHS == RHS);
  95. }
  96. };
  97. /// ArgList - Ordered collection of driver arguments.
  98. ///
  99. /// The ArgList class manages a list of Arg instances as well as
  100. /// auxiliary data and convenience methods to allow Tools to quickly
  101. /// check for the presence of Arg instances for a particular Option
  102. /// and to iterate over groups of arguments.
  103. class ArgList {
  104. public:
  105. using arglist_type = SmallVector<Arg *, 16>;
  106. using iterator = arg_iterator<arglist_type::iterator>;
  107. using const_iterator = arg_iterator<arglist_type::const_iterator>;
  108. using reverse_iterator = arg_iterator<arglist_type::reverse_iterator>;
  109. using const_reverse_iterator =
  110. arg_iterator<arglist_type::const_reverse_iterator>;
  111. template<unsigned N> using filtered_iterator =
  112. arg_iterator<arglist_type::const_iterator, N>;
  113. template<unsigned N> using filtered_reverse_iterator =
  114. arg_iterator<arglist_type::const_reverse_iterator, N>;
  115. private:
  116. /// The internal list of arguments.
  117. arglist_type Args;
  118. using OptRange = std::pair<unsigned, unsigned>;
  119. static OptRange emptyRange() { return {-1u, 0u}; }
  120. /// The first and last index of each different OptSpecifier ID.
  121. DenseMap<unsigned, OptRange> OptRanges;
  122. /// Get the range of indexes in which options with the specified IDs might
  123. /// reside, or (0, 0) if there are no such options.
  124. OptRange getRange(std::initializer_list<OptSpecifier> Ids) const;
  125. protected:
  126. // Make the default special members protected so they won't be used to slice
  127. // derived objects, but can still be used by derived objects to implement
  128. // their own special members.
  129. ArgList() = default;
  130. // Explicit move operations to ensure the container is cleared post-move
  131. // otherwise it could lead to a double-delete in the case of moving of an
  132. // InputArgList which deletes the contents of the container. If we could fix
  133. // up the ownership here (delegate storage/ownership to the derived class so
  134. // it can be a container of unique_ptr) this would be simpler.
  135. ArgList(ArgList &&RHS)
  136. : Args(std::move(RHS.Args)), OptRanges(std::move(RHS.OptRanges)) {
  137. RHS.Args.clear();
  138. RHS.OptRanges.clear();
  139. }
  140. ArgList &operator=(ArgList &&RHS) {
  141. Args = std::move(RHS.Args);
  142. RHS.Args.clear();
  143. OptRanges = std::move(RHS.OptRanges);
  144. RHS.OptRanges.clear();
  145. return *this;
  146. }
  147. // Protect the dtor to ensure this type is never destroyed polymorphically.
  148. ~ArgList() = default;
  149. // Implicitly convert a value to an OptSpecifier. Used to work around a bug
  150. // in MSVC's implementation of narrowing conversion checking.
  151. static OptSpecifier toOptSpecifier(OptSpecifier S) { return S; }
  152. public:
  153. /// @name Arg Access
  154. /// @{
  155. /// append - Append \p A to the arg list.
  156. void append(Arg *A);
  157. const arglist_type &getArgs() const { return Args; }
  158. unsigned size() const { return Args.size(); }
  159. /// @}
  160. /// @name Arg Iteration
  161. /// @{
  162. iterator begin() { return {Args.begin(), Args.end()}; }
  163. iterator end() { return {Args.end(), Args.end()}; }
  164. reverse_iterator rbegin() { return {Args.rbegin(), Args.rend()}; }
  165. reverse_iterator rend() { return {Args.rend(), Args.rend()}; }
  166. const_iterator begin() const { return {Args.begin(), Args.end()}; }
  167. const_iterator end() const { return {Args.end(), Args.end()}; }
  168. const_reverse_iterator rbegin() const { return {Args.rbegin(), Args.rend()}; }
  169. const_reverse_iterator rend() const { return {Args.rend(), Args.rend()}; }
  170. template<typename ...OptSpecifiers>
  171. iterator_range<filtered_iterator<sizeof...(OptSpecifiers)>>
  172. filtered(OptSpecifiers ...Ids) const {
  173. OptRange Range = getRange({toOptSpecifier(Ids)...});
  174. auto B = Args.begin() + Range.first;
  175. auto E = Args.begin() + Range.second;
  176. using Iterator = filtered_iterator<sizeof...(OptSpecifiers)>;
  177. return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
  178. Iterator(E, E, {toOptSpecifier(Ids)...}));
  179. }
  180. template<typename ...OptSpecifiers>
  181. iterator_range<filtered_reverse_iterator<sizeof...(OptSpecifiers)>>
  182. filtered_reverse(OptSpecifiers ...Ids) const {
  183. OptRange Range = getRange({toOptSpecifier(Ids)...});
  184. auto B = Args.rend() - Range.second;
  185. auto E = Args.rend() - Range.first;
  186. using Iterator = filtered_reverse_iterator<sizeof...(OptSpecifiers)>;
  187. return make_range(Iterator(B, E, {toOptSpecifier(Ids)...}),
  188. Iterator(E, E, {toOptSpecifier(Ids)...}));
  189. }
  190. /// @}
  191. /// @name Arg Removal
  192. /// @{
  193. /// eraseArg - Remove any option matching \p Id.
  194. void eraseArg(OptSpecifier Id);
  195. /// @}
  196. /// @name Arg Access
  197. /// @{
  198. /// hasArg - Does the arg list contain any option matching \p Id.
  199. ///
  200. /// \p Claim Whether the argument should be claimed, if it exists.
  201. template<typename ...OptSpecifiers>
  202. bool hasArgNoClaim(OptSpecifiers ...Ids) const {
  203. return getLastArgNoClaim(Ids...) != nullptr;
  204. }
  205. template<typename ...OptSpecifiers>
  206. bool hasArg(OptSpecifiers ...Ids) const {
  207. return getLastArg(Ids...) != nullptr;
  208. }
  209. /// Return true if the arg list contains multiple arguments matching \p Id.
  210. bool hasMultipleArgs(OptSpecifier Id) const {
  211. auto Args = filtered(Id);
  212. return (Args.begin() != Args.end()) && (++Args.begin()) != Args.end();
  213. }
  214. /// Return the last argument matching \p Id, or null.
  215. template<typename ...OptSpecifiers>
  216. Arg *getLastArg(OptSpecifiers ...Ids) const {
  217. Arg *Res = nullptr;
  218. for (Arg *A : filtered(Ids...)) {
  219. Res = A;
  220. Res->claim();
  221. }
  222. return Res;
  223. }
  224. /// Return the last argument matching \p Id, or null. Do not "claim" the
  225. /// option (don't mark it as having been used).
  226. template<typename ...OptSpecifiers>
  227. Arg *getLastArgNoClaim(OptSpecifiers ...Ids) const {
  228. for (Arg *A : filtered_reverse(Ids...))
  229. return A;
  230. return nullptr;
  231. }
  232. /// getArgString - Return the input argument string at \p Index.
  233. virtual const char *getArgString(unsigned Index) const = 0;
  234. /// getNumInputArgStrings - Return the number of original argument strings,
  235. /// which are guaranteed to be the first strings in the argument string
  236. /// list.
  237. virtual unsigned getNumInputArgStrings() const = 0;
  238. /// @}
  239. /// @name Argument Lookup Utilities
  240. /// @{
  241. /// getLastArgValue - Return the value of the last argument, or a default.
  242. StringRef getLastArgValue(OptSpecifier Id, StringRef Default = "") const;
  243. /// getAllArgValues - Get the values of all instances of the given argument
  244. /// as strings.
  245. std::vector<std::string> getAllArgValues(OptSpecifier Id) const;
  246. /// @}
  247. /// @name Translation Utilities
  248. /// @{
  249. /// hasFlag - Given an option \p Pos and its negative form \p Neg, return
  250. /// true if the option is present, false if the negation is present, and
  251. /// \p Default if neither option is given. If both the option and its
  252. /// negation are present, the last one wins.
  253. bool hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const;
  254. /// hasFlag - Given an option \p Pos, an alias \p PosAlias and its negative
  255. /// form \p Neg, return true if the option or its alias is present, false if
  256. /// the negation is present, and \p Default if none of the options are
  257. /// given. If multiple options are present, the last one wins.
  258. bool hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
  259. bool Default) const;
  260. /// Given an option Pos and its negative form Neg, render the option if Pos is
  261. /// present.
  262. void addOptInFlag(ArgStringList &Output, OptSpecifier Pos,
  263. OptSpecifier Neg) const;
  264. /// Render the option if Neg is present.
  265. void addOptOutFlag(ArgStringList &Output, OptSpecifier Pos,
  266. OptSpecifier Neg) const {
  267. addOptInFlag(Output, Neg, Pos);
  268. }
  269. /// Render only the last argument match \p Id0, if present.
  270. template<typename ...OptSpecifiers>
  271. void AddLastArg(ArgStringList &Output, OptSpecifiers ...Ids) const {
  272. if (Arg *A = getLastArg(Ids...)) // Calls claim() on all Ids's Args.
  273. A->render(*this, Output);
  274. }
  275. /// AddAllArgsExcept - Render all arguments matching any of the given ids
  276. /// and not matching any of the excluded ids.
  277. void AddAllArgsExcept(ArgStringList &Output, ArrayRef<OptSpecifier> Ids,
  278. ArrayRef<OptSpecifier> ExcludeIds) const;
  279. /// AddAllArgs - Render all arguments matching any of the given ids.
  280. void AddAllArgs(ArgStringList &Output, ArrayRef<OptSpecifier> Ids) const;
  281. /// AddAllArgs - Render all arguments matching the given ids.
  282. void AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
  283. OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
  284. /// AddAllArgValues - Render the argument values of all arguments
  285. /// matching the given ids.
  286. void AddAllArgValues(ArgStringList &Output, OptSpecifier Id0,
  287. OptSpecifier Id1 = 0U, OptSpecifier Id2 = 0U) const;
  288. /// AddAllArgsTranslated - Render all the arguments matching the
  289. /// given ids, but forced to separate args and using the provided
  290. /// name instead of the first option value.
  291. ///
  292. /// \param Joined - If true, render the argument as joined with
  293. /// the option specifier.
  294. void AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0,
  295. const char *Translation,
  296. bool Joined = false) const;
  297. /// ClaimAllArgs - Claim all arguments which match the given
  298. /// option id.
  299. void ClaimAllArgs(OptSpecifier Id0) const;
  300. /// ClaimAllArgs - Claim all arguments.
  301. ///
  302. void ClaimAllArgs() const;
  303. /// @}
  304. /// @name Arg Synthesis
  305. /// @{
  306. /// Construct a constant string pointer whose
  307. /// lifetime will match that of the ArgList.
  308. virtual const char *MakeArgStringRef(StringRef Str) const = 0;
  309. const char *MakeArgString(const Twine &Str) const {
  310. SmallString<256> Buf;
  311. return MakeArgStringRef(Str.toStringRef(Buf));
  312. }
  313. /// Create an arg string for (\p LHS + \p RHS), reusing the
  314. /// string at \p Index if possible.
  315. const char *GetOrMakeJoinedArgString(unsigned Index, StringRef LHS,
  316. StringRef RHS) const;
  317. void print(raw_ostream &O) const;
  318. void dump() const;
  319. /// @}
  320. };
  321. class InputArgList final : public ArgList {
  322. private:
  323. /// List of argument strings used by the contained Args.
  324. ///
  325. /// This is mutable since we treat the ArgList as being the list
  326. /// of Args, and allow routines to add new strings (to have a
  327. /// convenient place to store the memory) via MakeIndex.
  328. mutable ArgStringList ArgStrings;
  329. /// Strings for synthesized arguments.
  330. ///
  331. /// This is mutable since we treat the ArgList as being the list
  332. /// of Args, and allow routines to add new strings (to have a
  333. /// convenient place to store the memory) via MakeIndex.
  334. mutable std::list<std::string> SynthesizedStrings;
  335. /// The number of original input argument strings.
  336. unsigned NumInputArgStrings;
  337. /// Release allocated arguments.
  338. void releaseMemory();
  339. public:
  340. InputArgList() : NumInputArgStrings(0) {}
  341. InputArgList(const char* const *ArgBegin, const char* const *ArgEnd);
  342. InputArgList(InputArgList &&RHS)
  343. : ArgList(std::move(RHS)), ArgStrings(std::move(RHS.ArgStrings)),
  344. SynthesizedStrings(std::move(RHS.SynthesizedStrings)),
  345. NumInputArgStrings(RHS.NumInputArgStrings) {}
  346. InputArgList &operator=(InputArgList &&RHS) {
  347. releaseMemory();
  348. ArgList::operator=(std::move(RHS));
  349. ArgStrings = std::move(RHS.ArgStrings);
  350. SynthesizedStrings = std::move(RHS.SynthesizedStrings);
  351. NumInputArgStrings = RHS.NumInputArgStrings;
  352. return *this;
  353. }
  354. ~InputArgList() { releaseMemory(); }
  355. const char *getArgString(unsigned Index) const override {
  356. return ArgStrings[Index];
  357. }
  358. void replaceArgString(unsigned Index, const Twine &S) {
  359. ArgStrings[Index] = MakeArgString(S);
  360. }
  361. unsigned getNumInputArgStrings() const override {
  362. return NumInputArgStrings;
  363. }
  364. /// @name Arg Synthesis
  365. /// @{
  366. public:
  367. /// MakeIndex - Get an index for the given string(s).
  368. unsigned MakeIndex(StringRef String0) const;
  369. unsigned MakeIndex(StringRef String0, StringRef String1) const;
  370. using ArgList::MakeArgString;
  371. const char *MakeArgStringRef(StringRef Str) const override;
  372. /// @}
  373. };
  374. /// DerivedArgList - An ordered collection of driver arguments,
  375. /// whose storage may be in another argument list.
  376. class DerivedArgList final : public ArgList {
  377. const InputArgList &BaseArgs;
  378. /// The list of arguments we synthesized.
  379. mutable SmallVector<std::unique_ptr<Arg>, 16> SynthesizedArgs;
  380. public:
  381. /// Construct a new derived arg list from \p BaseArgs.
  382. DerivedArgList(const InputArgList &BaseArgs);
  383. const char *getArgString(unsigned Index) const override {
  384. return BaseArgs.getArgString(Index);
  385. }
  386. unsigned getNumInputArgStrings() const override {
  387. return BaseArgs.getNumInputArgStrings();
  388. }
  389. const InputArgList &getBaseArgs() const {
  390. return BaseArgs;
  391. }
  392. /// @name Arg Synthesis
  393. /// @{
  394. /// AddSynthesizedArg - Add a argument to the list of synthesized arguments
  395. /// (to be freed).
  396. void AddSynthesizedArg(Arg *A);
  397. using ArgList::MakeArgString;
  398. const char *MakeArgStringRef(StringRef Str) const override;
  399. /// AddFlagArg - Construct a new FlagArg for the given option \p Id and
  400. /// append it to the argument list.
  401. void AddFlagArg(const Arg *BaseArg, const Option Opt) {
  402. append(MakeFlagArg(BaseArg, Opt));
  403. }
  404. /// AddPositionalArg - Construct a new Positional arg for the given option
  405. /// \p Id, with the provided \p Value and append it to the argument
  406. /// list.
  407. void AddPositionalArg(const Arg *BaseArg, const Option Opt,
  408. StringRef Value) {
  409. append(MakePositionalArg(BaseArg, Opt, Value));
  410. }
  411. /// AddSeparateArg - Construct a new Positional arg for the given option
  412. /// \p Id, with the provided \p Value and append it to the argument
  413. /// list.
  414. void AddSeparateArg(const Arg *BaseArg, const Option Opt,
  415. StringRef Value) {
  416. append(MakeSeparateArg(BaseArg, Opt, Value));
  417. }
  418. /// AddJoinedArg - Construct a new Positional arg for the given option
  419. /// \p Id, with the provided \p Value and append it to the argument list.
  420. void AddJoinedArg(const Arg *BaseArg, const Option Opt,
  421. StringRef Value) {
  422. append(MakeJoinedArg(BaseArg, Opt, Value));
  423. }
  424. /// MakeFlagArg - Construct a new FlagArg for the given option \p Id.
  425. Arg *MakeFlagArg(const Arg *BaseArg, const Option Opt) const;
  426. /// MakePositionalArg - Construct a new Positional arg for the
  427. /// given option \p Id, with the provided \p Value.
  428. Arg *MakePositionalArg(const Arg *BaseArg, const Option Opt,
  429. StringRef Value) const;
  430. /// MakeSeparateArg - Construct a new Positional arg for the
  431. /// given option \p Id, with the provided \p Value.
  432. Arg *MakeSeparateArg(const Arg *BaseArg, const Option Opt,
  433. StringRef Value) const;
  434. /// MakeJoinedArg - Construct a new Positional arg for the
  435. /// given option \p Id, with the provided \p Value.
  436. Arg *MakeJoinedArg(const Arg *BaseArg, const Option Opt,
  437. StringRef Value) const;
  438. /// @}
  439. };
  440. } // end namespace opt
  441. } // end namespace llvm
  442. #endif // LLVM_OPTION_ARGLIST_H
  443. #ifdef __GNUC__
  444. #pragma GCC diagnostic pop
  445. #endif