Skip to content

[flang][fir]: Add conversion of fir.if to scf.if. #149959

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 25, 2025

Conversation

terapines-osc-mlir
Copy link
Contributor

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added flang Flang issues not falling into any other category flang:fir-hlfir labels Jul 22, 2025
@llvmbot
Copy link
Member

llvmbot commented Jul 22, 2025

@llvm/pr-subscribers-flang-fir-hlfir

Author: Terapines MLIR (terapines-osc-mlir)

Changes

This commmit is a supplement for #140374.
RFC:https://discourse.llvm.org/t/rfc-add-fir-affine-optimization-fir-pass-pipeline/86190/6


Full diff: https://github.com/llvm/llvm-project/pull/149959.diff

2 Files Affected:

  • (modified) flang/lib/Optimizer/Transforms/FIRToSCF.cpp (+48-2)
  • (added) flang/test/Fir/FirToSCF/if.fir (+57)
diff --git a/flang/lib/Optimizer/Transforms/FIRToSCF.cpp b/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
index d7d1865bc56ba..ad9d8ec136b22 100644
--- a/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
+++ b/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
@@ -87,13 +87,59 @@ struct DoLoopConversion : public OpRewritePattern<fir::DoLoopOp> {
     return success();
   }
 };
+
+void copyBlocksAndTransformResult(PatternRewriter &rewriter, Block &srcBlock,
+                                  Block &dstBlock) {
+  Operation *srcTerminator = srcBlock.getTerminator();
+  auto resultOp = dyn_cast<fir::ResultOp>(srcTerminator);
+
+  /// Do a simple copy when fir.result is not used.
+  if (resultOp == nullptr) {
+    dstBlock.getOperations().splice(dstBlock.begin(), srcBlock.getOperations());
+    return;
+  }
+
+  /// Drop the fir.result and insert a scf.yield in the end of the block
+  dstBlock.getOperations().splice(dstBlock.begin(), srcBlock.getOperations(),
+                                  srcBlock.begin(), std::prev(srcBlock.end()));
+
+  if (!resultOp->getOperands().empty()) {
+    rewriter.setInsertionPointToEnd(&dstBlock);
+    rewriter.create<scf::YieldOp>(resultOp.getLoc(), resultOp.getOperands());
+  }
+
+  rewriter.eraseOp(srcTerminator);
+}
+
+struct IfConversion : public OpRewritePattern<fir::IfOp> {
+  using OpRewritePattern<fir::IfOp>::OpRewritePattern;
+  LogicalResult matchAndRewrite(fir::IfOp ifOp,
+                                PatternRewriter &rewriter) const override {
+    mlir::Location loc = ifOp.getLoc();
+    bool hasElse = !ifOp.getElseRegion().empty();
+    auto scfIfOp = rewriter.create<scf::IfOp>(loc, ifOp->getResultTypes(),
+                                              ifOp.getCondition(), hasElse);
+
+    copyBlocksAndTransformResult(rewriter, ifOp.getThenRegion().front(),
+                                 scfIfOp.getThenRegion().front());
+
+    if (hasElse) {
+      copyBlocksAndTransformResult(rewriter, ifOp.getElseRegion().front(),
+                                   scfIfOp.getElseRegion().front());
+    }
+
+    scfIfOp->setAttrs(ifOp->getAttrs());
+    rewriter.replaceOp(ifOp, scfIfOp);
+    return success();
+  }
+};
 } // namespace
 
 void FIRToSCFPass::runOnOperation() {
   RewritePatternSet patterns(&getContext());
-  patterns.add<DoLoopConversion>(patterns.getContext());
+  patterns.add<DoLoopConversion, IfConversion>(patterns.getContext());
   ConversionTarget target(getContext());
-  target.addIllegalOp<fir::DoLoopOp>();
+  target.addIllegalOp<fir::DoLoopOp, fir::IfOp>();
   target.markUnknownOpDynamicallyLegal([](Operation *) { return true; });
   if (failed(
           applyPartialConversion(getOperation(), target, std::move(patterns))))
diff --git a/flang/test/Fir/FirToSCF/if.fir b/flang/test/Fir/FirToSCF/if.fir
new file mode 100644
index 0000000000000..fbb2f179411cf
--- /dev/null
+++ b/flang/test/Fir/FirToSCF/if.fir
@@ -0,0 +1,57 @@
+// RUN: fir-opt %s --fir-to-scf | FileCheck %s
+
+// CHECK-LABEL:   func.func @test_only(
+// CHECK-SAME:      %[[ARG0:.*]]: i1, %[[ARG1:.*]]: i32) {
+// CHECK:           scf.if %[[ARG0]] {
+// CHECK:             %[[VAL_1:.*]] = arith.addi %[[ARG1]], %[[ARG1]] : i32
+// CHECK:           }
+// CHECK:           return
+// CHECK:         }
+func.func @test_only(%arg0 : i1, %arg1 : i32) {
+  fir.if %arg0 {
+    %0 = arith.addi %arg1, %arg1 : i32
+  }
+  return
+}
+
+// CHECK-LABEL:   func.func @test_else()   {
+// CHECK:           %[[VAL_1:.*]] = arith.constant false
+// CHECK:           %[[VAL_2:.*]] = arith.constant 2 : i32
+// CHECK:           scf.if %[[VAL_1]] {
+// CHECK:             %[[VAL_3:.*]] = arith.constant 3 : i32
+// CHECK:           } else {
+// CHECK:             %[[VAL_3:.*]] = arith.constant 3 : i32
+// CHECK:           }
+// CHECK:           return
+// CHECK:         }
+func.func @test_else()   {
+  %false = arith.constant false
+  %1 = arith.constant 2 : i32
+  fir.if %false {
+    %2 = arith.constant 3 : i32
+  } else {
+    %3 = arith.constant 3 : i32
+  }
+  return
+}
+
+// CHECK-LABEL:   func.func @test_two_result()  {
+// CHECK:           %[[VAL_1:.*]] = arith.constant 2.000000e+00 : f32
+// CHECK:           %[[VAL_2:.*]] = arith.constant false
+// CHECK:           %[[RES:[0-9]+]]:2 = scf.if %[[VAL_2]] -> (f32, f32) {
+// CHECK:             scf.yield %[[VAL_1]], %[[VAL_1]] : f32, f32
+// CHECK:           } else {
+// CHECK:             scf.yield %[[VAL_1]], %[[VAL_1]] : f32, f32
+// CHECK:           }
+// CHECK:           return
+// CHECK:         }
+func.func @test_two_result() {
+  %1 = arith.constant 2.0 : f32
+  %cmp = arith.constant false
+  %x, %y = fir.if %cmp -> (f32, f32) {
+    fir.result %1, %1 : f32, f32
+  } else {
+    fir.result %1, %1 : f32, f32
+  }
+  return
+}
\ No newline at end of file

@terapines-osc-mlir terapines-osc-mlir force-pushed the firif-to-scfif branch 2 times, most recently from 358ac2c to 9ef83e5 Compare July 22, 2025 05:43
@clementval clementval requested a review from rscottmanley July 22, 2025 05:46
@terapines-osc-mlir terapines-osc-mlir force-pushed the firif-to-scfif branch 2 times, most recently from 77baecd to de4de9c Compare July 22, 2025 08:47
Copy link
Contributor

@tblah tblah left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM thanks!


if (!resultOp->getOperands().empty()) {
rewriter.setInsertionPointToEnd(&dstBlock);
rewriter.create<scf::YieldOp>(resultOp.getLoc(), resultOp.getOperands());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this old syntax is being replaced with YieldOp::create(rewriter, ....). For example, see #149917

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! All rewriter.create<T>(...)s are replaced by T::create(rewriter, ...)s.

@@ -87,13 +87,52 @@ struct DoLoopConversion : public OpRewritePattern<fir::DoLoopOp> {
return success();
}
};

void copyBlocksAndTransformResult(PatternRewriter &rewriter, Block &srcBlock,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be a lambda instead

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this should be a lambda instead

Copying block and transforming terminator is a common operation which can be shared by other functions in this file. Since all Fir to SCF transforms will be written in this file, I would like to keep this function this way for now.

@rscottmanley
Copy link
Contributor

The title of this MR confused me for a minute, can it just be "add conversion of fir.if to scf.if"? or "convert fir.if in FIRToSCF"

@terapines-osc-mlir terapines-osc-mlir force-pushed the firif-to-scfif branch 2 times, most recently from 3f548d1 to 0b0eef6 Compare July 23, 2025 02:35
@terapines-osc-mlir
Copy link
Contributor Author

The title of this MR confused me for a minute, can it just be "add conversion of fir.if to scf.if"? or "convert fir.if in FIRToSCF"

Thanks! Commit message is changed to what you had suggested.

@NexMing NexMing changed the title [flang][fir]: New optimizer transform of fir.if to scf.if. [flang][fir]: Add conversion of fir.if to scf.if. Jul 23, 2025
@NexMing NexMing changed the title [flang][fir]: Add conversion of fir.if to scf.if. [flang][fir]: Add conversion of fir.if to scf.if. Jul 23, 2025
@NexMing NexMing merged commit 8e9ca05 into llvm:main Jul 25, 2025
9 checks passed
Copy link

@terapines-osc-mlir Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

mahesh-attarde pushed a commit to mahesh-attarde/llvm-project that referenced this pull request Jul 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
flang:fir-hlfir flang Flang issues not falling into any other category
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants