diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index e745bce1bd037..3126025c0d922 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -2911,6 +2911,23 @@ int Compiler::impBoxPatternMatch(CORINFO_RESOLVED_TOKEN* pResolvedToken, case CEE_ISINST: if (codeAddr + 1 + sizeof(mdToken) + 1 <= codeEndp) { + // First, let's see if we can fold BOX+ISINST to just null if ISINST is known to return null + // for the given argument. Don't make inline observations for this case. + if ((opts == BoxPatterns::None) && ((impStackTop().val->gtFlags & GTF_SIDE_EFFECT) == 0) && + (info.compCompHnd->getBoxHelper(pResolvedToken->hClass) == CORINFO_HELP_BOX)) + { + CORINFO_RESOLVED_TOKEN isInstTok; + impResolveToken(codeAddr + 1, &isInstTok, CORINFO_TOKENKIND_Casting); + if (info.compCompHnd->compareTypesForCast(pResolvedToken->hClass, isInstTok.hClass) == + TypeCompareState::MustNot) + { + JITDUMP("\n Importing BOX; ISINST; as null\n"); + impPopStack(); + impPushOnStack(gtNewNull(), typeInfo(TYP_REF)); + return 1 + sizeof(mdToken); + } + } + const BYTE* nextCodeAddr = codeAddr + 1 + sizeof(mdToken); switch (nextCodeAddr[0])