Repository navigation
Description
Description
optHoistLoopCode can hoist a loop-invariant, possibly-faulting load (for example d.N with d a
parameter) out of a loop even though the loop header first stores to a local that a catch, finally
or filter reads. The hoisted copy then faults in the preheader, before the store, and the handler observes
the local's value from before the loop instead of the value stored on the first iteration.
The hoister decides whether a store is observable with
// optimizer.cpp, HoistVisitor::PostOrderVisit
// Assume all stores except "STORE_LCL_VAR<non-addr-exposed lcl>(...)" are globally visible.
if (tree->OperIsLocalStore())
{
isGloballyVisibleStore = m_compiler->lvaGetDesc(tree->AsLclVarCommon())->IsAddressExposed();
}A local that is live into a handler is observable too, without being address exposed. The JIT's alias analysis
already treats it that way (sideeffects.h, AliasSet::NodeInfo::WritesAnyLocation): "Stores to locals live
into handlers cannot be reordered with exception-throwing nodes so we conservatively consider them globally
visible." Loop hoisting does not apply that rule, so it reorders the store and the fault.
Reproduction Steps
using System;
using System.Runtime.CompilerServices;
public static class EhBaseline
{
public class Data { public int N; }
[MethodImpl(MethodImplOptions.NoInlining)]
public static int Run(Data d, int n)
{
int observed = -1;
int sum = 0;
try
{
int i = 0;
do
{
observed = i + 1; // read by the handler below
sum += d.N; // loop-invariant, possibly faulting: gets hoisted above the store
i++;
} while (i < n);
}
catch (NullReferenceException)
{
return observed;
}
return sum;
}
static int Main()
{
// Let Run reach Tier1 under default tiered compilation.
for (int round = 0; round < 3; round++)
{
for (int k = 0; k < 1000; k++) Run(new Data { N = 3 }, 4);
System.Threading.Thread.Sleep(300);
}
Console.WriteLine("non-null: " + Run(new Data { N = 3 }, 4));
Console.WriteLine("null d, observed = " + Run(null, 4) + " (expected 1)");
return 100;
}
}Build with -c Release and run with default settings. DOTNET_TieredCompilation=0 (or
[MethodImpl(MethodImplOptions.AggressiveOptimization)] on Run) reproduces without the warm-up loop.
Expected behavior
non-null: 12
null d, observed = 1 (expected 1)
With d == null, the first iteration stores observed = 1 and then faults on d.N, so the handler must
return 1.
Actual behavior
non-null: 12
null d, observed = -1 (expected 1)
The handler sees observed == -1, the value from before the loop. DOTNET_JitDump on the method shows the
load being hoisted:
Hoisting a copy of [000015] $182 from BB03 into PreHeader BB02 for loop L00 (head: BB03):
N005 ( 4, 4) [000015] ---XG+----- * IND int <l:$182, c:$183>
The preheader copy of d.N faults before the header's observed = i + 1 executes.
The for loop equivalent did not reproduce for me because, inside the try, the loop is not inverted, so the
body is not the loop header and its loads are not considered for hoisting; the do/while puts the body in the
header.
Regression?
Not a regression as far as I can tell. Reproduces identically on every runtime I could test: 6.0.36, 8.0.28,
9.0.17, 10.0.9 and 11.0.0-rc.1.26425.128. Not tested on .NET Framework.
Known Workarounds
- Make the local's address visible so the store is treated as globally visible, e.g.
System.Threading.Volatile.Write(ref observed, i + 1);(verified: the handler then observes1). [MethodImpl(MethodImplOptions.NoOptimization)]on the method, or a Debug build (verified for the latter).
Configuration
- .NET 6.0.36, 8.0.28, 9.0.17, 10.0.9, 11.0.0-rc.1.26425.128 (release JITs)
- Ubuntu Linux, x64. The bug is in the JIT's loop hoisting (IR level), so I would not expect it to be
x64-specific, but I have only tested x64. - Reproduces with default tiered compilation + Dynamic PGO once the method reaches Tier1, and with
DOTNET_TieredCompilation=0. Does not reproduce at Tier0 or in a Debug build (no hoisting).
Other information
The fix that matches the rest of the JIT is to treat a store to a local that is live into a handler as a
globally visible store in HoistVisitor::PostOrderVisit, mirroring AliasSet::NodeInfo::WritesAnyLocation:
LclVarDsc* const varDsc = m_compiler->lvaGetDesc(store);
isGloballyVisibleStore = varDsc->IsAddressExposed() ||
(varDsc->lvTracked ? varDsc->IsLiveInOutOfHandler() : (m_compiler->compHndBBtabCount > 0));lvLiveInOutOfHandler is computed by fgSsaLiveness (MarkMustInitAndEHVars) during SSA construction,
before loop hoisting runs. This only affects methods with handlers, and only faulting loads that follow such a
store in the header; pure invariant expressions are unaffected.
I ran into this while working on #134361 (hoisting of loads that local assertion prop marked non-faulting),
which includes this fix and a regression test (SumObservedByHandler); happy to split it into its own PR if
that is preferred.
Activity
dotnet-policy-service commentedon Sep 21, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
jakobbotsch commentedon Sep 23, 2026
Yes, please do that, we'll want to take the fix for that separately.
bbartels commentedon Sep 25, 2026
Will do, though as i mentioned in #134361 I am out of my depth, and this will be 95% AI assisted. I do try to do my best to reason about the changes, though my ability is limited in this space. So in case that is discouraged, then i'll leave it up to you :)
AndyAyersMS commentedon Nov 13, 2026
@bbartels are you still interested in fixing this?
bbartels commentedon Nov 13, 2026
@AndyAyersMS I probably wont find the time, and even if I do It'll mostly be AI driven 😅 So probably best to take it in case you were looking to do so :)
AndyAyersMS commentedon Nov 13, 2026
Ok, thanks for letting us know.