Skip to content

Commit e8b295c

Browse files
VSadovCopilotCopilotjkotas
authored
Improve GC stack scanning and GcInfoDecoder performance (#135807)
## Summary When the managed heap is small or when most marking is concurrent, stack scanning (`GcScanRoots`) can account for a substantial portion of GC pause duration. Profiling and instrumenting a 500-frame deep stack walk during `GC.Collect(0)` showed that each frameless activation was doing redundant work: - **3–4 `GetGCInfoToken` virtual calls and 3–4 `GcInfoDecoder` constructions per frame** (up to 4 on ReadyToRun frames and 4–5 on shared generic frames). - **1 full `T_CONTEXT` (1,232 bytes on Windows x64; 3,232 bytes on Linux x64) + `T_KNONVOLATILE_CONTEXT_POINTERS` (128 bytes) copy per frame** due to `CheckForSkippedFrames` unconditionally forcing an out-of-place unwind via `EnsureCallerContextIsValid` even when `m_crawl.pFrame` is at the base of the stack (`DebuggerU2MCatchHandlerFrame`) or `FRAME_TOP`. - **Full FP/vector state copies** whenever `EnsureCallerContextIsValid` *is* needed during a GC scan (e.g., on frames with a GS cookie). - **Bit-at-a-time `ReadOneFast()` loops** in `GcInfoDecoder::EnumerateLiveSlots` when scanning partially-interruptible live slot bitmasks and `couldBeLive` bit-vectors. ## Changes ### 1. Eliminate redundant per-frame GCInfo lookups and header decodes - **1a. R2R `JitCodeToMethodInfo` (`codeman.cpp`):** Reuse the already-computed `HotColdMappingLookupTable::LookupMappingForMethod` result (`isColdCode`). When the frame is in hot code, compute `m_relOffset = currentInstr - JitTokenToStartAddress(pCodeInfo->m_methodToken)` directly instead of calling `JitTokenToMethodRegionInfo` (which decoded unwind info size, constructed a `GcInfoDecoder(DECODE_CODE_LENGTH)` to get `hotSize`, and ran a second binary search in `LookupMappingForMethod`). Checked builds assert equality against `JitTokenToMethodRegionInfo`. - **1b. Cache `GCInfoToken` in `EECodeInfo` (`codeman.h`, `codeman.cpp`, `jitinterface.cpp`, `AsmOffsets.cs`):** Lazily cache `m_gcInfoToken` in `EECodeInfo::GetGCInfoToken()` and reset it in `EECodeInfo` initialization and `JitCodeToMethodInfo`. Reduces `IJitManager::GetGCInfoToken` calls from 3–4 per frame to 1 per frame. - **1c. Gate `GetParamContextType` in `GcStackCrawlCallBack` (`gcenv.ee.common.cpp`):** Only query `GetParamContextType` when the `MethodDesc` requires a generic context parameter (`RequiresInstMethodTableArg() || RequiresInstMethodDescArg()`, with Checked-build assertions verifying that `AcquiresInstMethodTableFromThis()` only produces `THIS`/`NONE` and all other methods produce `NONE`). - **1d. Merge generic context decoders (`eetwain.h`, `eetwain.cpp`, `codeman.cpp`, `gcenv.ee.common.cpp`):** Extend `ICodeManager::GetParamContextType` to optionally return the generic context token and prolog check from a single `GcInfoDecoder(gcInfoToken, DECODE_GENERICS_INST_CONTEXT | DECODE_PROLOG_LENGTH)`, replacing separate `GetParamContextType`, `SafeToReportGenericParamContext`, and `GetExactGenericsToken` decoders. ### 2. Avoid unnecessary `T_CONTEXT` copies during stack walks - **2a. Lazy caller context in `CheckForSkippedFrames` (`stackwalk.cpp`, `eetwain.cpp`, `exceptionhandling.cpp`, `threadsuspend.cpp`, `frameinfo.cpp`, `dacdbiimplstackwalk.cpp`):** Avoid forcing `EnsureCallerContextIsValid` in `CheckForSkippedFrames` when `m_crawl.pFrame == FRAME_TOP` or when `m_crawl.pFrame` is above `currentSP` and cannot belong to the current frameless activation. For frames without a GS cookie, `pRD->IsCallerContextValid` stays `FALSE` until `NextRaw()`, allowing `Thread::VirtualUnwindCallFrame` to unwind `pCurrentContext` in place with zero context copies. Checked builds assert after unwinding that `m_crawl.pFrame` was not skipped. - **2b. Cheaper context copy for GC root scans (`threads.h`, `eetwain.h`, `gcenv.ee.cpp`, `stackwalk.cpp`, `eetwain.cpp`, `frames.cpp`):** Add `GC_ROOT_SCAN` / `ICodeManagerFlags::GcRootScan` set by `ScanStackRoots`. When `EnsureCallerContextIsValid` is called on a GC scan (e.g., for GS-cookie frames), `CopyCallerContextForGCScan` copies only flags, GPRs, FP, SP, and IP (144 bytes instead of 1,232 bytes on Windows x64), preserving `ContextPointers` and ARM64 PAC SP fields while skipping the FP/vector state. ### 3. Word-level bit scanning in `GcInfoDecoder` (`gcinfodecoder.h`, `gcinfodecoder.cpp`) - **4a. Word reads + `TrailingZeroCount`:** Add `BitOperations::TrailingZeroCount`, `BitStreamReader::ReadWord`, and `BitStreamReader::SkipZerosAndReadOne`, replacing the bit-at-a-time `ReadOneFast()` loops in `TGcInfoDecoder::EnumerateLiveSlots` (shared across CoreCLR, DAC, and NativeAOT). --- ## Performance Measurements Measured on Windows x64 with a 500-frame deep stack benchmark (`GC.Collect(0)` in a loop of 2,000 iterations $\times$ 9 rounds after warmup, `DOTNET_TieredCompilation=0`) covering: - **`R2R_Small`**: 500 ReadyToRun frames (`crossgen2`-compiled) - **`JIT_Small`**: 500 small JIT frames (slim headers) - **`JIT_GenericShared`**: 500 shared generic frames (`GenericClass<T>`, `GenericStruct<T>`, `GenericStatic.Recurse<T>`) - **`JIT_GSCookie`**: 500 frames with `stackalloc` GS cookies (fat headers) - **`JIT_ManySlots`**: 500 frames with 32 tracked GC slots and sparse non-RLE live bit-vectors - **`Mixed_All`**: 500 frames (100 of each category above) ### Per-Frame Counter Breakdown (Depth = 500) | Scenario | Frames | `GetGCInfoToken` (Before -> After) | `GcInfoDecoder` (Before -> After) | `CallerCtxCopy` (Before -> After) | `ReadOneFast` Live-Slot Bits (Before -> After) | |---|---:|---:|---:|---:|---:| | `R2R_Small` | 511 | 2,040 (**3.99/f**) -> **511 (1.00/f)** | 2,040 (**3.99/f**) -> **1,022 (2.00/f)** | 511 (**1.00/f**) -> **1 (0.00/f)** | 1,398 -> **0** | | `JIT_Small` | 510 | 1,535 (**3.01/f**) -> **510 (1.00/f)** | 1,535 (**3.01/f**) -> **1,020 (2.00/f)** | 510 (**1.00/f**) -> **1 (0.00/f)** | 1,394 -> **0** | | `JIT_GenericShared` | 507 | 1,857 (**3.66/f**) -> **507 (1.00/f)** | 1,857 (**3.66/f**) -> **1,355 (2.67/f)** | 507 (**1.00/f**) -> **1 (0.00/f)** | 2,354 -> **0** | | `JIT_GSCookie` | 510 | 1,535 (**3.01/f**) -> **510 (1.00/f)** | 1,535 (**3.01/f**) -> **1,020 (2.00/f)** | 510 (**1.00/f** full) -> **501 (GPR-only)** | 2,020 -> **0** | | `JIT_ManySlots` | 511 | 1,539 (**3.01/f**) -> **511 (1.00/f)** | 1,539 (**3.01/f**) -> **1,022 (2.00/f)** | 511 (**1.00/f**) -> **1 (0.00/f)** | 15,047 -> **0** | | `Mixed_All` | 521 | 1,738 (**3.34/f**) -> **521 (1.00/f)** | 1,738 (**3.34/f**) -> **1,111 (2.13/f)** | 521 (**1.00/f**) -> **101 (GPR-only)** | 4,499 -> **0** | ### Workstation GC (`DOTNET_gcServer=0`) — Median `GC.GetTotalPauseDuration()` ($\mu\text{s}$/GC) | Scenario | Baseline | + 1a (R2R Offset) | + 1b (Token Cache) | + 1c (Gate Generic) | + 1d (Merge Decoders) | + 2a (Lazy CallerCtx) | + 2b (GPR-only Copy) | + 4a (Word BitScan) | Total Change | |---|---:|---:|---:|---:|---:|---:|---:|---:|---:| | `R2R_Small` | 174.64 | 160.06 | 156.67 | 156.64 | 155.03 | 150.94 | 146.44 | **140.13** | **-34.51 $\mu\text{s}$ (-19.8%)** | | `JIT_Small` | 154.95 | 145.14 | 146.03 | 148.23 | 143.74 | 134.89 | 138.28 | **130.81** | **-24.14 $\mu\text{s}$ (-15.6%)** | | `JIT_GenericShared` | 209.17 | 191.45 | 188.61 | 202.24 | 180.55 | 174.11 | 172.35 | **169.68** | **-39.49 $\mu\text{s}$ (-18.9%)** | | `JIT_GSCookie` | 203.32 | 186.78 | 187.26 | 182.42 | 177.60 | 181.05 | 171.92 | **174.15** | **-29.17 $\mu\text{s}$ (-14.3%)** | | `JIT_ManySlots` | 328.74 | 317.23 | 325.93 | 331.13 | 320.19 | 321.13 | 328.38 | **317.58** | **-11.16 $\mu\text{s}$ (-3.4%)** | | `Mixed_All` | 219.63 | 204.76 | 205.31 | 204.21 | 195.45 | 197.12 | 194.44 | **193.07** | **-26.56 $\mu\text{s}$ (-12.1%)** | ### Server GC (`DOTNET_gcServer=1`) — Median `GC.GetTotalPauseDuration()` ($\mu\text{s}$/GC) | Scenario | Baseline | Final | Total Change | |---|---:|---:|---:| | `R2R_Small` | 249.78 | **219.30** | **-30.48 $\mu\text{s}$ (-12.2%)** | | `JIT_Small` | 228.74 | **211.69** | **-17.05 $\mu\text{s}$ (-7.5%)** | | `JIT_GenericShared` | 286.12 | **247.11** | **-39.01 $\mu\text{s}$ (-13.6%)** | | `JIT_GSCookie` | 278.73 | **252.43** | **-26.30 $\mu\text{s}$ (-9.4%)** | | `JIT_ManySlots` | 410.27 | **398.15** | **-12.12 $\mu\text{s}$ (-3.0%)** | | `Mixed_All` | 298.87 | **274.87** | **-24.00 $\mu\text{s}$ (-8.0%)** | --- ## Validation - `.\build.cmd clr+libs -rc Release -lc Release` (including `mscordaccore` and `Runtime.WorkstationGC` / `Runtime.ServerGC` NativeAOT libraries): **Passed** - `.\build.cmd clr -rc Checked`: **Passed** - Library test suites against Checked CoreCLR: - `dotnet build /t:Test src\libraries\System.Runtime.Loader\tests\System.Runtime.Loader.Tests.csproj -p:Configuration=Release`: **Passed** - `dotnet build /t:Test src\libraries\System.Collections\tests\System.Collections.Tests.csproj -p:Configuration=Release`: **Passed** - `dotnet build /t:Test src\libraries\System.Runtime.InteropServices\tests\System.Runtime.InteropServices.UnitTests\System.Runtime.InteropServices.Tests.csproj -p:Configuration=Release`: **Passed** - Runtime test suites against Checked CoreCLR: - `src\tests\build.cmd -Test JIT\Generics\JIT.Generics.csproj x64 Checked` + `corerun.exe JIT.Generics.dll`: **Passed (exit code 100)** - `src\tests\build.cmd -Test async\async.csproj x64 Checked -Priority 1` + `corerun.exe async.dll`: **Passed (exit code 100)** > [!NOTE] > This pull request was authored with assistance from GitHub Copilot. --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot Autofix powered by AI <[email protected]> Co-authored-by: Jan Kotas <[email protected]>
1 parent 64c190b commit e8b295c

20 files changed

Lines changed: 729 additions & 262 deletions

File tree

‎src/coreclr/System.Private.CoreLib/src/System/Runtime/ExceptionServices/AsmOffsets.cs‎

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -58,19 +58,19 @@ class AsmOffsets
5858

5959
#if TARGET_64BIT
6060
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x8;
61-
public const int SIZEOF__StackFrameIterator = 0x150;
62-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x148;
63-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x132;
61+
public const int SIZEOF__StackFrameIterator = 0x168;
62+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x160;
63+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x14a;
6464
#elif TARGET_X86
6565
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x4;
66-
public const int SIZEOF__StackFrameIterator = 0x3d0;
67-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x3c2;
68-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x3cc;
66+
public const int SIZEOF__StackFrameIterator = 0x3dc;
67+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x3ce;
68+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x3d8;
6969
#else // TARGET_64BIT
7070
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x4;
71-
public const int SIZEOF__StackFrameIterator = 0xc8;
72-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0xc4;
73-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0xba;
71+
public const int SIZEOF__StackFrameIterator = 0xd4;
72+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0xd0;
73+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0xc6;
7474
#endif // TARGET_64BIT
7575

7676
#else // DEBUG
@@ -119,19 +119,19 @@ class AsmOffsets
119119

120120
#if TARGET_64BIT
121121
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x8;
122-
public const int SIZEOF__StackFrameIterator = 0x148;
123-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x140;
124-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x12a;
122+
public const int SIZEOF__StackFrameIterator = 0x160;
123+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x158;
124+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x142;
125125
#elif TARGET_X86
126126
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x4;
127-
public const int SIZEOF__StackFrameIterator = 0x3c8;
128-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x3ba;
129-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x3c4;
127+
public const int SIZEOF__StackFrameIterator = 0x3d4;
128+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0x3c6;
129+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0x3d0;
130130
#else // TARGET_64BIT
131131
public const int OFFSETOF__REGDISPLAY__m_pCurrentContext = 0x4;
132-
public const int SIZEOF__StackFrameIterator = 0xc0;
133-
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0xbc;
134-
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0xb2;
132+
public const int SIZEOF__StackFrameIterator = 0xcc;
133+
public const int OFFSETOF__StackFrameIterator__m_AdjustedControlPC = 0xc8;
134+
public const int OFFSETOF__StackFrameIterator__m_isRuntimeWrappedExceptions = 0xbe;
135135
#endif // TARGET_64BIT
136136

137137
#endif // DEBUG

‎src/coreclr/inc/eetwain.h‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ enum ICodeManagerFlags
9595
ReportFPBasedSlotsOnly
9696
= 0x0200, // EnumGCRefs/EnumerateLiveSlots should only include
9797
// slots that are based on the frame pointer
98+
GcRootScan = 0x0400, // GC root scan: skip FP/vector context copies and report generic loader allocators
9899
};
99100

100101
//*****************************************************************************
@@ -199,6 +200,8 @@ virtual bool HasTailCalls(EECodeInfo *pCodeInfo) = 0;
199200
the virtual register set. Same reference location cannot be enumerated
200201
multiple times (but all differenct references pointing to the same
201202
object have to be individually enumerated).
203+
With GcRootScan, hCallBack is a GCCONTEXT and promotion also reports
204+
the generic context's loader allocator.
202205
Returns success of operation.
203206
*/
204207
virtual bool EnumGcRefs(PREGDISPLAY pContext,
@@ -228,9 +231,11 @@ virtual OBJECTREF GetInstance(PREGDISPLAY pContext,
228231
virtual PTR_VOID GetParamTypeArg(PREGDISPLAY pContext,
229232
EECodeInfo * pCodeInfo) = 0;
230233

231-
// Returns the type of the context parameter (this, methodtable, methoddesc, or none)
234+
// Returns the type of the context parameter (this, methodtable, methoddesc, or none),
235+
// and optionally retrieves the generics token.
232236
virtual GenericParamContextType GetParamContextType(PREGDISPLAY pContext,
233-
EECodeInfo * pCodeInfo) = 0;
237+
EECodeInfo * pCodeInfo,
238+
PTR_VOID * ppGenericsToken = NULL) = 0;
234239

235240
/*
236241
Returns the offset of the GuardStack cookie if it exists.
@@ -426,18 +431,16 @@ virtual
426431
PTR_VOID GetParamTypeArg(PREGDISPLAY pContext,
427432
EECodeInfo * pCodeInfo);
428433

429-
// Returns the type of the context parameter (this, methodtable, methoddesc, or none)
434+
// Returns the type of the context parameter (this, methodtable, methoddesc, or none),
435+
// and optionally retrieves the generics token.
430436
virtual GenericParamContextType GetParamContextType(PREGDISPLAY pContext,
431-
EECodeInfo * pCodeInfo);
437+
EECodeInfo * pCodeInfo,
438+
PTR_VOID * ppGenericsToken = NULL);
432439

433440
#ifdef USE_GC_INFO_DECODER
434441
/*
435-
Returns the generics token. This is used by GetInstance() and GetParamTypeArg() on WIN64.
442+
Returns the generics token. This is used by profiler stackwalking.
436443
*/
437-
static
438-
PTR_VOID GetExactGenericsToken(PREGDISPLAY pContext,
439-
EECodeInfo * pCodeInfo);
440-
441444
static
442445
PTR_VOID GetExactGenericsToken(TADDR sp,
443446
TADDR fp,
@@ -515,7 +518,7 @@ HRESULT FixContextForEnC(PCONTEXT pCtx,
515518
#endif // #ifndef DACCESS_COMPILE
516519

517520
virtual void EnsureCallerContextIsValid( PREGDISPLAY pRD, EECodeInfo * pCodeInfo = NULL, unsigned flags = 0);
518-
static size_t GetCallerSp( PREGDISPLAY pRD );
521+
static size_t GetCallerSp( PREGDISPLAY pRD, EECodeInfo * pCodeInfo, unsigned flags );
519522
#ifdef TARGET_X86
520523
static size_t GetResumeSp( PCONTEXT pContext );
521524
#endif // TARGET_X86
@@ -600,7 +603,8 @@ PTR_VOID GetParamTypeArg(PREGDISPLAY pContext,
600603
EECodeInfo * pCodeInfo);
601604

602605
virtual GenericParamContextType GetParamContextType(PREGDISPLAY pContext,
603-
EECodeInfo * pCodeInfo);
606+
EECodeInfo * pCodeInfo,
607+
PTR_VOID * ppGenericsToken = NULL);
604608

605609
virtual
606610
void * GetGSCookieAddr(PREGDISPLAY pContext,

‎src/coreclr/inc/gcinfodecoder.h‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,29 @@ enum ICodeManagerFlags
201201

202202
#include "gcinfotypes.h"
203203

204+
namespace BitOperations
205+
{
206+
FORCEINLINE UINT32 TrailingZeroCount(size_t value)
207+
{
208+
_ASSERTE(value != 0);
209+
#if defined(_MSC_VER)
210+
unsigned long result;
211+
#if defined(HOST_64BIT)
212+
::_BitScanForward64(&result, value);
213+
#else
214+
::_BitScanForward(&result, value);
215+
#endif
216+
return static_cast<UINT32>(result);
217+
#else
218+
#if defined(HOST_64BIT)
219+
return static_cast<UINT32>(__builtin_ctzll(value));
220+
#else
221+
return static_cast<UINT32>(__builtin_ctz(value));
222+
#endif
223+
#endif
224+
}
225+
}
226+
204227
#ifdef _DEBUG
205228
#define MAX_PREDECODED_SLOTS 4
206229
#else
@@ -347,6 +370,55 @@ class BitStreamReader
347370
return result;
348371
}
349372

373+
// Reads up to the remaining bits in the current word (at most maxBits and at most BITS_PER_SIZE_T).
374+
// Returns the read bits in the low bits of the result and sets bitsRead to the number of bits consumed.
375+
FORCEINLINE size_t ReadWord(UINT32 maxBits, UINT32& bitsRead)
376+
{
377+
SUPPORTS_DAC;
378+
_ASSERTE(maxBits > 0);
379+
380+
if (m_RelPos == BITS_PER_SIZE_T)
381+
{
382+
m_pCurrent++;
383+
m_current = *m_pCurrent;
384+
m_RelPos = 0;
385+
}
386+
387+
UINT32 availBits = (UINT32)(BITS_PER_SIZE_T - m_RelPos);
388+
UINT32 chunkBits = _min(maxBits, availBits);
389+
bitsRead = chunkBits;
390+
391+
size_t mask = (chunkBits == BITS_PER_SIZE_T) ? ~(size_t)0 : ((size_t{ 1 } << chunkBits) - 1);
392+
size_t result = m_current & mask;
393+
m_current = (chunkBits == BITS_PER_SIZE_T) ? 0 : (m_current >> chunkBits);
394+
m_RelPos += chunkBits;
395+
396+
return result;
397+
}
398+
399+
// Counts consecutive zero bits up to the next set bit, consumes the zero bits and that set bit,
400+
// and returns the number of zero bits skipped.
401+
FORCEINLINE UINT32 SkipZerosAndReadOne()
402+
{
403+
SUPPORTS_DAC;
404+
405+
UINT32 skipped = 0;
406+
while (m_current == 0)
407+
{
408+
skipped += (UINT32)(BITS_PER_SIZE_T - m_RelPos);
409+
m_pCurrent++;
410+
m_current = *m_pCurrent;
411+
m_RelPos = 0;
412+
}
413+
414+
UINT32 tz = BitOperations::TrailingZeroCount(m_current);
415+
skipped += tz;
416+
UINT32 consume = tz + 1;
417+
m_RelPos += consume;
418+
m_current = (consume == BITS_PER_SIZE_T) ? 0 : (m_current >> consume);
419+
return skipped;
420+
}
421+
350422

351423
FORCEINLINE size_t GetCurrentPos()
352424
{

‎src/coreclr/vm/cdacstress.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -832,9 +832,9 @@ static HRESULT CollectRuntimeStackRefs(Thread* pThread, PCONTEXT regs, SArray<St
832832

833833
// Use a callback that matches DAC behavior (DacStackReferenceWalker::Callback):
834834
// Only call EnumGcRefs for frameless frames and GcScanRoots for explicit frames.
835-
// Deliberately skip the post-scan logic (LCG resolver promotion,
836-
// GcReportLoaderAllocator, generic param context) that GcStackCrawlCallBack
837-
// includes — the DAC's callback has that logic disabled (#if 0).
835+
// Deliberately skip LCG resolver and loader allocator promotion, including generic
836+
// contexts, by leaving GcRootScan unset and omitting GcStackCrawlCallBack's post-scan
837+
// logic. The DAC's callback has that logic disabled (#if 0).
838838
struct DiagContext { GCCONTEXT* gcctx; RuntimeRefCollectionContext* collectCtx; };
839839
DiagContext diagCtx = { &gcctx, &collectCtx };
840840

‎src/coreclr/vm/codeman.cpp‎

Lines changed: 50 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -3625,44 +3625,43 @@ TypeHandle InterpreterJitManager::ResolveEHClause(EE_ILEXCEPTION_CLAUSE* pEHClau
36253625
{
36263626
_ASSERTE(!HasCachedTypeHandle(pEHClause));
36273627

3628-
GenericParamContextType paramContextType = pCf->GetCodeManager()->GetParamContextType(pCf->GetRegisterSet(), pCf->GetCodeInfo());
3629-
_ASSERTE(SafeToReportGenericParamContext(pCf));
3630-
if (SafeToReportGenericParamContext(pCf))
3628+
PTR_VOID genericsToken = NULL;
3629+
GenericParamContextType paramContextType = pCf->GetCodeManager()->GetParamContextType(
3630+
pCf->GetRegisterSet(),
3631+
pCf->GetCodeInfo(),
3632+
&genericsToken);
3633+
MethodDesc *pMD = pCf->GetFunction();
3634+
TypeHandle declaringType = (TypeHandle)pMD->GetMethodTable();
3635+
3636+
// Shared generic code needs the frame's exact generic context to resolve the exception type.
3637+
if (paramContextType == GENERIC_PARAM_CONTEXT_METHODDESC)
36313638
{
3632-
MethodDesc *pMD = pCf->GetFunction();
3633-
TypeHandle declaringType = (TypeHandle)pMD->GetMethodTable();
3634-
3635-
// Handle the case where the method is a static shared generic method and we need to keep the type
3636-
// of the generic parameters alive
3637-
if (paramContextType == GENERIC_PARAM_CONTEXT_METHODDESC)
3638-
{
3639-
pMD = dac_cast<PTR_MethodDesc>(pCf->GetParamTypeArg());
3640-
declaringType = (TypeHandle)pMD->GetMethodTable();
3641-
}
3642-
else if (paramContextType == GENERIC_PARAM_CONTEXT_METHODTABLE)
3643-
{
3644-
declaringType = (TypeHandle)dac_cast<PTR_MethodTable>(pCf->GetParamTypeArg());
3645-
}
3646-
else
3639+
pMD = dac_cast<PTR_MethodDesc>(genericsToken);
3640+
declaringType = (TypeHandle)pMD->GetMethodTable();
3641+
}
3642+
else if (paramContextType == GENERIC_PARAM_CONTEXT_METHODTABLE)
3643+
{
3644+
declaringType = (TypeHandle)dac_cast<PTR_MethodTable>(genericsToken);
3645+
}
3646+
else
3647+
{
3648+
_ASSERTE(paramContextType == GENERIC_PARAM_CONTEXT_THIS);
3649+
GCX_COOP();
3650+
declaringType = (TypeHandle)dac_cast<PTR_MethodTable>(pCf->GetExactGenericArgsToken());
3651+
if (declaringType.IsNull())
36473652
{
3648-
_ASSERTE(paramContextType == GENERIC_PARAM_CONTEXT_THIS);
3649-
GCX_COOP();
3650-
declaringType = (TypeHandle)dac_cast<PTR_MethodTable>(pCf->GetExactGenericArgsToken());
3651-
if (declaringType.IsNull())
3652-
{
3653-
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
3654-
}
3653+
COMPlusThrow(kNullReferenceException, W("NullReference_This"));
36553654
}
3655+
}
36563656

3657-
_ASSERTE(!declaringType.IsNull());
3657+
_ASSERTE(!declaringType.IsNull());
36583658

3659-
SigTypeContext typeContext(pMD, declaringType);
3659+
SigTypeContext typeContext(pMD, declaringType);
36603660

3661-
Module* pModule = pMD->GetModule();
3661+
Module* pModule = pMD->GetModule();
36623662

3663-
thResolved = ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, pEHClause->ClassToken, &typeContext,
3664-
ClassLoader::ReturnNullIfNotFound);
3665-
}
3663+
thResolved = ClassLoader::LoadTypeDefOrRefOrSpecThrowing(pModule, pEHClause->ClassToken, &typeContext,
3664+
ClassLoader::ReturnNullIfNotFound);
36663665
}
36673666

36683667
return thResolved;
@@ -4688,6 +4687,7 @@ BOOL EECodeGenManager::JitCodeToMethodInfoWorker(
46884687
if (pCodeInfo)
46894688
{
46904689
pCodeInfo->m_methodToken = METHODTOKEN(pRangeSection, dac_cast<TADDR>(pCHdr));
4690+
pCodeInfo->m_gcInfoToken = { NULL, 0 };
46914691

46924692
// This can be counted on for Jitted code. For NGEN code in the case
46934693
// where we have hot/cold splitting this isn't valid and we need to
@@ -7242,7 +7242,8 @@ BOOL ReadyToRunJitManager::JitCodeToMethodInfo(RangeSection * pRangeSection,
72427242

72437243
#ifdef FEATURE_COLD_R2R_CODE
72447244
const int lookupIndex = HotColdMappingLookupTable::LookupMappingForMethod(pInfo, (ULONG)MethodIndex);
7245-
if ((lookupIndex != -1) && ((lookupIndex & 1) == 1))
7245+
const bool isColdCode = (lookupIndex != -1) && ((lookupIndex & 1) == 1);
7246+
if (isColdCode)
72467247
{
72477248
// If the MethodIndex happens to be the cold code block, turn it into the associated hot code block
72487249
MethodIndex = pInfo->m_pHotColdMap[lookupIndex];
@@ -7265,20 +7266,33 @@ BOOL ReadyToRunJitManager::JitCodeToMethodInfo(RangeSection * pRangeSection,
72657266
{
72667267
// We are using RUNTIME_FUNCTION as METHODTOKEN
72677268
pCodeInfo->m_methodToken = METHODTOKEN(pRangeSection, dac_cast<TADDR>(FunctionEntry));
7269+
pCodeInfo->m_gcInfoToken = { NULL, 0 };
72687270

72697271
AMD64_ONLY(_ASSERTE((RawFunctionEntry->UnwindData & RUNTIME_FUNCTION_INDIRECT) == 0));
72707272
pCodeInfo->m_pFunctionEntry = RawFunctionEntry;
7271-
MethodRegionInfo methodRegionInfo;
7272-
JitTokenToMethodRegionInfo(pCodeInfo->m_methodToken, &methodRegionInfo);
7273-
if ((methodRegionInfo.coldSize > 0) && (currentInstr >= methodRegionInfo.coldStartAddress))
7273+
#ifdef FEATURE_COLD_R2R_CODE
7274+
if (isColdCode)
72747275
{
7276+
MethodRegionInfo methodRegionInfo;
7277+
JitTokenToMethodRegionInfo(pCodeInfo->m_methodToken, &methodRegionInfo);
7278+
_ASSERTE((methodRegionInfo.coldSize > 0) && (currentInstr >= methodRegionInfo.coldStartAddress));
72757279
pCodeInfo->m_relOffset = (DWORD)
72767280
(methodRegionInfo.hotSize + (currentInstr - methodRegionInfo.coldStartAddress));
72777281
}
72787282
else
7283+
#endif // FEATURE_COLD_R2R_CODE
72797284
{
7280-
pCodeInfo->m_relOffset = (DWORD)(currentInstr - methodRegionInfo.hotStartAddress);
7285+
pCodeInfo->m_relOffset = (DWORD)(currentInstr - JitTokenToStartAddress(pCodeInfo->m_methodToken));
72817286
}
7287+
7288+
#ifdef _DEBUG
7289+
MethodRegionInfo debugMethodRegionInfo;
7290+
JitTokenToMethodRegionInfo(pCodeInfo->m_methodToken, &debugMethodRegionInfo);
7291+
DWORD expectedRelOffset = ((debugMethodRegionInfo.coldSize > 0) && (currentInstr >= debugMethodRegionInfo.coldStartAddress))
7292+
? (DWORD)(debugMethodRegionInfo.hotSize + (currentInstr - debugMethodRegionInfo.coldStartAddress))
7293+
: (DWORD)(currentInstr - debugMethodRegionInfo.hotStartAddress);
7294+
_ASSERTE(pCodeInfo->m_relOffset == expectedRelOffset);
7295+
#endif // _DEBUG
72827296
}
72837297

72847298
return TRUE;

‎src/coreclr/vm/codeman.h‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3232,7 +3232,13 @@ class EECodeInfo
32323232
GCInfoToken GetGCInfoToken()
32333233
{
32343234
WRAPPER_NO_CONTRACT;
3235-
return GetJitManager()->GetGCInfoToken(GetMethodToken());
3235+
if (m_gcInfoToken.Info == NULL)
3236+
{
3237+
m_gcInfoToken = GetJitManager()->GetGCInfoToken(GetMethodToken());
3238+
}
3239+
_ASSERTE(m_gcInfoToken.Info == GetJitManager()->GetGCInfoToken(GetMethodToken()).Info &&
3240+
m_gcInfoToken.Version == GetJitManager()->GetGCInfoToken(GetMethodToken()).Version);
3241+
return m_gcInfoToken;
32363242
}
32373243

32383244
PTR_VOID GetGCInfo()
@@ -3306,6 +3312,7 @@ ULONG GetFixedStackSize();
33063312
DWORD m_relOffset;
33073313
IsFuncletCache m_isFuncletCache;
33083314
PTR_RUNTIME_FUNCTION m_pFunctionEntry;
3315+
GCInfoToken m_gcInfoToken;
33093316

33103317
#ifdef TARGET_X86
33113318
PTR_CBYTE m_hdrInfoTable;
@@ -3351,6 +3358,4 @@ inline TADDR InterpreterJitManager::JitTokenToStartAddress(const METHODTOKEN& Me
33513358

33523359
#include "codeman.inl"
33533360

3354-
bool SafeToReportGenericParamContext(CrawlFrame* pCF);
3355-
33563361
#endif // !__CODEMAN_HPP__

0 commit comments

Comments
 (0)