[llvm-branch-commits] [flang] [flang] Track character temporary lifetimes for safe stack placement (PR #239312)

via llvm-branch-commits llvm-branch-commits at lists.llvm.org
Thu Nov 5 09:48:38 PST 2026


https://github.com/jeanPerier created https://github.com/llvm/llvm-project/pull/239312

Scalar hlfir.expr are currently never given hlfir.destroy and are always lowered as alloca, even when those alloca have dynamic length that pins them into unstructured control flow loops not surrounded by stack save/restore, leading to potential stack to grow on each iteration and to potential stack overflow.

Emit hlfir.destroy for them, add an explicit cleanup region to hlfir.yield_element, and preserve both through array constructor lowering, elemental inlining, WHERE lowering and bufferization, which now allocates these buffers with fir.allocmem. When such an allocation cannot be hoisted out of the loop, reclaim its stack space with one stacksave/stackrestore pair per block. Allocation placement then keeps these temporaries on the stack in every mode (except under -fdynamic-heap-array which matches the current behavior).

Note: an alternative would be to have the stack to heap promotion always promote allocation that it finds inside CFG cycles without stack save/restore to heap, but the final IR is less clean than using  destroy because it fallback to some indirect pointer bookkeeping at the function level. Also, it seems to me that the contract of hlfir.expr so far is that they should have matching hlfir.destroy, so it seems cleaner to align character. Please feel free to disagree.

Assisted-by: AI

>From 373ee32a032f056feb8bcc5e70bb2171329f0502 Mon Sep 17 00:00:00 2001
From: Jean Perier <jperier at nvidia.com>
Date: Thu, 5 Nov 2026 01:38:14 -0800
Subject: [PATCH] [flang] Track character temporary lifetimes for safe stack
 placement

Dynamic character expression buffers could grow the stack on every
iteration of an unstructured loop because their lifetimes were hidden
from allocation placement. Emit hlfir.destroy for them, add an explicit
cleanup region to hlfir.yield_element, and preserve both through array
constructor lowering, elemental inlining, WHERE lowering and
bufferization, which now allocates these buffers with fir.allocmem.
When such an allocation cannot be hoisted out of the loop, reclaim its
stack space with one stacksave/stackrestore pair per block. Allocation
placement then keeps these temporaries on the stack in every mode,
including offload regions (except under -fdynamic-heap-array).
---
 .../flang/Optimizer/Builder/Character.h       |  24 +-
 .../flang/Optimizer/Builder/HLFIRTools.h      |  17 +-
 .../include/flang/Optimizer/HLFIR/HLFIROps.td |  26 +-
 .../Optimizer/Support/AllocationPolicy.h      |   8 +-
 flang/lib/Lower/ConvertArrayConstructor.cpp   |  31 +--
 flang/lib/Lower/ConvertCall.cpp               |  29 ++-
 flang/lib/Lower/ConvertExprToHLFIR.cpp        | 238 ++++++++++--------
 flang/lib/Optimizer/Builder/CMakeLists.txt    |   1 +
 flang/lib/Optimizer/Builder/Character.cpp     |  33 +--
 flang/lib/Optimizer/Builder/HLFIRTools.cpp    | 114 ++++++---
 flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp     |   4 +
 .../HLFIR/Transforms/BufferizeHLFIR.cpp       |  75 ++++--
 .../HLFIR/Transforms/InlineElementals.cpp     |  33 +++
 .../LowerHLFIROrderedAssignments.cpp          |  35 ++-
 .../Transforms/OptimizedBufferization.cpp     |   9 +-
 .../Transforms/SimplifyHLFIRIntrinsics.cpp    |  40 +--
 .../Optimizer/Support/AllocationPolicy.cpp    |  13 +
 .../Transforms/AllocationPlacement.cpp        |  20 +-
 .../lib/Optimizer/Transforms/StackArrays.cpp  |  84 ++++---
 flang/lib/Optimizer/Transforms/StackArrays.h  |  18 +-
 .../Fir/allocation-placement-pipeline.fir     |  29 ++-
 flang/test/HLFIR/as_expr-codegen.fir          |   9 +-
 flang/test/HLFIR/associate-codegen.fir        |  26 +-
 flang/test/HLFIR/bufferize-conditional.fir    |  26 +-
 flang/test/HLFIR/bufferize01.fir              |   4 +-
 .../HLFIR/char_extremum-bufferization.fir     |  76 +++---
 .../HLFIR/character-expression-lifetimes.fir  |  36 +++
 flang/test/HLFIR/concat-bufferization.fir     |  42 ++--
 flang/test/HLFIR/destroy-codegen.fir          |   7 +-
 .../HLFIR/element-codegen-issue-118922.fir    |   4 +-
 flang/test/HLFIR/elemental-codegen.fir        |  27 +-
 flang/test/HLFIR/elemental-shallow-copy.fir   |   9 +-
 flang/test/HLFIR/elemental.fir                |  16 +-
 flang/test/HLFIR/get_length_codegen.fir       |   2 +-
 .../HLFIR/inline-elemental-cleanup-cfg.fir    | 132 ++++++++++
 flang/test/HLFIR/inline-elemental.fir         |  30 +++
 flang/test/HLFIR/no_reassoc-codegen.fir       |   5 +-
 .../where-element-cleanup.fir                 |  53 ++++
 flang/test/HLFIR/set_length-codegen.fir       |   9 +-
 .../simplify-hlfir-intrinsics-eoshift.fir     |   4 +-
 .../HLFIR/array-ctor-as-elemental-nested.f90  |   3 +-
 .../Lower/HLFIR/array-ctor-as-elemental.f90   |  20 +-
 .../HLFIR/character-expression-cleanup.f90    |  50 ++++
 flang/test/Lower/HLFIR/charconvert.f90        |  17 +-
 .../elemental-call-vector-subscripts.f90      |  85 +++++++
 .../implicit-type-conversion-allocatable.f90  |   3 +-
 flang/test/Lower/achar.f90                    |   3 +-
 flang/test/Lower/array-elemental-calls-2.f90  |   6 +-
 .../array-elemental-calls-char-byval.f90      |  15 +-
 .../array-elemental-calls-char-dynamic.f90    |  16 +-
 .../test/Lower/array-elemental-calls-char.f90 |   6 +-
 flang/test/Lower/charconvert.f90              |  10 +-
 .../character-expression-storage.f90          | 142 +++++++++++
 .../character-temporary-placement.fir         |  86 +++++++
 .../stack-arrays-block-lifetime.fir           | 105 ++++++++
 .../stack-arrays-crossing-lifetimes.fir       |  33 +++
 flang/test/Transforms/stack-arrays.fir        |   6 +-
 57 files changed, 1565 insertions(+), 439 deletions(-)
 create mode 100644 flang/test/HLFIR/character-expression-lifetimes.fir
 create mode 100644 flang/test/HLFIR/inline-elemental-cleanup-cfg.fir
 create mode 100644 flang/test/HLFIR/order_assignments/where-element-cleanup.fir
 create mode 100644 flang/test/Lower/HLFIR/character-expression-cleanup.f90
 create mode 100644 flang/test/Transforms/character-expression-storage.f90
 create mode 100644 flang/test/Transforms/character-temporary-placement.fir
 create mode 100644 flang/test/Transforms/stack-arrays-block-lifetime.fir
 create mode 100644 flang/test/Transforms/stack-arrays-crossing-lifetimes.fir

diff --git a/flang/include/flang/Optimizer/Builder/Character.h b/flang/include/flang/Optimizer/Builder/Character.h
index 658118eddcc909..613cb80e5ba9b5 100644
--- a/flang/include/flang/Optimizer/Builder/Character.h
+++ b/flang/include/flang/Optimizer/Builder/Character.h
@@ -63,13 +63,15 @@ class CharacterExprHelper {
   void createAssign(const fir::ExtendedValue &lhs,
                     const fir::ExtendedValue &rhs);
 
-  /// Create lhs // rhs in temp obtained with fir.alloca
+  /// Create lhs // rhs in a stack or heap temporary.
   fir::CharBoxValue createConcatenate(const fir::CharBoxValue &lhs,
-                                      const fir::CharBoxValue &rhs);
+                                      const fir::CharBoxValue &rhs,
+                                      bool useHeap = false);
 
-  /// Create {max,min}(lhs,rhs) in temp obtained with fir.alloca
-  fir::CharBoxValue
-  createCharExtremum(bool predIsMin, llvm::ArrayRef<fir::CharBoxValue> opCBVs);
+  /// Create {max,min}(lhs,rhs) in a stack or heap temporary.
+  fir::CharBoxValue createCharExtremum(bool predIsMin,
+                                       llvm::ArrayRef<fir::CharBoxValue> opCBVs,
+                                       bool useHeap = false);
 
   /// LEN_TRIM intrinsic.
   mlir::Value createLenTrim(const fir::CharBoxValue &str);
@@ -93,8 +95,10 @@ class CharacterExprHelper {
   std::pair<mlir::Value, mlir::Value> createUnboxChar(mlir::Value boxChar);
 
   /// Allocate a temp of fir::CharacterType type and length len.
-  /// Returns related fir.ref<fir.array<? x fir.char<kind>>>.
-  fir::CharBoxValue createCharacterTemp(mlir::Type type, mlir::Value len);
+  /// Use heap storage when useHeap is true. The caller must then free the
+  /// returned temporary.
+  fir::CharBoxValue createCharacterTemp(mlir::Type type, mlir::Value len,
+                                        bool useHeap = false);
 
   /// Allocate a temp of compile time constant length.
   /// Returns related fir.ref<fir.array<len x fir.char<kind>>>.
@@ -235,10 +239,12 @@ std::pair<mlir::Value, mlir::Value>
 extractCharacterProcedureTuple(fir::FirOpBuilder &builder, mlir::Location loc,
                                mlir::Value tuple, bool openBoxProc = true);
 
+/// Convert into a temporary, using heap storage when useHeap is true. The
+/// caller must free the result when heap storage is requested.
 fir::CharBoxValue convertCharacterKind(fir::FirOpBuilder &builder,
                                        mlir::Location loc,
-                                       fir::CharBoxValue srcBoxChar,
-                                       int toKind);
+                                       fir::CharBoxValue srcBoxChar, int toKind,
+                                       bool useHeap = false);
 
 } // namespace fir::factory
 
diff --git a/flang/include/flang/Optimizer/Builder/HLFIRTools.h b/flang/include/flang/Optimizer/Builder/HLFIRTools.h
index ce99a370526213..6c5361bc3096c2 100644
--- a/flang/include/flang/Optimizer/Builder/HLFIRTools.h
+++ b/flang/include/flang/Optimizer/Builder/HLFIRTools.h
@@ -358,10 +358,13 @@ mlir::Type getVariableElementType(hlfir::Entity variable);
 /// type (that may be an hlfir.expr type).
 mlir::Type getEntityElementType(hlfir::Entity entity);
 
