Skip to content

Delete VersionsWithType check from embedClassHandle - #116808

Closed
jkotas wants to merge 1 commit into
dotnet:mainfrom
jkotas:embedClassHandle
Closed

jkotas wants to merge 1 commit into
dotnet:mainfrom
jkotas:embedClassHandle

Conversation

@jkotas

@jkotas jkotas commented Jun 19, 2025

Copy link
Copy Markdown
Member

It should not be needed. Also, embedClassHandle alternative in embedGenericHandle does not have this check.

It should not be needed. Also, embedClassHandle alternative in embedGenericHandle does not have this check.
Copilot AI review requested due to automatic review settings June 19, 2025 06:00

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.

Pull Request Overview

This PR removes the unnecessary VersionsWithType check and associated exception from embedClassHandle to align its behavior with embedGenericHandle.

  • Deleted the guard that threw RequiresRuntimeJitException when a type wasn’t in VersionsWithType
  • Streamlined embedClassHandle to always emit a ready-to-run helper for the type handle
Comments suppressed due to low confidence (1)

src/coreclr/tools/aot/ILCompiler.ReadyToRun/JitInterface/CorInfoImpl.ReadyToRun.cs:2739

  • With the removal of the VersionsWithType guard, add tests covering cases where a type previously would have failed this check to ensure that embedClassHandle still behaves correctly without requiring a runtime JIT.
            TypeDesc type = HandleToObject(handle);

@jkotas

jkotas commented Jun 19, 2025

Copy link
Copy Markdown
Member Author

Context: #116651

@jkotas

jkotas commented Jun 19, 2025 •

Copy link
Copy Markdown
Member Author

@jkotas

jkotas commented Jun 19, 2025

Copy link
Copy Markdown
Member Author

/azp run runtime-coreclr crossgen2 outerloop

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@davidwrighton davidwrighton 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.

@jkotas, yes this is needed for PGO scenarios. Notably, there is a problem where we can identify via PGO that a particular path is most desireable, and devirtualize, but if the devirtualization target isn't within the current version bubble, we cannot safely do a devirtualize. If we make this change(which I think makes sense, we need to adjust the devirtualization logic to explicitly check that it is only devirtualizing types which are safe to do so.

We don't have good coverage for this sort of scenario in any of our test suites, so actually writing the test case would be a good to have although decidedly tricky to do.

@AndyAyersMS

Copy link
Copy Markdown
Member

we need to adjust the devirtualization logic to explicitly check that it is only devirtualizing types which are safe to do so.

Is this a similar kind of versions-with check, or something more involved?

@jkotas

jkotas commented Jul 18, 2025 •

Copy link
Copy Markdown
Member Author

I have spent some time trying to construct a repro that fails with this change. I was not able to construct one.

Guarded devirtualization kicks in only after a method gets devirtualized successfully. Devirtualization in crossgen has number of versioning checks that abort devirtualization. In particular,

// Impl type check
if (!_compilationModuleGroup.VersionsWithType(implType.GetTypeDefinition()))
{
devirtualizationDetail = CORINFO_DEVIRTUALIZATION_DETAIL.CORINFO_DEVIRTUALIZATION_FAILED_BUBBLE_IMPL;
return null;
}
is very similar to the embedClassHandle check deleted in this PR. As far as I can tell, this and other checks prevent us from ever reaching embedClassHandle during guarded devirtualization for any cases that may cause problems.

@davidwrighton Am I missing some detail?

@jkotas
jkotas requested a review from davidwrighton July 18, 2025 10:35
@github-actions

github-actions Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow state for the Holistic Review Orchestrator.

