Skip to content

Forward substitution for relops can create new data races #62048

Closed

Description

@SingleAccretion

Reproduction:

public class Program
{
    private static int _intStatic;

    private static void Main()
    {
        for (int i = 0; i < Environment.ProcessorCount; i++)
        {
            new Thread(() =>
            {
                while (true)
                {
                    Volatile.Write(ref _intStatic, 0);
                    Volatile.Write(ref _intStatic, 1);
                }
            }).Start();
        }

        while (true)
        {
            Problem(ref _intStatic);
        }
    }
    
    [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.AggressiveOptimization)]
    private static void Problem(ref int a)
    {
        var b = Volatile.Read(ref a) == 0;
        var c = b;
        if (b)
        {
            Assert(c);
        }
    }
    
    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void Assert(bool b)
    {
        if (!b)
        {
            throw new Exception("!!!");
        }
    }
}

Eventually this program will throw an exception, even as one would think it never should.

The cause is that in the branch forward substitution optimization, we copy the indirection and end up with two indirections (that can, naturally, disagree).

It is unclear to me whether this new behavior can be considered correct or not.

@dotnet/jit-contrib

Activity

  1. ghost added
    untriaged
    on Nov 25, 2021
  2. added
    area-CodeGen-coreclr
    on Nov 25, 2021
  3. added this to the milestone on Nov 29, 2021
  4. removed
    untriaged
    on Nov 29, 2021
  5. modified the milestones: , 7.0.0 on Nov 30, 2021
  6. AndyAyersMS commented on Nov 30, 2021

    @AndyAyersMS
    Member

    Thanks for pointing this out. We should be more careful here.

  7. self-assigned this
    on Nov 30, 2021
  8. added a commit that references this issue on Dec 1, 2021
    06d566f
  9. ghost added
    in-pr
    on Dec 1, 2021
  10. added a commit that references this issue on Dec 2, 2021
    2a80066
  11. ghost removed
    in-pr
    on Dec 2, 2021
  12. ghost locked as resolved and limited conversation to collaborators on Jan 1, 2022
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