MLIR 24.0.0git
PtrDialect.cpp
Go to the documentation of this file.
1//===- PtrDialect.cpp - Pointer dialect ---------------------*- C++ -*-===//
2//
3// This file is licensed 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 implements the Pointer dialect.
10//
11//===----------------------------------------------------------------------===//
12
14#include "mlir/IR/Matchers.h"
17
18using namespace mlir;
19using namespace mlir::ptr;
20
21//===----------------------------------------------------------------------===//
22// Common helper functions.
23//===----------------------------------------------------------------------===//
24
25/// Verifies that the alignment attribute is a power of 2 if present.
26static LogicalResult
27verifyAlignment(std::optional<int64_t> alignment,
29 if (!alignment)
30 return success();
31 if (alignment.value() <= 0)
32 return emitError() << "alignment must be positive";
33 if (!llvm::isPowerOf2_64(alignment.value()))
34 return emitError() << "alignment must be a power of 2";
35 return success();
36}
37
38//===----------------------------------------------------------------------===//
39// ConstantOp
40//===----------------------------------------------------------------------===//
41
42OpFoldResult ConstantOp::fold(FoldAdaptor adaptor) { return getValue(); }
43
44//===----------------------------------------------------------------------===//
45// FromPtrOp
46//===----------------------------------------------------------------------===//
47
48OpFoldResult FromPtrOp::fold(FoldAdaptor adaptor) {
49 // Fold the pattern:
50 // %ptr = ptr.to_ptr %v : type -> ptr
51 // (%mda = ptr.get_metadata %v : type)?
52 // %val = ptr.from_ptr %ptr (metadata %mda)? : ptr -> type
53 // To:
54 // %val -> %v
55 Value ptrLike;
56 FromPtrOp fromPtr = *this;
57 while (fromPtr != nullptr) {
58 auto toPtr = fromPtr.getPtr().getDefiningOp<ToPtrOp>();
59 // Cannot fold if it's not a `to_ptr` op or the initial and final types are
60 // different.
61 if (!toPtr || toPtr.getPtr().getType() != fromPtr.getType())
62 return ptrLike;
63 Value md = fromPtr.getMetadata();
64 // If the type has trivial metadata fold.
65 if (!fromPtr.getType().hasPtrMetadata()) {
66 ptrLike = toPtr.getPtr();
67 } else if (md) {
68 // Fold if the metadata can be verified to be equal.
69 if (auto mdOp = md.getDefiningOp<GetMetadataOp>();
70 mdOp && mdOp.getPtr() == toPtr.getPtr())
71 ptrLike = toPtr.getPtr();
72 }
73 // Check for a sequence of casts.
74 fromPtr = ptrLike ? ptrLike.getDefiningOp<FromPtrOp>() : nullptr;
75 }
76 return ptrLike;
77}
78
79LogicalResult FromPtrOp::verify() {
80 if (isa<PtrType>(getType()))
81 return emitError() << "the result type cannot be `!ptr.ptr`";
82 if (getType().getMemorySpace() != getPtr().getType().getMemorySpace()) {
83 return emitError()
84 << "expected the input and output to have the same memory space";
85 }
86 return success();
87}
88
89//===----------------------------------------------------------------------===//
90// GatherOp
91//===----------------------------------------------------------------------===//
92
93void GatherOp::getEffects(
95 &effects) {
96 // Gather performs reads from multiple memory locations specified by ptrs
97 effects.emplace_back(MemoryEffects::Read::get(), &getPtrsMutable());
98}
99
100LogicalResult GatherOp::verify() {
101 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
102
103 // Verify that the pointer type's memory space allows loads.
104 MemorySpaceAttrInterface ms =
105 cast<PtrType>(getPtrs().getType().getElementType()).getMemorySpace();
106 DataLayout dataLayout = DataLayout::closest(*this);
107 if (!ms.isValidLoad(getResult().getType(), AtomicOrdering::not_atomic,
108 getAlignment(), &dataLayout, emitDiag))
109 return failure();
110
111 // Verify the alignment.
112 return verifyAlignment(getAlignment(), emitDiag);
113}
114
115void GatherOp::build(OpBuilder &builder, OperationState &state, Type resultType,
116 Value ptrs, Value mask, Value passthrough,
117 unsigned alignment) {
118 build(builder, state, resultType, ptrs, mask, passthrough,
119 alignment ? std::optional<int64_t>(alignment) : std::nullopt);
120}
121
122//===----------------------------------------------------------------------===//
123// LoadOp
124//===----------------------------------------------------------------------===//
125
126/// Verifies the attributes and the type of atomic memory access operations.
127template <typename OpTy>
128static LogicalResult
129verifyAtomicMemOp(OpTy memOp, ArrayRef<AtomicOrdering> unsupportedOrderings) {
130 if (memOp.getOrdering() != AtomicOrdering::not_atomic) {
131 if (llvm::is_contained(unsupportedOrderings, memOp.getOrdering()))
132 return memOp.emitOpError("unsupported ordering '")
133 << stringifyAtomicOrdering(memOp.getOrdering()) << "'";
134 if (!memOp.getAlignment())
135 return memOp.emitOpError("expected alignment for atomic access");
136 return success();
137 }
138 if (memOp.getSyncscope()) {
139 return memOp.emitOpError(
140 "expected syncscope to be null for non-atomic access");
141 }
142 return success();
143}
144
145void LoadOp::getEffects(
147 &effects) {
148 effects.emplace_back(MemoryEffects::Read::get(), &getPtrMutable());
149 // Volatile operations can have target-specific read-write effects on
150 // memory besides the one referred to by the pointer operand.
151 // Similarly, atomic operations that are monotonic or stricter cause
152 // synchronization that from a language point-of-view, are arbitrary
153 // read-writes into memory.
154 if (getVolatile_() || (getOrdering() != AtomicOrdering::not_atomic &&
155 getOrdering() != AtomicOrdering::unordered)) {
156 effects.emplace_back(MemoryEffects::Write::get());
157 effects.emplace_back(MemoryEffects::Read::get());
158 }
159}
160
161LogicalResult LoadOp::verify() {
162 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
163 MemorySpaceAttrInterface ms = getPtr().getType().getMemorySpace();
164 DataLayout dataLayout = DataLayout::closest(*this);
165 if (!ms.isValidLoad(getResult().getType(), getOrdering(), getAlignment(),
166 &dataLayout, emitDiag))
167 return failure();
168 if (failed(verifyAlignment(getAlignment(), emitDiag)))
169 return failure();
170 return verifyAtomicMemOp(*this,
171 {AtomicOrdering::release, AtomicOrdering::acq_rel});
172}
173
174void LoadOp::build(OpBuilder &builder, OperationState &state, Type type,
175 Value addr, unsigned alignment, bool isVolatile,
176 bool isNonTemporal, bool isInvariant, bool isInvariantGroup,
177 AtomicOrdering ordering, StringRef syncscope) {
178 build(builder, state, type, addr,
179 alignment ? std::optional<int64_t>(alignment) : std::nullopt,
180 isVolatile, isNonTemporal, isInvariant, isInvariantGroup, ordering,
181 syncscope.empty() ? nullptr : builder.getStringAttr(syncscope));
182}
183//===----------------------------------------------------------------------===//
184// MaskedLoadOp
185//===----------------------------------------------------------------------===//
186
187void MaskedLoadOp::getEffects(
189 &effects) {
190 // MaskedLoad performs reads from the memory location specified by ptr.
191 effects.emplace_back(MemoryEffects::Read::get(), &getPtrMutable());
192}
193
194LogicalResult MaskedLoadOp::verify() {
195 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
196 // Verify that the pointer type's memory space allows loads.
197 MemorySpaceAttrInterface ms = getPtr().getType().getMemorySpace();
198 DataLayout dataLayout = DataLayout::closest(*this);
199 if (!ms.isValidLoad(getResult().getType(), AtomicOrdering::not_atomic,
200 getAlignment(), &dataLayout, emitDiag))
201 return failure();
202
203 // Verify the alignment.
204 return verifyAlignment(getAlignment(), emitDiag);
205}
206
207void MaskedLoadOp::build(OpBuilder &builder, OperationState &state,
208 Type resultType, Value ptr, Value mask,
209 Value passthrough, unsigned alignment) {
210 build(builder, state, resultType, ptr, mask, passthrough,
211 alignment ? std::optional<int64_t>(alignment) : std::nullopt);
212}
213
214//===----------------------------------------------------------------------===//
215// MaskedStoreOp
216//===----------------------------------------------------------------------===//
217
218void MaskedStoreOp::getEffects(
220 &effects) {
221 // MaskedStore performs writes to the memory location specified by ptr
222 effects.emplace_back(MemoryEffects::Write::get(), &getPtrMutable());
223}
224
225LogicalResult MaskedStoreOp::verify() {
226 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
227 // Verify that the pointer type's memory space allows stores.
228 MemorySpaceAttrInterface ms = getPtr().getType().getMemorySpace();
229 DataLayout dataLayout = DataLayout::closest(*this);
230 if (!ms.isValidStore(getValue().getType(), AtomicOrdering::not_atomic,
231 getAlignment(), &dataLayout, emitDiag))
232 return failure();
233
234 // Verify the alignment.
235 return verifyAlignment(getAlignment(), emitDiag);
236}
237
238void MaskedStoreOp::build(OpBuilder &builder, OperationState &state,
239 Value value, Value ptr, Value mask,
240 unsigned alignment) {
241 build(builder, state, value, ptr, mask,
242 alignment ? std::optional<int64_t>(alignment) : std::nullopt);
243}
244
245//===----------------------------------------------------------------------===//
246// ScatterOp
247//===----------------------------------------------------------------------===//
248
249void ScatterOp::getEffects(
251 &effects) {
252 // Scatter performs writes to multiple memory locations specified by ptrs
253 effects.emplace_back(MemoryEffects::Write::get(), &getPtrsMutable());
254}
255
256LogicalResult ScatterOp::verify() {
257 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
258
259 // Verify that the pointer type's memory space allows stores.
260 MemorySpaceAttrInterface ms =
261 cast<PtrType>(getPtrs().getType().getElementType()).getMemorySpace();
262 DataLayout dataLayout = DataLayout::closest(*this);
263 if (!ms.isValidStore(getValue().getType(), AtomicOrdering::not_atomic,
264 getAlignment(), &dataLayout, emitDiag))
265 return failure();
266
267 // Verify the alignment.
268 return verifyAlignment(getAlignment(), emitDiag);
269}
270
271void ScatterOp::build(OpBuilder &builder, OperationState &state, Value value,
272 Value ptrs, Value mask, unsigned alignment) {
273 build(builder, state, value, ptrs, mask,
274 alignment ? std::optional<int64_t>(alignment) : std::nullopt);
275}
276
277//===----------------------------------------------------------------------===//
278// StoreOp
279//===----------------------------------------------------------------------===//
280
281void StoreOp::getEffects(
283 &effects) {
284 effects.emplace_back(MemoryEffects::Write::get(), &getPtrMutable());
285 // Volatile operations can have target-specific read-write effects on
286 // memory besides the one referred to by the pointer operand.
287 // Similarly, atomic operations that are monotonic or stricter cause
288 // synchronization that from a language point-of-view, are arbitrary
289 // read-writes into memory.
290 if (getVolatile_() || (getOrdering() != AtomicOrdering::not_atomic &&
291 getOrdering() != AtomicOrdering::unordered)) {
292 effects.emplace_back(MemoryEffects::Write::get());
293 effects.emplace_back(MemoryEffects::Read::get());
294 }
295}
296
297LogicalResult StoreOp::verify() {
298 auto emitDiag = [&]() -> InFlightDiagnostic { return emitError(); };
299 MemorySpaceAttrInterface ms = getPtr().getType().getMemorySpace();
300 DataLayout dataLayout = DataLayout::closest(*this);
301 if (!ms.isValidStore(getValue().getType(), getOrdering(), getAlignment(),
302 &dataLayout, emitDiag))
303 return failure();
304 if (failed(verifyAlignment(getAlignment(), emitDiag)))
305 return failure();
306 return verifyAtomicMemOp(*this,
307 {AtomicOrdering::acquire, AtomicOrdering::acq_rel});
308}
309
310void StoreOp::build(OpBuilder &builder, OperationState &state, Value value,
311 Value addr, unsigned alignment, bool isVolatile,
312 bool isNonTemporal, bool isInvariantGroup,
313 AtomicOrdering ordering, StringRef syncscope) {
314 build(builder, state, value, addr,
315 alignment ? std::optional<int64_t>(alignment) : std::nullopt,
316 isVolatile, isNonTemporal, isInvariantGroup, ordering,
317 syncscope.empty() ? nullptr : builder.getStringAttr(syncscope));
318}
319
320//===----------------------------------------------------------------------===//
321// PtrAddOp
322//===----------------------------------------------------------------------===//
323
324/// Fold: ptradd ptr + 0 -> ptr
325OpFoldResult PtrAddOp::fold(FoldAdaptor adaptor) {
326 Attribute attr = adaptor.getOffset();
327 // A shaped offset can broadcast a scalar base to a shaped result.
328 if (!attr || getBase().getType() != getType())
329 return nullptr;
330 if (llvm::APInt value; m_ConstantInt(&value).match(attr) && value.isZero())
331 return getBase();
332 return nullptr;
333}
334
335LogicalResult PtrAddOp::inferReturnTypes(
336 MLIRContext *context, std::optional<Location> location, ValueRange operands,
337 DictionaryAttr attributes, PropertyRef properties, RegionRange regions,
338 SmallVectorImpl<Type> &inferredReturnTypes) {
339 // Get the base pointer and offset types.
340 Type baseType = operands[0].getType();
341 Type offsetType = operands[1].getType();
342
343 auto offTy = dyn_cast<ShapedType>(offsetType);
344 if (!offTy) {
345 // If the offset isn't shaped, the result is always the base type.
346 inferredReturnTypes.push_back(baseType);
347 return success();
348 }
349 auto baseTy = dyn_cast<ShapedType>(baseType);
350 if (!baseTy) {
351 // Base isn't shaped, but offset is, use the ShapedType from offset with the
352 // base pointer as element type.
353 inferredReturnTypes.push_back(offTy.clone(baseType));
354 return success();
355 }
356
357 // Both are shaped, their shape must match.
358 if (offTy.getShape() != baseTy.getShape()) {
359 if (location)
360 mlir::emitError(*location) << "shapes of base and offset must match";
361 return failure();
362 }
363
364 // Make sure they are the same kind of shaped type.
365 if (baseType.getTypeID() != offsetType.getTypeID()) {
366 if (location)
367 mlir::emitError(*location) << "the shaped containers type must match";
368 return failure();
369 }
370 inferredReturnTypes.push_back(baseType);
371 return success();
372}
373
374//===----------------------------------------------------------------------===//
375// PtrDiffOp
376//===----------------------------------------------------------------------===//
377
378LogicalResult PtrDiffOp::verify() {
379 // If the operands are not shaped early exit.
380 if (!isa<ShapedType>(getLhs().getType()))
381 return success();
382
383 // Just check the container type matches, `SameOperandsAndResultShape` handles
384 // the actual shape.
385 if (getResult().getType().getTypeID() != getLhs().getType().getTypeID()) {
386 return emitError() << "expected the result to have the same container "
387 "type as the operands when operands are shaped";
388 }
389
390 return success();
391}
392
393ptr::PtrType PtrDiffOp::getPtrType() {
394 Type lhsType = getLhs().getType();
395 if (auto shapedType = dyn_cast<ShapedType>(lhsType))
396 return cast<ptr::PtrType>(shapedType.getElementType());
397 return cast<ptr::PtrType>(lhsType);
398}
399
400Type PtrDiffOp::getIntType() {
401 Type resultType = getResult().getType();
402 if (auto shapedType = dyn_cast<ShapedType>(resultType))
403 return shapedType.getElementType();
404 return resultType;
405}
406
407//===----------------------------------------------------------------------===//
408// ToPtrOp
409//===----------------------------------------------------------------------===//
410
411OpFoldResult ToPtrOp::fold(FoldAdaptor adaptor) {
412 // Fold the pattern:
413 // %val = ptr.from_ptr %p (metadata ...)? : ptr -> type
414 // %ptr = ptr.to_ptr %val : type -> ptr
415 // To:
416 // %ptr -> %p
417 Value ptr;
418 ToPtrOp toPtr = *this;
419 while (toPtr != nullptr) {
420 auto fromPtr = toPtr.getPtr().getDefiningOp<FromPtrOp>();
421 // Cannot fold if it's not a `from_ptr` op.
422 if (!fromPtr)
423 return ptr;
424 ptr = fromPtr.getPtr();
425 // Check for chains of casts.
426 toPtr = ptr.getDefiningOp<ToPtrOp>();
427 }
428 return ptr;
429}
430
431LogicalResult ToPtrOp::verify() {
432 if (isa<PtrType>(getPtr().getType()))
433 return emitError() << "the input value cannot be of type `!ptr.ptr`";
434 if (getType().getMemorySpace() != getPtr().getType().getMemorySpace()) {
435 return emitError()
436 << "expected the input and output to have the same memory space";
437 }
438 return success();
439}
440
441//===----------------------------------------------------------------------===//
442// TypeOffsetOp
443//===----------------------------------------------------------------------===//
444
445llvm::TypeSize TypeOffsetOp::getTypeSize(std::optional<DataLayout> layout) {
446 if (!layout)
447 layout.emplace(DataLayout::closest(*this));
448 return layout->getTypeAllocSize(getElementType());
449}
450
451//===----------------------------------------------------------------------===//
452// Pointer API.
453//===----------------------------------------------------------------------===//
454
455#include "mlir/Dialect/Ptr/IR/PtrOpsDialect.cpp.inc"
456
457#define GET_ATTRDEF_CLASSES
458#include "mlir/Dialect/Ptr/IR/PtrOpsAttrs.cpp.inc"
459
460#include "mlir/Dialect/Ptr/IR/PtrOpsEnums.cpp.inc"
461
462#define GET_TYPEDEF_CLASSES
463#include "mlir/Dialect/Ptr/IR/PtrOpsTypes.cpp.inc"
464
465#define GET_OP_CLASSES
466#include "mlir/Dialect/Ptr/IR/PtrOps.cpp.inc"
return success()
static Value getBase(Value v)
Looks through known "view-like" ops to find the base memref.
static InFlightDiagnostic emitDiag(Location location, DiagnosticSeverity severity, const Twine &message)
Helper function used to emit a diagnostic with an optionally empty twine message.
static LogicalResult verifyAtomicMemOp(OpTy memOp, ArrayRef< AtomicOrdering > unsupportedOrderings)
Verifies the attributes and the type of atomic memory access operations.
static LogicalResult verifyAlignment(std::optional< int64_t > alignment, function_ref< InFlightDiagnostic()> emitError)
Verifies that the alignment attribute is a power of 2 if present.
static Type getElementType(Type type, ArrayRef< int32_t > indices, function_ref< InFlightDiagnostic(StringRef)> emitErrorFn)
Walks the given type hierarchy with the given indices, potentially down to component granularity,...
Definition SPIRVOps.cpp:230
Attributes are known-constant values of operations.
Definition Attributes.h:25
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
The main mechanism for performing data layout queries.
static DataLayout closest(Operation *op)
Returns the layout of the closest parent operation carrying layout info.
This class represents a diagnostic that is inflight and set to be reported.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class helps build Operations.
Definition Builders.h:210
This class represents a single result from folding an operation.
Type-safe wrapper around a void* for passing properties, including the properties structs of operatio...
This class provides an abstraction over the different types of ranges over Regions.
Definition Region.h:363
This class represents a specific instance of an effect.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
TypeID getTypeID()
Return a unique identifier for the concrete type.
Definition Types.h:101
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
type_range getType() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
Definition Matchers.h:527
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
This represents an operation in an abstracted form, suitable for use with the builder APIs.