Skip to content

[flang][fir] Add fir.if -> scf.if and add filecheck test file #142965

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 3 commits into from
Jun 10, 2025

Conversation

StarryCSF
Copy link
Contributor

Copy link

github-actions bot commented Jun 5, 2025

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 Jun 5, 2025
@llvmbot
Copy link
Member

llvmbot commented Jun 5, 2025

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

Author: Q (StarryCSF)

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/142965.diff

2 Files Affected:

  • (modified) flang/lib/Optimizer/Transforms/FIRToSCF.cpp (+56-2)
  • (added) flang/test/Fir/FirToSCF/if.fir (+97)
diff --git a/flang/lib/Optimizer/Transforms/FIRToSCF.cpp b/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
index f06ad2db90d55..12a6d3aad4c0d 100644
--- a/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
+++ b/flang/lib/Optimizer/Transforms/FIRToSCF.cpp
@@ -87,13 +87,67 @@ struct DoLoopConversion : public OpRewritePattern<fir::DoLoopOp> {
     return success();
   }
 };
+
+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();
+    mlir::detail::TypedValue<mlir::IntegerType> condition = ifOp.getCondition();
+    ValueTypeRange<ResultRange> resultTypes = ifOp.getResultTypes();
+    bool hasResult = !resultTypes.empty();
+    auto scfIfOp = rewriter.create<scf::IfOp>(loc, resultTypes, condition,
+                                              !ifOp.getElseRegion().empty());
+    // then region
+    assert(!ifOp.getThenRegion().empty() && "must have then region");
+    auto &firThenBlock = ifOp.getThenRegion().front();
+    auto &scfThenBlock = scfIfOp.getThenRegion().front();
+    auto &firThenOps = firThenBlock.getOperations();
+    mlir::Operation *firThenTerminator = firThenBlock.getTerminator();
+
+    rewriter.setInsertionPointToStart(&scfThenBlock);
+    // not splice terminator
+    scfThenBlock.getOperations().splice(scfThenBlock.begin(), firThenOps,
+                                        firThenOps.begin(),
+                                        std::prev(firThenOps.end()));
+    // create terminator scf.yield
+    if (hasResult) {
+      rewriter.setInsertionPointToEnd(&scfThenBlock);
+      mlir::OperandRange thenResults = firThenTerminator->getOperands();
+      rewriter.create<scf::YieldOp>(firThenTerminator->getLoc(), thenResults);
+    }
+
+    // else region
+    if (!ifOp.getElseRegion().empty()) {
+      auto &firElseBlock = ifOp.getElseRegion().front();
+      auto &scfElseBlock = scfIfOp.getElseRegion().front();
+      auto &firElseOps = firElseBlock.getOperations();
+      mlir::Operation *firElseTerminator = firElseBlock.getTerminator();
+
+      rewriter.setInsertionPointToStart(&scfElseBlock);
+      scfElseBlock.getOperations().splice(scfElseBlock.begin(), firElseOps,
+                                          firElseOps.begin(),
+                                          std::prev(firElseOps.end()));
+
+      if (hasResult) {
+        rewriter.setInsertionPointToEnd(&scfElseBlock);
+        mlir::OperandRange elseResults = firElseTerminator->getOperands();
+        rewriter.create<scf::YieldOp>(firElseTerminator->getLoc(), elseResults);
+      }
+    }
+
+    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..8885b0343095d
--- /dev/null
+++ b/flang/test/Fir/FirToSCF/if.fir
@@ -0,0 +1,97 @@
+
+// RUN: fir-opt %s --fir-to-scf | FileCheck %s
+
+// CHECK: func.func @_QFPtest_only(
+// CHECK:   %[[ARG0:.*]]: !fir.ref<tuple<!fir.ref<f32>>>) {
+// CHECK:   %[[VAL_0:.*]] = arith.constant 1 : i32
+// CHECK:   %[[VAL_1:.*]] = arith.constant false
+// CHECK:   %[[VAL_2:.*]] = arith.constant 0 : i32
+// CHECK:   scf.if %[[VAL_1:.*]] {
+// CHECK:    %[[VAL_3:.*]] = arith.addi %[[VAL_2:.*]], %[[VAL_0:.*]] : i32
+// CHECK:   }
+// CHECK:   return
+// CHECK:   }
+func.func @_QFPtest_only(%arg0: !fir.ref<tuple<!fir.ref<f32>>>) {
+    %c1_i32 = arith.constant 1 : i32
+    %false = arith.constant false
+    %c0_i32 = arith.constant 0 : i32
+    fir.if %false {
+      %0 = arith.addi %c0_i32, %c1_i32 : i32
+    }
+    return
+  }
+
+// CHECK: func.func @_QFPtest_else(
+// CHECK:   %[[ARG0:.*]]: !fir.ref<tuple<!fir.ref<f32>>>) {
+// CHECK:   %[[VAL_0:.*]] = arith.constant 1 : i32
+// CHECK:   %[[VAL_1:.*]] = arith.constant false
+// CHECK:   %[[VAL_2:.*]] = arith.constant 0 : i32
+// CHECK:   %[[VAL_3:.*]] = fir.dummy_scope : !fir.dscope
+// CHECK:   %[[VAL_4:.*]] = fir.coordinate_of %[[ARG0:.*]], %[[VAL_2:.*]] : (!fir.ref<tuple<!fir.ref<f32>>>, i32) -> !fir.llvm_ptr<!fir.ref<f32>>
+// CHECK:   %[[VAL_5:.*]] = fir.load %[[VAL_4:.*]] : !fir.llvm_ptr<!fir.ref<f32>>
+// CHECK:   %[[VAL_6:.*]] = fir.declare %[[VAL_5:.*]] {fortran_attrs = #fir.var_attrs<host_assoc>, uniq_name = "_QFEx"} : (!fir.ref<f32>) -> !fir.ref<f32>
+// CHECK:   %[[VAL_7:.*]] = fir.address_of(@_QFFtest_elseEsum) : !fir.ref<i32>
+// CHECK:   %[[VAL_10:.*]] = fir.declare %[[VAL_7:.*]] {uniq_name = "_QFFtest_elseEsum"} : (!fir.ref<i32>) -> !fir.ref<i32>
+// CHECK:   scf.if %[[VAL_1:.*]] {
+// CHECK:     %[[VAL_8:.*]] = fir.load %[[VAL_10:.*]] : !fir.ref<i32>
+// CHECK:     %[[VAL_9:.*]] = arith.addi %[[VAL_8:.*]], %[[VAL_0:.*]] : i32
+// CHECK:     fir.store %[[VAL_9:.*]] to %[[VAL_10:.*]] : !fir.ref<i32>
+// CHECK:   } else {
+// CHECK:     %[[VAL_8:.*]] = fir.load %[[VAL_10:.*]] : !fir.ref<i32>
+// CHECK:     %[[VAL_9:.*]] = arith.addi %[[VAL_8:.*]], %c1_i32 : i32
+// CHECK:     fir.store %[[VAL_9:.*]] to %[[VAL_10:.*]] : !fir.ref<i32>
+// CHECK:   }
+// CHECK:   return
+// CHECK: }
+func.func  @_QFPtest_else(%arg0: !fir.ref<tuple<!fir.ref<f32>>> {}) attributes {} {
+  %c1_i32 = arith.constant 1 : i32
+  %false = arith.constant false
+  %c0_i32 = arith.constant 0 : i32
+  %0 = fir.dummy_scope : !fir.dscope
+  %1 = fir.coordinate_of %arg0, %c0_i32 : (!fir.ref<tuple<!fir.ref<f32>>>, i32) -> !fir.llvm_ptr<!fir.ref<f32>>
+  %2 = fir.load %1 : !fir.llvm_ptr<!fir.ref<f32>>
+  %3 = fir.declare %2 {fortran_attrs = #fir.var_attrs<host_assoc>, uniq_name = "_QFEx"} : (!fir.ref<f32>) -> !fir.ref<f32>
+  %4 = fir.address_of(@_QFFtest_elseEsum) : !fir.ref<i32>
+  %5 = fir.declare %4 {uniq_name = "_QFFtest_elseEsum"} : (!fir.ref<i32>) -> !fir.ref<i32>
+  fir.if %false {
+    %6 = fir.load %5 : !fir.ref<i32>
+    %7 = arith.addi %6, %c1_i32 : i32
+    fir.store %7 to %5 : !fir.ref<i32>
+  } else {
+    %6 = fir.load %5 : !fir.ref<i32>
+    %7 = arith.addi %6, %c1_i32 : i32
+    fir.store %7 to %5 : !fir.ref<i32>
+  }
+  return
+}
+
+// CHECK-LABEL:     func.func @test_two_result() {
+// CHECK:           %[[VAL_0:.*]] = arith.constant 10 : i32
+// CHECK:           %[[VAL_1:.*]] = arith.constant 5 : i32
+// CHECK:           %[[VAL_2:.*]] = arith.cmpi sgt, %[[VAL_0:.*]], %[[VAL_1:.*]] : i32
+// CHECK:           %[[VAL_3:.*]] = arith.constant 3.140000e+00 : f32
+// CHECK:           %[[VAL_4:.*]] = arith.constant 2.710000e+00 : f32
+// CHECK:           %[[VAL_5:.*]] = arith.constant 1.000000e+00 : f32
+// CHECK:           %[[VAL_6:.*]] = arith.constant 2.000000e+00 : f32
+// CHECK:           %[[RES:[0-9]+]]:2 = scf.if %[[VAL_2:.*]] -> (f32, f32) {
+// CHECK:            scf.yield %[[VAL_3:.*]], %[[VAL_4:.*]] : f32, f32
+// CHECK:            } else {
+// CHECK:              scf.yield %[[VAL_5:.*]], %[[VAL_6:.*]] : f32, f32
+// CHECK:            }
+// CHECK:            return 
+// CHECK:            }
+func.func @test_two_result() {
+  %c10_i32 = arith.constant 10 : i32
+  %c5_i32 = arith.constant 5 : i32
+  %cmp = arith.cmpi sgt, %c10_i32, %c5_i32 : i32
+  %c3_14_f32 = arith.constant 3.14 : f32
+  %c2_71_f32 = arith.constant 2.71 : f32
+  %c1_0_f32 = arith.constant 1.0 : f32
+  %c2_0_f32 = arith.constant 2.0 : f32
+  %x, %y = fir.if %cmp -> (f32, f32) {
+    fir.result %c3_14_f32, %c2_71_f32 : f32, f32
+  } else {
+    fir.result %c1_0_f32, %c2_0_f32 : f32, f32
+  }
+  return
+}

@tblah
Copy link
Contributor

tblah commented Jun 5, 2025

See my comment on the old PR

@tblah tblah requested review from tblah and NexMing June 5, 2025 14:27
Copy link
Contributor

@NexMing NexMing left a comment

Choose a reason for hiding this comment

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

LGTM

@StarryCSF StarryCSF requested a review from clementval June 6, 2025 07:54
Copy link

github-actions bot commented Jun 6, 2025

✅ With the latest revision this PR passed the C/C++ code formatter.

Copy link
Contributor

@rscottmanley rscottmanley left a comment

Choose a reason for hiding this comment

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

LGTM

@StarryCSF StarryCSF requested a review from NexMing June 9, 2025 08:46
Copy link
Contributor

@vzakhari vzakhari left a comment

Choose a reason for hiding this comment

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

Thank you for the update!

@terapines-osc-circt terapines-osc-circt merged commit 823750d into llvm:main Jun 10, 2025
7 checks passed
Copy link

@StarryCSF 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!

rorth pushed a commit to rorth/llvm-project that referenced this pull request Jun 11, 2025
tomtor pushed a commit to tomtor/llvm-project that referenced this pull request Jun 14, 2025
lei137 added a commit to lei137/llvm-project that referenced this pull request Jun 23, 2025
@lei137
Copy link
Contributor

lei137 commented Jun 23, 2025

Sorry. I need to revert this patch since the builder flang-ppc64 have been red for 4 days due to the new tc segfaults on it:

$ fir-opt  --fir-to-scf flang/test/Fir/FirToSCF/if.fir 
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace.
Stack dump:
0.      Program arguments: fir-opt --fir-to-scf flang/test/Fir/FirToSCF/if.fir --fir-to-scf
Segmentation fault (core dumped)

lei137 added a commit that referenced this pull request Jun 23, 2025
…142965)" (#145345)

This reverts commit 823750d.

Test causes segfault on aix flang builder.
DrSergei pushed a commit to DrSergei/llvm-project that referenced this pull request Jun 24, 2025
…lvm#142965)" (llvm#145345)

This reverts commit 823750d.

Test causes segfault on aix flang builder.
anthonyhatran pushed a commit to anthonyhatran/llvm-project that referenced this pull request Jun 26, 2025
…lvm#142965)" (llvm#145345)

This reverts commit 823750d.

Test causes segfault on aix flang builder.
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.

9 participants