Skip to content

[browser][CoreCLR] Collect ReadyToRun PGO with indexed schemas - #137502

Open
pavelsavara wants to merge 20 commits into
mainfrom
pavelsavara/browser-coreclr-r2r-pgo-schema-table
Open

pavelsavara wants to merge 20 commits into
mainfrom
pavelsavara/browser-coreclr-r2r-pgo-schema-table

Conversation

@pavelsavara

@pavelsavara pavelsavara commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Summary

Enable opt-in PGO collection from published Browser/CoreCLR ReadyToRun applications and consume the resulting MIBC in a subsequent optimized, partial ReadyToRun publish.

Use ordinary R2R sparse-edge counts, integer value histograms, and cast input-type histograms, plus counter-free interpreter method discovery. Interpreter presence helps select additional bodies for the next compilation; it does not fabricate invocation counts or internal branch weights.

Design

  • Enable the existing JIT sparse-edge instrumentor for supported R2R compilations, including inlinees. Use ordinary EdgeLongCount records and existing profile-incorporation semantics; intrinsic expansion does not create a separate callee-invocation profile.
  • Reuse the JIT's ordinary value probes for Memmove and SequenceEqual lengths. Export sampled integers and their histogram counts alongside edges in the same EventPipe trace and MIBC, without changing the consumer or the MIBC format.
  • Collect actual input types at eligible isinst and castclass sites using the existing JIT class-profile helper and type-histogram format. Crossgen2 treats sampled types it cannot reference as unknown, so a speculative guard does not prevent an otherwise compilable Wasm method from getting R2R code.
  • Add the indexed PgoInstrumentationSchemas R2R section and PgoInstrumentationData fixup. Deterministic, deduplicated schemas preserve kinds, IL keys, counts and aligned offsets. The R2R format is 34.2, with the schema section at 129.
  • Resolve each import cell to stable, eight-byte-aligned runtime storage. Each edge uses one direct 64-bit counter. The JIT shares address construction with dynamic PGO and treats the resolved R2R pointer, not the counters, as invariant. Inlinees inherit the root's counter width. Crossgen2 honors minimal prejit profiling but cannot write synthesized counts to storage that does not exist until load time.
  • Aggregate compatible contributions by logical method and full edge identity, including the destination. Preserve the count/table pair and export only filled histogram samples, including type identities through the existing EventPipe metadata events. Validate image bounds, IL/schema identity and layout. If a method has incompatible counters, log and omit that method's profile without stopping export of other methods or stop-time identity capture.
  • Enable standalone Wasm cross-JIT support independently of the build host OS. Runtime storage and publishing remain limited to single-threaded Browser/CoreCLR.
  • Extend dotnet-pgo create-mibc --include-interpreted-rundown to select metadata-backed interpreter code ranges from method-load/rundown events. Preserve exact/canonical generic identities and existing instrumentation data; exclude dynamic helpers and methods without usable IL bodies.
  • Capture method/type identities once before the runtime provider shuts down. Stop-time rundown alone can contain code ranges without the MethodDetails needed to resolve uninstrumented methods. This capture-state enumeration adds no interpreter probes or per-call counters.

Integration and scope

  • PublishReadyToRunPgoInstrumentation=all or a MethodSet filter selects application/framework R2R instrumentation at publish time, independently of cooperative CPU sampling. --codegenopt:JitProfileValues=0 and --codegenopt:JitProfileCasts=0 disable their respective probes without disabling edges.
  • The SDK uses Crossgen2's dedicated --pgo-instrumentation option. It selects single-threaded Browser/CoreCLR instrumentation and preserves all original IL, including for methods outside the filter, even when --strip-il-bodies is also present. Without the switch, IL stripping is unchanged. Crossgen2 does not inspect raw --codegenopt values to validate instrumentation.
  • Preserve the interpreter's existing optional InterpPGO / InterpPGOMethods facility unchanged from the merged-main baseline. This workflow does not enable it or forward the instrumentation filter to the runtime. Leave DOTNET_InterpPGO off for normal R2R training; interpreter discovery needs no counters.
  • Keep matching producer/consumer MVIDs. Support single-threaded Browser/CoreCLR publishing with diagnostics enabled; reject unsupported configurations explicitly and invalidate incremental R2R outputs when profiling inputs change.
  • Collect with collectPgoTrace(), convert with the interpreter-rundown option, then publish with PublishReadyToRunPgoFiles and producer instrumentation disabled.
  • Prepared interpreter code is evidence of presence, not necessarily execution. Interpreter invocation frequency and branch statistics, receiver and method-target histograms for virtual/interface/delegate calls, and exact exception-flow parity remain out of scope. R2R profiles follow the existing JIT's flow and exception semantics.
  • 32-bit edge production and new Wasm lowering to unroll constant lengths are out of scope. This PR collects and exports value samples; it does not add a new optimization that uses them.

