MLIR  15.0.0git
Dialect.h
Go to the documentation of this file.
1 //===- Dialect.h - IR Dialect Description -----------------------*- 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 defines the 'dialect' abstraction.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef MLIR_IR_DIALECT_H
14 #define MLIR_IR_DIALECT_H
15 
18 #include "mlir/Support/TypeID.h"
19 
20 #include <map>
21 #include <tuple>
22 
23 namespace mlir {
24 class DialectAsmParser;
25 class DialectAsmPrinter;
26 class DialectInterface;
27 class OpBuilder;
28 class Type;
29 
30 //===----------------------------------------------------------------------===//
31 // Dialect
32 //===----------------------------------------------------------------------===//
33 
34 /// Dialects are groups of MLIR operations, types and attributes, as well as
35 /// behavior associated with the entire group. For example, hooks into other
36 /// systems for constant folding, interfaces, default named types for asm
37 /// printing, etc.
38 ///
39 /// Instances of the dialect object are loaded in a specific MLIRContext.
40 ///
41 class Dialect {
42 public:
43  /// Type for a callback provided by the dialect to parse a custom operation.
44  /// This is used for the dialect to provide an alternative way to parse custom
45  /// operations, including unregistered ones.
46  using ParseOpHook =
48 
49  virtual ~Dialect();
50 
51  /// Utility function that returns if the given string is a valid dialect
52  /// namespace
53  static bool isValidNamespace(StringRef str);
54 
55  MLIRContext *getContext() const { return context; }
56 
57  StringRef getNamespace() const { return name; }
58 
59  /// Returns the unique identifier that corresponds to this dialect.
60  TypeID getTypeID() const { return dialectID; }
61 
62  /// Returns true if this dialect allows for unregistered operations, i.e.
63  /// operations prefixed with the dialect namespace but not registered with
64  /// addOperation.
65  bool allowsUnknownOperations() const { return unknownOpsAllowed; }
66 
67  /// Return true if this dialect allows for unregistered types, i.e., types
68  /// prefixed with the dialect namespace but not registered with addType.
69  /// These are represented with OpaqueType.
70  bool allowsUnknownTypes() const { return unknownTypesAllowed; }
71 
72  /// Register dialect-wide canonicalization patterns. This method should only
73  /// be used to register canonicalization patterns that do not conceptually
74  /// belong to any single operation in the dialect. (In that case, use the op's
75  /// canonicalizer.) E.g., canonicalization patterns for op interfaces should
76  /// be registered here.
77  virtual void getCanonicalizationPatterns(RewritePatternSet &results) const {}
78 
79  /// Registered hook to materialize a single constant operation from a given
80  /// attribute value with the desired resultant type. This method should use
81  /// the provided builder to create the operation without changing the
82  /// insertion position. The generated operation is expected to be constant
83  /// like, i.e. single result, zero operands, non side-effecting, etc. On
84  /// success, this hook should return the value generated to represent the
85  /// constant value. Otherwise, it should return null on failure.
87  Type type, Location loc) {
88  return nullptr;
89  }
90 
91  //===--------------------------------------------------------------------===//
92  // Parsing Hooks
93  //===--------------------------------------------------------------------===//
94 
95  /// Parse an attribute registered to this dialect. If 'type' is nonnull, it
96  /// refers to the expected type of the attribute.
97  virtual Attribute parseAttribute(DialectAsmParser &parser, Type type) const;
98 
99  /// Print an attribute registered to this dialect. Note: The type of the
100  /// attribute need not be printed by this method as it is always printed by
101  /// the caller.
102  virtual void printAttribute(Attribute, DialectAsmPrinter &) const {
103  llvm_unreachable("dialect has no registered attribute printing hook");
104  }
105 
106  /// Parse a type registered to this dialect.
107  virtual Type parseType(DialectAsmParser &parser) const;
108 
109  /// Print a type registered to this dialect.
110  virtual void printType(Type, DialectAsmPrinter &) const {
111  llvm_unreachable("dialect has no registered type printing hook");
112  }
113 
114  /// Return the hook to parse an operation registered to this dialect, if any.
115  /// By default this will lookup for registered operations and return the
116  /// `parse()` method registered on the RegisteredOperationName. Dialects can
117  /// override this behavior and handle unregistered operations as well.
118  virtual Optional<ParseOpHook> getParseOperationHook(StringRef opName) const;
119 
120  /// Print an operation registered to this dialect.
121  /// This hook is invoked for registered operation which don't override the
122  /// `print()` method to define their own custom assembly.
123  virtual llvm::unique_function<void(Operation *, OpAsmPrinter &printer)>
124  getOperationPrinter(Operation *op) const;
125 
126  //===--------------------------------------------------------------------===//
127  // Verification Hooks
128  //===--------------------------------------------------------------------===//
129 
130  /// Verify an attribute from this dialect on the argument at 'argIndex' for
131  /// the region at 'regionIndex' on the given operation. Returns failure if
132  /// the verification failed, success otherwise. This hook may optionally be
133  /// invoked from any operation containing a region.
135  unsigned regionIndex,
136  unsigned argIndex,
138 
139  /// Verify an attribute from this dialect on the result at 'resultIndex' for
140  /// the region at 'regionIndex' on the given operation. Returns failure if
141  /// the verification failed, success otherwise. This hook may optionally be
142  /// invoked from any operation containing a region.
144  unsigned regionIndex,
145  unsigned resultIndex,
147 
148  /// Verify an attribute from this dialect on the given operation. Returns
149  /// failure if the verification failed, success otherwise.
151  return success();
152  }
153 
154  //===--------------------------------------------------------------------===//
155  // Interfaces
156  //===--------------------------------------------------------------------===//
157 
158  /// Lookup an interface for the given ID if one is registered, otherwise
159  /// nullptr.
161  auto it = registeredInterfaces.find(interfaceID);
162  return it != registeredInterfaces.end() ? it->getSecond().get() : nullptr;
163  }
164  template <typename InterfaceT> const InterfaceT *getRegisteredInterface() {
165  return static_cast<const InterfaceT *>(
166  getRegisteredInterface(InterfaceT::getInterfaceID()));
167  }
168 
169  /// Lookup an op interface for the given ID if one is registered, otherwise
170  /// nullptr.
171  virtual void *getRegisteredInterfaceForOp(TypeID interfaceID,
172  OperationName opName) {
173  return nullptr;
174  }
175  template <typename InterfaceT>
176  typename InterfaceT::Concept *
178  return static_cast<typename InterfaceT::Concept *>(
179  getRegisteredInterfaceForOp(InterfaceT::getInterfaceID(), opName));
180  }
181 
182  /// Register a dialect interface with this dialect instance.
183  void addInterface(std::unique_ptr<DialectInterface> interface);
184 
185  /// Register a set of dialect interfaces with this dialect instance.
186  template <typename... Args>
187  void addInterfaces() {
188  (void)std::initializer_list<int>{
189  0, (addInterface(std::make_unique<Args>(this)), 0)...};
190  }
191 
192 protected:
193  /// The constructor takes a unique namespace for this dialect as well as the
194  /// context to bind to.
195  /// Note: The namespace must not contain '.' characters.
196  /// Note: All operations belonging to this dialect must have names starting
197  /// with the namespace followed by '.'.
198  /// Example:
199  /// - "tf" for the TensorFlow ops like "tf.add".
200  Dialect(StringRef name, MLIRContext *context, TypeID id);
201 
202  /// This method is used by derived classes to add their operations to the set.
203  ///
204  template <typename... Args> void addOperations() {
205  (void)std::initializer_list<int>{
206  0, (RegisteredOperationName::insert<Args>(*this), 0)...};
207  }
208 
209  /// Register a set of type classes with this dialect.
210  template <typename... Args> void addTypes() {
211  (void)std::initializer_list<int>{0, (addType<Args>(), 0)...};
212  }
213 
214  /// Register a type instance with this dialect.
215  /// The use of this method is in general discouraged in favor of
216  /// 'addTypes<CustomType>()'.
217  void addType(TypeID typeID, AbstractType &&typeInfo);
218 
219  /// Register a set of attribute classes with this dialect.
220  template <typename... Args> void addAttributes() {
221  (void)std::initializer_list<int>{0, (addAttribute<Args>(), 0)...};
222  }
223 
224  /// Register an attribute instance with this dialect.
225  /// The use of this method is in general discouraged in favor of
226  /// 'addAttributes<CustomAttr>()'.
227  void addAttribute(TypeID typeID, AbstractAttribute &&attrInfo);
228 
229  /// Enable support for unregistered operations.
230  void allowUnknownOperations(bool allow = true) { unknownOpsAllowed = allow; }
231 
232  /// Enable support for unregistered types.
233  void allowUnknownTypes(bool allow = true) { unknownTypesAllowed = allow; }
234 
235 private:
236  Dialect(const Dialect &) = delete;
237  void operator=(Dialect &) = delete;
238 
239  /// Register an attribute instance with this dialect.
240  template <typename T> void addAttribute() {
241  // Add this attribute to the dialect and register it with the uniquer.
242  addAttribute(T::getTypeID(), AbstractAttribute::get<T>(*this));
243  detail::AttributeUniquer::registerAttribute<T>(context);
244  }
245 
246  /// Register a type instance with this dialect.
247  template <typename T> void addType() {
248  // Add this type to the dialect and register it with the uniquer.
249  addType(T::getTypeID(), AbstractType::get<T>(*this));
250  detail::TypeUniquer::registerType<T>(context);
251  }
252 
253  /// The namespace of this dialect.
254  StringRef name;
255 
256  /// The unique identifier of the derived Op class, this is used in the context
257  /// to allow registering multiple times the same dialect.
258  TypeID dialectID;
259 
260  /// This is the context that owns this Dialect object.
261  MLIRContext *context;
262 
263  /// Flag that specifies whether this dialect supports unregistered operations,
264  /// i.e. operations prefixed with the dialect namespace but not registered
265  /// with addOperation.
266  bool unknownOpsAllowed = false;
267 
268  /// Flag that specifies whether this dialect allows unregistered types, i.e.
269  /// types prefixed with the dialect namespace but not registered with addType.
270  /// These types are represented with OpaqueType.
271  bool unknownTypesAllowed = false;
272 
273  /// A collection of registered dialect interfaces.
275 
276  friend class DialectRegistry;
277  friend void registerDialect();
278  friend class MLIRContext;
279 };
280 
281 } // namespace mlir
282 
283 namespace llvm {
284 /// Provide isa functionality for Dialects.
285 template <typename T>
286 struct isa_impl<T, ::mlir::Dialect,
287  std::enable_if_t<std::is_base_of<::mlir::Dialect, T>::value>> {
288  static inline bool doit(const ::mlir::Dialect &dialect) {
289  return mlir::TypeID::get<T>() == dialect.getTypeID();
290  }
291 };
292 template <typename T>
293 struct isa_impl<
294  T, ::mlir::Dialect,
295  std::enable_if_t<std::is_base_of<::mlir::DialectInterface, T>::value>> {
296  static inline bool doit(const ::mlir::Dialect &dialect) {
297  return const_cast<::mlir::Dialect &>(dialect).getRegisteredInterface<T>();
298  }
299 };
300 template <typename T>
301 struct cast_retty_impl<T, ::mlir::Dialect *> {
302  using ret_type =
304  const T *>;
305 };
306 template <typename T>
307 struct cast_retty_impl<T, ::mlir::Dialect> {
308  using ret_type =
310  const T &>;
311 };
312 
313 template <typename T>
314 struct cast_convert_val<T, ::mlir::Dialect, ::mlir::Dialect> {
315  template <typename To>
317  doitImpl(::mlir::Dialect &dialect) {
318  return static_cast<To &>(dialect);
319  }
320  template <typename To>
322  const To &>
323  doitImpl(::mlir::Dialect &dialect) {
324  return *dialect.getRegisteredInterface<To>();
325  }
326 
327  static auto &doit(::mlir::Dialect &dialect) { return doitImpl<T>(dialect); }
328 };
329 template <class T>
330 struct cast_convert_val<T, ::mlir::Dialect *, ::mlir::Dialect *> {
331  static auto doit(::mlir::Dialect *dialect) {
332  return &cast_convert_val<T, ::mlir::Dialect, ::mlir::Dialect>::doit(
333  *dialect);
334  }
335 };
336 
337 } // namespace llvm
338 
339 #endif
TODO: Remove this file when SCCP and integer range analysis have been ported to the new framework...
TypeID getTypeID() const
Returns the unique identifier that corresponds to this dialect.
Definition: Dialect.h:60
void addInterfaces()
Register a set of dialect interfaces with this dialect instance.
Definition: Dialect.h:187
The OpAsmOpInterface, see OpAsmInterface.td for more details.
Definition: CallGraph.h:221
Operation is a basic unit of execution within MLIR.
Definition: Operation.h:28
void allowUnknownOperations(bool allow=true)
Enable support for unregistered operations.
Definition: Dialect.h:230
virtual Attribute parseAttribute(DialectAsmParser &parser, Type type) const
Parse an attribute registered to this dialect.
Definition: Dialect.cpp:57
static auto & doit(::mlir::Dialect &dialect)
Definition: Dialect.h:327
virtual void getCanonicalizationPatterns(RewritePatternSet &results) const
Register dialect-wide canonicalization patterns.
Definition: Dialect.h:77
virtual llvm::unique_function< void(Operation *, OpAsmPrinter &printer)> getOperationPrinter(Operation *op) const
Print an operation registered to this dialect.
Definition: Dialect.cpp:83
An inlay hint that for a type annotation.
virtual ~Dialect()
This class contains all of the static information common to all instances of a registered Type...
Definition: TypeSupport.h:30
void addOperations()
This method is used by derived classes to add their operations to the set.
Definition: Dialect.h:204
Dialect(StringRef name, MLIRContext *context, TypeID id)
The constructor takes a unique namespace for this dialect as well as the context to bind to...
Definition: Dialect.cpp:31
static constexpr const bool value
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:48
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:144
void addAttribute(TypeID typeID, AbstractAttribute &&attrInfo)
Register an attribute instance with this dialect.
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
friend void registerDialect()
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
const InterfaceT * getRegisteredInterface()
Definition: Dialect.h:164
virtual void * getRegisteredInterfaceForOp(TypeID interfaceID, OperationName opName)
Lookup an op interface for the given ID if one is registered, otherwise nullptr.
Definition: Dialect.h:171
const DialectInterface * getRegisteredInterface(TypeID interfaceID)
Lookup an interface for the given ID if one is registered, otherwise nullptr.
Definition: Dialect.h:160
Attributes are known-constant values of operations.
Definition: Attributes.h:24
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition: Dialect.h:41
virtual Optional< ParseOpHook > getParseOperationHook(StringRef opName) const
Return the hook to parse an operation registered to this dialect, if any.
Definition: Dialect.cpp:78
bool allowsUnknownTypes() const
Return true if this dialect allows for unregistered types, i.e., types prefixed with the dialect name...
Definition: Dialect.h:70
MLIRContext * getContext() const
Definition: Dialect.h:55
virtual LogicalResult verifyOperationAttribute(Operation *, NamedAttribute)
Verify an attribute from this dialect on the given operation.
Definition: Dialect.h:150
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:72
std::conditional_t< std::is_base_of<::mlir::Dialect, T >::value, T *, const T * > ret_type
Definition: Dialect.h:304
static int resultIndex(int i)
Definition: Operator.cpp:308
static std::enable_if_t< std::is_base_of<::mlir::Dialect, To >::value, To & > doitImpl(::mlir::Dialect &dialect)
Definition: Dialect.h:317
void addAttributes()
Register a set of attribute classes with this dialect.
Definition: Dialect.h:220
StringRef getNamespace() const
Definition: Dialect.h:57
void addInterface(std::unique_ptr< DialectInterface > interface)
Register a dialect interface with this dialect instance.
Definition: Dialect.cpp:97
void allowUnknownTypes(bool allow=true)
Enable support for unregistered types.
Definition: Dialect.h:233
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
void addTypes()
Register a set of type classes with this dialect.
Definition: Dialect.h:210
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:55
bool allowsUnknownOperations() const
Returns true if this dialect allows for unregistered operations, i.e.
Definition: Dialect.h:65
virtual void printType(Type, DialectAsmPrinter &) const
Print a type registered to this dialect.
Definition: Dialect.h:110
std::conditional_t< std::is_base_of<::mlir::Dialect, T >::value, T &, const T & > ret_type
Definition: Dialect.h:310
virtual LogicalResult verifyRegionArgAttribute(Operation *, unsigned regionIndex, unsigned argIndex, NamedAttribute)
Verify an attribute from this dialect on the argument at &#39;argIndex&#39; for the region at &#39;regionIndex&#39; o...
Definition: Dialect.cpp:42
InterfaceT::Concept * getRegisteredInterfaceForOp(OperationName opName)
Definition: Dialect.h:177
virtual void printAttribute(Attribute, DialectAsmPrinter &) const
Print an attribute registered to this dialect.
Definition: Dialect.h:102
static std::enable_if_t< std::is_base_of<::mlir::DialectInterface, To >::value, const To & > doitImpl(::mlir::Dialect &dialect)
Definition: Dialect.h:323
void addType(TypeID typeID, AbstractType &&typeInfo)
Register a type instance with this dialect.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
Definition: Dialect.h:86
This class helps build Operations.
Definition: Builders.h:184
This class contains all of the static information common to all instances of a registered Attribute...
The DialectAsmParser has methods for interacting with the asm parser when parsing attributes and type...
virtual Type parseType(DialectAsmParser &parser) const
Parse a type registered to this dialect.
Definition: Dialect.cpp:65
This class represents an interface overridden for a single dialect.
virtual LogicalResult verifyRegionResultAttribute(Operation *, unsigned regionIndex, unsigned resultIndex, NamedAttribute)
Verify an attribute from this dialect on the result at &#39;resultIndex&#39; for the region at &#39;regionIndex&#39; ...
Definition: Dialect.cpp:51
static bool isValidNamespace(StringRef str)
Utility function that returns if the given string is a valid dialect namespace.
Definition: Dialect.cpp:91