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 
9 #include "mlir/Dialect/SCF/BufferizableOpInterfaceImpl.h"
10 
11 #include "mlir/Dialect/Bufferization/IR/BufferizableOpInterface.h"
12 #include "mlir/Dialect/Bufferization/IR/Bufferization.h"
13 #include "mlir/Dialect/Bufferization/Transforms/OneShotAnalysis.h"
14 #include "mlir/Dialect/MemRef/IR/MemRef.h"
15 #include "mlir/Dialect/SCF/SCF.h"
16 #include "mlir/Dialect/Tensor/IR/Tensor.h"
17 #include "mlir/IR/Dialect.h"
18 #include "mlir/IR/Operation.h"
19 #include "mlir/IR/PatternMatch.h"
20 
21 using namespace mlir;
22 using namespace mlir::bufferization;
23 using namespace mlir::scf;
24 
25 namespace mlir {
26 namespace scf {
27 namespace {
28 
29 // bufferization.to_memref is not allowed to change the rank.
30 static void ensureToMemrefOpIsValid(Value tensor, Type memrefType) {
31 #ifndef NDEBUG
32   auto rankedTensorType = tensor.getType().dyn_cast<RankedTensorType>();
33   assert((!rankedTensorType || (memrefType.cast<MemRefType>().getRank() ==
34                                 rankedTensorType.getRank())) &&
35          "to_memref would be invalid: mismatching ranks");
36 #endif
37 }
38 
39 /// Bufferization of scf.execute_region. Can be analyzed, but bufferization not
40 /// fully implemented at the moment.
41 struct ExecuteRegionOpInterface
42     : public BufferizableOpInterface::ExternalModel<ExecuteRegionOpInterface,
43                                                     scf::ExecuteRegionOp> {
44   SmallVector<OpOperand *>
45   getAliasingOpOperand(Operation *op, OpResult opResult,
46                        const AnalysisState &state) const {
47     // ExecuteRegionOps do not have tensor OpOperands. The yielded value can be
48     // any SSA value that is in scope. To allow for use-def chain traversal
49     // through ExecuteRegionOps in the analysis, the corresponding yield value
50     // is considered to be aliasing with the result.
51     auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
52     size_t resultNum = std::distance(op->getOpResults().begin(),
53                                      llvm::find(op->getOpResults(), opResult));
54     // TODO: Support multiple blocks.
55     assert(executeRegionOp.getRegion().getBlocks().size() == 1 &&
56            "expected exactly 1 block");
57     auto yieldOp = dyn_cast<scf::YieldOp>(
58         executeRegionOp.getRegion().front().getTerminator());
59     assert(yieldOp && "expected scf.yield terminator in scf.execute_region");
60     return {&yieldOp->getOpOperand(resultNum)};
61   }
62 
63   // TODO: For better bufferization results, this could return `true` only if
64   // there is a memory write in the region.
65   bool isMemoryWrite(Operation *op, OpResult opResult,
66                      const AnalysisState &state) const {
67     // Similar to scf.if, results of this op are always considered memory writes
68     // in the analysis. This is a useful pattern for all ops that have tensor
69     // OpResults but no tensor OpOperands. By default, `isMemoryWrite` is
70     // implemented in terms of `bufferizesToMemoryWrite`, which does not work on
71     // ops without OpOperands.
72     return true;
73   }
74 
75   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
76                           const BufferizationOptions &options) const {
77     auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
78 
79     // Compute new result types.
80     SmallVector<Type> newResultTypes;
81     for (Type type : executeRegionOp->getResultTypes()) {
82       if (auto tensorType = type.dyn_cast<TensorType>()) {
83         // TODO: Infer the result type instead of computing it.
84         newResultTypes.push_back(getMemRefType(tensorType, options));
85       } else {
86         newResultTypes.push_back(type);
87       }
88     }
89 
90     // Create new op and move over region.
91     auto newOp =
92         rewriter.create<scf::ExecuteRegionOp>(op->getLoc(), newResultTypes);
93     newOp.getRegion().takeBody(executeRegionOp.getRegion());
94 
95     // Update terminator.
96     assert(newOp.getRegion().getBlocks().size() == 1 &&
97            "only 1 block supported");
98     Block *newBlock = &newOp.getRegion().front();
99     auto yieldOp = cast<scf::YieldOp>(newBlock->getTerminator());
100     rewriter.setInsertionPoint(yieldOp);
101     SmallVector<Value> newYieldValues;
102     for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
103       Value val = it.value();
104       if (val.getType().isa<TensorType>()) {
105         newYieldValues.push_back(rewriter.create<bufferization::ToMemrefOp>(
106             yieldOp.getLoc(), newResultTypes[it.index()], val));
107       } else {
108         newYieldValues.push_back(val);
109       }
110     }
111     rewriter.replaceOpWithNewOp<scf::YieldOp>(yieldOp, newYieldValues);
112 
113     // Update all uses of the old op.
114     rewriter.setInsertionPointAfter(newOp);
115     SmallVector<Value> newResults;
116     for (const auto &it : llvm::enumerate(executeRegionOp->getResultTypes())) {
117       if (it.value().isa<TensorType>()) {
118         newResults.push_back(rewriter.create<bufferization::ToTensorOp>(
119             executeRegionOp.getLoc(), newOp->getResult(it.index())));
120       } else {
121         newResults.push_back(newOp->getResult(it.index()));
122       }
123     }
124 
125     // Replace old op.
126     rewriter.replaceOp(executeRegionOp, newResults);
127 
128     return success();
129   }
130 
131   BufferRelation bufferRelation(Operation *op, OpResult opResult,
132                                 const AnalysisState &state) const {
133     return BufferRelation::Equivalent;
134   }
135 };
136 
137 /// Bufferization of scf.if. Replace with a new scf.if that yields memrefs.
138 struct IfOpInterface
139     : public BufferizableOpInterface::ExternalModel<IfOpInterface, scf::IfOp> {
140   SmallVector<OpOperand *>
141   getAliasingOpOperand(Operation *op, OpResult opResult,
142                        const AnalysisState &state) const {
143     // IfOps do not have tensor OpOperands. The yielded value can be any SSA
144     // value that is in scope. To allow for use-def chain traversal through
145     // IfOps in the analysis, both corresponding yield values from the then/else
146     // branches are considered to be aliasing with the result.
147     auto ifOp = cast<scf::IfOp>(op);
148     size_t resultNum = std::distance(op->getOpResults().begin(),
149                                      llvm::find(op->getOpResults(), opResult));
150     return {&ifOp.thenYield()->getOpOperand(resultNum),
151             &ifOp.elseYield()->getOpOperand(resultNum)};
152   }
153 
154   // TODO: For better bufferization results, this could return `true` only if
155   // there is a memory write in one (or both) of the branches. Since this is not
156   // allowed at the moment, we should never encounter scf.ifs that yield
157   // unmodified tensors. Such scf.yield ops could just fold away.
158   bool isMemoryWrite(Operation *op, OpResult opResult,
159                      const AnalysisState &state) const {
160     // IfOp results are always considered memory writes in the analysis. This
161     // design decision simplifies the analysis considerably. E.g., consider the
162     // following test case:
163     //
164     // %0 = "some_writing_op" : tensor<?xf32>
165     // %r = scf.if %c -> (tensor<?xf32>) {
166     //   scf.yield %0
167     // } else {
168     //   %1 = "another_writing_op"(%0) : tensor<?xf32>
169     // }
170     // "some_reading_op"(%r)
171     //
172     // "another_writing_op" in the above example should be able to bufferize
173     // inplace in the absence of another read of %0. However, if the scf.if op
174     // would not be considered a "write", the analysis would detect the
175     // following conflict:
176     //
177     // * read = some_reading_op
178     // * lastWrite = %0  (Note: The last write of %r would be a set: {%0, %1}.)
179     // * conflictingWrite = %1
180     //
181     // For more details, check the "scf.IfOp" section of the design document.
182     return true;
183   }
184 
185   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
186                           const BufferizationOptions &options) const {
187     auto ifOp = cast<scf::IfOp>(op);
188 
189     // Compute new types of the bufferized scf.if op.
190     SmallVector<Type> newTypes;
191     for (Type returnType : ifOp->getResultTypes()) {
192       if (auto tensorType = returnType.dyn_cast<TensorType>()) {
193         // TODO: Infer the result type instead of computing it.
194         newTypes.push_back(getMemRefType(tensorType, options));
195       } else {
196         newTypes.push_back(returnType);
197       }
198     }
199 
200     // Create new op.
201     auto newIfOp =
202         rewriter.create<scf::IfOp>(ifOp.getLoc(), newTypes, ifOp.getCondition(),
203                                    /*withElseRegion=*/true);
204 
205     // Remove terminators.
206     if (!newIfOp.thenBlock()->empty()) {
207       rewriter.eraseOp(newIfOp.thenBlock()->getTerminator());
208       rewriter.eraseOp(newIfOp.elseBlock()->getTerminator());
209     }
210 
211     // Move over then/else blocks.
212     rewriter.mergeBlocks(ifOp.thenBlock(), newIfOp.thenBlock());
213     rewriter.mergeBlocks(ifOp.elseBlock(), newIfOp.elseBlock());
214 
215     // Update scf.yield of new then-block.
216     auto thenYieldOp = cast<scf::YieldOp>(newIfOp.thenBlock()->getTerminator());
217     rewriter.setInsertionPoint(thenYieldOp);
218     SmallVector<Value> thenYieldValues;
219     for (OpOperand &operand : thenYieldOp->getOpOperands()) {
220       if (operand.get().getType().isa<TensorType>()) {
221         ensureToMemrefOpIsValid(operand.get(),
222                                 newTypes[operand.getOperandNumber()]);
223         Value toMemrefOp = rewriter.create<bufferization::ToMemrefOp>(
224             operand.get().getLoc(), newTypes[operand.getOperandNumber()],
225             operand.get());
226         operand.set(toMemrefOp);
227       }
228     }
229 
230     // Update scf.yield of new else-block.
231     auto elseYieldOp = cast<scf::YieldOp>(newIfOp.elseBlock()->getTerminator());
232     rewriter.setInsertionPoint(elseYieldOp);
233     SmallVector<Value> elseYieldValues;
234     for (OpOperand &operand : elseYieldOp->getOpOperands()) {
235       if (operand.get().getType().isa<TensorType>()) {
236         ensureToMemrefOpIsValid(operand.get(),
237                                 newTypes[operand.getOperandNumber()]);
238         Value toMemrefOp = rewriter.create<bufferization::ToMemrefOp>(
239             operand.get().getLoc(), newTypes[operand.getOperandNumber()],
240             operand.get());
241         operand.set(toMemrefOp);
242       }
243     }
244 
245     // Replace op results.
246     replaceOpWithBufferizedValues(rewriter, op, newIfOp->getResults());
247 
248     return success();
249   }
250 
251   BufferRelation bufferRelation(Operation *op, OpResult opResult,
252                                 const AnalysisState &state) const {
253     // IfOp results are equivalent to their corresponding yield values if both
254     // yield values are equivalent to each other.
255     auto bufferizableOp = cast<BufferizableOpInterface>(op);
256     SmallVector<OpOperand *> yieldValues =
257         bufferizableOp.getAliasingOpOperand(opResult, state);
258     assert(yieldValues.size() == 2 && "expected 2 yield values");
259     bool equivalentYields = state.areEquivalentBufferizedValues(
260         yieldValues[0]->get(), yieldValues[1]->get());
261     return equivalentYields ? BufferRelation::Equivalent : BufferRelation::None;
262   }
263 };
264 
265 /// Helper function for loop bufferization. Return the indices of all values
266 /// that have a tensor type.
267 static DenseSet<int64_t> getTensorIndices(ValueRange values) {
268   DenseSet<int64_t> result;
269   for (const auto &it : llvm::enumerate(values))
270     if (it.value().getType().isa<TensorType>())
271       result.insert(it.index());
272   return result;
273 }
274 
275 /// Helper function for loop bufferization. Return the indices of all
276 /// bbArg/yielded value pairs who's buffer relation is "Equivalent".
277 DenseSet<int64_t> getEquivalentBuffers(Block::BlockArgListType bbArgs,
278                                        ValueRange yieldedValues,
279                                        const AnalysisState &state) {
280   unsigned int minSize = std::min(bbArgs.size(), yieldedValues.size());
281   DenseSet<int64_t> result;
282   for (unsigned int i = 0; i < minSize; ++i) {
283     if (!bbArgs[i].getType().isa<TensorType>() ||
284         !yieldedValues[i].getType().isa<TensorType>())
285       continue;
286     if (state.areEquivalentBufferizedValues(bbArgs[i], yieldedValues[i]))
287       result.insert(i);
288   }
289   return result;
290 }
291 
292 /// Helper function for loop bufferization. Cast the given buffer to the given
293 /// memref type.
294 static Value castBuffer(OpBuilder &b, Value buffer, Type type) {
295   assert(type.isa<BaseMemRefType>() && "expected BaseMemRefType");
296   assert(buffer.getType().isa<BaseMemRefType>() && "expected BaseMemRefType");
297   // If the buffer already has the correct type, no cast is needed.
298   if (buffer.getType() == type)
299     return buffer;
300   // TODO: In case `type` has a layout map that is not the fully dynamic
301   // one, we may not be able to cast the buffer. In that case, the loop
302   // iter_arg's layout map must be changed (see uses of `castBuffer`).
303   assert(memref::CastOp::areCastCompatible(buffer.getType(), type) &&
304          "scf.while op bufferization: cast incompatible");
305   return b.create<memref::CastOp>(buffer.getLoc(), type, buffer).getResult();
306 }
307 
308 /// Helper function for loop bufferization. Return the bufferized values of the
309 /// given OpOperands. If an operand is not a tensor, return the original value.
310 static SmallVector<Value> getBuffers(RewriterBase &rewriter,
311                                      MutableArrayRef<OpOperand> operands,
312                                      const BufferizationOptions &options) {
313   SmallVector<Value> result;
314   for (OpOperand &opOperand : operands) {
315     if (opOperand.get().getType().isa<TensorType>()) {
316       Value resultBuffer = getBuffer(rewriter, opOperand.get(), options);
317       result.push_back(resultBuffer);
318     } else {
319       result.push_back(opOperand.get());
320     }
321   }
322   return result;
323 }
324 
325 /// Helper function for loop bufferization. Compute the buffer that should be
326 /// yielded from a loop block (loop body or loop condition).
327 static Value getYieldedBuffer(RewriterBase &rewriter, Value tensor,
328                               BaseMemRefType type,
329                               const BufferizationOptions &options) {
330   assert(tensor.getType().isa<TensorType>() && "expected tensor");
331   ensureToMemrefOpIsValid(tensor, type);
332   Value yieldedVal = getBuffer(rewriter, tensor, options);
333   return castBuffer(rewriter, yieldedVal, type);
334 }
335 
336 /// Helper function for loop bufferization. Given a range of values, apply
337 /// `func` to those marked in `tensorIndices`. Otherwise, store the unmodified
338 /// value in the result vector.
339 static SmallVector<Value>
340 convertTensorValues(ValueRange values, const DenseSet<int64_t> &tensorIndices,
341                     llvm::function_ref<Value(Value, int64_t)> func) {
342   SmallVector<Value> result;
343   for (const auto &it : llvm::enumerate(values)) {
344     size_t idx = it.index();
345     Value val = it.value();
346     result.push_back(tensorIndices.contains(idx) ? func(val, idx) : val);
347   }
348   return result;
349 }
350 
351 /// Helper function for loop bufferization. Given a list of pre-bufferization
352 /// yielded values, compute the list of bufferized yielded values.
353 SmallVector<Value> getYieldedValues(RewriterBase &rewriter, ValueRange values,
354                                     TypeRange bufferizedTypes,
355                                     const DenseSet<int64_t> &tensorIndices,
356                                     const BufferizationOptions &options) {
357   return convertTensorValues(
358       values, tensorIndices, [&](Value val, int64_t index) {
359         return getYieldedBuffer(rewriter, val,
360                                 bufferizedTypes[index].cast<BaseMemRefType>(),
361                                 options);
362       });
363 }
364 
365 /// Helper function for loop bufferization. Given a list of bbArgs of the new
366 /// (bufferized) loop op, wrap the bufferized tensor args (now memrefs) into
367 /// ToTensorOps, so that the block body can be moved over to the new op.
368 SmallVector<Value>
369 getBbArgReplacements(RewriterBase &rewriter, Block::BlockArgListType bbArgs,
370                      const DenseSet<int64_t> &tensorIndices) {
371   return convertTensorValues(
372       bbArgs, tensorIndices, [&](Value val, int64_t index) {
373         return rewriter.create<bufferization::ToTensorOp>(val.getLoc(), val);
374       });
375 }
376 
377 /// Bufferization of scf.for. Replace with a new scf.for that operates on
378 /// memrefs.
379 struct ForOpInterface
380     : public BufferizableOpInterface::ExternalModel<ForOpInterface,
381                                                     scf::ForOp> {
382   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
383                               const AnalysisState &state) const {
384     // scf::ForOp alone doesn't bufferize to a memory read, one of the uses of
385     // its matching bbArg may.
386     auto forOp = cast<scf::ForOp>(op);
387     return state.isValueRead(forOp.getRegionIterArgForOpOperand(opOperand));
388   }
389 
390   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
391                                const AnalysisState &state) const {
392     // Tensor iter_args of scf::ForOps are always considered as a write.
393     return true;
394   }
395 
396   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
397                                             const AnalysisState &state) const {
398     auto forOp = cast<scf::ForOp>(op);
399     return {forOp.getResultForOpOperand(opOperand)};
400   }
401 
402   BufferRelation bufferRelation(Operation *op, OpResult opResult,
403                                 const AnalysisState &state) const {
404     // ForOp results are equivalent to their corresponding init_args if the
405     // corresponding iter_args and yield values are equivalent.
406     auto forOp = cast<scf::ForOp>(op);
407     OpOperand &forOperand = forOp.getOpOperandForResult(opResult);
408     auto bbArg = forOp.getRegionIterArgForOpOperand(forOperand);
409     auto yieldOp =
410         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
411     bool equivalentYield = state.areEquivalentBufferizedValues(
412         bbArg, yieldOp->getOperand(opResult.getResultNumber()));
413     return equivalentYield ? BufferRelation::Equivalent : BufferRelation::None;
414   }
415 
416   bool isWritable(Operation *op, Value value,
417                   const AnalysisState &state) const {
418     // Interestingly, scf::ForOp's bbArg can **always** be viewed
419     // inplace from the perspective of ops nested under:
420     //   1. Either the matching iter operand is not bufferized inplace and an
421     //      alloc + optional copy makes the bbArg itself inplaceable.
422     //   2. Or the matching iter operand is bufferized inplace and bbArg just
423     //      bufferizes to that too.
424     return true;
425   }
426 
427   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
428                                  const AnalysisState &state) const {
429     auto bufferizableOp = cast<BufferizableOpInterface>(op);
430     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
431       return failure();
432 
433     if (!state.getOptions().enforceAliasingInvariants)
434       return success();
435 
436     // According to the `getAliasing...` implementations, a bufferized OpResult
437     // may alias only with the corresponding bufferized init_arg and with no
438     // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg;
439     // but not with any other OpOperand. If a corresponding OpResult/init_arg
440     // pair bufferizes to equivalent buffers, this aliasing requirement is
441     // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy.
442     // (New buffer copies do not alias with any buffer.)
443     auto forOp = cast<scf::ForOp>(op);
444     auto yieldOp =
445         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
446     OpBuilder::InsertionGuard g(rewriter);
447     rewriter.setInsertionPoint(yieldOp);
448 
449     // Indices of all iter_args that have tensor type. These are the ones that
450     // are bufferized.
451     DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
452     // For every yielded value, is the value equivalent to its corresponding
453     // bbArg?
454     DenseSet<int64_t> equivalentYields = getEquivalentBuffers(
455         forOp.getRegionIterArgs(), yieldOp.getResults(), state);
456     SmallVector<Value> yieldValues;
457     for (int64_t idx = 0;
458          idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) {
459       Value value = yieldOp.getResults()[idx];
460       if (!indices.contains(idx) || equivalentYields.contains(idx)) {
461         yieldValues.push_back(value);
462         continue;
463       }
464       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
465           yieldOp.getLoc(), value.getType().cast<RankedTensorType>(),
466           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
467       yieldValues.push_back(alloc);
468     }
469 
470     rewriter.updateRootInPlace(
471         yieldOp, [&]() { yieldOp.getResultsMutable().assign(yieldValues); });
472     return success();
473   }
474 
475   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
476                           const BufferizationOptions &options) const {
477     auto forOp = cast<scf::ForOp>(op);
478     Block *oldLoopBody = &forOp.getLoopBody().front();
479 
480     // Indices of all iter_args that have tensor type. These are the ones that
481     // are bufferized.
482     DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
483 
484     // The new memref init_args of the loop.
485     SmallVector<Value> initArgs =
486         getBuffers(rewriter, forOp.getIterOpOperands(), options);
487 
488     // Construct a new scf.for op with memref instead of tensor values.
489     auto newForOp = rewriter.create<scf::ForOp>(
490         forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
491         forOp.getStep(), initArgs);
492     newForOp->setAttrs(forOp->getAttrs());
493     ValueRange initArgsRange(initArgs);
494     TypeRange initArgsTypes(initArgsRange);
495     Block *loopBody = &newForOp.getLoopBody().front();
496 
497     // Set up new iter_args. The loop body uses tensors, so wrap the (memref)
498     // iter_args of the new loop in ToTensorOps.
499     rewriter.setInsertionPointToStart(loopBody);
500     SmallVector<Value> iterArgs =
501         getBbArgReplacements(rewriter, newForOp.getRegionIterArgs(), indices);
502     iterArgs.insert(iterArgs.begin(), newForOp.getInductionVar());
503 
504     // Erase terminator if present.
505     if (iterArgs.size() == 1)
506       rewriter.eraseOp(loopBody->getTerminator());
507 
508     // Move loop body to new loop.
509     rewriter.mergeBlocks(oldLoopBody, loopBody, iterArgs);
510 
511     // Update scf.yield of new loop.
512     auto yieldOp = cast<scf::YieldOp>(loopBody->getTerminator());
513     rewriter.setInsertionPoint(yieldOp);
514     SmallVector<Value> yieldValues = getYieldedValues(
515         rewriter, yieldOp.getResults(), initArgsTypes, indices, options);
516     yieldOp.getResultsMutable().assign(yieldValues);
517 
518     // Replace loop results.
519     replaceOpWithBufferizedValues(rewriter, op, newForOp->getResults());
520 
521     return success();
522   }
523 
524   /// Assert that yielded values of an scf.for op are equivalent to their
525   /// corresponding bbArgs. In that case, the buffer relations of the
526   /// corresponding OpResults are "Equivalent".
527   ///
528   /// If this is not the case, an allocs+copies are inserted and yielded from
529   /// the loop. This could be a performance problem, so it must be explicitly
530   /// activated with `alloc-return-allocs`.
531   LogicalResult verifyAnalysis(Operation *op,
532                                const AnalysisState &state) const {
533     const auto &options =
534         static_cast<const OneShotBufferizationOptions &>(state.getOptions());
535     if (options.allowReturnAllocs)
536       return success();
537 
538     auto forOp = cast<scf::ForOp>(op);
539     auto yieldOp =
540         cast<scf::YieldOp>(forOp.getLoopBody().front().getTerminator());
541     for (OpResult opResult : op->getOpResults()) {
542       if (!opResult.getType().isa<TensorType>())
543         continue;
544 
545       // Note: This is overly strict. We should check for aliasing bufferized
546       // values. But we don't have a "must-alias" analysis yet.
547       if (bufferRelation(op, opResult, state) != BufferRelation::Equivalent)
548         return yieldOp->emitError()
549                << "Yield operand #" << opResult.getResultNumber()
550                << " is not equivalent to the corresponding iter bbArg";
551     }
552 
553     return success();
554   }
555 };
556 
557 /// Bufferization of scf.while. Replace with a new scf.while that operates on
558 /// memrefs.
559 struct WhileOpInterface
560     : public BufferizableOpInterface::ExternalModel<WhileOpInterface,
561                                                     scf::WhileOp> {
562   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
563                               const AnalysisState &state) const {
564     // Tensor iter_args of scf::WhileOps are always considered as a read.
565     return true;
566   }
567 
568   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
569                                const AnalysisState &state) const {
570     // Tensor iter_args of scf::WhileOps are always considered as a write.
571     return true;
572   }
573 
574   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
575                                             const AnalysisState &state) const {
576     auto whileOp = cast<scf::WhileOp>(op);
577     unsigned int idx = opOperand.getOperandNumber();
578 
579     // The OpResults and OpOperands may not match. They may not even have the
580     // same type. The number of OpResults and OpOperands can also differ.
581     if (idx >= op->getNumResults() ||
582         opOperand.get().getType() != op->getResult(idx).getType())
583       return {};
584 
585     // The only aliasing OpResult may be the one at the same index.
586     return {whileOp->getResult(idx)};
587   }
588 
589   BufferRelation bufferRelation(Operation *op, OpResult opResult,
590                                 const AnalysisState &state) const {
591     // WhileOp results are equivalent to their corresponding init_args if the
592     // corresponding iter_args and yield values are equivalent (for both the
593     // "before" and the "after" block).
594     unsigned int resultNumber = opResult.getResultNumber();
595     auto whileOp = cast<scf::WhileOp>(op);
596 
597     // The "before" region bbArgs and the OpResults may not match.
598     if (resultNumber >= whileOp.getBeforeArguments().size())
599       return BufferRelation::None;
600     if (opResult.getType() !=
601         whileOp.getBeforeArguments()[resultNumber].getType())
602       return BufferRelation::None;
603 
604     auto conditionOp = whileOp.getConditionOp();
605     BlockArgument conditionBbArg = whileOp.getBeforeArguments()[resultNumber];
606     Value conditionOperand = conditionOp.getArgs()[resultNumber];
607     bool equivCondition =
608         state.areEquivalentBufferizedValues(conditionBbArg, conditionOperand);
609 
610     auto yieldOp = whileOp.getYieldOp();
611     BlockArgument bodyBbArg = whileOp.getAfterArguments()[resultNumber];
612     Value yieldOperand = yieldOp.getOperand(resultNumber);
613     bool equivYield =
614         state.areEquivalentBufferizedValues(bodyBbArg, yieldOperand);
615 
616     return equivCondition && equivYield ? BufferRelation::Equivalent
617                                         : BufferRelation::None;
618   }
619 
620   bool isWritable(Operation *op, Value value,
621                   const AnalysisState &state) const {
622     // Interestingly, scf::WhileOp's bbArg can **always** be viewed
623     // inplace from the perspective of ops nested under:
624     //   1. Either the matching iter operand is not bufferized inplace and an
625     //      alloc + optional copy makes the bbArg itself inplaceable.
626     //   2. Or the matching iter operand is bufferized inplace and bbArg just
627     //      bufferizes to that too.
628     return true;
629   }
630 
631   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
632                                  const AnalysisState &state) const {
633     auto bufferizableOp = cast<BufferizableOpInterface>(op);
634     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
635       return failure();
636 
637     if (!state.getOptions().enforceAliasingInvariants)
638       return success();
639 
640     // According to the `getAliasing...` implementations, a bufferized OpResult
641     // may alias only with the corresponding bufferized init_arg and with no
642     // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg;
643     // but not with any other OpOperand. If a corresponding OpResult/init_arg
644     // pair bufferizes to equivalent buffers, this aliasing requirement is
645     // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy.
646     // (New buffer copies do not alias with any buffer.)
647     OpBuilder::InsertionGuard g(rewriter);
648     auto whileOp = cast<scf::WhileOp>(op);
649     auto conditionOp = whileOp.getConditionOp();
650     auto yieldOp = whileOp.getYieldOp();
651 
652     // Indices of all bbArgs that have tensor type. These are the ones that
653     // are bufferized. The "before" and "after" regions may have different args.
654     DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits());
655     DenseSet<int64_t> indicesAfter =
656         getTensorIndices(whileOp.getAfterArguments());
657 
658     // For every yielded value, is the value equivalent to its corresponding
659     // bbArg?
660     DenseSet<int64_t> equivalentYieldsBefore = getEquivalentBuffers(
661         whileOp.getBeforeArguments(), conditionOp.getArgs(), state);
662     DenseSet<int64_t> equivalentYieldsAfter = getEquivalentBuffers(
663         whileOp.getAfterArguments(), whileOp.getYieldOp().getResults(), state);
664 
665     // Update "before" region.
666     rewriter.setInsertionPoint(conditionOp);
667     SmallVector<Value> beforeYieldValues;
668     for (int64_t idx = 0;
669          idx < static_cast<int64_t>(conditionOp.getArgs().size()); ++idx) {
670       Value value = conditionOp.getArgs()[idx];
671       if (!indicesBefore.contains(idx) ||
672           equivalentYieldsBefore.contains(idx)) {
673         beforeYieldValues.push_back(value);
674         continue;
675       }
676       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
677           conditionOp.getLoc(), value.getType().cast<RankedTensorType>(),
678           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
679       beforeYieldValues.push_back(alloc);
680     }
681     rewriter.updateRootInPlace(conditionOp, [&]() {
682       conditionOp.getArgsMutable().assign(beforeYieldValues);
683     });
684 
685     // Update "after" region.
686     rewriter.setInsertionPoint(yieldOp);
687     SmallVector<Value> afterYieldValues;
688     for (int64_t idx = 0;
689          idx < static_cast<int64_t>(yieldOp.getResults().size()); ++idx) {
690       Value value = yieldOp.getResults()[idx];
691       if (!indicesAfter.contains(idx) || equivalentYieldsAfter.contains(idx)) {
692         afterYieldValues.push_back(value);
693         continue;
694       }
695       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
696           yieldOp.getLoc(), value.getType().cast<RankedTensorType>(),
697           /*dynamicSizes=*/ValueRange(), value, /*escape=*/true);
698       afterYieldValues.push_back(alloc);
699     }
700     rewriter.updateRootInPlace(yieldOp, [&]() {
701       yieldOp.getResultsMutable().assign(afterYieldValues);
702     });
703 
704     return success();
705   }
706 
707   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
708                           const BufferizationOptions &options) const {
709     auto whileOp = cast<scf::WhileOp>(op);
710 
711     assert(whileOp.getBefore().getBlocks().size() == 1 &&
712            "regions with multiple blocks not supported");
713     Block *beforeBody = &whileOp.getBefore().front();
714     assert(whileOp.getAfter().getBlocks().size() == 1 &&
715            "regions with multiple blocks not supported");
716     Block *afterBody = &whileOp.getAfter().front();
717 
718     // Indices of all bbArgs that have tensor type. These are the ones that
719     // are bufferized. The "before" and "after" regions may have different args.
720     DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits());
721     DenseSet<int64_t> indicesAfter =
722         getTensorIndices(whileOp.getAfterArguments());
723 
724     // The new memref init_args of the loop.
725     SmallVector<Value> initArgs =
726         getBuffers(rewriter, whileOp->getOpOperands(), options);
727 
728     // The result types of a WhileOp are the same as the "after" bbArg types.
729     SmallVector<Type> argsTypesAfter = llvm::to_vector(
730         llvm::map_range(whileOp.getAfterArguments(), [&](BlockArgument bbArg) {
731           return getBufferType(bbArg, options).cast<Type>();
732         }));
733 
734     // Construct a new scf.while op with memref instead of tensor values.
735     ValueRange argsRangeBefore(initArgs);
736     TypeRange argsTypesBefore(argsRangeBefore);
737     auto newWhileOp = rewriter.create<scf::WhileOp>(whileOp.getLoc(),
738                                                     argsTypesAfter, initArgs);
739 
740     // Add before/after regions to the new op.
741     SmallVector<Location> bbArgLocsBefore(initArgs.size(), whileOp.getLoc());
742     SmallVector<Location> bbArgLocsAfter(argsTypesAfter.size(),
743                                          whileOp.getLoc());
744     Block *newBeforeBody = &newWhileOp.getBefore().emplaceBlock();
745     newWhileOp.getBefore().addArguments(argsTypesBefore, bbArgLocsBefore);
746     Block *newAfterBody = &newWhileOp.getAfter().emplaceBlock();
747     newWhileOp.getAfter().addArguments(argsTypesAfter, bbArgLocsAfter);
748 
749     // Set up new iter_args and move the loop condition block to the new op.
750     // The old block uses tensors, so wrap the (memref) bbArgs of the new block
751     // in ToTensorOps.
752     rewriter.setInsertionPointToStart(newBeforeBody);
753     SmallVector<Value> newBeforeArgs = getBbArgReplacements(
754         rewriter, newWhileOp.getBeforeArguments(), indicesBefore);
755     rewriter.mergeBlocks(beforeBody, newBeforeBody, newBeforeArgs);
756 
757     // Update scf.condition of new loop.
758     auto newConditionOp = newWhileOp.getConditionOp();
759     rewriter.setInsertionPoint(newConditionOp);
760     // Only equivalent buffers or new buffer allocations may be yielded to the
761     // "after" region.
762     // TODO: This could be relaxed for better bufferization results.
763     SmallVector<Value> newConditionArgs =
764         getYieldedValues(rewriter, newConditionOp.getArgs(), argsTypesAfter,
765                          indicesAfter, options);
766     newConditionOp.getArgsMutable().assign(newConditionArgs);
767 
768     // Set up new iter_args and move the loop body block to the new op.
769     // The old block uses tensors, so wrap the (memref) bbArgs of the new block
770     // in ToTensorOps.
771     rewriter.setInsertionPointToStart(newAfterBody);
772     SmallVector<Value> newAfterArgs = getBbArgReplacements(
773         rewriter, newWhileOp.getAfterArguments(), indicesAfter);
774     rewriter.mergeBlocks(afterBody, newAfterBody, newAfterArgs);
775 
776     // Update scf.yield of the new loop.
777     auto newYieldOp = newWhileOp.getYieldOp();
778     rewriter.setInsertionPoint(newYieldOp);
779     // Only equivalent buffers or new buffer allocations may be yielded to the
780     // "before" region.
781     // TODO: This could be relaxed for better bufferization results.
782     SmallVector<Value> newYieldValues =
783         getYieldedValues(rewriter, newYieldOp.getResults(), argsTypesBefore,
784                          indicesBefore, options);
785     newYieldOp.getResultsMutable().assign(newYieldValues);
786 
787     // Replace loop results.
788     replaceOpWithBufferizedValues(rewriter, op, newWhileOp->getResults());
789 
790     return success();
791   }
792 
793   /// Assert that yielded values of an scf.while op are equivalent to their
794   /// corresponding bbArgs. In that case, the buffer relations of the
795   /// corresponding OpResults are "Equivalent".
796   ///
797   /// If this is not the case, allocs+copies are inserted and yielded from
798   /// the loop. This could be a performance problem, so it must be explicitly
799   /// activated with `alloc-return-allocs`.
800   ///
801   /// Not: In contrast to scf::ForOp, scf::WhileOp has two regions and the
802   /// equivalence condition must be checked for both.
803   LogicalResult verifyAnalysis(Operation *op,
804                                const AnalysisState &state) const {
805     auto whileOp = cast<scf::WhileOp>(op);
806     const auto &options =
807         static_cast<const OneShotBufferizationOptions &>(state.getOptions());
808     if (options.allowReturnAllocs)
809       return success();
810 
811     auto conditionOp = whileOp.getConditionOp();
812     for (const auto &it : llvm::enumerate(conditionOp.getArgs())) {
813       if (!it.value().getType().isa<TensorType>())
814         continue;
815       if (!state.areEquivalentBufferizedValues(
816               it.value(), conditionOp->getBlock()->getArgument(it.index())))
817         return conditionOp->emitError()
818                << "Condition arg #" << it.index()
819                << " is not equivalent to the corresponding iter bbArg";
820     }
821 
822     auto yieldOp = whileOp.getYieldOp();
823     for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
824       if (!it.value().getType().isa<TensorType>())
825         continue;
826       if (!state.areEquivalentBufferizedValues(
827               it.value(), yieldOp->getBlock()->getArgument(it.index())))
828         return yieldOp->emitError()
829                << "Yield operand #" << it.index()
830                << " is not equivalent to the corresponding iter bbArg";
831     }
832 
833     return success();
834   }
835 };
836 
837 /// Bufferization of scf.yield. Bufferized as part of their enclosing ops, so
838 /// this is for analysis only.
839 struct YieldOpInterface
840     : public BufferizableOpInterface::ExternalModel<YieldOpInterface,
841                                                     scf::YieldOp> {
842   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
843                               const AnalysisState &state) const {
844     return true;
845   }
846 
847   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
848                                const AnalysisState &state) const {
849     return false;
850   }
851 
852   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
853                                             const AnalysisState &state) const {
854     if (isa<scf::IfOp>(op->getParentOp()))
855       return {op->getParentOp()->getResult(opOperand.getOperandNumber())};
856     if (isa<scf::ExecuteRegionOp>(op->getParentOp()))
857       return {op->getParentOp()->getResult(opOperand.getOperandNumber())};
858     return {};
859   }
860 
861   bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
862                             const AnalysisState &state) const {
863     // Yield operands always bufferize inplace. Otherwise, an alloc + copy
864     // may be generated inside the block. We should not return/yield allocations
865     // when possible.
866     return true;
867   }
868 
869   LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
870                           const BufferizationOptions &options) const {
871     auto yieldOp = cast<scf::YieldOp>(op);
872     if (!isa<scf::ExecuteRegionOp, scf::IfOp, scf::ForOp, scf::WhileOp>(
873             yieldOp->getParentOp()))
874       return yieldOp->emitError("unsupported scf::YieldOp parent");
875     return success();
876   }
877 };
878 
879 using tensor::ExtractSliceOp;
880 
881 /// Return the destinations that an ForeachThreadOp is inserting into. One per
882 /// ParallelInsertSliceOp.
883 static SmallVector<OpOperand *>
884 getInsertionDest(ForeachThreadOp foreachThreadOp) {
885   PerformConcurrentlyOp terminator = foreachThreadOp.getTerminator();
886   SmallVector<OpOperand *> result;
887   terminator.walk([&](ParallelInsertSliceOp insertOp) {
888     result.push_back(&insertOp->getOpOperand(1) /*dest*/);
889   });
890   return result;
891 }
892 
893 /// Bufferization of ForeachThreadOp. This also bufferizes the terminator of the
894 /// region. There are op interfaces for the terminators (PerformConcurrentlyOp
895 /// and ParallelInsertSliceOp), but these are only used during analysis. Not
896 /// for bufferization.
897 struct ForeachThreadOpInterface
898     : public BufferizableOpInterface::ExternalModel<ForeachThreadOpInterface,
899                                                     ForeachThreadOp> {
900   SmallVector<OpOperand *>
901   getAliasingOpOperand(Operation *op, OpResult opResult,
902                        const AnalysisState &state) const {
903     // Get OpOperand (dest) from corresponding ParallelInsertSliceOp.
904     auto foreachThreadOp = cast<ForeachThreadOp>(op);
905     return {getInsertionDest(foreachThreadOp)[opResult.getResultNumber()]};
906   }
907 
908   bool isMemoryWrite(Operation *op, OpResult opResult,
909                      const AnalysisState &state) const {
910     // This op is a memory write. Stop lookup here to avoid finding false
911     // conflicts involving this op and one of the ops in the region. This is
912     // similar to how scf.if ops are analyzed.
913     return true;
914   }
915 
916   BufferRelation bufferRelation(Operation *op, OpResult opResult,
917                                 const AnalysisState &state) const {
918     return BufferRelation::Equivalent;
919   }
920 
921   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
922                                  const AnalysisState &state) const {
923     auto bufferizableOp = cast<BufferizableOpInterface>(op);
924     if (failed(bufferizableOp.resolveTensorOpOperandConflicts(rewriter, state)))
925       return failure();
926 
927     OpBuilder::InsertionGuard g(rewriter);
928     auto foreachThreadOp = cast<ForeachThreadOp>(op);
929     for (OpResult opResult : foreachThreadOp->getOpResults()) {
930       SmallVector<OpOperand *> destOperands =
931           state.getAliasingOpOperand(opResult);
932       assert(destOperands.size() == 1 &&
933              "expected exactly one aliasing OpOperand");
934       assert(isa<ParallelInsertSliceOp>(destOperands.front()->getOwner()) &&
935              "expected ParallelInsertSliceOp");
936 
937       // Nothing to do if there is no conflict.
938       if (state.isInPlace(*destOperands.front()))
939         continue;
940 
941       // Create AllocTensorOp.
942       bool isYielded = state.isTensorYielded(opResult);
943       auto resultType = opResult.getType().cast<RankedTensorType>();
944       Value alloc = rewriter.create<bufferization::AllocTensorOp>(
945           op->getLoc(), resultType, /*dynamicDims=*/ValueRange(),
946           /*copy=*/destOperands.front()->get(),
947           /*escape=*/isYielded);
948 
949       // Update terminator operand.
950       rewriter.updateRootInPlace(destOperands.front()->getOwner(),
951                                  [&]() { destOperands.front()->set(alloc); });
952     }
953 
954     return success();
955   }
956 
957   LogicalResult bufferize(Operation *op, RewriterBase &b,
958                           const BufferizationOptions &options) const {
959     OpBuilder::InsertionGuard g(b);
960     auto foreachThreadOp = cast<ForeachThreadOp>(op);
961 
962     // Gather new results of the ForeachThreadOp.
963     SmallVector<Value> newResults;
964     for (OpResult opResult : foreachThreadOp->getOpResults()) {
965       OpOperand *insertDest =
966           getInsertionDest(foreachThreadOp)[opResult.getResultNumber()];
967       // Insert copies right before the PerformConcurrentlyOp terminator. They
968       // should not be inside terminator (which would be the default insertion
969       // point).
970       Value buffer = getBuffer(b, insertDest->get(), options);
971       newResults.push_back(buffer);
972     }
973 
974     // Create new ForeachThreadOp without any results and drop the automatically
975     // introduced terminator.
976     TypeRange newResultTypes;
977     auto newForeachThreadOp =
978         b.create<ForeachThreadOp>(foreachThreadOp.getLoc(), newResultTypes,
979                                   foreachThreadOp.getNumThreads());
980     newForeachThreadOp.getBody()->getTerminator()->erase();
981 
982     // Move over block contents of the old op.
983     b.mergeBlocks(foreachThreadOp.getBody(), newForeachThreadOp.getBody(),
984                   {newForeachThreadOp.getBody()->getArguments()});
985 
986     // Bufferize terminator.
987     auto performConcurrentlyOp = cast<PerformConcurrentlyOp>(
988         newForeachThreadOp.getBody()->getTerminator());
989     b.setInsertionPoint(performConcurrentlyOp);
990     unsigned resultCounter = 0;
991     WalkResult walkResult =
992         performConcurrentlyOp.walk([&](ParallelInsertSliceOp insertOp) {
993           Location loc = insertOp.getLoc();
994           Type srcType = getMemRefType(
995               insertOp.getSource().getType().cast<RankedTensorType>(), options);
996           // ParallelInsertSliceOp bufferizes to a copy.
997           auto srcMemref = b.create<bufferization::ToMemrefOp>(
998               loc, srcType, insertOp.getSource());
999           Value destMemref = newResults[resultCounter++];
1000           Value subview = b.create<memref::SubViewOp>(
1001               loc, destMemref, insertOp.getMixedOffsets(),
1002               insertOp.getMixedSizes(), insertOp.getMixedStrides());
1003           // This memcpy will fold away if everything bufferizes in-place.
1004           if (failed(options.createMemCpy(b, insertOp.getLoc(), srcMemref,
1005                                           subview)))
1006             return WalkResult::interrupt();
1007           b.eraseOp(insertOp);
1008           return WalkResult::advance();
1009         });
1010     if (walkResult.wasInterrupted())
1011       return failure();
1012 
1013     // Replace the op.
1014     replaceOpWithBufferizedValues(b, op, newResults);
1015 
1016     return success();
1017   }
1018 };
1019 
1020 /// Nothing to do for PerformConcurrentlyOp.
1021 struct PerformConcurrentlyOpInterface
1022     : public BufferizableOpInterface::ExternalModel<
1023           PerformConcurrentlyOpInterface, PerformConcurrentlyOp> {
1024   LogicalResult bufferize(Operation *op, RewriterBase &b,
1025                           const BufferizationOptions &options) const {
1026     llvm_unreachable("op does not have any tensor OpOperands / OpResults");
1027     return failure();
1028   }
1029 };
1030 
1031 /// Return true if the (ExtractSliceOp, ParallelInsertSliceOp) pair match (i.e.
1032 /// equivalent operand / result and same offset/sizes/strides specification).
1033 static bool areEquivalentExtractSliceOps(const AnalysisState &state,
1034                                          ExtractSliceOp st,
1035                                          ParallelInsertSliceOp sti) {
1036   if (!st || !sti)
1037     return false;
1038   if (st != sti &&
1039       !state.areEquivalentBufferizedValues(st.getSource(), sti.getDest()))
1040     return false;
1041   if (!sameOffsetsSizesAndStrides(st, sti, isEqualConstantIntOrValue))
1042     return false;
1043   return true;
1044 }
1045 
1046 /// Return true if `value` is originating from an ExtractSliceOp that matches
1047 /// the given InsertSliceOp.
1048 static bool hasMatchingExtractSliceOp(const AnalysisState &state, Value value,
1049                                       ParallelInsertSliceOp insertOp) {
1050   auto condition = [&](Value val) {
1051     if (auto extractOp = val.getDefiningOp<ExtractSliceOp>())
1052       if (areEquivalentExtractSliceOps(state, extractOp, insertOp))
1053         return true;
1054     return false;
1055   };
1056 
1057   return llvm::all_of(state.findValueInReverseUseDefChain(value, condition),
1058                       condition);
1059 }
1060 
1061 /// Analysis of ParallelInsertSliceOp.
1062 struct ParallelInsertSliceOpInterface
1063     : public BufferizableOpInterface::ExternalModel<
1064           ParallelInsertSliceOpInterface, ParallelInsertSliceOp> {
1065   SmallVector<OpResult> getAliasingOpResult(Operation *op, OpOperand &opOperand,
1066                                             const AnalysisState &state) const {
1067     if (&opOperand != &op->getOpOperand(1) /*dest*/)
1068       return {};
1069 
1070     // ParallelInsertSliceOp itself has no results. Tensors are returned via
1071     // the parent op.
1072     auto foreachThreadOp = op->getParentOfType<ForeachThreadOp>();
1073     assert(foreachThreadOp &&
1074            "could not find valid owner of parallel_insert_slice");
1075 
1076     // The i-th ParallelInsertSliceOp result is returned via the i-th OpResult
1077     // of the parent ForeachThreadOp.
1078     Block *block = op->getBlock();
1079     unsigned int opIdx = 0;
1080     for (ParallelInsertSliceOp insertOp :
1081          block->getOps<ParallelInsertSliceOp>()) {
1082       if (insertOp.getOperation() == op)
1083         break;
1084       ++opIdx;
1085     }
1086     assert(opIdx < foreachThreadOp->getNumResults() &&
1087            "could not find op inside terminator op");
1088 
1089     return {foreachThreadOp->getResult(opIdx)};
1090   }
1091 
1092   bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1093                               const AnalysisState &state) const {
1094     return true;
1095   }
1096 
1097   bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1098                                const AnalysisState &state) const {
1099     return &opOperand == &op->getOpOperand(1) /*dest*/;
1100   }
1101 
1102   BufferRelation bufferRelation(Operation *op, OpResult opResult,
1103                                 const AnalysisState &state) const {
1104     return BufferRelation::Equivalent;
1105   }
1106 
1107   LogicalResult resolveConflicts(Operation *op, RewriterBase &rewriter,
1108                                  const AnalysisState &state) const {
1109     return success();
1110   }
1111 
1112   LogicalResult bufferize(Operation *op, RewriterBase &b,
1113                           const BufferizationOptions &options) const {
1114     // Will be bufferized as part of ForeachThreadOp.
1115     return failure();
1116   }
1117 
1118   // TODO: This is copied from TensorInterfaceImpl.cpp. Find a way to share
1119   // the code.
1120   bool isNotConflicting(Operation *op, OpOperand *uRead,
1121                         OpOperand *uConflictingWrite,
1122                         const AnalysisState &state) const {
1123     Operation *readingOp = uRead->getOwner();
1124     Operation *conflictingWritingOp = uConflictingWrite->getOwner();
1125 
1126     // Special rules for matching ExtractSliceOp/InsertSliceOp pairs. If
1127     // uRead is an InsertSliceOp...
1128     if (auto insertSliceOp = dyn_cast<ParallelInsertSliceOp>(readingOp)) {
1129       // As an example, consider the following IR.
1130       //
1131       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
1132       // %1 = linalg.fill %cst, %0 {inplace= [true] }
1133       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
1134       //     {inplace= [true] }
1135 
1136       // TODO: Use insertSliceOp.getDestOpOperand etc. when available.
1137       if (uRead == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1138           hasMatchingExtractSliceOp(state, uConflictingWrite->get(),
1139                                     insertSliceOp))
1140         // Case 1: The main insight is that InsertSliceOp reads only part of
1141         // the destination tensor. The overwritten area is not read. If
1142         // uConflictingWrite writes into exactly the memory location that is
1143         // being read by uRead, this is not a conflict.
1144         //
1145         // In the above example:
1146         // uRead             = OpOperand 1 (%t) of tensor.insert_slice
1147         // uConflictingWrite = OpOperand 1 (%0) of linalg.fill
1148         //
1149         // The read of %t does not conflict with the write of the FillOp
1150         // (same aliases!) because the area that the FillOp operates on is
1151         // exactly the one that is *not* read via %t.
1152         return true;
1153 
1154       if (uRead == &insertSliceOp->getOpOperand(0) /*source*/ &&
1155           uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1156           hasMatchingExtractSliceOp(state, uRead->get(), insertSliceOp))
1157         // Case 2: The read of the source tensor and the write to the dest
1158         // tensor via an InsertSliceOp is not a conflict if the read is
1159         // reading exactly that part of an equivalent tensor that the
1160         // InsertSliceOp is writing.
1161         //
1162         // In the above example:
1163         // uRead             = OpOperand 0 (%1) of tensor.insert_slice
1164         // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
1165         return true;
1166     }
1167 
1168     // If uConflictingWrite is an InsertSliceOp...
1169     if (auto insertSliceOp =
1170             dyn_cast<ParallelInsertSliceOp>(conflictingWritingOp))
1171       // As an example, consider the following IR.
1172       //
1173       // %0 = tensor.extract_slice %t[%a, %b][%c, %d][1, 1] {inplace = [true] }
1174       // %1 = linalg.fill %cst, %0 {inplace= [true] }
1175       // %2 = tensor.insert_slice %1 into %t[%a, %b][%c, %d][1, 1]
1176       //     {inplace= [true] }
1177       // %3 = vector.transfer_read %1, %cst
1178       //
1179       // In the above example:
1180       // uRead             = OpOperand 0 (%1) of vector.transfer_read
1181       // uConflictingWrite = OpOperand 1 (%t) of tensor.insert_slice
1182       // lastWrite         = %1
1183       //
1184       // This is not a conflict because the InsertSliceOp overwrites the
1185       // memory segment of %1 with the exact same data. (Effectively, there
1186       // is no memory write here.)
1187       if (uConflictingWrite == &insertSliceOp->getOpOperand(1) /*dest*/ &&
1188           state.areEquivalentBufferizedValues(uRead->get(),
1189                                               insertSliceOp.getSource()) &&
1190           hasMatchingExtractSliceOp(state, insertSliceOp.getSource(),
1191                                     insertSliceOp))
1192         return true;
1193 
1194     return false;
1195   }
1196 };
1197 
1198 } // namespace
1199 } // namespace scf
1200 } // namespace mlir
1201 
1202 void mlir::scf::registerBufferizableOpInterfaceExternalModels(
1203     DialectRegistry &registry) {
1204   registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) {
1205     ExecuteRegionOp::attachInterface<ExecuteRegionOpInterface>(*ctx);
1206     ForOp::attachInterface<ForOpInterface>(*ctx);
1207     IfOp::attachInterface<IfOpInterface>(*ctx);
1208     ForeachThreadOp::attachInterface<ForeachThreadOpInterface>(*ctx);
1209     ParallelInsertSliceOp::attachInterface<ParallelInsertSliceOpInterface>(
1210         *ctx);
1211     PerformConcurrentlyOp::attachInterface<PerformConcurrentlyOpInterface>(
1212         *ctx);
1213     WhileOp::attachInterface<WhileOpInterface>(*ctx);
1214     YieldOp::attachInterface<YieldOpInterface>(*ctx);
1215   });
1216 }
1217