MLIR  20.0.0git
BufferizableOpInterfaceImpl.cpp
Go to the documentation of this file.
1 //===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
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 
10 
23 #include "mlir/IR/Dialect.h"
24 #include "mlir/IR/Operation.h"
25 
26 using namespace mlir;
27 using namespace mlir::bufferization;
28 using namespace mlir::tensor;
29 
30 namespace mlir {
31 namespace tensor {
32 namespace {
33 
34 struct CastOpInterface
35  : public BufferizableOpInterface::ExternalModel<CastOpInterface,
36  tensor::CastOp> {
37  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
38  const AnalysisState &state) const {
39  return false;
40  }
41 
42  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
43  const AnalysisState &state) const {
44  return false;
45  }
46 
47  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
48  const AnalysisState &state) const {
49  return {{op->getResult(0), BufferRelation::Equivalent}};
50  }
51 
52  FailureOr<BaseMemRefType>
54  SmallVector<Value> &invocationStack) const {
55  auto castOp = cast<tensor::CastOp>(op);
56  auto maybeSrcBufferType = bufferization::getBufferType(
57  castOp.getSource(), options, invocationStack);
58  if (failed(maybeSrcBufferType))
59  return failure();
60  Attribute memorySpace = maybeSrcBufferType->getMemorySpace();
61 
62  // Note: `getMemRefTypeWithFullyDynamicLayout` returns an unranked memref
63  // type in case the input is an unranked tensor type.
64 
65  // Case 1: Casting an unranked tensor
66  if (isa<UnrankedTensorType>(castOp.getSource().getType())) {
67  // When casting to a ranked tensor, we cannot infer any static offset or
68  // strides from the source. Assume fully dynamic.
69  return getMemRefTypeWithFullyDynamicLayout(castOp.getType(), memorySpace);
70  }
71 
72  // Case 2: Casting to an unranked tensor type
73  if (isa<UnrankedTensorType>(castOp.getType())) {
74  return getMemRefTypeWithFullyDynamicLayout(castOp.getType(), memorySpace);
75  }
76 
77  // Case 3: Ranked tensor -> ranked tensor. The offsets and strides do not
78  // change.
79  auto rankedResultType = cast<RankedTensorType>(castOp.getType());
80  return MemRefType::get(
81  rankedResultType.getShape(), rankedResultType.getElementType(),
82  llvm::cast<MemRefType>(*maybeSrcBufferType).getLayout(), memorySpace);
83  }
84 
85  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
86  const BufferizationOptions &options) const {
87  auto castOp = cast<tensor::CastOp>(op);
88 
89  // The result buffer still has the old (pre-cast) type.
90  FailureOr<Value> resultBuffer =
91  getBuffer(rewriter, castOp.getSource(), options);
92  if (failed(resultBuffer))
93  return failure();
94 
95  // Compute the new type.
96  auto resultMemRefType =
97  bufferization::getBufferType(castOp.getResult(), options);
98  if (failed(resultMemRefType))
99  return failure();
100  if (resultBuffer->getType() == *resultMemRefType) {
101  // This cast is a no-op.
102  replaceOpWithBufferizedValues(rewriter, op, *resultBuffer);
103  return success();
104  }
105 
106  // Replace the op with a memref.cast.
107  assert(memref::CastOp::areCastCompatible(resultBuffer->getType(),
108  *resultMemRefType) &&
109  "CallOp::bufferize: cast incompatible");
110  replaceOpWithNewBufferizedOp<memref::CastOp>(
111  rewriter, op, *resultMemRefType, *resultBuffer);
112 
113  return success();
114  }
115 };
116 
117 /// Bufferization of tensor.collapse_shape. Replace with memref.collapse_shape.
118 struct CollapseShapeOpInterface
119  : public BufferizableOpInterface::ExternalModel<CollapseShapeOpInterface,
120  tensor::CollapseShapeOp> {
121  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
122  const AnalysisState &state) const {
123  // tensor.collapse_shape may reallocate, at which point the source buffer is
124  // copied. I.e., there will be a memory read side effect on the bufferized
125  // source. This function conservatively returns "true" because whether a
126  // copy will be created or not is not known at this point.
127  return true;
128  }
129 
130  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
131  const AnalysisState &state) const {
132  return false;
133  }
134 
135  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
136  const AnalysisState &state) const {
137  // TODO: CollapseShapeOp may allocate at runtime.
138  return {{op->getOpResult(0), BufferRelation::Equivalent}};
139  }
140 
141  FailureOr<BaseMemRefType>
143  SmallVector<Value> &invocationStack) const {
144  auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);
145  auto maybeSrcBufferType = bufferization::getBufferType(
146  collapseShapeOp.getSrc(), options, invocationStack);
147  if (failed(maybeSrcBufferType))
148  return failure();
149  auto srcBufferType = llvm::cast<MemRefType>(*maybeSrcBufferType);
150  bool canBeCollapsed = memref::CollapseShapeOp::isGuaranteedCollapsible(
151  srcBufferType, collapseShapeOp.getReassociationIndices());
152 
153  if (!canBeCollapsed) {
154  // If dims cannot be collapsed, this op bufferizes to a new allocation.
155  RankedTensorType tensorResultType = collapseShapeOp.getResultType();
157  tensorResultType, srcBufferType.getMemorySpace());
158  }
159 
160  return memref::CollapseShapeOp::computeCollapsedType(
161  srcBufferType, collapseShapeOp.getReassociationIndices());
162  }
163 
164  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
165  const BufferizationOptions &options) const {
166  auto collapseShapeOp = cast<tensor::CollapseShapeOp>(op);
167  RankedTensorType tensorResultType = collapseShapeOp.getResultType();
168  FailureOr<Value> maybeBuffer =
169  getBuffer(rewriter, collapseShapeOp.getSrc(), options);
170  if (failed(maybeBuffer))
171  return failure();
172  Value buffer = *maybeBuffer;
173  auto bufferType = cast<MemRefType>(buffer.getType());
174 
175  if (tensorResultType.getRank() == 0) {
176  // 0-d collapses must go through a different op builder.
177  MemRefType resultType;
178 
179  if (bufferType.getLayout().isIdentity()) {
180  // Standard layout: result type has no offset.
181  MemRefLayoutAttrInterface layout;
182  resultType = MemRefType::get({}, tensorResultType.getElementType(),
183  layout, bufferType.getMemorySpace());
184  } else {
185  // Source memref has a layout map: result type has the same offset as
186  // the source type.
187  SmallVector<int64_t> strides;
188  int64_t offset;
189  if (failed(getStridesAndOffset(bufferType, strides, offset)))
190  return failure();
191  resultType = MemRefType::get(
192  {}, tensorResultType.getElementType(),
193  StridedLayoutAttr::get(op->getContext(), offset, {}),
194  bufferType.getMemorySpace());
195  }
196 
197  replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
198  rewriter, op, resultType, buffer, collapseShapeOp.getReassociation());
199  return success();
200  }
201 
202  // If the dims are not collapsible (due to an incompatible source layout
203  // map), force an out-of-place bufferization, i.e., a buffer copy. This
204  // newly allocated buffer will have no layout map and thus be collapsible.
205  bool canBeCollapsed = memref::CollapseShapeOp::isGuaranteedCollapsible(
206  bufferType, collapseShapeOp.getReassociationIndices());
207  if (!canBeCollapsed) {
208  // TODO: Create alloc_tensor ops during TensorCopyInsertion.
209  AnalysisState analysisState(options);
210  FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
211  rewriter, op->getLoc(), collapseShapeOp.getSrc(), options);
212  if (failed(tensorAlloc))
213  return failure();
214  auto memrefType =
215  MemRefType::get(collapseShapeOp.getSrcType().getShape(),
216  collapseShapeOp.getSrcType().getElementType(),
217  AffineMap(), bufferType.getMemorySpace());
218  buffer = rewriter.create<bufferization::ToMemrefOp>(
219  op->getLoc(), memrefType, *tensorAlloc);
220  }
221 
222  // Result type is inferred by the builder.
223  replaceOpWithNewBufferizedOp<memref::CollapseShapeOp>(
224  rewriter, op, buffer, collapseShapeOp.getReassociationIndices());
225  return success();
226  }
227 };
228 
229 /// Bufferization of tensor.dim. Replace with memref.dim.
230 struct DimOpInterface
231  : public BufferizableOpInterface::ExternalModel<DimOpInterface,
232  tensor::DimOp> {
233  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
234  const AnalysisState &state) const {
235  // The op reads the tensor's metadata but not its contents.
236  return false;
237  }
238 
239  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
240  const AnalysisState &state) const {
241  return false;
242  }
243 
244  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
245  const AnalysisState &state) const {
246  return {};
247  }
248 
249  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
250  const BufferizationOptions &options) const {
251  auto dimOp = cast<tensor::DimOp>(op);
252  FailureOr<Value> v = getBuffer(rewriter, dimOp.getSource(), options);
253  if (failed(v))
254  return failure();
255  replaceOpWithNewBufferizedOp<memref::DimOp>(rewriter, op, *v,
256  dimOp.getIndex());
257  return success();
258  }
259 };
260 
261 /// Bufferization of "tensor.empty". Replace with "bufferization.alloc_tensor".
262 struct EmptyOpInterface
263  : public BufferizableOpInterface::ExternalModel<EmptyOpInterface,
264  tensor::EmptyOp> {
265  bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
266 
267  bool resultBufferizesToMemoryWrite(Operation *op, OpResult opResult,
268  const AnalysisState &state) const {
269  // The returned tensor does not have specified contents.
270  return false;
271  }
272 
273  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
274  const BufferizationOptions &options) const {
275  auto emptyOp = cast<tensor::EmptyOp>(op);
276 
277  // Optimization: Fold away the op if it has no uses.
278  if (op->getUses().empty()) {
279  rewriter.eraseOp(op);
280  return success();
281  }
282 
283  // Allocate a tensor. This emits a "bufferization.alloc_tensor" op.
284  FailureOr<Value> allocTensor = allocateTensorForShapedValue(
285  rewriter, op->getLoc(), emptyOp.getResult(), options, /*copy=*/false);
286  if (failed(allocTensor))
287  return failure();
288  rewriter.replaceOp(op, *allocTensor);
289  return success();
290  }
291 };
292 
293 /// Bufferization of tensor.expand_shape. Replace with memref.expand_shape.
294 struct ExpandShapeOpInterface
295  : public BufferizableOpInterface::ExternalModel<ExpandShapeOpInterface,
296  tensor::ExpandShapeOp> {
297  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
298  const AnalysisState &state) const {
299  // In contrast to tensor.collapse_shape, this op can always be bufferized
300  // without a copy.
301  return false;
302  }
303 
304  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
305  const AnalysisState &state) const {
306  return false;
307  }
308 
309  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
310  const AnalysisState &state) const {
311  return {{op->getOpResult(0), BufferRelation::Equivalent}};
312  }
313 
314  FailureOr<BaseMemRefType>
316  SmallVector<Value> &invocationStack) const {
317  auto expandShapeOp = cast<tensor::ExpandShapeOp>(op);
318  auto maybeSrcBufferType = bufferization::getBufferType(
319  expandShapeOp.getSrc(), options, invocationStack);
320  if (failed(maybeSrcBufferType))
321  return failure();
322  auto srcBufferType = llvm::cast<MemRefType>(*maybeSrcBufferType);
323  auto maybeResultType = memref::ExpandShapeOp::computeExpandedType(
324  srcBufferType, expandShapeOp.getResultType().getShape(),
325  expandShapeOp.getReassociationIndices());
326  if (failed(maybeResultType))
327  return failure();
328  return *maybeResultType;
329  }
330 
331  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
332  const BufferizationOptions &options) const {
333  auto expandShapeOp = cast<tensor::ExpandShapeOp>(op);
334  auto tensorResultType = expandShapeOp.getResultType();
335  FailureOr<Value> buffer =
336  getBuffer(rewriter, expandShapeOp.getSrc(), options);
337  if (failed(buffer))
338  return failure();
339 
340  // Memref result type is inferred by the builder based on reassociation
341  // indices and result shape.
342  // TODO: Instead of inferring the output shape argument of
343  // memref.expand_shape op, use output_shape argument of tensor.expand_shape
344  // op.
345  replaceOpWithNewBufferizedOp<memref::ExpandShapeOp>(
346  rewriter, op, tensorResultType.getShape(), *buffer,
347  expandShapeOp.getReassociationIndices());
348  return success();
349  }
350 };
351 
352 /// Bufferization of tensor.extract_slice. Replace with memref.subview.
353 struct ExtractSliceOpInterface
354  : public BufferizableOpInterface::ExternalModel<ExtractSliceOpInterface,
355  tensor::ExtractSliceOp> {
356  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
357  const AnalysisState &state) const {
358  return false;
359  }
360 
361  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
362  const AnalysisState &state) const {
363  return false;
364  }
365 
366  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
367  const AnalysisState &state) const {
368  return {{op->getOpResult(0), BufferRelation::Unknown}};
369  }
370 
371  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
372  const BufferizationOptions &options) const {
373  auto extractSliceOp = cast<tensor::ExtractSliceOp>(op);
374  SmallVector<OpFoldResult> mixedOffsets = extractSliceOp.getMixedOffsets();
375  SmallVector<OpFoldResult> mixedSizes = extractSliceOp.getMixedSizes();
376  SmallVector<OpFoldResult> mixedStrides = extractSliceOp.getMixedStrides();
377  Location loc = extractSliceOp.getLoc();
378 
379  // Get source buffer.
380  FailureOr<Value> srcMemref =
381  getBuffer(rewriter, extractSliceOp.getSource(), options);
382  if (failed(srcMemref))
383  return failure();
384 
385  // Take a subview of the source buffer.
386  auto resultMemrefType =
387  bufferization::getBufferType(extractSliceOp.getResult(), options);
388  if (failed(resultMemrefType))
389  return failure();
390  Value subView = rewriter.create<memref::SubViewOp>(
391  loc, llvm::cast<MemRefType>(*resultMemrefType), *srcMemref,
392  mixedOffsets, mixedSizes, mixedStrides);
393 
394  replaceOpWithBufferizedValues(rewriter, op, subView);
395  return success();
396  }
397 
398  FailureOr<BaseMemRefType>
400  SmallVector<Value> &invocationStack) const {
401  auto extractSliceOp = cast<tensor::ExtractSliceOp>(op);
402  assert(value == extractSliceOp.getResult() && "invalid value");
403  auto srcMemrefType = bufferization::getBufferType(
404  extractSliceOp.getSource(), options, invocationStack);
405  if (failed(srcMemrefType))
406  return failure();
407  SmallVector<OpFoldResult> mixedOffsets = extractSliceOp.getMixedOffsets();
408  SmallVector<OpFoldResult> mixedSizes = extractSliceOp.getMixedSizes();
409  SmallVector<OpFoldResult> mixedStrides = extractSliceOp.getMixedStrides();
410  return cast<BaseMemRefType>(memref::SubViewOp::inferRankReducedResultType(
411  extractSliceOp.getType().getShape(),
412  llvm::cast<MemRefType>(*srcMemrefType), mixedOffsets, mixedSizes,
413  mixedStrides));
414  }
415 };
416 
417 /// Bufferization of tensor.extract. Replace with memref.load.
418 struct ExtractOpInterface
419  : public BufferizableOpInterface::ExternalModel<ExtractOpInterface,
420  tensor::ExtractOp> {
421  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
422  const AnalysisState &state) const {
423  return true;
424  }
425 
426  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
427  const AnalysisState &state) const {
428  return false;
429  }
430 
431  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
432  const AnalysisState &state) const {
433  return {};
434  }
435 
436  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
437  const BufferizationOptions &options) const {
438  auto extractOp = cast<tensor::ExtractOp>(op);
439  FailureOr<Value> srcMemref =
440  getBuffer(rewriter, extractOp.getTensor(), options);
441  if (failed(srcMemref))
442  return failure();
443  replaceOpWithNewBufferizedOp<memref::LoadOp>(rewriter, op, *srcMemref,
444  extractOp.getIndices());
445  return success();
446  }
447 };
448 
449 // Implements backtracking to traverse indices of the output buffer while
450 // iterating over op.elements().
451 static void createStores(RewriterBase &rewriter, Location loc, int dim,
452  Value buffer, ArrayRef<int64_t> shape,
453  ArrayRef<Value> constants,
454  OperandRange::iterator &elementIt,
455  SmallVectorImpl<Value> &indices) {
456  if (dim == static_cast<int>(shape.size()) - 1) {
457  for (int i = 0; i < shape.back(); ++i) {
458  indices.back() = constants[i];
459  rewriter.create<memref::StoreOp>(loc, *elementIt, buffer, indices);
460  ++elementIt;
461  }
462  return;
463  }
464  for (int i = 0; i < shape[dim]; ++i) {
465  indices[dim] = constants[i];
466  createStores(rewriter, loc, dim + 1, buffer, shape, constants, elementIt,
467  indices);
468  }
469 }
470 
471 /// Bufferization of tensor.from_elements.
472 struct FromElementsOpInterface
473  : public BufferizableOpInterface::ExternalModel<FromElementsOpInterface,
474  tensor::FromElementsOp> {
475 
476  bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
477 
478  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
479  const BufferizationOptions &options) const {
480  auto fromElementsOp = cast<tensor::FromElementsOp>(op);
481  auto tensorType = cast<RankedTensorType>(fromElementsOp.getType());
482 
483  // TODO: Implement memory space for this op.
484  if (options.defaultMemorySpaceFn(tensorType) != Attribute())
485  return op->emitError("memory space not implemented yet");
486 
487  // Allocate a buffer for the result.
488  Location loc = op->getLoc();
489  auto shape = tensorType.getShape();
490  // TODO: Create alloc_tensor ops during TensorCopyInsertion.
491  FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
492  rewriter, loc, fromElementsOp.getResult(), options,
493  /*copy=*/false);
494  if (failed(tensorAlloc))
495  return failure();
496  auto memrefType =
497  MemRefType::get(tensorType.getShape(), tensorType.getElementType());
498  Value buffer = rewriter.create<bufferization::ToMemrefOp>(
499  op->getLoc(), memrefType, *tensorAlloc);
500 
501  // Case: tensor<0xelem_type>.
502  if (fromElementsOp.getElements().empty()) {
503  replaceOpWithBufferizedValues(rewriter, op, buffer);
504  return success();
505  }
506 
507  // Case: tensor<elem_type>.
508  if (shape.empty()) {
509  rewriter.create<memref::StoreOp>(
510  loc, fromElementsOp.getElements().front(), buffer);
511  replaceOpWithBufferizedValues(rewriter, op, buffer);
512  return success();
513  }
514 
515  // Create constants for the range of possible indices [0, max{shape_i}).
516  auto maxDim = *llvm::max_element(shape);
517  SmallVector<Value, 2> constants;
518  constants.reserve(maxDim);
519  for (int i = 0; i < maxDim; ++i)
520  constants.push_back(rewriter.create<arith::ConstantIndexOp>(loc, i));
521 
522  // Traverse all `elements` and create `memref.store` ops.
523  auto elementIt = fromElementsOp.getElements().begin();
524  SmallVector<Value, 2> indices(tensorType.getRank(), constants[0]);
525  createStores(rewriter, loc, /*dim=*/0, buffer, shape, constants, elementIt,
526  indices);
527 
528  replaceOpWithBufferizedValues(rewriter, op, buffer);
529 
530  return success();
531  }
532 };
533 
534 /// Lower the body of a tensor.generate like op (one index-typed bbArg per dim).
535 /// Such ops are lowered to linalg.map with the given tensor as a destination.
536 ///
537 /// Example:
538 /// ```
539 /// %r = tensor.generate %x, %y {
540 /// ^bb0(%arg0: index, %arg1: index):
541 /// %0 = "some_op"(%arg0, %arg1) : (index, index) -> (index)
542 /// tensor.yield %0 : index
543 /// } : tensor<?x?xindex>
544 /// ```
545 ///
546 /// Is lowered to:
547 /// ```
548 /// linalg.map ins() outs(%dest) {
549 /// %d0 = linalg.index 0 : index
550 /// %d1 = linalg.index 1 : index
551 /// %0 = "some_op"(%d0, %d1) : (index, index) -> (index)
552 /// linalg.yield %0 : index
553 /// }
554 /// ```
555 static Value lowerGenerateLikeOpBody(RewriterBase &rewriter, Location loc,
556  Value tensorDestination,
557  ValueRange dynamicSizes,
558  Region &generateBody) {
559  assert(generateBody.hasOneBlock() && "expected body with single block");
560  auto tensorType = cast<RankedTensorType>(tensorDestination.getType());
561  assert(generateBody.getNumArguments() == tensorType.getRank() &&
562  "rank mismatch");
563 
564  // Create linalg::MapOp.
565  OpBuilder::InsertionGuard g(rewriter);
566  auto linalgOp =
567  rewriter.create<linalg::MapOp>(loc, tensorType, /*inputs=*/ValueRange(),
568  /*init=*/tensorDestination);
569  Block &linalgBody = linalgOp.getMapper().emplaceBlock();
570 
571  // Create linalg::IndexOps.
572  rewriter.setInsertionPointToStart(&linalgBody);
573  SmallVector<Value> indices;
574  for (int64_t dim = 0; dim < tensorType.getRank(); ++dim)
575  indices.push_back(rewriter.create<linalg::IndexOp>(loc, dim));
576 
577  // Move over body.
578  rewriter.mergeBlocks(&generateBody.front(), &linalgBody, indices);
579  auto yieldOp = cast<tensor::YieldOp>(linalgBody.getTerminator());
580  rewriter.replaceOpWithNewOp<linalg::YieldOp>(yieldOp, yieldOp.getValue());
581 
582  return linalgOp.getResult()[0];
583 }
584 
585 /// Bufferization of tensor.generate.
586 struct GenerateOpInterface
587  : public BufferizableOpInterface::ExternalModel<GenerateOpInterface,
588  tensor::GenerateOp> {
589 
590  bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
591 
592  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
593  const BufferizationOptions &options) const {
594  auto generateOp = cast<tensor::GenerateOp>(op);
595 
596  auto type = generateOp.getResult().getType();
597 
598  // TODO: Implement memory space for this op.
599  if (options.defaultMemorySpaceFn(type) != Attribute())
600  return op->emitError("memory space not implemented yet");
601 
602  // Allocate memory.
603  Location loc = op->getLoc();
604  FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
605  rewriter, loc, generateOp.getResult(), options,
606  /*copy=*/false);
607  if (failed(tensorAlloc))
608  return failure();
609 
610  Value result = lowerGenerateLikeOpBody(rewriter, loc, *tensorAlloc,
611  generateOp.getDynamicExtents(),
612  generateOp.getBody());
613  rewriter.replaceOp(generateOp, result);
614 
615  return success();
616  }
617 };
618 
619 /// Bufferization of tensor.insert. Replace with memref.store.
620 ///
621 /// Note: DstBufferizableOpInterfaceExternalModel provides many default method
622 /// implementations for DestinationStyle ops.
623 struct InsertOpInterface
624  : public DstBufferizableOpInterfaceExternalModel<InsertOpInterface,
625  tensor::InsertOp> {
626  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
627  const BufferizationOptions &options) const {
628  auto insertOp = cast<tensor::InsertOp>(op);
629  FailureOr<Value> destMemref =
630  getBuffer(rewriter, insertOp.getDest(), options);
631  if (failed(destMemref))
632  return failure();
633  rewriter.create<memref::StoreOp>(insertOp.getLoc(), insertOp.getScalar(),
634  *destMemref, insertOp.getIndices());
635  replaceOpWithBufferizedValues(rewriter, op, *destMemref);
636  return success();
637  }
638 };
639 
640 template <typename InsertOpTy>
641 static bool insertSliceOpRequiresRead(InsertOpTy insertSliceOp,
642  OpOperand &opOperand) {
643  // The source is always read.
644  if (opOperand == insertSliceOp.getSourceMutable())
645  return true;
646 
647  // For the destination, it depends...
648  assert(opOperand == insertSliceOp.getDestMutable() && "expected dest");
649 
650  // Dest is not read if it is entirely overwritten. E.g.:
651  // tensor.insert_slice %a into %t[0][10][1] : ... into tensor<10xf32>
652  bool allOffsetsZero =
653  llvm::all_of(insertSliceOp.getMixedOffsets(), isZeroIndex);
654  RankedTensorType destType = insertSliceOp.getDestType();
655  bool sizesMatchDestSizes =
656  areConstantIntValues(insertSliceOp.getMixedSizes(), destType.getShape());
657  bool allStridesOne =
658  areAllConstantIntValue(insertSliceOp.getMixedStrides(), 1);
659  return !(allOffsetsZero && sizesMatchDestSizes && allStridesOne);
660 }
661 
662 /// Bufferization of tensor.insert_slice. Replace with a memory copy. Under
663 /// certain circumstances, this op can also be a no-op.
664 ///
665 /// Note: DstBufferizableOpInterfaceExternalModel provides many default method
666 /// implementations for DestinationStyle ops.
667 struct InsertSliceOpInterface
668  : public DstBufferizableOpInterfaceExternalModel<InsertSliceOpInterface,
669  tensor::InsertSliceOp> {
670  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
671  const AnalysisState &state) const {
672  return insertSliceOpRequiresRead(cast<tensor::InsertSliceOp>(op),
673  opOperand);
674  }
675 
676  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
677  const BufferizationOptions &options) const {
678  // insert_slice ops arise from tiling and bufferizing them out-of-place is
679  // generally a deal breaker. When used with loops, this ends up cloning the
680  // whole tensor on every single iteration and is a symptom of a
681  // catastrophically bad scheduling decision.
682  // TODO: be very loud about it or even consider failing the pass.
683  auto insertSliceOp = cast<tensor::InsertSliceOp>(op);
684  SmallVector<OpFoldResult> mixedOffsets = insertSliceOp.getMixedOffsets();
685  SmallVector<OpFoldResult> mixedSizes = insertSliceOp.getMixedSizes();
686  SmallVector<OpFoldResult> mixedStrides = insertSliceOp.getMixedStrides();
687  Location loc = insertSliceOp.getLoc();
688 
689  // Get destination buffer.
690  FailureOr<Value> dstMemref =
691  getBuffer(rewriter, insertSliceOp.getDest(), options);
692  if (failed(dstMemref))
693  return failure();
694 
695  // Take a subview of the destination buffer.
696  auto dstMemrefType = cast<MemRefType>(dstMemref->getType());
697  auto subviewMemRefType =
698  cast<MemRefType>(memref::SubViewOp::inferRankReducedResultType(
699  insertSliceOp.getSourceType().getShape(), dstMemrefType,
700  mixedOffsets, mixedSizes, mixedStrides));
701  Value subView = rewriter.create<memref::SubViewOp>(
702  loc, subviewMemRefType, *dstMemref, mixedOffsets, mixedSizes,
703  mixedStrides);
704 
705  // Copy tensor. If this tensor.insert_slice has a matching
706  // tensor.extract_slice, the copy operation will eventually fold away.
707  FailureOr<Value> srcMemref =
708  getBuffer(rewriter, insertSliceOp.getSource(), options);
709  if (failed(srcMemref))
710  return failure();
711  if (failed(options.createMemCpy(rewriter, loc, *srcMemref, subView)))
712  return failure();
713 
714  replaceOpWithBufferizedValues(rewriter, op, *dstMemref);
715  return success();
716  }
717 };
718 
719 /// Bufferization of tensor.pad. Replace with bufferization.alloc_tensor +
720 /// linalg.map + insert_slice.
721 /// For best performance, vectorize before bufferization (better performance in
722 /// case of padding with a constant).
723 struct PadOpInterface
724  : public BufferizableOpInterface::ExternalModel<PadOpInterface,
725  tensor::PadOp> {
726  bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
727 
728  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
729  const AnalysisState &state) const {
730  return true;
731  }
732 
733  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
734  const AnalysisState &state) const {
735  return false;
736  }
737 
738  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
739  const AnalysisState &state) const {
740  return {};
741  }
742 
743  FailureOr<BaseMemRefType>
745  SmallVector<Value> &invocationStack) const {
746  // Infer memory space from the source tensor.
747  auto padOp = cast<tensor::PadOp>(op);
748  auto maybeSrcBufferType = bufferization::getBufferType(
749  padOp.getSource(), options, invocationStack);
750  if (failed(maybeSrcBufferType))
751  return failure();
752  MemRefLayoutAttrInterface layout;
753  return MemRefType::get(padOp.getResultType().getShape(),
754  padOp.getResultType().getElementType(), layout,
755  maybeSrcBufferType->getMemorySpace());
756  }
757 
758  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
759  const BufferizationOptions &options) const {
760  auto padOp = cast<tensor::PadOp>(op);
761  Location loc = padOp.getLoc();
762  RankedTensorType resultType = padOp.getResultType();
763  RankedTensorType srcType = padOp.getSourceType();
764 
765  auto toValue = [&](OpFoldResult ofr) {
766  if (ofr.is<Value>())
767  return ofr.get<Value>();
768  return rewriter
769  .create<arith::ConstantIndexOp>(loc, *getConstantIntValue(ofr))
770  .getResult();
771  };
772 
773  // Compute dynamic result dimensions.
774  SmallVector<OpFoldResult> mixedLowPad = padOp.getMixedLowPad();
775  SmallVector<OpFoldResult> mixedHighPad = padOp.getMixedHighPad();
776  SmallVector<Value> dynamicSizes;
777  for (int64_t i = 0; i < resultType.getRank(); ++i) {
778  if (!resultType.isDynamicDim(i))
779  continue;
780  Value srcDim = rewriter.create<tensor::DimOp>(loc, padOp.getSource(), i);
781  Value lowPad = toValue(mixedLowPad[i]);
782  Value highPad = toValue(mixedHighPad[i]);
783  AffineExpr s0, s1, s2;
784  bindSymbols(op->getContext(), s0, s1, s2);
785  AffineExpr sumExpr = s0 + s1 + s2;
786  Value sum = rewriter.create<affine::AffineApplyOp>(
787  loc, sumExpr, ValueRange{srcDim, lowPad, highPad});
788  dynamicSizes.push_back(sum);
789  }
790 
791  // Allocate a buffer for the padded result.
792  FailureOr<Value> tensorAlloc =
793  allocateTensorForShapedValue(rewriter, loc, padOp.getResult(), options,
794  /*copy=*/false);
795  if (failed(tensorAlloc))
796  return failure();
797 
798  // tensor::PadOp is like tensor::GenerateOp: The only difference is that
799  // only a part of the generated tensor is needed. For simplicity, we reuse
800  // the same functionality here.
801  Value filledBuffer = lowerGenerateLikeOpBody(
802  rewriter, loc, *tensorAlloc, dynamicSizes, padOp.getBodyRegion());
803 
804  // Create tensor::InsertSliceOp.
805  SmallVector<OpFoldResult> sliceSizes =
806  getMixedSizes(rewriter, loc, padOp.getSource());
807  SmallVector<OpFoldResult> sliceStrides(srcType.getRank(),
808  rewriter.getIndexAttr(1));
809  rewriter.replaceOpWithNewOp<tensor::InsertSliceOp>(
810  padOp, padOp.getSource(), filledBuffer,
811  /*offsets=*/padOp.getMixedLowPad(), sliceSizes, sliceStrides);
812 
813  return success();
814  }
815 };
816 
817 /// Bufferization of tensor.rank. Replace with memref.rank.
818 struct RankOpInterface
819  : public BufferizableOpInterface::ExternalModel<RankOpInterface,
820  tensor::RankOp> {
821  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
822  const AnalysisState &state) const {
823  // The op reads the tensor's metadata but not its contents.
824  return false;
825  }
826 
827  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
828  const AnalysisState &state) const {
829  return false;
830  }
831 
832  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
833  const AnalysisState &state) const {
834  return {};
835  }
836 
837  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
838  const BufferizationOptions &options) const {
839  auto rankOp = cast<tensor::RankOp>(op);
840  FailureOr<Value> v = getBuffer(rewriter, rankOp.getTensor(), options);
841  if (failed(v))
842  return failure();
843  replaceOpWithNewBufferizedOp<memref::RankOp>(rewriter, op, rankOp.getType(),
844  *v);
845  return success();
846  }
847 };
848 
849 /// Bufferization of tensor.reshape. Replace with memref.reshape.
850 struct ReshapeOpInterface
851  : public BufferizableOpInterface::ExternalModel<ReshapeOpInterface,
852  tensor::ReshapeOp> {
853  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
854  const AnalysisState &state) const {
855  // Depending on the layout map, the source buffer may have to be copied.
856  auto reshapeOp = cast<tensor::ReshapeOp>(op);
857  return opOperand == reshapeOp.getShapeMutable();
858  }
859 
860  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
861  const AnalysisState &state) const {
862  return false;
863  }
864 
865  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
866  const AnalysisState &state) const {
867  return {{op->getOpResult(0), BufferRelation::Equivalent}};
868  }
869 
870  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
871  const BufferizationOptions &options) const {
872  auto reshapeOp = cast<tensor::ReshapeOp>(op);
873  FailureOr<Value> srcBuffer =
874  getBuffer(rewriter, reshapeOp.getSource(), options);
875  FailureOr<Value> shapeBuffer =
876  getBuffer(rewriter, reshapeOp.getShape(), options);
877  if (failed(srcBuffer) || failed(shapeBuffer))
878  return failure();
879  auto maybeResultMemRefType =
880  bufferization::getBufferType(reshapeOp.getResult(), options);
881  if (failed(maybeResultMemRefType))
882  return failure();
883 
884  // memref.reshape requires the source buffer to have an identity layout.
885  // If the source memref does not have an identity layout, copy the source
886  // into a new buffer with an identity layout.
887  auto srcType = llvm::dyn_cast<MemRefType>(srcBuffer->getType());
888  if (srcType && !srcType.getLayout().isIdentity()) {
889  FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
890  rewriter, op->getLoc(), reshapeOp.getSource(), options);
891  if (failed(tensorAlloc))
892  return failure();
893  auto memrefType = MemRefType::get(
894  srcType.getShape(), srcType.getElementType(), AffineMap(),
895  cast<BaseMemRefType>(srcBuffer->getType()).getMemorySpace());
896  srcBuffer = rewriter
897  .create<bufferization::ToMemrefOp>(
898  op->getLoc(), memrefType, *tensorAlloc)
899  .getResult();
900  }
901 
902  replaceOpWithNewBufferizedOp<memref::ReshapeOp>(
903  rewriter, op, maybeResultMemRefType.value(), *srcBuffer, *shapeBuffer);
904  return success();
905  }
906 
907  FailureOr<BaseMemRefType>
909  SmallVector<Value> &invocationStack) const {
910  auto reshapeOp = cast<tensor::ReshapeOp>(op);
911  assert(value == reshapeOp.getResult() && "unexpected value provided");
912  auto maybeSourceBufferType = bufferization::getBufferType(
913  reshapeOp.getSource(), options, invocationStack);
914  if (failed(maybeSourceBufferType))
915  return failure();
917  reshapeOp.getResult().getType(),
918  cast<BaseMemRefType>(maybeSourceBufferType.value()).getMemorySpace());
919  }
920 };
921 
922 /// Analysis of ParallelInsertSliceOp.
923 struct ParallelInsertSliceOpInterface
924  : public BufferizableOpInterface::ExternalModel<
925  ParallelInsertSliceOpInterface, ParallelInsertSliceOp> {
926  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
927  const AnalysisState &state) const {
928  return {};
929  }
930 
931  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
932  const AnalysisState &state) const {
933  return insertSliceOpRequiresRead(cast<tensor::ParallelInsertSliceOp>(op),
934  opOperand);
935  }
936 
937  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
938  const AnalysisState &state) const {
939  auto parallelInsertSliceOp = cast<ParallelInsertSliceOp>(op);
940  return opOperand == parallelInsertSliceOp.getDestMutable();
941  }
942 
943  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
944  const BufferizationOptions &options) const {
945  OpBuilder::InsertionGuard g(rewriter);
946  auto parallelInsertSliceOp = cast<ParallelInsertSliceOp>(op);
947  ParallelCombiningOpInterface parallelCombiningParent =
948  parallelInsertSliceOp.getParallelCombiningParent();
949 
950  // Bufferize the op outside of the parallel combining terminator.
951  rewriter.setInsertionPoint(parallelCombiningParent);
952 
953  // Get source and destination buffers.
954  FailureOr<Value> destBuffer =
955  getBuffer(rewriter, parallelInsertSliceOp.getDest(), options);
956  if (failed(destBuffer))
957  return failure();
958  FailureOr<Value> srcBuffer =
959  getBuffer(rewriter, parallelInsertSliceOp.getSource(), options);
960  if (failed(srcBuffer))
961  return failure();
962 
963  // Take a subview of the destination buffer.
964  auto destBufferType = cast<MemRefType>(destBuffer->getType());
965  auto subviewMemRefType =
966  cast<MemRefType>(memref::SubViewOp::inferRankReducedResultType(
967  parallelInsertSliceOp.getSourceType().getShape(), destBufferType,
968  parallelInsertSliceOp.getMixedOffsets(),
969  parallelInsertSliceOp.getMixedSizes(),
970  parallelInsertSliceOp.getMixedStrides()));
971  Value subview = rewriter.create<memref::SubViewOp>(
972  parallelInsertSliceOp.getLoc(), subviewMemRefType, *destBuffer,
973  parallelInsertSliceOp.getMixedOffsets(),
974  parallelInsertSliceOp.getMixedSizes(),
975  parallelInsertSliceOp.getMixedStrides());
976 
977  // This memcpy will fold away if everything bufferizes in-place.
978  if (failed(options.createMemCpy(rewriter, parallelInsertSliceOp.getLoc(),
979  *srcBuffer, subview)))
980  return failure();
981 
982  // In case the source was allocated in the same block, make sure that the
983  // deallocation op (if any) appears after the memcpy. By default, deallocs
984  // are placed before the terminator, but this does not work for ForallOp
985  // because the terminator does more than just yielding a value.
986  //
987  // Note: This is not a problem for the destination buffer because these are
988  // assumed to always bufferize in-place.
989  for (Operation *user : srcBuffer->getUsers()) {
990  if (hasEffect<MemoryEffects::Free>(user)) {
991  if (user->getBlock() == parallelCombiningParent->getBlock())
992  rewriter.moveOpBefore(user, user->getBlock()->getTerminator());
993  break;
994  }
995  }
996 
997  // Delete the op.
998  rewriter.eraseOp(op);
999  return success();
1000  }
1001 
1002  /// tensor.parallel_insert_slice op has implicit inplace behavior. We
1003  /// shouldn't create copy to resolve conflict.
1004  LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
1005  const AnalysisState &state) const {
1006  return success();
1007  }
1008 };
1009 
1010 /// Bufferization of tensor.splat. Bufferizes to a new allocation that is filled
1011 /// with a linalg.map. Similar to tensor.generate.
1012 struct SplatOpInterface
1013  : public BufferizableOpInterface::ExternalModel<SplatOpInterface,
1014  tensor::SplatOp> {
1015 
1016  bool bufferizesToAllocation(Operation *op, Value value) const { return true; }
1017 
1018  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
1019  const BufferizationOptions &options) const {
1020  OpBuilder::InsertionGuard g(rewriter);
1021  auto splatOp = cast<tensor::SplatOp>(op);
1022 
1023  // Allocate memory.
1024  Location loc = op->getLoc();
1025  FailureOr<Value> tensorAlloc = allocateTensorForShapedValue(
1026  rewriter, loc, splatOp.getResult(), options,
1027  /*copy=*/false);
1028  if (failed(tensorAlloc))
1029  return failure();
1030 
1031  // Create linalg::MapOp.
1032  auto tensorType = cast<RankedTensorType>(tensorAlloc->getType());
1033 
1034  // TODO: Implement memory space for this op.
1035  if (options.defaultMemorySpaceFn(tensorType) != Attribute())
1036  return op->emitError("memory space not implemented yet");
1037 
1038  auto linalgOp =
1039  rewriter.create<linalg::MapOp>(loc, tensorType, /*inputs=*/ValueRange(),
1040  /*init=*/*tensorAlloc);
1041  Block &linalgBody = linalgOp.getMapper().emplaceBlock();
1042 
1043  // Create linalg::IndexOps.
1044  rewriter.setInsertionPointToStart(&linalgBody);
1045  rewriter.create<linalg::YieldOp>(loc, splatOp.getInput());
1046  rewriter.replaceOp(splatOp, linalgOp.getResult()[0]);
1047 
1048  return success();
1049  }
1050 };
1051 
1052 } // namespace
1053 } // namespace tensor
1054 } // namespace mlir
1055 
1057  DialectRegistry &registry) {
1058  registry.addExtension(+[](MLIRContext *ctx, tensor::TensorDialect *dialect) {
1059  CastOp::attachInterface<CastOpInterface>(*ctx);
1060  CollapseShapeOp::attachInterface<CollapseShapeOpInterface>(*ctx);
1061  DimOp::attachInterface<DimOpInterface>(*ctx);
1062  EmptyOp::attachInterface<EmptyOpInterface>(*ctx);
1063  ExpandShapeOp::attachInterface<ExpandShapeOpInterface>(*ctx);
1064  ExtractSliceOp::attachInterface<ExtractSliceOpInterface>(*ctx);
1065  ExtractOp::attachInterface<ExtractOpInterface>(*ctx);
1066  FromElementsOp::attachInterface<FromElementsOpInterface>(*ctx);
1067  GenerateOp::attachInterface<GenerateOpInterface>(*ctx);
1068  InsertOp::attachInterface<InsertOpInterface>(*ctx);
1069  InsertSliceOp::attachInterface<InsertSliceOpInterface>(*ctx);
1070  PadOp::attachInterface<PadOpInterface>(*ctx);
1071  ParallelInsertSliceOp::attachInterface<ParallelInsertSliceOpInterface>(
1072  *ctx);
1073  RankOp::attachInterface<RankOpInterface>(*ctx);
1074  ReshapeOp::attachInterface<ReshapeOpInterface>(*ctx);
1075  SplatOp::attachInterface<SplatOpInterface>(*ctx);
1076 
1077  // Load additional dialects of which ops may get created.
1078  ctx->loadDialect<arith::ArithDialect, linalg::LinalgDialect>();
1079  });
1080 
1081  // Bufferization requires SubsetInsertionOpInterface models. Make sure that
1082  // they are registered.
1084 }
static llvm::ManagedStatic< PassManagerOptions > options
Base type for affine expression.
Definition: AffineExpr.h:68
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition: AffineMap.h:46
Base class for generic analysis states.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
Block represents an ordered list of Operations.
Definition: Block.h:33
IntegerAttr getIndexAttr(int64_t value)
Definition: Builders.cpp:148
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:66
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
void loadDialect()
Load a dialect in the context.
Definition: MLIRContext.h:107
RAII guard to reset the insertion point of the builder when destroyed.
Definition: Builders.h:356
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition: Builders.h:439
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition: Builders.h:406
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:497
This class represents a single result from folding an operation.
Definition: OpDefinition.h:268
This class represents an operand of an operation.
Definition: Value.h:267
This is a value defined by a result of an operation.
Definition: Value.h:457
Operation is the basic unit of execution within MLIR.
Definition: Operation.h:88
OpResult getOpResult(unsigned idx)
Definition: Operation.h:416
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition: Operation.h:402
MLIRContext * getContext()
Return the context this operation is associated with.
Definition: Operation.h:216
Location getLoc()
The source location the operation was defined or derived from.
Definition: Operation.h:223
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:268
user_range getUsers()
Returns a range of all users.
Definition: Operation.h:869
use_range getUses()
Returns a range of all uses, which is useful for iterating over all uses.
Definition: Operation.h:842
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition: Region.h:26
unsigned getNumArguments()
Definition: Region.h:123
Block & front()
Definition: Region.h:65
bool hasOneBlock()
Return true if this region has exactly one block.
Definition: Region.h:68
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:400
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
void mergeBlocks(Block *source, Block *dest, ValueRange argValues=std::nullopt)
Inline the operations of block 'source' into the end of block 'dest'.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void moveOpBefore(Operation *op, Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Definition: PatternMatch.h:542
This class provides an abstraction over the different types of ranges over Values.
Definition: ValueRange.h:381
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:129
void replaceOpWithBufferizedValues(RewriterBase &rewriter, Operation *op, ValueRange values)
Replace an op with replacement values.
BaseMemRefType getMemRefTypeWithStaticIdentityLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with a static identity layout (i.e., no layout map).
FailureOr< Value > allocateTensorForShapedValue(OpBuilder &b, Location loc, Value shapedValue, const BufferizationOptions &options, bool copy=true)
Create an AllocTensorOp for the given shaped value (memref or tensor).
FailureOr< BaseMemRefType > getBufferType(Value value, const BufferizationOptions &options)
Return the buffer type for a given Value (tensor) after bufferization without bufferizing any IR.
FailureOr< Value > getBuffer(RewriterBase &rewriter, Value value, const BufferizationOptions &options)
Lookup the buffer for the given value.
BaseMemRefType getMemRefTypeWithFullyDynamicLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with fully dynamic layout.
SmallVector< OpFoldResult > getMixedSizes(OpBuilder &builder, Location loc, Value value)
Return the dimensions of the given memref value.
Definition: MemRefOps.cpp:77
void registerSubsetOpInterfaceExternalModels(DialectRegistry &registry)
void registerBufferizableOpInterfaceExternalModels(DialectRegistry &registry)
Include the generated interface declarations.
bool isZeroIndex(OpFoldResult v)
Return true if v is an IntegerAttr with value 0 of a ConstantIndexOp with attribute with value 0.
bool areConstantIntValues(ArrayRef< OpFoldResult > ofrs, ArrayRef< int64_t > values)
Return true if all of ofrs are constant integers equal to the corresponding value in values.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
bool areAllConstantIntValue(ArrayRef< OpFoldResult > ofrs, int64_t value)
Return true if all of ofrs are constant integers equal to value.
LogicalResult getStridesAndOffset(MemRefType t, SmallVectorImpl< int64_t > &strides, int64_t &offset)
Returns the strides of the MemRef if the layout map is in strided form.
void bindSymbols(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to SymbolExpr at positions: [0 .
Definition: AffineExpr.h:362
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
Options for BufferizableOpInterface-based bufferization.
Bufferizable ops that implement the DestinationStyleOpInterface can use this external model base clas...