MLIR  17.0.0git
Attributes.h
Go to the documentation of this file.
1 //===- Attributes.h - MLIR Attribute Classes --------------------*- 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 #ifndef MLIR_IR_ATTRIBUTES_H
10 #define MLIR_IR_ATTRIBUTES_H
11 
13 #include "llvm/Support/PointerLikeTypeTraits.h"
14 
15 namespace mlir {
16 class AsmState;
17 class StringAttr;
18 
19 /// Attributes are known-constant values of operations.
20 ///
21 /// Instances of the Attribute class are references to immortal key-value pairs
22 /// with immutable, uniqued keys owned by MLIRContext. As such, an Attribute is
23 /// a thin wrapper around an underlying storage pointer. Attributes are usually
24 /// passed by value.
25 class Attribute {
26 public:
27  /// Utility class for implementing attributes.
28  template <typename ConcreteType, typename BaseType, typename StorageType,
29  template <typename T> class... Traits>
30  using AttrBase = detail::StorageUserBase<ConcreteType, BaseType, StorageType,
31  detail::AttributeUniquer, Traits...>;
32 
34  using ValueType = void;
36 
37  constexpr Attribute() = default;
38  /* implicit */ Attribute(const ImplType *impl)
39  : impl(const_cast<ImplType *>(impl)) {}
40 
41  Attribute(const Attribute &other) = default;
42  Attribute &operator=(const Attribute &other) = default;
43 
44  bool operator==(Attribute other) const { return impl == other.impl; }
45  bool operator!=(Attribute other) const { return !(*this == other); }
46  explicit operator bool() const { return impl; }
47 
48  bool operator!() const { return impl == nullptr; }
49 
50  /// Casting utility functions. These are deprecated and will be removed,
51  /// please prefer using the `llvm` namespace variants instead.
52  template <typename... Tys>
53  bool isa() const;
54  template <typename... Tys>
55  bool isa_and_nonnull() const;
56  template <typename U>
57  U dyn_cast() const;
58  template <typename U>
59  U dyn_cast_or_null() const;
60  template <typename U>
61  U cast() const;
62 
63  /// Return a unique identifier for the concrete attribute type. This is used
64  /// to support dynamic type casting.
65  TypeID getTypeID() { return impl->getAbstractAttribute().getTypeID(); }
66 
67  /// Return the context this attribute belongs to.
68  MLIRContext *getContext() const;
69 
70  /// Get the dialect this attribute is registered to.
71  Dialect &getDialect() const {
72  return impl->getAbstractAttribute().getDialect();
73  }
74 
75  /// Print the attribute. If `elideType` is set, the attribute is printed
76  /// without a trailing colon type if it has one.
77  void print(raw_ostream &os, bool elideType = false) const;
78  void print(raw_ostream &os, AsmState &state, bool elideType = false) const;
79  void dump() const;
80 
81  /// Get an opaque pointer to the attribute.
82  const void *getAsOpaquePointer() const { return impl; }
83  /// Construct an attribute from the opaque pointer representation.
84  static Attribute getFromOpaquePointer(const void *ptr) {
85  return Attribute(reinterpret_cast<const ImplType *>(ptr));
86  }
87 
88  friend ::llvm::hash_code hash_value(Attribute arg);
89 
90  /// Returns true if the type was registered with a particular trait.
91  template <template <typename T> class Trait>
92  bool hasTrait() {
93  return getAbstractAttribute().hasTrait<Trait>();
94  }
95 
96  /// Return the abstract descriptor for this attribute.
98  return impl->getAbstractAttribute();
99  }
100 
101  /// Walk all of the immediately nested sub-attributes and sub-types. This
102  /// method does not recurse into sub elements.
104  function_ref<void(Type)> walkTypesFn) const {
105  getAbstractAttribute().walkImmediateSubElements(*this, walkAttrsFn,
106  walkTypesFn);
107  }
108 
109  /// Replace the immediately nested sub-attributes and sub-types with those
110  /// provided. The order of the provided elements is derived from the order of
111  /// the elements returned by the callbacks of `walkImmediateSubElements`. The
112  /// element at index 0 would replace the very first attribute given by
113  /// `walkImmediateSubElements`. On success, the new instance with the values
114  /// replaced is returned. If replacement fails, nullptr is returned.
116  ArrayRef<Type> replTypes) const {
117  return getAbstractAttribute().replaceImmediateSubElements(*this, replAttrs,
118  replTypes);
119  }
120 
121  /// Walk this attribute and all attibutes/types nested within using the
122  /// provided walk functions. See `AttrTypeWalker` for information on the
123  /// supported walk function types.
124  template <WalkOrder Order = WalkOrder::PostOrder, typename... WalkFns>
125  auto walk(WalkFns &&...walkFns) {
126  AttrTypeWalker walker;
127  (walker.addWalk(std::forward<WalkFns>(walkFns)), ...);
128  return walker.walk<Order>(*this);
129  }
130 
131  /// Recursively replace all of the nested sub-attributes and sub-types using
132  /// the provided map functions. Returns nullptr in the case of failure. See
133  /// `AttrTypeReplacer` for information on the support replacement function
134  /// types.
135  template <typename... ReplacementFns>
136  auto replace(ReplacementFns &&...replacementFns) {
137  AttrTypeReplacer replacer;
138  (replacer.addReplacement(std::forward<ReplacementFns>(replacementFns)),
139  ...);
140  return replacer.replace(*this);
141  }
142 
143  /// Return the internal Attribute implementation.
144  ImplType *getImpl() const { return impl; }
145 
146 protected:
147  ImplType *impl{nullptr};
148 };
149 
150 inline raw_ostream &operator<<(raw_ostream &os, Attribute attr) {
151  attr.print(os);
152  return os;
153 }
154 
155 template <typename... Tys>
156 bool Attribute::isa() const {
157  return llvm::isa<Tys...>(*this);
158 }
159 
160 template <typename... Tys>
162  return llvm::isa_and_present<Tys...>(*this);
163 }
164 
165 template <typename U>
167  return llvm::dyn_cast<U>(*this);
168 }
169 
170 template <typename U>
172  return llvm::dyn_cast_if_present<U>(*this);
173 }
174 
175 template <typename U>
176 U Attribute::cast() const {
177  return llvm::cast<U>(*this);
178 }
179 
180 inline ::llvm::hash_code hash_value(Attribute arg) {
182 }
183 
184 //===----------------------------------------------------------------------===//
185 // NamedAttribute
186 //===----------------------------------------------------------------------===//
187 
188 /// NamedAttribute represents a combination of a name and an Attribute value.
190 public:
191  NamedAttribute(StringAttr name, Attribute value);
192 
193  /// Return the name of the attribute.
194  StringAttr getName() const;
195 
196  /// Return the dialect of the name of this attribute, if the name is prefixed
197  /// by a dialect namespace. For example, `llvm.fast_math` would return the
198  /// LLVM dialect (if it is loaded). Returns nullptr if the dialect isn't
199  /// loaded, or if the name is not prefixed by a dialect namespace.
200  Dialect *getNameDialect() const;
201 
202  /// Return the value of the attribute.
203  Attribute getValue() const { return value; }
204 
205  /// Set the name of this attribute.
206  void setName(StringAttr newName);
207 
208  /// Set the value of this attribute.
209  void setValue(Attribute newValue) {
210  assert(value && "expected valid attribute value");
211  value = newValue;
212  }
213 
214  /// Compare this attribute to the provided attribute, ordering by name.
215  bool operator<(const NamedAttribute &rhs) const;
216  /// Compare this attribute to the provided string, ordering by name.
217  bool operator<(StringRef rhs) const;
218 
219  bool operator==(const NamedAttribute &rhs) const {
220  return name == rhs.name && value == rhs.value;
221  }
222  bool operator!=(const NamedAttribute &rhs) const { return !(*this == rhs); }
223 
224 private:
225  NamedAttribute(Attribute name, Attribute value) : name(name), value(value) {}
226 
227  /// Allow access to internals to enable hashing.
228  friend ::llvm::hash_code hash_value(const NamedAttribute &arg);
229  friend DenseMapInfo<NamedAttribute>;
230 
231  /// The name of the attribute. This is represented as a StringAttr, but
232  /// type-erased to Attribute in the field.
233  Attribute name;
234  /// The value of the attribute.
235  Attribute value;
236 };
237 
238 inline ::llvm::hash_code hash_value(const NamedAttribute &arg) {
239  using AttrPairT = std::pair<Attribute, Attribute>;
240  return DenseMapInfo<AttrPairT>::getHashValue(AttrPairT(arg.name, arg.value));
241 }
242 
243 /// Allow walking and replacing the subelements of a NamedAttribute.
244 template <>
246  template <typename T>
247  static void walk(T param, AttrTypeImmediateSubElementWalker &walker) {
248  walker.walk(param.getName());
249  walker.walk(param.getValue());
250  }
251  template <typename T>
252  static T replace(T param, AttrSubElementReplacements &attrRepls,
253  TypeSubElementReplacements &typeRepls) {
254  ArrayRef<Attribute> paramRepls = attrRepls.take_front(2);
255  return T(cast<decltype(param.getName())>(paramRepls[0]), paramRepls[1]);
256  }
257 };
258 
259 //===----------------------------------------------------------------------===//
260 // AttributeTraitBase
261 //===----------------------------------------------------------------------===//
262 
263 namespace AttributeTrait {
264 /// This class represents the base of an attribute trait.
265 template <typename ConcreteType, template <typename> class TraitType>
267 } // namespace AttributeTrait
268 
269 //===----------------------------------------------------------------------===//
270 // AttributeInterface
271 //===----------------------------------------------------------------------===//
272 
273 /// This class represents the base of an attribute interface. See the definition
274 /// of `detail::Interface` for requirements on the `Traits` type.
275 template <typename ConcreteType, typename Traits>
277  : public detail::Interface<ConcreteType, Attribute, Traits, Attribute,
278  AttributeTrait::TraitBase> {
279 public:
281  using InterfaceBase = detail::Interface<ConcreteType, Attribute, Traits,
284 
285 private:
286  /// Returns the impl interface instance for the given type.
287  static typename InterfaceBase::Concept *getInterfaceFor(Attribute attr) {
288  return attr.getAbstractAttribute().getInterface<ConcreteType>();
289  }
290 
291  /// Allow access to 'getInterfaceFor'.
292  friend InterfaceBase;
293 };
294 
295 //===----------------------------------------------------------------------===//
296 // Core AttributeTrait
297 //===----------------------------------------------------------------------===//
298 
299 /// This trait is used to determine if an attribute is mutable or not. It is
300 /// attached on an attribute if the corresponding ImplType defines a `mutate`
301 /// function with proper signature.
302 namespace AttributeTrait {
303 template <typename ConcreteType>
305 } // namespace AttributeTrait
306 
307 } // namespace mlir.
308 
309 namespace llvm {
310 
311 // Attribute hash just like pointers.
312 template <>
313 struct DenseMapInfo<mlir::Attribute> {
315  auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
316  return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
317  }
320  return mlir::Attribute(static_cast<mlir::Attribute::ImplType *>(pointer));
321  }
322  static unsigned getHashValue(mlir::Attribute val) {
323  return mlir::hash_value(val);
324  }
325  static bool isEqual(mlir::Attribute LHS, mlir::Attribute RHS) {
326  return LHS == RHS;
327  }
328 };
329 template <typename T>
331  T, std::enable_if_t<std::is_base_of<mlir::Attribute, T>::value &&
332  !mlir::detail::IsInterface<T>::value>>
333  : public DenseMapInfo<mlir::Attribute> {
334  static T getEmptyKey() {
335  const void *pointer = llvm::DenseMapInfo<const void *>::getEmptyKey();
336  return T::getFromOpaquePointer(pointer);
337  }
338  static T getTombstoneKey() {
340  return T::getFromOpaquePointer(pointer);
341  }
342 };
343 
344 /// Allow LLVM to steal the low bits of Attributes.
345 template <>
346 struct PointerLikeTypeTraits<mlir::Attribute> {
347  static inline void *getAsVoidPointer(mlir::Attribute attr) {
348  return const_cast<void *>(attr.getAsOpaquePointer());
349  }
350  static inline mlir::Attribute getFromVoidPointer(void *ptr) {
352  }
353  static constexpr int NumLowBitsAvailable = llvm::PointerLikeTypeTraits<
354  mlir::AttributeStorage *>::NumLowBitsAvailable;
355 };
356 
357 template <>
358 struct DenseMapInfo<mlir::NamedAttribute> {
361  return mlir::NamedAttribute(emptyAttr, emptyAttr);
362  }
365  return mlir::NamedAttribute(tombAttr, tombAttr);
366  }
367  static unsigned getHashValue(mlir::NamedAttribute val) {
368  return mlir::hash_value(val);
369  }
371  return lhs == rhs;
372  }
373 };
374 
375 /// Add support for llvm style casts. We provide a cast between To and From if
376 /// From is mlir::Attribute or derives from it.
377 template <typename To, typename From>
378 struct CastInfo<To, From,
379  std::enable_if_t<std::is_same_v<mlir::Attribute,
380  std::remove_const_t<From>> ||
381  std::is_base_of_v<mlir::Attribute, From>>>
383  DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
384  /// Arguments are taken as mlir::Attribute here and not as `From`, because
385  /// when casting from an intermediate type of the hierarchy to one of its
386  /// children, the val.getTypeID() inside T::classof will use the static
387  /// getTypeID of the parent instead of the non-static Type::getTypeID that
388  /// returns the dynamic ID. This means that T::classof would end up comparing
389  /// the static TypeID of the children to the static TypeID of its parent,
390  /// making it impossible to downcast from the parent to the child.
391  static inline bool isPossible(mlir::Attribute ty) {
392  /// Return a constant true instead of a dynamic true when casting to self or
393  /// up the hierarchy.
394  if constexpr (std::is_base_of_v<To, From>) {
395  (void)ty;
396  return true;
397  } else {
398  return To::classof(ty);
399  }
400  }
401  static inline To doCast(mlir::Attribute attr) { return To(attr.getImpl()); }
402 };
403 
404 } // namespace llvm
405 
406 #endif
This class contains all of the static information common to all instances of a registered Attribute.
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this attrib...
bool hasTrait() const
Returns true if the attribute has a particular trait.
void walkImmediateSubElements(Attribute attr, function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk the immediate sub-elements of this attribute.
Definition: Attributes.cpp:19
Attribute replaceImmediateSubElements(Attribute attr, ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediate sub-elements of this attribute.
Definition: Attributes.cpp:26
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:525
void walk(Attribute element)
Walk an attribute.
Attribute replace(Attribute attr)
Replace the given attribute/type, and recursively replace any sub elements.
void addReplacement(ReplaceFn< Attribute > fn)
Register a replacement function for mapping a given attribute or type.
This class is used by AttrTypeSubElementHandler instances to process sub element replacements.
ArrayRef< T > take_front(unsigned n)
Take the first N replacements as an ArrayRef, dropping them from this replacement list.
void addWalk(WalkFn< Attribute > &&fn)
Register a walk function for a given attribute or type.
WalkResult walk(T element)
Walk the given attribute/type, and recursively walk any sub elements.
This class represents the base of an attribute interface.
Definition: Attributes.h:278
detail::Interface< ConcreteType, Attribute, Traits, Attribute, AttributeTrait::TraitBase > InterfaceBase
Definition: Attributes.h:282
Base storage class appearing in an attribute.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
U dyn_cast_or_null() const
Definition: Attributes.h:171
Dialect & getDialect() const
Get the dialect this attribute is registered to.
Definition: Attributes.h:71
U dyn_cast() const
Definition: Attributes.h:166
auto walk(WalkFns &&...walkFns)
Walk this attribute and all attibutes/types nested within using the provided walk functions.
Definition: Attributes.h:125
ImplType * impl
Definition: Attributes.h:147
bool operator!() const
Definition: Attributes.h:48
Attribute(const ImplType *impl)
Definition: Attributes.h:38
constexpr Attribute()=default
U cast() const
Definition: Attributes.h:176
const AbstractTy & getAbstractAttribute() const
Return the abstract descriptor for this attribute.
Definition: Attributes.h:97
bool operator==(Attribute other) const
Definition: Attributes.h:44
void print(raw_ostream &os, bool elideType=false) const
Print the attribute.
auto replace(ReplacementFns &&...replacementFns)
Recursively replace all of the nested sub-attributes and sub-types using the provided map functions.
Definition: Attributes.h:136
void walkImmediateSubElements(function_ref< void(Attribute)> walkAttrsFn, function_ref< void(Type)> walkTypesFn) const
Walk all of the immediately nested sub-attributes and sub-types.
Definition: Attributes.h:103
void dump() const
bool operator!=(Attribute other) const
Definition: Attributes.h:45
bool isa() const
Casting utility functions.
Definition: Attributes.h:156
MLIRContext * getContext() const
Return the context this attribute belongs to.
Definition: Attributes.cpp:37
auto replaceImmediateSubElements(ArrayRef< Attribute > replAttrs, ArrayRef< Type > replTypes) const
Replace the immediately nested sub-attributes and sub-types with those provided.
Definition: Attributes.h:115
Attribute & operator=(const Attribute &other)=default
friend ::llvm::hash_code hash_value(Attribute arg)
Definition: Attributes.h:180
bool hasTrait()
Returns true if the type was registered with a particular trait.
Definition: Attributes.h:92
const void * getAsOpaquePointer() const
Get an opaque pointer to the attribute.
Definition: Attributes.h:82
Attribute(const Attribute &other)=default
bool isa_and_nonnull() const
Definition: Attributes.h:161
ImplType * getImpl() const
Return the internal Attribute implementation.
Definition: Attributes.h:144
TypeID getTypeID()
Return a unique identifier for the concrete attribute type.
Definition: Attributes.h:65
static Attribute getFromOpaquePointer(const void *ptr)
Construct an attribute from the opaque pointer representation.
Definition: Attributes.h:84
Dialects are groups of MLIR operations, types and attributes, as well as behavior associated with the...
Definition: Dialect.h:41
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
NamedAttribute represents a combination of a name and an Attribute value.
Definition: Attributes.h:189
StringAttr getName() const
Return the name of the attribute.
Definition: Attributes.cpp:49
void setName(StringAttr newName)
Set the name of this attribute.
Definition: Attributes.cpp:57
bool operator==(const NamedAttribute &rhs) const
Definition: Attributes.h:219
bool operator<(const NamedAttribute &rhs) const
Compare this attribute to the provided attribute, ordering by name.
Definition: Attributes.cpp:62
NamedAttribute(StringAttr name, Attribute value)
Definition: Attributes.cpp:43
Dialect * getNameDialect() const
Return the dialect of the name of this attribute, if the name is prefixed by a dialect namespace.
Definition: Attributes.cpp:53
friend ::llvm::hash_code hash_value(const NamedAttribute &arg)
Allow access to internals to enable hashing.
Definition: Attributes.h:238
void setValue(Attribute newValue)
Set the value of this attribute.
Definition: Attributes.h:209
Attribute getValue() const
Return the value of the attribute.
Definition: Attributes.h:203
bool operator!=(const NamedAttribute &rhs) const
Definition: Attributes.h:222
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
This class represents an abstract interface.
Interface< ConcreteType, Attribute, Traits, Attribute, AttributeTrait::TraitBase > InterfaceBase
Utility class for implementing users of storage classes uniqued by a StorageUniquer.
Helper class for implementing traits for storage classes.
Include the generated interface declarations.
Definition: CallGraph.h:229
This header declares functions that assit transformations in the MemRef dialect.
WalkOrder
Traversal order for region, block and operation walk utilities.
Definition: Visitors.h:63
inline ::llvm::hash_code hash_value(AffineExpr arg)
Make AffineExpr hashable.
Definition: AffineExpr.h:240
raw_ostream & operator<<(raw_ostream &os, const AliasResult &result)
Definition: AliasAnalysis.h:78
static bool isPossible(mlir::Attribute ty)
Arguments are taken as mlir::Attribute here and not as From, because when casting from an intermediat...
Definition: Attributes.h:391
static bool isEqual(mlir::Attribute LHS, mlir::Attribute RHS)
Definition: Attributes.h:325
static unsigned getHashValue(mlir::Attribute val)
Definition: Attributes.h:322
static mlir::Attribute getEmptyKey()
Definition: Attributes.h:314
static mlir::Attribute getTombstoneKey()
Definition: Attributes.h:318
static unsigned getHashValue(mlir::NamedAttribute val)
Definition: Attributes.h:367
static mlir::NamedAttribute getEmptyKey()
Definition: Attributes.h:359
static mlir::NamedAttribute getTombstoneKey()
Definition: Attributes.h:363
static bool isEqual(mlir::NamedAttribute lhs, mlir::NamedAttribute rhs)
Definition: Attributes.h:370
static mlir::Attribute getFromVoidPointer(void *ptr)
Definition: Attributes.h:350
static void * getAsVoidPointer(mlir::Attribute attr)
Definition: Attributes.h:347
static void walk(T param, AttrTypeImmediateSubElementWalker &walker)
Definition: Attributes.h:247
static T replace(T param, AttrSubElementReplacements &attrRepls, TypeSubElementReplacements &typeRepls)
Definition: Attributes.h:252
This class provides support for interacting with the SubElementInterfaces for different types of para...
This trait is used to determine if a storage user, like Type, is mutable or not.