MLIR 24.0.0git
AttributeSupport.h
Go to the documentation of this file.
1//===- AttributeSupport.h ---------------------------------------*- 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 support types for registering dialect extended attributes.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef MLIR_IR_ATTRIBUTESUPPORT_H
14#define MLIR_IR_ATTRIBUTESUPPORT_H
15
16#include "mlir/IR/MLIRContext.h"
18#include "mlir/IR/Types.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/Twine.h"
21
22namespace mlir {
23//===----------------------------------------------------------------------===//
24// AbstractAttribute
25//===----------------------------------------------------------------------===//
26
27/// This class contains all of the static information common to all instances of
28/// a registered Attribute.
29class AbstractAttribute {
30public:
31 using HasTraitFn = llvm::unique_function<bool(TypeID) const>;
36
37 /// Look up the specified abstract attribute in the MLIRContext and return a
38 /// reference to it.
39 static const AbstractAttribute &lookup(TypeID typeID, MLIRContext *context);
40
41 /// Look up the specified abstract attribute in the MLIRContext and return a
42 /// reference to it if it exists.
43 static std::optional<std::reference_wrapper<const AbstractAttribute>>
44 lookup(StringRef name, MLIRContext *context);
45
46 /// This method is used by Dialect objects when they register the list of
47 /// attributes they contain.
48 template <typename T>
49 static AbstractAttribute get(Dialect &dialect) {
50 return AbstractAttribute(dialect, T::getInterfaceMap(), T::getHasTraitFn(),
51 T::getWalkImmediateSubElementsFn(),
52 T::getReplaceImmediateSubElementsFn(),
53 T::getTypeID(), T::name);
54 }
55
56 /// Register the attribute `T` with `dialect`.
57 template <typename T>
58 static void insert(Dialect &dialect);
59
60 /// This method is used by Dialect objects to register attributes with
61 /// custom TypeIDs.
62 /// The use of this method is in general discouraged in favor of
63 /// 'get<CustomAttribute>(dialect)'.
65 get(Dialect &dialect, detail::InterfaceMap &&interfaceMap,
67 WalkImmediateSubElementsFn walkImmediateSubElementsFn,
68 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn,
69 TypeID typeID, StringRef name) {
70 return AbstractAttribute(dialect, std::move(interfaceMap),
71 std::move(hasTrait), walkImmediateSubElementsFn,
72 replaceImmediateSubElementsFn, typeID, name);
73 }
74
75 /// Return the dialect this attribute was registered to.
76 Dialect &getDialect() const { return const_cast<Dialect &>(dialect); }
77
78 /// Returns an instance of the concept object for the given interface if it
79 /// was registered to this attribute, null otherwise. This should not be used
80 /// directly.
81 template <typename T>
82 typename T::Concept *getInterface() const {
83 return interfaceMap.lookup<T>();
84 }
85
86 /// Returns true if the attribute has the interface with the given ID
87 /// registered.
88 bool hasInterface(TypeID interfaceID) const {
89 return interfaceMap.contains(interfaceID);
90 }
91
92 /// Returns true if the attribute has a particular trait.
93 template <template <typename T> class Trait>
94 bool hasTrait() const {
95 return hasTraitFn(TypeID::get<Trait>());
96 }
97
98 /// Returns true if the attribute has a particular trait.
99 bool hasTrait(TypeID traitID) const { return hasTraitFn(traitID); }
100
101 /// Walk the immediate sub-elements of this attribute.
103 function_ref<void(Attribute)> walkAttrsFn,
104 function_ref<void(Type)> walkTypesFn) const;
105
106 /// Replace the immediate sub-elements of this attribute.
108 ArrayRef<Attribute> replAttrs,
109 ArrayRef<Type> replTypes) const;
110
111 /// Return the unique identifier representing the concrete attribute class.
112 TypeID getTypeID() const { return typeID; }
113
114 /// Return the unique name representing the type.
115 StringRef getName() const { return name; }
116
117private:
118 /// Registers `attrInfo` with `dialect` and returns the context of `dialect`.
119 /// This is the part of `insert<T>` that requires the definition of `Dialect`.
120 static MLIRContext *insert(Dialect &dialect, AbstractAttribute &&attrInfo);
121
122 AbstractAttribute(Dialect &dialect, detail::InterfaceMap &&interfaceMap,
123 HasTraitFn &&hasTraitFn,
124 WalkImmediateSubElementsFn walkImmediateSubElementsFn,
125 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn,
126 TypeID typeID, StringRef name)
127 : dialect(dialect), interfaceMap(std::move(interfaceMap)),
128 hasTraitFn(std::move(hasTraitFn)),
129 walkImmediateSubElementsFn(walkImmediateSubElementsFn),
130 replaceImmediateSubElementsFn(replaceImmediateSubElementsFn),
131 typeID(typeID), name(name) {}
132
133 /// Give StorageUserBase access to the mutable lookup.
134 template <typename ConcreteT, typename BaseT, typename StorageT,
135 typename UniquerT, template <typename T> class... Traits>
137
138 /// Look up the specified abstract attribute in the MLIRContext and return a
139 /// (mutable) pointer to it. Return a null pointer if the attribute could not
140 /// be found in the context.
141 static AbstractAttribute *lookupMutable(TypeID typeID, MLIRContext *context);
142
143 /// This is the dialect that this attribute was registered to.
144 const Dialect &dialect;
145
146 /// This is a collection of the interfaces registered to this attribute.
147 detail::InterfaceMap interfaceMap;
148
149 /// Function to check if the attribute has a particular trait.
150 HasTraitFn hasTraitFn;
151
152 /// Function to walk the immediate sub-elements of this attribute.
153 WalkImmediateSubElementsFn walkImmediateSubElementsFn;
154
155 /// Function to replace the immediate sub-elements of this attribute.
156 ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn;
157
158 /// The unique identifier of the derived Attribute class.
159 const TypeID typeID;
160
161 /// The unique name of this attribute. The string is not owned by the context,
162 /// so the lifetime of this string should outlive the MLIR context.
163 const StringRef name;
164};
165
166//===----------------------------------------------------------------------===//
167// AttributeStorage
168//===----------------------------------------------------------------------===//
169
170namespace detail {
171class AttributeUniquer;
172class DistinctAttributeUniquer;
173} // namespace detail
174
175/// Base storage class appearing in an attribute. Derived storage classes should
176/// only be constructed within the context of the AttributeUniquer.
180 friend StorageUniquer;
181
182public:
183 /// Return the abstract descriptor for this attribute.
185 assert(abstractAttribute && "Malformed attribute storage object.");
186 return *abstractAttribute;
187 }
188
189protected:
190 /// Set the abstract attribute for this storage instance. This is used by the
191 /// AttributeUniquer when initializing a newly constructed storage object.
193 abstractAttribute = &abstractAttr;
194 }
195
196 /// Default initialization for attribute storage classes that require no
197 /// additional initialization.
198 void initialize(MLIRContext *context) {}
199
200private:
201 /// The abstract descriptor for this attribute.
202 const AbstractAttribute *abstractAttribute = nullptr;
203};
204
205/// Default storage type for attributes that require no additional
206/// initialization or storage.
208
209//===----------------------------------------------------------------------===//
210// AttributeStorageAllocator
211//===----------------------------------------------------------------------===//
212
213// This is a utility allocator used to allocate memory for instances of derived
214// Attributes.
216
217//===----------------------------------------------------------------------===//
218// AttributeUniquer
219//===----------------------------------------------------------------------===//
220namespace detail {
221// A utility class to get, or create, unique instances of attributes within an
222// MLIRContext. This class manages all creation and uniquing of attributes.
224public:
225 /// Get an uniqued instance of an attribute T.
226 template <typename T, typename... Args>
227 static T get(MLIRContext *ctx, Args &&...args) {
228 return getWithTypeID<T, Args...>(ctx, T::getTypeID(),
229 std::forward<Args>(args)...);
230 }
231
232 /// Get an uniqued instance of a parametric attribute T.
233 /// The use of this method is in general discouraged in favor of
234 /// 'get<T, Args>(ctx, args)'.
235 template <typename T, typename... Args>
236 static std::enable_if_t<
237 !std::is_same<typename T::ImplType, AttributeStorage>::value, T>
238 getWithTypeID(MLIRContext *ctx, TypeID typeID, Args &&...args) {
239#ifndef NDEBUG
241 llvm::report_fatal_error(
242 llvm::Twine("can't create Attribute '") + llvm::getTypeName<T>() +
243 "' because storage uniquer isn't initialized: the dialect was likely "
244 "not loaded, or the attribute wasn't added with addAttributes<...>() "
245 "in the Dialect::initialize() method.");
246#endif
247 return ctx->getAttributeUniquer().get<typename T::ImplType>(
248 [typeID, ctx](AttributeStorage *storage) {
249 initializeAttributeStorage(storage, ctx, typeID);
250
251 // Execute any additional attribute storage initialization with the
252 // context.
253 static_cast<typename T::ImplType *>(storage)->initialize(ctx);
254 },
255 typeID, std::forward<Args>(args)...);
256 }
257 /// Get an uniqued instance of a singleton attribute T.
258 /// The use of this method is in general discouraged in favor of
259 /// 'get<T, Args>(ctx, args)'.
260 template <typename T>
261 static std::enable_if_t<
262 std::is_same<typename T::ImplType, AttributeStorage>::value, T>
264#ifndef NDEBUG
266 llvm::report_fatal_error(
267 llvm::Twine("can't create Attribute '") + llvm::getTypeName<T>() +
268 "' because storage uniquer isn't initialized: the dialect was likely "
269 "not loaded, or the attribute wasn't added with addAttributes<...>() "
270 "in the Dialect::initialize() method.");
271#endif
272 return ctx->getAttributeUniquer().get<typename T::ImplType>(typeID);
273 }
274
275 template <typename T, typename... Args>
276 static LogicalResult mutate(MLIRContext *ctx, typename T::ImplType *impl,
277 Args &&...args) {
278 assert(impl && "cannot mutate null attribute");
279 return ctx->getAttributeUniquer().mutate(T::getTypeID(), impl,
280 std::forward<Args>(args)...);
281 }
282
283 /// Register an attribute instance T with the uniquer.
284 template <typename T>
285 static void registerAttribute(MLIRContext *ctx) {
286 registerAttribute<T>(ctx, T::getTypeID());
287 }
288
289 /// Register a parametric attribute instance T with the uniquer.
290 /// The use of this method is in general discouraged in favor of
291 /// 'registerAttribute<T>(ctx)'.
292 template <typename T>
293 static std::enable_if_t<
294 !std::is_same<typename T::ImplType, AttributeStorage>::value>
297 .registerParametricStorageType<typename T::ImplType>(typeID);
298 }
299 /// Register a singleton attribute instance T with the uniquer.
300 /// The use of this method is in general discouraged in favor of
301 /// 'registerAttribute<T>(ctx)'.
302 template <typename T>
303 static std::enable_if_t<
304 std::is_same<typename T::ImplType, AttributeStorage>::value>
307 .registerSingletonStorageType<typename T::ImplType>(
308 typeID, [ctx, typeID](AttributeStorage *storage) {
309 initializeAttributeStorage(storage, ctx, typeID);
310 });
311 }
312
313private:
314 /// Initialize the given attribute storage instance.
315 static void initializeAttributeStorage(AttributeStorage *storage,
316 MLIRContext *ctx, TypeID attrID);
317};
318
319// Internal function called by ODS generated code.
320// Default initializes the type within a FailureOr<T> if T is default
321// constructible and returns a reference to the instance.
322// Otherwise, returns a reference to the FailureOr<T>.
323template <class T>
324decltype(auto) unwrapForCustomParse(FailureOr<T> &failureOr) {
325 if constexpr (std::is_default_constructible_v<T>)
326 return failureOr.emplace();
327 else
328 return failureOr;
329}
330
331} // namespace detail
332
333template <typename T>
335 MLIRContext *context = insert(dialect, get<T>(dialect));
337}
338} // namespace mlir
339
340#endif
LogicalResult initialize(unsigned origNumLoops, ArrayRef< ReassociationIndices > foldedIterationDims)
This class contains all of the static information common to all instances of a registered Attribute.
llvm::unique_function< bool(TypeID) const > HasTraitFn
function_ref< void( Attribute, function_ref< void(Attribute)>, function_ref< void(Type)>)> WalkImmediateSubElementsFn
static AbstractAttribute get(Dialect &dialect)
This method is used by Dialect objects when they register the list of attributes they contain.
function_ref< Attribute(Attribute, ArrayRef< Attribute >, ArrayRef< Type >)> ReplaceImmediateSubElementsFn
static void insert(Dialect &dialect)
Register the attribute T with dialect.
static const AbstractAttribute & lookup(TypeID typeID, MLIRContext *context)
Look up the specified abstract attribute in the MLIRContext and return a reference to it.
TypeID getTypeID() const
Return the unique identifier representing the concrete attribute class.
Dialect & getDialect() const
Return the dialect this attribute was registered to.
static AbstractAttribute get(Dialect &dialect, detail::InterfaceMap &&interfaceMap, HasTraitFn &&hasTrait, WalkImmediateSubElementsFn walkImmediateSubElementsFn, ReplaceImmediateSubElementsFn replaceImmediateSubElementsFn, TypeID typeID, StringRef name)
This method is used by Dialect objects to register attributes with custom TypeIDs.
bool hasTrait() const
Returns true if the attribute has a particular trait.
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this attrib...
void walkImmediateSubElements(Attribute attr, function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk the immediate sub-elements of this attribute.
bool hasTrait(TypeID traitID) const
Returns true if the attribute has a particular trait.
Attribute replaceImmediateSubElements(Attribute attr, ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediate sub-elements of this attribute.
StringRef getName() const
Return the unique name representing the type.
bool hasInterface(TypeID interfaceID) const
Returns true if the attribute has the interface with the given ID registered.
Base storage class appearing in an attribute.
void initializeAbstractAttribute(const AbstractAttribute &abstractAttr)
Set the abstract attribute for this storage instance.
const AbstractAttribute & getAbstractAttribute() const
Return the abstract descriptor for this attribute.
void initialize(MLIRContext *context)
Default initialization for attribute storage classes that require no additional initialization.
Attributes are known-constant values of operations.
Definition Attributes.h:25
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition Dialect.h:38
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
StorageUniquer & getAttributeUniquer()
Returns the storage uniquer used for constructing attribute storage instances.
This class acts as the base storage that all storage classes must derived from.
This is a utility allocator used to allocate memory for instances of derived types.
LogicalResult mutate(TypeID id, Storage *storage, Args &&...args)
Changes the mutable component of 'storage' by forwarding the trailing arguments to the 'mutate' funct...
void registerSingletonStorageType(TypeID id, function_ref< void(Storage *)> initFn)
Register a new singleton storage class, this is necessary to get the singletone instance.
Storage * get(function_ref< void(Storage *)> initFn, TypeID id, Args &&...args)
Gets a uniqued instance of 'Storage'.
bool isSingletonStorageInitialized(TypeID id)
Test if there is a singleton storage uniquer initialized for the provided TypeID.
bool isParametricStorageInitialized(TypeID id)
Test if there is a parametric storage uniquer initialized for the provided TypeID.
void registerParametricStorageType(TypeID id)
Register a new parametric storage class, this is necessary to create instances of this class type.
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
static TypeID get()
Construct a type info object for the given type T.
Definition TypeID.h:245
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
static std::enable_if_t< std::is_same< typename T::ImplType, AttributeStorage >::value, T > getWithTypeID(MLIRContext *ctx, TypeID typeID)
Get an uniqued instance of a singleton attribute T.
static void registerAttribute(MLIRContext *ctx)
Register an attribute instance T with the uniquer.
static std::enable_if_t< !std::is_same< typename T::ImplType, AttributeStorage >::value > registerAttribute(MLIRContext *ctx, TypeID typeID)
Register a parametric attribute instance T with the uniquer.
static T get(MLIRContext *ctx, Args &&...args)
Get an uniqued instance of an attribute T.
static std::enable_if_t< !std::is_same< typename T::ImplType, AttributeStorage >::value, T > getWithTypeID(MLIRContext *ctx, TypeID typeID, Args &&...args)
Get an uniqued instance of a parametric attribute T.
static LogicalResult mutate(MLIRContext *ctx, typename T::ImplType *impl, Args &&...args)
static std::enable_if_t< std::is_same< typename T::ImplType, AttributeStorage >::value > registerAttribute(MLIRContext *ctx, TypeID typeID)
Register a singleton attribute instance T with the uniquer.
A specialized attribute uniquer for distinct attributes that always allocates since the distinct attr...
This class provides an efficient mapping between a given Interface type, and a particular implementat...
Utility class for implementing users of storage classes uniqued by a StorageUniquer.
AttrTypeReplacer.
decltype(auto) unwrapForCustomParse(FailureOr< T > &failureOr)
Include the generated interface declarations.
StorageUniquer::StorageAllocator AttributeStorageAllocator
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
AttributeStorage DefaultAttributeStorage
Default storage type for attributes that require no additional initialization or storage.