22#include "llvm/ADT/SmallVectorExtras.h"
36static bool doesNotAliasExternalValue(Value value, Region *region,
38 const OneShotAnalysisState &state) {
39 assert(region->
hasOneBlock() &&
"expected region with single block");
42 if (llvm::is_contained(exceptions, alias))
47 if (isa<OpResult>(alias) && !region->
isAncestor(aliasRegion))
54struct ConditionOpInterface
55 :
public BufferizableOpInterface::ExternalModel<ConditionOpInterface,
57 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
58 const AnalysisState &state)
const {
62 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
63 const AnalysisState &state)
const {
67 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
68 const AnalysisState &state)
const {
72 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
73 const AnalysisState &state)
const {
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());
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);
94 FailureOr<BufferLikeType> resultType = bufferization::getBufferType(
95 whileOp.getAfterArguments()[it.index()],
options, state);
98 FailureOr<Value> buffer =
99 castBuffer(rewriter, maybeBuffer->getLoc(), *maybeBuffer,
103 newArgs.push_back(*buffer);
105 newArgs.push_back(value);
109 replaceOpWithNewBufferizedOp<scf::ConditionOp>(
110 rewriter, op, conditionOp.getCondition(), newArgs);
117static scf::YieldOp getUniqueYieldOp(scf::ExecuteRegionOp executeRegionOp) {
119 for (
Block &block : executeRegionOp.getRegion()) {
120 if (
auto yieldOp = dyn_cast<scf::YieldOp>(block.getTerminator())) {
131struct ExecuteRegionOpInterface
132 :
public OpWithUnstructuredControlFlowBufferizableOpInterfaceExternalModel<
133 ExecuteRegionOpInterface, scf::ExecuteRegionOp> {
135 static bool supportsUnstructuredControlFlow() {
return true; }
137 bool isWritable(Operation *op, Value value,
138 const AnalysisState &state)
const {
142 LogicalResult verifyAnalysis(Operation *op,
143 const AnalysisState &state)
const {
144 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
146 if (!getUniqueYieldOp(executeRegionOp))
147 return op->
emitOpError(
"op without unique scf.yield is not supported");
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);
161 auto executeRegionOp = cast<scf::ExecuteRegionOp>(op);
163 assert(it != op->
getOpResults().end() &&
"invalid value");
164 size_t resultNum = std::distance(op->
getOpResults().begin(), it);
165 auto yieldOp = getUniqueYieldOp(executeRegionOp);
169 return {{&yieldOp->getOpOperand(resultNum), BufferRelation::Equivalent}};
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());
180 auto newOp = scf::ExecuteRegionOp::create(
181 rewriter, op->
getLoc(), newResultTypes, executeRegionOp.getNoInline());
182 newOp.getRegion().takeBody(executeRegionOp.getRegion());
185 for (
Block &block : newOp.getRegion())
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())));
199 newResults.push_back(newOp->getResult(it.index()));
204 rewriter.
replaceOp(executeRegionOp, newResults);
212 :
public BufferizableOpInterface::ExternalModel<IfOpInterface, scf::IfOp> {
213 AliasingOpOperandList
214 getAliasingOpOperands(Operation *op, Value value,
215 const AnalysisState &state)
const {
220 auto ifOp = cast<scf::IfOp>(op);
221 size_t resultNum = std::distance(op->
getOpResults().begin(),
223 OpOperand *thenOperand = &ifOp.thenYield()->getOpOperand(resultNum);
224 OpOperand *elseOperand = &ifOp.elseYield()->getOpOperand(resultNum);
225 return {{thenOperand, BufferRelation::Equivalent,
false},
226 {elseOperand, BufferRelation::Equivalent,
false}};
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);
236 SmallVector<Type> newTypes;
237 for (Value
result : ifOp.getResults()) {
238 if (!isa<TensorLikeType>(
result.getType())) {
239 newTypes.push_back(
result.getType());
242 auto bufferType = bufferization::getBufferType(
result,
options, state);
245 newTypes.push_back(*bufferType);
250 auto newIfOp = scf::IfOp::create(rewriter, ifOp.getLoc(), newTypes,
255 rewriter.
mergeBlocks(ifOp.thenBlock(), newIfOp.thenBlock());
256 rewriter.
mergeBlocks(ifOp.elseBlock(), newIfOp.elseBlock());
259 replaceOpWithBufferizedValues(rewriter, op, newIfOp->getResults());
264 FailureOr<BufferLikeType>
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());
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())) {
280 thenBufferType = cast<BufferLikeType>(thenValue.getType());
282 auto maybeBufferType = bufferization::getBufferType(
283 thenValue,
options, state, invocationStack);
284 if (
failed(maybeBufferType))
286 thenBufferType = *maybeBufferType;
288 if (isa<BufferLikeType>(elseValue.getType())) {
290 elseBufferType = cast<BufferLikeType>(elseValue.getType());
292 auto maybeBufferType = bufferization::getBufferType(
293 elseValue,
options, state, invocationStack);
294 if (
failed(maybeBufferType))
296 elseBufferType = *maybeBufferType;
300 if (thenBufferType == elseBufferType)
301 return cast<BufferLikeType>(thenBufferType);
303 auto reconciled =
options.reconcileBufferTypeMismatchFn(
304 thenBufferType, elseBufferType,
options);
306 return op->
emitError(
"incompatible buffer types on then/else branches");
314struct IndexSwitchOpInterface
315 :
public BufferizableOpInterface::ExternalModel<IndexSwitchOpInterface,
316 scf::IndexSwitchOp> {
317 AliasingOpOperandList
318 getAliasingOpOperands(Operation *op, Value value,
319 const AnalysisState &state)
const {
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) {
327 cast<scf::YieldOp>(switchOp.getCaseBlock(i).getTerminator());
328 result.addAlias(AliasingOpOperand(&yieldOp->getOpOperand(resultNum),
329 BufferRelation::Equivalent,
332 auto defaultYieldOp =
333 cast<scf::YieldOp>(switchOp.getDefaultBlock().getTerminator());
334 result.addAlias(AliasingOpOperand(&defaultYieldOp->getOpOperand(resultNum),
335 BufferRelation::Equivalent,
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);
347 SmallVector<Type> newTypes;
348 for (Value
result : switchOp.getResults()) {
349 if (!isa<TensorLikeType>(
result.getType())) {
350 newTypes.push_back(
result.getType());
353 auto bufferType = bufferization::getBufferType(
result,
options, state);
356 newTypes.push_back(*bufferType);
361 auto newSwitchOp = scf::IndexSwitchOp::create(
362 rewriter, switchOp.getLoc(), newTypes, switchOp.getArg(),
363 switchOp.getCases(), switchOp.getCases().size());
366 for (
auto [src, dest] :
367 llvm::zip(switchOp.getCaseRegions(), newSwitchOp.getCaseRegions()))
370 newSwitchOp.getDefaultRegion(),
371 newSwitchOp.getDefaultRegion().begin());
374 replaceOpWithBufferizedValues(rewriter, op, newSwitchOp->getResults());
379 FailureOr<BufferLikeType>
381 const BufferizationState &state,
382 SmallVector<Value> &invocationStack)
const {
383 auto switchOp = cast<scf::IndexSwitchOp>(op);
385 int64_t resultNum = cast<OpResult>(value).getResultNumber();
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()))
392 return bufferization::getBufferType(yieldedValue,
options, state,
397 auto maybeBufferType = getYieldedBufferType(switchOp.getDefaultBlock());
398 if (
failed(maybeBufferType))
400 BufferLikeType bufferType = *maybeBufferType;
403 for (int64_t i = 0, numCases = switchOp.getNumCases(); i < numCases; ++i) {
404 auto yieldedBufferType = getYieldedBufferType(switchOp.getCaseBlock(i));
405 if (
failed(yieldedBufferType))
409 if (bufferType == *yieldedBufferType)
412 auto reconciled =
options.reconcileBufferTypeMismatchFn(
413 bufferType, *yieldedBufferType,
options);
415 return op->
emitError(
"incompatible buffer types on switch cases");
416 bufferType = *reconciled;
419 return cast<BufferLikeType>(bufferType);
427 for (
const auto &it : llvm::enumerate(values))
428 if (isa<TensorLikeType>(it.value().getType()))
429 result.insert(it.index());
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()))
444 if (state.areEquivalentBufferizedValues(bbArgs[i], yieldedValues[i]))
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);
462 result.push_back(*resultBuffer);
464 result.push_back(opOperand.get());
473static SmallVector<Value>
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)) {
483 bufferization::ToTensorOp::create(rewriter, val.
getLoc(),
484 oldBbArgs[idx].getType(), val)
505static FailureOr<BufferLikeType> computeLoopRegionIterArgBufferType(
506 Operation *loopOp, BlockArgument iterArg, Value initArg, Value yieldedValue,
507 const BufferizationOptions &
options,
const BufferizationState &state,
508 SmallVector<Value> &invocationStack) {
510 auto initArgBufferType =
511 bufferization::getBufferType(initArg,
options, state, invocationStack);
512 if (
failed(initArgBufferType))
515 if (llvm::count(invocationStack, iterArg) >= 2) {
526 return *initArgBufferType;
530 BufferLikeType yieldedValueBufferType;
531 if (
auto bufferType = dyn_cast<BufferLikeType>(yieldedValue.
getType())) {
533 yieldedValueBufferType = bufferType;
537 auto maybeBufferType = bufferization::getBufferType(yieldedValue,
options,
538 state, invocationStack);
539 if (
failed(maybeBufferType))
541 yieldedValueBufferType = *maybeBufferType;
545 if (*initArgBufferType == yieldedValueBufferType)
546 return yieldedValueBufferType;
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");
562 auto reconciled =
options.reconcileBufferTypeMismatchFn(
563 *initArgBufferType, yieldedValueBufferType,
options);
566 "init_arg and yielded value bufferize to incompatible buffer types");
573bool mayHaveZeroIterations(scf::ForOp forOp) {
576 if (!lb.has_value() || !ub.has_value())
584 :
public BufferizableOpInterface::ExternalModel<ForOpInterface,
586 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
587 const AnalysisState &state)
const {
588 auto forOp = cast<scf::ForOp>(op);
592 if (mayHaveZeroIterations(forOp))
597 return state.isValueRead(forOp.getTiedLoopRegionIterArg(&opOperand));
600 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
601 const AnalysisState &state)
const {
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 relation == BufferRelation::Equivalent}};
615 BufferRelation bufferRelation(Operation *op, OpResult opResult,
616 const AnalysisState &state)
const {
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;
627 bool isWritable(Operation *op, Value value,
628 const AnalysisState &state)
const {
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)))
647 if (analysisState.getOptions().copyBeforeWrite)
655 auto forOp = cast<scf::ForOp>(op);
656 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
657 OpBuilder::InsertionGuard g(rewriter);
665 SmallVector<Value> yieldValues;
666 for (
const auto it : llvm::enumerate(yieldOp.getResults())) {
671 if (!
indices.contains(it.index()) ||
672 doesNotAliasExternalValue(
673 it.value(), &forOp.getRegion(),
674 forOp.getRegionIterArg(it.index()),
675 static_cast<const OneShotAnalysisState &
>(analysisState))) {
676 yieldValues.push_back(it.value());
679 FailureOr<Value> alloc = allocateTensorForShapedValue(
680 rewriter, yieldOp.getLoc(), it.value(), analysisState.getOptions(),
684 yieldValues.push_back(*alloc);
688 yieldOp, [&]() { yieldOp.getResultsMutable().assign(yieldValues); });
692 FailureOr<BufferLikeType>
694 const BufferizationState &state,
695 SmallVector<Value> &invocationStack)
const {
696 auto forOp = cast<scf::ForOp>(op);
698 assert(isa<TensorLikeType>(value.
getType()) &&
"expected tensor type");
700 if (
auto opResult = dyn_cast<OpResult>(value)) {
702 BlockArgument bbArg = forOp.getTiedLoopRegionIterArg(opResult);
703 return bufferization::getBufferType(bbArg,
options, state,
708 BlockArgument bbArg = cast<BlockArgument>(value);
709 unsigned resultNum = forOp.getTiedLoopResult(bbArg).getResultNumber();
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);
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();
731 FailureOr<SmallVector<Value>> maybeInitArgs =
732 getBuffers(rewriter, forOp.getInitArgsMutable(),
options, state);
733 if (
failed(maybeInitArgs))
735 SmallVector<Value> initArgs = *maybeInitArgs;
738 SmallVector<Value> castedInitArgs;
739 for (
const auto &it : llvm::enumerate(initArgs)) {
740 Value initArg = it.value();
741 Value
result = forOp->getResult(it.index());
743 if (!isa<TensorLikeType>(
result.getType())) {
744 castedInitArgs.push_back(initArg);
747 auto targetType = bufferization::getBufferType(
result,
options, state);
750 FailureOr<Value> castedInitArg =
751 castBuffer(rewriter, initArg.
getLoc(), initArg, *targetType,
options);
752 if (
failed(castedInitArg))
754 castedInitArgs.push_back(*castedInitArg);
758 auto newForOp = scf::ForOp::create(
759 rewriter, forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
760 forOp.getStep(), castedInitArgs,
nullptr,
761 forOp.getUnsignedCmp());
762 newForOp->setDiscardableAttrs(
763 forOp->getDiscardableAttrDictionary().getValue());
764 Block *loopBody = newForOp.getBody();
769 SmallVector<Value> iterArgs =
770 getBbArgReplacements(rewriter, newForOp.getRegionIterArgs(),
771 forOp.getRegionIterArgs(),
indices);
772 iterArgs.insert(iterArgs.begin(), newForOp.getInductionVar());
775 rewriter.
mergeBlocks(oldLoopBody, loopBody, iterArgs);
778 replaceOpWithBufferizedValues(rewriter, op, newForOp->getResults());
790 LogicalResult verifyAnalysis(Operation *op,
791 const AnalysisState &state)
const {
793 static_cast<const OneShotBufferizationOptions &
>(state.getOptions());
794 if (
options.allowReturnAllocsFromLoops)
797 auto forOp = cast<scf::ForOp>(op);
798 auto yieldOp = cast<scf::YieldOp>(forOp.getBody()->getTerminator());
800 if (!isa<TensorLikeType>(opResult.
getType()))
804 if (bufferRelation(op, opResult, state) != BufferRelation::Equivalent)
805 return yieldOp->emitError()
807 <<
" is not equivalent to the corresponding iter bbArg";
816struct WhileOpInterface
817 :
public BufferizableOpInterface::ExternalModel<WhileOpInterface,
819 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
820 const AnalysisState &state)
const {
825 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
826 const AnalysisState &state)
const {
831 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
832 const AnalysisState &state)
const {
833 auto whileOp = cast<scf::WhileOp>(op);
843 OpResult opResult = whileOp->getResult(idx);
844 BufferRelation relation = bufferRelation(op, opResult, state);
845 return {{opResult, relation,
846 relation == BufferRelation::Equivalent}};
849 BufferRelation bufferRelation(Operation *op, OpResult opResult,
850 const AnalysisState &state)
const {
855 auto whileOp = cast<scf::WhileOp>(op);
858 if (resultNumber >= whileOp.getBeforeArguments().size())
859 return BufferRelation::Unknown;
861 whileOp.getBeforeArguments()[resultNumber].getType())
862 return BufferRelation::Unknown;
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);
870 auto yieldOp = whileOp.getYieldOp();
871 BlockArgument bodyBbArg = whileOp.getAfterArguments()[resultNumber];
872 Value yieldOperand = yieldOp.getOperand(resultNumber);
874 state.areEquivalentBufferizedValues(bodyBbArg, yieldOperand);
876 return equivCondition && equivYield ? BufferRelation::Equivalent
877 : BufferRelation::Unknown;
880 bool isWritable(Operation *op, Value value,
881 const AnalysisState &state)
const {
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)))
900 if (analysisState.getOptions().copyBeforeWrite)
910 OpBuilder::InsertionGuard g(rewriter);
911 auto whileOp = cast<scf::WhileOp>(op);
912 auto conditionOp = whileOp.getConditionOp();
917 whileOp.getBeforeArguments(), conditionOp.getArgs(), analysisState);
919 getEquivalentBuffers(whileOp.getAfterArguments(),
920 whileOp.getYieldOp().getResults(), analysisState);
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);
934 FailureOr<Value> alloc = allocateTensorForShapedValue(
935 rewriter, conditionOp.getLoc(), value, analysisState.getOptions(),
939 beforeYieldValues.push_back(*alloc);
942 conditionOp.getArgsMutable().assign(beforeYieldValues);
948 LogicalResult bufferize(Operation *op, RewriterBase &rewriter,
949 const BufferizationOptions &
options,
950 BufferizationState &state)
const {
951 auto whileOp = cast<scf::WhileOp>(op);
957 getTensorIndices(whileOp.getAfterArguments());
960 FailureOr<SmallVector<Value>> maybeInitArgs =
961 getBuffers(rewriter, whileOp.getInitsMutable(),
options, state);
962 if (
failed(maybeInitArgs))
964 SmallVector<Value> initArgs = *maybeInitArgs;
967 SmallVector<Value> castedInitArgs;
968 for (
const auto &it : llvm::enumerate(initArgs)) {
969 Value initArg = it.value();
970 Value beforeArg = whileOp.getBeforeArguments()[it.index()];
972 if (!isa<TensorLikeType>(beforeArg.
getType())) {
973 castedInitArgs.push_back(initArg);
976 auto targetType = bufferization::getBufferType(beforeArg,
options, state);
979 FailureOr<Value> castedInitArg =
980 castBuffer(rewriter, initArg.
getLoc(), initArg, *targetType,
options);
981 if (
failed(castedInitArg))
983 castedInitArgs.push_back(*castedInitArg);
987 SmallVector<Type> argsTypesAfter = llvm::map_to_vector(
988 whileOp.getAfterArguments(), [&](BlockArgument bbArg) {
989 if (!isa<TensorLikeType>(bbArg.getType()))
990 return bbArg.getType();
992 return llvm::cast<Type>(
993 *bufferization::getBufferType(bbArg, options, state));
998 TypeRange argsTypesBefore(argsRangeBefore);
999 auto newWhileOp = scf::WhileOp::create(rewriter, whileOp.getLoc(),
1000 argsTypesAfter, castedInitArgs);
1003 SmallVector<Location> bbArgLocsBefore(castedInitArgs.size(),
1005 SmallVector<Location> bbArgLocsAfter(argsTypesAfter.size(),
1007 Block *newBeforeBody = &newWhileOp.getBefore().emplaceBlock();
1008 newWhileOp.getBefore().addArguments(argsTypesBefore, bbArgLocsBefore);
1009 Block *newAfterBody = &newWhileOp.getAfter().emplaceBlock();
1010 newWhileOp.getAfter().addArguments(argsTypesAfter, bbArgLocsAfter);
1016 SmallVector<Value> newBeforeArgs =
1017 getBbArgReplacements(rewriter, newWhileOp.getBeforeArguments(),
1018 whileOp.getBeforeArguments(), indicesBefore);
1019 rewriter.
mergeBlocks(whileOp.getBeforeBody(), newBeforeBody, newBeforeArgs);
1025 SmallVector<Value> newAfterArgs =
1026 getBbArgReplacements(rewriter, newWhileOp.getAfterArguments(),
1027 whileOp.getAfterArguments(), indicesAfter);
1028 rewriter.
mergeBlocks(whileOp.getAfterBody(), newAfterBody, newAfterArgs);
1031 replaceOpWithBufferizedValues(rewriter, op, newWhileOp->getResults());
1036 FailureOr<BufferLikeType>
1038 const BufferizationState &state,
1039 SmallVector<Value> &invocationStack)
const {
1040 auto whileOp = cast<scf::WhileOp>(op);
1042 assert(isa<TensorLikeType>(value.
getType()) &&
"expected tensor type");
1045 if (
auto bbArg = dyn_cast<BlockArgument>(value)) {
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);
1059 if (
auto opResult = dyn_cast<OpResult>(value)) {
1061 }
else if (cast<BlockArgument>(value).getOwner()->getParent() ==
1062 &whileOp.getAfter()) {
1063 resultNum = cast<BlockArgument>(value).getArgNumber();
1065 llvm_unreachable(
"invalid value");
1067 Value conditionYieldedVal = whileOp.getConditionOp().getArgs()[resultNum];
1068 if (!isa<TensorLikeType>(conditionYieldedVal.
getType())) {
1070 return cast<BufferLikeType>(conditionYieldedVal.
getType());
1072 return bufferization::getBufferType(conditionYieldedVal,
options, state,
1086 LogicalResult verifyAnalysis(Operation *op,
1087 const AnalysisState &state)
const {
1088 auto whileOp = cast<scf::WhileOp>(op);
1090 static_cast<const OneShotBufferizationOptions &
>(state.getOptions());
1091 if (
options.allowReturnAllocsFromLoops)
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()))
1100 !state.areEquivalentBufferizedValues(it.value(),
1102 return conditionOp->emitError()
1103 <<
"Condition arg #" << it.index()
1104 <<
" is not equivalent to the corresponding iter bbArg";
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()))
1113 !state.areEquivalentBufferizedValues(it.value(),
1115 return yieldOp->emitError()
1116 <<
"Yield operand #" << it.index()
1117 <<
" is not equivalent to the corresponding iter bbArg";
1126struct YieldOpInterface
1127 :
public BufferizableOpInterface::ExternalModel<YieldOpInterface,
1129 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1130 const AnalysisState &state)
const {
1134 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1135 const AnalysisState &state)
const {
1139 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
1140 const AnalysisState &state)
const {
1141 if (isa<scf::IfOp, scf::IndexSwitchOp>(op->
getParentOp()))
1143 BufferRelation::Equivalent,
false}};
1146 BufferRelation::Equivalent}};
1150 bool mustBufferizeInPlace(Operation *op, OpOperand &opOperand,
1151 const AnalysisState &state)
const {
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");
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);
1174 Value buffer = *maybeBuffer;
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);
1182 FailureOr<Value> castedBuffer = castBuffer(
1184 if (
failed(castedBuffer))
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);
1193 FailureOr<Value> castedBuffer = castBuffer(
1195 if (
failed(castedBuffer))
1197 buffer = *castedBuffer;
1199 newResults.push_back(buffer);
1201 newResults.push_back(value);
1205 replaceOpWithNewBufferizedOp<scf::YieldOp>(rewriter, op, newResults);
1214struct ForallOpInterface
1215 :
public BufferizableOpInterface::ExternalModel<ForallOpInterface,
1217 bool bufferizesToMemoryRead(Operation *op, OpOperand &opOperand,
1218 const AnalysisState &state)
const {
1226 bool bufferizesToMemoryWrite(Operation *op, OpOperand &opOperand,
1227 const AnalysisState &state)
const {
1232 AliasingValueList getAliasingValues(Operation *op, OpOperand &opOperand,
1233 const AnalysisState &state)
const {
1234 auto forallOp = cast<ForallOp>(op);
1236 {{forallOp.getTiedOpResult(&opOperand), BufferRelation::Equivalent}}};
1239 AliasingOpOperandList
1240 getAliasingOpOperands(Operation *op, Value value,
1241 const AnalysisState &state)
const {
1242 auto result = dyn_cast<OpResult>(value);
1245 auto forallOp = cast<ForallOp>(op);
1246 return {{forallOp.getTiedOpOperand(
result), BufferRelation::Equivalent}};
1249 bool isWritable(Operation *op, Value value,
1250 const AnalysisState &state)
const {
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();
1262 SmallVector<Value> buffers;
1263 for (Value out : forallOp.getOutputs()) {
1264 FailureOr<Value> buffer = getBuffer(rewriter, out,
options, state);
1267 buffers.push_back(*buffer);
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(),
1284 ForallOp newForallOp;
1285 newForallOp = ForallOp::create(
1286 rewriter, forallOp.getLoc(), forallOp.getMixedLowerBound(),
1287 forallOp.getMixedUpperBound(), forallOp.getMixedStep(),
1293 rewriter.
eraseOp(newForallOp.getBody()->getTerminator());
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(),
1304 replaceOpWithBufferizedValues(rewriter, op, buffers);
1309 FailureOr<BufferLikeType>
1311 const BufferizationState &state,
1312 SmallVector<Value> &invocationStack)
const {
1313 auto forallOp = cast<ForallOp>(op);
1315 if (
auto bbArg = dyn_cast<BlockArgument>(value))
1318 return bufferization::getBufferType(
1319 forallOp.getTiedOpOperand(bbArg)->get(),
options, state,
1324 return bufferization::getBufferType(
1325 forallOp.getOutputs()[cast<OpResult>(value).getResultNumber()],
options,
1326 state, invocationStack);
1330 auto forallOp = cast<ForallOp>(op);
1334 for (
auto [lb, ub, step] :
1335 llvm::zip(forallOp.getMixedLowerBound(), forallOp.getMixedUpperBound(),
1336 forallOp.getMixedStep())) {
1349 if (*lbConstant + *stepConstant < *ubConstant)
1355 bool isParallelRegion(Operation *op,
unsigned index)
const {
1361struct InParallelOpInterface
1362 :
public BufferizableOpInterface::ExternalModel<InParallelOpInterface,
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");
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);
static bool isRepetitiveRegion(Region *region, const BufferizationOptions &options)
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.
Block * getOwner() const
Returns the block that owns this argument.
MutableArrayRef< BlockArgument > BlockArgListType
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
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.
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
unsigned getResultNumber() const
Returns the number of this result.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
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.
result_range getOpResults()
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.
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
bool isProperAncestor(Region *other)
Return true if this region is a proper ancestor of the other region.
bool hasOneBlock()
Return true if this region has exactly one block.
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 ®ion, 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.
void replaceAllUsesWith(Value newValue)
Replace all uses of 'this' value with the new value, updating anything in the IR that uses 'this' to ...
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Region * getParentRegion()
Return the Region in which this Value is defined.
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)...
void registerBufferizableOpInterfaceExternalModels(DialectRegistry ®istry)
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.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet