MLIR 24.0.0git
BufferizableOpInterfaceImpl.cpp
Go to the documentation of this file.
1//===- BufferizableOpInterfaceImpl.cpp - Impl. of BufferizableOpInterface -===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
19#include "mlir/IR/Dialect.h"
20#include "mlir/IR/Operation.h"
22#include "llvm/ADT/SmallVectorExtras.h"
23
24using namespace mlir;
25using namespace mlir::bufferization;
26using namespace mlir::scf;
27
28namespace mlir {
29namespace scf {
30namespace {
31
32/// Helper function for loop bufferization. Return "true" if the given value
33/// is guaranteed to not alias with an external tensor apart from values in
34/// `exceptions`. A value is external if it is defined outside of the given
35/// region or if it is an entry block argument of the region.
36static bool doesNotAliasExternalValue(Value value, Region *region,
37 ValueRange exceptions,
38 const OneShotAnalysisState &state) {
39 assert(region->hasOneBlock() && "expected region with single block");
40 bool result = true;
41 state.applyOnAliases(value, [&](Value alias) {
42 if (llvm::is_contained(exceptions, alias))
43 return;
44 Region *aliasRegion = alias.getParentRegion();
45 if (isa<BlockArgument>(alias) && !region->isProperAncestor(aliasRegion))
46 result = false;
47 if (isa<OpResult>(alias) && !region->isAncestor(aliasRegion))
48 result = false;
49 });
50 return result;
51}
52
53/// Bufferization of scf.condition.
54struct ConditionOpInterface
55 : public BufferizableOpInterface::ExternalModel<ConditionOpInterface,
56 scf::ConditionOp> {
57 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
58 const AnalysisState &state) const {
59 return true;
60 }
61
62 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
63 const AnalysisState &state) const {
64 return false;
65 }
66
67 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
68 const AnalysisState &state) const {
69 return {};
70 }
71
72 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
73 const AnalysisState &state) const {
74 // Condition operands always bufferize inplace. Otherwise, an alloc + copy
75 // may be generated inside the block. We should not return/yield allocations
76 // when possible.
77 return true;
78 }
79
80 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
81 const BufferizationOptions &options,
82 BufferizationState &state) const {
83 auto conditionOp = cast<scf::ConditionOp>(op);
84 auto whileOp = cast<scf::WhileOp>(conditionOp->getParentOp());
85
86 SmallVector<Value> newArgs;
87 for (const auto &it : llvm::enumerate(conditionOp.getArgs())) {
88 Value value = it.value();
89 if (isa<TensorLikeType>(value.getType())) {
90 FailureOr<Value> maybeBuffer =
91 getBuffer(rewriter, value, options, state);
92 if (failed(maybeBuffer))
93 return failure();
94 FailureOr<BufferLikeType> resultType = bufferization::getBufferType(
95 whileOp.getAfterArguments()[it.index()], options, state);
96 if (failed(resultType))
97 return failure();
98 FailureOr<Value> buffer =
99 castBuffer(rewriter, maybeBuffer->getLoc(), *maybeBuffer,
100 *resultType, options);
101 if (failed(buffer))
102 return failure();
103 newArgs.push_back(*buffer);
104 } else {
105 newArgs.push_back(value);
106 }
107 }
108
109 replaceOpWithNewBufferizedOp<scf::ConditionOp>(
110 rewriter, op, conditionOp.getCondition(), newArgs);
111 return success();
112 }
113};
114
115/// Return the unique scf.yield op. If there are multiple or no scf.yield ops,
116/// return an empty op.
117static scf::YieldOp getUniqueYieldOp(scf::ExecuteRegionOp executeRegionOp) {
118 scf::YieldOp result;
119 for (Block &block : executeRegionOp.getRegion()) {
120 if (auto yieldOp = dyn_cast<scf::YieldOp>(block.getTerminator())) {
121 if (result)
122 return {};
123 result = yieldOp;
124 }
125 }
126 return result;
127}
128
129/// Bufferization of scf.execute_region. Can be analyzed, but bufferization not
130/// fully implemented at the moment.
131struct ExecuteRegionOpInterface
132 : public OpWithUnstructuredControlFlowBufferizableOpInterfaceExternalModel<
133 ExecuteRegionOpInterface, scf::ExecuteRegionOp> {
134
135 static bool supportsUnstructuredControlFlow() { return true; }
136
137 bool isWritable(Operation *op, Value value,
138 const AnalysisState &state) const {
139 return true;
140 }
141
142 LogicalResult verifyAnalysis(Operation *op,
143 const AnalysisState &state) const {
144 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
145 // TODO: scf.execute_region with multiple yields are not supported.
146 if (!getUniqueYieldOp(executeRegionOp))
147 return op->emitOpError("op without unique scf.yield is not supported");
148 return success();
149 }
150
151 AliasingOpOperandList
152 getAliasingOpOperands(Operation *op, Value value,
153 const AnalysisState &state) const {
154 if (auto bbArg = dyn_cast<BlockArgument>(value))
155 return getAliasingBranchOpOperands(op, bbArg, state);
156
157 // ExecuteRegionOps do not have tensor OpOperands. The yielded value can be
158 // any SSA value that is in scope. To allow for use-def chain traversal
159 // through ExecuteRegionOps in the analysis, the corresponding yield value
160 // is considered to be aliasing with the result.
161 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
162 auto it = llvm::find(op->getOpResults(), value);
163 assert(it != op->getOpResults().end() && "invalid value");
164 size_t resultNum = std::distance(op->getOpResults().begin(), it);
165 auto yieldOp = getUniqueYieldOp(executeRegionOp);
166 // Note: If there is no unique scf.yield op, `verifyAnalysis` will fail.
167 if (!yieldOp)
168 return {};
169 return {{&yieldOp->getOpOperand(resultNum), BufferRelation::Equivalent}};
170 }
171
172 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
173 const BufferizationOptions &options,
174 BufferizationState &state) const {
175 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
176 auto yieldOp = getUniqueYieldOp(executeRegionOp);
177 TypeRange newResultTypes(yieldOp.getResults());
178
179 // Create new op and move over region.
180 auto newOp = scf::ExecuteRegionOp::create(
181 rewriter, op->getLoc(), newResultTypes, executeRegionOp.getNoInline());
182 newOp.getRegion().takeBody(executeRegionOp.getRegion());
183
184 // Bufferize every block.
185 for (Block &block : newOp.getRegion())
187 options, state)))
188 return failure();
189
190 // Update all uses of the old op.
191 rewriter.setInsertionPointAfter(newOp);
192 SmallVector<Value> newResults;
193 for (const auto &it : llvm::enumerate(executeRegionOp->getResultTypes())) {
194 if (isa<TensorLikeType>(it.value())) {
195 newResults.push_back(bufferization::ToTensorOp::create(
196 rewriter, executeRegionOp.getLoc(), it.value(),
197 newOp->getResult(it.index())));
198 } else {
199 newResults.push_back(newOp->getResult(it.index()));
200 }
201 }
202
203 // Replace old op.
204 rewriter.replaceOp(executeRegionOp, newResults);
205
206 return success();
207 }
208};
209
210/// Bufferization of scf.if. Replace with a new scf.if that yields memrefs.
211struct IfOpInterface
212 : public BufferizableOpInterface::ExternalModel<IfOpInterface, scf::IfOp> {
213 AliasingOpOperandList
214 getAliasingOpOperands(Operation *op, Value value,
215 const AnalysisState &state) const {
216 // IfOps do not have tensor OpOperands. The yielded value can be any SSA
217 // value that is in scope. To allow for use-def chain traversal through
218 // IfOps in the analysis, both corresponding yield values from the then/else
219 // branches are considered to be aliasing with the result.
220 auto ifOp = cast<scf::IfOp>(op);
221 size_t resultNum = std::distance(op->getOpResults().begin(),
222 llvm::find(op->getOpResults(), value));
223 OpOperand *thenOperand = &ifOp.thenYield()->getOpOperand(resultNum);
224 OpOperand *elseOperand = &ifOp.elseYield()->getOpOperand(resultNum);
225 return {{thenOperand, BufferRelation::Equivalent, /*isDefinite=*/false},
226 {elseOperand, BufferRelation::Equivalent, /*isDefinite=*/false}};
227 }
228
229 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
230 const BufferizationOptions &options,
231 BufferizationState &state) const {
232 OpBuilder::InsertionGuard g(rewriter);
233 auto ifOp = cast<scf::IfOp>(op);
234
235 // Compute bufferized result types.
236 SmallVector<Type> newTypes;
237 for (Value result : ifOp.getResults()) {
238 if (!isa<TensorLikeType>(result.getType())) {
239 newTypes.push_back(result.getType());
240 continue;
241 }
242 auto bufferType = bufferization::getBufferType(result, options, state);
243 if (failed(bufferType))
244 return failure();
245 newTypes.push_back(*bufferType);
246 }
247
248 // Create new op.
249 rewriter.setInsertionPoint(ifOp);
250 auto newIfOp = scf::IfOp::create(rewriter, ifOp.getLoc(), newTypes,
251 ifOp.getCondition(),
252 /*withElseRegion=*/true);
253
254 // Move over then/else blocks.
255 rewriter.mergeBlocks(ifOp.thenBlock(), newIfOp.thenBlock());
256 rewriter.mergeBlocks(ifOp.elseBlock(), newIfOp.elseBlock());
257
258 // Replace op results.
259 replaceOpWithBufferizedValues(rewriter, op, newIfOp->getResults());
260
261 return success();
262 }
263
264 FailureOr<BufferLikeType>
265 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
266 const BufferizationState &state,
267 SmallVector<Value> &invocationStack) const {
268 auto ifOp = cast<scf::IfOp>(op);
269 auto thenYieldOp = cast<scf::YieldOp>(ifOp.thenBlock()->getTerminator());
270 auto elseYieldOp = cast<scf::YieldOp>(ifOp.elseBlock()->getTerminator());
271 assert(value.getDefiningOp() == op && "invalid valid");
272
273 // Determine buffer types of the true/false branches.
274 auto opResult = cast<OpResult>(value);
275 auto thenValue = thenYieldOp.getOperand(opResult.getResultNumber());
276 auto elseValue = elseYieldOp.getOperand(opResult.getResultNumber());
277 BufferLikeType thenBufferType, elseBufferType;
278 if (isa<BufferLikeType>(thenValue.getType())) {
279 // True branch was already bufferized.
280 thenBufferType = cast<BufferLikeType>(thenValue.getType());
281 } else {
282 auto maybeBufferType = bufferization::getBufferType(
283 thenValue, options, state, invocationStack);
284 if (failed(maybeBufferType))
285 return failure();
286 thenBufferType = *maybeBufferType;
287 }
288 if (isa<BufferLikeType>(elseValue.getType())) {
289 // False branch was already bufferized.
290 elseBufferType = cast<BufferLikeType>(elseValue.getType());
291 } else {
292 auto maybeBufferType = bufferization::getBufferType(
293 elseValue, options, state, invocationStack);
294 if (failed(maybeBufferType))
295 return failure();
296 elseBufferType = *maybeBufferType;
297 }
298
299 // Best case: Both branches have the exact same buffer type.
300 if (thenBufferType == elseBufferType)
301 return cast<BufferLikeType>(thenBufferType);
302
303 auto reconciled = options.reconcileBufferTypeMismatchFn(
304 thenBufferType, elseBufferType, options);
305 if (failed(reconciled))
306 return op->emitError("incompatible buffer types on then/else branches");
307
308 return *reconciled;
309 }
310};
311
312/// Bufferization of scf.index_switch. Replace with a new scf.index_switch that
313/// yields memrefs.
314struct IndexSwitchOpInterface
315 : public BufferizableOpInterface::ExternalModel<IndexSwitchOpInterface,
316 scf::IndexSwitchOp> {
317 AliasingOpOperandList
318 getAliasingOpOperands(Operation *op, Value value,
319 const AnalysisState &state) const {
320 // IndexSwitchOps do not have tensor OpOperands. The yielded value can be
321 // any SSA. This is similar to IfOps.
322 auto switchOp = cast<scf::IndexSwitchOp>(op);
323 int64_t resultNum = cast<OpResult>(value).getResultNumber();
324 AliasingOpOperandList result;
325 for (int64_t i = 0, numCases = switchOp.getNumCases(); i < numCases; ++i) {
326 auto yieldOp =
327 cast<scf::YieldOp>(switchOp.getCaseBlock(i).getTerminator());
328 result.addAlias(AliasingOpOperand(&yieldOp->getOpOperand(resultNum),
329 BufferRelation::Equivalent,
330 /*isDefinite=*/false));
331 }
332 auto defaultYieldOp =
333 cast<scf::YieldOp>(switchOp.getDefaultBlock().getTerminator());
334 result.addAlias(AliasingOpOperand(&defaultYieldOp->getOpOperand(resultNum),
335 BufferRelation::Equivalent,
336 /*isDefinite=*/false));
337 return result;
338 }
339
340 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
341 const BufferizationOptions &options,
342 BufferizationState &state) const {
343 OpBuilder::InsertionGuard g(rewriter);
344 auto switchOp = cast<scf::IndexSwitchOp>(op);
345
346 // Compute bufferized result types.
347 SmallVector<Type> newTypes;
348 for (Value result : switchOp.getResults()) {
349 if (!isa<TensorLikeType>(result.getType())) {
350 newTypes.push_back(result.getType());
351 continue;
352 }
353 auto bufferType = bufferization::getBufferType(result, options, state);
354 if (failed(bufferType))
355 return failure();
356 newTypes.push_back(*bufferType);
357 }
358
359 // Create new op.
360 rewriter.setInsertionPoint(switchOp);
361 auto newSwitchOp = scf::IndexSwitchOp::create(
362 rewriter, switchOp.getLoc(), newTypes, switchOp.getArg(),
363 switchOp.getCases(), switchOp.getCases().size());
364
365 // Move over blocks.
366 for (auto [src, dest] :
367 llvm::zip(switchOp.getCaseRegions(), newSwitchOp.getCaseRegions()))
368 rewriter.inlineRegionBefore(src, dest, dest.begin());
369 rewriter.inlineRegionBefore(switchOp.getDefaultRegion(),
370 newSwitchOp.getDefaultRegion(),
371 newSwitchOp.getDefaultRegion().begin());
372
373 // Replace op results.
374 replaceOpWithBufferizedValues(rewriter, op, newSwitchOp->getResults());
375
376 return success();
377 }
378
379 FailureOr<BufferLikeType>
380 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
381 const BufferizationState &state,
382 SmallVector<Value> &invocationStack) const {
383 auto switchOp = cast<scf::IndexSwitchOp>(op);
384 assert(value.getDefiningOp() == op && "invalid value");
385 int64_t resultNum = cast<OpResult>(value).getResultNumber();
386
387 auto getYieldedBufferType = [&](Block &b) -> FailureOr<BufferLikeType> {
388 auto yieldOp = cast<scf::YieldOp>(b.getTerminator());
389 Value yieldedValue = yieldOp->getOperand(resultNum);
390 if (auto bufferType = dyn_cast<BufferLikeType>(yieldedValue.getType()))
391 return bufferType;
392 return bufferization::getBufferType(yieldedValue, options, state,
393 invocationStack);
394 };
395
396 // Compute buffer type of the default case.
397 auto maybeBufferType = getYieldedBufferType(switchOp.getDefaultBlock());
398 if (failed(maybeBufferType))
399 return failure();
400 BufferLikeType bufferType = *maybeBufferType;
401
402 // Compute buffer types of all other cases.
403 for (int64_t i = 0, numCases = switchOp.getNumCases(); i < numCases; ++i) {
404 auto yieldedBufferType = getYieldedBufferType(switchOp.getCaseBlock(i));
405 if (failed(yieldedBufferType))
406 return failure();
407
408 // Best case: Both branches have the exact same buffer type.
409 if (bufferType == *yieldedBufferType)
410 continue;
411
412 auto reconciled = options.reconcileBufferTypeMismatchFn(
413 bufferType, *yieldedBufferType, options);
414 if (failed(reconciled))
415 return op->emitError("incompatible buffer types on switch cases");
416 bufferType = *reconciled;
417 }
418
419 return cast<BufferLikeType>(bufferType);
420 }
421};
422
423/// Helper function for loop bufferization. Return the indices of all values
424/// that have a tensor type.
425static DenseSet<int64_t> getTensorIndices(ValueRange values) {
427 for (const auto &it : llvm::enumerate(values))
428 if (isa<TensorLikeType>(it.value().getType()))
429 result.insert(it.index());
430 return result;
431}
432
433/// Helper function for loop bufferization. Return the indices of all
434/// bbArg/yielded value pairs who's buffer relation is "Equivalent".
435DenseSet<int64_t> getEquivalentBuffers(Block::BlockArgListType bbArgs,
436 ValueRange yieldedValues,
437 const AnalysisState &state) {
438 unsigned int minSize = std::min(bbArgs.size(), yieldedValues.size());
440 for (unsigned int i = 0; i < minSize; ++i) {
441 if (!isa<TensorLikeType>(bbArgs[i].getType()) ||
442 !isa<TensorLikeType>(yieldedValues[i].getType()))
443 continue;
444 if (state.areEquivalentBufferizedValues(bbArgs[i], yieldedValues[i]))
445 result.insert(i);
446 }
447 return result;
448}
449
450/// Helper function for loop bufferization. Return the bufferized values of the
451/// given OpOperands. If an operand is not a tensor, return the original value.
452static FailureOr<SmallVector<Value>>
453getBuffers(RewriterBase &rewriter, const MutableOperandRange &operands,
454 const BufferizationOptions &options, BufferizationState &state) {
455 SmallVector<Value> result;
456 for (OpOperand &opOperand : operands) {
457 if (isa<TensorLikeType>(opOperand.get().getType())) {
458 FailureOr<Value> resultBuffer =
459 getBuffer(rewriter, opOperand.get(), options, state);
460 if (failed(resultBuffer))
461 return failure();
462 result.push_back(*resultBuffer);
463 } else {
464 result.push_back(opOperand.get());
465 }
466 }
467 return result;
468}
469
470/// Helper function for loop bufferization. Given a list of bbArgs of the new
471/// (bufferized) loop op, wrap the bufferized tensor args (now memrefs) into
472/// ToTensorOps, so that the block body can be moved over to the new op.
473static SmallVector<Value>
474getBbArgReplacements(RewriterBase &rewriter, Block::BlockArgListType bbArgs,
475 Block::BlockArgListType oldBbArgs,
476 const DenseSet<int64_t> &tensorIndices) {
477 SmallVector<Value> result;
478 for (const auto &it : llvm::enumerate(bbArgs)) {
479 size_t idx = it.index();
480 Value val = it.value();
481 if (tensorIndices.contains(idx)) {
482 result.push_back(
483 bufferization::ToTensorOp::create(rewriter, val.getLoc(),
484 oldBbArgs[idx].getType(), val)
485 .getResult());
486 } else {
487 result.push_back(val);
488 }
489 }
490 return result;
491}
492
493/// Compute the bufferized type of a loop iter_arg. This type must be equal to
494/// the bufferized type of the corresponding init_arg and the bufferized type
495/// of the corresponding yielded value.
496///
497/// This function uses bufferization::getBufferType to compute the bufferized
498/// type of the init_arg and of the yielded value. (The computation of the
499/// bufferized yielded value type usually requires computing the bufferized type
500/// of the iter_arg again; the implementation of getBufferType traces back the
501/// use-def chain of the given value and computes a buffer type along the way.)
502/// If both buffer types are equal, no casts are needed the computed buffer type
503/// can be used directly. Otherwise, the buffer types can only differ in their
504/// layout map and a cast must be inserted.
505static FailureOr<BufferLikeType> computeLoopRegionIterArgBufferType(
506 Operation *loopOp, BlockArgument iterArg, Value initArg, Value yieldedValue,
507 const BufferizationOptions &options, const BufferizationState &state,
508 SmallVector<Value> &invocationStack) {
509 // Determine the buffer type of the init_arg.
510 auto initArgBufferType =
511 bufferization::getBufferType(initArg, options, state, invocationStack);
512 if (failed(initArgBufferType))
513 return failure();
514
515 if (llvm::count(invocationStack, iterArg) >= 2) {
516 // If the iter_arg is already twice on the invocation stack, just take the
517 // type of the init_arg. This is to avoid infinite loops when calculating
518 // the buffer type. This will most likely result in computing a memref type
519 // with a fully dynamic layout map.
520
521 // Note: For more precise layout map computation, a fixpoint iteration could
522 // be done (i.e., re-computing the yielded buffer type until the bufferized
523 // iter_arg type no longer changes). This current implementation immediately
524 // switches to a fully dynamic layout map when a mismatch between bufferized
525 // init_arg type and bufferized yield value type is detected.
526 return *initArgBufferType;
527 }
528
529 // Compute the buffer type of the yielded value.
530 BufferLikeType yieldedValueBufferType;
531 if (auto bufferType = dyn_cast<BufferLikeType>(yieldedValue.getType())) {
532 // scf.yield was already bufferized.
533 yieldedValueBufferType = bufferType;
534 } else {
535 // Note: This typically triggers a recursive call for the buffer type of
536 // the iter_arg.
537 auto maybeBufferType = bufferization::getBufferType(yieldedValue, options,
538 state, invocationStack);
539 if (failed(maybeBufferType))
540 return failure();
541 yieldedValueBufferType = *maybeBufferType;
542 }
543
544 // If yielded type and init_arg type are the same, use that type directly.
545 if (*initArgBufferType == yieldedValueBufferType)
546 return yieldedValueBufferType;
547
548 // If there is a mismatch between the yielded buffer type and the init_arg
549 // buffer type, the buffer type must be reconciled.
550#ifndef NDEBUG
551 if (auto iterTensorType = dyn_cast<TensorLikeType>(iterArg.getType())) {
552 const auto emitOpError = [&]() { return loopOp->emitOpError(); };
553 assert(succeeded(iterTensorType.verifyCompatibleBufferType(
554 yieldedValueBufferType, emitOpError)) &&
555 "incompatible yielded type");
556 assert(succeeded(iterTensorType.verifyCompatibleBufferType(
557 *initArgBufferType, emitOpError)) &&
558 "incompatible init_arg type");
559 }
560#endif // NDEBUG
561
562 auto reconciled = options.reconcileBufferTypeMismatchFn(
563 *initArgBufferType, yieldedValueBufferType, options);
564 if (failed(reconciled)) {
565 return loopOp->emitError(
566 "init_arg and yielded value bufferize to incompatible buffer types");
567 }
568
569 return *reconciled;
570}
571
572/// Return `true` if the given loop may have 0 iterations.
573bool mayHaveZeroIterations(scf::ForOp forOp) {
574 std::optional<int64_t> lb = getConstantIntValue(forOp.getLowerBound());
575 std::optional<int64_t> ub = getConstantIntValue(forOp.getUpperBound());
576 if (!lb.has_value() || !ub.has_value())
577 return true;
578 return *ub <= *lb;
579}
580
581/// Bufferization of scf.for. Replace with a new scf.for that operates on
582/// memrefs.
583struct ForOpInterface
584 : public BufferizableOpInterface::ExternalModel<ForOpInterface,
585 scf::ForOp> {
586 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
587 const AnalysisState &state) const {
588 auto forOp = cast<scf::ForOp>(op);
589
590 // If the loop has zero iterations, the results of the op are their
591 // corresponding init_args, meaning that the init_args bufferize to a read.
592 if (mayHaveZeroIterations(forOp))
593 return true;
594
595 // scf::ForOp alone doesn't bufferize to a memory read, one of the uses of
596 // its matching bbArg may.
597 return state.isValueRead(forOp.getTiedLoopRegionIterArg(&opOperand));
598 }
599
600 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
601 const AnalysisState &state) const {
602 // Tensor iter_args of scf::ForOps are always considered as a write.
603 return true;
604 }
605
606 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
607 const AnalysisState &state) const {
608 auto forOp = cast<scf::ForOp>(op);
609 OpResult opResult = forOp.getTiedLoopResult(&opOperand);
610 BufferRelation relation = bufferRelation(op, opResult, state);
611 return {{opResult, relation,
612 /*isDefinite=*/relation == BufferRelation::Equivalent}};
613 }
614
615 BufferRelation bufferRelation(Operation *op, OpResult opResult,
616 const AnalysisState &state) const {
617 // ForOp results are equivalent to their corresponding init_args if the
618 // corresponding iter_args and yield values are equivalent.
619 auto forOp = cast<scf::ForOp>(op);
620 BlockArgument bbArg = forOp.getTiedLoopRegionIterArg(opResult);
621 bool equivalentYield = state.areEquivalentBufferizedValues(
622 bbArg, forOp.getTiedLoopYieldedValue(bbArg)->get());
623 return equivalentYield ? BufferRelation::Equivalent
624 : BufferRelation::Unknown;
625 }
626
627 bool isWritable(Operation *op, Value value,
628 const AnalysisState &state) const {
629 // Interestingly, scf::ForOp's bbArg can **always** be viewed
630 // inplace from the perspective of ops nested under:
631 // 1. Either the matching iter operand is not bufferized inplace and an
632 // alloc + optional copy makes the bbArg itself inplaceable.
633 // 2. Or the matching iter operand is bufferized inplace and bbArg just
634 // bufferizes to that too.
635 return true;
636 }
637
638 LogicalResult
639 resolveConflicts(Operation *op, RewriterBase &rewriter,
640 const AnalysisState &analysisState,
641 const BufferizationState &bufferizationState) const {
642 auto bufferizableOp = cast<BufferizableOpInterface>(op);
643 if (failed(bufferizableOp.resolveTensorOpOperandConflicts(
644 rewriter, analysisState, bufferizationState)))
645 return failure();
646
647 if (analysisState.getOptions().copyBeforeWrite)
648 return success();
649
650 // According to the `getAliasing...` implementations, a bufferized OpResult
651 // may alias only with the corresponding bufferized init_arg (or with a
652 // newly allocated buffer) and not with other buffers defined outside of the
653 // loop. I.e., the i-th OpResult may alias with the i-th init_arg;
654 // but not with any other OpOperand.
655 auto forOp = cast<scf::ForOp>(op);
656 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
657 OpBuilder::InsertionGuard g(rewriter);
658 rewriter.setInsertionPoint(yieldOp);
659
660 // Indices of all iter_args that have tensor type. These are the ones that
661 // are bufferized.
662 DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
663 // For every yielded value, does it alias with something defined outside of
664 // the loop?
665 SmallVector<Value> yieldValues;
666 for (const auto it : llvm::enumerate(yieldOp.getResults())) {
667 // Note: `state` is guaranteed to be a `OneShotAnalysisState`, but this
668 // type cannot be used in the signature of `resolveConflicts` because the
669 // op interface is in the "IR" build unit and the `OneShotAnalysisState`
670 // is defined in the "Transforms" build unit.
671 if (!indices.contains(it.index()) ||
672 doesNotAliasExternalValue(
673 it.value(), &forOp.getRegion(),
674 /*exceptions=*/forOp.getRegionIterArg(it.index()),
675 static_cast<const OneShotAnalysisState &>(analysisState))) {
676 yieldValues.push_back(it.value());
677 continue;
678 }
679 FailureOr<Value> alloc = allocateTensorForShapedValue(
680 rewriter, yieldOp.getLoc(), it.value(), analysisState.getOptions(),
681 bufferizationState);
682 if (failed(alloc))
683 return failure();
684 yieldValues.push_back(*alloc);
685 }
686
687 rewriter.modifyOpInPlace(
688 yieldOp, [&]() { yieldOp.getResultsMutable().assign(yieldValues); });
689 return success();
690 }
691
692 FailureOr<BufferLikeType>
693 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
694 const BufferizationState &state,
695 SmallVector<Value> &invocationStack) const {
696 auto forOp = cast<scf::ForOp>(op);
697 assert(getOwnerOfValue(value) == op && "invalid value");
698 assert(isa<TensorLikeType>(value.getType()) && "expected tensor type");
699
700 if (auto opResult = dyn_cast<OpResult>(value)) {
701 // The type of an OpResult must match the corresponding iter_arg type.
702 BlockArgument bbArg = forOp.getTiedLoopRegionIterArg(opResult);
703 return bufferization::getBufferType(bbArg, options, state,
704 invocationStack);
705 }
706
707 // Compute result/argument number.
708 BlockArgument bbArg = cast<BlockArgument>(value);
709 unsigned resultNum = forOp.getTiedLoopResult(bbArg).getResultNumber();
710
711 // Compute the bufferized type.
712 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
713 Value yieldedValue = yieldOp.getOperand(resultNum);
714 BlockArgument iterArg = forOp.getRegionIterArgs()[resultNum];
715 Value initArg = forOp.getInitArgs()[resultNum];
716 return computeLoopRegionIterArgBufferType(
717 op, iterArg, initArg, yieldedValue, options, state, invocationStack);
718 }
719
720 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
721 const BufferizationOptions &options,
722 BufferizationState &state) const {
723 auto forOp = cast<scf::ForOp>(op);
724 Block *oldLoopBody = forOp.getBody();
725
726 // Indices of all iter_args that have tensor type. These are the ones that
727 // are bufferized.
728 DenseSet<int64_t> indices = getTensorIndices(forOp.getInitArgs());
729
730 // The new memref init_args of the loop.
731 FailureOr<SmallVector<Value>> maybeInitArgs =
732 getBuffers(rewriter, forOp.getInitArgsMutable(), options, state);
733 if (failed(maybeInitArgs))
734 return failure();
735 SmallVector<Value> initArgs = *maybeInitArgs;
736
737 // Cast init_args if necessary.
738 SmallVector<Value> castedInitArgs;
739 for (const auto &it : llvm::enumerate(initArgs)) {
740 Value initArg = it.value();
741 Value result = forOp->getResult(it.index());
742 // If the type is not a tensor, bufferization doesn't need to touch it.
743 if (!isa<TensorLikeType>(result.getType())) {
744 castedInitArgs.push_back(initArg);
745 continue;
746 }
747 auto targetType = bufferization::getBufferType(result, options, state);
748 if (failed(targetType))
749 return failure();
750 FailureOr<Value> castedInitArg =
751 castBuffer(rewriter, initArg.getLoc(), initArg, *targetType, options);
752 if (failed(castedInitArg))
753 return failure();
754 castedInitArgs.push_back(*castedInitArg);
755 }
756
757 // Construct a new scf.for op with memref instead of tensor values.
758 auto newForOp = scf::ForOp::create(
759 rewriter, forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
760 forOp.getStep(), castedInitArgs, /*bodyBuilder=*/nullptr,
761 forOp.getUnsignedCmp());
762 newForOp->setDiscardableAttrs(
763 forOp->getDiscardableAttrDictionary().getValue());
764 Block *loopBody = newForOp.getBody();
765
766 // Set up new iter_args. The loop body uses tensors, so wrap the (memref)
767 // iter_args of the new loop in ToTensorOps.
768 rewriter.setInsertionPointToStart(loopBody);
769 SmallVector<Value> iterArgs =
770 getBbArgReplacements(rewriter, newForOp.getRegionIterArgs(),
771 forOp.getRegionIterArgs(), indices);
772 iterArgs.insert(iterArgs.begin(), newForOp.getInductionVar());
773
774 // Move loop body to new loop.
775 rewriter.mergeBlocks(oldLoopBody, loopBody, iterArgs);
776
777 // Replace loop results.
778 replaceOpWithBufferizedValues(rewriter, op, newForOp->getResults());
779
780 return success();
781 }
782
783 /// Assert that yielded values of an scf.for op are equivalent to their
784 /// corresponding bbArgs. In that case, the buffer relations of the
785 /// corresponding OpResults are "Equivalent".
786 ///
787 /// If this is not the case, an allocs+copies are inserted and yielded from
788 /// the loop. This could be a performance problem, so it must be explicitly
789 /// activated with `alloc-return-allocs`.
790 LogicalResult verifyAnalysis(Operation *op,
791 const AnalysisState &state) const {
792 const auto &options =
793 static_cast<const OneShotBufferizationOptions &>(state.getOptions());
794 if (options.allowReturnAllocsFromLoops)
795 return success();
796
797 auto forOp = cast<scf::ForOp>(op);
798 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
799 for (OpResult opResult : op->getOpResults()) {
800 if (!isa<TensorLikeType>(opResult.getType()))
801 continue;
802 // Note: This is overly strict. We should check for aliasing bufferized
803 // values. But we don't have a "must-alias" analysis yet.
804 if (bufferRelation(op, opResult, state) != BufferRelation::Equivalent)
805 return yieldOp->emitError()
806 << "Yield operand #" << opResult.getResultNumber()
807 << " is not equivalent to the corresponding iter bbArg";
808 }
809
810 return success();
811 }
812};
813
814/// Bufferization of scf.while. Replace with a new scf.while that operates on
815/// memrefs.
816struct WhileOpInterface
817 : public BufferizableOpInterface::ExternalModel<WhileOpInterface,
818 scf::WhileOp> {
819 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
820 const AnalysisState &state) const {
821 // Tensor iter_args of scf::WhileOps are always considered as a read.
822 return true;
823 }
824
825 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
826 const AnalysisState &state) const {
827 // Tensor iter_args of scf::WhileOps are always considered as a write.
828 return true;
829 }
830
831 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
832 const AnalysisState &state) const {
833 auto whileOp = cast<scf::WhileOp>(op);
834 unsigned int idx = opOperand.getOperandNumber();
835
836 // The OpResults and OpOperands may not match. They may not even have the
837 // same type. The number of OpResults and OpOperands can also differ.
838 if (idx >= op->getNumResults() ||
839 opOperand.get().getType() != op->getResult(idx).getType())
840 return {};
841
842 // The only aliasing OpResult may be the one at the same index.
843 OpResult opResult = whileOp->getResult(idx);
844 BufferRelation relation = bufferRelation(op, opResult, state);
845 return {{opResult, relation,
846 /*isDefinite=*/relation == BufferRelation::Equivalent}};
847 }
848
849 BufferRelation bufferRelation(Operation *op, OpResult opResult,
850 const AnalysisState &state) const {
851 // WhileOp results are equivalent to their corresponding init_args if the
852 // corresponding iter_args and yield values are equivalent (for both the
853 // "before" and the "after" block).
854 unsigned int resultNumber = opResult.getResultNumber();
855 auto whileOp = cast<scf::WhileOp>(op);
856
857 // The "before" region bbArgs and the OpResults may not match.
858 if (resultNumber >= whileOp.getBeforeArguments().size())
859 return BufferRelation::Unknown;
860 if (opResult.getType() !=
861 whileOp.getBeforeArguments()[resultNumber].getType())
862 return BufferRelation::Unknown;
863
864 auto conditionOp = whileOp.getConditionOp();
865 BlockArgument conditionBbArg = whileOp.getBeforeArguments()[resultNumber];
866 Value conditionOperand = conditionOp.getArgs()[resultNumber];
867 bool equivCondition =
868 state.areEquivalentBufferizedValues(conditionBbArg, conditionOperand);
869
870 auto yieldOp = whileOp.getYieldOp();
871 BlockArgument bodyBbArg = whileOp.getAfterArguments()[resultNumber];
872 Value yieldOperand = yieldOp.getOperand(resultNumber);
873 bool equivYield =
874 state.areEquivalentBufferizedValues(bodyBbArg, yieldOperand);
875
876 return equivCondition && equivYield ? BufferRelation::Equivalent
877 : BufferRelation::Unknown;
878 }
879
880 bool isWritable(Operation *op, Value value,
881 const AnalysisState &state) const {
882 // Interestingly, scf::WhileOp's bbArg can **always** be viewed
883 // inplace from the perspective of ops nested under:
884 // 1. Either the matching iter operand is not bufferized inplace and an
885 // alloc + optional copy makes the bbArg itself inplaceable.
886 // 2. Or the matching iter operand is bufferized inplace and bbArg just
887 // bufferizes to that too.
888 return true;
889 }
890
891 LogicalResult
892 resolveConflicts(Operation *op, RewriterBase &rewriter,
893 const AnalysisState &analysisState,
894 const BufferizationState &bufferizationState) const {
895 auto bufferizableOp = cast<BufferizableOpInterface>(op);
896 if (failed(bufferizableOp.resolveTensorOpOperandConflicts(
897 rewriter, analysisState, bufferizationState)))
898 return failure();
899
900 if (analysisState.getOptions().copyBeforeWrite)
901 return success();
902
903 // According to the `getAliasing...` implementations, a bufferized OpResult
904 // may alias only with the corresponding bufferized init_arg and with no
905 // other buffers. I.e., the i-th OpResult may alias with the i-th init_arg;
906 // but not with any other OpOperand. If a corresponding OpResult/init_arg
907 // pair bufferizes to equivalent buffers, this aliasing requirement is
908 // satisfied. Otherwise, we cannot be sure and must yield a new buffer copy.
909 // (New buffer copies do not alias with any buffer.)
910 OpBuilder::InsertionGuard g(rewriter);
911 auto whileOp = cast<scf::WhileOp>(op);
912 auto conditionOp = whileOp.getConditionOp();
913
914 // For every yielded value, is the value equivalent to its corresponding
915 // bbArg?
916 DenseSet<int64_t> equivalentYieldsBefore = getEquivalentBuffers(
917 whileOp.getBeforeArguments(), conditionOp.getArgs(), analysisState);
918 DenseSet<int64_t> equivalentYieldsAfter =
919 getEquivalentBuffers(whileOp.getAfterArguments(),
920 whileOp.getYieldOp().getResults(), analysisState);
921
922 // Update "before" region.
923 rewriter.setInsertionPoint(conditionOp);
924 SmallVector<Value> beforeYieldValues;
925 for (int64_t idx = 0;
926 idx < static_cast<int64_t>(conditionOp.getArgs().size()); ++idx) {
927 Value value = conditionOp.getArgs()[idx];
928 if (!isa<TensorLikeType>(value.getType()) ||
929 (equivalentYieldsAfter.contains(idx) &&
930 equivalentYieldsBefore.contains(idx))) {
931 beforeYieldValues.push_back(value);
932 continue;
933 }
934 FailureOr<Value> alloc = allocateTensorForShapedValue(
935 rewriter, conditionOp.getLoc(), value, analysisState.getOptions(),
936 bufferizationState);
937 if (failed(alloc))
938 return failure();
939 beforeYieldValues.push_back(*alloc);
940 }
941 rewriter.modifyOpInPlace(conditionOp, [&]() {
942 conditionOp.getArgsMutable().assign(beforeYieldValues);
943 });
944
945 return success();
946 }
947
948 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
949 const BufferizationOptions &options,
950 BufferizationState &state) const {
951 auto whileOp = cast<scf::WhileOp>(op);
952
953 // Indices of all bbArgs that have tensor type. These are the ones that
954 // are bufferized. The "before" and "after" regions may have different args.
955 DenseSet<int64_t> indicesBefore = getTensorIndices(whileOp.getInits());
956 DenseSet<int64_t> indicesAfter =
957 getTensorIndices(whileOp.getAfterArguments());
958
959 // The new memref init_args of the loop.
960 FailureOr<SmallVector<Value>> maybeInitArgs =
961 getBuffers(rewriter, whileOp.getInitsMutable(), options, state);
962 if (failed(maybeInitArgs))
963 return failure();
964 SmallVector<Value> initArgs = *maybeInitArgs;
965
966 // Cast init_args if necessary.
967 SmallVector<Value> castedInitArgs;
968 for (const auto &it : llvm::enumerate(initArgs)) {
969 Value initArg = it.value();
970 Value beforeArg = whileOp.getBeforeArguments()[it.index()];
971 // If the type is not a tensor, bufferization doesn't need to touch it.
972 if (!isa<TensorLikeType>(beforeArg.getType())) {
973 castedInitArgs.push_back(initArg);
974 continue;
975 }
976 auto targetType = bufferization::getBufferType(beforeArg, options, state);
977 if (failed(targetType))
978 return failure();
979 FailureOr<Value> castedInitArg =
980 castBuffer(rewriter, initArg.getLoc(), initArg, *targetType, options);
981 if (failed(castedInitArg))
982 return failure();
983 castedInitArgs.push_back(*castedInitArg);
984 }
985
986 // The result types of a WhileOp are the same as the "after" bbArg types.
987 SmallVector<Type> argsTypesAfter = llvm::map_to_vector(
988 whileOp.getAfterArguments(), [&](BlockArgument bbArg) {
989 if (!isa<TensorLikeType>(bbArg.getType()))
990 return bbArg.getType();
991 // TODO: error handling
992 return llvm::cast<Type>(
993 *bufferization::getBufferType(bbArg, options, state));
994 });
995
996 // Construct a new scf.while op with memref instead of tensor values.
997 ValueRange argsRangeBefore(castedInitArgs);
998 TypeRange argsTypesBefore(argsRangeBefore);
999 auto newWhileOp = scf::WhileOp::create(rewriter, whileOp.getLoc(),
1000 argsTypesAfter, castedInitArgs);
1001
1002 // Add before/after regions to the new op.
1003 SmallVector<Location> bbArgLocsBefore(castedInitArgs.size(),
1004 whileOp.getLoc());
1005 SmallVector<Location> bbArgLocsAfter(argsTypesAfter.size(),
1006 whileOp.getLoc());
1007 Block *newBeforeBody = &newWhileOp.getBefore().emplaceBlock();
1008 newWhileOp.getBefore().addArguments(argsTypesBefore, bbArgLocsBefore);
1009 Block *newAfterBody = &newWhileOp.getAfter().emplaceBlock();
1010 newWhileOp.getAfter().addArguments(argsTypesAfter, bbArgLocsAfter);
1011
1012 // Set up new iter_args and move the loop condition block to the new op.
1013 // The old block uses tensors, so wrap the (memref) bbArgs of the new block
1014 // in ToTensorOps.
1015 rewriter.setInsertionPointToStart(newBeforeBody);
1016 SmallVector<Value> newBeforeArgs =
1017 getBbArgReplacements(rewriter, newWhileOp.getBeforeArguments(),
1018 whileOp.getBeforeArguments(), indicesBefore);
1019 rewriter.mergeBlocks(whileOp.getBeforeBody(), newBeforeBody, newBeforeArgs);
1020
1021 // Set up new iter_args and move the loop body block to the new op.
1022 // The old block uses tensors, so wrap the (memref) bbArgs of the new block
1023 // in ToTensorOps.
1024 rewriter.setInsertionPointToStart(newAfterBody);
1025 SmallVector<Value> newAfterArgs =
1026 getBbArgReplacements(rewriter, newWhileOp.getAfterArguments(),
1027 whileOp.getAfterArguments(), indicesAfter);
1028 rewriter.mergeBlocks(whileOp.getAfterBody(), newAfterBody, newAfterArgs);
1029
1030 // Replace loop results.
1031 replaceOpWithBufferizedValues(rewriter, op, newWhileOp->getResults());
1032
1033 return success();
1034 }
1035
1036 FailureOr<BufferLikeType>
1037 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
1038 const BufferizationState &state,
1039 SmallVector<Value> &invocationStack) const {
1040 auto whileOp = cast<scf::WhileOp>(op);
1041 assert(getOwnerOfValue(value) == op && "invalid value");
1042 assert(isa<TensorLikeType>(value.getType()) && "expected tensor type");
1043
1044 // Case 1: Block argument of the "before" region.
1045 if (auto bbArg = dyn_cast<BlockArgument>(value)) {
1046 if (bbArg.getOwner()->getParent() == &whileOp.getBefore()) {
1047 Value initArg = whileOp.getInits()[bbArg.getArgNumber()];
1048 auto yieldOp = whileOp.getYieldOp();
1049 Value yieldedValue = yieldOp.getOperand(bbArg.getArgNumber());
1050 return computeLoopRegionIterArgBufferType(
1051 op, bbArg, initArg, yieldedValue, options, state, invocationStack);
1052 }
1053 }
1054
1055 // Case 2: OpResult of the loop or block argument of the "after" region.
1056 // The bufferized "after" bbArg type can be directly computed from the
1057 // bufferized "before" bbArg type.
1058 unsigned resultNum;
1059 if (auto opResult = dyn_cast<OpResult>(value)) {
1060 resultNum = opResult.getResultNumber();
1061 } else if (cast<BlockArgument>(value).getOwner()->getParent() ==
1062 &whileOp.getAfter()) {
1063 resultNum = cast<BlockArgument>(value).getArgNumber();
1064 } else {
1065 llvm_unreachable("invalid value");
1066 }
1067 Value conditionYieldedVal = whileOp.getConditionOp().getArgs()[resultNum];
1068 if (!isa<TensorLikeType>(conditionYieldedVal.getType())) {
1069 // scf.condition was already bufferized.
1070 return cast<BufferLikeType>(conditionYieldedVal.getType());
1071 }
1072 return bufferization::getBufferType(conditionYieldedVal, options, state,
1073 invocationStack);
1074 }
1075
1076 /// Assert that yielded values of an scf.while op are equivalent to their
1077 /// corresponding bbArgs. In that case, the buffer relations of the
1078 /// corresponding OpResults are "Equivalent".
1079 ///
1080 /// If this is not the case, allocs+copies are inserted and yielded from
1081 /// the loop. This could be a performance problem, so it must be explicitly
1082 /// activated with `allow-return-allocs`.
1083 ///
1084 /// Not: In contrast to scf::ForOp, scf::WhileOp has two regions and the
1085 /// equivalence condition must be checked for both.
1086 LogicalResult verifyAnalysis(Operation *op,
1087 const AnalysisState &state) const {
1088 auto whileOp = cast<scf::WhileOp>(op);
1089 const auto &options =
1090 static_cast<const OneShotBufferizationOptions &>(state.getOptions());
1091 if (options.allowReturnAllocsFromLoops)
1092 return success();
1093
1094 auto conditionOp = whileOp.getConditionOp();
1095 for (const auto &it : llvm::enumerate(conditionOp.getArgs())) {
1096 Block *block = conditionOp->getBlock();
1097 if (!isa<TensorLikeType>(it.value().getType()))
1098 continue;
1099 if (it.index() >= block->getNumArguments() ||
1100 !state.areEquivalentBufferizedValues(it.value(),
1101 block->getArgument(it.index())))
1102 return conditionOp->emitError()
1103 << "Condition arg #" << it.index()
1104 << " is not equivalent to the corresponding iter bbArg";
1105 }
1106
1107 auto yieldOp = whileOp.getYieldOp();
1108 for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
1109 Block *block = yieldOp->getBlock();
1110 if (!isa<TensorLikeType>(it.value().getType()))
1111 continue;
1112 if (it.index() >= block->getNumArguments() ||
1113 !state.areEquivalentBufferizedValues(it.value(),
1114 block->getArgument(it.index())))
1115 return yieldOp->emitError()
1116 << "Yield operand #" << it.index()
1117 << " is not equivalent to the corresponding iter bbArg";
1118 }
1119
1120 return success();
1121 }
1122};
1123
1124/// Bufferization of scf.yield. Bufferized as part of their enclosing ops, so
1125/// this is for analysis only.
1126struct YieldOpInterface
1127 : public BufferizableOpInterface::ExternalModel<YieldOpInterface,
1128 scf::YieldOp> {
1129 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1130 const AnalysisState &state) const {
1131 return true;
1132 }
1133
1134 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1135 const AnalysisState &state) const {
1136 return false;
1137 }
1138
1139 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
1140 const AnalysisState &state) const {
1141 if (isa<scf::IfOp, scf::IndexSwitchOp>(op->getParentOp()))
1142 return {{op->getParentOp()->getResult(opOperand.getOperandNumber()),
1143 BufferRelation::Equivalent, /*isDefinite=*/false}};
1144 if (isa<scf::ExecuteRegionOp>(op->getParentOp()))
1145 return {{op->getParentOp()->getResult(opOperand.getOperandNumber()),
1146 BufferRelation::Equivalent}};
1147 return {};
1148 }
1149
1150 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
1151 const AnalysisState &state) const {
1152 // Yield operands always bufferize inplace. Otherwise, an alloc + copy
1153 // may be generated inside the block. We should not return/yield allocations
1154 // when possible.
1155 return true;
1156 }
1157
1158 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
1159 const BufferizationOptions &options,
1160 BufferizationState &state) const {
1161 auto yieldOp = cast<scf::YieldOp>(op);
1162 if (!isa<scf::ExecuteRegionOp, scf::IfOp, scf::IndexSwitchOp, scf::ForOp,
1163 scf::WhileOp>(yieldOp->getParentOp()))
1164 return yieldOp->emitError("unsupported scf::YieldOp parent");
1165
1166 SmallVector<Value> newResults;
1167 for (const auto &it : llvm::enumerate(yieldOp.getResults())) {
1168 Value value = it.value();
1169 if (isa<TensorLikeType>(value.getType())) {
1170 FailureOr<Value> maybeBuffer =
1171 getBuffer(rewriter, value, options, state);
1172 if (failed(maybeBuffer))
1173 return failure();
1174 Value buffer = *maybeBuffer;
1175 // We may have to cast the value before yielding it.
1176 if (isa<scf::ForOp, scf::IfOp, scf::IndexSwitchOp>(
1177 yieldOp->getParentOp())) {
1178 FailureOr<BufferLikeType> resultType = bufferization::getBufferType(
1179 yieldOp->getParentOp()->getResult(it.index()), options, state);
1180 if (failed(resultType))
1181 return failure();
1182 FailureOr<Value> castedBuffer = castBuffer(
1183 rewriter, buffer.getLoc(), buffer, *resultType, options);
1184 if (failed(castedBuffer))
1185 return failure();
1186 buffer = *castedBuffer;
1187 } else if (auto whileOp =
1188 dyn_cast<scf::WhileOp>(yieldOp->getParentOp())) {
1189 FailureOr<BufferLikeType> resultType = bufferization::getBufferType(
1190 whileOp.getBeforeArguments()[it.index()], options, state);
1191 if (failed(resultType))
1192 return failure();
1193 FailureOr<Value> castedBuffer = castBuffer(
1194 rewriter, buffer.getLoc(), buffer, *resultType, options);
1195 if (failed(castedBuffer))
1196 return failure();
1197 buffer = *castedBuffer;
1198 }
1199 newResults.push_back(buffer);
1200 } else {
1201 newResults.push_back(value);
1202 }
1203 }
1204
1205 replaceOpWithNewBufferizedOp<scf::YieldOp>(rewriter, op, newResults);
1206 return success();
1207 }
1208};
1209
1210/// Bufferization of ForallOp. This also bufferizes the terminator of the
1211/// region. There are op interfaces for the terminators (InParallelOp
1212/// and ParallelInsertSliceOp), but these are only used during analysis. Not
1213/// for bufferization.
1214struct ForallOpInterface
1215 : public BufferizableOpInterface::ExternalModel<ForallOpInterface,
1216 ForallOp> {
1217 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1218 const AnalysisState &state) const {
1219 // All tensor operands to `scf.forall` are `shared_outs` and all
1220 // shared outs are assumed to be read by the loop. This does not
1221 // account for the case where the entire value is over-written,
1222 // but being conservative here.
1223 return true;
1224 }
1225
1226 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1227 const AnalysisState &state) const {
1228 // Outputs of scf::ForallOps are always considered as a write.
1229 return true;
1230 }
1231
1232 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
1233 const AnalysisState &state) const {
1234 auto forallOp = cast<ForallOp>(op);
1235 return {
1236 {{forallOp.getTiedOpResult(&opOperand), BufferRelation::Equivalent}}};
1237 }
1238
1239 AliasingOpOperandList
1240 getAliasingOpOperands(Operation *op, Value value,
1241 const AnalysisState &state) const {
1242 auto result = dyn_cast<OpResult>(value);
1243 if (!result)
1244 return {};
1245 auto forallOp = cast<ForallOp>(op);
1246 return {{forallOp.getTiedOpOperand(result), BufferRelation::Equivalent}};
1247 }
1248
1249 bool isWritable(Operation *op, Value value,
1250 const AnalysisState &state) const {
1251 return true;
1252 }
1253
1254 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
1255 const BufferizationOptions &options,
1256 BufferizationState &state) const {
1257 OpBuilder::InsertionGuard guard(rewriter);
1258 auto forallOp = cast<ForallOp>(op);
1259 int64_t rank = forallOp.getRank();
1260
1261 // Get buffers for all output operands.
1262 SmallVector<Value> buffers;
1263 for (Value out : forallOp.getOutputs()) {
1264 FailureOr<Value> buffer = getBuffer(rewriter, out, options, state);
1265 if (failed(buffer))
1266 return failure();
1267 buffers.push_back(*buffer);
1268 }
1269
1270 // Use buffers instead of block arguments.
1271 rewriter.setInsertionPointToStart(forallOp.getBody());
1272 for (const auto &it : llvm::zip(
1273 forallOp.getBody()->getArguments().drop_front(rank), buffers)) {
1274 BlockArgument bbArg = std::get<0>(it);
1275 Value buffer = std::get<1>(it);
1276 Value bufferAsTensor = ToTensorOp::create(rewriter, forallOp.getLoc(),
1277 bbArg.getType(), buffer);
1278 bbArg.replaceAllUsesWith(bufferAsTensor);
1279 }
1280
1281 // Create new ForallOp without any results and drop the automatically
1282 // introduced terminator.
1283 rewriter.setInsertionPoint(forallOp);
1284 ForallOp newForallOp;
1285 newForallOp = ForallOp::create(
1286 rewriter, forallOp.getLoc(), forallOp.getMixedLowerBound(),
1287 forallOp.getMixedUpperBound(), forallOp.getMixedStep(),
1288 /*outputs=*/ValueRange(), forallOp.getMapping());
1289
1290 // Keep discardable attributes from the original op.
1291 newForallOp->setDiscardableAttrs(op->getDiscardableAttrDictionary());
1292
1293 rewriter.eraseOp(newForallOp.getBody()->getTerminator());
1294
1295 // Move over block contents of the old op.
1296 SmallVector<Value> replacementBbArgs;
1297 replacementBbArgs.append(newForallOp.getBody()->getArguments().begin(),
1298 newForallOp.getBody()->getArguments().end());
1299 replacementBbArgs.append(forallOp.getOutputs().size(), Value());
1300 rewriter.mergeBlocks(forallOp.getBody(), newForallOp.getBody(),
1301 replacementBbArgs);
1302
1303 // Remove the old op and replace all of its uses.
1304 replaceOpWithBufferizedValues(rewriter, op, buffers);
1305
1306 return success();
1307 }
1308
1309 FailureOr<BufferLikeType>
1310 getBufferType(Operation *op, Value value, const BufferizationOptions &options,
1311 const BufferizationState &state,
1312 SmallVector<Value> &invocationStack) const {
1313 auto forallOp = cast<ForallOp>(op);
1314
1315 if (auto bbArg = dyn_cast<BlockArgument>(value))
1316 // A tensor block argument has the same bufferized type as the
1317 // corresponding output operand.
1318 return bufferization::getBufferType(
1319 forallOp.getTiedOpOperand(bbArg)->get(), options, state,
1320 invocationStack);
1321
1322 // The bufferized result type is the same as the bufferized type of the
1323 // corresponding output operand.
1324 return bufferization::getBufferType(
1325 forallOp.getOutputs()[cast<OpResult>(value).getResultNumber()], options,
1326 state, invocationStack);
1327 }
1328
1329 bool isRepetitiveRegion(Operation *op, unsigned index) const {
1330 auto forallOp = cast<ForallOp>(op);
1331
1332 // This op is repetitive if it has 1 or more steps.
1333 // If the control variables are dynamic, it is also considered so.
1334 for (auto [lb, ub, step] :
1335 llvm::zip(forallOp.getMixedLowerBound(), forallOp.getMixedUpperBound(),
1336 forallOp.getMixedStep())) {
1337 std::optional<int64_t> lbConstant = getConstantIntValue(lb);
1338 if (!lbConstant)
1339 return true;
1340
1341 std::optional<int64_t> ubConstant = getConstantIntValue(ub);
1342 if (!ubConstant)
1343 return true;
1344
1345 std::optional<int64_t> stepConstant = getConstantIntValue(step);
1346 if (!stepConstant)
1347 return true;
1348
1349 if (*lbConstant + *stepConstant < *ubConstant)
1350 return true;
1351 }
1352 return false;
1353 }
1354
1355 bool isParallelRegion(Operation *op, unsigned index) const {
1356 return isRepetitiveRegion(op, index);
1357 }
1358};
1359
1360/// Nothing to do for InParallelOp.
1361struct InParallelOpInterface
1362 : public BufferizableOpInterface::ExternalModel<InParallelOpInterface,
1363 InParallelOp> {
1364 LogicalResult bufferize(Operation *op, RewriterBase &b,
1365 const BufferizationOptions &options,
1366 BufferizationState &state) const {
1367 llvm_unreachable("op does not have any tensor OpOperands / OpResults");
1368 return failure();
1369 }
1370};
1371
1372} // namespace
1373} // namespace scf
1374} // namespace mlir
1375
1377 DialectRegistry &registry) {
1378 registry.addExtension(+[](MLIRContext *ctx, scf::SCFDialect *dialect) {
1379 ConditionOp::attachInterface<ConditionOpInterface>(*ctx);
1380 ExecuteRegionOp::attachInterface<ExecuteRegionOpInterface>(*ctx);
1381 ForOp::attachInterface<ForOpInterface>(*ctx);
1382 IfOp::attachInterface<IfOpInterface>(*ctx);
1383 IndexSwitchOp::attachInterface<IndexSwitchOpInterface>(*ctx);
1384 ForallOp::attachInterface<ForallOpInterface>(*ctx);
1385 InParallelOp::attachInterface<InParallelOpInterface>(*ctx);
1386 WhileOp::attachInterface<WhileOpInterface>(*ctx);
1387 YieldOp::attachInterface<YieldOpInterface>(*ctx);
1388 });
1389}
return success()
static bool isRepetitiveRegion(Region *region, const BufferizationOptions &options)
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static llvm::ManagedStatic< PassManagerOptions > options
static RankedTensorType getBufferType(const SparseTensorType &stt, bool needTmpCOO)
static Operation * getOwnerOfValue(Value value)
unsigned getArgNumber() const
Returns the number of this argument.
Definition Value.h:320
Block * getOwner() const
Returns the block that owns this argument.
Definition Value.h:317
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
bool addExtension(TypeID extensionID, std::unique_ptr< DialectExtensionBase > extension)
Add the given extension to the registry.
IRValueT get() const
Return the current value being used by this operand.
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
unsigned getResultNumber() const
Returns the number of this result.
Definition Value.h:468
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
Definition Operation.h:251
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
DictionaryAttr getDiscardableAttrDictionary()
Return all of the discardable attributes on this operation as a DictionaryAttr.
Definition Operation.h:555
result_range getOpResults()
Definition Operation.h:447
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
unsigned getNumResults()
Return the number of results held by this operation.
Definition Operation.h:431
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
Definition Region.h:234
bool isProperAncestor(Region *other)
Return true if this region is a proper ancestor of the other region.
Definition Region.cpp:50
bool hasOneBlock()
Return true if this region has exactly one block.
Definition Region.h:68
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
void modifyOpInPlace(Operation *root, CallableT &&callable)
This method is a utility wrapper around an in-place modification of an operation.
void inlineRegionBefore(Region &region, Region &parent, Region::iterator before)
Move the blocks that belong to "region" before the given position in another region "parent".
Type getType() const
Return the type of this value.
Definition Value.h:105
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
Definition Value.h:149
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
void applyOnAliases(Value v, function_ref< void(Value)> fun) const
Apply fun to all aliases of v.
LogicalResult bufferizeBlockSignature(Block *block, RewriterBase &rewriter, const BufferizationOptions &options, BufferizationState &state)
Bufferize the signature of block and its callers (i.e., ops that have the given block as a successor)...
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
void registerBufferizableOpInterfaceExternalModels(DialectRegistry &registry)
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125