MLIR  17.0.0git
Types.h
Go to the documentation of this file.
1 //===- Types.h - MLIR Type 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_TYPES_H
10 #define MLIR_IR_TYPES_H
11 
12 #include "mlir/IR/TypeSupport.h"
13 #include "llvm/ADT/ArrayRef.h"
14 #include "llvm/ADT/DenseMapInfo.h"
15 #include "llvm/Support/PointerLikeTypeTraits.h"
16 
17 namespace mlir {
18 class AsmState;
19 
20 /// Instances of the Type class are uniqued, have an immutable identifier and an
21 /// optional mutable component. They wrap a pointer to the storage object owned
22 /// by MLIRContext. Therefore, instances of Type are passed around by value.
23 ///
24 /// Some types are "primitives" meaning they do not have any parameters, for
25 /// example the Index type. Parametric types have additional information that
26 /// differentiates the types of the same class, for example the Integer type has
27 /// bitwidth, making i8 and i16 belong to the same kind by be different
28 /// instances of the IntegerType. Type parameters are part of the unique
29 /// immutable key. The mutable component of the type can be modified after the
30 /// type is created, but cannot affect the identity of the type.
31 ///
32 /// Types are constructed and uniqued via the 'detail::TypeUniquer' class.
33 ///
34 /// Derived type classes are expected to implement several required
35 /// implementation hooks:
36 /// * Optional:
37 /// - static LogicalResult verify(
38 /// function_ref<InFlightDiagnostic()> emitError,
39 /// Args... args)
40 /// * This method is invoked when calling the 'TypeBase::get/getChecked'
41 /// methods to ensure that the arguments passed in are valid to construct
42 /// a type instance with.
43 /// * This method is expected to return failure if a type cannot be
44 /// constructed with 'args', success otherwise.
45 /// * 'args' must correspond with the arguments passed into the
46 /// 'TypeBase::get' call.
47 ///
48 ///
49 /// Type storage objects inherit from TypeStorage and contain the following:
50 /// - The dialect that defined the type.
51 /// - Any parameters of the type.
52 /// - An optional mutable component.
53 /// For non-parametric types, a convenience DefaultTypeStorage is provided.
54 /// Parametric storage types must derive TypeStorage and respect the following:
55 /// - Define a type alias, KeyTy, to a type that uniquely identifies the
56 /// instance of the type.
57 /// * The key type must be constructible from the values passed into the
58 /// detail::TypeUniquer::get call.
59 /// * If the KeyTy does not have an llvm::DenseMapInfo specialization, the
60 /// storage class must define a hashing method:
61 /// 'static unsigned hashKey(const KeyTy &)'
62 ///
63 /// - Provide a method, 'bool operator==(const KeyTy &) const', to
64 /// compare the storage instance against an instance of the key type.
65 ///
66 /// - Provide a static construction method:
67 /// 'DerivedStorage *construct(TypeStorageAllocator &, const KeyTy &key)'
68 /// that builds a unique instance of the derived storage. The arguments to
69 /// this function are an allocator to store any uniqued data within the
70 /// context and the key type for this storage.
71 ///
72 /// - If they have a mutable component, this component must not be a part of
73 /// the key.
74 class Type {
75 public:
76  /// Utility class for implementing types.
77  template <typename ConcreteType, typename BaseType, typename StorageType,
78  template <typename T> class... Traits>
79  using TypeBase = detail::StorageUserBase<ConcreteType, BaseType, StorageType,
80  detail::TypeUniquer, Traits...>;
81 
83 
85 
86  constexpr Type() = default;
87  /* implicit */ Type(const ImplType *impl)
88  : impl(const_cast<ImplType *>(impl)) {}
89 
90  Type(const Type &other) = default;
91  Type &operator=(const Type &other) = default;
92 
93  bool operator==(Type other) const { return impl == other.impl; }
94  bool operator!=(Type other) const { return !(*this == other); }
95  explicit operator bool() const { return impl; }
96 
97  bool operator!() const { return impl == nullptr; }
98 
99  template <typename... Tys>
100  bool isa() const;
101  template <typename... Tys>
102  bool isa_and_nonnull() const;
103  template <typename U>
104  U dyn_cast() const;
105  template <typename U>
106  U dyn_cast_or_null() const;
107  template <typename U>
108  U cast() const;
109 
110  // Support type casting Type to itself.
111  static bool classof(Type) { return true; }
112 
113  /// Return a unique identifier for the concrete type. This is used to support
114  /// dynamic type casting.
115  TypeID getTypeID() { return impl->getAbstractType().getTypeID(); }
116 
117  /// Return the MLIRContext in which this type was uniqued.
118  MLIRContext *getContext() const;
119 
120  /// Get the dialect this type is registered to.
121  Dialect &getDialect() const { return impl->getAbstractType().getDialect(); }
122 
123  // Convenience predicates. This is only for floating point types,
124  // derived types should use isa/dyn_cast.
125  bool isIndex() const;
126  bool isFloat8E5M2() const;
127  bool isFloat8E4M3FN() const;
128  bool isBF16() const;
129  bool isF16() const;
130  bool isF32() const;
131  bool isF64() const;
132  bool isF80() const;
133  bool isF128() const;
134 
135  /// Return true if this is an integer type with the specified width.
136  bool isInteger(unsigned width) const;
137  /// Return true if this is a signless integer type (with the specified width).
138  bool isSignlessInteger() const;
139  bool isSignlessInteger(unsigned width) const;
140  /// Return true if this is a signed integer type (with the specified width).
141  bool isSignedInteger() const;
142  bool isSignedInteger(unsigned width) const;
143  /// Return true if this is an unsigned integer type (with the specified
144  /// width).
145  bool isUnsignedInteger() const;
146  bool isUnsignedInteger(unsigned width) const;
147 
148  /// Return the bit width of an integer or a float type, assert failure on
149  /// other types.
150  unsigned getIntOrFloatBitWidth() const;
151 
152  /// Return true if this is a signless integer or index type.
153  bool isSignlessIntOrIndex() const;
154  /// Return true if this is a signless integer, index, or float type.
155  bool isSignlessIntOrIndexOrFloat() const;
156  /// Return true of this is a signless integer or a float type.
157  bool isSignlessIntOrFloat() const;
158 
159  /// Return true if this is an integer (of any signedness) or an index type.
160  bool isIntOrIndex() const;
161  /// Return true if this is an integer (of any signedness) or a float type.
162  bool isIntOrFloat() const;
163  /// Return true if this is an integer (of any signedness), index, or float
164  /// type.
165  bool isIntOrIndexOrFloat() const;
166 
167  /// Print the current type.
168  void print(raw_ostream &os) const;
169  void print(raw_ostream &os, AsmState &state) const;
170  void dump() const;
171 
172  friend ::llvm::hash_code hash_value(Type arg);
173 
174  /// Methods for supporting PointerLikeTypeTraits.
175  const void *getAsOpaquePointer() const {
176  return static_cast<const void *>(impl);
177  }
178  static Type getFromOpaquePointer(const void *pointer) {
179  return Type(reinterpret_cast<ImplType *>(const_cast<void *>(pointer)));
180  }
181 
182  /// Returns true if the type was registered with a particular trait.
183  template <template <typename T> class Trait>
184  bool hasTrait() {
185  return getAbstractType().hasTrait<Trait>();
186  }
187 
188  /// Return the abstract type descriptor for this type.
189  const AbstractTy &getAbstractType() { return impl->getAbstractType(); }
190 
191  /// Return the Type implementation.
192  ImplType *getImpl() const { return impl; }
193 
194 protected:
195  ImplType *impl{nullptr};
196 };
197 
198 inline raw_ostream &operator<<(raw_ostream &os, Type type) {
199  type.print(os);
200  return os;
201 }
202 
203 //===----------------------------------------------------------------------===//
204 // TypeTraitBase
205 //===----------------------------------------------------------------------===//
206 
207 namespace TypeTrait {
208 /// This class represents the base of a type trait.
209 template <typename ConcreteType, template <typename> class TraitType>
211 } // namespace TypeTrait
212 
213 //===----------------------------------------------------------------------===//
214 // TypeInterface
215 //===----------------------------------------------------------------------===//
216 
217 /// This class represents the base of a type interface. See the definition of
218 /// `detail::Interface` for requirements on the `Traits` type.
219 template <typename ConcreteType, typename Traits>
220 class TypeInterface : public detail::Interface<ConcreteType, Type, Traits, Type,
221  TypeTrait::TraitBase> {
222 public:
227 
228 private:
229  /// Returns the impl interface instance for the given type.
230  static typename InterfaceBase::Concept *getInterfaceFor(Type type) {
231  return type.getAbstractType().getInterface<ConcreteType>();
232  }
233 
234  /// Allow access to 'getInterfaceFor'.
235  friend InterfaceBase;
236 };
237 
238 //===----------------------------------------------------------------------===//
239 // Core TypeTrait
240 //===----------------------------------------------------------------------===//
241 
242 /// This trait is used to determine if a type is mutable or not. It is attached
243 /// on a type if the corresponding ImplType defines a `mutate` function with
244 /// a proper signature.
245 namespace TypeTrait {
246 template <typename ConcreteType>
248 } // namespace TypeTrait
249 
250 //===----------------------------------------------------------------------===//
251 // Type Utils
252 //===----------------------------------------------------------------------===//
253 
254 // Make Type hashable.
255 inline ::llvm::hash_code hash_value(Type arg) {
257 }
258 
259 template <typename... Tys>
260 bool Type::isa() const {
261  return llvm::isa<Tys...>(*this);
262 }
263 
264 template <typename... Tys>
265 bool Type::isa_and_nonnull() const {
266  return llvm::isa_and_present<Tys...>(*this);
267 }
268 
269 template <typename U>
270 U Type::dyn_cast() const {
271  return llvm::dyn_cast<U>(*this);
272 }
273 
274 template <typename U>
276  return llvm::dyn_cast_or_null<U>(*this);
277 }
278 
279 template <typename U>
280 U Type::cast() const {
281  return llvm::cast<U>(*this);
282 }
283 
284 } // namespace mlir
285 
286 namespace llvm {
287 
288 // Type hash just like pointers.
289 template <>
290 struct DenseMapInfo<mlir::Type> {
292  auto *pointer = llvm::DenseMapInfo<void *>::getEmptyKey();
293  return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
294  }
297  return mlir::Type(static_cast<mlir::Type::ImplType *>(pointer));
298  }
299  static unsigned getHashValue(mlir::Type val) { return mlir::hash_value(val); }
300  static bool isEqual(mlir::Type LHS, mlir::Type RHS) { return LHS == RHS; }
301 };
302 template <typename T>
303 struct DenseMapInfo<T, std::enable_if_t<std::is_base_of<mlir::Type, T>::value &&
304  !mlir::detail::IsInterface<T>::value>>
305  : public DenseMapInfo<mlir::Type> {
306  static T getEmptyKey() {
307  const void *pointer = llvm::DenseMapInfo<const void *>::getEmptyKey();
308  return T::getFromOpaquePointer(pointer);
309  }
310  static T getTombstoneKey() {
312  return T::getFromOpaquePointer(pointer);
313  }
314 };
315 
316 /// We align TypeStorage by 8, so allow LLVM to steal the low bits.
317 template <>
318 struct PointerLikeTypeTraits<mlir::Type> {
319 public:
320  static inline void *getAsVoidPointer(mlir::Type I) {
321  return const_cast<void *>(I.getAsOpaquePointer());
322  }
323  static inline mlir::Type getFromVoidPointer(void *P) {
325  }
326  static constexpr int NumLowBitsAvailable = 3;
327 };
328 
329 /// Add support for llvm style casts.
330 /// We provide a cast between To and From if From is mlir::Type or derives from
331 /// it
332 template <typename To, typename From>
333 struct CastInfo<
334  To, From,
335  std::enable_if_t<std::is_same_v<mlir::Type, std::remove_const_t<From>> ||
336  std::is_base_of_v<mlir::Type, From>>>
338  DefaultDoCastIfPossible<To, From, CastInfo<To, From>> {
339  /// Arguments are taken as mlir::Type here and not as `From`, because when
340  /// casting from an intermediate type of the hierarchy to one of its children,
341  /// the val.getTypeID() inside T::classof will use the static getTypeID of the
342  /// parent instead of the non-static Type::getTypeID that returns the dynamic
343  /// ID. This means that T::classof would end up comparing the static TypeID of
344  /// the children to the static TypeID of its parent, making it impossible to
345  /// downcast from the parent to the child.
346  static inline bool isPossible(mlir::Type ty) {
347  /// Return a constant true instead of a dynamic true when casting to self or
348  /// up the hierarchy.
349  return std::is_same_v<To, std::remove_const_t<From>> ||
350  std::is_base_of_v<To, From> || To::classof(ty);
351  }
352  static inline To doCast(mlir::Type ty) { return To(ty.getImpl()); }
353 };
354 
355 } // namespace llvm
356 
357 #endif // MLIR_IR_TYPES_H
This class contains all of the static information common to all instances of a registered Type.
Definition: TypeSupport.h:30
T::Concept * getInterface() const
Returns an instance of the concept object for the given interface if it was registered to this type,...
Definition: TypeSupport.h:63
bool hasTrait() const
Returns true if the type has a particular trait.
Definition: TypeSupport.h:74
This class provides management for the lifetime of the state used when printing the IR.
Definition: AsmState.h:525
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:56
This class provides an efficient unique identifier for a specific C++ type.
Definition: TypeID.h:104
This class represents the base of a type interface.
Definition: Types.h:221
detail::Interface< ConcreteType, Type, Traits, Type, TypeTrait::TraitBase > InterfaceBase
Definition: Types.h:225
Base storage class appearing in a Type.
Definition: TypeSupport.h:122
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition: Types.h:74
void print(raw_ostream &os) const
Print the current type.
bool isF64() const
Definition: Types.cpp:26
const void * getAsOpaquePointer() const
Methods for supporting PointerLikeTypeTraits.
Definition: Types.h:175
U cast() const
Definition: Types.h:280
bool isInteger(unsigned width) const
Return true if this is an integer type with the specified width.
Definition: Types.cpp:33
static bool classof(Type)
Definition: Types.h:111
Dialect & getDialect() const
Get the dialect this type is registered to.
Definition: Types.h:121
Type(const Type &other)=default
bool isSignlessIntOrIndex() const
Return true if this is a signless integer or index type.
Definition: Types.cpp:75
U dyn_cast_or_null() const
Definition: Types.h:275
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition: Types.cpp:19
bool isa_and_nonnull() const
Definition: Types.h:265
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
Definition: Types.cpp:51
bool isFloat8E4M3FN() const
Definition: Types.cpp:22
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition: Types.cpp:39
ImplType * impl
Definition: Types.h:195
friend ::llvm::hash_code hash_value(Type arg)
Definition: Types.h:255
static Type getFromOpaquePointer(const void *pointer)
Definition: Types.h:178
bool isIndex() const
Definition: Types.cpp:30
bool hasTrait()
Returns true if the type was registered with a particular trait.
Definition: Types.h:184
constexpr Type()=default
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition: Types.cpp:91
U dyn_cast() const
Definition: Types.h:270
bool isF32() const
Definition: Types.cpp:25
const AbstractTy & getAbstractType()
Return the abstract type descriptor for this type.
Definition: Types.h:189
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition: Types.cpp:63
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition: Types.cpp:87
Type & operator=(const Type &other)=default
ImplType * getImpl() const
Return the Type implementation.
Definition: Types.h:192
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition: Types.cpp:89
Type(const ImplType *impl)
Definition: Types.h:87
bool isFloat8E5M2() const
Definition: Types.cpp:21
bool operator!() const
Definition: Types.h:97
bool operator==(Type other) const
Definition: Types.h:93
bool isF128() const
Definition: Types.cpp:28
TypeID getTypeID()
Return a unique identifier for the concrete type.
Definition: Types.h:115
void dump() const
bool operator!=(Type other) const
Definition: Types.h:94
bool isF16() const
Definition: Types.cpp:24
bool isF80() const
Definition: Types.cpp:27
bool isa() const
Definition: Types.h:260
bool isSignlessIntOrFloat() const
Return true of this is a signless integer or a float type.
Definition: Types.cpp:83
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition: Types.cpp:93
bool isBF16() const
Definition: Types.cpp:23
bool isSignlessIntOrIndexOrFloat() const
Return true if this is a signless integer, index, or float type.
Definition: Types.cpp:79
This class represents an abstract interface.
Interface< ConcreteType, Type, Traits, Type, TypeTrait::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
Include the generated interface declarations.
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::Type ty)
Arguments are taken as mlir::Type here and not as From, because when casting from an intermediate typ...
Definition: Types.h:346
static mlir::Type getEmptyKey()
Definition: Types.h:291
static unsigned getHashValue(mlir::Type val)
Definition: Types.h:299
static mlir::Type getTombstoneKey()
Definition: Types.h:295
static bool isEqual(mlir::Type LHS, mlir::Type RHS)
Definition: Types.h:300
static void * getAsVoidPointer(mlir::Type I)
Definition: Types.h:320
static mlir::Type getFromVoidPointer(void *P)
Definition: Types.h:323
This trait is used to determine if a storage user, like Type, is mutable or not.
A utility class to get, or create, unique instances of types within an MLIRContext.
Definition: TypeSupport.h:166