Validation

Local runtime/tool configuration: Browser/Wasm, CoreCLR, Debug unless noted. Browser applications cover Debug and Release.

Validation Result
Runtime/native libraries/host/pretest and CoreCLR TypeScript Rollup builds Passed
dotnet-pgo tests 21/21 passed in the earlier sparse-edge/interpreter validation
Wasm compiler/ABI/profile tests 156/156 passed on the current head, including exact IL preservation for selected and unselected methods, the stripping control, and cast profiles with local and unreferenceable types
SDK pack rebuild and mixed R2R / interpreter Chrome regression Passed, 1/1: skipped the incompatible method, retained unrelated counters and captured method identity
Windows x64 Debug JIT smoke Optimized instrumented Tier1 executed correctly with 32-bit and 64-bit probes in the root and inlinee
Wasm codegen spot check Same edge increments on three methods. DirectCalls reused one import-cell load (154 → 143 code bytes); EntryAndBackedge stayed at 106; SwitchEdges grew from 170 to 179. No timing claim.
R2R profile -> MIBC -> partial publish -> consumer browser execution 3/3 passed with cast collection and the type-reference safeguard, before switching the SDK to the dedicated CLI option
Cast-profile roundtrip with the dedicated switch 1/1 passed: captured the expected types, generated a guarded fast path, and verified hot/cold, null, and failed-match behavior in Chrome
Existing interpreter counters and physically zero-counter/prewarmed discovery 3/3 passed in the earlier sparse-edge/interpreter validation
Unsupported publishing/building configurations 4/4 passed with the renamed SDK property on the current head
Real-trace method-boundary filtering regression Before fix: 1 out-of-window root; after fix: 0
Patch whitespace Passed

The three Chrome roundtrips cover Debug/non-composite/all methods, Release/composite/all methods, and Release/non-composite/filtered methods with CPU sampling. They verify the exact SequenceEqual samples 4, 4, 4, 8, 8, sparse edge counts, preservation of measured profiles when adding interpreter presence roots, matching MVIDs, and execution of the partial consumer. The focused cast roundtrip and four configuration tests ran through the rebuilt SDK pack with the dedicated switch.

Cast codegen evidence (not a timing result): the focused trace exported four CastHot and one CastCold sample. The consumer bypasses the cast helper for the hot type and keeps a fallback; the method grew from 65 to 139 Wasm code bytes. The broad Debug Blazor trace exported 137 cast histograms across 102 methods, including two string-dominated sites consumed in RenderTreeBuilder.AddAttribute. No wall-clock speedup was measured.

The zero-counter case prepares the target before tracing and discovers it without InterpPGO, instrumentation data or invented CPU-sample weights. Separate cases retain the existing Debug/Release interpreter-counter behavior.

Exact local build and test commands

Run from the repository root in PowerShell. The build and test commands below passed; the table distinguishes the earlier validation from the latest runs.

.\build.cmd -bl -os browser -subset clr+libs.native+host+libs.pretest -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false
.\build.cmd -bl -os browser -subset clr.runtime+clr.crossarchtools+host.native+libs.pretest -c Debug /p:RuntimeFlavor=CoreCLR /p:EnableHotReloadInRuntimeConfigDevFile=false

Push-Location src\native
npm run rollup:debug
Pop-Location

$common = @(
    '/p:TargetOS=browser',
    '/p:TargetArchitecture=wasm',
    '/p:Configuration=Debug',
    '/p:RuntimeFlavor=CoreCLR',
    '/p:EnableHotReloadInRuntimeConfigDevFile=false'
)

.\dotnet.cmd build -bl:D:\pgo-production-tools.binlog @common src\coreclr\tools\dotnet-pgo\tests\dotnet-pgo.Tests.csproj '/t:Build;Test'

.\dotnet.cmd build -bl:D:\pgo-production-sdk.binlog @common src\mono\nuget\Microsoft.NET.Sdk.WebAssembly.Pack\Microsoft.NET.Sdk.WebAssembly.Pack.pkgproj /t:Rebuild /p:BuildPackageLibraryReferences=false

.\dotnet.cmd build -bl:D:\r2r-value-browser-final.binlog @common src\mono\wasm\Wasm.Build.Tests '/t:Build;Test' /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XUnitMethodName=Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorEventPipeTestWithSparseEdgePgoReadyToRun

.\dotnet.cmd build -bl:D:\pgo-production-interpreter.binlog @common src\mono\wasm\Wasm.Build.Tests '/t:Build;Test' /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XUnitMethodName=Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorEventPipeTestWithInterpPgo

.\dotnet.cmd build -bl:D:\pgo-production-invalid.binlog @common src\mono\wasm\Wasm.Build.Tests '/t:Build;Test' /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XUnitMethodName=Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorPgoRejectsUnsupportedConfiguration

.\dotnet.cmd build -bl:D:\r2r-pgo-feedback-compiler.binlog @common '/t:Build;Test' '/p:TestRunnerAdditionalArguments=-class ILCompiler.ReadyToRun.Tests.WasmArgumentLayoutTests' src\coreclr\tools\aot\ILCompiler.ReadyToRun.Tests

.\dotnet.cmd build -bl:D:\r2r-pgo-feedback-pack.binlog @common src\mono\nuget\Microsoft.NET.Sdk.WebAssembly.Pack\Microsoft.NET.Sdk.WebAssembly.Pack.pkgproj /t:Rebuild /p:BuildPackageLibraryReferences=false

.\dotnet.cmd build -bl:D:\r2r-pgo-feedback-browser.binlog @common '/t:Build;Test' /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false /p:XUnitMethodName=Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorPgoTraceSkipsIncompatibleMethodProfiles src\mono\wasm\Wasm.Build.Tests

.\build.cmd -bl -os windows -arch x64 -subset clr.runtime -c Debug /p:RuntimeFlavor=CoreCLR
.\build.cmd -bl -os windows -arch x64 -subset clr.corelib+clr.nativecorelib -c Debug /p:RuntimeFlavor=CoreCLR

.\dotnet.cmd build -bl:D:\r2r-pgo-switch-compiler.binlog @common '/t:Build;Test' '/p:TestRunnerAdditionalArguments=-class ILCompiler.ReadyToRun.Tests.WasmArgumentLayoutTests' src\coreclr\tools\aot\ILCompiler.ReadyToRun.Tests

.\dotnet.cmd build -bl:D:\r2r-pgo-switch-pack.binlog @common src\mono\nuget\Microsoft.NET.Sdk.WebAssembly.Pack\Microsoft.NET.Sdk.WebAssembly.Pack.pkgproj /t:Rebuild /p:BuildPackageLibraryReferences=false

.\dotnet.cmd build -bl:D:\r2r-pgo-switch-browser.binlog @common '/t:Build;Test' /p:TestUsingWorkloads=false /p:InstallWorkloadForTesting=false /p:Scenario=WasmTestOnChrome /p:InstallChromeForTests=false '/p:XUnitMethodName=Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorPgoRejectsUnsupportedConfiguration -method Wasm.Build.Tests.Blazor.EventPipeDiagnosticsTests.BlazorReadyToRunCastProfileRoundtrip' src\mono\wasm\Wasm.Build.Tests

git diff --check

No full compiler-suite rerun, Mono/WASI/multithread validation, or application-speedup claim is included. Normal optimization can reclassify incorporated measured profiles as synthesized; the tests retain exact numeric checks rather than requiring a final source label to remain Static.

Tracking: #130521. Its broader interpreter/exception-profile scope is not claimed complete here. The Wasm direct-call readiness fix has an independent repro in #138199.

Note

This PR description was generated with GitHub Copilot assistance.

pavelsavara and others added 2 commits November 13, 2026 11:13
Collect 64-bit IL block profiles through normal JIT instrumentation and
preserve distinct intrinsic and interpreter invocation contributions.
Resolve indexed R2R schemas to stable counter storage and carry the
profiles through EventPipe, MIBC, and partial ReadyToRun consumption.

Add publish configuration, schema and compiler regressions, browser
round trips, and usage documentation.

Co-authored-by: Copilot <[email protected]>
Preserve legacy interpreter profiling outside single-threaded Browser,
use per-method schema allocation chains, and handle sparse flow inference
conservatively when exception exits are not measurable.

Include the pending main merge and all local PGO fixes.

Co-authored-by: Copilot <[email protected]>
@pavelsavara pavelsavara added this to the 12.0.0 milestone Nov 13, 2026
@pavelsavara pavelsavara added arch-wasm WebAssembly architecture area-ReadyToRun labels Nov 13, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to 'arch-wasm': @lewing, @pavelsavara
See info in area-owners.md if you want to be subscribed.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging @dotnet/jit-contrib for JIT-EE GUID update

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/crossgen-contrib
See info in area-owners.md if you want to be subscribed.

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

Require exactly one method with counter data rather than one method in
the entire MIBC. Rundown-only method records are expected in published
application traces and do not indicate instrumentation filter leakage.
Preserve the exact invocation count, schema kind, and IL offset checks.

Co-authored-by: Copilot <[email protected]>
Comment thread src/coreclr/jit/fgprofile.cpp Resolved
Comment thread src/coreclr/jit/fgprofile.cpp Resolved
pavelsavara and others added 4 commits November 23, 2026 12:12
Use shared effective settings for block and edge probes and honor minimal
prejit profiling. Read counter width on Wasm32 and inherit it in inlinees,
preserving the required 64-bit R2R layout.

Keep measured input when the compiler cannot write synthesized counts
through R2R imports. Cover the configuration paths in Wasm compiler tests.

Co-authored-by: Copilot <[email protected]>
Reuse the standard integer histogram probe for Memmove and SequenceEqual
lengths. Export filled samples alongside sparse edge counts so existing
EventPipe-to-MIBC tooling can carry both in the same profile.

Cover the value-probe toggle and verify exact samples in the Blazor
producer/consumer roundtrip.

Co-authored-by: Copilot <[email protected]>
Report an actionable Crossgen2 error instead of silently forcing
64-bit counters when Wasm R2R instrumentation is enabled and the
effective JitCollect64BitCounts override is zero.

Co-authored-by: Copilot <[email protected]>
Report explicit interlocked, scalable, or multi-slot padding requests
instead of silently using direct single-slot counters. Leave the
supported overrides and uninstrumented compilations unchanged.

Co-authored-by: Copilot <[email protected]>
@pavelsavara

Copy link
Copy Markdown
Member Author

@AndyAyersMS, Browser/CoreCLR R2R now collects ordinary sparse-edge counts and Memmove/SequenceEqual length histograms.

We kept one direct 64-bit counter per edge for single-threaded Browser R2R.
Crossgen2 now rejects explicit requests for 32-bit, interlocked, scalable, or padded probes rather than silently ignoring them. Wasm constant-length unrolling is also out of scope for this PR.

pavelsavara and others added 2 commits November 23, 2026 17:13
Initialize the JIT's 64-bit count option on 32-bit non-Wasm targets,
treat whitespace-only Wasm PGO filters as disabled in Crossgen2 and the
SDK, and keep flush-time instrumentation roots from overriding time
windows already applied to observed R2R or JIT method events.

Co-authored-by: Copilot <[email protected]>
Comment thread src/coreclr/jit/importer.cpp Resolved
Comment thread src/coreclr/inc/readytorunhelpers.h Resolved

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

Just a few nits on the JIT side...

Comment thread src/coreclr/jit/fgprofile.cpp Resolved
Comment thread src/coreclr/jit/fgprofile.cpp Resolved
Comment thread src/coreclr/jit/compiler.cpp Resolved
Comment thread src/coreclr/jit/jitconfigvalues.h Resolved
pavelsavara and others added 3 commits November 23, 2026 19:40
Crossgen2 already applies canonical profiles to exact generic inlinees, so
the extra lookup is unnecessary.

Co-authored-by: Copilot <[email protected]>
Log and skip incompatible counters for the affected method only. Capture method identities independently of counter export, and cover mixed ReadyToRun and interpreter profiling in Chrome.

Co-authored-by: Copilot <[email protected]>
Share address generation between JIT and R2R probes, and mark the resolved R2R import-cell pointer invariant. Inherit the root counter width for all inlinees.

Rename the internal R2R instrumentation filter without changing the Browser SDK property. Remove raw counter-option validation while keeping the supported R2R probe mode and retained-IL requirement.

Co-authored-by: Copilot <[email protected]>
Comment thread src/mono/wasm/features.md Resolved
Comment thread src/mono/wasm/features.md Resolved
Collect cast type histograms in Browser CoreCLR ReadyToRun and export them through the existing EventPipe and MIBC path. Treat unreferenceable types as unknown so speculative guards cannot prevent R2R compilation.

Wire PublishReadyToRunPgoInstrumentation to the Crossgen2 --pgo-instrumentation switch. Preserve all original IL in instrumented images without validating raw JIT options.

Co-authored-by: Copilot <[email protected]>
Drive instrumentation through CORJIT_FLAG_BBINSTR without rewriting JIT options. Preserve the composite-only IL stripping diagnostic before retaining IL in instrumented images.

Co-authored-by: Copilot <[email protected]>

const bool profileCast = (JitConfig.JitClassProfiling() > 0) && impIsCastHelperEligibleForClassProbe(call) &&
(call->gtHandleHistogramProfileCandidateInfo != nullptr);
if (IsAot())

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.

Is there some reason we don't enable class profiles for R2R?

I get that we want minimal profiling, and maybe why we want 64 bit counts, but beyond that I don't understand why we are limiting and modifying the data we can collect.

I'd prefer if we mostly collected the same data as we do elsewhere. If we are going to light up bespoke profiling for some apps it may actually provide a nice performance boost by lighting up meaningful GDVs.

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

arch-wasm WebAssembly architecture area-ReadyToRun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants