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