Skip to content

Consider eliding a fixed statement if the thing being pinned is a local #40553

Open

Description

@tannergooding

C# disallows taking the address of an already fixed expression. This means that logic such as the following will result in CS0213:

int x = 0;
fixed (int* px = &x) { }

This normally means that you can't write code which unnecessarily pins data. However, the JIT will also inline methods and so it is possible to have something like the following:

public static int T1()
{
    int x = 5;
    return M1(ref x);
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int M1(ref int x)
{
    fixed (int* pX = &x)
    {
        return *pX;
    }
}

In this code, M1 is being aggressively inlined and that means it will be pinning the local x, which is "already fixed" and therefore does not need to be pinned. However, the JIT does not currently elide this case and it still emits the logic for performing the pin. In an "ideal" scenario, it would see that the reference being pinned is to a local and allow it to be elided allowing improved code generation.

In particular, I believe this to be a common pattern for P/Invoke like operations. In particular, it isn't uncommon to see code such as:

[DllImport("Kernel32")]
public static extern int QueryPerformanceCounter(out long performanceCount);

public static void SomeMethod()
{
    QueryPerformanceCounter(out long counter);
}

In this scenario, it would be beneficial to elide the pin when the P/Invoke stub (and therefore the pinning logic) is inlined.

category:cq
theme:pinning
skill-level:intermediate
cost:medium

Activity

  1. Dotnet-GitSync-Bot commented on Aug 7, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    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.

  2. added
    untriaged
    on Aug 7, 2020
  3. added
    area-CodeGen-coreclr
    on Aug 7, 2020
  4. AaronRobinsonMSFT commented on Aug 7, 2020

    @AaronRobinsonMSFT
    Member

    @AndyAyersMS and @BruceForstall I think this is a codegen issue, but could also see it being something the interop team needs to do to help.

  5. AndyAyersMS commented on Aug 8, 2020

    @AndyAyersMS
    Member

    No, it is codegen. We should be able to tell if a pinned local resolves to the address of some other local.

  6. removed
    untriaged
    on Aug 8, 2020
  7. added this to the Future milestone on Aug 8, 2020
  8. EgorBo commented on Aug 8, 2020

    @EgorBo
    Member
    int[] array = GC.AllocateArray<int>(100, pinned: true);
    fixed (int* p = array) // redundant pinning
    {
    
    }

    does it make sense to also elide it here?

  9. AaronRobinsonMSFT commented on Aug 8, 2020

    @AaronRobinsonMSFT
    Member

    @EgorBo Is that type of allocation observed by the JIT here? Seem like the GC.AllocateArray<T>() would need to be special cased in the JIT to know the allocation was special.

    does it make sense to also elide it here?

    The offline question I had for @tannergooding about this feature is the savings relative to the added complexity. I can see the simple cases like the QueryPerformanceCounter scenario above being possible and I think I have the conceptual understanding to accept it probably isn't too costly. Extending this to special case the results of specific function calls seems rather dubious in the cost/benefit calculus, but would welcome being be educated that it isn't difficult.

    I think understanding the potential savings would be a benefit to this issue.

  10. tannergooding commented on Aug 8, 2020

    @tannergooding
    MemberAuthor

    @EgorBo, my understanding is that it is more expensive to check if an arbitrary ref is already pinned than it is do just perform the pin, thus we could realistically only do it for cases like ref T where the ref is to a known local. I believe this would have direct benefit to the inlining scenario, especially around P/Invokes (possibly around the existing pattern and definitely around the new recommended pattern using source generators/automated tooling).

    In the case of the GC.AllocateArray, I would imagine it is likely better to just use Unsafe.AsPointer as I wouldn't expect the pattern to be nearly as common nor as easy to detect.
    (We already have some optimizations around ref T where T is a local; eliding a pin is just not one of them).

  11. added
    JitUntriaged
    on Oct 28, 2020
  12. removed
    JitUntriaged
    on Nov 13, 2020
  13. added a commit that references this issue on Jun 11, 2022
  14. added a commit that references this issue on Jun 13, 2022
  15. added a commit that references this issue on Jun 17, 2022
  16. added a commit that references this issue on Jun 23, 2022
  17. AndyAyersMS commented on Sep 19, 2022

    @AndyAyersMS
    Member

    I believe this is fixed, but somebody should verify.

  18. aromaa commented on Jan 20, 2023

    @aromaa
    Contributor

    This is fixed for the examples above but there's still more to do to make this light up for Span<T> or structs with ref fields.

    For example, the following is not optimized:

    long result = 0;
    QueryPerformanceCounter(new Span<long>(ref result));
    
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static unsafe void QueryPerformanceCounter(Span<long> value)
    {
    	fixed (long* pointer = value)
    	{
    		QueryPerformanceCounter(pointer);
    	}
    
    	[DllImport("kernel32.dll", ExactSpelling = true), SuppressGCTransition]
    	static extern int QueryPerformanceCounter(long* lpPerformanceCount);
    }

    Or replace the usage of Span<T> with Pointer:

    public ref struct Pointer
    {
    	private ref long value;
    
    	public Pointer(ref long pointer) => this.value = ref pointer;
    
    	public ref long GetPinnableReference() => ref this.value;
    }

    For Pointer we have simpler IR. The V04 is the pinned local:

    ***** BB01
    STMT00000 ( 0x000[E-] ... 0x002 )
    N003 (  5,  4) [000003] -A--G---R--                         *  ASG       long   $VN.Void
    N002 (  3,  2) [000002] D---G--N---                         +--*  LCL_VAR   long  (AX) V00 loc0          $VN.Void
    N001 (  1,  1) [000001] -----------                         \--*  CNS_INT   long   0 $c0
    
    ***** BB01
    STMT00004 ( INL01 @ 0x000[E-] ... ??? ) <- INLRT @ 0x003[E-]
    N003 (  3,  3) [000016] -A------R--                         *  ASG       byref  $VN.Void
    N002 (  1,  1) [000015] D------N---                         +--*  LCL_VAR   byref  V06 tmp5         d:1 $VN.Void
    N001 (  3,  3) [000014] -----------                         \--*  LCL_VAR_ADDR byref  V00 loc0          $100
    
    ***** BB01
    STMT00006 ( INL02 @ 0x000[E-] ... ??? ) <- INLRT @ 0x00A[--]
    N003 (  5,  4) [000022] -A------R--                         *  ASG       byref  $VN.Void
    N002 (  3,  2) [000021] D------N---                         +--*  LCL_VAR   byref  V04 tmp3          $VN.Void
    N001 (  1,  1) [000040] -----------                         \--*  LCL_VAR   byref  V06 tmp5         u:1 $100
    
    ***** BB01
    STMT00008 ( INL02 @ 0x00B[E-] ... ??? ) <- INLRT @ 0x00A[--]
    N006 ( 16, 10) [000028] -ACXG------                         *  CALL unman int    Program:QueryPerformanceCounter(ulong):int $180
    N005 (  2,  4) [000049] -A--------- arg0 in rcx             \--*  COMMA     long   $140
    N003 (  1,  3) [000046] -A------R--                            +--*  ASG       long   $VN.Void
    N002 (  1,  1) [000045] D------N---                            |  +--*  LCL_VAR   long   V08 tmp7         d:1 $VN.Void
    N001 (  1,  1) [000023] -----------                            |  \--*  LCL_VAR   byref  V06 tmp5         u:1 (last use) $100
    N004 (  1,  1) [000047] -----------                            \--*  LCL_VAR   long   V08 tmp7         u:1 (last use) $140
    

    But for Span<T> we have a bit more complex IR. The V04 is the pinned local:

    ***** BB01
    STMT00000 ( 0x000[E-] ... 0x002 )
    N003 (  5,  4) [000003] -A--G---R--                         *  ASG       long   $VN.Void
    N002 (  3,  2) [000002] D---G--N---                         +--*  LCL_VAR   long  (AX) V00 loc0          $VN.Void
    N001 (  1,  1) [000001] -----------                         \--*  CNS_INT   long   0 $c0
    
    ***** BB01
    STMT00005 ( INL01 @ 0x000[E-] ... ??? ) <- INLRT @ ???
    N003 (  7,  6) [000019] -A------R--                         *  ASG       byref  $VN.Void
    N002 (  3,  2) [000018] D------N---                         +--*  LCL_VAR   byref  V08 tmp7         d:1 $VN.Void
    N001 (  3,  3) [000017] -----------                         \--*  LCL_VAR_ADDR byref  V00 loc0          $100
    
    ***** BB01
    STMT00012 ( 0x00A[--] ... ??? )
    N005 (  7,  5) [000072] -A---------                         *  COMMA     void   $140
    N003 (  7,  5) [000068] -A------R--                         +--*  ASG       byref  $VN.Void
    N002 (  3,  2) [000066] D------N---                         |  +--*  LCL_VAR   byref  V10 tmp9         d:1 $VN.Void
    N001 (  3,  2) [000067] -----------                         |  \--*  LCL_VAR   byref  V08 tmp7         u:1 (last use) $100
    N004 (  0,  0) [000071] -----------                         \--*  NOP       void   $140
    
    ***** BB01
    STMT00017 ( INL03 @ 0x00E[E-] ... ??? ) <- INL02 @ 0x000[E-] <- INLRT @ 0x00A[--]
    N003 (  3,  3) [000061] -A------R--                         *  ASG       byref  $VN.Void
    N002 (  1,  1) [000060] D------N---                         +--*  LCL_VAR   byref  V07 tmp6         d:1 $VN.Void
    N001 (  3,  2) [000059] -----------                         \--*  LCL_VAR   byref  V10 tmp9         u:1 (last use) $100
    
    ***** BB01
    STMT00008 ( INL02 @ 0x000[E-] ... ??? ) <- INLRT @ 0x00A[--]
    N003 (  5,  4) [000029] -A------R--                         *  ASG       byref  $VN.Void
    N002 (  3,  2) [000028] D------N---                         +--*  LCL_VAR   byref  V04 tmp3          $VN.Void
    N001 (  1,  1) [000054] -----------                         \--*  LCL_VAR   byref  V07 tmp6         u:1 $100
    
    ***** BB01
    STMT00010 ( INL02 @ 0x00B[E-] ... ??? ) <- INLRT @ 0x00A[--]
    N006 ( 16, 10) [000035] -ACXG------                         *  CALL unman int    Program:QueryPerformanceCounter(ulong):int $1c0
    N005 (  2,  4) [000077] -A--------- arg0 in rcx             \--*  COMMA     long   $180
    N003 (  1,  3) [000074] -A------R--                            +--*  ASG       long   $VN.Void
    N002 (  1,  1) [000073] D------N---                            |  +--*  LCL_VAR   long   V12 tmp11        d:1 $VN.Void
    N001 (  1,  1) [000030] -----------                            |  \--*  LCL_VAR   byref  V07 tmp6         u:1 (last use) $100
    N004 (  1,  1) [000075] -----------                            \--*  LCL_VAR   long   V12 tmp11        u:1 (last use) $180
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclr

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions