From 009bd8fcdb4085acedc2b80b27b0684cd47a9a20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michal=20Strehovsk=C3=BD?= Date: Mon, 17 Nov 2025 14:28:38 +0100 Subject: [PATCH] Skip nullcheck frozen object in unbox optimization Fixes the build crash in #121697. Since with TrimMode=partial, we consider all static fields targets of reflection, we cannot allow inlining their contents. With full trimming allowed, the optimization is unlocked and we hit an assert when trying to nullcheck a constant. --- src/coreclr/jit/importer.cpp | 30 ++++++++++++++++++++---------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 9bc7aa13eb59d3..751e15211b57fb 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -10480,16 +10480,26 @@ void Compiler::impImportBlockCode(BasicBlock* block) GenTree* boxPayloadOffset = gtNewIconNode(TARGET_POINTER_SIZE, TYP_I_IMPL); GenTree* boxPayloadAddress = gtNewOperNode(GT_ADD, TYP_BYREF, cloneOperand, boxPayloadOffset); - GenTree* nullcheck = gtNewNullCheck(op1); - // Add an ordering dependency between the null - // check and forming the byref; the JIT assumes - // in many places that the only legal null - // byref is literally 0, and since the byref - // leaks out here, we need to ensure it is - // nullchecked. - nullcheck->SetHasOrderingSideEffect(); - boxPayloadAddress->SetHasOrderingSideEffect(); - GenTree* result = gtNewOperNode(GT_COMMA, TYP_BYREF, nullcheck, boxPayloadAddress); + + GenTree* result; + if (fgAddrCouldBeNull(op1)) + { + GenTree* nullcheck = gtNewNullCheck(op1); + // Add an ordering dependency between the null + // check and forming the byref; the JIT assumes + // in many places that the only legal null + // byref is literally 0, and since the byref + // leaks out here, we need to ensure it is + // nullchecked. + nullcheck->SetHasOrderingSideEffect(); + boxPayloadAddress->SetHasOrderingSideEffect(); + result = gtNewOperNode(GT_COMMA, TYP_BYREF, nullcheck, boxPayloadAddress); + } + else + { + // We don't need a nullcheck if this is e.g. a preinitialized value + result = boxPayloadAddress; + } impPushOnStack(result, tiRetVal); break; }