Repository navigation
Closed
Labels
area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIbug
Description
Sorry that I don't know whether it is the proper place to ask this:
I know that now Thread.VolatileRead is wrapper of Volatile.Read, it is different from .NETFramework, does Thread.VolatileRead (.NETFramework) load variables from memory instead of registers by using [MethodImpl(MethodImplOptions.NoInlining)]:
[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static int VolatileRead(ref int address)
{
int ret = address;
MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
return ret;
}I think memory barrier here is for preventing reordering, and the read of the latest value is guaranteed by 'NoInling' ?
I have tested with code below:
class Program
{
public static int result;
public static int finished;
static void Thread2()
{
result = 143;
finished = 1;
}
static void Main()
{
finished = 0;
// Run Thread2() in a new thread
new Thread(new ThreadStart(Thread2)).Start();
// Wait for Thread2 to signal that it has a result by setting
// finished to 1.
for (; ; )
{
if (TestVolatileRead(ref finished)==1)
{
Console.WriteLine("result = {0}", result);
break;
}
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static int TestVolatileRead(ref int address)
{
int ret = address;
Thread.MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
return ret;
}
}And if I remove 'NoInlining' and run in Release mode, the program sometimes will be endless because of read finished from register is always 0.
Could anyone help me figure it out, Thanks.
Metadata
Metadata
Assignees
Labels
area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIbug
Activity
Dotnet-GitSync-Bot commentedon Aug 6, 2020
I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.
[-][Questions] Implementation of Thread.VolatileRead[/-][+][Question] Implementation of Thread.VolatileRead[/+]danmoseley commentedon Aug 6, 2020
@kouvel
8ggmaker commentedon Aug 6, 2020
If we don't set NoInlining to TestVolatieMethod, we need to change the implementation to:
the first memory barrier is to get the latest value, and the second for preventing reodering, is it right?
john-h-k commentedon Aug 7, 2020
Yeah so this is the old .NET Framework impl, and it is kinda... horrible. In .NET Core, the
VolatileReadmethods simply forward forwards toVolatile, which are intrinsics that use thevolatile.prefix in IL, which causes the runtime to do everything correctly (insert barriers where necessary on ARM/MIPS, and prevent caching optimisations).It appears they don't do this in framework, presumably because they didn't do IL rewriting like .NET Core does for
Volatile, Unsafe, Interlocked, etc. Though this is complete guess work because the runtime isn't open source for framework.So instead they just insert a full memory barrier, which does achieve
volatilesemantics (acquire and release semantics for reads and writes to be specific, iirc from ECMA), but is complete overkill, and not great for perf. On x86/64, acquire/release semantics are implicit, and so the barrier is, I believe, entirely unnecessary and just a waste of 100 cycles. TheNoInliningis to prevent the JIT doing constant folding or reading from locals - it doesn't necessarily have to be a register, but the idea is if it was inlined the JIT could cache it in some form, and preventing inlining stops that. (putting avolatile.prefix on the read prevents the JIT using a cached version and is why the .NET Core impl doesn't needNoInlining)I don't think this will actually fix it. Without the
volatileprefix, you need to prevent inlining or the JIT could local cache it, even with a memory barrier, I think8ggmaker commentedon Aug 7, 2020
@john-h-k Thanks for your explanation.
And I have used SharpLab to see the JIT ASM of this code, the core part is the if statement check of
seem it is safe because it does not cache the value, and load each time (L004c).
2. Platform: .NET Framework (X64), Without NoInling:
It caches the value in ecx and cmp the same value, it is not safe.
And if we add another memory barrier before the assignment statement:
It is safe, because it load value each time (L0074).
If we change finished to volatile, and just use finished==1 to do check:
4. Platform: .NET Framework, Volatile field, no memory barrier:
It is safe by loading value each time. But I have a question about instruction reordering:
this method is converted to:
and whether finished is volatile or not, the instructions are same, how it prevents reordering to avoid finished variable be assigned before result.
kouvel commentedon Aug 11, 2020
Looks like this repros in .NET Core too. Regarding:
The memory load appears to have been hoisted outside the loop, shouldn't the memory barrier have prevented that? Moving to CodeGen area for now.
Typically stores are not reordered, but to be perfectly correct
finished = 1probably should be a volatile write instead. Otherwise it is theoretically possible thatfinished == 1would be seen andresult == 0.1 remaining item
kouvel commentedon Aug 12, 2020
Because it's a loop there is a memory barrier before the load too (on subsequent iterations of the loop). So while the memory load for the first loop iteration could be hoisted out of the loop, subsequent iterations should be loading from memory I think.
kouvel commentedon Aug 12, 2020
For a volatile load the memory barrier is after the load to ensure that any subsequent loads are at least as recent as the volatile load.
8ggmaker commentedon Aug 12, 2020
I got you point, because there is a loop, so the next time it should load from memory, but the instructions generated load the value to register out of the loop, and each time it loads from ecx register, it is still the cached value
If the last line is jnz L006f, I think it should be right
AndyAyersMS commentedon Aug 13, 2020
cc @dotnet/jit-contrib
Looking at what the jit does. Here's the Loop body
The jit's will hoist the load out of the loop:
Surprised we'd hoist like this with (or without) the memory barrier. I thought we treated statics as implicitly volatile.
Resulting loop may not terminate
Note using the actual
Thread.VolatileReadworks as expected; codegen for the loop isbriansull commentedon Aug 13, 2020
A memory barrier should block any expression from being hoisted before it.
I will take a look.
briansull commentedon Aug 14, 2020
This issue is now fixed with #40821
And I added a test case derived from the test here
kouvel commentedon Aug 14, 2020
Thanks! Would the fix be ported to .NET Framework too?
briansull commentedon Aug 14, 2020
I would say that this is unlikely to meet the bar to be ported to the desktop .NET Framework.
kouvel commentedon Aug 14, 2020
Oh ok. Using
Thread.VolatileReadorVolatile.Readis working as expected in .NET Framework 4.8 (the former has theNoInliningattribute).briansull commentedon Aug 14, 2020
The fix address a missing check for a Thread.MemoryBarrier()
All of the other memory ordering checking instructions were already covered by the current code.