MLIR 24.0.0git
SCF.cpp
Go to the documentation of this file.
1//===- SCF.cpp - Structured Control Flow Operations -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
21#include "mlir/IR/IRMapping.h"
22#include "mlir/IR/Matchers.h"
23#include "mlir/IR/Operation.h"
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"
38#include <optional>
39
40using namespace mlir;
41using namespace mlir::scf;
42
43#include "mlir/Dialect/SCF/IR/SCFOpsDialect.cpp.inc"
44
45//===----------------------------------------------------------------------===//
46// SCFDialect Dialect Interfaces
47//===----------------------------------------------------------------------===//
48
49namespace {
50struct SCFInlinerInterface : public DialectInlinerInterface {
51 using DialectInlinerInterface::DialectInlinerInterface;
52 // We don't have any special restrictions on what can be inlined into
53 // destination regions (e.g. while/conditional bodies). Always allow it.
54 bool isLegalToInline(Region *dest, Region *src, bool wouldBeCloned,
55 IRMapping &valueMapping) const final {
56 return true;
57 }
58 // Operations in scf dialect are always legal to inline since they are
59 // pure.
60 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
61 return true;
62 }
63 // Handle the given inlined terminator by replacing it with a new operation
64 // as necessary. Required when the region has only one block.
65 void handleTerminator(Operation *op, ValueRange valuesToRepl) const final {
66 auto retValOp = dyn_cast<scf::YieldOp>(op);
67 if (!retValOp)
68 return;
69
70 for (auto retValue : llvm::zip(valuesToRepl, retValOp.getOperands())) {
71 std::get<0>(retValue).replaceAllUsesWith(std::get<1>(retValue));
72 }
73 }
74};
75} // namespace
76
77//===----------------------------------------------------------------------===//
78// SCFDialect
79//===----------------------------------------------------------------------===//
80
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>();
90}
91
92/// Default callback for IfOp builders. Inserts a yield without arguments.
94 scf::YieldOp::create(builder, loc);
95}
96
97/// Verifies that the first block of the given `region` is terminated by a
98/// TerminatorTy. Reports errors on the given operation if it is not the case.
99template <typename TerminatorTy>
100static TerminatorTy verifyAndGetTerminator(Operation *op, Region &region,
101 StringRef errorMessage) {
102 Operation *terminatorOperation = nullptr;
103 if (!region.empty() && !region.front().empty()) {
104 terminatorOperation = &region.front().back();
105 if (auto yield = dyn_cast_or_null<TerminatorTy>(terminatorOperation))
106 return yield;
107 }
108 auto diag = op->emitOpError(errorMessage);
109 if (terminatorOperation)
110 diag.attachNote(terminatorOperation->getLoc()) << "terminator here";
111 return nullptr;
112}
113
114std::optional<llvm::APSInt> mlir::scf::computeUbMinusLb(Value lb, Value ub,
115 bool isSigned) {
116 llvm::APSInt diff;
117 auto addOp = ub.getDefiningOp<arith::AddIOp>();
118 if (!addOp)
119 return std::nullopt;
120 if ((isSigned && !addOp.hasNoSignedWrap()) ||
121 (!isSigned && !addOp.hasNoUnsignedWrap()))
122 return std::nullopt;
123
124 if (addOp.getLhs() != lb ||
125 !matchPattern(addOp.getRhs(), m_ConstantInt(&diff)))
126 return std::nullopt;
127 return diff;
128}
129
130//===----------------------------------------------------------------------===//
131// ExecuteRegionOp
132//===----------------------------------------------------------------------===//
133
134///
135/// (ssa-id `=`)? `execute_region` `->` function-result-type `{`
136/// block+
137/// `}`
138///
139/// Example:
140/// scf.execute_region -> i32 {
141/// %idx = load %rI[%i] : memref<128xi32>
142/// return %idx : i32
143/// }
144///
145ParseResult ExecuteRegionOp::parse(OpAsmParser &parser,
147 if (parser.parseOptionalArrowTypeList(result.types))
148 return failure();
149
150 if (succeeded(parser.parseOptionalKeyword("no_inline")))
151 result.addAttribute("no_inline", parser.getBuilder().getUnitAttr());
152
153 // Introduce the body region and parse it.
154 Region *body = result.addRegion();
155 if (parser.parseRegion(*body, /*arguments=*/{}, /*argTypes=*/{}) ||
156 parser.parseOptionalAttrDict(result.attributes))
157 return failure();
158
159 return success();
160}
161
162void ExecuteRegionOp::print(OpAsmPrinter &p) {
163 p.printOptionalArrowTypeList(getResultTypes());
164 p << ' ';
165 if (getNoInline())
166 p << "no_inline ";
167 p.printRegion(getRegion(),
168 /*printEntryBlockArgs=*/false,
169 /*printBlockTerminators=*/true);
170 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
171}
172
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");
178 return success();
179}
180
181// Inline an ExecuteRegionOp if its parent can contain multiple blocks.
182// TODO generalize the conditions for operations which can be inlined into.
183// func @func_execute_region_elim() {
184// "test.foo"() : () -> ()
185// %v = scf.execute_region -> i64 {
186// %c = "test.cmp"() : () -> i1
187// cf.cond_br %c, ^bb2, ^bb3
188// ^bb2:
189// %x = "test.val1"() : () -> i64
190// cf.br ^bb4(%x : i64)
191// ^bb3:
192// %y = "test.val2"() : () -> i64
193// cf.br ^bb4(%y : i64)
194// ^bb4(%z : i64):
195// scf.yield %z : i64
196// }
197// "test.bar"(%v) : (i64) -> ()
198// return
199// }
200//
201// becomes
202//
203// func @func_execute_region_elim() {
204// "test.foo"() : () -> ()
205// %c = "test.cmp"() : () -> i1
206// cf.cond_br %c, ^bb1, ^bb2
207// ^bb1: // pred: ^bb0
208// %x = "test.val1"() : () -> i64
209// cf.br ^bb3(%x : i64)
210// ^bb2: // pred: ^bb0
211// %y = "test.val2"() : () -> i64
212// cf.br ^bb3(%y : i64)
213// ^bb3(%z: i64): // 2 preds: ^bb1, ^bb2
214// "test.bar"(%z) : (i64) -> ()
215// return
216// }
217//
218struct MultiBlockExecuteInliner : public OpRewritePattern<ExecuteRegionOp> {
219 using OpRewritePattern<ExecuteRegionOp>::OpRewritePattern;
220
221 LogicalResult matchAndRewrite(ExecuteRegionOp op,
222 PatternRewriter &rewriter) const override {
223 if (op.getNoInline())
224 return failure();
225 if (!isa<FunctionOpInterface, ExecuteRegionOp>(op->getParentOp()))
226 return failure();
227
228 Block *prevBlock = op->getBlock();
229 Block *postBlock = rewriter.splitBlock(prevBlock, op->getIterator());
230 rewriter.setInsertionPointToEnd(prevBlock);
231
232 cf::BranchOp::create(rewriter, op.getLoc(), &op.getRegion().front());
233
234 for (Block &blk : op.getRegion()) {
235 if (YieldOp yieldOp = dyn_cast<YieldOp>(blk.getTerminator())) {
236 rewriter.setInsertionPoint(yieldOp);
237 cf::BranchOp::create(rewriter, yieldOp.getLoc(), postBlock,
238 yieldOp.getResults());
239 rewriter.eraseOp(yieldOp);
240 }
241 }
242
243 rewriter.inlineRegionBefore(op.getRegion(), postBlock);
244 SmallVector<Value> blockArgs;
245
246 for (auto res : op.getResults())
247 blockArgs.push_back(postBlock->addArgument(res.getType(), res.getLoc()));
248
249 rewriter.replaceOp(op, blockArgs);
250 return success();
251 }
252};
253
254void ExecuteRegionOp::getCanonicalizationPatterns(RewritePatternSet &results,
255 MLIRContext *context) {
256 results.add<MultiBlockExecuteInliner>(context);
258 results, ExecuteRegionOp::getOperationName());
259 // Inline ops with a single block that are not marked as "no_inline".
261 results, ExecuteRegionOp::getOperationName(),
263 return failure(cast<ExecuteRegionOp>(op).getNoInline());
264 });
265}
266
267void ExecuteRegionOp::getSuccessorRegions(
269 // If the predecessor is the ExecuteRegionOp, branch into the body.
270 if (point.isParent()) {
271 regions.push_back(RegionSuccessor(&getRegion()));
272 return;
273 }
274
275 // Otherwise, the region branches back to the parent operation.
276 regions.push_back(RegionSuccessor(getOperation()));
277}
278
279void ExecuteRegionOp::getRegionInvocationBounds(
281 bounds.emplace_back(/*lb=*/1, /*ub=*/1);
282}
283
284ValueRange ExecuteRegionOp::getSuccessorInputs(RegionSuccessor successor) {
285 return successor.isOperation() ? ValueRange(getOperation()->getResults())
286 : ValueRange();
287}
288
289//===----------------------------------------------------------------------===//
290// ConditionOp
291//===----------------------------------------------------------------------===//
292
294ConditionOp::getMutableSuccessorOperands(RegionSuccessor point) {
295 assert((point.isOperation() ||
296 point.getSuccessor() == &getParentOp().getAfter()) &&
297 "condition op can only exit the loop or branch to the after"
298 "region");
299 // Pass all operands except the condition to the successor region.
300 return getArgsMutable();
301}
302
303void ConditionOp::getSuccessorRegions(
305 FoldAdaptor adaptor(operands, *this);
306
307 WhileOp whileOp = getParentOp();
308
309 // Condition can either lead to the after region or back to the parent op
310 // depending on whether the condition is true or not.
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())
315 regions.push_back(RegionSuccessor(whileOp.getOperation()));
316}
317
318//===----------------------------------------------------------------------===//
319// ForOp
320//===----------------------------------------------------------------------===//
321
322void ForOp::build(OpBuilder &builder, OperationState &result, Value lb,
323 Value ub, Value step, ValueRange initArgs,
324 BodyBuilderFn bodyBuilder, bool unsignedCmp) {
325 OpBuilder::InsertionGuard guard(builder);
326
327 if (unsignedCmp)
328 result.addAttribute(getUnsignedCmpAttrName(result.name),
329 builder.getUnitAttr());
330 result.addOperands({lb, ub, step});
331 result.addOperands(initArgs);
332 for (Value v : initArgs)
333 result.addTypes(v.getType());
334 Type t = lb.getType();
335 Region *bodyRegion = result.addRegion();
336 Block *bodyBlock = builder.createBlock(bodyRegion);
337 bodyBlock->addArgument(t, result.location);
338 for (Value v : initArgs)
339 bodyBlock->addArgument(v.getType(), v.getLoc());
340
341 // Create the default terminator if the builder is not provided and if the
342 // iteration arguments are not provided. Otherwise, leave this to the caller
343 // because we don't know which values to return from the loop.
344 if (initArgs.empty() && !bodyBuilder) {
345 ForOp::ensureTerminator(*bodyRegion, builder, result.location);
346 } else if (bodyBuilder) {
347 OpBuilder::InsertionGuard guard(builder);
348 builder.setInsertionPointToStart(bodyBlock);
349 bodyBuilder(builder, result.location, bodyBlock->getArgument(0),
350 bodyBlock->getArguments().drop_front());
351 }
352}
353
354LogicalResult ForOp::verify() {
355 // Check that the body block has at least the induction variable argument.
356 // This must be checked before verifyRegions() and before any region trait
357 // verifiers (e.g. LoopLikeOpInterface) that call getRegionIterArgs(), to
358 // avoid crashing with an out-of-bounds drop_front on an empty arg list.
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();
364
365 // Check that the number of init args and op results is the same.
366 if (getInitArgs().size() != getNumResults())
367 return emitOpError(
368 "mismatch in number of loop-carried values and defined values");
369
370 return success();
371}
372
373LogicalResult ForOp::verifyRegions() {
374 // Check that the body block has at least the induction variable argument.
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();
379
380 // Check that the body defines as single block argument for the induction
381 // variable.
382 if (getInductionVar().getType() != getLowerBound().getType())
383 return emitOpError(
384 "expected induction variable to be same type as bounds and step");
385
386 if (getNumRegionIterArgs() != getNumResults())
387 return emitOpError(
388 "mismatch in number of basic block args and defined values");
389
390 auto initArgs = getInitArgs();
391 auto iterArgs = getRegionIterArgs();
392 auto opResults = getResults();
393 unsigned i = 0;
394 for (auto e : llvm::zip(initArgs, iterArgs, opResults)) {
395 if (std::get<0>(e).getType() != std::get<2>(e).getType())
396 return emitOpError() << "types mismatch between " << i
397 << "th iter operand and defined value";
398 if (std::get<1>(e).getType() != std::get<2>(e).getType())
399 return emitOpError() << "types mismatch between " << i
400 << "th iter region arg and defined value";
401
402 ++i;
403 }
404 return success();
405}
406
407std::optional<SmallVector<Value>> ForOp::getLoopInductionVars() {
408 return SmallVector<Value>{getInductionVar()};
409}
410
411std::optional<SmallVector<OpFoldResult>> ForOp::getLoopLowerBounds() {
413}
414
415std::optional<SmallVector<OpFoldResult>> ForOp::getLoopSteps() {
416 return SmallVector<OpFoldResult>{OpFoldResult(getStep())};
417}
418
419std::optional<SmallVector<OpFoldResult>> ForOp::getLoopUpperBounds() {
421}
422
423bool ForOp::isValidInductionVarType(Type type) {
424 return type.isIndex() || type.isSignlessInteger();
425}
426
427LogicalResult ForOp::setLoopLowerBounds(ArrayRef<OpFoldResult> bounds) {
428 if (bounds.size() != 1)
429 return failure();
430 if (auto val = dyn_cast<Value>(bounds[0])) {
431 setLowerBound(val);
432 return success();
433 }
434 return failure();
435}
436
437LogicalResult ForOp::setLoopUpperBounds(ArrayRef<OpFoldResult> bounds) {
438 if (bounds.size() != 1)
439 return failure();
440 if (auto val = dyn_cast<Value>(bounds[0])) {
441 setUpperBound(val);
442 return success();
443 }
444 return failure();
445}
446
447LogicalResult ForOp::setLoopSteps(ArrayRef<OpFoldResult> steps) {
448 if (steps.size() != 1)
449 return failure();
450 if (auto val = dyn_cast<Value>(steps[0])) {
451 setStep(val);
452 return success();
453 }
454 return failure();
455}
456
457std::optional<ResultRange> ForOp::getLoopResults() { return getResults(); }
458
459/// Promotes the loop body of a forOp to its containing block if the forOp
460/// it can be determined that the loop has a single iteration.
461LogicalResult ForOp::promoteIfSingleIteration(RewriterBase &rewriter) {
462 std::optional<APInt> tripCount = getStaticTripCount();
463 LDBG() << "promoteIfSingleIteration tripCount is " << tripCount
464 << " for loop "
465 << OpWithFlags(getOperation(), OpPrintingFlags().skipRegions());
466 if (!tripCount.has_value() || tripCount->getZExtValue() > 1)
467 return failure();
468
469 if (*tripCount == 0) {
470 rewriter.replaceAllUsesWith(getResults(), getInitArgs());
471 rewriter.eraseOp(*this);
472 return success();
473 }
474
475 // Replace all results with the yielded values.
476 auto yieldOp = cast<scf::YieldOp>(getBody()->getTerminator());
477 rewriter.replaceAllUsesWith(getResults(), getYieldedValues());
478
479 // Replace block arguments with lower bound (replacement for IV) and
480 // iter_args.
481 SmallVector<Value> bbArgReplacements;
482 bbArgReplacements.push_back(getLowerBound());
483 llvm::append_range(bbArgReplacements, getInitArgs());
484
485 // Move the loop body operations to the loop's containing block.
486 rewriter.inlineBlockBefore(getBody(), getOperation()->getBlock(),
487 getOperation()->getIterator(), bbArgReplacements);
488
489 // Erase the old terminator and the loop.
490 rewriter.eraseOp(yieldOp);
491 rewriter.eraseOp(*this);
492
493 return success();
494}
495
496/// Prints the initialization list in the form of
497/// <prefix>(%inner = %outer, %inner2 = %outer2, <...>)
498/// where 'inner' values are assumed to be region arguments and 'outer' values
499/// are regular SSA values.
501 Block::BlockArgListType blocksArgs,
502 ValueRange initializers,
503 StringRef prefix = "") {
504 assert(blocksArgs.size() == initializers.size() &&
505 "expected same length of arguments and initializers");
506 if (initializers.empty())
507 return;
508
509 p << prefix << '(';
510 llvm::interleaveComma(llvm::zip(blocksArgs, initializers), p, [&](auto it) {
511 p << std::get<0>(it) << " = " << std::get<1>(it);
512 });
513 p << ")";
514}
515
516void ForOp::print(OpAsmPrinter &p) {
517 if (getUnsignedCmp())
518 p << " unsigned";
519
520 p << " " << getInductionVar() << " = " << getLowerBound() << " to "
521 << getUpperBound() << " step " << getStep();
522
523 printInitializationList(p, getRegionIterArgs(), getInitArgs(), " iter_args");
524 if (!getInitArgs().empty())
525 p << " -> (" << getInitArgs().getTypes() << ')';
526 p << ' ';
527 if (Type t = getInductionVar().getType(); !t.isIndex())
528 p << " : " << t << ' ';
529 p.printRegion(getRegion(),
530 /*printEntryBlockArgs=*/false,
531 /*printBlockTerminators=*/!getInitArgs().empty());
532 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
533}
534
535ParseResult ForOp::parse(OpAsmParser &parser, OperationState &result) {
536 auto &builder = parser.getBuilder();
537 Type type;
538
539 OpAsmParser::Argument inductionVariable;
541
542 if (succeeded(parser.parseOptionalKeyword("unsigned")))
543 result.addAttribute(getUnsignedCmpAttrName(result.name),
544 builder.getUnitAttr());
545
546 // Parse the induction variable followed by '='.
547 if (parser.parseOperand(inductionVariable.ssaName) || parser.parseEqual() ||
548 // Parse loop bounds.
549 parser.parseOperand(lb) || parser.parseKeyword("to") ||
550 parser.parseOperand(ub) || parser.parseKeyword("step") ||
551 parser.parseOperand(step))
552 return failure();
553
554 // Parse the optional initial iteration arguments.
557 regionArgs.push_back(inductionVariable);
558
559 bool hasIterArgs = succeeded(parser.parseOptionalKeyword("iter_args"));
560 if (hasIterArgs) {
561 // Parse assignment list and results type list.
562 if (parser.parseAssignmentList(regionArgs, operands) ||
563 parser.parseArrowTypeList(result.types))
564 return failure();
565 }
566
567 if (regionArgs.size() != result.types.size() + 1)
568 return parser.emitError(
569 parser.getNameLoc(),
570 "mismatch in number of loop-carried values and defined values");
571
572 // Parse optional type, else assume Index.
573 if (parser.parseOptionalColon())
574 type = builder.getIndexType();
575 else if (parser.parseType(type))
576 return failure();
577
578 // Set block argument types, so that they are known when parsing the region.
579 regionArgs.front().type = type;
580 for (auto [iterArg, type] :
581 llvm::zip_equal(llvm::drop_begin(regionArgs), result.types))
582 iterArg.type = type;
583
584 // Parse the body region.
585 Region *body = result.addRegion();
586 if (parser.parseRegion(*body, regionArgs))
587 return failure();
588 ForOp::ensureTerminator(*body, builder, result.location);
589
590 // Resolve input operands. This should be done after parsing the region to
591 // catch invalid IR where operands were defined inside of the region.
592 if (parser.resolveOperand(lb, type, result.operands) ||
593 parser.resolveOperand(ub, type, result.operands) ||
594 parser.resolveOperand(step, type, result.operands))
595 return failure();
596 if (hasIterArgs) {
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;
601 if (parser.resolveOperand(std::get<1>(argOperandType), type,
602 result.operands))
603 return failure();
604 }
605 }
606
607 // Parse the optional attribute list.
608 if (parser.parseOptionalAttrDict(result.attributes))
609 return failure();
610
611 return success();
612}
613
614SmallVector<Region *> ForOp::getLoopRegions() { return {&getRegion()}; }
615
616Block::BlockArgListType ForOp::getRegionIterArgs() {
617 return getBody()->getArguments().drop_front(getNumInductionVars());
618}
619
620MutableArrayRef<OpOperand> ForOp::getInitsMutable() {
621 return getInitArgsMutable();
622}
623
624FailureOr<LoopLikeOpInterface>
625ForOp::replaceWithAdditionalYields(RewriterBase &rewriter,
626 ValueRange newInitOperands,
627 bool replaceInitOperandUsesInLoop,
628 const NewYieldValuesFn &newYieldValuesFn) {
629 // Create a new loop before the existing one, with the extra operands.
630 OpBuilder::InsertionGuard g(rewriter);
631 rewriter.setInsertionPoint(getOperation());
632 auto inits = llvm::to_vector(getInitArgs());
633 inits.append(newInitOperands.begin(), newInitOperands.end());
634 scf::ForOp newLoop = scf::ForOp::create(
635 rewriter, getLoc(), getLowerBound(), getUpperBound(), getStep(), inits,
636 [](OpBuilder &, Location, Value, ValueRange) {}, getUnsignedCmp());
637 newLoop->setDiscardableAttrs(getOperation()->getDiscardableAttrDictionary());
638
639 // Generate the new yield values and append them to the scf.yield operation.
640 auto yieldOp = cast<scf::YieldOp>(getBody()->getTerminator());
641 ArrayRef<BlockArgument> newIterArgs =
642 newLoop.getBody()->getArguments().take_back(newInitOperands.size());
643 {
644 OpBuilder::InsertionGuard g(rewriter);
645 rewriter.setInsertionPoint(yieldOp);
646 SmallVector<Value> newYieldedValues =
647 newYieldValuesFn(rewriter, getLoc(), newIterArgs);
648 assert(newInitOperands.size() == newYieldedValues.size() &&
649 "expected as many new yield values as new iter operands");
650 rewriter.modifyOpInPlace(yieldOp, [&]() {
651 yieldOp.getResultsMutable().append(newYieldedValues);
652 });
653 }
654
655 // Move the loop body to the new op.
656 rewriter.mergeBlocks(getBody(), newLoop.getBody(),
657 newLoop.getBody()->getArguments().take_front(
658 getBody()->getNumArguments()));
659
660 if (replaceInitOperandUsesInLoop) {
661 // Replace all uses of `newInitOperands` with the corresponding basic block
662 // arguments.
663 for (auto it : llvm::zip(newInitOperands, newIterArgs)) {
664 rewriter.replaceUsesWithIf(std::get<0>(it), std::get<1>(it),
665 [&](OpOperand &use) {
666 Operation *user = use.getOwner();
667 return newLoop->isProperAncestor(user);
668 });
669 }
670 }
671
672 // Replace the old loop.
673 rewriter.replaceOp(getOperation(),
674 newLoop->getResults().take_front(getNumResults()));
675 return cast<LoopLikeOpInterface>(newLoop.getOperation());
676}
677
679 auto ivArg = llvm::dyn_cast<BlockArgument>(val);
680 if (!ivArg)
681 return ForOp();
682 assert(ivArg.getOwner() && "unlinked block argument");
683 auto *containingOp = ivArg.getOwner()->getParentOp();
684 return dyn_cast_or_null<ForOp>(containingOp);
685}
686
687OperandRange ForOp::getEntrySuccessorOperands(RegionSuccessor successor) {
688 return getInitArgs();
689}
690
691void ForOp::getSuccessorRegions(RegionBranchPoint point,
693 if (std::optional<APInt> tripCount = getStaticTripCount()) {
694 // The loop has a known static trip count.
695 if (point.isParent()) {
696 if (*tripCount == 0) {
697 // The loop has zero iterations. It branches directly back to the
698 // parent.
699 regions.push_back(RegionSuccessor(getOperation()));
700 } else {
701 // The loop has at least one iteration. It branches into the body.
702 regions.push_back(RegionSuccessor(&getRegion()));
703 }
704 return;
705 } else if (*tripCount == 1) {
706 // The loop has exactly 1 iteration. Therefore, it branches from the
707 // region to the parent. (No further iteration.)
708 regions.push_back(RegionSuccessor(getOperation()));
709 return;
710 }
711 }
712
713 // Both the operation itself and the region may be branching into the body or
714 // back into the operation itself. It is possible for loop not to enter the
715 // body.
716 regions.push_back(RegionSuccessor(&getRegion()));
717 regions.push_back(RegionSuccessor(getOperation()));
718}
719
720ValueRange ForOp::getSuccessorInputs(RegionSuccessor successor) {
721 return successor.isOperation() ? ValueRange(getResults())
722 : ValueRange(getRegionIterArgs());
723}
724
725SmallVector<Region *> ForallOp::getLoopRegions() { return {&getRegion()}; }
726
727/// Promotes the loop body of a forallOp to its containing block if it can be
728/// determined that the loop has a single iteration.
729LogicalResult scf::ForallOp::promoteIfSingleIteration(RewriterBase &rewriter) {
730 for (auto [lb, ub, step] :
731 llvm::zip(getMixedLowerBound(), getMixedUpperBound(), getMixedStep())) {
732 auto tripCount =
733 constantTripCount(lb, ub, step, /*isSigned=*/true, computeUbMinusLb);
734 if (!tripCount.has_value() || *tripCount != 1)
735 return failure();
736 }
737
738 return promote(rewriter, *this);
739}
740
741Block::BlockArgListType ForallOp::getRegionIterArgs() {
742 return getBody()->getArguments().drop_front(getRank());
743}
744
745MutableArrayRef<OpOperand> ForallOp::getInitsMutable() {
746 return getOutputsMutable();
747}
748
749/// Promotes the loop body of a scf::ForallOp to its containing block.
750LogicalResult mlir::scf::promote(RewriterBase &rewriter,
751 scf::ForallOp forallOp) {
752 OpBuilder::InsertionGuard g(rewriter);
753 scf::InParallelOp terminator = forallOp.getTerminator();
754
755 // Check that all combining ops can be promoted before modifying the IR,
756 // including materializing the lower bounds below.
757 for (Operation &op : terminator.getYieldingOps()) {
758 if (!isa<tensor::ParallelInsertSliceOp>(op))
759 return rewriter.notifyMatchFailure(forallOp, [&](Diagnostic &diag) {
760 diag << "unsupported parallel combining op: " << op.getName();
761 });
762 }
763
764 // Replace block arguments with lower bounds (replacements for IVs) and
765 // outputs.
766 SmallVector<Value> bbArgReplacements = forallOp.getLowerBound(rewriter);
767 bbArgReplacements.append(forallOp.getOutputs().begin(),
768 forallOp.getOutputs().end());
769
770 // Collect combining ops in shared output order before inlining replaces the
771 // output block arguments. Keep a separate list for each output.
773 yieldingOps.reserve(forallOp.getNumResults());
774
775 for (BlockArgument outputArg : forallOp.getRegionIterArgs()) {
776 auto &outputOps = yieldingOps.emplace_back();
777
778 for (Operation *op : forallOp.getCombiningOps(outputArg)) {
779 auto combiningOp = cast<ParallelCombiningOpInterface>(op);
780 // Supported tensor.parallel_insert_slice ops have a single destination.
781 if (combiningOp->getParentOp() != terminator.getOperation() ||
782 combiningOp.getUpdatedDestinations()[0].get() != outputArg)
783 continue;
784
785 outputOps.push_back(combiningOp);
786 }
787 }
788
789 // Move the loop body operations to the loop's containing block.
790 rewriter.inlineBlockBefore(forallOp.getBody(), forallOp->getBlock(),
791 forallOp->getIterator(), bbArgReplacements);
792
793 // Replace the terminator with tensor.insert_slice ops.
794 rewriter.setInsertionPointAfter(forallOp);
795 SmallVector<Value> results;
796 results.reserve(forallOp.getResults().size());
797 for (auto [output, combiningOps] :
798 llvm::zip_equal(forallOp.getOutputs(), yieldingOps)) {
799 Value result = output;
800
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());
808 }
809
810 results.push_back(result);
811 }
812
813 rewriter.replaceAllUsesWith(forallOp.getResults(), results);
814
815 // Erase the old terminator and the loop.
816 rewriter.eraseOp(terminator);
817 rewriter.eraseOp(forallOp);
818 return success();
819}
820
822 OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
823 ValueRange steps, ValueRange iterArgs,
825 bodyBuilder) {
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");
830
831 // If there are no bounds, call the body-building function and return early.
832 if (lbs.empty()) {
833 ValueVector results =
834 bodyBuilder ? bodyBuilder(builder, loc, ValueRange(), iterArgs)
835 : ValueVector();
836 assert(results.size() == iterArgs.size() &&
837 "loop nest body must return as many values as loop has iteration "
838 "arguments");
839 return LoopNest{{}, std::move(results)};
840 }
841
842 // First, create the loop structure iteratively using the body-builder
843 // callback of `ForOp::build`. Do not create `YieldOp`s yet.
844 OpBuilder::InsertionGuard guard(builder);
847 loops.reserve(lbs.size());
848 ivs.reserve(lbs.size());
849 ValueRange currentIterArgs = iterArgs;
850 Location currentLoc = loc;
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,
854 [&](OpBuilder &nestedBuilder, Location nestedLoc, Value iv,
855 ValueRange args) {
856 ivs.push_back(iv);
857 // It is safe to store ValueRange args because it points to block
858 // arguments of a loop operation that we also own.
859 currentIterArgs = args;
860 currentLoc = nestedLoc;
861 });
862 // Set the builder to point to the body of the newly created loop. We don't
863 // do this in the callback because the builder is reset when the callback
864 // returns.
865 builder.setInsertionPointToStart(loop.getBody());
866 loops.push_back(loop);
867 }
868
869 // For all loops but the innermost, yield the results of the nested loop.
870 for (unsigned i = 0, e = loops.size() - 1; i < e; ++i) {
871 builder.setInsertionPointToEnd(loops[i].getBody());
872 scf::YieldOp::create(builder, loc, loops[i + 1].getResults());
873 }
874
875 // In the body of the innermost loop, call the body building function if any
876 // and yield its results.
877 builder.setInsertionPointToStart(loops.back().getBody());
878 ValueVector results = bodyBuilder
879 ? bodyBuilder(builder, currentLoc, ivs,
880 loops.back().getRegionIterArgs())
881 : ValueVector();
882 assert(results.size() == iterArgs.size() &&
883 "loop nest body must return as many values as loop has iteration "
884 "arguments");
885 builder.setInsertionPointToEnd(loops.back().getBody());
886 scf::YieldOp::create(builder, loc, results);
887
888 // Return the loops.
889 ValueVector nestResults;
890 llvm::append_range(nestResults, loops.front().getResults());
891 return LoopNest{std::move(loops), std::move(nestResults)};
892}
893
895 OpBuilder &builder, Location loc, ValueRange lbs, ValueRange ubs,
896 ValueRange steps,
897 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilder) {
898 // Delegate to the main function by wrapping the body builder.
899 return buildLoopNest(builder, loc, lbs, ubs, steps, {},
900 [&bodyBuilder](OpBuilder &nestedBuilder,
901 Location nestedLoc, ValueRange ivs,
903 if (bodyBuilder)
904 bodyBuilder(nestedBuilder, nestedLoc, ivs);
905 return {};
906 });
907}
908
911 OpOperand &operand, Value replacement,
912 const ValueTypeCastFnTy &castFn) {
913 assert(operand.getOwner() == forOp);
914 Type oldType = operand.get().getType(), newType = replacement.getType();
915
916 // 1. Create new iter operands, exactly 1 is replaced.
917 assert(operand.getOperandNumber() >= forOp.getNumControlOperands() &&
918 "expected an iter OpOperand");
919 assert(operand.get().getType() != replacement.getType() &&
920 "Expected a different type");
921 SmallVector<Value> newIterOperands;
922 for (OpOperand &opOperand : forOp.getInitArgsMutable()) {
923 if (opOperand.getOperandNumber() == operand.getOperandNumber()) {
924 newIterOperands.push_back(replacement);
925 continue;
926 }
927 newIterOperands.push_back(opOperand.get());
928 }
929
930 // 2. Create the new forOp shell.
931 scf::ForOp newForOp = scf::ForOp::create(
932 rewriter, forOp.getLoc(), forOp.getLowerBound(), forOp.getUpperBound(),
933 forOp.getStep(), newIterOperands, /*bodyBuilder=*/nullptr,
934 forOp.getUnsignedCmp());
935 newForOp->setDiscardableAttrs(
936 forOp->getDiscardableAttrDictionary().getValue());
937 Block &newBlock = newForOp.getRegion().front();
938 SmallVector<Value, 4> newBlockTransferArgs(newBlock.getArguments().begin(),
939 newBlock.getArguments().end());
940
941 // 3. Inject an incoming cast op at the beginning of the block for the bbArg
942 // corresponding to the `replacement` value.
943 OpBuilder::InsertionGuard g(rewriter);
944 rewriter.setInsertionPointToStart(&newBlock);
945 BlockArgument newRegionIterArg = newForOp.getTiedLoopRegionIterArg(
946 &newForOp->getOpOperand(operand.getOperandNumber()));
947 Value castIn = castFn(rewriter, newForOp.getLoc(), oldType, newRegionIterArg);
948 newBlockTransferArgs[newRegionIterArg.getArgNumber()] = castIn;
949
950 // 4. Steal the old block ops, mapping to the newBlockTransferArgs.
951 Block &oldBlock = forOp.getRegion().front();
952 rewriter.mergeBlocks(&oldBlock, &newBlock, newBlockTransferArgs);
953
954 // 5. Inject an outgoing cast op at the end of the block and yield it instead.
955 auto clonedYieldOp = cast<scf::YieldOp>(newBlock.getTerminator());
956 rewriter.setInsertionPoint(clonedYieldOp);
957 unsigned yieldIdx =
958 newRegionIterArg.getArgNumber() - forOp.getNumInductionVars();
959 Value castOut = castFn(rewriter, newForOp.getLoc(), newType,
960 clonedYieldOp.getOperand(yieldIdx));
961 SmallVector<Value> newYieldOperands = clonedYieldOp.getOperands();
962 newYieldOperands[yieldIdx] = castOut;
963 scf::YieldOp::create(rewriter, newForOp.getLoc(), newYieldOperands);
964 rewriter.eraseOp(clonedYieldOp);
965
966 // 6. Inject an outgoing cast op after the forOp.
967 rewriter.setInsertionPointAfter(newForOp);
968 SmallVector<Value> newResults = newForOp.getResults();
969 newResults[yieldIdx] =
970 castFn(rewriter, newForOp.getLoc(), oldType, newResults[yieldIdx]);
971
972 return newResults;
973}
974
975bool mlir::scf::isShapePreserving(ForOp forOp, int64_t arg) {
976 assert(arg < static_cast<int64_t>(forOp.getNumResults()) &&
977 "arg is out of bounds");
978 Value value = forOp.getYieldedValues()[arg];
979 while (value) {
980 if (value == forOp.getRegionIterArgs()[arg])
981 return true;
982 OpResult opResult = dyn_cast<OpResult>(value);
983 if (!opResult)
984 return false;
985
987 .Case([&](DestinationStyleOpInterface op) {
988 return op.getTiedOpOperand(opResult)->get();
989 })
990 .Case([&](ForOp forOp) {
991 return isShapePreserving(forOp, opResult.getResultNumber())
992 ? forOp.getInitArgs()[opResult.getResultNumber()]
993 : Value();
994 })
995 .Default(nullptr);
996 }
997 return false;
998}
999
1000namespace {
1001/// Fold scf.for iter_arg/result pairs that go through incoming/ougoing
1002/// a tensor.cast op pair so as to pull the tensor.cast inside the scf.for:
1003///
1004/// ```
1005/// %0 = tensor.cast %t0 : tensor<32x1024xf32> to tensor<?x?xf32>
1006/// %1 = scf.for %i = %c0 to %c1024 step %c32 iter_args(%iter_t0 = %0)
1007/// -> (tensor<?x?xf32>) {
1008/// %2 = call @do(%iter_t0) : (tensor<?x?xf32>) -> tensor<32x1024xf32>
1009/// %3 = tensor.cast %2 : tensor<32x1024xf32> to tensor<?x?xf32>
1010/// scf.yield %3 : tensor<?x?xf32>
1011/// }
1012/// use_of(%1)
1013/// ```
1014///
1015/// folds into:
1016///
1017/// ```
1018/// %0 = scf.for %arg2 = %c0 to %c1024 step %c32 iter_args(%arg3 = %arg0)
1019/// -> (tensor<32x1024xf32>) {
1020/// %2 = tensor.cast %arg3 : tensor<32x1024xf32> to tensor<?x?xf32>
1021/// %3 = call @do(%2) : (tensor<?x?xf32>) -> tensor<32x1024xf32>
1022/// scf.yield %3 : tensor<32x1024xf32>
1023/// }
1024/// %1 = tensor.cast %0 : tensor<32x1024xf32> to tensor<?x?xf32>
1025/// use_of(%1)
1026/// ```
1027struct ForOpTensorCastFolder : public OpRewritePattern<ForOp> {
1029
1030 LogicalResult matchAndRewrite(ForOp op,
1031 PatternRewriter &rewriter) const override {
1032 for (auto it : llvm::zip(op.getInitArgsMutable(), op.getResults())) {
1033 OpOperand &iterOpOperand = std::get<0>(it);
1034 auto incomingCast = iterOpOperand.get().getDefiningOp<tensor::CastOp>();
1035 if (!incomingCast ||
1036 incomingCast.getSource().getType() == incomingCast.getType())
1037 continue;
1038 // If the dest type of the cast does not preserve static information in
1039 // the source type.
1041 incomingCast.getDest().getType(),
1042 incomingCast.getSource().getType()))
1043 continue;
1044 if (!std::get<1>(it).hasOneUse())
1045 continue;
1046 // The fold casts the yielded value to the cast's source type, which is
1047 // only valid if every iteration yields a value of that type. A dynamic
1048 // dimension of that type stays dynamic, so its size may still change
1049 // between iterations; only the static sizes are asserted.
1050 int64_t resultNumber = std::get<1>(it).getResultNumber();
1051 auto yieldedCast =
1052 op.getYieldedValues()[resultNumber].getDefiningOp<tensor::CastOp>();
1053 bool yieldsStaticType =
1054 yieldedCast && yieldedCast.getSource().getType() ==
1055 incomingCast.getSource().getType();
1056 if (!yieldsStaticType && !isShapePreserving(op, resultNumber))
1057 continue;
1058
1059 // Create a new ForOp with that iter operand replaced.
1060 rewriter.replaceOp(
1062 rewriter, op, iterOpOperand, incomingCast.getSource(),
1063 [](OpBuilder &b, Location loc, Type type, Value source) {
1064 return tensor::CastOp::create(b, loc, type, source);
1065 }));
1066 return success();
1067 }
1068 return failure();
1069 }
1070};
1071} // namespace
1072
1073void ForOp::getCanonicalizationPatterns(RewritePatternSet &results,
1074 MLIRContext *context) {
1075 results.add<ForOpTensorCastFolder>(context);
1077 results, ForOp::getOperationName());
1078 // Inline single-iteration loops before applying the generic region branch op
1079 // canonicalizations, which may otherwise remove tied iter_args and results
1080 // independently.
1082 results, ForOp::getOperationName(),
1083 /*replBuilderFn=*/
1084 [](OpBuilder &builder, Location loc, Value value) {
1085 // scf.for has only one non-successor input value: the loop induction
1086 // variable. In case of a single acyclic path through the op, the IV can
1087 // be safely replaced with the lower bound.
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();
1092 },
1094 /*benefit=*/2);
1095}
1096
1097std::optional<APInt> ForOp::getConstantStep() {
1098 IntegerAttr step;
1099 if (matchPattern(getStep(), m_Constant(&step)))
1100 return step.getValue();
1101 return {};
1102}
1103
1104std::optional<MutableArrayRef<OpOperand>> ForOp::getYieldedValuesMutable() {
1105 return cast<scf::YieldOp>(getBody()->getTerminator()).getResultsMutable();
1106}
1107
1108Speculation::Speculatability ForOp::getSpeculatability() {
1109 // `scf.for (I = Start; I < End; I += 1)` terminates for all values of Start
1110 // and End.
1111 if (auto constantStep = getConstantStep())
1112 if (*constantStep == 1)
1114
1115 // For Step != 1, the loop may not terminate. We can add more smarts here if
1116 // needed.
1118}
1119
1120std::optional<APInt> ForOp::getStaticTripCount() {
1121 return constantTripCount(getLowerBound(), getUpperBound(), getStep(),
1122 /*isSigned=*/!getUnsignedCmp(), computeUbMinusLb);
1123}
1124
1125//===----------------------------------------------------------------------===//
1126// ForallOp
1127//===----------------------------------------------------------------------===//
1128
1129LogicalResult ForallOp::verify() {
1130 unsigned numLoops = getRank();
1131 // Check number of outputs.
1132 if (getNumResults() != getOutputs().size())
1133 return emitOpError("produces ")
1134 << getNumResults() << " results, but has only "
1135 << getOutputs().size() << " outputs";
1136
1137 // Check that the body defines block arguments for thread indices and outputs.
1138 auto *body = getBody();
1139 if (body->getNumArguments() != numLoops + getOutputs().size())
1140 return emitOpError("region expects ") << numLoops << " arguments";
1141 for (int64_t i = 0; i < numLoops; ++i)
1142 if (!body->getArgument(i).getType().isIndex())
1143 return emitOpError("expects ")
1144 << i << "-th block argument to be an index";
1145 for (unsigned i = 0; i < getOutputs().size(); ++i)
1146 if (body->getArgument(i + numLoops).getType() != getOutputs()[i].getType())
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()))
1153 return emitOpError() << getMappingAttrName()
1154 << " supports at most one device masking attribute";
1155 }
1156
1157 // Verify mixed static/dynamic control variables.
1158 Operation *op = getOperation();
1159 if (failed(verifyListOfOperandsOrIntegers(op, "lower bound", numLoops,
1160 getStaticLowerBound(),
1161 getDynamicLowerBound())))
1162 return failure();
1163 if (failed(verifyListOfOperandsOrIntegers(op, "upper bound", numLoops,
1164 getStaticUpperBound(),
1165 getDynamicUpperBound())))
1166 return failure();
1167 if (failed(verifyListOfOperandsOrIntegers(op, "step", numLoops,
1168 getStaticStep(), getDynamicStep())))
1169 return failure();
1170
1171 return success();
1172}
1173
1174void ForallOp::print(OpAsmPrinter &p) {
1175 Operation *op = getOperation();
1176 p << " (" << getInductionVars();
1177 if (isNormalized()) {
1178 p << ") in ";
1179 printDynamicIndexList(p, op, getDynamicUpperBound(), getStaticUpperBound(),
1180 /*valueTypes=*/{}, /*scalables=*/{},
1182 } else {
1183 p << ") = ";
1184 printDynamicIndexList(p, op, getDynamicLowerBound(), getStaticLowerBound(),
1185 /*valueTypes=*/{}, /*scalables=*/{},
1187 p << " to ";
1188 printDynamicIndexList(p, op, getDynamicUpperBound(), getStaticUpperBound(),
1189 /*valueTypes=*/{}, /*scalables=*/{},
1191 p << " step ";
1192 printDynamicIndexList(p, op, getDynamicStep(), getStaticStep(),
1193 /*valueTypes=*/{}, /*scalables=*/{},
1195 }
1196 printInitializationList(p, getRegionOutArgs(), getOutputs(), " shared_outs");
1197 p << " ";
1198 if (!getRegionOutArgs().empty())
1199 p << "-> (" << getResultTypes() << ") ";
1200 p.printRegion(getRegion(),
1201 /*printEntryBlockArgs=*/false,
1202 /*printBlockTerminators=*/getNumResults() > 0);
1203 SmallVector<NamedAttribute> attrs(op->getDiscardableAttrs());
1204 if (ArrayAttr mapping = getMappingAttr())
1205 attrs.emplace_back(getMappingAttrName(), mapping);
1206 llvm::sort(attrs);
1207 p.printOptionalAttrDict(attrs);
1208}
1209
1210ParseResult ForallOp::parse(OpAsmParser &parser, OperationState &result) {
1211 OpBuilder b(parser.getContext());
1212 auto indexType = b.getIndexType();
1213
1214 // Parse an opening `(` followed by thread index variables followed by `)`
1215 // TODO: when we can refer to such "induction variable"-like handles from the
1216 // declarative assembly format, we can implement the parser as a custom hook.
1217 SmallVector<OpAsmParser::Argument, 4> ivs;
1219 return failure();
1220
1221 DenseI64ArrayAttr staticLbs, staticUbs, staticSteps;
1222 SmallVector<OpAsmParser::UnresolvedOperand> dynamicLbs, dynamicUbs,
1223 dynamicSteps;
1224 if (succeeded(parser.parseOptionalKeyword("in"))) {
1225 // Parse upper bounds.
1226 if (parseDynamicIndexList(parser, dynamicUbs, staticUbs,
1227 /*valueTypes=*/nullptr,
1229 parser.resolveOperands(dynamicUbs, indexType, result.operands))
1230 return failure();
1231
1232 unsigned numLoops = ivs.size();
1233 staticLbs = b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 0));
1234 staticSteps = b.getDenseI64ArrayAttr(SmallVector<int64_t>(numLoops, 1));
1235 } else {
1236 // Parse lower bounds.
1237 if (parser.parseEqual() ||
1238 parseDynamicIndexList(parser, dynamicLbs, staticLbs,
1239 /*valueTypes=*/nullptr,
1241
1242 parser.resolveOperands(dynamicLbs, indexType, result.operands))
1243 return failure();
1244
1245 // Parse upper bounds.
1246 if (parser.parseKeyword("to") ||
1247 parseDynamicIndexList(parser, dynamicUbs, staticUbs,
1248 /*valueTypes=*/nullptr,
1250 parser.resolveOperands(dynamicUbs, indexType, result.operands))
1251 return failure();
1252
1253 // Parse step values.
1254 if (parser.parseKeyword("step") ||
1255 parseDynamicIndexList(parser, dynamicSteps, staticSteps,
1256 /*valueTypes=*/nullptr,
1258 parser.resolveOperands(dynamicSteps, indexType, result.operands))
1259 return failure();
1260 }
1261
1262 // Parse out operands and results.
1263 SmallVector<OpAsmParser::Argument, 4> regionOutArgs;
1264 SmallVector<OpAsmParser::UnresolvedOperand, 4> outOperands;
1265 SMLoc outOperandsLoc = parser.getCurrentLocation();
1266 if (succeeded(parser.parseOptionalKeyword("shared_outs"))) {
1267 if (outOperands.size() != result.types.size())
1268 return parser.emitError(outOperandsLoc,
1269 "mismatch between out operands and types");
1270 if (parser.parseAssignmentList(regionOutArgs, outOperands) ||
1271 parser.parseOptionalArrowTypeList(result.types) ||
1272 parser.resolveOperands(outOperands, result.types, outOperandsLoc,
1273 result.operands))
1274 return failure();
1275 }
1276
1277 // Parse region.
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);
1283 }
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);
1288 }
1289 if (parser.parseRegion(*region, regionArgs))
1290 return failure();
1291
1292 // Ensure terminator and move region.
1293 ForallOp::ensureTerminator(*region, b, result.location);
1294 result.addRegion(std::move(region));
1295
1296 // Parse the optional attribute list.
1297 if (parser.parseOptionalAttrDict(result.attributes))
1298 return failure();
1299
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())}));
1309 return success();
1310}
1311
1312// Builder that takes loop bounds.
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,
1318 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
1319 SmallVector<int64_t> staticLbs, staticUbs, staticSteps;
1320 SmallVector<Value> dynamicLbs, dynamicUbs, dynamicSteps;
1321 dispatchIndexOpFoldResults(lbs, dynamicLbs, staticLbs);
1322 dispatchIndexOpFoldResults(ubs, dynamicUbs, staticUbs);
1323 dispatchIndexOpFoldResults(steps, dynamicSteps, staticSteps);
1324
1325 result.addOperands(dynamicLbs);
1326 result.addOperands(dynamicUbs);
1327 result.addOperands(dynamicSteps);
1328 result.addOperands(outputs);
1329 result.addTypes(TypeRange(outputs));
1330
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));
1337 result.addAttribute(
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),
1345 mapping.value());
1346 }
1347
1348 Region *bodyRegion = result.addRegion();
1349 OpBuilder::InsertionGuard g(b);
1350 b.createBlock(bodyRegion);
1351 Block &bodyBlock = bodyRegion->front();
1352
1353 // Add block arguments for indices and outputs.
1354 bodyBlock.addArguments(
1355 SmallVector<Type>(lbs.size(), b.getIndexType()),
1356 SmallVector<Location>(staticLbs.size(), result.location));
1357 bodyBlock.addArguments(
1358 TypeRange(outputs),
1359 SmallVector<Location>(outputs.size(), result.location));
1360
1361 b.setInsertionPointToStart(&bodyBlock);
1362 if (!bodyBuilderFn) {
1363 ForallOp::ensureTerminator(*bodyRegion, b, result.location);
1364 return;
1365 }
1366 bodyBuilderFn(b, result.location, bodyBlock.getArguments());
1367}
1368
1369// Builder that takes loop bounds.
1370void ForallOp::build(
1371 mlir::OpBuilder &b, mlir::OperationState &result,
1372 ArrayRef<OpFoldResult> ubs, ValueRange outputs,
1373 std::optional<ArrayAttr> mapping,
1374 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn) {
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);
1379}
1380
1381// Checks if the lbs are zeros and steps are ones.
1382bool ForallOp::isNormalized() {
1383 auto allEqual = [](ArrayRef<OpFoldResult> results, int64_t val) {
1384 return llvm::all_of(results, [&](OpFoldResult ofr) {
1385 auto intValue = getConstantIntValue(ofr);
1386 return intValue.has_value() && intValue == val;
1387 });
1388 };
1389 return allEqual(getMixedLowerBound(), 0) && allEqual(getMixedStep(), 1);
1390}
1391
1392InParallelOp ForallOp::getTerminator() {
1393 return cast<InParallelOp>(getBody()->getTerminator());
1394}
1395
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);
1401 }
1402 }
1403 return storeOps;
1404}
1405
1406SmallVector<DeviceMappingAttrInterface> ForallOp::getDeviceMappingAttrs() {
1407 SmallVector<DeviceMappingAttrInterface> res;
1408 if (!getMapping())
1409 return res;
1410 for (auto attr : getMapping()->getValue()) {
1411 auto m = dyn_cast<DeviceMappingAttrInterface>(attr);
1412 if (m)
1413 res.push_back(m);
1414 }
1415 return res;
1416}
1417
1418FailureOr<DeviceMaskingAttrInterface> ForallOp::getDeviceMaskingAttr() {
1419 DeviceMaskingAttrInterface res;
1420 if (!getMapping())
1421 return res;
1422 for (auto attr : getMapping()->getValue()) {
1423 auto m = dyn_cast<DeviceMaskingAttrInterface>(attr);
1424 if (m && res)
1425 return failure();
1426 if (m)
1427 res = m;
1428 }
1429 return res;
1430}
1431
1432bool ForallOp::usesLinearMapping() {
1433 SmallVector<DeviceMappingAttrInterface> ifaces = getDeviceMappingAttrs();
1434 if (ifaces.empty())
1435 return false;
1436 return ifaces.front().isLinearMapping();
1437}
1438
1439std::optional<SmallVector<Value>> ForallOp::getLoopInductionVars() {
1440 return SmallVector<Value>{getBody()->getArguments().take_front(getRank())};
1441}
1442
1443// Get lower bounds as OpFoldResult.
1444std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopLowerBounds() {
1445 Builder b(getOperation()->getContext());
1446 return getMixedValues(getStaticLowerBound(), getDynamicLowerBound(), b);
1447}
1448
1449// Get upper bounds as OpFoldResult.
1450std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopUpperBounds() {
1451 Builder b(getOperation()->getContext());
1452 return getMixedValues(getStaticUpperBound(), getDynamicUpperBound(), b);
1453}
1454
1455// Get steps as OpFoldResult.
1456std::optional<SmallVector<OpFoldResult>> ForallOp::getLoopSteps() {
1457 Builder b(getOperation()->getContext());
1458 return getMixedValues(getStaticStep(), getDynamicStep(), b);
1459}
1460
1462 auto tidxArg = llvm::dyn_cast<BlockArgument>(val);
1463 if (!tidxArg)
1464 return ForallOp();
1465 assert(tidxArg.getOwner() && "unlinked block argument");
1466 auto *containingOp = tidxArg.getOwner()->getParentOp();
1467 return dyn_cast<ForallOp>(containingOp);
1468}
1469
1470namespace {
1471/// Fold tensor.dim(forall shared_outs(... = %t)) to tensor.dim(%t).
1472struct DimOfForallOp : public OpRewritePattern<tensor::DimOp> {
1473 using OpRewritePattern<tensor::DimOp>::OpRewritePattern;
1474
1475 LogicalResult matchAndRewrite(tensor::DimOp dimOp,
1476 PatternRewriter &rewriter) const final {
1477 auto forallOp = dimOp.getSource().getDefiningOp<ForallOp>();
1478 if (!forallOp)
1479 return failure();
1480 Value sharedOut =
1481 forallOp.getTiedOpOperand(llvm::cast<OpResult>(dimOp.getSource()))
1482 ->get();
1483 rewriter.modifyOpInPlace(
1484 dimOp, [&]() { dimOp.getSourceMutable().assign(sharedOut); });
1485 return success();
1486 }
1487};
1488
1489class ForallOpControlOperandsFolder : public OpRewritePattern<ForallOp> {
1490public:
1491 using OpRewritePattern<ForallOp>::OpRewritePattern;
1492
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());
1498 if (failed(foldDynamicIndexList(mixedLowerBound)) &&
1499 failed(foldDynamicIndexList(mixedUpperBound)) &&
1500 failed(foldDynamicIndexList(mixedStep)))
1501 return failure();
1502
1503 rewriter.modifyOpInPlace(op, [&]() {
1504 SmallVector<Value> dynamicLowerBound, dynamicUpperBound, dynamicStep;
1505 SmallVector<int64_t> staticLowerBound, staticUpperBound, staticStep;
1506 dispatchIndexOpFoldResults(mixedLowerBound, dynamicLowerBound,
1507 staticLowerBound);
1508 op.getDynamicLowerBoundMutable().assign(dynamicLowerBound);
1509 op.setStaticLowerBound(staticLowerBound);
1510
1511 dispatchIndexOpFoldResults(mixedUpperBound, dynamicUpperBound,
1512 staticUpperBound);
1513 op.getDynamicUpperBoundMutable().assign(dynamicUpperBound);
1514 op.setStaticUpperBound(staticUpperBound);
1515
1516 dispatchIndexOpFoldResults(mixedStep, dynamicStep, staticStep);
1517 op.getDynamicStepMutable().assign(dynamicStep);
1518 op.setStaticStep(staticStep);
1519
1520 op->setInherentAttr(
1521 rewriter.getStringAttr(ForallOp::getOperandSegmentSizeAttr()),
1522 rewriter.getDenseI32ArrayAttr(
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())}));
1527 });
1528 return success();
1529 }
1530};
1531
1532/// The following canonicalization pattern folds the iter arguments of
1533/// scf.forall op if :-
1534/// 1. The corresponding result has zero uses.
1535/// 2. The iter argument is NOT being modified within the loop body.
1536/// uses.
1537///
1538/// Example of first case :-
1539/// INPUT:
1540/// %res:3 = scf.forall ... shared_outs(%arg0 = %a, %arg1 = %b, %arg2 = %c)
1541/// {
1542/// ...
1543/// <SOME USE OF %arg0>
1544/// <SOME USE OF %arg1>
1545/// <SOME USE OF %arg2>
1546/// ...
1547/// scf.forall.in_parallel {
1548/// <STORE OP WITH DESTINATION %arg1>
1549/// <STORE OP WITH DESTINATION %arg0>
1550/// <STORE OP WITH DESTINATION %arg2>
1551/// }
1552/// }
1553/// return %res#1
1554///
1555/// OUTPUT:
1556/// %res:3 = scf.forall ... shared_outs(%new_arg0 = %b)
1557/// {
1558/// ...
1559/// <SOME USE OF %a>
1560/// <SOME USE OF %new_arg0>
1561/// <SOME USE OF %c>
1562/// ...
1563/// scf.forall.in_parallel {
1564/// <STORE OP WITH DESTINATION %new_arg0>
1565/// }
1566/// }
1567/// return %res
1568///
1569/// NOTE: 1. All uses of the folded shared_outs (iter argument) within the
1570/// scf.forall is replaced by their corresponding operands.
1571/// 2. Even if there are <STORE OP WITH DESTINATION *> ops within the body
1572/// of the scf.forall besides within scf.forall.in_parallel terminator,
1573/// this canonicalization remains valid. For more details, please refer
1574/// to :
1575/// https://github.com/llvm/llvm-project/pull/90189#discussion_r1589011124
1576/// 3. TODO(avarma): Generalize it for other store ops. Currently it
1577/// handles tensor.parallel_insert_slice ops only.
1578///
1579/// Example of second case :-
1580/// INPUT:
1581/// %res:2 = scf.forall ... shared_outs(%arg0 = %a, %arg1 = %b)
1582/// {
1583/// ...
1584/// <SOME USE OF %arg0>
1585/// <SOME USE OF %arg1>
1586/// ...
1587/// scf.forall.in_parallel {
1588/// <STORE OP WITH DESTINATION %arg1>
1589/// }
1590/// }
1591/// return %res#0, %res#1
1592///
1593/// OUTPUT:
1594/// %res = scf.forall ... shared_outs(%new_arg0 = %b)
1595/// {
1596/// ...
1597/// <SOME USE OF %a>
1598/// <SOME USE OF %new_arg0>
1599/// ...
1600/// scf.forall.in_parallel {
1601/// <STORE OP WITH DESTINATION %new_arg0>
1602/// }
1603/// }
1604/// return %a, %res
1605struct ForallOpIterArgsFolder : public OpRewritePattern<ForallOp> {
1606 using OpRewritePattern<ForallOp>::OpRewritePattern;
1607
1608 LogicalResult matchAndRewrite(ForallOp forallOp,
1609 PatternRewriter &rewriter) const final {
1610 // Step 1: For a given i-th result of scf.forall, check the following :-
1611 // a. If it has any use.
1612 // b. If the corresponding iter argument is being modified within
1613 // the loop, i.e. has at least one store op with the iter arg as
1614 // its destination operand. For this we use
1615 // ForallOp::getCombiningOps(iter_arg).
1616 //
1617 // Based on the check we maintain the following :-
1618 // a. op results, block arguments, outputs to delete
1619 // b. new outputs (i.e., outputs to retain)
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(),
1626 false);
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;
1635 blockIndicesToDelete[blockArg.getArgNumber()] = true;
1636 } else {
1637 newOuts.push_back(opOperand->get());
1638 }
1639 }
1640
1641 // Return early if all results of scf.forall have at least one use and being
1642 // modified within the loop.
1643 if (resultsToDelete.empty())
1644 return failure();
1645
1646 // Step 2: Erase combining ops and replace uses of deleted results and
1647 // block arguments with the corresponding outputs.
1648 for (auto blockArg : blockArgsToDelete) {
1649 SmallVector<Operation *> combiningOps =
1650 forallOp.getCombiningOps(blockArg);
1651 for (Operation *combiningOp : combiningOps)
1652 rewriter.eraseOp(combiningOp);
1653 }
1654 for (auto [blockArg, result, out] :
1655 llvm::zip_equal(blockArgsToDelete, resultsToDelete, outsToDelete)) {
1656 rewriter.replaceAllUsesWith(blockArg, out);
1657 rewriter.replaceAllUsesWith(result, out);
1658 }
1659 // TODO: There is no rewriter API for erasing block arguments.
1660 rewriter.modifyOpInPlace(forallOp, [&]() {
1661 forallOp.getBody()->eraseArguments(blockIndicesToDelete);
1662 });
1663
1664 // Step 3. Create a new scf.forall op with only the shared_outs/results
1665 // that should be retained.
1666 auto newForallOp = cast<scf::ForallOp>(
1667 rewriter.eraseOpResults(forallOp, resultIndicesToDelete));
1668 newForallOp.getOutputsMutable().assign(newOuts);
1669
1670 return success();
1671 }
1672};
1673
1674struct ForallOpSingleOrZeroIterationDimsFolder
1675 : public OpRewritePattern<ForallOp> {
1676 using OpRewritePattern<ForallOp>::OpRewritePattern;
1677
1678 LogicalResult matchAndRewrite(ForallOp op,
1679 PatternRewriter &rewriter) const override {
1680 // Do not fold dimensions if they are mapped to processing units.
1681 if (op.getMapping().has_value() && !op.getMapping()->empty())
1682 return failure();
1683 Location loc = op.getLoc();
1684
1685 // Compute new loop bounds that omit all single-iteration loop dimensions.
1686 SmallVector<OpFoldResult> newMixedLowerBounds, newMixedUpperBounds,
1687 newMixedSteps;
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 =
1693 constantTripCount(lb, ub, step, /*isSigned=*/true, computeUbMinusLb);
1694 if (numIterations.has_value()) {
1695 // Remove the loop if it performs zero iterations.
1696 if (*numIterations == 0) {
1697 rewriter.replaceOp(op, op.getOutputs());
1698 return success();
1699 }
1700 // Replace the loop induction variable by the lower bound if the loop
1701 // performs a single iteration. Otherwise, copy the loop bounds.
1702 if (*numIterations == 1) {
1703 singleIterationIVs.emplace_back(iv, lb);
1704 continue;
1705 }
1706 }
1707 newMixedLowerBounds.push_back(lb);
1708 newMixedUpperBounds.push_back(ub);
1709 newMixedSteps.push_back(step);
1710 }
1711
1712 // All of the loop dimensions perform a single iteration. Inline loop body.
1713 if (newMixedLowerBounds.empty())
1714 return promote(rewriter, op);
1715
1716 // Exit if none of the loop dimensions perform a single iteration.
1717 if (newMixedLowerBounds.size() == static_cast<unsigned>(op.getRank())) {
1718 return rewriter.notifyMatchFailure(
1719 op, "no dimensions have 0 or 1 iterations");
1720 }
1721
1722 // Materialize lower bounds only after all failure paths, including
1723 // promotion above, so that failed rewrites leave the IR unchanged.
1724 IRMapping mapping;
1725 for (auto [iv, lb] : singleIterationIVs)
1726 mapping.map(iv, getValueOrCreateConstantIndexOp(rewriter, loc, lb));
1727
1728 // Replace the loop by a lower-dimensional loop.
1729 ForallOp newOp;
1730 newOp = ForallOp::create(rewriter, loc, newMixedLowerBounds,
1731 newMixedUpperBounds, newMixedSteps,
1732 op.getOutputs(), std::nullopt, nullptr);
1733 rewriter.eraseBlock(newOp.getBody());
1734 newOp.setMappingAttr(op.getMappingAttr());
1735 newOp->setDiscardableAttrs(op->getDiscardableAttrDictionary());
1736 rewriter.cloneRegionBefore(op.getRegion(), newOp.getRegion(),
1737 newOp.getRegion().begin(), mapping);
1738 rewriter.replaceOp(op, newOp.getResults());
1739 return success();
1740 }
1741};
1742
1743/// Replace all induction vars with a single trip count with their lower bound.
1744struct ForallOpReplaceConstantInductionVar : public OpRewritePattern<ForallOp> {
1745 using OpRewritePattern<ForallOp>::OpRewritePattern;
1746
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())) {
1754 if (iv.hasNUses(0))
1755 continue;
1756 auto numIterations =
1757 constantTripCount(lb, ub, step, /*isSigned=*/true, computeUbMinusLb);
1758 if (!numIterations.has_value() || numIterations.value() != 1) {
1759 continue;
1760 }
1761 rewriter.replaceAllUsesWith(
1762 iv, getValueOrCreateConstantIndexOp(rewriter, loc, lb));
1763 changed = true;
1764 }
1765 return success(changed);
1766 }
1767};
1768
1769/// Replace a read of the init value of a shared_outs in the body with a read of
1770/// the tied block argument, when the read is a tensor.extract_slice of a tile
1771/// that the iteration also writes with a tensor.parallel_insert_slice. This
1772/// lets bufferization read and write the tile in place, without copying the
1773/// whole tensor.
1774///
1775/// Reads of other tiles are left alone, because other iterations may update
1776/// them in the block argument but not in the init value.
1777///
1778/// Example:
1779/// INPUT:
1780/// scf.forall (%i) ... shared_outs(%arg1 = %a) {
1781/// tensor.extract_slice %a[%i] [1]
1782/// ...
1783/// scf.forall.in_parallel {
1784/// tensor.parallel_insert_slice ... into %arg1[%i] [1]
1785/// }
1786/// }
1787///
1788/// OUTPUT:
1789/// scf.forall (%i) ... shared_outs(%arg1 = %a) {
1790/// tensor.extract_slice %arg1[%i] [1]
1791/// ...
1792/// scf.forall.in_parallel {
1793/// tensor.parallel_insert_slice ... into %arg1[%i] [1]
1794/// }
1795/// }
1796struct ForallOpReplaceInitUsesWithBlockArg : public OpRewritePattern<ForallOp> {
1797 using OpRewritePattern<ForallOp>::OpRewritePattern;
1798
1799 /// Whether `slice` is provably equivalent to one of `candidates`.
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;
1807 });
1808 }
1809
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);
1816 // The tiles of the shared_outs that the iteration writes.
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));
1823 });
1824
1825 // Whether `use` of the init reads, inside the body, one of those tiles.
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);
1831 };
1832 for (OpOperand &use : llvm::make_early_inc_range(llvm::make_filter_range(
1833 init->get().getUses(), isReadOfWrittenTile))) {
1834 // Read the block argument instead. Both are the same tensor here, and
1835 // for the block argument bufferization can tell that the tile is read
1836 // and written in place, with no copy.
1837 rewriter.modifyOpInPlace(use.getOwner(), [&] { use.set(blockArg); });
1838 changed = true;
1839 }
1840 }
1841 return success(changed);
1842 }
1843};
1844
1845struct FoldTensorCastOfOutputIntoForallOp
1846 : public OpRewritePattern<scf::ForallOp> {
1847 using OpRewritePattern<scf::ForallOp>::OpRewritePattern;
1848
1849 struct TypeCast {
1850 Type srcType;
1851 Type dstType;
1852 };
1853
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>();
1860 if (!castOp)
1861 continue;
1862
1863 // Only casts that that preserve static information, i.e. will make the
1864 // loop result type "more" static than before, will be folded.
1865 if (!tensor::preservesStaticInformation(castOp.getDest().getType(),
1866 castOp.getSource().getType())) {
1867 continue;
1868 }
1869
1870 // The parallel_insert_slice ops that write to this output will insert
1871 // into a tensor of the cast source type. Do not fold the cast if one of
1872 // them would be statically out-of-bounds: the op would not verify.
1873 auto castSrcType = cast<RankedTensorType>(castOp.getSource().getType());
1874 BlockArgument outputArg = forallOp.getRegionIterArgs()[en.index()];
1875 if (llvm::any_of(
1876 forallOp.getTerminator().getYieldingOps(), [&](Operation &op) {
1877 auto insertOp = dyn_cast<tensor::ParallelInsertSliceOp>(&op);
1878 if (!insertOp || insertOp.getDest() != outputArg)
1879 return false;
1880 return !verifyInBoundsSlice(castSrcType.getShape(),
1881 insertOp.getMixedOffsets(),
1882 insertOp.getMixedSizes(),
1883 insertOp.getMixedStrides())
1884 .isValid;
1885 })) {
1886 continue;
1887 }
1888
1889 tensorCastProducers[en.index()] =
1890 TypeCast{castOp.getSource().getType(), castOp.getType()};
1891 newOutputTensors[en.index()] = castOp.getSource();
1892 }
1893
1894 if (tensorCastProducers.empty())
1895 return failure();
1896
1897 // Create new loop.
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);
1910 }
1911
1912 // Move old body into new parallel loop.
1913 SmallVector<Value> ivsBlockArgs =
1914 llvm::to_vector(bbArgs.take_front(forallOp.getRank()));
1915 ivsBlockArgs.append(castBlockArgs);
1916 rewriter.mergeBlocks(forallOp.getBody(),
1917 bbArgs.front().getParentBlock(), ivsBlockArgs);
1918 });
1919
1920 // After `mergeBlocks` happened, the destinations in the terminator may be
1921 // mapped to tensor.cast values wrapping the new output bbArgs (introduced
1922 // for indices in `tensorCastProducers`). Update those destinations to
1923 // point directly to the output bbArgs, bypassing the casts.
1924 //
1925 // Note: we cannot zip yieldingOps with regionIterArgs by position because
1926 // a parallel_insert_slice inside in_parallel may write to any shared
1927 // output, not necessarily the one at the same position.
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)
1936 continue;
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());
1941 }
1942 }
1943
1944 // Cast results back to the original types.
1945 rewriter.setInsertionPointAfter(newForallOp);
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,
1950 oldTypeResult);
1951 }
1952 rewriter.replaceOp(forallOp, castResults);
1953 return success();
1954 }
1955};
1956
1957} // namespace
1958
1959void ForallOp::getCanonicalizationPatterns(RewritePatternSet &results,
1960 MLIRContext *context) {
1961 results.add<DimOfForallOp, FoldTensorCastOfOutputIntoForallOp,
1962 ForallOpControlOperandsFolder, ForallOpIterArgsFolder,
1963 ForallOpSingleOrZeroIterationDimsFolder,
1964 ForallOpReplaceConstantInductionVar,
1965 ForallOpReplaceInitUsesWithBlockArg>(context);
1966}
1967
1968void ForallOp::getSuccessorRegions(RegionBranchPoint point,
1969 SmallVectorImpl<RegionSuccessor> &regions) {
1970 // There are two region branch points:
1971 // 1. "parent": entering the forall op for the first time.
1972 // 2. scf.in_parallel terminator
1973 if (point.isParent()) {
1974 // When first entering the forall op, the control flow typically branches
1975 // into the forall body. (In parallel for multiple threads.)
1976 regions.push_back(RegionSuccessor(&getRegion()));
1977 // However, when there are 0 threads, the control flow may branch back to
1978 // the parent immediately.
1979 regions.push_back(RegionSuccessor(getOperation()));
1980 } else {
1981 // In accordance with the semantics of forall, its body is executed in
1982 // parallel by multiple threads. We should not expect to branch back into
1983 // the forall body after the region's execution is complete.
1984 regions.push_back(RegionSuccessor(getOperation()));
1985 }
1986}
1987
1988//===----------------------------------------------------------------------===//
1989// InParallelOp
1990//===----------------------------------------------------------------------===//
1991
1992// Build a InParallelOp with mixed static and dynamic entries.
1993void InParallelOp::build(OpBuilder &b, OperationState &result) {
1994 OpBuilder::InsertionGuard g(b);
1995 Region *bodyRegion = result.addRegion();
1996 b.createBlock(bodyRegion);
1997}
1998
1999LogicalResult InParallelOp::verify() {
2000 scf::ForallOp forallOp =
2001 dyn_cast<scf::ForallOp>(getOperation()->getParentOp());
2002 if (!forallOp)
2003 return this->emitOpError("expected forall op parent");
2004
2005 for (Operation &op : getRegion().front().getOperations()) {
2006 auto parallelCombiningOp = dyn_cast<ParallelCombiningOpInterface>(&op);
2007 if (!parallelCombiningOp) {
2008 return this->emitOpError("expected only ParallelCombiningOpInterface")
2009 << " ops";
2010 }
2011
2012 // Verify that inserts are into out block arguments.
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");
2018 }
2019 }
2020
2021 return success();
2022}
2023
2024void InParallelOp::print(OpAsmPrinter &p) {
2025 p << " ";
2026 p.printRegion(getRegion(),
2027 /*printEntryBlockArgs=*/false,
2028 /*printBlockTerminators=*/false);
2030 getOperation()->getDiscardableAttrDictionary().getValue());
2031}
2032
2033ParseResult InParallelOp::parse(OpAsmParser &parser, OperationState &result) {
2034 auto &builder = parser.getBuilder();
2035
2036 SmallVector<OpAsmParser::Argument, 8> regionOperands;
2037 std::unique_ptr<Region> region = std::make_unique<Region>();
2038 if (parser.parseRegion(*region, regionOperands))
2039 return failure();
2040
2041 if (region->empty())
2042 OpBuilder(builder.getContext()).createBlock(region.get());
2043 result.addRegion(std::move(region));
2044
2045 // Parse the optional attribute list.
2046 if (parser.parseOptionalAttrDict(result.attributes))
2047 return failure();
2048 return success();
2049}
2050
2051OpResult InParallelOp::getParentResult(int64_t idx) {
2052 return getOperation()->getParentOp()->getResult(idx);
2053}
2054
2055SmallVector<BlockArgument> InParallelOp::getDests() {
2056 SmallVector<BlockArgument> updatedDests;
2057 for (Operation &yieldingOp : getYieldingOps()) {
2058 auto parallelCombiningOp =
2059 dyn_cast<ParallelCombiningOpInterface>(&yieldingOp);
2060 if (!parallelCombiningOp)
2061 continue;
2062 for (OpOperand &updatedOperand :
2063 parallelCombiningOp.getUpdatedDestinations())
2064 updatedDests.push_back(cast<BlockArgument>(updatedOperand.get()));
2065 }
2066 return updatedDests;
2067}
2068
2069llvm::iterator_range<Block::iterator> InParallelOp::getYieldingOps() {
2070 return getRegion().front().getOperations();
2071}
2072
2073//===----------------------------------------------------------------------===//
2074// IfOp
2075//===----------------------------------------------------------------------===//
2076
2078 assert(a && "expected non-empty operation");
2079 assert(b && "expected non-empty operation");
2080
2081 IfOp ifOp = a->getParentOfType<IfOp>();
2082 while (ifOp) {
2083 // Check if b is inside ifOp. (We already know that a is.)
2084 if (ifOp->isProperAncestor(b))
2085 // b is contained in ifOp. a and b are in mutually exclusive branches if
2086 // they are in different blocks of ifOp.
2087 return static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*a)) !=
2088 static_cast<bool>(ifOp.thenBlock()->findAncestorOpInBlock(*b));
2089 // Check next enclosing IfOp.
2090 ifOp = ifOp->getParentOfType<IfOp>();
2091 }
2092
2093 // Could not find a common IfOp among a's and b's ancestors.
2094 return false;
2095}
2096
2097LogicalResult
2098IfOp::inferReturnTypes(MLIRContext *ctx, std::optional<Location> loc,
2099 IfOp::Adaptor adaptor,
2100 SmallVectorImpl<Type> &inferredReturnTypes) {
2101 if (adaptor.getRegions().empty())
2102 return failure();
2103 Region *r = &adaptor.getThenRegion();
2104 if (r->empty())
2105 return failure();
2106 Block &b = r->front();
2107 if (b.empty())
2108 return failure();
2109 auto yieldOp = llvm::dyn_cast<YieldOp>(b.back());
2110 if (!yieldOp)
2111 return failure();
2112 TypeRange types = yieldOp.getOperandTypes();
2113 llvm::append_range(inferredReturnTypes, types);
2114 return success();
2115}
2116
2117void IfOp::build(OpBuilder &builder, OperationState &result,
2118 TypeRange resultTypes, Value cond) {
2119 return build(builder, result, resultTypes, cond, /*addThenBlock=*/false,
2120 /*addElseBlock=*/false);
2121}
2122
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);
2130
2131 // Add regions and blocks.
2132 OpBuilder::InsertionGuard guard(builder);
2133 Region *thenRegion = result.addRegion();
2134 if (addThenBlock)
2135 builder.createBlock(thenRegion);
2136 Region *elseRegion = result.addRegion();
2137 if (addElseBlock)
2138 builder.createBlock(elseRegion);
2139}
2140
2141void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
2142 bool withElseRegion) {
2143 build(builder, result, TypeRange{}, cond, withElseRegion);
2144}
2145
2146void IfOp::build(OpBuilder &builder, OperationState &result,
2147 TypeRange resultTypes, Value cond, bool withElseRegion) {
2148 result.addTypes(resultTypes);
2149 result.addOperands(cond);
2150
2151 // Build then region.
2152 OpBuilder::InsertionGuard guard(builder);
2153 Region *thenRegion = result.addRegion();
2154 builder.createBlock(thenRegion);
2155 if (resultTypes.empty())
2156 IfOp::ensureTerminator(*thenRegion, builder, result.location);
2157
2158 // Build else region.
2159 Region *elseRegion = result.addRegion();
2160 if (withElseRegion) {
2161 builder.createBlock(elseRegion);
2162 if (resultTypes.empty())
2163 IfOp::ensureTerminator(*elseRegion, builder, result.location);
2164 }
2165}
2166
2167void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
2168 function_ref<void(OpBuilder &, Location)> thenBuilder,
2169 function_ref<void(OpBuilder &, Location)> elseBuilder) {
2170 assert(thenBuilder && "the builder callback for 'then' must be present");
2171 result.addOperands(cond);
2172
2173 // Build then region.
2174 OpBuilder::InsertionGuard guard(builder);
2175 Region *thenRegion = result.addRegion();
2176 builder.createBlock(thenRegion);
2177 thenBuilder(builder, result.location);
2178
2179 // Build else region.
2180 Region *elseRegion = result.addRegion();
2181 if (elseBuilder) {
2182 builder.createBlock(elseRegion);
2183 elseBuilder(builder, result.location);
2184 }
2185
2186 // Infer result types.
2187 SmallVector<Type> inferredReturnTypes;
2188 MLIRContext *ctx = builder.getContext();
2189 auto attrDict = DictionaryAttr::get(ctx, result.attributes);
2190 if (succeeded(inferReturnTypes(ctx, std::nullopt, result.operands, attrDict,
2191 /*properties=*/PropertyRef{}, result.regions,
2192 inferredReturnTypes))) {
2193 result.addTypes(inferredReturnTypes);
2194 }
2195}
2196
2197LogicalResult IfOp::verify() {
2198 if (getNumResults() != 0 && getElseRegion().empty())
2199 return emitOpError("must have an else block if defining values");
2200 return success();
2201}
2202
2203ParseResult IfOp::parse(OpAsmParser &parser, OperationState &result) {
2204 // Create the regions for 'then'.
2205 result.regions.reserve(2);
2206 Region *thenRegion = result.addRegion();
2207 Region *elseRegion = result.addRegion();
2208
2209 auto &builder = parser.getBuilder();
2210 OpAsmParser::UnresolvedOperand cond;
2211 Type i1Type = builder.getIntegerType(1);
2212 if (parser.parseOperand(cond) ||
2213 parser.resolveOperand(cond, i1Type, result.operands))
2214 return failure();
2215 // Parse optional results type list.
2216 if (parser.parseOptionalArrowTypeList(result.types))
2217 return failure();
2218 // Parse the 'then' region.
2219 if (parser.parseRegion(*thenRegion, /*arguments=*/{}, /*argTypes=*/{}))
2220 return failure();
2221 IfOp::ensureTerminator(*thenRegion, parser.getBuilder(), result.location);
2222
2223 // If we find an 'else' keyword then parse the 'else' region.
2224 if (!parser.parseOptionalKeyword("else")) {
2225 if (parser.parseRegion(*elseRegion, /*arguments=*/{}, /*argTypes=*/{}))
2226 return failure();
2227 IfOp::ensureTerminator(*elseRegion, parser.getBuilder(), result.location);
2228 }
2229
2230 // Parse the optional attribute list.
2231 if (parser.parseOptionalAttrDict(result.attributes))
2232 return failure();
2233 return success();
2234}
2235
2236void IfOp::print(OpAsmPrinter &p) {
2237 bool printBlockTerminators = false;
2238
2239 p << " " << getCondition();
2240 if (!getResults().empty()) {
2241 p << " -> (" << getResultTypes() << ")";
2242 // Print yield explicitly if the op defines values.
2243 printBlockTerminators = true;
2244 }
2245 p << ' ';
2246 p.printRegion(getThenRegion(),
2247 /*printEntryBlockArgs=*/false,
2248 /*printBlockTerminators=*/printBlockTerminators);
2249
2250 // Print the 'else' regions if it exists and has a block.
2251 auto &elseRegion = getElseRegion();
2252 if (!elseRegion.empty()) {
2253 p << " else ";
2254 p.printRegion(elseRegion,
2255 /*printEntryBlockArgs=*/false,
2256 /*printBlockTerminators=*/printBlockTerminators);
2257 }
2258
2259 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
2260}
2261
2262void IfOp::getSuccessorRegions(RegionBranchPoint point,
2263 SmallVectorImpl<RegionSuccessor> &regions) {
2264 // The `then` and the `else` region branch back to the parent operation or one
2265 // of the recursive parent operations (early exit case).
2266 if (!point.isParent()) {
2267 regions.push_back(RegionSuccessor(getOperation()));
2268 return;
2269 }
2270
2271 regions.push_back(RegionSuccessor(&getThenRegion()));
2272
2273 // Don't consider the else region if it is empty.
2274 Region *elseRegion = &this->getElseRegion();
2275 if (elseRegion->empty())
2276 regions.push_back(RegionSuccessor(getOperation()));
2277 else
2278 regions.push_back(RegionSuccessor(elseRegion));
2279}
2280
2281ValueRange IfOp::getSuccessorInputs(RegionSuccessor successor) {
2282 return successor.isOperation() ? ValueRange(getOperation()->getResults())
2283 : ValueRange();
2284}
2285
2286void IfOp::getEntrySuccessorRegions(ArrayRef<Attribute> operands,
2287 SmallVectorImpl<RegionSuccessor> &regions) {
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());
2292
2293 // If the else region is empty, execution continues after the parent op.
2294 if (!boolAttr || !boolAttr.getValue()) {
2295 if (!getElseRegion().empty())
2296 regions.emplace_back(&getElseRegion());
2297 else
2298 regions.emplace_back(RegionSuccessor(getOperation()));
2299 }
2300}
2301
2302LogicalResult IfOp::fold(FoldAdaptor adaptor,
2303 SmallVectorImpl<OpFoldResult> &results) {
2304 // if (!c) then A() else B() -> if c then B() else A()
2305 if (getElseRegion().empty())
2306 return failure();
2307
2308 arith::XOrIOp xorStmt = getCondition().getDefiningOp<arith::XOrIOp>();
2309 if (!xorStmt)
2310 return failure();
2311
2312 if (!matchPattern(xorStmt.getRhs(), m_One()))
2313 return failure();
2314
2315 getConditionMutable().assign(xorStmt.getLhs());
2316 Block *thenBlock = &getThenRegion().front();
2317 // It would be nicer to use iplist::swap, but that has no implemented
2318 // callbacks See: https://llvm.org/doxygen/ilist_8h_source.html#l00224
2319 getThenRegion().getBlocks().splice(getThenRegion().getBlocks().begin(),
2320 getElseRegion().getBlocks());
2321 getElseRegion().getBlocks().splice(getElseRegion().getBlocks().begin(),
2322 getThenRegion().getBlocks(), thenBlock);
2323 return success();
2324}
2325
2326void IfOp::getRegionInvocationBounds(
2327 ArrayRef<Attribute> operands,
2328 SmallVectorImpl<InvocationBounds> &invocationBounds) {
2329 if (auto cond = llvm::dyn_cast_or_null<BoolAttr>(operands[0])) {
2330 // If the condition is known, then one region is known to be executed once
2331 // and the other zero times.
2332 invocationBounds.emplace_back(0, cond.getValue() ? 1 : 0);
2333 invocationBounds.emplace_back(0, cond.getValue() ? 0 : 1);
2334 } else {
2335 // Non-constant condition. Each region may be executed 0 or 1 times.
2336 invocationBounds.assign(2, {0, 1});
2337 }
2338}
2339
2340namespace {
2341/// Hoist any yielded results whose operands are defined outside
2342/// the if, to a select instruction.
2343struct ConvertTrivialIfToSelect : public OpRewritePattern<IfOp> {
2344 using OpRewritePattern<IfOp>::OpRewritePattern;
2345
2346 LogicalResult matchAndRewrite(IfOp op,
2347 PatternRewriter &rewriter) const override {
2348 if (op->getNumResults() == 0)
2349 return failure();
2350
2351 auto cond = op.getCondition();
2352 auto thenYieldArgs = op.thenYield().getOperands();
2353 auto elseYieldArgs = op.elseYield().getOperands();
2354
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());
2360 }
2361 // Early exit if there aren't any yielded values we can
2362 // hoist outside the if.
2363 if (nonHoistable.size() == op->getNumResults())
2364 return failure();
2365
2366 IfOp replacement = IfOp::create(rewriter, op.getLoc(), nonHoistable, cond,
2367 /*withElseRegion=*/false);
2368 if (replacement.thenBlock())
2369 rewriter.eraseBlock(replacement.thenBlock());
2370 replacement.getThenRegion().takeBody(op.getThenRegion());
2371 replacement.getElseRegion().takeBody(op.getElseRegion());
2372
2373 SmallVector<Value> results(op->getNumResults());
2374 assert(thenYieldArgs.size() == results.size());
2375 assert(elseYieldArgs.size() == results.size());
2376
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());
2384 if (&replacement.getThenRegion() == trueVal.getParentRegion() ||
2385 &replacement.getElseRegion() == falseVal.getParentRegion()) {
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;
2391 else
2392 results[it.index()] = arith::SelectOp::create(rewriter, op.getLoc(),
2393 cond, trueVal, falseVal);
2394 }
2395
2396 rewriter.setInsertionPointToEnd(replacement.thenBlock());
2397 rewriter.replaceOpWithNewOp<YieldOp>(replacement.thenYield(), trueYields);
2398
2399 rewriter.setInsertionPointToEnd(replacement.elseBlock());
2400 rewriter.replaceOpWithNewOp<YieldOp>(replacement.elseYield(), falseYields);
2401
2402 rewriter.replaceOp(op, results);
2403 return success();
2404 }
2405};
2406
2407/// Allow the true region of an if to assume the condition is true
2408/// and vice versa. For example:
2409///
2410/// scf.if %cmp {
2411/// print(%cmp)
2412/// }
2413///
2414/// becomes
2415///
2416/// scf.if %cmp {
2417/// print(true)
2418/// }
2419///
2420struct ConditionPropagation : public OpRewritePattern<IfOp> {
2421 using OpRewritePattern<IfOp>::OpRewritePattern;
2422
2423 /// Kind of parent region in the ancestor cache.
2424 enum class Parent { Then, Else, None };
2425
2426 /// Returns the kind of region ("then", "else", or "none") of the
2427 /// IfOp that the given region is transitively nested in. Updates
2428 /// the cache accordingly.
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;
2442 }
2443 if (&op.getElseRegion() == toCheck) {
2444 for (Region *region : seen)
2445 cache[region] = Parent::Else;
2446 return Parent::Else;
2447 }
2448 toCheck = toCheck->getParentRegion();
2449 }
2450
2451 for (Region *region : seen)
2452 cache[region] = Parent::None;
2453 return Parent::None;
2454 }
2455
2456 LogicalResult matchAndRewrite(IfOp op,
2457 PatternRewriter &rewriter) const override {
2458 // Early exit if the condition is constant since replacing a constant
2459 // in the body with another constant isn't a simplification.
2460 if (matchPattern(op.getCondition(), m_Constant()))
2461 return failure();
2462
2463 bool changed = false;
2464 mlir::Type i1Ty = rewriter.getI1Type();
2465
2466 // These variables serve to prevent creating duplicate constants
2467 // and hold constant true or false values.
2468 Value constantTrue = nullptr;
2469 Value constantFalse = nullptr;
2470
2472 for (OpOperand &use :
2473 llvm::make_early_inc_range(op.getCondition().getUses())) {
2474 switch (getParentType(use.getOwner()->getParentRegion(), op, cache,
2475 op.getCondition().getParentRegion())) {
2476 case Parent::Then: {
2477 changed = true;
2478
2479 if (!constantTrue)
2480 constantTrue = arith::ConstantOp::create(
2481 rewriter, op.getLoc(), i1Ty, rewriter.getIntegerAttr(i1Ty, 1));
2482
2483 rewriter.modifyOpInPlace(use.getOwner(),
2484 [&]() { use.set(constantTrue); });
2485 break;
2486 }
2487 case Parent::Else: {
2488 changed = true;
2489
2490 if (!constantFalse)
2491 constantFalse = arith::ConstantOp::create(
2492 rewriter, op.getLoc(), i1Ty, rewriter.getIntegerAttr(i1Ty, 0));
2493
2494 rewriter.modifyOpInPlace(use.getOwner(),
2495 [&]() { use.set(constantFalse); });
2496 break;
2497 }
2498 case Parent::None: {
2499 auto selectOp = dyn_cast<arith::SelectOp>(use.getOwner());
2500 if (!selectOp || use.getOperandNumber() != 0)
2501 break;
2502
2503 // Refine captured select results only at uses in the matching branch.
2504 // Uses outside the if must retain the select result.
2505 changed |= rewriter.replaceUsesWithIf(
2506 selectOp.getResult(), selectOp.getTrueValue(),
2507 [&](OpOperand &selectUse) {
2508 return getParentType(
2509 selectUse.getOwner()->getParentRegion(), op, cache,
2510 op.getCondition().getParentRegion()) == Parent::Then;
2511 });
2512 changed |= rewriter.replaceUsesWithIf(
2513 selectOp.getResult(), selectOp.getFalseValue(),
2514 [&](OpOperand &selectUse) {
2515 return getParentType(
2516 selectUse.getOwner()->getParentRegion(), op, cache,
2517 op.getCondition().getParentRegion()) == Parent::Else;
2518 });
2519 break;
2520 }
2521 }
2522 }
2523
2524 return success(changed);
2525 }
2526};
2527
2528/// Remove any statements from an if that are equivalent to the condition
2529/// or its negation. For example:
2530///
2531/// %res:2 = scf.if %cmp {
2532/// yield something(), true
2533/// } else {
2534/// yield something2(), false
2535/// }
2536/// print(%res#1)
2537///
2538/// becomes
2539/// %res = scf.if %cmp {
2540/// yield something()
2541/// } else {
2542/// yield something2()
2543/// }
2544/// print(%cmp)
2545///
2546/// Additionally if both branches yield the same value, replace all uses
2547/// of the result with the yielded value.
2548///
2549/// %res:2 = scf.if %cmp {
2550/// yield something(), %arg1
2551/// } else {
2552/// yield something2(), %arg1
2553/// }
2554/// print(%res#1)
2555///
2556/// becomes
2557/// %res = scf.if %cmp {
2558/// yield something()
2559/// } else {
2560/// yield something2()
2561/// }
2562/// print(%arg1)
2563///
2564struct ReplaceIfYieldWithConditionOrValue : public OpRewritePattern<IfOp> {
2565 using OpRewritePattern<IfOp>::OpRewritePattern;
2566
2567 LogicalResult matchAndRewrite(IfOp op,
2568 PatternRewriter &rewriter) const override {
2569 // Early exit if there are no results that could be replaced.
2570 if (op.getNumResults() == 0)
2571 return failure();
2572
2573 auto trueYield =
2574 cast<scf::YieldOp>(op.getThenRegion().back().getTerminator());
2575 auto falseYield =
2576 cast<scf::YieldOp>(op.getElseRegion().back().getTerminator());
2577
2578 rewriter.setInsertionPoint(op->getBlock(),
2579 op.getOperation()->getIterator());
2580 bool changed = false;
2581 Type i1Ty = rewriter.getI1Type();
2582 for (auto [trueResult, falseResult, opResult] :
2583 llvm::zip(trueYield.getResults(), falseYield.getResults(),
2584 op.getResults())) {
2585 if (trueResult == falseResult) {
2586 if (!opResult.use_empty()) {
2587 opResult.replaceAllUsesWith(trueResult);
2588 changed = true;
2589 }
2590 continue;
2591 }
2592
2593 BoolAttr trueYield, falseYield;
2594 if (!matchPattern(trueResult, m_Constant(&trueYield)) ||
2595 !matchPattern(falseResult, m_Constant(&falseYield)))
2596 continue;
2597
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(),
2605 constDialect
2606 ->materializeConstant(rewriter,
2607 rewriter.getIntegerAttr(i1Ty, 1), i1Ty,
2608 op.getLoc())
2609 ->getResult(0));
2610 opResult.replaceAllUsesWith(notCond);
2611 changed = true;
2612 }
2613 }
2614 if (trueVal && !falseVal) {
2615 if (!opResult.use_empty()) {
2616 opResult.replaceAllUsesWith(op.getCondition());
2617 changed = true;
2618 }
2619 }
2620 }
2621 return success(changed);
2622 }
2623};
2624
2625/// Merge any consecutive scf.if's with the same condition.
2626///
2627/// scf.if %cond {
2628/// firstCodeTrue();...
2629/// } else {
2630/// firstCodeFalse();...
2631/// }
2632/// %res = scf.if %cond {
2633/// secondCodeTrue();...
2634/// } else {
2635/// secondCodeFalse();...
2636/// }
2637///
2638/// becomes
2639/// %res = scf.if %cmp {
2640/// firstCodeTrue();...
2641/// secondCodeTrue();...
2642/// } else {
2643/// firstCodeFalse();...
2644/// secondCodeFalse();...
2645/// }
2646struct CombineIfs : public OpRewritePattern<IfOp> {
2647 using OpRewritePattern<IfOp>::OpRewritePattern;
2648
2649 LogicalResult matchAndRewrite(IfOp nextIf,
2650 PatternRewriter &rewriter) const override {
2651 Block *parent = nextIf->getBlock();
2652 if (nextIf == &parent->front())
2653 return failure();
2654
2655 auto prevIf = dyn_cast<IfOp>(nextIf->getPrevNode());
2656 if (!prevIf)
2657 return failure();
2658
2659 // Determine the logical then/else blocks when prevIf's
2660 // condition is used. Null means the block does not exist
2661 // in that case (e.g. empty else). If neither of these
2662 // are set, the two conditions cannot be compared.
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();
2669 }
2670 if (arith::XOrIOp notv =
2671 nextIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
2672 if (notv.getLhs() == prevIf.getCondition() &&
2673 matchPattern(notv.getRhs(), m_One())) {
2674 nextElse = nextIf.thenBlock();
2675 if (!nextIf.getElseRegion().empty())
2676 nextThen = nextIf.elseBlock();
2677 }
2678 }
2679 if (arith::XOrIOp notv =
2680 prevIf.getCondition().getDefiningOp<arith::XOrIOp>()) {
2681 if (notv.getLhs() == nextIf.getCondition() &&
2682 matchPattern(notv.getRhs(), m_One())) {
2683 nextElse = nextIf.thenBlock();
2684 if (!nextIf.getElseRegion().empty())
2685 nextThen = nextIf.elseBlock();
2686 }
2687 }
2688
2689 if (!nextThen && !nextElse)
2690 return failure();
2691
2692 SmallVector<Value> prevElseYielded;
2693 if (!prevIf.getElseRegion().empty())
2694 prevElseYielded = prevIf.elseYield().getOperands();
2695 // Replace all uses of return values of op within nextIf with the
2696 // corresponding yields
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())) {
2701 if (nextThen && nextThen->getParent()->isAncestor(
2702 use.getOwner()->getParentRegion())) {
2703 rewriter.startOpModification(use.getOwner());
2704 use.set(std::get<1>(it));
2705 rewriter.finalizeOpModification(use.getOwner());
2706 } else if (nextElse && nextElse->getParent()->isAncestor(
2707 use.getOwner()->getParentRegion())) {
2708 rewriter.startOpModification(use.getOwner());
2709 use.set(std::get<2>(it));
2710 rewriter.finalizeOpModification(use.getOwner());
2711 }
2712 }
2713
2714 SmallVector<Type> mergedTypes(prevIf.getResultTypes());
2715 llvm::append_range(mergedTypes, nextIf.getResultTypes());
2716
2717 IfOp combinedIf = IfOp::create(rewriter, nextIf.getLoc(), mergedTypes,
2718 prevIf.getCondition(), /*hasElse=*/false);
2719 rewriter.eraseBlock(&combinedIf.getThenRegion().back());
2720
2721 rewriter.inlineRegionBefore(prevIf.getThenRegion(),
2722 combinedIf.getThenRegion(),
2723 combinedIf.getThenRegion().begin());
2724
2725 if (nextThen) {
2726 YieldOp thenYield = combinedIf.thenYield();
2727 YieldOp thenYield2 = cast<YieldOp>(nextThen->getTerminator());
2728 rewriter.mergeBlocks(nextThen, combinedIf.thenBlock());
2729 rewriter.setInsertionPointToEnd(combinedIf.thenBlock());
2730
2731 SmallVector<Value> mergedYields(thenYield.getOperands());
2732 llvm::append_range(mergedYields, thenYield2.getOperands());
2733 YieldOp::create(rewriter, thenYield2.getLoc(), mergedYields);
2734 rewriter.eraseOp(thenYield);
2735 rewriter.eraseOp(thenYield2);
2736 }
2737
2738 rewriter.inlineRegionBefore(prevIf.getElseRegion(),
2739 combinedIf.getElseRegion(),
2740 combinedIf.getElseRegion().begin());
2741
2742 if (nextElse) {
2743 if (combinedIf.getElseRegion().empty()) {
2744 rewriter.inlineRegionBefore(*nextElse->getParent(),
2745 combinedIf.getElseRegion(),
2746 combinedIf.getElseRegion().begin());
2747 } else {
2748 YieldOp elseYield = combinedIf.elseYield();
2749 YieldOp elseYield2 = cast<YieldOp>(nextElse->getTerminator());
2750 rewriter.mergeBlocks(nextElse, combinedIf.elseBlock());
2751
2752 rewriter.setInsertionPointToEnd(combinedIf.elseBlock());
2753
2754 SmallVector<Value> mergedElseYields(elseYield.getOperands());
2755 llvm::append_range(mergedElseYields, elseYield2.getOperands());
2756
2757 YieldOp::create(rewriter, elseYield2.getLoc(), mergedElseYields);
2758 rewriter.eraseOp(elseYield);
2759 rewriter.eraseOp(elseYield2);
2760 }
2761 }
2762
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());
2768 else
2769 nextValues.push_back(pair.value());
2770 }
2771 rewriter.replaceOp(prevIf, prevValues);
2772 rewriter.replaceOp(nextIf, nextValues);
2773 return success();
2774 }
2775};
2776
2777/// Pattern to remove an empty else branch.
2778struct RemoveEmptyElseBranch : public OpRewritePattern<IfOp> {
2779 using OpRewritePattern<IfOp>::OpRewritePattern;
2780
2781 LogicalResult matchAndRewrite(IfOp ifOp,
2782 PatternRewriter &rewriter) const override {
2783 // Cannot remove else region when there are operation results.
2784 if (ifOp.getNumResults())
2785 return failure();
2786 Block *elseBlock = ifOp.elseBlock();
2787 if (!elseBlock || !llvm::hasSingleElement(*elseBlock))
2788 return failure();
2789 auto newIfOp = rewriter.cloneWithoutRegions(ifOp);
2790 rewriter.inlineRegionBefore(ifOp.getThenRegion(), newIfOp.getThenRegion(),
2791 newIfOp.getThenRegion().begin());
2792 rewriter.eraseOp(ifOp);
2793 return success();
2794 }
2795};
2796
2797/// Convert nested `if`s into `arith.andi` + single `if`.
2798///
2799/// scf.if %arg0 {
2800/// scf.if %arg1 {
2801/// ...
2802/// scf.yield
2803/// }
2804/// scf.yield
2805/// }
2806/// becomes
2807///
2808/// %0 = arith.andi %arg0, %arg1
2809/// scf.if %0 {
2810/// ...
2811/// scf.yield
2812/// }
2813struct CombineNestedIfs : public OpRewritePattern<IfOp> {
2814 using OpRewritePattern<IfOp>::OpRewritePattern;
2815
2816 LogicalResult matchAndRewrite(IfOp op,
2817 PatternRewriter &rewriter) const override {
2818 auto nestedOps = op.thenBlock()->without_terminator();
2819 // Nested `if` must be the only op in block.
2820 if (!llvm::hasSingleElement(nestedOps))
2821 return failure();
2822
2823 // If there is an else block, it can only yield
2824 if (op.elseBlock() && !llvm::hasSingleElement(*op.elseBlock()))
2825 return failure();
2826
2827 auto nestedIf = dyn_cast<IfOp>(*nestedOps.begin());
2828 if (!nestedIf)
2829 return failure();
2830
2831 if (nestedIf.elseBlock() && !llvm::hasSingleElement(*nestedIf.elseBlock()))
2832 return failure();
2833
2834 SmallVector<Value> thenYield(op.thenYield().getOperands());
2835 SmallVector<Value> elseYield;
2836 if (op.elseBlock())
2837 llvm::append_range(elseYield, op.elseYield().getOperands());
2838
2839 // A list of indices for which we should upgrade the value yielded
2840 // in the else to a select.
2841 SmallVector<unsigned> elseYieldsToUpgradeToSelect;
2842
2843 // If the outer scf.if yields a value produced by the inner scf.if,
2844 // only permit combining if the value yielded when the condition
2845 // is false in the outer scf.if is the same value yielded when the
2846 // inner scf.if condition is false.
2847 // Note that the array access to elseYield will not go out of bounds
2848 // since it must have the same length as thenYield, since they both
2849 // come from the same scf.if.
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()]) {
2855 return failure();
2856 }
2857 // If the correctness test passes, we will yield
2858 // corresponding value from the inner scf.if
2859 thenYield[tup.index()] = nestedIf.thenYield().getOperand(nestedIdx);
2860 continue;
2861 }
2862
2863 // Otherwise, we need to ensure the else block of the combined
2864 // condition still returns the same value when the outer condition is
2865 // true and the inner condition is false. This can be accomplished if
2866 // the then value is defined outside the outer scf.if and we replace the
2867 // value with a select that considers just the outer condition. Since
2868 // the else region contains just the yield, its yielded value is
2869 // defined outside the scf.if, by definition.
2870
2871 // If the then value is defined within the scf.if, bail.
2872 if (tup.value().getParentRegion() == &op.getThenRegion()) {
2873 return failure();
2874 }
2875 elseYieldsToUpgradeToSelect.push_back(tup.index());
2876 }
2877
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);
2882 Block *newIfBlock = rewriter.createBlock(&newIf.getThenRegion());
2883
2884 SmallVector<Value> results;
2885 llvm::append_range(results, newIf.getResults());
2886 rewriter.setInsertionPoint(newIf);
2887
2888 for (auto idx : elseYieldsToUpgradeToSelect)
2889 results[idx] =
2890 arith::SelectOp::create(rewriter, op.getLoc(), op.getCondition(),
2891 thenYield[idx], elseYield[idx]);
2892
2893 rewriter.mergeBlocks(nestedIf.thenBlock(), newIfBlock);
2894 rewriter.setInsertionPointToEnd(newIf.thenBlock());
2895 rewriter.replaceOpWithNewOp<YieldOp>(newIf.thenYield(), thenYield);
2896 if (!elseYield.empty()) {
2897 rewriter.createBlock(&newIf.getElseRegion());
2898 rewriter.setInsertionPointToEnd(newIf.elseBlock());
2899 YieldOp::create(rewriter, loc, elseYield);
2900 }
2901 rewriter.replaceOp(op, results);
2902 return success();
2903 }
2904};
2905
2906} // namespace
2907
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());
2917}
2918
2919Block *IfOp::thenBlock() { return &getThenRegion().back(); }
2920YieldOp IfOp::thenYield() { return cast<YieldOp>(&thenBlock()->back()); }
2921Block *IfOp::elseBlock() {
2922 Region &r = getElseRegion();
2923 if (r.empty())
2924 return nullptr;
2925 return &r.back();
2926}
2927YieldOp IfOp::elseYield() { return cast<YieldOp>(&elseBlock()->back()); }
2928
2929//===----------------------------------------------------------------------===//
2930// ParallelOp
2931//===----------------------------------------------------------------------===//
2932
2933void ParallelOp::build(
2934 OpBuilder &builder, OperationState &result, ValueRange lowerBounds,
2935 ValueRange upperBounds, ValueRange steps, ValueRange initVals,
2936 function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)>
2937 bodyBuilderFn,
2938 bool unsignedCmp) {
2939 result.addOperands(lowerBounds);
2940 result.addOperands(upperBounds);
2941 result.addOperands(steps);
2942 result.addOperands(initVals);
2943 if (unsignedCmp)
2944 result.addAttribute(getUnsignedCmpAttrName(result.name),
2945 builder.getUnitAttr());
2946 result.addAttribute(
2947 ParallelOp::getOperandSegmentSizeAttr(),
2948 builder.getDenseI32ArrayAttr({static_cast<int32_t>(lowerBounds.size()),
2949 static_cast<int32_t>(upperBounds.size()),
2950 static_cast<int32_t>(steps.size()),
2951 static_cast<int32_t>(initVals.size())}));
2952 result.addTypes(initVals.getTypes());
2953
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();
2959 Block *bodyBlock = builder.createBlock(bodyRegion, {}, argTypes, argLocs);
2960
2961 if (bodyBuilderFn) {
2962 builder.setInsertionPointToStart(bodyBlock);
2963 bodyBuilderFn(builder, result.location,
2964 bodyBlock->getArguments().take_front(numIVs),
2965 bodyBlock->getArguments().drop_front(numIVs));
2966 }
2967 // Add terminator only if there are no reductions.
2968 if (initVals.empty())
2969 ParallelOp::ensureTerminator(*bodyRegion, builder, result.location);
2970}
2971
2972void ParallelOp::build(
2973 OpBuilder &builder, OperationState &result, ValueRange lowerBounds,
2974 ValueRange upperBounds, ValueRange steps,
2975 function_ref<void(OpBuilder &, Location, ValueRange)> bodyBuilderFn,
2976 bool unsignedCmp) {
2977 // Only pass a non-null wrapper if bodyBuilderFn is non-null itself. Make sure
2978 // we don't capture a reference to a temporary by constructing the lambda at
2979 // function level.
2980 auto wrappedBuilderFn = [&bodyBuilderFn](OpBuilder &nestedBuilder,
2981 Location nestedLoc, ValueRange ivs,
2982 ValueRange) {
2983 bodyBuilderFn(nestedBuilder, nestedLoc, ivs);
2984 };
2985 function_ref<void(OpBuilder &, Location, ValueRange, ValueRange)> wrapper;
2986 if (bodyBuilderFn)
2987 wrapper = wrappedBuilderFn;
2988
2989 build(builder, result, lowerBounds, upperBounds, steps, ValueRange(), wrapper,
2990 unsignedCmp);
2991}
2992
2993LogicalResult ParallelOp::verify() {
2994 // Check that there is at least one value in lowerBound, upperBound and step.
2995 // It is sufficient to test only step, because it is ensured already that the
2996 // number of elements in lowerBound, upperBound and step are the same.
2997 Operation::operand_range stepValues = getStep();
2998 if (stepValues.empty())
2999 return emitOpError(
3000 "needs at least one tuple element for lowerBound, upperBound and step");
3001
3002 // Check whether all constant step values are positive.
3003 for (Value stepValue : stepValues)
3004 if (auto cst = getConstantIntValue(stepValue))
3005 if (*cst <= 0)
3006 return emitOpError("constant step operand must be positive");
3007
3008 // Check that the body defines the same number of block arguments as the
3009 // number of tuple elements in step.
3010 Block *body = getBody();
3011 if (body->getNumArguments() != stepValues.size())
3012 return emitOpError() << "expects the same number of induction variables: "
3013 << body->getNumArguments()
3014 << " as bound and step values: " << stepValues.size();
3015 for (auto arg : body->getArguments())
3016 if (!arg.getType().isIndex())
3017 return emitOpError(
3018 "expects arguments for the induction variable to be of index type");
3019
3020 // Check that the terminator is an scf.reduce op.
3022 *this, getRegion(), "expects body to terminate with 'scf.reduce'");
3023 if (!reduceOp)
3024 return failure();
3025
3026 // Check that the number of results is the same as the number of reductions.
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: "
3033 << reductionsSize;
3034 if (resultsSize != initValsSize)
3035 return emitOpError() << "expects number of results: " << resultsSize
3036 << " to be the same as number of initial values: "
3037 << initValsSize;
3038 if (reduceOp.getNumOperands() != initValsSize)
3039 // Delegate error reporting to ReduceOp
3040 return success();
3041
3042 // Check that the types of the results and reductions are the same.
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;
3052 }
3053 return success();
3054}
3055
3056ParseResult ParallelOp::parse(OpAsmParser &parser, OperationState &result) {
3057 auto &builder = parser.getBuilder();
3058 if (succeeded(parser.parseOptionalKeyword("unsigned")))
3059 result.addAttribute(getUnsignedCmpAttrName(result.name),
3060 builder.getUnitAttr());
3061
3062 // Parse an opening `(` followed by induction variables followed by `)`
3063 SmallVector<OpAsmParser::Argument, 4> ivs;
3065 return failure();
3066
3067 // Parse loop bounds.
3068 SmallVector<OpAsmParser::UnresolvedOperand, 4> lower;
3069 if (parser.parseEqual() ||
3070 parser.parseOperandList(lower, ivs.size(),
3072 parser.resolveOperands(lower, builder.getIndexType(), result.operands))
3073 return failure();
3074
3075 SmallVector<OpAsmParser::UnresolvedOperand, 4> upper;
3076 if (parser.parseKeyword("to") ||
3077 parser.parseOperandList(upper, ivs.size(),
3079 parser.resolveOperands(upper, builder.getIndexType(), result.operands))
3080 return failure();
3081
3082 // Parse step values.
3083 SmallVector<OpAsmParser::UnresolvedOperand, 4> steps;
3084 if (parser.parseKeyword("step") ||
3085 parser.parseOperandList(steps, ivs.size(),
3087 parser.resolveOperands(steps, builder.getIndexType(), result.operands))
3088 return failure();
3089
3090 // Parse init values.
3091 SmallVector<OpAsmParser::UnresolvedOperand, 4> initVals;
3092 if (succeeded(parser.parseOptionalKeyword("init"))) {
3093 if (parser.parseOperandList(initVals, OpAsmParser::Delimiter::Paren))
3094 return failure();
3095 }
3096
3097 // Parse optional results in case there is a reduce.
3098 if (parser.parseOptionalArrowTypeList(result.types))
3099 return failure();
3100
3101 // Now parse the body.
3102 Region *body = result.addRegion();
3103 for (auto &iv : ivs)
3104 iv.type = builder.getIndexType();
3105 if (parser.parseRegion(*body, ivs))
3106 return failure();
3107
3108 // Set `operandSegmentSizes` attribute.
3109 result.addAttribute(
3110 ParallelOp::getOperandSegmentSizeAttr(),
3111 builder.getDenseI32ArrayAttr({static_cast<int32_t>(lower.size()),
3112 static_cast<int32_t>(upper.size()),
3113 static_cast<int32_t>(steps.size()),
3114 static_cast<int32_t>(initVals.size())}));
3115
3116 // Parse attributes.
3117 if (parser.parseOptionalAttrDict(result.attributes) ||
3118 parser.resolveOperands(initVals, result.types, parser.getNameLoc(),
3119 result.operands))
3120 return failure();
3121
3122 // Add a terminator if none was parsed.
3123 ParallelOp::ensureTerminator(*body, builder, result.location);
3124 return success();
3125}
3126
3127void ParallelOp::print(OpAsmPrinter &p) {
3128 if (getUnsignedCmp())
3129 p << " unsigned";
3130 p << " (" << getBody()->getArguments() << ") = (" << getLowerBound()
3131 << ") to (" << getUpperBound() << ") step (" << getStep() << ")";
3132 if (!getInitVals().empty())
3133 p << " init (" << getInitVals() << ")";
3134 p.printOptionalArrowTypeList(getResultTypes());
3135 p << ' ';
3136 p.printRegion(getRegion(), /*printEntryBlockArgs=*/false);
3137 p.printOptionalAttrDict((*this)->getDiscardableAttrDictionary().getValue());
3138}
3139
3140SmallVector<Region *> ParallelOp::getLoopRegions() { return {&getRegion()}; }
3141
3142std::optional<SmallVector<Value>> ParallelOp::getLoopInductionVars() {
3143 return SmallVector<Value>{getBody()->getArguments()};
3144}
3145
3146std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopLowerBounds() {
3147 return getLowerBound();
3148}
3149
3150std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopUpperBounds() {
3151 return getUpperBound();
3152}
3153
3154std::optional<SmallVector<OpFoldResult>> ParallelOp::getLoopSteps() {
3155 return getStep();
3156}
3157
3159 auto ivArg = llvm::dyn_cast<BlockArgument>(val);
3160 if (!ivArg)
3161 return ParallelOp();
3162 assert(ivArg.getOwner() && "unlinked block argument");
3163 auto *containingOp = ivArg.getOwner()->getParentOp();
3164 return dyn_cast<ParallelOp>(containingOp);
3165}
3166
3167namespace {
3168// Collapse loop dimensions that perform a single iteration.
3169struct ParallelOpSingleOrZeroIterationDimsFolder
3170 : public OpRewritePattern<ParallelOp> {
3171 using OpRewritePattern<ParallelOp>::OpRewritePattern;
3172
3173 LogicalResult matchAndRewrite(ParallelOp op,
3174 PatternRewriter &rewriter) const override {
3175 Location loc = op.getLoc();
3176
3177 // Compute new loop bounds that omit all single-iteration loop dimensions.
3178 SmallVector<Value> newLowerBounds, newUpperBounds, newSteps;
3179 IRMapping mapping;
3180 for (auto [lb, ub, step, iv] :
3181 llvm::zip(op.getLowerBound(), op.getUpperBound(), op.getStep(),
3182 op.getInductionVars())) {
3183 auto numIterations = constantTripCount(lb, ub, step, !op.getUnsignedCmp(),
3185 if (numIterations.has_value()) {
3186 // Remove the loop if it performs zero iterations.
3187 if (*numIterations == 0) {
3188 rewriter.replaceOp(op, op.getInitVals());
3189 return success();
3190 }
3191 // Replace the loop induction variable by the lower bound if the loop
3192 // performs a single iteration. Otherwise, copy the loop bounds.
3193 if (*numIterations == 1) {
3194 mapping.map(iv, getValueOrCreateConstantIndexOp(rewriter, loc, lb));
3195 continue;
3196 }
3197 }
3198 newLowerBounds.push_back(lb);
3199 newUpperBounds.push_back(ub);
3200 newSteps.push_back(step);
3201 }
3202 // Exit if none of the loop dimensions perform a single iteration.
3203 if (newLowerBounds.size() == op.getLowerBound().size())
3204 return failure();
3205
3206 if (newLowerBounds.empty()) {
3207 // All of the loop dimensions perform a single iteration. Inline
3208 // loop body and nested ReduceOp's
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]);
3218 mapping.map(reduceBlock.getArgument(1),
3219 mapping.lookupOrDefault(reduceOp.getOperands()[i]));
3220 for (auto &reduceBodyOp : reduceBlock.without_terminator())
3221 rewriter.clone(reduceBodyOp, mapping);
3222
3223 auto result = mapping.lookupOrDefault(
3224 cast<ReduceReturnOp>(reduceBlock.getTerminator()).getResult());
3225 results.push_back(result);
3226 }
3227
3228 rewriter.replaceOp(op, results);
3229 return success();
3230 }
3231 // Replace the parallel loop by lower-dimensional parallel loop.
3232 auto newOp = ParallelOp::create(rewriter, op.getLoc(), newLowerBounds,
3233 newUpperBounds, newSteps, op.getInitVals(),
3234 nullptr, op.getUnsignedCmp());
3235 // Erase the empty block that was inserted by the builder.
3236 rewriter.eraseBlock(newOp.getBody());
3237 // Clone the loop body and remap the block arguments of the collapsed loops
3238 // (inlining does not support a cancellable block argument mapping).
3239 rewriter.cloneRegionBefore(op.getRegion(), newOp.getRegion(),
3240 newOp.getRegion().begin(), mapping);
3241 rewriter.replaceOp(op, newOp.getResults());
3242 return success();
3243 }
3244};
3245
3246struct MergeNestedParallelLoops : public OpRewritePattern<ParallelOp> {
3247 using OpRewritePattern<ParallelOp>::OpRewritePattern;
3248
3249 LogicalResult matchAndRewrite(ParallelOp op,
3250 PatternRewriter &rewriter) const override {
3251 Block &outerBody = *op.getBody();
3252 if (!llvm::hasSingleElement(outerBody.without_terminator()))
3253 return failure();
3254
3255 auto innerOp = dyn_cast<ParallelOp>(outerBody.front());
3256 if (!innerOp)
3257 return failure();
3258
3259 if (op.getUnsignedCmp() != innerOp.getUnsignedCmp())
3260 return failure();
3261
3262 for (auto val : outerBody.getArguments())
3263 if (llvm::is_contained(innerOp.getLowerBound(), val) ||
3264 llvm::is_contained(innerOp.getUpperBound(), val) ||
3265 llvm::is_contained(innerOp.getStep(), val))
3266 return failure();
3267
3268 // Reductions are not supported yet.
3269 if (!op.getInitVals().empty() || !innerOp.getInitVals().empty())
3270 return failure();
3271
3272 auto bodyBuilder = [&](OpBuilder &builder, Location /*loc*/,
3273 ValueRange iterVals, ValueRange) {
3274 Block &innerBody = *innerOp.getBody();
3275 assert(iterVals.size() ==
3276 (outerBody.getNumArguments() + innerBody.getNumArguments()));
3277 IRMapping mapping;
3278 mapping.map(outerBody.getArguments(),
3279 iterVals.take_front(outerBody.getNumArguments()));
3280 mapping.map(innerBody.getArguments(),
3281 iterVals.take_back(innerBody.getNumArguments()));
3282 for (Operation &op : innerBody.without_terminator())
3283 builder.clone(op, mapping);
3284 };
3285
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());
3291 return ret;
3292 };
3293
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());
3299
3300 rewriter.replaceOpWithNewOp<ParallelOp>(op, newLowerBounds, newUpperBounds,
3301 newSteps, ValueRange(),
3302 bodyBuilder);
3303 return success();
3304 }
3305};
3306
3307} // namespace
3308
3309void ParallelOp::getCanonicalizationPatterns(RewritePatternSet &results,
3310 MLIRContext *context) {
3311 results
3312 .add<ParallelOpSingleOrZeroIterationDimsFolder, MergeNestedParallelLoops>(
3313 context);
3314}
3315
3316/// Given the region at `index`, or the parent operation if `index` is None,
3317/// return the successor regions. These are the regions that may be selected
3318/// during the flow of control. `operands` is a set of optional attributes that
3319/// correspond to a constant value for each operand, or null if that operand is
3320/// not a constant.
3321void ParallelOp::getSuccessorRegions(
3322 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &regions) {
3323 // Both the operation itself and the region may be branching into the body or
3324 // back into the operation itself. It is possible for loop not to enter the
3325 // body.
3326 regions.push_back(RegionSuccessor(&getRegion()));
3327 regions.push_back(RegionSuccessor(getOperation()));
3328}
3329
3330//===----------------------------------------------------------------------===//
3331// ReduceOp
3332//===----------------------------------------------------------------------===//
3333
3334void ReduceOp::build(OpBuilder &builder, OperationState &result) {}
3335
3336void ReduceOp::build(OpBuilder &builder, OperationState &result,
3337 ValueRange operands) {
3338 result.addOperands(operands);
3339 for (Value v : operands) {
3340 OpBuilder::InsertionGuard guard(builder);
3341 Region *bodyRegion = result.addRegion();
3342 builder.createBlock(bodyRegion, {},
3343 ArrayRef<Type>{v.getType(), v.getType()},
3344 {result.location, result.location});
3345 }
3346}
3347
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();
3354 // The region of a ReduceOp has two arguments of the same type as its
3355 // corresponding operand.
3356 for (int64_t i = 0, e = getReductions().size(); i < e; ++i) {
3357 auto type = getOperands()[i].getType();
3358 Block &block = getReductions()[i].front();
3359 if (block.empty())
3360 return emitOpError() << i << "-th reduction has an empty body";
3361 if (block.getNumArguments() != 2 ||
3362 llvm::any_of(block.getArguments(), [&](const BlockArgument &arg) {
3363 return arg.getType() != type;
3364 }))
3365 return emitOpError() << "expected two block arguments with type " << type
3366 << " in the " << i << "-th reduction region";
3367
3368 // Check that the block is terminated by a ReduceReturnOp.
3369 if (!isa<ReduceReturnOp>(block.getTerminator()))
3370 return emitOpError("reduction bodies must be terminated with an "
3371 "'scf.reduce.return' op");
3372 }
3373
3374 return success();
3375}
3376
3377MutableOperandRange
3378ReduceOp::getMutableSuccessorOperands(RegionSuccessor point) {
3379 // No operands are forwarded to the next iteration.
3380 return MutableOperandRange(getOperation(), /*start=*/0, /*length=*/0);
3381}
3382
3383//===----------------------------------------------------------------------===//
3384// ReduceReturnOp
3385//===----------------------------------------------------------------------===//
3386
3387LogicalResult ReduceReturnOp::verify() {
3388 // The type of the return value should be the same type as the types of the
3389 // block arguments of the reduction body.
3390 Block *reductionBody = getOperation()->getBlock();
3391 // Should already be verified by an op trait.
3392 assert(isa<ReduceOp>(reductionBody->getParentOp()) && "expected scf.reduce");
3393 Type expectedResultType = reductionBody->getArgument(0).getType();
3394 if (expectedResultType != getResult().getType())
3395 return emitOpError() << "must have type " << expectedResultType
3396 << " (the type of the reduction inputs)";
3397 return success();
3398}
3399
3400//===----------------------------------------------------------------------===//
3401// WhileOp
3402//===----------------------------------------------------------------------===//
3403
3404void WhileOp::build(::mlir::OpBuilder &odsBuilder,
3405 ::mlir::OperationState &odsState, TypeRange resultTypes,
3406 ValueRange inits, BodyBuilderFn beforeBuilder,
3407 BodyBuilderFn afterBuilder) {
3408 odsState.addOperands(inits);
3409 odsState.addTypes(resultTypes);
3410
3411 OpBuilder::InsertionGuard guard(odsBuilder);
3412
3413 // Build before region.
3414 SmallVector<Location, 4> beforeArgLocs;
3415 beforeArgLocs.reserve(inits.size());
3416 for (Value operand : inits) {
3417 beforeArgLocs.push_back(operand.getLoc());
3418 }
3419
3420 Region *beforeRegion = odsState.addRegion();
3421 Block *beforeBlock = odsBuilder.createBlock(beforeRegion, /*insertPt=*/{},
3422 inits.getTypes(), beforeArgLocs);
3423 if (beforeBuilder)
3424 beforeBuilder(odsBuilder, odsState.location, beforeBlock->getArguments());
3425
3426 // Build after region.
3427 SmallVector<Location, 4> afterArgLocs(resultTypes.size(), odsState.location);
3428
3429 Region *afterRegion = odsState.addRegion();
3430 Block *afterBlock = odsBuilder.createBlock(afterRegion, /*insertPt=*/{},
3431 resultTypes, afterArgLocs);
3432
3433 if (afterBuilder)
3434 afterBuilder(odsBuilder, odsState.location, afterBlock->getArguments());
3435}
3436
3437ConditionOp WhileOp::getConditionOp() {
3438 return cast<ConditionOp>(getBeforeBody()->getTerminator());
3439}
3440
3441YieldOp WhileOp::getYieldOp() {
3442 return cast<YieldOp>(getAfterBody()->getTerminator());
3443}
3444
3445std::optional<MutableArrayRef<OpOperand>> WhileOp::getYieldedValuesMutable() {
3446 return getYieldOp().getResultsMutable();
3447}
3448
3449Block::BlockArgListType WhileOp::getBeforeArguments() {
3450 return getBeforeBody()->getArguments();
3451}
3452
3453Block::BlockArgListType WhileOp::getAfterArguments() {
3454 return getAfterBody()->getArguments();
3455}
3456
3457Block::BlockArgListType WhileOp::getRegionIterArgs() {
3458 return getBeforeArguments();
3459}
3460
3461OperandRange WhileOp::getEntrySuccessorOperands(RegionSuccessor successor) {
3462 assert(successor.getSuccessor() == &getBefore() &&
3463 "WhileOp is expected to branch only to the first region");
3464 return getInits();
3465}
3466
3467void WhileOp::getSuccessorRegions(RegionBranchPoint point,
3468 SmallVectorImpl<RegionSuccessor> &regions) {
3469 // The parent op always branches to the condition region.
3470 if (point.isParent()) {
3471 regions.emplace_back(&getBefore());
3472 return;
3473 }
3474
3475 assert(llvm::is_contained(
3476 {&getAfter(), &getBefore()},
3477 point.getTerminatorPredecessorOrNull()->getParentRegion()) &&
3478 "there are only two regions in a WhileOp");
3479 // The body region always branches back to the condition region.
3480 if (point.getTerminatorPredecessorOrNull()->getParentRegion() ==
3481 &getAfter()) {
3482 regions.emplace_back(&getBefore());
3483 return;
3484 }
3485
3486 regions.push_back(RegionSuccessor(getOperation()));
3487 regions.emplace_back(&getAfter());
3488}
3489
3490ValueRange WhileOp::getSuccessorInputs(RegionSuccessor successor) {
3491 if (successor.isOperation())
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");
3498}
3499
3500SmallVector<Region *> WhileOp::getLoopRegions() {
3501 return {&getBefore(), &getAfter()};
3502}
3503
3504/// Parses a `while` op.
3505///
3506/// op ::= `scf.while` assignments `:` function-type region `do` region
3507/// `attributes` attribute-dict
3508/// initializer ::= /* empty */ | `(` assignment-list `)`
3509/// assignment-list ::= assignment | assignment `,` assignment-list
3510/// assignment ::= ssa-value `=` ssa-value
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();
3516
3517 OptionalParseResult listResult =
3518 parser.parseOptionalAssignmentList(regionArgs, operands);
3519 if (listResult.has_value() && failed(listResult.value()))
3520 return failure();
3521
3522 FunctionType functionType;
3523 SMLoc typeLoc = parser.getCurrentLocation();
3524 if (failed(parser.parseColonType(functionType)))
3525 return failure();
3526
3527 result.addTypes(functionType.getResults());
3528
3529 if (functionType.getNumInputs() != operands.size()) {
3530 return parser.emitError(typeLoc)
3531 << "expected as many input types as operands " << "(expected "
3532 << operands.size() << " got " << functionType.getNumInputs() << ")";
3533 }
3534
3535 // Resolve input operands.
3536 if (failed(parser.resolveOperands(operands, functionType.getInputs(),
3537 parser.getCurrentLocation(),
3538 result.operands)))
3539 return failure();
3540
3541 // Propagate the types into the region arguments.
3542 for (size_t i = 0, e = regionArgs.size(); i != e; ++i)
3543 regionArgs[i].type = functionType.getInput(i);
3544
3545 return failure(parser.parseRegion(*before, regionArgs) ||
3546 parser.parseKeyword("do") || parser.parseRegion(*after) ||
3547 parser.parseOptionalAttrDictWithKeyword(result.attributes));
3548}
3549
3550/// Prints a `while` op.
3551void scf::WhileOp::print(OpAsmPrinter &p) {
3552 printInitializationList(p, getBeforeArguments(), getInits(), " ");
3553 p << " : ";
3554 p.printFunctionalType(getInits().getTypes(), getResults().getTypes());
3555 p << ' ';
3556 p.printRegion(getBefore(), /*printEntryBlockArgs=*/false);
3557 p << " do ";
3558 p.printRegion(getAfter());
3560 (*this)->getDiscardableAttrDictionary().getValue());
3561}
3562
3563LogicalResult scf::WhileOp::verify() {
3564 auto beforeTerminator = verifyAndGetTerminator<scf::ConditionOp>(
3565 *this, getBefore(),
3566 "expects the 'before' region to terminate with 'scf.condition'");
3567 if (!beforeTerminator)
3568 return failure();
3569
3570 auto afterTerminator = verifyAndGetTerminator<scf::YieldOp>(
3571 *this, getAfter(),
3572 "expects the 'after' region to terminate with 'scf.yield'");
3573 return success(afterTerminator != nullptr);
3574}
3575
3576namespace {
3577/// Move a scf.if op that is directly before the scf.condition op in the while
3578/// before region, and whose condition matches the condition of the
3579/// scf.condition op, down into the while after region.
3580///
3581/// scf.while (..) : (...) -> ... {
3582/// %additional_used_values = ...
3583/// %cond = ...
3584/// ...
3585/// %res = scf.if %cond -> (...) {
3586/// use(%additional_used_values)
3587/// ... // then block
3588/// scf.yield %then_value
3589/// } else {
3590/// scf.yield %else_value
3591/// }
3592/// scf.condition(%cond) %res, ...
3593/// } do {
3594/// ^bb0(%res_arg, ...):
3595/// use(%res_arg)
3596/// ...
3597///
3598/// becomes
3599/// scf.while (..) : (...) -> ... {
3600/// %additional_used_values = ...
3601/// %cond = ...
3602/// ...
3603/// scf.condition(%cond) %else_value, ..., %additional_used_values
3604/// } do {
3605/// ^bb0(%res_arg ..., %additional_args): :
3606/// use(%additional_args)
3607/// ... // if then block
3608/// use(%then_value)
3609/// ...
3610struct WhileMoveIfDown : public OpRewritePattern<scf::WhileOp> {
3611 using OpRewritePattern<scf::WhileOp>::OpRewritePattern;
3612
3613 LogicalResult matchAndRewrite(scf::WhileOp op,
3614 PatternRewriter &rewriter) const override {
3615 auto conditionOp = op.getConditionOp();
3616
3617 // Only support ifOp right before the condition at the moment. Relaxing this
3618 // would require to:
3619 // - check that the body does not have side-effects conflicting with
3620 // operations between the if and the condition.
3621 // - check that results of the if operation are only used as arguments to
3622 // the condition.
3623 auto ifOp = dyn_cast_or_null<scf::IfOp>(conditionOp->getPrevNode());
3624
3625 // Check that the ifOp is directly before the conditionOp and that it
3626 // matches the condition of the conditionOp. Also ensure that the ifOp has
3627 // no else block with content, as that would complicate the transformation.
3628 // TODO: support else blocks with content.
3629 if (!ifOp || ifOp.getCondition() != conditionOp.getCondition() ||
3630 (ifOp.elseBlock() && !ifOp.elseBlock()->without_terminator().empty()))
3631 return failure();
3632
3633 assert((ifOp->use_empty() || (llvm::all_equal(ifOp->getUsers()) &&
3634 *ifOp->user_begin() == conditionOp)) &&
3635 "ifOp has unexpected uses");
3636
3637 Location loc = op.getLoc();
3638
3639 // Replace uses of ifOp results in the conditionOp with the yielded values
3640 // from the ifOp branches: the after-region argument takes the `then` value,
3641 // while the condition operand -- which becomes a while result once the
3642 // condition is false -- takes the `else` value.
3643 //
3644 // The same ifOp result may be forwarded to several condition operands, so
3645 // assign into the specific operand instead of replacing all uses of the
3646 // ifOp result, which would also rewrite the operands not yet visited.
3647 for (auto [idx, arg] : llvm::enumerate(conditionOp.getArgs())) {
3648 auto it = llvm::find(ifOp->getResults(), arg);
3649 if (it == ifOp->getResults().end())
3650 continue;
3651 size_t ifOpIdx = it.getIndex();
3652 rewriter.replaceAllUsesWith(op.getAfterArguments()[idx],
3653 ifOp.thenYield()->getOperand(ifOpIdx));
3654 unsigned argIdx = idx;
3655 Value elseValue = ifOp.elseYield()->getOperand(ifOpIdx);
3656 rewriter.modifyOpInPlace(conditionOp, [&] {
3657 conditionOp.getArgsMutable()[argIdx].assign(elseValue);
3658 });
3659 }
3660
3661 // Collect additional used values from before region.
3662 SetVector<Value> additionalUsedValuesSet;
3663 visitUsedValuesDefinedAbove(ifOp.getThenRegion(), [&](OpOperand *operand) {
3664 if (&op.getBefore() == operand->get().getParentRegion())
3665 additionalUsedValuesSet.insert(operand->get());
3666 });
3667
3668 // Create new whileOp with additional used values as results.
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);
3675
3676 auto newWhileOp =
3677 scf::WhileOp::create(rewriter, loc, newResultTypes, op.getInits());
3678
3679 rewriter.modifyOpInPlace(newWhileOp, [&] {
3680 newWhileOp.getBefore().takeBody(op.getBefore());
3681 newWhileOp.getAfter().takeBody(op.getAfter());
3682 newWhileOp.getAfter().addArguments(
3683 additionalValueTypes,
3684 SmallVector<Location>(additionalValueSize, loc));
3685 });
3686
3687 rewriter.modifyOpInPlace(conditionOp, [&] {
3688 conditionOp.getArgsMutable().append(additionalUsedValues);
3689 });
3690
3691 // Replace uses of additional used values inside the ifOp then region with
3692 // the whileOp after region arguments.
3693 rewriter.replaceUsesWithIf(
3694 additionalUsedValues,
3695 newWhileOp.getAfterArguments().take_back(additionalValueSize),
3696 [&](OpOperand &use) {
3697 return ifOp.getThenRegion().isAncestor(
3698 use.getOwner()->getParentRegion());
3699 });
3700
3701 // Inline ifOp then region into new whileOp after region.
3702 rewriter.eraseOp(ifOp.thenYield());
3703 rewriter.inlineBlockBefore(ifOp.thenBlock(), newWhileOp.getAfterBody(),
3704 newWhileOp.getAfterBody()->begin());
3705 rewriter.eraseOp(ifOp);
3706 rewriter.replaceOp(op,
3707 newWhileOp->getResults().drop_back(additionalValueSize));
3708 return success();
3709 }
3710};
3711
3712/// Replace uses of the condition within the do block with true, since otherwise
3713/// the block would not be evaluated.
3714///
3715/// scf.while (..) : (i1, ...) -> ... {
3716/// %condition = call @evaluate_condition() : () -> i1
3717/// scf.condition(%condition) %condition : i1, ...
3718/// } do {
3719/// ^bb0(%arg0: i1, ...):
3720/// use(%arg0)
3721/// ...
3722///
3723/// becomes
3724/// scf.while (..) : (i1, ...) -> ... {
3725/// %condition = call @evaluate_condition() : () -> i1
3726/// scf.condition(%condition) %condition : i1, ...
3727/// } do {
3728/// ^bb0(%arg0: i1, ...):
3729/// use(%true)
3730/// ...
3731struct WhileConditionTruth : public OpRewritePattern<WhileOp> {
3732 using OpRewritePattern<WhileOp>::OpRewritePattern;
3733
3734 LogicalResult matchAndRewrite(WhileOp op,
3735 PatternRewriter &rewriter) const override {
3736 auto term = op.getConditionOp();
3737
3738 // These variables serve to prevent creating duplicate constants
3739 // and hold constant true or false values.
3740 Value constantTrue = nullptr;
3741
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()) {
3747 if (!constantTrue)
3748 constantTrue = arith::ConstantOp::create(
3749 rewriter, op.getLoc(), term.getCondition().getType(),
3750 rewriter.getBoolAttr(true));
3751
3752 rewriter.replaceAllUsesWith(std::get<1>(yieldedAndBlockArgs),
3753 constantTrue);
3754 replaced = true;
3755 }
3756 }
3757 }
3758 return success(replaced);
3759 }
3760};
3761
3762/// Simplify values that the condition forwards as a select on the condition:
3763/// the do block only runs if the condition is true, and the loop only exits if
3764/// it is false.
3765///
3766/// %res = scf.while (..) : (...) -> (i32, ...) {
3767/// %condition = call @evaluate_condition() : () -> i1
3768/// %v = arith.select %condition, %a, %b : i32
3769/// scf.condition(%condition) %v, ... : i32, ...
3770/// } do {
3771/// ^bb0(%arg0: i32, ...):
3772/// use(%arg0)
3773/// ...
3774/// }
3775/// use(%res#0)
3776///
3777/// becomes, if %a and %b are defined outside of the loop,
3778///
3779/// %res = scf.while (..) : (...) -> (i32, ...) {
3780/// %condition = call @evaluate_condition() : () -> i1
3781/// %v = arith.select %condition, %a, %b : i32
3782/// scf.condition(%condition) %a, ... : i32, ...
3783/// } do {
3784/// ^bb0(%arg0: i32, ...):
3785/// use(%a)
3786/// ...
3787/// }
3788/// use(%b)
3789///
3790/// More generally, once either the loop result or the do block argument has no
3791/// uses, the condition forwards the value seen by the remaining uses (%a or %b)
3792/// instead of the select, which may then fold away.
3793struct WhileConditionSelect : public OpRewritePattern<WhileOp> {
3794 using OpRewritePattern<WhileOp>::OpRewritePattern;
3795
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())) {
3803 auto select = arg.getDefiningOp<arith::SelectOp>();
3804 if (!select || select.getCondition() != condition)
3805 continue;
3806 Value trueValue = select.getTrueValue();
3807 Value falseValue = select.getFalseValue();
3808 if (!afterArg.use_empty() && op.isDefinedOutsideOfLoop(trueValue)) {
3809 rewriter.replaceAllUsesWith(afterArg, trueValue);
3810 changed = true;
3811 }
3812 if (!result.use_empty() && falseValue != result &&
3813 op.isDefinedOutsideOfLoop(falseValue)) {
3814 rewriter.replaceAllUsesWith(result, falseValue);
3815 changed = true;
3816 }
3817 // Forward the value that the remaining uses see.
3818 Value forwarded;
3819 if (result.use_empty())
3820 forwarded = trueValue;
3821 else if (afterArg.use_empty())
3822 forwarded = falseValue;
3823 if (forwarded && forwarded != arg) {
3824 size_t condIdx = idx;
3825 rewriter.modifyOpInPlace(
3826 term, [&] { term.getArgsMutable()[condIdx].set(forwarded); });
3827 changed = true;
3828 }
3829 }
3830 return success(changed);
3831 }
3832};
3833
3834/// Replace operations equivalent to the condition in the do block with true,
3835/// since otherwise the block would not be evaluated.
3836///
3837/// scf.while (..) : (i32, ...) -> ... {
3838/// %z = ... : i32
3839/// %condition = cmpi pred %z, %a
3840/// scf.condition(%condition) %z : i32, ...
3841/// } do {
3842/// ^bb0(%arg0: i32, ...):
3843/// %condition2 = cmpi pred %arg0, %a
3844/// use(%condition2)
3845/// ...
3846///
3847/// becomes
3848/// scf.while (..) : (i32, ...) -> ... {
3849/// %z = ... : i32
3850/// %condition = cmpi pred %z, %a
3851/// scf.condition(%condition) %z : i32, ...
3852/// } do {
3853/// ^bb0(%arg0: i32, ...):
3854/// use(%true)
3855/// ...
3856struct WhileCmpCond : public OpRewritePattern<scf::WhileOp> {
3857 using OpRewritePattern<scf::WhileOp>::OpRewritePattern;
3858
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>();
3864 if (!cmp)
3865 return failure();
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))
3870 continue;
3871 for (OpOperand &u :
3872 llvm::make_early_inc_range(std::get<1>(tup).getUses())) {
3873 auto cmp2 = dyn_cast<arith::CmpIOp>(u.getOwner());
3874 if (!cmp2)
3875 continue;
3876 // For a binary operator 1-opIdx gets the other side.
3877 if (cmp2.getOperand(1 - opIdx) != cmp.getOperand(1 - opIdx))
3878 continue;
3879 bool samePredicate;
3880 if (cmp2.getPredicate() == cmp.getPredicate())
3881 samePredicate = true;
3882 else if (cmp2.getPredicate() ==
3883 arith::invertPredicate(cmp.getPredicate()))
3884 samePredicate = false;
3885 else
3886 continue;
3887
3888 rewriter.replaceOpWithNewOp<arith::ConstantIntOp>(cmp2, samePredicate,
3889 1);
3890 changed = true;
3891 }
3892 }
3893 }
3894 return success(changed);
3895 }
3896};
3897
3898/// If both ranges contain same values return mappping indices from args2 to
3899/// args1. Otherwise return std::nullopt.
3900static std::optional<SmallVector<unsigned>> getArgsMapping(ValueRange args1,
3901 ValueRange args2) {
3902 if (args1.size() != args2.size())
3903 return std::nullopt;
3904
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;
3910
3911 ret[std::distance(args2.begin(), it)] = static_cast<unsigned>(i);
3912 }
3913
3914 return ret;
3915}
3916
3917static bool hasDuplicates(ValueRange args) {
3918 llvm::SmallDenseSet<Value> set;
3919 for (Value arg : args) {
3920 if (!set.insert(arg).second)
3921 return true;
3922 }
3923 return false;
3924}
3925
3926/// If `before` block args are directly forwarded to `scf.condition`, rearrange
3927/// `scf.condition` args into same order as block args. Update `after` block
3928/// args and op result values accordingly.
3929/// Needed to simplify `scf.while` -> `scf.for` uplifting.
3930struct WhileOpAlignBeforeArgs : public OpRewritePattern<WhileOp> {
3931 using Base::Base;
3932
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();
3938 ValueRange termArgs = oldTerm.getArgs();
3939 if (beforeArgs == termArgs)
3940 return failure();
3941
3942 if (hasDuplicates(termArgs))
3943 return failure();
3944
3945 auto mapping = getArgsMapping(beforeArgs, termArgs);
3946 if (!mapping)
3947 return failure();
3948
3949 {
3950 OpBuilder::InsertionGuard g(rewriter);
3951 rewriter.setInsertionPoint(oldTerm);
3952 rewriter.replaceOpWithNewOp<ConditionOp>(oldTerm, oldTerm.getCondition(),
3953 beforeArgs);
3954 }
3955
3956 auto *oldAfter = loop.getAfterBody();
3957
3958 SmallVector<Type> newResultTypes(beforeArgs.size());
3959 for (auto &&[i, j] : llvm::enumerate(*mapping))
3960 newResultTypes[j] = loop.getResult(i).getType();
3961
3962 auto newLoop = WhileOp::create(
3963 rewriter, loop.getLoc(), newResultTypes, loop.getInits(),
3964 /*beforeBuilder=*/nullptr, /*afterBuilder=*/nullptr);
3965 auto *newBefore = newLoop.getBeforeBody();
3966 auto *newAfter = newLoop.getAfterBody();
3967
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);
3973 }
3974
3975 rewriter.inlineBlockBefore(oldBefore, newBefore, newBefore->begin(),
3976 newBefore->getArguments());
3977 rewriter.inlineBlockBefore(oldAfter, newAfter, newAfter->begin(),
3978 newAfterArgs);
3979
3980 rewriter.replaceOp(loop, newResults);
3981 return success();
3982 }
3983};
3984} // namespace
3985
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());
3994}
3995
3996//===----------------------------------------------------------------------===//
3997// IndexSwitchOp
3998//===----------------------------------------------------------------------===//
3999
4000/// Parse the case regions and values.
4001static ParseResult
4003 SmallVectorImpl<std::unique_ptr<Region>> &caseRegions) {
4004 SmallVector<int64_t> caseValues;
4005 while (succeeded(p.parseOptionalKeyword("case"))) {
4006 int64_t value;
4007 Region &region = *caseRegions.emplace_back(std::make_unique<Region>());
4008 if (p.parseInteger(value) || p.parseRegion(region, /*arguments=*/{}))
4009 return failure();
4010 caseValues.push_back(value);
4011 }
4012 cases = p.getBuilder().getDenseI64ArrayAttr(caseValues);
4013 return success();
4014}
4015
4016/// Print the case regions and values.
4018 DenseI64ArrayAttr cases, RegionRange caseRegions) {
4019 for (auto [value, region] : llvm::zip(cases.asArrayRef(), caseRegions)) {
4020 p.printNewline();
4021 p << "case " << value << ' ';
4022 p.printRegion(*region, /*printEntryBlockArgs=*/false);
4023 }
4024}
4025
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";
4031 }
4032
4033 DenseSet<int64_t> valueSet;
4034 for (int64_t value : getCases())
4035 if (!valueSet.insert(value).second)
4036 return emitOpError("has duplicate case value: ") << value;
4037 auto verifyRegion = [&](Region &region, const Twine &name) -> LogicalResult {
4038 auto yield = dyn_cast<YieldOp>(region.front().back());
4039 if (!yield)
4040 return emitOpError("expected region to end with scf.yield, but got ")
4041 << region.front().back().getName();
4042
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";
4049 }
4050 for (auto [idx, result, operand] :
4051 llvm::enumerate(getResultTypes(), yield.getOperands())) {
4052 if (!operand)
4053 return yield.emitOpError() << "operand " << idx << " is null\n";
4054 if (result == operand.getType())
4055 continue;
4056 return (emitOpError("expected result #")
4057 << idx << " of each region to be " << result)
4058 .attachNote(yield.getLoc())
4059 << name << " returns " << operand.getType() << " here";
4060 }
4061 return success();
4062 };
4063
4064 if (failed(verifyRegion(getDefaultRegion(), "default region")))
4065 return failure();
4066 for (auto [idx, caseRegion] : llvm::enumerate(getCaseRegions()))
4067 if (failed(verifyRegion(caseRegion, "case region #" + Twine(idx))))
4068 return failure();
4069
4070 return success();
4071}
4072
4073unsigned scf::IndexSwitchOp::getNumCases() { return getCases().size(); }
4074
4075Block &scf::IndexSwitchOp::getDefaultBlock() {
4076 return getDefaultRegion().front();
4077}
4078
4079Block &scf::IndexSwitchOp::getCaseBlock(unsigned idx) {
4080 assert(idx < getNumCases() && "case index out-of-bounds");
4081 return getCaseRegions()[idx].front();
4082}
4083
4084void IndexSwitchOp::getSuccessorRegions(
4085 RegionBranchPoint point, SmallVectorImpl<RegionSuccessor> &successors) {
4086 // All regions branch back to the parent op.
4087 if (!point.isParent()) {
4088 successors.push_back(RegionSuccessor(getOperation()));
4089 return;
4090 }
4091
4092 llvm::append_range(successors, getRegions());
4093}
4094
4095ValueRange IndexSwitchOp::getSuccessorInputs(RegionSuccessor successor) {
4096 return successor.isOperation() ? ValueRange(getOperation()->getResults())
4097 : ValueRange();
4098}
4099
4100void IndexSwitchOp::getEntrySuccessorRegions(
4101 ArrayRef<Attribute> operands,
4102 SmallVectorImpl<RegionSuccessor> &successors) {
4103 FoldAdaptor adaptor(operands, *this);
4104
4105 // If a constant was not provided, all regions are possible successors.
4106 auto arg = dyn_cast_or_null<IntegerAttr>(adaptor.getArg());
4107 if (!arg) {
4108 llvm::append_range(successors, getRegions());
4109 return;
4110 }
4111
4112 // Otherwise, try to find a case with a matching value. If not, the
4113 // default region is the only successor.
4114 for (auto [caseValue, caseRegion] : llvm::zip(getCases(), getCaseRegions())) {
4115 if (caseValue == arg.getInt()) {
4116 successors.emplace_back(&caseRegion);
4117 return;
4118 }
4119 }
4120 successors.emplace_back(&getDefaultRegion());
4121}
4122
4123void IndexSwitchOp::getRegionInvocationBounds(
4124 ArrayRef<Attribute> operands, SmallVectorImpl<InvocationBounds> &bounds) {
4125 auto operandValue = llvm::dyn_cast_or_null<IntegerAttr>(operands.front());
4126 if (!operandValue) {
4127 // All regions are invoked at most once.
4128 bounds.append(getNumRegions(), InvocationBounds(/*lb=*/0, /*ub=*/1));
4129 return;
4130 }
4131
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(/*lb=*/0, /*ub=*/i == liveIndex);
4138}
4139
4140void IndexSwitchOp::getCanonicalizationPatterns(RewritePatternSet &results,
4141 MLIRContext *context) {
4143 results, IndexSwitchOp::getOperationName());
4145 results, IndexSwitchOp::getOperationName());
4146}
4147
4148//===----------------------------------------------------------------------===//
4149// TableGen'd op method definitions
4150//===----------------------------------------------------------------------===//
4151
4152#define GET_OP_CLASSES
4153#include "mlir/Dialect/SCF/IR/SCFOps.cpp.inc"
return success()
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 &region, const Twine &name)
Definition EmitC.cpp:1506
static ParseResult parseSwitchCases(OpAsmParser &parser, DenseI64ArrayAttr &cases, SmallVectorImpl< std::unique_ptr< Region > > &caseRegions)
Parse the case regions and values.
Definition EmitC.cpp:1481
static void printSwitchCases(OpAsmPrinter &p, Operation *op, DenseI64ArrayAttr cases, RegionRange caseRegions)
Print the case regions and values.
Definition EmitC.cpp:1497
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,...
Definition SCF.cpp:500
static TerminatorTy verifyAndGetTerminator(Operation *op, Region &region, StringRef errorMessage)
Verifies that the first block of the given region is terminated by a TerminatorTy.
Definition SCF.cpp:100
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.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
ArrayAttr()
b getContext())
*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`
@ None
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.
Definition Value.h:308
unsigned getArgNumber() const
Returns the number of this argument.
Definition Value.h:320
Block represents an ordered list of Operations.
Definition Block.h:34
MutableArrayRef< BlockArgument > BlockArgListType
Definition Block.h:110
bool empty()
Definition Block.h:173
BlockArgument getArgument(unsigned i)
Definition Block.h:154
unsigned getNumArguments()
Definition Block.h:153
iterator_range< args_iterator > addArguments(TypeRange types, ArrayRef< Location > locs)
Add one argument to the argument list for each type specified in the list.
Definition Block.cpp:165
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Definition Block.cpp:27
Operation & front()
Definition Block.h:178
Operation & back()
Definition Block.h:177
Operation * getTerminator()
Get the terminator operation of this block.
Definition Block.cpp:249
BlockArgument addArgument(Type type, Location loc)
Add one value to the argument list.
Definition Block.cpp:158
BlockArgListType getArguments()
Definition Block.h:112
iterator_range< iterator > without_terminator()
Return an iterator range over the operation within this block excluding the terminator operation at t...
Definition Block.h:222
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
Definition Block.cpp:31
bool getValue() const
Return the boolean value of this attribute.
UnitAttr getUnitAttr()
Definition Builders.cpp:106
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
Definition Builders.cpp:171
IntegerAttr getIntegerAttr(Type type, int64_t value)
Definition Builders.cpp:237
DenseI64ArrayAttr getDenseI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:175
IntegerType getIntegerType(unsigned width)
Definition Builders.cpp:75
BoolAttr getBoolAttr(bool value)
Definition Builders.cpp:108
StringAttr getStringAttr(const Twine &bytes)
Definition Builders.cpp:271
IntegerType getI1Type()
Definition Builders.cpp:61
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
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...
Definition Dialect.h:83
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
auto lookupOrDefault(T from) const
Lookup a mapped value within the map.
Definition IRMapping.h:65
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
Definition IRMapping.h:30
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...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class provides a mutable adaptor for a range of operands.
Definition ValueRange.h:119
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 &region, 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.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
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.
Definition Builders.cpp:439
Operation * clone(Operation &op, IRMapping &mapper)
Creates a deep copy of the specified operation, remapping any operands that use values outside of the...
Definition Builders.cpp:581
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
Definition Builders.h:439
void cloneRegionBefore(Region &region, Region &parent, Region::iterator before, IRMapping &mapping)
Clone the blocks that belong to "region" before the given position in another region "parent".
Definition Builders.cpp:608
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Operation * cloneWithoutRegions(Operation &op, IRMapping &mapper)
Creates a deep copy of this operation but keep the operation regions empty.
Definition Builders.h:596
This class represents a single result from folding an operation.
This class represents an operand of an operation.
Definition Value.h:256
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Definition Value.cpp:231
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.
Definition Value.h:456
Operation * getOwner() const
Returns the operation that owns this result.
Definition Value.h:465
unsigned getResultNumber() const
Returns the number of this result.
Definition Value.h:468
A wrapper class that allows for printing an operation with a set of flags, useful to act as a "stream...
Definition Operation.h:1171
This class implements the operand iterators for the Operation class.
Definition ValueRange.h:44
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
OperandRange operand_range
Definition Operation.h:398
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
Definition Operation.h:255
auto getDiscardableAttrs()
Return a range of all of discardable attributes on this operation.
Definition Operation.h:540
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
Region * getParentRegion()
Returns the region to which the instruction belongs.
Definition Operation.h:247
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.
Definition Region.h:363
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.
Definition Region.h:26
Block & front()
Definition Region.h:65
Region * getParentRegion()
Return the region containing this region or nullptr if the region is attached to a top-level operatio...
Definition Region.cpp:45
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
Definition Region.h:234
Block & back()
Definition Region.h:64
bool empty()
Definition Region.h:60
unsigned getNumArguments()
Definition Region.h:136
iterator begin()
Definition Region.h:55
BlockArgument getArgument(unsigned i)
Definition Region.h:137
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 &region, 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.
Definition TypeRange.h:40
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
Definition Types.cpp:66
bool isIndex() const
Definition Types.cpp:56
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.
Definition ValueRange.h:392
type_range getTypes() const
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
user_range getUsers() const
Definition Value.h:218
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
Region * getParentRegion()
Return the Region in which this Value is defined.
Definition Value.cpp:39
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
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.
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
ParallelOp getParallelForInductionVarOwner(Value val)
Returns the parallel loop parent of an induction variable.
Definition SCF.cpp:3158
void buildTerminatedBody(OpBuilder &builder, Location loc)
Default callback for IfOp builders. Inserts a yield without arguments.
Definition SCF.cpp:93
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.
Definition SCF.cpp:821
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.
Definition SCF.cpp:2077
std::optional< llvm::APSInt > computeUbMinusLb(Value lb, Value ub, bool isSigned)
Helper function to compute the difference between two values.
Definition SCF.cpp:114
ForOp getForInductionVarOwner(Value val)
Returns the loop parent of an induction variable.
Definition SCF.cpp:678
SmallVector< Value > ValueVector
An owning vector of values, handy to return from functions.
Definition SCF.h:59
bool isShapePreserving(ForOp forOp, int64_t arg)
A simple, conservative analysis to determine if the loop is shape preserving.
Definition SCF.cpp:975
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...
Definition SCF.h:102
ForallOp getForallOpThreadIndexOwner(Value val)
Returns the ForallOp parent of an thread index variable.
Definition SCF.cpp:1461
SmallVector< Value > replaceAndCastForOpIterArg(RewriterBase &rewriter, scf::ForOp forOp, OpOperand &operand, Value replacement, const ValueTypeCastFnTy &castFn)
Definition SCF.cpp:910
LogicalResult promote(RewriterBase &rewriter, scf::ForallOp forallOp)
Promotes the loop body of a scf::ForallOp to its containing block.
Definition SCF.cpp:750
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.
Definition Matchers.h:490
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...
Definition Matchers.h:527
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.
Definition Utils.cpp:311
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
Definition LLVM.h:125
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:128
detail::constant_int_predicate_matcher m_One()
Matches a constant scalar / vector splat / tensor splat integer one.
Definition Matchers.h:478
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.
Definition Utils.cpp:114
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:123
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.
Definition Matchers.h:369
void visitUsedValuesDefinedAbove(Region &region, 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
Definition LLVM.h:155
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
Definition SCF.cpp:221
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.