{
  "version": 5,
  "last_dispatched_commit": "89916eacf9b7175804275fb0c9d5ddabab291072",
  "last_dispatched_base_ref": "main",
  "last_dispatched_base_sha": "96e283d3938c40dd7eb3e8bb6c25827e66c45a26",
  "last_reviewed_commit": "89916eacf9b7175804275fb0c9d5ddabab291072",
  "last_reviewed_base_ref": "main",
  "last_reviewed_base_sha": "96e283d3938c40dd7eb3e8bb6c25827e66c45a26",
  "last_recorded_worker_run_id": "29672712532",
  "review_attempt_commit": "",
  "review_attempt_base_ref": "",
  "review_attempt_count": 0,
  "max_review_attempts": 5,
  "review_history_format": "holistic-review-disclosure-v1",
  "review_history": [
    {
      "commit": "89916eacf9b7175804275fb0c9d5ddabab291072",
      "review_id": 4729973448
    }
  ]
}

@github-actions github-actions Bot 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.

Holistic Review

Motivation: embedClassHandle in the ReadyToRun compiler previously threw RequiresRuntimeJitException whenever the requested type did not version with the current compilation module group. The PR removes this check on the grounds that it should not be necessary, noting that the embedClassHandle-equivalent path inside embedGenericHandle/ceeInfoEmbedGenericHandle performs no such check. The goal is to allow R2R codegen to embed type handles for types outside the current version bubble (e.g. so PGO-driven devirtualization can target cross-bubble types).

Approach: The change deletes the two-line guard so that embedClassHandle unconditionally creates a ReadyToRunHelperId.TypeHandle import via SymbolNodeFactory.CreateReadyToRunHelper and returns an indirection cell. The R2R helper/import mechanism resolves the type handle at load/run time through a fixup, so an embedded handle for a cross-version-bubble type is representable in the R2R image, which is consistent with the analogous handling in ceeInfoEmbedGenericHandle.

Summary: The mechanical change is small and self-consistent with the generic-handle path. The correctness concern is not in this file: with the guard gone, embedClassHandle will no longer reject types outside the version bubble, so any caller that previously relied on this method to reject unsafe cross-bubble embeddings (most importantly the devirtualization decision logic in getCallInfo) must independently ensure it only devirtualizes to types that are safe under versioning. As the area owner notes on this PR, the companion devirtualization-safety adjustment and test coverage are prerequisites; removing this check in isolation could allow an R2R image to devirtualize to a type/method whose layout or sealed-ness can change during a servicing event. I recommend landing this together with the devirtualization guard change and a regression test that exercises the cross-version-bubble devirtualization path, rather than as a standalone deletion.

Detailed Findings

  • Removing the guard shifts a versioning-safety invariant onto callers (non-blocking, cross-cutting). The deleted VersionsWithType check was the point that prevented embedding a class handle for a type outside the current version bubble. getCallInfo already contains careful version-bubble reasoning for devirtualization (callVirtCrossingVersionBubble, the VersionsWithMethodBody checks around lines 2043-2083), but that logic gates method devirtualization, not embedClassHandle usage directly. Please confirm that every caller of embedClassHandle (and the devirtualization paths that lead to embedding a class handle) enforces version-bubble safety on its own, and land the devirtualization adjustment referenced in the PR discussion alongside this deletion so the compiler cannot bake a servicing-unsafe devirtualization into an R2R image.
  • Missing test coverage. There is currently no test exercising cross-version-bubble type-handle embedding / devirtualization. Given the subtlety, a regression test (even if tricky to author, as noted on the PR) would meaningfully de-risk this change and any future refactors of the R2R devirtualization logic.

Note

This review was generated by this repository's Holistic Review agentic workflow to complement the built-in Copilot review.

Generated by Holistic Review · 62.4 AIC · ⌖ 10.6 AIC · ⊞ 10K

@AndyAyersMS

Copy link
Copy Markdown
Member

@davidwrighton can we reconsider this? It would unblock some stack allocation of arrays in R2R codegen.

@davidwrighton

Copy link
Copy Markdown
Member

@jkotas Looking closely at DevirtualizationManager and the other embedClassHandle callers, removing the VersionsWithType(type) check from embedClassHandle is not fully covered by the existing checks in DevirtualizationManager.ResolveVirtualMethod:

1. Guarded devirtualization with generic interface variance when implType is an open generic in the version bubble instantiated over an external type

In DevirtualizationManager.ResolveVirtualMethod (DevirtualizationManager.cs#L95-L100), the check is:

if (!_compilationModuleGroup.VersionsWithType(implType.GetTypeDefinition()) ||
    !_compilationModuleGroup.VersionsWithTypeReference(implType))

Notice that it checks VersionsWithType(implType.GetTypeDefinition()), not VersionsWithType(implType). Previously, embedClassHandle checked VersionsWithType(type) on the full constructed InstantiatedType (which recursively checks all generic type arguments via ReadyToRunCompilationModuleGroupBase.VersionsWithType).

When a class-based guarded devirtualization is emitted (obj->MethodTable == expectedMT ? DirectCall() : VirtualCall()), the guard only checks that the object's runtime MethodTable equals implType. However, when declMethod is on a variant generic interface, which interface implementation on implType wins dispatch can depend on the base-type / interface hierarchy of implType's generic type arguments, even though implType's own MethodTable is completely unchanged!

Concretely, suppose External.dll (outside the version bubble) defines:

// External.dll v1:
public class Base {}
public class Tag {} // v2 changes this to: public class Tag : Base {}

And the R2R-compiled assembly (inside the version bubble) defines:

public interface IA<out T> {}
public interface I<in T> { int GetId(); }

public class C<T> : I<IA<Base>>, I<IA<T>>
{
    int I<IA<Base>>.GetId() => 1;
    int I<IA<T>>.GetId() => 2;
}

For a call to I<IA<Base>>.GetId() where PGO (or exact type propagation) predicts implType = C<External.Tag>:

  1. VersionsWithType(typeof(C<>)) is true and VersionsWithTypeReference(typeof(C<External.Tag>)) is true.
  2. At R2R compile time (against External.dll v1), C<External.Tag> only converts to I<IA<Base>> via I<IA<Base>>.GetId() => 1, so DevirtualizationManager.ResolveVirtualMethod resolves the call to C<External.Tag>.I<IA<Base>>.GetId().
  3. With VersionsWithType removed from embedClassHandle, embedClassHandle(C<External.Tag>) succeeds and GDV emits:
    if (obj->pMT == typeof(C<External.Tag>)) return 1;
  4. When External.dll v2 updates Tag to derive from Base (public class Tag : Base), IA<Base> is now assignable from IA<Tag> (out), so I<IA<T>> converts to I<IA<Base>> (in). Because I<IA<T>> appears later in C<T>'s interface list, CoreCLR's interface dispatch resolves ((I<IA<Base>>)new C<External.Tag>()).GetId() to 2 (I<IA<T>>.GetId()).
  5. Yet at runtime, obj->pMT == typeof(C<External.Tag>) still evaluates to true, so the R2R GDV fast path takes the devirtualized branch and returns 1 instead of 2.

To make embedClassHandle removal safe for devirtualization, DevirtualizationManager.ResolveVirtualMethod either needs to require _compilationModuleGroup.VersionsWithType(implType) (at least when declMethod.OwningType.IsInterface and variance can participate), or verify that any type arguments participating in variant interface dispatch version with the bubble.

2. PGO-guided positive cast expansion (helperexpansion.cpp)

The other embedClassHandle caller affected by removing VersionsWithType is late cast expansion (fgLateCastExpansionForCall / PickCandidatesForTypeCheck in src/coreclr/jit/helperexpansion.cpp), which embeds the PGO likelyClasses[0] handle and queries compareTypesForCast(likelyCls, castToCls):

  • Negative casts (MustNot) are guarded by IsNegativeCastResultVersionResilient(fromType, toType), which checks VersionsWithType across toType, fromType's base hierarchy, and fromType.RuntimeInterfaces.
  • Positive casts (Must) in CorInfoImpl.compareTypesForCast (CorInfoImpl.cs:3192) do not check VersionsWithType, relying on the assumption that an external type will not remove base types or interfaces in a servicing update. That assumption is fine for normal class/interface inheritance, though it means PGO cast expansion will now start embedding external class handles for positive cast fast-paths (obj->pMT == likelyCls).

Note

This comment was created with assistance from GitHub Copilot.

@davidwrighton

Copy link
Copy Markdown
Member

@AndyAyersMS I think these issues are actually very tractable. AI is now much better at doing the across the board searches to find issues here, and this is the sort of thing my gut feel last year felt were in the codebase.. (Unfortunately, it looks like it also found some real issues which need addressing in current logic as well... see #137054)

@jkotas

jkotas commented Nov 6, 2026

Copy link
Copy Markdown
Member Author

Superseded by #137054

@jkotas jkotas closed this Nov 6, 2026
@jkotas
jkotas deleted the embedClassHandle branch November 7, 2026 07:44
davidwrighton added a commit that referenced this pull request Nov 10, 2026
…Type for R2R interface devirt (#137057)

## Summary

Replaces #116808.

1. **`CorInfoImpl.embedClassHandle` (`CorInfoImpl.ReadyToRun.cs`)**:
- Incorporates the change from #116808 removing the `if
(!_compilation.CompilationModuleGroup.VersionsWithType(type)) throw new
RequiresRuntimeJitException(...)` guard in `embedClassHandle`.
`GetTypeHandleImport(type)` already validates token/signature
representability via `CheckIfReferenceable`
(`VersionsWithTypeReference`).
2. **`DevirtualizationManager.ResolveVirtualMethod`
(`DevirtualizationManager.cs`)**:
- Previously, `ResolveVirtualMethod` only checked
`_compilationModuleGroup.VersionsWithType(implType.GetTypeDefinition())`
and `VersionsWithTypeReference(implType)`.
- When `declMethod` is an interface method and `implType` is an
in-bubble generic class instantiated over an external type argument
(`C<ExternalType>`), `VersionsWithType(implType.GetTypeDefinition())` is
`true` while `VersionsWithType(implType)` is `false`. Previously, when
`embedClassHandle` was called for guarded devirtualization or exact-type
checks on `C<ExternalType>`, `embedClassHandle`'s
`VersionsWithType(type)` check threw `RequiresRuntimeJitException` and
aborted R2R compilation of the method.
- Without that check in `embedClassHandle`, `ResolveVirtualMethod` would
allow interface devirtualization on `C<ExternalType>` even though a
compatible base-type/interface change to `ExternalType` outside the
version bubble can alter variant interface dispatch on `C<ExternalType>`
while the guarded `obj->pMT == typeof(C<ExternalType>)` check still
succeeds at runtime.
- `DevirtualizationManager.ResolveVirtualMethod` now requires
`_compilationModuleGroup.VersionsWithType(implType)` when
`declMethod.OwningType.IsInterface`.

Also see #137056 (resolving #137054) for the related
`getDefaultEqualityComparerClass` / `getDefaultComparerClass` and
per-instantiation intrinsic version-bubble fixes.

## Validation

- Added
`R2RTestSuites.EmbedClassHandleAndInterfaceDevirtRespectVersionBubble`.
- Ran:
- `./dotnet.sh test
src/coreclr/tools/aot/ILCompiler.ReadyToRun.Tests/ILCompiler.ReadyToRun.Tests.csproj
-c Checked /p:CoreCLRConfiguration=Checked
/p:LibrariesConfiguration=Release --no-build` — Passed (304 passed, 15
skipped, 0 failed).

Replaces #116808

> [!NOTE]
> This pull request was generated with the assistance of GitHub Copilot.

---------

Co-authored-by: Copilot <[email protected]>
Copilot-Session: 1fecf3aa-5b6f-4510-851b-cd58c6d40b80
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants