MLIR 24.0.0git
BufferizableOpInterface.cpp
Go to the documentation of this file.
1//===- BufferizableOpInterface.cpp - Bufferizable Ops ---=----------------===//
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
15#include "mlir/IR/AsmState.h"
16#include "mlir/IR/Operation.h"
18#include "mlir/IR/Value.h"
20#include "llvm/ADT/ScopeExit.h"
21#include "llvm/ADT/SmallVectorExtras.h"
22
23//===----------------------------------------------------------------------===//
24// BufferizableOpInterface
25//===----------------------------------------------------------------------===//
26
27namespace mlir {
28namespace bufferization {
29
30#include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.cpp.inc"
31
32} // namespace bufferization
33} // namespace mlir
34
35MLIR_DEFINE_EXPLICIT_TYPE_ID(mlir::bufferization::AnalysisState)
36
37#define DEBUG_TYPE "bufferizable-op-interface"
38
39using namespace mlir;
40using namespace bufferization;
41
42static bool isRepetitiveRegion(Region *region,
44 Operation *op = region->getParentOp();
45 if (auto bufferizableOp = options.dynCastBufferizableOp(op))
46 if (bufferizableOp.isRepetitiveRegion(region->getRegionNumber()))
47 return true;
48 return false;
49}
50
51Region *AnalysisState::getEnclosingRepetitiveRegion(
53 if (!op->getBlock())
54 return nullptr;
55 if (auto iter = enclosingRepetitiveRegionCache.find_as(op);
56 iter != enclosingRepetitiveRegionCache.end())
57 return iter->second;
58 return enclosingRepetitiveRegionCache[op] =
60}
61
62Region *AnalysisState::getEnclosingRepetitiveRegion(
63 Value value, const BufferizationOptions &options) {
64 if (auto iter = enclosingRepetitiveRegionCache.find_as(value);
65 iter != enclosingRepetitiveRegionCache.end())
66 return iter->second;
67
68 Region *region = value.getParentRegion();
69 // Collect all visited regions since we only know the repetitive region we
70 // want to map it to later on
71 SmallVector<Region *> visitedRegions;
72 while (region) {
73 visitedRegions.push_back(region);
74 if (isRepetitiveRegion(region, options))
75 break;
76 region = region->getParentRegion();
77 }
78 enclosingRepetitiveRegionCache[value] = region;
79 for (Region *r : visitedRegions)
80 enclosingRepetitiveRegionCache[r] = region;
81 return region;
82}
83
84Region *AnalysisState::getEnclosingRepetitiveRegion(
85 Block *block, const BufferizationOptions &options) {
86 if (auto iter = enclosingRepetitiveRegionCache.find_as(block);
87 iter != enclosingRepetitiveRegionCache.end())
88 return iter->second;
89
90 Region *region = block->getParent();
91 Operation *op = nullptr;
92 // Collect all visited regions since we only know the repetitive region we
93 // want to map it to later on
94 SmallVector<Region *> visitedRegions;
95 do {
96 op = region->getParentOp();
97 if (isRepetitiveRegion(region, options))
98 break;
99 } while ((region = op->getParentRegion()));
100
101 enclosingRepetitiveRegionCache[block] = region;
102 for (Region *r : visitedRegions)
103 enclosingRepetitiveRegionCache[r] = region;
104 return region;
105}
106
107bool AnalysisState::insideMutuallyExclusiveRegions(Operation *op0,
108 Operation *op1) {
109 auto key = std::make_pair(op0, op1);
110 if (auto iter = insideMutuallyExclusiveRegionsCache.find(key);
111 iter != insideMutuallyExclusiveRegionsCache.end())
112 return iter->second;
114 // Populate results for both orderings of the ops.
115 insideMutuallyExclusiveRegionsCache[key] = result;
116 insideMutuallyExclusiveRegionsCache[std::make_pair(op1, op0)] = result;
117 return result;
118}
119
120void AnalysisState::resetCache() {
121 enclosingRepetitiveRegionCache.clear();
122 insideMutuallyExclusiveRegionsCache.clear();
123}
124
125SymbolTableCollection &BufferizationState::getSymbolTables() {
126 return symbolTables;
127}
128
129SymbolTableCollection &BufferizationState::getSymbolTables() const {
130 return symbolTables;
131}
132
133Region *bufferization::getNextEnclosingRepetitiveRegion(
134 Region *region, const BufferizationOptions &options) {
135 assert(isRepetitiveRegion(region, options) && "expected repetitive region");
136 while ((region = region->getParentRegion())) {
137 if (isRepetitiveRegion(region, options))
138 break;
139 }
140 return region;
141}
142
143Region *bufferization::getParallelRegion(Region *region,
144 const BufferizationOptions &options) {
145 while (region) {
146 auto bufferizableOp = options.dynCastBufferizableOp(region->getParentOp());
147 if (bufferizableOp &&
148 bufferizableOp.isParallelRegion(region->getRegionNumber())) {
149 assert(isRepetitiveRegion(region, options) &&
150 "expected that all parallel regions are also repetitive regions");
151 return region;
152 }
153 region = region->getParentRegion();
154 }
155 return nullptr;
156}
157
158Operation *bufferization::getOwnerOfValue(Value value) {
159 if (auto opResult = llvm::dyn_cast<OpResult>(value))
160 return opResult.getDefiningOp();
161 return llvm::cast<BlockArgument>(value).getOwner()->getParentOp();
162}
163
164/// Create an AllocTensorOp for the given shaped value. If `copy` is set, the
165/// shaped value is copied. Otherwise, a tensor with undefined contents is
166/// allocated.
167FailureOr<Value> bufferization::allocateTensorForShapedValue(
168 OpBuilder &b, Location loc, Value shapedValue,
169 const BufferizationOptions &options, const BufferizationState &state,
170 bool copy) {
171 Value tensor = shapedValue;
172 if (llvm::isa<MemRefType>(shapedValue.getType())) {
173 tensor = ToTensorOp::create(
174 b, loc, memref::getTensorTypeFromMemRefType(shapedValue.getType()),
175 shapedValue);
176 } else if (llvm::isa<UnrankedTensorType>(shapedValue.getType()) ||
177 llvm::isa<UnrankedMemRefType>(shapedValue.getType())) {
178 return getOwnerOfValue(shapedValue)
179 ->emitError("copying of unranked tensors is not implemented");
180 }
181 auto tensorType = llvm::cast<TensorLikeType>(tensor.getType());
182 SmallVector<Value> dynamicSizes;
183 // Only a ranked tensor result takes sizes; any other result has the shape of
184 // its buffer type.
185 auto rankedTensorType = dyn_cast<RankedTensorType>(tensorType);
186 if (!copy && rankedTensorType) {
187 // Compute the dynamic part of the shape.
188 // First try to query the shape via ReifyRankedShapedTypeOpInterface.
189 bool reifiedShapes = false;
190 if (llvm::isa<RankedTensorType>(shapedValue.getType()) &&
191 llvm::isa<OpResult>(shapedValue)) {
193 if (succeeded(
194 reifyResultShapes(b, shapedValue.getDefiningOp(), resultDims))) {
195 reifiedShapes = true;
196 auto &shape =
197 resultDims[llvm::cast<OpResult>(shapedValue).getResultNumber()];
198 for (const auto &dim : enumerate(rankedTensorType.getShape())) {
199 if (ShapedType::isDynamic(dim.value())) {
200 dynamicSizes.push_back(
201 getValueOrCreateConstantIndexOp(b, loc, shape[dim.index()]));
202 }
203 }
204 }
205 }
206
207 // If the shape could not be reified, create DimOps.
208 if (!reifiedShapes)
209 populateDynamicDimSizes(b, loc, tensor, dynamicSizes);
210 }
211
212 // Create AllocTensorOp.
213 auto allocTensorOp = AllocTensorOp::create(b, loc, tensorType, dynamicSizes,
214 copy ? tensor : Value());
215
216 // Add 'memory_space' attribute. Not needed if 'copy' operand is specified.
217 if (copy)
218 return allocTensorOp.getResult();
219 auto copyBufferType = getBufferType(tensor, options, state);
220 if (failed(copyBufferType))
221 return failure();
222 // A buffer that is not a memref has no memory space to inherit.
223 std::optional<Attribute> memorySpace;
224 if (auto copyMemRefType = dyn_cast<BaseMemRefType>(*copyBufferType))
225 memorySpace = copyMemRefType.getMemorySpace();
226 if (!memorySpace)
227 memorySpace =
228 options.defaultMemorySpaceFn(cast<TensorLikeType>(tensorType));
229 if (memorySpace.has_value())
230 allocTensorOp.setMemorySpaceAttr(memorySpace.value());
231 return allocTensorOp.getResult();
232}
233
234LogicalResult BufferizableOpInterface::resolveTensorOpOperandConflicts(
235 RewriterBase &rewriter, const AnalysisState &analysisState,
236 const BufferizationState &bufferizationState) {
237 OpBuilder::InsertionGuard g(rewriter);
238 Operation *op = getOperation();
239 SmallVector<OpOperand *> outOfPlaceOpOperands;
240 DenseSet<OpOperand *> copiedOpOperands;
241 SmallVector<Value> outOfPlaceValues;
242 DenseSet<Value> copiedOpValues;
243
244 // Find all out-of-place OpOperands.
245 for (OpOperand &opOperand : op->getOpOperands()) {
246 Type operandType = opOperand.get().getType();
247 if (!llvm::isa<TensorLikeType>(operandType))
248 continue;
249 if (analysisState.isInPlace(opOperand))
250 continue;
251 if (llvm::isa<UnrankedTensorType>(operandType))
252 return op->emitError("copying of unranked tensors is not implemented");
253
254 AliasingValueList aliasingValues =
255 analysisState.getAliasingValues(opOperand);
256 if (aliasingValues.getNumAliases() == 1 &&
257 isa<OpResult>(aliasingValues.getAliases()[0].value) &&
258 !analysisState.bufferizesToMemoryWrite(opOperand) &&
259 analysisState
260 .getAliasingOpOperands(aliasingValues.getAliases()[0].value)
261 .getNumAliases() == 1 &&
262 !isa<UnrankedTensorType>(
263 aliasingValues.getAliases()[0].value.getType())) {
264 // The op itself does not write but may create exactly one alias. Instead
265 // of copying the OpOperand, copy the OpResult. The OpResult can sometimes
266 // be smaller than the OpOperand (e.g., in the case of an extract_slice,
267 // where the result is usually a smaller part of the source). Do not apply
268 // this optimization if the OpResult is an unranked tensor (because those
269 // cannot be copied at the moment).
270 Value value = aliasingValues.getAliases()[0].value;
271 outOfPlaceValues.push_back(value);
272 if (!analysisState.canOmitTensorCopy(opOperand))
273 copiedOpValues.insert(value);
274 } else {
275 // In all other cases, make a copy of the OpOperand.
276 outOfPlaceOpOperands.push_back(&opOperand);
277 if (!analysisState.canOmitTensorCopy(opOperand))
278 copiedOpOperands.insert(&opOperand);
279 }
280 }
281
282 // Insert copies of OpOperands.
283 rewriter.setInsertionPoint(op);
284 for (OpOperand *opOperand : outOfPlaceOpOperands) {
285 FailureOr<Value> copy = allocateTensorForShapedValue(
286 rewriter, op->getLoc(), opOperand->get(), analysisState.getOptions(),
287 bufferizationState, copiedOpOperands.contains(opOperand));
288 if (failed(copy))
289 return failure();
290 rewriter.modifyOpInPlace(op, [&]() { opOperand->set(*copy); });
291 }
292
293 // Insert copies of Values.
294 rewriter.setInsertionPointAfter(op);
295 for (Value value : outOfPlaceValues) {
296 FailureOr<Value> copy = allocateTensorForShapedValue(
297 rewriter, op->getLoc(), value, analysisState.getOptions(),
298 bufferizationState, copiedOpValues.count(value));
299 if (failed(copy))
300 return failure();
301 SmallVector<OpOperand *> uses = llvm::map_to_vector(
302 value.getUses(), [](OpOperand &use) { return &use; });
303 for (OpOperand *use : uses) {
304 // Do not update the alloc_tensor op that we just created.
305 if (use->getOwner() == copy->getDefiningOp())
306 continue;
307 // tensor.dim ops may have been created to be used as alloc_tensor op
308 // dynamic extents. Do not update these either.
309 if (isa<tensor::DimOp>(use->getOwner()))
310 continue;
311 rewriter.modifyOpInPlace(use->getOwner(), [&]() { use->set(*copy); });
312 }
313 }
314
315 return success();
316}
317
318//===----------------------------------------------------------------------===//
319// OpFilter
320//===----------------------------------------------------------------------===//
321
322bool OpFilter::isOpAllowed(Operation *op) const {
323 // All other ops: Allow/disallow according to filter.
324 bool isAllowed = !hasAllowRule();
325 for (const Entry &entry : entries) {
326 bool filterResult = entry.fn(op);
327 switch (entry.type) {
328 case Entry::ALLOW:
329 isAllowed |= filterResult;
330 break;
331 case Entry::DENY:
332 if (filterResult)
333 // DENY filter matches. This op is no allowed. (Even if other ALLOW
334 // filters may match.)
335 return false;
336 };
337 }
338 return isAllowed;
339}
340
341//===----------------------------------------------------------------------===//
342// BufferizationOptions
343//===----------------------------------------------------------------------===//
344
345namespace {
346
347// A helper overload for bufferization::getMemRefTypeWithFullyDynamicLayout().
348BaseMemRefType getMemRefTypeWithFullyDynamicLayout(ArrayRef<int64_t> shape,
349 mlir::Type elementType,
350 Attribute memorySpace) {
351 int64_t dynamicOffset = ShapedType::kDynamic;
352 SmallVector<int64_t> dynamicStrides(shape.size(), ShapedType::kDynamic);
353 auto stridedLayout = StridedLayoutAttr::get(elementType.getContext(),
354 dynamicOffset, dynamicStrides);
355 return MemRefType::get(shape, elementType, stridedLayout, memorySpace);
356}
357
358/// Create a memref allocation with the given type and dynamic extents.
359FailureOr<Value> defaultCreateAlloc(OpBuilder &b, Location loc, MemRefType type,
360 ValueRange dynShape,
361 unsigned int bufferAlignment) {
362 // Default buffer allocation via AllocOp.
363 if (bufferAlignment != 0)
364 return memref::AllocOp::create(b, loc, type, dynShape,
365 b.getI64IntegerAttr(bufferAlignment))
366 .getResult();
367 return memref::AllocOp::create(b, loc, type, dynShape).getResult();
368}
369
370/// Create a memory copy between two memref buffers.
371LogicalResult defaultCreateMemCpy(OpBuilder &b, Location loc, Value from,
372 Value to) {
373 memref::CopyOp::create(b, loc, from, to);
374 return success();
375}
376
377/// Create a `memref.cast` between two cast-compatible memrefs; refuse any
378/// other pair.
379FailureOr<Value> defaultCreateCast(OpBuilder &b, Location loc, Type dest,
380 Value value) {
381 if (!isa<BaseMemRefType>(dest) || !isa<BaseMemRefType>(value.getType()) ||
382 !memref::CastOp::areCastCompatible(value.getType(), dest))
383 return failure();
384 return memref::CastOp::create(b, loc, dest, value).getResult();
385}
386
387/// Default function arg type converter: Use a fully dynamic layout map.
388BufferLikeType
389defaultFunctionArgTypeConverter(TensorLikeType type, Attribute memorySpace,
390 func::FuncOp funcOp,
391 const BufferizationOptions &options) {
392 if (auto tensorType = mlir::dyn_cast<TensorType>(type)) {
393 return cast<BufferLikeType>(
394 bufferization::getMemRefTypeWithFullyDynamicLayout(tensorType,
395 memorySpace));
396 }
397
398 // If not builtin, fallback to unknown type conversion.
399 return options.unknownTypeConverterFn(type, memorySpace, options);
400}
401/// Default unknown type converter: Use a fully dynamic layout map.
402BufferLikeType
403defaultUnknownTypeConverter(TensorLikeType tensorType, Attribute memorySpace,
404 const BufferizationOptions &options) {
405 return cast<BufferLikeType>(
406 bufferization::getMemRefTypeWithFullyDynamicLayout(
407 cast<TensorType>(tensorType), memorySpace));
408}
409
410/// Default reconcile hook: memory space mismatch is an error, layout mismatch
411/// is resolved by promoting to fully dynamic.
412FailureOr<BufferLikeType>
413defaultReconcileBufferTypeMismatch(BufferLikeType x, BufferLikeType y,
414 const BufferizationOptions &) {
415 const auto xMemRef = cast<BaseMemRefType>(x);
416 const auto yMemRef = cast<BaseMemRefType>(y);
417
418 if (xMemRef.getMemorySpace() != yMemRef.getMemorySpace())
419 return failure();
420
421 if (isa<UnrankedMemRefType>(xMemRef)) {
422 // unranked memrefs have no layout.
423 return x;
424 }
425
426 return cast<BufferLikeType>(::getMemRefTypeWithFullyDynamicLayout(
427 xMemRef.getShape(), xMemRef.getElementType(), xMemRef.getMemorySpace()));
428}
429
430} // namespace
431
432// Default constructor for BufferizationOptions.
433BufferizationOptions::BufferizationOptions()
434 : allocationFn(defaultCreateAlloc), memCpyFn(defaultCreateMemCpy),
435 castFn(defaultCreateCast),
436 functionArgTypeConverterFn(defaultFunctionArgTypeConverter),
437 unknownTypeConverterFn(defaultUnknownTypeConverter),
438 reconcileBufferTypeMismatchFn(defaultReconcileBufferTypeMismatch) {}
439
440bool BufferizationOptions::isOpAllowed(Operation *op) const {
441 // Special case: If function boundary bufferization is deactivated, do not
442 // allow ops that belong to the `func` dialect.
443 bool isFuncBoundaryOp = isa_and_nonnull<func::FuncDialect>(op->getDialect());
444 if (!bufferizeFunctionBoundaries && isFuncBoundaryOp)
445 return false;
446
447 return opFilter.isOpAllowed(op);
448}
449
450BufferizableOpInterface
451BufferizationOptions::dynCastBufferizableOp(Operation *op) const {
452 if (!isOpAllowed(op))
453 return nullptr;
454 auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op);
455 if (!bufferizableOp)
456 return nullptr;
457 return bufferizableOp;
458}
459
460BufferizableOpInterface
461BufferizationOptions::dynCastBufferizableOp(Value value) const {
462 return dynCastBufferizableOp(getOwnerOfValue(value));
463}
464
465void BufferizationOptions::setFunctionBoundaryTypeConversion(
466 LayoutMapOption layoutMapOption) {
467 functionArgTypeConverterFn = [=](TensorLikeType type, Attribute memorySpace,
468 func::FuncOp funcOp,
469 const BufferizationOptions &options) {
470 if (auto tensorType = mlir::dyn_cast<TensorType>(type)) {
471 if (layoutMapOption == LayoutMapOption::IdentityLayoutMap)
472 return cast<BufferLikeType>(
473 bufferization::getMemRefTypeWithStaticIdentityLayout(tensorType,
474 memorySpace));
475 return cast<BufferLikeType>(
476 bufferization::getMemRefTypeWithFullyDynamicLayout(tensorType,
477 memorySpace));
478 }
479
480 // If not builtin, fallback to unknown type conversion.
481 return options.unknownTypeConverterFn(type, memorySpace, options);
482 };
483 inferFunctionResultLayout =
484 layoutMapOption == LayoutMapOption::InferLayoutMap;
485}
486
487//===----------------------------------------------------------------------===//
488// Helper functions for BufferizableOpInterface
489//===----------------------------------------------------------------------===//
490
492 if (auto bbArg = llvm::dyn_cast<BlockArgument>(value)) {
493 b.setInsertionPointToStart(bbArg.getOwner());
494 } else {
495 b.setInsertionPointAfter(value.getDefiningOp());
496 }
497}
498
499/// Determine which OpOperand* will alias with `value` if the op is bufferized
500/// in place. Return all tensor OpOperand* if the op is not bufferizable.
501AliasingOpOperandList AnalysisState::getAliasingOpOperands(Value value) const {
502 if (Operation *op = getOwnerOfValue(value))
503 if (auto bufferizableOp = getOptions().dynCastBufferizableOp(op))
504 return bufferizableOp.getAliasingOpOperands(value, *this);
505
506 // The op is not bufferizable.
507 return detail::unknownGetAliasingOpOperands(value);
508}
509
510/// Determine which Values will alias with `opOperand` if the op is bufferized
511/// in place. Return all tensor Values if the op is not bufferizable.
512AliasingValueList AnalysisState::getAliasingValues(OpOperand &opOperand) const {
513 if (auto bufferizableOp =
514 getOptions().dynCastBufferizableOp(opOperand.getOwner()))
515 return bufferizableOp.getAliasingValues(opOperand, *this);
516
517 // The op is not bufferizable.
518 return detail::unknownGetAliasingValues(opOperand);
519}
520
521/// Return true if `opOperand` bufferizes to a memory read. Return `true` if the
522/// op is not bufferizable.
523bool AnalysisState::bufferizesToMemoryRead(OpOperand &opOperand) const {
524 if (auto bufferizableOp =
525 getOptions().dynCastBufferizableOp(opOperand.getOwner()))
526 return bufferizableOp.bufferizesToMemoryRead(opOperand, *this);
527
528 // Unknown op that returns a tensor. The inplace analysis does not support it.
529 // Conservatively return true.
530 return true;
531}
532
533/// Return true if `opOperand` bufferizes to a memory write. Return
534/// `true` if the op is not bufferizable.
535bool AnalysisState::bufferizesToMemoryWrite(OpOperand &opOperand) const {
536 if (auto bufferizableOp =
537 getOptions().dynCastBufferizableOp(opOperand.getOwner()))
538 return bufferizableOp.bufferizesToMemoryWrite(opOperand, *this);
539
540 // Unknown op that returns a tensor. The inplace analysis does not support it.
541 // Conservatively return true.
542 return true;
543}
544
545/// Return true if `opOperand` does neither read nor write but bufferizes to an
546/// alias. Return false if the op is not bufferizable.
547bool AnalysisState::bufferizesToAliasOnly(OpOperand &opOperand) const {
548 if (auto bufferizableOp =
549 getOptions().dynCastBufferizableOp(opOperand.getOwner()))
550 return bufferizableOp.bufferizesToAliasOnly(opOperand, *this);
551
552 // Unknown op that returns a tensor. The inplace analysis does not support it.
553 // Conservatively return false.
554 return false;
555}
556
557bool AnalysisState::bufferizesToMemoryWrite(Value value) const {
558 auto opResult = llvm::dyn_cast<OpResult>(value);
559 if (!opResult)
560 return true;
561 auto bufferizableOp = getOptions().dynCastBufferizableOp(value);
562 if (!bufferizableOp)
563 return true;
564 return bufferizableOp.resultBufferizesToMemoryWrite(opResult, *this);
565}
566
567/// Return true if the given value is read by an op that bufferizes to a memory
568/// read. Also takes into account ops that create an alias but do not read by
569/// themselves (e.g., ExtractSliceOp).
570bool AnalysisState::isValueRead(Value value) const {
571 assert(llvm::isa<TensorLikeType>(value.getType()) &&
572 "expected TensorLikeType");
573 SmallVector<OpOperand *> workingSet;
574 DenseSet<OpOperand *> visited;
575 for (OpOperand &use : value.getUses())
576 workingSet.push_back(&use);
577
578 while (!workingSet.empty()) {
579 OpOperand *uMaybeReading = workingSet.pop_back_val();
580 if (!visited.insert(uMaybeReading).second)
581 continue;
582
583 // Skip over all ops that neither read nor write (but create an alias).
584 if (bufferizesToAliasOnly(*uMaybeReading))
585 for (AliasingValue alias : getAliasingValues(*uMaybeReading))
586 for (OpOperand &use : alias.value.getUses())
587 workingSet.push_back(&use);
588 if (bufferizesToMemoryRead(*uMaybeReading))
589 return true;
590 }
591
592 return false;
593}
594
595// Starting from `opOperand`, follow the use-def chain in reverse, always
596// selecting the aliasing OpOperands. Find and return Values for which
597// `condition` evaluates to true. Uses of such matching Values are not
598// traversed any further, the visited aliasing opOperands will be preserved
599// through `visitedOpOperands`.
600llvm::SetVector<Value> AnalysisState::findValueInReverseUseDefChain(
601 OpOperand *opOperand, llvm::function_ref<bool(Value)> condition,
602 TraversalConfig config,
603 llvm::DenseSet<OpOperand *> *visitedOpOperands) const {
604 llvm::DenseSet<Value> visited;
605 llvm::SetVector<Value> result, workingSet;
606 workingSet.insert(opOperand->get());
607
608 if (visitedOpOperands)
609 visitedOpOperands->insert(opOperand);
610
611 while (!workingSet.empty()) {
612 Value value = workingSet.pop_back_val();
613
614 if (!config.revisitAlreadyVisitedValues && visited.contains(value)) {
615 // Stop traversal if value was already visited.
616 if (config.alwaysIncludeLeaves)
617 result.insert(value);
618 continue;
619 }
620 visited.insert(value);
621
622 if (condition(value)) {
623 result.insert(value);
624 continue;
625 }
626
627 if (!config.followUnknownOps && !options.dynCastBufferizableOp(value)) {
628 // Stop iterating if `followUnknownOps` is unset and the op is either
629 // not bufferizable or excluded in the OpFilter.
630 if (config.alwaysIncludeLeaves)
631 result.insert(value);
632 continue;
633 }
634
635 AliasingOpOperandList aliases = getAliasingOpOperands(value);
636 if (aliases.getNumAliases() == 0) {
637 // The traversal ends naturally if there are no more OpOperands that
638 // could be followed.
639 if (config.alwaysIncludeLeaves)
640 result.insert(value);
641 continue;
642 }
643
644 for (AliasingOpOperand a : aliases) {
645 if (config.followEquivalentOnly &&
646 a.relation != BufferRelation::Equivalent) {
647 // Stop iterating if `followEquivalentOnly` is set but the alias is not
648 // equivalent.
649 if (config.alwaysIncludeLeaves)
650 result.insert(value);
651 continue;
652 }
653
654 if (config.followInPlaceOnly && !isInPlace(*a.opOperand)) {
655 // Stop iterating if `followInPlaceOnly` is set but the alias is
656 // out-of-place.
657 if (config.alwaysIncludeLeaves)
658 result.insert(value);
659 continue;
660 }
661
662 if (config.followSameTypeOrCastsOnly &&
663 a.opOperand->get().getType() != value.getType() &&
664 !value.getDefiningOp<CastOpInterface>()) {
665 // Stop iterating if `followSameTypeOrCastsOnly` is set but the alias is
666 // has a different type and the op is not a cast.
667 if (config.alwaysIncludeLeaves)
668 result.insert(value);
669 continue;
670 }
671
672 workingSet.insert(a.opOperand->get());
673 if (visitedOpOperands)
674 visitedOpOperands->insert(a.opOperand);
675 }
676 }
677
678 return result;
679}
680
681// Find the values that define the contents of the given operand's value.
682llvm::SetVector<Value>
683AnalysisState::findDefinitions(OpOperand *opOperand) const {
684 TraversalConfig config;
685 config.alwaysIncludeLeaves = false;
686 return findValueInReverseUseDefChain(
687 opOperand, [&](Value v) { return this->bufferizesToMemoryWrite(v); },
688 config);
689}
690
691AnalysisState::AnalysisState(const BufferizationOptions &options)
693
695 : options(options), type(type) {
696 for (const BufferizationOptions::AnalysisStateInitFn &fn :
697 options.stateInitializers)
698 fn(*this);
699}
700
701bool AnalysisState::canOmitTensorCopy(OpOperand &opOperand) const {
702 // Do not copy if the tensor has undefined contents.
703 if (hasUndefinedContents(&opOperand))
704 return true;
705
706 // Do not copy if the buffer of the tensor is entirely overwritten (with
707 // values that do not depend on the old tensor).
708 if (bufferizesToMemoryWrite(opOperand) && !bufferizesToMemoryRead(opOperand))
709 return true;
710
711 // Do not copy if the tensor is never read.
712 AliasingValueList aliases = getAliasingValues(opOperand);
713 if (!bufferizesToMemoryRead(opOperand) &&
714 llvm::none_of(aliases,
715 [&](AliasingValue a) { return isValueRead(a.value); }))
716 return true;
717
718 // Default: Cannot omit the copy.
719 return false;
720}
721
722bool AnalysisState::isInPlace(OpOperand &opOperand) const {
723 // ToBufferOps are always in-place.
724 if (isa<ToBufferOp>(opOperand.getOwner()))
725 return true;
726
727 // In the absence of analysis information, OpOperands that bufferize to a
728 // memory write are out-of-place, i.e., an alloc and copy is inserted.
729 return !bufferizesToMemoryWrite(opOperand);
730}
731
732bool AnalysisState::areEquivalentBufferizedValues(Value v1, Value v2) const {
733 // In the absence of analysis information, we do not know if the values are
734 // equivalent. The conservative answer is "false".
735 return false;
736}
737
738bool AnalysisState::areAliasingBufferizedValues(Value v1, Value v2) const {
739 // In the absence of analysis information, we do not know if the values may be
740 // aliasing. The conservative answer is "true".
741 return true;
742}
743
744bool AnalysisState::hasUndefinedContents(OpOperand *opOperand) const {
745 // In the absence of analysis information, the conservative answer is "false".
746 return false;
747}
748
749FailureOr<Value> bufferization::getBuffer(RewriterBase &rewriter, Value value,
750 const BufferizationOptions &options,
751 const BufferizationState &state) {
752#ifndef NDEBUG
753 auto tensorType = llvm::dyn_cast<TensorLikeType>(value.getType());
754 assert(tensorType && "unexpected non-tensor type");
755#endif // NDEBUG
756
757 // Replace "%t = to_tensor %m" with %m.
758 if (auto toTensorOp = value.getDefiningOp<bufferization::ToTensorOp>())
759 return toTensorOp.getBuffer();
760
761 // Insert to_buffer op.
762 OpBuilder::InsertionGuard g(rewriter);
763 setInsertionPointAfter(rewriter, value);
764 FailureOr<BufferLikeType> bufferType = getBufferType(value, options, state);
765 if (failed(bufferType))
766 return failure();
767
768 return bufferization::ToBufferOp::create(rewriter, value.getLoc(),
769 *bufferType, value)
770 .getResult();
771}
772
773FailureOr<Value>
774bufferization::castBuffer(OpBuilder &b, Location loc, Value buffer, Type type,
775 const BufferizationOptions &options) {
776 if (buffer.getType() == type)
777 return buffer;
778 FailureOr<Value> casted = options.castFn(b, loc, type, buffer);
779 if (failed(casted))
780 return emitError(loc) << "cannot cast a buffer of type " << buffer.getType()
781 << " to " << type;
782 return casted;
783}
784
785/// Return the buffer type for a given Value (tensor) after bufferization.
786FailureOr<BufferLikeType>
787bufferization::getBufferType(Value value, const BufferizationOptions &options,
788 const BufferizationState &state) {
789 SmallVector<Value> invocationStack;
790 return getBufferType(value, options, state, invocationStack);
791}
792
793/// Return the buffer type for a given Value (tensor) after bufferization.
794FailureOr<BufferLikeType>
795bufferization::getBufferType(Value value, const BufferizationOptions &options,
796 const BufferizationState &state,
797 SmallVector<Value> &invocationStack) {
798 assert(llvm::isa<TensorLikeType>(value.getType()) &&
799 "unexpected non-tensor type");
800 invocationStack.push_back(value);
801 llvm::scope_exit popFromStack([&]() { invocationStack.pop_back(); });
802
803 // Try querying BufferizableOpInterface.
804 Operation *op = getOwnerOfValue(value);
805 auto bufferizableOp = options.dynCastBufferizableOp(op);
806 if (bufferizableOp)
807 return bufferizableOp.getBufferType(value, options, state, invocationStack);
808
809 // Op is not bufferizable.
810 auto memSpace =
811 options.defaultMemorySpaceFn(cast<TensorLikeType>(value.getType()));
812 if (!memSpace.has_value())
813 return op->emitError("could not infer memory space");
814
815 return options.unknownTypeConverterFn(cast<TensorLikeType>(value.getType()),
816 *memSpace, options);
817}
818
819bool bufferization::hasTensorSemantics(Operation *op) {
820 if (auto bufferizableOp = dyn_cast<BufferizableOpInterface>(op))
821 return bufferizableOp.hasTensorSemantics();
822 return detail::defaultHasTensorSemantics(op);
823}
824
825void bufferization::replaceOpWithBufferizedValues(RewriterBase &rewriter,
826 Operation *op,
827 ValueRange values) {
828 assert(values.size() == op->getNumResults() &&
829 "expected one value per OpResult");
830 OpBuilder::InsertionGuard g(rewriter);
831
832 // Replace all OpResults with the given values.
833 SmallVector<Value> replacements;
834 for (OpResult opResult : op->getOpResults()) {
835 Value replacement = values[opResult.getResultNumber()];
836 if (llvm::isa<TensorLikeType>(opResult.getType())) {
837 // The OpResult is a tensor. Such values are replaced with memrefs during
838 // bufferization.
839 assert(llvm::isa<BufferLikeType>(replacement.getType()) &&
840 "tensor op result should be replaced with a buffer value");
841 // The existing uses of the OpResult still expect a tensor. Insert a
842 // ToTensorOp. Throughout bufferization, this ToTensorOp will gradually
843 // loose all of its users and eventually DCE away.
844 rewriter.setInsertionPointAfter(op);
845 replacement = bufferization::ToTensorOp::create(
846 rewriter, replacement.getLoc(), opResult.getType(), replacement);
847 }
848 replacements.push_back(replacement);
849 }
850
851 rewriter.replaceOp(op, replacements);
852}
853
854//===----------------------------------------------------------------------===//
855// Bufferization-specific IRMapping support with debugging.
856//===----------------------------------------------------------------------===//
857
859bufferization::getMemRefTypeWithFullyDynamicLayout(TensorType tensorType,
860 Attribute memorySpace) {
861 // Case 1: Unranked memref type.
862 if (auto unrankedTensorType =
863 llvm::dyn_cast<UnrankedTensorType>(tensorType)) {
864 return UnrankedMemRefType::get(unrankedTensorType.getElementType(),
865 memorySpace);
866 }
867
868 // Case 2: Ranked memref type.
869 return ::getMemRefTypeWithFullyDynamicLayout(
870 tensorType.getShape(), tensorType.getElementType(), memorySpace);
871}
872
873/// Return a MemRef type with a static identity layout (i.e., no layout map). If
874/// the given tensor type is unranked, return an unranked MemRef type.
876bufferization::getMemRefTypeWithStaticIdentityLayout(TensorType tensorType,
877 Attribute memorySpace) {
878 // Case 1: Unranked memref type.
879 if (auto unrankedTensorType =
880 llvm::dyn_cast<UnrankedTensorType>(tensorType)) {
881 return UnrankedMemRefType::get(unrankedTensorType.getElementType(),
882 memorySpace);
883 }
884
885 // Case 2: Ranked memref type.
886 auto rankedTensorType = llvm::cast<RankedTensorType>(tensorType);
887 MemRefLayoutAttrInterface layout = {};
888 return MemRefType::get(rankedTensorType.getShape(),
889 rankedTensorType.getElementType(), layout,
890 memorySpace);
891}
892
893//===----------------------------------------------------------------------===//
894// Default implementations of interface methods
895//===----------------------------------------------------------------------===//
896
897bool bufferization::detail::defaultResultBufferizesToMemoryWrite(
898 OpResult opResult, const AnalysisState &state) {
899 auto bufferizableOp = cast<BufferizableOpInterface>(opResult.getDefiningOp());
900 AliasingOpOperandList opOperands =
901 bufferizableOp.getAliasingOpOperands(opResult, state);
902
903 // Case 1: OpResults that have no aliasing OpOperand usually bufferize to
904 // memory writes.
905 if (opOperands.getAliases().empty())
906 return true;
907
908 // Case 2: If an aliasing OpOperand bufferizes to a memory write, the OpResult
909 // may bufferize to a memory write.
910 if (llvm::any_of(opOperands, [&](AliasingOpOperand alias) {
911 return state.bufferizesToMemoryWrite(*alias.opOperand);
912 }))
913 return true;
914
915 // Case 3: Check if a nested aliasing OpOperand value bufferizes to a memory
916 // write. (Or: The reverse SSA use-def chain ends inside the reigon.) In that
917 // case, the OpResult bufferizes to a memory write. E.g.:
918 //
919 // %0 = "some_writing_op" : tensor<?xf32>
920 // %r = scf.if ... -> tensor<?xf32> {
921 // scf.yield %0 : tensor<?xf32>
922 // } else {
923 // %1 = "another_writing_op"(%0) : tensor<?xf32>
924 // scf.yield %1 : tensor<?xf32>
925 // }
926 // "some_reading_op"(%r)
927 //
928 // %r bufferizes to a memory write because an aliasing OpOperand value (%1)
929 // bufferizes to a memory write and the defining op is inside the scf.if.
930 //
931 // Note: This treatment of surrouding ops is useful for ops that have a
932 // region but no OpOperand such as scf.if or scf.execute_region. It simplifies
933 // the analysis considerably.
934 //
935 // "another_writing_op" in the above example should be able to bufferize
936 // inplace in the absence of another read of %0. However, if the scf.if op
937 // would not be considered a "write", the analysis would detect the
938 // following conflict:
939 //
940 // * read = some_reading_op
941 // * lastWrite = %0 (Note: The last write of %r would be a set: {%0, %1}.)
942 // * conflictingWrite = %1
943 //
944 auto isMemoryWriteInsideOp = [&](Value v) {
945 Operation *op = getOwnerOfValue(v);
946 if (!opResult.getDefiningOp()->isAncestor(op))
947 return false;
948 return state.bufferizesToMemoryWrite(v);
949 };
950 TraversalConfig config;
951 config.alwaysIncludeLeaves = false;
952 for (AliasingOpOperand alias : opOperands) {
953 if (!state
954 .findValueInReverseUseDefChain(alias.opOperand,
955 isMemoryWriteInsideOp, config)
956 .empty())
957 return true;
958 }
959 return false;
960}
961
962// Compute the AliasingOpOperandList for a given Value based on
963// getAliasingValues.
964AliasingOpOperandList bufferization::detail::defaultGetAliasingOpOperands(
965 Value value, const AnalysisState &state) {
966 Operation *op = getOwnerOfValue(value);
968 for (OpOperand &opOperand : op->getOpOperands()) {
969 if (!llvm::isa<TensorLikeType>(opOperand.get().getType()))
970 continue;
971 AliasingValueList aliasingValues = state.getAliasingValues(opOperand);
972 for (const auto &it : aliasingValues)
973 if (it.value == value)
974 result.emplace_back(&opOperand, it.relation, it.isDefinite);
975 }
976 return AliasingOpOperandList(std::move(result));
977}
978
979FailureOr<BufferLikeType> bufferization::detail::defaultGetBufferType(
980 Value value, const BufferizationOptions &options,
981 const BufferizationState &bufferizationState,
982 SmallVector<Value> &invocationStack) {
983 assert(llvm::isa<TensorType>(value.getType()) && "expected tensor type");
984 auto tensorType = cast<TensorType>(value.getType());
985
986 auto elementType = tensorType.getElementType();
987
988 if (!BaseMemRefType::isValidElementType(elementType))
989 return getOwnerOfValue(value)->emitError()
990 << "cannot bufferize value of type " << tensorType
991 << ": element type " << elementType
992 << " is not a valid memref element type";
993
994 // No further analysis is possible for a block argument.
995 if (llvm::isa<BlockArgument>(value)) {
996 return options.unknownTypeConverterFn(cast<TensorLikeType>(tensorType),
997 /*memorySpace=*/nullptr, options);
998 }
999
1000 // Value is an OpResult.
1001 Operation *op = getOwnerOfValue(value);
1002 auto opResult = llvm::cast<OpResult>(value);
1003 AnalysisState analysisState(options);
1004 AliasingOpOperandList aliases = analysisState.getAliasingOpOperands(opResult);
1005 if (aliases.getNumAliases() > 0 &&
1006 aliases.getAliases()[0].relation == BufferRelation::Equivalent) {
1007 // If the OpResult has an equivalent OpOperand, both OpResult and
1008 // OpOperand bufferize to the exact same buffer type.
1009 Value equivalentOperand = aliases.getAliases().front().opOperand->get();
1010 return getBufferType(equivalentOperand, options, bufferizationState,
1011 invocationStack);
1012 }
1013
1014 // If we do not know the memory space and there is no default memory space,
1015 // report a failure.
1016 auto memSpace =
1017 options.defaultMemorySpaceFn(cast<TensorLikeType>(tensorType));
1018 if (!memSpace.has_value())
1019 return op->emitError("could not infer memory space");
1020
1021 return options.unknownTypeConverterFn(cast<TensorLikeType>(tensorType),
1022 *memSpace, options);
1023}
1024
1025bool bufferization::detail::defaultIsRepetitiveRegion(
1026 BufferizableOpInterface bufferizableOp, unsigned index) {
1027 assert(index < bufferizableOp->getNumRegions() && "invalid region index");
1028 auto regionInterface =
1029 dyn_cast<RegionBranchOpInterface>(bufferizableOp.getOperation());
1030 if (!regionInterface)
1031 return false;
1032 return regionInterface.isRepetitiveRegion(index);
1033}
1034
1035AliasingOpOperandList
1036bufferization::detail::unknownGetAliasingOpOperands(Value value) {
1037 // TODO: Take into account successor blocks.
1038 // No aliasing in case of non-entry blocks.
1039 if (auto bbArg = dyn_cast<BlockArgument>(value))
1040 if (bbArg.getOwner() != &bbArg.getOwner()->getParent()->getBlocks().front())
1041 return {};
1042
1043 // Unknown op: Conservatively assume that each OpResult may alias with every
1044 // OpOperand. In addition, each block argument of an entry block may alias
1045 // with every OpOperand.
1046 AliasingOpOperandList r;
1047 for (OpOperand &operand : value.getDefiningOp()->getOpOperands())
1048 if (isa<TensorLikeType>(operand.get().getType()))
1049 r.addAlias({&operand, BufferRelation::Unknown, /*isDefinite=*/false});
1050 return r;
1051}
1052
1053AliasingValueList
1054bufferization::detail::unknownGetAliasingValues(OpOperand &opOperand) {
1055 // TODO: Take into account successor blocks.
1056 // Unknown op: Conservatively assume that each OpResult may alias with every
1057 // OpOperand. In addition, each block argument of an entry block may alias
1058 // with every OpOperand.
1059 AliasingValueList r;
1060 for (OpResult result : opOperand.getOwner()->getOpResults())
1061 if (llvm::isa<TensorLikeType>(result.getType()))
1062 r.addAlias({result, BufferRelation::Unknown, /*isDefinite=*/false});
1063 for (Region &region : opOperand.getOwner()->getRegions())
1064 if (!region.getBlocks().empty())
1065 for (BlockArgument bbArg : region.getBlocks().front().getArguments())
1066 if (isa<TensorLikeType>(bbArg.getType()))
1067 r.addAlias({bbArg, BufferRelation::Unknown, /*isDefinite=*/false});
1068 return r;
1069}
1070
1071bool bufferization::detail::defaultHasTensorSemantics(Operation *op) {
1072 auto isaTensor = [](Type t) { return isa<TensorLikeType>(t); };
1073 bool hasTensorBlockArgument = any_of(op->getRegions(), [&](Region &r) {
1074 return any_of(r.getBlocks(), [&](Block &b) {
1075 return any_of(b.getArguments(), [&](BlockArgument bbArg) {
1076 return isaTensor(bbArg.getType());
1077 });
1078 });
1079 });
1080 if (hasTensorBlockArgument)
1081 return true;
1082
1083 if (any_of(op->getResultTypes(), isaTensor))
1084 return true;
1085 return any_of(op->getOperandTypes(), isaTensor);
1086}
1087
1088FailureOr<BaseMemRefType>
1089bufferization::detail::asMemRefType(FailureOr<BufferLikeType> bufferType) {
1090 if (failed(bufferType))
1091 return failure();
1092 return cast<BaseMemRefType>(*bufferType);
1093}
1094
1095bool bufferization::detail::typesMatchAfterBufferization(Operation &op,
1096 Value tensor,
1097 Value buffer) {
1098 return mlir::succeeded(
1099 cast<TensorLikeType>(tensor.getType())
1100 .verifyCompatibleBufferType(cast<BufferLikeType>(buffer.getType()),
1101 [&]() { return op.emitError(); }));
1102}
return success()
static void setInsertionPointAfter(OpBuilder &b, Value value)
static bool isRepetitiveRegion(Region *region, const BufferizationOptions &options)
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...
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static bool isaTensor(Type t)
static llvm::ManagedStatic< PassManagerOptions > options
static RankedTensorType getBufferType(const SparseTensorType &stt, bool needTmpCOO)
#define MLIR_DEFINE_EXPLICIT_TYPE_ID(CLASS_NAME)
Definition TypeID.h:323
static Operation * getOwnerOfValue(Value value)
Base class for generic analysis states.
AnalysisState(LatticeAnchor anchor)
Create the analysis state on the given lattice anchor.
Attributes are known-constant values of operations.
Definition Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
static bool isValidElementType(Type type)
Return true if the specified element type is ok in a memref.
This class represents an argument of a Block.
Definition Value.h:308
Block represents an ordered list of Operations.
Definition Block.h:34
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
IRValueT get() const
Return the current value being used by this operand.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
This class represents an operand of an operation.
Definition Value.h:256
This is a value defined by a result of an operation.
Definition Value.h:456
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
Dialect * getDialect()
Return the dialect this operation is associated with, or nullptr if the associated dialect is not loa...
Definition Operation.h:237
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
MutableArrayRef< OpOperand > getOpOperands()
Definition Operation.h:410
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
operand_type_range getOperandTypes()
Definition Operation.h:424
MutableArrayRef< Region > getRegions()
Returns the regions held by this operation.
Definition Operation.h:731
result_type_range getResultTypes()
Definition Operation.h:455
bool isAncestor(Operation *other)
Return true if this operation is an ancestor of the other operation.
Definition Operation.h:288
result_range getOpResults()
Definition Operation.h:447
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
Definition Region.cpp:45
unsigned getRegionNumber()
Return the number of this region in the parent operation.
Definition Region.cpp:62
Operation * getParentOp()
Return the parent operation this region is attached to.
Definition Region.h:198
BlockListType & getBlocks()
Definition Region.h:45
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
This class represents a collection of SymbolTables.
Tensor types represent multi-dimensional arrays, and have two variants: RankedTensorType and Unranked...
ArrayRef< int64_t > getShape() const
Returns the shape of this tensor type.
Type getElementType() const
Returns the element type of this tensor type.
This class provides an efficient unique identifier for a specific C++ type.
Definition TypeID.h:107
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
void populateDynamicDimSizes(OpBuilder &b, Location loc, Value shapedValue, SmallVector< Value > &dynamicDims)
Populate dynamicDims with tensor::DimOp / memref::DimOp results for all dynamic dimensions of the giv...
constexpr void enumerate(std::tuple< Tys... > &tuple, CallbackT &&callback)
Definition Matchers.h:344
Type getTensorTypeFromMemRefType(Type type)
Return an unranked/ranked tensor type for the given unranked/ranked memref type.
Definition MemRefOps.cpp:63
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
LogicalResult reifyResultShapes(OpBuilder &b, Operation *op, ReifiedRankedShapedTypeDims &reifiedReturnShapes)
Reify the shape of the result of an operation (typically in terms of the shape of its operands).
bool insideMutuallyExclusiveRegions(Operation *a, Operation *b)
Return true if a and b are in mutually exclusive regions as per RegionBranchOpInterface.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Region * getEnclosingRepetitiveRegion(Operation *op)
Return the first enclosing region of the given op that may be executed repetitively as per RegionBran...
SmallVector< SmallVector< OpFoldResult > > ReifiedRankedShapedTypeDims
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
Definition Utils.cpp:114
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...