[flang-commits] [flang] [flang][FIR][Mem2Reg] Add supoort for FIR. (PR #172808)

via flang-commits flang-commits at lists.llvm.org
Thu Dec 18 07:12:44 PST 2025


================
@@ -186,6 +186,33 @@ static mlir::Type wrapAllocaResultType(mlir::Type intype) {
   return fir::ReferenceType::get(intype);
 }
 
+llvm::SmallVector<mlir::MemorySlot> fir::AllocaOp::getPromotableSlots() {
+  // TODO: support promotion of allocas with LEN params or shape operands
+  if (hasLenParams() || hasShapeOperands())
+    return {};
+
+  return {mlir::MemorySlot{getResult(), getAllocatedType()}};
+}
+
+mlir::Value fir::AllocaOp::getDefaultValue(const mlir::MemorySlot &slot,
+                                           mlir::OpBuilder &builder) {
+  return fir::UndefOp::create(builder, getLoc(), slot.elemType);
+}
+
+void fir::AllocaOp::handleBlockArgument(const mlir::MemorySlot &slot,
+                                        mlir::BlockArgument argument,
+                                        mlir::OpBuilder &builder) {}
+
+std::optional<mlir::PromotableAllocationOpInterface>
+fir::AllocaOp::handlePromotionComplete(const mlir::MemorySlot &slot,
+                                       mlir::Value defaultValue,
+                                       mlir::OpBuilder &builder) {
+  if (defaultValue && defaultValue.use_empty())
+    defaultValue.getDefiningOp()->erase();
----------------
jeanPerier wrote:

Why is up to mem2reg to delete the value producer if it is not used?

I get that in the boring cases of unused allocas, this makes sense to delete the Undef, but the should this code check that this is a fir::UndefOp?

I would not want this to delete operation with side effects that may have produced the value like the call to foo in:

```
%temp = fir.alloca 
%x = call @foo()
%fir.store %x to %temp
! does nothing with temp
```

This may be worth adding as a test BTW.

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


More information about the flang-commits mailing list