31#include "llvm/ADT/MapVector.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallVectorExtras.h"
35#include "llvm/ADT/TypeSwitch.h"
36#include "llvm/Support/Casting.h"
37#include "llvm/Support/DebugLog.h"
43#include "mlir/Dialect/SCF/IR/SCFOpsDialect.cpp.inc"
50struct SCFInlinerInterface :
public DialectInlinerInterface {
51 using DialectInlinerInterface::DialectInlinerInterface;
55 IRMapping &valueMapping)
const final {
60 bool isLegalToInline(Operation *, Region *,
bool, IRMapping &)
const final {
65 void handleTerminator(Operation *op,
ValueRange valuesToRepl)
const final {
66 auto retValOp = dyn_cast<scf::YieldOp>(op);
70 for (
auto retValue : llvm::zip(valuesToRepl, retValOp.getOperands())) {
71 std::get<0>(retValue).replaceAllUsesWith(std::get<1>(retValue));
81void SCFDialect::initialize() {
82 addInterfaces<SCFInlinerInterface>();
83 declarePromisedInterface<ConvertToEmitCPatternInterface, SCFDialect>();
84 declarePromisedInterfaces<bufferization::BufferDeallocationOpInterface,
85 InParallelOp, ReduceReturnOp>();
86 declarePromisedInterfaces<bufferization::BufferizableOpInterface, ConditionOp,
87 ExecuteRegionOp, ForOp, IfOp, IndexSwitchOp,
88 ForallOp, InParallelOp, WhileOp, YieldOp>();
89 declarePromisedInterface<ValueBoundsOpInterface, ForOp>();
94 scf::YieldOp::create(builder, loc);
99template <
typename TerminatorTy>
101 StringRef errorMessage) {
102 Operation *terminatorOperation =
nullptr;
104 terminatorOperation = ®ion.
front().
back();
105 if (
auto yield = dyn_cast_or_null<TerminatorTy>(terminatorOperation))
109 if (terminatorOperation)
110 diag.attachNote(terminatorOperation->
getLoc()) <<
"terminator here";
117 auto addOp =
ub.getDefiningOp<arith::AddIOp>();
120 if ((isSigned && !addOp.hasNoSignedWrap()) ||
121 (!isSigned && !addOp.hasNoUnsignedWrap()))
124 if (addOp.getLhs() != lb ||
145ParseResult ExecuteRegionOp::parse(
OpAsmParser &parser,
173LogicalResult ExecuteRegionOp::verify() {
174 if (getRegion().empty())
175 return emitOpError(
"region needs to have at least one block");
176 if (getRegion().front().getNumArguments() > 0)
177 return emitOpError(
"region cannot have any arguments");
223 if (op.getNoInline())
225 if (!isa<FunctionOpInterface, ExecuteRegionOp>(op->getParentOp()))
228 Block *prevBlock = op->getBlock();
232 cf::BranchOp::create(rewriter, op.getLoc(), &op.getRegion().front());
234 for (
Block &blk : op.getRegion()) {
235 if (YieldOp yieldOp = dyn_cast<YieldOp>(blk.getTerminator())) {
237 cf::BranchOp::create(rewriter, yieldOp.getLoc(), postBlock,
238 yieldOp.getResults());
246 for (
auto res : op.getResults())
247 blockArgs.push_back(postBlock->
addArgument(res.getType(), res.getLoc()));
258 results, ExecuteRegionOp::getOperationName());
261 results, ExecuteRegionOp::getOperationName(),
263 return failure(cast<ExecuteRegionOp>(op).getNoInline());
267void ExecuteRegionOp::getSuccessorRegions(
279void ExecuteRegionOp::getRegionInvocationBounds(
281 bounds.emplace_back(1, 1);
297 "condition op can only exit the loop or branch to the after"
300 return getArgsMutable();
303void ConditionOp::getSuccessorRegions(
305 FoldAdaptor adaptor(operands, *
this);
307 WhileOp whileOp = getParentOp();
311 auto boolAttr = dyn_cast_or_null<BoolAttr>(adaptor.getCondition());
312 if (!boolAttr || boolAttr.getValue())
313 regions.emplace_back(&whileOp.getAfter());
314 if (!boolAttr || !boolAttr.getValue())
324 BodyBuilderFn bodyBuilder,
bool unsignedCmp) {
328 result.addAttribute(getUnsignedCmpAttrName(
result.name),
331 result.addOperands(initArgs);
332 for (
Value v : initArgs)
333 result.addTypes(v.getType());
338 for (
Value v : initArgs)
344 if (initArgs.empty() && !bodyBuilder) {
345 ForOp::ensureTerminator(*bodyRegion, builder,
result.location);
346 }
else if (bodyBuilder) {
354LogicalResult ForOp::verify() {
359 if (getBody()->getNumArguments() < getNumInductionVars())
360 return emitOpError(
"expected body to have at least ")
361 << getNumInductionVars()
362 <<
" argument(s) for the induction variable, but got "
363 << getBody()->getNumArguments();
366 if (getInitArgs().size() != getNumResults())
368 "mismatch in number of loop-carried values and defined values");
373LogicalResult ForOp::verifyRegions() {
375 if (getBody()->getNumArguments() < getNumInductionVars())
376 return emitOpError(
"expected body to have at least ")
377 << getNumInductionVars() <<
" argument(s) for the induction "
378 <<
"variable, but got " << getBody()->getNumArguments();
384 "expected induction variable to be same type as bounds and step");
386 if (getNumRegionIterArgs() != getNumResults())
388 "mismatch in number of basic block args and defined values");
390 auto initArgs = getInitArgs();
391 auto iterArgs = getRegionIterArgs();
392 auto opResults = getResults();
394 for (
auto e : llvm::zip(initArgs, iterArgs, opResults)) {
396 return emitOpError() <<
"types mismatch between " << i
397 <<
"th iter operand and defined value";
399 return emitOpError() <<
"types mismatch between " << i
400 <<
"th iter region arg and defined value";
407std::optional<SmallVector<Value>> ForOp::getLoopInductionVars() {
411std::optional<SmallVector<OpFoldResult>> ForOp::getLoopLowerBounds() {
415std::optional<SmallVector<OpFoldResult>> ForOp::getLoopSteps() {
419std::optional<SmallVector<OpFoldResult>> ForOp::getLoopUpperBounds() {
423bool ForOp::isValidInductionVarType(
Type type) {
428 if (bounds.size() != 1)
430 if (
auto val = dyn_cast<Value>(bounds[0])) {
438 if (bounds.size() != 1)
440 if (
auto val = dyn_cast<Value>(bounds[0])) {
448 if (steps.size() != 1)
450 if (
auto val = dyn_cast<Value>(steps[0])) {
457std::optional<ResultRange> ForOp::getLoopResults() {
return getResults(); }
461LogicalResult ForOp::promoteIfSingleIteration(
RewriterBase &rewriter) {
462 std::optional<APInt> tripCount = getStaticTripCount();
463 LDBG() <<
"promoteIfSingleIteration tripCount is " << tripCount
466 if (!tripCount.has_value() || tripCount->getZExtValue() > 1)
469 if (*tripCount == 0) {
476 auto yieldOp = cast<scf::YieldOp>(getBody()->getTerminator());
483 llvm::append_range(bbArgReplacements, getInitArgs());
487 getOperation()->getIterator(), bbArgReplacements);
503 StringRef prefix =
"") {
504 assert(blocksArgs.size() == initializers.size() &&
505 "expected same length of arguments and initializers");
506 if (initializers.empty())
510 llvm::interleaveComma(llvm::zip(blocksArgs, initializers), p, [&](
auto it) {
511 p << std::get<0>(it) <<
" = " << std::get<1>(it);
517 if (getUnsignedCmp())
520 p <<
" " << getInductionVar() <<
" = " <<
getLowerBound() <<
" to "
524 if (!getInitArgs().empty())
525 p <<
" -> (" << getInitArgs().getTypes() <<
')';
528 p <<
" : " << t <<
' ';
531 !getInitArgs().empty());
543 result.addAttribute(getUnsignedCmpAttrName(
result.name),
557 regionArgs.push_back(inductionVariable);
567 if (regionArgs.size() !=
result.types.size() + 1)
570 "mismatch in number of loop-carried values and defined values");
579 regionArgs.front().type = type;
580 for (
auto [iterArg, type] :
581 llvm::zip_equal(llvm::drop_begin(regionArgs),
result.types))
588 ForOp::ensureTerminator(*body, builder,
result.location);
597 for (
auto argOperandType : llvm::zip_equal(llvm::drop_begin(regionArgs),
598 operands,
result.types)) {
599 Type type = std::get<2>(argOperandType);
600 std::get<0>(argOperandType).type = type;
617 return getBody()->getArguments().drop_front(getNumInductionVars());
621 return getInitArgsMutable();
624FailureOr<LoopLikeOpInterface>
625ForOp::replaceWithAdditionalYields(
RewriterBase &rewriter,
627 bool replaceInitOperandUsesInLoop,
632 auto inits = llvm::to_vector(getInitArgs());
633 inits.append(newInitOperands.begin(), newInitOperands.end());
634 scf::ForOp newLoop = scf::ForOp::create(
637 newLoop->setDiscardableAttrs(getOperation()->getDiscardableAttrDictionary());
640 auto yieldOp = cast<scf::YieldOp>(getBody()->getTerminator());
642 newLoop.getBody()->getArguments().take_back(newInitOperands.size());
647 newYieldValuesFn(rewriter, getLoc(), newIterArgs);
648 assert(newInitOperands.size() == newYieldedValues.size() &&
649 "expected as many new yield values as new iter operands");
651 yieldOp.getResultsMutable().append(newYieldedValues);
657 newLoop.getBody()->getArguments().take_front(
658 getBody()->getNumArguments()));
660 if (replaceInitOperandUsesInLoop) {
663 for (
auto it : llvm::zip(newInitOperands, newIterArgs)) {
674 newLoop->getResults().take_front(getNumResults()));
675 return cast<LoopLikeOpInterface>(newLoop.getOperation());
679 auto ivArg = llvm::dyn_cast<BlockArgument>(val);
682 assert(ivArg.getOwner() &&
"unlinked block argument");
683 auto *containingOp = ivArg.getOwner()->getParentOp();
684 return dyn_cast_or_null<ForOp>(containingOp);
688 return getInitArgs();
693 if (std::optional<APInt> tripCount = getStaticTripCount()) {
696 if (*tripCount == 0) {
705 }
else if (*tripCount == 1) {
729LogicalResult scf::ForallOp::promoteIfSingleIteration(RewriterBase &rewriter) {
730 for (
auto [lb, ub, step] :
731 llvm::zip(getMixedLowerBound(), getMixedUpperBound(), getMixedStep())) {
734 if (!tripCount.has_value() || *tripCount != 1)
738 return promote(rewriter, *
this);
742 return getBody()->getArguments().drop_front(getRank());
745MutableArrayRef<OpOperand> ForallOp::getInitsMutable() {
746 return getOutputsMutable();
751 scf::ForallOp forallOp) {
753 scf::InParallelOp terminator = forallOp.getTerminator();
757 for (
Operation &op : terminator.getYieldingOps()) {
758 if (!isa<tensor::ParallelInsertSliceOp>(op))
760 diag <<
"unsupported parallel combining op: " << op.
getName();
767 bbArgReplacements.append(forallOp.getOutputs().begin(),
768 forallOp.getOutputs().end());
773 yieldingOps.reserve(forallOp.getNumResults());
775 for (
BlockArgument outputArg : forallOp.getRegionIterArgs()) {
776 auto &outputOps = yieldingOps.emplace_back();
778 for (
Operation *op : forallOp.getCombiningOps(outputArg)) {
779 auto combiningOp = cast<ParallelCombiningOpInterface>(op);
781 if (combiningOp->getParentOp() != terminator.getOperation() ||
782 combiningOp.getUpdatedDestinations()[0].get() != outputArg)
785 outputOps.push_back(combiningOp);
791 forallOp->getIterator(), bbArgReplacements);
796 results.reserve(forallOp.getResults().size());
797 for (
auto [output, combiningOps] :
798 llvm::zip_equal(forallOp.getOutputs(), yieldingOps)) {
801 for (ParallelCombiningOpInterface combiningOp : combiningOps) {
802 auto insertOp = cast<tensor::ParallelInsertSliceOp>(combiningOp);
803 result = tensor::InsertSliceOp::create(
804 rewriter, forallOp.getLoc(),
result.getType(), insertOp.getSource(),
805 result, insertOp.getOffsets(), insertOp.getSizes(),
806 insertOp.getStrides(), insertOp.getStaticOffsets(),
807 insertOp.getStaticSizes(), insertOp.getStaticStrides());
810 results.push_back(
result);
826 assert(lbs.size() == ubs.size() &&
827 "expected the same number of lower and upper bounds");
828 assert(lbs.size() == steps.size() &&
829 "expected the same number of lower bounds and steps");
834 bodyBuilder ? bodyBuilder(builder, loc,
ValueRange(), iterArgs)
836 assert(results.size() == iterArgs.size() &&
837 "loop nest body must return as many values as loop has iteration "
839 return LoopNest{{}, std::move(results)};
847 loops.reserve(lbs.size());
848 ivs.reserve(lbs.size());
851 for (
unsigned i = 0, e = lbs.size(); i < e; ++i) {
852 auto loop = scf::ForOp::create(
853 builder, currentLoc, lbs[i], ubs[i], steps[i], currentIterArgs,
859 currentIterArgs = args;
860 currentLoc = nestedLoc;
866 loops.push_back(loop);
870 for (
unsigned i = 0, e = loops.size() - 1; i < e; ++i) {
872 scf::YieldOp::create(builder, loc, loops[i + 1].getResults());
879 ? bodyBuilder(builder, currentLoc, ivs,
880 loops.back().getRegionIterArgs())
882 assert(results.size() == iterArgs.size() &&
883 "loop nest body must return as many values as loop has iteration "
886 scf::YieldOp::create(builder, loc, results);
890 llvm::append_range(nestResults, loops.front().getResults());
891 return LoopNest{std::move(loops), std::move(nestResults)};
904 bodyBuilder(nestedBuilder, nestedLoc, ivs);
913 assert(operand.
getOwner() == forOp);
918 "expected an iter OpOperand");
920 "Expected a different type");
922 for (
OpOperand &opOperand : forOp.getInitArgsMutable()) {
927 newIterOperands.push_back(opOperand.get());
931 scf::ForOp newForOp = scf::ForOp::create(
932 rewriter, forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
933 forOp.getStep(), newIterOperands,
nullptr,
934 forOp.getUnsignedCmp());
935 newForOp->setDiscardableAttrs(
936 forOp->getDiscardableAttrDictionary().getValue());
937 Block &newBlock = newForOp.getRegion().
front();
945 BlockArgument newRegionIterArg = newForOp.getTiedLoopRegionIterArg(
947 Value castIn = castFn(rewriter, newForOp.getLoc(), oldType, newRegionIterArg);
948 newBlockTransferArgs[newRegionIterArg.
getArgNumber()] = castIn;
952 rewriter.
mergeBlocks(&oldBlock, &newBlock, newBlockTransferArgs);
955 auto clonedYieldOp = cast<scf::YieldOp>(newBlock.
getTerminator());
958 newRegionIterArg.
getArgNumber() - forOp.getNumInductionVars();
959 Value castOut = castFn(rewriter, newForOp.getLoc(), newType,
960 clonedYieldOp.getOperand(yieldIdx));
962 newYieldOperands[yieldIdx] = castOut;
963 scf::YieldOp::create(rewriter, newForOp.getLoc(), newYieldOperands);
964 rewriter.
eraseOp(clonedYieldOp);
969 newResults[yieldIdx] =
970 castFn(rewriter, newForOp.getLoc(), oldType, newResults[yieldIdx]);
976 assert(arg <
static_cast<int64_t>(forOp.getNumResults()) &&
977 "arg is out of bounds");
978 Value value = forOp.getYieldedValues()[arg];
980 if (value == forOp.getRegionIterArgs()[arg])
982 OpResult opResult = dyn_cast<OpResult>(value);
987 .Case([&](DestinationStyleOpInterface op) {
988 return op.getTiedOpOperand(opResult)->get();
990 .Case([&](ForOp forOp) {
1030 LogicalResult matchAndRewrite(ForOp op,
1032 for (
auto it : llvm::zip(op.getInitArgsMutable(), op.getResults())) {
1033 OpOperand &iterOpOperand = std::get<0>(it);
1035 if (!incomingCast ||
1036 incomingCast.getSource().getType() == incomingCast.getType())
1041 incomingCast.getDest().getType(),
1042 incomingCast.getSource().getType()))
1044 if (!std::get<1>(it).hasOneUse())
1050 int64_t resultNumber = std::get<1>(it).getResultNumber();
1052 op.getYieldedValues()[resultNumber].getDefiningOp<tensor::CastOp>();
1053 bool yieldsStaticType =
1054 yieldedCast && yieldedCast.getSource().getType() ==
1055 incomingCast.getSource().getType();
1062 rewriter, op, iterOpOperand, incomingCast.getSource(),
1064 return tensor::CastOp::create(b, loc, type, source);
1073void ForOp::getCanonicalizationPatterns(RewritePatternSet &results,
1074 MLIRContext *context) {
1075 results.
add<ForOpTensorCastFolder>(context);
1077 results, ForOp::getOperationName());
1082 results, ForOp::getOperationName(),
1084 [](OpBuilder &builder, Location loc, Value value) {
1088 auto blockArg = cast<BlockArgument>(value);
1089 assert(blockArg.getArgNumber() == 0 &&
"expected induction variable");
1090 auto forOp = cast<ForOp>(blockArg.getOwner()->getParentOp());
1091 return forOp.getLowerBound();
1097std::optional<APInt> ForOp::getConstantStep() {
1100 return step.getValue();
1104std::optional<MutableArrayRef<OpOperand>> ForOp::getYieldedValuesMutable() {
1105 return cast<scf::YieldOp>(getBody()->getTerminator()).getResultsMutable();
1111 if (
auto constantStep = getConstantStep())
1112 if (*constantStep == 1)
1120std::optional<APInt> ForOp::getStaticTripCount() {
1129LogicalResult ForallOp::verify() {
1130 unsigned numLoops = getRank();
1132 if (getNumResults() != getOutputs().size())
1133 return emitOpError(
"produces ")
1134 << getNumResults() <<
" results, but has only "
1135 << getOutputs().size() <<
" outputs";
1138 auto *body = getBody();
1140 return emitOpError(
"region expects ") << numLoops <<
" arguments";
1141 for (int64_t i = 0; i < numLoops; ++i)
1143 return emitOpError(
"expects ")
1144 << i <<
"-th block argument to be an index";
1145 for (
unsigned i = 0; i < getOutputs().size(); ++i)
1147 return emitOpError(
"type mismatch between ")
1148 << i <<
"-th output and corresponding block argument";
1149 if (getMapping().has_value() && !getMapping()->empty()) {
1150 if (getDeviceMappingAttrs().size() != numLoops)
1151 return emitOpError() <<
"mapping attribute size must match op rank";
1152 if (
failed(getDeviceMaskingAttr()))
1154 <<
" supports at most one device masking attribute";
1158 Operation *op = getOperation();
1160 getStaticLowerBound(),
1161 getDynamicLowerBound())))
1164 getStaticUpperBound(),
1165 getDynamicUpperBound())))
1168 getStaticStep(), getDynamicStep())))
1174void ForallOp::print(OpAsmPrinter &p) {
1175 Operation *op = getOperation();
1176 p <<
" (" << getInductionVars();
1177 if (isNormalized()) {
1198 if (!getRegionOutArgs().empty())
1199 p <<
"-> (" << getResultTypes() <<
") ";
1200 p.printRegion(getRegion(),
1202 getNumResults() > 0);
1204 if (
ArrayAttr mapping = getMappingAttr())
1207 p.printOptionalAttrDict(attrs);
1210ParseResult ForallOp::parse(OpAsmParser &parser, OperationState &
result) {
1212 auto indexType =
b.getIndexType();
1217 SmallVector<OpAsmParser::Argument, 4> ivs;
1222 SmallVector<OpAsmParser::UnresolvedOperand> dynamicLbs, dynamicUbs,
1232 unsigned numLoops = ivs.size();
1233 staticLbs =
b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 0));
1234 staticSteps =
b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 1));
1263 SmallVector<OpAsmParser::Argument, 4> regionOutArgs;
1264 SmallVector<OpAsmParser::UnresolvedOperand, 4> outOperands;
1267 if (outOperands.size() !=
result.types.size())
1269 "mismatch between out operands and types");
1278 SmallVector<OpAsmParser::Argument, 4> regionArgs;
1279 std::unique_ptr<Region> region = std::make_unique<Region>();
1280 for (
auto &iv : ivs) {
1281 iv.type =
b.getIndexType();
1282 regionArgs.push_back(iv);
1284 for (
const auto &it : llvm::enumerate(regionOutArgs)) {
1285 auto &out = it.value();
1286 out.type =
result.types[it.index()];
1287 regionArgs.push_back(out);
1293 ForallOp::ensureTerminator(*region,
b,
result.location);
1294 result.addRegion(std::move(region));
1300 result.addAttribute(
"staticLowerBound", staticLbs);
1301 result.addAttribute(
"staticUpperBound", staticUbs);
1302 result.addAttribute(
"staticStep", staticSteps);
1303 result.addAttribute(
"operandSegmentSizes",
1305 {static_cast<int32_t>(dynamicLbs.size()),
1306 static_cast<int32_t>(dynamicUbs.size()),
1307 static_cast<int32_t>(dynamicSteps.size()),
1308 static_cast<int32_t>(outOperands.size())}));
1313void ForallOp::build(
1314 mlir::OpBuilder &
b, mlir::OperationState &
result,
1315 ArrayRef<OpFoldResult> lbs, ArrayRef<OpFoldResult> ubs,
1316 ArrayRef<OpFoldResult> steps,
ValueRange outputs,
1317 std::optional<ArrayAttr> mapping,
1319 SmallVector<int64_t> staticLbs, staticUbs, staticSteps;
1320 SmallVector<Value> dynamicLbs, dynamicUbs, dynamicSteps;
1325 result.addOperands(dynamicLbs);
1326 result.addOperands(dynamicUbs);
1327 result.addOperands(dynamicSteps);
1328 result.addOperands(outputs);
1331 result.addAttribute(getStaticLowerBoundAttrName(
result.name),
1332 b.getDenseI64ArrayAttr(staticLbs));
1333 result.addAttribute(getStaticUpperBoundAttrName(
result.name),
1334 b.getDenseI64ArrayAttr(staticUbs));
1335 result.addAttribute(getStaticStepAttrName(
result.name),
1336 b.getDenseI64ArrayAttr(staticSteps));
1338 "operandSegmentSizes",
1339 b.getDenseI32ArrayAttr({static_cast<int32_t>(dynamicLbs.size()),
1340 static_cast<int32_t>(dynamicUbs.size()),
1341 static_cast<int32_t>(dynamicSteps.size()),
1342 static_cast<int32_t>(outputs.size())}));
1343 if (mapping.has_value()) {
1344 result.addAttribute(ForallOp::getMappingAttrName(
result.name),
1348 Region *bodyRegion =
result.addRegion();
1349 OpBuilder::InsertionGuard g(
b);
1350 b.createBlock(bodyRegion);
1355 SmallVector<Type>(lbs.size(),
b.getIndexType()),
1356 SmallVector<Location>(staticLbs.size(),
result.location));
1359 SmallVector<Location>(outputs.size(),
result.location));
1361 b.setInsertionPointToStart(&bodyBlock);
1362 if (!bodyBuilderFn) {
1363 ForallOp::ensureTerminator(*bodyRegion,
b,
result.location);
1370void ForallOp::build(
1371 mlir::OpBuilder &
b, mlir::OperationState &
result,
1372 ArrayRef<OpFoldResult> ubs,
ValueRange outputs,
1373 std::optional<ArrayAttr> mapping,
1375 unsigned numLoops = ubs.size();
1376 SmallVector<OpFoldResult> lbs(numLoops,
b.getIndexAttr(0));
1377 SmallVector<OpFoldResult> steps(numLoops,
b.getIndexAttr(1));
1378 build(
b,
result, lbs, ubs, steps, outputs, mapping, bodyBuilderFn);
1382bool ForallOp::isNormalized() {
1383 auto allEqual = [](ArrayRef<OpFoldResult> results, int64_t val) {
1384 return llvm::all_of(results, [&](OpFoldResult ofr) {
1386 return intValue.has_value() && intValue == val;
1389 return allEqual(getMixedLowerBound(), 0) && allEqual(getMixedStep(), 1);
1392InParallelOp ForallOp::getTerminator() {
1393 return cast<InParallelOp>(getBody()->getTerminator());
1396SmallVector<Operation *> ForallOp::getCombiningOps(BlockArgument bbArg) {
1397 SmallVector<Operation *> storeOps;
1398 for (Operation *user : bbArg.
getUsers()) {
1399 if (
auto parallelOp = dyn_cast<ParallelCombiningOpInterface>(user)) {
1400 storeOps.push_back(parallelOp);
1406SmallVector<DeviceMappingAttrInterface> ForallOp::getDeviceMappingAttrs() {
1407 SmallVector<DeviceMappingAttrInterface> res;
1410 for (
auto attr : getMapping()->getValue()) {
1411 auto m = dyn_cast<DeviceMappingAttrInterface>(attr);
1418FailureOr<DeviceMaskingAttrInterface> ForallOp::getDeviceMaskingAttr() {
1419 DeviceMaskingAttrInterface res;
1422 for (
auto attr : getMapping()->getValue()) {
1423 auto m = dyn_cast<DeviceMaskingAttrInterface>(attr);
1432bool ForallOp::usesLinearMapping() {
1433 SmallVector<DeviceMappingAttrInterface> ifaces = getDeviceMappingAttrs();
1436 return ifaces.front().isLinearMapping();
1439std::optional<SmallVector<Value>> ForallOp::getLoopInductionVars() {
1440 return SmallVector<Value>{getBody()->getArguments().take_front(getRank())};
1444std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopLowerBounds() {
1446 return getMixedValues(getStaticLowerBound(), getDynamicLowerBound(),
b);
1450std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopUpperBounds() {
1452 return getMixedValues(getStaticUpperBound(), getDynamicUpperBound(),
b);
1456std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopSteps() {
1462 auto tidxArg = llvm::dyn_cast<BlockArgument>(val);
1465 assert(tidxArg.getOwner() &&
"unlinked block argument");
1466 auto *containingOp = tidxArg.getOwner()->getParentOp();
1467 return dyn_cast<ForallOp>(containingOp);
1475 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
1477 auto forallOp = dimOp.getSource().getDefiningOp<ForallOp>();
1481 forallOp.getTiedOpOperand(llvm::cast<OpResult>(dimOp.getSource()))
1484 dimOp, [&]() { dimOp.getSourceMutable().assign(sharedOut); });
1489class ForallOpControlOperandsFolder :
public OpRewritePattern<ForallOp> {
1491 using OpRewritePattern<ForallOp>::OpRewritePattern;
1493 LogicalResult matchAndRewrite(ForallOp op,
1494 PatternRewriter &rewriter)
const override {
1495 SmallVector<OpFoldResult> mixedLowerBound(op.getMixedLowerBound());
1496 SmallVector<OpFoldResult> mixedUpperBound(op.getMixedUpperBound());
1497 SmallVector<OpFoldResult> mixedStep(op.getMixedStep());
1504 SmallVector<Value> dynamicLowerBound, dynamicUpperBound, dynamicStep;
1505 SmallVector<int64_t> staticLowerBound, staticUpperBound, staticStep;
1508 op.getDynamicLowerBoundMutable().assign(dynamicLowerBound);
1509 op.setStaticLowerBound(staticLowerBound);
1513 op.getDynamicUpperBoundMutable().assign(dynamicUpperBound);
1514 op.setStaticUpperBound(staticUpperBound);
1517 op.getDynamicStepMutable().assign(dynamicStep);
1518 op.setStaticStep(staticStep);
1520 op->setInherentAttr(
1521 rewriter.
getStringAttr(ForallOp::getOperandSegmentSizeAttr()),
1523 {static_cast<int32_t>(dynamicLowerBound.size()),
1524 static_cast<int32_t>(dynamicUpperBound.size()),
1525 static_cast<int32_t>(dynamicStep.size()),
1526 static_cast<int32_t>(op.getNumResults())}));
1605struct ForallOpIterArgsFolder :
public OpRewritePattern<ForallOp> {
1606 using OpRewritePattern<ForallOp>::OpRewritePattern;
1608 LogicalResult matchAndRewrite(ForallOp forallOp,
1609 PatternRewriter &rewriter)
const final {
1620 SmallVector<Value> resultsToDelete;
1621 SmallVector<Value> outsToDelete;
1622 SmallVector<BlockArgument> blockArgsToDelete;
1623 SmallVector<Value> newOuts;
1624 BitVector resultIndicesToDelete(forallOp.getNumResults(),
false);
1625 BitVector blockIndicesToDelete(forallOp.getBody()->getNumArguments(),
1627 for (OpResult
result : forallOp.getResults()) {
1628 OpOperand *opOperand = forallOp.getTiedOpOperand(
result);
1629 BlockArgument blockArg = forallOp.getTiedBlockArgument(opOperand);
1630 if (
result.use_empty() || forallOp.getCombiningOps(blockArg).empty()) {
1631 resultsToDelete.push_back(
result);
1632 outsToDelete.push_back(opOperand->
get());
1633 blockArgsToDelete.push_back(blockArg);
1634 resultIndicesToDelete[
result.getResultNumber()] =
true;
1637 newOuts.push_back(opOperand->
get());
1643 if (resultsToDelete.empty())
1648 for (
auto blockArg : blockArgsToDelete) {
1649 SmallVector<Operation *> combiningOps =
1650 forallOp.getCombiningOps(blockArg);
1651 for (Operation *combiningOp : combiningOps)
1652 rewriter.
eraseOp(combiningOp);
1654 for (
auto [blockArg,
result, out] :
1655 llvm::zip_equal(blockArgsToDelete, resultsToDelete, outsToDelete)) {
1661 forallOp.getBody()->eraseArguments(blockIndicesToDelete);
1666 auto newForallOp = cast<scf::ForallOp>(
1668 newForallOp.getOutputsMutable().assign(newOuts);
1674struct ForallOpSingleOrZeroIterationDimsFolder
1675 :
public OpRewritePattern<ForallOp> {
1676 using OpRewritePattern<ForallOp>::OpRewritePattern;
1678 LogicalResult matchAndRewrite(ForallOp op,
1679 PatternRewriter &rewriter)
const override {
1681 if (op.getMapping().has_value() && !op.getMapping()->empty())
1683 Location loc = op.getLoc();
1686 SmallVector<OpFoldResult> newMixedLowerBounds, newMixedUpperBounds,
1688 SmallVector<std::pair<Value, OpFoldResult>> singleIterationIVs;
1689 for (
auto [lb, ub, step, iv] :
1690 llvm::zip(op.getMixedLowerBound(), op.getMixedUpperBound(),
1691 op.getMixedStep(), op.getInductionVars())) {
1692 auto numIterations =
1694 if (numIterations.has_value()) {
1696 if (*numIterations == 0) {
1697 rewriter.
replaceOp(op, op.getOutputs());
1702 if (*numIterations == 1) {
1703 singleIterationIVs.emplace_back(iv, lb);
1707 newMixedLowerBounds.push_back(lb);
1708 newMixedUpperBounds.push_back(ub);
1709 newMixedSteps.push_back(step);
1713 if (newMixedLowerBounds.empty())
1717 if (newMixedLowerBounds.size() ==
static_cast<unsigned>(op.getRank())) {
1719 op,
"no dimensions have 0 or 1 iterations");
1725 for (
auto [iv, lb] : singleIterationIVs)
1730 newOp = ForallOp::create(rewriter, loc, newMixedLowerBounds,
1731 newMixedUpperBounds, newMixedSteps,
1732 op.getOutputs(), std::nullopt,
nullptr);
1734 newOp.setMappingAttr(op.getMappingAttr());
1735 newOp->setDiscardableAttrs(op->getDiscardableAttrDictionary());
1737 newOp.getRegion().begin(), mapping);
1738 rewriter.
replaceOp(op, newOp.getResults());
1744struct ForallOpReplaceConstantInductionVar :
public OpRewritePattern<ForallOp> {
1745 using OpRewritePattern<ForallOp>::OpRewritePattern;
1747 LogicalResult matchAndRewrite(ForallOp op,
1748 PatternRewriter &rewriter)
const override {
1749 Location loc = op.getLoc();
1750 bool changed =
false;
1751 for (
auto [lb, ub, step, iv] :
1752 llvm::zip(op.getMixedLowerBound(), op.getMixedUpperBound(),
1753 op.getMixedStep(), op.getInductionVars())) {
1756 auto numIterations =
1758 if (!numIterations.has_value() || numIterations.value() != 1) {
1796struct ForallOpReplaceInitUsesWithBlockArg :
public OpRewritePattern<ForallOp> {
1797 using OpRewritePattern<ForallOp>::OpRewritePattern;
1800 static bool isEquivalentToAny(MLIRContext *ctx,
1801 const HyperrectangularSlice &
slice,
1802 ArrayRef<HyperrectangularSlice> candidates) {
1803 return llvm::any_of(candidates, [&](
const HyperrectangularSlice &other) {
1804 FailureOr<bool> equivalent =
1806 return succeeded(equivalent) && *equivalent;
1810 LogicalResult matchAndRewrite(ForallOp op,
1811 PatternRewriter &rewriter)
const override {
1812 bool changed =
false;
1813 for (OpResult
result : op.getResults()) {
1814 OpOperand *init = op.getTiedOpOperand(
result);
1815 BlockArgument blockArg = op.getTiedBlockArgument(init);
1817 SmallVector<HyperrectangularSlice> written = llvm::map_to_vector(
1818 llvm::make_filter_range(op.getCombiningOps(blockArg),
1819 llvm::IsaPred<tensor::ParallelInsertSliceOp>),
1820 [](Operation *combiningOp) {
1821 return HyperrectangularSlice(
1822 cast<tensor::ParallelInsertSliceOp>(combiningOp));
1826 auto isReadOfWrittenTile = [&](OpOperand &use) {
1827 auto extractOp = dyn_cast<tensor::ExtractSliceOp>(use.
getOwner());
1828 return extractOp && op->isProperAncestor(extractOp) &&
1829 isEquivalentToAny(op.getContext(),
1830 HyperrectangularSlice(extractOp), written);
1832 for (OpOperand &use : llvm::make_early_inc_range(llvm::make_filter_range(
1833 init->
get().
getUses(), isReadOfWrittenTile))) {
1845struct FoldTensorCastOfOutputIntoForallOp
1846 :
public OpRewritePattern<scf::ForallOp> {
1847 using OpRewritePattern<scf::ForallOp>::OpRewritePattern;
1854 LogicalResult matchAndRewrite(scf::ForallOp forallOp,
1855 PatternRewriter &rewriter)
const final {
1856 llvm::SmallMapVector<unsigned, TypeCast, 2> tensorCastProducers;
1857 llvm::SmallVector<Value> newOutputTensors = forallOp.getOutputs();
1858 for (
auto en : llvm::enumerate(newOutputTensors)) {
1859 auto castOp = en.value().getDefiningOp<tensor::CastOp>();
1866 castOp.getSource().getType())) {
1873 auto castSrcType = cast<RankedTensorType>(castOp.getSource().getType());
1874 BlockArgument outputArg = forallOp.getRegionIterArgs()[en.index()];
1876 forallOp.getTerminator().getYieldingOps(), [&](Operation &op) {
1877 auto insertOp = dyn_cast<tensor::ParallelInsertSliceOp>(&op);
1878 if (!insertOp || insertOp.getDest() != outputArg)
1880 return !verifyInBoundsSlice(castSrcType.getShape(),
1881 insertOp.getMixedOffsets(),
1882 insertOp.getMixedSizes(),
1883 insertOp.getMixedStrides())
1889 tensorCastProducers[en.index()] =
1890 TypeCast{castOp.getSource().getType(), castOp.getType()};
1891 newOutputTensors[en.index()] = castOp.getSource();
1894 if (tensorCastProducers.empty())
1898 Location loc = forallOp.getLoc();
1899 auto newForallOp = ForallOp::create(
1900 rewriter, loc, forallOp.getMixedLowerBound(),
1901 forallOp.getMixedUpperBound(), forallOp.getMixedStep(),
1902 newOutputTensors, forallOp.getMapping(),
1903 [&](OpBuilder nestedBuilder, Location nestedLoc,
ValueRange bbArgs) {
1904 auto castBlockArgs =
1905 llvm::to_vector(bbArgs.take_back(forallOp->getNumResults()));
1906 for (auto [index, cast] : tensorCastProducers) {
1907 Value &oldTypeBBArg = castBlockArgs[index];
1908 oldTypeBBArg = tensor::CastOp::create(nestedBuilder, nestedLoc,
1909 cast.dstType, oldTypeBBArg);
1913 SmallVector<Value> ivsBlockArgs =
1914 llvm::to_vector(bbArgs.take_front(forallOp.getRank()));
1915 ivsBlockArgs.append(castBlockArgs);
1917 bbArgs.front().getParentBlock(), ivsBlockArgs);
1928 llvm::SmallDenseSet<Value> newIterArgSet(
1929 newForallOp.getRegionIterArgs().begin(),
1930 newForallOp.getRegionIterArgs().end());
1931 auto terminator = newForallOp.getTerminator();
1932 for (
auto &yieldingOp : terminator.getYieldingOps()) {
1933 auto parallelCombiningOp =
1934 dyn_cast<ParallelCombiningOpInterface>(&yieldingOp);
1935 if (!parallelCombiningOp)
1937 for (OpOperand &dest : parallelCombiningOp.getUpdatedDestinations()) {
1938 auto castOp = dest.get().getDefiningOp<tensor::CastOp>();
1939 if (castOp && newIterArgSet.contains(castOp.getSource()))
1940 dest.set(castOp.getSource());
1946 SmallVector<Value> castResults = newForallOp.getResults();
1947 for (
auto &item : tensorCastProducers) {
1948 Value &oldTypeResult = castResults[item.first];
1949 oldTypeResult = tensor::CastOp::create(rewriter, loc, item.second.dstType,
1952 rewriter.
replaceOp(forallOp, castResults);
1959void ForallOp::getCanonicalizationPatterns(RewritePatternSet &results,
1960 MLIRContext *context) {
1961 results.
add<DimOfForallOp, FoldTensorCastOfOutputIntoForallOp,
1962 ForallOpControlOperandsFolder, ForallOpIterArgsFolder,
1963 ForallOpSingleOrZeroIterationDimsFolder,
1964 ForallOpReplaceConstantInductionVar,
1965 ForallOpReplaceInitUsesWithBlockArg>(context);
1968void ForallOp::getSuccessorRegions(RegionBranchPoint point,
1969 SmallVectorImpl<RegionSuccessor> ®ions) {
1976 regions.push_back(RegionSuccessor(&getRegion()));
1979 regions.push_back(RegionSuccessor(getOperation()));
1984 regions.push_back(RegionSuccessor(getOperation()));
1993void InParallelOp::build(OpBuilder &
b, OperationState &
result) {
1994 OpBuilder::InsertionGuard g(
b);
1995 Region *bodyRegion =
result.addRegion();
1996 b.createBlock(bodyRegion);
1999LogicalResult InParallelOp::verify() {
2000 scf::ForallOp forallOp =
2001 dyn_cast<scf::ForallOp>(getOperation()->getParentOp());
2003 return this->emitOpError(
"expected forall op parent");
2005 for (Operation &op : getRegion().front().getOperations()) {
2006 auto parallelCombiningOp = dyn_cast<ParallelCombiningOpInterface>(&op);
2007 if (!parallelCombiningOp) {
2008 return this->emitOpError(
"expected only ParallelCombiningOpInterface")
2013 MutableOperandRange dests = parallelCombiningOp.getUpdatedDestinations();
2014 ArrayRef<BlockArgument> regionOutArgs = forallOp.getRegionOutArgs();
2015 for (OpOperand &dest : dests) {
2016 if (!llvm::is_contained(regionOutArgs, dest.get()))
2017 return op.
emitOpError(
"may only insert into an output block argument");
2024void InParallelOp::print(OpAsmPrinter &p) {
2030 getOperation()->getDiscardableAttrDictionary().getValue());
2033ParseResult InParallelOp::parse(OpAsmParser &parser, OperationState &
result) {
2036 SmallVector<OpAsmParser::Argument, 8> regionOperands;
2037 std::unique_ptr<Region> region = std::make_unique<Region>();
2041 if (region->empty())
2042 OpBuilder(builder.
getContext()).createBlock(region.get());
2043 result.addRegion(std::move(region));
2051OpResult InParallelOp::getParentResult(int64_t idx) {
2052 return getOperation()->getParentOp()->getResult(idx);
2055SmallVector<BlockArgument> InParallelOp::getDests() {
2056 SmallVector<BlockArgument> updatedDests;
2057 for (Operation &yieldingOp : getYieldingOps()) {
2058 auto parallelCombiningOp =
2059 dyn_cast<ParallelCombiningOpInterface>(&yieldingOp);
2060 if (!parallelCombiningOp)
2062 for (OpOperand &updatedOperand :
2063 parallelCombiningOp.getUpdatedDestinations())
2064 updatedDests.push_back(cast<BlockArgument>(updatedOperand.get()));
2066 return updatedDests;
2069llvm::iterator_range<Block::iterator> InParallelOp::getYieldingOps() {
2070 return getRegion().front().getOperations();
2078 assert(a &&
"expected non-empty operation");
2079 assert(
b &&
"expected non-empty operation");
2084 if (ifOp->isProperAncestor(
b))
2087 return static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*a)) !=
2088 static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*
b));
2090 ifOp = ifOp->getParentOfType<IfOp>();
2098IfOp::inferReturnTypes(
MLIRContext *ctx, std::optional<Location> loc,
2099 IfOp::Adaptor adaptor,
2101 if (adaptor.getRegions().empty())
2103 Region *r = &adaptor.getThenRegion();
2109 auto yieldOp = llvm::dyn_cast<YieldOp>(
b.back());
2112 TypeRange types = yieldOp.getOperandTypes();
2113 llvm::append_range(inferredReturnTypes, types);
2119 return build(builder,
result, resultTypes, cond,
false,
2123void IfOp::build(OpBuilder &builder, OperationState &
result,
2124 TypeRange resultTypes, Value cond,
bool addThenBlock,
2125 bool addElseBlock) {
2126 assert((!addElseBlock || addThenBlock) &&
2127 "must not create else block w/o then block");
2128 result.addTypes(resultTypes);
2129 result.addOperands(cond);
2132 OpBuilder::InsertionGuard guard(builder);
2133 Region *thenRegion =
result.addRegion();
2136 Region *elseRegion =
result.addRegion();
2141void IfOp::build(OpBuilder &builder, OperationState &
result, Value cond,
2142 bool withElseRegion) {
2146void IfOp::build(OpBuilder &builder, OperationState &
result,
2147 TypeRange resultTypes, Value cond,
bool withElseRegion) {
2148 result.addTypes(resultTypes);
2149 result.addOperands(cond);
2152 OpBuilder::InsertionGuard guard(builder);
2153 Region *thenRegion =
result.addRegion();
2155 if (resultTypes.empty())
2156 IfOp::ensureTerminator(*thenRegion, builder,
result.location);
2159 Region *elseRegion =
result.addRegion();
2160 if (withElseRegion) {
2162 if (resultTypes.empty())
2163 IfOp::ensureTerminator(*elseRegion, builder,
result.location);
2167void IfOp::build(OpBuilder &builder, OperationState &
result, Value cond,
2169 function_ref<
void(OpBuilder &, Location)> elseBuilder) {
2170 assert(thenBuilder &&
"the builder callback for 'then' must be present");
2171 result.addOperands(cond);
2174 OpBuilder::InsertionGuard guard(builder);
2175 Region *thenRegion =
result.addRegion();
2177 thenBuilder(builder,
result.location);
2180 Region *elseRegion =
result.addRegion();
2183 elseBuilder(builder,
result.location);
2187 SmallVector<Type> inferredReturnTypes;
2189 auto attrDict = DictionaryAttr::get(ctx,
result.attributes);
2190 if (succeeded(inferReturnTypes(ctx, std::nullopt,
result.operands, attrDict,
2191 PropertyRef{},
result.regions,
2192 inferredReturnTypes))) {
2193 result.addTypes(inferredReturnTypes);
2197LogicalResult IfOp::verify() {
2198 if (getNumResults() != 0 && getElseRegion().empty())
2199 return emitOpError(
"must have an else block if defining values");
2203ParseResult IfOp::parse(OpAsmParser &parser, OperationState &
result) {
2205 result.regions.reserve(2);
2206 Region *thenRegion =
result.addRegion();
2207 Region *elseRegion =
result.addRegion();
2210 OpAsmParser::UnresolvedOperand cond;
2236void IfOp::print(OpAsmPrinter &p) {
2237 bool printBlockTerminators =
false;
2239 p <<
" " << getCondition();
2240 if (!getResults().empty()) {
2241 p <<
" -> (" << getResultTypes() <<
")";
2243 printBlockTerminators =
true;
2248 printBlockTerminators);
2251 auto &elseRegion = getElseRegion();
2252 if (!elseRegion.
empty()) {
2256 printBlockTerminators);
2262void IfOp::getSuccessorRegions(RegionBranchPoint point,
2263 SmallVectorImpl<RegionSuccessor> ®ions) {
2267 regions.push_back(RegionSuccessor(getOperation()));
2271 regions.push_back(RegionSuccessor(&getThenRegion()));
2274 Region *elseRegion = &this->getElseRegion();
2275 if (elseRegion->
empty())
2276 regions.push_back(RegionSuccessor(getOperation()));
2278 regions.push_back(RegionSuccessor(elseRegion));
2281ValueRange IfOp::getSuccessorInputs(RegionSuccessor successor) {
2286void IfOp::getEntrySuccessorRegions(ArrayRef<Attribute> operands,
2287 SmallVectorImpl<RegionSuccessor> ®ions) {
2288 FoldAdaptor adaptor(operands, *
this);
2289 auto boolAttr = dyn_cast_or_null<BoolAttr>(adaptor.getCondition());
2290 if (!boolAttr || boolAttr.getValue())
2291 regions.emplace_back(&getThenRegion());
2294 if (!boolAttr || !boolAttr.getValue()) {
2295 if (!getElseRegion().empty())
2296 regions.emplace_back(&getElseRegion());
2298 regions.emplace_back(RegionSuccessor(getOperation()));
2302LogicalResult IfOp::fold(FoldAdaptor adaptor,
2303 SmallVectorImpl<OpFoldResult> &results) {
2305 if (getElseRegion().empty())
2308 arith::XOrIOp xorStmt = getCondition().getDefiningOp<arith::XOrIOp>();
2315 getConditionMutable().assign(xorStmt.getLhs());
2316 Block *thenBlock = &getThenRegion().front();
2319 getThenRegion().getBlocks().splice(getThenRegion().getBlocks().begin(),
2320 getElseRegion().getBlocks());
2321 getElseRegion().getBlocks().splice(getElseRegion().getBlocks().begin(),
2322 getThenRegion().getBlocks(), thenBlock);
2326void IfOp::getRegionInvocationBounds(
2327 ArrayRef<Attribute> operands,
2328 SmallVectorImpl<InvocationBounds> &invocationBounds) {
2329 if (
auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0])) {
2332 invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
2333 invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
2336 invocationBounds.assign(2, {0, 1});
2343struct ConvertTrivialIfToSelect :
public OpRewritePattern<IfOp> {
2344 using OpRewritePattern<IfOp>::OpRewritePattern;
2346 LogicalResult matchAndRewrite(IfOp op,
2347 PatternRewriter &rewriter)
const override {
2348 if (op->getNumResults() == 0)
2351 auto cond = op.getCondition();
2352 auto thenYieldArgs = op.thenYield().getOperands();
2353 auto elseYieldArgs = op.elseYield().getOperands();
2355 SmallVector<Type> nonHoistable;
2356 for (
auto [trueVal, falseVal] : llvm::zip(thenYieldArgs, elseYieldArgs)) {
2357 if (&op.getThenRegion() == trueVal.getParentRegion() ||
2358 &op.getElseRegion() == falseVal.getParentRegion())
2359 nonHoistable.push_back(trueVal.getType());
2363 if (nonHoistable.size() == op->getNumResults())
2366 IfOp
replacement = IfOp::create(rewriter, op.getLoc(), nonHoistable, cond,
2370 replacement.getThenRegion().takeBody(op.getThenRegion());
2371 replacement.getElseRegion().takeBody(op.getElseRegion());
2373 SmallVector<Value> results(op->getNumResults());
2374 assert(thenYieldArgs.size() == results.size());
2375 assert(elseYieldArgs.size() == results.size());
2377 SmallVector<Value> trueYields;
2378 SmallVector<Value> falseYields;
2380 for (
const auto &it :
2381 llvm::enumerate(llvm::zip(thenYieldArgs, elseYieldArgs))) {
2382 Value trueVal = std::get<0>(it.value());
2383 Value falseVal = std::get<1>(it.value());
2386 results[it.index()] =
replacement.getResult(trueYields.size());
2387 trueYields.push_back(trueVal);
2388 falseYields.push_back(falseVal);
2389 }
else if (trueVal == falseVal)
2390 results[it.index()] = trueVal;
2392 results[it.index()] = arith::SelectOp::create(rewriter, op.getLoc(),
2393 cond, trueVal, falseVal);
2420struct ConditionPropagation :
public OpRewritePattern<IfOp> {
2421 using OpRewritePattern<IfOp>::OpRewritePattern;
2424 enum class Parent { Then, Else,
None };
2429 static Parent getParentType(Region *toCheck, IfOp op,
2431 Region *endRegion) {
2432 SmallVector<Region *> seen;
2433 while (toCheck != endRegion) {
2434 auto found = cache.find(toCheck);
2435 if (found != cache.end())
2436 return found->second;
2437 seen.push_back(toCheck);
2438 if (&op.getThenRegion() == toCheck) {
2439 for (Region *region : seen)
2440 cache[region] = Parent::Then;
2441 return Parent::Then;
2443 if (&op.getElseRegion() == toCheck) {
2444 for (Region *region : seen)
2445 cache[region] = Parent::Else;
2446 return Parent::Else;
2451 for (Region *region : seen)
2452 cache[region] = Parent::None;
2453 return Parent::None;
2456 LogicalResult matchAndRewrite(IfOp op,
2457 PatternRewriter &rewriter)
const override {
2463 bool changed =
false;
2468 Value constantTrue =
nullptr;
2469 Value constantFalse =
nullptr;
2472 for (OpOperand &use :
2473 llvm::make_early_inc_range(op.getCondition().getUses())) {
2476 case Parent::Then: {
2480 constantTrue = arith::ConstantOp::create(
2484 [&]() { use.set(constantTrue); });
2487 case Parent::Else: {
2491 constantFalse = arith::ConstantOp::create(
2495 [&]() { use.set(constantFalse); });
2498 case Parent::None: {
2499 auto selectOp = dyn_cast<arith::SelectOp>(use.
getOwner());
2506 selectOp.getResult(), selectOp.getTrueValue(),
2507 [&](OpOperand &selectUse) {
2508 return getParentType(
2509 selectUse.getOwner()->getParentRegion(), op, cache,
2510 op.getCondition().getParentRegion()) == Parent::Then;
2513 selectOp.getResult(), selectOp.getFalseValue(),
2514 [&](OpOperand &selectUse) {
2515 return getParentType(
2516 selectUse.getOwner()->getParentRegion(), op, cache,
2517 op.getCondition().getParentRegion()) == Parent::Else;
2564struct ReplaceIfYieldWithConditionOrValue :
public OpRewritePattern<IfOp> {
2565 using OpRewritePattern<IfOp>::OpRewritePattern;
2567 LogicalResult matchAndRewrite(IfOp op,
2568 PatternRewriter &rewriter)
const override {
2570 if (op.getNumResults() == 0)
2574 cast<scf::YieldOp>(op.getThenRegion().back().getTerminator());
2576 cast<scf::YieldOp>(op.getElseRegion().back().getTerminator());
2579 op.getOperation()->getIterator());
2580 bool changed =
false;
2582 for (
auto [trueResult, falseResult, opResult] :
2583 llvm::zip(trueYield.getResults(), falseYield.getResults(),
2585 if (trueResult == falseResult) {
2586 if (!opResult.use_empty()) {
2587 opResult.replaceAllUsesWith(trueResult);
2593 BoolAttr trueYield, falseYield;
2598 bool trueVal = trueYield.
getValue();
2599 bool falseVal = falseYield.
getValue();
2600 if (!trueVal && falseVal) {
2601 if (!opResult.use_empty()) {
2602 Dialect *constDialect = trueResult.getDefiningOp()->getDialect();
2603 Value notCond = arith::XOrIOp::create(
2604 rewriter, op.getLoc(), op.getCondition(),
2610 opResult.replaceAllUsesWith(notCond);
2614 if (trueVal && !falseVal) {
2615 if (!opResult.use_empty()) {
2616 opResult.replaceAllUsesWith(op.getCondition());
2646struct CombineIfs :
public OpRewritePattern<IfOp> {
2647 using OpRewritePattern<IfOp>::OpRewritePattern;
2649 LogicalResult matchAndRewrite(IfOp nextIf,
2650 PatternRewriter &rewriter)
const override {
2651 Block *parent = nextIf->getBlock();
2652 if (nextIf == &parent->
front())
2655 auto prevIf = dyn_cast<IfOp>(nextIf->getPrevNode());
2663 Block *nextThen =
nullptr;
2664 Block *nextElse =
nullptr;
2665 if (nextIf.getCondition() == prevIf.getCondition()) {
2666 nextThen = nextIf.thenBlock();
2667 if (!nextIf.getElseRegion().empty())
2668 nextElse = nextIf.elseBlock();
2670 if (arith::XOrIOp notv =
2671 nextIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
2672 if (notv.getLhs() == prevIf.getCondition() &&
2674 nextElse = nextIf.thenBlock();
2675 if (!nextIf.getElseRegion().empty())
2676 nextThen = nextIf.elseBlock();
2679 if (arith::XOrIOp notv =
2680 prevIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
2681 if (notv.getLhs() == nextIf.getCondition() &&
2683 nextElse = nextIf.thenBlock();
2684 if (!nextIf.getElseRegion().empty())
2685 nextThen = nextIf.elseBlock();
2689 if (!nextThen && !nextElse)
2692 SmallVector<Value> prevElseYielded;
2693 if (!prevIf.getElseRegion().empty())
2694 prevElseYielded = prevIf.elseYield().getOperands();
2697 for (
auto it : llvm::zip(prevIf.getResults(),
2698 prevIf.thenYield().getOperands(), prevElseYielded))
2699 for (OpOperand &use :
2700 llvm::make_early_inc_range(std::get<0>(it).getUses())) {
2704 use.
set(std::get<1>(it));
2709 use.
set(std::get<2>(it));
2714 SmallVector<Type> mergedTypes(prevIf.getResultTypes());
2715 llvm::append_range(mergedTypes, nextIf.getResultTypes());
2717 IfOp combinedIf = IfOp::create(rewriter, nextIf.getLoc(), mergedTypes,
2718 prevIf.getCondition(),
false);
2719 rewriter.
eraseBlock(&combinedIf.getThenRegion().back());
2722 combinedIf.getThenRegion(),
2723 combinedIf.getThenRegion().begin());
2726 YieldOp thenYield = combinedIf.thenYield();
2727 YieldOp thenYield2 = cast<YieldOp>(nextThen->
getTerminator());
2728 rewriter.
mergeBlocks(nextThen, combinedIf.thenBlock());
2731 SmallVector<Value> mergedYields(thenYield.getOperands());
2732 llvm::append_range(mergedYields, thenYield2.getOperands());
2733 YieldOp::create(rewriter, thenYield2.getLoc(), mergedYields);
2739 combinedIf.getElseRegion(),
2740 combinedIf.getElseRegion().begin());
2743 if (combinedIf.getElseRegion().empty()) {
2745 combinedIf.getElseRegion(),
2746 combinedIf.getElseRegion().
begin());
2748 YieldOp elseYield = combinedIf.elseYield();
2749 YieldOp elseYield2 = cast<YieldOp>(nextElse->
getTerminator());
2750 rewriter.
mergeBlocks(nextElse, combinedIf.elseBlock());
2754 SmallVector<Value> mergedElseYields(elseYield.getOperands());
2755 llvm::append_range(mergedElseYields, elseYield2.getOperands());
2757 YieldOp::create(rewriter, elseYield2.getLoc(), mergedElseYields);
2763 SmallVector<Value> prevValues;
2764 SmallVector<Value> nextValues;
2765 for (
const auto &pair : llvm::enumerate(combinedIf.getResults())) {
2766 if (pair.index() < prevIf.getNumResults())
2767 prevValues.push_back(pair.value());
2769 nextValues.push_back(pair.value());
2778struct RemoveEmptyElseBranch :
public OpRewritePattern<IfOp> {
2779 using OpRewritePattern<IfOp>::OpRewritePattern;
2781 LogicalResult matchAndRewrite(IfOp ifOp,
2782 PatternRewriter &rewriter)
const override {
2784 if (ifOp.getNumResults())
2786 Block *elseBlock = ifOp.elseBlock();
2787 if (!elseBlock || !llvm::hasSingleElement(*elseBlock))
2791 newIfOp.getThenRegion().begin());
2813struct CombineNestedIfs :
public OpRewritePattern<IfOp> {
2814 using OpRewritePattern<IfOp>::OpRewritePattern;
2816 LogicalResult matchAndRewrite(IfOp op,
2817 PatternRewriter &rewriter)
const override {
2818 auto nestedOps = op.thenBlock()->without_terminator();
2820 if (!llvm::hasSingleElement(nestedOps))
2824 if (op.elseBlock() && !llvm::hasSingleElement(*op.elseBlock()))
2827 auto nestedIf = dyn_cast<IfOp>(*nestedOps.begin());
2831 if (nestedIf.elseBlock() && !llvm::hasSingleElement(*nestedIf.elseBlock()))
2834 SmallVector<Value> thenYield(op.thenYield().getOperands());
2835 SmallVector<Value> elseYield;
2837 llvm::append_range(elseYield, op.elseYield().getOperands());
2841 SmallVector<unsigned> elseYieldsToUpgradeToSelect;
2850 for (
const auto &tup : llvm::enumerate(thenYield)) {
2851 if (tup.value().getDefiningOp() == nestedIf) {
2852 auto nestedIdx = llvm::cast<OpResult>(tup.value()).getResultNumber();
2853 if (nestedIf.elseYield().getOperand(nestedIdx) !=
2854 elseYield[tup.index()]) {
2859 thenYield[tup.index()] = nestedIf.thenYield().getOperand(nestedIdx);
2872 if (tup.value().getParentRegion() == &op.getThenRegion()) {
2875 elseYieldsToUpgradeToSelect.push_back(tup.index());
2878 Location loc = op.getLoc();
2879 Value newCondition = arith::AndIOp::create(rewriter, loc, op.getCondition(),
2880 nestedIf.getCondition());
2881 auto newIf = IfOp::create(rewriter, loc, op.getResultTypes(), newCondition);
2884 SmallVector<Value> results;
2885 llvm::append_range(results, newIf.getResults());
2888 for (
auto idx : elseYieldsToUpgradeToSelect)
2890 arith::SelectOp::create(rewriter, op.getLoc(), op.getCondition(),
2891 thenYield[idx], elseYield[idx]);
2893 rewriter.
mergeBlocks(nestedIf.thenBlock(), newIfBlock);
2896 if (!elseYield.empty()) {
2899 YieldOp::create(rewriter, loc, elseYield);
2908void IfOp::getCanonicalizationPatterns(RewritePatternSet &results,
2909 MLIRContext *context) {
2910 results.
add<CombineIfs, CombineNestedIfs, ConditionPropagation,
2911 ConvertTrivialIfToSelect, RemoveEmptyElseBranch,
2912 ReplaceIfYieldWithConditionOrValue>(context);
2914 results, IfOp::getOperationName());
2916 IfOp::getOperationName());
2919Block *IfOp::thenBlock() {
return &getThenRegion().back(); }
2920YieldOp IfOp::thenYield() {
return cast<YieldOp>(&thenBlock()->back()); }
2921Block *IfOp::elseBlock() {
2922 Region &r = getElseRegion();
2927YieldOp IfOp::elseYield() {
return cast<YieldOp>(&elseBlock()->back()); }
2933void ParallelOp::build(
2939 result.addOperands(lowerBounds);
2940 result.addOperands(upperBounds);
2941 result.addOperands(steps);
2942 result.addOperands(initVals);
2944 result.addAttribute(getUnsignedCmpAttrName(
result.name),
2947 ParallelOp::getOperandSegmentSizeAttr(),
2949 static_cast<int32_t>(upperBounds.size()),
2950 static_cast<int32_t>(steps.size()),
2951 static_cast<int32_t>(initVals.size())}));
2954 OpBuilder::InsertionGuard guard(builder);
2955 unsigned numIVs = steps.size();
2956 SmallVector<Type, 8> argTypes(numIVs, builder.
getIndexType());
2957 SmallVector<Location, 8> argLocs(numIVs,
result.location);
2958 Region *bodyRegion =
result.addRegion();
2961 if (bodyBuilderFn) {
2963 bodyBuilderFn(builder,
result.location,
2968 if (initVals.empty())
2969 ParallelOp::ensureTerminator(*bodyRegion, builder,
result.location);
2972void ParallelOp::build(
2980 auto wrappedBuilderFn = [&bodyBuilderFn](OpBuilder &nestedBuilder,
2983 bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
2987 wrapper = wrappedBuilderFn;
2989 build(builder,
result, lowerBounds, upperBounds, steps,
ValueRange(), wrapper,
2993LogicalResult ParallelOp::verify() {
2998 if (stepValues.empty())
3000 "needs at least one tuple element for lowerBound, upperBound and step");
3003 for (Value stepValue : stepValues)
3006 return emitOpError(
"constant step operand must be positive");
3010 Block *body = getBody();
3012 return emitOpError() <<
"expects the same number of induction variables: "
3014 <<
" as bound and step values: " << stepValues.size();
3016 if (!arg.getType().isIndex())
3018 "expects arguments for the induction variable to be of index type");
3022 *
this, getRegion(),
"expects body to terminate with 'scf.reduce'");
3027 auto resultsSize = getResults().size();
3028 auto reductionsSize = reduceOp.getReductions().size();
3029 auto initValsSize = getInitVals().size();
3030 if (resultsSize != reductionsSize)
3031 return emitOpError() <<
"expects number of results: " << resultsSize
3032 <<
" to be the same as number of reductions: "
3034 if (resultsSize != initValsSize)
3035 return emitOpError() <<
"expects number of results: " << resultsSize
3036 <<
" to be the same as number of initial values: "
3038 if (reduceOp.getNumOperands() != initValsSize)
3043 for (int64_t i = 0; i < static_cast<int64_t>(reductionsSize); ++i) {
3044 auto resultType = getOperation()->getResult(i).getType();
3045 auto reductionOperandType = reduceOp.getOperands()[i].getType();
3046 if (resultType != reductionOperandType)
3047 return reduceOp.emitOpError()
3048 <<
"expects type of " << i
3049 <<
"-th reduction operand: " << reductionOperandType
3050 <<
" to be the same as the " << i
3051 <<
"-th result type: " << resultType;
3056ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &
result) {
3059 result.addAttribute(getUnsignedCmpAttrName(
result.name),
3063 SmallVector<OpAsmParser::Argument, 4> ivs;
3068 SmallVector<OpAsmParser::UnresolvedOperand, 4> lower;
3075 SmallVector<OpAsmParser::UnresolvedOperand, 4> upper;
3083 SmallVector<OpAsmParser::UnresolvedOperand, 4> steps;
3091 SmallVector<OpAsmParser::UnresolvedOperand, 4> initVals;
3102 Region *body =
result.addRegion();
3103 for (
auto &iv : ivs)
3110 ParallelOp::getOperandSegmentSizeAttr(),
3112 static_cast<int32_t>(upper.size()),
3113 static_cast<int32_t>(steps.size()),
3114 static_cast<int32_t>(initVals.size())}));
3123 ParallelOp::ensureTerminator(*body, builder,
result.location);
3127void ParallelOp::print(OpAsmPrinter &p) {
3128 if (getUnsignedCmp())
3130 p <<
" (" << getBody()->getArguments() <<
") = (" <<
getLowerBound()
3131 <<
") to (" <<
getUpperBound() <<
") step (" << getStep() <<
")";
3132 if (!getInitVals().empty())
3133 p <<
" init (" << getInitVals() <<
")";
3140SmallVector<Region *> ParallelOp::getLoopRegions() {
return {&getRegion()}; }
3142std::optional<SmallVector<Value>> ParallelOp::getLoopInductionVars() {
3143 return SmallVector<Value>{getBody()->getArguments()};
3146std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopLowerBounds() {
3150std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopUpperBounds() {
3154std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopSteps() {
3159 auto ivArg = llvm::dyn_cast<BlockArgument>(val);
3161 return ParallelOp();
3162 assert(ivArg.getOwner() &&
"unlinked block argument");
3163 auto *containingOp = ivArg.getOwner()->getParentOp();
3164 return dyn_cast<ParallelOp>(containingOp);
3169struct ParallelOpSingleOrZeroIterationDimsFolder
3173 LogicalResult matchAndRewrite(ParallelOp op,
3180 for (
auto [lb,
ub, step, iv] :
3181 llvm::zip(op.getLowerBound(), op.getUpperBound(), op.getStep(),
3182 op.getInductionVars())) {
3185 if (numIterations.has_value()) {
3187 if (*numIterations == 0) {
3188 rewriter.
replaceOp(op, op.getInitVals());
3193 if (*numIterations == 1) {
3198 newLowerBounds.push_back(lb);
3199 newUpperBounds.push_back(ub);
3200 newSteps.push_back(step);
3203 if (newLowerBounds.size() == op.getLowerBound().size())
3206 if (newLowerBounds.empty()) {
3209 SmallVector<Value> results;
3210 results.reserve(op.getInitVals().size());
3211 for (
auto &bodyOp : op.getBody()->without_terminator())
3212 rewriter.
clone(bodyOp, mapping);
3213 auto reduceOp = cast<ReduceOp>(op.getBody()->getTerminator());
3214 for (int64_t i = 0, e = reduceOp.getReductions().size(); i < e; ++i) {
3215 Block &reduceBlock = reduceOp.getReductions()[i].front();
3216 auto initValIndex = results.size();
3217 mapping.
map(reduceBlock.
getArgument(0), op.getInitVals()[initValIndex]);
3221 rewriter.
clone(reduceBodyOp, mapping);
3224 cast<ReduceReturnOp>(reduceBlock.
getTerminator()).getResult());
3225 results.push_back(
result);
3232 auto newOp = ParallelOp::create(rewriter, op.getLoc(), newLowerBounds,
3233 newUpperBounds, newSteps, op.getInitVals(),
3234 nullptr, op.getUnsignedCmp());
3240 newOp.getRegion().begin(), mapping);
3241 rewriter.
replaceOp(op, newOp.getResults());
3246struct MergeNestedParallelLoops :
public OpRewritePattern<ParallelOp> {
3247 using OpRewritePattern<ParallelOp>::OpRewritePattern;
3249 LogicalResult matchAndRewrite(ParallelOp op,
3250 PatternRewriter &rewriter)
const override {
3251 Block &outerBody = *op.getBody();
3255 auto innerOp = dyn_cast<ParallelOp>(outerBody.
front());
3259 if (op.getUnsignedCmp() != innerOp.getUnsignedCmp())
3263 if (llvm::is_contained(innerOp.getLowerBound(), val) ||
3264 llvm::is_contained(innerOp.getUpperBound(), val) ||
3265 llvm::is_contained(innerOp.getStep(), val))
3269 if (!op.getInitVals().empty() || !innerOp.getInitVals().empty())
3272 auto bodyBuilder = [&](OpBuilder &builder, Location ,
3274 Block &innerBody = *innerOp.getBody();
3275 assert(iterVals.size() ==
3283 builder.
clone(op, mapping);
3286 auto concatValues = [](
const auto &first,
const auto &second) {
3287 SmallVector<Value> ret;
3288 ret.reserve(first.size() + second.size());
3289 ret.assign(first.begin(), first.end());
3290 ret.append(second.begin(), second.end());
3294 auto newLowerBounds =
3295 concatValues(op.getLowerBound(), innerOp.getLowerBound());
3296 auto newUpperBounds =
3297 concatValues(op.getUpperBound(), innerOp.getUpperBound());
3298 auto newSteps = concatValues(op.getStep(), innerOp.getStep());
3309void ParallelOp::getCanonicalizationPatterns(RewritePatternSet &results,
3310 MLIRContext *context) {
3312 .
add<ParallelOpSingleOrZeroIterationDimsFolder, MergeNestedParallelLoops>(
3321void ParallelOp::getSuccessorRegions(
3322 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> ®ions) {
3326 regions.push_back(RegionSuccessor(&getRegion()));
3327 regions.push_back(RegionSuccessor(getOperation()));
3334void ReduceOp::build(OpBuilder &builder, OperationState &
result) {}
3336void ReduceOp::build(OpBuilder &builder, OperationState &
result,
3338 result.addOperands(operands);
3339 for (Value v : operands) {
3340 OpBuilder::InsertionGuard guard(builder);
3341 Region *bodyRegion =
result.addRegion();
3343 ArrayRef<Type>{v.getType(), v.getType()},
3348LogicalResult ReduceOp::verifyRegions() {
3349 if (getReductions().size() != getOperands().size())
3350 return emitOpError() <<
"expects number of reduction regions: "
3351 << getReductions().size()
3352 <<
" to be the same as number of reduction operands: "
3353 << getOperands().size();
3356 for (int64_t i = 0, e = getReductions().size(); i < e; ++i) {
3357 auto type = getOperands()[i].getType();
3358 Block &block = getReductions()[i].front();
3360 return emitOpError() << i <<
"-th reduction has an empty body";
3362 llvm::any_of(block.
getArguments(), [&](
const BlockArgument &arg) {
3363 return arg.getType() != type;
3365 return emitOpError() <<
"expected two block arguments with type " << type
3366 <<
" in the " << i <<
"-th reduction region";
3370 return emitOpError(
"reduction bodies must be terminated with an "
3371 "'scf.reduce.return' op");
3378ReduceOp::getMutableSuccessorOperands(RegionSuccessor point) {
3380 return MutableOperandRange(getOperation(), 0, 0);
3387LogicalResult ReduceReturnOp::verify() {
3390 Block *reductionBody = getOperation()->getBlock();
3392 assert(isa<ReduceOp>(reductionBody->
getParentOp()) &&
"expected scf.reduce");
3394 if (expectedResultType != getResult().
getType())
3395 return emitOpError() <<
"must have type " << expectedResultType
3396 <<
" (the type of the reduction inputs)";
3404void WhileOp::build(::mlir::OpBuilder &odsBuilder,
3405 ::mlir::OperationState &odsState,
TypeRange resultTypes,
3406 ValueRange inits, BodyBuilderFn beforeBuilder,
3407 BodyBuilderFn afterBuilder) {
3411 OpBuilder::InsertionGuard guard(odsBuilder);
3414 SmallVector<Location, 4> beforeArgLocs;
3415 beforeArgLocs.reserve(inits.size());
3416 for (Value operand : inits) {
3417 beforeArgLocs.push_back(operand.getLoc());
3420 Region *beforeRegion = odsState.
addRegion();
3422 inits.getTypes(), beforeArgLocs);
3427 SmallVector<Location, 4> afterArgLocs(resultTypes.size(), odsState.
location);
3429 Region *afterRegion = odsState.
addRegion();
3431 resultTypes, afterArgLocs);
3437ConditionOp WhileOp::getConditionOp() {
3438 return cast<ConditionOp>(getBeforeBody()->getTerminator());
3441YieldOp WhileOp::getYieldOp() {
3442 return cast<YieldOp>(getAfterBody()->getTerminator());
3445std::optional<MutableArrayRef<OpOperand>> WhileOp::getYieldedValuesMutable() {
3446 return getYieldOp().getResultsMutable();
3450 return getBeforeBody()->getArguments();
3454 return getAfterBody()->getArguments();
3458 return getBeforeArguments();
3461OperandRange WhileOp::getEntrySuccessorOperands(RegionSuccessor successor) {
3463 "WhileOp is expected to branch only to the first region");
3467void WhileOp::getSuccessorRegions(RegionBranchPoint point,
3468 SmallVectorImpl<RegionSuccessor> ®ions) {
3471 regions.emplace_back(&getBefore());
3475 assert(llvm::is_contained(
3476 {&getAfter(), &getBefore()},
3478 "there are only two regions in a WhileOp");
3482 regions.emplace_back(&getBefore());
3486 regions.push_back(RegionSuccessor(getOperation()));
3487 regions.emplace_back(&getAfter());
3490ValueRange WhileOp::getSuccessorInputs(RegionSuccessor successor) {
3492 return getOperation()->getResults();
3493 if (successor == &getBefore())
3494 return getBefore().getArguments();
3495 if (successor == &getAfter())
3496 return getAfter().getArguments();
3497 llvm_unreachable(
"invalid region successor");
3500SmallVector<Region *> WhileOp::getLoopRegions() {
3501 return {&getBefore(), &getAfter()};
3511ParseResult scf::WhileOp::parse(OpAsmParser &parser, OperationState &
result) {
3512 SmallVector<OpAsmParser::Argument, 4> regionArgs;
3513 SmallVector<OpAsmParser::UnresolvedOperand, 4> operands;
3514 Region *before =
result.addRegion();
3515 Region *after =
result.addRegion();
3517 OptionalParseResult listResult =
3522 FunctionType functionType;
3527 result.addTypes(functionType.getResults());
3529 if (functionType.getNumInputs() != operands.size()) {
3531 <<
"expected as many input types as operands " <<
"(expected "
3532 << operands.size() <<
" got " << functionType.getNumInputs() <<
")";
3542 for (
size_t i = 0, e = regionArgs.size(); i != e; ++i)
3543 regionArgs[i].type = functionType.getInput(i);
3545 return failure(parser.
parseRegion(*before, regionArgs) ||
3551void scf::WhileOp::print(OpAsmPrinter &p) {
3560 (*this)->getDiscardableAttrDictionary().getValue());
3563LogicalResult scf::WhileOp::verify() {
3566 "expects the 'before' region to terminate with 'scf.condition'");
3567 if (!beforeTerminator)
3572 "expects the 'after' region to terminate with 'scf.yield'");
3573 return success(afterTerminator !=
nullptr);
3610struct WhileMoveIfDown :
public OpRewritePattern<scf::WhileOp> {
3611 using OpRewritePattern<scf::WhileOp>::OpRewritePattern;
3613 LogicalResult matchAndRewrite(scf::WhileOp op,
3614 PatternRewriter &rewriter)
const override {
3615 auto conditionOp = op.getConditionOp();
3623 auto ifOp = dyn_cast_or_null<scf::IfOp>(conditionOp->getPrevNode());
3629 if (!ifOp || ifOp.getCondition() != conditionOp.getCondition() ||
3630 (ifOp.elseBlock() && !ifOp.elseBlock()->without_terminator().empty()))
3633 assert((ifOp->use_empty() || (llvm::all_equal(ifOp->getUsers()) &&
3634 *ifOp->user_begin() == conditionOp)) &&
3635 "ifOp has unexpected uses");
3637 Location loc = op.getLoc();
3647 for (
auto [idx, arg] : llvm::enumerate(conditionOp.getArgs())) {
3648 auto it = llvm::find(ifOp->getResults(), arg);
3649 if (it == ifOp->getResults().end())
3651 size_t ifOpIdx = it.getIndex();
3653 ifOp.thenYield()->getOperand(ifOpIdx));
3654 unsigned argIdx = idx;
3655 Value elseValue = ifOp.elseYield()->getOperand(ifOpIdx);
3657 conditionOp.getArgsMutable()[argIdx].assign(elseValue);
3664 if (&op.getBefore() == operand->get().getParentRegion())
3665 additionalUsedValuesSet.insert(operand->get());
3669 auto additionalUsedValues = additionalUsedValuesSet.getArrayRef();
3670 auto additionalValueTypes = llvm::map_to_vector(
3671 additionalUsedValues, [](Value val) {
return val.
getType(); });
3672 size_t additionalValueSize = additionalUsedValues.size();
3673 SmallVector<Type> newResultTypes(op.getResultTypes());
3674 newResultTypes.append(additionalValueTypes);
3677 scf::WhileOp::create(rewriter, loc, newResultTypes, op.getInits());
3680 newWhileOp.getBefore().takeBody(op.getBefore());
3681 newWhileOp.getAfter().takeBody(op.getAfter());
3682 newWhileOp.getAfter().addArguments(
3683 additionalValueTypes,
3684 SmallVector<Location>(additionalValueSize, loc));
3688 conditionOp.getArgsMutable().append(additionalUsedValues);
3694 additionalUsedValues,
3695 newWhileOp.getAfterArguments().take_back(additionalValueSize),
3696 [&](OpOperand &use) {
3697 return ifOp.getThenRegion().isAncestor(
3698 use.getOwner()->getParentRegion());
3702 rewriter.
eraseOp(ifOp.thenYield());
3704 newWhileOp.getAfterBody()->begin());
3707 newWhileOp->getResults().drop_back(additionalValueSize));
3731struct WhileConditionTruth :
public OpRewritePattern<WhileOp> {
3732 using OpRewritePattern<WhileOp>::OpRewritePattern;
3734 LogicalResult matchAndRewrite(WhileOp op,
3735 PatternRewriter &rewriter)
const override {
3736 auto term = op.getConditionOp();
3740 Value constantTrue =
nullptr;
3742 bool replaced =
false;
3743 for (
auto yieldedAndBlockArgs :
3744 llvm::zip(term.getArgs(), op.getAfterArguments())) {
3745 if (std::get<0>(yieldedAndBlockArgs) == term.getCondition()) {
3746 if (!std::get<1>(yieldedAndBlockArgs).use_empty()) {
3748 constantTrue = arith::ConstantOp::create(
3749 rewriter, op.getLoc(), term.getCondition().getType(),
3793struct WhileConditionSelect :
public OpRewritePattern<WhileOp> {
3794 using OpRewritePattern<WhileOp>::OpRewritePattern;
3796 LogicalResult matchAndRewrite(WhileOp op,
3797 PatternRewriter &rewriter)
const override {
3798 ConditionOp term = op.getConditionOp();
3799 Value condition = term.getCondition();
3800 bool changed =
false;
3801 for (
auto [idx, arg, afterArg,
result] : llvm::enumerate(
3802 term.getArgs(), op.getAfterArguments(), op.getResults())) {
3804 if (!select || select.getCondition() != condition)
3806 Value trueValue = select.getTrueValue();
3807 Value falseValue = select.getFalseValue();
3808 if (!afterArg.use_empty() && op.isDefinedOutsideOfLoop(trueValue)) {
3813 op.isDefinedOutsideOfLoop(falseValue)) {
3820 forwarded = trueValue;
3821 else if (afterArg.use_empty())
3822 forwarded = falseValue;
3823 if (forwarded && forwarded != arg) {
3824 size_t condIdx = idx;
3826 term, [&] { term.getArgsMutable()[condIdx].set(forwarded); });
3856struct WhileCmpCond :
public OpRewritePattern<scf::WhileOp> {
3857 using OpRewritePattern<scf::WhileOp>::OpRewritePattern;
3859 LogicalResult matchAndRewrite(scf::WhileOp op,
3860 PatternRewriter &rewriter)
const override {
3861 using namespace scf;
3862 auto cond = op.getConditionOp();
3863 auto cmp = cond.getCondition().getDefiningOp<arith::CmpIOp>();
3866 bool changed =
false;
3867 for (
auto tup : llvm::zip(cond.getArgs(), op.getAfterArguments())) {
3868 for (
size_t opIdx = 0; opIdx < 2; opIdx++) {
3869 if (std::get<0>(tup) != cmp.getOperand(opIdx))
3872 llvm::make_early_inc_range(std::get<1>(tup).getUses())) {
3873 auto cmp2 = dyn_cast<arith::CmpIOp>(u.getOwner());
3877 if (cmp2.getOperand(1 - opIdx) != cmp.getOperand(1 - opIdx))
3880 if (cmp2.getPredicate() == cmp.getPredicate())
3881 samePredicate =
true;
3882 else if (cmp2.getPredicate() ==
3883 arith::invertPredicate(cmp.getPredicate()))
3884 samePredicate =
false;
3900static std::optional<SmallVector<unsigned>> getArgsMapping(
ValueRange args1,
3902 if (args1.size() != args2.size())
3903 return std::nullopt;
3905 SmallVector<unsigned> ret(args1.size());
3906 for (
auto &&[i, arg1] : llvm::enumerate(args1)) {
3907 auto it = llvm::find(args2, arg1);
3908 if (it == args2.end())
3909 return std::nullopt;
3911 ret[std::distance(args2.begin(), it)] =
static_cast<unsigned>(i);
3918 llvm::SmallDenseSet<Value> set;
3919 for (Value arg : args) {
3920 if (!set.insert(arg).second)
3930struct WhileOpAlignBeforeArgs :
public OpRewritePattern<WhileOp> {
3933 LogicalResult matchAndRewrite(WhileOp loop,
3934 PatternRewriter &rewriter)
const override {
3935 auto *oldBefore = loop.getBeforeBody();
3936 ConditionOp oldTerm = loop.getConditionOp();
3937 ValueRange beforeArgs = oldBefore->getArguments();
3939 if (beforeArgs == termArgs)
3942 if (hasDuplicates(termArgs))
3945 auto mapping = getArgsMapping(beforeArgs, termArgs);
3950 OpBuilder::InsertionGuard g(rewriter);
3956 auto *oldAfter = loop.getAfterBody();
3958 SmallVector<Type> newResultTypes(beforeArgs.size());
3959 for (
auto &&[i, j] : llvm::enumerate(*mapping))
3960 newResultTypes[j] = loop.getResult(i).getType();
3962 auto newLoop = WhileOp::create(
3963 rewriter, loop.getLoc(), newResultTypes, loop.getInits(),
3965 auto *newBefore = newLoop.getBeforeBody();
3966 auto *newAfter = newLoop.getAfterBody();
3968 SmallVector<Value> newResults(beforeArgs.size());
3969 SmallVector<Value> newAfterArgs(beforeArgs.size());
3970 for (
auto &&[i, j] : llvm::enumerate(*mapping)) {
3971 newResults[i] = newLoop.getResult(j);
3972 newAfterArgs[i] = newAfter->getArgument(j);
3976 newBefore->getArguments());
3986void WhileOp::getCanonicalizationPatterns(RewritePatternSet &results,
3987 MLIRContext *context) {
3988 results.
add<WhileConditionTruth, WhileConditionSelect, WhileCmpCond,
3989 WhileOpAlignBeforeArgs, WhileMoveIfDown>(context);
3991 results, WhileOp::getOperationName());
3993 WhileOp::getOperationName());
4007 Region ®ion = *caseRegions.emplace_back(std::make_unique<Region>());
4010 caseValues.push_back(value);
4019 for (
auto [value, region] : llvm::zip(cases.
asArrayRef(), caseRegions)) {
4021 p <<
"case " << value <<
' ';
4026LogicalResult scf::IndexSwitchOp::verify() {
4027 if (getCases().size() != getCaseRegions().size()) {
4028 return emitOpError(
"has ")
4029 << getCaseRegions().size() <<
" case regions but "
4030 << getCases().size() <<
" case values";
4034 for (int64_t value : getCases())
4035 if (!valueSet.insert(value).second)
4036 return emitOpError(
"has duplicate case value: ") << value;
4037 auto verifyRegion = [&](Region ®ion,
const Twine &name) -> LogicalResult {
4038 auto yield = dyn_cast<YieldOp>(region.
front().
back());
4040 return emitOpError(
"expected region to end with scf.yield, but got ")
4043 if (yield.getNumOperands() != getNumResults()) {
4044 return (emitOpError(
"expected each region to return ")
4045 << getNumResults() <<
" values, but " << name <<
" returns "
4046 << yield.getNumOperands())
4047 .attachNote(yield.getLoc())
4048 <<
"see yield operation here";
4050 for (
auto [idx,
result, operand] :
4051 llvm::enumerate(getResultTypes(), yield.getOperands())) {
4053 return yield.emitOpError() <<
"operand " << idx <<
" is null\n";
4054 if (
result == operand.getType())
4056 return (emitOpError(
"expected result #")
4057 << idx <<
" of each region to be " <<
result)
4058 .attachNote(yield.getLoc())
4059 << name <<
" returns " << operand.getType() <<
" here";
4066 for (
auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
4073unsigned scf::IndexSwitchOp::getNumCases() {
return getCases().size(); }
4075Block &scf::IndexSwitchOp::getDefaultBlock() {
4076 return getDefaultRegion().front();
4079Block &scf::IndexSwitchOp::getCaseBlock(
unsigned idx) {
4080 assert(idx < getNumCases() &&
"case index out-of-bounds");
4081 return getCaseRegions()[idx].front();
4084void IndexSwitchOp::getSuccessorRegions(
4085 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &successors) {
4088 successors.push_back(RegionSuccessor(getOperation()));
4092 llvm::append_range(successors, getRegions());
4095ValueRange IndexSwitchOp::getSuccessorInputs(RegionSuccessor successor) {
4100void IndexSwitchOp::getEntrySuccessorRegions(
4101 ArrayRef<Attribute> operands,
4102 SmallVectorImpl<RegionSuccessor> &successors) {
4103 FoldAdaptor adaptor(operands, *
this);
4106 auto arg = dyn_cast_or_null<IntegerAttr>(adaptor.getArg());
4108 llvm::append_range(successors, getRegions());
4114 for (
auto [caseValue, caseRegion] : llvm::zip(getCases(), getCaseRegions())) {
4115 if (caseValue == arg.getInt()) {
4116 successors.emplace_back(&caseRegion);
4120 successors.emplace_back(&getDefaultRegion());
4123void IndexSwitchOp::getRegionInvocationBounds(
4124 ArrayRef<Attribute> operands, SmallVectorImpl<InvocationBounds> &bounds) {
4125 auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
4126 if (!operandValue) {
4128 bounds.append(getNumRegions(), InvocationBounds(0, 1));
4132 unsigned liveIndex = getNumRegions() - 1;
4133 const auto *it = llvm::find(getCases(), operandValue.getInt());
4134 if (it != getCases().end())
4135 liveIndex = std::distance(getCases().begin(), it);
4136 for (
unsigned i = 0, e = getNumRegions(); i < e; ++i)
4137 bounds.emplace_back(0, i == liveIndex);
4140void IndexSwitchOp::getCanonicalizationPatterns(RewritePatternSet &results,
4141 MLIRContext *context) {
4143 results, IndexSwitchOp::getOperationName());
4145 results, IndexSwitchOp::getOperationName());
4152#define GET_OP_CLASSES
4153#include "mlir/Dialect/SCF/IR/SCFOps.cpp.inc"
static std::optional< int64_t > getUpperBound(Value iv)
Gets the constant upper bound on an affine.for iv.
static std::optional< int64_t > getLowerBound(Value iv)
Gets the constant lower bound on an iv.
static LogicalResult verifyRegion(emitc::SwitchOp op, Region ®ion, const Twine &name)
static ParseResult parseSwitchCases(OpAsmParser &parser, DenseI64ArrayAttr &cases, SmallVectorImpl< std::unique_ptr< Region > > &caseRegions)
Parse the case regions and values.
static void printSwitchCases(OpAsmPrinter &p, Operation *op, DenseI64ArrayAttr cases, RegionRange caseRegions)
Print the case regions and values.
static void printInitializationList(OpAsmPrinter &p, Block::BlockArgListType blocksArgs, ValueRange initializers, StringRef prefix="")
Prints the initialization list in the form of <prefix>(inner = outer, inner2 = outer2,...
static TerminatorTy verifyAndGetTerminator(Operation *op, Region ®ion, StringRef errorMessage)
Verifies that the first block of the given region is terminated by a TerminatorTy.
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be the output argument nBegin is set to its * replacement(set to `begin` if no invalidation happens). Since outgoing *copies could have been inserted at `end`
static SmallVector< Value > slice(OpBuilder &b, Location loc, Value value, VectorType nativeType)
@ Paren
Parens surrounding zero or more operands.
virtual Builder & getBuilder() const =0
Return a builder which provides useful access to MLIRContext, global objects like types and attribute...
virtual ParseResult parseOptionalAttrDict(NamedAttrList &result)=0
Parse a named dictionary into 'result' if it is present.
virtual ParseResult parseOptionalKeyword(StringRef keyword)=0
Parse the given keyword if present.
MLIRContext * getContext() const
virtual InFlightDiagnostic emitError(SMLoc loc, const Twine &message={})=0
Emit a diagnostic at the specified location and return failure.
virtual ParseResult parseOptionalColon()=0
Parse a : token if present.
ParseResult parseInteger(IntT &result)
Parse an integer value from the stream.
virtual ParseResult parseEqual()=0
Parse a = token.
virtual ParseResult parseOptionalAttrDictWithKeyword(NamedAttrList &result)=0
Parse a named dictionary into 'result' if the attributes keyword is present.
virtual ParseResult parseColonType(Type &result)=0
Parse a colon followed by a type.
virtual SMLoc getCurrentLocation()=0
Get the location of the next token and store it into the argument.
virtual SMLoc getNameLoc() const =0
Return the location of the original name token.
virtual ParseResult parseType(Type &result)=0
Parse a type.
virtual ParseResult parseOptionalArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an optional arrow followed by a type list.
virtual ParseResult parseArrowTypeList(SmallVectorImpl< Type > &result)=0
Parse an arrow followed by a type list.
ParseResult parseKeyword(StringRef keyword)
Parse a given keyword.
void printOptionalArrowTypeList(TypeRange &&types)
Print an optional arrow followed by a type list.
virtual void printNewline()
Print a newline and indent the printer to the start of the current operation/attribute/type.
This class represents an argument of a Block.
unsigned getArgNumber() const
Returns the number of this argument.
Block represents an ordered list of Operations.
MutableArrayRef< BlockArgument > BlockArgListType
BlockArgument getArgument(unsigned i)
unsigned getNumArguments()
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
BlockArgListType getArguments()
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
bool getValue() const
Return the boolean value of this attribute.
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
IntegerAttr getIntegerAttr(Type type, int64_t value)
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
IntegerType getIntegerType(unsigned width)
BoolAttr getBoolAttr(bool value)
StringAttr getStringAttr(const Twine &bytes)
MLIRContext * getContext() const
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
virtual Operation * materializeConstant(OpBuilder &builder, Attribute value, Type type, Location loc)
Registered hook to materialize a single constant operation from a given attribute value with the desi...
This is a utility class for mapping one set of IR entities to another.
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
IRValueT get() const
Return the current value being used by this operand.
void set(IRValueT newValue)
Set the current value being used by this operand.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
This class provides a mutable adaptor for a range of operands.
The OpAsmParser has methods for interacting with the asm parser: parsing things from it,...
virtual OptionalParseResult parseOptionalAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)=0
virtual ParseResult parseRegion(Region ®ion, ArrayRef< Argument > arguments={}, bool enableNameShadowing=false)=0
Parses a region.
virtual ParseResult parseArgumentList(SmallVectorImpl< Argument > &result, Delimiter delimiter=Delimiter::None, bool allowType=false, bool allowAttrs=false)=0
Parse zero or more arguments with a specified surrounding delimiter.
ParseResult parseAssignmentList(SmallVectorImpl< Argument > &lhs, SmallVectorImpl< UnresolvedOperand > &rhs)
Parse a list of assignments of the form (x1 = y1, x2 = y2, ...)
virtual ParseResult resolveOperand(const UnresolvedOperand &operand, Type type, SmallVectorImpl< Value > &result)=0
Resolve an operand to an SSA value, emitting an error on failure.
ParseResult resolveOperands(Operands &&operands, Type type, SmallVectorImpl< Value > &result)
Resolve a list of operands to SSA values, emitting an error on failure, or appending the results to t...
virtual ParseResult parseOperand(UnresolvedOperand &result, bool allowResultNumber=true)=0
Parse a single SSA value operand name along with a result number if allowResultNumber is true.
virtual ParseResult parseOperandList(SmallVectorImpl< UnresolvedOperand > &result, Delimiter delimiter=Delimiter::None, bool allowResultNumber=true, int requiredOperandCount=-1)=0
Parse zero or more SSA comma-separated operand references with a specified surrounding delimiter,...
This is a pure-virtual base class that exposes the asmprinter hooks necessary to implement a custom p...
virtual void printOptionalAttrDictWithKeyword(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary prefixed with 'attribute...
virtual void printOptionalAttrDict(ArrayRef< NamedAttribute > attrs, ArrayRef< StringRef > elidedAttrs={})=0
If the specified operation has attributes, print out an attribute dictionary with their values.
void printFunctionalType(Operation *op)
Print the complete type of an operation in functional form.
virtual void printRegion(Region &blocks, bool printEntryBlockArgs=true, bool printBlockTerminators=true, bool printEmptyBlock=false)=0
Prints a region.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
Block * createBlock(Region *parent, Region::iterator insertPt={}, TypeRange argTypes={}, ArrayRef< Location > locs={})
Add new block with 'argTypes' arguments and set the insertion point to the end of it.
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
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 setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void cloneRegionBefore(Region ®ion, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
This class represents a single result from folding an operation.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Set of flags used to control the behavior of the various IR print methods (e.g.
This is a value defined by a result of an operation.
Operation * getOwner() const
Returns the operation that owns this result.
unsigned getResultNumber() const
Returns the number of this result.
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
This class implements the operand iterators for the Operation class.
Operation is the basic unit of execution within MLIR.
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Location getLoc()
The source location the operation was defined or derived from.
OperandRange operand_range
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
auto getDiscardableAttrs()
Return a range of all of discardable attributes on this operation.
OperationName getName()
The name of an operation is the key identifier for it.
Region * getParentRegion()
Returns the region to which the instruction belongs.
bool isProperAncestor(Operation *other)
Return true if this operation is a proper ancestor of the other operation.
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
ParseResult value() const
Access the internal ParseResult value.
bool has_value() const
Returns true if we contain a valid ParseResult value.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
This class represents a point being branched from in the methods of the RegionBranchOpInterface.
bool isParent() const
Returns true if branching from the parent op.
RegionBranchTerminatorOpInterface getTerminatorPredecessorOrNull() const
Returns the terminator if branching from a region.
This class provides an abstraction over the different types of ranges over Regions.
This class represents a successor of a region.
Region * getSuccessor() const
Return the given region successor.
bool isOperation() const
Return true if the successor is an operation.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
unsigned getNumArguments()
BlockArgument getArgument(unsigned i)
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
virtual void eraseBlock(Block *block)
This method erases all operations in a block.
Block * splitBlock(Block *block, Block::iterator before)
Split the operations starting at "before" (inclusive) out of the given block into a new 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 finalizeOpModification(Operation *op)
This method is used to signal the end of an in-place modification of the given operation.
virtual void eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
Operation * eraseOpResults(Operation *op, const BitVector &eraseIndices)
Erase the specified results of the given operation.
virtual void inlineBlockBefore(Block *source, Block *dest, Block::iterator before, ValueRange argValues={})
Inline the operations of block 'source' into block 'dest' before the given position.
void mergeBlocks(Block *source, Block *dest, ValueRange argValues={})
Inline the operations of block 'source' into the end of block 'dest'.
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
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".
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
virtual void startOpModification(Operation *op)
This method is used to notify the rewriter that an in-place operation modification is about to happen...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
This class provides an abstraction over the various different ranges of value types.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
static FailureOr< bool > areEquivalentSlices(MLIRContext *ctx, const HyperrectangularSlice &slice1, const HyperrectangularSlice &slice2)
Return "true" if the given slices are guaranteed to be equivalent.
This class provides an abstraction over the different types of ranges over Values.
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
user_range getUsers() const
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.
ArrayRef< T > asArrayRef() const
Operation * getOwner() const
Return the owner of this operand.
constexpr auto RecursivelySpeculatable
Speculatability
This enum is returned from the getSpeculatability method in the ConditionallySpeculatable op interfac...
constexpr auto NotSpeculatable
static Value defaultReplBuilderFn(OpBuilder &builder, Location loc, Value value)
Default implementation of the non-successor-input replacement builder function.
static LogicalResult defaultMatcherFn(Operation *op)
Default implementation of the pattern matcher function.
StringRef getMappingAttrName()
Name of the mapping attribute produced by loop mappers.
ParallelOp getParallelForInductionVarOwner(Value val)
Returns the parallel loop parent of an induction variable.
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback for IfOp builders. Inserts a yield without arguments.
LoopNest buildLoopNest(OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs, ValueRange steps, ValueRange iterArgs, function_ref< ValueVector(OpBuilder &, Location, ValueRange, ValueRange)> bodyBuilder=nullptr)
Creates a perfect nest of "for" loops, i.e.
bool insideMutuallyExclusiveBranches(Operation *a, Operation *b)
Return true if ops a and b (or their ancestors) are in mutually exclusive regions/blocks of an IfOp.
std::optional< llvm::APSInt > computeUbMinusLb(Value lb, Value ub, bool isSigned)
Helper function to compute the difference between two values.
ForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
SmallVector< Value > ValueVector
An owning vector of values, handy to return from functions.
bool isShapePreserving(ForOp forOp, int64_t arg)
A simple, conservative analysis to determine if the loop is shape preserving.
llvm::function_ref< Value(OpBuilder &, Location loc, Type, Value)> ValueTypeCastFnTy
Perform a replacement of one iter OpOperand of an scf.for to the replacement value with a different t...
ForallOp getForallOpThreadIndexOwner(Value val)
Returns the ForallOp parent of an thread index variable.
SmallVector< Value > replaceAndCastForOpIterArg(RewriterBase &rewriter, scf::ForOp forOp, OpOperand &operand, Value replacement, const ValueTypeCastFnTy &castFn)
LogicalResult promote(RewriterBase &rewriter, scf::ForallOp forallOp)
Promotes the loop body of a scf::ForallOp to its containing block.
bool preservesStaticInformation(Type source, Type target)
Returns true if target is a ranked tensor type that preserves static information available in the sou...
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::function< SmallVector< Value >( OpBuilder &b, Location loc, ArrayRef< BlockArgument > newBbArgs)> NewYieldValuesFn
A function that returns the additional yielded values during replaceWithAdditionalYields.
ParseResult parseDynamicIndexList(OpAsmParser &parser, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &values, DenseI64ArrayAttr &integers, DenseBoolArrayAttr &scalableFlags, SmallVectorImpl< Type > *valueTypes=nullptr, AsmParser::Delimiter delimiter=AsmParser::Delimiter::Square)
Parser hooks for custom directive in assemblyFormat.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
llvm::SetVector< T, Vector, Set, N > SetVector
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
Value getValueOrCreateConstantIndexOp(OpBuilder &b, Location loc, OpFoldResult ofr)
Converts an OpFoldResult to a Value.
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
void populateRegionBranchOpInterfaceInliningPattern(RewritePatternSet &patterns, StringRef opName, NonSuccessorInputReplacementBuilderFn replBuilderFn=detail::defaultReplBuilderFn, PatternMatcherFn matcherFn=detail::defaultMatcherFn, PatternBenefit benefit=1)
Populate a pattern that inlines the body of region branch ops when there is a single acyclic path thr...
LogicalResult verifyListOfOperandsOrIntegers(Operation *op, StringRef name, unsigned expectedNumElements, ArrayRef< int64_t > attr, ValueRange values)
Verify that a the values has as many elements as the number of entries in attr for which isDynamic ev...
void populateRegionBranchOpInterfaceCanonicalizationPatterns(RewritePatternSet &patterns, StringRef opName, PatternBenefit benefit=1)
Populate canonicalization patterns that simplify successor operands/inputs of region branch operation...
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
void visitUsedValuesDefinedAbove(Region ®ion, Region &limit, function_ref< void(OpOperand *)> callback)
Calls callback for each use of a value within region or its descendants that was defined at the ances...
llvm::function_ref< Fn > function_ref
void printDynamicIndexList(OpAsmPrinter &printer, Operation *op, OperandRange values, ArrayRef< int64_t > integers, ArrayRef< bool > scalableFlags, TypeRange valueTypes=TypeRange(), AsmParser::Delimiter delimiter=AsmParser::Delimiter::Square)
Printer hooks for custom directive in assemblyFormat.
std::optional< APInt > constantTripCount(OpFoldResult lb, OpFoldResult ub, OpFoldResult step, bool isSigned, llvm::function_ref< std::optional< llvm::APSInt >(Value, Value, bool)> computeUbMinusLb)
Return the number of iterations for a loop with a lower bound lb, upper bound ub and step step,...
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
LogicalResult matchAndRewrite(ExecuteRegionOp op, PatternRewriter &rewriter) const override
UnresolvedOperand ssaName
This is the representation of an operand reference.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
OpRewritePattern(MLIRContext *context, PatternBenefit benefit=1, ArrayRef< StringRef > generatedNames={})
This represents an operation in an abstracted form, suitable for use with the builder APIs.
void addOperands(ValueRange newOperands)
void addTypes(ArrayRef< Type > newTypes)
Region * addRegion()
Create a region that should be attached to the operation.