MLIR 24.0.0git
BufferizableOpInterface.h
Go to the documentation of this file.
1//===- BufferizableOpInterface.h - Bufferizable Ops -------------*- 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_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
10#define MLIR_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
11
12#include "mlir/IR/Operation.h"
14#include "mlir/Support/LLVM.h"
15#include "llvm/ADT/DenseMapInfoVariant.h"
16#include "llvm/ADT/SetVector.h"
17#include <optional>
18
19#include "mlir/Dialect/Bufferization/IR/BufferizationEnums.h.inc"
21
22namespace mlir {
23class OpBuilder;
24namespace func {
25class FuncOp;
26}
27
28namespace bufferization {
29
30class AnalysisState;
31class BufferizableOpInterface;
32
33/// Specifies a fine-grain relationship between buffers to enable more analysis.
34enum class BufferRelation {
35 Unknown,
36 // TODO: ResultContainsOperand,
37 // TODO: OperandContainsResult,
38 Equivalent
39};
40
41/// A maybe aliasing OpOperand. If `isDefinite` is `true`, the OpOperand is
42/// guaranteed to alias at runtime.
43struct AliasingOpOperand {
44 AliasingOpOperand(OpOperand *opOperand, BufferRelation relation,
45 bool isDefinite = true)
46 : opOperand(opOperand), relation(relation), isDefinite(isDefinite) {}
47
48 OpOperand *opOperand;
49 BufferRelation relation;
50 bool isDefinite;
51};
52
53/// A maybe aliasing Value. If `isDefinite` is `true`, the Value is guaranteed
54/// to alias at runtime.
55struct AliasingValue {
56 AliasingValue(Value value, BufferRelation relation, bool isDefinite = true)
57 : value(value), relation(relation), isDefinite(isDefinite) {}
58
59 Value value;
60 BufferRelation relation;
61 bool isDefinite;
62};
63
64template <typename T>
65class AliasList {
66public:
67 /// Create an empty list of aliases.
68 AliasList() = default;
69
70 /// Create a list of aliases.
71 AliasList(std::initializer_list<T> elems) {
72 for (T alias : elems)
73 addAlias(alias);
74 }
75
76 /// Create a list of aliases.
77 AliasList(SmallVector<T> &&aliases) : aliases(std::move(aliases)) {}
78
79 ArrayRef<T> getAliases() const { return aliases; }
80
81 size_t getNumAliases() const { return aliases.size(); }
82
83 void addAlias(T alias) { aliases.push_back(alias); }
84
85 auto begin() const { return aliases.begin(); }
86 auto end() const { return aliases.end(); }
87
88private:
89 /// The list of aliases.
90 SmallVector<T> aliases;
91};
92
93/// A list of possible aliasing OpOperands. This list models the runtime
94/// aliasing relationship for a Value.
95using AliasingOpOperandList = AliasList<AliasingOpOperand>;
96
97/// A list of possible aliasing Values. This list models the runtime aliasing
98/// relationship for an OpOperand.
99using AliasingValueList = AliasList<AliasingValue>;
100
101class OpFilter {
102public:
103 /// An op filter entry. Filters can be used to specify which ops should be
104 /// processed by the bufferization.
105 struct Entry {
106 /// If the filter function evaluates to `true`, the filter matches.
107 using FilterFn = std::function<bool(Operation *)>;
108
109 /// Filter type: A filter can either be a DENY filter or an ALLOW filter.
110 enum FilterType : int8_t { DENY = 0, ALLOW = 1 };
111
112 FilterFn fn;
113 FilterType type;
114 };
115
116 /// Return whether the op is allowed or not.
117 ///
118 /// If the filter does not have an ALLOW rule, ops are allowed by default,
119 /// unless they are explicitly marked as DENY. If the filter has at least one
120 /// ALLOW rule, ops are denied by default and only allowed if they match
121 /// an ALLOW rule and no DENY rule.
122 bool isOpAllowed(Operation *op) const;
123
124 /// Allow the given dialects.
125 ///
126 /// This function adds one or multiple ALLOW entries.
127 template <typename... DialectTs>
128 void allowDialect() {
129 // The following expands a call to allowDialectImpl for each dialect
130 // in 'DialectTs'.
131 (allowDialectImpl<DialectTs>(), ...);
132 }
133
134 /// Deny the given dialects.
135 ///
136 /// This function adds one or multiple DENY entries.
137 template <typename... DialectTs>
138 void denyDialect() {
139 (denyDialectImpl<DialectTs>(), ...);
140 }
141
142 /// Allow the given dialect.
143 ///
144 /// This function adds an ALLOW entry.
145 void allowDialect(StringRef dialectNamespace) {
146 Entry::FilterFn filterFn = [=](Operation *op) {
147 return op->getName().getDialectNamespace() == dialectNamespace;
148 };
149 entries.push_back(Entry{filterFn, Entry::FilterType::ALLOW});
150 }
151
152 /// Deny the given dialect.
153 ///
154 /// This function adds a DENY entry.
155 void denyDialect(StringRef dialectNamespace) {
156 Entry::FilterFn filterFn = [=](Operation *op) {
157 return op->getName().getDialectNamespace() == dialectNamespace;
158 };
159 entries.push_back(Entry{filterFn, Entry::FilterType::DENY});
160 }
161
162 /// Allow the given ops.
163 ///
164 /// This function adds one or multiple ALLOW entries.
165 template <typename... OpTys>
166 void allowOperation() {
167 (allowOperationImpl<OpTys>(), ...);
168 }
169
170 /// Deny the given ops.
171 ///
172 /// This function adds one or multiple DENY entries.
173 template <typename... OpTys>
174 void denyOperation() {
175 (denyOperationImpl<OpTys>(), ...);
176 }
177
178 /// Allow the given op.
179 ///
180 /// This function adds an ALLOW entry.
181 void allowOperation(StringRef opName) {
182 Entry::FilterFn filterFn = [=](Operation *op) {
183 return op->getName().getStringRef() == opName;
184 };
185 allowOperation(filterFn);
186 }
187
188 /// Deny the given op.
189 ///
190 /// This function adds a DENY entry.
191 void denyOperation(StringRef opName) {
192 Entry::FilterFn filterFn = [=](Operation *op) {
193 return op->getName().getStringRef() == opName;
194 };
195 denyOperation(filterFn);
196 }
197
198 /// Allow ops that are matched by `fn`.
199 ///
200 /// This function adds an ALLOW entry.
201 void allowOperation(Entry::FilterFn fn) {
202 entries.push_back(Entry{fn, Entry::FilterType::ALLOW});
203 }
204
205 /// Deny ops that are matched by `fn`.
206 ///
207 /// This function adds a DENY entry.
208 void denyOperation(Entry::FilterFn fn) {
209 entries.push_back(Entry{fn, Entry::FilterType::DENY});
210 }
211
212private:
213 /// Return `true` if the filter has at least one ALLOW rule.
214 bool hasAllowRule() const {
215 for (const Entry &e : entries)
216 if (e.type == Entry::FilterType::ALLOW)
217 return true;
218 return false;
219 }
220
221 /// Allow a dialect.
222 template <typename DialectT>
223 void allowDialectImpl() {
224 allowDialect(DialectT::getDialectNamespace());
225 }
226
227 /// Deny a dialect.
228 template <typename DialectT>
229 void denyDialectImpl() {
230 denyDialect(DialectT::getDialectNamespace());
231 }
232
233 /// Allow an op.
234 template <typename OpTy>
235 void allowOperationImpl() {
236 allowOperation(OpTy::getOperationName());
237 }
238
239 /// Deny an op.
240 template <typename OpTy>
241 void denyOperationImpl() {
242 denyOperation(OpTy::getOperationName());
243 }
244
245 /// A list of filter entries that determine whether an op should be allowed or
246 /// denied. If the filter has an ALLOW rule, only ops that are allowed and not
247 /// denied are allowed. If the filter does not have an ALLOW rule, only ops
248 /// that are not denied are allowed.
249 SmallVector<Entry> entries;
250};
251
252/// Options for BufferizableOpInterface-based bufferization.
253struct BufferizationOptions {
254 /// Allocator function: Generate a memref allocation with the given type,
255 /// dynamic extents and alignment.
256 using AllocationFn = std::function<FailureOr<Value>(
257 OpBuilder &, Location, MemRefType, ValueRange, unsigned int)>;
258 /// Memcpy function: Generate a memcpy between two buffers.
259 using MemCpyFn =
260 std::function<LogicalResult(OpBuilder &, Location, Value, Value)>;
261 /// Cast function: Convert a buffer value to a new value with the specified
262 /// type. This method is typically used when a simple cast-like operation is
263 /// sufficient to convert the buffer value, for example, when layout maps
264 /// between buffer value and resulting type do not match. Returns failure if
265 /// the value cannot be cast to that type.
266 using CastFn =
267 std::function<FailureOr<Value>(OpBuilder &, Location, Type, Value)>;
268 /// Initializer function for analysis state.
269 using AnalysisStateInitFn = std::function<void(AnalysisState &)>;
270 /// Tensor-like -> Buffer-like type conversion.
271 /// Parameters: tensor-like type, memory space, func op, bufferization options
272 using FunctionArgTypeConverterFn =
273 std::function<BufferLikeType(TensorLikeType, Attribute memorySpace,
274 func::FuncOp, const BufferizationOptions &)>;
275 /// Tensor -> MemRef type conversion.
276 /// Parameters: tensor type, memory space, bufferization options
277 using UnknownTypeConverterFn = std::function<BufferLikeType(
278 TensorLikeType, Attribute memorySpace, const BufferizationOptions &)>;
279 // Produce a MemorySpace attribute from a tensor type
280 using DefaultMemorySpaceFn =
281 std::function<std::optional<Attribute>(TensorLikeType t)>;
282
283 /// Resolve a mismatch between buffer types that were independently inferred,
284 /// which results in a conflict at the "merge" point. Returns `failure()` to
285 /// signal bufferization failure; returns a buffer-like type when
286 /// reconciliation suceeded.
287 using ReconcileBufferTypeMismatchFn = std::function<FailureOr<BufferLikeType>(
288 BufferLikeType, BufferLikeType, const BufferizationOptions &)>;
289
290 BufferizationOptions();
291
292 /// Try to cast the given op to BufferizableOpInterface if the op is allow
293 /// listed.
294 BufferizableOpInterface dynCastBufferizableOp(Operation *op) const;
295
296 /// Try to cast the given value to BufferizableOpInterface if the op is allow
297 /// listed.
298 BufferizableOpInterface dynCastBufferizableOp(Value value) const;
299
300 /// A filter that specifies which ops should be bufferized and which ops
301 /// should be ignored.
302 OpFilter opFilter;
303
304 /// Return `true` if the given op should be bufferized.
305 bool isOpAllowed(Operation *op) const;
306
307 /// Specifies whether not bufferizable ops are allowed in the input. If so,
308 /// bufferization.to_buffer and bufferization.to_tensor ops are inserted at
309 /// the boundaries.
310 bool allowUnknownOps = false;
311
312 /// Specifies whether function boundaries (ops in the func dialect) should be
313 /// bufferized or not.
314 bool bufferizeFunctionBoundaries = false;
315
316 /// Whether the IR may contain a parallel region. When unset, the analysis
317 /// walks the IR to compute it.
318 /// Note: If the IR contains a parallel region, but this flag is set to
319 /// "false", the bufferization may produce incorrect IR.
320 std::optional<bool> mayHaveParallelRegions = std::nullopt;
321
322 /// This function controls buffer types on function signatures. Sets
323 /// `functionArgTypeConverterFn` and `inferFunctionResultLayout` accordingly.
324 ///
325 /// * InferLayoutMap: All function parameter types have a fully dynamic layout
326 /// map, but function result types are inferred from the body of the
327 /// function.
328 /// * FullyDynamicLayoutMap: All function parameter types and result types
329 /// have a fully dynamic layout map. This option is most efficient because
330 /// any layout map can be casted to a fully dynamic one.
331 /// * IdentityLayoutMap: All function parameter types and result types have a
332 /// static identity layout (i.e., no layout map). This option may introduce
333 /// additional buffer allocs and copies because layout maps cannot be casted
334 /// away.
335 ///
336 /// Note: Inferred layout maps may not be desireable when interacting with
337 /// external functions, because the generated function signatures will be less
338 /// predictable.
339 void setFunctionBoundaryTypeConversion(LayoutMapOption layoutMapOption);
340
341 /// Create a memref allocation with the given type and dynamic extents.
342 AllocationFn allocationFn = nullptr;
343
344 /// Creates a memcpy between two given buffers.
345 MemCpyFn memCpyFn = nullptr;
346
347 /// Creates a cast function from a buffer value to a new type.
348 CastFn castFn = nullptr;
349
350 /// Type conversion from tensors to buffers. This type conversion is used to
351 /// determine bufferized function argument and result types.
352 ///
353 /// By default, if tensor is a (builtin) tensor type, it is converted to a
354 /// memref type with a fully dynamic layout map; if tensor is a (generic)
355 /// tensor-like type, it is converted using unknownTypeConverterFn.
356 ///
357 /// If `bufferizeFunctionBoundaries` is not set, this function isn't used.
358 FunctionArgTypeConverterFn functionArgTypeConverterFn = nullptr;
359
360 /// If true, function result types are inferred from the body of the function.
361 /// Otherwise, function result type is determined by
362 /// `functionArgTypeConverterFn`.
363 ///
364 /// If `bufferizeFunctionBoundaries` is not set, this flag has no effect.
365 bool inferFunctionResultLayout = true;
366
367 /// Type conversion from tensors to memrefs. This type conversion is used if
368 /// no memref type could be inferred during bufferization. By default, returns
369 /// a memref type with a fully dynamic layout map.
370 UnknownTypeConverterFn unknownTypeConverterFn = nullptr;
371
372 // Use during type conversion to determine the memory space for memref based
373 // on the original tensor type if the memory space cannot be inferred.
374 // Returning std::nullopt will cause bufferization to fail (useful to indicate
375 // failure to determine memory space for a tensor type).
376 DefaultMemorySpaceFn defaultMemorySpaceFn =
377 [](TensorLikeType t) -> std::optional<Attribute> { return Attribute(); };
378
379 /// Hook to resolve a mismatch between conflicting buffer types that were
380 /// independently inferred and have to now "converge" to a common buffer type
381 /// (e.g. due to differences in iterations of a loop or branches of
382 /// if-statements). Depending on the situation and the types involved, this
383 /// may produce a "joined" type (e.g. a type combining properties of both), or
384 /// either one of the two types, etc. The default keeps the framework
385 /// behavior: promote to fully-dynamic layout on layout mismatch, fail on
386 /// memory-space mismatch.
387 ReconcileBufferTypeMismatchFn reconcileBufferTypeMismatchFn = nullptr;
388
389 /// If set to `true`, the analysis is skipped. A buffer is copied before every
390 /// write. This flag cannot be used together with `testAnalysisOnly = true`.
391 bool copyBeforeWrite = false;
392
393 /// If set to `true`, does not modify the IR apart from adding attributes (for
394 /// checking the results of the analysis) and post analysis steps.
395 bool testAnalysisOnly = false;
396
397 /// If set to `true`, the IR is annotated with details about RaW conflicts.
398 /// For debugging only. Should be used together with `testAnalysisOnly`.
399 bool printConflicts = false;
400
401 /// Buffer alignment for new memory allocations.
402 unsigned int bufferAlignment = 64;
403
404 /// Initializer functions for analysis state. These can be used to
405 /// initialize dialect-specific analysis state.
406 SmallVector<AnalysisStateInitFn> stateInitializers;
407};
408
409/// Traversal parameters for `findValueInReverseUseDefChain`.
410struct TraversalConfig {
411 /// Specifies if leaves (that do not have further OpOperands to follow)
412 /// should be returned even if they do not match the specified filter.
413 bool alwaysIncludeLeaves = true;
414
415 /// Specifies whether out-of-place/undecided OpOperands should be followed.
416 bool followInPlaceOnly = false;
417
418 /// Specifies whether non-equivalent OpOperands should be followed.
419 bool followEquivalentOnly = false;
420
421 /// Specifies whether unknown/non-bufferizable/ops not included in the
422 /// OpFilter of BufferizationOptions should be followed.
423 bool followUnknownOps = false;
424
425 /// Specifies whether OpOperands with a different type that are not the result
426 /// of a CastOpInterface op should be followed.
427 bool followSameTypeOrCastsOnly = false;
428
429 /// Specifies whether already visited values should be visited again.
430 /// (Note: This can result in infinite looping.)
431 bool revisitAlreadyVisitedValues = false;
432};
433
434/// AnalysisState provides a variety of helper functions for dealing with
435/// tensor values.
436class AnalysisState {
437public:
438 /// Determine which OpOperand* will alias with `value` if the op is
439 /// bufferized in place. Return all tensor OpOperand* if the op is not
440 /// bufferizable.
441 AliasingOpOperandList getAliasingOpOperands(Value value) const;
442
443 /// Determine which Value will alias with `opOperand` if the op is bufferized
444 /// in place. Return all tensor Values if the op is not bufferizable.
445 AliasingValueList getAliasingValues(OpOperand &opOperand) const;
446
447 /// Return true if `opOperand` bufferizes to a memory read. Return `true` if
448 /// the op is not bufferizable.
449 bool bufferizesToMemoryRead(OpOperand &opOperand) const;
450
451 /// Return true if `opOperand` bufferizes to a memory write. Return true` if
452 /// the op is not bufferizable.
453 bool bufferizesToMemoryWrite(OpOperand &opOperand) const;
454
455 /// Return true if the given `value` bufferizes to a memory write. Return
456 /// true if the value is a block argument. Return `true` if the defining op is
457 /// not bufferizable. Otherwise, consult the BufferizableOpInterface.
458 bool bufferizesToMemoryWrite(Value value) const;
459
460 /// Return true if `opOperand` does neither read nor write but bufferizes to
461 /// an alias. Return false if the op is not bufferizable.
462 bool bufferizesToAliasOnly(OpOperand &opOperand) const;
463
464 /// Return true if a copy can always be avoided when allocating a new tensor
465 /// for the given OpOperand.
466 bool canOmitTensorCopy(OpOperand &opOperand) const;
467
468 /// Return true if the given value is read by an op that bufferizes to a
469 /// memory read. Also takes into account ops that create an alias but do not
470 /// read by themselves (e.g., ExtractSliceOp).
471 bool isValueRead(Value value) const;
472
473 /// Starting from `opOperand`, follow the use-def chain in reverse, always
474 /// selecting the aliasing OpOperands. Find and return Values for which
475 /// `condition` evaluates to true. OpOperands of such matching Values are not
476 /// traversed any further, the visited aliasing opOperands will be preserved
477 /// through `visitedOpOperands`.
478 ///
479 /// When reaching the end of a chain, also return the last Value of that
480 /// chain if `config.alwaysIncludeLeaves` is set.
481 ///
482 /// Example:
483 ///
484 /// 8
485 /// |
486 /// 6* 7* +-----+----+
487 /// | | | |
488 /// 2* 3 4* 5
489 /// | | | |
490 /// +----------+----------+----------+
491 /// |
492 /// 1
493 ///
494 /// In the above example, Values with a star satisfy the condition. When
495 /// starting the traversal from Value 1, the resulting SetVector is:
496 /// { 2, 7, 8, 5 }
497 ///
498 /// Additional stopping conditions for the traversal can be specified in
499 /// `config`.
500 SetVector<Value> findValueInReverseUseDefChain(
501 OpOperand *opOperand, llvm::function_ref<bool(Value)> condition,
502 TraversalConfig config = TraversalConfig(),
503 llvm::DenseSet<OpOperand *> *visitedOpOperands = nullptr) const;
504
505 /// Find the values that may define the contents of the given value at
506 /// runtime. A block argument is always a definition. An OpResult is a
507 /// definition if it bufferizes to memory write. If it does not bufferize to
508 /// a memory write but has aliasing operands, we continue the lookup on these
509 /// values.
510 ///
511 /// Example: %r = tensor.insert %f into %t[%c0] : tensor<?xf32>
512 /// findDefinitions(%r) = {%r} because %r bufferizes to memory write.
513 ///
514 /// Example: %r = tensor.empty() : tensor<10xf32>
515 /// findDefinitions(%r) = {} because tensor.empty does not the define the
516 /// contents of its result (i.e., it does not bufferize to a memory write)
517 /// and it has no aliasing OpOperands.
518 ///
519 /// Example:
520 /// %a = arith.constant ... : tensor<10xf32>
521 /// %b1 = tensor.insert %f into %t : tensor<50xf32>
522 /// %b2 = tensor.extract_slice %b1[0][10][1] : tensor<50xf32> tensor<10xf32>
523 /// %r = arith.select %cond, %a, %b : tensor<10xf32>
524 /// findDefinitions(%r) = {%a, %b1}. %r and %b2 are skipped (lookup continues
525 /// in the operands) because their defining ops do not define the contents of
526 /// the tensor.
527 ///
528 /// Example:
529 /// %a = tensor.empty() : tensor<10xf32>
530 /// %b = arith.constant ... : tensor<10xf32>
531 /// %r = arith.select %cond, %a, %b : tensor<10xf32>
532 /// findDefinitions(%r) = {%b}. %a is excluded because it does not define the
533 /// contents of the tensor.
534 ///
535 /// Note: OpResults of unknown ops are handled conservatively and assumed to
536 /// be definitions.
537 SetVector<Value> findDefinitions(OpOperand *opOperand) const;
538
539 /// Return `true` if the given OpResult has been decided to bufferize inplace.
540 virtual bool isInPlace(OpOperand &opOperand) const;
541
542 /// Return true if `v1` and `v2` bufferize to equivalent buffers.
543 virtual bool areEquivalentBufferizedValues(Value v1, Value v2) const;
544
545 /// Return true if `v1` and `v2` may bufferize to aliasing buffers.
546 virtual bool areAliasingBufferizedValues(Value v1, Value v2) const;
547
548 /// Return `true` if the given tensor has undefined contents.
549 virtual bool hasUndefinedContents(OpOperand *opOperand) const;
550
551 /// Return a reference to the BufferizationOptions.
552 const BufferizationOptions &getOptions() const { return options; }
553
554 AnalysisState(const BufferizationOptions &options);
555
556 // AnalysisState should be passed as a reference.
557 AnalysisState(const AnalysisState &) = delete;
558
559 virtual ~AnalysisState() = default;
560
561 static bool classof(const AnalysisState *base) { return true; }
562
563 TypeID getType() const { return type; }
564
565 /// Return the closest enclosing repetitive region around the given op.
566 Region *getEnclosingRepetitiveRegion(Operation *op,
567 const BufferizationOptions &options);
568
569 /// Return the closest enclosing repetitive region around the place where the
570 /// given value is defined.
571 Region *getEnclosingRepetitiveRegion(Value value,
572 const BufferizationOptions &options);
573
574 /// Return the closest enclosing repetitive region around the given block.
575 Region *getEnclosingRepetitiveRegion(Block *block,
576 const BufferizationOptions &options);
577
578 virtual void resetCache();
579
580 /// Checks whether `op0` and `op1` are inside mutually exclusive regions.
581 /// The logic defers to `mlir::insideMutuallyExclusiveRegions`, but the
582 /// result is cached.
583 bool insideMutuallyExclusiveRegions(Operation *op0, Operation *op1);
584
585protected:
586 AnalysisState(const BufferizationOptions &options, TypeID type);
587
588private:
589 /// A reference to current bufferization options.
590 const BufferizationOptions &options;
591
592 /// The type of analysis.
593 TypeID type;
594
595 /// Cache containing closest ancestor repetitive Region.
596 DenseMap<std::variant<Operation *, Block *, Region *, Value>, Region *>
597 enclosingRepetitiveRegionCache;
598
599 /// Cache that specifies whether the two operations are in mutually exclusive
600 /// regions.
601 DenseMap<std::pair<Operation *, Operation *>, bool>
602 insideMutuallyExclusiveRegionsCache;
603};
604
605/// BufferizationState provides information about the state of the IR during the
606/// bufferization process.
607class BufferizationState {
608public:
609 /// Get a reference to the collection of cached symbol tables.
610 SymbolTableCollection &getSymbolTables();
611 /// Const overload so callers can reuse the cache from a const state.
612 SymbolTableCollection &getSymbolTables() const;
613
614private:
615 /// The cached symbol tables.
616 /// The user is expected to update / invalidate the cached symbol tables if
617 /// the bufferized operation has the Symbol or SymbolTable traits.
618 mutable SymbolTableCollection symbolTables;
619};
620
621/// Create an AllocTensorOp for the given shaped value (memref or tensor).
622/// If `copy` is set, the shaped value is copied. Otherwise, a tensor with
623/// undefined contents is allocated.
624FailureOr<Value>
625allocateTensorForShapedValue(OpBuilder &b, Location loc, Value shapedValue,
626 const BufferizationOptions &options,
627 const BufferizationState &state, bool copy = true);
628
629/// Lookup the buffer for the given value. If the value was not bufferized
630/// yet, wrap it in a ToBufferOp. Otherwise, it is the result of a ToTensorOp,
631/// from which the memref operand is returned.
632FailureOr<Value> getBuffer(RewriterBase &rewriter, Value value,
633 const BufferizationOptions &options,
634 const BufferizationState &state);
635
636/// Cast `buffer` to `type` with the options' cast function. Returns `buffer`
637/// itself if it already has that type. Reports an error at `loc` and returns
638/// failure if the cast is refused.
639FailureOr<Value> castBuffer(OpBuilder &b, Location loc, Value buffer, Type type,
640 const BufferizationOptions &options);
641
642/// Return the buffer type for a given Value (tensor) after bufferization
643/// without bufferizing any IR.
644///
645/// Note: It should be sufficient to call `getBuffer()->getType()` in most
646/// cases. However, when a buffer type should be predicted without modifying any
647/// IR, this function can be used.
648///
649/// This function is a wrapper around BufferizableOpInterface::getBufferType.
650FailureOr<BufferLikeType> getBufferType(Value value,
651 const BufferizationOptions &options,
652 const BufferizationState &state);
653
654/// Return the buffer type for a given Value (tensor) after bufferization
655/// without bufferizing any IR. This function (and not the other overload
656/// without `invocationStack`) can be used from `getBufferType` implementations
657/// of the `BufferizableOpInterface`.
658///
659/// Note: It should be sufficient to call `getBuffer()->getType()` in most
660/// cases. However, when a buffer type should be predicted without modifying any
661/// IR, this function can be used.
662///
663/// This function is a wrapper around `BufferizableOpInterface::getBufferType`.
664FailureOr<BufferLikeType> getBufferType(Value value,
665 const BufferizationOptions &options,
666 const BufferizationState &state,
667 SmallVector<Value> &invocationStack);
668
669/// Return "true" if the given op has tensor semantics and should be bufferized.
670/// If the op is bufferizable, the BufferizableOpInterface is queried.
671/// Otherwise, an op has tensor semantics if it has tensor operands, tensor
672/// op results and/or tensor block arguments.
673bool hasTensorSemantics(Operation *op);
674
675/// Replace an op with replacement values. The op is deleted. Tensor OpResults
676/// must be replaced with memref values.
677void replaceOpWithBufferizedValues(RewriterBase &rewriter, Operation *op,
678 ValueRange values);
679
680/// Replace an op with a new op. The new op must have the same number of
681/// results as the replaced op. The new op may not return any tensor values.
682template <typename OpTy, typename... Args>
683OpTy replaceOpWithNewBufferizedOp(RewriterBase &rewriter, Operation *op,
684 Args &&...args) {
685 auto newOp =
686 OpTy::create(rewriter, op->getLoc(), std::forward<Args>(args)...);
687 replaceOpWithBufferizedValues(rewriter, op, newOp->getResults());
688 return newOp;
689}
690
691/// Return a MemRef type with fully dynamic layout. If the given tensor type
692/// is unranked, return an unranked MemRef type.
693BaseMemRefType
694getMemRefTypeWithFullyDynamicLayout(TensorType tensorType,
695 Attribute memorySpace = nullptr);
696
697/// Return a MemRef type with a static identity layout (i.e., no layout map). If
698/// the given tensor type is unranked, return an unranked MemRef type.
699BaseMemRefType
700getMemRefTypeWithStaticIdentityLayout(TensorType tensorType,
701 Attribute memorySpace = nullptr);
702
703/// Return the owner of the given value. In case of a BlockArgument that is the
704/// owner of the block. In case of an OpResult that is the defining op.
705Operation *getOwnerOfValue(Value value);
706
707/// Assuming that the given region is repetitive, find the next enclosing
708/// repetitive region.
709Region *getNextEnclosingRepetitiveRegion(Region *region,
710 const BufferizationOptions &options);
711
712/// If `region` is a parallel region, return `region`. Otherwise, find the first
713/// enclosing parallel region of `region`. If there is no such region, return
714/// "nullptr".
715///
716/// Note: Whether a region is parallel or sequential is queried from the
717/// `BufferizableOpInterface`.
718Region *getParallelRegion(Region *region, const BufferizationOptions &options);
719
720namespace detail {
721/// This is the default implementation of
722/// BufferizableOpInterface::getAliasingOpOperands. Should not be called from
723/// other places.
724AliasingOpOperandList defaultGetAliasingOpOperands(Value value,
725 const AnalysisState &state);
726
727/// This is the default implementation of
728/// BufferizableOpInterface::getBufferType. Should not be called from other
729/// places.
730FailureOr<BufferLikeType>
731defaultGetBufferType(Value value, const BufferizationOptions &options,
732 const BufferizationState &state,
733 SmallVector<Value> &invocationStack);
734
735/// This is the default implementation of
736/// BufferizableOpInterface::resultBufferizesToMemoryWrite. Should not be called
737/// from other places.
738bool defaultResultBufferizesToMemoryWrite(OpResult opResult,
739 const AnalysisState &state);
740
741/// This is the default implementation of
742/// BufferizableOpInterface::isRepetitiveRegion. Should not be called from other
743/// places.
744bool defaultIsRepetitiveRegion(BufferizableOpInterface bufferizableOp,
745 unsigned index);
746
747/// This is the default implementation of getAliasingOpOperands in case the
748/// defining op does not implement the BufferizableOpInterface.
749AliasingOpOperandList unknownGetAliasingOpOperands(Value value);
750
751/// This is the default implementation of getAliasingValues in case the owner
752/// op does not implement the BufferizableOpInterface.
753AliasingValueList unknownGetAliasingValues(OpOperand &opOperand);
754
755/// This is the default implementation of
756/// BufferizableOpInterface::hasTensorSemantics
757bool defaultHasTensorSemantics(Operation *op);
758
759/// This is a helper function used when buffer type is guaranteed to be memref.
760/// It performs two actions: failure state checking and an explicit llvm::cast<>
761/// from the buffer-like type interface to a BaseMemRefType. This allows easier
762/// management of differences in C++ types at the API boundaries. Valid buffer
763/// type is casted to the memref type. Otherwise, the failure state is
764/// propagated i.e. asMemRefType(mlir::failure()) returns mlir::failure().
765FailureOr<BaseMemRefType> asMemRefType(FailureOr<BufferLikeType> bufferType);
766
767/// This function is a free-standing helper that relies on
768/// bufferization::TensorLikeTypeInterface to verify the types in tensor and
769/// buffer worlds match.
770bool typesMatchAfterBufferization(Operation &op, Value tensor, Value buffer);
771} // namespace detail
772
773} // namespace bufferization
774} // namespace mlir
775
776MLIR_DECLARE_EXPLICIT_TYPE_ID(mlir::bufferization::AnalysisState)
777
778//===----------------------------------------------------------------------===//
779// Bufferization Interfaces
780//===----------------------------------------------------------------------===//
781
782#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h.inc"
783
784#endif // MLIR_DIALECT_BUFFERIZATION_IR_BUFFERIZABLEOPINTERFACE_H_
bufferization::BufferResultsToOutParamsOpts::AllocationFn AllocationFn
bufferization::BufferResultsToOutParamsOpts::MemCpyFn MemCpyFn
static void copy(Location loc, Value dst, Value src, Value size, OpBuilder &builder)
Copies the given number of bytes from src to dst pointers.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static llvm::ManagedStatic< PassManagerOptions > options
static RankedTensorType getBufferType(const SparseTensorType &stt, bool needTmpCOO)
#define MLIR_DECLARE_EXPLICIT_TYPE_ID(CLASS_NAME)
Definition TypeID.h:321
static Operation * getOwnerOfValue(Value value)
This class helps build Operations.
Definition Builders.h:210
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
bool insideMutuallyExclusiveRegions(Operation *a, Operation *b)
Return true if a and b are in mutually exclusive regions as per RegionBranchOpInterface.
Region * getEnclosingRepetitiveRegion(Operation *op)
Return the first enclosing region of the given op that may be executed repetitively as per RegionBran...