Skip to content

JIT: overview of proposed local var reference count changes #10702

Closed

Description

@AndyAyersMS

This issue proposes a series of changes to reduce the overhead and increase the fidelity of local variable reference counts in the jit. The main idea is to get rid of the current costly and buggy incremental count maintenance in favor of batch updates that are done just before accurate ref counts are needed.

See discussion in #8715 for background.

Expected impact is:

  • 4-5% improvement in tier0 / minopts / debug throughput
  • minimal impact to optimized jit throughput
  • smaller frame sizes in some cases where reference counts are currently inflated
  • removal of workarounds to artificially inflate reference counts to avoid asserts

The more accurate reference counts and weighted counts are likely to cause widespread codegen diffs. Hopefully these will mostly be improvements, but some regressions are certainly possible.

Proposed steps are:

cc @dotnet/jit-contrib

category:implementation
theme:ir
skill-level:expert
cost:large

Activity

  1. self-assigned this
    on Jul 17, 2018
  2. AndyAyersMS commented on Jul 18, 2018

    @AndyAyersMS
    MemberAuthor

    Currently local ref counts become valid after lvaMarkLocalVars and are supposed to stay valid for the remainder of compilation (will update as I discover more)....

    Here are some of the references / updates to ref counts that happen before that point:

    • lvaPromoteStructVar -- ref count bump for promoted reg arg fields for "prolog" init count
    • fgMarkImplicitByRefArgs -- zero ref counts for implicit by-ref parameters
    • fgMarkAddressExposedLocals -- track ref counts for implicit by-ref parameters
    • fgRetypeImplicitByRefArgs -- use ref counts to decide whether to promote implict by-ref parameters
    • fgMakeOutgoingStructArgCopy -- use implicit by-ref parameter ref count to try and detect if the last use of the parameter is a call arg; if so try and avoid a copy
    • fgGrabTempWithImplicitUse -- eg for the inline pinvoke frame var, hidden stub parameter
    • lvaMarkLocalVars does some ref count manipulation before turning on "ref counts valid" mode
  3. mikedn commented on Jul 18, 2018

    @mikedn
    Contributor

    4-5% improvement in tier0 / minopts / debug throughput

    I'm curious how did you come up with that estimate :). Also, do we even need ref counts in minopts?

  4. AndyAyersMS commented on Jul 18, 2018

    @AndyAyersMS
    MemberAuthor

    Perf estimates are from #8715.

    The improvement under MinOpts increases to about 4.7%.

    I have a reasonably up to date version of this so can re-validate ... probably a good idea.

  5. AndyAyersMS commented on Jul 18, 2018

    @AndyAyersMS
    MemberAuthor

    Yeah, performance estimates still seem to hold up, eg PMI of Microsoft.CodeAnalysis.CSharp with minopts goes from 1334ms to 1275ms, around 4.5%, based on the just-updated prototype.

    Actual benefit may be higher because the prototype still leaves a lot of ref counting cruft behind.

  6. AndyAyersMS commented on Jul 18, 2018

    @AndyAyersMS
    MemberAuthor

    Roughly speaking, the "invalid" ref count accesses in the current scheme (ref count reads, incs, decs, or sets before the jit officially starts ref counting) fall into categories:

    • setting up implicit ref counts for locals that will never have explicit IR references (referenced in the prolog, say, or referenced via EH or GC)
    • setting up transient implicit ref counts for locals whose references will appear eventually once constructs are lowered
    • conveying information during morph for the implicit byref promotion / unpromotion
    • conveying information during morph for optimization of last use struct args to avoid copies
    • count manipulations that seem easily avoidable

    The implicit cases can perhaps better be handled by new local var property bits, eg lvHasImplicitReference or lvHasTemporaryImplicitReference. If these bits are set then the lvRefCnt() should always return nonzero counts (likely just adding 1 to the explicit ref count result is sufficient) and likewise for the weighted version. The distinction between always implicit and transiently implicit may not matter as it might be OK to lump them together into one category. But if not, then at some point when the appropriate lowering happens the transient implicit bit can be turned off and ref counts established for the variable.

    The conveying cases can perhaps be tolerated by using a different set of APIs or a special parameter to permit temporary (short-lifetime) use of ref counts for some subset of locals.

    Struct last use copy avoidance is arguably something better handled by the work on first class structs as that should be more general, more capable, and less fragile.

  7. AndyAyersMS commented on Jul 19, 2018

    @AndyAyersMS
    MemberAuthor

    dotnet/coreclr#19012 should clear up the implicit reference cases and the avoidable cases.

    For the other cases, one thought is to essentially make ref counts into something like a phased var, where the count fields are valid only for a certain time and certain purpose. The various APIs would then be extended with an enum describing the accessing phase, and this would be error-checked against the current phase. This could extend later to describe intervals when the counts are valid or potentially stale.

    The error checking is a bit clunky with the current API shape as we either also need to pass in the compiler instance or fetch it from TLS. But perhaps the latter is acceptable....?

  8. briansull commented on Jul 19, 2018

    @briansull
    Contributor

    The error checking is a bit clunky with the current API shape as we either also need to pass in the compiler instance or fetch it from TLS. But perhaps the latter is acceptable....?

    It is fine for use in Debug only code, but we should avoid using it for retail code

  9. AndyAyersMS commented on Jul 19, 2018

    @AndyAyersMS
    MemberAuthor

    It would be something like this:

    inline unsigned short LclVarDsc::lvRefCnt(RefCountState state) const
    {
        
    #if defined(DEBUG)
        assert(state != RCS_INVALID);
        Compiler* compiler = JitTls::GetCompiler();
        assert(compiler->lvaRefCountState == state);
    #endif
        
        if (lvImplicitlyReferenced && (m_lvRefCnt == 0))
        {
            return 1;
        }
        
        return m_lvRefCnt;
    }
    
  10. CarolEidt commented on Jul 19, 2018

    @CarolEidt
    Contributor

    conveying information during morph for optimization of last use struct args to avoid copies

    This rings a bell, but I don't recall exactly what's being done. Can you point me to this?

    Re: the error checking, I think it's fine to fetch the compiler instance from TLS for an assert.

  11. AndyAyersMS commented on Jul 19, 2018

    @AndyAyersMS
    MemberAuthor

    Look at fgMakeOutgoingStructArgCopy

  12. CarolEidt commented on Jul 19, 2018

    @CarolEidt
    Contributor

    Thanks @AndyAyersMS - I now recall that some time ago when I was making the first round of 1st class struct changes, I deleted this line: https://github.com/dotnet/coreclr/blob/master/src/jit/morph.cpp#L5297 but it caused diffs, which I was trying to avoid and I wanted to analyze it further - so I created that "to do" and it's still there :-(

  13. 21 remaining items

  14. AndyAyersMS commented on Aug 16, 2018

    @AndyAyersMS
    MemberAuthor

    Playing around with removing the local table sort. Think removing it may also have minimal codegen impact. Should have data shortly.

    Because of the way lvaSortByRefCount is currently written, we may end up tracking less than lclMAX_TRACKED locals and still leave some trackable locals untracked (because some low-numbered locals are untrackable).

  15. CarolEidt commented on Aug 16, 2018

    @CarolEidt
    Contributor

    If we are eliminating the sort, we may want to still consider https://github.com/dotnet/coreclr/issues/11339. I think it could improve throughput to make the set of lclVars that are live across blocks more dense, and would also enable slightly different heuristics for the two types. Also, many, if not all, of the locals introduced in Rationalizer and Lowering are live only within a block (and usually single-def) - knowing those properties would be beneficial to register allocation.

  16. CarolEidt commented on Aug 16, 2018

    @CarolEidt
    Contributor

    .. and if it is indeed the case that Rationalizer and Lowering only ever introduce lclVars that are live only within a block, then perhaps we could avoid running liveness after those phases, and just set the lvTracked field and the GTF_VAR_DEATH flag appropriately as new lcls are introduced by the backend.

  17. AndyAyersMS commented on Aug 16, 2018

    @AndyAyersMS
    MemberAuthor

    Interesting.

    Since we walk the IR to recompute the ref counts, we should be able to fairly cheaply determine if a trackable local's lifetime is block-local, and split the tracking index assignment into two passes so the globally live locals all have low tracking indexes.

  18. AndyAyersMS commented on Aug 17, 2018

    @AndyAyersMS
    MemberAuthor

    Back to sorting for the moment -- very few methods (~10) in the pmi -f set have more than 512 trackable locals, and the issue I noted above doesn't seem to crop up for any of them, as we evidently do a good enough job sorting that in the first 512 sorted candidates all are trackable.

    So one might expect a small number of diffs.

    However, the numbers say otherwise:

    PMI Diffs for System.Private.CoreLib.dll, framework assemblies for x64 default jit
    Summary:
    (Lower is better)
    Total bytes of diff: 8277 (0.02% of base)
        diff is a regression.
    Top file regressions by size (bytes):
           11170 : Microsoft.Diagnostics.Tracing.TraceEvent.dasm (0.38% of base)
            2488 : Microsoft.CodeAnalysis.VisualBasic.dasm (0.04% of base)
            1470 : Microsoft.CodeAnalysis.CSharp.dasm (0.03% of base)
            1243 : System.Linq.Parallel.dasm (0.11% of base)
             677 : System.Collections.Immutable.dasm (0.08% of base)
    Top file improvements by size (bytes):
           -1957 : System.Private.CoreLib.dasm (-0.05% of base)
           -1766 : System.Private.Xml.dasm (-0.05% of base)
           -1014 : System.Security.Cryptography.Algorithms.dasm (-0.30% of base)
            -936 : System.Security.Cryptography.X509Certificates.dasm (-0.42% of base)
            -813 : System.Net.Http.dasm (-0.15% of base)
    98 total files with size differences (55 improved, 43 regressed), 31 unchanged.
    Top method regressions by size (bytes):
            3699 : Microsoft.Diagnostics.Tracing.TraceEvent.dasm - Microsoft.Diagnostics.Tracing.Parsers.KernelTraceEventParser:EnumerateTemplates(ref,ref):this
            3550 : Microsoft.Diagnostics.Tracing.TraceEvent.dasm - Microsoft.Diagnostics.Tracing.CtfTraceEventSource:InitEventMap():ref
            2680 : Microsoft.Diagnostics.Tracing.TraceEvent.dasm - Microsoft.Diagnostics.Tracing.Parsers.ClrPrivateTraceEventParser:EnumerateTemplates(ref,ref):this
            1356 : Microsoft.Diagnostics.Tracing.TraceEvent.dasm - Microsoft.Diagnostics.Tracing.Parsers.ClrTraceEventParser:EnumerateTemplates(ref,ref):this
            1277 : Microsoft.CodeAnalysis.VisualBasic.dasm - Microsoft.CodeAnalysis.VisualBasic.BoundTreeVisitor`2[Vector`1,Int64][System.Numerics.Vector`1[System.Single],System.Int64]:VisitInternal(ref,struct):long:this
    Top method improvements by size (bytes):
            -502 : System.Private.Xml.dasm - System.Xml.Serialization.XmlSerializationWriterCodeGen:WriteElements(ref,ref,ref,ref,ref,ref,bool,bool):this
            -289 : System.Private.CoreLib.dasm - <ReadAsyncInternal>d__66:MoveNext():this
            -282 : System.Reflection.Metadata.dasm - System.Reflection.Metadata.MetadataReader:InitializeTableReaders(struct,ubyte,ref,ref):this
            -200 : System.Security.Cryptography.Algorithms.dasm - System.Security.Cryptography.KeyFormatHelper:ReadEncryptedPkcs8(ref,struct,struct,ref,byref,byref) (20 methods)
            -200 : System.Security.Cryptography.Algorithms.dasm - System.Security.Cryptography.KeyFormatHelper:ReadEncryptedPkcs8(ref,struct,struct,struct,ref,byref,byref) (10 methods)
    5524 total methods with size differences (2589 improved, 2935 regressed), 219099 unchanged.
    

    For the most not sorting this would be a size wash or win except for the trace event methods -- they have huge numbers of temps. We can "fix" the problem there by less aggressively tracking structs but that's not good in general. (The wins seem to come perhaps from changes in CSE behavior; haven't looked at this to closely yet).

    So we might consider some kind of two-pass tracking selection where the first pass picks out higher priority cases and the second pass then fills in anything else trackable until we run out of space. Or several passes if we want to get globally live things densely clustered in the ID space.

    The second issue is that the jit is evidently sensitive to the ordering relationship induced by the ID -- these have been effectively "permuted" by not sorting the table, and this is likely what causes the larger number of diffs. If we're sorting the IDs reflect an underlying ordering metric based on weighted ref counts (and other things) it seems likely we can track down where the ordering comparison happens with IDs and perhaps replace it with the predicate used to sort -- if it's not needed too often.

  19. AndyAyersMS commented on Aug 17, 2018

    @AndyAyersMS
    MemberAuthor

    Worth pointing out that the methods with big regressions all have large numbers of trackable but untracked locals. Some rough accounting...

    Assembly Method Final number of trackable untracked
    Microsoft.Diagnostics.Tracing.TraceEvent ApplicationServerTraceEventParser:EnumerateTemplates(ref,ref):this 1809
    Microsoft.Diagnostics.Tracing.TraceEvent CtfTraceEventSource:InitEventMap():ref 705
    Microsoft.Diagnostics.Tracing.TraceEvent KernelTraceEventParser:EnumerateTemplates(ref,ref):this 496
    Microsoft.Diagnostics.Tracing.TraceEvent ClrPrivateTraceEventParser:EnumerateTemplates(ref,ref):this 233
    Microsoft.CodeAnalysis.VisualBasic BoundTreeVisitor`2:VisitInternal(ref,struct):long:this 147
    System.Private.Xml XmlReflectionImporter:ImportAccessorMapping(ref,ref,ref,ref,ref,bool,bool,ref):this 135
    Microsoft.Diagnostics.Tracing.TraceEvent ClrTraceEventParser:EnumerateTemplates(ref,ref):this 118
    System.Text.RegularExpressions RegexInterpreter:Go():this 67
    Microsoft.CodeAnalysis.VisualBasic Binder:ReportOverloadResolutionFailureForASingleCandidate(ref,ref,int,byref,struct,struct,bool,bool,bool,bool,ref,ref,bool,ref,ref):this 37
    Microsoft.CodeAnalysis.VisualBasic VisualBasicCommandLineParser:Parse(ref,ref,ref,ref):ref:this 4
  20. mikedn commented on Aug 17, 2018

    @mikedn
    Contributor

    Worth pointing out that the methods with big regressions all have large numbers of trackable but untracked locals. Some rough accounting...

    Considering that such large methods tend to be rare would it make sense to increase the max number of tracked variables?

  21. AndyAyersMS commented on Aug 17, 2018

    @AndyAyersMS
    MemberAuthor

    Maybe? The liveness time and space cost is proportional to BV size * number of BBs. So if a method has a lot of locals but few BBs then sure, we could up the limit. If it has a lot of locals and a lot of BBs then perhaps we shouldn't be optimizing it at all.

    Divergence (at least in cases I've explored so far) for fully trackable methods seems to come about in LinearScan::buildIntervals() where we create intervals for reg params in lvVarIndex order.

    We can rewrite this bit to just sort the tracked reg params (usually just a handful) using the old predicate.

  22. mikedn commented on Aug 18, 2018

    @mikedn
    Contributor

    The liveness time and space cost is proportional to BV size * number of BBs. So if a method has a lot of locals but few BBs then sure, we could up the limit. If it has a lot of locals and a lot of BBs then perhaps we shouldn't be optimizing it at all.

    Yep, it needs to be done with care, we probably don't need another JIT64. I was considering making the max number of tracked variables configurable after I got rid of fixed size arrays in 18504, just to see what impact increasing the limit has. But I've yet to get to it...

    Or several passes if we want to get globally live things densely clustered in the ID space.

    Hmm, I suppose that would allow making the global BB BVs smaller than the BVs used for local liveness. But such a change is probably rather tricky and would not help if it turns out that there number of globally live lclvars is high.

  23. AndyAyersMS commented on Jan 16, 2019

    @AndyAyersMS
    MemberAuthor

    lvaMarkLclRefs still does a bunch of unrelated computation but I'm not planning on disentangling it any time soon. Moving to future.

  24. transferred this issue fromdotnet/coreclron Jan 31, 2020
  25. added this to the Future milestone on Jan 31, 2020
  26. AndyAyersMS commented on Feb 19, 2020

    @AndyAyersMS
    MemberAuthor

    This is basically done, so will close.

  27. ghost locked as resolved and limited conversation to collaborators on Dec 16, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

JitThroughputarea-CodeGen-coreclr

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions