Skip to content

JIT: (bug) stack-move peephole coalesces two Volatile.Writes to an address-exposed local #135386

Closed

Description

@EgorBo

The x64 emitter's redundant-stack-move peephole removes a volatile store to a stack local when it's identical to the previous instruction. ECMA-335 I.12.6.7 says an optimizing compiler shall not remove or coalesce volatile operations.

Minimal Repro

using System;
using System.Runtime.CompilerServices;
using System.Threading;

public class Program
{
    [MethodImpl(MethodImplOptions.NoInlining)]
    static void Use(ref int x) { }

    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    static int Test(int v)
    {
        int x = 0;
        Use(ref x);
        Volatile.Write(ref x, v);
        Volatile.Write(ref x, v);
        return Volatile.Read(ref x);
    }

    public static void Main() => Console.WriteLine(Test(5));
}

Expected

Two mov dword ptr [rsp+0x28], ebx stores, one per Volatile.Write.

Actual

       lea      rcx, [rsp+0x28]
       call     [Program:Use(byref)]
       mov      dword ptr [rsp+0x28], ebx      ; only one store
       mov      eax, dword ptr [rsp+0x28]

JitDump: -- suppressing mov because last instruction already moved from src to dst. The program prints the correct value (5).

Regression?

No. Reproduces on .NET 8.0, 9.0, 10.0, 11.0-rc2 and main.

Notes

  • Volatile indirections of a contained GT_LCL_ADDR go through emitIns_S_R/emitIns_R_S, and IsRedundantStackMov (emitxarch.cpp) has no notion of volatility. A volatile load of the same register right after a store to the same slot would be dropped too ("opposite move").
  • Low impact: spec conformance only, no wrong result observed; another thread can only reach such a local through an unsafe pointer.
  • Fix: skip the peephole for GTF_IND_VOLATILE indirections.
  • Related: JIT x64: IsRedundantStackMov ignores EVEX embedded masks, dropping moves after a masked store to a stack local #135004 (IsRedundantStackMov also ignores EVEX embedded masks).

Activity

  1. added this to the 12.0.0 milestone on Oct 8, 2026
  2. added
    area-CodeGen-coreclr
    on Oct 8, 2026
  3. dotnet-policy-service commented on Oct 8, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  4. self-assigned this
    on Oct 13, 2026
  5. added a commit that references this issue on Oct 14, 2026
    d46dd2e
  6. locked and limited conversation to collaborators on Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrbug

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions