diff --git a/src/coreclr/jit/helperexpansion.cpp b/src/coreclr/jit/helperexpansion.cpp index b180a8fd7564e7..d9b2b2aa5c5a8c 100644 --- a/src/coreclr/jit/helperexpansion.cpp +++ b/src/coreclr/jit/helperexpansion.cpp @@ -1853,34 +1853,40 @@ 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 + //------------------------------------------------------------------------------ -// PickCandidateForTypeCheck: picks a class 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 // // 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 @@ -1915,12 +1921,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(); @@ -1931,23 +1934,27 @@ 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; + const unsigned isAbstractFlags = CORINFO_FLG_INTERFACE | CORINFO_FLG_ABSTRACT; + // - // 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 @@ -1955,13 +1962,16 @@ 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[] // @@ -1974,16 +1984,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[] @@ -1994,214 +2009,210 @@ 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 GDV's threshold on how many guesses we can make (can be 3 by default). + 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++) + { + // 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; + 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) - { - // 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) + if (numExactClasses == 1) { - // 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 + ///////////////////////////////////////////////////////////////////////////////////////////////////// - const TypeCompareState castResult = comp->info.compCompHnd->compareTypesForCast(result, 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 NO_CLASS_HANDLE; - } - else if (castResult == TypeCompareState::Must) - { - // return actual object on successful type check - *typeCheckPassed = TypeCheckPassedAction::ReturnObj; - } - else if (castResult == TypeCompareState::MustNot) + CORINFO_CLASS_HANDLE likelyClasses[MAX_CAST_GUESSES] = {}; + unsigned likelyLikelihoods[MAX_CAST_GUESSES] = {}; + int likelyClassCount = 0; + comp->pickGDV(castHelper, castHelper->gtCastHelperILOffset, false, likelyClasses, nullptr, &likelyClassCount, + likelyLikelihoods); + + if (likelyClassCount > 0) { - // Our likely candidate never passes the type check (may happen with PGO-driven expansion), - if (!isCastClass) + // TODO-InlineCast: support multiple candidates, for now always pick the first one + // 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) { - // return null on successful type check - *typeCheckPassed = TypeCheckPassedAction::ReturnNull; + return 0; } - else + + // 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: speculative guesses + ///////////////////////////////////////////////////////////////////////////////////////////////////// + + 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) & isAbstractFlags) != 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(); + } } //------------------------------------------------------------------------------ @@ -2218,13 +2229,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; } @@ -2239,7 +2252,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; @@ -2256,6 +2274,9 @@ 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 > // // fallbackBb (BBJ_ALWAYS): [weight: or 0] // tmp = helper_call(expectedCls, obj); @@ -2286,13 +2307,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; @@ -2300,13 +2328,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 { @@ -2317,7 +2345,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 @@ -2340,16 +2368,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 @@ -2358,13 +2407,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); // @@ -2373,7 +2437,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/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 {