From 58d830ddbb70199dbb6167b52aba6b3bf61b7b1c Mon Sep 17 00:00:00 2001 From: EgorBo Date: Thu, 25 Jan 2024 19:31:16 +0100 Subject: [PATCH 01/10] Keep importer for now --- src/coreclr/jit/helperexpansion.cpp | 102 +++++++++++++++++----------- src/coreclr/jit/importer.cpp | 9 +-- 2 files changed, 64 insertions(+), 47 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index 6567af900f7b69..e98f37ad2c5d64 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1797,31 +1797,12 @@ bool Compiler::fgVNBasedIntrinsicExpansionForCall_ReadUtf8(BasicBlock** pBlock, // PhaseStatus Compiler::fgLateCastExpansion() { - if (!doesMethodHaveExpandableCasts()) + if (!doesMethodHaveExpandableCasts() || opts.OptimizationDisabled()) { // Nothing to expand in the current method return PhaseStatus::MODIFIED_NOTHING; } - if (!opts.IsOptimizedWithProfile()) - { - // Currently, we're only interested in expanding cast helpers using profile data - return PhaseStatus::MODIFIED_NOTHING; - } - - if (JitConfig.JitConsumeProfileForCasts() == 0) - { - return PhaseStatus::MODIFIED_NOTHING; - } - - const bool preferSize = opts.jitFlags->IsSet(JitFlags::JIT_FLAG_SIZE_OPT); - if (preferSize) - { - // The optimization comes with a codegen size increase - JITDUMP("Optimized for size - bail out.\n"); - return PhaseStatus::MODIFIED_NOTHING; - } - // TODO-InlineCast: should we still inline some trivial cases even in cold blocks? const bool skipForRarelyRunBlocks = true; return fgExpandHelper<&Compiler::fgLateCastExpansionForCall>(skipForRarelyRunBlocks); @@ -1831,6 +1812,7 @@ enum class TypeCheckFailedAction { ReturnNull, CallHelper, + CallHelper_Specialized, CallHelper_AlwaysThrows }; @@ -1947,14 +1929,25 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com const bool isCastToExact = comp->info.compCompHnd->isExactType(castToCls); if (isCastToExact && ((helper == CORINFO_HELP_CHKCASTCLASS) || (helper == CORINFO_HELP_CHKCASTARRAY))) { - // (string)obj - // (string[])obj + result = castToCls; + + // obj is string + // obj is string[] // - // Fallbacks for these expansions always throw InvalidCastException - *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; + if ((helper == CORINFO_HELP_CHKCASTCLASS)) + { + // (string)obj + // + // Fallback for this expansion always throws InvalidCastException + // TODO: can we do the same for string[]? (importer did not) + *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; + + // Assume that exceptions are rare + *likelihood = 100; - // Assume that exceptions are rare - *likelihood = 100; + // Update the common denominator class to be more exact + *commonCls = result; + } // We're done, there is no need in consulting with PGO data } @@ -1965,39 +1958,55 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com // obj is string[] // // Fallbacks for these expansions simply return null + // TODO: should we keep the helper call for ISINSTANCEOFARRAY like we do for CHKCASTARRAY above? + // The logic is copied from the importer. *typeCheckFailed = TypeCheckFailedAction::ReturnNull; + + // We're done, there is no need in consulting with PGO data + result = castToCls; } else { + CORINFO_CLASS_HANDLE exactClass = NO_CLASS_HANDLE; // 2) If VM can tell us the exact class for this "cast to" class - use it. // Just make sure the class is truly exact. - if ((comp->info.compCompHnd->getExactClasses(castToCls, 1, &result) == 1) && - comp->info.compCompHnd->isExactType(result)) + if ((comp->info.compCompHnd->getExactClasses(castToCls, 1, &exactClass) == 1) && + comp->info.compCompHnd->isExactType(exactClass)) { - if (isCastClass) + result = exactClass; + + if ((helper == CORINFO_HELP_CHKCASTINTERFACE) || (helper == CORINFO_HELP_CHKCASTCLASS)) { // Fallback call is only needed for castclass and only to throw InvalidCastException *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; // Assume that exceptions are rare *likelihood = 100; + + // Update the common denominator class to be more exact + *commonCls = result; } - else + else if ((helper == CORINFO_HELP_ISINSTANCEOFINTERFACE) || (helper == CORINFO_HELP_ISINSTANCEOFCLASS)) { // Fallback for isinst simply returns null here *typeCheckFailed = TypeCheckFailedAction::ReturnNull; - } - // Update the common denominator class to be more exact - *commonCls = result; + // Update the common denominator class to be more exact + *commonCls = result; + } } else { // 3) Consult with PGO data LikelyClassMethodRecord likelyClasses[MAX_GDV_TYPE_CHECKS]; - unsigned likelyClassCount = - getLikelyClasses(likelyClasses, MAX_GDV_TYPE_CHECKS, comp->fgPgoSchema, comp->fgPgoSchemaCount, - comp->fgPgoData, (int)castHelper->gtCastHelperILOffset); + unsigned likelyClassCount = 0; + + if (comp->opts.IsOptimizedWithProfile() && (JitConfig.JitConsumeProfileForCasts() != 0)) + { + const int ilOffset = (int)castHelper->gtCastHelperILOffset; + likelyClassCount = getLikelyClasses(likelyClasses, MAX_GDV_TYPE_CHECKS, comp->fgPgoSchema, + comp->fgPgoSchemaCount, comp->fgPgoData, ilOffset); + } if (likelyClassCount != 0) { @@ -2152,10 +2161,12 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com unreached(); } - if (isCastClass && (result == castToCls) && (*typeCheckFailed == TypeCheckFailedAction::CallHelper)) + if ((helper == CORINFO_HELP_CHKCASTCLASS) && (result == castToCls) && + (*typeCheckFailed == TypeCheckFailedAction::CallHelper)) { - // TODO-InlineCast: Change helper to faster CORINFO_HELP_CHKCASTCLASS_SPECIAL - // it won't check for null and castToCls assuming we've already done it inline. + // A small optimization - use a slightly faster fallback which assumes that we've already checked + // for null and for castToCls itself so it won't do it again. + *typeCheckFailed = TypeCheckFailedAction::CallHelper_Specialized; } assert(result != NO_CLASS_HANDLE); @@ -2268,7 +2279,18 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, } else { - GenTree* fallbackTree = gtNewTempStore(tmpNum, call); + GenTreeCall* helperCall = call; + if (typeCheckFailedAction == TypeCheckFailedAction::CallHelper_Specialized) + { + // Re-create the call with a specialized helper + // For JIT we probably can just change the gtCallMethHnd in the existing call, but let's unify with AOT + helperCall = gtNewHelperCallNode(CORINFO_HELP_CHKCASTCLASS_SPECIAL, call->TypeGet(), + helperCall->gtArgs.GetUserArgByIndex(0)->GetNode(), + helperCall->gtArgs.GetUserArgByIndex(1)->GetNode()); + fgMorphCall(helperCall); + gtSetEvalOrder(helperCall); + } + GenTree* fallbackTree = gtNewTempStore(tmpNum, helperCall); fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, typeCheckBb, fallbackTree, debugInfo, lastBb, true); } diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 5393c4a7425421..205fca7a584a33 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -5462,7 +5462,6 @@ GenTree* Compiler::impCastClassOrIsInstToTree( // Pessimistically assume the jit cannot expand this as an inline test bool canExpandInline = false; - bool partialExpand = false; bool reversedMTCheck = false; const CorInfoHelpFunc helper = info.compCompHnd->getCastingHelper(pResolvedToken, isCastClass); @@ -5559,7 +5558,7 @@ GenTree* Compiler::impCastClassOrIsInstToTree( // GenTree* op2Var = op2; - if (isCastClass && !partialExpand && (exactCls == NO_CLASS_HANDLE)) + if (isCastClass && (exactCls == NO_CLASS_HANDLE)) { // if exactCls is not null we won't have to clone op2 (it will be used only for the fallback) op2Var = fgInsertCommaFormTemp(&op2); @@ -5597,11 +5596,7 @@ GenTree* Compiler::impCastClassOrIsInstToTree( // use the special helper that skips the cases checked by our inlined cast specialHelper = CORINFO_HELP_CHKCASTCLASS_SPECIAL; } - condTrue = gtNewHelperCallNode(specialHelper, TYP_REF, partialExpand ? op2 : op2Var, gtClone(op1)); - } - else if (partialExpand) - { - condTrue = gtNewHelperCallNode(helper, TYP_REF, op2, gtClone(op1)); + condTrue = gtNewHelperCallNode(specialHelper, TYP_REF, op2Var, gtClone(op1)); } else { From 8d699cd65dc276a3058e7f961b4af51d0d107a7c Mon Sep 17 00:00:00 2001 From: EgorBo Date: Fri, 26 Jan 2024 23:40:43 +0100 Subject: [PATCH 02/10] remove morphing --- src/coreclr/jit/helperexpansion.cpp | 18 +++++------------- src/coreclr/jit/importer.cpp | 3 +++ 2 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index e98f37ad2c5d64..59a580a5f88eb8 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -2279,18 +2279,13 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, } else { - GenTreeCall* helperCall = call; if (typeCheckFailedAction == TypeCheckFailedAction::CallHelper_Specialized) { - // Re-create the call with a specialized helper - // For JIT we probably can just change the gtCallMethHnd in the existing call, but let's unify with AOT - helperCall = gtNewHelperCallNode(CORINFO_HELP_CHKCASTCLASS_SPECIAL, call->TypeGet(), - helperCall->gtArgs.GetUserArgByIndex(0)->GetNode(), - helperCall->gtArgs.GetUserArgByIndex(1)->GetNode()); - fgMorphCall(helperCall); - gtSetEvalOrder(helperCall); + // A slightly faster fallback which assumes that we've already checked + // for null and for castToCls itself. + call->gtCallMethHnd = eeFindHelper(CORINFO_HELP_CHKCASTCLASS_SPECIAL); } - GenTree* fallbackTree = gtNewTempStore(tmpNum, helperCall); + GenTree* fallbackTree = gtNewTempStore(tmpNum, call); fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, typeCheckBb, fallbackTree, debugInfo, lastBb, true); } @@ -2337,10 +2332,7 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, // nullcheckBb->inheritWeight(firstBb); typeCheckBb->inheritWeightPercentage(nullcheckBb, 50); - fallbackBb->inheritWeightPercentage(typeCheckBb, - (typeCheckFailedAction == TypeCheckFailedAction::CallHelper_AlwaysThrows) - ? 0 - : 100 - likelihood); + fallbackBb->inheritWeightPercentage(typeCheckBb, fallbackBb->KindIs(BBJ_THROW) ? 0 : 100 - likelihood); typeCheckSucceedBb->inheritWeightPercentage(typeCheckBb, likelihood); lastBb->inheritWeight(firstBb); diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 205fca7a584a33..955b75af71faae 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -5460,6 +5460,9 @@ GenTree* Compiler::impCastClassOrIsInstToTree( shouldExpandInline = isCastClass && isClassExact; } + // CI test + shouldExpandInline = false; + // Pessimistically assume the jit cannot expand this as an inline test bool canExpandInline = false; bool reversedMTCheck = false; From c211572edce1f6198d4e705cc24344b915ab7060 Mon Sep 17 00:00:00 2001 From: Egor Bogatov Date: Sat, 27 Jan 2024 11:52:12 +0100 Subject: [PATCH 03/10] Update importer.cpp --- src/coreclr/jit/importer.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 955b75af71faae..205fca7a584a33 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -5460,9 +5460,6 @@ GenTree* Compiler::impCastClassOrIsInstToTree( shouldExpandInline = isCastClass && isClassExact; } - // CI test - shouldExpandInline = false; - // Pessimistically assume the jit cannot expand this as an inline test bool canExpandInline = false; bool reversedMTCheck = false; From c84e144778b504322ab41aa9773ae7453b0fa35f Mon Sep 17 00:00:00 2001 From: EgorBo Date: Mon, 29 Jan 2024 12:19:11 +0100 Subject: [PATCH 04/10] New set of improvements for late casts --- src/coreclr/jit/helperexpansion.cpp | 579 +++++++++++++++++----------- src/coreclr/jit/importer.cpp | 2 + 2 files changed, 350 insertions(+), 231 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index 59a580a5f88eb8..c80a4f75dd8e40 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1822,8 +1822,81 @@ enum class TypeCheckPassedAction ReturnNull, }; +// Some arbitrary limit on the number of guesses we can make +// The actual number of guesses is usually much smaller +#define MAX_CAST_GUESSES 8 + +//------------------------------------------------------------------------------ +// GetLikelyClassesForCast: returns a list of likely classes for the given cast +// using profile data. +// +// Arguments: +// comp - Compiler instance +// ilOffset - IL offset of the cast +// candidates - [out] Array of likely class handles (up to MAX_CAST_GUESSES) +// likelihoods - [out] Array of their likelihoods [0..100] +// +// Returns: +// Number of likely classes +// +static int GetLikelyClassesForCast(Compiler* comp, + int ilOffset, + CORINFO_CLASS_HANDLE* candidates, + unsigned* likelihoods) +{ + if (!comp->opts.IsOptimizedWithProfile() || (JitConfig.JitConsumeProfileForCasts() == 0)) + { + return 0; + } + + LikelyClassMethodRecord likelyClasses[MAX_CAST_GUESSES]; + unsigned likelyClassCount = getLikelyClasses(likelyClasses, MAX_CAST_GUESSES, comp->fgPgoSchema, + comp->fgPgoSchemaCount, comp->fgPgoData, ilOffset); + + if (likelyClassCount == 0) + { + return 0; + } + + int numberOfCandidates = 0; + for (UINT32 i = 0; i < likelyClassCount; i++) + { +#ifdef DEBUG + const char* className = comp->eeGetClassName((CORINFO_CLASS_HANDLE)likelyClasses[i].handle); + JITDUMP(" %u) %p (%s) [likelihood:%u%%]\n", i + 1, likelyClasses[i].handle, className, + likelyClasses[i].likelihood); +#endif + + CORINFO_CLASS_HANDLE cls = (CORINFO_CLASS_HANDLE)likelyClasses[i].handle; + if (cls != NO_CLASS_HANDLE) + { + // Validate static profile data + if ((comp->info.compCompHnd->getClassAttribs(candidates[0]) & + (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != 0) + { + // Possible scenario: someone changed Foo to be an interface/abstract class/static class, + // but static profile data still reports it as a normal likely class. + + // Should we ignore this case and continue with the next likely class? + // Conservatively treat it as compromised profile data and bail out. + return 0; + } + + candidates[numberOfCandidates] = cls; + likelihoods[numberOfCandidates] = likelyClasses[i].likelihood; + numberOfCandidates++; + } + else + { + // TODO-InlineCast: null as a likely class could mean that the object is mostly null, + // but we currently don't take advantage of that. + } + } + return numberOfCandidates; +} + //------------------------------------------------------------------------------ -// PickCandidateForTypeCheck: picks a class to use as a fast type check against +// PickCandidatesForTypeCheck: picks a class(es) to use as a fast type check against // the object being casted. The function also defines the strategy to follow // if the type check fails or passes. // @@ -1838,18 +1911,19 @@ enum class TypeCheckPassedAction // Returns: // Likely class handle or NO_CLASS_HANDLE // -static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* comp, - GenTreeCall* castHelper, - CORINFO_CLASS_HANDLE* commonCls, - unsigned* likelihood, - TypeCheckFailedAction* typeCheckFailed, - TypeCheckPassedAction* typeCheckPassed) +static int PickCandidatesForTypeCheck(Compiler* comp, + GenTreeCall* castHelper, + CORINFO_CLASS_HANDLE* candidates, + CORINFO_CLASS_HANDLE* commonCls, + unsigned* likelihoods, + TypeCheckFailedAction* typeCheckFailed, + TypeCheckPassedAction* typeCheckPassed) { if (!castHelper->IsHelperCall() || ((castHelper->gtCallMoreFlags & GTF_CALL_M_CAST_CAN_BE_EXPANDED) == 0)) { // It's not eligible for expansion (already expanded in importer) // To be removed once we move cast expansion here completely. - return NO_CLASS_HANDLE; + return 0; } // Helper calls are never tail calls @@ -1884,12 +1958,9 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com // Other helper calls are not cast helpers default: - return NO_CLASS_HANDLE; + return 0; } - // result is the class we're going to use as a guess for the type check. - CORINFO_CLASS_HANDLE result = NO_CLASS_HANDLE; - // First, let's grab the expected class we're casting to/checking instance of: // E.g. "call CORINFO_HELP_ISINSTANCEOFCLASS(castToCls, obj)" GenTree* clsArg = castHelper->gtArgs.GetUserArgByIndex(0)->GetNode(); @@ -1900,23 +1971,25 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com // TODO-InlineCast: if CSE becomes a problem - move the whole phase after assertion prop, // so we can still rely on VN to get the class handle. JITDUMP("clsArg is not a constant handle - bail out.\n"); - return NO_CLASS_HANDLE; + return 0; } - // Assume that the type check will pass with 50% probability by default - *likelihood = 50; - // Assume that in the slow path (fallback) we'll always invoke the helper. // In some cases we can optimize this further e.g. either mark it additionally // as no-return (BBJ_THROW) or simply return null. *typeCheckFailed = TypeCheckFailedAction::CallHelper; + // In most cases, a successful type check will return the object itself + // there is just one exception - see below in PGO handling. + *typeCheckPassed = TypeCheckPassedAction::ReturnObj; + // A common denominator class for the fast and the fallback paths // can be used as a class for LCL_VAR storing the result of the expansion. + // in most cases it's just the generic "cast to" class. *commonCls = castToCls; // - // Now we need to figure out what class to use for the fast path, we have 4 options: + // Now we need to figure out what classes to use for the fast path, we have 4 options: // 1) If "cast to" class is already exact we can go ahead and make some decisions // 2) If VM can tell us the exact class for this class/interface via getExactClasses - use it // e.g. NativeAOT can promise us that for e.g. "foo is IMyInterface" foo can only ever be @@ -1924,13 +1997,15 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com // 3) If we have PGO data and there is a dominating candidate - use it. // 4) Try to speculate and make optimistic guesses // + // NOTE: only 2) supports multiple candidates at the moment. + // + // // 1) If "cast to" class is already exact we can go ahead and make some decisions + // const bool isCastToExact = comp->info.compCompHnd->isExactType(castToCls); if (isCastToExact && ((helper == CORINFO_HELP_CHKCASTCLASS) || (helper == CORINFO_HELP_CHKCASTARRAY))) { - result = castToCls; - // obj is string // obj is string[] // @@ -1943,16 +2018,21 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; // Assume that exceptions are rare - *likelihood = 100; + likelihoods[0] = 100; - // Update the common denominator class to be more exact - *commonCls = result; + // Update the common denominator class to be more exact as + // the fallback always throws anyway, so we don't have to worry about what it returns. + *commonCls = castToCls; } - - // We're done, there is no need in consulting with PGO data + else + { + // 50% chance of successful type check (speculative guess) + likelihoods[0] = 50; + } + candidates[0] = castToCls; + return 1; } - else if (isCastToExact && - ((helper == CORINFO_HELP_ISINSTANCEOFARRAY) || (helper == CORINFO_HELP_ISINSTANCEOFCLASS))) + if (isCastToExact && ((helper == CORINFO_HELP_ISINSTANCEOFARRAY) || (helper == CORINFO_HELP_ISINSTANCEOFCLASS))) { // obj is string // obj is string[] @@ -1963,214 +2043,199 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com *typeCheckFailed = TypeCheckFailedAction::ReturnNull; // We're done, there is no need in consulting with PGO data - result = castToCls; + candidates[0] = castToCls; + // 50% chance of successful type check (speculative guess) + likelihoods[0] = 50; + return 1; } - else - { - CORINFO_CLASS_HANDLE exactClass = NO_CLASS_HANDLE; - // 2) If VM can tell us the exact class for this "cast to" class - use it. - // Just make sure the class is truly exact. - if ((comp->info.compCompHnd->getExactClasses(castToCls, 1, &exactClass) == 1) && - comp->info.compCompHnd->isExactType(exactClass)) - { - result = exactClass; - if ((helper == CORINFO_HELP_CHKCASTINTERFACE) || (helper == CORINFO_HELP_CHKCASTCLASS)) - { - // Fallback call is only needed for castclass and only to throw InvalidCastException - *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; + // + // 2) If VM can tell us the exact class for this "cast to" class - use it. + // Just make sure the class is truly exact. + // - // Assume that exceptions are rare - *likelihood = 100; + // Let's re-use the same threshold as for the GDV expansion on how many + // guesses we can make. + const int maxTypeChecks = min(comp->getGDVMaxTypeChecks(), MAX_CAST_GUESSES); - // Update the common denominator class to be more exact - *commonCls = result; - } - else if ((helper == CORINFO_HELP_ISINSTANCEOFINTERFACE) || (helper == CORINFO_HELP_ISINSTANCEOFCLASS)) - { - // Fallback for isinst simply returns null here - *typeCheckFailed = TypeCheckFailedAction::ReturnNull; + CORINFO_CLASS_HANDLE exactClasses[MAX_CAST_GUESSES] = {}; + const int numExactClasses = comp->info.compCompHnd->getExactClasses(castToCls, maxTypeChecks, exactClasses); + bool allTrulyExact = true; + for (int i = 0; i < numExactClasses; i++) + { + if (!comp->info.compCompHnd->isExactType(exactClasses[i])) + { + allTrulyExact = false; + break; + } + } - // Update the common denominator class to be more exact - *commonCls = result; - } + if ((numExactClasses > 0) && allTrulyExact) + { + // We know all exact classes, but we don't know the likelihoods + // TODO-InlineCast: check if we also have PGO data around (a rare case for getExactClasses, + // since it's NativeAOT-only at the moment, and we rarely have static profile data for it). + for (int i = 0; i < numExactClasses; i++) + { + likelihoods[i] = 100 / (numExactClasses + 1); + // E.g. 3 classes - 25%,25%,25% and 25% for the fallback + // A small integer rounding error is not a big deal here. } - else + + memcpy(candidates, exactClasses, numExactClasses * sizeof(CORINFO_CLASS_HANDLE)); + if ((helper == CORINFO_HELP_CHKCASTINTERFACE) || (helper == CORINFO_HELP_CHKCASTCLASS)) { - // 3) Consult with PGO data - LikelyClassMethodRecord likelyClasses[MAX_GDV_TYPE_CHECKS]; - unsigned likelyClassCount = 0; + // Fallback call is only needed for castclass and only to throw InvalidCastException + *typeCheckFailed = TypeCheckFailedAction::CallHelper_AlwaysThrows; - if (comp->opts.IsOptimizedWithProfile() && (JitConfig.JitConsumeProfileForCasts() != 0)) + // Since the fallback is cold, recalculate the likelihoods + for (int i = 0; i < numExactClasses; i++) { - const int ilOffset = (int)castHelper->gtCastHelperILOffset; - likelyClassCount = getLikelyClasses(likelyClasses, MAX_GDV_TYPE_CHECKS, comp->fgPgoSchema, - comp->fgPgoSchemaCount, comp->fgPgoData, ilOffset); + likelihoods[i] = 100 / numExactClasses; + // E.g. 3 classes - 33%,33%,33% } - if (likelyClassCount != 0) - { -#ifdef DEBUG - // Print all the candidates and their likelihoods to the log - for (UINT32 i = 0; i < likelyClassCount; i++) - { - const char* className = comp->eeGetClassName((CORINFO_CLASS_HANDLE)likelyClasses[i].handle); - JITDUMP(" %u) %p (%s) [likelihood:%u%%]\n", i + 1, likelyClasses[i].handle, className, - likelyClasses[i].likelihood); - } - - // Optional stress mode to pick a random known class, rather than - // the most likely known class. - if (JitConfig.JitRandomGuardedDevirtualization() != 0) - { - // Reuse the random inliner's random state. - CLRRandom* const random = comp->impInlineRoot()->m_inlineStrategy->GetRandom( - JitConfig.JitRandomGuardedDevirtualization()); - unsigned index = static_cast(random->Next(static_cast(likelyClassCount))); - - likelyClasses[0].likelihood = 100; - likelyClasses[0].handle = likelyClasses[index].handle; - } -#endif - - // if there is a dominating candidate with >= 50% likelihood, use it - const unsigned likelihoodMinThreshold = 50; - if (likelyClasses[0].likelihood < likelihoodMinThreshold) - { - JITDUMP("Likely class likelihood is below %u%% - bail out.\n", likelihoodMinThreshold); - return NO_CLASS_HANDLE; - } - - *likelihood = likelyClasses[0].likelihood; - result = (CORINFO_CLASS_HANDLE)likelyClasses[0].handle; - - // Validate static profile data - if ((comp->info.compCompHnd->getClassAttribs(result) & - (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != 0) - { - // Possible scenario: someone changed Foo to be an interface/abstract class/static class, - // but static profile data still reports it as a normal likely class. - JITDUMP("Likely class is abstract/interface - bail out (stale PGO data?).\n"); - return NO_CLASS_HANDLE; - } - } - // - // 4) Last chance: let's try to speculate! - // - else if (helper == CORINFO_HELP_CHKCASTINTERFACE) - { - // Nothing to speculate here, e.g. (IDisposable)obj - return NO_CLASS_HANDLE; - } - else if (helper == CORINFO_HELP_CHKCASTARRAY) - { - // CHKCASTARRAY against exact classes is already handled above, so it's not exact here. - // - // (int[])obj - can we use int[] as a guess? No! It's an overhead if obj is uint[] - // or any int-backed enum - // - return NO_CLASS_HANDLE; - } - else if (helper == CORINFO_HELP_CHKCASTCLASS) - { - // CHKCASTCLASS against exact classes is already handled above, so it's not exact here. - // - // let's use castToCls as a guess, we might regress some cases, but at least we know that unrelated - // types are going to throw InvalidCastException, so we can assume the overhead happens rarely. - result = castToCls; - } - else if (helper == CORINFO_HELP_CHKCASTANY) - { - // Same as CORINFO_HELP_CHKCASTCLASS above, the only difference - let's check castToCls for - // being non-abstract and non-interface first as it makes no sense to speculate on those. - if ((comp->info.compCompHnd->getClassAttribs(castToCls) & - (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != 0) - { - return NO_CLASS_HANDLE; - } - result = castToCls; - } - else if (helper == CORINFO_HELP_ISINSTANCEOFINTERFACE) - { - // Nothing to speculate here, e.g. obj is IDisposable - return NO_CLASS_HANDLE; - } - else if (helper == CORINFO_HELP_ISINSTANCEOFARRAY) - { - // ISINSTANCEOFARRAY against exact classes is already handled above, so it's not exact here. - // - // obj is int[] - can we use int[] as a guess? No! It's an overhead if obj is uint[] - // or any int-backed enum[] - return NO_CLASS_HANDLE; - } - else if (helper == CORINFO_HELP_ISINSTANCEOFCLASS) + if (numExactClasses == 1) { - // ISINSTANCEOFCLASS against exact classes is already handled above, so it's not exact here. - // - // obj is MyClass - can we use MyClass as a guess? No! It's an overhead for any other type except - // MyClass and its subclasses - chances of hitting that overhead are too high. - // - return NO_CLASS_HANDLE; - } - else if (helper == CORINFO_HELP_ISINSTANCEOFANY) - { - // ditto + type variance, etc. - return NO_CLASS_HANDLE; + // Update the common denominator class to be more exact + // since the fallback always throws, and we have just one possible candidate. + *commonCls = exactClasses[0]; } - else + } + else if ((helper == CORINFO_HELP_ISINSTANCEOFINTERFACE) || (helper == CORINFO_HELP_ISINSTANCEOFCLASS)) + { + // Fallback for isinst simply returns null here + *typeCheckFailed = TypeCheckFailedAction::ReturnNull; + + if (numExactClasses == 1) { - unreached(); + // Update the common denominator class to be more exact + // since the fallback is just null, and we have just one possible candidate. + *commonCls = exactClasses[0]; } } + return numExactClasses; } - if (result == NO_CLASS_HANDLE) - { - // TODO-InlineCast: null coming from PGO data could be a hint for us to only expand the null check - return NO_CLASS_HANDLE; - } + // + // 3) Consult with PGO data + // + CORINFO_CLASS_HANDLE likelyClasses[MAX_CAST_GUESSES] = {}; + unsigned likelyLikelihoods[MAX_CAST_GUESSES] = {}; + unsigned likelyClassCount = + GetLikelyClassesForCast(comp, (int)castHelper->gtCastHelperILOffset, likelyClasses, likelyLikelihoods); - const TypeCompareState castResult = comp->info.compCompHnd->compareTypesForCast(result, castToCls); - if (castResult == TypeCompareState::May) + if (likelyClassCount > 0) { - // TODO-InlineCast: do we need to check for May here? Conservatively assume that we do. - JITDUMP("compareTypesForCast returned May for this candidate\n"); - return NO_CLASS_HANDLE; - } - else if (castResult == TypeCompareState::Must) - { - // return actual object on successful type check - *typeCheckPassed = TypeCheckPassedAction::ReturnObj; - } - else if (castResult == TypeCompareState::MustNot) - { - // Our likely candidate never passes the type check (may happen with PGO-driven expansion), - if (!isCastClass) + // if there is a dominating candidate with >= 50% likelihood, use it + // TODO-InlineCast: support multiple candidates, for now always pick the first one + const unsigned likelihoodMinThreshold = 50; + if (likelyLikelihoods[0] < likelihoodMinThreshold) { - // return null on successful type check - *typeCheckPassed = TypeCheckPassedAction::ReturnNull; + JITDUMP("Likely class likelihood is below %u%% - bail out.\n", likelihoodMinThreshold); + return 0; } - else + + likelihoods[0] = likelyLikelihoods[0]; + candidates[0] = likelyClasses[0]; + + // We don't fully trust PGO data, so let's check it via compareTypesForCast + const TypeCompareState castResult = comp->info.compCompHnd->compareTypesForCast(candidates[0], castToCls); + if (castResult == TypeCompareState::May) + { + // TODO-InlineCast: do we need to check for May here? Conservatively assume that we do. + JITDUMP("compareTypesForCast returned May for this candidate\n"); + return 0; + } + if (castResult == TypeCompareState::Must) + { + // return actual object on successful type check + *typeCheckPassed = TypeCheckPassedAction::ReturnObj; + return 1; + } + if (castResult == TypeCompareState::MustNot) { + // Our likely candidate never passes the type check (may happen with PGO-driven expansion), + if (!isCastClass) + { + // return null on successful type check + *typeCheckPassed = TypeCheckPassedAction::ReturnNull; + return 1; + } // give up on castclass - it's going to throw InvalidCastException anyway - return NO_CLASS_HANDLE; + return 0; } } - else - { - unreached(); - } - if ((helper == CORINFO_HELP_CHKCASTCLASS) && (result == castToCls) && - (*typeCheckFailed == TypeCheckFailedAction::CallHelper)) + // + // 4) Last chance: let's try to speculate! + // + switch (helper) { - // A small optimization - use a slightly faster fallback which assumes that we've already checked - // for null and for castToCls itself so it won't do it again. - *typeCheckFailed = TypeCheckFailedAction::CallHelper_Specialized; - } + case CORINFO_HELP_CHKCASTINTERFACE: + // Nothing to speculate here, e.g. (IDisposable)obj + return 0; - assert(result != NO_CLASS_HANDLE); - return result; + case CORINFO_HELP_CHKCASTARRAY: + // CHKCASTARRAY against exact classes is already handled above, so it's not exact here. + // + // (int[])obj - can we use int[] as a guess? No! It's an overhead if obj is uint[] + // or any int-backed enum + return 0; + + case CORINFO_HELP_CHKCASTCLASS: + // CHKCASTCLASS against exact classes is already handled above, so it's not exact here. + // + // let's use castToCls as a guess, we might regress some cases, but at least we know that unrelated + // types are going to throw InvalidCastException, so we can assume the overhead happens rarely. + candidates[0] = castToCls; + // 50% chance of successful type check (speculative guess) + likelihoods[0] = 50; + // + // A small optimization - use a slightly faster fallback which assumes that we've already checked + // for null and for castToCls itself, so it won't do it again. + *typeCheckFailed = TypeCheckFailedAction::CallHelper_Specialized; + return 1; + + case CORINFO_HELP_CHKCASTANY: + // Same as CORINFO_HELP_CHKCASTCLASS above, the only difference - let's check castToCls for + // being non-abstract and non-interface first as it makes no sense to speculate on those. + if ((comp->info.compCompHnd->getClassAttribs(castToCls) & (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != + 0) + { + return 0; + } + candidates[0] = castToCls; + // 50% chance of successful type check (speculative guess) + likelihoods[0] = 50; + return 1; + + case CORINFO_HELP_ISINSTANCEOFINTERFACE: + // Nothing to speculate here, e.g. obj is IDisposable + return 0; + + case CORINFO_HELP_ISINSTANCEOFARRAY: + // ISINSTANCEOFARRAY against exact classes is already handled above, so it's not exact here. + // + // obj is int[] - can we use int[] as a guess? No! It's an overhead if obj is uint[] + // or any int-backed enum[] + return 0; + + case CORINFO_HELP_ISINSTANCEOFCLASS: + // ISINSTANCEOFCLASS against exact classes is already handled above, so it's not exact here. + // + // obj is MyClass - can we use MyClass as a guess? No! It's an overhead for any other type except + // MyClass and its subclasses - chances of hitting that overhead are too high. + // + return 0; + + case CORINFO_HELP_ISINSTANCEOFANY: + // ditto + type variance, etc. + return 0; + + default: + unreached(); + } } //------------------------------------------------------------------------------ @@ -2187,13 +2252,15 @@ static CORINFO_CLASS_HANDLE PickCandidateForTypeCheck(Compiler* com // bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, GenTreeCall* call) { - unsigned likelihood; TypeCheckFailedAction typeCheckFailedAction; TypeCheckPassedAction typeCheckPassedAction; CORINFO_CLASS_HANDLE commonCls; - CORINFO_CLASS_HANDLE expectedExactCls = - PickCandidateForTypeCheck(this, call, &commonCls, &likelihood, &typeCheckFailedAction, &typeCheckPassedAction); - if (expectedExactCls == NO_CLASS_HANDLE) + CORINFO_CLASS_HANDLE expectedExactClasses[MAX_CAST_GUESSES] = {}; + unsigned likelihoods[MAX_CAST_GUESSES] = {}; + + const int numOfCandidates = PickCandidatesForTypeCheck(this, call, expectedExactClasses, &commonCls, likelihoods, + &typeCheckFailedAction, &typeCheckPassedAction); + if (numOfCandidates == 0) { return false; } @@ -2208,7 +2275,12 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, BasicBlock* firstBb; BasicBlock* lastBb; const unsigned tmpNum = SplitAtTreeAndReplaceItWithLocal(this, block, stmt, call, &firstBb, &lastBb); - lvaSetClass(tmpNum, commonCls); + + // TODO-InlineCast: we can't set tmp's class because it's assigned to obj before we can make any assumptions + // we need to slightly reshape the expansion to make it work. Although, it's possible that there is no value + // in class in this late phase. + // lvaSetClass(tmpNum, commonCls); + GenTree* tmpNode = gtNewLclvNode(tmpNum, call->TypeGet()); *pBlock = lastBb; @@ -2226,6 +2298,8 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, // if (tmp->pMT == likelyCls) // goto typeCheckSucceedBb; // + // < there can be multiple typeCheckBbs > + // // fallbackBb (BBJ_ALWAYS): [weight: or 0] // tmp = helper_call(expectedCls, obj); // goto lastBb; @@ -2255,13 +2329,20 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, gtSetStmtInfo(assignTmp); fgSetStmtSeq(assignTmp); - // Block 2: typeCheckBb + // Block 2: typeCheckBb(s) // TODO-InlineCast: if likelyCls == expectedCls we can consider saving to a local to re-use. - GenTree* likelyClsNode = gtNewIconEmbClsHndNode(expectedExactCls); - GenTree* mtCheck = gtNewOperNode(GT_EQ, TYP_INT, gtNewMethodTableLookup(gtCloneExpr(tmpNode)), likelyClsNode); - mtCheck->gtFlags |= GTF_RELOP_JMP_USED; - GenTree* jtrue = gtNewOperNode(GT_JTRUE, TYP_VOID, mtCheck); - BasicBlock* typeCheckBb = fgNewBBFromTreeAfter(BBJ_COND, nullcheckBb, jtrue, debugInfo, lastBb, true); + + BasicBlock* typeChecksBbs[MAX_CAST_GUESSES] = {}; + BasicBlock* lastTypeCheckBb = nullcheckBb; + for (int candidateId = 0; candidateId < numOfCandidates; candidateId++) + { + GenTree* likelyClsNode = gtNewIconEmbClsHndNode(expectedExactClasses[candidateId]); + GenTree* mtCheck = gtNewOperNode(GT_EQ, TYP_INT, gtNewMethodTableLookup(gtCloneExpr(tmpNode)), likelyClsNode); + mtCheck->gtFlags |= GTF_RELOP_JMP_USED; + GenTree* jtrue = gtNewOperNode(GT_JTRUE, TYP_VOID, mtCheck); + typeChecksBbs[candidateId] = fgNewBBFromTreeAfter(BBJ_COND, lastTypeCheckBb, jtrue, debugInfo, lastBb, true); + lastTypeCheckBb = typeChecksBbs[candidateId]; + } // Block 3: fallbackBb BasicBlock* fallbackBb; @@ -2269,13 +2350,13 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, { // fallback call is used only to throw InvalidCastException call->gtCallMoreFlags |= GTF_CALL_M_DOES_NOT_RETURN; - fallbackBb = fgNewBBFromTreeAfter(BBJ_THROW, typeCheckBb, call, debugInfo, nullptr, true); + fallbackBb = fgNewBBFromTreeAfter(BBJ_THROW, lastTypeCheckBb, call, debugInfo, nullptr, true); } else if (typeCheckFailedAction == TypeCheckFailedAction::ReturnNull) { // if fallback call is not needed, we just assign null to tmp GenTree* fallbackTree = gtNewTempStore(tmpNum, gtNewNull()); - fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, typeCheckBb, fallbackTree, debugInfo, lastBb, true); + fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, lastTypeCheckBb, fallbackTree, debugInfo, lastBb, true); } else { @@ -2286,7 +2367,7 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, call->gtCallMethHnd = eeFindHelper(CORINFO_HELP_CHKCASTCLASS_SPECIAL); } GenTree* fallbackTree = gtNewTempStore(tmpNum, call); - fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, typeCheckBb, fallbackTree, debugInfo, lastBb, true); + fallbackBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, lastTypeCheckBb, fallbackTree, debugInfo, lastBb, true); } // Block 4: typeCheckSucceedBb @@ -2309,16 +2390,37 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, // firstBb->SetTarget(nullcheckBb); nullcheckBb->SetTrueTarget(lastBb); - nullcheckBb->SetFalseTarget(typeCheckBb); - typeCheckBb->SetTrueTarget(typeCheckSucceedBb); - typeCheckBb->SetFalseTarget(fallbackBb); + nullcheckBb->SetFalseTarget(typeChecksBbs[0]); + + // Tricky case - wire up multiple type check blocks (in most cases there is only one) + for (int candidateId = 0; candidateId < numOfCandidates; candidateId++) + { + BasicBlock* curTypeCheckBb = typeChecksBbs[candidateId]; + + // All type checks jump straight to the typeCheckSucceedBb on success + curTypeCheckBb->SetTrueTarget(typeCheckSucceedBb); + fgAddRefPred(typeCheckSucceedBb, curTypeCheckBb); + + // or ... + if (candidateId == numOfCandidates - 1) + { + // ... jump to the fallbackBb on last type check's failure + curTypeCheckBb->SetFalseTarget(fallbackBb); + fgAddRefPred(fallbackBb, curTypeCheckBb); + } + else + { + // ... jump to the next type check on failure + curTypeCheckBb->SetFalseTarget(typeChecksBbs[candidateId + 1]); + fgAddRefPred(typeChecksBbs[candidateId + 1], curTypeCheckBb); + } + } + fgRemoveRefPred(lastBb, firstBb); fgAddRefPred(nullcheckBb, firstBb); - fgAddRefPred(typeCheckBb, nullcheckBb); + fgAddRefPred(typeChecksBbs[0], nullcheckBb); fgAddRefPred(lastBb, nullcheckBb); - fgAddRefPred(fallbackBb, typeCheckBb); fgAddRefPred(lastBb, typeCheckSucceedBb); - fgAddRefPred(typeCheckSucceedBb, typeCheckBb); if (typeCheckFailedAction != TypeCheckFailedAction::CallHelper_AlwaysThrows) { // if fallbackBb is BBJ_THROW then it has no successors @@ -2327,13 +2429,28 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, // // Re-distribute weights - // We assume obj is 50%/50% null/not-null (TODO-InlineCast: rely on PGO) - // and rely on profile for the slow path. // nullcheckBb->inheritWeight(firstBb); - typeCheckBb->inheritWeightPercentage(nullcheckBb, 50); - fallbackBb->inheritWeightPercentage(typeCheckBb, fallbackBb->KindIs(BBJ_THROW) ? 0 : 100 - likelihood); - typeCheckSucceedBb->inheritWeightPercentage(typeCheckBb, likelihood); + unsigned totalLikelihood = 0; + for (int candidateId = 0; candidateId < numOfCandidates; candidateId++) + { + unsigned likelihood = likelihoods[candidateId]; + BasicBlock* curTypeCheckBb = typeChecksBbs[candidateId]; + if (candidateId == 0) + { + // We assume obj is 50%/50% null/not-null (TODO-InlineCast: rely on PGO) + // and rely on profile for the slow path. + curTypeCheckBb->inheritWeightPercentage(nullcheckBb, 50); + } + else + { + BasicBlock* prevTypeCheckBb = typeChecksBbs[candidateId - 1]; + curTypeCheckBb->inheritWeightPercentage(prevTypeCheckBb, likelihood); + } + totalLikelihood += likelihood; + } + fallbackBb->inheritWeightPercentage(lastTypeCheckBb, fallbackBb->KindIs(BBJ_THROW) ? 0 : 100 - totalLikelihood); + typeCheckSucceedBb->inheritWeightPercentage(typeChecksBbs[0], totalLikelihood); lastBb->inheritWeight(firstBb); // @@ -2342,7 +2459,7 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, assert(BasicBlock::sameEHRegion(firstBb, lastBb)); assert(BasicBlock::sameEHRegion(firstBb, nullcheckBb)); assert(BasicBlock::sameEHRegion(firstBb, fallbackBb)); - assert(BasicBlock::sameEHRegion(firstBb, typeCheckBb)); + assert(BasicBlock::sameEHRegion(firstBb, lastTypeCheckBb)); // Bonus step: merge prevBb with nullcheckBb as they are likely to be mergeable if (fgCanCompactBlocks(firstBb, nullcheckBb)) diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index 205fca7a584a33..fda2230eb93d0f 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -5460,6 +5460,8 @@ GenTree* Compiler::impCastClassOrIsInstToTree( shouldExpandInline = isCastClass && isClassExact; } + shouldExpandInline = false; // CI test + // Pessimistically assume the jit cannot expand this as an inline test bool canExpandInline = false; bool reversedMTCheck = false; From 96e061bc26a2f1845da41a01b22b5a717add3cea Mon Sep 17 00:00:00 2001 From: EgorBo Date: Wed, 31 Jan 2024 17:46:10 +0100 Subject: [PATCH 05/10] Clean up --- src/coreclr/jit/helperexpansion.cpp | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index c80a4f75dd8e40..cf21b27dcd802a 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1896,15 +1896,16 @@ static int GetLikelyClassesForCast(Compiler* comp, } //------------------------------------------------------------------------------ -// PickCandidatesForTypeCheck: picks a class(es) to use as a fast type check against +// PickCandidatesForTypeCheck: picks classes to use as fast type checks against // the object being casted. The function also defines the strategy to follow -// if the type check fails or passes. +// if the type checks fail or pass. // // Arguments: // comp - Compiler instance // castHelper - Cast helper call to expand +// candidates - [out] Classes (guesses) to use in the fast path (up to MAX_CAST_GUESSES) // commonCls - [out] Common denominator class for the fast and the fallback paths. -// likelihood - [out] Likelihood of successful type check [0..100] +// likelihoods - [out] Likelihoods of successful type checks [0..100] // typeCheckFailed - [out] Action to perform if the type check fails // typeCheckPassed - [out] Action to perform if the type check passes // @@ -2000,7 +2001,7 @@ static int PickCandidatesForTypeCheck(Compiler* comp, // NOTE: only 2) supports multiple candidates at the moment. // - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// // 1) If "cast to" class is already exact we can go ahead and make some decisions // const bool isCastToExact = comp->info.compCompHnd->isExactType(castToCls); @@ -2049,13 +2050,12 @@ static int PickCandidatesForTypeCheck(Compiler* comp, return 1; } - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// // 2) If VM can tell us the exact class for this "cast to" class - use it. // Just make sure the class is truly exact. // - // Let's re-use the same threshold as for the GDV expansion on how many - // guesses we can make. + // Let's re-use GDV's threshold on how many guesses we can make. const int maxTypeChecks = min(comp->getGDVMaxTypeChecks(), MAX_CAST_GUESSES); CORINFO_CLASS_HANDLE exactClasses[MAX_CAST_GUESSES] = {}; @@ -2063,6 +2063,15 @@ static int PickCandidatesForTypeCheck(Compiler* comp, bool allTrulyExact = true; for (int i = 0; i < numExactClasses; i++) { + // TODO-InlineCast: we shouldn't need isExactType check, otherwise we skip cases like this: + // + // if (obj is IMyInterface) { ... } + // + // class MyClass : IMyInterface + // class MySubClass : MyClass + // + // (and both classes are the only ones implementing the interface) + // if (!comp->info.compCompHnd->isExactType(exactClasses[i])) { allTrulyExact = false; @@ -2117,7 +2126,7 @@ static int PickCandidatesForTypeCheck(Compiler* comp, return numExactClasses; } - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// // 3) Consult with PGO data // CORINFO_CLASS_HANDLE likelyClasses[MAX_CAST_GUESSES] = {}; @@ -2167,8 +2176,8 @@ static int PickCandidatesForTypeCheck(Compiler* comp, } } - // - // 4) Last chance: let's try to speculate! + ///////////////////////////////////////////////////////////////////////////////////////////////////// + // 4) Last chance: speculative guesses // switch (helper) { From 90c03f617f9eee442b7e6a03a0f593332f352417 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Wed, 31 Jan 2024 17:50:44 +0100 Subject: [PATCH 06/10] revert unrelated changes --- src/coreclr/jit/helperexpansion.cpp | 203 ++++++++++++++++------------ 1 file changed, 117 insertions(+), 86 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index cf21b27dcd802a..1fd1e31859e72c 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -571,28 +571,31 @@ bool Compiler::fgExpandThreadLocalAccessForCallNativeAOT(BasicBlock** pBlock, St newFirstStmt = newFirstStmt->GetNextStmt(); } - if (TargetOS::IsWindows) - { #ifdef TARGET_64BIT - // prevBb (BBJ_NONE): [weight: 1.0] - // ... - // - // tlsRootNullCondBB (BBJ_COND): [weight: 1.0] - // fastPathValue = [tlsRootAddress] - // if (fastPathValue != nullptr) - // goto fastPathBb; - // - // fallbackBb (BBJ_ALWAYS): [weight: 0] - // tlsRoot = HelperCall(); - // goto block; - // - // fastPathBb(BBJ_ALWAYS): [weight: 1.0] - // tlsRoot = fastPathValue; - // - // block (...): [weight: 1.0] - // use(tlsRoot); - // ... + // prevBb (BBJ_NONE): [weight: 1.0] + // ... + // + // tlsRootNullCondBB (BBJ_COND): [weight: 1.0] + // fastPathValue = [tlsRootAddress] + // if (fastPathValue != nullptr) + // goto fastPathBb; + // + // fallbackBb (BBJ_ALWAYS): [weight: 0] + // tlsRoot = HelperCall(); + // goto block; + // + // fastPathBb(BBJ_ALWAYS): [weight: 1.0] + // tlsRoot = fastPathValue; + // + // block (...): [weight: 1.0] + // use(tlsRoot); + // ... + + GenTree* tlsRootAddr = nullptr; + CORINFO_CONST_LOOKUP tlsRootObject = threadStaticInfo.tlsRootObject; + if (TargetOS::IsWindows) + { // Mark this ICON as a TLS_HDL, codegen will use FS:[cns] or GS:[cns] GenTree* tlsValue = gtNewIconHandleNode(threadStaticInfo.offsetOfThreadLocalStoragePointer, GTF_ICON_TLS_HDL); tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT); @@ -609,100 +612,128 @@ bool Compiler::fgExpandThreadLocalAccessForCallNativeAOT(BasicBlock** pBlock, St // Base of coreclr's thread local storage tlsValue = gtNewIndir(TYP_I_IMPL, tlsValue, GTF_IND_NONFAULTING | GTF_IND_INVARIANT); - CORINFO_CONST_LOOKUP tlsRootObject = threadStaticInfo.tlsRootObject; - // This resolves to an offset which is TYP_INT GenTree* tlsRootOffset = gtNewIconNode((size_t)tlsRootObject.handle, TYP_INT); tlsRootOffset->gtFlags |= GTF_ICON_SECREL_OFFSET; // Add the tlsValue and tlsRootOffset to produce tlsRootAddr. - GenTree* tlsRootAddr = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsValue, tlsRootOffset); + tlsRootAddr = gtNewOperNode(GT_ADD, TYP_I_IMPL, tlsValue, tlsRootOffset); + } + else if (TargetOS::IsUnix) + { + // Code sequence to access thread local variable on linux/x64: + // data16 + // lea rdi, 0x7FE5C418CD28 ; tlsRootObject + // data16 data16 + // call _tls_get_addr + // + // This sequence along with `data16` prefix is expected by the linker so it + // will patch these with TLS access. + GenTree* tls_get_addr_val = + gtNewIconHandleNode((size_t)threadStaticInfo.tlsGetAddrFtnPtr.handle, GTF_ICON_FTN_ADDR); + tls_get_addr_val->SetContained(); + + // GenTreeCall* tlsRefCall = gtNewCallNode(CT_ tls_get_addr_val, TYP_I_IMPL); + GenTreeCall* tlsRefCall = gtNewIndCallNode(tls_get_addr_val, TYP_I_IMPL); + tlsRefCall->gtFlags |= GTF_TLS_GET_ADDR; + // // + + // This is an indirect call which takes an argument. + // Populate and set the ABI appropriately. + assert(tlsRootObject.handle != 0); + GenTree* tlsArg = gtNewIconNode((size_t)tlsRootObject.handle, TYP_I_IMPL); + tlsArg->gtFlags |= GTF_ICON_TLSGD_OFFSET; + tlsRefCall->gtArgs.PushBack(this, NewCallArg::Primitive(tlsArg)); + + fgMorphArgs(tlsRefCall); + + tlsRefCall->gtFlags |= GTF_EXCEPT | (tls_get_addr_val->gtFlags & GTF_GLOB_EFFECT); + tlsRootAddr = tlsRefCall; + } + else + { + unreached(); + } - // Cache the TlsRootAddr value - unsigned tlsRootAddrLclNum = lvaGrabTemp(true DEBUGARG("TlsRootAddr access")); - lvaTable[tlsRootAddrLclNum].lvType = TYP_I_IMPL; - GenTree* tlsRootAddrDef = gtNewStoreLclVarNode(tlsRootAddrLclNum, tlsRootAddr); - GenTree* tlsRootAddrUse = gtNewLclVarNode(tlsRootAddrLclNum); + // Cache the TlsRootAddr value + unsigned tlsRootAddrLclNum = lvaGrabTemp(true DEBUGARG("TlsRootAddr access")); + lvaTable[tlsRootAddrLclNum].lvType = TYP_I_IMPL; + GenTree* tlsRootAddrDef = gtNewStoreLclVarNode(tlsRootAddrLclNum, tlsRootAddr); + GenTree* tlsRootAddrUse = gtNewLclVarNode(tlsRootAddrLclNum); - // See comments near finalLclNum above regarding TYP_REF - GenTree* tlsRootVal = gtNewIndir(TYP_REF, tlsRootAddrUse, GTF_IND_NONFAULTING | GTF_IND_INVARIANT); + // See comments near finalLclNum above regarding TYP_REF + GenTree* tlsRootVal = gtNewIndir(TYP_REF, tlsRootAddrUse, GTF_IND_NONFAULTING | GTF_IND_INVARIANT); - GenTree* tlsRootDef = gtNewStoreLclVarNode(finalLclNum, tlsRootVal); + GenTree* tlsRootDef = gtNewStoreLclVarNode(finalLclNum, tlsRootVal); - GenTree* tlsRootNullCond = gtNewOperNode(GT_NE, TYP_INT, gtCloneExpr(finalLcl), gtNewIconNode(0, TYP_I_IMPL)); - tlsRootNullCond = gtNewOperNode(GT_JTRUE, TYP_VOID, tlsRootNullCond); + GenTree* tlsRootNullCond = gtNewOperNode(GT_NE, TYP_INT, gtCloneExpr(finalLcl), gtNewIconNode(0, TYP_I_IMPL)); + tlsRootNullCond = gtNewOperNode(GT_JTRUE, TYP_VOID, tlsRootNullCond); - // tlsRootNullCondBB - BasicBlock* tlsRootNullCondBB = fgNewBBFromTreeAfter(BBJ_COND, prevBb, tlsRootAddrDef, debugInfo); - fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootNullCond)); - fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootDef)); + // tlsRootNullCondBB + BasicBlock* tlsRootNullCondBB = fgNewBBFromTreeAfter(BBJ_COND, prevBb, tlsRootAddrDef, debugInfo); + fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootNullCond)); + fgInsertStmtAfter(tlsRootNullCondBB, tlsRootNullCondBB->firstStmt(), fgNewStmtFromTree(tlsRootDef)); - CORINFO_CONST_LOOKUP threadStaticSlowHelper = threadStaticInfo.threadStaticBaseSlow; + CORINFO_CONST_LOOKUP threadStaticSlowHelper = threadStaticInfo.threadStaticBaseSlow; - // See comments near finalLclNum above regarding TYP_REF - GenTreeCall* slowHelper = - gtNewIndCallNode(gtNewIconHandleNode((size_t)threadStaticSlowHelper.addr, GTF_ICON_TLS_HDL), TYP_REF); - GenTree* helperArg = gtClone(tlsRootAddrUse); - slowHelper->gtArgs.PushBack(this, NewCallArg::Primitive(helperArg)); - fgMorphArgs(slowHelper); + // See comments near finalLclNum above regarding TYP_REF + GenTreeCall* slowHelper = + gtNewIndCallNode(gtNewIconHandleNode((size_t)threadStaticSlowHelper.addr, GTF_ICON_TLS_HDL), TYP_REF); + GenTree* helperArg = gtClone(tlsRootAddrUse); + slowHelper->gtArgs.PushBack(this, NewCallArg::Primitive(helperArg)); + fgMorphArgs(slowHelper); - // fallbackBb - GenTree* fallbackValueDef = gtNewStoreLclVarNode(finalLclNum, slowHelper); - BasicBlock* fallbackBb = - fgNewBBFromTreeAfter(BBJ_ALWAYS, tlsRootNullCondBB, fallbackValueDef, debugInfo, block, true); + // fallbackBb + GenTree* fallbackValueDef = gtNewStoreLclVarNode(finalLclNum, slowHelper); + BasicBlock* fallbackBb = + fgNewBBFromTreeAfter(BBJ_ALWAYS, tlsRootNullCondBB, fallbackValueDef, debugInfo, block, true); - GenTree* fastPathValueDef = gtNewStoreLclVarNode(finalLclNum, gtCloneExpr(finalLcl)); - BasicBlock* fastPathBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, fallbackBb, fastPathValueDef, debugInfo, block, true); + GenTree* fastPathValueDef = gtNewStoreLclVarNode(finalLclNum, gtCloneExpr(finalLcl)); + BasicBlock* fastPathBb = fgNewBBFromTreeAfter(BBJ_ALWAYS, fallbackBb, fastPathValueDef, debugInfo, block, true); - *callUse = finalLcl; + *callUse = finalLcl; - fgMorphStmtBlockOps(block, stmt); - gtUpdateStmtSideEffects(stmt); + fgMorphStmtBlockOps(block, stmt); + gtUpdateStmtSideEffects(stmt); - // - // Update preds in all new blocks - // - fgAddRefPred(fallbackBb, tlsRootNullCondBB); - fgAddRefPred(fastPathBb, tlsRootNullCondBB); + // + // Update preds in all new blocks + // + fgAddRefPred(fallbackBb, tlsRootNullCondBB); + fgAddRefPred(fastPathBb, tlsRootNullCondBB); - fgAddRefPred(block, fallbackBb); - fgAddRefPred(block, fastPathBb); + fgAddRefPred(block, fallbackBb); + fgAddRefPred(block, fastPathBb); - tlsRootNullCondBB->SetTrueTarget(fastPathBb); - tlsRootNullCondBB->SetFalseTarget(fallbackBb); + tlsRootNullCondBB->SetTrueTarget(fastPathBb); + tlsRootNullCondBB->SetFalseTarget(fallbackBb); - // Inherit the weights - block->inheritWeight(prevBb); - tlsRootNullCondBB->inheritWeight(prevBb); - fastPathBb->inheritWeight(prevBb); + // Inherit the weights + block->inheritWeight(prevBb); + tlsRootNullCondBB->inheritWeight(prevBb); + fastPathBb->inheritWeight(prevBb); - // fallback will just execute first time - fallbackBb->bbSetRunRarely(); + // fallback will just execute first time + fallbackBb->bbSetRunRarely(); - fgRemoveRefPred(block, prevBb); - fgAddRefPred(tlsRootNullCondBB, prevBb); - prevBb->SetTarget(tlsRootNullCondBB); + fgRemoveRefPred(block, prevBb); + fgAddRefPred(tlsRootNullCondBB, prevBb); + prevBb->SetTarget(tlsRootNullCondBB); - // All blocks are expected to be in the same EH region - assert(BasicBlock::sameEHRegion(prevBb, block)); - assert(BasicBlock::sameEHRegion(prevBb, tlsRootNullCondBB)); - assert(BasicBlock::sameEHRegion(prevBb, fastPathBb)); + // All blocks are expected to be in the same EH region + assert(BasicBlock::sameEHRegion(prevBb, block)); + assert(BasicBlock::sameEHRegion(prevBb, tlsRootNullCondBB)); + assert(BasicBlock::sameEHRegion(prevBb, fastPathBb)); - JITDUMP("tlsRootNullCondBB: " FMT_BB "\n", tlsRootNullCondBB->bbNum); - JITDUMP("fallbackBb: " FMT_BB "\n", fallbackBb->bbNum); - JITDUMP("fastPathBb: " FMT_BB "\n", fastPathBb->bbNum); + JITDUMP("tlsRootNullCondBB: " FMT_BB "\n", tlsRootNullCondBB->bbNum); + JITDUMP("fallbackBb: " FMT_BB "\n", fallbackBb->bbNum); + JITDUMP("fastPathBb: " FMT_BB "\n", fastPathBb->bbNum); #else - unreached(); + unreached(); #endif // TARGET_64BIT - return true; - } - else - { - unreached(); - } - return false; + return true; } //------------------------------------------------------------------------------ From 3609ada0b29cd7c3ea66ffe6db69ae86b8b74958 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Wed, 31 Jan 2024 19:50:21 +0100 Subject: [PATCH 07/10] Fix compilation --- src/coreclr/jit/helperexpansion.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index 1fd1e31859e72c..179d0e85d1b983 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1902,7 +1902,7 @@ static int GetLikelyClassesForCast(Compiler* comp, if (cls != NO_CLASS_HANDLE) { // Validate static profile data - if ((comp->info.compCompHnd->getClassAttribs(candidates[0]) & + if ((comp->info.compCompHnd->getClassAttribs(cls) & (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != 0) { // Possible scenario: someone changed Foo to be an interface/abstract class/static class, From b8344ffe8a563e9c74ee83329eaec1983bf95674 Mon Sep 17 00:00:00 2001 From: EgorBo Date: Wed, 31 Jan 2024 23:38:33 +0100 Subject: [PATCH 08/10] Clean up --- src/coreclr/jit/helperexpansion.cpp | 108 ++++++---------------------- src/coreclr/jit/importercalls.cpp | 40 +++++++++-- 2 files changed, 58 insertions(+), 90 deletions(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index 179d0e85d1b983..fe7bdaba12e483 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1857,75 +1857,6 @@ enum class TypeCheckPassedAction // The actual number of guesses is usually much smaller #define MAX_CAST_GUESSES 8 -//------------------------------------------------------------------------------ -// GetLikelyClassesForCast: returns a list of likely classes for the given cast -// using profile data. -// -// Arguments: -// comp - Compiler instance -// ilOffset - IL offset of the cast -// candidates - [out] Array of likely class handles (up to MAX_CAST_GUESSES) -// likelihoods - [out] Array of their likelihoods [0..100] -// -// Returns: -// Number of likely classes -// -static int GetLikelyClassesForCast(Compiler* comp, - int ilOffset, - CORINFO_CLASS_HANDLE* candidates, - unsigned* likelihoods) -{ - if (!comp->opts.IsOptimizedWithProfile() || (JitConfig.JitConsumeProfileForCasts() == 0)) - { - return 0; - } - - LikelyClassMethodRecord likelyClasses[MAX_CAST_GUESSES]; - unsigned likelyClassCount = getLikelyClasses(likelyClasses, MAX_CAST_GUESSES, comp->fgPgoSchema, - comp->fgPgoSchemaCount, comp->fgPgoData, ilOffset); - - if (likelyClassCount == 0) - { - return 0; - } - - int numberOfCandidates = 0; - for (UINT32 i = 0; i < likelyClassCount; i++) - { -#ifdef DEBUG - const char* className = comp->eeGetClassName((CORINFO_CLASS_HANDLE)likelyClasses[i].handle); - JITDUMP(" %u) %p (%s) [likelihood:%u%%]\n", i + 1, likelyClasses[i].handle, className, - likelyClasses[i].likelihood); -#endif - - CORINFO_CLASS_HANDLE cls = (CORINFO_CLASS_HANDLE)likelyClasses[i].handle; - if (cls != NO_CLASS_HANDLE) - { - // Validate static profile data - if ((comp->info.compCompHnd->getClassAttribs(cls) & - (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != 0) - { - // Possible scenario: someone changed Foo to be an interface/abstract class/static class, - // but static profile data still reports it as a normal likely class. - - // Should we ignore this case and continue with the next likely class? - // Conservatively treat it as compromised profile data and bail out. - return 0; - } - - candidates[numberOfCandidates] = cls; - likelihoods[numberOfCandidates] = likelyClasses[i].likelihood; - numberOfCandidates++; - } - else - { - // TODO-InlineCast: null as a likely class could mean that the object is mostly null, - // but we currently don't take advantage of that. - } - } - return numberOfCandidates; -} - //------------------------------------------------------------------------------ // PickCandidatesForTypeCheck: picks classes to use as fast type checks against // the object being casted. The function also defines the strategy to follow @@ -2020,6 +1951,8 @@ static int PickCandidatesForTypeCheck(Compiler* comp, // in most cases it's just the generic "cast to" class. *commonCls = castToCls; + const unsigned isAbstractFlags = CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT; + // // Now we need to figure out what classes to use for the fast path, we have 4 options: // 1) If "cast to" class is already exact we can go ahead and make some decisions @@ -2034,7 +1967,8 @@ static int PickCandidatesForTypeCheck(Compiler* comp, ///////////////////////////////////////////////////////////////////////////////////////////////////// // 1) If "cast to" class is already exact we can go ahead and make some decisions - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// + const bool isCastToExact = comp->info.compCompHnd->isExactType(castToCls); if (isCastToExact && ((helper == CORINFO_HELP_CHKCASTCLASS) || (helper == CORINFO_HELP_CHKCASTARRAY))) { @@ -2084,9 +2018,9 @@ static int PickCandidatesForTypeCheck(Compiler* comp, ///////////////////////////////////////////////////////////////////////////////////////////////////// // 2) If VM can tell us the exact class for this "cast to" class - use it. // Just make sure the class is truly exact. - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// - // Let's re-use GDV's threshold on how many guesses we can make. + // Let's re-use GDV's threshold on how many guesses we can make (can be 3 by default). const int maxTypeChecks = min(comp->getGDVMaxTypeChecks(), MAX_CAST_GUESSES); CORINFO_CLASS_HANDLE exactClasses[MAX_CAST_GUESSES] = {}; @@ -2159,26 +2093,29 @@ static int PickCandidatesForTypeCheck(Compiler* comp, ///////////////////////////////////////////////////////////////////////////////////////////////////// // 3) Consult with PGO data - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// + CORINFO_CLASS_HANDLE likelyClasses[MAX_CAST_GUESSES] = {}; unsigned likelyLikelihoods[MAX_CAST_GUESSES] = {}; - unsigned likelyClassCount = - GetLikelyClassesForCast(comp, (int)castHelper->gtCastHelperILOffset, likelyClasses, likelyLikelihoods); + int likelyClassCount = 0; + comp->pickGDV(castHelper, castHelper->gtCastHelperILOffset, false, likelyClasses, nullptr, &likelyClassCount, + likelihoods); if (likelyClassCount > 0) { - // if there is a dominating candidate with >= 50% likelihood, use it // TODO-InlineCast: support multiple candidates, for now always pick the first one - const unsigned likelihoodMinThreshold = 50; - if (likelyLikelihoods[0] < likelihoodMinThreshold) + // It's already supported, but it requires some careful performance testing to enable. + // + likelihoods[0] = likelyLikelihoods[0]; + candidates[0] = likelyClasses[0]; + + // Protect from stale static PGO data if a candidate becomes abstract/interface + if ((likelyClasses[0] == NO_CLASS_HANDLE) || + (comp->info.compCompHnd->getClassAttribs(likelyClasses[0]) & isAbstractFlags) != 0) { - JITDUMP("Likely class likelihood is below %u%% - bail out.\n", likelihoodMinThreshold); return 0; } - likelihoods[0] = likelyLikelihoods[0]; - candidates[0] = likelyClasses[0]; - // We don't fully trust PGO data, so let's check it via compareTypesForCast const TypeCompareState castResult = comp->info.compCompHnd->compareTypesForCast(candidates[0], castToCls); if (castResult == TypeCompareState::May) @@ -2209,7 +2146,8 @@ static int PickCandidatesForTypeCheck(Compiler* comp, ///////////////////////////////////////////////////////////////////////////////////////////////////// // 4) Last chance: speculative guesses - // + ///////////////////////////////////////////////////////////////////////////////////////////////////// + switch (helper) { case CORINFO_HELP_CHKCASTINTERFACE: @@ -2240,8 +2178,7 @@ static int PickCandidatesForTypeCheck(Compiler* comp, case CORINFO_HELP_CHKCASTANY: // Same as CORINFO_HELP_CHKCASTCLASS above, the only difference - let's check castToCls for // being non-abstract and non-interface first as it makes no sense to speculate on those. - if ((comp->info.compCompHnd->getClassAttribs(castToCls) & (CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT)) != - 0) + if ((comp->info.compCompHnd->getClassAttribs(castToCls) & isAbstractFlags) != 0) { return 0; } @@ -2337,6 +2274,7 @@ bool Compiler::fgLateCastExpansionForCall(BasicBlock** pBlock, Statement* stmt, // typeCheckBb (BBJ_COND): [weight: 0.5] // if (tmp->pMT == likelyCls) // goto typeCheckSucceedBb; + // goto (either next type check or fallbackBb) // // < there can be multiple typeCheckBbs > // diff --git a/src/coreclr/jit/importercalls.cpp b/src/coreclr/jit/importercalls.cpp index a9dee3bf25744a..f491d054aacbb9 100644 --- a/src/coreclr/jit/importercalls.cpp +++ b/src/coreclr/jit/importercalls.cpp @@ -5758,10 +5758,10 @@ void Compiler::addFatPointerCandidate(GenTreeCall* call) } //------------------------------------------------------------------------ -// pickGDV: Use profile information to pick a GDV candidate for a call site. +// pickGDV: Use profile information to pick a GDV/cast type candidate for a call site. // // Arguments: -// call - the call +// call - the call (either virtual or cast helper) // ilOffset - exact IL offset of the call // isInterface - whether or not the call target is defined on an interface // classGuesses - [out] the classes to guess for (mutually exclusive with methodGuess) @@ -5782,7 +5782,7 @@ void Compiler::pickGDV(GenTreeCall* call, const int maxLikelyClasses = MAX_GDV_TYPE_CHECKS; LikelyClassMethodRecord likelyClasses[maxLikelyClasses]; unsigned numberOfClasses = 0; - if (call->IsVirtualStub() || call->IsVirtualVtable()) + if (call->IsVirtualStub() || call->IsVirtualVtable() || call->IsHelperCall()) { numberOfClasses = getLikelyClasses(likelyClasses, maxLikelyClasses, fgPgoSchema, fgPgoSchemaCount, fgPgoData, ilOffset); @@ -5800,6 +5800,7 @@ void Compiler::pickGDV(GenTreeCall* call, // if (!opts.IsReadyToRun() && (call->IsVirtualVtable() || call->IsDelegateInvoke())) { + assert(!call->IsHelperCall()); numberOfMethods = getLikelyMethods(likelyMethods, maxLikelyMethods, fgPgoSchema, fgPgoSchemaCount, fgPgoData, ilOffset); } @@ -5891,6 +5892,7 @@ void Compiler::pickGDV(GenTreeCall* call, } else { + assert(!call->IsHelperCall()); methodGuesses[0] = (CORINFO_METHOD_HANDLE)likelyMethods[index - numberOfClasses].handle; likelihoods[0] = 100; *candidatesCount = 1; @@ -5921,12 +5923,40 @@ void Compiler::pickGDV(GenTreeCall* call, if (maxNumberOfGuesses == 1) { // We're allowed to make only a single guess - it means we want to work only with dominating types - likelihoodThreshold = isInterface ? 25 : 30; + if (call->IsHelperCall()) + { + // Casts. Most casts aren't too expensive + likelihoodThreshold = 50; + } + else if (isInterface) + { + // interface calls + likelihoodThreshold = 25; + } + else + { + // virtual calls + likelihoodThreshold = 30; + } } else if (maxNumberOfGuesses == 2) { // Two guesses - slightly relax the thresholds - likelihoodThreshold = isInterface ? 15 : 20; + if (call->IsHelperCall()) + { + // Casts. Most casts aren't too expensive + likelihoodThreshold = 40; + } + else if (isInterface) + { + // interface calls + likelihoodThreshold = 15; + } + else + { + // virtual calls + likelihoodThreshold = 20; + } } else { From aae43be906e949e92de866932ac20d35721a589e Mon Sep 17 00:00:00 2001 From: Egor Bogatov Date: Thu, 1 Feb 2024 01:58:55 +0100 Subject: [PATCH 09/10] Update importer.cpp --- src/coreclr/jit/importer.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/coreclr/jit/importer.cpp b/src/coreclr/jit/importer.cpp index b59f0871728ee2..a5901e40d721bc 100644 --- a/src/coreclr/jit/importer.cpp +++ b/src/coreclr/jit/importer.cpp @@ -5460,8 +5460,6 @@ GenTree* Compiler::impCastClassOrIsInstToTree( shouldExpandInline = isCastClass && isClassExact; } - shouldExpandInline = false; // CI test - // Pessimistically assume the jit cannot expand this as an inline test bool canExpandInline = false; bool reversedMTCheck = false; From faf6b3f084cad08ab7f94c453096d241980ebe1a Mon Sep 17 00:00:00 2001 From: EgorBo Date: Thu, 1 Feb 2024 23:54:10 +0100 Subject: [PATCH 10/10] Fix diffs --- src/coreclr/jit/helperexpansion.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index fe7bdaba12e483..d9b2b2aa5c5a8c 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -2099,7 +2099,7 @@ static int PickCandidatesForTypeCheck(Compiler* comp, unsigned likelyLikelihoods[MAX_CAST_GUESSES] = {}; int likelyClassCount = 0; comp->pickGDV(castHelper, castHelper->gtCastHelperILOffset, false, likelyClasses, nullptr, &likelyClassCount, - likelihoods); + likelyLikelihoods); if (likelyClassCount > 0) {