Skip to content

ILC: make IsAsyncCall instantiation-invariant - #136002

Merged
MichalStrehovsky merged 2 commits into
dotnet:mainfrom
wpscott:ilc-asynccall-instantiation-invariant
Oct 19, 2026
Merged

MichalStrehovsky merged 2 commits into
dotnet:mainfrom
wpscott:ilc-asynccall-instantiation-invariant

Conversation

@wpscott

@wpscott wpscott commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #135922.

Problem

Awaiting a Task<ValueTask> (or Task<ValueTask<int>>) in a NativeAOT app published with
OptimizationPreference=Size throws NullReferenceException. The same code works with
OptimizationPreference=Speed, with runtime-async disabled, and on CoreCLR.

var tcs = new TaskCompletionSource<ValueTask>();
tcs.SetResult(ValueTask.CompletedTask);
ValueTask inner = await tcs.Task.ConfigureAwait(false);
await inner.ConfigureAwait(false);

cdb on the Size build: all faults are at AsyncHelpers.TransparentAwait<ValueTask>+0xc
(test dword ptr [rbx+34h], 1600000h = Task.m_stateFlags) with rbx = rdx = 0, while the real
Task<ValueTask> object sits in r8.

Root cause

MethodExtensions.IsAsyncCall evaluates the Task/ValueTask check on the instantiated signature:

method.IsAsync && !method.Signature.ReturnsTaskOrValueTask()

For AsyncHelpers.TransparentAwait<T>(Task<T>) the definition returns !!T, so the answer is "yes",
but for T = ValueTask / T = ValueTask<int> the instantiated signature returns a ValueTask, so it
flips to "no". The result is instantiation-dependent, which the runtime never does: AsyncMethodFlags
are computed once from the definition (vm/class.cpp, ClassifyMethodReturnKind +
AsyncMethodFlags::AsyncCall) and read back by MethodDesc::IsAsyncMethod for every instantiation.

Compiler::impWrapTopOfStackInAwait, which inserts the call, relies on that: it asserts
awaitSig.isAsyncCall() and unconditionally adds a WellKnownArg::AsyncContinuation argument. When
the callee is compiled without CORJIT_FLAG_ASYNC, the hidden continuation parameter is missing. For
results that are 16-byte structs the hidden return buffer takes RCX, so the caller layout
[retbuf][asyncCont][task] puts the task in R8 while the callee reads it from RDX:

; caller
movq 0x8(%rsi),%r8     ; Task<ValueTask>
leaq -0x48(%rbp),%rcx  ; retbuf
xorl %edx,%edx         ; async continuation
call TransparentAwait<ValueTask>

; callee (compiled without the async calling convention)
movq %rcx,%rsi         ; retbuf
movq %rdx,%rbx         ; "task" == 0  -> AV at [0+0x34]

With the fix the callee reads %r8, matching the call site. Results of type int/void are
unaffected because there is no return buffer, so the extra argument lands in the unused RCX - which
is why Task<int> never failed.

Fix

Evaluate the return type on the generic method definition so the predicate is instantiation-invariant,
matching the runtime flag semantics:

-            (method.IsAsync && !method.Signature.ReturnsTaskOrValueTask());
+            (method.IsAsync && !method.GetTypicalMethodDefinition().Signature.ReturnsTaskOrValueTask());

This also makes getJitFlags set CORJIT_FLAG_ASYNC and Get_CORINFO_SIG_INFO set
CORINFO_CALLCONV_ASYNCCALL for these instantiations, which is what the JIT already assumes.

Test

src/tests/async/regression/135922.cs awaits Task<ValueTask> and Task<ValueTask<int>> and
round-trips the awaited results.

Note on coverage: the failure itself needs all three of NativeAOT, OptimizationPreference=Size, and the
inserted TransparentAwait call not being inlined - CoreCLR folds the await and the AOT test pipeline
compiles such xunit tests with default (Speed) settings, so this test is a semantic regression test
rather than a direct reproducer of the AOT crash.

Verification

Manually, against a NativeAOT toolchain built from this branch (build.cmd clr.aot+libs -rc Release -lc Release):

configuration before after
NativeAOT Size (--Os), Task<ValueTask> / Task<ValueTask<int>> NullReferenceException pass
NativeAOT Size, Task<int> / Task / Task.Run(() => ValueTask) pass pass
NativeAOT Speed pass pass
CoreCLR pass pass

The before/after runs used an ilc rebuilt from the same tree with and without the one-line change; the
new test builds in the test tree (src\tests\build.cmd x64 Release -Test async\regression\135922.csproj).

Related: #129896 / #130482 made the JIT-inserted call inlineable, which hides this on the JIT side and
under OptimizationPreference=Speed; the arity mismatch remains whenever the call stays out of line.

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 17, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
13 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: @agocke, @dotnet/ilc-contrib
See info in area-owners.md if you want to be subscribed.

@wpscott

wpscott commented Oct 17, 2026

Copy link
Copy Markdown
Contributor Author

@dotnet-policy-service agree

@MichalStrehovsky MichalStrehovsky 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 otherwise, thanks!

MethodExtensions.IsAsyncCall evaluated Signature.ReturnsTaskOrValueTask() on the
instantiated signature, so the answer depended on the instantiation for
AsyncHelpers.TransparentAwait<T>(Task<T>): true for T=int, but false for
T=ValueTask/ValueTask<int>, whose instantiated signature returns a
ValueTask.

The runtime computes the async method flags once, on the generic method
definition (vm/class.cpp ClassifyMethodReturnKind + AsyncMethodFlags::AsyncCall,
read back by MethodDesc::IsAsyncMethod), and instantiations share that flag.
The JIT's Compiler::impWrapTopOfStackInAwait, which inserts the call in the
first place, assumes exactly that: it asserts awaitSig.isAsyncCall() and
unconditionally passes a WellKnownArg::AsyncContinuation argument.

When the callee is compiled without the async calling convention
(CORJIT_FLAG_ASYNC is derived from the same predicate), the hidden
continuation parameter is missing. For results that are 16-byte structs the
hidden return buffer takes RCX, so the caller's [retbuf][asyncCont][task]
layout puts Task<T> in R8 while the callee reads it from RDX. The callee then
dereferences null at Task.m_stateFlags.

This is observable in NativeAOT with OptimizationPreference=Size: awaiting
Task<ValueTask> or Task<ValueTask<int>> throws NullReferenceException at
AsyncHelpers.TransparentAwait<ValueTask>+0xc, while the same code works when
the inserted call is inlined (OptimizationPreference=Speed), when
runtime-async is disabled, and on CoreCLR. Results of type int or void are
unaffected because there is no return buffer, so the extra continuation slot
lands in the unused RCX.

Evaluate the return type check on the generic method definition instead, which
makes the answer instantiation-invariant and matches the runtime's own flag
semantics.

Add src/tests/async/regression/135922, which awaits Task<ValueTask> and
Task<ValueTask<int>> and round-trips the awaited results.

Fixes dotnet#135922
@wpscott
wpscott force-pushed the ilc-asynccall-instantiation-invariant branch from be3e54e to 994a6d6 Compare October 19, 2026 13:42
@wpscott
wpscott marked this pull request as ready for review October 19, 2026 13:59
@wpscott

wpscott commented Oct 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review! I've addressed all three suggestions but force-pushed the updated branch instead of adding a new commit.

My apologies for rewriting the commit history.

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

Thank you!

@MichalStrehovsky

Copy link
Copy Markdown
Member

/ba-g timeout in networking test, tired of filing issues that are only going to be put in Future milestone

@MichalStrehovsky
MichalStrehovsky merged commit c4ed8c8 into dotnet:main Oct 19, 2026
105 of 108 checks passed
@MichalStrehovsky

Copy link
Copy Markdown
Member

/backport to release/11.0

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Oct 20, 2026
agocke pushed a commit that referenced this pull request Oct 21, 2026
#136115)

Backport of #136002 to release/11.0

/cc @MichalStrehovsky @wpscott

## Customer Impact

- [X] Customer reported
- [ ] Found internally

Bad codegen with runtime async leading to crashes. Customer reported in
#135922. Affects both native AOT and ReadyToRun.

## Regression

- [ ] Yes
- [X] No

Runtime-async is a new feature.

## Testing

Test that hits the failure was added. Triggering this requires
interactions of several things that we didn't hit in any of our testing.

## Risk

The risk should be low, the fix is obvious.

**IMPORTANT**: If this backport is for a servicing release, please
verify that:

- For .NET 8 and .NET 9: The PR target branch is `release/X.0-staging`,
not `release/X.0`.
- For .NET 10+: The PR target branch is `release/X.0` (no `-staging`
suffix).

## Package authoring no longer needed in .NET 9

**IMPORTANT**: Starting with .NET 9, you no longer need to edit a NuGet
package's csproj to enable building and bump the version.
Keep in mind that we still need package authoring in .NET 8 and older
versions.

Co-authored-by: wpscott <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 20, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-NativeAOT-coreclr community-contribution Indicates that the PR has been added by a community member runtime-async

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[NativeAOT][RuntimeAsync] NullReferenceException awaiting Task<ValueTask> / Task<ValueTask<T>>

3 participants