Skip to content

JIT: Add KnownBits analysis and use it to fold relops - #137936

Open
EgorBo wants to merge 4 commits into
dotnet:mainfrom
EgorBo:knownbits-relops
Open

EgorBo wants to merge 4 commits into
dotnet:mainfrom
EgorBo:knownbits-relops

Conversation

@EgorBo

@EgorBo EgorBo commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Contributes to #129276.

Adds a port of LLVM's KnownBits to RyuJIT and uses it in global assertion prop to fold X relop CNS.

What's in

  • knownbits.h: single-word (up to 64 bits) port of LLVM's APInt/KnownBits and their transfer functions. LLVM's names and structure are kept to make comparing with the original easy (Apache-2.0 WITH LLVM-exception, THIRD-PARTY-NOTICES.TXT updated).
  • KnownBitsAnalysis: computes the known bits (and signed/unsigned bounds) of a VN from:
    • AND, OR, XOR, NOT, NEG, ADD, SUB, MUL, DIV, MOD, UDIV, UMOD, LSH, RSH, RSZ, including checked ADD/SUB/MUL (as nsw/nuw)
    • casts (including checked ones), small unsigned types, relops (0 or 1)
    • PHIs, using the assertions on the incoming edges (cached per phase)
    • X relop CNS and X relop Y assertions
  • Global assertion prop folds X relop CNS (EQ/NE/LT/LE/GT/GE, signed and unsigned, int and long).
  • JTRUE now creates X relop CNS assertions for long compares too.

Examples

((x << 3) % 8) == 0                         // true
((x << 1) & 1) != 0                         // false
((x | 8) & 8) != 0                          // true
(x & 0x11) == 0x02                          // false (ranges can't see this)
((a & 0x0F) & (b & 0xF0)) == 0              // true
((x * 6) & 1) != 0                          // false
(x | int.MinValue) < 0                      // true
(bytes[i] & 0x100) != 0                     // false
if (x < 16u) { (x & 0x10) != 0 }            // false
if (l >= 0 && l < 100) { (l & 0x80) != 0 }  // false (long)
int v = c ? 4 : 12; (v & 3) == 0            // true (PHI)

Not in this PR


Diffs - my initial prototype had -1.2MB diffs, but I decided to simplify it & make some changes to keep the TP regression sane. I filed a separate PR to improve TP by 0.5% to mitigate regressions in this PR.

The PR is big, but it isn't too complex. It consists of 3 things:

  1. knownbits.h - an almost fully original copy of the LLVM sources. I only had to adapt APInt because I didn't want to pull in the entire LLVM infrastructure for it.
  2. knownbitsanalysis.cpp - a simplistic analysis of known bits using VN and assertions. Very similar to our GetRangeFromAssertions. A few more things/assertions can be handled here as follow-ups.
  3. Actual use of the known bits to fold conditions in optAssertionPropGlobal_RelOp. For now, only for limited cases in the initial PR, to keep the TP regression sane.

I plan a couple of follow-ups to benefit from known bits in more places, e.g., it's very profitable for removing checked contexts or redundant casts. https://gist.github.com/EgorBo/5d2ddcb93f0dc34cf69ba6ab5e57b7e2

libclrjit.dll size increase +18,944 bytes (but it reduces a lot more from r2r)

@github-actions github-actions Bot added the area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI label Nov 19, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 6 pipeline(s).
9 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

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

@EgorBo

This comment was marked as resolved.

@azure-pipelines

This comment was marked as resolved.

@EgorBo

EgorBo commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

/azp run Fuzzlyn, runtime-coreclr outerloop, runtime-coreclr libraries-jitstress

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The new branch-folding analysis lacks targeted tests exercising global assertion propagation across signed/unsigned comparisons, masked shifts, exception preservation, and PHI facts including loop backedges.

1 open issue
What changed in this PR

Adds LLVM-derived KnownBits analysis to RyuJIT, complementing range analysis with bit-pattern facts to fold integer comparisons during global assertion propagation. This advances #129276 without introducing DemandedBits or the separate long-comparison narrowing work.

Changes:

  • Adds known-bit transfer functions and value-number analysis using bounds, assertions, and PHI inputs.
  • Integrates comparison folding and assertion generation for long comparisons.
  • Registers the new sources and documents LLVM attribution.
File Description
THIRD-PARTY-NOTICES.TXT Adds the LLVM KnownBits license notice.
src/​coreclr/​jit/​knownbitsanalysis.h Declares the analysis interface and query limits.
src/​coreclr/​jit/​knownbitsanalysis.cpp Implements value-number, bounds, assertion, and PHI analysis.
src/​coreclr/​jit/​knownbits.h Adds single-word integer helpers and known-bit transfer functions.
src/​coreclr/​jit/​compiler.h Adds storage for the PHI analysis cache.
src/​coreclr/​jit/​CMakeLists.txt Registers the new source and headers.
src/​coreclr/​jit/​assertionprop.cpp Integrates folding, long-comparison assertions, and cache lifecycle.

Review effort: Balanced

Comment thread src/coreclr/jit/assertionprop.cpp Resolved
@EgorBo

EgorBo commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

/azp run Fuzzlyn, runtime-coreclr outerloop, runtime-coreclr libraries-jitstress

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).

Comment thread THIRD-PARTY-NOTICES.TXT Resolved
@EgorBo

EgorBo commented Nov 20, 2026 •

Copy link
Copy Markdown
Member Author

PTAL @AndyAyersMS cc @jakobbotsch @dotnet/jit-contrib

Diffs - my initial prototype had -1.2MB diffs, but I decided to simplify it & make some changes to keep the TP regression sane. I filed a separate PR to improve TP by 0.5% to mitigate regressions in this PR.

The PR is big, but it isn't too complex. It consists of 3 things:

  1. knownbits.h - an almost fully original copy of the LLVM sources. I only had to adapt APInt because I didn't want to pull in the entire LLVM infrastructure for it.
  2. knownbitsanalysis.cpp - a simplistic analysis of known bits using VN and assertions. Very similar to our GetRangeFromAssertions. A few more things/assertions can be handled here as follow-ups. Not much can be shared between constant ranges & known bits since they're quite different.
  3. Actual use of the known bits to fold conditions in optAssertionPropGlobal_RelOp. For now, only for limited cases in the initial PR, to keep the TP regression sane.

I plan a couple of follow-ups to benefit from known bits in more places, e.g., it's very profitable for removing checked contexts or redundant casts.

@AndyAyersMS AndyAyersMS left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall this looks good to me.

Is there some way to stress test this? Hard to tell how much coverage we're getting since we're intentionally limiting calls to to control TP.

Maybe two dimensions of stress, one that relaxes depth, the other that just calls this more often to try an optimize things?

if ((genActualType(vnStore->TypeOfVN(op1VN)) != TYP_INT) || (genActualType(vnStore->TypeOfVN(op2VN)) != TYP_INT))
const var_types op1Type = genActualType(vnStore->TypeOfVN(op1VN));
const var_types op2Type = genActualType(vnStore->TypeOfVN(op2VN));
if ((op1Type == TYP_LONG) && (op2Type == TYP_LONG) && !isEqualityRelop)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do these new assertions cause other assertions to get kicked out? I thought we had metrics here but I only see them for local AP.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, global AP caps the table at 512 so it can happen. Added GlobalAssertionCount/GlobalAssertionOverflow metrics so we can track it in SPMI.

Comment thread src/coreclr/jit/knownbitsanalysis.cpp Outdated
result.resetAll();
}

cache->Set(vn, result, KnownBitsPhiCache::Overwrite);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't expect to actually overwrite here, do we?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It overwrites the "being computed" marker we set before visiting the PHI args. Added a comment.

Comment thread src/coreclr/jit/knownbitsanalysis.cpp Outdated
KnownBits amount = Compute(funcApp.GetArg(1), 32, assertions);
#ifdef TARGET_64BIT
// The shift amount is masked.
amount = amount & KnownBits::makeConstant(APInt(32, width - 1));

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I understand this, shift amount is masked on 32 bit targets too

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, switched to TARGET_MASKS_SHIFTS, arm32 is the only one that does not mask.

// Arguments:
// vn - the value number
// width - the bit width of the value (32 or 64)
// assertions - the assertions that hold for "vn", can be uninit

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since you apply assertions to "otherVN" below, seems like this is understating what these represent.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair, reworded the comment.

