Skip to content

Calls to Interlocked.CompareExchange<T> prevents inlining #8662

Closed
@redknightlois

Description

@redknightlois

This is the smaller code that showcase the issue. This code is working very hard to avoid cache issues but still have to pay for the call because it refuses to inline in CoreCLR 1.1 and CoreCLR 2.0 (1w old build).

I may be missing something, but dont see any reason why it shouldn't inline.

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program<object>();
            p.Test();

            Console.WriteLine("Hello World!");
        }
    }

    public class Program<T> where T : class, new()
    {
        [StructLayout(LayoutKind.Sequential, Size = 128)]
        private struct CacheAwareElement
        {
            private readonly long _pad1;
            private T Value;

            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            public static bool TryClaim(ref CacheAwareElement bucket, out T item)
            {
                // Note that the initial read is optimistically not synchronized. That is intentional. 
                // We will interlock only when we have a candidate. in a worst case we may miss some
                // recently returned objects. Not a big deal.
                T inst = bucket.Value;
                if (inst != null && inst == Interlocked.CompareExchange(ref bucket.Value, null, inst))
                    goto Done;

                item = null;
                return false;

                Done:
                item = inst;
                return true;
            }
        }

        private CacheAwareElement _element;

        [MethodImpl(MethodImplOptions.NoInlining)]
        public T Test()
        {
            T instance;
            CacheAwareElement.TryClaim(ref _element, out instance);
            return instance;
        }
    }
}

cc @AndyAyersMS

category:cq
theme:inlining
skill-level:expert
cost:medium

Metadata

Metadata

Assignees

Labels

area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMIenhancementProduct code improvement that does NOT require public API changes/additionsin-prThere is an active PR which will close this issue when it is mergedoptimizationtenet-performancePerformance related issue

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions