MLIR  18.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 
14 #include "mlir/IR/Attributes.h"
15 #include "mlir/IR/Dialect.h"
16 #include "mlir/IR/Operation.h"
17 
18 using namespace mlir;
19 using namespace mlir::bufferization;
20 
21 namespace {
22 /// Bufferization of arith.constant. Replace with memref.get_global.
23 struct ConstantOpInterface
24  : public BufferizableOpInterface::ExternalModel<ConstantOpInterface,
25  arith::ConstantOp> {
26  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
27  const BufferizationOptions &options) const {
28  auto constantOp = cast<arith::ConstantOp>(op);
29 
30  Attribute memorySpace;
31  if (options.defaultMemorySpace.has_value())
32  memorySpace = *options.defaultMemorySpace;
33  else
34  return constantOp->emitError("could not infer memory space");
35 
36  // Only ranked tensors are supported.
37  if (!isa<RankedTensorType>(constantOp.getType()))
38  return failure();
39 
40  // Only constants inside a module are supported.
41  auto moduleOp = constantOp->getParentOfType<ModuleOp>();
42  if (!moduleOp)
43  return failure();
44 
45  // Create global memory segment and replace tensor with memref pointing to
46  // that memory segment.
48  getGlobalFor(constantOp, options.bufferAlignment, memorySpace);
49  if (failed(globalOp))
50  return failure();
51  memref::GlobalOp globalMemref = *globalOp;
52  replaceOpWithNewBufferizedOp<memref::GetGlobalOp>(
53  rewriter, op, globalMemref.getType(), globalMemref.getName());
54 
55  return success();
56  }
57 
58  bool isWritable(Operation *op, Value value,
59  const AnalysisState &state) const {
60  // Memory locations returned by memref::GetGlobalOp may not be written to.
61  assert(isa<OpResult>(value));
62  return false;
63  }
64 };
65 
66 struct IndexCastOpInterface
67  : public BufferizableOpInterface::ExternalModel<IndexCastOpInterface,
68  arith::IndexCastOp> {
69  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
70  const AnalysisState &state) const {
71  return false;
72  }
73 
74  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
75  const AnalysisState &state) const {
76  return false;
77  }
78 
79  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
80  const AnalysisState &state) const {
81  return {{op->getResult(0), BufferRelation::Equivalent}};
82  }
83 
84  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
85  const BufferizationOptions &options) const {
86  auto castOp = cast<arith::IndexCastOp>(op);
87  auto resultTensorType = cast<TensorType>(castOp.getType());
88 
89  FailureOr<Value> source = getBuffer(rewriter, castOp.getIn(), options);
90  if (failed(source))
91  return failure();
92  auto sourceType = cast<BaseMemRefType>(source->getType());
93 
94  // Result type should have same layout and address space as the source type.
95  BaseMemRefType resultType;
96  if (auto rankedMemRefType = dyn_cast<MemRefType>(sourceType)) {
97  resultType = MemRefType::get(
98  rankedMemRefType.getShape(), resultTensorType.getElementType(),
99  rankedMemRefType.getLayout(), rankedMemRefType.getMemorySpace());
100  } else {
101  auto unrankedMemrefType = cast<UnrankedMemRefType>(sourceType);
102  resultType = UnrankedMemRefType::get(resultTensorType.getElementType(),
103  unrankedMemrefType.getMemorySpace());
104  }
105 
106  replaceOpWithNewBufferizedOp<arith::IndexCastOp>(rewriter, op, resultType,
107  *source);
108  return success();
109  }
110 };
111 
112 /// Bufferization of arith.select. Just replace the operands.
113 struct SelectOpInterface
114  : public BufferizableOpInterface::ExternalModel<SelectOpInterface,
115  arith::SelectOp> {
116  bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
117  const AnalysisState &state) const {
118  return false;
119  }
120 
121  bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
122  const AnalysisState &state) const {
123  return false;
124  }
125 
126  AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
127  const AnalysisState &state) const {
128  return {{op->getOpResult(0) /*result*/, BufferRelation::Equivalent,
129  /*isDefinite=*/false}};
130  }
131 
132  LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
133  const BufferizationOptions &options) const {
134  auto selectOp = cast<arith::SelectOp>(op);
135  Location loc = selectOp.getLoc();
136 
137  // Elementwise conditions are not supported yet. To bufferize such an op,
138  // it could be lowered to an elementwise "linalg.generic" with a new
139  // "tensor.empty" out tensor, followed by "empty tensor elimination". Such
140  // IR will bufferize.
141  if (!selectOp.getCondition().getType().isInteger(1))
142  return op->emitOpError("only i1 condition values are supported");
143 
144  // TODO: It would be more efficient to copy the result of the `select` op
145  // instead of its OpOperands. In the worst case, 2 copies are inserted at
146  // the moment (one for each tensor). When copying the op result, only one
147  // copy would be needed.
148  FailureOr<Value> maybeTrueBuffer =
149  getBuffer(rewriter, selectOp.getTrueValue(), options);
150  FailureOr<Value> maybeFalseBuffer =
151  getBuffer(rewriter, selectOp.getFalseValue(), options);
152  if (failed(maybeTrueBuffer) || failed(maybeFalseBuffer))
153  return failure();
154  Value trueBuffer = *maybeTrueBuffer;
155  Value falseBuffer = *maybeFalseBuffer;
156 
157  // The "true" and the "false" operands must have the same type. If the
158  // buffers have different types, they differ only in their layout map. Cast
159  // both of them to the most dynamic MemRef type.
160  if (trueBuffer.getType() != falseBuffer.getType()) {
161  auto targetType =
162  bufferization::getBufferType(selectOp.getResult(), options);
163  if (failed(targetType))
164  return failure();
165  if (trueBuffer.getType() != *targetType)
166  trueBuffer =
167  rewriter.create<memref::CastOp>(loc, *targetType, trueBuffer);
168  if (falseBuffer.getType() != *targetType)
169  falseBuffer =
170  rewriter.create<memref::CastOp>(loc, *targetType, falseBuffer);
171  }
172 
173  replaceOpWithNewBufferizedOp<arith::SelectOp>(
174  rewriter, op, selectOp.getCondition(), trueBuffer, falseBuffer);
175  return success();
176  }
177 
180  SmallVector<Value> &invocationStack) const {
181  auto selectOp = cast<arith::SelectOp>(op);
182  assert(value == selectOp.getResult() && "invalid value");
183  auto trueType = bufferization::getBufferType(selectOp.getTrueValue(),
184  options, invocationStack);
185  auto falseType = bufferization::getBufferType(selectOp.getFalseValue(),
186  options, invocationStack);
187  if (failed(trueType) || failed(falseType))
188  return failure();
189  if (*trueType == *falseType)
190  return *trueType;
191  if (trueType->getMemorySpace() != falseType->getMemorySpace())
192  return op->emitError("inconsistent memory space on true/false operands");
193 
194  // If the buffers have different types, they differ only in their layout
195  // map.
196  auto memrefType = llvm::cast<MemRefType>(*trueType);
198  RankedTensorType::get(memrefType.getShape(),
199  memrefType.getElementType()),
200  memrefType.getMemorySpace());
201  }
202 };
203 
204 } // namespace
205 
207  DialectRegistry &registry) {
208  registry.addExtension(+[](MLIRContext *ctx, ArithDialect *dialect) {
209  ConstantOp::attachInterface<ConstantOpInterface>(*ctx);
210  IndexCastOp::attachInterface<IndexCastOpInterface>(*ctx);
211  SelectOp::attachInterface<SelectOpInterface>(*ctx);
212  });
213 }
static llvm::ManagedStatic< PassManagerOptions > options
Base class for generic analysis states.
Attributes are known-constant values of operations.
Definition: Attributes.h:25
This class provides a shared interface for ranked and unranked memref types.
Definition: BuiltinTypes.h:138
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
void addExtension(std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
This class provides support for representing a failure result, or a valid value of type T.
Definition: LogicalResult.h:78
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition: Location.h:63
MLIRContext is the top-level object for a collection of MLIR operations.
Definition: MLIRContext.h:60
Operation * create(const OperationState &state)
Creates an operation given the fields represented as an OperationState.
Definition: Builders.cpp:446
This class represents an operand of an operation.
Definition: Value.h:263
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
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
Definition: Operation.cpp:267
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
Definition: Operation.cpp:640
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
Definition: PatternMatch.h:399
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:125
void registerBufferizableOpInterfaceExternalModels(DialectRegistry &registry)
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.
FailureOr< memref::GlobalOp > getGlobalFor(arith::ConstantOp constantOp, uint64_t alignment, Attribute memorySpace={})
BaseMemRefType getMemRefTypeWithFullyDynamicLayout(TensorType tensorType, Attribute memorySpace=nullptr)
Return a MemRef type with fully dynamic layout.
Include the generated interface declarations.
LogicalResult failure(bool isFailure=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:62
LogicalResult success(bool isSuccess=true)
Utility function to generate a LogicalResult.
Definition: LogicalResult.h:56
auto get(MLIRContext *context, Ts &&...params)
Helper method that injects context only if needed, this helps unify some of the attribute constructio...
bool failed(LogicalResult result)
Utility function that returns true if the provided LogicalResult corresponds to a failure value.
Definition: LogicalResult.h:72
This class represents an efficient way to signal success or failure.
Definition: LogicalResult.h:26
Options for BufferizableOpInterface-based bufferization.