-using ElementalKernelGenerator = std::function<hlfir::Entity(
+using ElementalKernelResult =
+    std::pair<hlfir::Entity, std::optional<hlfir::CleanupFunction>>;
+using ElementalKernelGenerator = std::function<ElementalKernelResult(
     mlir::Location, fir::FirOpBuilder &, mlir::ValueRange)>;
 /// Generate an hlfir.elementalOp given call back to generate the element
-/// value at for each iteration.
+/// value for each iteration and its explicit cleanup, if any. The cleanup
+/// callback is emitted in the yield_element cleanup region.
 /// If exprType is specified, this will be the return type of the elemental op.
 /// If exprType is not specified, the resulting expression type is computed
 /// from the given \p elementType and \p shape, and the type is polymorphic
@@ -432,7 +435,8 @@ llvm::SmallVector<mlir::Value> genLoopNestWithReductions(
 /// Inline the body of an hlfir.elemental at the current insertion point
 /// given a list of one based indices. This generates the computation
 /// of one element of the elemental expression. Return the YieldElementOp
-/// whose value argument is the element value.
+/// whose value argument is the element value. The caller must emit or transfer
+/// its cleanup region after consuming that value, then erase the yield.
 /// The original hlfir::ElementalOp is left untouched.
 hlfir::YieldElementOp inlineElementalOp(mlir::Location loc,
                                         fir::FirOpBuilder &builder,
@@ -446,11 +450,16 @@ hlfir::YieldElementOp inlineElementalOp(mlir::Location loc,
 /// current context and uses values that have been cloned already. A callback is
 /// provided to indicate if an hlfir.apply inside the hlfir.elemental must be
 /// immediately replaced by the inlining of the applied hlfir.elemental.
+/// Collect callbacks for the cloned yield_element cleanup regions, preserving
+/// the mapping for each inlined instance. The caller must execute the callbacks
+/// in reverse order after consuming the result. An elemental_addr's own cleanup
+/// remains the caller's responsibility.
 mlir::Value inlineElementalOp(
     mlir::Location loc, fir::FirOpBuilder &builder,
     hlfir::ElementalOpInterface elemental, mlir::ValueRange oneBasedIndices,
     mlir::IRMapping &mapper,
-    const std::function<bool(hlfir::ElementalOp)> &mustRecursivelyInline);
+    const std::function<bool(hlfir::ElementalOp)> &mustRecursivelyInline,
+    llvm::SmallVectorImpl<hlfir::CleanupFunction> &cleanups);
 
 /// Generate an element-by-element assignment from \p rhs to \p lhs for arrays
 /// that are known not to alias. The assignment is performed using a loop nest
diff --git a/flang/include/flang/Optimizer/HLFIR/HLFIROps.td b/flang/include/flang/Optimizer/HLFIR/HLFIROps.td
index 16cf30ffcf0ebc..7b685bfda398ba 100644
--- a/flang/include/flang/Optimizer/HLFIR/HLFIROps.td
+++ b/flang/include/flang/Optimizer/HLFIR/HLFIROps.td
@@ -1128,7 +1128,7 @@ def hlfir_ElementalOp : hlfir_Op<"elemental",
 
       mlir::Region& getElementalRegion() { return getRegion(); }
       mlir::Value getElementEntity();
-      mlir::Region* getElementCleanup() { return nullptr; }
+      mlir::Region* getElementCleanup();
 
       /// Must this elemental be evaluated in order?
       bool isOrdered() { return !getUnordered(); }
@@ -1145,17 +1145,28 @@ def hlfir_ElementalOp : hlfir_Op<"elemental",
   let hasVerifier = 1;
 }
 
-def hlfir_YieldElementOp : hlfir_Op<"yield_element", [Terminator, HasParent<"ElementalOp">, Pure]> {
+def hlfir_YieldElementOp : hlfir_Op<"yield_element", [Terminator,
+    HasParent<"ElementalOp">,
+    SingleBlockImplicitTerminator<"fir::FirEndOp">,
+    RecursiveMemoryEffects]> {
   let summary = "Yield the elemental value in an ElementalOp";
   let description = [{
     Yield the element value of the current elemental expression iteration
     in an hlfir.elemental region. See hlfir.elemental description for an
-    example.
+    example. The optional cleanup region is executed after the element value
+    has been consumed. It explicitly describes the cleanup of temporaries
+    created by this iteration, including the yielded expression itself. There
+    is no implicit destruction of the yielded value.
+
+    When an elemental is inlined, this cleanup must follow the consumption of
+    its scalar result. When inlined into another elemental, it can be appended
+    to that elemental's yield cleanup.
   }];
 
   let arguments = (ins AnyType:$element_value);
+  let regions = (region MaxSizedRegion<1>:$cleanup);
 
-  let assemblyFormat = "$element_value attr-dict `:` type($element_value)";
+  let assemblyFormat = "$element_value attr-dict `:` type($element_value) custom<YieldOpCleanup>($cleanup)";
 }
 
 def hlfir_ApplyOp : hlfir_Op<"apply", [NoMemoryEffect, AttrSizedOperandSegments]> {
@@ -1230,10 +1241,9 @@ def hlfir_DestroyOp : hlfir_Op<"destroy", [MemoryEffects<[MemFree]>]> {
     is placed into a memory buffer, so that the library runtime
     can be called on it. The element type of the hlfir.expr must be
     derived type in this case.
-    It is not required to create an hlfir.destroy operation for and hlfir.expr
-    created inside an hlfir.elemental and returned in the hlfir.yield_element.
-    The last use of such expression is implicit and an hlfir.destroy could
-    not be emitted after the hlfir.yield_element since it is a terminator.
+    An expression created inside an hlfir.elemental and returned by its
+    hlfir.yield_element is destroyed in the yield's cleanup region, after
+    the element value has been consumed.
 
     Note that hlfir.destroy are currently generated by Fortran lowering that
     has a good view of the expression use contexts, but this will need to be
diff --git a/flang/include/flang/Optimizer/Support/AllocationPolicy.h b/flang/include/flang/Optimizer/Support/AllocationPolicy.h
index 43b6b7731928fc..f61864fb627589 100644
--- a/flang/include/flang/Optimizer/Support/AllocationPolicy.h
+++ b/flang/include/flang/Optimizer/Support/AllocationPolicy.h
@@ -116,7 +116,7 @@ bool shouldUseStackForCopyin(
     const AllocationSizeContext &sizeContext,
     std::optional<std::int64_t> alignment = std::nullopt);
 
-/// Facts about a single existing array allocation used to decide its placement.
+/// Facts about an existing allocation used to decide its placement.
 struct AllocationInfo : PendingAllocationInfo {
   /// The allocation operation (fir.alloca or fir.allocmem).
   mlir::Operation *op = nullptr;
@@ -124,6 +124,12 @@ struct AllocationInfo : PendingAllocationInfo {
   bool isCurrentlyOnStack = false;
 };
 
+/// Return true if \p info describes a scalar character expression buffer: a
+/// compiler temporary fir.allocmem of character type. Such buffers have
+/// explicit lifetimes but retain their historical stack storage independently
+/// of the array placement policy.
+bool isCharacterTemporary(const AllocationInfo &info);
+
 /// Size-based placement policy, usable before the allocation is created.
 /// Decides whether an allocation described by \p info should live on the stack,
 /// given the \p policy in effect and the per-function stack bytes already
diff --git a/flang/lib/Lower/ConvertArrayConstructor.cpp b/flang/lib/Lower/ConvertArrayConstructor.cpp
index a76527b4e74542..c01ddd6d4e71de 100644
--- a/flang/lib/Lower/ConvertArrayConstructor.cpp
+++ b/flang/lib/Lower/ConvertArrayConstructor.cpp
@@ -234,32 +234,11 @@ class AsElementalStrategy : public StrategyBase {
       elementResult =
           builder.createConvert(loc, exprType.getElementType(), elementResult);
 
-    // The clean-ups associated with the implied-do body operations
-    // must be initiated before the YieldElementOp, so we have to pop the scope
-    // right now.
-    stmtCtx.finalizeAndPop();
-
-    // This is a hacky way to get rid of the DestroyOp clean-up
-    // associated with the final ac-value result if it is hlfir.expr.
-    // Example:
-    //   ... = (/(REPEAT(REPEAT(CHAR(i),2),2),i=1,n)/)
-    // Each intrinsic call lowering will produce hlfir.expr result
-    // with the associated clean-up, but only the last of them
-    // is wrong. It is wrong because the value is used in hlfir.yield_element,
-    // so it cannot be destroyed.
-    mlir::Operation *destroyOp = nullptr;
-    for (mlir::Operation *useOp : elementResult.getUsers())
-      if (mlir::isa<hlfir::DestroyOp>(useOp)) {
-        if (destroyOp)
-          fir::emitFatalError(loc,
-                              "multiple DestroyOp's for ac-value expression");
-        destroyOp = useOp;
-      }
-
-    if (destroyOp)
-      destroyOp->erase();
-
-    hlfir::YieldElementOp::create(builder, loc, elementResult);
+    auto yield = hlfir::YieldElementOp::create(builder, loc, elementResult);
+    Fortran::lower::genCleanUpInRegionIfAny(loc, builder, yield.getCleanup(),
+                                            stmtCtx);
+    if (yield.getCleanup().empty())
+      stmtCtx.pop();
   }
 
   // Override the default, because the context scope must be popped in
diff --git a/flang/lib/Lower/ConvertCall.cpp b/flang/lib/Lower/ConvertCall.cpp
index 8400743c0a30d9..52c17fd1313fb2 100644
--- a/flang/lib/Lower/ConvertCall.cpp
+++ b/flang/lib/Lower/ConvertCall.cpp
@@ -1178,8 +1178,12 @@ static hlfir::EntityWithAttributes genStmtFunctionRef(
   symMap.popScope();
   // The result must not be a variable.
   result = hlfir::loadTrivialScalar(loc, builder, result);
-  if (result.isVariable())
+  if (result.isVariable()) {
     result = hlfir::Entity{hlfir::AsExprOp::create(builder, loc, result)};
+    fir::FirOpBuilder *bldr = &builder;
+    stmtCtx.attachCleanup(
+        [=]() { hlfir::DestroyOp::create(*bldr, loc, result); });
+  }
   for (auto associate : exprAssociations)
     hlfir::EndAssociateOp::create(builder, loc, associate);
   return hlfir::EntityWithAttributes{result};
@@ -2730,18 +2734,20 @@ class ElementalCallBuilder {
             loc,
             "compute elemental PDT function result length parameters in HLFIR");
     }
-    auto genKernel = [&](mlir::Location l, fir::FirOpBuilder &b,
-                         mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
+    auto genKernel =
+        [&](mlir::Location l, fir::FirOpBuilder &b,
+            mlir::ValueRange oneBasedIndices) -> hlfir::ElementalKernelResult {
       callContext.stmtCtx.pushScope();
       for (auto &preparedActual : loweredActuals)
         if (preparedActual)
           preparedActual->setElementalIndices(oneBasedIndices);
       auto res = *impl().genElementalKernel(loweredActuals, callContext);
-      callContext.stmtCtx.finalizeAndPop();
-      // Note that an hlfir.destroy is not emitted for the result since it
-      // is still used by the hlfir.yield_element that also marks its last
-      // use.
-      return res;
+      if (mlir::isa<hlfir::ExprType>(res.getType())) {
+        fir::FirOpBuilder *bldr = &b;
+        callContext.stmtCtx.attachCleanup(
+            [=]() { hlfir::DestroyOp::create(*bldr, l, res); });
+      }
+      return {res, [&callContext]() { callContext.stmtCtx.finalizeAndPop(); }};
     };
     mlir::Value polymorphicMold;
     if (fir::isPolymorphicType(*callContext.resultType))
@@ -3812,9 +3818,14 @@ hlfir::Entity Fortran::lower::PreparedActualArgument::getActual(
       std::get<hlfir::ElementalAddrOp>(actual);
   mlir::IRMapping mapper;
   auto alwaysFalse = [](hlfir::ElementalOp) -> bool { return false; };
+  llvm::SmallVector<hlfir::CleanupFunction> cleanups;
   mlir::Value addr = hlfir::inlineElementalOp(
       loc, builder, elementalAddr, *oneBasedElementalIndices, mapper,
-      /*mustRecursivelyInline=*/alwaysFalse);
+      /*mustRecursivelyInline=*/alwaysFalse, cleanups);
+  // Subscript expressions are evaluated outside elemental_addr and cleaned
+  // up by the enclosing statement. This call only clones the address kernel:
+  // it does not recursively inline applies (which could add element cleanups).
+  assert(cleanups.empty() && "non-recursive address inlining has no cleanups");
   assert(elementalAddr.getCleanup().empty() && "no clean-up expected");
   elementalAddr.erase();
   return hlfir::Entity{addr};
diff --git a/flang/lib/Lower/ConvertExprToHLFIR.cpp b/flang/lib/Lower/ConvertExprToHLFIR.cpp
index 745f88930858a5..1d91e8dc9060c5 100644
--- a/flang/lib/Lower/ConvertExprToHLFIR.cpp
+++ b/flang/lib/Lower/ConvertExprToHLFIR.cpp
@@ -1153,6 +1153,22 @@ HlfirDesignatorBuilder::convertVectorSubscriptedExprToElementalAddr(
 // Binary Operation implementation
 //===--------------------------------------------------------------------===//
 
+/// Register the lifetime at the expression's creation point. Elemental kernels
+/// use their own context, emitted in the yield_element cleanup region.
+static void attachExprCleanup(mlir::Location loc, fir::FirOpBuilder &builder,
+                              mlir::Value expr,
+                              Fortran::lower::StatementContext &stmtCtx) {
+  fir::FirOpBuilder *bldr = &builder;
+  stmtCtx.attachCleanup([=]() { hlfir::DestroyOp::create(*bldr, loc, expr); });
+}
+
+static std::optional<hlfir::CleanupFunction>
+getElementCleanup(Fortran::lower::StatementContext &stmtCtx) {
+  if (!stmtCtx.hasCode())
+    return std::nullopt;
+  return [&stmtCtx]() { stmtCtx.finalizeAndReset(); };
+}
+
 template <typename T>
 struct BinaryOp {};
 
@@ -1163,10 +1179,10 @@ struct BinaryOp {};
       Fortran::evaluate::Type<Fortran::common::TypeCategory::GenBinTyCat>>> {  \
     using Op = Fortran::evaluate::GenBinEvOp<                                  \
         Fortran::evaluate::Type<Fortran::common::TypeCategory::GenBinTyCat>>;  \
-    static hlfir::EntityWithAttributes gen(mlir::Location loc,                 \
-                                           fir::FirOpBuilder &builder,         \
-                                           const Op &, hlfir::Entity lhs,      \
-                                           hlfir::Entity rhs) {                \
+    static hlfir::EntityWithAttributes                                         \
+    gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,            \
+        hlfir::Entity lhs, hlfir::Entity rhs,                                  \
+        Fortran::lower::StatementContext &stmtCtx) {                           \
       if constexpr (Fortran::common::TypeCategory::GenBinTyCat ==              \
                     Fortran::common::TypeCategory::Unsigned) {                 \
         return hlfir::EntityWithAttributes{                                    \
@@ -1200,10 +1216,10 @@ struct BinaryOp<Fortran::evaluate::Divide<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>> {
   using Op = Fortran::evaluate::Divide<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.kind();
     mlir::Type ty = Fortran::lower::getFIRType(
         builder.getContext(), Fortran::common::TypeCategory::Complex, kind,
@@ -1225,10 +1241,10 @@ struct BinaryOp<Fortran::evaluate::Divide<
 template <Fortran::common::TypeCategory TC>
 struct BinaryOp<Fortran::evaluate::Power<Fortran::evaluate::Type<TC>>> {
   using Op = Fortran::evaluate::Power<Fortran::evaluate::Type<TC>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.kind();
     mlir::Type ty = Fortran::lower::getFIRType(builder.getContext(), TC, kind,
                                                /*params=*/{});
@@ -1240,10 +1256,10 @@ template <Fortran::common::TypeCategory TC>
 struct BinaryOp<
     Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC>>> {
   using Op = Fortran::evaluate::RealToIntPower<Fortran::evaluate::Type<TC>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.kind();
     mlir::Type ty = Fortran::lower::getFIRType(builder.getContext(), TC, kind,
                                                /*params=*/{});
@@ -1254,10 +1270,10 @@ struct BinaryOp<
 template <Fortran::common::TypeCategory TC>
 struct BinaryOp<Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC>>> {
   using Op = Fortran::evaluate::Extremum<Fortran::evaluate::Type<TC>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     llvm::SmallVector<mlir::Value, 2> args{lhs, rhs};
     fir::ExtendedValue res = op.ordering == Fortran::evaluate::Ordering::Greater
                                  ? fir::genMax(builder, loc, args)
@@ -1276,9 +1292,9 @@ struct BinaryOp<Fortran::evaluate::Extremum<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Character>>> {
   using Op = Fortran::evaluate::Extremum<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Character>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &, const Op &,
-                                         hlfir::Entity, hlfir::Entity) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &, const Op &, hlfir::Entity,
+      hlfir::Entity, Fortran::lower::StatementContext &stmtCtx) {
     fir::emitFatalError(loc, "Fortran::evaluate::Extremum are unexpected");
   }
   static void genResultTypeParams(mlir::Location loc, fir::FirOpBuilder &,
@@ -1313,10 +1329,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer>>> {
   using Op = Fortran::evaluate::Relational<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     auto cmp = mlir::arith::CmpIOp::create(
         builder, loc, Fortran::lower::translateSignedRelational(op.opr), lhs,
         rhs);
@@ -1329,10 +1345,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Unsigned>>> {
   using Op = Fortran::evaluate::Relational<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Unsigned>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.left().kind();
     int bits = Fortran::evaluate::Type<
         Fortran::common::TypeCategory::Integer>::Scalar::bits(kind);
@@ -1353,10 +1369,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Real>>> {
   using Op = Fortran::evaluate::Relational<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Real>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     auto cmp = mlir::arith::CmpFOp::create(
         builder, loc, Fortran::lower::translateFloatRelational(op.opr), lhs,
         rhs);
@@ -1369,10 +1385,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>> {
   using Op = Fortran::evaluate::Relational<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     auto cmp = fir::CmpcOp::create(
         builder, loc, Fortran::lower::translateFloatRelational(op.opr), lhs,
         rhs);
@@ -1385,10 +1401,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Character>>> {
   using Op = Fortran::evaluate::Relational<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Character>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     auto cmp = hlfir::CmpCharOp::create(
         builder, loc, translateSignedRelational(op.opr), lhs, rhs);
     return hlfir::EntityWithAttributes{cmp};
@@ -1398,10 +1414,10 @@ struct BinaryOp<Fortran::evaluate::Relational<
 template <>
 struct BinaryOp<Fortran::evaluate::LogicalOperation> {
   using Op = Fortran::evaluate::LogicalOperation;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs,
-                                         hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     bool lhsIsLogical = mlir::isa<fir::LogicalType>(lhs.getType());
     bool rhsIsLogical = mlir::isa<fir::LogicalType>(rhs.getType());
     if (lhsIsLogical || rhsIsLogical) {
@@ -1455,9 +1471,10 @@ struct BinaryOp<Fortran::evaluate::LogicalOperation> {
 template <>
 struct BinaryOp<Fortran::evaluate::ComplexConstructor> {
   using Op = Fortran::evaluate::ComplexConstructor;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder, const Op &,
-                                         hlfir::Entity lhs, hlfir::Entity rhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,
+      hlfir::Entity lhs, hlfir::Entity rhs,
+      Fortran::lower::StatementContext &stmtCtx) {
     mlir::Value res =
         fir::factory::Complex{builder, loc}.createComplex(lhs, rhs);
     return hlfir::EntityWithAttributes{res};
@@ -1467,15 +1484,16 @@ struct BinaryOp<Fortran::evaluate::ComplexConstructor> {
 template <>
 struct BinaryOp<Fortran::evaluate::SetLength> {
   using Op = Fortran::evaluate::SetLength;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder, const Op &,
-                                         hlfir::Entity string,
-                                         hlfir::Entity length) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,
+      hlfir::Entity string, hlfir::Entity length,
+      Fortran::lower::StatementContext &stmtCtx) {
     // The input length may be a user input and needs to be sanitized as per
     // Fortran 2018 7.4.4.2 point 5.
     mlir::Value safeLength = fir::factory::genMaxWithZero(builder, loc, length);
-    return hlfir::EntityWithAttributes{
-        hlfir::SetLengthOp::create(builder, loc, string, safeLength)};
+    auto result = hlfir::SetLengthOp::create(builder, loc, string, safeLength);
+    attachExprCleanup(loc, builder, result, stmtCtx);
+    return hlfir::EntityWithAttributes{result};
   }
   static void
   genResultTypeParams(mlir::Location, fir::FirOpBuilder &, hlfir::Entity,
@@ -1490,10 +1508,12 @@ struct BinaryOp<Fortran::evaluate::Concat> {
   using Op = Fortran::evaluate::Concat;
   hlfir::EntityWithAttributes gen(mlir::Location loc,
                                   fir::FirOpBuilder &builder, const Op &,
-                                  hlfir::Entity lhs, hlfir::Entity rhs) {
+                                  hlfir::Entity lhs, hlfir::Entity rhs,
+                                  Fortran::lower::StatementContext &stmtCtx) {
     assert(len && "genResultTypeParams must have been called");
     auto concat =
         hlfir::ConcatOp::create(builder, loc, mlir::ValueRange{lhs, rhs}, len);
+    attachExprCleanup(loc, builder, concat.getResult(), stmtCtx);
     return hlfir::EntityWithAttributes{concat.getResult()};
   }
   void
@@ -1525,9 +1545,9 @@ struct UnaryOp {};
 template <>
 struct UnaryOp<Fortran::evaluate::Not> {
   using Op = Fortran::evaluate::Not;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder, const Op &,
-                                         hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     mlir::Value one = builder.createBool(loc, true);
     mlir::Value val = builder.createConvert(loc, builder.getI1Type(), lhs);
     return hlfir::EntityWithAttributes{
@@ -1540,9 +1560,9 @@ struct UnaryOp<Fortran::evaluate::Negate<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer>>> {
   using Op = Fortran::evaluate::Negate<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Integer>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.kind();
     // Like LLVM, integer negation is the binary op "0 - value"
     mlir::Type type = Fortran::lower::getFIRType(
@@ -1559,9 +1579,9 @@ struct UnaryOp<Fortran::evaluate::Negate<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Unsigned>>> {
   using Op = Fortran::evaluate::Negate<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Unsigned>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     const int kind = op.kind();
     int bits = Fortran::evaluate::Type<
         Fortran::common::TypeCategory::Integer>::Scalar::bits(kind);
@@ -1582,9 +1602,9 @@ struct UnaryOp<Fortran::evaluate::Negate<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Real>>> {
   using Op = Fortran::evaluate::Negate<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Real>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder, const Op &,
-                                         hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     return hlfir::EntityWithAttributes{
         mlir::arith::NegFOp::create(builder, loc, lhs)};
   }
@@ -1595,9 +1615,9 @@ struct UnaryOp<Fortran::evaluate::Negate<
     Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>> {
   using Op = Fortran::evaluate::Negate<
       Fortran::evaluate::Type<Fortran::common::TypeCategory::Complex>>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder, const Op &,
-                                         hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     return hlfir::EntityWithAttributes{fir::NegcOp::create(builder, loc, lhs)};
   }
 };
@@ -1605,9 +1625,9 @@ struct UnaryOp<Fortran::evaluate::Negate<
 template <>
 struct UnaryOp<Fortran::evaluate::ComplexComponent> {
   using Op = Fortran::evaluate::ComplexComponent;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     mlir::Value res = fir::factory::Complex{builder, loc}.extractComplexPart(
         lhs, op.isImaginaryPart);
     return hlfir::EntityWithAttributes{res};
@@ -1617,12 +1637,14 @@ struct UnaryOp<Fortran::evaluate::ComplexComponent> {
 template <typename T>
 struct UnaryOp<Fortran::evaluate::Parentheses<T>> {
   using Op = Fortran::evaluate::Parentheses<T>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs) {
-    if (lhs.isVariable())
-      return hlfir::EntityWithAttributes{
-          hlfir::AsExprOp::create(builder, loc, lhs)};
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
+    if (lhs.isVariable()) {
+      auto result = hlfir::AsExprOp::create(builder, loc, lhs);
+      attachExprCleanup(loc, builder, result, stmtCtx);
+      return hlfir::EntityWithAttributes{result};
+    }
     return hlfir::EntityWithAttributes{
         hlfir::NoReassocOp::create(builder, loc, lhs.getType(), lhs)};
   }
@@ -1638,13 +1660,15 @@ struct UnaryOp<Fortran::evaluate::Parentheses<T>> {
 template <Fortran::common::TypeCategory TC1, Fortran::common::TypeCategory TC2>
 struct UnaryOp<Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1>, TC2>> {
   using Op = Fortran::evaluate::Convert<Fortran::evaluate::Type<TC1>, TC2>;
-  static hlfir::EntityWithAttributes gen(mlir::Location loc,
-                                         fir::FirOpBuilder &builder,
-                                         const Op &op, hlfir::Entity lhs) {
+  static hlfir::EntityWithAttributes
+  gen(mlir::Location loc, fir::FirOpBuilder &builder, const Op &op,
+      hlfir::Entity lhs, Fortran::lower::StatementContext &stmtCtx) {
     int kind = op.kind();
     if constexpr (TC1 == Fortran::common::TypeCategory::Character &&
                   TC2 == TC1) {
-      return hlfir::convertCharacterKind(loc, builder, lhs, kind);
+      auto result = hlfir::convertCharacterKind(loc, builder, lhs, kind);
+      attachExprCleanup(loc, builder, result, stmtCtx);
+      return result;
     }
     mlir::Type type = Fortran::lower::getFIRType(builder.getContext(), TC1,
                                                  kind, /*params=*/{});
@@ -1907,13 +1931,13 @@ class HlfirBuilder {
           Fortran::lower::genEnumerationOrdinalDesignator(loc, builder, base);
     mlir::Value shape = hlfir::genShape(loc, builder, base);
     auto kernel = [&](mlir::Location l, fir::FirOpBuilder &b,
-                      mlir::ValueRange idx) -> hlfir::Entity {
+                      mlir::ValueRange idx) -> hlfir::ElementalKernelResult {
       mlir::Value elem =
           ordinals ? hlfir::loadTrivialScalar(
                          l, b, hlfir::getElementAt(l, b, *ordinals, idx))
                    : genEnumerationOrdinalValue(
                          l, b, hlfir::getElementAt(l, b, base, idx));
-      return hlfir::Entity{b.createConvert(l, eleTy, elem)};
+      return {hlfir::Entity{b.createConvert(l, eleTy, elem)}, std::nullopt};
     };
     mlir::Value elemental =
         hlfir::genElementalOp(loc, builder, eleTy, shape, /*typeParams=*/{},
@@ -1937,14 +1961,17 @@ class HlfirBuilder {
             loc, getConverter(), enumExpr, getSymMap(), getStmtCtx());
     assert(addrOp.getCleanup().empty() && "no clean-up expected");
     auto kernel = [&](mlir::Location l, fir::FirOpBuilder &b,
-                      mlir::ValueRange idx) -> hlfir::Entity {
+                      mlir::ValueRange idx) -> hlfir::ElementalKernelResult {
       mlir::IRMapping mapper;
       auto alwaysFalse = [](hlfir::ElementalOp) -> bool { return false; };
-      hlfir::Entity elem{
-          hlfir::inlineElementalOp(l, b, addrOp, idx, mapper, alwaysFalse)};
+      llvm::SmallVector<hlfir::CleanupFunction> cleanups;
+      hlfir::Entity elem{hlfir::inlineElementalOp(l, b, addrOp, idx, mapper,
+                                                  alwaysFalse, cleanups)};
+      assert(cleanups.empty() &&
+             "non-recursive address inlining has no cleanups");
       mlir::Value ordinal = hlfir::loadTrivialScalar(
           l, b, Fortran::lower::genEnumerationOrdinalDesignator(l, b, elem));
-      return hlfir::Entity{b.createConvert(l, eleTy, ordinal)};
+      return {hlfir::Entity{b.createConvert(l, eleTy, ordinal)}, std::nullopt};
     };
     mlir::Value elemental = hlfir::genElementalOp(
         loc, builder, eleTy, addrOp.getShape(), /*typeParams=*/{}, kernel,
@@ -1996,7 +2023,7 @@ class HlfirBuilder {
       unaryOp.genResultTypeParams(loc, builder, left, typeParams);
     }
     if (rank == 0)
-      return unaryOp.gen(loc, builder, op.derived(), left);
+      return unaryOp.gen(loc, builder, op.derived(), left, getStmtCtx());
 
     // Elemental expression.
     mlir::Type elementType;
@@ -2012,12 +2039,15 @@ class HlfirBuilder {
                                      /*params=*/{});
     }
     mlir::Value shape = hlfir::genShape(loc, builder, left);
-    auto genKernel = [&op, &left, &unaryOp](
-                         mlir::Location l, fir::FirOpBuilder &b,
-                         mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
+    Fortran::lower::StatementContext elementContext;
+    auto genKernel =
+        [&op, &left, &unaryOp, &elementContext](
+            mlir::Location l, fir::FirOpBuilder &b,
+            mlir::ValueRange oneBasedIndices) -> hlfir::ElementalKernelResult {
       auto leftElement = hlfir::getElementAt(l, b, left, oneBasedIndices);
       auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
-      return unaryOp.gen(l, b, op.derived(), leftVal);
+      auto result = unaryOp.gen(l, b, op.derived(), leftVal, elementContext);
+      return {result, getElementCleanup(elementContext)};
     };
     mlir::Value elemental = hlfir::genElementalOp(
         loc, builder, elementType, shape, typeParams, genKernel,
@@ -2055,7 +2085,8 @@ class HlfirBuilder {
       if (noReassoc)
         builder.setFastMathFlags(fmfBackup &
                                  ~mlir::arith::FastMathFlags::reassoc);
-      auto res = binaryOp.gen(loc, builder, op.derived(), left, right);
+      auto res =
+          binaryOp.gen(loc, builder, op.derived(), left, right, getStmtCtx());
       builder.setFastMathFlags(fmfBackup);
       return res;
     }
@@ -2084,9 +2115,11 @@ class HlfirBuilder {
       assert(right.isArray() && "must have at least one array operand");
       shape = hlfir::genShape(loc, builder, right);
     }
-    auto genKernel = [&op, &left, &right, &binaryOp, noReassoc](
-                         mlir::Location l, fir::FirOpBuilder &b,
-                         mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
+    Fortran::lower::StatementContext elementContext;
+    auto genKernel =
+        [&op, &left, &right, &binaryOp, noReassoc, &elementContext](
+            mlir::Location l, fir::FirOpBuilder &b,
+            mlir::ValueRange oneBasedIndices) -> hlfir::ElementalKernelResult {
       auto fmfBackup = b.getFastMathFlags();
       if (noReassoc)
         b.setFastMathFlags(fmfBackup & ~mlir::arith::FastMathFlags::reassoc);
@@ -2094,9 +2127,10 @@ class HlfirBuilder {
       auto rightElement = hlfir::getElementAt(l, b, right, oneBasedIndices);
       auto leftVal = hlfir::loadTrivialScalar(l, b, leftElement);
       auto rightVal = hlfir::loadTrivialScalar(l, b, rightElement);
-      auto result = binaryOp.gen(l, b, op.derived(), leftVal, rightVal);
+      auto result =
+          binaryOp.gen(l, b, op.derived(), leftVal, rightVal, elementContext);
       b.setFastMathFlags(fmfBackup);
-      return result;
+      return {result, getElementCleanup(elementContext)};
     };
     auto iofBackup = builder.getIntegerOverflowFlags();
     // nsw is never added to operations on vector subscripts
diff --git a/flang/lib/Optimizer/Builder/CMakeLists.txt b/flang/lib/Optimizer/Builder/CMakeLists.txt
index b77e21d40476c9..f01d3a13c3eb52 100644
--- a/flang/lib/Optimizer/Builder/CMakeLists.txt
+++ b/flang/lib/Optimizer/Builder/CMakeLists.txt
@@ -62,6 +62,7 @@ add_flang_library(FIRBuilder
   ${extension_libs}
 
   MLIR_LIBS
+  MLIRTransformUtils
   ${dialect_libs}
   ${extension_libs}
 )
diff --git a/flang/lib/Optimizer/Builder/Character.cpp b/flang/lib/Optimizer/Builder/Character.cpp
index a5e32fec059789..670417b8887463 100644
--- a/flang/lib/Optimizer/Builder/Character.cpp
+++ b/flang/lib/Optimizer/Builder/Character.cpp
@@ -366,9 +366,8 @@ void fir::factory::CharacterExprHelper::createPadding(
       });
 }
 
-fir::CharBoxValue
-fir::factory::CharacterExprHelper::createCharacterTemp(mlir::Type type,
-                                                       mlir::Value len) {
+fir::CharBoxValue fir::factory::CharacterExprHelper::createCharacterTemp(
+    mlir::Type type, mlir::Value len, bool useHeap) {
   auto kind = recoverCharacterType(type).getFKind();
   auto typeLen = fir::CharacterType::unknownLen();
   // If len is a constant, reflect the length in the type.
@@ -380,8 +379,10 @@ fir::factory::CharacterExprHelper::createCharacterTemp(mlir::Type type,
   llvm::SmallVector<mlir::Value> lenParams;
   if (typeLen == fir::CharacterType::unknownLen())
     lenParams.push_back(len);
-  auto ref = builder.allocateLocal(loc, charTy, "", ".chrtmp",
-                                   /*shape=*/{}, lenParams);
+  auto ref = useHeap ? builder.createHeapTemporary(loc, charTy, ".chrtmp",
+                                                   /*shape=*/{}, lenParams)
+                     : builder.allocateLocal(loc, charTy, "", ".chrtmp",
+                                             /*shape=*/{}, lenParams);
   return {ref, len};
 }
 
@@ -486,13 +487,13 @@ void fir::factory::CharacterExprHelper::createAssign(
 }
 
 fir::CharBoxValue fir::factory::CharacterExprHelper::createConcatenate(
-    const fir::CharBoxValue &lhs, const fir::CharBoxValue &rhs) {
+    const fir::CharBoxValue &lhs, const fir::CharBoxValue &rhs, bool useHeap) {
   auto lhsLen = builder.createConvert(loc, builder.getCharacterLengthType(),
                                       lhs.getLen());
   auto rhsLen = builder.createConvert(loc, builder.getCharacterLengthType(),
                                       rhs.getLen());
   mlir::Value len = mlir::arith::AddIOp::create(builder, loc, lhsLen, rhsLen);
-  auto temp = createCharacterTemp(getCharacterType(rhs), len);
+  auto temp = createCharacterTemp(getCharacterType(rhs), len, useHeap);
   createCopy(temp, lhs, lhsLen);
   auto one = builder.createIntegerConstant(loc, len.getType(), 1);
   auto upperBound = mlir::arith::SubIOp::create(builder, loc, len, one);
@@ -796,7 +797,7 @@ fir::factory::getCharacterProcedureTupleType(mlir::Type funcPointerType) {
 }
 
 fir::CharBoxValue fir::factory::CharacterExprHelper::createCharExtremum(
-    bool predIsMin, llvm::ArrayRef<fir::CharBoxValue> opCBVs) {
+    bool predIsMin, llvm::ArrayRef<fir::CharBoxValue> opCBVs, bool useHeap) {
   // inputs: we are given a vector of all of the charboxes of the arguments
   // passed to hlfir.char_extremum, as well as the predicate for whether we
   // want llt or lgt
@@ -853,17 +854,17 @@ fir::CharBoxValue fir::factory::CharacterExprHelper::createCharExtremum(
 
   // now that we know the lexicographically biggest/smallest char and which char
   // had the biggest len, we can populate a temp CBV and return it
-  fir::CharBoxValue temp = createCharacterTemp(resultBuf.getType(), biggestLen);
+  fir::CharBoxValue temp =
+      createCharacterTemp(resultBuf.getType(), biggestLen, useHeap);
   auto toBuf = temp;
   fir::CharBoxValue fromBuf{resultBuf, resultLen};
   createAssign(toBuf, fromBuf);
   return temp;
 }
 
-fir::CharBoxValue
-fir::factory::convertCharacterKind(fir::FirOpBuilder &builder,
-                                   mlir::Location loc,
-                                   fir::CharBoxValue srcBoxChar, int toKind) {
+fir::CharBoxValue fir::factory::convertCharacterKind(
+    fir::FirOpBuilder &builder, mlir::Location loc,
+    fir::CharBoxValue srcBoxChar, int toKind, bool useHeap) {
   // Use char_convert. Each code point is translated from a
   // narrower/wider encoding to the target encoding. For example, 'A'
   // may be translated from 0x41 : i8 to 0x0041 : i16. The symbol
@@ -892,8 +893,10 @@ fir::factory::convertCharacterKind(fir::FirOpBuilder &builder,
   }
   mlir::Type toType =
       fir::CharacterType::getUnknownLen(builder.getContext(), toKind);
-  auto dest = builder.createTemporary(loc, toType, /*name=*/{}, /*shape=*/{},
-                                      mlir::ValueRange{bufferSize});
+  auto dest = useHeap ? builder.createHeapTemporary(loc, toType, /*name=*/{},
+                                                    /*shape=*/{}, {bufferSize})
+                      : builder.createTemporary(loc, toType, /*name=*/{},
+                                                /*shape=*/{}, {bufferSize});
   fir::CharConvertOp::create(builder, loc, boxCharAddr, srcBoxChar.getLen(),
                              dest);
   return fir::CharBoxValue{dest, srcBoxChar.getLen()};
diff --git a/flang/lib/Optimizer/Builder/HLFIRTools.cpp b/flang/lib/Optimizer/Builder/HLFIRTools.cpp
index 231c8f282cdcb3..013af9811736e6 100644
--- a/flang/lib/Optimizer/Builder/HLFIRTools.cpp
+++ b/flang/lib/Optimizer/Builder/HLFIRTools.cpp
@@ -20,6 +20,7 @@
 #include "flang/Optimizer/HLFIR/HLFIROps.h"
 #include "mlir/IR/IRMapping.h"
 #include "mlir/Support/LLVM.h"
+#include "mlir/Transforms/RegionUtils.h"
 #include "llvm/ADT/TypeSwitch.h"
 #include <mlir/Dialect/LLVMIR/LLVMAttrs.h>
 #include <mlir/Dialect/OpenMP/OpenMPDialect.h>
@@ -925,21 +926,27 @@ hlfir::ElementalOp hlfir::genElementalOp(
       builder, loc, exprType, shape, polymorphicMold, typeParams, isUnordered);
   auto insertPt = builder.saveInsertionPoint();
   builder.setInsertionPointToStart(elementalOp.getBody());
-  mlir::Value elementResult = genKernel(loc, builder, elementalOp.getIndices());
+  auto [element, cleanup] = genKernel(loc, builder, elementalOp.getIndices());
+  mlir::Value elementResult = element;
   // Numerical and logical scalars may be lowered to another type than the
   // Fortran expression type (e.g i1 instead of fir.logical). Array expression
   // values are typed according to their Fortran type. Insert a cast if needed
   // here.
   if (fir::isa_trivial(elementResult.getType()))
     elementResult = builder.createConvert(loc, elementType, elementResult);
-  hlfir::YieldElementOp::create(builder, loc, elementResult);
+  auto yield = hlfir::YieldElementOp::create(builder, loc, elementResult);
+  if (cleanup) {
+    builder.createBlock(&yield.getCleanup());
+    (*cleanup)();
+    if (yield.getCleanup().front().empty())
+      yield.getCleanup().front().erase();
+    else
+      hlfir::YieldElementOp::ensureTerminator(yield.getCleanup(), builder, loc);
+  }
   builder.restoreInsertionPoint(insertPt);
   return elementalOp;
 }
 
-// TODO: we do not actually need to clone the YieldElementOp,
-// because returning its getElementValue() operand should be enough
-// for all callers of this function.
 hlfir::YieldElementOp
 hlfir::inlineElementalOp(mlir::Location loc, fir::FirOpBuilder &builder,
                          hlfir::ElementalOp elemental,
@@ -957,11 +964,31 @@ hlfir::inlineElementalOp(mlir::Location loc, fir::FirOpBuilder &builder,
   return yield;
 }
 
+/// Save only the mappings of values captured by this cleanup, not the whole
+/// expression tree's mapping. Each inlined evaluation needs its own snapshot:
+/// a later application of the same elemental overwrites its value mappings.
+static hlfir::CleanupFunction getElementCleanup(mlir::Region &cleanup,
+                                                fir::FirOpBuilder &builder,
+                                                const mlir::IRMapping &mapper) {
+  mlir::IRMapping cleanupMapper;
+  mlir::visitUsedValuesDefinedAbove(
+      cleanup, cleanup, [&](mlir::OpOperand *operand) {
+        mlir::Value value = operand->get();
+        if (mlir::Value mapped = mapper.lookupOrNull(value))
+          cleanupMapper.map(value, mapped);
+      });
+  return [&cleanup, &builder, mapper = std::move(cleanupMapper)]() mutable {
+    for (auto &op : cleanup.front().without_terminator())
+      builder.clone(op, mapper);
+  };
+}
+
 mlir::Value hlfir::inlineElementalOp(
     mlir::Location loc, fir::FirOpBuilder &builder,
     hlfir::ElementalOpInterface elemental, mlir::ValueRange oneBasedIndices,
     mlir::IRMapping &mapper,
-    const std::function<bool(hlfir::ElementalOp)> &mustRecursivelyInline) {
+    const std::function<bool(hlfir::ElementalOp)> &mustRecursivelyInline,
+    llvm::SmallVectorImpl<hlfir::CleanupFunction> &cleanups) {
   mlir::Region &region = elemental.getElementalRegion();
   // hlfir.elemental region is a SizedRegion<1>.
   assert(region.hasOneBlock() && "elemental region must have one block");
@@ -977,15 +1004,23 @@ mlir::Value hlfir::inlineElementalOp(
           hlfir::ElementalOpInterface elementalIface =
               mlir::cast<hlfir::ElementalOpInterface>(
                   appliedElemental.getOperation());
-          mlir::Value inlined = inlineElementalOp(loc, builder, elementalIface,
-                                                  clonedApplyIndices, mapper,
-                                                  mustRecursivelyInline);
+          mlir::Value inlined = inlineElementalOp(
+              loc, builder, elementalIface, clonedApplyIndices, mapper,
+              mustRecursivelyInline, cleanups);
           mapper.map(apply.getResult(), inlined);
           continue;
         }
     (void)builder.clone(op, mapper);
   }
-  return mapper.lookupOrDefault(elemental.getElementEntity());
+  mlir::Value result = mapper.lookupOrDefault(elemental.getElementEntity());
+  if (auto yield = mlir::dyn_cast<hlfir::YieldElementOp>(
+          region.front().getTerminator())) {
+    if (!yield.getCleanup().empty()) {
+      cleanups.push_back(
+          getElementCleanup(yield.getCleanup(), builder, mapper));
+    }
+  }
+  return result;
 }
 
 hlfir::LoopNest hlfir::genLoopNest(mlir::Location loc,
@@ -1369,18 +1404,20 @@ hlfir::cloneToElementalOp(mlir::Location loc, fir::FirOpBuilder &builder,
   hlfir::genLengthParameters(loc, builder, scalarAddress, typeParams);
 
   builder.setInsertionPointAfter(elementalAddrOp);
-  auto genKernel = [&](mlir::Location l, fir::FirOpBuilder &b,
-                       mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
+  auto genKernel =
+      [&](mlir::Location l, fir::FirOpBuilder &b,
+          mlir::ValueRange oneBasedIndices) -> hlfir::ElementalKernelResult {
     mlir::IRMapping mapper;
     mapper.map(elementalAddrOp.getIndices(), oneBasedIndices);
-    mlir::Operation *newOp = nullptr;
-    for (auto &op : elementalAddrOp.getBody().back().getOperations())
-      newOp = b.clone(op, mapper);
-    auto newYielOp = mlir::dyn_cast_or_null<hlfir::YieldOp>(newOp);
-    assert(newYielOp && "hlfir.elemental_addr is ill formed");
-    hlfir::Entity newAddr{newYielOp.getEntity()};
-    newYielOp->erase();
-    return hlfir::loadTrivialScalar(l, b, newAddr);
+    for (auto &op : elementalAddrOp.getBody().back().without_terminator())
+      b.clone(op, mapper);
+    auto yield = mlir::cast<hlfir::YieldOp>(
+        elementalAddrOp.getBody().back().getTerminator());
+    hlfir::Entity newAddr{mapper.lookupOrDefault(yield.getEntity())};
+    hlfir::Entity element = hlfir::loadTrivialScalar(l, b, newAddr);
+    if (yield.getCleanup().empty())
+      return {element, std::nullopt};
+    return {element, getElementCleanup(yield.getCleanup(), b, mapper)};
   };
   mlir::Type elementType = scalarAddress.getFortranElementType();
   return hlfir::genElementalOp(
@@ -1485,7 +1522,13 @@ hlfir::createTempFromMold(mlir::Location loc, fir::FirOpBuilder &builder,
     extents = hlfir::getExplicitExtentsFromShape(shape, builder);
   }
 
-  bool useStack = !mold.isArray() && !mold.isPolymorphic();
+  // Keep character temporary lifetimes explicit until allocation placement.
+  // In particular, a dynamic scalar character alloca in a CFG loop cannot be
+  // reclaimed by the structured-loop stack reclamation pass.
+  auto charType =
+      mlir::dyn_cast<fir::CharacterType>(mold.getFortranElementType());
+  bool useStack = !mold.isArray() && !mold.isPolymorphic() &&
+                  (!charType || charType.hasConstantLen());
   auto genTempDeclareOp =
       [](fir::FirOpBuilder &builder, mlir::Location loc, mlir::Value memref,
          llvm::StringRef name, mlir::Value shape,
@@ -1543,13 +1586,18 @@ hlfir::convertCharacterKind(mlir::Location loc, fir::FirOpBuilder &builder,
                                      scalarChar.getFortranElementType());
   assert(src.first.getCharBox() && "must be scalar character");
   fir::CharBoxValue res = fir::factory::convertCharacterKind(
-      builder, loc, *src.first.getCharBox(), toKind);
+      builder, loc, *src.first.getCharBox(), toKind,
+      /*useHeap=*/!fir::getIntIfConstant(src.first.getCharBox()->getLen()));
   if (src.second.has_value())
     src.second.value()();
 
-  return hlfir::EntityWithAttributes{hlfir::DeclareOp::create(
+  auto declare = hlfir::DeclareOp::create(
       builder, loc, res.getAddr(), ".temp.kindconvert", /*shape=*/nullptr,
-      /*typeparams=*/mlir::ValueRange{res.getLen()})};
+      /*typeparams=*/mlir::ValueRange{res.getLen()});
+  return hlfir::EntityWithAttributes{hlfir::AsExprOp::create(
+      builder, loc, declare.getBase(),
+      builder.createBool(loc,
+                         mlir::isa<fir::HeapType>(res.getAddr().getType())))};
 }
 
 std::pair<hlfir::Entity, std::optional<hlfir::CleanupFunction>>
@@ -1583,20 +1631,24 @@ hlfir::genTypeAndKindConvert(mlir::Location loc, fir::FirOpBuilder &builder,
                            ? mlir::Value{hlfir::convertCharacterKind(
                                  loc, builder, source, *toKindCharConvert)}
                            : builder.convertWithSemantics(loc, toType, source);
+    if (toKindCharConvert) {
+      fir::FirOpBuilder *bldr = &builder;
+      return {hlfir::Entity{cast},
+              [=]() { hlfir::DestroyOp::create(*bldr, loc, cast); }};
+    }
     return {hlfir::Entity{cast}, std::nullopt};
   }
 
   mlir::Value shape = hlfir::genShape(loc, builder, source);
-  auto genKernel = [source, toType, toKindCharConvert](
-                       mlir::Location loc, fir::FirOpBuilder &builder,
-                       mlir::ValueRange oneBasedIndices) -> hlfir::Entity {
+  auto genKernel =
+      [source, toType](
+          mlir::Location loc, fir::FirOpBuilder &builder,
+          mlir::ValueRange oneBasedIndices) -> hlfir::ElementalKernelResult {
     auto elementPtr =
         hlfir::getElementAt(loc, builder, source, oneBasedIndices);
     auto val = hlfir::loadTrivialScalar(loc, builder, elementPtr);
-    if (toKindCharConvert)
-      return hlfir::convertCharacterKind(loc, builder, val, *toKindCharConvert);
-    return hlfir::EntityWithAttributes{
-        builder.convertWithSemantics(loc, toType, val)};
+    return hlfir::genTypeAndKindConvert(loc, builder, val, toType,
+                                        /*preserveLowerBounds=*/false);
   };
   llvm::SmallVector<mlir::Value, 1> lenParams;
   hlfir::genLengthParameters(loc, builder, source, lenParams);
diff --git a/flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp b/flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
index d84b1bb2040ca2..c9f11216437f73 100644
--- a/flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
+++ b/flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
@@ -1892,6 +1892,10 @@ mlir::Value hlfir::ElementalOp::getElementEntity() {
   return mlir::cast<hlfir::YieldElementOp>(getBody()->back()).getElementValue();
 }
 
+mlir::Region *hlfir::ElementalOp::getElementCleanup() {
+  return &mlir::cast<hlfir::YieldElementOp>(getBody()->back()).getCleanup();
+}
+
 llvm::LogicalResult hlfir::ElementalOp::verify() {
   mlir::Value mold = getMold();
   hlfir::ExprType resultType = mlir::cast<hlfir::ExprType>(getType());
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp b/flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp
index 8fd4ead9f3ca71..abed28128f5049 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp
@@ -292,9 +292,13 @@ struct ConcatOpConversion : public mlir::OpConversionPattern<hlfir::ConcatOp> {
     auto [lhsExv, c1] = hlfir::translateToExtendedValue(loc, builder, lhs);
     auto [rhsExv, c2] = hlfir::translateToExtendedValue(loc, builder, rhs);
     assert(!c1 && !c2 && "expected variables");
-    fir::ExtendedValue res =
+    bool useHeap = !mlir::cast<fir::CharacterType>(
+                        hlfir::getFortranElementType(concat.getType()))
+                        .hasConstantLen();
+    fir::CharBoxValue temp =
         fir::factory::CharacterExprHelper{builder, loc}.createConcatenate(
-            *lhsExv.getCharBox(), *rhsExv.getCharBox());
+            *lhsExv.getCharBox(), *rhsExv.getCharBox(), useHeap);
+    fir::ExtendedValue res = temp;
     // Ensure the memory type is the same as the result type.
     mlir::Type addrType = fir::ReferenceType::get(
         hlfir::getFortranElementType(concat.getResult().getType()));
@@ -304,8 +308,9 @@ struct ConcatOpConversion : public mlir::OpConversionPattern<hlfir::ConcatOp> {
         hlfir::Entity{hlfir::genDeclare(loc, builder, res, "tmp",
                                         fir::FortranVariableFlagsAttr{})
                           .getBase()};
-    mlir::Value bufferizedExpr =
-        packageBufferizedExpr(loc, builder, hlfirTempRes, false);
+    mlir::Value bufferizedExpr = packageBufferizedExpr(
+        loc, builder, hlfirTempRes,
+        mlir::isa<fir::HeapType>(temp.getBuffer().getType()));
     rewriter.replaceOp(concat, bufferizedExpr);
     return mlir::success();
   }
@@ -326,8 +331,12 @@ struct SetLengthOpConversion
     auto charType = hlfir::getFortranElementType(setLength.getType());
     llvm::StringRef tmpName{".tmp"};
     llvm::SmallVector<mlir::Value, 1> lenParams{adaptor.getLength()};
-    auto alloca = builder.createTemporary(loc, charType, tmpName,
-                                          /*shape=*/{}, lenParams);
+    bool mustFree = !mlir::cast<fir::CharacterType>(charType).hasConstantLen();
+    auto alloca = mustFree
+                      ? builder.createHeapTemporary(loc, charType, tmpName,
+                                                    /*shape=*/{}, lenParams)
+                      : builder.createTemporary(loc, charType, tmpName,
+                                                /*shape=*/{}, lenParams);
     auto declareOp = hlfir::DeclareOp::create(
         builder, loc, alloca, tmpName, /*shape=*/mlir::Value{}, lenParams);
     hlfir::Entity temp{declareOp.getBase()};
@@ -337,7 +346,7 @@ struct SetLengthOpConversion
                             /*keep_lhs_length_if_realloc=*/false,
                             /*temporary_lhs=*/true);
     mlir::Value bufferizedExpr =
-        packageBufferizedExpr(loc, builder, temp, false);
+        packageBufferizedExpr(loc, builder, temp, mustFree);
     rewriter.replaceOp(setLength, bufferizedExpr);
     return mlir::success();
   }
@@ -774,21 +783,33 @@ struct ElementalOpConversion
     auto yield = hlfir::inlineElementalOp(loc, builder, elemental,
                                           loopNest.oneBasedIndices);
     hlfir::Entity elementValue(yield.getElementValue());
+    hlfir::AsExprOp skippedAsExpr;
+    auto onlyYieldAndCleanupUses = [&](mlir::Value expr) {
+      return llvm::all_of(expr.getUsers(), [&](mlir::Operation *user) {
+        if (user == yield)
+          return true;
+        auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(user);
+        // Only direct cleanup destroys are omitted when replaying the region
+        // below. A destroy nested in another operation would retain a use of
+        // the as_expr we want to erase. Finalization must also be preserved.
+        return destroy && !destroy.mustFinalizeExpr() &&
+               destroy->getParentOp() == yield;
+      });
+    };
     // Skip final AsExpr if any. It would create an element temporary,
     // which is no needed since the element will be assigned right away in
     // the array temporary. An hlfir.as_expr may have been added if the
     // elemental is a "view" over a variable (e.g parentheses or transpose).
     if (auto asExpr = elementValue.getDefiningOp<hlfir::AsExprOp>()) {
-      if (asExpr->hasOneUse() && !asExpr.isMove()) {
+      if (onlyYieldAndCleanupUses(asExpr.getResult()) && !asExpr.isMove()) {
         // Check that the asExpr is the final operation before the yield,
         // otherwise, clean-ups could impact the memory being re-used.
         if (asExpr->getNextNode() == yield.getOperation()) {
+          skippedAsExpr = asExpr;
           elementValue = hlfir::Entity{asExpr.getVar()};
-          rewriter.eraseOp(asExpr);
         }
       }
     }
-    rewriter.eraseOp(yield);
     // Assign the element value to the temp element for this iteration.
     auto tempElement =
         hlfir::getElementAt(loc, builder, temp, loopNest.oneBasedIndices);
@@ -801,26 +822,31 @@ struct ElementalOpConversion
     auto elemType = hlfir::getFortranElementType(elementValue.getType());
     if (asExpr && asExpr.isMove() && mlir::isa<fir::RecordType>(elemType) &&
         hlfir::mayHaveAllocatableComponent(elemType) &&
-        wasCreatedInCurrentBlock(elementValue, builder)) {
+        wasCreatedInCurrentBlock(elementValue, builder) &&
+        onlyYieldAndCleanupUses(elementValue)) {
       auto load = fir::LoadOp::create(builder, loc, asExpr.getVar());
       fir::StoreOp::create(builder, loc, load, tempElement);
+      skippedAsExpr = asExpr;
     } else {
       hlfir::AssignOp::create(builder, loc, elementValue, tempElement,
                               /*realloc=*/false,
                               /*keep_lhs_length_if_realloc=*/false,
                               /*temporary_lhs=*/true);
-
-      // hlfir.yield_element implicitly marks the end-of-life its operand if
-      // it is an expression created in the hlfir.elemental (since it is its
-      // last use and an hlfir.destroy could not be created afterwards)
-      // Now that this node has been removed and the expression has been used in
-      // the assign, insert an hlfir.destroy to mark the expression end-of-life.
-      // If the expression creation allocated a buffer on the heap inside the
-      // loop, this will ensure the buffer properly deallocated.
-      if (mlir::isa<hlfir::ExprType>(elementValue.getType()) &&
-          wasCreatedInCurrentBlock(elementValue, builder))
-        hlfir::DestroyOp::create(builder, loc, elementValue);
     }
+    // Cleanup is explicit in HLFIR. When a copy is elided or its components
+    // are moved into the array result, omit only that expression's destroy.
+    if (!yield.getCleanup().empty()) {
+      mlir::IRMapping cleanupMapper;
+      for (auto &op : yield.getCleanup().front().without_terminator()) {
+        if (auto destroy = mlir::dyn_cast<hlfir::DestroyOp>(op))
+          if (skippedAsExpr && destroy.getExpr() == skippedAsExpr.getResult())
+            continue;
+        builder.clone(op, cleanupMapper);
+      }
+    }
+    rewriter.eraseOp(yield);
+    if (skippedAsExpr)
+      rewriter.eraseOp(skippedAsExpr);
     builder.restoreInsertionPoint(insPt);
 
     mlir::Value bufferizedExpr =
@@ -870,7 +896,8 @@ struct CharExtremumOpConversion
 
     fir::ExtendedValue res =
         fir::factory::CharacterExprHelper{builder, loc}.createCharExtremum(
-            predIsMin, opCBVs);
+            predIsMin, opCBVs, /*useHeap=*/true);
+    bool mustFree = mlir::isa<fir::HeapType>(fir::getBase(res).getType());
     mlir::Type addrType = fir::ReferenceType::get(
         hlfir::getFortranElementType(char_extremum.getResult().getType()));
     mlir::Value cast = builder.createConvert(loc, addrType, fir::getBase(res));
@@ -880,7 +907,7 @@ struct CharExtremumOpConversion
                                         fir::FortranVariableFlagsAttr{})
                           .getBase()};
     mlir::Value bufferizedExpr =
-        packageBufferizedExpr(loc, builder, hlfirTempRes, false);
+        packageBufferizedExpr(loc, builder, hlfirTempRes, mustFree);
     rewriter.replaceOp(char_extremum, bufferizedExpr);
     return mlir::success();
   }
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/InlineElementals.cpp b/flang/lib/Optimizer/HLFIR/Transforms/InlineElementals.cpp
index c84f3c373336cd..75bbaa789b1e3d 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/InlineElementals.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/InlineElementals.cpp
@@ -83,6 +83,10 @@ getReadDependencies(hlfir::ElementalOp elemental,
           return mlir::WalkResult::advance();
         }
 
+        // The walk visits nested effects, including yield_element cleanup.
+        if (op->hasTrait<mlir::OpTrait::HasRecursiveMemoryEffects>())
+          return mlir::WalkResult::advance();
+
         // Fail-safe: For operations without the interface, conservatively
         // assume we cannot reason about the dependency.
         return mlir::WalkResult::interrupt();
@@ -367,11 +371,40 @@ class InlineElementalConversion
     assert(elemental.getRegion().hasOneBlock() &&
            "expect elemental region to have one block");
 
+    auto sourceYield =
+        mlir::cast<hlfir::YieldElementOp>(elemental.getBody()->getTerminator());
+    auto consumer = mlir::dyn_cast<hlfir::ElementalOp>(apply->getParentOp());
+    // Keep scalar cleanup in the apply's block so its lifetime does not cross
+    // control-flow boundaries.
+    if (!sourceYield.getCleanup().empty() && !consumer &&
+        (!destroy || destroy->getBlock() != apply->getBlock() ||
+         !apply->isBeforeInBlock(destroy)))
+      return rewriter.notifyMatchFailure(
+          elemental, "cannot preserve element cleanup when inlining");
+
     fir::FirOpBuilder builder{rewriter, elemental.getOperation()};
     builder.setInsertionPointAfter(apply);
     hlfir::YieldElementOp yield = hlfir::inlineElementalOp(
         elemental.getLoc(), builder, elemental, apply.getIndices());
 
+    if (!yield.getCleanup().empty()) {
+      mlir::Block &cleanup = yield.getCleanup().front();
+      rewriter.eraseOp(cleanup.getTerminator());
+      if (consumer) {
+        // The consumer's result may use the inlined element's storage. Keep
+        // its cleanup until after the consumer's value has itself been used.
+        auto consumerYield = mlir::cast<hlfir::YieldElementOp>(
+            consumer.getBody()->getTerminator());
+        auto &destination = consumerYield.getCleanup();
+        hlfir::YieldElementOp::ensureTerminator(destination, rewriter,
+                                                consumer.getLoc());
+        rewriter.inlineBlockBefore(&cleanup,
+                                   destination.front().getTerminator());
+      } else {
+        rewriter.inlineBlockBefore(&cleanup, destroy);
+      }
+    }
+
     // remove the old elemental and all of the bookkeeping
     rewriter.replaceOp(apply, {yield.getElementValue()});
     rewriter.eraseOp(yield);
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/LowerHLFIROrderedAssignments.cpp b/flang/lib/Optimizer/HLFIR/Transforms/LowerHLFIROrderedAssignments.cpp
index dcc40c7b25c5c0..07d1bd6bcbd36b 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/LowerHLFIROrderedAssignments.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/LowerHLFIROrderedAssignments.cpp
@@ -75,9 +75,10 @@ struct MaskedArrayExpr {
                             mlir::IRMapping &mapper);
   /// Return the value of an element value for this expression given the current
   /// where loop indices.
-  mlir::Value generateElementalParts(fir::FirOpBuilder &builder,
-                                     mlir::ValueRange oneBasedIndices,
-                                     mlir::IRMapping &mapper);
+  mlir::Value generateElementalParts(
+      fir::FirOpBuilder &builder, mlir::ValueRange oneBasedIndices,
+      mlir::IRMapping &mapper,
+      llvm::SmallVectorImpl<hlfir::CleanupFunction> &cleanups);
   /// Generate the cleanup for the none elemental parts, if any. This must be
   /// called after the loops created for the WHERE construct.
   void generateNoneElementalCleanupIfAny(fir::FirOpBuilder &builder,
@@ -845,14 +846,30 @@ OrderedAssignmentRewriter::generateMaskedEntity(MaskedArrayExpr &maskedExpr) {
   // at the current insertion point (inside the where loops, and any fir.if
   // generated for previous masks).
   builder.restoreInsertionPoint(insertionPoint);
+  llvm::SmallVector<hlfir::CleanupFunction> cleanups;
   mlir::Value scalar = maskedExpr.generateElementalParts(
-      builder, whereLoopNest->oneBasedIndices, mapper);
+      builder, whereLoopNest->oneBasedIndices, mapper, cleanups);
   /// Generate cleanups for the elemental parts inside the loops (setting the
   /// location so that the assignment will be generated before the cleanups).
   if (!maskedExpr.isOuterMaskExpr)
     if (mlir::Operation *firstCleanup =
             maskedExpr.generateMaskedExprCleanUps(builder, mapper))
       builder.setInsertionPoint(firstCleanup);
+  // Replay each inlined yield's cleanup after the assignment. Remember the
+  // operation before the insertion point so the caller can insert the consumer
+  // before these newly cloned operations.
+  if (!cleanups.empty()) {
+    auto *block = builder.getBlock();
+    auto point = builder.getInsertionPoint();
+    mlir::Operation *previous =
+        point == block->begin() ? nullptr : &*std::prev(point);
+    for (auto &cleanup : llvm::reverse(cleanups))
+      cleanup();
+    if (previous)
+      builder.setInsertionPointAfter(previous);
+    else
+      builder.setInsertionPointToStart(block);
+  }
   return scalar;
 }
 
@@ -969,10 +986,10 @@ mlir::Value MaskedArrayExpr::generateShape(fir::FirOpBuilder &builder,
   return hlfir::genShape(loc, builder, hlfir::Entity{clonedEntity});
 }
 
-mlir::Value
-MaskedArrayExpr::generateElementalParts(fir::FirOpBuilder &builder,
-                                        mlir::ValueRange oneBasedIndices,
-                                        mlir::IRMapping &mapper) {
+mlir::Value MaskedArrayExpr::generateElementalParts(
+    fir::FirOpBuilder &builder, mlir::ValueRange oneBasedIndices,
+    mlir::IRMapping &mapper,
+    llvm::SmallVectorImpl<hlfir::CleanupFunction> &cleanups) {
   assert(noneElementalPartWasGenerated &&
          "non elemental part must have been generated");
   if (!isOuterMaskExpr) {
@@ -1005,7 +1022,7 @@ MaskedArrayExpr::generateElementalParts(fir::FirOpBuilder &builder,
     return elementalParts.contains(appliedElemental.getOperation());
   };
   return inlineElementalOp(loc, builder, elemental, oneBasedIndices, mapper,
-                           mustRecursivelyInline);
+                           mustRecursivelyInline, cleanups);
 }
 
 mlir::Operation *
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/OptimizedBufferization.cpp b/flang/lib/Optimizer/HLFIR/Transforms/OptimizedBufferization.cpp
index 53d4a42e2deff3..0d944d9375fd95 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/OptimizedBufferization.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/OptimizedBufferization.cpp
@@ -24,6 +24,7 @@
 #include "flang/Optimizer/OpenMP/Passes.h"
 #include "mlir/Dialect/Func/IR/FuncOps.h"
 #include "mlir/IR/Dominance.h"
+#include "mlir/IR/IRMapping.h"
 #include "mlir/IR/PatternMatch.h"
 #include "mlir/Interfaces/SideEffectInterfaces.h"
 #include "mlir/Pass/Pass.h"
@@ -481,7 +482,6 @@ llvm::LogicalResult ElementalAssignBufferization::matchAndRewrite(
   auto yield = hlfir::inlineElementalOp(loc, builder, elemental,
                                         loopNest.oneBasedIndices);
   hlfir::Entity elementValue{yield.getElementValue()};
-  rewriter.eraseOp(yield);
 
   // Assign the element value to the array element for this iteration.
   auto arrayElement =
@@ -494,6 +494,13 @@ llvm::LogicalResult ElementalAssignBufferization::matchAndRewrite(
               fir::getAccessGroupsAttrName()))
     newAssign->setAttr(fir::getAccessGroupsAttrName(), accessGroups);
 
+  if (!yield.getCleanup().empty()) {
+    mlir::IRMapping cleanupMapper;
+    for (auto &op : yield.getCleanup().front().without_terminator())
+      builder.clone(op, cleanupMapper);
+  }
+  rewriter.eraseOp(yield);
+
   rewriter.eraseOp(match->assign);
   rewriter.eraseOp(match->destroy);
   rewriter.eraseOp(elemental);
diff --git a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
index 73fda2d35bee92..346a7c6df8a824 100644
--- a/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
+++ b/flang/lib/Optimizer/HLFIR/Transforms/SimplifyHLFIRIntrinsics.cpp
@@ -133,8 +133,10 @@ class TransposeAsElementalConversion
     llvm::SmallVector<mlir::Value, 1> typeParams;
     hlfir::genLengthParameters(loc, builder, array, typeParams);
 
-    auto genKernel = [&array](mlir::Location loc, fir::FirOpBuilder &builder,
-                              mlir::ValueRange inputIndices) -> hlfir::Entity {
+    auto genKernel =
+        [&array](
+            mlir::Location loc, fir::FirOpBuilder &builder,
+            mlir::ValueRange inputIndices) -> hlfir::ElementalKernelResult {
       assert(inputIndices.size() == 2 && "checked in TransposeOp::validate");
       const std::initializer_list<mlir::Value> initList = {inputIndices[1],
                                                            inputIndices[0]};
@@ -142,7 +144,7 @@ class TransposeAsElementalConversion
       hlfir::Entity element =
           hlfir::getElementAt(loc, builder, array, transposedIndices);
       hlfir::Entity val = hlfir::loadTrivialScalar(loc, builder, element);
-      return val;
+      return {val, std::nullopt};
     };
     hlfir::ElementalOp elementalOp = hlfir::genElementalOp(
         loc, builder, elementType, resultShape, typeParams, genKernel,
@@ -1179,8 +1181,9 @@ mlir::LogicalResult ReductionAsElementalConverter::convert() {
       maskValue = genMaskValue(mask, isPresentPred, {});
   }
 
-  auto genKernel = [&](mlir::Location loc, fir::FirOpBuilder &builder,
-                       mlir::ValueRange inputIndices) -> hlfir::Entity {
+  auto genKernel =
+      [&](mlir::Location loc, fir::FirOpBuilder &builder,
+          mlir::ValueRange inputIndices) -> hlfir::ElementalKernelResult {
     // Loop over all indices in the DIM dimension, and reduce all values.
     // If DIM is not present, do total reduction.
 
@@ -1247,11 +1250,11 @@ mlir::LogicalResult ReductionAsElementalConverter::convert() {
     llvm::SmallVector<mlir::Value, 1> reductionFinalValues =
         hlfir::genLoopNestWithReductions(
             loc, builder, extents, reductionInitValues, genBody, isUnordered());
-    return genFinalResult(reductionFinalValues);
+    return {genFinalResult(reductionFinalValues), std::nullopt};
   };
 
   if (isTotalReduce) {
-    hlfir::Entity result = genKernel(loc, builder, mlir::ValueRange{});
+    hlfir::Entity result = genKernel(loc, builder, mlir::ValueRange{}).first;
     rewriter.replaceOp(op, result);
     return mlir::success();
   }
@@ -1766,8 +1769,9 @@ class ArrayShiftConversion : public mlir::OpRewritePattern<Op> {
       std::tie(boundaryVal, boundaryIsScalarPred) =
           genScalarBoundaryForEOShift(loc, builder, op);
 
-    auto genKernel = [&](mlir::Location loc, fir::FirOpBuilder &builder,
-                         mlir::ValueRange inputIndices) -> hlfir::Entity {
+    auto genKernel =
+        [&](mlir::Location loc, fir::FirOpBuilder &builder,
+            mlir::ValueRange inputIndices) -> hlfir::ElementalKernelResult {
       llvm::SmallVector<mlir::Value, maxRank> indices{inputIndices};
       if (!shiftVal) {
         // When the array is not a vector, section
@@ -1831,7 +1835,7 @@ class ArrayShiftConversion : public mlir::OpRewritePattern<Op> {
                 .genElse(
                     [&]() { fir::ResultOp::create(builder, loc, boundaryVal); })
                 .getResults()[0];
-        return hlfir::Entity{result};
+        return {hlfir::Entity{result}, std::nullopt};
       } else {
         // CSHIFT:
         // Element i of the result (1-based) is element
@@ -1861,7 +1865,7 @@ class ArrayShiftConversion : public mlir::OpRewritePattern<Op> {
         indices[dimVal - 1] = newIndex;
         hlfir::Entity element =
             hlfir::getElementAt(loc, builder, array, indices);
-        return hlfir::loadTrivialScalar(loc, builder, element);
+        return {hlfir::loadTrivialScalar(loc, builder, element), std::nullopt};
       }
     };
 
@@ -2942,8 +2946,9 @@ class MatmulConversion : public mlir::OpRewritePattern<Op> {
                      mlir::Value innerProductExtent) {
     mlir::OpBuilder::InsertionGuard guard(builder);
     mlir::Type resultElementType = resultType.getElementType();
-    auto genKernel = [&](mlir::Location loc, fir::FirOpBuilder &builder,
-                         mlir::ValueRange resultIndices) -> hlfir::Entity {
+    auto genKernel =
+        [&](mlir::Location loc, fir::FirOpBuilder &builder,
+            mlir::ValueRange resultIndices) -> hlfir::ElementalKernelResult {
       mlir::Value initValue =
           fir::factory::createZeroValue(builder, loc, resultElementType);
       // The inner product loop may be unordered if FastMathFlags::reassoc
@@ -2996,7 +3001,7 @@ class MatmulConversion : public mlir::OpRewritePattern<Op> {
       llvm::SmallVector<mlir::Value, 1> innerProductValue =
           hlfir::genLoopNestWithReductions(loc, builder, {innerProductExtent},
                                            {initValue}, genBody, isUnordered);
-      return hlfir::Entity{innerProductValue[0]};
+      return {hlfir::Entity{innerProductValue[0]}, std::nullopt};
     };
     hlfir::ElementalOp elementalOp = hlfir::genElementalOp(
         loc, builder, resultElementType, resultShape, /*typeParams=*/{},
@@ -3145,8 +3150,9 @@ class ReshapeAsElementalConversion
           builder.createIntegerConstant(loc, indexType, idx + 1)));
     auto resultShape = fir::ShapeOp::create(builder, loc, resultExtents);
 
-    auto genKernel = [&](mlir::Location loc, fir::FirOpBuilder &builder,
-                         mlir::ValueRange inputIndices) -> hlfir::Entity {
+    auto genKernel =
+        [&](mlir::Location loc, fir::FirOpBuilder &builder,
+            mlir::ValueRange inputIndices) -> hlfir::ElementalKernelResult {
       mlir::Value linearIndex =
           computeLinearIndex(loc, builder, resultExtents, inputIndices);
       fir::IfOp ifOp;
@@ -3195,7 +3201,7 @@ class ReshapeAsElementalConversion
         arrayElement = ifOp.getResult(0);
       }
 
-      return hlfir::Entity{arrayElement};
+      return {hlfir::Entity{arrayElement}, std::nullopt};
     };
     hlfir::ElementalOp elementalOp = hlfir::genElementalOp(
         loc, builder, elementType, resultShape, typeParams, genKernel,
diff --git a/flang/lib/Optimizer/Support/AllocationPolicy.cpp b/flang/lib/Optimizer/Support/AllocationPolicy.cpp
index e0cdbeff2a97fa..0a3e00a5ab464a 100644
--- a/flang/lib/Optimizer/Support/AllocationPolicy.cpp
+++ b/flang/lib/Optimizer/Support/AllocationPolicy.cpp
@@ -12,6 +12,7 @@
 
 #include "flang/Optimizer/Support/AllocationPolicy.h"
 #include "flang/Optimizer/Dialect/FIRAttr.h"
+#include "flang/Optimizer/Dialect/FIROps.h"
 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
 #include "flang/Optimizer/Dialect/FIRType.h"
 #include "mlir/IR/BuiltinOps.h"
@@ -128,11 +129,23 @@ bool fir::shouldAllocateOnStack(const PendingAllocationInfo &info,
                                    stackBytesUsed);
 }
 
+bool fir::isCharacterTemporary(const AllocationInfo &info) {
+  auto allocmem = mlir::dyn_cast_if_present<fir::AllocMemOp>(info.op);
+  return allocmem && info.isTemporary &&
+         mlir::isa<fir::CharacterType>(allocmem.getAllocatedType());
+}
+
 fir::AllocationPlacement
 fir::decideAllocationPlacement(const AllocationInfo &info,
                                const AllocationPolicy &basePolicy,
                                std::size_t stackBytesUsed) {
   using P = fir::AllocationPlacement;
+  // Scalar character expression buffers retain their historical stack
+  // storage independently of the array size policy, including in device
+  // regions. The caller still has to prove the lifetime is safe.
+  if (isCharacterTemporary(info))
+    return P::Stack;
+
   AllocationPolicy policy = policyFor(info, basePolicy);
 
   // An allocation that is not known to be dynamic but whose size cannot be
diff --git a/flang/lib/Optimizer/Transforms/AllocationPlacement.cpp b/flang/lib/Optimizer/Transforms/AllocationPlacement.cpp
index a630460dc9e694..b7e4064e44e55f 100644
--- a/flang/lib/Optimizer/Transforms/AllocationPlacement.cpp
+++ b/flang/lib/Optimizer/Transforms/AllocationPlacement.cpp
@@ -116,6 +116,12 @@ static fir::AllocationPlacement
 decideLegacyPlacement(const fir::AllocationInfo &info, bool stackArrays,
                       bool dynamicArrayOnHeap) {
   using P = fir::AllocationPlacement;
+  // Character expression buffers retain their historical stack storage, unless
+  // -fdynamic-heap-array asks for runtime-sized allocations to be on the heap,
+  // which the memory-allocation-opt pass applied to them.
+  if (fir::isCharacterTemporary(info))
+    return !stackArrays && dynamicArrayOnHeap && info.isDynamic ? P::Leave
+                                                                : P::Stack;
   if (stackArrays)
     return info.isCurrentlyOnStack || fir::isInOffloadRegion(info.context)
                ? P::Leave
@@ -207,11 +213,17 @@ void AllocationPlacementPass::runOnOperation() {
         return;
     }
 
-    // Only array allocations are considered, except that, like the
-    // memory-allocation-opt pass, legacy mode may move any allocation with a
-    // runtime size to the heap.
+    // Only array allocations are considered, with two exceptions. Character
+    // expression buffers carry explicit lifetimes, just like array
+    // temporaries, but retain their historical preference for stack storage
+    // independently of the array size policy. Only move them when the shared
+    // analysis can prove that their stack storage is safely reclaimed. And,
+    // like the memory-allocation-opt pass, legacy mode may move any allocation
+    // with a runtime size to the heap.
     mlir::Type inTy = alloca ? alloca.getInType() : allocmem.getAllocatedType();
-    if (!mlir::isa<fir::SequenceType>(inTy) &&
+    bool isCharacterTemp = allocmem && mlir::isa<fir::CharacterType>(inTy) &&
+                           isTemporaryAllocation(op);
+    if (!mlir::isa<fir::SequenceType>(inTy) && !isCharacterTemp &&
         !(legacy && alloca && alloca.isDynamic()))
       return;
 
diff --git a/flang/lib/Optimizer/Transforms/StackArrays.cpp b/flang/lib/Optimizer/Transforms/StackArrays.cpp
index 6b8edde0c2d927..70441c1468ca41 100644
--- a/flang/lib/Optimizer/Transforms/StackArrays.cpp
+++ b/flang/lib/Optimizer/Transforms/StackArrays.cpp
@@ -249,7 +249,15 @@ static mlir::Value lookThroughDeclaresAndConverts(mlir::Value value) {
       value = declareOp.getMemref();
     else if (auto convertOp = llvm::dyn_cast<fir::ConvertOp>(op))
       value = convertOp->getOperand(0);
-    else
+    else if (auto noReassoc = llvm::dyn_cast<fir::NoReassocOp>(op))
+      value = noReassoc.getVal();
+    else if (auto boxAddr = llvm::dyn_cast<fir::BoxAddrOp>(op)) {
+      auto box = lookThroughDeclaresAndConverts(boxAddr.getVal());
+      if (auto embox = box.getDefiningOp<fir::EmboxCharOp>())
+        value = embox.getMemref();
+      else
+        return value;
+    } else
       return value;
   }
   return value;
@@ -275,9 +283,10 @@ mlir::LogicalResult AllocationAnalysis::visitOperation(
     }
 
     auto retTy = allocmem.getAllocatedType();
-    if (!mlir::isa<fir::SequenceType>(retTy)) {
-      LLVM_DEBUG(llvm::dbgs()
-                 << "--Allocation is not for an array: skipping\n");
+    if (!mlir::isa<fir::SequenceType, fir::CharacterType>(retTy)) {
+      LLVM_DEBUG(
+          llvm::dbgs()
+          << "--Allocation is not for an array or character: skipping\n");
       return mlir::success();
     }
 
@@ -417,11 +426,12 @@ fir::StackArraysAnalysisWrapper::analyseFunction(mlir::Operation *func) {
   // through the function because otherwise the allocation may have an intende
   // lifetime longer than the current stack frame (e.g. a heap allocation which
   // is then freed by another function).
+  llvm::DenseMap<mlir::Block *, bool> blockCanSaveRestore;
   for (mlir::Value freedValue : freedValues) {
     fir::AllocMemOp allocmem = freedValue.getDefiningOp<fir::AllocMemOp>();
     InsertionPoint insertionPoint =
         AllocMemConversion::findAllocaInsertionPoint(
-            allocmem, allocToFreeMemMap[allocmem]);
+            allocmem, allocToFreeMemMap[allocmem], blockCanSaveRestore);
     if (insertionPoint)
       candidateOps.insert({allocmem, insertionPoint});
   }
@@ -539,7 +549,8 @@ static bool isInStackGrowingLoop(mlir::Operation *op) {
 
 fir::InsertionPoint fir::AllocMemConversion::findAllocaInsertionPoint(
     fir::AllocMemOp &oldAlloc,
-    const llvm::SmallVector<mlir::Operation *> &freeOps) {
+    const llvm::SmallVector<mlir::Operation *> &freeOps,
+    llvm::DenseMap<mlir::Block *, bool> &blockCanSaveRestore) {
   // Ideally the alloca should be inserted at the end of the function entry
   // block so that we do not allocate stack space in a loop. However,
   // the operands to the alloca may not be available that early, so insert it
@@ -559,7 +570,8 @@ fir::InsertionPoint fir::AllocMemConversion::findAllocaInsertionPoint(
       if (isInStackGrowingLoop(oldAllocOp)) {
         // where we want to put it is in a loop, and even the old location is in
         // a loop. Give up.
-        return findAllocaLoopInsertionPoint(oldAlloc, freeOps);
+        return findAllocaLoopInsertionPoint(oldAlloc, freeOps,
+                                            blockCanSaveRestore);
       }
       return {oldAllocOp};
     }
@@ -649,32 +661,32 @@ fir::InsertionPoint fir::AllocMemConversion::findAllocaInsertionPoint(
 
 fir::InsertionPoint fir::AllocMemConversion::findAllocaLoopInsertionPoint(
     fir::AllocMemOp &oldAlloc,
-    const llvm::SmallVector<mlir::Operation *> &freeOps) {
-  mlir::Operation *oldAllocOp = oldAlloc;
-  // This is only called as a last resort. We should try to insert at the
-  // location of the old allocation, which is inside of a loop, using
-  // llvm.stacksave/llvm.stackrestore
-
-  assert(freeOps.size() && "DFA should only return freed memory");
-
-  // Don't attempt to reason about a stacksave/stackrestore between different
-  // blocks
+    const llvm::SmallVector<mlir::Operation *> &freeOps,
+    llvm::DenseMap<mlir::Block *, bool> &blockCanSaveRestore) {
+  mlir::Block *block = oldAlloc->getBlock();
+  assert(!freeOps.empty() && "DFA should only return freed memory");
+  // A single block scope reclaims every promoted allocation together,
+  // regardless of whether the individual lifetimes are nested or crossing.
   for (mlir::Operation *free : freeOps)
-    if (free->getBlock() != oldAllocOp->getBlock())
+    if (free->getBlock() != block)
       return {nullptr};
 
-  // Check that there aren't any other stack allocations in between the
-  // stack save and stack restore
-  // note: for flang generated temporaries there should only be one free op
-  for (mlir::Operation *free : freeOps) {
-    for (mlir::Operation *op = oldAlloc; op && op != free;
-         op = op->getNextNode()) {
-      if (mlir::isa<fir::AllocaOp>(op))
-        return {nullptr};
-    }
+  auto [it, inserted] = blockCanSaveRestore.try_emplace(block, false);
+  if (inserted) {
+    // Do not reclaim pre-existing stack storage or interfere with another
+    // stack scope. Nested heap allocations are analyzed independently and
+    // either stay on the heap or receive a safe allocation scope of their own.
+    auto walkResult = block->walk([&](mlir::Operation *op) {
+      return mlir::isa<fir::AllocaOp, mlir::LLVM::AllocaOp,
+                       mlir::LLVM::StackSaveOp, mlir::LLVM::StackRestoreOp>(op)
+                 ? mlir::WalkResult::interrupt()
+                 : mlir::WalkResult::advance();
+    });
+    it->second = !walkResult.wasInterrupted();
   }
-
-  return InsertionPoint{oldAllocOp, /*shouldStackSaveRestore=*/true};
+  if (!it->second)
+    return {nullptr};
+  return InsertionPoint{oldAlloc.getOperation(), /*saveRestoreStack=*/true};
 }
 
 std::optional<fir::AllocaOp>
@@ -732,18 +744,16 @@ visitFreeMemOp(fir::AllocMemOp oldAlloc,
 
 void fir::AllocMemConversion::insertStackSaveRestore(
     fir::AllocMemOp oldAlloc, mlir::PatternRewriter &rewriter) const {
+  mlir::Block *block = oldAlloc->getBlock();
+  if (!blocksWithStackSaveRestore.insert(block).second)
+    return;
   mlir::OpBuilder::InsertionGuard insertGuard(rewriter);
   auto mod = oldAlloc->getParentOfType<mlir::ModuleOp>();
   fir::FirOpBuilder builder{rewriter, mod};
-
-  builder.setInsertionPoint(oldAlloc);
+  builder.setInsertionPointToStart(block);
   mlir::Value sp = builder.genStackSave(oldAlloc.getLoc());
-
-  auto createStackRestoreCall = [&](mlir::Operation *user) {
-    builder.setInsertionPoint(user);
-    builder.genStackRestore(user->getLoc(), sp);
-  };
-  visitFreeMemOp(oldAlloc, createStackRestoreCall);
+  builder.setInsertionPoint(block->getTerminator());
+  builder.genStackRestore(oldAlloc.getLoc(), sp);
 }
 
 void fir::AllocMemConversion::insertLifetimeMarkers(
diff --git a/flang/lib/Optimizer/Transforms/StackArrays.h b/flang/lib/Optimizer/Transforms/StackArrays.h
index d4f0e99943e993..d979baaee31685 100644
--- a/flang/lib/Optimizer/Transforms/StackArrays.h
+++ b/flang/lib/Optimizer/Transforms/StackArrays.h
@@ -28,6 +28,7 @@
 #include "mlir/Interfaces/DataLayoutInterfaces.h"
 #include "mlir/Support/TypeID.h"
 #include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
 #include "llvm/ADT/PointerUnion.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/Support/Casting.h"
@@ -67,8 +68,8 @@ class InsertionPoint {
   mlir::Block *tryGetBlock() const { return tryGetPtr<mlir::Block>(); }
 
   /// Get whether the stack should be saved/restored. If yes, an llvm.stacksave
-  /// intrinsic should be added before the alloca, and an llvm.stackrestore
-  /// intrinsic should be added where the freemem is
+  /// intrinsic should be added at the start of the allocation block, and an
+  /// llvm.stackrestore intrinsic should be added before its terminator.
   bool shouldSaveRestoreStack() const { return saveRestoreStack; }
 
   operator bool() const { return tryGetOperation() || tryGetBlock(); }
@@ -122,9 +123,10 @@ class AllocMemConversion : public mlir::OpRewritePattern<fir::AllocMemOp> {
 
   /// Determine where to insert the alloca operation. The returned value should
   /// be checked to see if it is inside a loop
-  static InsertionPoint
-  findAllocaInsertionPoint(fir::AllocMemOp &oldAlloc,
-                           const llvm::SmallVector<mlir::Operation *> &freeOps);
+  static InsertionPoint findAllocaInsertionPoint(
+      fir::AllocMemOp &oldAlloc,
+      const llvm::SmallVector<mlir::Operation *> &freeOps,
+      llvm::DenseMap<mlir::Block *, bool> &blockCanSaveRestore);
 
 private:
   /// Handle to the DFA (already run)
@@ -132,19 +134,21 @@ class AllocMemConversion : public mlir::OpRewritePattern<fir::AllocMemOp> {
 
   const std::optional<mlir::DataLayout> &dl;
   const std::optional<fir::KindMapping> &kindMap;
+  mutable llvm::DenseSet<mlir::Block *> blocksWithStackSaveRestore;
 
   /// If we failed to find an insertion point not inside a loop, see if it would
   /// be safe to use an llvm.stacksave/llvm.stackrestore inside the loop
   static InsertionPoint findAllocaLoopInsertionPoint(
       fir::AllocMemOp &oldAlloc,
-      const llvm::SmallVector<mlir::Operation *> &freeOps);
+      const llvm::SmallVector<mlir::Operation *> &freeOps,
+      llvm::DenseMap<mlir::Block *, bool> &blockCanSaveRestore);
 
   /// Returns the alloca if it was successfully inserted, otherwise {}
   std::optional<fir::AllocaOp>
   insertAlloca(fir::AllocMemOp &oldAlloc,
                mlir::PatternRewriter &rewriter) const;
 
-  /// Inserts a stacksave before oldAlloc and a stackrestore after each freemem
+  /// Insert one stacksave/stackrestore pair for the entire allocation block.
   void insertStackSaveRestore(fir::AllocMemOp oldAlloc,
                               mlir::PatternRewriter &rewriter) const;
   /// Emit lifetime markers for newAlloc between oldAlloc and each freemem.
diff --git a/flang/test/Fir/allocation-placement-pipeline.fir b/flang/test/Fir/allocation-placement-pipeline.fir
index 8362c2bc99a70f..c13b0322e0df7c 100644
--- a/flang/test/Fir/allocation-placement-pipeline.fir
+++ b/flang/test/Fir/allocation-placement-pipeline.fir
@@ -5,8 +5,8 @@
 
 // RUN: tco -enable-allocation-placement %s --mlir-pass-statistics --mlir-pass-statistics-display=pipeline -o /dev/null 2>&1 | FileCheck %s --check-prefix=PASSES
 // RUN: tco %s --mlir-pass-statistics --mlir-pass-statistics-display=pipeline -o /dev/null 2>&1 | FileCheck %s --check-prefix=PASSES
-// RUN: tco -enable-allocation-placement %s | FileCheck %s --check-prefix=NEW
-// RUN: tco %s | FileCheck %s --check-prefix=OLD
+// RUN: tco -enable-allocation-placement %s | FileCheck %s --check-prefixes=NEW,CHAR
+// RUN: tco %s | FileCheck %s --check-prefixes=OLD,CHAR
 
 // REQUIRES: asserts
 
@@ -33,3 +33,28 @@ func.func @small_temp() {
   fir.freemem %0 : !fir.heap<!fir.array<10xi32>>
   return
 }
+
+// Character expression buffers go on the stack in both cases, and their
+// storage is reclaimed in each iteration of an unstructured loop.
+// CHAR-LABEL: define void @character_in_cfg_loop
+// CHAR: call ptr @llvm.stacksave
+// CHAR-NOT: @malloc
+// CHAR: alloca i8, i64
+// CHAR-NOT: @malloc
+// CHAR: call void @llvm.stackrestore
+
+func.func private @extent() -> index
+func.func private @use_char(!fir.ref<!fir.char<1,?>>)
+
+func.func @character_in_cfg_loop(%again: i1) {
+  cf.br ^loop
+^loop:
+  %n = fir.call @extent() : () -> index
+  %0 = fir.allocmem !fir.char<1,?>(%n : index)
+  %1 = fir.convert %0 : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+  fir.call @use_char(%1) : (!fir.ref<!fir.char<1,?>>) -> ()
+  fir.freemem %0 : !fir.heap<!fir.char<1,?>>
+  cf.cond_br %again, ^loop, ^exit
+^exit:
+  return
+}
diff --git a/flang/test/HLFIR/as_expr-codegen.fir b/flang/test/HLFIR/as_expr-codegen.fir
index 61824c3019dbd9..da1343572e7cc9 100644
--- a/flang/test/HLFIR/as_expr-codegen.fir
+++ b/flang/test/HLFIR/as_expr-codegen.fir
@@ -5,19 +5,22 @@
 func.func @char_expr(%addr: !fir.ref<!fir.char<1,?>>, %len: index) {
   %0:2 = hlfir.declare %addr typeparams %len uniq_name("c") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
   %1 = hlfir.as_expr %0#0 : (!fir.boxchar<1>) -> !hlfir.expr<!fir.char<1,?>>
+  hlfir.destroy %1 : !hlfir.expr<!fir.char<1,?>>
   return
 }
 // CHECK-LABEL:   func.func @char_expr(
 // CHECK-SAME:    %[[VAL_0:.*]]: !fir.ref<!fir.char<1,?>>,
 // CHECK-SAME:    %[[VAL_1:.*]]: index) {
 // CHECK:  %[[VAL_2:.*]]:2 = hlfir.declare %[[VAL_0]] typeparams %[[VAL_1]] uniq_name("c") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:  %[[VAL_3:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_1]] : index) <{bindc_name = ".tmp"}>
-// CHECK:  %[[VAL_4:.*]]:2 = hlfir.declare %[[VAL_3]] typeparams %[[VAL_1]] uniq_name(".tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:  %[[VAL_3:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_1]] : index) <{bindc_name = ".tmp", uniq_name = ""}>
+// CHECK:  %[[VAL_4:.*]]:2 = hlfir.declare %[[VAL_3]] typeparams %[[VAL_1]] uniq_name(".tmp") : (!fir.heap<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.heap<!fir.char<1,?>>)
 // CHECK:  hlfir.assign %[[VAL_2]]#0 to %[[VAL_4]]#0 temporary_lhs : !fir.boxchar<1>, !fir.boxchar<1>
-// CHECK:  %[[VAL_5:.*]] = arith.constant false
+// CHECK:  %[[VAL_5:.*]] = arith.constant true
 // CHECK:  %[[VAL_6:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:  %[[VAL_7:.*]] = fir.insert_value %[[VAL_6]], %[[VAL_5]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:  %[[VAL_8:.*]] = fir.insert_value %[[VAL_7]], %[[VAL_4]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
+// CHECK:  %[[VAL_11:.*]] = fir.box_addr %[[VAL_4]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:  fir.freemem %[[VAL_11]] : !fir.heap<!fir.char<1,?>>
 
 func.func @char_expr_2(%addr: !fir.ref<!fir.char<1,10>>, %len: index) {
   %0:2 = hlfir.declare %addr typeparams %len uniq_name("c") : (!fir.ref<!fir.char<1,10>>, index) -> (!fir.ref<!fir.char<1,10>>, !fir.ref<!fir.char<1,10>>)
diff --git a/flang/test/HLFIR/associate-codegen.fir b/flang/test/HLFIR/associate-codegen.fir
index bc6c33865ea6e6..0de4d5a4d574ca 100644
--- a/flang/test/HLFIR/associate-codegen.fir
+++ b/flang/test/HLFIR/associate-codegen.fir
@@ -76,11 +76,11 @@ func.func @associate_char(%arg0: !fir.boxchar<1> ) {
 // CHECK:           %[[VAL_5:.*]] = fir.undefined !fir.ref<!fir.char<1>>
 // CHECK:           %[[VAL_6:.*]]:2 = hlfir.declare %[[VAL_5]] typeparams %[[VAL_1]] uniq_name("char_literal") fortran_attrs<parameter> : (!fir.ref<!fir.char<1>>, index) -> (!fir.ref<!fir.char<1>>, !fir.ref<!fir.char<1>>)
 // CHECK:           %[[VAL_7:.*]] = arith.addi %[[VAL_2]]#1, %[[VAL_1]] : index
-// CHECK:           %[[VAL_8:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:           %[[VAL_8:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:           %[[VAL_9:.*]] = arith.constant 1 : i64
 // CHECK:           %[[VAL_10:.*]] = fir.convert %[[VAL_2]]#1 : (index) -> i64
 // CHECK:           %[[VAL_11:.*]] = arith.muli %[[VAL_9]], %[[VAL_10]] : i64
-// CHECK:           %[[VAL_13:.*]] = fir.convert %[[VAL_8]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:           %[[VAL_13:.*]] = fir.convert %[[VAL_8]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           %[[VAL_14:.*]] = fir.convert %[[VAL_3]]#1 : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           "llvm.intr.memmove"(%[[VAL_13]], %[[VAL_14]], %[[VAL_11]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:           %[[VAL_15:.*]] = arith.constant 1 : index
@@ -90,12 +90,13 @@ func.func @associate_char(%arg0: !fir.boxchar<1> ) {
 // CHECK:             %[[VAL_19:.*]] = fir.convert %[[VAL_6]]#0 : (!fir.ref<!fir.char<1>>) -> !fir.ref<!fir.array<1x!fir.char<1>>>
 // CHECK:             %[[VAL_20:.*]] = fir.coordinate_of %[[VAL_19]], %[[VAL_18]] : (!fir.ref<!fir.array<1x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             %[[VAL_21:.*]] = fir.load %[[VAL_20]] : !fir.ref<!fir.char<1>>
-// CHECK:             %[[VAL_22:.*]] = fir.convert %[[VAL_8]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:             %[[VAL_22:.*]] = fir.convert %[[VAL_8]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_23:.*]] = fir.coordinate_of %[[VAL_22]], %[[VAL_17]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             fir.store %[[VAL_21]] to %[[VAL_23]] : !fir.ref<!fir.char<1>>
 // CHECK:           }
-// CHECK:           %[[VAL_24:.*]]:2 = hlfir.declare %[[VAL_8]] typeparams %[[VAL_7]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:           %[[VAL_25:.*]] = arith.constant false
+// CHECK:           %[[VAL_8_REF:.*]] = fir.convert %[[VAL_8]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:           %[[VAL_24:.*]]:2 = hlfir.declare %[[VAL_8_REF]] typeparams %[[VAL_7]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:           %[[VAL_25:.*]] = arith.constant true
 // CHECK:           %[[VAL_26:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_27:.*]] = fir.insert_value %[[VAL_26]], %[[VAL_25]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_28:.*]] = fir.insert_value %[[VAL_27]], %[[VAL_24]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
@@ -105,6 +106,8 @@ func.func @associate_char(%arg0: !fir.boxchar<1> ) {
 // CHECK:           %[[VAL_32:.*]] = fir.insert_value %[[VAL_31]], %[[VAL_29]], [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_33:.*]] = fir.box_addr %[[VAL_29]] : (!fir.boxchar<1>) -> !fir.ref<!fir.char<1,?>>
 // CHECK:           fir.call @take_c(%[[VAL_29]]) : (!fir.boxchar<1>) -> ()
+// CHECK:           %[[VAL_34:.*]] = fir.convert %[[VAL_33]] : (!fir.ref<!fir.char<1,?>>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:           fir.freemem %[[VAL_34]] : !fir.heap<!fir.char<1,?>>
 // CHECK:           return
 // CHECK:         }
 
@@ -337,6 +340,8 @@ func.func @_QPtest_multiple_expr_uses_inside_elemental() {
     %42 = fir.convert %ci1 : (i1) -> !fir.logical<4>
     hlfir.yield_element %42 : !fir.logical<4>
   }
+  hlfir.destroy %23 : !hlfir.expr<?x!fir.logical<4>>
+  hlfir.destroy %20 : !hlfir.expr<!fir.char<1,?>>
   return
 }
 // CHECK-LABEL:   func.func @_QPtest_multiple_expr_uses_inside_elemental() {
@@ -354,13 +359,16 @@ func.func @_QPtest_multiple_expr_uses_inside_elemental() {
 // CHECK:           %[[VAL_13:.*]] = arith.constant true
 // CHECK:           %[[VAL_14:.*]] = arith.constant 1 : index
 // CHECK:           fir.do_loop %[[VAL_15:.*]] = %[[VAL_14]] to %[[VAL_9]] step %[[VAL_14]] unordered {
-// CHECK:             %[[VAL_16:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_4]] : index) <{bindc_name = ".tmp"}>
-// CHECK:             %[[VAL_18:.*]]:2 = hlfir.declare %[[VAL_16]] typeparams %[[VAL_4]] uniq_name(".tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:             %[[VAL_16:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_4]] : index) <{bindc_name = ".tmp", uniq_name = ""}>
+// CHECK:             %[[VAL_18:.*]]:2 = hlfir.declare %[[VAL_16]] typeparams %[[VAL_4]] uniq_name(".tmp") : (!fir.heap<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.heap<!fir.char<1,?>>)
 // CHECK:             hlfir.assign %[[VAL_5]]#0 to %[[VAL_18]]#0 temporary_lhs : !fir.boxchar<1>, !fir.boxchar<1>
-// CHECK:             %[[VAL_17:.*]] = arith.constant false
+// CHECK:             %[[VAL_17:.*]] = arith.constant true
 // CHECK:             %[[VAL_19:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:             %[[VAL_20:.*]] = fir.insert_value %[[VAL_19]], %[[VAL_17]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:             %[[VAL_21:.*]] = fir.insert_value %[[VAL_20]], %[[VAL_18]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
+// CHECK:             %[[VAL_28:.*]] = fir.convert %[[VAL_18]]#1 : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:             %[[VAL_29:.*]] = fir.convert %[[VAL_28]] : (!fir.ref<!fir.char<1,?>>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:             fir.freemem %[[VAL_29]] : !fir.heap<!fir.char<1,?>>
 // CHECK:             %[[VAL_22:.*]] = arith.constant true
 // CHECK:             %[[VAL_23:.*]] = fir.convert %[[VAL_22]] : (i1) -> !fir.logical<4>
 // CHECK:             %[[VAL_24:.*]] = hlfir.designate %[[VAL_12]]#0 (%[[VAL_15]])  : (!fir.box<!fir.array<?x!fir.logical<4>>>, index) -> !fir.ref<!fir.logical<4>>
@@ -369,6 +377,8 @@ func.func @_QPtest_multiple_expr_uses_inside_elemental() {
 // CHECK:           %[[VAL_25:.*]] = fir.undefined tuple<!fir.box<!fir.array<?x!fir.logical<4>>>, i1>
 // CHECK:           %[[VAL_26:.*]] = fir.insert_value %[[VAL_25]], %[[VAL_13]], [1 : index] : (tuple<!fir.box<!fir.array<?x!fir.logical<4>>>, i1>, i1) -> tuple<!fir.box<!fir.array<?x!fir.logical<4>>>, i1>
 // CHECK:           %[[VAL_27:.*]] = fir.insert_value %[[VAL_26]], %[[VAL_12]]#0, [0 : index] : (tuple<!fir.box<!fir.array<?x!fir.logical<4>>>, i1>, !fir.box<!fir.array<?x!fir.logical<4>>>) -> tuple<!fir.box<!fir.array<?x!fir.logical<4>>>, i1>
+// CHECK:           %[[VAL_30:.*]] = fir.box_addr %[[VAL_5]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:           fir.freemem %[[VAL_30]] : !fir.heap<!fir.char<1,?>>
 // CHECK:           return
 // CHECK:         }
 
diff --git a/flang/test/HLFIR/bufferize-conditional.fir b/flang/test/HLFIR/bufferize-conditional.fir
index 494b33b5f85982..406fec650f562e 100644
--- a/flang/test/HLFIR/bufferize-conditional.fir
+++ b/flang/test/HLFIR/bufferize-conditional.fir
@@ -256,7 +256,7 @@ func.func @test_char_array_static_len(%cond: i1, %a: !fir.ref<!fir.array<3x!fir.
 
 // --- Test 8: Scalar character (dynamic length) ---
 // tempBaseType is !fir.boxchar<1>. A non-move as_expr copies the yielded
-// variable into a stack temp (mustFree=false).
+// variable into a heap temp (mustFree=true).
 func.func @test_scalar_char_dynamic(%cond: i1, %a: !fir.boxchar<1>, %b: !fir.boxchar<1>) {
   %0 = hlfir.conditional %cond : (i1) -> !hlfir.expr<!fir.char<1,?>> {
     hlfir.yield %a : !fir.boxchar<1>
@@ -269,16 +269,21 @@ func.func @test_scalar_char_dynamic(%cond: i1, %a: !fir.boxchar<1>, %b: !fir.box
 // CHECK-LABEL: func.func @test_scalar_char_dynamic(
 // CHECK-SAME:    %[[COND:.*]]: i1, %[[A:.*]]: !fir.boxchar<1>, %[[B:.*]]: !fir.boxchar<1>)
 // CHECK:       %[[IF:.*]]:2 = fir.if %[[COND]] -> (!fir.boxchar<1>, i1) {
+// CHECK:         fir.allocmem !fir.char<1,?>
 // CHECK:         %[[T1:.*]]:2 = hlfir.declare %{{.*}} typeparams %{{.*}} uniq_name(".tmp")
 // CHECK:         hlfir.assign %[[A]] to %[[T1]]#0 temporary_lhs
-// CHECK:         %[[FALSE1:.*]] = arith.constant false
-// CHECK:         fir.result %[[T1]]#0, %[[FALSE1]] : !fir.boxchar<1>, i1
+// CHECK:         %[[TRUE1:.*]] = arith.constant true
+// CHECK:         fir.result %[[T1]]#0, %[[TRUE1]] : !fir.boxchar<1>, i1
 // CHECK:       } else {
+// CHECK:         fir.allocmem !fir.char<1,?>
 // CHECK:         %[[T2:.*]]:2 = hlfir.declare %{{.*}} typeparams %{{.*}} uniq_name(".tmp")
 // CHECK:         hlfir.assign %[[B]] to %[[T2]]#0 temporary_lhs
-// CHECK:         %[[FALSE2:.*]] = arith.constant false
-// CHECK:         fir.result %[[T2]]#0, %[[FALSE2]] : !fir.boxchar<1>, i1
+// CHECK:         %[[TRUE2:.*]] = arith.constant true
+// CHECK:         fir.result %[[T2]]#0, %[[TRUE2]] : !fir.boxchar<1>, i1
 // CHECK:       }
+// CHECK:       fir.if %[[IF]]#1 {
+// CHECK:         %[[ADDR:.*]] = fir.box_addr %[[IF]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:         fir.freemem %[[ADDR]] : !fir.heap<!fir.char<1,?>>
 
 // --- Test 9: Asymmetric branches (non-polymorphic + polymorphic) ---
 // One branch yields !fir.ref (non-polymorphic), the other !fir.class
@@ -363,12 +368,17 @@ func.func private @_QPfunc_alloc_char(!fir.boxchar<1>) -> !fir.box<!fir.heap<!fi
 // CHECK:         fir.freemem %[[HEAP]]
 // CHECK:         fir.result %[[BOXCHAR]], %[[TRUE]] : !fir.boxchar<1>, i1
 // CHECK:       } else {
-// Non-forwarding: variable copied into a stack temp (mustFree=false):
+// Non-forwarding: variable copied into a heap temp (mustFree=true):
+// CHECK:         fir.allocmem !fir.char<1,?>
 // CHECK:         %[[T:.*]]:2 = hlfir.declare %{{.*}} typeparams %{{.*}} uniq_name(".tmp")
 // CHECK:         hlfir.assign %[[ARG]] to %[[T]]#0 temporary_lhs
-// CHECK:         %[[FALSE:.*]] = arith.constant false
-// CHECK:         fir.result %[[T]]#0, %[[FALSE]] : !fir.boxchar<1>, i1
+// CHECK:         %[[TRUE2:.*]] = arith.constant true
+// CHECK:         fir.result %[[T]]#0, %[[TRUE2]] : !fir.boxchar<1>, i1
 // CHECK:       }
+// CHECK:       hlfir.assign %[[IF]]#0 to %[[ARG]]
+// CHECK:       fir.if %[[IF]]#1 {
+// CHECK:         %[[ADDR:.*]] = fir.box_addr %[[IF]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:         fir.freemem %[[ADDR]] : !fir.heap<!fir.char<1,?>>
 
 // --- Test 11: Array expr from hlfir.elemental (buffer forwarding) ---
 // When a branch yields an hlfir.expr produced by hlfir.elemental, the
diff --git a/flang/test/HLFIR/bufferize01.fir b/flang/test/HLFIR/bufferize01.fir
index fda8f81371f58c..5101bf6a0dfb14 100644
--- a/flang/test/HLFIR/bufferize01.fir
+++ b/flang/test/HLFIR/bufferize01.fir
@@ -128,7 +128,9 @@ func.func @_QPtest1() {
     %38 = fir.box_elesize %30 : (!fir.box<!fir.heap<!fir.array<1x!fir.char<1,?>>>>) -> index
     %39 = hlfir.apply %31, %arg0 typeparams %38 : (!hlfir.expr<1x!fir.char<1,?>>, index, index) -> !hlfir.expr<!fir.char<1,?>>
     %40 = hlfir.no_reassoc %39 : !hlfir.expr<!fir.char<1,?>>
-    hlfir.yield_element %40 : !hlfir.expr<!fir.char<1,?>>
+    hlfir.yield_element %40 : !hlfir.expr<!fir.char<1,?>> cleanup {
+      hlfir.destroy %40 : !hlfir.expr<!fir.char<1,?>>
+    }
   }
   %35:3 = hlfir.associate %34(%33) typeparams %32 uniq_name("adapt.valuebyref") : (!hlfir.expr<1x!fir.char<1,?>>, !fir.shape<1>, index) -> (!fir.box<!fir.array<1x!fir.char<1,?>>>, !fir.ref<!fir.array<1x!fir.char<1,?>>>, i1)
   %36 = fir.shape %c1 : (index) -> !fir.shape<1>
diff --git a/flang/test/HLFIR/char_extremum-bufferization.fir b/flang/test/HLFIR/char_extremum-bufferization.fir
index 76835c7715609e..120964f7bf3d36 100644
--- a/flang/test/HLFIR/char_extremum-bufferization.fir
+++ b/flang/test/HLFIR/char_extremum-bufferization.fir
@@ -33,13 +33,13 @@ func.func @_QPmax1(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_13:.*]] = arith.cmpi sgt, %[[VAL_12]], %[[C0_I32]] : i32
 // CHECK:   %[[VAL_14:.*]] = arith.select %[[VAL_13]], %[[VAL_5]]#1, %[[VAL_3]]#1 : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_15:.*]] = arith.select %[[VAL_13]], %[[VAL_4]]#1, %[[VAL_2]]#1 : index
-// CHECK:   %[[VAL_16:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_16:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_17:.*]] = arith.cmpi slt, %[[VAL_7]], %[[VAL_15]] : index
 // CHECK:   %[[VAL_18:.*]] = arith.select %[[VAL_17]], %[[VAL_7]], %[[VAL_15]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_19:.*]] = fir.convert %[[VAL_18]] : (index) -> i64
 // CHECK:   %[[VAL_20:.*]] = arith.muli %[[C1_I64]], %[[VAL_19]] : i64
-// CHECK:   %[[VAL_21:.*]] = fir.convert %[[VAL_16]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_21:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_22:.*]] = fir.convert %[[VAL_14]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_21]], %[[VAL_22]], %[[VAL_20]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1:.*]] = arith.constant 1 : index
@@ -49,16 +49,19 @@ func.func @_QPmax1(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_25:.*]] = fir.insert_value %[[VAL_24]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_0:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG3:.*]] = %[[VAL_18:.*]] to %[[VAL_23]] step %[[C1_0]] {
-// CHECK:     %[[VAL_30:.*]] = fir.convert %[[VAL_16]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_30:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_31:.*]] = fir.coordinate_of %[[VAL_30]], %[[ARG3]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_25:.*]] to %[[VAL_31]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_16]] typeparams %[[VAL_7]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:   %[[FALSE_1:.*]] = arith.constant false
+// CHECK:   %[[VAL_44:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:   %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_44]] typeparams %[[VAL_7]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:   %[[FALSE_1:.*]] = arith.constant true
 // CHECK:   %[[VAL_27:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_28:.*]] = fir.insert_value %[[VAL_27]], %[[FALSE_1]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_29:.*]] = fir.insert_value %[[VAL_28]], %[[VAL_26]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   hlfir.assign %[[VAL_26]]#0 to %[[VAL_1]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:   %[[VAL_45:.*]] = fir.box_addr %[[VAL_26]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:   fir.freemem %[[VAL_45]] : !fir.heap<!fir.char<1,?>>
 // CHECK:   return
 // CHECK: }
 
@@ -94,13 +97,13 @@ func.func @_QPmin1(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_13:.*]] = arith.cmpi slt, %[[VAL_12]], %[[C0_I32]] : i32
 // CHECK:   %[[VAL_14:.*]] = arith.select %[[VAL_13]], %[[VAL_5]]#1, %[[VAL_3]]#1 : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_15:.*]] = arith.select %[[VAL_13]], %[[VAL_4]]#1, %[[VAL_2]]#1 : index
-// CHECK:   %[[VAL_16:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_16:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_7]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_17:.*]] = arith.cmpi slt, %[[VAL_7]], %[[VAL_15]] : index
 // CHECK:   %[[VAL_18:.*]] = arith.select %[[VAL_17]], %[[VAL_7]], %[[VAL_15]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_19:.*]] = fir.convert %[[VAL_18]] : (index) -> i64
 // CHECK:   %[[VAL_20:.*]] = arith.muli %[[C1_I64]], %[[VAL_19]] : i64
-// CHECK:   %[[VAL_21:.*]] = fir.convert %[[VAL_16]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_21:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_22:.*]] = fir.convert %[[VAL_14]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_21]], %[[VAL_22]], %[[VAL_20]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1:.*]] = arith.constant 1 : index
@@ -110,16 +113,19 @@ func.func @_QPmin1(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_25:.*]] = fir.insert_value %[[VAL_24]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_0:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG3:.*]] = %[[VAL_18:.*]] to %[[VAL_23]] step %[[C1_0]] {
-// CHECK:     %[[VAL_30:.*]] = fir.convert %[[VAL_16]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_30:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_31:.*]] = fir.coordinate_of %[[VAL_30]], %[[ARG3]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_25:.*]] to %[[VAL_31]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_16]] typeparams %[[VAL_7]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:   %[[FALSE_1:.*]] = arith.constant false
+// CHECK:   %[[VAL_46:.*]] = fir.convert %[[VAL_16]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:   %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_46]] typeparams %[[VAL_7]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:   %[[FALSE_1:.*]] = arith.constant true
 // CHECK:   %[[VAL_27:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_28:.*]] = fir.insert_value %[[VAL_27]], %[[FALSE_1]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_29:.*]] = fir.insert_value %[[VAL_28]], %[[VAL_26]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   hlfir.assign %[[VAL_26]]#0 to %[[VAL_1]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:   %[[VAL_47:.*]] = fir.box_addr %[[VAL_26]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:   fir.freemem %[[VAL_47]] : !fir.heap<!fir.char<1,?>>
 // CHECK:   return
 // CHECK: }
 
@@ -188,13 +194,13 @@ func.func @_QPmax2(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_23:.*]] = fir.convert %[[VAL_13]] : (!fir.ref<!fir.char<1,20>>) -> !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_24:.*]] = arith.select %[[VAL_21]], %[[VAL_23]], %[[VAL_22]] : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_25:.*]] = arith.select %[[VAL_21]], %[[C20]], %[[C10]] : index
-// CHECK:   %[[VAL_26:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_15]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_26:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_15]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_27:.*]] = arith.cmpi slt, %[[VAL_15]], %[[VAL_25]] : index
 // CHECK:   %[[VAL_28:.*]] = arith.select %[[VAL_27]], %[[VAL_15]], %[[VAL_25]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_29:.*]] = fir.convert %[[VAL_28]] : (index) -> i64
 // CHECK:   %[[VAL_30:.*]] = arith.muli %[[C1_I64]], %[[VAL_29]] : i64
-// CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_32:.*]] = fir.convert %[[VAL_24]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_31]], %[[VAL_32]], %[[VAL_30]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1_3:.*]] = arith.constant 1 : index
@@ -204,19 +210,21 @@ func.func @_QPmax2(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_35:.*]] = fir.insert_value %[[VAL_34]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_4:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG3:.*]] = %[[VAL_28:.*]] to %[[VAL_33]] step %[[C1_4]] {
-// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_43:.*]] = fir.coordinate_of %[[VAL_42]], %[[ARG3]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_35:.*]] to %[[VAL_43]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_36:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,20>>
+// CHECK:   %[[VAL_36:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,20>>
 // CHECK:   %[[VAL_37:.*]]:2 = hlfir.declare %[[VAL_36]] typeparams %[[VAL_15]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,20>>, index) -> (!fir.ref<!fir.char<1,20>>, !fir.ref<!fir.char<1,20>>)
-// CHECK:   %[[FALSE_5:.*]] = arith.constant false
+// CHECK:   %[[FALSE_5:.*]] = arith.constant true
 // CHECK:   %[[VAL_38:.*]] = fir.undefined tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[VAL_39:.*]] = fir.insert_value %[[VAL_38]], %[[FALSE_5]], [1 : index] : (tuple<!fir.ref<!fir.char<1,20>>, i1>, i1) -> tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[VAL_40:.*]] = fir.insert_value %[[VAL_39]], %[[VAL_37]]#0, [0 : index] : (tuple<!fir.ref<!fir.char<1,20>>, i1>, !fir.ref<!fir.char<1,20>>) -> tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[C1_6:.*]] = arith.constant 1 : index
 // CHECK:   %[[VAL_41:.*]] = hlfir.designate %[[VAL_3]]#0 (%[[C1_6]])  typeparams %[[VAL_0]]#1 : (!fir.box<!fir.array<100x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
 // CHECK:   hlfir.assign %[[VAL_37]]#0 to %[[VAL_41:.*]] : !fir.ref<!fir.char<1,20>>, !fir.boxchar<1>
+// CHECK:   %[[VAL_48:.*]] = fir.convert %[[VAL_37]]#0 : (!fir.ref<!fir.char<1,20>>) -> !fir.heap<!fir.char<1,20>>
+// CHECK:   fir.freemem %[[VAL_48]] : !fir.heap<!fir.char<1,20>>
 // CHECK:   return
 // CHECK: }
 
@@ -285,13 +293,13 @@ func.func @_QPmin2(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_23:.*]] = fir.convert %[[VAL_13]] : (!fir.ref<!fir.char<1,20>>) -> !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_24:.*]] = arith.select %[[VAL_21]], %[[VAL_23]], %[[VAL_22]] : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_25:.*]] = arith.select %[[VAL_21]], %[[C20]], %[[C10]] : index
-// CHECK:   %[[VAL_26:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_15]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_26:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_15]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_27:.*]] = arith.cmpi slt, %[[VAL_15]], %[[VAL_25]] : index
 // CHECK:   %[[VAL_28:.*]] = arith.select %[[VAL_27]], %[[VAL_15]], %[[VAL_25]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_29:.*]] = fir.convert %[[VAL_28]] : (index) -> i64
 // CHECK:   %[[VAL_30:.*]] = arith.muli %[[C1_I64]], %[[VAL_29]] : i64
-// CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_32:.*]] = fir.convert %[[VAL_24]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_31]], %[[VAL_32]], %[[VAL_30]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1_3:.*]] = arith.constant 1 : index
@@ -301,19 +309,21 @@ func.func @_QPmin2(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_35:.*]] = fir.insert_value %[[VAL_34]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_4:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG3:.*]] = %[[VAL_28:.*]] to %[[VAL_33]] step %[[C1_4]] {
-// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_43:.*]] = fir.coordinate_of %[[VAL_42]], %[[ARG3]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_35:.*]] to %[[VAL_43]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_36:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,20>>
+// CHECK:   %[[VAL_36:.*]] = fir.convert %[[VAL_26]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,20>>
 // CHECK:   %[[VAL_37:.*]]:2 = hlfir.declare %[[VAL_36]] typeparams %[[VAL_15]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,20>>, index) -> (!fir.ref<!fir.char<1,20>>, !fir.ref<!fir.char<1,20>>)
-// CHECK:   %[[FALSE_5:.*]] = arith.constant false
+// CHECK:   %[[FALSE_5:.*]] = arith.constant true
 // CHECK:   %[[VAL_38:.*]] = fir.undefined tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[VAL_39:.*]] = fir.insert_value %[[VAL_38]], %[[FALSE_5]], [1 : index] : (tuple<!fir.ref<!fir.char<1,20>>, i1>, i1) -> tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[VAL_40:.*]] = fir.insert_value %[[VAL_39]], %[[VAL_37]]#0, [0 : index] : (tuple<!fir.ref<!fir.char<1,20>>, i1>, !fir.ref<!fir.char<1,20>>) -> tuple<!fir.ref<!fir.char<1,20>>, i1>
 // CHECK:   %[[C1_6:.*]] = arith.constant 1 : index
 // CHECK:   %[[VAL_41:.*]] = hlfir.designate %[[VAL_3]]#0 (%[[C1_6]])  typeparams %[[VAL_0]]#1 : (!fir.box<!fir.array<100x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
 // CHECK:   hlfir.assign %[[VAL_37]]#0 to %[[VAL_41:.*]] : !fir.ref<!fir.char<1,20>>, !fir.boxchar<1>
+// CHECK:   %[[VAL_49:.*]] = fir.convert %[[VAL_37]]#0 : (!fir.ref<!fir.char<1,20>>) -> !fir.heap<!fir.char<1,20>>
+// CHECK:   fir.freemem %[[VAL_49]] : !fir.heap<!fir.char<1,20>>
 // CHECK:   return
 // CHECK: }
 
@@ -363,13 +373,13 @@ func.func @_QPmax3(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_25:.*]] = arith.cmpi sgt, %[[VAL_24]], %[[C0_I32_0]] : i32
 // CHECK:   %[[VAL_26:.*]] = arith.select %[[VAL_25]], %[[VAL_7]]#1, %[[VAL_16]] : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_27:.*]] = arith.select %[[VAL_25]], %[[VAL_6]]#1, %[[VAL_17]] : index
-// CHECK:   %[[VAL_28:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_19]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_28:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_19]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_29:.*]] = arith.cmpi slt, %[[VAL_19]], %[[VAL_27]] : index
 // CHECK:   %[[VAL_30:.*]] = arith.select %[[VAL_29]], %[[VAL_19]], %[[VAL_27]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_30]] : (index) -> i64
 // CHECK:   %[[VAL_32:.*]] = arith.muli %[[C1_I64]], %[[VAL_31]] : i64
-// CHECK:   %[[VAL_33:.*]] = fir.convert %[[VAL_28]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_33:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_34:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_33]], %[[VAL_34]], %[[VAL_32]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1:.*]] = arith.constant 1 : index
@@ -379,16 +389,19 @@ func.func @_QPmax3(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_37:.*]] = fir.insert_value %[[VAL_36]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_1:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG4:.*]] = %[[VAL_30:.*]] to %[[VAL_35]] step %[[C1_1]] {
-// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_28]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_43:.*]] = fir.coordinate_of %[[VAL_42]], %[[ARG4]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_37:.*]] to %[[VAL_43]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_38:.*]]:2 = hlfir.declare %[[VAL_28]] typeparams %[[VAL_19]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:   %[[FALSE_2:.*]] = arith.constant false
+// CHECK:   %[[VAL_50:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:   %[[VAL_38:.*]]:2 = hlfir.declare %[[VAL_50]] typeparams %[[VAL_19]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:   %[[FALSE_2:.*]] = arith.constant true
 // CHECK:   %[[VAL_39:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_40:.*]] = fir.insert_value %[[VAL_39]], %[[FALSE_2]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_41:.*]] = fir.insert_value %[[VAL_40]], %[[VAL_38]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   hlfir.assign %[[VAL_38]]#0 to %[[VAL_1]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:   %[[VAL_51:.*]] = fir.box_addr %[[VAL_38]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:   fir.freemem %[[VAL_51]] : !fir.heap<!fir.char<1,?>>
 // CHECK:   return
 // CHECK: }
 
@@ -438,13 +451,13 @@ func.func @_QPmin3(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_25:.*]] = arith.cmpi slt, %[[VAL_24]], %[[C0_I32_0]] : i32
 // CHECK:   %[[VAL_26:.*]] = arith.select %[[VAL_25]], %[[VAL_7]]#1, %[[VAL_16]] : !fir.ref<!fir.char<1,?>>
 // CHECK:   %[[VAL_27:.*]] = arith.select %[[VAL_25]], %[[VAL_6]]#1, %[[VAL_17]] : index
-// CHECK:   %[[VAL_28:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_19]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:   %[[VAL_28:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_19]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:   %[[VAL_29:.*]] = arith.cmpi slt, %[[VAL_19]], %[[VAL_27]] : index
 // CHECK:   %[[VAL_30:.*]] = arith.select %[[VAL_29]], %[[VAL_19]], %[[VAL_27]] : index
 // CHECK:   %[[C1_I64:.*]] = arith.constant 1 : i64
 // CHECK:   %[[VAL_31:.*]] = fir.convert %[[VAL_30]] : (index) -> i64
 // CHECK:   %[[VAL_32:.*]] = arith.muli %[[C1_I64]], %[[VAL_31]] : i64
-// CHECK:   %[[VAL_33:.*]] = fir.convert %[[VAL_28]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:   %[[VAL_33:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   %[[VAL_34:.*]] = fir.convert %[[VAL_26]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:   "llvm.intr.memmove"(%[[VAL_33]], %[[VAL_34]], %[[VAL_32]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:   %[[C1:.*]] = arith.constant 1 : index
@@ -454,15 +467,18 @@ func.func @_QPmin3(%arg0: !fir.boxchar<1> {fir.bindc_name = "c1"}, %arg1: !fir.b
 // CHECK:   %[[VAL_37:.*]] = fir.insert_value %[[VAL_36]], %[[C32_I8]], [0 : index] : (!fir.char<1>, i8) -> !fir.char<1>
 // CHECK:   %[[C1_1:.*]] = arith.constant 1 : index
 // CHECK:   fir.do_loop %[[ARG4:.*]] = %[[VAL_30:.*]] to %[[VAL_35]] step %[[C1_1]] {
-// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_28]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:     %[[VAL_42:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:     %[[VAL_43:.*]] = fir.coordinate_of %[[VAL_42]], %[[ARG4]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:     fir.store %[[VAL_37:.*]] to %[[VAL_43]] : !fir.ref<!fir.char<1>>
 // CHECK:   }
-// CHECK:   %[[VAL_38:.*]]:2 = hlfir.declare %[[VAL_28]] typeparams %[[VAL_19]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:   %[[FALSE_2:.*]] = arith.constant false
+// CHECK:   %[[VAL_52:.*]] = fir.convert %[[VAL_28]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:   %[[VAL_38:.*]]:2 = hlfir.declare %[[VAL_52]] typeparams %[[VAL_19]] uniq_name(".tmp.char_extremum") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:   %[[FALSE_2:.*]] = arith.constant true
 // CHECK:   %[[VAL_39:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_40:.*]] = fir.insert_value %[[VAL_39]], %[[FALSE_2]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   %[[VAL_41:.*]] = fir.insert_value %[[VAL_40]], %[[VAL_38]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:   hlfir.assign %[[VAL_38]]#0 to %[[VAL_1]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:   %[[VAL_53:.*]] = fir.box_addr %[[VAL_38]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:   fir.freemem %[[VAL_53]] : !fir.heap<!fir.char<1,?>>
 // CHECK:   return
 // CHECK: }
diff --git a/flang/test/HLFIR/character-expression-lifetimes.fir b/flang/test/HLFIR/character-expression-lifetimes.fir
new file mode 100644
index 00000000000000..003899d91d1ece
--- /dev/null
+++ b/flang/test/HLFIR/character-expression-lifetimes.fir
@@ -0,0 +1,36 @@
+// RUN: fir-opt %s --canonicalize="region-simplify=disabled" --bufferize-hlfir --canonicalize="region-simplify=disabled" | FileCheck %s
+
+// Explicit cleanup of an intermediate expression survives association through
+// no_reassoc and releases the buffer after the comparison.
+// CHECK-LABEL: func.func @intermediate
+// CHECK: fir.allocmem !fir.char<1,?>
+// CHECK: hlfir.cmpchar
+// CHECK: fir.freemem
+// CHECK-NOT: fir.freemem
+// CHECK: return
+func.func @intermediate(%a: !fir.boxchar<1>, %b: !fir.boxchar<1>, %c: !fir.boxchar<1>, %n: index) -> i1 {
+  %x = hlfir.concat %a, %b len %n : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
+  %alias = hlfir.no_reassoc %x : !hlfir.expr<!fir.char<1,?>>
+  %assoc:3 = hlfir.associate %alias typeparams %n : (!hlfir.expr<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>, i1)
+  %test = hlfir.cmpchar eq %assoc#0 %c : (!fir.boxchar<1>, !fir.boxchar<1>) -> i1
+  hlfir.end_associate %assoc#1, %assoc#2 : !fir.ref<!fir.char<1,?>>, i1
+  hlfir.destroy %x : !hlfir.expr<!fir.char<1,?>>
+  return %test : i1
+}
+
+// An explicit cleanup in another CFG block must not be replaced or rejected
+// when inspecting the expression's other uses.
+// CHECK-LABEL: func.func @existing_cleanup
+// CHECK: fir.allocmem !fir.char<1,?>
+// CHECK: hlfir.assign
+// CHECK: fir.freemem
+// CHECK-NOT: fir.freemem
+// CHECK: return
+func.func @existing_cleanup(%a: !fir.boxchar<1>, %b: !fir.boxchar<1>, %out: !fir.boxchar<1>, %n: index) {
+  %x = hlfir.concat %a, %b len %n : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
+  cf.br ^next
+^next:
+  hlfir.assign %x to %out : !hlfir.expr<!fir.char<1,?>>, !fir.boxchar<1>
+  hlfir.destroy %x : !hlfir.expr<!fir.char<1,?>>
+  return
+}
diff --git a/flang/test/HLFIR/concat-bufferization.fir b/flang/test/HLFIR/concat-bufferization.fir
index 063c85175a5f21..234fb95a589cc7 100644
--- a/flang/test/HLFIR/concat-bufferization.fir
+++ b/flang/test/HLFIR/concat-bufferization.fir
@@ -13,6 +13,7 @@ func.func @concat(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2: !fir.bo
   %6 = arith.addi %2#1, %4#1 : index
   %7 = hlfir.concat %3#0, %5#0 len %6 : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
   hlfir.assign %7 to %1#0 : !hlfir.expr<!fir.char<1,?>>, !fir.boxchar<1>
+  hlfir.destroy %7 : !hlfir.expr<!fir.char<1,?>>
   return
 }
 // CHECK-LABEL:   func.func @concat(
@@ -27,11 +28,11 @@ func.func @concat(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2: !fir.bo
 // CHECK:           %[[VAL_8:.*]]:2 = hlfir.declare %[[VAL_7]]#0 typeparams %[[VAL_7]]#1 uniq_name("c3") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
 // CHECK:           %[[VAL_9:.*]] = arith.addi %[[VAL_5]]#1, %[[VAL_7]]#1 : index
 // CHECK:           %[[VAL_10:.*]] = arith.addi %[[VAL_5]]#1, %[[VAL_7]]#1 : index
-// CHECK:           %[[VAL_11:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_10]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:           %[[VAL_11:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_10]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:           %[[VAL_12:.*]] = arith.constant 1 : i64
 // CHECK:           %[[VAL_13:.*]] = fir.convert %[[VAL_5]]#1 : (index) -> i64
 // CHECK:           %[[VAL_14:.*]] = arith.muli %[[VAL_12]], %[[VAL_13]] : i64
-// CHECK:           %[[VAL_15:.*]] = fir.convert %[[VAL_11]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:           %[[VAL_15:.*]] = fir.convert %[[VAL_11]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           %[[VAL_16:.*]] = fir.convert %[[VAL_6]]#1 : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           "llvm.intr.memmove"(%[[VAL_15]], %[[VAL_16]], %[[VAL_14]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:           %[[VAL_17:.*]] = arith.constant 1 : index
@@ -41,16 +42,19 @@ func.func @concat(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2: !fir.bo
 // CHECK:             %[[VAL_21:.*]] = fir.convert %[[VAL_8]]#1 : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_22:.*]] = fir.coordinate_of %[[VAL_21]], %[[VAL_20]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             %[[VAL_23:.*]] = fir.load %[[VAL_22]] : !fir.ref<!fir.char<1>>
-// CHECK:             %[[VAL_24:.*]] = fir.convert %[[VAL_11]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:             %[[VAL_24:.*]] = fir.convert %[[VAL_11]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_25:.*]] = fir.coordinate_of %[[VAL_24]], %[[VAL_19]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             fir.store %[[VAL_23]] to %[[VAL_25]] : !fir.ref<!fir.char<1>>
 // CHECK:           }
-// CHECK:           %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_11]] typeparams %[[VAL_10]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:           %[[VAL_27:.*]] = arith.constant false
+// CHECK:           %[[VAL_11_REF:.*]] = fir.convert %[[VAL_11]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:           %[[VAL_26:.*]]:2 = hlfir.declare %[[VAL_11_REF]] typeparams %[[VAL_10]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:           %[[VAL_27:.*]] = arith.constant true
 // CHECK:           %[[VAL_28:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_29:.*]] = fir.insert_value %[[VAL_28]], %[[VAL_27]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_30:.*]] = fir.insert_value %[[VAL_29]], %[[VAL_26]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           hlfir.assign %[[VAL_26]]#0 to %[[VAL_4]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:           %[[VAL_31:.*]] = fir.box_addr %[[VAL_26]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:           fir.freemem %[[VAL_31]] : !fir.heap<!fir.char<1,?>>
 // CHECK:           return
 // CHECK:         }
 
@@ -69,6 +73,8 @@ func.func @concat_chained(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2:
   %10 = arith.addi %8, %6#1 : index
   %11 = hlfir.concat %9, %7#0 len %10 : (!hlfir.expr<!fir.char<1,?>>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
   hlfir.assign %11 to %1#0 : !hlfir.expr<!fir.char<1,?>>, !fir.boxchar<1>
+  hlfir.destroy %11 : !hlfir.expr<!fir.char<1,?>>
+  hlfir.destroy %9 : !hlfir.expr<!fir.char<1,?>>
   return
 }
 
@@ -87,11 +93,11 @@ func.func @concat_chained(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2:
 // CHECK:           %[[VAL_11:.*]]:2 = hlfir.declare %[[VAL_10]]#0 typeparams %[[VAL_10]]#1 uniq_name("c4") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
 // CHECK:           %[[VAL_12:.*]] = arith.addi %[[VAL_6]]#1, %[[VAL_8]]#1 : index
 // CHECK:           %[[VAL_13:.*]] = arith.addi %[[VAL_6]]#1, %[[VAL_8]]#1 : index
-// CHECK:           %[[VAL_14:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_13]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:           %[[VAL_14:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_13]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:           %[[VAL_15:.*]] = arith.constant 1 : i64
 // CHECK:           %[[VAL_16:.*]] = fir.convert %[[VAL_6]]#1 : (index) -> i64
 // CHECK:           %[[VAL_17:.*]] = arith.muli %[[VAL_15]], %[[VAL_16]] : i64
-// CHECK:           %[[VAL_18:.*]] = fir.convert %[[VAL_14]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:           %[[VAL_18:.*]] = fir.convert %[[VAL_14]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           %[[VAL_19:.*]] = fir.convert %[[VAL_7]]#1 : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           "llvm.intr.memmove"(%[[VAL_18]], %[[VAL_19]], %[[VAL_17]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:           %[[VAL_20:.*]] = arith.constant 1 : index
@@ -101,22 +107,23 @@ func.func @concat_chained(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2:
 // CHECK:             %[[VAL_24:.*]] = fir.convert %[[VAL_9]]#1 : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_25:.*]] = fir.coordinate_of %[[VAL_24]], %[[VAL_23]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             %[[VAL_26:.*]] = fir.load %[[VAL_25]] : !fir.ref<!fir.char<1>>
-// CHECK:             %[[VAL_27:.*]] = fir.convert %[[VAL_14]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:             %[[VAL_27:.*]] = fir.convert %[[VAL_14]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_28:.*]] = fir.coordinate_of %[[VAL_27]], %[[VAL_22]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             fir.store %[[VAL_26]] to %[[VAL_28]] : !fir.ref<!fir.char<1>>
 // CHECK:           }
-// CHECK:           %[[VAL_29:.*]]:2 = hlfir.declare %[[VAL_14]] typeparams %[[VAL_13]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:           %[[VAL_30:.*]] = arith.constant false
+// CHECK:           %[[VAL_14_REF:.*]] = fir.convert %[[VAL_14]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:           %[[VAL_29:.*]]:2 = hlfir.declare %[[VAL_14_REF]] typeparams %[[VAL_13]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:           %[[VAL_30:.*]] = arith.constant true
 // CHECK:           %[[VAL_31:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_32:.*]] = fir.insert_value %[[VAL_31]], %[[VAL_30]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_33:.*]] = fir.insert_value %[[VAL_32]], %[[VAL_29]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_34:.*]] = arith.addi %[[VAL_12]], %[[VAL_10]]#1 : index
 // CHECK:           %[[VAL_35:.*]] = arith.addi %[[VAL_13]], %[[VAL_10]]#1 : index
-// CHECK:           %[[VAL_36:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_35]] : index) <{bindc_name = ".chrtmp"}>
+// CHECK:           %[[VAL_36:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_35]] : index) <{bindc_name = ".chrtmp", uniq_name = ""}>
 // CHECK:           %[[VAL_37:.*]] = arith.constant 1 : i64
 // CHECK:           %[[VAL_38:.*]] = fir.convert %[[VAL_13]] : (index) -> i64
 // CHECK:           %[[VAL_39:.*]] = arith.muli %[[VAL_37]], %[[VAL_38]] : i64
-// CHECK:           %[[VAL_40:.*]] = fir.convert %[[VAL_36]] : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
+// CHECK:           %[[VAL_40:.*]] = fir.convert %[[VAL_36]] : (!fir.heap<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           %[[VAL_41:.*]] = fir.convert %[[VAL_29]]#1 : (!fir.ref<!fir.char<1,?>>) -> !llvm.ptr
 // CHECK:           "llvm.intr.memmove"(%[[VAL_40]], %[[VAL_41]], %[[VAL_39]]) <{isVolatile = false}> : (!llvm.ptr, !llvm.ptr, i64) -> ()
 // CHECK:           %[[VAL_42:.*]] = arith.constant 1 : index
@@ -126,15 +133,20 @@ func.func @concat_chained(%arg0: !fir.boxchar<1>, %arg1: !fir.boxchar<1>, %arg2:
 // CHECK:             %[[VAL_46:.*]] = fir.convert %[[VAL_11]]#1 : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_47:.*]] = fir.coordinate_of %[[VAL_46]], %[[VAL_45]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             %[[VAL_48:.*]] = fir.load %[[VAL_47]] : !fir.ref<!fir.char<1>>
-// CHECK:             %[[VAL_49:.*]] = fir.convert %[[VAL_36]] : (!fir.ref<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
+// CHECK:             %[[VAL_49:.*]] = fir.convert %[[VAL_36]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.array<?x!fir.char<1>>>
 // CHECK:             %[[VAL_50:.*]] = fir.coordinate_of %[[VAL_49]], %[[VAL_44]] : (!fir.ref<!fir.array<?x!fir.char<1>>>, index) -> !fir.ref<!fir.char<1>>
 // CHECK:             fir.store %[[VAL_48]] to %[[VAL_50]] : !fir.ref<!fir.char<1>>
 // CHECK:           }
-// CHECK:           %[[VAL_51:.*]]:2 = hlfir.declare %[[VAL_36]] typeparams %[[VAL_35]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:           %[[VAL_52:.*]] = arith.constant false
+// CHECK:           %[[VAL_36_REF:.*]] = fir.convert %[[VAL_36]] : (!fir.heap<!fir.char<1,?>>) -> !fir.ref<!fir.char<1,?>>
+// CHECK:           %[[VAL_51:.*]]:2 = hlfir.declare %[[VAL_36_REF]] typeparams %[[VAL_35]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:           %[[VAL_52:.*]] = arith.constant true
 // CHECK:           %[[VAL_53:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_54:.*]] = fir.insert_value %[[VAL_53]], %[[VAL_52]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           %[[VAL_55:.*]] = fir.insert_value %[[VAL_54]], %[[VAL_51]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:           hlfir.assign %[[VAL_51]]#0 to %[[VAL_5]]#0 : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:           %[[VAL_56:.*]] = fir.box_addr %[[VAL_51]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:           fir.freemem %[[VAL_56]] : !fir.heap<!fir.char<1,?>>
+// CHECK:           %[[VAL_57:.*]] = fir.box_addr %[[VAL_29]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:           fir.freemem %[[VAL_57]] : !fir.heap<!fir.char<1,?>>
 // CHECK:           return
 // CHECK:         }
diff --git a/flang/test/HLFIR/destroy-codegen.fir b/flang/test/HLFIR/destroy-codegen.fir
index 76ecc351e97b84..49a10d1860a719 100644
--- a/flang/test/HLFIR/destroy-codegen.fir
+++ b/flang/test/HLFIR/destroy-codegen.fir
@@ -1,5 +1,4 @@
-// Test hlfir.destroy code generation and hlfir.yield_element "implicit
-// hlfir.destroy" aspect.
+// Test hlfir.destroy code generation and explicit elemental cleanup.
 
 // RUN: fir-opt %s -bufferize-hlfir | FileCheck %s
 
@@ -33,7 +32,9 @@ func.func @test_elemental() {
     %buffer = fir.allocmem !fir.char<1,20>
     %must_free = arith.constant true
     %expr = hlfir.as_expr %buffer move %must_free: (!fir.heap<!fir.char<1,20>>, i1) -> !hlfir.expr<!fir.char<1,20>>
-    hlfir.yield_element %expr : !hlfir.expr<!fir.char<1,20>>
+    hlfir.yield_element %expr : !hlfir.expr<!fir.char<1,20>> cleanup {
+      hlfir.destroy %expr : !hlfir.expr<!fir.char<1,20>>
+    }
   }
   return
 }
diff --git a/flang/test/HLFIR/element-codegen-issue-118922.fir b/flang/test/HLFIR/element-codegen-issue-118922.fir
index 473b739e0cf7b1..97fac59399fc2c 100644
--- a/flang/test/HLFIR/element-codegen-issue-118922.fir
+++ b/flang/test/HLFIR/element-codegen-issue-118922.fir
@@ -13,7 +13,9 @@ func.func @_QMmPbug(%val: !fir.char<1>, %var: !fir.ref<!fir.array<10x!fir.char<1
     %addr = fir.convert %alloc: (!fir.heap<!fir.char<1>>) -> !fir.ref<!fir.char<1>>
     %9 = hlfir.as_expr %addr : (!fir.ref<!fir.char<1>>) -> !hlfir.expr<!fir.char<1>>
     fir.freemem  %alloc : !fir.heap<!fir.char<1>>
-    hlfir.yield_element %9 : !hlfir.expr<!fir.char<1>>
+    hlfir.yield_element %9 : !hlfir.expr<!fir.char<1>> cleanup {
+      hlfir.destroy %9 : !hlfir.expr<!fir.char<1>>
+    }
   }
   hlfir.assign %expr to %var : !hlfir.expr<10x!fir.char<1>>, !fir.ref<!fir.array<10x!fir.char<1>>>
   hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1>>
diff --git a/flang/test/HLFIR/elemental-codegen.fir b/flang/test/HLFIR/elemental-codegen.fir
index b4f4568a189e18..d7984fe43e1986 100644
--- a/flang/test/HLFIR/elemental-codegen.fir
+++ b/flang/test/HLFIR/elemental-codegen.fir
@@ -48,7 +48,9 @@ func.func @char_type(%arg0: !fir.box<!fir.array<?x!fir.char<1,?>>>, %arg1: index
   ^bb0(%arg4: index):
     %2 = hlfir.designate %arg0 (%arg4)  typeparams %arg3 : (!fir.box<!fir.array<?x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
     %3 = hlfir.concat %2, %2 len %arg2 : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
-    hlfir.yield_element %3 : !hlfir.expr<!fir.char<1,?>>
+    hlfir.yield_element %3 : !hlfir.expr<!fir.char<1,?>> cleanup {
+      hlfir.destroy %3 : !hlfir.expr<!fir.char<1,?>>
+    }
   }
   return
 }
@@ -66,12 +68,14 @@ func.func @char_type(%arg0: !fir.box<!fir.array<?x!fir.char<1,?>>>, %arg1: index
 // CHECK:      %[[VAL_10:.*]] = hlfir.designate %[[VAL_0]] (%[[VAL_9]])  typeparams %[[VAL_3]] : (!fir.box<!fir.array<?x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
                // concatenation
 // CHECK:      %[[VAL_30:.*]]:2 = hlfir.declare %[[VAL_14:.*]] typeparams %[[VAL_13:.*]] uniq_name("tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
-// CHECK:      %[[VAL_31:.*]] = arith.constant false
+// CHECK:      %[[VAL_31:.*]] = arith.constant true
 // CHECK:      %[[VAL_32:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:      %[[VAL_33:.*]] = fir.insert_value %[[VAL_32]], %[[VAL_31]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:      %[[VAL_34:.*]] = fir.insert_value %[[VAL_33]], %[[VAL_30]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:      %[[VAL_35:.*]] = hlfir.designate %[[VAL_6]]#0 (%[[VAL_9]])  typeparams %[[VAL_2]] : (!fir.box<!fir.array<?x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
 // CHECK:      hlfir.assign %[[VAL_30]]#0 to %[[VAL_35]] temporary_lhs : !fir.boxchar<1>, !fir.boxchar<1>
+// CHECK:      %[[VAL_39:.*]] = fir.box_addr %[[VAL_30]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:      fir.freemem %[[VAL_39]] : !fir.heap<!fir.char<1,?>>
 // CHECK:    }
 // CHECK:    %[[VAL_36:.*]] = fir.undefined tuple<!fir.box<!fir.array<?x!fir.char<1,?>>>, i1>
 // CHECK:    %[[VAL_37:.*]] = fir.insert_value %[[VAL_36]], %[[VAL_7]], [1 : index] : (tuple<!fir.box<!fir.array<?x!fir.char<1,?>>>, i1>, i1) -> tuple<!fir.box<!fir.array<?x!fir.char<1,?>>>, i1>
@@ -84,7 +88,9 @@ func.func @derived_transpose(%arg0: !fir.box<!fir.array<?x?x!fir.type<t{field:f3
   ^bb0(%arg4: index, %arg5: index):
     %2 = hlfir.designate %arg0 (%arg4, %arg5) : (!fir.box<!fir.array<?x?x!fir.type<t{field:f32}>>>, index, index) -> !fir.box<!fir.type<t{field:f32}>>
     %3 = hlfir.as_expr %2 : (!fir.box<!fir.type<t{field:f32}>>) -> !hlfir.expr<!fir.type<t{field:f32}>>
-    hlfir.yield_element %3 : !hlfir.expr<!fir.type<t{field:f32}>>
+    hlfir.yield_element %3 : !hlfir.expr<!fir.type<t{field:f32}>> cleanup {
+      hlfir.destroy %3 : !hlfir.expr<!fir.type<t{field:f32}>>
+    }
   }
   return
 }
@@ -148,7 +154,9 @@ func.func @test_polymorphic(%arg0: !fir.class<!fir.type<_QMtypesTt>> {fir.bindc_
   ^bb0(%arg3: index, %arg4: index):
     %6 = hlfir.designate %2#0 (%arg3, %arg4)  : (!fir.class<!fir.array<?x?x!fir.type<_QMtypesTt>>>, index, index) -> !fir.class<!fir.type<_QMtypesTt>>
     %7 = hlfir.as_expr %6 : (!fir.class<!fir.type<_QMtypesTt>>) -> !hlfir.expr<!fir.type<_QMtypesTt>?>
-    hlfir.yield_element %7 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    hlfir.yield_element %7 : !hlfir.expr<!fir.type<_QMtypesTt>?> cleanup {
+      hlfir.destroy %7 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    }
   }
   return
 }
@@ -197,7 +205,9 @@ func.func @test_polymorphic_expr(%arg0: !fir.class<!fir.type<_QMtypesTt>> {fir.b
   ^bb0(%arg3: index, %arg4: index):
     %6 = hlfir.designate %2#0 (%arg3, %arg4)  : (!fir.class<!fir.array<?x?x!fir.type<_QMtypesTt>>>, index, index) -> !fir.class<!fir.type<_QMtypesTt>>
     %7 = hlfir.as_expr %6 : (!fir.class<!fir.type<_QMtypesTt>>) -> !hlfir.expr<!fir.type<_QMtypesTt>?>
-    hlfir.yield_element %7 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    hlfir.yield_element %7 : !hlfir.expr<!fir.type<_QMtypesTt>?> cleanup {
+      hlfir.destroy %7 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    }
   }
   %8 = hlfir.elemental %4 mold %5 unordered : (!fir.shape<2>, !hlfir.expr<?x?x!fir.type<_QMtypesTt>?>) -> !hlfir.expr<?x?x!fir.type<_QMtypesTt>?> {
   ^bb0(%arg3: index, %arg4: index):
@@ -261,9 +271,10 @@ func.func @test_polymorphic_expr(%arg0: !fir.class<!fir.type<_QMtypesTt>> {fir.b
 // CHECK:               %[[VAL_50:.*]] = fir.insert_value %[[VAL_49]], %[[VAL_46]], [0 : index] : (tuple<!fir.class<!fir.type<_QMtypesTt>>, i1>, !fir.class<!fir.type<_QMtypesTt>>) -> tuple<!fir.class<!fir.type<_QMtypesTt>>, i1>
 // CHECK:               %[[VAL_51:.*]] = hlfir.designate %[[VAL_41]]#0 (%[[VAL_45]], %[[VAL_44]])  : (!fir.class<!fir.array<?x?x!fir.type<_QMtypesTt>>>, index, index) -> !fir.class<!fir.type<_QMtypesTt>>
 // CHECK:               hlfir.assign %[[VAL_46]] to %[[VAL_51]] temporary_lhs : !fir.class<!fir.type<_QMtypesTt>>, !fir.class<!fir.type<_QMtypesTt>>
-// CHECK:               %[[VAL_52:.*]] = fir.box_addr %[[VAL_46]] : (!fir.class<!fir.type<_QMtypesTt>>) -> !fir.heap<!fir.type<_QMtypesTt>>
-// CHECK:               %[[VAL_53:.*]] = fir.convert %[[VAL_46]] : (!fir.class<!fir.type<_QMtypesTt>>) -> !fir.box<none>
-// CHECK:               fir.call @_FortranADestroyWithoutFinalization(%[[VAL_53]]) : (!fir.box<none>) -> ()
+// The apply result borrows the first array's element. Consuming it must not
+// destroy its allocatable components.
+// CHECK-NOT:           @_FortranADestroyWithoutFinalization
+// CHECK-NOT:           fir.freemem
 // CHECK:             }
 // CHECK:           }
 // CHECK:           %[[VAL_54:.*]] = fir.undefined tuple<!fir.class<!fir.array<?x?x!fir.type<_QMtypesTt>>>, i1>
diff --git a/flang/test/HLFIR/elemental-shallow-copy.fir b/flang/test/HLFIR/elemental-shallow-copy.fir
index 19c337df9638bb..e748ce3a8a5bee 100644
--- a/flang/test/HLFIR/elemental-shallow-copy.fir
+++ b/flang/test/HLFIR/elemental-shallow-copy.fir
@@ -1,5 +1,6 @@
 // Check that an elemental result of a derived type with an allocatable
-// component is shallow-copied into the array result.
+// component is shallow-copied into the array result. The skipped scalar
+// as_expr must not leave behind its bufferization tuple or a destroy.
 // RUN: fir-opt %s --bufferize-hlfir | FileCheck %s
 
 func.func @_QMtypesPtest() {
@@ -13,7 +14,9 @@ func.func @_QMtypesPtest() {
   ^bb0(%arg0: index):
     %26:2 = hlfir.declare %0 uniq_name(".tmp.func_result") : (!fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>) -> (!fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>, !fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>)
     %27 = hlfir.as_expr %26#0 move %false : (!fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>, i1) -> !hlfir.expr<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
-    hlfir.yield_element %27 : !hlfir.expr<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
+    hlfir.yield_element %27 : !hlfir.expr<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>> cleanup {
+      hlfir.destroy %27 : !hlfir.expr<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
+    }
   }
   hlfir.assign %23 to %19#0 : !hlfir.expr<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>, !fir.ref<!fir.array<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>>
   hlfir.destroy %23 : !hlfir.expr<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
@@ -25,7 +28,9 @@ func.func @_QMtypesPtest() {
 // CHECK:           %[[VAL_7:.*]]:2 = hlfir.declare %[[VAL_6]](%{{.*}}) uniq_name(".tmp.array") : (!fir.heap<!fir.array<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>>, !fir.shape<1>) -> (!fir.heap<!fir.array<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>>, !fir.heap<!fir.array<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>>)
 // CHECK:           fir.do_loop %[[VAL_10:.*]] = %{{.*}} to %{{.*}} step %{{.*}} {
 // CHECK:             %[[VAL_11:.*]]:2 = hlfir.declare %[[VAL_2]] uniq_name(".tmp.func_result") : (!fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>) -> (!fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>, !fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>)
+// CHECK-NOT:         fir.undefined tuple
 // CHECK:             %[[VAL_15:.*]] = hlfir.designate %[[VAL_7]]#0 (%[[VAL_10]])  : (!fir.heap<!fir.array<1x!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>>, index) -> !fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
 // CHECK:             %[[VAL_16:.*]] = fir.load %[[VAL_11]]#0 : !fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
 // CHECK:             fir.store %[[VAL_16]] to %[[VAL_15]] : !fir.ref<!fir.type<_QMtypesTt{x:!fir.box<!fir.heap<f32>>}>>
+// CHECK-NOT:         @_FortranADestroy
 // CHECK:           }
diff --git a/flang/test/HLFIR/elemental.fir b/flang/test/HLFIR/elemental.fir
index 174c39b99b3721..cd6858d315db24 100644
--- a/flang/test/HLFIR/elemental.fir
+++ b/flang/test/HLFIR/elemental.fir
@@ -38,7 +38,9 @@ func.func @char_type(%x: !fir.box<!fir.array<?x!fir.char<1,?>>>, %n: index, %l :
   ^bb0(%i: index):
     %4 = hlfir.designate %x (%i) typeparams %l0 : (!fir.box<!fir.array<?x!fir.char<1,?>>>, index, index) -> !fir.boxchar<1>
     %6 = hlfir.concat %4, %4 len %l : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
-    hlfir.yield_element %6 : !hlfir.expr<!fir.char<1,?>>
+    hlfir.yield_element %6 : !hlfir.expr<!fir.char<1,?>> cleanup {
+      hlfir.destroy %6 : !hlfir.expr<!fir.char<1,?>>
+    }
   }
   return
 }
@@ -62,7 +64,9 @@ func.func @parametrized_derived_transpose(%x: !fir.box<!fir.array<?x?x!pdt>>, %n
   ^bb0(%j: index, %i: index):
     %4 = hlfir.designate %x (%j, %i) typeparams %l : (!fir.box<!fir.array<?x?x!pdt>>, index, index, i32) -> !fir.box<!pdt>
     %5 = hlfir.as_expr %4 : (!fir.box<!pdt>) -> !hlfir.expr<!pdt>
-    hlfir.yield_element %5 : !hlfir.expr<!pdt>
+    hlfir.yield_element %5 : !hlfir.expr<!pdt> cleanup {
+      hlfir.destroy %5 : !hlfir.expr<!pdt>
+    }
   }
   return
 }
@@ -105,7 +109,9 @@ func.func @polymorphic_mold_var(%arg0: !fir.class<!fir.array<?x!fir.type<_QMtype
   %4 = hlfir.elemental %3 mold %arg0 unordered : (!fir.shape<1>, !fir.class<!fir.array<?x!fir.type<_QMtypesTt>>>) -> !hlfir.expr<?x!fir.type<_QMtypesTt>?> {
   ^bb0(%arg2: index):
     %6 = fir.undefined !hlfir.expr<!fir.type<_QMtypesTt>?>
-    hlfir.yield_element %6 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    hlfir.yield_element %6 : !hlfir.expr<!fir.type<_QMtypesTt>?> cleanup {
+      hlfir.destroy %6 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    }
   }
   return
 }
@@ -126,7 +132,9 @@ func.func @polymorphic_mold_expr(%shape : index) {
   %4 = hlfir.elemental %3 mold %mold unordered : (!fir.shape<1>, !hlfir.expr<?x!fir.type<_QMtypesTt>?>) -> !hlfir.expr<?x!fir.type<_QMtypesTt>?> {
   ^bb0(%arg2: index):
     %6 = fir.undefined !hlfir.expr<!fir.type<_QMtypesTt>?>
-    hlfir.yield_element %6 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    hlfir.yield_element %6 : !hlfir.expr<!fir.type<_QMtypesTt>?> cleanup {
+      hlfir.destroy %6 : !hlfir.expr<!fir.type<_QMtypesTt>?>
+    }
   }
   return
 }
diff --git a/flang/test/HLFIR/get_length_codegen.fir b/flang/test/HLFIR/get_length_codegen.fir
index 04d7ba152a23bd..c9e007b3593e02 100644
--- a/flang/test/HLFIR/get_length_codegen.fir
+++ b/flang/test/HLFIR/get_length_codegen.fir
@@ -27,7 +27,7 @@ fir.global linkonce @_QQclX616263 constant : !fir.char<1,3> {
 // CHECK:           %[[VAL_1:.*]] = arith.constant 3 : index
 // CHECK:           %[[VAL_2:.*]]:2 = fir.unboxchar %[[VAL_0]] : (!fir.boxchar<1>) -> (!fir.ref<!fir.char<1,?>>, index)
 // CHECK:           %[[VAL_9:.*]] = arith.addi %[[VAL_1]], %[[VAL_2]]#1 : index
-// CHECK:           %[[VAL_33:.*]]:2 = hlfir.declare %[[VAL_31:.*]] typeparams %[[VAL_9]] uniq_name(".tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:           %[[VAL_33:.*]]:2 = hlfir.declare %[[VAL_31:.*]] typeparams %[[VAL_9]] uniq_name(".tmp") : (!fir.heap<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.heap<!fir.char<1,?>>)
 // CHECK:           return %[[VAL_9]] : index
 // CHECK:         }
 
diff --git a/flang/test/HLFIR/inline-elemental-cleanup-cfg.fir b/flang/test/HLFIR/inline-elemental-cleanup-cfg.fir
new file mode 100644
index 00000000000000..12e7150def7bf4
--- /dev/null
+++ b/flang/test/HLFIR/inline-elemental-cleanup-cfg.fir
@@ -0,0 +1,132 @@
+// RUN: fir-opt %s --inline-elementals | FileCheck %s
+
+// Conservatively keep the array even when cleanup is in an unconditional
+// successor block. Scalar cleanup is only supported in the apply block.
+func.func @successor_cleanup(%a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.char<1,4>>, %condition: i1) {
+  %c1 = arith.constant 1 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c10 = arith.constant 10 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  %expr = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+  ^bb0(%i: index):
+    %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+    %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+    hlfir.yield_element %temp : !hlfir.expr<!fir.char<1,4>> cleanup {
+      hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+    }
+  }
+
+  %element = hlfir.apply %expr, %c1 typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+  hlfir.assign %element to %out : !hlfir.expr<!fir.char<1,4>>, !fir.ref<!fir.char<1,4>>
+  cf.br ^cleanup
+^cleanup:
+  hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1,4>>
+  return
+}
+// CHECK-LABEL: func.func @successor_cleanup
+// CHECK: %[[ARRAY:.*]] = hlfir.elemental
+// CHECK: hlfir.apply %[[ARRAY]]
+// CHECK: hlfir.assign
+// CHECK-NEXT: cf.br ^[[EXIT:.*]]
+// CHECK: ^[[EXIT]]:
+// CHECK-NEXT: hlfir.destroy %[[ARRAY]]
+// CHECK-NEXT: return
+
+// The array dominates the join, but a scalar from only one branch does not.
+func.func @conditional_apply(%a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.char<1,4>>, %condition: i1) {
+  %c1 = arith.constant 1 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c10 = arith.constant 10 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  %expr = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+  ^bb0(%i: index):
+    %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+    %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+    hlfir.yield_element %temp : !hlfir.expr<!fir.char<1,4>> cleanup {
+      hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+    }
+  }
+  cf.cond_br %condition, ^then, ^cleanup
+^then:
+  %element = hlfir.apply %expr, %c1 typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+  hlfir.assign %element to %out : !hlfir.expr<!fir.char<1,4>>, !fir.ref<!fir.char<1,4>>
+  cf.br ^cleanup
+^cleanup:
+  hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1,4>>
+  return
+}
+// CHECK-LABEL: func.func @conditional_apply
+// CHECK: %[[ARRAY:.*]] = hlfir.elemental
+// CHECK: cf.cond_br
+// CHECK: hlfir.apply %[[ARRAY]]
+// CHECK: hlfir.assign
+// CHECK: cf.br
+// CHECK: hlfir.destroy %[[ARRAY]]
+// CHECK: return
+
+// A scalar produced inside a loop cannot be cleaned up outside its region.
+func.func @loop_apply(%a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.char<1,4>>, %condition: i1) {
+  %c1 = arith.constant 1 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c10 = arith.constant 10 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  %expr = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+  ^bb0(%i: index):
+    %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+    %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+    hlfir.yield_element %temp : !hlfir.expr<!fir.char<1,4>> cleanup {
+      hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+    }
+  }
+  fir.do_loop %j = %c1 to %c10 step %c1 {
+    %element = hlfir.apply %expr, %c1 typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+    hlfir.assign %element to %out : !hlfir.expr<!fir.char<1,4>>, !fir.ref<!fir.char<1,4>>
+  }
+  hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1,4>>
+  return
+}
+// CHECK-LABEL: func.func @loop_apply
+// CHECK: %[[ARRAY:.*]] = hlfir.elemental
+// CHECK: fir.do_loop
+// CHECK: hlfir.apply %[[ARRAY]]
+// CHECK: hlfir.assign
+// CHECK: }
+// CHECK-NEXT: hlfir.destroy %[[ARRAY]]
+// CHECK-NEXT: return
+
+// Apply dominates destroy, but can execute several times before it. Cleaning
+// up only at destroy would leak all but the last scalar temporary.
+func.func @cfg_loop_apply(%a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.char<1,4>>, %condition: i1) {
+  %c1 = arith.constant 1 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c10 = arith.constant 10 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  %expr = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+  ^bb0(%i: index):
+    %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+    %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+    hlfir.yield_element %temp : !hlfir.expr<!fir.char<1,4>> cleanup {
+      hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+    }
+  }
+  cf.br ^loop
+^loop:
+  %element = hlfir.apply %expr, %c1 typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+  hlfir.assign %element to %out : !hlfir.expr<!fir.char<1,4>>, !fir.ref<!fir.char<1,4>>
+  cf.cond_br %condition, ^loop, ^cleanup
+^cleanup:
+  hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1,4>>
+  return
+}
+// CHECK-LABEL: func.func @cfg_loop_apply
+// CHECK: %[[ARRAY:.*]] = hlfir.elemental
+// CHECK: cf.br
+// CHECK: hlfir.apply %[[ARRAY]]
+// CHECK: hlfir.assign
+// CHECK: cf.cond_br
+// CHECK: hlfir.destroy %[[ARRAY]]
+// CHECK-NEXT: return
diff --git a/flang/test/HLFIR/inline-elemental.fir b/flang/test/HLFIR/inline-elemental.fir
index c67342b5ad9f10..ab193a4838f09e 100644
--- a/flang/test/HLFIR/inline-elemental.fir
+++ b/flang/test/HLFIR/inline-elemental.fir
@@ -343,3 +343,33 @@ func.func @noinline_due_to_finalization(%arg0: !fir.box<!fir.array<?x!fir.type<_
 // CHECK:             %[[VAL_13:.*]] = hlfir.apply %[[VAL_6]], %{{.*}} : (!hlfir.expr<?x!fir.type<_QMtypesTt1{x:f32}>>, index) -> !hlfir.expr<!fir.type<_QMtypesTt1{x:f32}>>
 // CHECK:           hlfir.destroy %[[VAL_11]] : !hlfir.expr<?x!fir.type<_QMtypesTt1{x:f32}>>
 // CHECK:           hlfir.destroy %[[VAL_6]] finalize : !hlfir.expr<?x!fir.type<_QMtypesTt1{x:f32}>>
+
+// Outside an elemental consumer, clone cleanup after the scalar's uses at
+// the original array destruction point, including through no_reassoc.
+func.func @scalar_character_cleanup(%a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.char<1,4>>) {
+  %c1 = arith.constant 1 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c10 = arith.constant 10 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  %expr = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+  ^bb0(%i: index):
+    %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+    %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+    %alias = hlfir.no_reassoc %temp : !hlfir.expr<!fir.char<1,4>>
+    hlfir.yield_element %alias : !hlfir.expr<!fir.char<1,4>> cleanup {
+      hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+    }
+  }
+  %element = hlfir.apply %expr, %c1 typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+  hlfir.assign %element to %out : !hlfir.expr<!fir.char<1,4>>, !fir.ref<!fir.char<1,4>>
+  hlfir.destroy %expr : !hlfir.expr<10x!fir.char<1,4>>
+  return
+}
+// CHECK-LABEL: func.func @scalar_character_cleanup
+// CHECK-NOT: hlfir.elemental
+// CHECK: %[[TEMP:.*]] = hlfir.concat
+// CHECK: %[[ALIAS:.*]] = hlfir.no_reassoc %[[TEMP]]
+// CHECK-NEXT: hlfir.assign %[[ALIAS]]
+// CHECK-NEXT: hlfir.destroy %[[TEMP]]
+// CHECK-NEXT: return
diff --git a/flang/test/HLFIR/no_reassoc-codegen.fir b/flang/test/HLFIR/no_reassoc-codegen.fir
index 85a5f01565cd12..a648637df08301 100644
--- a/flang/test/HLFIR/no_reassoc-codegen.fir
+++ b/flang/test/HLFIR/no_reassoc-codegen.fir
@@ -6,12 +6,15 @@ func.func @no_reassoc_expr(%addr: !fir.ref<!fir.char<1,?>>, %len: index) {
   %0:2 = hlfir.declare %addr typeparams %len uniq_name("c") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
   %1 = hlfir.as_expr %0#0 : (!fir.boxchar<1>) -> !hlfir.expr<!fir.char<1,?>>
   %2 = hlfir.no_reassoc %1 : !hlfir.expr<!fir.char<1,?>>
+  hlfir.destroy %1 : !hlfir.expr<!fir.char<1,?>>
   return
 }
-// CHECK:  %[[VAL_4:.*]] = fir.alloca !fir.char<1,?>
+// CHECK-LABEL: func.func @no_reassoc_expr
+// CHECK:  %[[VAL_4:.*]] = fir.allocmem !fir.char<1,?>
 // CHECK:  %[[VAL_5:.*]] = fir.declare %[[VAL_4]] {{.*}}
 // CHECK:  %[[VAL_6:.*]] = fir.emboxchar %[[VAL_5]], %{{.*}}
 // CHECK:  fir.no_reassoc %[[VAL_6]] : !fir.boxchar<1>
+// CHECK:  fir.freemem
 
 func.func @no_reassoc_var(%addr: !fir.ref<!fir.char<1,?>>, %len: index) {
   %0:2 = hlfir.declare %addr typeparams %len uniq_name("c") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
diff --git a/flang/test/HLFIR/order_assignments/where-element-cleanup.fir b/flang/test/HLFIR/order_assignments/where-element-cleanup.fir
new file mode 100644
index 00000000000000..a1c5a69be62373
--- /dev/null
+++ b/flang/test/HLFIR/order_assignments/where-element-cleanup.fir
@@ -0,0 +1,53 @@
+// RUN: fir-opt %s --lower-hlfir-ordered-assignments | FileCheck %s
+
+// Applying the same producer twice recursively inlines two distinct scalar
+// temporaries. Each cleanup must keep the mapping from its own evaluation.
+func.func @repeated_apply(%mask: !fir.ref<!fir.array<10x!fir.logical<4>>>, %a: !fir.ref<!fir.array<10x!fir.char<1,2>>>, %out: !fir.ref<!fir.array<10x!fir.char<1,8>>>) {
+  %c10 = arith.constant 10 : index
+  %c2 = arith.constant 2 : index
+  %c4 = arith.constant 4 : index
+  %c8 = arith.constant 8 : index
+  %shape = fir.shape %c10 : (index) -> !fir.shape<1>
+  hlfir.where {
+    hlfir.yield %mask : !fir.ref<!fir.array<10x!fir.logical<4>>>
+  } do {
+    hlfir.region_assign {
+      %producer = hlfir.elemental %shape typeparams %c4 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,4>> {
+      ^bb0(%i: index):
+        %a_i = hlfir.designate %a (%i) typeparams %c2 : (!fir.ref<!fir.array<10x!fir.char<1,2>>>, index, index) -> !fir.ref<!fir.char<1,2>>
+        %temp = hlfir.concat %a_i, %a_i len %c4 : (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, index) -> !hlfir.expr<!fir.char<1,4>>
+        hlfir.yield_element %temp : !hlfir.expr<!fir.char<1,4>> cleanup {
+          hlfir.destroy %temp : !hlfir.expr<!fir.char<1,4>>
+        }
+      }
+      %consumer = hlfir.elemental %shape typeparams %c8 unordered : (!fir.shape<1>, index) -> !hlfir.expr<10x!fir.char<1,8>> {
+      ^bb0(%j: index):
+        %left = hlfir.apply %producer, %j typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+        %right = hlfir.apply %producer, %j typeparams %c4 : (!hlfir.expr<10x!fir.char<1,4>>, index, index) -> !hlfir.expr<!fir.char<1,4>>
+        %joined = hlfir.concat %left, %right len %c8 : (!hlfir.expr<!fir.char<1,4>>, !hlfir.expr<!fir.char<1,4>>, index) -> !hlfir.expr<!fir.char<1,8>>
+        hlfir.yield_element %joined : !hlfir.expr<!fir.char<1,8>> cleanup {
+          hlfir.destroy %joined : !hlfir.expr<!fir.char<1,8>>
+        }
+      }
+      hlfir.yield %consumer : !hlfir.expr<10x!fir.char<1,8>> cleanup {
+        hlfir.destroy %consumer : !hlfir.expr<10x!fir.char<1,8>>
+        hlfir.destroy %producer : !hlfir.expr<10x!fir.char<1,4>>
+      }
+    } to {
+      hlfir.yield %out : !fir.ref<!fir.array<10x!fir.char<1,8>>>
+    }
+  }
+  return
+}
+// CHECK-LABEL: func.func @repeated_apply
+// CHECK: fir.do_loop
+// CHECK: fir.if
+// CHECK: %[[LEFT:.*]] = hlfir.concat
+// CHECK: %[[RIGHT:.*]] = hlfir.concat
+// CHECK: %[[JOINED:.*]] = hlfir.concat %[[LEFT]], %[[RIGHT]]
+// CHECK: hlfir.assign %[[JOINED]]
+// CHECK-NEXT: hlfir.destroy %[[JOINED]]
+// CHECK-NEXT: hlfir.destroy %[[RIGHT]]
+// CHECK-NEXT: hlfir.destroy %[[LEFT]]
+// CHECK-NOT: hlfir.destroy
+// CHECK: return
diff --git a/flang/test/HLFIR/set_length-codegen.fir b/flang/test/HLFIR/set_length-codegen.fir
index 07985e6383489e..c78519f95d3fcc 100644
--- a/flang/test/HLFIR/set_length-codegen.fir
+++ b/flang/test/HLFIR/set_length-codegen.fir
@@ -19,15 +19,18 @@ func.func @test_cst_len(%str : !fir.boxchar<1>) {
 
 func.func @test_dyn_len(%str : !fir.ref<!fir.char<1,10>>, %len : index) {
   %0 = hlfir.set_length %str len %len : (!fir.ref<!fir.char<1,10>>, index) -> !hlfir.expr<!fir.char<1,?>>
+  hlfir.destroy %0 : !hlfir.expr<!fir.char<1,?>>
   return
 }
 // CHECK-LABEL:   func.func @test_dyn_len(
 // CHECK-SAME:    %[[VAL_0:.*]]: !fir.ref<!fir.char<1,10>>,
 // CHECK-SAME:    %[[VAL_1:.*]]: index) {
-// CHECK:  %[[VAL_2:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_1]] : index) <{bindc_name = ".tmp"}>
-// CHECK:  %[[VAL_3:.*]]:2 = hlfir.declare %[[VAL_2]] typeparams %[[VAL_1]] uniq_name(".tmp") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+// CHECK:  %[[VAL_2:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_1]] : index) <{bindc_name = ".tmp", uniq_name = ""}>
+// CHECK:  %[[VAL_3:.*]]:2 = hlfir.declare %[[VAL_2]] typeparams %[[VAL_1]] uniq_name(".tmp") : (!fir.heap<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.heap<!fir.char<1,?>>)
 // CHECK:  hlfir.assign %[[VAL_0]] to %[[VAL_3]]#0 temporary_lhs : !fir.ref<!fir.char<1,10>>, !fir.boxchar<1>
-// CHECK:  %[[VAL_4:.*]] = arith.constant false
+// CHECK:  %[[VAL_4:.*]] = arith.constant true
 // CHECK:  %[[VAL_5:.*]] = fir.undefined tuple<!fir.boxchar<1>, i1>
 // CHECK:  %[[VAL_6:.*]] = fir.insert_value %[[VAL_5]], %[[VAL_4]], [1 : index] : (tuple<!fir.boxchar<1>, i1>, i1) -> tuple<!fir.boxchar<1>, i1>
 // CHECK:  %[[VAL_7:.*]] = fir.insert_value %[[VAL_6]], %[[VAL_3]]#0, [0 : index] : (tuple<!fir.boxchar<1>, i1>, !fir.boxchar<1>) -> tuple<!fir.boxchar<1>, i1>
+// CHECK:  %[[VAL_8:.*]] = fir.box_addr %[[VAL_3]]#0 : (!fir.boxchar<1>) -> !fir.heap<!fir.char<1,?>>
+// CHECK:  fir.freemem %[[VAL_8]] : !fir.heap<!fir.char<1,?>>
diff --git a/flang/test/HLFIR/simplify-hlfir-intrinsics-eoshift.fir b/flang/test/HLFIR/simplify-hlfir-intrinsics-eoshift.fir
index 583d4900967f0d..593781b61d9160 100644
--- a/flang/test/HLFIR/simplify-hlfir-intrinsics-eoshift.fir
+++ b/flang/test/HLFIR/simplify-hlfir-intrinsics-eoshift.fir
@@ -2102,7 +2102,9 @@ func.func @_QPeoshift17c(%arg0: !fir.ref<i32> {fir.bindc_name = "n"}, %arg1: !fi
     %23 = hlfir.designate %13#0 (%arg2, %arg3)  typeparams %c10 : (!fir.box<!fir.array<?x?x!fir.char<1,10>>>, index, index, index) -> !fir.ref<!fir.char<1,10>>
     %24 = hlfir.designate %13#0 (%arg2, %arg3)  typeparams %c10 : (!fir.box<!fir.array<?x?x!fir.char<1,10>>>, index, index, index) -> !fir.ref<!fir.char<1,10>>
     %25 = hlfir.concat %23, %24 len %c20 : (!fir.ref<!fir.char<1,10>>, !fir.ref<!fir.char<1,10>>, index) -> !hlfir.expr<!fir.char<1,20>>
-    hlfir.yield_element %25 : !hlfir.expr<!fir.char<1,20>>
+    hlfir.yield_element %25 : !hlfir.expr<!fir.char<1,20>> cleanup {
+      hlfir.destroy %25 : !hlfir.expr<!fir.char<1,20>>
+    }
   }
   %15:2 = hlfir.declare %1#0 uniq_name("_QFeoshift17cFcharc_boundaryEn") : (!fir.ref<i32>) -> (!fir.ref<i32>, !fir.ref<i32>)
   %16 = fir.load %15#0 : !fir.ref<i32>
diff --git a/flang/test/Lower/HLFIR/array-ctor-as-elemental-nested.f90 b/flang/test/Lower/HLFIR/array-ctor-as-elemental-nested.f90
index dd379e5fb82c3f..808730295390c7 100644
--- a/flang/test/Lower/HLFIR/array-ctor-as-elemental-nested.f90
+++ b/flang/test/Lower/HLFIR/array-ctor-as-elemental-nested.f90
@@ -32,9 +32,10 @@
 ! CHECK:             %[[VAL_23:.*]] = fir.embox %[[VAL_21]]#0(%[[VAL_17]]) : (!fir.ref<!fir.array<2xf32>>, !fir.shape<1>) -> !fir.box<!fir.array<2xf32>>
 ! CHECK:             %[[VAL_24:.*]] = fir.convert %[[VAL_23]] : (!fir.box<!fir.array<2xf32>>) -> !fir.box<!fir.array<?xf32>>
 ! CHECK:             %[[VAL_25:.*]] = fir.call @_QPfoo(%[[VAL_24]]) proc_attrs<pure> fastmath<contract> : (!fir.box<!fir.array<?xf32>>) -> f32
+! CHECK:             hlfir.yield_element %[[VAL_25]] : f32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_21]]#1, %[[VAL_21]]#2 : !fir.ref<!fir.array<2xf32>>, i1
 ! CHECK:             hlfir.destroy %[[VAL_22]] : !hlfir.expr<2xf32>
-! CHECK:             hlfir.yield_element %[[VAL_25]] : f32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_26:.*]] to %[[VAL_4]]#0 : !hlfir.expr<2xf32>, !fir.ref<!fir.array<2xf32>>
 ! CHECK:           hlfir.destroy %[[VAL_26]] : !hlfir.expr<2xf32>
diff --git a/flang/test/Lower/HLFIR/array-ctor-as-elemental.f90 b/flang/test/Lower/HLFIR/array-ctor-as-elemental.f90
index f8fe506939b6f6..a5bdc51c13543d 100644
--- a/flang/test/Lower/HLFIR/array-ctor-as-elemental.f90
+++ b/flang/test/Lower/HLFIR/array-ctor-as-elemental.f90
@@ -128,7 +128,7 @@ integer function impure_foo(i)
 ! CHECK:  return
 
 ! Test that the hlfir.expr result of the outer intrinsic call
-! is not destructed.
+! is destroyed in the element cleanup after its value has been consumed.
 subroutine test_hlfir_expr_result_destruction
   character(4) :: a(21)
   a = (/ (repeat(repeat(char(i),2),2),i=1,n) /)
@@ -142,16 +142,12 @@ subroutine test_hlfir_expr_result_destruction
 ! CHECK:             %[[VAL_68:.*]]:3 = hlfir.associate %[[VAL_66]] typeparams %{{.*}} {adapt.valuebyref} : (!hlfir.expr<!fir.char<1,2>>, index) -> (!fir.ref<!fir.char<1,2>>, !fir.ref<!fir.char<1,2>>, i1)
 ! CHECK:             %[[VAL_81:.*]]:2 = hlfir.declare %{{.*}} typeparams %{{.*}} uniq_name(".tmp.intrinsic_result") : (!fir.heap<!fir.char<1,4>>, index) -> (!fir.heap<!fir.char<1,4>>, !fir.heap<!fir.char<1,4>>)
 ! CHECK:             %[[VAL_83:.*]] = hlfir.as_expr %[[VAL_81]]#0 move %{{.*}} : (!fir.heap<!fir.char<1,4>>, i1) -> !hlfir.expr<!fir.char<1,4>>
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
-! CHECK:             hlfir.end_associate %[[VAL_68]]#1, %[[VAL_68]]#2 : !fir.ref<!fir.char<1,2>>, i1
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
-! CHECK:             hlfir.destroy %[[VAL_66]] : !hlfir.expr<!fir.char<1,2>>
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
-! CHECK:             hlfir.end_associate %[[VAL_51]]#1, %[[VAL_51]]#2 : !fir.ref<!fir.char<1>>, i1
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
-! CHECK:             hlfir.destroy %[[VAL_48]] : !hlfir.expr<!fir.char<1>>
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
-! CHECK:             hlfir.yield_element %[[VAL_83]] : !hlfir.expr<!fir.char<1,4>>
-! CHECK-NOT:         hlfir.destroy %[[VAL_83]]
+! CHECK-NEXT:        hlfir.yield_element %[[VAL_83]] : !hlfir.expr<!fir.char<1,4>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_83]] : !hlfir.expr<!fir.char<1,4>>
+! CHECK-NEXT:          hlfir.end_associate %[[VAL_68]]#1, %[[VAL_68]]#2 : !fir.ref<!fir.char<1,2>>, i1
+! CHECK-NEXT:          hlfir.destroy %[[VAL_66]] : !hlfir.expr<!fir.char<1,2>>
+! CHECK-NEXT:          hlfir.end_associate %[[VAL_51]]#1, %[[VAL_51]]#2 : !fir.ref<!fir.char<1>>, i1
+! CHECK-NEXT:          hlfir.destroy %[[VAL_48]] : !hlfir.expr<!fir.char<1>>
+! CHECK-NEXT:        }
 ! CHECK:           }
 ! CHECK-NOT:       hlfir.destroy %[[VAL_83]]
diff --git a/flang/test/Lower/HLFIR/character-expression-cleanup.f90 b/flang/test/Lower/HLFIR/character-expression-cleanup.f90
new file mode 100644
index 00000000000000..e7a56ac26262e8
--- /dev/null
+++ b/flang/test/Lower/HLFIR/character-expression-cleanup.f90
@@ -0,0 +1,50 @@
+! RUN: bbc -emit-hlfir %s -o - | FileCheck %s
+
+subroutine concat_cleanup(a, b, c)
+  character(*) :: a, b, c
+  c = (a // b)
+end subroutine
+! CHECK-LABEL: func.func @_QPconcat_cleanup
+! CHECK: %[[EXPR:.*]] = hlfir.concat
+! CHECK: %[[ALIAS:.*]] = hlfir.no_reassoc %[[EXPR]]
+! CHECK: hlfir.assign %[[ALIAS]]
+! CHECK: hlfir.destroy %[[EXPR]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: return
+
+subroutine statement_function_cleanup(a, b)
+  character(*) :: a, b
+  character(len(a)) :: f, x
+  f(x) = x
+  b = f(a)
+end subroutine
+! CHECK-LABEL: func.func @_QPstatement_function_cleanup
+! CHECK: %[[EXPR:.*]] = hlfir.set_length
+! CHECK: hlfir.assign %[[EXPR]]
+! CHECK: hlfir.destroy %[[EXPR]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: return
+
+subroutine parens_cleanup(a, b)
+  character(*) :: a, b
+  b = (a)
+end subroutine
+! CHECK-LABEL: func.func @_QPparens_cleanup
+! CHECK: %[[EXPR:.*]] = hlfir.as_expr
+! CHECK: hlfir.assign %[[EXPR]]
+! CHECK: hlfir.destroy %[[EXPR]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: return
+
+subroutine kind_cleanup(a, b)
+  character(*) :: a
+  character(kind=4, len=*) :: b
+  b = a
+end subroutine
+! CHECK-LABEL: func.func @_QPkind_cleanup
+! CHECK: fir.allocmem !fir.char<4,?>
+! CHECK: fir.char_convert
+! CHECK: %[[EXPR:.*]] = hlfir.as_expr {{.*}} move
+! CHECK: hlfir.assign %[[EXPR]]
+! CHECK: hlfir.destroy %[[EXPR]]
+! CHECK: return
diff --git a/flang/test/Lower/HLFIR/charconvert.f90 b/flang/test/Lower/HLFIR/charconvert.f90
index b945f31e6bd227..95e121afd49d84 100644
--- a/flang/test/Lower/HLFIR/charconvert.f90
+++ b/flang/test/Lower/HLFIR/charconvert.f90
@@ -22,8 +22,8 @@ end subroutine charconvert1
 ! CHECK:     %[[VAL_42:.*]]:2 = fir.unboxchar %[[VAL_39]] : (!fir.boxchar<4>) -> (!fir.ref<!fir.char<4,?>>, index)
 ! CHECK:     %[[C4_5:.*]] = arith.constant 4 : index
 ! CHECK:     %[[VAL_40:.*]] = arith.muli %[[VAL_38]], %[[C4_5]] : index
-! CHECK:     %[[VAL_41:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_40]] : index)
-! CHECK:     fir.char_convert %[[VAL_42]]#0 for %[[VAL_38:.*]] to %[[VAL_41]] : !fir.ref<!fir.char<4,?>>, index, !fir.ref<!fir.char<1,?>>
+! CHECK:     %[[VAL_41:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_40]] : index)
+! CHECK:     fir.char_convert %[[VAL_42]]#0 for %[[VAL_38:.*]] to %[[VAL_41]] : !fir.ref<!fir.char<4,?>>, index, !fir.heap<!fir.char<1,?>>
 
 subroutine charconvert2(x)
   integer,intent(in) :: x
@@ -46,8 +46,9 @@ end subroutine charconvert2
 ! CHECK:   %[[FALSE:.*]] = arith.constant false
 ! CHECK:   %[[VAL_9:.*]] = hlfir.as_expr %[[VAL_0]] move %[[FALSE]] : (!fir.ref<!fir.char<1>>, i1) -> !hlfir.expr<!fir.char<1>>
 ! CHECK:   %[[C1_0:.*]] = arith.constant 1 : index
+! CHECK:   %[[ASSOC:.*]]:3 = hlfir.associate %[[VAL_9]]
 ! CHECK:   %[[VAL_10:.*]] = fir.alloca !fir.char<4,?>(%[[C1_0]] : index)
-! CHECK:   fir.char_convert %[[VAL_0:.*]] for %[[C1_0]] to %[[VAL_10]] : !fir.ref<!fir.char<1>>, index, !fir.ref<!fir.char<4,?>>
+! CHECK:   fir.char_convert %[[ASSOC]]#0 for %[[C1_0]] to %[[VAL_10]] : !fir.ref<!fir.char<1>>, index, !fir.ref<!fir.char<4,?>>
 
 subroutine charconvert3(c, c4)
   character(kind=1, len=*) :: c
@@ -64,8 +65,10 @@ subroutine charconvert3(c, c4)
 ! CHECK:   %[[VAL_4:.*]] = arith.addi %[[VAL_0]]#1, %[[VAL_0]]#1 : index
 ! CHECK:   %[[VAL_5:.*]] = hlfir.concat %[[VAL_1]]#0, %[[VAL_1]]#0 len %[[VAL_4]] : (!fir.boxchar<1>, !fir.boxchar<1>, index) -> !hlfir.expr<!fir.char<1,?>>
 ! CHECK:   %[[VAL_7:.*]]:3 = hlfir.associate %[[VAL_5]] typeparams %[[VAL_4]] {adapt.valuebyref} : (!hlfir.expr<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>, i1)
-! CHECK:   %[[VAL_6:.*]] = fir.alloca !fir.char<4,?>(%[[VAL_4]] : index)
-! CHECK:   fir.char_convert %[[VAL_7]]#1 for %[[VAL_4:.*]] to %[[VAL_6]] : !fir.ref<!fir.char<1,?>>, index, !fir.ref<!fir.char<4,?>>
+! CHECK:   %[[VAL_6:.*]] = fir.allocmem !fir.char<4,?>(%[[VAL_4]] : index)
+! CHECK:   fir.char_convert %[[VAL_7]]#1 for %[[VAL_4:.*]] to %[[VAL_6]] : !fir.ref<!fir.char<1,?>>, index, !fir.heap<!fir.char<4,?>>
 ! CHECK:   hlfir.end_associate %[[VAL_7]]#1, %[[VAL_7]]#2 : !fir.ref<!fir.char<1,?>>, i1
-! CHECK:   %[[VAL_8:.*]]:2 = hlfir.declare %[[VAL_6]] typeparams %[[VAL_4]] uniq_name(".temp.kindconvert") : (!fir.ref<!fir.char<4,?>>, index) -> (!fir.boxchar<4>, !fir.ref<!fir.char<4,?>>)
-! CHECK:   hlfir.assign %[[VAL_8]]#0 to %[[VAL_3]]#0 : !fir.boxchar<4>, !fir.boxchar<4>
+! CHECK:   %[[VAL_8:.*]]:2 = hlfir.declare %[[VAL_6]] typeparams %[[VAL_4]] uniq_name(".temp.kindconvert") : (!fir.heap<!fir.char<4,?>>, index) -> (!fir.boxchar<4>, !fir.heap<!fir.char<4,?>>)
+! CHECK:   %[[CONVERTED:.*]] = hlfir.as_expr %[[VAL_8]]#0 move
+! CHECK:   hlfir.assign %[[CONVERTED]] to %[[VAL_3]]#0 : !hlfir.expr<!fir.char<4,?>>, !fir.boxchar<4>
+! CHECK:   hlfir.destroy %[[CONVERTED]]
diff --git a/flang/test/Lower/HLFIR/elemental-call-vector-subscripts.f90 b/flang/test/Lower/HLFIR/elemental-call-vector-subscripts.f90
index 6440ed37812a42..31f85eb9002612 100644
--- a/flang/test/Lower/HLFIR/elemental-call-vector-subscripts.f90
+++ b/flang/test/Lower/HLFIR/elemental-call-vector-subscripts.f90
@@ -91,3 +91,88 @@ elemental subroutine foo2(j)
 ! CHECK:             fir.call @_QPfoo2(%[[VAL_23]]#0){{.*}}: (!fir.ref<i64>) -> ()
 ! CHECK:             hlfir.end_associate %[[VAL_23]]#1, %[[VAL_23]]#2 : !fir.ref<i64>, i1
 ! CHECK:           }
+
+subroutine vector_index(x, a, b)
+  real :: x(:)
+  integer :: a(:), b(:)
+  interface
+    elemental subroutine consume(x)
+      real, intent(in) :: x
+    end subroutine
+  end interface
+  call consume(x(a+b))
+end subroutine
+subroutine scalar_index(x, a, b, v)
+  real :: x(:,:)
+  integer :: a(:), b(:), v(:)
+  interface
+    elemental subroutine consume(x)
+      real, intent(in) :: x
+    end subroutine
+  end interface
+  call consume(x(v,sum(a+b)))
+end subroutine
+subroutine character_index(x, a, b)
+  real :: x(:)
+  character(*) :: a(:), b(:)
+  interface
+    elemental subroutine consume(x)
+      real, intent(in) :: x
+    end subroutine
+  end interface
+  call consume(x(len_trim(a//b)))
+end subroutine
+
+! The index expression arrays belong to the enclosing statement, not the
+! per-element address computation. No cleanup may precede the call loop.
+! CHECK-LABEL: func.func @_QPvector_index
+! CHECK: %[[ADD:.*]] = hlfir.elemental
+! CHECK: arith.addi
+! CHECK: %[[CAST:.*]] = hlfir.elemental
+! CHECK: hlfir.apply %[[ADD]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: fir.do_loop
+! CHECK: hlfir.apply %[[CAST]]
+! CHECK: fir.call @_QPconsume
+! CHECK: }
+! CHECK-NEXT: hlfir.destroy %[[CAST]]
+! CHECK-NEXT: hlfir.destroy %[[ADD]]
+! CHECK-NEXT: return
+
+! CHECK-LABEL: func.func @_QPscalar_index
+! CHECK: %[[VECTOR:.*]] = hlfir.elemental
+! CHECK: %[[ADD:.*]] = hlfir.elemental
+! CHECK: %[[SUM:.*]] = hlfir.sum %[[ADD]]
+! CHECK: %[[INDEX:.*]] = fir.convert %[[SUM]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: fir.do_loop
+! CHECK: %[[V:.*]] = hlfir.apply %[[VECTOR]]
+! CHECK: hlfir.designate %{{.*}} (%[[V]], %[[INDEX]])
+! CHECK: fir.call @_QPconsume
+! CHECK: }
+! CHECK-NEXT: hlfir.destroy %[[ADD]]
+! CHECK-NEXT: hlfir.destroy %[[VECTOR]]
+! CHECK-NEXT: return
+
+! Character subexpressions retain their per-element cleanup regions, while
+! their containing arrays are cleaned up after the elemental subroutine call.
+! CHECK-LABEL: func.func @_QPcharacter_index
+! CHECK: %[[CHARS:.*]] = hlfir.elemental
+! CHECK: %[[CONCAT:.*]] = hlfir.concat
+! CHECK-NEXT: hlfir.yield_element %[[CONCAT]] : {{.*}} cleanup {
+! CHECK-NEXT: hlfir.destroy %[[CONCAT]]
+! CHECK: %[[LENGTHS:.*]] = hlfir.elemental
+! CHECK: hlfir.apply %[[CHARS]]
+! CHECK: hlfir.yield_element {{.*}} cleanup {
+! CHECK: hlfir.end_associate
+! CHECK: %[[INDICES:.*]] = hlfir.elemental
+! CHECK: hlfir.apply %[[LENGTHS]]
+! CHECK-NOT: hlfir.destroy
+! CHECK: fir.do_loop
+! CHECK: hlfir.apply %[[INDICES]]
+! CHECK: fir.call @_QPconsume
+! CHECK: }
+! CHECK-NEXT: hlfir.destroy %[[INDICES]]
+! CHECK-NEXT: hlfir.destroy %[[LENGTHS]]
+! CHECK-NEXT: hlfir.destroy %[[CHARS]]
+! CHECK-NEXT: return
diff --git a/flang/test/Lower/HLFIR/implicit-type-conversion-allocatable.f90 b/flang/test/Lower/HLFIR/implicit-type-conversion-allocatable.f90
index c263d4870f3584..845916d4d9cf85 100644
--- a/flang/test/Lower/HLFIR/implicit-type-conversion-allocatable.f90
+++ b/flang/test/Lower/HLFIR/implicit-type-conversion-allocatable.f90
@@ -60,7 +60,8 @@ subroutine kind_and_length(a, b)
 ! CHECK:           %[[VAL_12:.*]] = fir.alloca !fir.char<4,?>(%[[VAL_4]] : index)
 ! CHECK:           fir.char_convert %[[VAL_11]] for %[[VAL_4]] to %[[VAL_12]] : !fir.ref<!fir.char<1,2>>, index, !fir.ref<!fir.char<4,?>>
 ! CHECK:           %[[VAL_13:.*]]:2 = hlfir.declare %[[VAL_12:[a-z0-9]*]] typeparams %[[VAL_4:[a-z0-9]*]] uniq_name(".temp.kindconvert") : (!fir.ref<!fir.char<4,?>>, index) -> (!fir.boxchar<4>, !fir.ref<!fir.char<4,?>>)
-! CHECK:           hlfir.yield_element %[[VAL_13]]#0 : !fir.boxchar<4>
+! CHECK:           %[[EXPR:.*]] = hlfir.as_expr %[[VAL_13]]#0 move
+! CHECK:           hlfir.yield_element %[[EXPR]] : !hlfir.expr<!fir.char<4,?>>
 ! CHECK:         }
 ! CHECK:         hlfir.assign %[[VAL_9]] to %[[VAL_3]]#0 realloc keep_lhs_len : !hlfir.expr<?x!fir.char<4,2>>, !fir.ref<!fir.box<!fir.heap<!fir.array<?x!fir.char<4,4>>>>>
 
diff --git a/flang/test/Lower/achar.f90 b/flang/test/Lower/achar.f90
index c916df45e80d4e..408b82ddfc931a 100644
--- a/flang/test/Lower/achar.f90
+++ b/flang/test/Lower/achar.f90
@@ -29,7 +29,8 @@ end subroutine achar_test1
 ! CHECK: fir.char_convert %[[ASSOC]]#0 for %{{.*}} to %[[KIND_TMP]] : !fir.ref<!fir.char<1>>, index, !fir.ref<!fir.char<2,?>>
 ! CHECK: hlfir.end_associate %[[ASSOC]]#1, %[[ASSOC]]#2 : !fir.ref<!fir.char<1>>, i1
 ! CHECK: %[[CONVERTED:.*]]:2 = hlfir.declare %[[KIND_TMP]] typeparams %{{.*}} uniq_name(".temp.kindconvert")
-! CHECK: %[[SET_LENGTH:.*]] = hlfir.set_length %[[CONVERTED]]#0
+! CHECK: %[[KIND_EXPR:.*]] = hlfir.as_expr %[[CONVERTED]]#0 move
+! CHECK: %[[SET_LENGTH:.*]] = hlfir.set_length %[[KIND_EXPR]]
 ! CHECK: hlfir.assign %[[SET_LENGTH]] to %[[CH]]#0
 ! CHECK: hlfir.destroy %[[EXPR]]
 ! CHECK: fir.call @_QPachar_test1_foo(%{{.*}}) {{.*}}: (!fir.boxchar<2>) -> ()
diff --git a/flang/test/Lower/array-elemental-calls-2.f90 b/flang/test/Lower/array-elemental-calls-2.f90
index b807a95369f9a7..383cfe57cc652d 100644
--- a/flang/test/Lower/array-elemental-calls-2.f90
+++ b/flang/test/Lower/array-elemental-calls-2.f90
@@ -43,8 +43,9 @@ subroutine check_binary_ops()
 ! CHECK:    %[[VAL_37:.*]] = hlfir.apply %[[VAL_29]], %[[ARG0]] : (!hlfir.expr<10xi32>, index) -> i32
 ! CHECK:    %[[VAL_38:.*]]:3 = hlfir.associate %[[VAL_37]] {adapt.valuebyref} : (i32) -> (!fir.ref<i32>, !fir.ref<i32>, i1)
 ! CHECK:    %[[VAL_39:.*]] = fir.call @_QPelem_func(%[[VAL_38]]#0) {{.*}} : (!fir.ref<i32>) -> i32
+! CHECK:    hlfir.yield_element %[[VAL_39]] : i32 cleanup {
 ! CHECK:    hlfir.end_associate %[[VAL_38]]#1, %[[VAL_38]]#2 : !fir.ref<i32>, i1
-! CHECK:    hlfir.yield_element %[[VAL_39]] : i32
+! CHECK:             }
 ! CHECK:  }
 end subroutine
 
@@ -294,8 +295,9 @@ integer elemental function elem_func_derived(x)
 ! CHECK:    %[[VAL_50:.*]] = hlfir.apply %[[VAL_42]], %[[ARG1]] : (!hlfir.expr<?x!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>, index) -> !hlfir.expr<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>
 ! CHECK:    %[[VAL_51:.*]]:3 = hlfir.associate %[[VAL_50]] {adapt.valuebyref} : (!hlfir.expr<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>) -> (!fir.ref<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>, !fir.ref<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>, i1)
 ! CHECK:    %[[VAL_52:.*]] = fir.call @_QPelem_func_derived(%[[VAL_51]]#0) {{.*}} : (!fir.ref<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>) -> i32
+! CHECK:    hlfir.yield_element %[[VAL_52]] : i32 cleanup {
 ! CHECK:    hlfir.end_associate %[[VAL_51]]#1, %[[VAL_51]]#2 : !fir.ref<!fir.type<_QMtest_opsFcheck_parentheses_derivedTt{i:i32}>>, i1
-! CHECK:    hlfir.yield_element %[[VAL_52]] : i32
+! CHECK:             }
 ! CHECK:  }
 end subroutine
 end module
diff --git a/flang/test/Lower/array-elemental-calls-char-byval.f90 b/flang/test/Lower/array-elemental-calls-char-byval.f90
index 880050dd4fdf5d..2933dee377b62a 100644
--- a/flang/test/Lower/array-elemental-calls-char-byval.f90
+++ b/flang/test/Lower/array-elemental-calls-char-byval.f90
@@ -41,8 +41,9 @@ subroutine foo1(i, j, c)
 ! CHECK:             %[[VAL_19:.*]]:3 = hlfir.associate %[[VAL_18]] typeparams %[[VAL_4]]#1 {adapt.valuebyref} : (!hlfir.expr<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>, i1)
 ! CHECK:             %[[VAL_20:.*]] = hlfir.designate %[[VAL_14]]#0 (%[[VAL_16]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_21:.*]] = fir.call @_QPelem(%[[VAL_19]]#0, %[[VAL_20]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_21]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_19]]#1, %[[VAL_19]]#2 : !fir.ref<!fir.char<1,?>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_21]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_15]] to %[[VAL_11]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_15]] : !hlfir.expr<10xi32>
@@ -73,8 +74,9 @@ subroutine foo2(i, j, c)
 ! CHECK:             %[[VAL_15:.*]]:3 = hlfir.associate %[[VAL_14]] typeparams %[[VAL_4]]#1 {adapt.valuebyref} : (!hlfir.expr<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>, i1)
 ! CHECK:             %[[VAL_16:.*]] = hlfir.designate %[[VAL_11]]#0 (%[[VAL_13]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_17:.*]] = fir.call @_QPelem(%[[VAL_15]]#0, %[[VAL_16]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_17]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_15]]#1, %[[VAL_15]]#2 : !fir.ref<!fir.char<1,?>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_17]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_12]] to %[[VAL_8]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_12]] : !hlfir.expr<10xi32>
@@ -122,8 +124,9 @@ subroutine foo3(i, j)
 ! CHECK:             %[[VAL_28:.*]] = fir.emboxchar %[[VAL_27]]#0, %[[VAL_15]] : (!fir.ref<!fir.char<1>>, index) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_29:.*]] = hlfir.designate %[[VAL_9]]#0 (%[[VAL_25]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_30:.*]] = fir.call @_QPelem(%[[VAL_28]], %[[VAL_29]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_30]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_27]]#1, %[[VAL_27]]#2 : !fir.ref<!fir.char<1>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_30]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_24]] to %[[VAL_6]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_24]] : !hlfir.expr<10xi32>
@@ -164,8 +167,9 @@ subroutine foo4(i, j)
 ! CHECK:             %[[VAL_23:.*]] = fir.emboxchar %[[VAL_22]]#0, %[[VAL_21]] : (!fir.ref<!fir.char<1>>, index) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_24:.*]] = hlfir.designate %[[VAL_9]]#0 (%[[VAL_20]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_25:.*]] = fir.call @_QPelem(%[[VAL_23]], %[[VAL_24]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_25]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_22]]#1, %[[VAL_22]]#2 : !fir.ref<!fir.char<1>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_25]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_19]] to %[[VAL_6]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_19]] : !hlfir.expr<10xi32>
@@ -200,8 +204,9 @@ subroutine foo5(i, j)
 ! CHECK:             %[[VAL_16:.*]] = fir.emboxchar %[[VAL_15]]#0, %[[VAL_10]] : (!fir.ref<!fir.char<1,5>>, index) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_17:.*]] = hlfir.designate %[[VAL_8]]#0 (%[[VAL_13]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_18:.*]] = fir.call @_QPelem(%[[VAL_16]], %[[VAL_17]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_18]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_15]]#1, %[[VAL_15]]#2 : !fir.ref<!fir.char<1,5>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_18]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_12]] to %[[VAL_5]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_12]] : !hlfir.expr<10xi32>
diff --git a/flang/test/Lower/array-elemental-calls-char-dynamic.f90 b/flang/test/Lower/array-elemental-calls-char-dynamic.f90
index 3eeb3873a1cfb7..0bdcb015688d09 100644
--- a/flang/test/Lower/array-elemental-calls-char-dynamic.f90
+++ b/flang/test/Lower/array-elemental-calls-char-dynamic.f90
@@ -43,7 +43,8 @@ elemental function bug_145151_1(c_dummy)
 ! CHECK:             %[[VAL_21:.*]] = fir.call @_QPbug_145151_1(%[[VAL_20]], %[[VAL_14]], %[[VAL_19]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.ref<!fir.char<1,?>>, index, !fir.boxchar<1>) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_23:.*]] = arith.constant false
 ! CHECK:             %[[VAL_24:.*]] = hlfir.as_expr %[[VAL_22]]#0 move %[[VAL_23]] : (!fir.boxchar<1>, i1) -> !hlfir.expr<!fir.char<1,?>>
-! CHECK:             hlfir.yield_element %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>>
+! CHECK:             hlfir.yield_element %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>>
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_15]] to %[[VAL_1]]#0 : !hlfir.expr<?x!fir.char<1,?>>, !fir.box<!fir.array<?x!fir.char<1,?>>>
 ! CHECK:           hlfir.destroy %[[VAL_15]] : !hlfir.expr<?x!fir.char<1,?>>
@@ -93,7 +94,8 @@ elemental function bug_145151_2(x)
 ! CHECK:             %[[VAL_18:.*]] = fir.call @_QPbug_145151_2(%[[VAL_17]], %[[VAL_12]], %[[VAL_16]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.ref<!fir.char<1,?>>, index, f32) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_20:.*]] = arith.constant false
 ! CHECK:             %[[VAL_21:.*]] = hlfir.as_expr %[[VAL_19]]#0 move %[[VAL_20]] : (!fir.boxchar<1>, i1) -> !hlfir.expr<!fir.char<1,?>>
-! CHECK:             hlfir.yield_element %[[VAL_21]] : !hlfir.expr<!fir.char<1,?>>
+! CHECK:             hlfir.yield_element %[[VAL_21]] : !hlfir.expr<!fir.char<1,?>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_21]] : !hlfir.expr<!fir.char<1,?>>
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_13]] to %[[VAL_1]]#0 : !hlfir.expr<?x!fir.char<1,?>>, !fir.box<!fir.array<?x!fir.char<1,?>>>
 ! CHECK:           hlfir.destroy %[[VAL_13]] : !hlfir.expr<?x!fir.char<1,?>>
@@ -161,7 +163,8 @@ elemental function f_opt(x, opt)
 ! CHECK:             %[[VAL_29:.*]] = fir.call @_QPf_opt(%[[VAL_28]], %[[VAL_21]], %[[VAL_24]], %[[VAL_25]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.ref<!fir.char<1,?>>, index, !fir.ref<f32>, !fir.ref<f32>) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_31:.*]] = arith.constant false
 ! CHECK:             %[[VAL_32:.*]] = hlfir.as_expr %[[VAL_30]]#0 move %[[VAL_31]] : (!fir.boxchar<1>, i1) -> !hlfir.expr<!fir.char<1,?>>
-! CHECK:             hlfir.yield_element %[[VAL_32]] : !hlfir.expr<!fir.char<1,?>>
+! CHECK:             hlfir.yield_element %[[VAL_32]] : !hlfir.expr<!fir.char<1,?>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_32]] : !hlfir.expr<!fir.char<1,?>>
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_22]] to %[[VAL_2]]#0 : !hlfir.expr<?x!fir.char<1,?>>, !fir.box<!fir.array<?x!fir.char<1,?>>>
 ! CHECK:           hlfir.destroy %[[VAL_22]] : !hlfir.expr<?x!fir.char<1,?>>
@@ -227,7 +230,8 @@ elemental function f_poly(p1, p2)
 ! CHECK:             %[[VAL_35:.*]] = fir.call @_QPf_poly(%[[VAL_34]], %[[VAL_29]], %[[VAL_32]], %[[VAL_33]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.ref<!fir.char<1,?>>, index, !fir.class<!fir.type<_QFtest_polymorphicTt>>, !fir.class<!fir.type<_QFtest_polymorphicTt>>) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_37:.*]] = arith.constant false
 ! CHECK:             %[[VAL_38:.*]] = hlfir.as_expr %[[VAL_36]]#0 move %[[VAL_37]] : (!fir.boxchar<1>, i1) -> !hlfir.expr<!fir.char<1,?>>
-! CHECK:             hlfir.yield_element %[[VAL_38]] : !hlfir.expr<!fir.char<1,?>>
+! CHECK:             hlfir.yield_element %[[VAL_38]] : !hlfir.expr<!fir.char<1,?>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_38]] : !hlfir.expr<!fir.char<1,?>>
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_30]] to %[[VAL_3]]#0 : !hlfir.expr<?x!fir.char<1,?>>, !fir.box<!fir.array<?x!fir.char<1,?>>>
 ! CHECK:           hlfir.destroy %[[VAL_30]] : !hlfir.expr<?x!fir.char<1,?>>
@@ -274,8 +278,10 @@ elemental function f_value(c_dummy)
 ! CHECK:             %[[VAL_21:.*]] = fir.call @_QPf_value(%[[VAL_20]], %[[VAL_13]], %[[VAL_19]]#0) proc_attrs<elemental, pure> fastmath<contract> : (!fir.ref<!fir.char<1,?>>, index, !fir.boxchar<1>) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_23:.*]] = arith.constant false
 ! CHECK:             %[[VAL_24:.*]] = hlfir.as_expr %[[VAL_22]]#0 move %[[VAL_23]] : (!fir.boxchar<1>, i1) -> !hlfir.expr<!fir.char<1,?>>
+! CHECK:             hlfir.yield_element %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>> cleanup {
+! CHECK-NEXT:          hlfir.destroy %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>>
 ! CHECK:             hlfir.end_associate %[[VAL_19]]#1, %[[VAL_19]]#2 : !fir.ref<!fir.char<1,?>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_24]] : !hlfir.expr<!fir.char<1,?>>
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_14]] to %[[VAL_1]]#0 : !hlfir.expr<?x!fir.char<1,?>>, !fir.box<!fir.array<?x!fir.char<1,?>>>
 ! CHECK:           hlfir.destroy %[[VAL_14]] : !hlfir.expr<?x!fir.char<1,?>>
diff --git a/flang/test/Lower/array-elemental-calls-char.f90 b/flang/test/Lower/array-elemental-calls-char.f90
index d5b7c434e93dab..f62d6d057448e4 100644
--- a/flang/test/Lower/array-elemental-calls-char.f90
+++ b/flang/test/Lower/array-elemental-calls-char.f90
@@ -177,8 +177,9 @@ subroutine foo3(i, j)
 ! CHECK:             %[[VAL_27:.*]]:3 = hlfir.associate %[[VAL_26]] typeparams %[[VAL_15]] {adapt.valuebyref} : (!hlfir.expr<!fir.char<1>>, index) -> (!fir.ref<!fir.char<1>>, !fir.ref<!fir.char<1>>, i1)
 ! CHECK:             %[[VAL_28:.*]] = fir.emboxchar %[[VAL_27]]#0, %[[VAL_15]] : (!fir.ref<!fir.char<1>>, index) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_29:.*]] = fir.call @_QPelem(%[[VAL_28]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_29]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_27]]#1, %[[VAL_27]]#2 : !fir.ref<!fir.char<1>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_29]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_24]] to %[[VAL_6]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_24]] : !hlfir.expr<10xi32>
@@ -211,8 +212,9 @@ subroutine foo4(i, j)
 ! CHECK:             %[[VAL_16:.*]] = fir.emboxchar %[[VAL_15]]#0, %[[VAL_10]] : (!fir.ref<!fir.char<1,5>>, index) -> !fir.boxchar<1>
 ! CHECK:             %[[VAL_17:.*]] = hlfir.designate %[[VAL_8]]#0 (%[[VAL_13]])  : (!fir.ref<!fir.array<10xi32>>, index) -> !fir.ref<i32>
 ! CHECK:             %[[VAL_18:.*]] = fir.call @_QPelem2(%[[VAL_16]], %[[VAL_17]]) proc_attrs<elemental, pure> fastmath<contract> : (!fir.boxchar<1>, !fir.ref<i32>) -> i32
+! CHECK:             hlfir.yield_element %[[VAL_18]] : i32 cleanup {
 ! CHECK:             hlfir.end_associate %[[VAL_15]]#1, %[[VAL_15]]#2 : !fir.ref<!fir.char<1,5>>, i1
-! CHECK:             hlfir.yield_element %[[VAL_18]] : i32
+! CHECK:             }
 ! CHECK:           }
 ! CHECK:           hlfir.assign %[[VAL_12]] to %[[VAL_5]]#0 : !hlfir.expr<10xi32>, !fir.ref<!fir.array<10xi32>>
 ! CHECK:           hlfir.destroy %[[VAL_12]] : !hlfir.expr<10xi32>
diff --git a/flang/test/Lower/charconvert.f90 b/flang/test/Lower/charconvert.f90
index 8171ad9997218c..d22ce8262fa47e 100644
--- a/flang/test/Lower/charconvert.f90
+++ b/flang/test/Lower/charconvert.f90
@@ -17,8 +17,8 @@ subroutine test_c4_to_c1(c4, c1)
 ! CHECK:   %[[VAL_1:.*]]:2 = hlfir.declare %[[VAL_0]]#0 typeparams %[[VAL_0]]#1 dummy_scope %{{[0-9]+}} arg {{[0-9]+}} uniq_name("_QFtest_c1_to_c4Ec1") : (!fir.ref<!fir.char<1,?>>, index, !fir.dscope) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
 ! CHECK:   %[[VAL_2:.*]]:2 = fir.unboxchar %[[ARG0]] : (!fir.boxchar<4>) -> (!fir.ref<!fir.char<4,?>>, index)
 ! CHECK:   %[[VAL_3:.*]]:2 = hlfir.declare %[[VAL_2]]#0 typeparams %[[VAL_2]]#1 dummy_scope %{{[0-9]+}} arg {{[0-9]+}} uniq_name("_QFtest_c1_to_c4Ec4") : (!fir.ref<!fir.char<4,?>>, index, !fir.dscope) -> (!fir.boxchar<4>, !fir.ref<!fir.char<4,?>>)
-! CHECK:   %[[VAL_4:.*]] = fir.alloca !fir.char<4,?>(%[[VAL_0]]#1 : index)
-! CHECK:   fir.char_convert %[[VAL_1]]#1 for %[[VAL_0]]#1 to %[[VAL_4:.*]] : !fir.ref<!fir.char<1,?>>, index, !fir.ref<!fir.char<4,?>>
+! CHECK:   %[[VAL_4:.*]] = fir.allocmem !fir.char<4,?>(%[[VAL_0]]#1 : index)
+! CHECK:   fir.char_convert %[[VAL_1]]#1 for %[[VAL_0]]#1 to %[[VAL_4:.*]] : !fir.ref<!fir.char<1,?>>, index, !fir.heap<!fir.char<4,?>>
 
 ! CHECK: func.func @_QPtest_c4_to_c1(%[[ARG0:.*]]: !fir.boxchar<4> {fir.bindc_name = "c4"}, %[[ARG1:.*]]: !fir.boxchar<1> {fir.bindc_name = "c1"}) {
 ! CHECK:   %[[VAL_0:.*]]:2 = fir.unboxchar %[[ARG1]] : (!fir.boxchar<1>) -> (!fir.ref<!fir.char<1,?>>, index)
@@ -27,6 +27,6 @@ subroutine test_c4_to_c1(c4, c1)
 ! CHECK:   %[[VAL_3:.*]]:2 = hlfir.declare %[[VAL_2]]#0 typeparams %[[VAL_2]]#1 dummy_scope %{{[0-9]+}} arg {{[0-9]+}} uniq_name("_QFtest_c4_to_c1Ec4") : (!fir.ref<!fir.char<4,?>>, index, !fir.dscope) -> (!fir.boxchar<4>, !fir.ref<!fir.char<4,?>>)
 ! CHECK:   %[[C4:.*]] = arith.constant 4 : index
 ! CHECK:   %[[VAL_4:.*]] = arith.muli %[[VAL_2]]#1, %[[C4]] : index
-! CHECK:   %[[VAL_5:.*]] = fir.alloca !fir.char<1,?>(%[[VAL_4]] : index)
-! CHECK:   fir.char_convert %[[VAL_3]]#1 for %[[VAL_2]]#1 to %[[VAL_5:.*]] : !fir.ref<!fir.char<4,?>>, index, !fir.ref<!fir.char<1,?>>
-! CHECK:   %[[VAL_6:.*]]:2 = hlfir.declare %[[VAL_5]] typeparams %[[VAL_2]]#1 uniq_name(".temp.kindconvert") : (!fir.ref<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.ref<!fir.char<1,?>>)
+! CHECK:   %[[VAL_5:.*]] = fir.allocmem !fir.char<1,?>(%[[VAL_4]] : index)
+! CHECK:   fir.char_convert %[[VAL_3]]#1 for %[[VAL_2]]#1 to %[[VAL_5:.*]] : !fir.ref<!fir.char<4,?>>, index, !fir.heap<!fir.char<1,?>>
+! CHECK:   %[[VAL_6:.*]]:2 = hlfir.declare %[[VAL_5]] typeparams %[[VAL_2]]#1 uniq_name(".temp.kindconvert") : (!fir.heap<!fir.char<1,?>>, index) -> (!fir.boxchar<1>, !fir.heap<!fir.char<1,?>>)
diff --git a/flang/test/Transforms/character-expression-storage.f90 b/flang/test/Transforms/character-expression-storage.f90
new file mode 100644
index 00000000000000..e607b2ddfc096b
--- /dev/null
+++ b/flang/test/Transforms/character-expression-storage.f90
@@ -0,0 +1,142 @@
+! RUN: bbc -emit-fir %s -o - | fir-opt --canonicalize --allocation-placement | FileCheck %s
+! RUN: bbc -emit-hlfir %s -o - | fir-opt --inline-elementals | FileCheck %s --check-prefix=INLINE
+! RUN: bbc -emit-hlfir %s -o - | fir-opt --lower-hlfir-ordered-assignments | FileCheck %s --check-prefix=WHERE
+! RUN: bbc -emit-hlfir %s -o - | fir-opt --inline-elementals --opt-bufferization | FileCheck %s --check-prefix=OPT
+
+! A statement in an unstructured loop must reclaim its character temporaries
+! before the backedge, including when the statement is under an IF.
+subroutine scalar_loop(s, n)
+  character(*) :: s
+  integer :: n, i
+  i = 0
+  do while (i < n)
+    i = i + 1
+    if (i /= 2) call consume(s(1:i) // '')
+  end do
+end subroutine
+! CHECK-LABEL: func.func @_QPscalar_loop
+! CHECK: llvm.intr.stacksave
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK: fir.call @_QPconsume
+! CHECK: llvm.intr.stackrestore
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK: return
+
+! After elemental fusion, the scalar scratch buffers of an element are
+! reclaimed before the next iteration.
+subroutine concat_array(a, b, c)
+  character(*) :: a(:), b(:), c(:)
+  c = a // b // '!'
+end subroutine
+! CHECK-LABEL: func.func @_QPconcat_array
+! CHECK: fir.do_loop
+! CHECK: llvm.intr.stacksave
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK: llvm.intr.stackrestore
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK: return
+
+! The concatenation becomes an intermediate scalar expression when the
+! elementals are fused. It needs cleanup even though it is not yielded.
+subroutine compare_array(a, b, c, result)
+  character(*) :: a(:), b(:), c(:)
+  logical :: result(:)
+  result = a // b == c
+end subroutine
+! CHECK-LABEL: func.func @_QPcompare_array
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK: fir.do_loop
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK-NOT: fir.alloca !fir.char
+! CHECK: return
+
+! Masked assignment recursively inlines elemental bodies through a different
+! path. Both the intermediate and final scalar results need cleanup.
+subroutine masked_concat(a, b, c, mask)
+  character(*) :: a(:), b(:), c(:)
+  logical :: mask(:)
+  where (mask) c = a // b // '!'
+end subroutine
+! CHECK-LABEL: func.func @_QPmasked_concat
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK: return
+
+! Inlining appends the producer cleanup to the consumer cleanup. Both
+! temporaries are destroyed exactly once after the final value is consumed.
+! INLINE-LABEL: func.func @_QPconcat_array
+! INLINE: %[[INNER:.*]] = hlfir.concat
+! INLINE: %[[OUTER:.*]] = hlfir.concat %[[INNER]]
+! INLINE: hlfir.yield_element %[[OUTER]] : {{.*}} cleanup {
+! INLINE-NEXT: hlfir.destroy %[[OUTER]]
+! INLINE-NEXT: hlfir.destroy %[[INNER]]
+! INLINE-NEXT: }
+
+! The logical consumer does not transfer the character result to its yield.
+! INLINE-LABEL: func.func @_QPcompare_array
+! INLINE: %[[TEMP:.*]] = hlfir.concat
+! INLINE: hlfir.cmpchar
+! INLINE: hlfir.yield_element {{.*}} cleanup {
+! INLINE-NEXT: hlfir.destroy %[[TEMP]]
+! INLINE-NEXT: }
+
+! Exercise recursive inlining directly, without the inline-elementals pass.
+! WHERE-LABEL: func.func @_QPmasked_concat
+! WHERE: %[[INNER:.*]] = hlfir.concat
+! WHERE: %[[OUTER:.*]] = hlfir.concat %[[INNER]]
+! WHERE: hlfir.assign %[[OUTER]]
+! WHERE-NEXT: hlfir.destroy %[[OUTER]]
+! WHERE-NEXT: hlfir.destroy %[[INNER]]
+! WHERE-NOT: hlfir.destroy
+! WHERE: return
+
+subroutine parenthesized_compare(a, b, c, result)
+  character(*) :: a(:), b(:), c(:)
+  logical :: result(:)
+  result = (a // b) == c
+end subroutine
+! INLINE-LABEL: func.func @_QPparenthesized_compare
+! INLINE: %[[TEMP:.*]] = hlfir.concat
+! INLINE: %[[ALIAS:.*]] = hlfir.no_reassoc %[[TEMP]]
+! INLINE-NOT: hlfir.destroy
+! INLINE: hlfir.cmpchar
+! INLINE: hlfir.yield_element {{.*}} cleanup {
+! INLINE-NEXT: hlfir.destroy %[[TEMP]]
+! INLINE-NEXT: }
+! CHECK-LABEL: func.func @_QPparenthesized_compare
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK: fir.do_loop
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK-NOT: fir.alloca !fir.char
+! CHECK: return
+
+subroutine masked_parentheses(a, b, c, mask)
+  character(*) :: a(:), b(:), c(:)
+  logical :: mask(:)
+  where (mask) c = (a // b)
+end subroutine
+! WHERE-LABEL: func.func @_QPmasked_parentheses
+! WHERE: %[[TEMP:.*]] = hlfir.concat
+! WHERE: %[[ALIAS:.*]] = hlfir.no_reassoc %[[TEMP]]
+! WHERE: hlfir.assign %[[ALIAS]]
+! WHERE-NEXT: hlfir.destroy %[[TEMP]]
+! WHERE-NOT: hlfir.destroy
+! WHERE: return
+! CHECK-LABEL: func.func @_QPmasked_parentheses
+! CHECK: fir.alloca !fir.char<1,?>
+! CHECK-NOT: fir.allocmem !fir.char
+! CHECK-NOT: fir.alloca !fir.char
+! CHECK: return
+
+! Optimized bufferization must retain intermediate character cleanup after
+! assigning the logical element directly into the output array.
+! OPT-LABEL: func.func @_QPcompare_array
+! OPT-NOT: hlfir.elemental
+! OPT: fir.do_loop
+! OPT: %[[TEMP:.*]] = hlfir.concat
+! OPT: hlfir.cmpchar
+! OPT: hlfir.assign
+! OPT-NEXT: hlfir.destroy %[[TEMP]]
+! OPT-NOT: hlfir.elemental
+! OPT: return
diff --git a/flang/test/Transforms/character-temporary-placement.fir b/flang/test/Transforms/character-temporary-placement.fir
new file mode 100644
index 00000000000000..fa87f7e418866f
--- /dev/null
+++ b/flang/test/Transforms/character-temporary-placement.fir
@@ -0,0 +1,86 @@
+// RUN: fir-opt %s --allocation-placement | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --stack-arrays | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --allocation-placement="legacy=true" | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --allocation-placement="legacy=true stack-arrays=true" | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --allocation-placement="legacy=true stack-arrays=true dynamic-array-on-heap=true" | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --allocation-placement="legacy=true dynamic-array-on-heap=true" | FileCheck %s --check-prefix=HEAP --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore --implicit-check-not=fir.alloca
+
+module {
+  func.func private @extent() -> index
+  func.func private @use(!fir.heap<!fir.char<1,?>>)
+  func.func private @use_array(!fir.heap<!fir.array<?xi32>>)
+
+  // Character temporaries prefer the stack even without -fstack-arrays. When
+  // emulating the legacy passes, -fdynamic-heap-array keeps them on the heap.
+  // HEAP-LABEL: func.func @character_in_cfg_loop
+  // HEAP: fir.allocmem !fir.char<1,?>
+  // HEAP: fir.freemem
+  // CHECK-LABEL: func.func @character_in_cfg_loop
+  // CHECK: %[[SP:.*]] = llvm.intr.stacksave
+  // CHECK: %[[TEMP:.*]] = fir.alloca !fir.char<1,?>
+  // CHECK: fir.call @use
+  // CHECK: llvm.intr.stackrestore %[[SP]]
+  // CHECK-NOT: fir.freemem
+  // CHECK: cf.cond_br
+  func.func @character_in_cfg_loop(%again: i1) {
+    cf.br ^loop
+  ^loop:
+    %n = fir.call @extent() : () -> index
+    %s = fir.allocmem !fir.char<1,?>(%n : index)
+    fir.call @use(%s) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %s : !fir.heap<!fir.char<1,?>>
+    cf.cond_br %again, ^loop, ^exit
+  ^exit:
+    return
+  }
+
+  // Crossing lifetimes share one block scope, so both can use stack storage.
+  // CHECK-LABEL: func.func @crossing_lifetimes
+  // CHECK: %[[SP:.*]] = llvm.intr.stacksave
+  // CHECK-NOT: llvm.intr.stacksave
+  // CHECK-COUNT-2: fir.alloca !fir.char<1,?>
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK-COUNT-2: fir.call @use
+  // CHECK: llvm.intr.stackrestore %[[SP]]
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK: cf.cond_br
+  func.func @crossing_lifetimes(%again: i1) {
+    cf.br ^loop
+  ^loop:
+    %n = fir.call @extent() : () -> index
+    %a = fir.allocmem !fir.char<1,?>(%n : index)
+    %b = fir.allocmem !fir.char<1,?>(%n : index)
+    fir.call @use(%a) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %a : !fir.heap<!fir.char<1,?>>
+    fir.call @use(%b) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %b : !fir.heap<!fir.char<1,?>>
+    cf.cond_br %again, ^loop, ^exit
+  ^exit:
+    return
+  }
+
+  // Nested lifetimes use the same single block scope.
+  // CHECK-LABEL: func.func @nested_lifetimes
+  // CHECK: %[[SP:.*]] = llvm.intr.stacksave
+  // CHECK-NOT: llvm.intr.stacksave
+  // CHECK-COUNT-2: fir.alloca !fir.char<1,?>
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK-COUNT-2: fir.call @use
+  // CHECK: llvm.intr.stackrestore %[[SP]]
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK: cf.cond_br
+  func.func @nested_lifetimes(%again: i1) {
+    cf.br ^loop
+  ^loop:
+    %n = fir.call @extent() : () -> index
+    %a = fir.allocmem !fir.char<1,?>(%n : index)
+    %b = fir.allocmem !fir.char<1,?>(%n : index)
+    fir.call @use(%b) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %b : !fir.heap<!fir.char<1,?>>
+    fir.call @use(%a) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %a : !fir.heap<!fir.char<1,?>>
+    cf.cond_br %again, ^loop, ^exit
+  ^exit:
+    return
+  }
+}
diff --git a/flang/test/Transforms/stack-arrays-block-lifetime.fir b/flang/test/Transforms/stack-arrays-block-lifetime.fir
new file mode 100644
index 00000000000000..3691a0637768b7
--- /dev/null
+++ b/flang/test/Transforms/stack-arrays-block-lifetime.fir
@@ -0,0 +1,105 @@
+// RUN: fir-opt %s --stack-arrays | FileCheck %s --check-prefixes=CHECK,SA
+// RUN: fir-opt %s --allocation-placement | FileCheck %s --check-prefixes=CHECK,AP
+// RUN: fir-opt %s --allocation-placement="legacy=true" | FileCheck %s --check-prefixes=CHECK,AP
+
+func.func private @extent() -> index
+func.func private @use(!fir.heap<!fir.char<1,?>>)
+func.func private @use_ref(!fir.ref<!fir.char<1,?>>)
+
+// An existing alloca before the temporary must not be reclaimed at block exit.
+// CHECK-LABEL: func.func @existing_alloca
+// CHECK-NOT: llvm.intr.stacksave
+// CHECK: fir.alloca
+// CHECK: fir.allocmem
+// CHECK: fir.freemem
+// CHECK-NOT: llvm.intr.stackrestore
+// CHECK: return
+func.func @existing_alloca(%again: i1) {
+  cf.br ^loop
+^loop:
+  %n = fir.call @extent() : () -> index
+  %a = fir.alloca !fir.char<1,?>(%n : index)
+  %s = fir.allocmem !fir.char<1,?>(%n : index)
+  fir.call @use(%s) : (!fir.heap<!fir.char<1,?>>) -> ()
+  fir.freemem %s : !fir.heap<!fir.char<1,?>>
+  cf.cond_br %again, ^loop, ^exit
+^exit:
+  fir.call @use_ref(%a) : (!fir.ref<!fir.char<1,?>>) -> ()
+  return
+}
+
+// An allocation whose free is in another block cannot join this block scope.
+// CHECK-LABEL: func.func @free_in_successor
+// CHECK-NOT: llvm.intr.stacksave
+// CHECK: fir.allocmem
+// CHECK: fir.freemem
+// CHECK-NOT: llvm.intr.stackrestore
+// CHECK: return
+func.func @free_in_successor(%again: i1) {
+  cf.br ^loop
+^loop:
+  %n = fir.call @extent() : () -> index
+  %s = fir.allocmem !fir.char<1,?>(%n : index)
+  fir.call @use(%s) : (!fir.heap<!fir.char<1,?>>) -> ()
+  cf.br ^cleanup
+^cleanup:
+  fir.freemem %s : !fir.heap<!fir.char<1,?>>
+  cf.cond_br %again, ^loop, ^exit
+^exit:
+  return
+}
+
+// Allocation placement keeps the character stack preference in device regions,
+// and the allocation stays in the region. The stack-arrays pass leaves the
+// allocations of offload regions alone.
+// CHECK-LABEL: func.func @offload
+// CHECK: acc.parallel
+// SA-NOT: fir.alloca
+// SA: fir.allocmem !fir.char
+// SA: fir.freemem
+// AP-NOT: fir.allocmem
+// AP: fir.alloca !fir.char
+// AP-NOT: fir.freemem
+// CHECK: acc.yield
+func.func @offload(%n: index) {
+  acc.parallel {
+    %s = fir.allocmem !fir.char<1,?>(%n : index)
+    fir.call @use(%s) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %s : !fir.heap<!fir.char<1,?>>
+    acc.yield
+  }
+  return
+}
+
+// Each block can reclaim its own promoted allocations. A nested allocmem
+// does not prevent promotion of the outer block's temporary.
+// CHECK-LABEL: func.func @nested_allocations
+// CHECK: %[[OUTER:.*]] = llvm.intr.stacksave
+// CHECK: fir.alloca !fir.char
+// CHECK: fir.if
+// CHECK: %[[INNER:.*]] = llvm.intr.stacksave
+// CHECK: fir.alloca !fir.char
+// CHECK: fir.call @use
+// CHECK: llvm.intr.stackrestore %[[INNER]]
+// CHECK: }
+// CHECK: fir.call @use
+// CHECK: llvm.intr.stackrestore %[[OUTER]]
+// CHECK: cf.cond_br
+// CHECK: return
+func.func @nested_allocations(%again: i1, %condition: i1) {
+  cf.br ^loop
+^loop:
+  %n = fir.call @extent() : () -> index
+  %outer = fir.allocmem !fir.char<1,?>(%n : index)
+  fir.if %condition {
+    %m = fir.call @extent() : () -> index
+    %inner = fir.allocmem !fir.char<1,?>(%m : index)
+    fir.call @use(%inner) : (!fir.heap<!fir.char<1,?>>) -> ()
+    fir.freemem %inner : !fir.heap<!fir.char<1,?>>
+  }
+  fir.call @use(%outer) : (!fir.heap<!fir.char<1,?>>) -> ()
+  fir.freemem %outer : !fir.heap<!fir.char<1,?>>
+  cf.cond_br %again, ^loop, ^exit
+^exit:
+  return
+}
diff --git a/flang/test/Transforms/stack-arrays-crossing-lifetimes.fir b/flang/test/Transforms/stack-arrays-crossing-lifetimes.fir
new file mode 100644
index 00000000000000..f3c9e3fd4ed31c
--- /dev/null
+++ b/flang/test/Transforms/stack-arrays-crossing-lifetimes.fir
@@ -0,0 +1,33 @@
+// RUN: fir-opt %s --stack-arrays | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+// RUN: fir-opt %s --allocation-placement="stack-arrays=true" | FileCheck %s --implicit-check-not=llvm.intr.stacksave --implicit-check-not=llvm.intr.stackrestore
+
+module {
+  func.func private @extent() -> index
+  func.func private @use(!fir.heap<!fir.array<?xi32>>)
+
+  // Both allocations are reclaimed at block exit. Their crossing individual
+  // lifetimes do not require separate stack scopes or heap fallback.
+  // CHECK-LABEL: func.func @crossing
+  // CHECK: %[[SP:.*]] = llvm.intr.stacksave
+  // CHECK-NOT: llvm.intr.stacksave
+  // CHECK-COUNT-2: fir.alloca !fir.array<?xi32>
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK-COUNT-2: fir.call @use
+  // CHECK: llvm.intr.stackrestore %[[SP]]
+  // CHECK-NOT: llvm.intr.stackrestore
+  // CHECK: cf.cond_br
+  func.func @crossing(%again: i1) {
+    cf.br ^loop
+  ^loop:
+    %n = fir.call @extent() : () -> index
+    %a = fir.allocmem !fir.array<?xi32>, %n
+    %b = fir.allocmem !fir.array<?xi32>, %n
+    fir.call @use(%a) : (!fir.heap<!fir.array<?xi32>>) -> ()
+    fir.freemem %a : !fir.heap<!fir.array<?xi32>>
+    fir.call @use(%b) : (!fir.heap<!fir.array<?xi32>>) -> ()
+    fir.freemem %b : !fir.heap<!fir.array<?xi32>>
+    cf.cond_br %again, ^loop, ^exit
+  ^exit:
+    return
+  }
+}
diff --git a/flang/test/Transforms/stack-arrays.fir b/flang/test/Transforms/stack-arrays.fir
index f236b016c6864d..975f350ce13aae 100644
--- a/flang/test/Transforms/stack-arrays.fir
+++ b/flang/test/Transforms/stack-arrays.fir
@@ -209,8 +209,8 @@ func.func @placement3() {
 // CHECK-NEXT:   %[[C2:.*]] = arith.constant 2 : index
 // CHECK-NEXT:   %[[C10:.*]] = arith.constant 10 : index
 // CHECK-NEXT:   fir.do_loop
-// CHECK-NEXT:     %[[SUM:.*]] = arith.addi %[[C1]], %[[C2]] : index
 // CHECK-NEXT:     %[[SP:.*]] = llvm.intr.stacksave : !llvm.ptr
+// CHECK-NEXT:     %[[SUM:.*]] = arith.addi %[[C1]], %[[C2]] : index
 // CHECK-NEXT:     %[[MEM:.*]] = fir.alloca !fir.array<?xi32>, %[[SUM]]
 // CHECK:     llvm.intr.stackrestore %[[SP]] : !llvm.ptr
 // CHECK-NEXT:     fir.result
@@ -246,8 +246,8 @@ func.func @placement4(%arg0 : i1) {
 // CHECK-NEXT:   %[[C10:.*]] = arith.constant 10 : index
 // CHECK-NEXT:   cf.br ^bb1
 // CHECK-NEXT: ^bb1:
-// CHECK-NEXT:   %[[C3:.*]] = arith.constant 3 : index
 // CHECK-NEXT:   %[[SP:.*]] = llvm.intr.stacksave : !llvm.ptr
+// CHECK-NEXT:   %[[C3:.*]] = arith.constant 3 : index
 // CHECK-NEXT:   %[[MEM:.*]] = fir.alloca !fir.array<?xi32>, %[[C3]]
 // CHECK:   llvm.intr.stackrestore %[[SP]] : !llvm.ptr
 // CHECK-NEXT:   cf.cond_br %arg0, ^bb1, ^bb2
@@ -446,8 +446,8 @@ func.func @placement_loop_declare() {
 // CHECK-NEXT:   %[[C2:.*]] = arith.constant 2 : index
 // CHECK-NEXT:   %[[C10:.*]] = arith.constant 10 : index
 // CHECK-NEXT:   fir.do_loop
-// CHECK-NEXT:     %[[SUM:.*]] = arith.addi %[[C1]], %[[C2]] : index
 // CHECK-NEXT:     %[[SP:.*]] = llvm.intr.stacksave : !llvm.ptr
+// CHECK-NEXT:     %[[SUM:.*]] = arith.addi %[[C1]], %[[C2]] : index
 // CHECK-NEXT:     %[[MEM:.*]] = fir.alloca !fir.array<?xi32>, %[[SUM]]
 // CHECK:          llvm.intr.stackrestore %[[SP]] : !llvm.ptr
 // CHECK-NEXT:     fir.result



More information about the llvm-branch-commits mailing list