[Mlir-commits] [mlir] [mlir][scf] Uplift `scf.while` to `scf.for` (PR #76108)

Mehdi Amini llvmlistbot at llvm.org
Tue Apr 2 04:33:05 PDT 2024


================
@@ -0,0 +1,238 @@
+//===- UpliftWhileToFor.cpp - scf.while to scf.for loop uplifting ---------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Transforms SCF.WhileOp's into SCF.ForOp's.
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Dialect/SCF/Transforms/Passes.h"
+
+#include "mlir/Dialect/Arith/IR/Arith.h"
+#include "mlir/Dialect/SCF/IR/SCF.h"
+#include "mlir/Dialect/SCF/Transforms/Patterns.h"
+#include "mlir/IR/Dominance.h"
+#include "mlir/IR/PatternMatch.h"
+#include "mlir/Transforms/GreedyPatternRewriteDriver.h"
+
+namespace mlir {
+#define GEN_PASS_DEF_TESTSCFUPLIFTWHILETOFOR
+#include "mlir/Dialect/SCF/Transforms/Passes.h.inc"
+} // namespace mlir
+
+using namespace mlir;
+
+namespace {
+struct UpliftWhileOp : public OpRewritePattern<scf::WhileOp> {
+  using OpRewritePattern::OpRewritePattern;
+
+  LogicalResult matchAndRewrite(scf::WhileOp loop,
+                                PatternRewriter &rewriter) const override {
+    Block *beforeBody = loop.getBeforeBody();
+    if (!llvm::hasSingleElement(beforeBody->without_terminator()))
+      return rewriter.notifyMatchFailure(loop, "Loop body must have single op");
+
+    auto cmp = dyn_cast<arith::CmpIOp>(beforeBody->front());
+    if (!cmp)
+      return rewriter.notifyMatchFailure(loop,
+                                         "Loop body must have single cmp op");
+
+    scf::ConditionOp beforeTerm = loop.getConditionOp();
+    if (!cmp->hasOneUse() && beforeTerm.getCondition() == cmp.getResult())
+      return rewriter.notifyMatchFailure(loop, [&](Diagnostic &diag) {
+        diag << "Expected single condiditon use: " << *cmp;
----------------
joker-eph wrote:

```suggestion
        diag << "Expected single condition use: " << *cmp;
```

https://github.com/llvm/llvm-project/pull/76108


More information about the Mlir-commits mailing list