[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:23:16 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,
----------------
SusanTan wrote:
If I understand correctly TRANSFER is indeed a kind of bitcast and gets lowered to function calls. The problem with the lowering is that before fir-to-memref:
```
// %h holds logical bits that originally came from TRANSFER payload.
%h = fir.allocmem !fir.logical<4>
%v = fir.load %h : !fir.heap<!fir.logical<4>>
fir.store %v to %dst : !fir.ref<!fir.logical<4>>
//TRANSFER (%dst)
```
because we can't lower !fir.heap\<\> type in FIRToMemRef, fir.load remain unconverted and we are left with:
```
%h = fir.allocmem !fir.logical<4>
%v = fir.load %h : !fir.heap<!fir.logical<4>>
%i = fir.convert %v : (!fir.logical<4>) -> i32 // normalizes to 0/1
%m = fir.convert %dst : (!fir.ref<!fir.logical<4>>) -> memref<i32>
memref.store %i, %m[] : memref<i32>
//TRANSFER (%m)
```
So the solution I came up with is first, we will need to convert the fir.load on heap type to memref.load. From there, eliminate any additional converts that still might narrow the logical.
Alternative we can try specializing the lowering of `fir.convert logical->i<width>`. We already distinguish fir.convert that are specifically used by FIRToMemRef by detecting if it's converted to/from a memref type, but this isn't enough because not all such converts are converted to memref types. Some like in this situation are just marshaled to standard types (i32). We don't have logic to detect this yet and in order to detect this, we will have to add attributes to fir.convert to distinguish the fir.convert used for FIRToMemRef lowering and the rest. From there, we can do special lowering of logical to i32 castings.
I'm happy to explore other ways to resolve this issue as well!
https://github.com/llvm/llvm-project/pull/187721
More information about the flang-commits
mailing list