diff --git a/src/coreclr/src/jit/importer.cpp b/src/coreclr/src/jit/importer.cpp index fb9e10c6a98093..055918d16c619b 100644 --- a/src/coreclr/src/jit/importer.cpp +++ b/src/coreclr/src/jit/importer.cpp @@ -21193,14 +21193,45 @@ void Compiler::impDevirtualizeCall(GenTreeCall* call, // https://github.com/dotnet/runtime/issues/38477 // but hopefully the derived method conforms to // the base in most other ways. - *method = derivedMethod; - *methodFlags = derivedMethodAttribs; - *contextHandle = MAKE_METHODCONTEXT(derivedMethod); + *method = derivedMethod; + *methodFlags = derivedMethodAttribs; + + if (((SIZE_T)(*contextHandle) & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_METHOD) + { + *contextHandle = MAKE_METHODCONTEXT(derivedMethod); + } + else + { + assert(((SIZE_T)(*contextHandle) & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS); + if (isExact) + { + *contextHandle = MAKE_CLASSCONTEXT(objClass); + } + else + { + *contextHandle = MAKE_CLASSCONTEXT(derivedClass); + } + } // Update context handle. - if ((exactContextHandle != nullptr) && (*exactContextHandle != nullptr)) + if ((exactContextHandle != nullptr)) { - *exactContextHandle = MAKE_METHODCONTEXT(derivedMethod); + if (((SIZE_T)(*exactContextHandle) & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_METHOD) + { + *exactContextHandle = MAKE_METHODCONTEXT(derivedMethod); + } + else + { + assert(((SIZE_T)(*exactContextHandle) & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS); + if (isExact) + { + *exactContextHandle = MAKE_CLASSCONTEXT(objClass); + } + else + { + *exactContextHandle = MAKE_CLASSCONTEXT(derivedClass); + } + } } #ifdef FEATURE_READYTORUN_COMPILER