Comment thread src/coreclr/jit/knownbits.h Resolved
Comment thread src/coreclr/jit/knownbitsanalysis.cpp Resolved
Comment thread src/coreclr/jit/knownbits.h Outdated
Comment on lines +592 to +608
// Stand-in for the std::optional<bool> results of llvm::KnownBits's comparisons.
struct KnownBool
{
bool HasValue;
bool Value;

KnownBool()
: HasValue(false)
, Value(false)
{
}
KnownBool(bool Value)
: HasValue(true)
, Value(Value)
{
}
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could probably be unified with RelopEvaluationResult

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, switched to RelopEvaluationResult.

Comment thread src/coreclr/jit/knownbitsanalysis.cpp Outdated
Comment on lines +11 to +18
// The known bits of PHIs, see KnownBitsAnalysis::ComputeForPhi.
struct KnownBitsPhiCache : public JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, KnownBits>
{
KnownBitsPhiCache(CompAllocator alloc)
: JitHashTable(alloc)
{
}
};

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any reason for this instead of a typedef? We use typedefs everywhere else.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, it is a typedef now.

Comment thread src/coreclr/jit/knownbitsanalysis.cpp Outdated
case VNF_RSH:
case VNF_RSZ:
{
KnownBits amount = Compute(funcApp.GetArg(1), 32, assertions);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's guaranteed that the shift amount is TYP_INT (CIL allows native int shift amount). Can that cause a problem here?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. It now computes the amount at its own width and truncates it.

Comment thread src/coreclr/jit/knownbitsanalysis.cpp Outdated
Comment on lines +610 to +612
BitVecOps::Iter iter(m_compiler->apTraits, assertions);
unsigned index = 0;
while (iter.NextElem(&index))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BitVecOps::VisitBits is more efficient than BitVecOps::Iter.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jakobbotsch, do we want to sweep the rest of Iter usages? I can give it a try :)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure, that sounds like a good change.
One thing we may want to experiment with for TP purposes is rewriting BitVecOps::VisitBits into a shape that calls the functor only once, to facilitate inlining even large-looking callbacks.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wanted to have for (const AssertionDsc& dsc : everywhere, but couldn't do that without a 0.2/0.3 TP regression :\

EgorBo and others added 2 commits November 25, 2026 14:45
- Use RelopEvaluationResult instead of KnownBool
- Use a typedef for the PHI cache
- Handle native int shift amounts, use TARGET_MASKS_SHIFTS
- Use BitVecOps::VisitBits in MergeAssertions
- Add STRESS_KNOWNBITS_BUDGET and STRESS_KNOWNBITS_RELOPS stress modes
- Add GlobalAssertionCount/GlobalAssertionOverflow metrics

Co-authored-by: Copilot <[email protected]>
Copilot-Session: acaabbe4-a3ed-45ef-838d-d23718212f6e
@EgorBo

EgorBo commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Added two stress modes: STRESS_KNOWNBITS_BUDGET (larger budget and PHI depth, also looks through 32-bit PHIs) and STRESS_KNOWNBITS_RELOPS (analyzes all EQ/NE relops).

@EgorBo

EgorBo commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

@jakobbotsch @AndyAyersMS I've addressed the feedback, anything else? I want to use known-bits in a few more places to unlock the full diffs 🙂

Comment thread src/coreclr/jit/knownbitsanalysis.h Outdated
Comment on lines +65 to +67
// Not to be inlined (LTCG does that): this is called from a hot path of the assertion
// propagation where it rarely has anything to do, having it inlined there costs TP.
NOINLINE RelopEvaluationResult EvalRelop(GenTreeOp* relop, ASSERT_VALARG_TP assertions);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How big of a TP cost..? I would suggest we leave those decisions up to the native compiler unless it is really egregious. Since the TP runs don't have PGO it is also hard to make an informed decision.

@EgorBo EgorBo Nov 25, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jakobbotsch That is from my early attempts to keep the TP regression sane, it's currently quite small (~+0.25%) so I'm removing it.

Co-authored-by: Copilot <[email protected]>
Copilot-Session: acaabbe4-a3ed-45ef-838d-d23718212f6e

@jakobbotsch jakobbotsch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@AndyAyersMS AndyAyersMS left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM too

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-CodeGen-coreclr CLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants