MLIR  20.0.0git
PassOptions.h
Go to the documentation of this file.
1 //===- PassOptions.h - Pass Option Utilities --------------------*- C++ -*-===//
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 //
9 // This file contains utilities for registering options with compiler passes and
10 // pipelines.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MLIR_PASS_PASSOPTIONS_H_
15 #define MLIR_PASS_PASSOPTIONS_H_
16 
17 #include "mlir/Support/LLVM.h"
18 #include "llvm/ADT/FunctionExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Compiler.h"
22 #include <memory>
23 
24 namespace mlir {
25 class OpPassManager;
26 
27 namespace detail {
28 namespace pass_options {
29 /// Parse a string containing a list of comma-delimited elements, invoking the
30 /// given parser for each sub-element and passing them to the provided
31 /// element-append functor.
32 LogicalResult
33 parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName,
34  StringRef optionStr,
35  function_ref<LogicalResult(StringRef)> elementParseFn);
36 template <typename ElementParser, typename ElementAppendFn>
37 LogicalResult parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName,
38  StringRef optionStr,
39  ElementParser &elementParser,
40  ElementAppendFn &&appendFn) {
42  opt, argName, optionStr, [&](StringRef valueStr) {
43  typename ElementParser::parser_data_type value = {};
44  if (elementParser.parse(opt, argName, valueStr, value))
45  return failure();
46  appendFn(value);
47  return success();
48  });
49 }
50 
51 /// Trait used to detect if a type has a operator<< method.
52 template <typename T>
54  decltype(std::declval<raw_ostream &>() << std::declval<T>());
55 template <typename T>
56 using has_stream_operator = llvm::is_detected<has_stream_operator_trait, T>;
57 
58 /// Utility methods for printing option values.
59 template <typename ParserT>
60 static void printOptionValue(raw_ostream &os, const bool &value) {
61  os << (value ? StringRef("true") : StringRef("false"));
62 }
63 template <typename ParserT>
64 static void printOptionValue(raw_ostream &os, const std::string &str) {
65  // Check if the string needs to be escaped before writing it to the ostream.
66  const size_t spaceIndex = str.find_first_of(' ');
67  const size_t escapeIndex =
68  std::min({str.find_first_of('{'), str.find_first_of('\''),
69  str.find_first_of('"')});
70  const bool requiresEscape = spaceIndex < escapeIndex;
71  if (requiresEscape)
72  os << "{";
73  os << str;
74  if (requiresEscape)
75  os << "}";
76 }
77 template <typename ParserT, typename DataT>
78 static std::enable_if_t<has_stream_operator<DataT>::value>
79 printOptionValue(raw_ostream &os, const DataT &value) {
80  os << value;
81 }
82 template <typename ParserT, typename DataT>
83 static std::enable_if_t<!has_stream_operator<DataT>::value>
84 printOptionValue(raw_ostream &os, const DataT &value) {
85  // If the value can't be streamed, fallback to checking for a print in the
86  // parser.
87  ParserT::print(os, value);
88 }
89 } // namespace pass_options
90 
91 /// Base container class and manager for all pass options.
92 class PassOptions : protected llvm::cl::SubCommand {
93 private:
94  /// This is the type-erased option base class. This provides some additional
95  /// hooks into the options that are not available via llvm::cl::Option.
96  class OptionBase {
97  public:
98  virtual ~OptionBase() = default;
99 
100  /// Out of line virtual function to provide home for the class.
101  virtual void anchor();
102 
103  /// Print the name and value of this option to the given stream.
104  virtual void print(raw_ostream &os) = 0;
105 
106  /// Return the argument string of this option.
107  StringRef getArgStr() const { return getOption()->ArgStr; }
108 
109  /// Returns true if this option has any value assigned to it.
110  bool hasValue() const { return optHasValue; }
111 
112  protected:
113  /// Return the main option instance.
114  virtual const llvm::cl::Option *getOption() const = 0;
115 
116  /// Copy the value from the given option into this one.
117  virtual void copyValueFrom(const OptionBase &other) = 0;
118 
119  /// Flag indicating if this option has a value.
120  bool optHasValue = false;
121 
122  /// Allow access to private methods.
123  friend PassOptions;
124  };
125 
126  /// This is the parser that is used by pass options that use literal options.
127  /// This is a thin wrapper around the llvm::cl::parser, that exposes some
128  /// additional methods.
129  template <typename DataType>
130  struct GenericOptionParser : public llvm::cl::parser<DataType> {
132 
133  /// Returns an argument name that maps to the specified value.
134  std::optional<StringRef> findArgStrForValue(const DataType &value) {
135  for (auto &it : this->Values)
136  if (it.V.compare(value))
137  return it.Name;
138  return std::nullopt;
139  }
140  };
141 
142  /// This is the parser that is used by pass options that wrap PassOptions
143  /// instances. Like GenericOptionParser, this is a thin wrapper around
144  /// llvm::cl::basic_parser.
145  template <typename PassOptionsT>
146  struct PassOptionsParser : public llvm::cl::basic_parser<PassOptionsT> {
148  // Parse the options object by delegating to
149  // `PassOptionsT::parseFromString`.
150  bool parse(llvm::cl::Option &, StringRef, StringRef arg,
151  PassOptionsT &value) {
152  return failed(value.parseFromString(arg));
153  }
154 
155  // Print the options object by delegating to `PassOptionsT::print`.
156  static void print(llvm::raw_ostream &os, const PassOptionsT &value) {
157  value.print(os);
158  }
159  };
160 
161  /// Utility methods for printing option values.
162  template <typename DataT>
163  static void printValue(raw_ostream &os, GenericOptionParser<DataT> &parser,
164  const DataT &value) {
165  if (std::optional<StringRef> argStr = parser.findArgStrForValue(value))
166  os << *argStr;
167  else
168  llvm_unreachable("unknown data value for option");
169  }
170  template <typename DataT, typename ParserT>
171  static void printValue(raw_ostream &os, ParserT &parser, const DataT &value) {
172  detail::pass_options::printOptionValue<ParserT>(os, value);
173  }
174 
175 public:
176  /// The specific parser to use. This is necessary because we need to provide
177  /// additional methods for certain data type parsers.
178  template <typename DataType>
179  using OptionParser = std::conditional_t<
180  // If the data type is derived from PassOptions, use the
181  // PassOptionsParser.
182  std::is_base_of_v<PassOptions, DataType>, PassOptionsParser<DataType>,
183  // Otherwise, use GenericOptionParser where it is well formed, and fall
184  // back to llvm::cl::parser otherwise.
185  // TODO: We should upstream the methods in GenericOptionParser to avoid
186  // the need to do this.
187  std::conditional_t<std::is_base_of<llvm::cl::generic_parser_base,
189  GenericOptionParser<DataType>,
191 
192  /// This class represents a specific pass option, with a provided
193  /// data type.
194  template <typename DataType, typename OptionParser = OptionParser<DataType>>
195  class Option
196  : public llvm::cl::opt<DataType, /*ExternalStorage=*/false, OptionParser>,
197  public OptionBase {
198  public:
199  template <typename... Args>
200  Option(PassOptions &parent, StringRef arg, Args &&...args)
201  : llvm::cl::opt<DataType, /*ExternalStorage=*/false, OptionParser>(
202  arg, llvm::cl::sub(parent), std::forward<Args>(args)...) {
203  assert(!this->isPositional() && !this->isSink() &&
204  "sink and positional options are not supported");
205  parent.options.push_back(this);
206 
207  // Set a callback to track if this option has a value.
208  this->setCallback([this](const auto &) { this->optHasValue = true; });
209  }
210  ~Option() override = default;
211  using llvm::cl::opt<DataType, /*ExternalStorage=*/false,
212  OptionParser>::operator=;
213  Option &operator=(const Option &other) {
214  *this = other.getValue();
215  return *this;
216  }
217 
218  private:
219  /// Return the main option instance.
220  const llvm::cl::Option *getOption() const final { return this; }
221 
222  /// Print the name and value of this option to the given stream.
223  void print(raw_ostream &os) final {
224  os << this->ArgStr << '=';
225  printValue(os, this->getParser(), this->getValue());
226  }
227 
228  /// Copy the value from the given option into this one.
229  void copyValueFrom(const OptionBase &other) final {
230  this->setValue(static_cast<const Option<DataType, OptionParser> &>(other)
231  .getValue());
232  optHasValue = other.optHasValue;
233  }
234  };
235 
236  /// This class represents a specific pass option that contains a list of
237  /// values of the provided data type. The elements within the textual form of
238  /// this option are parsed assuming they are comma-separated. Delimited
239  /// sub-ranges within individual elements of the list may contain commas that
240  /// are not treated as separators for the top-level list.
241  template <typename DataType, typename OptionParser = OptionParser<DataType>>
243  : public llvm::cl::list<DataType, /*StorageClass=*/bool, OptionParser>,
244  public OptionBase {
245  public:
246  template <typename... Args>
247  ListOption(PassOptions &parent, StringRef arg, Args &&...args)
248  : llvm::cl::list<DataType, /*StorageClass=*/bool, OptionParser>(
249  arg, llvm::cl::sub(parent), std::forward<Args>(args)...),
250  elementParser(*this) {
251  assert(!this->isPositional() && !this->isSink() &&
252  "sink and positional options are not supported");
253  assert(!(this->getMiscFlags() & llvm::cl::MiscFlags::CommaSeparated) &&
254  "ListOption is implicitly comma separated, specifying "
255  "CommaSeparated is extraneous");
256  parent.options.push_back(this);
257  elementParser.initialize();
258  }
259  ~ListOption() override = default;
262  *this = ArrayRef<DataType>(other);
263  this->optHasValue = other.optHasValue;
264  return *this;
265  }
266 
267  bool handleOccurrence(unsigned pos, StringRef argName,
268  StringRef arg) override {
269  if (this->isDefaultAssigned()) {
270  this->clear();
271  this->overwriteDefault();
272  }
273  this->optHasValue = true;
275  *this, argName, arg, elementParser,
276  [&](const DataType &value) { this->addValue(value); }));
277  }
278 
279  /// Allow assigning from an ArrayRef.
281  ((std::vector<DataType> &)*this).assign(values.begin(), values.end());
282  optHasValue = true;
283  return *this;
284  }
285 
286  /// Allow accessing the data held by this option.
288  return static_cast<std::vector<DataType> &>(*this);
289  }
291  return static_cast<const std::vector<DataType> &>(*this);
292  }
293 
294  private:
295  /// Return the main option instance.
296  const llvm::cl::Option *getOption() const final { return this; }
297 
298  /// Print the name and value of this option to the given stream.
299  void print(raw_ostream &os) final {
300  // Don't print the list if empty. An empty option value can be treated as
301  // an element of the list in certain cases (e.g. ListOption<std::string>).
302  if ((**this).empty())
303  return;
304 
305  os << this->ArgStr << "={";
306  auto printElementFn = [&](const DataType &value) {
307  printValue(os, this->getParser(), value);
308  };
309  llvm::interleave(*this, os, printElementFn, ",");
310  os << "}";
311  }
312 
313  /// Copy the value from the given option into this one.
314  void copyValueFrom(const OptionBase &other) final {
315  *this = static_cast<const ListOption<DataType, OptionParser> &>(other);
316  }
317 
318  /// The parser to use for parsing the list elements.
319  OptionParser elementParser;
320  };
321 
322  PassOptions() = default;
323  /// Delete the copy constructor to avoid copying the internal options map.
324  PassOptions(const PassOptions &) = delete;
325  PassOptions(PassOptions &&) = delete;
326 
327  /// Copy the option values from 'other' into 'this', where 'other' has the
328  /// same options as 'this'.
329  void copyOptionValuesFrom(const PassOptions &other);
330 
331  /// Parse options out as key=value pairs that can then be handed off to the
332  /// `llvm::cl` command line passing infrastructure. Everything is space
333  /// separated.
334  LogicalResult parseFromString(StringRef options,
335  raw_ostream &errorStream = llvm::errs());
336 
337  /// Print the options held by this struct in a form that can be parsed via
338  /// 'parseFromString'.
339  void print(raw_ostream &os) const;
340 
341  /// Print the help string for the options held by this struct. `descIndent` is
342  /// the indent that the descriptions should be aligned.
343  void printHelp(size_t indent, size_t descIndent) const;
344 
345  /// Return the maximum width required when printing the help string.
346  size_t getOptionWidth() const;
347 
348 private:
349  /// A list of all of the opaque options.
350  std::vector<OptionBase *> options;
351 };
352 } // namespace detail
353 
354 //===----------------------------------------------------------------------===//
355 // PassPipelineOptions
356 //===----------------------------------------------------------------------===//
357 
358 /// Subclasses of PassPipelineOptions provide a set of options that can be used
359 /// to initialize a pass pipeline. See PassPipelineRegistration for usage
360 /// details.
361 ///
362 /// Usage:
363 ///
364 /// struct MyPipelineOptions : PassPipelineOptions<MyPassOptions> {
365 /// ListOption<int> someListFlag{*this, "flag-name", llvm::cl::desc("...")};
366 /// };
367 template <typename T>
369 public:
370  /// Factory that parses the provided options and returns a unique_ptr to the
371  /// struct.
372  static std::unique_ptr<T> createFromString(StringRef options) {
373  auto result = std::make_unique<T>();
374  if (failed(result->parseFromString(options)))
375  return nullptr;
376  return result;
377  }
378 };
379 
380 /// A default empty option struct to be used for passes that do not need to take
381 /// any options.
382 struct EmptyPipelineOptions : public PassPipelineOptions<EmptyPipelineOptions> {
383 };
384 } // namespace mlir
385 
386 //===----------------------------------------------------------------------===//
387 // MLIR Options
388 //===----------------------------------------------------------------------===//
389 
390 namespace llvm {
391 namespace cl {
392 //===----------------------------------------------------------------------===//
393 // std::vector+SmallVector
394 
395 namespace detail {
396 template <typename VectorT, typename ElementT>
397 class VectorParserBase : public basic_parser_impl {
398 public:
399  VectorParserBase(Option &opt) : basic_parser_impl(opt), elementParser(opt) {}
400 
401  using parser_data_type = VectorT;
402 
403  bool parse(Option &opt, StringRef argName, StringRef arg,
404  parser_data_type &vector) {
405  if (!arg.consume_front("[") || !arg.consume_back("]")) {
406  return opt.error("expected vector option to be wrapped with '[]'",
407  argName);
408  }
409 
411  opt, argName, arg, elementParser,
412  [&](const ElementT &value) { vector.push_back(value); }));
413  }
414 
415  static void print(raw_ostream &os, const VectorT &vector) {
416  llvm::interleave(
417  vector, os,
418  [&](const ElementT &value) {
420  llvm::cl::parser<ElementT>>(os, value);
421  },
422  ",");
423  }
424 
425  void printOptionInfo(const Option &opt, size_t globalWidth) const {
426  // Add the `vector<>` qualifier to the option info.
427  outs() << " --" << opt.ArgStr;
428  outs() << "=<vector<" << elementParser.getValueName() << ">>";
429  Option::printHelpStr(opt.HelpStr, globalWidth, getOptionWidth(opt));
430  }
431 
432  size_t getOptionWidth(const Option &opt) const {
433  // Add the `vector<>` qualifier to the option width.
434  StringRef vectorExt("vector<>");
435  return elementParser.getOptionWidth(opt) + vectorExt.size();
436  }
437 
438 private:
439  llvm::cl::parser<ElementT> elementParser;
440 };
441 } // namespace detail
442 
443 template <typename T>
444 class parser<std::vector<T>>
445  : public detail::VectorParserBase<std::vector<T>, T> {
446 public:
447  parser(Option &opt) : detail::VectorParserBase<std::vector<T>, T>(opt) {}
448 };
449 template <typename T, unsigned N>
450 class parser<SmallVector<T, N>>
451  : public detail::VectorParserBase<SmallVector<T, N>, T> {
452 public:
453  parser(Option &opt) : detail::VectorParserBase<SmallVector<T, N>, T>(opt) {}
454 };
455 
456 //===----------------------------------------------------------------------===//
457 // OpPassManager: OptionValue
458 
459 template <>
460 struct OptionValue<mlir::OpPassManager> final : GenericOptionValue {
462 
468 
469  /// Returns if the current option has a value.
470  bool hasValue() const { return value.get(); }
471 
472  /// Returns the current value of the option.
474  assert(hasValue() && "invalid option value");
475  return *value;
476  }
477 
478  /// Set the value of the option.
479  void setValue(const mlir::OpPassManager &newValue);
480  void setValue(StringRef pipelineStr);
481 
482  /// Compare the option with the provided value.
483  bool compare(const mlir::OpPassManager &rhs) const;
484  bool compare(const GenericOptionValue &rhs) const override {
485  const auto &rhsOV =
486  static_cast<const OptionValue<mlir::OpPassManager> &>(rhs);
487  if (!rhsOV.hasValue())
488  return false;
489  return compare(rhsOV.getValue());
490  }
491 
492 private:
493  void anchor() override;
494 
495  /// The underlying pass manager. We use a unique_ptr to avoid the need for the
496  /// full type definition.
497  std::unique_ptr<mlir::OpPassManager> value;
498 };
499 
500 //===----------------------------------------------------------------------===//
501 // OpPassManager: Parser
502 
503 extern template class basic_parser<mlir::OpPassManager>;
504 
505 template <>
507 public:
508  /// A utility struct used when parsing a pass manager that prevents the need
509  /// for a default constructor on OpPassManager.
510  struct ParsedPassManager {
512  ParsedPassManager(ParsedPassManager &&);
514  operator const mlir::OpPassManager &() const {
515  assert(value && "parsed value was invalid");
516  return *value;
517  }
518 
519  std::unique_ptr<mlir::OpPassManager> value;
520  };
521  using parser_data_type = ParsedPassManager;
523 
524  parser(Option &opt) : basic_parser(opt) {}
525 
526  bool parse(Option &, StringRef, StringRef arg, ParsedPassManager &value);
527 
528  /// Print an instance of the underling option value to the given stream.
529  static void print(raw_ostream &os, const mlir::OpPassManager &value);
530 
531  // Overload in subclass to provide a better default value.
532  StringRef getValueName() const override { return "pass-manager"; }
533 
534  void printOptionDiff(const Option &opt, mlir::OpPassManager &pm,
535  const OptVal &defaultValue, size_t globalWidth) const;
536 
537  // An out-of-line virtual method to provide a 'home' for this class.
538  void anchor() override;
539 };
540 
541 } // namespace cl
542 } // namespace llvm
543 
544 #endif // MLIR_PASS_PASSOPTIONS_H_
static Value min(ImplicitLocOpBuilder &builder, Value value, Value bound)
static void print(spirv::VerCapExtAttr triple, DialectAsmPrinter &printer)
size_t getOptionWidth(const Option &opt) const
Definition: PassOptions.h:432
bool parse(Option &opt, StringRef argName, StringRef arg, parser_data_type &vector)
Definition: PassOptions.h:403
void printOptionInfo(const Option &opt, size_t globalWidth) const
Definition: PassOptions.h:425
static void print(raw_ostream &os, const VectorT &vector)
Definition: PassOptions.h:415
static void print(raw_ostream &os, const mlir::OpPassManager &value)
Print an instance of the underling option value to the given stream.
StringRef getValueName() const override
Definition: PassOptions.h:532
void printOptionDiff(const Option &opt, mlir::OpPassManager &pm, const OptVal &defaultValue, size_t globalWidth) const
bool parse(Option &, StringRef, StringRef arg, ParsedPassManager &value)
This class represents a pass manager that runs passes on either a specific operation type,...
Definition: PassManager.h:47
Subclasses of PassPipelineOptions provide a set of options that can be used to initialize a pass pipe...
Definition: PassOptions.h:368
static std::unique_ptr< T > createFromString(StringRef options)
Factory that parses the provided options and returns a unique_ptr to the struct.
Definition: PassOptions.h:372
This class represents a specific pass option that contains a list of values of the provided data type...
Definition: PassOptions.h:244
ListOption< DataType, OptionParser > & operator=(ArrayRef< DataType > values)
Allow assigning from an ArrayRef.
Definition: PassOptions.h:280
ListOption(PassOptions &parent, StringRef arg, Args &&...args)
Definition: PassOptions.h:247
ListOption< DataType, OptionParser > & operator=(const ListOption< DataType, OptionParser > &other)
Definition: PassOptions.h:261
MutableArrayRef< DataType > operator*()
Allow accessing the data held by this option.
Definition: PassOptions.h:287
ArrayRef< DataType > operator*() const
Definition: PassOptions.h:290
bool handleOccurrence(unsigned pos, StringRef argName, StringRef arg) override
Definition: PassOptions.h:267
This class represents a specific pass option, with a provided data type.
Definition: PassOptions.h:197
Option & operator=(const Option &other)
Definition: PassOptions.h:213
Option(PassOptions &parent, StringRef arg, Args &&...args)
Definition: PassOptions.h:200
Base container class and manager for all pass options.
Definition: PassOptions.h:92
size_t getOptionWidth() const
Return the maximum width required when printing the help string.
void printHelp(size_t indent, size_t descIndent) const
Print the help string for the options held by this struct.
PassOptions(PassOptions &&)=delete
LogicalResult parseFromString(StringRef options, raw_ostream &errorStream=llvm::errs())
Parse options out as key=value pairs that can then be handed off to the llvm::cl command line passing...
void print(raw_ostream &os) const
Print the options held by this struct in a form that can be parsed via 'parseFromString'.
void copyOptionValuesFrom(const PassOptions &other)
Copy the option values from 'other' into 'this', where 'other' has the same options as 'this'.
PassOptions(const PassOptions &)=delete
Delete the copy constructor to avoid copying the internal options map.
std::conditional_t< std::is_base_of_v< PassOptions, DataType >, PassOptionsParser< DataType >, std::conditional_t< std::is_base_of< llvm::cl::generic_parser_base, llvm::cl::parser< DataType > >::value, GenericOptionParser< DataType >, llvm::cl::parser< DataType > >> OptionParser
The specific parser to use.
Definition: PassOptions.h:190
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition: CallGraph.h:229
static void printOptionValue(raw_ostream &os, const bool &value)
Utility methods for printing option values.
Definition: PassOptions.h:60
LogicalResult parseCommaSeparatedList(llvm::cl::Option &opt, StringRef argName, StringRef optionStr, function_ref< LogicalResult(StringRef)> elementParseFn)
Parse a string containing a list of comma-delimited elements, invoking the given parser for each sub-...
decltype(std::declval< raw_ostream & >()<< std::declval< T >()) has_stream_operator_trait
Trait used to detect if a type has a operator<< method.
Definition: PassOptions.h:54
llvm::is_detected< has_stream_operator_trait, T > has_stream_operator
Definition: PassOptions.h:56
int compare(const Fraction &x, const Fraction &y)
Three-way comparison between two fractions.
Definition: Fraction.h:68
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition: Query.cpp:20
Include the generated interface declarations.
mlir::OpPassManager & getValue() const
Returns the current value of the option.
Definition: PassOptions.h:473
void setValue(const mlir::OpPassManager &newValue)
Set the value of the option.
OptionValue(const OptionValue< mlir::OpPassManager > &rhs)
bool compare(const mlir::OpPassManager &rhs) const
Compare the option with the provided value.
bool compare(const GenericOptionValue &rhs) const override
Definition: PassOptions.h:484
OptionValue< mlir::OpPassManager > & operator=(const mlir::OpPassManager &rhs)
OptionValue(const mlir::OpPassManager &value)
void setValue(StringRef pipelineStr)
bool hasValue() const
Returns if the current option has a value.
Definition: PassOptions.h:470
std::unique_ptr< mlir::OpPassManager > value
Definition: PassOptions.h:519
A default empty option struct to be used for passes that do not need to take any options.
Definition: PassOptions.h:382