[flang-commits] [flang] [flang] add an optimization to remove fir.convert usage in FIRToMemRef (PR #187721)

Susan Tan ス-ザン タン via flang-commits flang-commits at lists.llvm.org
Fri Mar 20 09:17:09 PDT 2026


================
@@ -1010,6 +1010,21 @@ void FIRToMemRef::rewriteStoreOp(fir::StoreOp store, PatternRewriter &rewriter,
   Value value = store.getValue();
   rewriter.setInsertionPointAfter(store);
 
+  // Small local optimization that avoids the round-trip:
+  //   %25 = memref.load ... : memref<i32>
+  //   %26 = fir.convert %25 : (i32) -> !fir.logical<4>   // from load rewrite
+  //   %27 = fir.convert %26 : (!fir.logical<4>) -> i32   // from store rewrite
+  //   memref.store %27, ... : memref<i32>
+  // which would normalize the loaded value to 1 and break TRANSFER-like flows,
+  // e.g. transfer(transfer(i, .true.), 0).
+  if (auto to = value.getDefiningOp<fir::ConvertOp>()) {
+    Value raw = to.getValue();
+    if (auto memrefTy = dyn_cast<MemRefType>(converted.getType()))
----------------
SusanTan wrote:

Yes that's the exact problem I'm trying to avoid... because it is narrowing and in the TRANSFER case it shouldn't be narrowed. This is the example:
```
program p
  implicit none
  integer :: i, j
  i = 42
  j = transfer(transfer(i, .true.), 0)
  print *, j
end program
```
the print should be original number 42 instead of 1. The narrowing using fir.convert (which was meant for bit casting in this scenario) made the number to change to 1.

This MR alone doesn't really solve the problem completely and there will be a followup one.

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


More information about the flang-commits mailing list