Skip to content

CSE Heuristic Tuning with additional registers #117560

Open

Description

@DeepakRajendrakumaran

Description

As part of APX feature enablement(reference), we have added an additional 16 GPRs for TARGET_AMD64(This is turned off by default and will be turned on only if user explicitly turns on APX).

While adding the APX features have shown reduced instruction count and better perf score(currently we are doing our analysis using superpmi since the hardware is not yet available), I did notice some cases showing regression. One area where adding the additional registers have caused issues is the CSE heuristic

Analysis

Background:
With No APX
Total GPR = 16
Total Callee Trashed GPR = 7

With APX
Total GPR = 32
Total Callee Trashed GPR = 7 + 16(The new GPRs all fall under this)

Relevance to CSE Heuristic:
The Moderate CSE Promotion logic uses CNT_CALLEE_TRASH (code). This causes the JIT to now promote more CSE candidates. The issue occurs when the newly promoted CSE candidates require CALLEE SAVED registers(the total CALLEE saved registers have remained the same with/without APX). This leads to issues like spill to stack if we run out of CALLEE SAVED registers

Experiments:
I tweaked the JIT so that the CNT_CALLEE_TRASH value can bet set via env variables just for optCSE . CSE performs better with CNT_CALLEE_TRASH = 7(pre APX) vs CNT_CALLEE_TRASH = 23(with APX).

Looking at the JITDump for the regression cases, we are promoting more CSE candidates where CSE is live across calls resulting in issue highlighted above

Image Image

Possible Solutions

I am trying to tweak the CSE heuristic to take into consideration register preference for tracked variables(CALLEE SAVED vs CALLER SAVED). Something along these lines- link

The issue I’m facing is we do not have the register preference information at time of CSE_Heuristic::Initialize

  1. Is it realistic to try this with the current implementation?
  2. What’s a good place to try to add this(if register preference is CALLEE_SAVED or CALLEE_TRASHED) information(I assume to LclVarDsc)

Activity

  1. added
    untriaged
    on Jul 11, 2025
  2. added
    needs-area-label
    on Jul 11, 2025
  3. DeepakRajendrakumaran commented on Jul 11, 2025

    @DeepakRajendrakumaran
    ContributorAuthor

    From @AndyAyersMS There is a notion in CSE of a “call crossing “ CSE (though it is approximate). We should be able to use that to tune.

    Do you mean candidate->LiveAcrossCall()? If yes, I'm not sure how to use that information to influence the Moderate CSE Promotion threshold. This is because we set those thresholds using all tracked variables(lvaTrackedCount) - here. The way I envision the change would require us to know how many of those tracked variables have a preference for CALLEE_SAVED vs CALLEE_TRASHED

  4. added
    apx
    and removed
    untriaged
    needs-area-label
    on Jul 11, 2025
  5. tannergooding commented on Jul 11, 2025

    @tannergooding
    Member

    I would think we want to track CALLEE_SAVE vs CALLEE_TRASH CSEs independently, rather than together.

    Something that lives in a CALLEE_TRASH register requires no prologue/epilogue code, but does require spilling if it is live across a call. While something that lives in a CALLEE_SAVE register requires prologue/epilogue code, but does not require spilling if it is live across a call.

    With that we should prefer CALLEE_TRASH for anything that is not live across a call. If we run out of that "budget" or something is live across a call, then we can do a secondary check for profitability after factoring in the prologue/epilogue code cost. Something that is live across a call could similarly do an additional profitability check to use a CALLEE_TRASH for the spill/reload cost across that call.

    We can also consider some cases like that something coming from an method local constant (i.e. float/simd constants) doesn't require spill/reload and can just load the value fresh after the call (basically treating it as two separate CSEs). We have some existing logic to consider whether something is likely to be enregistered or has a stack slot already. For some types of locals, we can CSE a load and then avoid the spill and just reload as well (similar to the float/simd constant scenario).

    I think there's a number of potential improvements here and that we just aren't taking advantage of that today. Such considerations were less meaningful when the current CSE heuristics were originally written and xarch had far fewer registers available.

  6. EgorBo commented on Jul 12, 2025

    @EgorBo
    Member

    I would think we want to track CALLEE_SAVE vs CALLEE_TRASH CSEs independently, rather than together.

    Presumably, the only proper solution is to not use these ABI heuristics at all when decide what to perform CSE for, let the LSRA decide when to re-materialize and how and perform CSE pretty much always (except for cold blocks, etc). These all are just heuristics that don't anyhow force the back-end to use only calle-saved registers for these CSE candidates. I presume, this is how e.g. LLVM does that

  7. tannergooding commented on Jul 12, 2025

    @tannergooding
    Member

    These all are just heuristics that don't anyhow force the back-end to use only calle-saved registers for these CSE candidates

    Right. In the "ideal" scenario we could just CSE everything and then LSRA would know when to propagate certain trees "back" to their uses if an optimal slot can't be picked. -- This should even improve throughput due to having less nodes to process in typical scenarios.

    I think this would require some additional table or information to be able to reliably know when something is a CSE local, when no additional defs/writes for that local exist, and what the original tree for that CSE is.

  8. DeepakRajendrakumaran commented on Jul 14, 2025

    @DeepakRajendrakumaran
    ContributorAuthor

    Looks like there are a couple of solutions here with varying amount of changes required. I've been looking into improving this along the lines of Tanner's suggestion - I would think we want to track CALLEE_SAVE vs CALLEE_TRASH CSEs independently, rather than together.

    I'm going to go through the different relevant steps as I understand it in order to make sure I'm not making any incorrect assumptions. Please feel free to correct me if that's the case

    Step 1:

    optValnumCSE_Locate - Walks the tree and identifies possible CSE candidates

    Step 2:

    optValnumCSE_DataFlow + optValnumCSE_InitDataFlow - This is where the dataflow analysis is done for CSE. Importantly for the purposes of this discussion, this is where we identify which of these are available across calls(code). This allows us to check using getCSEAvailCrossCallBit(CSEnum)

    Step 3:
    optValnumCSE_Availability labels the CSEs with Use/Def information

    Step 4:
    CSE_Heuristic::Initialize - analyzes the method’s locals and register pressure, estimates stack frame size, and sets up thresholds for aggressive and moderate CSE promotion. These thresholds guide later decisions about which CSEs are likely to be profitable and register-allocated.

    Moderate CSE Promotion cutoff represented as moderateRefCnt in code is calculated here and later used during PromotionCheck to decide whether a CSE candidate should be promoted using "moderate" cost assumption. moderateRefCnt is calculated iterating through tracked variables

    For the purposes of this discussion, the following code snippet should suffice

    for (unsigned trackedIndex = 0; trackedIndex < m_pCompiler->lvaTrackedCount; trackedIndex++)
     {
    
    ............
    if ((moderateRefCnt == 0) && (enregCount > cntModerateEnreg))
            {
                if (CodeOptKind() == Compiler::SMALL_CODE)
                {
                    moderateRefCnt = varDsc->lvRefCnt();
                }
                else
                {
                    moderateRefCnt = varDsc->lvRefCntWtd();
                }
                moderateRefCnt += (BB_UNITY_WEIGHT / 2);
            }
           moderateRefCnt = max(BB_UNITY_WEIGHT, moderateRefCnt);
    ...............
    }
    

    In the above none of moderateRefCnt, enregCount or cntModerateEnreg differentiate between CALLEE_SAVED and CALLEE_TRASHED

    Step 5 - ConsiderCandidates goes through CSE candidates and decides whether to perform that CSE

    PromotionCheck uses the moderateRefCnt value calculated above

    bool CSE_Heuristic::PromotionCheck(CSE_Candidate* candidate)
    {
    ...................
    weight_t cseRefCnt = (candidate->DefCount() * 2) + candidate->UseCount();
    ................
    else if (cseRefCnt >= moderateRefCnt)
            {
                // Record that we are choosing to use the moderate promotion rules
                //
                candidate->SetModerate();
                if (!candidate->LiveAcrossCall() && canEnregister)
                {
    #ifdef DEBUG
                    if (m_pCompiler->verbose)
                    {
                        printf("Moderate CSE Promotion (CSE never live at call) (%f >= %f)\n", cseRefCnt, moderateRefCnt);
                    }
    #endif
                    cse_def_cost = 2;
                    cse_use_cost = 1;
                }
                else // candidate is live across call or not enregisterable.
                {
    #ifdef DEBUG
                    if (m_pCompiler->verbose)
                    {
                        printf("Moderate CSE Promotion (%s) (%f >= %f)\n",
                               candidate->LiveAcrossCall() ? "CSE is live across a call" : "not enregisterable", cseRefCnt,
                               moderateRefCnt);
                    }
    #endif
                    cse_def_cost = 2;
                    if (canEnregister)
                    {
                        if (enregCount < cntAggressiveEnreg)
                        {
                            cse_use_cost = 1;
                        }
                        else
                        {
                            cse_use_cost = 2;
                        }
                    }
                    else
                    {
                        cse_use_cost = 3;
                    }
                }
            }
    ..............................
    }
    

    The CSE candidate has access to relevant info(CALLEE_SAVED vs CALLEE_TRASHED) using candidate->LiveAcrossCall(). This is obtained during the CSE dataflow analysis(Step 2). So, in theory if we tweak the logic to have separate moderateRefCnt for CALLEE_SAVED vs CALLEE_TRASHED(and maybe ever int vs float vs mask), we can have a better performing heuristic

    @tannergooding

    1. Is this what you had in mind too?
    2. The issue I'm running into is that in order to test this hypothesis is that , in step 4 when JIT calculates , we use tracked vars obtained via the following
      LclVarDsc* varDsc = m_pCompiler->lvaGetDescByTrackedIndex(trackedIndex);

    And I'm not sure how I can obtain register preference(SAVED vs TRASHED) for LclVarDsc at CSE phase

  9. added
    area-CodeGen-coreclr
    on Jul 14, 2025
  10. dotnet-policy-service commented on Jul 14, 2025

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
    See info in area-owners.md if you want to be subscribed.

  11. DeepakRajendrakumaran commented on Jul 17, 2025

    @DeepakRajendrakumaran
    ContributorAuthor

    @AndyAyersMS @jakobbotsch Do you have any inputs on how best to proceed here?

  12. added this to the 11.0.0 milestone on Jul 23, 2025
  13. JulieLeeMSFT commented on Jul 23, 2025

    @JulieLeeMSFT
    Member

    Moved to .NET 11.

  14. modified the milestones: 11.0.0, 12.0.0 on Jul 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

JIT-CSEapxarea-CodeGen-coreclrtenet-performance

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions