1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
5 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10 XX Imports the given method and converts it to semantic trees XX
12 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
13 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
23 #define Verify(cond, msg) \
28 verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
32 #define VerifyOrReturn(cond, msg) \
37 verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
42 #define VerifyOrReturnSpeculative(cond, msg, speculative) \
56 verRaiseVerifyExceptionIfNeeded(INDEBUG(msg) DEBUGARG(__FILE__) DEBUGARG(__LINE__)); \
62 /*****************************************************************************/
64 void Compiler::impInit()
68 impTreeList = nullptr;
69 impTreeLast = nullptr;
70 impInlinedCodeSize = 0;
74 /*****************************************************************************
76 * Pushes the given tree on the stack.
79 void Compiler::impPushOnStack(GenTreePtr tree, typeInfo ti)
81 /* Check for overflow. If inlining, we may be using a bigger stack */
83 if ((verCurrentState.esStackDepth >= info.compMaxStack) &&
84 (verCurrentState.esStackDepth >= impStkSize || ((compCurBB->bbFlags & BBF_IMPORTED) == 0)))
86 BADCODE("stack overflow");
90 // If we are pushing a struct, make certain we know the precise type!
91 if (tree->TypeGet() == TYP_STRUCT)
93 assert(ti.IsType(TI_STRUCT));
94 CORINFO_CLASS_HANDLE clsHnd = ti.GetClassHandle();
95 assert(clsHnd != NO_CLASS_HANDLE);
98 if (tiVerificationNeeded && !ti.IsDead())
100 assert(typeInfo::AreEquivalent(NormaliseForStack(ti), ti)); // types are normalized
102 // The ti type is consistent with the tree type.
105 // On 64-bit systems, nodes whose "proper" type is "native int" get labeled TYP_LONG.
106 // In the verification type system, we always transform "native int" to "TI_INT".
107 // Ideally, we would keep track of which nodes labeled "TYP_LONG" are really "native int", but
108 // attempts to do that have proved too difficult. Instead, we'll assume that in checks like this,
109 // when there's a mismatch, it's because of this reason -- the typeInfo::AreEquivalentModuloNativeInt
110 // method used in the last disjunct allows exactly this mismatch.
111 assert(ti.IsDead() || ti.IsByRef() && (tree->TypeGet() == TYP_I_IMPL || tree->TypeGet() == TYP_BYREF) ||
112 ti.IsUnboxedGenericTypeVar() && tree->TypeGet() == TYP_REF ||
113 ti.IsObjRef() && tree->TypeGet() == TYP_REF || ti.IsMethod() && tree->TypeGet() == TYP_I_IMPL ||
114 ti.IsType(TI_STRUCT) && tree->TypeGet() != TYP_REF ||
115 typeInfo::AreEquivalentModuloNativeInt(NormaliseForStack(ti),
116 NormaliseForStack(typeInfo(tree->TypeGet()))));
118 // If it is a struct type, make certain we normalized the primitive types
119 assert(!ti.IsType(TI_STRUCT) ||
120 info.compCompHnd->getTypeForPrimitiveValueClass(ti.GetClassHandle()) == CORINFO_TYPE_UNDEF);
124 if (VERBOSE && tiVerificationNeeded)
127 printf(TI_DUMP_PADDING);
128 printf("About to push to stack: ");
131 #endif // VERBOSE_VERIFY
135 verCurrentState.esStack[verCurrentState.esStackDepth].seTypeInfo = ti;
136 verCurrentState.esStack[verCurrentState.esStackDepth++].val = tree;
138 if ((tree->gtType == TYP_LONG) && (compLongUsed == false))
142 else if (((tree->gtType == TYP_FLOAT) || (tree->gtType == TYP_DOUBLE)) && (compFloatingPointUsed == false))
144 compFloatingPointUsed = true;
148 /******************************************************************************/
149 // used in the inliner, where we can assume typesafe code. please don't use in the importer!!
150 inline void Compiler::impPushOnStackNoType(GenTreePtr tree)
152 assert(verCurrentState.esStackDepth < impStkSize);
153 INDEBUG(verCurrentState.esStack[verCurrentState.esStackDepth].seTypeInfo = typeInfo());
154 verCurrentState.esStack[verCurrentState.esStackDepth++].val = tree;
156 if ((tree->gtType == TYP_LONG) && (compLongUsed == false))
160 else if (((tree->gtType == TYP_FLOAT) || (tree->gtType == TYP_DOUBLE)) && (compFloatingPointUsed == false))
162 compFloatingPointUsed = true;
166 inline void Compiler::impPushNullObjRefOnStack()
168 impPushOnStack(gtNewIconNode(0, TYP_REF), typeInfo(TI_NULL));
171 // This method gets called when we run into unverifiable code
172 // (and we are verifying the method)
174 inline void Compiler::verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* msg) DEBUGARG(const char* file)
175 DEBUGARG(unsigned line))
177 // Remember that the code is not verifiable
178 // Note that the method may yet pass canSkipMethodVerification(),
179 // and so the presence of unverifiable code may not be an issue.
180 tiIsVerifiableCode = FALSE;
183 const char* tail = strrchr(file, '\\');
189 if (JitConfig.JitBreakOnUnsafeCode())
191 assert(!"Unsafe code detected");
195 JITLOG((LL_INFO10000, "Detected unsafe code: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
196 msg, info.compFullName, impCurOpcName, impCurOpcOffs));
198 if (verNeedsVerification() || compIsForImportOnly())
200 JITLOG((LL_ERROR, "Verification failure: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
201 msg, info.compFullName, impCurOpcName, impCurOpcOffs));
202 verRaiseVerifyException(INDEBUG(msg) DEBUGARG(file) DEBUGARG(line));
206 inline void DECLSPEC_NORETURN Compiler::verRaiseVerifyException(INDEBUG(const char* msg) DEBUGARG(const char* file)
207 DEBUGARG(unsigned line))
209 JITLOG((LL_ERROR, "Verification failure: %s:%d : %s, while compiling %s opcode %s, IL offset %x\n", file, line,
210 msg, info.compFullName, impCurOpcName, impCurOpcOffs));
213 // BreakIfDebuggerPresent();
214 if (getBreakOnBadCode())
216 assert(!"Typechecking error");
220 RaiseException(SEH_VERIFICATION_EXCEPTION, EXCEPTION_NONCONTINUABLE, 0, nullptr);
224 // helper function that will tell us if the IL instruction at the addr passed
225 // by param consumes an address at the top of the stack. We use it to save
227 bool Compiler::impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle)
229 assert(!compIsForInlining());
233 opcode = (OPCODE)getU1LittleEndian(codeAddr);
237 // case CEE_LDFLDA: We're taking this one out as if you have a sequence
243 // of a primitivelike struct, you end up after morphing with addr of a local
244 // that's not marked as addrtaken, which is wrong. Also ldflda is usually used
245 // for structs that contain other structs, which isnt a case we handle very
246 // well now for other reasons.
250 // We won't collapse small fields. This is probably not the right place to have this
251 // check, but we're only using the function for this purpose, and is easy to factor
252 // out if we need to do so.
254 CORINFO_RESOLVED_TOKEN resolvedToken;
255 impResolveToken(codeAddr + sizeof(__int8), &resolvedToken, CORINFO_TOKENKIND_Field);
257 CORINFO_CLASS_HANDLE clsHnd;
258 var_types lclTyp = JITtype2varType(info.compCompHnd->getFieldType(resolvedToken.hField, &clsHnd));
260 // Preserve 'small' int types
261 if (lclTyp > TYP_INT)
263 lclTyp = genActualType(lclTyp);
266 if (varTypeIsSmall(lclTyp))
280 void Compiler::impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind)
282 pResolvedToken->tokenContext = impTokenLookupContextHandle;
283 pResolvedToken->tokenScope = info.compScopeHnd;
284 pResolvedToken->token = getU4LittleEndian(addr);
285 pResolvedToken->tokenType = kind;
287 if (!tiVerificationNeeded)
289 info.compCompHnd->resolveToken(pResolvedToken);
293 Verify(eeTryResolveToken(pResolvedToken), "Token resolution failed");
297 /*****************************************************************************
299 * Pop one tree from the stack.
302 StackEntry Compiler::impPopStack()
304 if (verCurrentState.esStackDepth == 0)
306 BADCODE("stack underflow");
311 if (VERBOSE && tiVerificationNeeded)
314 printf(TI_DUMP_PADDING);
315 printf("About to pop from the stack: ");
316 const typeInfo& ti = verCurrentState.esStack[verCurrentState.esStackDepth - 1].seTypeInfo;
319 #endif // VERBOSE_VERIFY
322 return verCurrentState.esStack[--verCurrentState.esStackDepth];
325 StackEntry Compiler::impPopStack(CORINFO_CLASS_HANDLE& structType)
327 StackEntry ret = impPopStack();
328 structType = verCurrentState.esStack[verCurrentState.esStackDepth].seTypeInfo.GetClassHandle();
332 GenTreePtr Compiler::impPopStack(typeInfo& ti)
334 StackEntry ret = impPopStack();
339 /*****************************************************************************
341 * Peep at n'th (0-based) tree on the top of the stack.
344 StackEntry& Compiler::impStackTop(unsigned n)
346 if (verCurrentState.esStackDepth <= n)
348 BADCODE("stack underflow");
351 return verCurrentState.esStack[verCurrentState.esStackDepth - n - 1];
353 /*****************************************************************************
354 * Some of the trees are spilled specially. While unspilling them, or
355 * making a copy, these need to be handled specially. The function
356 * enumerates the operators possible after spilling.
359 #ifdef DEBUG // only used in asserts
360 static bool impValidSpilledStackEntry(GenTreePtr tree)
362 if (tree->gtOper == GT_LCL_VAR)
367 if (tree->OperIsConst())
376 /*****************************************************************************
378 * The following logic is used to save/restore stack contents.
379 * If 'copy' is true, then we make a copy of the trees on the stack. These
380 * have to all be cloneable/spilled values.
383 void Compiler::impSaveStackState(SavedStack* savePtr, bool copy)
385 savePtr->ssDepth = verCurrentState.esStackDepth;
387 if (verCurrentState.esStackDepth)
389 savePtr->ssTrees = new (this, CMK_ImpStack) StackEntry[verCurrentState.esStackDepth];
390 size_t saveSize = verCurrentState.esStackDepth * sizeof(*savePtr->ssTrees);
394 StackEntry* table = savePtr->ssTrees;
396 /* Make a fresh copy of all the stack entries */
398 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++, table++)
400 table->seTypeInfo = verCurrentState.esStack[level].seTypeInfo;
401 GenTreePtr tree = verCurrentState.esStack[level].val;
403 assert(impValidSpilledStackEntry(tree));
405 switch (tree->gtOper)
412 table->val = gtCloneExpr(tree);
416 assert(!"Bad oper - Not covered by impValidSpilledStackEntry()");
423 memcpy(savePtr->ssTrees, verCurrentState.esStack, saveSize);
428 void Compiler::impRestoreStackState(SavedStack* savePtr)
430 verCurrentState.esStackDepth = savePtr->ssDepth;
432 if (verCurrentState.esStackDepth)
434 memcpy(verCurrentState.esStack, savePtr->ssTrees,
435 verCurrentState.esStackDepth * sizeof(*verCurrentState.esStack));
439 /*****************************************************************************
441 * Get the tree list started for a new basic block.
443 inline void Compiler::impBeginTreeList()
445 assert(impTreeList == nullptr && impTreeLast == nullptr);
447 impTreeList = impTreeLast = new (this, GT_BEG_STMTS) GenTree(GT_BEG_STMTS, TYP_VOID);
450 /*****************************************************************************
452 * Store the given start and end stmt in the given basic block. This is
453 * mostly called by impEndTreeList(BasicBlock *block). It is called
454 * directly only for handling CEE_LEAVEs out of finally-protected try's.
457 inline void Compiler::impEndTreeList(BasicBlock* block, GenTreePtr firstStmt, GenTreePtr lastStmt)
459 assert(firstStmt->gtOper == GT_STMT);
460 assert(lastStmt->gtOper == GT_STMT);
462 /* Make the list circular, so that we can easily walk it backwards */
464 firstStmt->gtPrev = lastStmt;
466 /* Store the tree list in the basic block */
468 block->bbTreeList = firstStmt;
470 /* The block should not already be marked as imported */
471 assert((block->bbFlags & BBF_IMPORTED) == 0);
473 block->bbFlags |= BBF_IMPORTED;
476 /*****************************************************************************
478 * Store the current tree list in the given basic block.
481 inline void Compiler::impEndTreeList(BasicBlock* block)
483 assert(impTreeList->gtOper == GT_BEG_STMTS);
485 GenTreePtr firstTree = impTreeList->gtNext;
489 /* The block should not already be marked as imported */
490 assert((block->bbFlags & BBF_IMPORTED) == 0);
492 // Empty block. Just mark it as imported
493 block->bbFlags |= BBF_IMPORTED;
497 // Ignore the GT_BEG_STMTS
498 assert(firstTree->gtPrev == impTreeList);
500 impEndTreeList(block, firstTree, impTreeLast);
504 if (impLastILoffsStmt != nullptr)
506 impLastILoffsStmt->gtStmt.gtStmtLastILoffs = compIsForInlining() ? BAD_IL_OFFSET : impCurOpcOffs;
507 impLastILoffsStmt = nullptr;
510 impTreeList = impTreeLast = nullptr;
514 /*****************************************************************************
516 * Check that storing the given tree doesnt mess up the semantic order. Note
517 * that this has only limited value as we can only check [0..chkLevel).
520 inline void Compiler::impAppendStmtCheck(GenTreePtr stmt, unsigned chkLevel)
525 assert(stmt->gtOper == GT_STMT);
527 if (chkLevel == (unsigned)CHECK_SPILL_ALL)
529 chkLevel = verCurrentState.esStackDepth;
532 if (verCurrentState.esStackDepth == 0 || chkLevel == 0 || chkLevel == (unsigned)CHECK_SPILL_NONE)
537 GenTreePtr tree = stmt->gtStmt.gtStmtExpr;
539 // Calls can only be appended if there are no GTF_GLOB_EFFECT on the stack
541 if (tree->gtFlags & GTF_CALL)
543 for (unsigned level = 0; level < chkLevel; level++)
545 assert((verCurrentState.esStack[level].val->gtFlags & GTF_GLOB_EFFECT) == 0);
549 if (tree->gtOper == GT_ASG)
551 // For an assignment to a local variable, all references of that
552 // variable have to be spilled. If it is aliased, all calls and
553 // indirect accesses have to be spilled
555 if (tree->gtOp.gtOp1->gtOper == GT_LCL_VAR)
557 unsigned lclNum = tree->gtOp.gtOp1->gtLclVarCommon.gtLclNum;
558 for (unsigned level = 0; level < chkLevel; level++)
560 assert(!gtHasRef(verCurrentState.esStack[level].val, lclNum, false));
561 assert(!lvaTable[lclNum].lvAddrExposed ||
562 (verCurrentState.esStack[level].val->gtFlags & GTF_SIDE_EFFECT) == 0);
566 // If the access may be to global memory, all side effects have to be spilled.
568 else if (tree->gtOp.gtOp1->gtFlags & GTF_GLOB_REF)
570 for (unsigned level = 0; level < chkLevel; level++)
572 assert((verCurrentState.esStack[level].val->gtFlags & GTF_GLOB_REF) == 0);
579 /*****************************************************************************
581 * Append the given GT_STMT node to the current block's tree list.
582 * [0..chkLevel) is the portion of the stack which we will check for
583 * interference with stmt and spill if needed.
586 inline void Compiler::impAppendStmt(GenTreePtr stmt, unsigned chkLevel)
588 assert(stmt->gtOper == GT_STMT);
589 noway_assert(impTreeLast != nullptr);
591 /* If the statement being appended has any side-effects, check the stack
592 to see if anything needs to be spilled to preserve correct ordering. */
594 GenTreePtr expr = stmt->gtStmt.gtStmtExpr;
595 unsigned flags = expr->gtFlags & GTF_GLOB_EFFECT;
597 // Assignment to (unaliased) locals don't count as a side-effect as
598 // we handle them specially using impSpillLclRefs(). Temp locals should
601 if ((expr->gtOper == GT_ASG) && (expr->gtOp.gtOp1->gtOper == GT_LCL_VAR) &&
602 !(expr->gtOp.gtOp1->gtFlags & GTF_GLOB_REF) && !gtHasLocalsWithAddrOp(expr->gtOp.gtOp2))
604 unsigned op2Flags = expr->gtOp.gtOp2->gtFlags & GTF_GLOB_EFFECT;
605 assert(flags == (op2Flags | GTF_ASG));
609 if (chkLevel == (unsigned)CHECK_SPILL_ALL)
611 chkLevel = verCurrentState.esStackDepth;
614 if (chkLevel && chkLevel != (unsigned)CHECK_SPILL_NONE)
616 assert(chkLevel <= verCurrentState.esStackDepth);
620 // If there is a call, we have to spill global refs
621 bool spillGlobEffects = (flags & GTF_CALL) ? true : false;
623 if (expr->gtOper == GT_ASG)
625 GenTree* lhs = expr->gtGetOp1();
626 // If we are assigning to a global ref, we have to spill global refs on stack.
627 // TODO-1stClassStructs: Previously, spillGlobEffects was set to true for
628 // GT_INITBLK and GT_COPYBLK, but this is overly conservative, and should be
629 // revisited. (Note that it was NOT set to true for GT_COPYOBJ.)
630 if (!expr->OperIsBlkOp())
632 // If we are assigning to a global ref, we have to spill global refs on stack
633 if ((lhs->gtFlags & GTF_GLOB_REF) != 0)
635 spillGlobEffects = true;
638 else if ((lhs->OperIsBlk() && !lhs->AsBlk()->HasGCPtr()) ||
639 ((lhs->OperGet() == GT_LCL_VAR) &&
640 (lvaTable[lhs->AsLclVarCommon()->gtLclNum].lvStructGcCount == 0)))
642 spillGlobEffects = true;
646 impSpillSideEffects(spillGlobEffects, chkLevel DEBUGARG("impAppendStmt"));
650 impSpillSpecialSideEff();
654 impAppendStmtCheck(stmt, chkLevel);
656 /* Point 'prev' at the previous node, so that we can walk backwards */
658 stmt->gtPrev = impTreeLast;
660 /* Append the expression statement to the list */
662 impTreeLast->gtNext = stmt;
666 impMarkContiguousSIMDFieldAssignments(stmt);
669 /* Once we set impCurStmtOffs in an appended tree, we are ready to
670 report the following offsets. So reset impCurStmtOffs */
672 if (impTreeLast->gtStmt.gtStmtILoffsx == impCurStmtOffs)
674 impCurStmtOffsSet(BAD_IL_OFFSET);
678 if (impLastILoffsStmt == nullptr)
680 impLastILoffsStmt = stmt;
691 /*****************************************************************************
693 * Insert the given GT_STMT "stmt" before GT_STMT "stmtBefore"
696 inline void Compiler::impInsertStmtBefore(GenTreePtr stmt, GenTreePtr stmtBefore)
698 assert(stmt->gtOper == GT_STMT);
699 assert(stmtBefore->gtOper == GT_STMT);
701 GenTreePtr stmtPrev = stmtBefore->gtPrev;
702 stmt->gtPrev = stmtPrev;
703 stmt->gtNext = stmtBefore;
704 stmtPrev->gtNext = stmt;
705 stmtBefore->gtPrev = stmt;
708 /*****************************************************************************
710 * Append the given expression tree to the current block's tree list.
711 * Return the newly created statement.
714 GenTreePtr Compiler::impAppendTree(GenTreePtr tree, unsigned chkLevel, IL_OFFSETX offset)
718 /* Allocate an 'expression statement' node */
720 GenTreePtr expr = gtNewStmt(tree, offset);
722 /* Append the statement to the current block's stmt list */
724 impAppendStmt(expr, chkLevel);
729 /*****************************************************************************
731 * Insert the given exression tree before GT_STMT "stmtBefore"
734 void Compiler::impInsertTreeBefore(GenTreePtr tree, IL_OFFSETX offset, GenTreePtr stmtBefore)
736 assert(stmtBefore->gtOper == GT_STMT);
738 /* Allocate an 'expression statement' node */
740 GenTreePtr expr = gtNewStmt(tree, offset);
742 /* Append the statement to the current block's stmt list */
744 impInsertStmtBefore(expr, stmtBefore);
747 /*****************************************************************************
749 * Append an assignment of the given value to a temp to the current tree list.
750 * curLevel is the stack level for which the spill to the temp is being done.
753 void Compiler::impAssignTempGen(unsigned tmp,
756 GenTreePtr* pAfterStmt, /* = NULL */
757 IL_OFFSETX ilOffset, /* = BAD_IL_OFFSET */
758 BasicBlock* block /* = NULL */
761 GenTreePtr asg = gtNewTempAssign(tmp, val);
763 if (!asg->IsNothingNode())
767 GenTreePtr asgStmt = gtNewStmt(asg, ilOffset);
768 *pAfterStmt = fgInsertStmtAfter(block, *pAfterStmt, asgStmt);
772 impAppendTree(asg, curLevel, impCurStmtOffs);
777 /*****************************************************************************
778 * same as above, but handle the valueclass case too
781 void Compiler::impAssignTempGen(unsigned tmpNum,
783 CORINFO_CLASS_HANDLE structType,
785 GenTreePtr* pAfterStmt, /* = NULL */
786 IL_OFFSETX ilOffset, /* = BAD_IL_OFFSET */
787 BasicBlock* block /* = NULL */
792 if (varTypeIsStruct(val))
794 assert(tmpNum < lvaCount);
795 assert(structType != NO_CLASS_HANDLE);
797 // if the method is non-verifiable the assert is not true
798 // so at least ignore it in the case when verification is turned on
799 // since any block that tries to use the temp would have failed verification.
800 var_types varType = lvaTable[tmpNum].lvType;
801 assert(tiVerificationNeeded || varType == TYP_UNDEF || varTypeIsStruct(varType));
802 lvaSetStruct(tmpNum, structType, false);
804 // Now, set the type of the struct value. Note that lvaSetStruct may modify the type
805 // of the lclVar to a specialized type (e.g. TYP_SIMD), based on the handle (structType)
806 // that has been passed in for the value being assigned to the temp, in which case we
807 // need to set 'val' to that same type.
808 // Note also that if we always normalized the types of any node that might be a struct
809 // type, this would not be necessary - but that requires additional JIT/EE interface
810 // calls that may not actually be required - e.g. if we only access a field of a struct.
812 val->gtType = lvaTable[tmpNum].lvType;
814 GenTreePtr dst = gtNewLclvNode(tmpNum, val->gtType);
815 asg = impAssignStruct(dst, val, structType, curLevel, pAfterStmt, block);
819 asg = gtNewTempAssign(tmpNum, val);
822 if (!asg->IsNothingNode())
826 GenTreePtr asgStmt = gtNewStmt(asg, ilOffset);
827 *pAfterStmt = fgInsertStmtAfter(block, *pAfterStmt, asgStmt);
831 impAppendTree(asg, curLevel, impCurStmtOffs);
836 /*****************************************************************************
838 * Pop the given number of values from the stack and return a list node with
840 * The 'prefixTree' argument may optionally contain an argument
841 * list that is prepended to the list returned from this function.
843 * The notion of prepended is a bit misleading in that the list is backwards
844 * from the way I would expect: The first element popped is at the end of
845 * the returned list, and prefixTree is 'before' that, meaning closer to
846 * the end of the list. To get to prefixTree, you have to walk to the
849 * For ARG_ORDER_R2L prefixTree is only used to insert extra arguments, as
850 * such we reverse its meaning such that returnValue has a reversed
851 * prefixTree at the head of the list.
854 GenTreeArgList* Compiler::impPopList(unsigned count,
856 CORINFO_SIG_INFO* sig,
857 GenTreeArgList* prefixTree)
859 assert(sig == nullptr || count == sig->numArgs);
862 CORINFO_CLASS_HANDLE structType;
863 GenTreeArgList* treeList;
865 if (Target::g_tgtArgOrder == Target::ARG_ORDER_R2L)
871 treeList = prefixTree;
876 StackEntry se = impPopStack();
877 typeInfo ti = se.seTypeInfo;
878 GenTreePtr temp = se.val;
880 if (varTypeIsStruct(temp))
882 // Morph trees that aren't already OBJs or MKREFANY to be OBJs
883 assert(ti.IsType(TI_STRUCT));
884 structType = ti.GetClassHandleForValueClass();
885 temp = impNormStructVal(temp, structType, (unsigned)CHECK_SPILL_ALL);
888 /* NOTE: we defer bashing the type for I_IMPL to fgMorphArgs */
889 flags |= temp->gtFlags;
890 treeList = gtNewListNode(temp, treeList);
897 if (sig->retTypeSigClass != nullptr && sig->retType != CORINFO_TYPE_CLASS &&
898 sig->retType != CORINFO_TYPE_BYREF && sig->retType != CORINFO_TYPE_PTR && sig->retType != CORINFO_TYPE_VAR)
900 // Make sure that all valuetypes (including enums) that we push are loaded.
901 // This is to guarantee that if a GC is triggerred from the prestub of this methods,
902 // all valuetypes in the method signature are already loaded.
903 // We need to be able to find the size of the valuetypes, but we cannot
904 // do a class-load from within GC.
905 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(sig->retTypeSigClass);
908 CORINFO_ARG_LIST_HANDLE argLst = sig->args;
909 CORINFO_CLASS_HANDLE argClass;
910 CORINFO_CLASS_HANDLE argRealClass;
911 GenTreeArgList* args;
914 for (args = treeList, count = sig->numArgs; count > 0; args = args->Rest(), count--)
916 PREFIX_ASSUME(args != nullptr);
918 CorInfoType corType = strip(info.compCompHnd->getArgType(sig, argLst, &argClass));
920 // insert implied casts (from float to double or double to float)
922 if (corType == CORINFO_TYPE_DOUBLE && args->Current()->TypeGet() == TYP_FLOAT)
924 args->Current() = gtNewCastNode(TYP_DOUBLE, args->Current(), TYP_DOUBLE);
926 else if (corType == CORINFO_TYPE_FLOAT && args->Current()->TypeGet() == TYP_DOUBLE)
928 args->Current() = gtNewCastNode(TYP_FLOAT, args->Current(), TYP_FLOAT);
931 // insert any widening or narrowing casts for backwards compatibility
933 args->Current() = impImplicitIorI4Cast(args->Current(), JITtype2varType(corType));
935 if (corType != CORINFO_TYPE_CLASS && corType != CORINFO_TYPE_BYREF && corType != CORINFO_TYPE_PTR &&
936 corType != CORINFO_TYPE_VAR && (argRealClass = info.compCompHnd->getArgClass(sig, argLst)) != nullptr)
938 // Everett MC++ could generate IL with a mismatched valuetypes. It used to work with Everett JIT,
939 // but it stopped working in Whidbey when we have started passing simple valuetypes as underlying
941 // We will try to adjust for this case here to avoid breaking customers code (see VSW 485789 for
943 if (corType == CORINFO_TYPE_VALUECLASS && !varTypeIsStruct(args->Current()))
945 args->Current() = impNormStructVal(args->Current(), argRealClass, (unsigned)CHECK_SPILL_ALL, true);
948 // Make sure that all valuetypes (including enums) that we push are loaded.
949 // This is to guarantee that if a GC is triggered from the prestub of this methods,
950 // all valuetypes in the method signature are already loaded.
951 // We need to be able to find the size of the valuetypes, but we cannot
952 // do a class-load from within GC.
953 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(argRealClass);
956 argLst = info.compCompHnd->getArgNext(argLst);
960 if (Target::g_tgtArgOrder == Target::ARG_ORDER_R2L)
962 // Prepend the prefixTree
964 // Simple in-place reversal to place treeList
965 // at the end of a reversed prefixTree
966 while (prefixTree != nullptr)
968 GenTreeArgList* next = prefixTree->Rest();
969 prefixTree->Rest() = treeList;
970 treeList = prefixTree;
977 /*****************************************************************************
979 * Pop the given number of values from the stack in reverse order (STDCALL/CDECL etc.)
980 * The first "skipReverseCount" items are not reversed.
983 GenTreeArgList* Compiler::impPopRevList(unsigned count,
985 CORINFO_SIG_INFO* sig,
986 unsigned skipReverseCount)
989 assert(skipReverseCount <= count);
991 GenTreeArgList* list = impPopList(count, flagsPtr, sig);
994 if (list == nullptr || skipReverseCount == count)
999 GenTreeArgList* ptr = nullptr; // Initialized to the first node that needs to be reversed
1000 GenTreeArgList* lastSkipNode = nullptr; // Will be set to the last node that does not need to be reversed
1002 if (skipReverseCount == 0)
1008 lastSkipNode = list;
1009 // Get to the first node that needs to be reversed
1010 for (unsigned i = 0; i < skipReverseCount - 1; i++)
1012 lastSkipNode = lastSkipNode->Rest();
1015 PREFIX_ASSUME(lastSkipNode != nullptr);
1016 ptr = lastSkipNode->Rest();
1019 GenTreeArgList* reversedList = nullptr;
1023 GenTreeArgList* tmp = ptr->Rest();
1024 ptr->Rest() = reversedList;
1027 } while (ptr != nullptr);
1029 if (skipReverseCount)
1031 lastSkipNode->Rest() = reversedList;
1036 return reversedList;
1040 /*****************************************************************************
1041 Assign (copy) the structure from 'src' to 'dest'. The structure is a value
1042 class of type 'clsHnd'. It returns the tree that should be appended to the
1043 statement list that represents the assignment.
1044 Temp assignments may be appended to impTreeList if spilling is necessary.
1045 curLevel is the stack level for which a spill may be being done.
1048 GenTreePtr Compiler::impAssignStruct(GenTreePtr dest,
1050 CORINFO_CLASS_HANDLE structHnd,
1052 GenTreePtr* pAfterStmt, /* = NULL */
1053 BasicBlock* block /* = NULL */
1056 assert(varTypeIsStruct(dest));
1058 while (dest->gtOper == GT_COMMA)
1060 assert(varTypeIsStruct(dest->gtOp.gtOp2)); // Second thing is the struct
1062 // Append all the op1 of GT_COMMA trees before we evaluate op2 of the GT_COMMA tree.
1065 *pAfterStmt = fgInsertStmtAfter(block, *pAfterStmt, gtNewStmt(dest->gtOp.gtOp1, impCurStmtOffs));
1069 impAppendTree(dest->gtOp.gtOp1, curLevel, impCurStmtOffs); // do the side effect
1072 // set dest to the second thing
1073 dest = dest->gtOp.gtOp2;
1076 assert(dest->gtOper == GT_LCL_VAR || dest->gtOper == GT_RETURN || dest->gtOper == GT_FIELD ||
1077 dest->gtOper == GT_IND || dest->gtOper == GT_OBJ || dest->gtOper == GT_INDEX);
1079 if (dest->OperGet() == GT_LCL_VAR && src->OperGet() == GT_LCL_VAR &&
1080 src->gtLclVarCommon.gtLclNum == dest->gtLclVarCommon.gtLclNum)
1083 return gtNewNothingNode();
1086 // TODO-1stClassStructs: Avoid creating an address if it is not needed,
1087 // or re-creating a Blk node if it is.
1088 GenTreePtr destAddr;
1090 if (dest->gtOper == GT_IND || dest->OperIsBlk())
1092 destAddr = dest->gtOp.gtOp1;
1096 destAddr = gtNewOperNode(GT_ADDR, TYP_BYREF, dest);
1099 return (impAssignStructPtr(destAddr, src, structHnd, curLevel, pAfterStmt, block));
1102 /*****************************************************************************/
1104 GenTreePtr Compiler::impAssignStructPtr(GenTreePtr destAddr,
1106 CORINFO_CLASS_HANDLE structHnd,
1108 GenTreePtr* pAfterStmt, /* = NULL */
1109 BasicBlock* block /* = NULL */
1113 GenTreePtr dest = nullptr;
1114 unsigned destFlags = 0;
1116 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1117 assert(varTypeIsStruct(src) || (src->gtOper == GT_ADDR && src->TypeGet() == TYP_BYREF));
1118 // TODO-ARM-BUG: Does ARM need this?
1119 // TODO-ARM64-BUG: Does ARM64 need this?
1120 assert(src->gtOper == GT_LCL_VAR || src->gtOper == GT_FIELD || src->gtOper == GT_IND || src->gtOper == GT_OBJ ||
1121 src->gtOper == GT_CALL || src->gtOper == GT_MKREFANY || src->gtOper == GT_RET_EXPR ||
1122 src->gtOper == GT_COMMA || src->gtOper == GT_ADDR ||
1123 (src->TypeGet() != TYP_STRUCT && (GenTree::OperIsSIMD(src->gtOper) || src->gtOper == GT_LCL_FLD)));
1124 #else // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1125 assert(varTypeIsStruct(src));
1127 assert(src->gtOper == GT_LCL_VAR || src->gtOper == GT_FIELD || src->gtOper == GT_IND || src->gtOper == GT_OBJ ||
1128 src->gtOper == GT_CALL || src->gtOper == GT_MKREFANY || src->gtOper == GT_RET_EXPR ||
1129 src->gtOper == GT_COMMA ||
1130 (src->TypeGet() != TYP_STRUCT && (GenTree::OperIsSIMD(src->gtOper) || src->gtOper == GT_LCL_FLD)));
1131 #endif // !defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1132 if (destAddr->OperGet() == GT_ADDR)
1134 GenTree* destNode = destAddr->gtGetOp1();
1135 // If the actual destination is a local (for non-LEGACY_BACKEND), or already a block node, or is a node that
1136 // will be morphed, don't insert an OBJ(ADDR).
1137 if (destNode->gtOper == GT_INDEX || destNode->OperIsBlk()
1138 #ifndef LEGACY_BACKEND
1139 || ((destNode->OperGet() == GT_LCL_VAR) && (destNode->TypeGet() == src->TypeGet()))
1140 #endif // !LEGACY_BACKEND
1145 destType = destNode->TypeGet();
1149 destType = src->TypeGet();
1152 var_types asgType = src->TypeGet();
1154 if (src->gtOper == GT_CALL)
1156 if (src->AsCall()->TreatAsHasRetBufArg(this))
1158 // Case of call returning a struct via hidden retbuf arg
1160 // insert the return value buffer into the argument list as first byref parameter
1161 src->gtCall.gtCallArgs = gtNewListNode(destAddr, src->gtCall.gtCallArgs);
1163 // now returns void, not a struct
1164 src->gtType = TYP_VOID;
1166 // return the morphed call node
1171 // Case of call returning a struct in one or more registers.
1173 var_types returnType = (var_types)src->gtCall.gtReturnType;
1175 // We won't use a return buffer, so change the type of src->gtType to 'returnType'
1176 src->gtType = genActualType(returnType);
1178 // First we try to change this to "LclVar/LclFld = call"
1180 if ((destAddr->gtOper == GT_ADDR) && (destAddr->gtOp.gtOp1->gtOper == GT_LCL_VAR))
1182 // If it is a multi-reg struct return, don't change the oper to GT_LCL_FLD.
1183 // That is, the IR will be of the form lclVar = call for multi-reg return
1185 GenTreePtr lcl = destAddr->gtOp.gtOp1;
1186 if (src->AsCall()->HasMultiRegRetVal())
1188 // Mark the struct LclVar as used in a MultiReg return context
1189 // which currently makes it non promotable.
1190 // TODO-1stClassStructs: Eliminate this pessimization when we can more generally
1191 // handle multireg returns.
1192 lcl->gtFlags |= GTF_DONT_CSE;
1193 lvaTable[lcl->gtLclVarCommon.gtLclNum].lvIsMultiRegRet = true;
1195 else // The call result is not a multireg return
1197 // We change this to a GT_LCL_FLD (from a GT_ADDR of a GT_LCL_VAR)
1198 lcl->ChangeOper(GT_LCL_FLD);
1199 fgLclFldAssign(lcl->gtLclVarCommon.gtLclNum);
1202 lcl->gtType = src->gtType;
1203 asgType = src->gtType;
1206 #if defined(_TARGET_ARM_)
1207 // TODO-Cleanup: This should have been taken care of in the above HasMultiRegRetVal() case,
1208 // but that method has not been updadted to include ARM.
1209 impMarkLclDstNotPromotable(lcl->gtLclVarCommon.gtLclNum, src, structHnd);
1210 lcl->gtFlags |= GTF_DONT_CSE;
1211 #elif defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1212 // Not allowed for FEATURE_CORCLR which is the only SKU available for System V OSs.
1213 assert(!src->gtCall.IsVarargs() && "varargs not allowed for System V OSs.");
1215 // Make the struct non promotable. The eightbytes could contain multiple fields.
1216 // TODO-1stClassStructs: Eliminate this pessimization when we can more generally
1217 // handle multireg returns.
1218 // TODO-Cleanup: Why is this needed here? This seems that it will set this even for
1219 // non-multireg returns.
1220 lcl->gtFlags |= GTF_DONT_CSE;
1221 lvaTable[lcl->gtLclVarCommon.gtLclNum].lvIsMultiRegRet = true;
1224 else // we don't have a GT_ADDR of a GT_LCL_VAR
1226 // !!! The destination could be on stack. !!!
1227 // This flag will let us choose the correct write barrier.
1228 asgType = returnType;
1229 destFlags = GTF_IND_TGTANYWHERE;
1233 else if (src->gtOper == GT_RET_EXPR)
1235 GenTreePtr call = src->gtRetExpr.gtInlineCandidate;
1236 noway_assert(call->gtOper == GT_CALL);
1238 if (call->AsCall()->HasRetBufArg())
1240 // insert the return value buffer into the argument list as first byref parameter
1241 call->gtCall.gtCallArgs = gtNewListNode(destAddr, call->gtCall.gtCallArgs);
1243 // now returns void, not a struct
1244 src->gtType = TYP_VOID;
1245 call->gtType = TYP_VOID;
1247 // We already have appended the write to 'dest' GT_CALL's args
1248 // So now we just return an empty node (pruning the GT_RET_EXPR)
1253 // Case of inline method returning a struct in one or more registers.
1255 var_types returnType = (var_types)call->gtCall.gtReturnType;
1257 // We won't need a return buffer
1258 asgType = returnType;
1259 src->gtType = genActualType(returnType);
1260 call->gtType = src->gtType;
1262 // If we've changed the type, and it no longer matches a local destination,
1263 // we must use an indirection.
1264 if ((dest != nullptr) && (dest->OperGet() == GT_LCL_VAR) && (dest->TypeGet() != asgType))
1269 // !!! The destination could be on stack. !!!
1270 // This flag will let us choose the correct write barrier.
1271 destFlags = GTF_IND_TGTANYWHERE;
1274 else if (src->OperIsBlk())
1276 asgType = impNormStructType(structHnd);
1277 if (src->gtOper == GT_OBJ)
1279 assert(src->gtObj.gtClass == structHnd);
1282 else if (src->gtOper == GT_INDEX)
1284 asgType = impNormStructType(structHnd);
1285 assert(src->gtIndex.gtStructElemClass == structHnd);
1287 else if (src->gtOper == GT_MKREFANY)
1289 // Since we are assigning the result of a GT_MKREFANY,
1290 // "destAddr" must point to a refany.
1292 GenTreePtr destAddrClone;
1294 impCloneExpr(destAddr, &destAddrClone, structHnd, curLevel, pAfterStmt DEBUGARG("MKREFANY assignment"));
1296 assert(offsetof(CORINFO_RefAny, dataPtr) == 0);
1297 assert(destAddr->gtType == TYP_I_IMPL || destAddr->gtType == TYP_BYREF);
1298 GetZeroOffsetFieldMap()->Set(destAddr, GetFieldSeqStore()->CreateSingleton(GetRefanyDataField()));
1299 GenTreePtr ptrSlot = gtNewOperNode(GT_IND, TYP_I_IMPL, destAddr);
1300 GenTreeIntCon* typeFieldOffset = gtNewIconNode(offsetof(CORINFO_RefAny, type), TYP_I_IMPL);
1301 typeFieldOffset->gtFieldSeq = GetFieldSeqStore()->CreateSingleton(GetRefanyTypeField());
1302 GenTreePtr typeSlot =
1303 gtNewOperNode(GT_IND, TYP_I_IMPL, gtNewOperNode(GT_ADD, destAddr->gtType, destAddrClone, typeFieldOffset));
1305 // append the assign of the pointer value
1306 GenTreePtr asg = gtNewAssignNode(ptrSlot, src->gtOp.gtOp1);
1309 *pAfterStmt = fgInsertStmtAfter(block, *pAfterStmt, gtNewStmt(asg, impCurStmtOffs));
1313 impAppendTree(asg, curLevel, impCurStmtOffs);
1316 // return the assign of the type value, to be appended
1317 return gtNewAssignNode(typeSlot, src->gtOp.gtOp2);
1319 else if (src->gtOper == GT_COMMA)
1321 // The second thing is the struct or its address.
1322 assert(varTypeIsStruct(src->gtOp.gtOp2) || src->gtOp.gtOp2->gtType == TYP_BYREF);
1325 *pAfterStmt = fgInsertStmtAfter(block, *pAfterStmt, gtNewStmt(src->gtOp.gtOp1, impCurStmtOffs));
1329 impAppendTree(src->gtOp.gtOp1, curLevel, impCurStmtOffs); // do the side effect
1332 // Evaluate the second thing using recursion.
1333 return impAssignStructPtr(destAddr, src->gtOp.gtOp2, structHnd, curLevel, pAfterStmt, block);
1335 else if (src->IsLocal())
1337 asgType = src->TypeGet();
1339 else if (asgType == TYP_STRUCT)
1341 asgType = impNormStructType(structHnd);
1342 src->gtType = asgType;
1343 #ifdef LEGACY_BACKEND
1344 if (asgType == TYP_STRUCT)
1346 GenTree* srcAddr = gtNewOperNode(GT_ADDR, TYP_BYREF, src);
1347 src = gtNewOperNode(GT_IND, TYP_STRUCT, srcAddr);
1351 if (dest == nullptr)
1353 // TODO-1stClassStructs: We shouldn't really need a block node as the destination
1354 // if this is a known struct type.
1355 if (asgType == TYP_STRUCT)
1357 dest = gtNewObjNode(structHnd, destAddr);
1358 gtSetObjGcInfo(dest->AsObj());
1359 // Although an obj as a call argument was always assumed to be a globRef
1360 // (which is itself overly conservative), that is not true of the operands
1361 // of a block assignment.
1362 dest->gtFlags &= ~GTF_GLOB_REF;
1363 dest->gtFlags |= (destAddr->gtFlags & GTF_GLOB_REF);
1365 else if (varTypeIsStruct(asgType))
1367 dest = new (this, GT_BLK) GenTreeBlk(GT_BLK, asgType, destAddr, genTypeSize(asgType));
1371 dest = gtNewOperNode(GT_IND, asgType, destAddr);
1376 dest->gtType = asgType;
1379 dest->gtFlags |= destFlags;
1380 destFlags = dest->gtFlags;
1382 // return an assignment node, to be appended
1383 GenTree* asgNode = gtNewAssignNode(dest, src);
1384 gtBlockOpInit(asgNode, dest, src, false);
1386 // TODO-1stClassStructs: Clean up the settings of GTF_DONT_CSE on the lhs
1388 if ((destFlags & GTF_DONT_CSE) == 0)
1390 dest->gtFlags &= ~(GTF_DONT_CSE);
1395 /*****************************************************************************
1396 Given a struct value, and the class handle for that structure, return
1397 the expression for the address for that structure value.
1399 willDeref - does the caller guarantee to dereference the pointer.
1402 GenTreePtr Compiler::impGetStructAddr(GenTreePtr structVal,
1403 CORINFO_CLASS_HANDLE structHnd,
1407 assert(varTypeIsStruct(structVal) || eeIsValueClass(structHnd));
1409 var_types type = structVal->TypeGet();
1411 genTreeOps oper = structVal->gtOper;
1413 if (oper == GT_OBJ && willDeref)
1415 assert(structVal->gtObj.gtClass == structHnd);
1416 return (structVal->gtObj.Addr());
1418 else if (oper == GT_CALL || oper == GT_RET_EXPR || oper == GT_OBJ || oper == GT_MKREFANY)
1420 unsigned tmpNum = lvaGrabTemp(true DEBUGARG("struct address for call/obj"));
1422 impAssignTempGen(tmpNum, structVal, structHnd, curLevel);
1424 // The 'return value' is now the temp itself
1426 type = genActualType(lvaTable[tmpNum].TypeGet());
1427 GenTreePtr temp = gtNewLclvNode(tmpNum, type);
1428 temp = gtNewOperNode(GT_ADDR, TYP_BYREF, temp);
1431 else if (oper == GT_COMMA)
1433 assert(structVal->gtOp.gtOp2->gtType == type); // Second thing is the struct
1435 GenTreePtr oldTreeLast = impTreeLast;
1436 structVal->gtOp.gtOp2 = impGetStructAddr(structVal->gtOp.gtOp2, structHnd, curLevel, willDeref);
1437 structVal->gtType = TYP_BYREF;
1439 if (oldTreeLast != impTreeLast)
1441 // Some temp assignment statement was placed on the statement list
1442 // for Op2, but that would be out of order with op1, so we need to
1443 // spill op1 onto the statement list after whatever was last
1444 // before we recursed on Op2 (i.e. before whatever Op2 appended).
1445 impInsertTreeBefore(structVal->gtOp.gtOp1, impCurStmtOffs, oldTreeLast->gtNext);
1446 structVal->gtOp.gtOp1 = gtNewNothingNode();
1452 return (gtNewOperNode(GT_ADDR, TYP_BYREF, structVal));
1455 //------------------------------------------------------------------------
1456 // impNormStructType: Given a (known to be) struct class handle structHnd, normalize its type,
1457 // and optionally determine the GC layout of the struct.
1460 // structHnd - The class handle for the struct type of interest.
1461 // gcLayout - (optional, default nullptr) - a BYTE pointer, allocated by the caller,
1462 // into which the gcLayout will be written.
1463 // pNumGCVars - (optional, default nullptr) - if non-null, a pointer to an unsigned,
1464 // which will be set to the number of GC fields in the struct.
1465 // pSimdBaseType - (optional, default nullptr) - if non-null, and the struct is a SIMD
1466 // type, set to the SIMD base type
1469 // The JIT type for the struct (e.g. TYP_STRUCT, or TYP_SIMD*).
1470 // The gcLayout will be returned using the pointers provided by the caller, if non-null.
1471 // It may also modify the compFloatingPointUsed flag if the type is a SIMD type.
1474 // The caller must set gcLayout to nullptr OR ensure that it is large enough
1475 // (see ICorStaticInfo::getClassGClayout in corinfo.h).
1478 // Normalizing the type involves examining the struct type to determine if it should
1479 // be modified to one that is handled specially by the JIT, possibly being a candidate
1480 // for full enregistration, e.g. TYP_SIMD16.
1482 var_types Compiler::impNormStructType(CORINFO_CLASS_HANDLE structHnd,
1484 unsigned* pNumGCVars,
1485 var_types* pSimdBaseType)
1487 assert(structHnd != NO_CLASS_HANDLE);
1489 const DWORD structFlags = info.compCompHnd->getClassAttribs(structHnd);
1490 var_types structType = TYP_STRUCT;
1492 // On coreclr the check for GC includes a "may" to account for the special
1493 // ByRef like span structs. The added check for "CONTAINS_STACK_PTR" is the particular bit.
1494 // When this is set the struct will contain a ByRef that could be a GC pointer or a native
1496 const bool mayContainGCPtrs =
1497 ((structFlags & CORINFO_FLG_CONTAINS_STACK_PTR) != 0 || ((structFlags & CORINFO_FLG_CONTAINS_GC_PTR) != 0));
1500 // Check to see if this is a SIMD type.
1501 if (featureSIMD && !mayContainGCPtrs)
1503 unsigned originalSize = info.compCompHnd->getClassSize(structHnd);
1505 if ((originalSize >= minSIMDStructBytes()) && (originalSize <= maxSIMDStructBytes()))
1507 unsigned int sizeBytes;
1508 var_types simdBaseType = getBaseTypeAndSizeOfSIMDType(structHnd, &sizeBytes);
1509 if (simdBaseType != TYP_UNKNOWN)
1511 assert(sizeBytes == originalSize);
1512 structType = getSIMDTypeForSize(sizeBytes);
1513 if (pSimdBaseType != nullptr)
1515 *pSimdBaseType = simdBaseType;
1517 // Also indicate that we use floating point registers.
1518 compFloatingPointUsed = true;
1522 #endif // FEATURE_SIMD
1524 // Fetch GC layout info if requested
1525 if (gcLayout != nullptr)
1527 unsigned numGCVars = info.compCompHnd->getClassGClayout(structHnd, gcLayout);
1529 // Verify that the quick test up above via the class attributes gave a
1530 // safe view of the type's GCness.
1532 // Note there are cases where mayContainGCPtrs is true but getClassGClayout
1533 // does not report any gc fields.
1535 assert(mayContainGCPtrs || (numGCVars == 0));
1537 if (pNumGCVars != nullptr)
1539 *pNumGCVars = numGCVars;
1544 // Can't safely ask for number of GC pointers without also
1545 // asking for layout.
1546 assert(pNumGCVars == nullptr);
1552 //****************************************************************************
1553 // Given TYP_STRUCT value 'structVal', make sure it is 'canonical', that is
1554 // it is either an OBJ or a MKREFANY node, or a node (e.g. GT_INDEX) that will be morphed.
1556 GenTreePtr Compiler::impNormStructVal(GenTreePtr structVal,
1557 CORINFO_CLASS_HANDLE structHnd,
1559 bool forceNormalization /*=false*/)
1561 assert(forceNormalization || varTypeIsStruct(structVal));
1562 assert(structHnd != NO_CLASS_HANDLE);
1563 var_types structType = structVal->TypeGet();
1564 bool makeTemp = false;
1565 if (structType == TYP_STRUCT)
1567 structType = impNormStructType(structHnd);
1569 bool alreadyNormalized = false;
1570 GenTreeLclVarCommon* structLcl = nullptr;
1572 genTreeOps oper = structVal->OperGet();
1575 // GT_RETURN and GT_MKREFANY don't capture the handle.
1579 alreadyNormalized = true;
1583 structVal->gtCall.gtRetClsHnd = structHnd;
1588 structVal->gtRetExpr.gtRetClsHnd = structHnd;
1593 structVal->gtArgPlace.gtArgPlaceClsHnd = structHnd;
1597 // This will be transformed to an OBJ later.
1598 alreadyNormalized = true;
1599 structVal->gtIndex.gtStructElemClass = structHnd;
1600 structVal->gtIndex.gtIndElemSize = info.compCompHnd->getClassSize(structHnd);
1604 // Wrap it in a GT_OBJ.
1605 structVal->gtType = structType;
1606 structVal = gtNewObjNode(structHnd, gtNewOperNode(GT_ADDR, TYP_BYREF, structVal));
1611 structLcl = structVal->AsLclVarCommon();
1612 // Wrap it in a GT_OBJ.
1613 structVal = gtNewObjNode(structHnd, gtNewOperNode(GT_ADDR, TYP_BYREF, structVal));
1620 // These should already have the appropriate type.
1621 assert(structVal->gtType == structType);
1622 alreadyNormalized = true;
1626 assert(structVal->gtType == structType);
1627 structVal = gtNewObjNode(structHnd, structVal->gtGetOp1());
1628 alreadyNormalized = true;
1633 assert(varTypeIsSIMD(structVal) && (structVal->gtType == structType));
1635 #endif // FEATURE_SIMD
1639 // The second thing could either be a block node or a GT_SIMD or a GT_COMMA node.
1640 GenTree* blockNode = structVal->gtOp.gtOp2;
1641 assert(blockNode->gtType == structType);
1643 // Is this GT_COMMA(op1, GT_COMMA())?
1644 GenTree* parent = structVal;
1645 if (blockNode->OperGet() == GT_COMMA)
1647 // Find the last node in the comma chain.
1650 assert(blockNode->gtType == structType);
1652 blockNode = blockNode->gtOp.gtOp2;
1653 } while (blockNode->OperGet() == GT_COMMA);
1657 if (blockNode->OperGet() == GT_SIMD)
1659 parent->gtOp.gtOp2 = impNormStructVal(blockNode, structHnd, curLevel, forceNormalization);
1660 alreadyNormalized = true;
1665 assert(blockNode->OperIsBlk());
1667 // Sink the GT_COMMA below the blockNode addr.
1668 // That is GT_COMMA(op1, op2=blockNode) is tranformed into
1669 // blockNode(GT_COMMA(TYP_BYREF, op1, op2's op1)).
1671 // In case of a chained GT_COMMA case, we sink the last
1672 // GT_COMMA below the blockNode addr.
1673 GenTree* blockNodeAddr = blockNode->gtOp.gtOp1;
1674 assert(blockNodeAddr->gtType == TYP_BYREF);
1675 GenTree* commaNode = parent;
1676 commaNode->gtType = TYP_BYREF;
1677 commaNode->gtOp.gtOp2 = blockNodeAddr;
1678 blockNode->gtOp.gtOp1 = commaNode;
1679 if (parent == structVal)
1681 structVal = blockNode;
1683 alreadyNormalized = true;
1689 assert(!"Unexpected node in impNormStructVal()");
1692 structVal->gtType = structType;
1693 GenTree* structObj = structVal;
1695 if (!alreadyNormalized || forceNormalization)
1699 unsigned tmpNum = lvaGrabTemp(true DEBUGARG("struct address for call/obj"));
1701 impAssignTempGen(tmpNum, structVal, structHnd, curLevel);
1703 // The structVal is now the temp itself
1705 structLcl = gtNewLclvNode(tmpNum, structType)->AsLclVarCommon();
1706 // TODO-1stClassStructs: Avoid always wrapping in GT_OBJ.
1707 structObj = gtNewObjNode(structHnd, gtNewOperNode(GT_ADDR, TYP_BYREF, structLcl));
1709 else if (varTypeIsStruct(structType) && !structVal->OperIsBlk())
1711 // Wrap it in a GT_OBJ
1712 structObj = gtNewObjNode(structHnd, gtNewOperNode(GT_ADDR, TYP_BYREF, structVal));
1716 if (structLcl != nullptr)
1718 // A OBJ on a ADDR(LCL_VAR) can never raise an exception
1719 // so we don't set GTF_EXCEPT here.
1720 if (!lvaIsImplicitByRefLocal(structLcl->gtLclNum))
1722 structObj->gtFlags &= ~GTF_GLOB_REF;
1727 // In general a OBJ is an indirection and could raise an exception.
1728 structObj->gtFlags |= GTF_EXCEPT;
1733 /******************************************************************************/
1734 // Given a type token, generate code that will evaluate to the correct
1735 // handle representation of that token (type handle, field handle, or method handle)
1737 // For most cases, the handle is determined at compile-time, and the code
1738 // generated is simply an embedded handle.
1740 // Run-time lookup is required if the enclosing method is shared between instantiations
1741 // and the token refers to formal type parameters whose instantiation is not known
1744 GenTreePtr Compiler::impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
1745 BOOL* pRuntimeLookup /* = NULL */,
1746 BOOL mustRestoreHandle /* = FALSE */,
1747 BOOL importParent /* = FALSE */)
1749 assert(!fgGlobalMorph);
1751 CORINFO_GENERICHANDLE_RESULT embedInfo;
1752 info.compCompHnd->embedGenericHandle(pResolvedToken, importParent, &embedInfo);
1756 *pRuntimeLookup = embedInfo.lookup.lookupKind.needsRuntimeLookup;
1759 if (mustRestoreHandle && !embedInfo.lookup.lookupKind.needsRuntimeLookup)
1761 switch (embedInfo.handleType)
1763 case CORINFO_HANDLETYPE_CLASS:
1764 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun((CORINFO_CLASS_HANDLE)embedInfo.compileTimeHandle);
1767 case CORINFO_HANDLETYPE_METHOD:
1768 info.compCompHnd->methodMustBeLoadedBeforeCodeIsRun((CORINFO_METHOD_HANDLE)embedInfo.compileTimeHandle);
1771 case CORINFO_HANDLETYPE_FIELD:
1772 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(
1773 info.compCompHnd->getFieldClass((CORINFO_FIELD_HANDLE)embedInfo.compileTimeHandle));
1781 return impLookupToTree(pResolvedToken, &embedInfo.lookup, gtTokenToIconFlags(pResolvedToken->token),
1782 embedInfo.compileTimeHandle);
1785 GenTreePtr Compiler::impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
1786 CORINFO_LOOKUP* pLookup,
1787 unsigned handleFlags,
1788 void* compileTimeHandle)
1790 if (!pLookup->lookupKind.needsRuntimeLookup)
1792 // No runtime lookup is required.
1793 // Access is direct or memory-indirect (of a fixed address) reference
1795 CORINFO_GENERIC_HANDLE handle = nullptr;
1796 void* pIndirection = nullptr;
1797 assert(pLookup->constLookup.accessType != IAT_PPVALUE);
1799 if (pLookup->constLookup.accessType == IAT_VALUE)
1801 handle = pLookup->constLookup.handle;
1803 else if (pLookup->constLookup.accessType == IAT_PVALUE)
1805 pIndirection = pLookup->constLookup.addr;
1807 return gtNewIconEmbHndNode(handle, pIndirection, handleFlags, 0, nullptr, compileTimeHandle);
1809 else if (compIsForInlining())
1811 // Don't import runtime lookups when inlining
1812 // Inlining has to be aborted in such a case
1813 compInlineResult->NoteFatal(InlineObservation::CALLSITE_GENERIC_DICTIONARY_LOOKUP);
1818 // Need to use dictionary-based access which depends on the typeContext
1819 // which is only available at runtime, not at compile-time.
1821 return impRuntimeLookupToTree(pResolvedToken, pLookup, compileTimeHandle);
1825 #ifdef FEATURE_READYTORUN_COMPILER
1826 GenTreePtr Compiler::impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup,
1827 unsigned handleFlags,
1828 void* compileTimeHandle)
1830 CORINFO_GENERIC_HANDLE handle = nullptr;
1831 void* pIndirection = nullptr;
1832 assert(pLookup->accessType != IAT_PPVALUE);
1834 if (pLookup->accessType == IAT_VALUE)
1836 handle = pLookup->handle;
1838 else if (pLookup->accessType == IAT_PVALUE)
1840 pIndirection = pLookup->addr;
1842 return gtNewIconEmbHndNode(handle, pIndirection, handleFlags, 0, nullptr, compileTimeHandle);
1845 GenTreePtr Compiler::impReadyToRunHelperToTree(
1846 CORINFO_RESOLVED_TOKEN* pResolvedToken,
1847 CorInfoHelpFunc helper,
1849 GenTreeArgList* args /* =NULL*/,
1850 CORINFO_LOOKUP_KIND* pGenericLookupKind /* =NULL. Only used with generics */)
1852 CORINFO_CONST_LOOKUP lookup;
1853 #if COR_JIT_EE_VERSION > 460
1854 if (!info.compCompHnd->getReadyToRunHelper(pResolvedToken, pGenericLookupKind, helper, &lookup))
1859 info.compCompHnd->getReadyToRunHelper(pResolvedToken, helper, &lookup);
1862 GenTreePtr op1 = gtNewHelperCallNode(helper, type, GTF_EXCEPT, args);
1864 op1->gtCall.setEntryPoint(lookup);
1870 GenTreePtr Compiler::impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo)
1872 GenTreePtr op1 = nullptr;
1874 switch (pCallInfo->kind)
1877 op1 = new (this, GT_FTN_ADDR) GenTreeFptrVal(TYP_I_IMPL, pCallInfo->hMethod);
1879 #ifdef FEATURE_READYTORUN_COMPILER
1880 if (opts.IsReadyToRun())
1882 op1->gtFptrVal.gtEntryPoint = pCallInfo->codePointerLookup.constLookup;
1883 op1->gtFptrVal.gtLdftnResolvedToken = new (this, CMK_Unknown) CORINFO_RESOLVED_TOKEN;
1884 *op1->gtFptrVal.gtLdftnResolvedToken = *pResolvedToken;
1888 op1->gtFptrVal.gtEntryPoint.addr = nullptr;
1893 case CORINFO_CALL_CODE_POINTER:
1894 if (compIsForInlining())
1896 // Don't import runtime lookups when inlining
1897 // Inlining has to be aborted in such a case
1898 compInlineResult->NoteFatal(InlineObservation::CALLSITE_GENERIC_DICTIONARY_LOOKUP);
1902 op1 = impLookupToTree(pResolvedToken, &pCallInfo->codePointerLookup, GTF_ICON_FTN_ADDR, pCallInfo->hMethod);
1906 noway_assert(!"unknown call kind");
1913 //------------------------------------------------------------------------
1914 // getRuntimeContextTree: find pointer to context for runtime lookup.
1917 // kind - lookup kind.
1920 // Return GenTree pointer to generic shared context.
1923 // Reports about generic context using.
1925 GenTreePtr Compiler::getRuntimeContextTree(CORINFO_RUNTIME_LOOKUP_KIND kind)
1927 GenTreePtr ctxTree = nullptr;
1929 // Collectible types requires that for shared generic code, if we use the generic context parameter
1930 // that we report it. (This is a conservative approach, we could detect some cases particularly when the
1931 // context parameter is this that we don't need the eager reporting logic.)
1932 lvaGenericsContextUsed = true;
1934 if (kind == CORINFO_LOOKUP_THISOBJ)
1937 ctxTree = gtNewLclvNode(info.compThisArg, TYP_REF);
1939 // Vtable pointer of this object
1940 ctxTree = gtNewOperNode(GT_IND, TYP_I_IMPL, ctxTree);
1941 ctxTree->gtFlags |= GTF_EXCEPT; // Null-pointer exception
1942 ctxTree->gtFlags |= GTF_IND_INVARIANT;
1946 assert(kind == CORINFO_LOOKUP_METHODPARAM || kind == CORINFO_LOOKUP_CLASSPARAM);
1948 ctxTree = gtNewLclvNode(info.compTypeCtxtArg, TYP_I_IMPL); // Exact method descriptor as passed in as last arg
1953 /*****************************************************************************/
1954 /* Import a dictionary lookup to access a handle in code shared between
1955 generic instantiations.
1956 The lookup depends on the typeContext which is only available at
1957 runtime, and not at compile-time.
1958 pLookup->token1 and pLookup->token2 specify the handle that is needed.
1961 1. pLookup->indirections == CORINFO_USEHELPER : Call a helper passing it the
1962 instantiation-specific handle, and the tokens to lookup the handle.
1963 2. pLookup->indirections != CORINFO_USEHELPER :
1964 2a. pLookup->testForNull == false : Dereference the instantiation-specific handle
1966 2b. pLookup->testForNull == true : Dereference the instantiation-specific handle.
1967 If it is non-NULL, it is the handle required. Else, call a helper
1968 to lookup the handle.
1971 GenTreePtr Compiler::impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
1972 CORINFO_LOOKUP* pLookup,
1973 void* compileTimeHandle)
1976 // This method can only be called from the importer instance of the Compiler.
1977 // In other word, it cannot be called by the instance of the Compiler for the inlinee.
1978 assert(!compIsForInlining());
1980 GenTreePtr ctxTree = getRuntimeContextTree(pLookup->lookupKind.runtimeLookupKind);
1982 #ifdef FEATURE_READYTORUN_COMPILER
1983 if (opts.IsReadyToRun())
1985 return impReadyToRunHelperToTree(pResolvedToken, CORINFO_HELP_READYTORUN_GENERIC_HANDLE, TYP_I_IMPL,
1986 gtNewArgList(ctxTree), &pLookup->lookupKind);
1990 CORINFO_RUNTIME_LOOKUP* pRuntimeLookup = &pLookup->runtimeLookup;
1991 // It's available only via the run-time helper function
1992 if (pRuntimeLookup->indirections == CORINFO_USEHELPER)
1994 GenTreeArgList* helperArgs =
1995 gtNewArgList(ctxTree, gtNewIconEmbHndNode(pRuntimeLookup->signature, nullptr, GTF_ICON_TOKEN_HDL, 0,
1996 nullptr, compileTimeHandle));
1998 return gtNewHelperCallNode(pRuntimeLookup->helper, TYP_I_IMPL, GTF_EXCEPT, helperArgs);
2002 GenTreePtr slotPtrTree = ctxTree;
2004 if (pRuntimeLookup->testForNull)
2006 slotPtrTree = impCloneExpr(ctxTree, &ctxTree, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
2007 nullptr DEBUGARG("impRuntimeLookup slot"));
2010 // Applied repeated indirections
2011 for (WORD i = 0; i < pRuntimeLookup->indirections; i++)
2015 slotPtrTree = gtNewOperNode(GT_IND, TYP_I_IMPL, slotPtrTree);
2016 slotPtrTree->gtFlags |= GTF_IND_NONFAULTING;
2017 slotPtrTree->gtFlags |= GTF_IND_INVARIANT;
2019 if (pRuntimeLookup->offsets[i] != 0)
2022 gtNewOperNode(GT_ADD, TYP_I_IMPL, slotPtrTree, gtNewIconNode(pRuntimeLookup->offsets[i], TYP_I_IMPL));
2026 // No null test required
2027 if (!pRuntimeLookup->testForNull)
2029 if (pRuntimeLookup->indirections == 0)
2034 slotPtrTree = gtNewOperNode(GT_IND, TYP_I_IMPL, slotPtrTree);
2035 slotPtrTree->gtFlags |= GTF_IND_NONFAULTING;
2037 if (!pRuntimeLookup->testForFixup)
2042 impSpillSideEffects(true, CHECK_SPILL_ALL DEBUGARG("bubbling QMark0"));
2044 GenTreePtr op1 = impCloneExpr(slotPtrTree, &slotPtrTree, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
2045 nullptr DEBUGARG("impRuntimeLookup test"));
2046 op1 = impImplicitIorI4Cast(op1, TYP_INT); // downcast the pointer to a TYP_INT on 64-bit targets
2048 // Use a GT_AND to check for the lowest bit and indirect if it is set
2049 GenTreePtr testTree = gtNewOperNode(GT_AND, TYP_INT, op1, gtNewIconNode(1));
2050 GenTreePtr relop = gtNewOperNode(GT_EQ, TYP_INT, testTree, gtNewIconNode(0));
2051 relop->gtFlags |= GTF_RELOP_QMARK;
2053 op1 = impCloneExpr(slotPtrTree, &slotPtrTree, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
2054 nullptr DEBUGARG("impRuntimeLookup indir"));
2055 op1 = gtNewOperNode(GT_ADD, TYP_I_IMPL, op1, gtNewIconNode(-1, TYP_I_IMPL)); // subtract 1 from the pointer
2056 GenTreePtr indirTree = gtNewOperNode(GT_IND, TYP_I_IMPL, op1);
2057 GenTreePtr colon = new (this, GT_COLON) GenTreeColon(TYP_I_IMPL, slotPtrTree, indirTree);
2059 GenTreePtr qmark = gtNewQmarkNode(TYP_I_IMPL, relop, colon);
2061 unsigned tmp = lvaGrabTemp(true DEBUGARG("spilling QMark0"));
2062 impAssignTempGen(tmp, qmark, (unsigned)CHECK_SPILL_NONE);
2063 return gtNewLclvNode(tmp, TYP_I_IMPL);
2066 assert(pRuntimeLookup->indirections != 0);
2068 impSpillSideEffects(true, CHECK_SPILL_ALL DEBUGARG("bubbling QMark1"));
2070 // Extract the handle
2071 GenTreePtr handle = gtNewOperNode(GT_IND, TYP_I_IMPL, slotPtrTree);
2072 handle->gtFlags |= GTF_IND_NONFAULTING;
2074 GenTreePtr handleCopy = impCloneExpr(handle, &handle, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
2075 nullptr DEBUGARG("impRuntimeLookup typehandle"));
2078 GenTreeArgList* helperArgs =
2079 gtNewArgList(ctxTree, gtNewIconEmbHndNode(pRuntimeLookup->signature, nullptr, GTF_ICON_TOKEN_HDL, 0, nullptr,
2080 compileTimeHandle));
2081 GenTreePtr helperCall = gtNewHelperCallNode(pRuntimeLookup->helper, TYP_I_IMPL, GTF_EXCEPT, helperArgs);
2083 // Check for null and possibly call helper
2084 GenTreePtr relop = gtNewOperNode(GT_NE, TYP_INT, handle, gtNewIconNode(0, TYP_I_IMPL));
2085 relop->gtFlags |= GTF_RELOP_QMARK;
2087 GenTreePtr colon = new (this, GT_COLON) GenTreeColon(TYP_I_IMPL,
2088 gtNewNothingNode(), // do nothing if nonnull
2091 GenTreePtr qmark = gtNewQmarkNode(TYP_I_IMPL, relop, colon);
2094 if (handleCopy->IsLocal())
2096 tmp = handleCopy->gtLclVarCommon.gtLclNum;
2100 tmp = lvaGrabTemp(true DEBUGARG("spilling QMark1"));
2103 impAssignTempGen(tmp, qmark, (unsigned)CHECK_SPILL_NONE);
2104 return gtNewLclvNode(tmp, TYP_I_IMPL);
2107 /******************************************************************************
2108 * Spills the stack at verCurrentState.esStack[level] and replaces it with a temp.
2109 * If tnum!=BAD_VAR_NUM, the temp var used to replace the tree is tnum,
2110 * else, grab a new temp.
2111 * For structs (which can be pushed on the stack using obj, etc),
2112 * special handling is needed
2115 struct RecursiveGuard
2120 m_pAddress = nullptr;
2127 *m_pAddress = false;
2131 void Init(bool* pAddress, bool bInitialize)
2133 assert(pAddress && *pAddress == false && "Recursive guard violation");
2134 m_pAddress = pAddress;
2146 bool Compiler::impSpillStackEntry(unsigned level,
2150 bool bAssertOnRecursion,
2157 RecursiveGuard guard;
2158 guard.Init(&impNestedStackSpill, bAssertOnRecursion);
2161 GenTreePtr tree = verCurrentState.esStack[level].val;
2163 /* Allocate a temp if we haven't been asked to use a particular one */
2165 if (tiVerificationNeeded)
2167 // Ignore bad temp requests (they will happen with bad code and will be
2168 // catched when importing the destblock)
2169 if ((tnum != BAD_VAR_NUM && tnum >= lvaCount) && verNeedsVerification())
2176 if (tnum != BAD_VAR_NUM && (tnum >= lvaCount))
2182 if (tnum == BAD_VAR_NUM)
2184 tnum = lvaGrabTemp(true DEBUGARG(reason));
2186 else if (tiVerificationNeeded && lvaTable[tnum].TypeGet() != TYP_UNDEF)
2188 // if verification is needed and tnum's type is incompatible with
2189 // type on that stack, we grab a new temp. This is safe since
2190 // we will throw a verification exception in the dest block.
2192 var_types valTyp = tree->TypeGet();
2193 var_types dstTyp = lvaTable[tnum].TypeGet();
2195 // if the two types are different, we return. This will only happen with bad code and will
2196 // be catched when importing the destblock. We still allow int/byrefs and float/double differences.
2197 if ((genActualType(valTyp) != genActualType(dstTyp)) &&
2199 #ifndef _TARGET_64BIT_
2200 (valTyp == TYP_I_IMPL && dstTyp == TYP_BYREF) || (valTyp == TYP_BYREF && dstTyp == TYP_I_IMPL) ||
2201 #endif // !_TARGET_64BIT_
2202 (varTypeIsFloating(dstTyp) && varTypeIsFloating(valTyp))))
2204 if (verNeedsVerification())
2211 /* Assign the spilled entry to the temp */
2212 impAssignTempGen(tnum, tree, verCurrentState.esStack[level].seTypeInfo.GetClassHandle(), level);
2214 // The tree type may be modified by impAssignTempGen, so use the type of the lclVar.
2215 var_types type = genActualType(lvaTable[tnum].TypeGet());
2216 GenTreePtr temp = gtNewLclvNode(tnum, type);
2217 verCurrentState.esStack[level].val = temp;
2222 /*****************************************************************************
2224 * Ensure that the stack has only spilled values
2227 void Compiler::impSpillStackEnsure(bool spillLeaves)
2229 assert(!spillLeaves || opts.compDbgCode);
2231 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
2233 GenTreePtr tree = verCurrentState.esStack[level].val;
2235 if (!spillLeaves && tree->OperIsLeaf())
2240 // Temps introduced by the importer itself don't need to be spilled
2242 bool isTempLcl = (tree->OperGet() == GT_LCL_VAR) && (tree->gtLclVarCommon.gtLclNum >= info.compLocalsCount);
2249 impSpillStackEntry(level, BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impSpillStackEnsure"));
2253 void Compiler::impSpillEvalStack()
2255 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
2257 impSpillStackEntry(level, BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impSpillEvalStack"));
2261 /*****************************************************************************
2263 * If the stack contains any trees with side effects in them, assign those
2264 * trees to temps and append the assignments to the statement list.
2265 * On return the stack is guaranteed to be empty.
2268 inline void Compiler::impEvalSideEffects()
2270 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG("impEvalSideEffects"));
2271 verCurrentState.esStackDepth = 0;
2274 /*****************************************************************************
2276 * If the stack contains any trees with side effects in them, assign those
2277 * trees to temps and replace them on the stack with refs to their temps.
2278 * [0..chkLevel) is the portion of the stack which will be checked and spilled.
2281 inline void Compiler::impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason))
2283 assert(chkLevel != (unsigned)CHECK_SPILL_NONE);
2285 /* Before we make any appends to the tree list we must spill the
2286 * "special" side effects (GTF_ORDER_SIDEEFF on a GT_CATCH_ARG) */
2288 impSpillSpecialSideEff();
2290 if (chkLevel == (unsigned)CHECK_SPILL_ALL)
2292 chkLevel = verCurrentState.esStackDepth;
2295 assert(chkLevel <= verCurrentState.esStackDepth);
2297 unsigned spillFlags = spillGlobEffects ? GTF_GLOB_EFFECT : GTF_SIDE_EFFECT;
2299 for (unsigned i = 0; i < chkLevel; i++)
2301 GenTreePtr tree = verCurrentState.esStack[i].val;
2303 GenTreePtr lclVarTree;
2305 if ((tree->gtFlags & spillFlags) != 0 ||
2306 (spillGlobEffects && // Only consider the following when spillGlobEffects == TRUE
2307 !impIsAddressInLocal(tree, &lclVarTree) && // No need to spill the GT_ADDR node on a local.
2308 gtHasLocalsWithAddrOp(tree))) // Spill if we still see GT_LCL_VAR that contains lvHasLdAddrOp or
2309 // lvAddrTaken flag.
2311 impSpillStackEntry(i, BAD_VAR_NUM DEBUGARG(false) DEBUGARG(reason));
2316 /*****************************************************************************
2318 * If the stack contains any trees with special side effects in them, assign
2319 * those trees to temps and replace them on the stack with refs to their temps.
2322 inline void Compiler::impSpillSpecialSideEff()
2324 // Only exception objects need to be carefully handled
2326 if (!compCurBB->bbCatchTyp)
2331 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
2333 GenTreePtr tree = verCurrentState.esStack[level].val;
2334 // Make sure if we have an exception object in the sub tree we spill ourselves.
2335 if (gtHasCatchArg(tree))
2337 impSpillStackEntry(level, BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impSpillSpecialSideEff"));
2342 /*****************************************************************************
2344 * Spill all stack references to value classes (TYP_STRUCT nodes)
2347 void Compiler::impSpillValueClasses()
2349 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
2351 GenTreePtr tree = verCurrentState.esStack[level].val;
2353 if (fgWalkTreePre(&tree, impFindValueClasses) == WALK_ABORT)
2355 // Tree walk was aborted, which means that we found a
2356 // value class on the stack. Need to spill that
2359 impSpillStackEntry(level, BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impSpillValueClasses"));
2364 /*****************************************************************************
2366 * Callback that checks if a tree node is TYP_STRUCT
2369 Compiler::fgWalkResult Compiler::impFindValueClasses(GenTreePtr* pTree, fgWalkData* data)
2371 fgWalkResult walkResult = WALK_CONTINUE;
2373 if ((*pTree)->gtType == TYP_STRUCT)
2375 // Abort the walk and indicate that we found a value class
2377 walkResult = WALK_ABORT;
2383 /*****************************************************************************
2385 * If the stack contains any trees with references to local #lclNum, assign
2386 * those trees to temps and replace their place on the stack with refs to
2390 void Compiler::impSpillLclRefs(ssize_t lclNum)
2392 /* Before we make any appends to the tree list we must spill the
2393 * "special" side effects (GTF_ORDER_SIDEEFF) - GT_CATCH_ARG */
2395 impSpillSpecialSideEff();
2397 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
2399 GenTreePtr tree = verCurrentState.esStack[level].val;
2401 /* If the tree may throw an exception, and the block has a handler,
2402 then we need to spill assignments to the local if the local is
2403 live on entry to the handler.
2404 Just spill 'em all without considering the liveness */
2406 bool xcptnCaught = ehBlockHasExnFlowDsc(compCurBB) && (tree->gtFlags & (GTF_CALL | GTF_EXCEPT));
2408 /* Skip the tree if it doesn't have an affected reference,
2409 unless xcptnCaught */
2411 if (xcptnCaught || gtHasRef(tree, lclNum, false))
2413 impSpillStackEntry(level, BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impSpillLclRefs"));
2418 /*****************************************************************************
2420 * Push catch arg onto the stack.
2421 * If there are jumps to the beginning of the handler, insert basic block
2422 * and spill catch arg to a temp. Update the handler block if necessary.
2424 * Returns the basic block of the actual handler.
2427 BasicBlock* Compiler::impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd)
2429 // Do not inject the basic block twice on reimport. This should be
2430 // hit only under JIT stress. See if the block is the one we injected.
2431 // Note that EH canonicalization can inject internal blocks here. We might
2432 // be able to re-use such a block (but we don't, right now).
2433 if ((hndBlk->bbFlags & (BBF_IMPORTED | BBF_INTERNAL | BBF_DONT_REMOVE | BBF_HAS_LABEL | BBF_JMP_TARGET)) ==
2434 (BBF_IMPORTED | BBF_INTERNAL | BBF_DONT_REMOVE | BBF_HAS_LABEL | BBF_JMP_TARGET))
2436 GenTreePtr tree = hndBlk->bbTreeList;
2438 if (tree != nullptr && tree->gtOper == GT_STMT)
2440 tree = tree->gtStmt.gtStmtExpr;
2441 assert(tree != nullptr);
2443 if ((tree->gtOper == GT_ASG) && (tree->gtOp.gtOp1->gtOper == GT_LCL_VAR) &&
2444 (tree->gtOp.gtOp2->gtOper == GT_CATCH_ARG))
2446 tree = gtNewLclvNode(tree->gtOp.gtOp1->gtLclVarCommon.gtLclNum, TYP_REF);
2448 impPushOnStack(tree, typeInfo(TI_REF, clsHnd));
2450 return hndBlk->bbNext;
2454 // If we get here, it must have been some other kind of internal block. It's possible that
2455 // someone prepended something to our injected block, but that's unlikely.
2458 /* Push the exception address value on the stack */
2459 GenTreePtr arg = new (this, GT_CATCH_ARG) GenTree(GT_CATCH_ARG, TYP_REF);
2461 /* Mark the node as having a side-effect - i.e. cannot be
2462 * moved around since it is tied to a fixed location (EAX) */
2463 arg->gtFlags |= GTF_ORDER_SIDEEFF;
2465 /* Spill GT_CATCH_ARG to a temp if there are jumps to the beginning of the handler */
2466 if (hndBlk->bbRefs > 1 || compStressCompile(STRESS_CATCH_ARG, 5))
2468 if (hndBlk->bbRefs == 1)
2473 /* Create extra basic block for the spill */
2474 BasicBlock* newBlk = fgNewBBbefore(BBJ_NONE, hndBlk, /* extendRegion */ true);
2475 newBlk->bbFlags |= BBF_IMPORTED | BBF_DONT_REMOVE | BBF_HAS_LABEL | BBF_JMP_TARGET;
2476 newBlk->setBBWeight(hndBlk->bbWeight);
2477 newBlk->bbCodeOffs = hndBlk->bbCodeOffs;
2479 /* Account for the new link we are about to create */
2482 /* Spill into a temp */
2483 unsigned tempNum = lvaGrabTemp(false DEBUGARG("SpillCatchArg"));
2484 lvaTable[tempNum].lvType = TYP_REF;
2485 arg = gtNewTempAssign(tempNum, arg);
2487 hndBlk->bbStkTempsIn = tempNum;
2489 /* Report the debug info. impImportBlockCode won't treat
2490 * the actual handler as exception block and thus won't do it for us. */
2491 if (info.compStmtOffsetsImplicit & ICorDebugInfo::CALL_SITE_BOUNDARIES)
2493 impCurStmtOffs = newBlk->bbCodeOffs | IL_OFFSETX_STKBIT;
2494 arg = gtNewStmt(arg, impCurStmtOffs);
2497 fgInsertStmtAtEnd(newBlk, arg);
2499 arg = gtNewLclvNode(tempNum, TYP_REF);
2502 impPushOnStack(arg, typeInfo(TI_REF, clsHnd));
2507 /*****************************************************************************
2509 * Given a tree, clone it. *pClone is set to the cloned tree.
2510 * Returns the original tree if the cloning was easy,
2511 * else returns the temp to which the tree had to be spilled to.
2512 * If the tree has side-effects, it will be spilled to a temp.
2515 GenTreePtr Compiler::impCloneExpr(GenTreePtr tree,
2517 CORINFO_CLASS_HANDLE structHnd,
2519 GenTreePtr* pAfterStmt DEBUGARG(const char* reason))
2521 if (!(tree->gtFlags & GTF_GLOB_EFFECT))
2523 GenTreePtr clone = gtClone(tree, true);
2532 /* Store the operand in a temp and return the temp */
2534 unsigned temp = lvaGrabTemp(true DEBUGARG(reason));
2536 // impAssignTempGen() may change tree->gtType to TYP_VOID for calls which
2537 // return a struct type. It also may modify the struct type to a more
2538 // specialized type (e.g. a SIMD type). So we will get the type from
2539 // the lclVar AFTER calling impAssignTempGen().
2541 impAssignTempGen(temp, tree, structHnd, curLevel, pAfterStmt, impCurStmtOffs);
2542 var_types type = genActualType(lvaTable[temp].TypeGet());
2544 *pClone = gtNewLclvNode(temp, type);
2545 return gtNewLclvNode(temp, type);
2548 /*****************************************************************************
2549 * Remember the IL offset (including stack-empty info) for the trees we will
2553 inline void Compiler::impCurStmtOffsSet(IL_OFFSET offs)
2555 if (compIsForInlining())
2557 GenTreePtr callStmt = impInlineInfo->iciStmt;
2558 assert(callStmt->gtOper == GT_STMT);
2559 impCurStmtOffs = callStmt->gtStmt.gtStmtILoffsx;
2563 assert(offs == BAD_IL_OFFSET || (offs & IL_OFFSETX_BITS) == 0);
2564 IL_OFFSETX stkBit = (verCurrentState.esStackDepth > 0) ? IL_OFFSETX_STKBIT : 0;
2565 impCurStmtOffs = offs | stkBit;
2569 /*****************************************************************************
2570 * Returns current IL offset with stack-empty and call-instruction info incorporated
2572 inline IL_OFFSETX Compiler::impCurILOffset(IL_OFFSET offs, bool callInstruction)
2574 if (compIsForInlining())
2576 return BAD_IL_OFFSET;
2580 assert(offs == BAD_IL_OFFSET || (offs & IL_OFFSETX_BITS) == 0);
2581 IL_OFFSETX stkBit = (verCurrentState.esStackDepth > 0) ? IL_OFFSETX_STKBIT : 0;
2582 IL_OFFSETX callInstructionBit = callInstruction ? IL_OFFSETX_CALLINSTRUCTIONBIT : 0;
2583 return offs | stkBit | callInstructionBit;
2587 /*****************************************************************************
2589 * Remember the instr offset for the statements
2591 * When we do impAppendTree(tree), we can't set tree->gtStmtLastILoffs to
2592 * impCurOpcOffs, if the append was done because of a partial stack spill,
2593 * as some of the trees corresponding to code up to impCurOpcOffs might
2594 * still be sitting on the stack.
2595 * So we delay marking of gtStmtLastILoffs until impNoteLastILoffs().
2596 * This should be called when an opcode finally/explicitly causes
2597 * impAppendTree(tree) to be called (as opposed to being called because of
2598 * a spill caused by the opcode)
2603 void Compiler::impNoteLastILoffs()
2605 if (impLastILoffsStmt == nullptr)
2607 // We should have added a statement for the current basic block
2608 // Is this assert correct ?
2610 assert(impTreeLast);
2611 assert(impTreeLast->gtOper == GT_STMT);
2613 impTreeLast->gtStmt.gtStmtLastILoffs = compIsForInlining() ? BAD_IL_OFFSET : impCurOpcOffs;
2617 impLastILoffsStmt->gtStmt.gtStmtLastILoffs = compIsForInlining() ? BAD_IL_OFFSET : impCurOpcOffs;
2618 impLastILoffsStmt = nullptr;
2624 /*****************************************************************************
2625 * We don't create any GenTree (excluding spills) for a branch.
2626 * For debugging info, we need a placeholder so that we can note
2627 * the IL offset in gtStmt.gtStmtOffs. So append an empty statement.
2630 void Compiler::impNoteBranchOffs()
2632 if (opts.compDbgCode)
2634 impAppendTree(gtNewNothingNode(), (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
2638 /*****************************************************************************
2639 * Locate the next stmt boundary for which we need to record info.
2640 * We will have to spill the stack at such boundaries if it is not
2642 * Returns the next stmt boundary (after the start of the block)
2645 unsigned Compiler::impInitBlockLineInfo()
2647 /* Assume the block does not correspond with any IL offset. This prevents
2648 us from reporting extra offsets. Extra mappings can cause confusing
2649 stepping, especially if the extra mapping is a jump-target, and the
2650 debugger does not ignore extra mappings, but instead rewinds to the
2651 nearest known offset */
2653 impCurStmtOffsSet(BAD_IL_OFFSET);
2655 if (compIsForInlining())
2660 IL_OFFSET blockOffs = compCurBB->bbCodeOffs;
2662 if ((verCurrentState.esStackDepth == 0) && (info.compStmtOffsetsImplicit & ICorDebugInfo::STACK_EMPTY_BOUNDARIES))
2664 impCurStmtOffsSet(blockOffs);
2667 if (false && (info.compStmtOffsetsImplicit & ICorDebugInfo::CALL_SITE_BOUNDARIES))
2669 impCurStmtOffsSet(blockOffs);
2672 /* Always report IL offset 0 or some tests get confused.
2673 Probably a good idea anyways */
2677 impCurStmtOffsSet(blockOffs);
2680 if (!info.compStmtOffsetsCount)
2685 /* Find the lowest explicit stmt boundary within the block */
2687 /* Start looking at an entry that is based on our instr offset */
2689 unsigned index = (info.compStmtOffsetsCount * blockOffs) / info.compILCodeSize;
2691 if (index >= info.compStmtOffsetsCount)
2693 index = info.compStmtOffsetsCount - 1;
2696 /* If we've guessed too far, back up */
2698 while (index > 0 && info.compStmtOffsets[index - 1] >= blockOffs)
2703 /* If we guessed short, advance ahead */
2705 while (info.compStmtOffsets[index] < blockOffs)
2709 if (index == info.compStmtOffsetsCount)
2711 return info.compStmtOffsetsCount;
2715 assert(index < info.compStmtOffsetsCount);
2717 if (info.compStmtOffsets[index] == blockOffs)
2719 /* There is an explicit boundary for the start of this basic block.
2720 So we will start with bbCodeOffs. Else we will wait until we
2721 get to the next explicit boundary */
2723 impCurStmtOffsSet(blockOffs);
2731 /*****************************************************************************/
2733 static inline bool impOpcodeIsCallOpcode(OPCODE opcode)
2747 /*****************************************************************************/
2749 static inline bool impOpcodeIsCallSiteBoundary(OPCODE opcode)
2766 /*****************************************************************************/
2768 // One might think it is worth caching these values, but results indicate
2770 // In addition, caching them causes SuperPMI to be unable to completely
2771 // encapsulate an individual method context.
2772 CORINFO_CLASS_HANDLE Compiler::impGetRefAnyClass()
2774 CORINFO_CLASS_HANDLE refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
2775 assert(refAnyClass != (CORINFO_CLASS_HANDLE) nullptr);
2779 CORINFO_CLASS_HANDLE Compiler::impGetTypeHandleClass()
2781 CORINFO_CLASS_HANDLE typeHandleClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPE_HANDLE);
2782 assert(typeHandleClass != (CORINFO_CLASS_HANDLE) nullptr);
2783 return typeHandleClass;
2786 CORINFO_CLASS_HANDLE Compiler::impGetRuntimeArgumentHandle()
2788 CORINFO_CLASS_HANDLE argIteratorClass = info.compCompHnd->getBuiltinClass(CLASSID_ARGUMENT_HANDLE);
2789 assert(argIteratorClass != (CORINFO_CLASS_HANDLE) nullptr);
2790 return argIteratorClass;
2793 CORINFO_CLASS_HANDLE Compiler::impGetStringClass()
2795 CORINFO_CLASS_HANDLE stringClass = info.compCompHnd->getBuiltinClass(CLASSID_STRING);
2796 assert(stringClass != (CORINFO_CLASS_HANDLE) nullptr);
2800 CORINFO_CLASS_HANDLE Compiler::impGetObjectClass()
2802 CORINFO_CLASS_HANDLE objectClass = info.compCompHnd->getBuiltinClass(CLASSID_SYSTEM_OBJECT);
2803 assert(objectClass != (CORINFO_CLASS_HANDLE) nullptr);
2807 /*****************************************************************************
2808 * "&var" can be used either as TYP_BYREF or TYP_I_IMPL, but we
2809 * set its type to TYP_BYREF when we create it. We know if it can be
2810 * changed to TYP_I_IMPL only at the point where we use it
2814 void Compiler::impBashVarAddrsToI(GenTreePtr tree1, GenTreePtr tree2)
2816 if (tree1->IsVarAddr())
2818 tree1->gtType = TYP_I_IMPL;
2821 if (tree2 && tree2->IsVarAddr())
2823 tree2->gtType = TYP_I_IMPL;
2827 /*****************************************************************************
2828 * TYP_INT and TYP_I_IMPL can be used almost interchangeably, but we want
2829 * to make that an explicit cast in our trees, so any implicit casts that
2830 * exist in the IL (at least on 64-bit where TYP_I_IMPL != TYP_INT) are
2831 * turned into explicit casts here.
2832 * We also allow an implicit conversion of a ldnull into a TYP_I_IMPL(0)
2835 GenTreePtr Compiler::impImplicitIorI4Cast(GenTreePtr tree, var_types dstTyp)
2837 var_types currType = genActualType(tree->gtType);
2838 var_types wantedType = genActualType(dstTyp);
2840 if (wantedType != currType)
2842 // Automatic upcast for a GT_CNS_INT into TYP_I_IMPL
2843 if ((tree->OperGet() == GT_CNS_INT) && varTypeIsI(dstTyp))
2845 if (!varTypeIsI(tree->gtType) || ((tree->gtType == TYP_REF) && (tree->gtIntCon.gtIconVal == 0)))
2847 tree->gtType = TYP_I_IMPL;
2850 #ifdef _TARGET_64BIT_
2851 else if (varTypeIsI(wantedType) && (currType == TYP_INT))
2853 // Note that this allows TYP_INT to be cast to a TYP_I_IMPL when wantedType is a TYP_BYREF or TYP_REF
2854 tree = gtNewCastNode(TYP_I_IMPL, tree, TYP_I_IMPL);
2856 else if ((wantedType == TYP_INT) && varTypeIsI(currType))
2858 // Note that this allows TYP_BYREF or TYP_REF to be cast to a TYP_INT
2859 tree = gtNewCastNode(TYP_INT, tree, TYP_INT);
2861 #endif // _TARGET_64BIT_
2867 /*****************************************************************************
2868 * TYP_FLOAT and TYP_DOUBLE can be used almost interchangeably in some cases,
2869 * but we want to make that an explicit cast in our trees, so any implicit casts
2870 * that exist in the IL are turned into explicit casts here.
2873 GenTreePtr Compiler::impImplicitR4orR8Cast(GenTreePtr tree, var_types dstTyp)
2875 #ifndef LEGACY_BACKEND
2876 if (varTypeIsFloating(tree) && varTypeIsFloating(dstTyp) && (dstTyp != tree->gtType))
2878 tree = gtNewCastNode(dstTyp, tree, dstTyp);
2880 #endif // !LEGACY_BACKEND
2885 //------------------------------------------------------------------------
2886 // impInitializeArrayIntrinsic: Attempts to replace a call to InitializeArray
2887 // with a GT_COPYBLK node.
2890 // sig - The InitializeArray signature.
2893 // A pointer to the newly created GT_COPYBLK node if the replacement succeeds or
2894 // nullptr otherwise.
2897 // The function recognizes the following IL pattern:
2898 // ldc <length> or a list of ldc <lower bound>/<length>
2901 // ldtoken <field handle>
2902 // call InitializeArray
2903 // The lower bounds need not be constant except when the array rank is 1.
2904 // The function recognizes all kinds of arrays thus enabling a small runtime
2905 // such as CoreRT to skip providing an implementation for InitializeArray.
2907 GenTreePtr Compiler::impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig)
2909 assert(sig->numArgs == 2);
2911 GenTreePtr fieldTokenNode = impStackTop(0).val;
2912 GenTreePtr arrayLocalNode = impStackTop(1).val;
2915 // Verify that the field token is known and valid. Note that It's also
2916 // possible for the token to come from reflection, in which case we cannot do
2917 // the optimization and must therefore revert to calling the helper. You can
2918 // see an example of this in bvt\DynIL\initarray2.exe (in Main).
2921 // Check to see if the ldtoken helper call is what we see here.
2922 if (fieldTokenNode->gtOper != GT_CALL || (fieldTokenNode->gtCall.gtCallType != CT_HELPER) ||
2923 (fieldTokenNode->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD)))
2928 // Strip helper call away
2929 fieldTokenNode = fieldTokenNode->gtCall.gtCallArgs->Current();
2931 if (fieldTokenNode->gtOper == GT_IND)
2933 fieldTokenNode = fieldTokenNode->gtOp.gtOp1;
2936 // Check for constant
2937 if (fieldTokenNode->gtOper != GT_CNS_INT)
2942 CORINFO_FIELD_HANDLE fieldToken = (CORINFO_FIELD_HANDLE)fieldTokenNode->gtIntCon.gtCompileTimeHandle;
2943 if (!fieldTokenNode->IsIconHandle(GTF_ICON_FIELD_HDL) || (fieldToken == nullptr))
2949 // We need to get the number of elements in the array and the size of each element.
2950 // We verify that the newarr statement is exactly what we expect it to be.
2951 // If it's not then we just return NULL and we don't optimize this call
2955 // It is possible the we don't have any statements in the block yet
2957 if (impTreeLast->gtOper != GT_STMT)
2959 assert(impTreeLast->gtOper == GT_BEG_STMTS);
2964 // We start by looking at the last statement, making sure it's an assignment, and
2965 // that the target of the assignment is the array passed to InitializeArray.
2967 GenTreePtr arrayAssignment = impTreeLast->gtStmt.gtStmtExpr;
2968 if ((arrayAssignment->gtOper != GT_ASG) || (arrayAssignment->gtOp.gtOp1->gtOper != GT_LCL_VAR) ||
2969 (arrayLocalNode->gtOper != GT_LCL_VAR) ||
2970 (arrayAssignment->gtOp.gtOp1->gtLclVarCommon.gtLclNum != arrayLocalNode->gtLclVarCommon.gtLclNum))
2976 // Make sure that the object being assigned is a helper call.
2979 GenTreePtr newArrayCall = arrayAssignment->gtOp.gtOp2;
2980 if ((newArrayCall->gtOper != GT_CALL) || (newArrayCall->gtCall.gtCallType != CT_HELPER))
2986 // Verify that it is one of the new array helpers.
2989 bool isMDArray = false;
2991 if (newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_NEWARR_1_DIRECT) &&
2992 newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_NEWARR_1_OBJ) &&
2993 newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_NEWARR_1_VC) &&
2994 newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_NEWARR_1_ALIGN8)
2995 #ifdef FEATURE_READYTORUN_COMPILER
2996 && newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_READYTORUN_NEWARR_1)
3000 #if COR_JIT_EE_VERSION > 460
3001 if (newArrayCall->gtCall.gtCallMethHnd != eeFindHelper(CORINFO_HELP_NEW_MDARR_NONVARARG))
3010 CORINFO_CLASS_HANDLE arrayClsHnd = (CORINFO_CLASS_HANDLE)newArrayCall->gtCall.compileTimeHelperArgumentHandle;
3013 // Make sure we found a compile time handle to the array
3022 S_UINT32 numElements;
3026 rank = info.compCompHnd->getArrayRank(arrayClsHnd);
3033 GenTreeArgList* tokenArg = newArrayCall->gtCall.gtCallArgs;
3034 assert(tokenArg != nullptr);
3035 GenTreeArgList* numArgsArg = tokenArg->Rest();
3036 assert(numArgsArg != nullptr);
3037 GenTreeArgList* argsArg = numArgsArg->Rest();
3038 assert(argsArg != nullptr);
3041 // The number of arguments should be a constant between 1 and 64. The rank can't be 0
3042 // so at least one length must be present and the rank can't exceed 32 so there can
3043 // be at most 64 arguments - 32 lengths and 32 lower bounds.
3046 if ((!numArgsArg->Current()->IsCnsIntOrI()) || (numArgsArg->Current()->AsIntCon()->IconValue() < 1) ||
3047 (numArgsArg->Current()->AsIntCon()->IconValue() > 64))
3052 unsigned numArgs = static_cast<unsigned>(numArgsArg->Current()->AsIntCon()->IconValue());
3053 bool lowerBoundsSpecified;
3055 if (numArgs == rank * 2)
3057 lowerBoundsSpecified = true;
3059 else if (numArgs == rank)
3061 lowerBoundsSpecified = false;
3064 // If the rank is 1 and a lower bound isn't specified then the runtime creates
3065 // a SDArray. Note that even if a lower bound is specified it can be 0 and then
3066 // we get a SDArray as well, see the for loop below.
3080 // The rank is known to be at least 1 so we can start with numElements being 1
3081 // to avoid the need to special case the first dimension.
3084 numElements = S_UINT32(1);
3088 static bool IsArgsFieldInit(GenTree* tree, unsigned index, unsigned lvaNewObjArrayArgs)
3090 return (tree->OperGet() == GT_ASG) && IsArgsFieldIndir(tree->gtGetOp1(), index, lvaNewObjArrayArgs) &&
3091 IsArgsAddr(tree->gtGetOp1()->gtGetOp1()->gtGetOp1(), lvaNewObjArrayArgs);
3094 static bool IsArgsFieldIndir(GenTree* tree, unsigned index, unsigned lvaNewObjArrayArgs)
3096 return (tree->OperGet() == GT_IND) && (tree->gtGetOp1()->OperGet() == GT_ADD) &&
3097 (tree->gtGetOp1()->gtGetOp2()->IsIntegralConst(sizeof(INT32) * index)) &&
3098 IsArgsAddr(tree->gtGetOp1()->gtGetOp1(), lvaNewObjArrayArgs);
3101 static bool IsArgsAddr(GenTree* tree, unsigned lvaNewObjArrayArgs)
3103 return (tree->OperGet() == GT_ADDR) && (tree->gtGetOp1()->OperGet() == GT_LCL_VAR) &&
3104 (tree->gtGetOp1()->AsLclVar()->GetLclNum() == lvaNewObjArrayArgs);
3107 static bool IsComma(GenTree* tree)
3109 return (tree != nullptr) && (tree->OperGet() == GT_COMMA);
3113 unsigned argIndex = 0;
3116 for (comma = argsArg->Current(); Match::IsComma(comma); comma = comma->gtGetOp2())
3118 if (lowerBoundsSpecified)
3121 // In general lower bounds can be ignored because they're not needed to
3122 // calculate the total number of elements. But for single dimensional arrays
3123 // we need to know if the lower bound is 0 because in this case the runtime
3124 // creates a SDArray and this affects the way the array data offset is calculated.
3129 GenTree* lowerBoundAssign = comma->gtGetOp1();
3130 assert(Match::IsArgsFieldInit(lowerBoundAssign, argIndex, lvaNewObjArrayArgs));
3131 GenTree* lowerBoundNode = lowerBoundAssign->gtGetOp2();
3133 if (lowerBoundNode->IsIntegralConst(0))
3139 comma = comma->gtGetOp2();
3143 GenTree* lengthNodeAssign = comma->gtGetOp1();
3144 assert(Match::IsArgsFieldInit(lengthNodeAssign, argIndex, lvaNewObjArrayArgs));
3145 GenTree* lengthNode = lengthNodeAssign->gtGetOp2();
3147 if (!lengthNode->IsCnsIntOrI())
3152 numElements *= S_SIZE_T(lengthNode->AsIntCon()->IconValue());
3156 assert((comma != nullptr) && Match::IsArgsAddr(comma, lvaNewObjArrayArgs));
3158 if (argIndex != numArgs)
3166 // Make sure there are exactly two arguments: the array class and
3167 // the number of elements.
3170 GenTreePtr arrayLengthNode;
3172 GenTreeArgList* args = newArrayCall->gtCall.gtCallArgs;
3173 #ifdef FEATURE_READYTORUN_COMPILER
3174 if (newArrayCall->gtCall.gtCallMethHnd == eeFindHelper(CORINFO_HELP_READYTORUN_NEWARR_1))
3176 // Array length is 1st argument for readytorun helper
3177 arrayLengthNode = args->Current();
3182 // Array length is 2nd argument for regular helper
3183 arrayLengthNode = args->Rest()->Current();
3187 // Make sure that the number of elements look valid.
3189 if (arrayLengthNode->gtOper != GT_CNS_INT)
3194 numElements = S_SIZE_T(arrayLengthNode->gtIntCon.gtIconVal);
3196 if (!info.compCompHnd->isSDArray(arrayClsHnd))
3202 CORINFO_CLASS_HANDLE elemClsHnd;
3203 var_types elementType = JITtype2varType(info.compCompHnd->getChildType(arrayClsHnd, &elemClsHnd));
3206 // Note that genTypeSize will return zero for non primitive types, which is exactly
3207 // what we want (size will then be 0, and we will catch this in the conditional below).
3208 // Note that we don't expect this to fail for valid binaries, so we assert in the
3209 // non-verification case (the verification case should not assert but rather correctly
3210 // handle bad binaries). This assert is not guarding any specific invariant, but rather
3211 // saying that we don't expect this to happen, and if it is hit, we need to investigate
3215 S_UINT32 elemSize(genTypeSize(elementType));
3216 S_UINT32 size = elemSize * S_UINT32(numElements);
3218 if (size.IsOverflow())
3223 if ((size.Value() == 0) || (varTypeIsGC(elementType)))
3225 assert(verNeedsVerification());
3229 void* initData = info.compCompHnd->getArrayInitializationData(fieldToken, size.Value());
3236 // At this point we are ready to commit to implementing the InitializeArray
3237 // intrinsic using a struct assignment. Pop the arguments from the stack and
3238 // return the struct assignment node.
3244 const unsigned blkSize = size.Value();
3249 unsigned dataOffset = eeGetMDArrayDataOffset(elementType, rank);
3251 dst = gtNewOperNode(GT_ADD, TYP_BYREF, arrayLocalNode, gtNewIconNode(dataOffset, TYP_I_IMPL));
3255 dst = gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewIndexRef(elementType, arrayLocalNode, gtNewIconNode(0)));
3257 GenTreePtr blk = gtNewBlockVal(dst, blkSize);
3258 GenTreePtr srcAddr = gtNewIconHandleNode((size_t)initData, GTF_ICON_STATIC_HDL);
3259 GenTreePtr src = gtNewOperNode(GT_IND, TYP_STRUCT, srcAddr);
3261 return gtNewBlkOpNode(blk, // dst
3268 /*****************************************************************************/
3269 // Returns the GenTree that should be used to do the intrinsic instead of the call.
3270 // Returns NULL if an intrinsic cannot be used
3272 GenTreePtr Compiler::impIntrinsic(GenTreePtr newobjThis,
3273 CORINFO_CLASS_HANDLE clsHnd,
3274 CORINFO_METHOD_HANDLE method,
3275 CORINFO_SIG_INFO* sig,
3279 CorInfoIntrinsics* pIntrinsicID)
3281 bool mustExpand = false;
3282 #if COR_JIT_EE_VERSION > 460
3283 CorInfoIntrinsics intrinsicID = info.compCompHnd->getIntrinsicID(method, &mustExpand);
3285 CorInfoIntrinsics intrinsicID = info.compCompHnd->getIntrinsicID(method);
3287 *pIntrinsicID = intrinsicID;
3289 #ifndef _TARGET_ARM_
3290 genTreeOps interlockedOperator;
3293 if (intrinsicID == CORINFO_INTRINSIC_StubHelpers_GetStubContext)
3295 // must be done regardless of DbgCode and MinOpts
3296 return gtNewLclvNode(lvaStubArgumentVar, TYP_I_IMPL);
3298 #ifdef _TARGET_64BIT_
3299 if (intrinsicID == CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr)
3301 // must be done regardless of DbgCode and MinOpts
3302 return gtNewOperNode(GT_ADDR, TYP_I_IMPL, gtNewLclvNode(lvaStubArgumentVar, TYP_I_IMPL));
3305 assert(intrinsicID != CORINFO_INTRINSIC_StubHelpers_GetStubContextAddr);
3308 GenTreePtr retNode = nullptr;
3311 // We disable the inlining of instrinsics for MinOpts.
3313 if (!mustExpand && (opts.compDbgCode || opts.MinOpts()))
3315 *pIntrinsicID = CORINFO_INTRINSIC_Illegal;
3319 // Currently we don't have CORINFO_INTRINSIC_Exp because it does not
3320 // seem to work properly for Infinity values, we don't do
3321 // CORINFO_INTRINSIC_Pow because it needs a Helper which we currently don't have
3323 var_types callType = JITtype2varType(sig->retType);
3325 /* First do the intrinsics which are always smaller than a call */
3327 switch (intrinsicID)
3329 GenTreePtr op1, op2;
3331 case CORINFO_INTRINSIC_Sin:
3332 case CORINFO_INTRINSIC_Sqrt:
3333 case CORINFO_INTRINSIC_Abs:
3334 case CORINFO_INTRINSIC_Cos:
3335 case CORINFO_INTRINSIC_Round:
3336 case CORINFO_INTRINSIC_Cosh:
3337 case CORINFO_INTRINSIC_Sinh:
3338 case CORINFO_INTRINSIC_Tan:
3339 case CORINFO_INTRINSIC_Tanh:
3340 case CORINFO_INTRINSIC_Asin:
3341 case CORINFO_INTRINSIC_Acos:
3342 case CORINFO_INTRINSIC_Atan:
3343 case CORINFO_INTRINSIC_Atan2:
3344 case CORINFO_INTRINSIC_Log10:
3345 case CORINFO_INTRINSIC_Pow:
3346 case CORINFO_INTRINSIC_Exp:
3347 case CORINFO_INTRINSIC_Ceiling:
3348 case CORINFO_INTRINSIC_Floor:
3350 // These are math intrinsics
3352 assert(callType != TYP_STRUCT);
3356 #if defined(LEGACY_BACKEND)
3357 if (IsTargetIntrinsic(intrinsicID))
3358 #elif !defined(_TARGET_X86_)
3359 // Intrinsics that are not implemented directly by target instructions will
3360 // be re-materialized as users calls in rationalizer. For prefixed tail calls,
3361 // don't do this optimization, because
3362 // a) For back compatibility reasons on desktop.Net 4.6 / 4.6.1
3363 // b) It will be non-trivial task or too late to re-materialize a surviving
3364 // tail prefixed GT_INTRINSIC as tail call in rationalizer.
3365 if (!IsIntrinsicImplementedByUserCall(intrinsicID) || !tailCall)
3367 // On x86 RyuJIT, importing intrinsics that are implemented as user calls can cause incorrect calculation
3368 // of the depth of the stack if these intrinsics are used as arguments to another call. This causes bad
3369 // code generation for certain EH constructs.
3370 if (!IsIntrinsicImplementedByUserCall(intrinsicID))
3373 switch (sig->numArgs)
3376 op1 = impPopStack().val;
3378 #if FEATURE_X87_DOUBLES
3380 // X87 stack doesn't differentiate between float/double
3381 // so it doesn't need a cast, but everybody else does
3382 // Just double check it is at least a FP type
3383 noway_assert(varTypeIsFloating(op1));
3385 #else // FEATURE_X87_DOUBLES
3387 if (op1->TypeGet() != callType)
3389 op1 = gtNewCastNode(callType, op1, callType);
3392 #endif // FEATURE_X87_DOUBLES
3394 op1 = new (this, GT_INTRINSIC)
3395 GenTreeIntrinsic(genActualType(callType), op1, intrinsicID, method);
3399 op2 = impPopStack().val;
3400 op1 = impPopStack().val;
3402 #if FEATURE_X87_DOUBLES
3404 // X87 stack doesn't differentiate between float/double
3405 // so it doesn't need a cast, but everybody else does
3406 // Just double check it is at least a FP type
3407 noway_assert(varTypeIsFloating(op2));
3408 noway_assert(varTypeIsFloating(op1));
3410 #else // FEATURE_X87_DOUBLES
3412 if (op2->TypeGet() != callType)
3414 op2 = gtNewCastNode(callType, op2, callType);
3416 if (op1->TypeGet() != callType)
3418 op1 = gtNewCastNode(callType, op1, callType);
3421 #endif // FEATURE_X87_DOUBLES
3423 op1 = new (this, GT_INTRINSIC)
3424 GenTreeIntrinsic(genActualType(callType), op1, op2, intrinsicID, method);
3428 NO_WAY("Unsupported number of args for Math Instrinsic");
3431 #ifndef LEGACY_BACKEND
3432 if (IsIntrinsicImplementedByUserCall(intrinsicID))
3434 op1->gtFlags |= GTF_CALL;
3442 #ifdef _TARGET_XARCH_
3443 // TODO-ARM-CQ: reenable treating Interlocked operation as intrinsic
3444 case CORINFO_INTRINSIC_InterlockedAdd32:
3445 interlockedOperator = GT_LOCKADD;
3446 goto InterlockedBinOpCommon;
3447 case CORINFO_INTRINSIC_InterlockedXAdd32:
3448 interlockedOperator = GT_XADD;
3449 goto InterlockedBinOpCommon;
3450 case CORINFO_INTRINSIC_InterlockedXchg32:
3451 interlockedOperator = GT_XCHG;
3452 goto InterlockedBinOpCommon;
3454 #ifdef _TARGET_AMD64_
3455 case CORINFO_INTRINSIC_InterlockedAdd64:
3456 interlockedOperator = GT_LOCKADD;
3457 goto InterlockedBinOpCommon;
3458 case CORINFO_INTRINSIC_InterlockedXAdd64:
3459 interlockedOperator = GT_XADD;
3460 goto InterlockedBinOpCommon;
3461 case CORINFO_INTRINSIC_InterlockedXchg64:
3462 interlockedOperator = GT_XCHG;
3463 goto InterlockedBinOpCommon;
3464 #endif // _TARGET_AMD64_
3466 InterlockedBinOpCommon:
3467 assert(callType != TYP_STRUCT);
3468 assert(sig->numArgs == 2);
3470 op2 = impPopStack().val;
3471 op1 = impPopStack().val;
3477 // field (for example)
3479 // In the case where the first argument is the address of a local, we might
3480 // want to make this *not* make the var address-taken -- but atomic instructions
3481 // on a local are probably pretty useless anyway, so we probably don't care.
3483 op1 = gtNewOperNode(interlockedOperator, genActualType(callType), op1, op2);
3484 op1->gtFlags |= GTF_GLOB_EFFECT;
3487 #endif // _TARGET_XARCH_
3489 case CORINFO_INTRINSIC_MemoryBarrier:
3491 assert(sig->numArgs == 0);
3493 op1 = new (this, GT_MEMORYBARRIER) GenTree(GT_MEMORYBARRIER, TYP_VOID);
3494 op1->gtFlags |= GTF_GLOB_EFFECT;
3498 #ifdef _TARGET_XARCH_
3499 // TODO-ARM-CQ: reenable treating InterlockedCmpXchg32 operation as intrinsic
3500 case CORINFO_INTRINSIC_InterlockedCmpXchg32:
3501 #ifdef _TARGET_AMD64_
3502 case CORINFO_INTRINSIC_InterlockedCmpXchg64:
3505 assert(callType != TYP_STRUCT);
3506 assert(sig->numArgs == 3);
3509 op3 = impPopStack().val; // comparand
3510 op2 = impPopStack().val; // value
3511 op1 = impPopStack().val; // location
3513 GenTreePtr node = new (this, GT_CMPXCHG) GenTreeCmpXchg(genActualType(callType), op1, op2, op3);
3515 node->gtCmpXchg.gtOpLocation->gtFlags |= GTF_DONT_CSE;
3521 case CORINFO_INTRINSIC_StringLength:
3522 op1 = impPopStack().val;
3523 if (!opts.MinOpts() && !opts.compDbgCode)
3525 GenTreeArrLen* arrLen =
3526 new (this, GT_ARR_LENGTH) GenTreeArrLen(TYP_INT, op1, offsetof(CORINFO_String, stringLen));
3531 /* Create the expression "*(str_addr + stringLengthOffset)" */
3532 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1,
3533 gtNewIconNode(offsetof(CORINFO_String, stringLen), TYP_I_IMPL));
3534 op1 = gtNewOperNode(GT_IND, TYP_INT, op1);
3539 case CORINFO_INTRINSIC_StringGetChar:
3540 op2 = impPopStack().val;
3541 op1 = impPopStack().val;
3542 op1 = gtNewIndexRef(TYP_CHAR, op1, op2);
3543 op1->gtFlags |= GTF_INX_STRING_LAYOUT;
3547 case CORINFO_INTRINSIC_InitializeArray:
3548 retNode = impInitializeArrayIntrinsic(sig);
3551 case CORINFO_INTRINSIC_Array_Address:
3552 case CORINFO_INTRINSIC_Array_Get:
3553 case CORINFO_INTRINSIC_Array_Set:
3554 retNode = impArrayAccessIntrinsic(clsHnd, sig, memberRef, readonlyCall, intrinsicID);
3557 case CORINFO_INTRINSIC_GetTypeFromHandle:
3558 op1 = impStackTop(0).val;
3559 if (op1->gtOper == GT_CALL && (op1->gtCall.gtCallType == CT_HELPER) &&
3560 gtIsTypeHandleToRuntimeTypeHelper(op1))
3562 op1 = impPopStack().val;
3563 // Change call to return RuntimeType directly.
3564 op1->gtType = TYP_REF;
3567 // Call the regular function.
3570 case CORINFO_INTRINSIC_RTH_GetValueInternal:
3571 op1 = impStackTop(0).val;
3572 if (op1->gtOper == GT_CALL && (op1->gtCall.gtCallType == CT_HELPER) &&
3573 gtIsTypeHandleToRuntimeTypeHelper(op1))
3576 // Helper-RuntimeTypeHandle -> TreeToGetNativeTypeHandle
3579 // TreeToGetNativeTypeHandle
3581 // Remove call to helper and return the native TypeHandle pointer that was the parameter
3584 op1 = impPopStack().val;
3586 // Get native TypeHandle argument to old helper
3587 op1 = op1->gtCall.gtCallArgs;
3588 assert(op1->OperIsList());
3589 assert(op1->gtOp.gtOp2 == nullptr);
3590 op1 = op1->gtOp.gtOp1;
3593 // Call the regular function.
3596 #ifndef LEGACY_BACKEND
3597 case CORINFO_INTRINSIC_Object_GetType:
3599 op1 = impPopStack().val;
3600 op1 = new (this, GT_INTRINSIC) GenTreeIntrinsic(genActualType(callType), op1, intrinsicID, method);
3602 // Set the CALL flag to indicate that the operator is implemented by a call.
3603 // Set also the EXCEPTION flag because the native implementation of
3604 // CORINFO_INTRINSIC_Object_GetType intrinsic can throw NullReferenceException.
3605 op1->gtFlags |= (GTF_CALL | GTF_EXCEPT);
3609 // Implement ByReference Ctor. This wraps the assignment of the ref into a byref-like field
3610 // in a value type. The canonical example of this is Span<T>. In effect this is just a
3611 // substitution. The parameter byref will be assigned into the newly allocated object.
3612 case CORINFO_INTRINSIC_ByReference_Ctor:
3614 // Remove call to constructor and directly assign the byref passed
3615 // to the call to the first slot of the ByReference struct.
3616 op1 = impPopStack().val;
3617 GenTreePtr thisptr = newobjThis;
3618 CORINFO_FIELD_HANDLE fldHnd = info.compCompHnd->getFieldInClass(clsHnd, 0);
3619 GenTreePtr field = gtNewFieldRef(TYP_BYREF, fldHnd, thisptr, 0, false);
3620 GenTreePtr assign = gtNewAssignNode(field, op1);
3621 GenTreePtr byReferenceStruct = gtCloneExpr(thisptr->gtGetOp1());
3622 assert(byReferenceStruct != nullptr);
3623 impPushOnStack(byReferenceStruct, typeInfo(TI_STRUCT, clsHnd));
3627 // Implement ptr value getter for ByReference struct.
3628 case CORINFO_INTRINSIC_ByReference_Value:
3630 op1 = impPopStack().val;
3631 CORINFO_FIELD_HANDLE fldHnd = info.compCompHnd->getFieldInClass(clsHnd, 0);
3632 GenTreePtr field = gtNewFieldRef(TYP_BYREF, fldHnd, op1, 0, false);
3637 /* Unknown intrinsic */
3643 if (retNode == nullptr)
3645 NO_WAY("JIT must expand the intrinsic!");
3652 /*****************************************************************************/
3654 GenTreePtr Compiler::impArrayAccessIntrinsic(
3655 CORINFO_CLASS_HANDLE clsHnd, CORINFO_SIG_INFO* sig, int memberRef, bool readonlyCall, CorInfoIntrinsics intrinsicID)
3657 /* If we are generating SMALL_CODE, we don't want to use intrinsics for
3658 the following, as it generates fatter code.
3661 if (compCodeOpt() == SMALL_CODE)
3666 /* These intrinsics generate fatter (but faster) code and are only
3667 done if we don't need SMALL_CODE */
3669 unsigned rank = (intrinsicID == CORINFO_INTRINSIC_Array_Set) ? (sig->numArgs - 1) : sig->numArgs;
3671 // The rank 1 case is special because it has to handle two array formats
3672 // we will simply not do that case
3673 if (rank > GT_ARR_MAX_RANK || rank <= 1)
3678 CORINFO_CLASS_HANDLE arrElemClsHnd = nullptr;
3679 var_types elemType = JITtype2varType(info.compCompHnd->getChildType(clsHnd, &arrElemClsHnd));
3681 // For the ref case, we will only be able to inline if the types match
3682 // (verifier checks for this, we don't care for the nonverified case and the
3683 // type is final (so we don't need to do the cast)
3684 if ((intrinsicID != CORINFO_INTRINSIC_Array_Get) && !readonlyCall && varTypeIsGC(elemType))
3686 // Get the call site signature
3687 CORINFO_SIG_INFO LocalSig;
3688 eeGetCallSiteSig(memberRef, info.compScopeHnd, impTokenLookupContextHandle, &LocalSig);
3689 assert(LocalSig.hasThis());
3691 CORINFO_CLASS_HANDLE actualElemClsHnd;
3693 if (intrinsicID == CORINFO_INTRINSIC_Array_Set)
3695 // Fetch the last argument, the one that indicates the type we are setting.
3696 CORINFO_ARG_LIST_HANDLE argType = LocalSig.args;
3697 for (unsigned r = 0; r < rank; r++)
3699 argType = info.compCompHnd->getArgNext(argType);
3702 typeInfo argInfo = verParseArgSigToTypeInfo(&LocalSig, argType);
3703 actualElemClsHnd = argInfo.GetClassHandle();
3707 assert(intrinsicID == CORINFO_INTRINSIC_Array_Address);
3709 // Fetch the return type
3710 typeInfo retInfo = verMakeTypeInfo(LocalSig.retType, LocalSig.retTypeClass);
3711 assert(retInfo.IsByRef());
3712 actualElemClsHnd = retInfo.GetClassHandle();
3715 // if it's not final, we can't do the optimization
3716 if (!(info.compCompHnd->getClassAttribs(actualElemClsHnd) & CORINFO_FLG_FINAL))
3722 unsigned arrayElemSize;
3723 if (elemType == TYP_STRUCT)
3725 assert(arrElemClsHnd);
3727 arrayElemSize = info.compCompHnd->getClassSize(arrElemClsHnd);
3731 arrayElemSize = genTypeSize(elemType);
3734 if ((unsigned char)arrayElemSize != arrayElemSize)
3736 // arrayElemSize would be truncated as an unsigned char.
3737 // This means the array element is too large. Don't do the optimization.
3741 GenTreePtr val = nullptr;
3743 if (intrinsicID == CORINFO_INTRINSIC_Array_Set)
3745 // Assignment of a struct is more work, and there are more gets than sets.
3746 if (elemType == TYP_STRUCT)
3751 val = impPopStack().val;
3752 assert(genActualType(elemType) == genActualType(val->gtType) ||
3753 (elemType == TYP_FLOAT && val->gtType == TYP_DOUBLE) ||
3754 (elemType == TYP_INT && val->gtType == TYP_BYREF) ||
3755 (elemType == TYP_DOUBLE && val->gtType == TYP_FLOAT));
3758 noway_assert((unsigned char)GT_ARR_MAX_RANK == GT_ARR_MAX_RANK);
3760 GenTreePtr inds[GT_ARR_MAX_RANK];
3761 for (unsigned k = rank; k > 0; k--)
3763 inds[k - 1] = impPopStack().val;
3766 GenTreePtr arr = impPopStack().val;
3767 assert(arr->gtType == TYP_REF);
3769 GenTreePtr arrElem =
3770 new (this, GT_ARR_ELEM) GenTreeArrElem(TYP_BYREF, arr, static_cast<unsigned char>(rank),
3771 static_cast<unsigned char>(arrayElemSize), elemType, &inds[0]);
3773 if (intrinsicID != CORINFO_INTRINSIC_Array_Address)
3775 arrElem = gtNewOperNode(GT_IND, elemType, arrElem);
3778 if (intrinsicID == CORINFO_INTRINSIC_Array_Set)
3780 assert(val != nullptr);
3781 return gtNewAssignNode(arrElem, val);
3789 BOOL Compiler::verMergeEntryStates(BasicBlock* block, bool* changed)
3793 // do some basic checks first
3794 if (block->bbStackDepthOnEntry() != verCurrentState.esStackDepth)
3799 if (verCurrentState.esStackDepth > 0)
3801 // merge stack types
3802 StackEntry* parentStack = block->bbStackOnEntry();
3803 StackEntry* childStack = verCurrentState.esStack;
3805 for (i = 0; i < verCurrentState.esStackDepth; i++, parentStack++, childStack++)
3807 if (tiMergeToCommonParent(&parentStack->seTypeInfo, &childStack->seTypeInfo, changed) == FALSE)
3814 // merge initialization status of this ptr
3816 if (verTrackObjCtorInitState)
3818 // If we're tracking the CtorInitState, then it must not be unknown in the current state.
3819 assert(verCurrentState.thisInitialized != TIS_Bottom);
3821 // If the successor block's thisInit state is unknown, copy it from the current state.
3822 if (block->bbThisOnEntry() == TIS_Bottom)
3825 verSetThisInit(block, verCurrentState.thisInitialized);
3827 else if (verCurrentState.thisInitialized != block->bbThisOnEntry())
3829 if (block->bbThisOnEntry() != TIS_Top)
3832 verSetThisInit(block, TIS_Top);
3834 if (block->bbFlags & BBF_FAILED_VERIFICATION)
3836 // The block is bad. Control can flow through the block to any handler that catches the
3837 // verification exception, but the importer ignores bad blocks and therefore won't model
3838 // this flow in the normal way. To complete the merge into the bad block, the new state
3839 // needs to be manually pushed to the handlers that may be reached after the verification
3840 // exception occurs.
3842 // Usually, the new state was already propagated to the relevant handlers while processing
3843 // the predecessors of the bad block. The exception is when the bad block is at the start
3844 // of a try region, meaning it is protected by additional handlers that do not protect its
3847 if (block->hasTryIndex() && ((block->bbFlags & BBF_TRY_BEG) != 0))
3849 // Push TIS_Top to the handlers that protect the bad block. Note that this can cause
3850 // recursive calls back into this code path (if successors of the current bad block are
3851 // also bad blocks).
3853 ThisInitState origTIS = verCurrentState.thisInitialized;
3854 verCurrentState.thisInitialized = TIS_Top;
3855 impVerifyEHBlock(block, true);
3856 verCurrentState.thisInitialized = origTIS;
3864 assert(verCurrentState.thisInitialized == TIS_Bottom && block->bbThisOnEntry() == TIS_Bottom);
3870 /*****************************************************************************
3871 * 'logMsg' is true if a log message needs to be logged. false if the caller has
3872 * already logged it (presumably in a more detailed fashion than done here)
3873 * 'bVerificationException' is true for a verification exception, false for a
3874 * "call unauthorized by host" exception.
3877 void Compiler::verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg))
3879 block->bbJumpKind = BBJ_THROW;
3880 block->bbFlags |= BBF_FAILED_VERIFICATION;
3882 impCurStmtOffsSet(block->bbCodeOffs);
3885 // we need this since BeginTreeList asserts otherwise
3886 impTreeList = impTreeLast = nullptr;
3887 block->bbFlags &= ~BBF_IMPORTED;
3891 JITLOG((LL_ERROR, "Verification failure: while compiling %s near IL offset %x..%xh \n", info.compFullName,
3892 block->bbCodeOffs, block->bbCodeOffsEnd));
3895 printf("\n\nVerification failure: %s near IL %xh \n", info.compFullName, block->bbCodeOffs);
3899 if (JitConfig.DebugBreakOnVerificationFailure())
3907 // if the stack is non-empty evaluate all the side-effects
3908 if (verCurrentState.esStackDepth > 0)
3910 impEvalSideEffects();
3912 assert(verCurrentState.esStackDepth == 0);
3914 GenTreePtr op1 = gtNewHelperCallNode(CORINFO_HELP_VERIFICATION, TYP_VOID, GTF_EXCEPT,
3915 gtNewArgList(gtNewIconNode(block->bbCodeOffs)));
3916 // verCurrentState.esStackDepth = 0;
3917 impAppendTree(op1, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
3919 // The inliner is not able to handle methods that require throw block, so
3920 // make sure this methods never gets inlined.
3921 info.compCompHnd->setMethodAttribs(info.compMethodHnd, CORINFO_FLG_BAD_INLINEE);
3924 /*****************************************************************************
3927 void Compiler::verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg))
3930 // In AMD64, for historical reasons involving design limitations of JIT64, the VM has a
3931 // slightly different mechanism in which it calls the JIT to perform IL verification:
3932 // in the case of transparent methods the VM calls for a predicate IsVerifiable()
3933 // that consists of calling the JIT with the IMPORT_ONLY flag and with the IL verify flag on.
3934 // If the JIT determines the method is not verifiable, it should raise the exception to the VM and let
3935 // it bubble up until reported by the runtime. Currently in RyuJIT, this method doesn't bubble
3936 // up the exception, instead it embeds a throw inside the offending basic block and lets this
3937 // to fail upon runtime of the jitted method.
3939 // For AMD64 we don't want this behavior when the JIT has been called only for verification (i.e.
3940 // with the IMPORT_ONLY and IL Verification flag set) because this won't actually generate code,
3941 // just try to find out whether to fail this method before even actually jitting it. So, in case
3942 // we detect these two conditions, instead of generating a throw statement inside the offending
3943 // basic block, we immediately fail to JIT and notify the VM to make the IsVerifiable() predicate
3944 // to return false and make RyuJIT behave the same way JIT64 does.
3946 // The rationale behind this workaround is to avoid modifying the VM and maintain compatibility between JIT64 and
3947 // RyuJIT for the time being until we completely replace JIT64.
3948 // TODO-ARM64-Cleanup: We probably want to actually modify the VM in the future to avoid the unnecesary two passes.
3950 // In AMD64 we must make sure we're behaving the same way as JIT64, meaning we should only raise the verification
3951 // exception if we are only importing and verifying. The method verNeedsVerification() can also modify the
3952 // tiVerificationNeeded flag in the case it determines it can 'skip verification' during importation and defer it
3953 // to a runtime check. That's why we must assert one or the other (since the flag tiVerificationNeeded can
3954 // be turned off during importation).
3955 CLANG_FORMAT_COMMENT_ANCHOR;
3957 #ifdef _TARGET_64BIT_
3960 bool canSkipVerificationResult =
3961 info.compCompHnd->canSkipMethodVerification(info.compMethodHnd) != CORINFO_VERIFICATION_CANNOT_SKIP;
3962 assert(tiVerificationNeeded || canSkipVerificationResult);
3965 // Add the non verifiable flag to the compiler
3966 if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IMPORT_ONLY))
3968 tiIsVerifiableCode = FALSE;
3970 #endif //_TARGET_64BIT_
3971 verResetCurrentState(block, &verCurrentState);
3972 verConvertBBToThrowVerificationException(block DEBUGARG(logMsg));
3975 impNoteLastILoffs(); // Remember at which BC offset the tree was finished
3979 /******************************************************************************/
3980 typeInfo Compiler::verMakeTypeInfo(CorInfoType ciType, CORINFO_CLASS_HANDLE clsHnd)
3982 assert(ciType < CORINFO_TYPE_COUNT);
3987 case CORINFO_TYPE_STRING:
3988 case CORINFO_TYPE_CLASS:
3989 tiResult = verMakeTypeInfo(clsHnd);
3990 if (!tiResult.IsType(TI_REF))
3991 { // type must be consistent with element type
3996 #ifdef _TARGET_64BIT_
3997 case CORINFO_TYPE_NATIVEINT:
3998 case CORINFO_TYPE_NATIVEUINT:
4001 // If we have more precise information, use it
4002 return verMakeTypeInfo(clsHnd);
4006 return typeInfo::nativeInt();
4009 #endif // _TARGET_64BIT_
4011 case CORINFO_TYPE_VALUECLASS:
4012 case CORINFO_TYPE_REFANY:
4013 tiResult = verMakeTypeInfo(clsHnd);
4014 // type must be constant with element type;
4015 if (!tiResult.IsValueClass())
4020 case CORINFO_TYPE_VAR:
4021 return verMakeTypeInfo(clsHnd);
4023 case CORINFO_TYPE_PTR: // for now, pointers are treated as an error
4024 case CORINFO_TYPE_VOID:
4028 case CORINFO_TYPE_BYREF:
4030 CORINFO_CLASS_HANDLE childClassHandle;
4031 CorInfoType childType = info.compCompHnd->getChildType(clsHnd, &childClassHandle);
4032 return ByRef(verMakeTypeInfo(childType, childClassHandle));
4038 { // If we have more precise information, use it
4039 return typeInfo(TI_STRUCT, clsHnd);
4043 return typeInfo(JITtype2tiType(ciType));
4049 /******************************************************************************/
4051 typeInfo Compiler::verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd, bool bashStructToRef /* = false */)
4053 if (clsHnd == nullptr)
4058 // Byrefs should only occur in method and local signatures, which are accessed
4059 // using ICorClassInfo and ICorClassInfo.getChildType.
4060 // So findClass() and getClassAttribs() should not be called for byrefs
4062 if (JITtype2varType(info.compCompHnd->asCorInfoType(clsHnd)) == TYP_BYREF)
4064 assert(!"Did findClass() return a Byref?");
4068 unsigned attribs = info.compCompHnd->getClassAttribs(clsHnd);
4070 if (attribs & CORINFO_FLG_VALUECLASS)
4072 CorInfoType t = info.compCompHnd->getTypeForPrimitiveValueClass(clsHnd);
4074 // Meta-data validation should ensure that CORINF_TYPE_BYREF should
4075 // not occur here, so we may want to change this to an assert instead.
4076 if (t == CORINFO_TYPE_VOID || t == CORINFO_TYPE_BYREF || t == CORINFO_TYPE_PTR)
4081 #ifdef _TARGET_64BIT_
4082 if (t == CORINFO_TYPE_NATIVEINT || t == CORINFO_TYPE_NATIVEUINT)
4084 return typeInfo::nativeInt();
4086 #endif // _TARGET_64BIT_
4088 if (t != CORINFO_TYPE_UNDEF)
4090 return (typeInfo(JITtype2tiType(t)));
4092 else if (bashStructToRef)
4094 return (typeInfo(TI_REF, clsHnd));
4098 return (typeInfo(TI_STRUCT, clsHnd));
4101 else if (attribs & CORINFO_FLG_GENERIC_TYPE_VARIABLE)
4103 // See comment in _typeInfo.h for why we do it this way.
4104 return (typeInfo(TI_REF, clsHnd, true));
4108 return (typeInfo(TI_REF, clsHnd));
4112 /******************************************************************************/
4113 BOOL Compiler::verIsSDArray(typeInfo ti)
4115 if (ti.IsNullObjRef())
4116 { // nulls are SD arrays
4120 if (!ti.IsType(TI_REF))
4125 if (!info.compCompHnd->isSDArray(ti.GetClassHandleForObjRef()))
4132 /******************************************************************************/
4133 /* Given 'arrayObjectType' which is an array type, fetch the element type. */
4134 /* Returns an error type if anything goes wrong */
4136 typeInfo Compiler::verGetArrayElemType(typeInfo arrayObjectType)
4138 assert(!arrayObjectType.IsNullObjRef()); // you need to check for null explictly since that is a success case
4140 if (!verIsSDArray(arrayObjectType))
4145 CORINFO_CLASS_HANDLE childClassHandle = nullptr;
4146 CorInfoType ciType = info.compCompHnd->getChildType(arrayObjectType.GetClassHandleForObjRef(), &childClassHandle);
4148 return verMakeTypeInfo(ciType, childClassHandle);
4151 /*****************************************************************************
4153 typeInfo Compiler::verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args)
4155 CORINFO_CLASS_HANDLE classHandle;
4156 CorInfoType ciType = strip(info.compCompHnd->getArgType(sig, args, &classHandle));
4158 var_types type = JITtype2varType(ciType);
4159 if (varTypeIsGC(type))
4161 // For efficiency, getArgType only returns something in classHandle for
4162 // value types. For other types that have addition type info, you
4163 // have to call back explicitly
4164 classHandle = info.compCompHnd->getArgClass(sig, args);
4167 NO_WAY("Could not figure out Class specified in argument or local signature");
4171 return verMakeTypeInfo(ciType, classHandle);
4174 /*****************************************************************************/
4176 // This does the expensive check to figure out whether the method
4177 // needs to be verified. It is called only when we fail verification,
4178 // just before throwing the verification exception.
4180 BOOL Compiler::verNeedsVerification()
4182 // If we have previously determined that verification is NOT needed
4183 // (for example in Compiler::compCompile), that means verification is really not needed.
4184 // Return the same decision we made before.
4185 // (Note: This literally means that tiVerificationNeeded can never go from 0 to 1.)
4187 if (!tiVerificationNeeded)
4189 return tiVerificationNeeded;
4192 assert(tiVerificationNeeded);
4194 // Ok, we haven't concluded that verification is NOT needed. Consult the EE now to
4195 // obtain the answer.
4196 CorInfoCanSkipVerificationResult canSkipVerificationResult =
4197 info.compCompHnd->canSkipMethodVerification(info.compMethodHnd);
4199 // canSkipVerification will return one of the following three values:
4200 // CORINFO_VERIFICATION_CANNOT_SKIP = 0, // Cannot skip verification during jit time.
4201 // CORINFO_VERIFICATION_CAN_SKIP = 1, // Can skip verification during jit time.
4202 // CORINFO_VERIFICATION_RUNTIME_CHECK = 2, // Skip verification during jit time,
4203 // but need to insert a callout to the VM to ask during runtime
4204 // whether to skip verification or not.
4206 // Set tiRuntimeCalloutNeeded if canSkipVerification() instructs us to insert a callout for runtime check
4207 if (canSkipVerificationResult == CORINFO_VERIFICATION_RUNTIME_CHECK)
4209 tiRuntimeCalloutNeeded = true;
4212 if (canSkipVerificationResult == CORINFO_VERIFICATION_DONT_JIT)
4214 // Dev10 706080 - Testers don't like the assert, so just silence it
4215 // by not using the macros that invoke debugAssert.
4219 // When tiVerificationNeeded is true, JIT will do the verification during JIT time.
4220 // The following line means we will NOT do jit time verification if canSkipVerification
4221 // returns CORINFO_VERIFICATION_CAN_SKIP or CORINFO_VERIFICATION_RUNTIME_CHECK.
4222 tiVerificationNeeded = (canSkipVerificationResult == CORINFO_VERIFICATION_CANNOT_SKIP);
4223 return tiVerificationNeeded;
4226 BOOL Compiler::verIsByRefLike(const typeInfo& ti)
4232 if (!ti.IsType(TI_STRUCT))
4236 return info.compCompHnd->getClassAttribs(ti.GetClassHandleForValueClass()) & CORINFO_FLG_CONTAINS_STACK_PTR;
4239 BOOL Compiler::verIsSafeToReturnByRef(const typeInfo& ti)
4241 if (ti.IsPermanentHomeByRef())
4251 BOOL Compiler::verIsBoxable(const typeInfo& ti)
4253 return (ti.IsPrimitiveType() || ti.IsObjRef() // includes boxed generic type variables
4254 || ti.IsUnboxedGenericTypeVar() ||
4255 (ti.IsType(TI_STRUCT) &&
4256 // exclude byreflike structs
4257 !(info.compCompHnd->getClassAttribs(ti.GetClassHandleForValueClass()) & CORINFO_FLG_CONTAINS_STACK_PTR)));
4260 // Is it a boxed value type?
4261 bool Compiler::verIsBoxedValueType(typeInfo ti)
4263 if (ti.GetType() == TI_REF)
4265 CORINFO_CLASS_HANDLE clsHnd = ti.GetClassHandleForObjRef();
4266 return !!eeIsValueClass(clsHnd);
4274 /*****************************************************************************
4276 * Check if a TailCall is legal.
4279 bool Compiler::verCheckTailCallConstraint(
4281 CORINFO_RESOLVED_TOKEN* pResolvedToken,
4282 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a type parameter?
4283 bool speculative // If true, won't throw if verificatoin fails. Instead it will
4284 // return false to the caller.
4285 // If false, it will throw.
4289 CORINFO_SIG_INFO sig;
4290 unsigned int popCount = 0; // we can't pop the stack since impImportCall needs it, so
4291 // this counter is used to keep track of how many items have been
4294 CORINFO_METHOD_HANDLE methodHnd = nullptr;
4295 CORINFO_CLASS_HANDLE methodClassHnd = nullptr;
4296 unsigned methodClassFlgs = 0;
4298 assert(impOpcodeIsCallOpcode(opcode));
4300 if (compIsForInlining())
4305 // for calli, VerifyOrReturn that this is not a virtual method
4306 if (opcode == CEE_CALLI)
4308 /* Get the call sig */
4309 eeGetSig(pResolvedToken->token, info.compScopeHnd, impTokenLookupContextHandle, &sig);
4311 // We don't know the target method, so we have to infer the flags, or
4312 // assume the worst-case.
4313 mflags = (sig.callConv & CORINFO_CALLCONV_HASTHIS) ? 0 : CORINFO_FLG_STATIC;
4317 methodHnd = pResolvedToken->hMethod;
4319 mflags = info.compCompHnd->getMethodAttribs(methodHnd);
4321 // When verifying generic code we pair the method handle with its
4322 // owning class to get the exact method signature.
4323 methodClassHnd = pResolvedToken->hClass;
4324 assert(methodClassHnd);
4326 eeGetMethodSig(methodHnd, &sig, methodClassHnd);
4328 // opcode specific check
4329 methodClassFlgs = info.compCompHnd->getClassAttribs(methodClassHnd);
4332 // We must have got the methodClassHnd if opcode is not CEE_CALLI
4333 assert((methodHnd != nullptr && methodClassHnd != nullptr) || opcode == CEE_CALLI);
4335 if ((sig.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
4337 eeGetCallSiteSig(pResolvedToken->token, info.compScopeHnd, impTokenLookupContextHandle, &sig);
4340 // check compatibility of the arguments
4341 unsigned int argCount;
4342 argCount = sig.numArgs;
4343 CORINFO_ARG_LIST_HANDLE args;
4347 typeInfo tiDeclared = verParseArgSigToTypeInfo(&sig, args).NormaliseForStack();
4349 // check that the argument is not a byref for tailcalls
4350 VerifyOrReturnSpeculative(!verIsByRefLike(tiDeclared), "tailcall on byrefs", speculative);
4352 // For unsafe code, we might have parameters containing pointer to the stack location.
4353 // Disallow the tailcall for this kind.
4354 CORINFO_CLASS_HANDLE classHandle;
4355 CorInfoType ciType = strip(info.compCompHnd->getArgType(&sig, args, &classHandle));
4356 VerifyOrReturnSpeculative(ciType != CORINFO_TYPE_PTR, "tailcall on CORINFO_TYPE_PTR", speculative);
4358 args = info.compCompHnd->getArgNext(args);
4362 popCount += sig.numArgs;
4364 // check for 'this' which is on non-static methods, not called via NEWOBJ
4365 if (!(mflags & CORINFO_FLG_STATIC))
4367 // Always update the popCount.
4368 // This is crucial for the stack calculation to be correct.
4369 typeInfo tiThis = impStackTop(popCount).seTypeInfo;
4372 if (opcode == CEE_CALLI)
4374 // For CALLI, we don't know the methodClassHnd. Therefore, let's check the "this" object
4376 if (tiThis.IsValueClass())
4380 VerifyOrReturnSpeculative(!verIsByRefLike(tiThis), "byref in tailcall", speculative);
4384 // Check type compatibility of the this argument
4385 typeInfo tiDeclaredThis = verMakeTypeInfo(methodClassHnd);
4386 if (tiDeclaredThis.IsValueClass())
4388 tiDeclaredThis.MakeByRef();
4391 VerifyOrReturnSpeculative(!verIsByRefLike(tiDeclaredThis), "byref in tailcall", speculative);
4395 // Tail calls on constrained calls should be illegal too:
4396 // when instantiated at a value type, a constrained call may pass the address of a stack allocated value
4397 VerifyOrReturnSpeculative(!pConstrainedResolvedToken, "byref in constrained tailcall", speculative);
4399 // Get the exact view of the signature for an array method
4400 if (sig.retType != CORINFO_TYPE_VOID)
4402 if (methodClassFlgs & CORINFO_FLG_ARRAY)
4404 assert(opcode != CEE_CALLI);
4405 eeGetCallSiteSig(pResolvedToken->token, info.compScopeHnd, impTokenLookupContextHandle, &sig);
4409 typeInfo tiCalleeRetType = verMakeTypeInfo(sig.retType, sig.retTypeClass);
4410 typeInfo tiCallerRetType =
4411 verMakeTypeInfo(info.compMethodInfo->args.retType, info.compMethodInfo->args.retTypeClass);
4413 // void return type gets morphed into the error type, so we have to treat them specially here
4414 if (sig.retType == CORINFO_TYPE_VOID)
4416 VerifyOrReturnSpeculative(info.compMethodInfo->args.retType == CORINFO_TYPE_VOID, "tailcall return mismatch",
4421 VerifyOrReturnSpeculative(tiCompatibleWith(NormaliseForStack(tiCalleeRetType),
4422 NormaliseForStack(tiCallerRetType), true),
4423 "tailcall return mismatch", speculative);
4426 // for tailcall, stack must be empty
4427 VerifyOrReturnSpeculative(verCurrentState.esStackDepth == popCount, "stack non-empty on tailcall", speculative);
4429 return true; // Yes, tailcall is legal
4432 /*****************************************************************************
4434 * Checks the IL verification rules for the call
4437 void Compiler::verVerifyCall(OPCODE opcode,
4438 CORINFO_RESOLVED_TOKEN* pResolvedToken,
4439 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
4442 const BYTE* delegateCreateStart,
4443 const BYTE* codeAddr,
4444 CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName))
4447 CORINFO_SIG_INFO* sig = nullptr;
4448 unsigned int popCount = 0; // we can't pop the stack since impImportCall needs it, so
4449 // this counter is used to keep track of how many items have been
4452 // for calli, VerifyOrReturn that this is not a virtual method
4453 if (opcode == CEE_CALLI)
4455 Verify(false, "Calli not verifiable");
4459 //<NICE> It would be nice to cache the rest of it, but eeFindMethod is the big ticket item.
4460 mflags = callInfo->verMethodFlags;
4462 sig = &callInfo->verSig;
4464 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
4466 eeGetCallSiteSig(pResolvedToken->token, pResolvedToken->tokenScope, pResolvedToken->tokenContext, sig);
4469 // opcode specific check
4470 unsigned methodClassFlgs = callInfo->classFlags;
4474 // cannot do callvirt on valuetypes
4475 VerifyOrReturn(!(methodClassFlgs & CORINFO_FLG_VALUECLASS), "callVirt on value class");
4476 VerifyOrReturn(sig->hasThis(), "CallVirt on static method");
4481 assert(!tailCall); // Importer should not allow this
4482 VerifyOrReturn((mflags & CORINFO_FLG_CONSTRUCTOR) && !(mflags & CORINFO_FLG_STATIC),
4483 "newobj must be on instance");
4485 if (methodClassFlgs & CORINFO_FLG_DELEGATE)
4487 VerifyOrReturn(sig->numArgs == 2, "wrong number args to delegate ctor");
4488 typeInfo tiDeclaredObj = verParseArgSigToTypeInfo(sig, sig->args).NormaliseForStack();
4489 typeInfo tiDeclaredFtn =
4490 verParseArgSigToTypeInfo(sig, info.compCompHnd->getArgNext(sig->args)).NormaliseForStack();
4491 VerifyOrReturn(tiDeclaredFtn.IsNativeIntType(), "ftn arg needs to be a native int type");
4493 assert(popCount == 0);
4494 typeInfo tiActualObj = impStackTop(1).seTypeInfo;
4495 typeInfo tiActualFtn = impStackTop(0).seTypeInfo;
4497 VerifyOrReturn(tiActualFtn.IsMethod(), "delegate needs method as first arg");
4498 VerifyOrReturn(tiCompatibleWith(tiActualObj, tiDeclaredObj, true), "delegate object type mismatch");
4499 VerifyOrReturn(tiActualObj.IsNullObjRef() || tiActualObj.IsType(TI_REF),
4500 "delegate object type mismatch");
4502 CORINFO_CLASS_HANDLE objTypeHandle =
4503 tiActualObj.IsNullObjRef() ? nullptr : tiActualObj.GetClassHandleForObjRef();
4505 // the method signature must be compatible with the delegate's invoke method
4507 // check that for virtual functions, the type of the object used to get the
4508 // ftn ptr is the same as the type of the object passed to the delegate ctor.
4509 // since this is a bit of work to determine in general, we pattern match stylized
4512 // the delegate creation code check, which used to be done later, is now done here
4513 // so we can read delegateMethodRef directly from
4514 // from the preceding LDFTN or CEE_LDVIRTFN instruction sequence;
4515 // we then use it in our call to isCompatibleDelegate().
4517 mdMemberRef delegateMethodRef = mdMemberRefNil;
4518 VerifyOrReturn(verCheckDelegateCreation(delegateCreateStart, codeAddr, delegateMethodRef),
4519 "must create delegates with certain IL");
4521 CORINFO_RESOLVED_TOKEN delegateResolvedToken;
4522 delegateResolvedToken.tokenContext = impTokenLookupContextHandle;
4523 delegateResolvedToken.tokenScope = info.compScopeHnd;
4524 delegateResolvedToken.token = delegateMethodRef;
4525 delegateResolvedToken.tokenType = CORINFO_TOKENKIND_Method;
4526 info.compCompHnd->resolveToken(&delegateResolvedToken);
4528 CORINFO_CALL_INFO delegateCallInfo;
4529 eeGetCallInfo(&delegateResolvedToken, nullptr /* constraint typeRef */,
4530 addVerifyFlag(CORINFO_CALLINFO_SECURITYCHECKS), &delegateCallInfo);
4532 BOOL isOpenDelegate = FALSE;
4533 VerifyOrReturn(info.compCompHnd->isCompatibleDelegate(objTypeHandle, delegateResolvedToken.hClass,
4534 tiActualFtn.GetMethod(), pResolvedToken->hClass,
4536 "function incompatible with delegate");
4538 // check the constraints on the target method
4539 VerifyOrReturn(info.compCompHnd->satisfiesClassConstraints(delegateResolvedToken.hClass),
4540 "delegate target has unsatisfied class constraints");
4541 VerifyOrReturn(info.compCompHnd->satisfiesMethodConstraints(delegateResolvedToken.hClass,
4542 tiActualFtn.GetMethod()),
4543 "delegate target has unsatisfied method constraints");
4545 // See ECMA spec section 1.8.1.5.2 (Delegating via instance dispatch)
4546 // for additional verification rules for delegates
4547 CORINFO_METHOD_HANDLE actualMethodHandle = tiActualFtn.GetMethod();
4548 DWORD actualMethodAttribs = info.compCompHnd->getMethodAttribs(actualMethodHandle);
4549 if (impIsLDFTN_TOKEN(delegateCreateStart, codeAddr))
4552 if ((actualMethodAttribs & CORINFO_FLG_VIRTUAL) && ((actualMethodAttribs & CORINFO_FLG_FINAL) == 0)
4554 && StrictCheckForNonVirtualCallToVirtualMethod()
4558 if (info.compCompHnd->shouldEnforceCallvirtRestriction(info.compScopeHnd))
4560 VerifyOrReturn(tiActualObj.IsThisPtr() && lvaIsOriginalThisReadOnly() ||
4561 verIsBoxedValueType(tiActualObj),
4562 "The 'this' parameter to the call must be either the calling method's "
4563 "'this' parameter or "
4564 "a boxed value type.");
4569 if (actualMethodAttribs & CORINFO_FLG_PROTECTED)
4571 BOOL targetIsStatic = actualMethodAttribs & CORINFO_FLG_STATIC;
4573 Verify(targetIsStatic || !isOpenDelegate,
4574 "Unverifiable creation of an open instance delegate for a protected member.");
4576 CORINFO_CLASS_HANDLE instanceClassHnd = (tiActualObj.IsNullObjRef() || targetIsStatic)
4578 : tiActualObj.GetClassHandleForObjRef();
4580 // In the case of protected methods, it is a requirement that the 'this'
4581 // pointer be a subclass of the current context. Perform this check.
4582 Verify(info.compCompHnd->canAccessFamily(info.compMethodHnd, instanceClassHnd),
4583 "Accessing protected method through wrong type.");
4588 // fall thru to default checks
4590 VerifyOrReturn(!(mflags & CORINFO_FLG_ABSTRACT), "method abstract");
4592 VerifyOrReturn(!((mflags & CORINFO_FLG_CONSTRUCTOR) && (methodClassFlgs & CORINFO_FLG_DELEGATE)),
4593 "can only newobj a delegate constructor");
4595 // check compatibility of the arguments
4596 unsigned int argCount;
4597 argCount = sig->numArgs;
4598 CORINFO_ARG_LIST_HANDLE args;
4602 typeInfo tiActual = impStackTop(popCount + argCount).seTypeInfo;
4604 typeInfo tiDeclared = verParseArgSigToTypeInfo(sig, args).NormaliseForStack();
4605 VerifyOrReturn(tiCompatibleWith(tiActual, tiDeclared, true), "type mismatch");
4607 args = info.compCompHnd->getArgNext(args);
4613 popCount += sig->numArgs;
4615 // check for 'this' which are is non-static methods, not called via NEWOBJ
4616 CORINFO_CLASS_HANDLE instanceClassHnd = info.compClassHnd;
4617 if (!(mflags & CORINFO_FLG_STATIC) && (opcode != CEE_NEWOBJ))
4619 typeInfo tiThis = impStackTop(popCount).seTypeInfo;
4622 // If it is null, we assume we can access it (since it will AV shortly)
4623 // If it is anything but a reference class, there is no hierarchy, so
4624 // again, we don't need the precise instance class to compute 'protected' access
4625 if (tiThis.IsType(TI_REF))
4627 instanceClassHnd = tiThis.GetClassHandleForObjRef();
4630 // Check type compatibility of the this argument
4631 typeInfo tiDeclaredThis = verMakeTypeInfo(pResolvedToken->hClass);
4632 if (tiDeclaredThis.IsValueClass())
4634 tiDeclaredThis.MakeByRef();
4637 // If this is a call to the base class .ctor, set thisPtr Init for
4639 if (mflags & CORINFO_FLG_CONSTRUCTOR)
4641 if (verTrackObjCtorInitState && tiThis.IsThisPtr() &&
4642 verIsCallToInitThisPtr(info.compClassHnd, pResolvedToken->hClass))
4644 assert(verCurrentState.thisInitialized !=
4645 TIS_Bottom); // This should never be the case just from the logic of the verifier.
4646 VerifyOrReturn(verCurrentState.thisInitialized == TIS_Uninit,
4647 "Call to base class constructor when 'this' is possibly initialized");
4648 // Otherwise, 'this' is now initialized.
4649 verCurrentState.thisInitialized = TIS_Init;
4650 tiThis.SetInitialisedObjRef();
4654 // We allow direct calls to value type constructors
4655 // NB: we have to check that the contents of tiThis is a value type, otherwise we could use a
4656 // constrained callvirt to illegally re-enter a .ctor on a value of reference type.
4657 VerifyOrReturn(tiThis.IsByRef() && DereferenceByRef(tiThis).IsValueClass(),
4658 "Bad call to a constructor");
4662 if (pConstrainedResolvedToken != nullptr)
4664 VerifyOrReturn(tiThis.IsByRef(), "non-byref this type in constrained call");
4666 typeInfo tiConstraint = verMakeTypeInfo(pConstrainedResolvedToken->hClass);
4668 // We just dereference this and test for equality
4669 tiThis.DereferenceByRef();
4670 VerifyOrReturn(typeInfo::AreEquivalent(tiThis, tiConstraint),
4671 "this type mismatch with constrained type operand");
4673 // Now pretend the this type is the boxed constrained type, for the sake of subsequent checks
4674 tiThis = typeInfo(TI_REF, pConstrainedResolvedToken->hClass);
4677 // To support direct calls on readonly byrefs, just pretend tiDeclaredThis is readonly too
4678 if (tiDeclaredThis.IsByRef() && tiThis.IsReadonlyByRef())
4680 tiDeclaredThis.SetIsReadonlyByRef();
4683 VerifyOrReturn(tiCompatibleWith(tiThis, tiDeclaredThis, true), "this type mismatch");
4685 if (tiThis.IsByRef())
4687 // Find the actual type where the method exists (as opposed to what is declared
4688 // in the metadata). This is to prevent passing a byref as the "this" argument
4689 // while calling methods like System.ValueType.GetHashCode() which expect boxed objects.
4691 CORINFO_CLASS_HANDLE actualClassHnd = info.compCompHnd->getMethodClass(pResolvedToken->hMethod);
4692 VerifyOrReturn(eeIsValueClass(actualClassHnd),
4693 "Call to base type of valuetype (which is never a valuetype)");
4696 // Rules for non-virtual call to a non-final virtual method:
4699 // The "this" pointer is considered to be "possibly written" if
4700 // 1. Its address have been taken (LDARGA 0) anywhere in the method.
4702 // 2. It has been stored to (STARG.0) anywhere in the method.
4704 // A non-virtual call to a non-final virtual method is only allowed if
4705 // 1. The this pointer passed to the callee is an instance of a boxed value type.
4707 // 2. The this pointer passed to the callee is the current method's this pointer.
4708 // (and) The current method's this pointer is not "possibly written".
4710 // Thus the rule is that if you assign to this ANYWHERE you can't make "base" calls to
4711 // virtual methods. (Luckily this does affect .ctors, since they are not virtual).
4712 // This is stronger that is strictly needed, but implementing a laxer rule is significantly
4713 // hard and more error prone.
4715 if (opcode == CEE_CALL && (mflags & CORINFO_FLG_VIRTUAL) && ((mflags & CORINFO_FLG_FINAL) == 0)
4717 && StrictCheckForNonVirtualCallToVirtualMethod()
4721 if (info.compCompHnd->shouldEnforceCallvirtRestriction(info.compScopeHnd))
4724 tiThis.IsThisPtr() && lvaIsOriginalThisReadOnly() || verIsBoxedValueType(tiThis),
4725 "The 'this' parameter to the call must be either the calling method's 'this' parameter or "
4726 "a boxed value type.");
4731 // check any constraints on the callee's class and type parameters
4732 VerifyOrReturn(info.compCompHnd->satisfiesClassConstraints(pResolvedToken->hClass),
4733 "method has unsatisfied class constraints");
4734 VerifyOrReturn(info.compCompHnd->satisfiesMethodConstraints(pResolvedToken->hClass, pResolvedToken->hMethod),
4735 "method has unsatisfied method constraints");
4737 if (mflags & CORINFO_FLG_PROTECTED)
4739 VerifyOrReturn(info.compCompHnd->canAccessFamily(info.compMethodHnd, instanceClassHnd),
4740 "Can't access protected method");
4743 // Get the exact view of the signature for an array method
4744 if (sig->retType != CORINFO_TYPE_VOID)
4746 eeGetMethodSig(pResolvedToken->hMethod, sig, pResolvedToken->hClass);
4749 // "readonly." prefixed calls only allowed for the Address operation on arrays.
4750 // The methods supported by array types are under the control of the EE
4751 // so we can trust that only the Address operation returns a byref.
4754 typeInfo tiCalleeRetType = verMakeTypeInfo(sig->retType, sig->retTypeClass);
4755 VerifyOrReturn((methodClassFlgs & CORINFO_FLG_ARRAY) && tiCalleeRetType.IsByRef(),
4756 "unexpected use of readonly prefix");
4759 // Verify the tailcall
4762 verCheckTailCallConstraint(opcode, pResolvedToken, pConstrainedResolvedToken, false);
4766 /*****************************************************************************
4767 * Checks that a delegate creation is done using the following pattern:
4769 * ldvirtftn targetMemberRef
4771 * ldftn targetMemberRef
4773 * 'delegateCreateStart' points at the last dup or ldftn in this basic block (null if
4774 * not in this basic block)
4776 * targetMemberRef is read from the code sequence.
4777 * targetMemberRef is validated iff verificationNeeded.
4780 BOOL Compiler::verCheckDelegateCreation(const BYTE* delegateCreateStart,
4781 const BYTE* codeAddr,
4782 mdMemberRef& targetMemberRef)
4784 if (impIsLDFTN_TOKEN(delegateCreateStart, codeAddr))
4786 targetMemberRef = getU4LittleEndian(&delegateCreateStart[2]);
4789 else if (impIsDUP_LDVIRTFTN_TOKEN(delegateCreateStart, codeAddr))
4791 targetMemberRef = getU4LittleEndian(&delegateCreateStart[3]);
4798 typeInfo Compiler::verVerifySTIND(const typeInfo& tiTo, const typeInfo& value, const typeInfo& instrType)
4800 Verify(!tiTo.IsReadonlyByRef(), "write to readonly byref");
4801 typeInfo ptrVal = verVerifyLDIND(tiTo, instrType);
4802 typeInfo normPtrVal = typeInfo(ptrVal).NormaliseForStack();
4803 if (!tiCompatibleWith(value, normPtrVal, true))
4805 Verify(tiCompatibleWith(value, normPtrVal, true), "type mismatch");
4806 compUnsafeCastUsed = true;
4811 typeInfo Compiler::verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType)
4813 assert(!instrType.IsStruct());
4818 ptrVal = DereferenceByRef(ptr);
4819 if (instrType.IsObjRef() && !ptrVal.IsObjRef())
4821 Verify(false, "bad pointer");
4822 compUnsafeCastUsed = true;
4824 else if (!instrType.IsObjRef() && !typeInfo::AreEquivalent(instrType, ptrVal))
4826 Verify(false, "pointer not consistent with instr");
4827 compUnsafeCastUsed = true;
4832 Verify(false, "pointer not byref");
4833 compUnsafeCastUsed = true;
4839 // Verify that the field is used properly. 'tiThis' is NULL for statics,
4840 // 'fieldFlags' is the fields attributes, and mutator is TRUE if it is a
4841 // ld*flda or a st*fld.
4842 // 'enclosingClass' is given if we are accessing a field in some specific type.
4844 void Compiler::verVerifyField(CORINFO_RESOLVED_TOKEN* pResolvedToken,
4845 const CORINFO_FIELD_INFO& fieldInfo,
4846 const typeInfo* tiThis,
4848 BOOL allowPlainStructAsThis)
4850 CORINFO_CLASS_HANDLE enclosingClass = pResolvedToken->hClass;
4851 unsigned fieldFlags = fieldInfo.fieldFlags;
4852 CORINFO_CLASS_HANDLE instanceClass =
4853 info.compClassHnd; // for statics, we imagine the instance is the current class.
4855 bool isStaticField = ((fieldFlags & CORINFO_FLG_FIELD_STATIC) != 0);
4858 Verify(!(fieldFlags & CORINFO_FLG_FIELD_UNMANAGED), "mutating an RVA bases static");
4859 if ((fieldFlags & CORINFO_FLG_FIELD_FINAL))
4861 Verify((info.compFlags & CORINFO_FLG_CONSTRUCTOR) && enclosingClass == info.compClassHnd &&
4862 info.compIsStatic == isStaticField,
4863 "bad use of initonly field (set or address taken)");
4867 if (tiThis == nullptr)
4869 Verify(isStaticField, "used static opcode with non-static field");
4873 typeInfo tThis = *tiThis;
4875 if (allowPlainStructAsThis && tThis.IsValueClass())
4880 // If it is null, we assume we can access it (since it will AV shortly)
4881 // If it is anything but a refernce class, there is no hierarchy, so
4882 // again, we don't need the precise instance class to compute 'protected' access
4883 if (tiThis->IsType(TI_REF))
4885 instanceClass = tiThis->GetClassHandleForObjRef();
4888 // Note that even if the field is static, we require that the this pointer
4889 // satisfy the same constraints as a non-static field This happens to
4890 // be simpler and seems reasonable
4891 typeInfo tiDeclaredThis = verMakeTypeInfo(enclosingClass);
4892 if (tiDeclaredThis.IsValueClass())
4894 tiDeclaredThis.MakeByRef();
4896 // we allow read-only tThis, on any field access (even stores!), because if the
4897 // class implementor wants to prohibit stores he should make the field private.
4898 // we do this by setting the read-only bit on the type we compare tThis to.
4899 tiDeclaredThis.SetIsReadonlyByRef();
4901 else if (verTrackObjCtorInitState && tThis.IsThisPtr())
4903 // Any field access is legal on "uninitialized" this pointers.
4904 // The easiest way to implement this is to simply set the
4905 // initialized bit for the duration of the type check on the
4906 // field access only. It does not change the state of the "this"
4907 // for the function as a whole. Note that the "tThis" is a copy
4908 // of the original "this" type (*tiThis) passed in.
4909 tThis.SetInitialisedObjRef();
4912 Verify(tiCompatibleWith(tThis, tiDeclaredThis, true), "this type mismatch");
4915 // Presently the JIT does not check that we don't store or take the address of init-only fields
4916 // since we cannot guarantee their immutability and it is not a security issue.
4918 // check any constraints on the fields's class --- accessing the field might cause a class constructor to run.
4919 VerifyOrReturn(info.compCompHnd->satisfiesClassConstraints(enclosingClass),
4920 "field has unsatisfied class constraints");
4921 if (fieldFlags & CORINFO_FLG_FIELD_PROTECTED)
4923 Verify(info.compCompHnd->canAccessFamily(info.compMethodHnd, instanceClass),
4924 "Accessing protected method through wrong type.");
4928 void Compiler::verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode)
4930 if (tiOp1.IsNumberType())
4932 #ifdef _TARGET_64BIT_
4933 Verify(tiCompatibleWith(tiOp1, tiOp2, true), "Cond type mismatch");
4934 #else // _TARGET_64BIT
4935 // [10/17/2013] Consider changing this: to put on my verification lawyer hat,
4936 // this is non-conforming to the ECMA Spec: types don't have to be equivalent,
4937 // but compatible, since we can coalesce native int with int32 (see section III.1.5).
4938 Verify(typeInfo::AreEquivalent(tiOp1, tiOp2), "Cond type mismatch");
4939 #endif // !_TARGET_64BIT_
4941 else if (tiOp1.IsObjRef())
4953 Verify(FALSE, "Cond not allowed on object types");
4955 Verify(tiOp2.IsObjRef(), "Cond type mismatch");
4957 else if (tiOp1.IsByRef())
4959 Verify(tiOp2.IsByRef(), "Cond type mismatch");
4963 Verify(tiOp1.IsMethod() && tiOp2.IsMethod(), "Cond type mismatch");
4967 void Compiler::verVerifyThisPtrInitialised()
4969 if (verTrackObjCtorInitState)
4971 Verify(verCurrentState.thisInitialized == TIS_Init, "this ptr is not initialized");
4975 BOOL Compiler::verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target)
4977 // Either target == context, in this case calling an alternate .ctor
4978 // Or target is the immediate parent of context
4980 return ((target == context) || (target == info.compCompHnd->getParentType(context)));
4983 GenTreePtr Compiler::impImportLdvirtftn(GenTreePtr thisPtr,
4984 CORINFO_RESOLVED_TOKEN* pResolvedToken,
4985 CORINFO_CALL_INFO* pCallInfo)
4987 if ((pCallInfo->methodFlags & CORINFO_FLG_EnC) && !(pCallInfo->classFlags & CORINFO_FLG_INTERFACE))
4989 NO_WAY("Virtual call to a function added via EnC is not supported");
4992 #ifdef FEATURE_READYTORUN_COMPILER
4993 if (opts.IsReadyToRun())
4995 if (!pCallInfo->exactContextNeedsRuntimeLookup)
4997 GenTreeCall* call = gtNewHelperCallNode(CORINFO_HELP_READYTORUN_VIRTUAL_FUNC_PTR, TYP_I_IMPL, GTF_EXCEPT,
4998 gtNewArgList(thisPtr));
5000 call->setEntryPoint(pCallInfo->codePointerLookup.constLookup);
5005 // We need a runtime lookup. CoreRT has a ReadyToRun helper for that too.
5006 if (IsTargetAbi(CORINFO_CORERT_ABI))
5008 GenTreePtr ctxTree = getRuntimeContextTree(pCallInfo->codePointerLookup.lookupKind.runtimeLookupKind);
5010 return impReadyToRunHelperToTree(pResolvedToken, CORINFO_HELP_READYTORUN_GENERIC_HANDLE, TYP_I_IMPL,
5011 gtNewArgList(ctxTree), &pCallInfo->codePointerLookup.lookupKind);
5016 // Get the exact descriptor for the static callsite
5017 GenTreePtr exactTypeDesc = impParentClassTokenToHandle(pResolvedToken);
5018 if (exactTypeDesc == nullptr)
5019 { // compDonotInline()
5023 GenTreePtr exactMethodDesc = impTokenToHandle(pResolvedToken);
5024 if (exactMethodDesc == nullptr)
5025 { // compDonotInline()
5029 GenTreeArgList* helpArgs = gtNewArgList(exactMethodDesc);
5031 helpArgs = gtNewListNode(exactTypeDesc, helpArgs);
5033 helpArgs = gtNewListNode(thisPtr, helpArgs);
5035 // Call helper function. This gets the target address of the final destination callsite.
5037 return gtNewHelperCallNode(CORINFO_HELP_VIRTUAL_FUNC_PTR, TYP_I_IMPL, GTF_EXCEPT, helpArgs);
5040 /*****************************************************************************
5042 * Build and import a box node
5045 void Compiler::impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken)
5047 // Get the tree for the type handle for the boxed object. In the case
5048 // of shared generic code or ngen'd code this might be an embedded
5050 // Note we can only box do it if the class construtor has been called
5051 // We can always do it on primitive types
5053 GenTreePtr op1 = nullptr;
5054 GenTreePtr op2 = nullptr;
5057 impSpillSpecialSideEff();
5059 // Now get the expression to box from the stack.
5060 CORINFO_CLASS_HANDLE operCls;
5061 GenTreePtr exprToBox = impPopStack(operCls).val;
5063 CorInfoHelpFunc boxHelper = info.compCompHnd->getBoxHelper(pResolvedToken->hClass);
5064 if (boxHelper == CORINFO_HELP_BOX)
5066 // we are doing 'normal' boxing. This means that we can inline the box operation
5067 // Box(expr) gets morphed into
5068 // temp = new(clsHnd)
5069 // cpobj(temp+4, expr, clsHnd)
5071 // The code paths differ slightly below for structs and primitives because
5072 // "cpobj" differs in these cases. In one case you get
5073 // impAssignStructPtr(temp+4, expr, clsHnd)
5074 // and the other you get
5077 if (impBoxTempInUse || impBoxTemp == BAD_VAR_NUM)
5079 impBoxTemp = lvaGrabTemp(true DEBUGARG("Box Helper"));
5082 // needs to stay in use until this box expression is appended
5083 // some other node. We approximate this by keeping it alive until
5084 // the opcode stack becomes empty
5085 impBoxTempInUse = true;
5087 #ifdef FEATURE_READYTORUN_COMPILER
5088 bool usingReadyToRunHelper = false;
5090 if (opts.IsReadyToRun())
5092 op1 = impReadyToRunHelperToTree(pResolvedToken, CORINFO_HELP_READYTORUN_NEW, TYP_REF);
5093 usingReadyToRunHelper = (op1 != nullptr);
5096 if (!usingReadyToRunHelper)
5099 // TODO: ReadyToRun: When generic dictionary lookups are necessary, replace the lookup call
5100 // and the newfast call with a single call to a dynamic R2R cell that will:
5101 // 1) Load the context
5102 // 2) Perform the generic dictionary lookup and caching, and generate the appropriate stub
5103 // 3) Allocate and return the new object for boxing
5104 // Reason: performance (today, we'll always use the slow helper for the R2R generics case)
5106 // Ensure that the value class is restored
5107 op2 = impTokenToHandle(pResolvedToken, nullptr, TRUE /* mustRestoreHandle */);
5109 { // compDonotInline()
5113 op1 = gtNewHelperCallNode(info.compCompHnd->getNewHelper(pResolvedToken, info.compMethodHnd), TYP_REF, 0,
5117 /* Remember that this basic block contains 'new' of an array */
5118 compCurBB->bbFlags |= BBF_HAS_NEWOBJ;
5120 GenTreePtr asg = gtNewTempAssign(impBoxTemp, op1);
5122 GenTreePtr asgStmt = impAppendTree(asg, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
5124 op1 = gtNewLclvNode(impBoxTemp, TYP_REF);
5125 op2 = gtNewIconNode(sizeof(void*), TYP_I_IMPL);
5126 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1, op2);
5128 if (varTypeIsStruct(exprToBox))
5130 assert(info.compCompHnd->getClassSize(pResolvedToken->hClass) == info.compCompHnd->getClassSize(operCls));
5131 op1 = impAssignStructPtr(op1, exprToBox, operCls, (unsigned)CHECK_SPILL_ALL);
5135 lclTyp = exprToBox->TypeGet();
5136 if (lclTyp == TYP_BYREF)
5138 lclTyp = TYP_I_IMPL;
5140 CorInfoType jitType = info.compCompHnd->asCorInfoType(pResolvedToken->hClass);
5141 if (impIsPrimitive(jitType))
5143 lclTyp = JITtype2varType(jitType);
5145 assert(genActualType(exprToBox->TypeGet()) == genActualType(lclTyp) ||
5146 varTypeIsFloating(lclTyp) == varTypeIsFloating(exprToBox->TypeGet()));
5147 var_types srcTyp = exprToBox->TypeGet();
5148 var_types dstTyp = lclTyp;
5150 if (srcTyp != dstTyp)
5152 assert((varTypeIsFloating(srcTyp) && varTypeIsFloating(dstTyp)) ||
5153 (varTypeIsIntegral(srcTyp) && varTypeIsIntegral(dstTyp)));
5154 exprToBox = gtNewCastNode(dstTyp, exprToBox, dstTyp);
5156 op1 = gtNewAssignNode(gtNewOperNode(GT_IND, lclTyp, op1), exprToBox);
5159 op2 = gtNewLclvNode(impBoxTemp, TYP_REF);
5160 op1 = gtNewOperNode(GT_COMMA, TYP_REF, op1, op2);
5162 // Record that this is a "box" node.
5163 op1 = new (this, GT_BOX) GenTreeBox(TYP_REF, op1, asgStmt);
5165 // If it is a value class, mark the "box" node. We can use this information
5166 // to optimise several cases:
5167 // "box(x) == null" --> false
5168 // "(box(x)).CallAnInterfaceMethod(...)" --> "(&x).CallAValueTypeMethod"
5169 // "(box(x)).CallAnObjectMethod(...)" --> "(&x).CallAValueTypeMethod"
5171 op1->gtFlags |= GTF_BOX_VALUE;
5172 assert(op1->IsBoxedValue());
5173 assert(asg->gtOper == GT_ASG);
5177 // Don't optimize, just call the helper and be done with it
5179 // Ensure that the value class is restored
5180 op2 = impTokenToHandle(pResolvedToken, nullptr, TRUE /* mustRestoreHandle */);
5182 { // compDonotInline()
5186 GenTreeArgList* args = gtNewArgList(op2, impGetStructAddr(exprToBox, operCls, (unsigned)CHECK_SPILL_ALL, true));
5187 op1 = gtNewHelperCallNode(boxHelper, TYP_REF, GTF_EXCEPT, args);
5190 /* Push the result back on the stack, */
5191 /* even if clsHnd is a value class we want the TI_REF */
5192 typeInfo tiRetVal = typeInfo(TI_REF, info.compCompHnd->getTypeForBox(pResolvedToken->hClass));
5193 impPushOnStack(op1, tiRetVal);
5196 //------------------------------------------------------------------------
5197 // impImportNewObjArray: Build and import `new` of multi-dimmensional array
5200 // pResolvedToken - The CORINFO_RESOLVED_TOKEN that has been initialized
5201 // by a call to CEEInfo::resolveToken().
5202 // pCallInfo - The CORINFO_CALL_INFO that has been initialized
5203 // by a call to CEEInfo::getCallInfo().
5206 // The multi-dimensional array constructor arguments (array dimensions) are
5207 // pushed on the IL stack on entry to this method.
5210 // Multi-dimensional array constructors are imported as calls to a JIT
5211 // helper, not as regular calls.
5213 void Compiler::impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo)
5215 GenTreePtr classHandle = impParentClassTokenToHandle(pResolvedToken);
5216 if (classHandle == nullptr)
5217 { // compDonotInline()
5221 assert(pCallInfo->sig.numArgs);
5224 GenTreeArgList* args;
5227 // There are two different JIT helpers that can be used to allocate
5228 // multi-dimensional arrays:
5230 // - CORINFO_HELP_NEW_MDARR - takes the array dimensions as varargs.
5231 // This variant is deprecated. It should be eventually removed.
5233 // - CORINFO_HELP_NEW_MDARR_NONVARARG - takes the array dimensions as
5234 // pointer to block of int32s. This variant is more portable.
5236 // The non-varargs helper is enabled for CoreRT only for now. Enabling this
5237 // unconditionally would require ReadyToRun version bump.
5239 CLANG_FORMAT_COMMENT_ANCHOR;
5241 #if COR_JIT_EE_VERSION > 460
5242 if (!opts.IsReadyToRun() || IsTargetAbi(CORINFO_CORERT_ABI))
5244 LclVarDsc* newObjArrayArgsVar;
5246 // Reuse the temp used to pass the array dimensions to avoid bloating
5247 // the stack frame in case there are multiple calls to multi-dim array
5248 // constructors within a single method.
5249 if (lvaNewObjArrayArgs == BAD_VAR_NUM)
5251 lvaNewObjArrayArgs = lvaGrabTemp(false DEBUGARG("NewObjArrayArgs"));
5252 lvaTable[lvaNewObjArrayArgs].lvType = TYP_BLK;
5253 lvaTable[lvaNewObjArrayArgs].lvExactSize = 0;
5256 // Increase size of lvaNewObjArrayArgs to be the largest size needed to hold 'numArgs' integers
5257 // for our call to CORINFO_HELP_NEW_MDARR_NONVARARG.
5258 lvaTable[lvaNewObjArrayArgs].lvExactSize =
5259 max(lvaTable[lvaNewObjArrayArgs].lvExactSize, pCallInfo->sig.numArgs * sizeof(INT32));
5261 // The side-effects may include allocation of more multi-dimensional arrays. Spill all side-effects
5262 // to ensure that the shared lvaNewObjArrayArgs local variable is only ever used to pass arguments
5263 // to one allocation at a time.
5264 impSpillSideEffects(true, (unsigned)CHECK_SPILL_ALL DEBUGARG("impImportNewObjArray"));
5267 // The arguments of the CORINFO_HELP_NEW_MDARR_NONVARARG helper are:
5268 // - Array class handle
5269 // - Number of dimension arguments
5270 // - Pointer to block of int32 dimensions - address of lvaNewObjArrayArgs temp.
5273 node = gtNewLclvNode(lvaNewObjArrayArgs, TYP_BLK);
5274 node = gtNewOperNode(GT_ADDR, TYP_I_IMPL, node);
5276 // Pop dimension arguments from the stack one at a time and store it
5277 // into lvaNewObjArrayArgs temp.
5278 for (int i = pCallInfo->sig.numArgs - 1; i >= 0; i--)
5280 GenTreePtr arg = impImplicitIorI4Cast(impPopStack().val, TYP_INT);
5282 GenTreePtr dest = gtNewLclvNode(lvaNewObjArrayArgs, TYP_BLK);
5283 dest = gtNewOperNode(GT_ADDR, TYP_I_IMPL, dest);
5284 dest = gtNewOperNode(GT_ADD, TYP_I_IMPL, dest,
5285 new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, sizeof(INT32) * i));
5286 dest = gtNewOperNode(GT_IND, TYP_INT, dest);
5288 node = gtNewOperNode(GT_COMMA, node->TypeGet(), gtNewAssignNode(dest, arg), node);
5291 args = gtNewArgList(node);
5293 // pass number of arguments to the helper
5294 args = gtNewListNode(gtNewIconNode(pCallInfo->sig.numArgs), args);
5296 args = gtNewListNode(classHandle, args);
5298 node = gtNewHelperCallNode(CORINFO_HELP_NEW_MDARR_NONVARARG, TYP_REF, 0, args);
5304 // The varargs helper needs the type and method handles as last
5305 // and last-1 param (this is a cdecl call, so args will be
5306 // pushed in reverse order on the CPU stack)
5309 args = gtNewArgList(classHandle);
5311 // pass number of arguments to the helper
5312 args = gtNewListNode(gtNewIconNode(pCallInfo->sig.numArgs), args);
5314 unsigned argFlags = 0;
5315 args = impPopList(pCallInfo->sig.numArgs, &argFlags, &pCallInfo->sig, args);
5317 node = gtNewHelperCallNode(CORINFO_HELP_NEW_MDARR, TYP_REF, 0, args);
5319 // varargs, so we pop the arguments
5320 node->gtFlags |= GTF_CALL_POP_ARGS;
5323 // At the present time we don't track Caller pop arguments
5324 // that have GC references in them
5325 for (GenTreeArgList* temp = args; temp; temp = temp->Rest())
5327 assert(temp->Current()->gtType != TYP_REF);
5332 node->gtFlags |= args->gtFlags & GTF_GLOB_EFFECT;
5333 node->gtCall.compileTimeHelperArgumentHandle = (CORINFO_GENERIC_HANDLE)pResolvedToken->hClass;
5335 // Remember that this basic block contains 'new' of a md array
5336 compCurBB->bbFlags |= BBF_HAS_NEWARRAY;
5338 impPushOnStack(node, typeInfo(TI_REF, pResolvedToken->hClass));
5341 GenTreePtr Compiler::impTransformThis(GenTreePtr thisPtr,
5342 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
5343 CORINFO_THIS_TRANSFORM transform)
5347 case CORINFO_DEREF_THIS:
5349 GenTreePtr obj = thisPtr;
5351 // This does a LDIND on the obj, which should be a byref. pointing to a ref
5352 impBashVarAddrsToI(obj);
5353 assert(genActualType(obj->gtType) == TYP_I_IMPL || obj->gtType == TYP_BYREF);
5354 CorInfoType constraintTyp = info.compCompHnd->asCorInfoType(pConstrainedResolvedToken->hClass);
5356 obj = gtNewOperNode(GT_IND, JITtype2varType(constraintTyp), obj);
5357 // ldind could point anywhere, example a boxed class static int
5358 obj->gtFlags |= (GTF_EXCEPT | GTF_GLOB_REF | GTF_IND_TGTANYWHERE);
5363 case CORINFO_BOX_THIS:
5365 // Constraint calls where there might be no
5366 // unboxed entry point require us to implement the call via helper.
5367 // These only occur when a possible target of the call
5368 // may have inherited an implementation of an interface
5369 // method from System.Object or System.ValueType. The EE does not provide us with
5370 // "unboxed" versions of these methods.
5372 GenTreePtr obj = thisPtr;
5374 assert(obj->TypeGet() == TYP_BYREF || obj->TypeGet() == TYP_I_IMPL);
5375 obj = gtNewObjNode(pConstrainedResolvedToken->hClass, obj);
5376 obj->gtFlags |= GTF_EXCEPT;
5378 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(pConstrainedResolvedToken->hClass);
5379 var_types objType = JITtype2varType(jitTyp);
5380 if (impIsPrimitive(jitTyp))
5382 if (obj->OperIsBlk())
5384 obj->ChangeOperUnchecked(GT_IND);
5386 // Obj could point anywhere, example a boxed class static int
5387 obj->gtFlags |= GTF_IND_TGTANYWHERE;
5388 obj->gtOp.gtOp2 = nullptr; // must be zero for tree walkers
5391 obj->gtType = JITtype2varType(jitTyp);
5392 assert(varTypeIsArithmetic(obj->gtType));
5395 // This pushes on the dereferenced byref
5396 // This is then used immediately to box.
5397 impPushOnStack(obj, verMakeTypeInfo(pConstrainedResolvedToken->hClass).NormaliseForStack());
5399 // This pops off the byref-to-a-value-type remaining on the stack and
5400 // replaces it with a boxed object.
5401 // This is then used as the object to the virtual call immediately below.
5402 impImportAndPushBox(pConstrainedResolvedToken);
5403 if (compDonotInline())
5408 obj = impPopStack().val;
5411 case CORINFO_NO_THIS_TRANSFORM:
5417 //------------------------------------------------------------------------
5418 // impCanPInvokeInline: check whether PInvoke inlining should enabled in current method.
5421 // true if PInvoke inlining should be enabled in current method, false otherwise
5424 // Checks a number of ambient conditions where we could pinvoke but choose not to
5426 bool Compiler::impCanPInvokeInline()
5428 return getInlinePInvokeEnabled() && (!opts.compDbgCode) && (compCodeOpt() != SMALL_CODE) &&
5429 (!opts.compNoPInvokeInlineCB) // profiler is preventing inline pinvoke
5433 //------------------------------------------------------------------------
5434 // impCanPInvokeInlineCallSite: basic legality checks using information
5435 // from a call to see if the call qualifies as an inline pinvoke.
5438 // block - block contaning the call, or for inlinees, block
5439 // containing the call being inlined
5442 // true if this call can legally qualify as an inline pinvoke, false otherwise
5445 // For runtimes that support exception handling interop there are
5446 // restrictions on using inline pinvoke in handler regions.
5448 // * We have to disable pinvoke inlining inside of filters because
5449 // in case the main execution (i.e. in the try block) is inside
5450 // unmanaged code, we cannot reuse the inlined stub (we still need
5451 // the original state until we are in the catch handler)
5453 // * We disable pinvoke inlining inside handlers since the GSCookie
5454 // is in the inlined Frame (see
5455 // CORINFO_EE_INFO::InlinedCallFrameInfo::offsetOfGSCookie), but
5456 // this would not protect framelets/return-address of handlers.
5458 // These restrictions are currently also in place for CoreCLR but
5459 // can be relaxed when coreclr/#8459 is addressed.
5461 bool Compiler::impCanPInvokeInlineCallSite(BasicBlock* block)
5463 if (block->hasHndIndex())
5468 // The remaining limitations do not apply to CoreRT
5469 if (IsTargetAbi(CORINFO_CORERT_ABI))
5474 #ifdef _TARGET_AMD64_
5475 // On x64, we disable pinvoke inlining inside of try regions.
5476 // Here is the comment from JIT64 explaining why:
5478 // [VSWhidbey: 611015] - because the jitted code links in the
5479 // Frame (instead of the stub) we rely on the Frame not being
5480 // 'active' until inside the stub. This normally happens by the
5481 // stub setting the return address pointer in the Frame object
5482 // inside the stub. On a normal return, the return address
5483 // pointer is zeroed out so the Frame can be safely re-used, but
5484 // if an exception occurs, nobody zeros out the return address
5485 // pointer. Thus if we re-used the Frame object, it would go
5486 // 'active' as soon as we link it into the Frame chain.
5488 // Technically we only need to disable PInvoke inlining if we're
5489 // in a handler or if we're in a try body with a catch or
5490 // filter/except where other non-handler code in this method
5491 // might run and try to re-use the dirty Frame object.
5493 // A desktop test case where this seems to matter is
5494 // jit\jit64\ebvts\mcpp\sources2\ijw\__clrcall\vector_ctor_dtor.02\deldtor_clr.exe
5495 if (block->hasTryIndex())
5499 #endif // _TARGET_AMD64_
5504 //------------------------------------------------------------------------
5505 // impCheckForPInvokeCall examine call to see if it is a pinvoke and if so
5506 // if it can be expressed as an inline pinvoke.
5509 // call - tree for the call
5510 // methHnd - handle for the method being called (may be null)
5511 // sig - signature of the method being called
5512 // mflags - method flags for the method being called
5513 // block - block contaning the call, or for inlinees, block
5514 // containing the call being inlined
5517 // Sets GTF_CALL_M_PINVOKE on the call for pinvokes.
5519 // Also sets GTF_CALL_UNMANAGED on call for inline pinvokes if the
5520 // call passes a combination of legality and profitabilty checks.
5522 // If GTF_CALL_UNMANAGED is set, increments info.compCallUnmanaged
5524 void Compiler::impCheckForPInvokeCall(
5525 GenTreePtr call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags, BasicBlock* block)
5527 CorInfoUnmanagedCallConv unmanagedCallConv;
5529 // If VM flagged it as Pinvoke, flag the call node accordingly
5530 if ((mflags & CORINFO_FLG_PINVOKE) != 0)
5532 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_PINVOKE;
5537 if ((mflags & CORINFO_FLG_PINVOKE) == 0 || (mflags & CORINFO_FLG_NOSECURITYWRAP) == 0)
5542 unmanagedCallConv = info.compCompHnd->getUnmanagedCallConv(methHnd);
5546 CorInfoCallConv callConv = CorInfoCallConv(sig->callConv & CORINFO_CALLCONV_MASK);
5547 if (callConv == CORINFO_CALLCONV_NATIVEVARARG)
5549 // Used by the IL Stubs.
5550 callConv = CORINFO_CALLCONV_C;
5552 static_assert_no_msg((unsigned)CORINFO_CALLCONV_C == (unsigned)CORINFO_UNMANAGED_CALLCONV_C);
5553 static_assert_no_msg((unsigned)CORINFO_CALLCONV_STDCALL == (unsigned)CORINFO_UNMANAGED_CALLCONV_STDCALL);
5554 static_assert_no_msg((unsigned)CORINFO_CALLCONV_THISCALL == (unsigned)CORINFO_UNMANAGED_CALLCONV_THISCALL);
5555 unmanagedCallConv = CorInfoUnmanagedCallConv(callConv);
5557 assert(!call->gtCall.gtCallCookie);
5560 if (unmanagedCallConv != CORINFO_UNMANAGED_CALLCONV_C && unmanagedCallConv != CORINFO_UNMANAGED_CALLCONV_STDCALL &&
5561 unmanagedCallConv != CORINFO_UNMANAGED_CALLCONV_THISCALL)
5565 optNativeCallCount++;
5567 if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IL_STUB) && methHnd == nullptr)
5569 // PInvoke CALLI in IL stubs must be inlined
5574 if (!impCanPInvokeInlineCallSite(block))
5579 // PInvoke CALL in IL stubs must be inlined on CoreRT. Skip the ambient conditions checks and
5580 // profitability checks
5581 if (!(opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IL_STUB) && IsTargetAbi(CORINFO_CORERT_ABI)))
5583 if (!impCanPInvokeInline())
5588 // Size-speed tradeoff: don't use inline pinvoke at rarely
5589 // executed call sites. The non-inline version is more
5591 if (block->isRunRarely())
5597 // The expensive check should be last
5598 if (info.compCompHnd->pInvokeMarshalingRequired(methHnd, sig))
5604 JITLOG((LL_INFO1000000, "\nInline a CALLI PINVOKE call from method %s", info.compFullName));
5606 call->gtFlags |= GTF_CALL_UNMANAGED;
5607 info.compCallUnmanaged++;
5609 // AMD64 convention is same for native and managed
5610 if (unmanagedCallConv == CORINFO_UNMANAGED_CALLCONV_C)
5612 call->gtFlags |= GTF_CALL_POP_ARGS;
5615 if (unmanagedCallConv == CORINFO_UNMANAGED_CALLCONV_THISCALL)
5617 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_UNMGD_THISCALL;
5621 GenTreePtr Compiler::impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset)
5623 var_types callRetTyp = JITtype2varType(sig->retType);
5625 /* The function pointer is on top of the stack - It may be a
5626 * complex expression. As it is evaluated after the args,
5627 * it may cause registered args to be spilled. Simply spill it.
5630 // Ignore this trivial case.
5631 if (impStackTop().val->gtOper != GT_LCL_VAR)
5633 impSpillStackEntry(verCurrentState.esStackDepth - 1,
5634 BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impImportIndirectCall"));
5637 /* Get the function pointer */
5639 GenTreePtr fptr = impPopStack().val;
5640 assert(genActualType(fptr->gtType) == TYP_I_IMPL);
5643 // This temporary must never be converted to a double in stress mode,
5644 // because that can introduce a call to the cast helper after the
5645 // arguments have already been evaluated.
5647 if (fptr->OperGet() == GT_LCL_VAR)
5649 lvaTable[fptr->gtLclVarCommon.gtLclNum].lvKeepType = 1;
5653 /* Create the call node */
5655 GenTreePtr call = gtNewIndCallNode(fptr, callRetTyp, nullptr, ilOffset);
5657 call->gtFlags |= GTF_EXCEPT | (fptr->gtFlags & GTF_GLOB_EFFECT);
5662 /*****************************************************************************/
5664 void Compiler::impPopArgsForUnmanagedCall(GenTreePtr call, CORINFO_SIG_INFO* sig)
5666 assert(call->gtFlags & GTF_CALL_UNMANAGED);
5668 /* Since we push the arguments in reverse order (i.e. right -> left)
5669 * spill any side effects from the stack
5671 * OBS: If there is only one side effect we do not need to spill it
5672 * thus we have to spill all side-effects except last one
5675 unsigned lastLevelWithSideEffects = UINT_MAX;
5677 unsigned argsToReverse = sig->numArgs;
5679 // For "thiscall", the first argument goes in a register. Since its
5680 // order does not need to be changed, we do not need to spill it
5682 if (call->gtCall.gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL)
5684 assert(argsToReverse);
5688 #ifndef _TARGET_X86_
5689 // Don't reverse args on ARM or x64 - first four args always placed in regs in order
5693 for (unsigned level = verCurrentState.esStackDepth - argsToReverse; level < verCurrentState.esStackDepth; level++)
5695 if (verCurrentState.esStack[level].val->gtFlags & GTF_ORDER_SIDEEFF)
5697 assert(lastLevelWithSideEffects == UINT_MAX);
5699 impSpillStackEntry(level,
5700 BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impPopArgsForUnmanagedCall - other side effect"));
5702 else if (verCurrentState.esStack[level].val->gtFlags & GTF_SIDE_EFFECT)
5704 if (lastLevelWithSideEffects != UINT_MAX)
5706 /* We had a previous side effect - must spill it */
5707 impSpillStackEntry(lastLevelWithSideEffects,
5708 BAD_VAR_NUM DEBUGARG(false) DEBUGARG("impPopArgsForUnmanagedCall - side effect"));
5710 /* Record the level for the current side effect in case we will spill it */
5711 lastLevelWithSideEffects = level;
5715 /* This is the first side effect encountered - record its level */
5717 lastLevelWithSideEffects = level;
5722 /* The argument list is now "clean" - no out-of-order side effects
5723 * Pop the argument list in reverse order */
5725 unsigned argFlags = 0;
5726 GenTreePtr args = call->gtCall.gtCallArgs =
5727 impPopRevList(sig->numArgs, &argFlags, sig, sig->numArgs - argsToReverse);
5729 if (call->gtCall.gtCallMoreFlags & GTF_CALL_M_UNMGD_THISCALL)
5731 GenTreePtr thisPtr = args->Current();
5732 impBashVarAddrsToI(thisPtr);
5733 assert(thisPtr->TypeGet() == TYP_I_IMPL || thisPtr->TypeGet() == TYP_BYREF);
5738 call->gtFlags |= args->gtFlags & GTF_GLOB_EFFECT;
5742 //------------------------------------------------------------------------
5743 // impInitClass: Build a node to initialize the class before accessing the
5744 // field if necessary
5747 // pResolvedToken - The CORINFO_RESOLVED_TOKEN that has been initialized
5748 // by a call to CEEInfo::resolveToken().
5750 // Return Value: If needed, a pointer to the node that will perform the class
5751 // initializtion. Otherwise, nullptr.
5754 GenTreePtr Compiler::impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken)
5756 CorInfoInitClassResult initClassResult =
5757 info.compCompHnd->initClass(pResolvedToken->hField, info.compMethodHnd, impTokenLookupContextHandle);
5759 if ((initClassResult & CORINFO_INITCLASS_USE_HELPER) == 0)
5765 GenTreePtr node = impParentClassTokenToHandle(pResolvedToken, &runtimeLookup);
5767 if (node == nullptr)
5769 assert(compDonotInline());
5775 node = gtNewHelperCallNode(CORINFO_HELP_INITCLASS, TYP_VOID, 0, gtNewArgList(node));
5779 // Call the shared non gc static helper, as its the fastest
5780 node = fgGetSharedCCtor(pResolvedToken->hClass);
5786 GenTreePtr Compiler::impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp)
5788 GenTreePtr op1 = nullptr;
5797 ival = *((bool*)fldAddr);
5801 ival = *((signed char*)fldAddr);
5805 ival = *((unsigned char*)fldAddr);
5809 ival = *((short*)fldAddr);
5814 ival = *((unsigned short*)fldAddr);
5819 ival = *((int*)fldAddr);
5821 op1 = gtNewIconNode(ival);
5826 lval = *((__int64*)fldAddr);
5827 op1 = gtNewLconNode(lval);
5831 dval = *((float*)fldAddr);
5832 op1 = gtNewDconNode(dval);
5833 #if !FEATURE_X87_DOUBLES
5834 // X87 stack doesn't differentiate between float/double
5835 // so R4 is treated as R8, but everybody else does
5836 op1->gtType = TYP_FLOAT;
5837 #endif // FEATURE_X87_DOUBLES
5841 dval = *((double*)fldAddr);
5842 op1 = gtNewDconNode(dval);
5846 assert(!"Unexpected lclTyp");
5853 GenTreePtr Compiler::impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
5854 CORINFO_ACCESS_FLAGS access,
5855 CORINFO_FIELD_INFO* pFieldInfo,
5860 switch (pFieldInfo->fieldAccessor)
5862 case CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER:
5864 assert(!compIsForInlining());
5866 // We first call a special helper to get the statics base pointer
5867 op1 = impParentClassTokenToHandle(pResolvedToken);
5869 // compIsForInlining() is false so we should not neve get NULL here
5870 assert(op1 != nullptr);
5872 var_types type = TYP_BYREF;
5874 switch (pFieldInfo->helper)
5876 case CORINFO_HELP_GETGENERICS_NONGCTHREADSTATIC_BASE:
5879 case CORINFO_HELP_GETGENERICS_GCSTATIC_BASE:
5880 case CORINFO_HELP_GETGENERICS_NONGCSTATIC_BASE:
5881 case CORINFO_HELP_GETGENERICS_GCTHREADSTATIC_BASE:
5884 assert(!"unknown generic statics helper");
5888 op1 = gtNewHelperCallNode(pFieldInfo->helper, type, 0, gtNewArgList(op1));
5890 FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField);
5891 op1 = gtNewOperNode(GT_ADD, type, op1,
5892 new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, pFieldInfo->offset, fs));
5896 case CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER:
5898 #ifdef FEATURE_READYTORUN_COMPILER
5899 if (opts.IsReadyToRun())
5901 unsigned callFlags = 0;
5903 if (info.compCompHnd->getClassAttribs(pResolvedToken->hClass) & CORINFO_FLG_BEFOREFIELDINIT)
5905 callFlags |= GTF_CALL_HOISTABLE;
5908 op1 = gtNewHelperCallNode(CORINFO_HELP_READYTORUN_STATIC_BASE, TYP_BYREF, callFlags);
5910 op1->gtCall.setEntryPoint(pFieldInfo->fieldLookup);
5915 op1 = fgGetStaticsCCtorHelper(pResolvedToken->hClass, pFieldInfo->helper);
5919 FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField);
5920 op1 = gtNewOperNode(GT_ADD, op1->TypeGet(), op1,
5921 new (this, GT_CNS_INT) GenTreeIntCon(TYP_INT, pFieldInfo->offset, fs));
5925 #if COR_JIT_EE_VERSION > 460
5926 case CORINFO_FIELD_STATIC_READYTORUN_HELPER:
5928 #ifdef FEATURE_READYTORUN_COMPILER
5929 noway_assert(opts.IsReadyToRun());
5930 CORINFO_LOOKUP_KIND kind = info.compCompHnd->getLocationOfThisType(info.compMethodHnd);
5931 assert(kind.needsRuntimeLookup);
5933 GenTreePtr ctxTree = getRuntimeContextTree(kind.runtimeLookupKind);
5934 GenTreeArgList* args = gtNewArgList(ctxTree);
5936 unsigned callFlags = 0;
5938 if (info.compCompHnd->getClassAttribs(pResolvedToken->hClass) & CORINFO_FLG_BEFOREFIELDINIT)
5940 callFlags |= GTF_CALL_HOISTABLE;
5942 var_types type = TYP_BYREF;
5943 op1 = gtNewHelperCallNode(CORINFO_HELP_READYTORUN_GENERIC_STATIC_BASE, type, callFlags, args);
5945 op1->gtCall.setEntryPoint(pFieldInfo->fieldLookup);
5946 FieldSeqNode* fs = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField);
5947 op1 = gtNewOperNode(GT_ADD, type, op1,
5948 new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, pFieldInfo->offset, fs));
5951 #endif // FEATURE_READYTORUN_COMPILER
5954 #endif // COR_JIT_EE_VERSION > 460
5957 if (!(access & CORINFO_ACCESS_ADDRESS))
5959 // In future, it may be better to just create the right tree here instead of folding it later.
5960 op1 = gtNewFieldRef(lclTyp, pResolvedToken->hField);
5962 if (pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP)
5964 op1->gtType = TYP_REF; // points at boxed object
5965 FieldSeqNode* firstElemFldSeq =
5966 GetFieldSeqStore()->CreateSingleton(FieldSeqStore::FirstElemPseudoField);
5968 gtNewOperNode(GT_ADD, TYP_BYREF, op1,
5969 new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, sizeof(void*), firstElemFldSeq));
5971 if (varTypeIsStruct(lclTyp))
5973 // Constructor adds GTF_GLOB_REF. Note that this is *not* GTF_EXCEPT.
5974 op1 = gtNewObjNode(pFieldInfo->structType, op1);
5978 op1 = gtNewOperNode(GT_IND, lclTyp, op1);
5979 op1->gtFlags |= GTF_GLOB_REF | GTF_IND_NONFAULTING;
5987 void** pFldAddr = nullptr;
5988 void* fldAddr = info.compCompHnd->getFieldAddress(pResolvedToken->hField, (void**)&pFldAddr);
5990 FieldSeqNode* fldSeq = GetFieldSeqStore()->CreateSingleton(pResolvedToken->hField);
5992 /* Create the data member node */
5993 if (pFldAddr == nullptr)
5995 op1 = gtNewIconHandleNode((size_t)fldAddr, GTF_ICON_STATIC_HDL, fldSeq);
5999 op1 = gtNewIconHandleNode((size_t)pFldAddr, GTF_ICON_STATIC_HDL, fldSeq);
6001 // There are two cases here, either the static is RVA based,
6002 // in which case the type of the FIELD node is not a GC type
6003 // and the handle to the RVA is a TYP_I_IMPL. Or the FIELD node is
6004 // a GC type and the handle to it is a TYP_BYREF in the GC heap
6005 // because handles to statics now go into the large object heap
6007 var_types handleTyp = (var_types)(varTypeIsGC(lclTyp) ? TYP_BYREF : TYP_I_IMPL);
6008 op1 = gtNewOperNode(GT_IND, handleTyp, op1);
6009 op1->gtFlags |= GTF_IND_INVARIANT | GTF_IND_NONFAULTING;
6016 if (pFieldInfo->fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP)
6018 op1 = gtNewOperNode(GT_IND, TYP_REF, op1);
6020 FieldSeqNode* fldSeq = GetFieldSeqStore()->CreateSingleton(FieldSeqStore::FirstElemPseudoField);
6022 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1,
6023 new (this, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, sizeof(void*), fldSeq));
6026 if (!(access & CORINFO_ACCESS_ADDRESS))
6028 op1 = gtNewOperNode(GT_IND, lclTyp, op1);
6029 op1->gtFlags |= GTF_GLOB_REF;
6035 // In general try to call this before most of the verification work. Most people expect the access
6036 // exceptions before the verification exceptions. If you do this after, that usually doesn't happen. Turns
6037 // out if you can't access something we also think that you're unverifiable for other reasons.
6038 void Compiler::impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall)
6040 if (result != CORINFO_ACCESS_ALLOWED)
6042 impHandleAccessAllowedInternal(result, helperCall);
6046 void Compiler::impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall)
6050 case CORINFO_ACCESS_ALLOWED:
6052 case CORINFO_ACCESS_ILLEGAL:
6053 // if we're verifying, then we need to reject the illegal access to ensure that we don't think the
6054 // method is verifiable. Otherwise, delay the exception to runtime.
6055 if (compIsForImportOnly())
6057 info.compCompHnd->ThrowExceptionForHelper(helperCall);
6061 impInsertHelperCall(helperCall);
6064 case CORINFO_ACCESS_RUNTIME_CHECK:
6065 impInsertHelperCall(helperCall);
6070 void Compiler::impInsertHelperCall(CORINFO_HELPER_DESC* helperInfo)
6072 // Construct the argument list
6073 GenTreeArgList* args = nullptr;
6074 assert(helperInfo->helperNum != CORINFO_HELP_UNDEF);
6075 for (unsigned i = helperInfo->numArgs; i > 0; --i)
6077 const CORINFO_HELPER_ARG& helperArg = helperInfo->args[i - 1];
6078 GenTreePtr currentArg = nullptr;
6079 switch (helperArg.argType)
6081 case CORINFO_HELPER_ARG_TYPE_Field:
6082 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(
6083 info.compCompHnd->getFieldClass(helperArg.fieldHandle));
6084 currentArg = gtNewIconEmbFldHndNode(helperArg.fieldHandle);
6086 case CORINFO_HELPER_ARG_TYPE_Method:
6087 info.compCompHnd->methodMustBeLoadedBeforeCodeIsRun(helperArg.methodHandle);
6088 currentArg = gtNewIconEmbMethHndNode(helperArg.methodHandle);
6090 case CORINFO_HELPER_ARG_TYPE_Class:
6091 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(helperArg.classHandle);
6092 currentArg = gtNewIconEmbClsHndNode(helperArg.classHandle);
6094 case CORINFO_HELPER_ARG_TYPE_Module:
6095 currentArg = gtNewIconEmbScpHndNode(helperArg.moduleHandle);
6097 case CORINFO_HELPER_ARG_TYPE_Const:
6098 currentArg = gtNewIconNode(helperArg.constant);
6101 NO_WAY("Illegal helper arg type");
6103 args = (currentArg == nullptr) ? gtNewArgList(currentArg) : gtNewListNode(currentArg, args);
6107 * Mark as CSE'able, and hoistable. Consider marking hoistable unless you're in the inlinee.
6108 * Also, consider sticking this in the first basic block.
6110 GenTreePtr callout = gtNewHelperCallNode(helperInfo->helperNum, TYP_VOID, GTF_EXCEPT, args);
6111 impAppendTree(callout, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
6114 void Compiler::impInsertCalloutForDelegate(CORINFO_METHOD_HANDLE callerMethodHnd,
6115 CORINFO_METHOD_HANDLE calleeMethodHnd,
6116 CORINFO_CLASS_HANDLE delegateTypeHnd)
6118 #ifdef FEATURE_CORECLR
6119 if (!info.compCompHnd->isDelegateCreationAllowed(delegateTypeHnd, calleeMethodHnd))
6121 // Call the JIT_DelegateSecurityCheck helper before calling the actual function.
6122 // This helper throws an exception if the CLR host disallows the call.
6124 GenTreePtr helper = gtNewHelperCallNode(CORINFO_HELP_DELEGATE_SECURITY_CHECK, TYP_VOID, GTF_EXCEPT,
6125 gtNewArgList(gtNewIconEmbClsHndNode(delegateTypeHnd),
6126 gtNewIconEmbMethHndNode(calleeMethodHnd)));
6127 // Append the callout statement
6128 impAppendTree(helper, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
6130 #endif // FEATURE_CORECLR
6133 // Checks whether the return types of caller and callee are compatible
6134 // so that callee can be tail called. Note that here we don't check
6135 // compatibility in IL Verifier sense, but on the lines of return type
6136 // sizes are equal and get returned in the same return register.
6137 bool Compiler::impTailCallRetTypeCompatible(var_types callerRetType,
6138 CORINFO_CLASS_HANDLE callerRetTypeClass,
6139 var_types calleeRetType,
6140 CORINFO_CLASS_HANDLE calleeRetTypeClass)
6142 // Note that we can not relax this condition with genActualType() as the
6143 // calling convention dictates that the caller of a function with a small
6144 // typed return value is responsible for normalizing the return val.
6145 if (callerRetType == calleeRetType)
6150 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
6152 if (callerRetType == TYP_VOID)
6154 // This needs to be allowed to support the following IL pattern that Jit64 allows:
6159 // Note that the above IL pattern is not valid as per IL verification rules.
6160 // Therefore, only full trust code can take advantage of this pattern.
6164 // These checks return true if the return value type sizes are the same and
6165 // get returned in the same return register i.e. caller doesn't need to normalize
6166 // return value. Some of the tail calls permitted by below checks would have
6167 // been rejected by IL Verifier before we reached here. Therefore, only full
6168 // trust code can make those tail calls.
6169 unsigned callerRetTypeSize = 0;
6170 unsigned calleeRetTypeSize = 0;
6171 bool isCallerRetTypMBEnreg =
6172 VarTypeIsMultiByteAndCanEnreg(callerRetType, callerRetTypeClass, &callerRetTypeSize, true);
6173 bool isCalleeRetTypMBEnreg =
6174 VarTypeIsMultiByteAndCanEnreg(calleeRetType, calleeRetTypeClass, &calleeRetTypeSize, true);
6176 if (varTypeIsIntegral(callerRetType) || isCallerRetTypMBEnreg)
6178 return (varTypeIsIntegral(calleeRetType) || isCalleeRetTypMBEnreg) && (callerRetTypeSize == calleeRetTypeSize);
6180 #endif // _TARGET_AMD64_ || _TARGET_ARM64_
6188 PREFIX_TAILCALL_EXPLICIT = 0x00000001, // call has "tail" IL prefix
6189 PREFIX_TAILCALL_IMPLICIT =
6190 0x00000010, // call is treated as having "tail" prefix even though there is no "tail" IL prefix
6191 PREFIX_TAILCALL = (PREFIX_TAILCALL_EXPLICIT | PREFIX_TAILCALL_IMPLICIT),
6192 PREFIX_VOLATILE = 0x00000100,
6193 PREFIX_UNALIGNED = 0x00001000,
6194 PREFIX_CONSTRAINED = 0x00010000,
6195 PREFIX_READONLY = 0x00100000
6198 /********************************************************************************
6200 * Returns true if the current opcode and and the opcodes following it correspond
6201 * to a supported tail call IL pattern.
6204 bool Compiler::impIsTailCallILPattern(bool tailPrefixed,
6206 const BYTE* codeAddrOfNextOpcode,
6207 const BYTE* codeEnd,
6209 bool* isCallPopAndRet /* = nullptr */)
6211 // Bail out if the current opcode is not a call.
6212 if (!impOpcodeIsCallOpcode(curOpcode))
6217 #if !FEATURE_TAILCALL_OPT_SHARED_RETURN
6218 // If shared ret tail opt is not enabled, we will enable
6219 // it for recursive methods.
6223 // we can actually handle if the ret is in a fallthrough block, as long as that is the only part of the
6224 // sequence. Make sure we don't go past the end of the IL however.
6225 codeEnd = min(codeEnd + 1, info.compCode + info.compILCodeSize);
6228 // Bail out if there is no next opcode after call
6229 if (codeAddrOfNextOpcode >= codeEnd)
6234 // Scan the opcodes to look for the following IL patterns if either
6235 // i) the call is not tail prefixed (i.e. implicit tail call) or
6236 // ii) if tail prefixed, IL verification is not needed for the method.
6238 // Only in the above two cases we can allow the below tail call patterns
6239 // violating ECMA spec.
6255 #ifdef _TARGET_AMD64_
6258 nextOpcode = (OPCODE)getU1LittleEndian(codeAddrOfNextOpcode);
6259 codeAddrOfNextOpcode += sizeof(__int8);
6260 } while ((codeAddrOfNextOpcode < codeEnd) && // Haven't reached end of method
6261 (!tailPrefixed || !tiVerificationNeeded) && // Not ".tail" prefixed or method requires no IL verification
6262 ((nextOpcode == CEE_NOP) || ((nextOpcode == CEE_POP) && (++cntPop == 1)))); // Next opcode = nop or exactly
6263 // one pop seen so far.
6265 nextOpcode = (OPCODE)getU1LittleEndian(codeAddrOfNextOpcode);
6268 if (isCallPopAndRet)
6270 // Allow call+pop+ret to be tail call optimized if caller ret type is void
6271 *isCallPopAndRet = (nextOpcode == CEE_RET) && (cntPop == 1);
6274 #ifdef _TARGET_AMD64_
6276 // Tail call IL pattern could be either of the following
6277 // 1) call/callvirt/calli + ret
6278 // 2) call/callvirt/calli + pop + ret in a method returning void.
6279 return (nextOpcode == CEE_RET) && ((cntPop == 0) || ((cntPop == 1) && (info.compRetType == TYP_VOID)));
6280 #else //!_TARGET_AMD64_
6281 return (nextOpcode == CEE_RET) && (cntPop == 0);
6285 /*****************************************************************************
6287 * Determine whether the call could be converted to an implicit tail call
6290 bool Compiler::impIsImplicitTailCallCandidate(
6291 OPCODE opcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive)
6294 #if FEATURE_TAILCALL_OPT
6295 if (!opts.compTailCallOpt)
6300 if (opts.compDbgCode || opts.MinOpts())
6305 // must not be tail prefixed
6306 if (prefixFlags & PREFIX_TAILCALL_EXPLICIT)
6311 #if !FEATURE_TAILCALL_OPT_SHARED_RETURN
6312 // the block containing call is marked as BBJ_RETURN
6313 // We allow shared ret tail call optimization on recursive calls even under
6314 // !FEATURE_TAILCALL_OPT_SHARED_RETURN.
6315 if (!isRecursive && (compCurBB->bbJumpKind != BBJ_RETURN))
6317 #endif // !FEATURE_TAILCALL_OPT_SHARED_RETURN
6319 // must be call+ret or call+pop+ret
6320 if (!impIsTailCallILPattern(false, opcode, codeAddrOfNextOpcode, codeEnd, isRecursive))
6328 #endif // FEATURE_TAILCALL_OPT
6331 //------------------------------------------------------------------------
6332 // impImportCall: import a call-inspiring opcode
6335 // opcode - opcode that inspires the call
6336 // pResolvedToken - resolved token for the call target
6337 // pConstrainedResolvedToken - resolved constraint token (or nullptr)
6338 // newObjThis - tree for this pointer or uninitalized newobj temp (or nullptr)
6339 // prefixFlags - IL prefix flags for the call
6340 // callInfo - EE supplied info for the call
6341 // rawILOffset - IL offset of the opcode
6344 // Type of the call's return value.
6347 // opcode can be CEE_CALL, CEE_CALLI, CEE_CALLVIRT, or CEE_NEWOBJ.
6349 // For CEE_NEWOBJ, newobjThis should be the temp grabbed for the allocated
6350 // uninitalized object.
6353 #pragma warning(push)
6354 #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function
6357 var_types Compiler::impImportCall(OPCODE opcode,
6358 CORINFO_RESOLVED_TOKEN* pResolvedToken,
6359 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
6360 GenTreePtr newobjThis,
6362 CORINFO_CALL_INFO* callInfo,
6363 IL_OFFSET rawILOffset)
6365 assert(opcode == CEE_CALL || opcode == CEE_CALLVIRT || opcode == CEE_NEWOBJ || opcode == CEE_CALLI);
6367 IL_OFFSETX ilOffset = impCurILOffset(rawILOffset, true);
6368 var_types callRetTyp = TYP_COUNT;
6369 CORINFO_SIG_INFO* sig = nullptr;
6370 CORINFO_METHOD_HANDLE methHnd = nullptr;
6371 CORINFO_CLASS_HANDLE clsHnd = nullptr;
6372 unsigned clsFlags = 0;
6373 unsigned mflags = 0;
6374 unsigned argFlags = 0;
6375 GenTreePtr call = nullptr;
6376 GenTreeArgList* args = nullptr;
6377 CORINFO_THIS_TRANSFORM constraintCallThisTransform = CORINFO_NO_THIS_TRANSFORM;
6378 CORINFO_CONTEXT_HANDLE exactContextHnd = nullptr;
6379 BOOL exactContextNeedsRuntimeLookup = FALSE;
6380 bool canTailCall = true;
6381 const char* szCanTailCallFailReason = nullptr;
6382 int tailCall = prefixFlags & PREFIX_TAILCALL;
6383 bool readonlyCall = (prefixFlags & PREFIX_READONLY) != 0;
6385 // Synchronized methods need to call CORINFO_HELP_MON_EXIT at the end. We could
6386 // do that before tailcalls, but that is probably not the intended
6387 // semantic. So just disallow tailcalls from synchronized methods.
6388 // Also, popping arguments in a varargs function is more work and NYI
6389 // If we have a security object, we have to keep our frame around for callers
6390 // to see any imperative security.
6391 if (info.compFlags & CORINFO_FLG_SYNCH)
6393 canTailCall = false;
6394 szCanTailCallFailReason = "Caller is synchronized";
6396 #if !FEATURE_FIXED_OUT_ARGS
6397 else if (info.compIsVarArgs)
6399 canTailCall = false;
6400 szCanTailCallFailReason = "Caller is varargs";
6402 #endif // FEATURE_FIXED_OUT_ARGS
6403 else if (opts.compNeedSecurityCheck)
6405 canTailCall = false;
6406 szCanTailCallFailReason = "Caller requires a security check.";
6409 // We only need to cast the return value of pinvoke inlined calls that return small types
6411 // TODO-AMD64-Cleanup: Remove this when we stop interoperating with JIT64, or if we decide to stop
6412 // widening everything! CoreCLR does not support JIT64 interoperation so no need to widen there.
6413 // The existing x64 JIT doesn't bother widening all types to int, so we have to assume for
6414 // the time being that the callee might be compiled by the other JIT and thus the return
6415 // value will need to be widened by us (or not widened at all...)
6417 // ReadyToRun code sticks with default calling convention that does not widen small return types.
6419 bool checkForSmallType = opts.IsJit64Compat() || opts.IsReadyToRun();
6420 bool bIntrinsicImported = false;
6422 CORINFO_SIG_INFO calliSig;
6423 GenTreeArgList* extraArg = nullptr;
6425 /*-------------------------------------------------------------------------
6426 * First create the call node
6429 if (opcode == CEE_CALLI)
6431 /* Get the call site sig */
6432 eeGetSig(pResolvedToken->token, info.compScopeHnd, impTokenLookupContextHandle, &calliSig);
6434 callRetTyp = JITtype2varType(calliSig.retType);
6435 clsHnd = calliSig.retTypeClass;
6437 call = impImportIndirectCall(&calliSig, ilOffset);
6439 // We don't know the target method, so we have to infer the flags, or
6440 // assume the worst-case.
6441 mflags = (calliSig.callConv & CORINFO_CALLCONV_HASTHIS) ? 0 : CORINFO_FLG_STATIC;
6446 unsigned structSize =
6447 (callRetTyp == TYP_STRUCT) ? info.compCompHnd->getClassSize(calliSig.retTypeSigClass) : 0;
6448 printf("\nIn Compiler::impImportCall: opcode is %s, kind=%d, callRetType is %s, structSize is %d\n",
6449 opcodeNames[opcode], callInfo->kind, varTypeName(callRetTyp), structSize);
6452 // This should be checked in impImportBlockCode.
6453 assert(!compIsForInlining() || !(impInlineInfo->inlineCandidateInfo->dwRestrictions & INLINE_RESPECT_BOUNDARY));
6458 // We cannot lazily obtain the signature of a CALLI call because it has no method
6459 // handle that we can use, so we need to save its full call signature here.
6460 assert(call->gtCall.callSig == nullptr);
6461 call->gtCall.callSig = new (this, CMK_CorSig) CORINFO_SIG_INFO;
6462 *call->gtCall.callSig = calliSig;
6465 if (IsTargetAbi(CORINFO_CORERT_ABI))
6467 bool managedCall = (calliSig.callConv & GTF_CALL_UNMANAGED) == 0;
6470 addFatPointerCandidate(call->AsCall());
6474 else // (opcode != CEE_CALLI)
6476 CorInfoIntrinsics intrinsicID = CORINFO_INTRINSIC_Count;
6478 // Passing CORINFO_CALLINFO_ALLOWINSTPARAM indicates that this JIT is prepared to
6479 // supply the instantiation parameters necessary to make direct calls to underlying
6480 // shared generic code, rather than calling through instantiating stubs. If the
6481 // returned signature has CORINFO_CALLCONV_PARAMTYPE then this indicates that the JIT
6482 // must indeed pass an instantiation parameter.
6484 methHnd = callInfo->hMethod;
6486 sig = &(callInfo->sig);
6487 callRetTyp = JITtype2varType(sig->retType);
6489 mflags = callInfo->methodFlags;
6494 unsigned structSize = (callRetTyp == TYP_STRUCT) ? info.compCompHnd->getClassSize(sig->retTypeSigClass) : 0;
6495 printf("\nIn Compiler::impImportCall: opcode is %s, kind=%d, callRetType is %s, structSize is %d\n",
6496 opcodeNames[opcode], callInfo->kind, varTypeName(callRetTyp), structSize);
6499 if (compIsForInlining())
6501 /* Does this call site have security boundary restrictions? */
6503 if (impInlineInfo->inlineCandidateInfo->dwRestrictions & INLINE_RESPECT_BOUNDARY)
6505 compInlineResult->NoteFatal(InlineObservation::CALLSITE_CROSS_BOUNDARY_SECURITY);
6509 /* Does the inlinee need a security check token on the frame */
6511 if (mflags & CORINFO_FLG_SECURITYCHECK)
6513 compInlineResult->NoteFatal(InlineObservation::CALLEE_NEEDS_SECURITY_CHECK);
6517 /* Does the inlinee use StackCrawlMark */
6519 if (mflags & CORINFO_FLG_DONT_INLINE_CALLER)
6521 compInlineResult->NoteFatal(InlineObservation::CALLEE_STACK_CRAWL_MARK);
6525 /* For now ignore delegate invoke */
6527 if (mflags & CORINFO_FLG_DELEGATE_INVOKE)
6529 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_DELEGATE_INVOKE);
6533 /* For now ignore varargs */
6534 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_NATIVEVARARG)
6536 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_NATIVE_VARARGS);
6540 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
6542 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_MANAGED_VARARGS);
6546 if ((mflags & CORINFO_FLG_VIRTUAL) && (sig->sigInst.methInstCount != 0) && (opcode == CEE_CALLVIRT))
6548 compInlineResult->NoteFatal(InlineObservation::CALLEE_IS_GENERIC_VIRTUAL);
6553 clsHnd = pResolvedToken->hClass;
6555 clsFlags = callInfo->classFlags;
6558 // If this is a call to JitTestLabel.Mark, do "early inlining", and record the test attribute.
6560 // This recognition should really be done by knowing the methHnd of the relevant Mark method(s).
6561 // These should be in mscorlib.h, and available through a JIT/EE interface call.
6562 const char* modName;
6563 const char* className;
6564 const char* methodName;
6565 if ((className = eeGetClassName(clsHnd)) != nullptr &&
6566 strcmp(className, "System.Runtime.CompilerServices.JitTestLabel") == 0 &&
6567 (methodName = eeGetMethodName(methHnd, &modName)) != nullptr && strcmp(methodName, "Mark") == 0)
6569 return impImportJitTestLabelMark(sig->numArgs);
6573 // <NICE> Factor this into getCallInfo </NICE>
6574 if ((mflags & CORINFO_FLG_INTRINSIC) && !pConstrainedResolvedToken)
6576 call = impIntrinsic(newobjThis, clsHnd, methHnd, sig, pResolvedToken->token, readonlyCall,
6577 (canTailCall && (tailCall != 0)), &intrinsicID);
6579 if (call != nullptr)
6581 assert(!(mflags & CORINFO_FLG_VIRTUAL) || (mflags & CORINFO_FLG_FINAL) ||
6582 (clsFlags & CORINFO_FLG_FINAL));
6584 #ifdef FEATURE_READYTORUN_COMPILER
6585 if (call->OperGet() == GT_INTRINSIC)
6587 if (opts.IsReadyToRun())
6589 noway_assert(callInfo->kind == CORINFO_CALL);
6590 call->gtIntrinsic.gtEntryPoint = callInfo->codePointerLookup.constLookup;
6594 call->gtIntrinsic.gtEntryPoint.addr = nullptr;
6599 bIntrinsicImported = true;
6607 call = impSIMDIntrinsic(opcode, newobjThis, clsHnd, methHnd, sig, pResolvedToken->token);
6608 if (call != nullptr)
6610 bIntrinsicImported = true;
6614 #endif // FEATURE_SIMD
6616 if ((mflags & CORINFO_FLG_VIRTUAL) && (mflags & CORINFO_FLG_EnC) && (opcode == CEE_CALLVIRT))
6618 NO_WAY("Virtual call to a function added via EnC is not supported");
6621 if ((sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_DEFAULT &&
6622 (sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_VARARG &&
6623 (sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_NATIVEVARARG)
6625 BADCODE("Bad calling convention");
6628 //-------------------------------------------------------------------------
6629 // Construct the call node
6631 // Work out what sort of call we're making.
6632 // Dispense with virtual calls implemented via LDVIRTFTN immediately.
6634 constraintCallThisTransform = callInfo->thisTransform;
6636 exactContextHnd = callInfo->contextHandle;
6637 exactContextNeedsRuntimeLookup = callInfo->exactContextNeedsRuntimeLookup;
6639 // Recursive call is treaded as a loop to the begining of the method.
6640 if (methHnd == info.compMethodHnd)
6645 JITDUMP("\nFound recursive call in the method. Mark BB%02u to BB%02u as having a backward branch.\n",
6646 fgFirstBB->bbNum, compCurBB->bbNum);
6649 fgMarkBackwardJump(fgFirstBB, compCurBB);
6652 switch (callInfo->kind)
6655 case CORINFO_VIRTUALCALL_STUB:
6657 assert(!(mflags & CORINFO_FLG_STATIC)); // can't call a static method
6658 assert(!(clsFlags & CORINFO_FLG_VALUECLASS));
6659 if (callInfo->stubLookup.lookupKind.needsRuntimeLookup)
6662 if (compIsForInlining())
6664 // Don't import runtime lookups when inlining
6665 // Inlining has to be aborted in such a case
6666 /* XXX Fri 3/20/2009
6667 * By the way, this would never succeed. If the handle lookup is into the generic
6668 * dictionary for a candidate, you'll generate different dictionary offsets and the
6669 * inlined code will crash.
6671 * To anyone code reviewing this, when could this ever succeed in the future? It'll
6672 * always have a handle lookup. These lookups are safe intra-module, but we're just
6675 compInlineResult->NoteFatal(InlineObservation::CALLSITE_HAS_COMPLEX_HANDLE);
6679 GenTreePtr stubAddr = impRuntimeLookupToTree(pResolvedToken, &callInfo->stubLookup, methHnd);
6680 assert(!compDonotInline());
6682 // This is the rough code to set up an indirect stub call
6683 assert(stubAddr != nullptr);
6685 // The stubAddr may be a
6686 // complex expression. As it is evaluated after the args,
6687 // it may cause registered args to be spilled. Simply spill it.
6689 unsigned lclNum = lvaGrabTemp(true DEBUGARG("VirtualCall with runtime lookup"));
6690 impAssignTempGen(lclNum, stubAddr, (unsigned)CHECK_SPILL_ALL);
6691 stubAddr = gtNewLclvNode(lclNum, TYP_I_IMPL);
6693 // Create the actual call node
6695 assert((sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_VARARG &&
6696 (sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_NATIVEVARARG);
6698 call = gtNewIndCallNode(stubAddr, callRetTyp, nullptr);
6700 call->gtFlags |= GTF_EXCEPT | (stubAddr->gtFlags & GTF_GLOB_EFFECT);
6701 call->gtFlags |= GTF_CALL_VIRT_STUB;
6704 // No tailcalls allowed for these yet...
6705 canTailCall = false;
6706 szCanTailCallFailReason = "VirtualCall with runtime lookup";
6711 // ok, the stub is available at compile type.
6713 call = gtNewCallNode(CT_USER_FUNC, callInfo->hMethod, callRetTyp, nullptr, ilOffset);
6714 call->gtCall.gtStubCallStubAddr = callInfo->stubLookup.constLookup.addr;
6715 call->gtFlags |= GTF_CALL_VIRT_STUB;
6716 assert(callInfo->stubLookup.constLookup.accessType != IAT_PPVALUE);
6717 if (callInfo->stubLookup.constLookup.accessType == IAT_PVALUE)
6719 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_VIRTSTUB_REL_INDIRECT;
6723 #ifdef FEATURE_READYTORUN_COMPILER
6724 if (opts.IsReadyToRun())
6726 // Null check is sometimes needed for ready to run to handle
6727 // non-virtual <-> virtual changes between versions
6728 if (callInfo->nullInstanceCheck)
6730 call->gtFlags |= GTF_CALL_NULLCHECK;
6738 case CORINFO_VIRTUALCALL_VTABLE:
6740 assert(!(mflags & CORINFO_FLG_STATIC)); // can't call a static method
6741 assert(!(clsFlags & CORINFO_FLG_VALUECLASS));
6742 call = gtNewCallNode(CT_USER_FUNC, callInfo->hMethod, callRetTyp, nullptr, ilOffset);
6743 call->gtFlags |= GTF_CALL_VIRT_VTABLE;
6747 case CORINFO_VIRTUALCALL_LDVIRTFTN:
6749 if (compIsForInlining())
6751 compInlineResult->NoteFatal(InlineObservation::CALLSITE_HAS_CALL_VIA_LDVIRTFTN);
6755 assert(!(mflags & CORINFO_FLG_STATIC)); // can't call a static method
6756 assert(!(clsFlags & CORINFO_FLG_VALUECLASS));
6757 // OK, We've been told to call via LDVIRTFTN, so just
6758 // take the call now....
6760 args = impPopList(sig->numArgs, &argFlags, sig);
6762 GenTreePtr thisPtr = impPopStack().val;
6763 thisPtr = impTransformThis(thisPtr, pConstrainedResolvedToken, callInfo->thisTransform);
6764 if (compDonotInline())
6769 // Clone the (possibly transformed) "this" pointer
6770 GenTreePtr thisPtrCopy;
6771 thisPtr = impCloneExpr(thisPtr, &thisPtrCopy, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
6772 nullptr DEBUGARG("LDVIRTFTN this pointer"));
6774 GenTreePtr fptr = nullptr;
6775 bool coreRTGenericVirtualMethod =
6776 ((sig->callConv & CORINFO_CALLCONV_GENERIC) != 0) && IsTargetAbi(CORINFO_CORERT_ABI);
6777 #if COR_JIT_EE_VERSION > 460
6778 if (coreRTGenericVirtualMethod)
6780 GenTreePtr runtimeMethodHandle = nullptr;
6781 if (callInfo->exactContextNeedsRuntimeLookup)
6783 runtimeMethodHandle =
6784 impRuntimeLookupToTree(pResolvedToken, &callInfo->codePointerLookup, methHnd);
6788 runtimeMethodHandle = gtNewIconEmbMethHndNode(pResolvedToken->hMethod);
6790 fptr = gtNewHelperCallNode(CORINFO_HELP_GVMLOOKUP_FOR_SLOT, TYP_I_IMPL, GTF_EXCEPT,
6791 gtNewArgList(thisPtr, runtimeMethodHandle));
6794 #endif // COR_JIT_EE_VERSION
6796 fptr = impImportLdvirtftn(thisPtr, pResolvedToken, callInfo);
6799 if (compDonotInline())
6804 thisPtr = nullptr; // can't reuse it
6806 // Now make an indirect call through the function pointer
6808 unsigned lclNum = lvaGrabTemp(true DEBUGARG("VirtualCall through function pointer"));
6809 impAssignTempGen(lclNum, fptr, (unsigned)CHECK_SPILL_ALL);
6810 fptr = gtNewLclvNode(lclNum, TYP_I_IMPL);
6812 // Create the actual call node
6814 call = gtNewIndCallNode(fptr, callRetTyp, args, ilOffset);
6815 call->gtCall.gtCallObjp = thisPtrCopy;
6816 call->gtFlags |= GTF_EXCEPT | (fptr->gtFlags & GTF_GLOB_EFFECT);
6818 if (coreRTGenericVirtualMethod)
6820 addFatPointerCandidate(call->AsCall());
6822 #ifdef FEATURE_READYTORUN_COMPILER
6823 if (opts.IsReadyToRun())
6825 // Null check is needed for ready to run to handle
6826 // non-virtual <-> virtual changes between versions
6827 call->gtFlags |= GTF_CALL_NULLCHECK;
6831 // Sine we are jumping over some code, check that its OK to skip that code
6832 assert((sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_VARARG &&
6833 (sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_NATIVEVARARG);
6839 // This is for a non-virtual, non-interface etc. call
6840 call = gtNewCallNode(CT_USER_FUNC, callInfo->hMethod, callRetTyp, nullptr, ilOffset);
6842 // We remove the nullcheck for the GetType call instrinsic.
6843 // TODO-CQ: JIT64 does not introduce the null check for many more helper calls
6845 if (callInfo->nullInstanceCheck &&
6846 !((mflags & CORINFO_FLG_INTRINSIC) != 0 && (intrinsicID == CORINFO_INTRINSIC_Object_GetType)))
6848 call->gtFlags |= GTF_CALL_NULLCHECK;
6851 #ifdef FEATURE_READYTORUN_COMPILER
6852 if (opts.IsReadyToRun())
6854 call->gtCall.setEntryPoint(callInfo->codePointerLookup.constLookup);
6860 case CORINFO_CALL_CODE_POINTER:
6862 // The EE has asked us to call by computing a code pointer and then doing an
6863 // indirect call. This is because a runtime lookup is required to get the code entry point.
6865 // These calls always follow a uniform calling convention, i.e. no extra hidden params
6866 assert((sig->callConv & CORINFO_CALLCONV_PARAMTYPE) == 0);
6868 assert((sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_VARARG);
6869 assert((sig->callConv & CORINFO_CALLCONV_MASK) != CORINFO_CALLCONV_NATIVEVARARG);
6872 impLookupToTree(pResolvedToken, &callInfo->codePointerLookup, GTF_ICON_FTN_ADDR, callInfo->hMethod);
6874 if (compDonotInline())
6879 // Now make an indirect call through the function pointer
6881 unsigned lclNum = lvaGrabTemp(true DEBUGARG("Indirect call through function pointer"));
6882 impAssignTempGen(lclNum, fptr, (unsigned)CHECK_SPILL_ALL);
6883 fptr = gtNewLclvNode(lclNum, TYP_I_IMPL);
6885 call = gtNewIndCallNode(fptr, callRetTyp, nullptr, ilOffset);
6886 call->gtFlags |= GTF_EXCEPT | (fptr->gtFlags & GTF_GLOB_EFFECT);
6887 if (callInfo->nullInstanceCheck)
6889 call->gtFlags |= GTF_CALL_NULLCHECK;
6896 assert(!"unknown call kind");
6900 //-------------------------------------------------------------------------
6903 PREFIX_ASSUME(call != nullptr);
6905 if (mflags & CORINFO_FLG_NOGCCHECK)
6907 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_NOGCCHECK;
6910 // Mark call if it's one of the ones we will maybe treat as an intrinsic
6911 if (intrinsicID == CORINFO_INTRINSIC_Object_GetType || intrinsicID == CORINFO_INTRINSIC_TypeEQ ||
6912 intrinsicID == CORINFO_INTRINSIC_TypeNEQ || intrinsicID == CORINFO_INTRINSIC_GetCurrentManagedThread ||
6913 intrinsicID == CORINFO_INTRINSIC_GetManagedThreadId)
6915 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_SPECIAL_INTRINSIC;
6919 assert(clsHnd || (opcode == CEE_CALLI)); // We're never verifying for CALLI, so this is not set.
6921 /* Some sanity checks */
6923 // CALL_VIRT and NEWOBJ must have a THIS pointer
6924 assert((opcode != CEE_CALLVIRT && opcode != CEE_NEWOBJ) || (sig->callConv & CORINFO_CALLCONV_HASTHIS));
6925 // static bit and hasThis are negations of one another
6926 assert(((mflags & CORINFO_FLG_STATIC) != 0) == ((sig->callConv & CORINFO_CALLCONV_HASTHIS) == 0));
6927 assert(call != nullptr);
6929 /*-------------------------------------------------------------------------
6930 * Check special-cases etc
6933 /* Special case - Check if it is a call to Delegate.Invoke(). */
6935 if (mflags & CORINFO_FLG_DELEGATE_INVOKE)
6937 assert(!compIsForInlining());
6938 assert(!(mflags & CORINFO_FLG_STATIC)); // can't call a static method
6939 assert(mflags & CORINFO_FLG_FINAL);
6941 /* Set the delegate flag */
6942 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_DELEGATE_INV;
6944 if (callInfo->secureDelegateInvoke)
6946 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_SECURE_DELEGATE_INV;
6949 if (opcode == CEE_CALLVIRT)
6951 assert(mflags & CORINFO_FLG_FINAL);
6953 /* It should have the GTF_CALL_NULLCHECK flag set. Reset it */
6954 assert(call->gtFlags & GTF_CALL_NULLCHECK);
6955 call->gtFlags &= ~GTF_CALL_NULLCHECK;
6959 CORINFO_CLASS_HANDLE actualMethodRetTypeSigClass;
6960 actualMethodRetTypeSigClass = sig->retTypeSigClass;
6961 if (varTypeIsStruct(callRetTyp))
6963 callRetTyp = impNormStructType(actualMethodRetTypeSigClass);
6964 call->gtType = callRetTyp;
6968 /* Check for varargs */
6969 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG ||
6970 (sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_NATIVEVARARG)
6972 BADCODE("Varargs not supported.");
6974 #endif // !FEATURE_VARARG
6976 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG ||
6977 (sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_NATIVEVARARG)
6979 assert(!compIsForInlining());
6981 /* Set the right flags */
6983 call->gtFlags |= GTF_CALL_POP_ARGS;
6984 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_VARARGS;
6986 /* Can't allow tailcall for varargs as it is caller-pop. The caller
6987 will be expecting to pop a certain number of arguments, but if we
6988 tailcall to a function with a different number of arguments, we
6989 are hosed. There are ways around this (caller remembers esp value,
6990 varargs is not caller-pop, etc), but not worth it. */
6991 CLANG_FORMAT_COMMENT_ANCHOR;
6996 canTailCall = false;
6997 szCanTailCallFailReason = "Callee is varargs";
7001 /* Get the total number of arguments - this is already correct
7002 * for CALLI - for methods we have to get it from the call site */
7004 if (opcode != CEE_CALLI)
7007 unsigned numArgsDef = sig->numArgs;
7009 eeGetCallSiteSig(pResolvedToken->token, info.compScopeHnd, impTokenLookupContextHandle, sig);
7012 // We cannot lazily obtain the signature of a vararg call because using its method
7013 // handle will give us only the declared argument list, not the full argument list.
7014 assert(call->gtCall.callSig == nullptr);
7015 call->gtCall.callSig = new (this, CMK_CorSig) CORINFO_SIG_INFO;
7016 *call->gtCall.callSig = *sig;
7019 // For vararg calls we must be sure to load the return type of the
7020 // method actually being called, as well as the return types of the
7021 // specified in the vararg signature. With type equivalency, these types
7022 // may not be the same.
7023 if (sig->retTypeSigClass != actualMethodRetTypeSigClass)
7025 if (actualMethodRetTypeSigClass != nullptr && sig->retType != CORINFO_TYPE_CLASS &&
7026 sig->retType != CORINFO_TYPE_BYREF && sig->retType != CORINFO_TYPE_PTR &&
7027 sig->retType != CORINFO_TYPE_VAR)
7029 // Make sure that all valuetypes (including enums) that we push are loaded.
7030 // This is to guarantee that if a GC is triggerred from the prestub of this methods,
7031 // all valuetypes in the method signature are already loaded.
7032 // We need to be able to find the size of the valuetypes, but we cannot
7033 // do a class-load from within GC.
7034 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(actualMethodRetTypeSigClass);
7038 assert(numArgsDef <= sig->numArgs);
7041 /* We will have "cookie" as the last argument but we cannot push
7042 * it on the operand stack because we may overflow, so we append it
7043 * to the arg list next after we pop them */
7046 if (mflags & CORINFO_FLG_SECURITYCHECK)
7048 assert(!compIsForInlining());
7050 // Need security prolog/epilog callouts when there is
7051 // imperative security in the method. This is to give security a
7052 // chance to do any setup in the prolog and cleanup in the epilog if needed.
7054 if (compIsForInlining())
7056 // Cannot handle this if the method being imported is an inlinee by itself.
7057 // Because inlinee method does not have its own frame.
7059 compInlineResult->NoteFatal(InlineObservation::CALLEE_NEEDS_SECURITY_CHECK);
7064 tiSecurityCalloutNeeded = true;
7066 // If the current method calls a method which needs a security check,
7067 // (i.e. the method being compiled has imperative security)
7068 // we need to reserve a slot for the security object in
7069 // the current method's stack frame
7070 opts.compNeedSecurityCheck = true;
7074 //--------------------------- Inline NDirect ------------------------------
7076 // For inline cases we technically should look at both the current
7077 // block and the call site block (or just the latter if we've
7078 // fused the EH trees). However the block-related checks pertain to
7079 // EH and we currently won't inline a method with EH. So for
7080 // inlinees, just checking the call site block is sufficient.
7082 // New lexical block here to avoid compilation errors because of GOTOs.
7083 BasicBlock* block = compIsForInlining() ? impInlineInfo->iciBlock : compCurBB;
7084 impCheckForPInvokeCall(call, methHnd, sig, mflags, block);
7087 if (call->gtFlags & GTF_CALL_UNMANAGED)
7089 // We set up the unmanaged call by linking the frame, disabling GC, etc
7090 // This needs to be cleaned up on return
7093 canTailCall = false;
7094 szCanTailCallFailReason = "Callee is native";
7097 checkForSmallType = true;
7099 impPopArgsForUnmanagedCall(call, sig);
7103 else if ((opcode == CEE_CALLI) && (((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_STDCALL) ||
7104 ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_C) ||
7105 ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_THISCALL) ||
7106 ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_FASTCALL)))
7108 if (!info.compCompHnd->canGetCookieForPInvokeCalliSig(sig))
7110 // Normally this only happens with inlining.
7111 // However, a generic method (or type) being NGENd into another module
7112 // can run into this issue as well. There's not an easy fall-back for NGEN
7113 // so instead we fallback to JIT.
7114 if (compIsForInlining())
7116 compInlineResult->NoteFatal(InlineObservation::CALLSITE_CANT_EMBED_PINVOKE_COOKIE);
7120 IMPL_LIMITATION("Can't get PInvoke cookie (cross module generics)");
7126 GenTreePtr cookie = eeGetPInvokeCookie(sig);
7128 // This cookie is required to be either a simple GT_CNS_INT or
7129 // an indirection of a GT_CNS_INT
7131 GenTreePtr cookieConst = cookie;
7132 if (cookie->gtOper == GT_IND)
7134 cookieConst = cookie->gtOp.gtOp1;
7136 assert(cookieConst->gtOper == GT_CNS_INT);
7138 // Setting GTF_DONT_CSE on the GT_CNS_INT as well as on the GT_IND (if it exists) will ensure that
7139 // we won't allow this tree to participate in any CSE logic
7141 cookie->gtFlags |= GTF_DONT_CSE;
7142 cookieConst->gtFlags |= GTF_DONT_CSE;
7144 call->gtCall.gtCallCookie = cookie;
7148 canTailCall = false;
7149 szCanTailCallFailReason = "PInvoke calli";
7153 /*-------------------------------------------------------------------------
7154 * Create the argument list
7157 //-------------------------------------------------------------------------
7158 // Special case - for varargs we have an implicit last argument
7160 if ((sig->callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG)
7162 assert(!compIsForInlining());
7164 void *varCookie, *pVarCookie;
7165 if (!info.compCompHnd->canGetVarArgsHandle(sig))
7167 compInlineResult->NoteFatal(InlineObservation::CALLSITE_CANT_EMBED_VARARGS_COOKIE);
7171 varCookie = info.compCompHnd->getVarArgsHandle(sig, &pVarCookie);
7172 assert((!varCookie) != (!pVarCookie));
7173 GenTreePtr cookie = gtNewIconEmbHndNode(varCookie, pVarCookie, GTF_ICON_VARG_HDL);
7175 assert(extraArg == nullptr);
7176 extraArg = gtNewArgList(cookie);
7179 //-------------------------------------------------------------------------
7180 // Extra arg for shared generic code and array methods
7182 // Extra argument containing instantiation information is passed in the
7183 // following circumstances:
7184 // (a) To the "Address" method on array classes; the extra parameter is
7185 // the array's type handle (a TypeDesc)
7186 // (b) To shared-code instance methods in generic structs; the extra parameter
7187 // is the struct's type handle (a vtable ptr)
7188 // (c) To shared-code per-instantiation non-generic static methods in generic
7189 // classes and structs; the extra parameter is the type handle
7190 // (d) To shared-code generic methods; the extra parameter is an
7191 // exact-instantiation MethodDesc
7193 // We also set the exact type context associated with the call so we can
7194 // inline the call correctly later on.
7196 if (sig->callConv & CORINFO_CALLCONV_PARAMTYPE)
7198 assert(call->gtCall.gtCallType == CT_USER_FUNC);
7199 if (clsHnd == nullptr)
7201 NO_WAY("CALLI on parameterized type");
7204 assert(opcode != CEE_CALLI);
7206 GenTreePtr instParam;
7209 // Instantiated generic method
7210 if (((SIZE_T)exactContextHnd & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_METHOD)
7212 CORINFO_METHOD_HANDLE exactMethodHandle =
7213 (CORINFO_METHOD_HANDLE)((SIZE_T)exactContextHnd & ~CORINFO_CONTEXTFLAGS_MASK);
7215 if (!exactContextNeedsRuntimeLookup)
7217 #ifdef FEATURE_READYTORUN_COMPILER
7218 if (opts.IsReadyToRun())
7221 impReadyToRunLookupToTree(&callInfo->instParamLookup, GTF_ICON_METHOD_HDL, exactMethodHandle);
7222 if (instParam == nullptr)
7230 instParam = gtNewIconEmbMethHndNode(exactMethodHandle);
7231 info.compCompHnd->methodMustBeLoadedBeforeCodeIsRun(exactMethodHandle);
7236 instParam = impTokenToHandle(pResolvedToken, &runtimeLookup, TRUE /*mustRestoreHandle*/);
7237 if (instParam == nullptr)
7244 // otherwise must be an instance method in a generic struct,
7245 // a static method in a generic type, or a runtime-generated array method
7248 assert(((SIZE_T)exactContextHnd & CORINFO_CONTEXTFLAGS_MASK) == CORINFO_CONTEXTFLAGS_CLASS);
7249 CORINFO_CLASS_HANDLE exactClassHandle =
7250 (CORINFO_CLASS_HANDLE)((SIZE_T)exactContextHnd & ~CORINFO_CONTEXTFLAGS_MASK);
7252 if (compIsForInlining() && (clsFlags & CORINFO_FLG_ARRAY) != 0)
7254 compInlineResult->NoteFatal(InlineObservation::CALLEE_IS_ARRAY_METHOD);
7258 if ((clsFlags & CORINFO_FLG_ARRAY) && readonlyCall)
7260 // We indicate "readonly" to the Address operation by using a null
7262 instParam = gtNewIconNode(0, TYP_REF);
7265 if (!exactContextNeedsRuntimeLookup)
7267 #ifdef FEATURE_READYTORUN_COMPILER
7268 if (opts.IsReadyToRun())
7271 impReadyToRunLookupToTree(&callInfo->instParamLookup, GTF_ICON_CLASS_HDL, exactClassHandle);
7272 if (instParam == nullptr)
7280 instParam = gtNewIconEmbClsHndNode(exactClassHandle);
7281 info.compCompHnd->classMustBeLoadedBeforeCodeIsRun(exactClassHandle);
7286 instParam = impParentClassTokenToHandle(pResolvedToken, &runtimeLookup, TRUE /*mustRestoreHandle*/);
7287 if (instParam == nullptr)
7294 assert(extraArg == nullptr);
7295 extraArg = gtNewArgList(instParam);
7298 // Inlining may need the exact type context (exactContextHnd) if we're inlining shared generic code, in particular
7299 // to inline 'polytypic' operations such as static field accesses, type tests and method calls which
7300 // rely on the exact context. The exactContextHnd is passed back to the JitInterface at appropriate points.
7301 // exactContextHnd is not currently required when inlining shared generic code into shared
7302 // generic code, since the inliner aborts whenever shared code polytypic operations are encountered
7303 // (e.g. anything marked needsRuntimeLookup)
7304 if (exactContextNeedsRuntimeLookup)
7306 exactContextHnd = nullptr;
7309 //-------------------------------------------------------------------------
7310 // The main group of arguments
7312 args = call->gtCall.gtCallArgs = impPopList(sig->numArgs, &argFlags, sig, extraArg);
7316 call->gtFlags |= args->gtFlags & GTF_GLOB_EFFECT;
7319 //-------------------------------------------------------------------------
7320 // The "this" pointer
7322 if (!(mflags & CORINFO_FLG_STATIC) && !((opcode == CEE_NEWOBJ) && (newobjThis == nullptr)))
7326 if (opcode == CEE_NEWOBJ)
7332 obj = impPopStack().val;
7333 obj = impTransformThis(obj, pConstrainedResolvedToken, constraintCallThisTransform);
7334 if (compDonotInline())
7340 /* Is this a virtual or interface call? */
7342 if ((call->gtFlags & GTF_CALL_VIRT_KIND_MASK) != GTF_CALL_NONVIRT)
7344 /* only true object pointers can be virtual */
7346 assert(obj->gtType == TYP_REF);
7352 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_NONVIRT_SAME_THIS;
7356 /* Store the "this" value in the call */
7358 call->gtFlags |= obj->gtFlags & GTF_GLOB_EFFECT;
7359 call->gtCall.gtCallObjp = obj;
7362 //-------------------------------------------------------------------------
7363 // The "this" pointer for "newobj"
7365 if (opcode == CEE_NEWOBJ)
7367 if (clsFlags & CORINFO_FLG_VAROBJSIZE)
7369 assert(!(clsFlags & CORINFO_FLG_ARRAY)); // arrays handled separately
7370 // This is a 'new' of a variable sized object, wher
7371 // the constructor is to return the object. In this case
7372 // the constructor claims to return VOID but we know it
7373 // actually returns the new object
7374 assert(callRetTyp == TYP_VOID);
7375 callRetTyp = TYP_REF;
7376 call->gtType = TYP_REF;
7377 impSpillSpecialSideEff();
7379 impPushOnStack(call, typeInfo(TI_REF, clsHnd));
7383 if (clsFlags & CORINFO_FLG_DELEGATE)
7385 // New inliner morph it in impImportCall.
7386 // This will allow us to inline the call to the delegate constructor.
7387 call = fgOptimizeDelegateConstructor(call, &exactContextHnd);
7390 if (!bIntrinsicImported)
7393 #if defined(DEBUG) || defined(INLINE_DATA)
7395 // Keep track of the raw IL offset of the call
7396 call->gtCall.gtRawILOffset = rawILOffset;
7398 #endif // defined(DEBUG) || defined(INLINE_DATA)
7400 // Is it an inline candidate?
7401 impMarkInlineCandidate(call, exactContextHnd, callInfo);
7404 // append the call node.
7405 impAppendTree(call, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
7407 // Now push the value of the 'new onto the stack
7409 // This is a 'new' of a non-variable sized object.
7410 // Append the new node (op1) to the statement list,
7411 // and then push the local holding the value of this
7412 // new instruction on the stack.
7414 if (clsFlags & CORINFO_FLG_VALUECLASS)
7416 assert(newobjThis->gtOper == GT_ADDR && newobjThis->gtOp.gtOp1->gtOper == GT_LCL_VAR);
7418 unsigned tmp = newobjThis->gtOp.gtOp1->gtLclVarCommon.gtLclNum;
7419 impPushOnStack(gtNewLclvNode(tmp, lvaGetRealType(tmp)), verMakeTypeInfo(clsHnd).NormaliseForStack());
7423 if (newobjThis->gtOper == GT_COMMA)
7425 // In coreclr the callout can be inserted even if verification is disabled
7426 // so we cannot rely on tiVerificationNeeded alone
7428 // We must have inserted the callout. Get the real newobj.
7429 newobjThis = newobjThis->gtOp.gtOp2;
7432 assert(newobjThis->gtOper == GT_LCL_VAR);
7433 impPushOnStack(gtNewLclvNode(newobjThis->gtLclVarCommon.gtLclNum, TYP_REF), typeInfo(TI_REF, clsHnd));
7443 // This check cannot be performed for implicit tail calls for the reason
7444 // that impIsImplicitTailCallCandidate() is not checking whether return
7445 // types are compatible before marking a call node with PREFIX_TAILCALL_IMPLICIT.
7446 // As a result it is possible that in the following case, we find that
7447 // the type stack is non-empty if Callee() is considered for implicit
7449 // int Caller(..) { .... void Callee(); ret val; ... }
7451 // Note that we cannot check return type compatibility before ImpImportCall()
7452 // as we don't have required info or need to duplicate some of the logic of
7455 // For implicit tail calls, we perform this check after return types are
7456 // known to be compatible.
7457 if ((tailCall & PREFIX_TAILCALL_EXPLICIT) && (verCurrentState.esStackDepth != 0))
7459 BADCODE("Stack should be empty after tailcall");
7462 // Note that we can not relax this condition with genActualType() as
7463 // the calling convention dictates that the caller of a function with
7464 // a small-typed return value is responsible for normalizing the return val
7467 !impTailCallRetTypeCompatible(info.compRetType, info.compMethodInfo->args.retTypeClass, callRetTyp,
7468 callInfo->sig.retTypeClass))
7470 canTailCall = false;
7471 szCanTailCallFailReason = "Return types are not tail call compatible";
7474 // Stack empty check for implicit tail calls.
7475 if (canTailCall && (tailCall & PREFIX_TAILCALL_IMPLICIT) && (verCurrentState.esStackDepth != 0))
7477 #ifdef _TARGET_AMD64_
7478 // JIT64 Compatibility: Opportunistic tail call stack mismatch throws a VerificationException
7479 // in JIT64, not an InvalidProgramException.
7480 Verify(false, "Stack should be empty after tailcall");
7481 #else // _TARGET_64BIT_
7482 BADCODE("Stack should be empty after tailcall");
7483 #endif //!_TARGET_64BIT_
7486 // assert(compCurBB is not a catch, finally or filter block);
7487 // assert(compCurBB is not a try block protected by a finally block);
7489 // Check for permission to tailcall
7490 bool explicitTailCall = (tailCall & PREFIX_TAILCALL_EXPLICIT) != 0;
7492 assert(!explicitTailCall || compCurBB->bbJumpKind == BBJ_RETURN);
7496 // True virtual or indirect calls, shouldn't pass in a callee handle.
7497 CORINFO_METHOD_HANDLE exactCalleeHnd = ((call->gtCall.gtCallType != CT_USER_FUNC) ||
7498 ((call->gtFlags & GTF_CALL_VIRT_KIND_MASK) != GTF_CALL_NONVIRT))
7501 GenTreePtr thisArg = call->gtCall.gtCallObjp;
7503 if (info.compCompHnd->canTailCall(info.compMethodHnd, methHnd, exactCalleeHnd, explicitTailCall))
7506 if (explicitTailCall)
7508 // In case of explicit tail calls, mark it so that it is not considered
7510 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_EXPLICIT_TAILCALL;
7514 printf("\nGTF_CALL_M_EXPLICIT_TAILCALL bit set for call ");
7522 #if FEATURE_TAILCALL_OPT
7523 // Must be an implicit tail call.
7524 assert((tailCall & PREFIX_TAILCALL_IMPLICIT) != 0);
7526 // It is possible that a call node is both an inline candidate and marked
7527 // for opportunistic tail calling. In-lining happens before morhphing of
7528 // trees. If in-lining of an in-line candidate gets aborted for whatever
7529 // reason, it will survive to the morphing stage at which point it will be
7530 // transformed into a tail call after performing additional checks.
7532 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_IMPLICIT_TAILCALL;
7536 printf("\nGTF_CALL_M_IMPLICIT_TAILCALL bit set for call ");
7542 #else //! FEATURE_TAILCALL_OPT
7543 NYI("Implicit tail call prefix on a target which doesn't support opportunistic tail calls");
7545 #endif // FEATURE_TAILCALL_OPT
7548 // we can't report success just yet...
7552 canTailCall = false;
7553 // canTailCall reported its reasons already
7557 printf("\ninfo.compCompHnd->canTailCall returned false for call ");
7566 // If this assert fires it means that canTailCall was set to false without setting a reason!
7567 assert(szCanTailCallFailReason != nullptr);
7572 printf("\nRejecting %splicit tail call for call ", explicitTailCall ? "ex" : "im");
7574 printf(": %s\n", szCanTailCallFailReason);
7577 info.compCompHnd->reportTailCallDecision(info.compMethodHnd, methHnd, explicitTailCall, TAILCALL_FAIL,
7578 szCanTailCallFailReason);
7582 // Note: we assume that small return types are already normalized by the managed callee
7583 // or by the pinvoke stub for calls to unmanaged code.
7585 if (!bIntrinsicImported)
7588 // Things needed to be checked when bIntrinsicImported is false.
7591 assert(call->gtOper == GT_CALL);
7592 assert(sig != nullptr);
7594 // Tail calls require us to save the call site's sig info so we can obtain an argument
7595 // copying thunk from the EE later on.
7596 if (call->gtCall.callSig == nullptr)
7598 call->gtCall.callSig = new (this, CMK_CorSig) CORINFO_SIG_INFO;
7599 *call->gtCall.callSig = *sig;
7602 if (compIsForInlining() && opcode == CEE_CALLVIRT)
7604 GenTreePtr callObj = call->gtCall.gtCallObjp;
7605 assert(callObj != nullptr);
7607 unsigned callKind = call->gtFlags & GTF_CALL_VIRT_KIND_MASK;
7609 if (((callKind != GTF_CALL_NONVIRT) || (call->gtFlags & GTF_CALL_NULLCHECK)) &&
7610 impInlineIsGuaranteedThisDerefBeforeAnySideEffects(call->gtCall.gtCallArgs, callObj,
7611 impInlineInfo->inlArgInfo))
7613 impInlineInfo->thisDereferencedFirst = true;
7617 #if defined(DEBUG) || defined(INLINE_DATA)
7619 // Keep track of the raw IL offset of the call
7620 call->gtCall.gtRawILOffset = rawILOffset;
7622 #endif // defined(DEBUG) || defined(INLINE_DATA)
7624 // Is it an inline candidate?
7625 impMarkInlineCandidate(call, exactContextHnd, callInfo);
7629 // Push or append the result of the call
7630 if (callRetTyp == TYP_VOID)
7632 if (opcode == CEE_NEWOBJ)
7634 // we actually did push something, so don't spill the thing we just pushed.
7635 assert(verCurrentState.esStackDepth > 0);
7636 impAppendTree(call, verCurrentState.esStackDepth - 1, impCurStmtOffs);
7640 impAppendTree(call, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
7645 impSpillSpecialSideEff();
7647 if (clsFlags & CORINFO_FLG_ARRAY)
7649 eeGetCallSiteSig(pResolvedToken->token, pResolvedToken->tokenScope, pResolvedToken->tokenContext, sig);
7652 // Find the return type used for verification by interpreting the method signature.
7653 // NB: we are clobbering the already established sig.
7654 if (tiVerificationNeeded)
7656 // Actually, we never get the sig for the original method.
7657 sig = &(callInfo->verSig);
7660 typeInfo tiRetVal = verMakeTypeInfo(sig->retType, sig->retTypeClass);
7661 tiRetVal.NormaliseForStack();
7663 // The CEE_READONLY prefix modifies the verification semantics of an Address
7664 // operation on an array type.
7665 if ((clsFlags & CORINFO_FLG_ARRAY) && readonlyCall && tiRetVal.IsByRef())
7667 tiRetVal.SetIsReadonlyByRef();
7670 if (tiVerificationNeeded)
7672 // We assume all calls return permanent home byrefs. If they
7673 // didn't they wouldn't be verifiable. This is also covering
7674 // the Address() helper for multidimensional arrays.
7675 if (tiRetVal.IsByRef())
7677 tiRetVal.SetIsPermanentHomeByRef();
7683 // Sometimes "call" is not a GT_CALL (if we imported an intrinsic that didn't turn into a call)
7685 bool fatPointerCandidate = call->AsCall()->IsFatPointerCandidate();
7686 if (varTypeIsStruct(callRetTyp))
7688 call = impFixupCallStructReturn(call, sig->retTypeClass);
7691 if ((call->gtFlags & GTF_CALL_INLINE_CANDIDATE) != 0)
7693 assert(opts.OptEnabled(CLFLG_INLINING));
7694 assert(!fatPointerCandidate); // We should not try to inline calli.
7696 // Make the call its own tree (spill the stack if needed).
7697 impAppendTree(call, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
7699 // TODO: Still using the widened type.
7700 call = gtNewInlineCandidateReturnExpr(call, genActualType(callRetTyp));
7704 if (fatPointerCandidate)
7706 // fatPointer candidates should be in statements of the form call() or var = call().
7707 // Such form allows to find statements with fat calls without walking through whole trees
7708 // and removes problems with cutting trees.
7709 assert(!bIntrinsicImported);
7710 assert(IsTargetAbi(CORINFO_CORERT_ABI));
7711 if (call->OperGet() != GT_LCL_VAR) // can be already converted by impFixupCallStructReturn.
7713 unsigned calliSlot = lvaGrabTemp(true DEBUGARG("calli"));
7714 LclVarDsc* varDsc = &lvaTable[calliSlot];
7715 varDsc->lvVerTypeInfo = tiRetVal;
7716 impAssignTempGen(calliSlot, call, clsHnd, (unsigned)CHECK_SPILL_NONE);
7717 // impAssignTempGen can change src arg list and return type for call that returns struct.
7718 var_types type = genActualType(lvaTable[calliSlot].TypeGet());
7719 call = gtNewLclvNode(calliSlot, type);
7722 // For non-candidates we must also spill, since we
7723 // might have locals live on the eval stack that this
7725 impSpillSideEffects(true, CHECK_SPILL_ALL DEBUGARG("non-inline candidate call"));
7729 if (!bIntrinsicImported)
7731 //-------------------------------------------------------------------------
7733 /* If the call is of a small type and the callee is managed, the callee will normalize the result
7735 However, we need to normalize small type values returned by unmanaged
7736 functions (pinvoke). The pinvoke stub does the normalization, but we need to do it here
7737 if we use the shorter inlined pinvoke stub. */
7739 if (checkForSmallType && varTypeIsIntegral(callRetTyp) && genTypeSize(callRetTyp) < genTypeSize(TYP_INT))
7741 call = gtNewCastNode(genActualType(callRetTyp), call, callRetTyp);
7745 impPushOnStack(call, tiRetVal);
7748 // VSD functions get a new call target each time we getCallInfo, so clear the cache.
7749 // Also, the call info cache for CALLI instructions is largely incomplete, so clear it out.
7750 // if ( (opcode == CEE_CALLI) || (callInfoCache.fetchCallInfo().kind == CORINFO_VIRTUALCALL_STUB))
7751 // callInfoCache.uncacheCallInfo();
7756 #pragma warning(pop)
7759 bool Compiler::impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo)
7761 CorInfoType corType = methInfo->args.retType;
7763 if ((corType == CORINFO_TYPE_VALUECLASS) || (corType == CORINFO_TYPE_REFANY))
7765 // We have some kind of STRUCT being returned
7767 structPassingKind howToReturnStruct = SPK_Unknown;
7769 var_types returnType = getReturnTypeForStruct(methInfo->args.retTypeClass, &howToReturnStruct);
7771 if (howToReturnStruct == SPK_ByReference)
7782 var_types Compiler::impImportJitTestLabelMark(int numArgs)
7784 TestLabelAndNum tlAndN;
7788 StackEntry se = impPopStack();
7789 assert(se.seTypeInfo.GetType() == TI_INT);
7790 GenTreePtr val = se.val;
7791 assert(val->IsCnsIntOrI());
7792 tlAndN.m_tl = (TestLabel)val->AsIntConCommon()->IconValue();
7794 else if (numArgs == 3)
7796 StackEntry se = impPopStack();
7797 assert(se.seTypeInfo.GetType() == TI_INT);
7798 GenTreePtr val = se.val;
7799 assert(val->IsCnsIntOrI());
7800 tlAndN.m_num = val->AsIntConCommon()->IconValue();
7802 assert(se.seTypeInfo.GetType() == TI_INT);
7804 assert(val->IsCnsIntOrI());
7805 tlAndN.m_tl = (TestLabel)val->AsIntConCommon()->IconValue();
7812 StackEntry expSe = impPopStack();
7813 GenTreePtr node = expSe.val;
7815 // There are a small number of special cases, where we actually put the annotation on a subnode.
7816 if (tlAndN.m_tl == TL_LoopHoist && tlAndN.m_num >= 100)
7818 // A loop hoist annotation with value >= 100 means that the expression should be a static field access,
7819 // a GT_IND of a static field address, which should be the sum of a (hoistable) helper call and possibly some
7820 // offset within the the static field block whose address is returned by the helper call.
7821 // The annotation is saying that this address calculation, but not the entire access, should be hoisted.
7822 GenTreePtr helperCall = nullptr;
7823 assert(node->OperGet() == GT_IND);
7824 tlAndN.m_num -= 100;
7825 GetNodeTestData()->Set(node->gtOp.gtOp1, tlAndN);
7826 GetNodeTestData()->Remove(node);
7830 GetNodeTestData()->Set(node, tlAndN);
7833 impPushOnStack(node, expSe.seTypeInfo);
7834 return node->TypeGet();
7838 //-----------------------------------------------------------------------------------
7839 // impFixupCallStructReturn: For a call node that returns a struct type either
7840 // adjust the return type to an enregisterable type, or set the flag to indicate
7841 // struct return via retbuf arg.
7844 // call - GT_CALL GenTree node
7845 // retClsHnd - Class handle of return type of the call
7848 // Returns new GenTree node after fixing struct return of call node
7850 GenTreePtr Compiler::impFixupCallStructReturn(GenTreePtr call, CORINFO_CLASS_HANDLE retClsHnd)
7852 assert(call->gtOper == GT_CALL);
7854 if (!varTypeIsStruct(call))
7859 call->gtCall.gtRetClsHnd = retClsHnd;
7861 GenTreeCall* callNode = call->AsCall();
7863 #if FEATURE_MULTIREG_RET
7864 // Initialize Return type descriptor of call node
7865 ReturnTypeDesc* retTypeDesc = callNode->GetReturnTypeDesc();
7866 retTypeDesc->InitializeStructReturnType(this, retClsHnd);
7867 #endif // FEATURE_MULTIREG_RET
7869 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
7871 // Not allowed for FEATURE_CORCLR which is the only SKU available for System V OSs.
7872 assert(!callNode->IsVarargs() && "varargs not allowed for System V OSs.");
7874 // The return type will remain as the incoming struct type unless normalized to a
7875 // single eightbyte return type below.
7876 callNode->gtReturnType = call->gtType;
7878 unsigned retRegCount = retTypeDesc->GetReturnRegCount();
7879 if (retRegCount != 0)
7881 if (retRegCount == 1)
7883 // struct returned in a single register
7884 callNode->gtReturnType = retTypeDesc->GetReturnRegType(0);
7888 // must be a struct returned in two registers
7889 assert(retRegCount == 2);
7891 if ((!callNode->CanTailCall()) && (!callNode->IsInlineCandidate()))
7893 // Force a call returning multi-reg struct to be always of the IR form
7896 // No need to assign a multi-reg struct to a local var if:
7897 // - It is a tail call or
7898 // - The call is marked for in-lining later
7899 return impAssignMultiRegTypeToVar(call, retClsHnd);
7905 // struct not returned in registers i.e returned via hiddden retbuf arg.
7906 callNode->gtCallMoreFlags |= GTF_CALL_M_RETBUFFARG;
7909 #else // not FEATURE_UNIX_AMD64_STRUCT_PASSING
7911 #if FEATURE_MULTIREG_RET && defined(_TARGET_ARM_)
7912 // There is no fixup necessary if the return type is a HFA struct.
7913 // HFA structs are returned in registers for ARM32 and ARM64
7915 if (!call->gtCall.IsVarargs() && IsHfa(retClsHnd))
7917 if (call->gtCall.CanTailCall())
7919 if (info.compIsVarArgs)
7921 // We cannot tail call because control needs to return to fixup the calling
7922 // convention for result return.
7923 call->gtCall.gtCallMoreFlags &= ~GTF_CALL_M_EXPLICIT_TAILCALL;
7927 // If we can tail call returning HFA, then don't assign it to
7928 // a variable back and forth.
7933 if (call->gtFlags & GTF_CALL_INLINE_CANDIDATE)
7938 unsigned retRegCount = retTypeDesc->GetReturnRegCount();
7939 if (retRegCount >= 2)
7941 return impAssignMultiRegTypeToVar(call, retClsHnd);
7944 #endif // _TARGET_ARM_
7946 // Check for TYP_STRUCT type that wraps a primitive type
7947 // Such structs are returned using a single register
7948 // and we change the return type on those calls here.
7950 structPassingKind howToReturnStruct;
7951 var_types returnType = getReturnTypeForStruct(retClsHnd, &howToReturnStruct);
7953 if (howToReturnStruct == SPK_ByReference)
7955 assert(returnType == TYP_UNKNOWN);
7956 call->gtCall.gtCallMoreFlags |= GTF_CALL_M_RETBUFFARG;
7960 assert(returnType != TYP_UNKNOWN);
7961 call->gtCall.gtReturnType = returnType;
7963 // ToDo: Refactor this common code sequence into its own method as it is used 4+ times
7964 if ((returnType == TYP_LONG) && (compLongUsed == false))
7966 compLongUsed = true;
7968 else if (((returnType == TYP_FLOAT) || (returnType == TYP_DOUBLE)) && (compFloatingPointUsed == false))
7970 compFloatingPointUsed = true;
7973 #if FEATURE_MULTIREG_RET
7974 unsigned retRegCount = retTypeDesc->GetReturnRegCount();
7975 assert(retRegCount != 0);
7977 if (retRegCount >= 2)
7979 if ((!callNode->CanTailCall()) && (!callNode->IsInlineCandidate()))
7981 // Force a call returning multi-reg struct to be always of the IR form
7984 // No need to assign a multi-reg struct to a local var if:
7985 // - It is a tail call or
7986 // - The call is marked for in-lining later
7987 return impAssignMultiRegTypeToVar(call, retClsHnd);
7990 #endif // FEATURE_MULTIREG_RET
7993 #endif // not FEATURE_UNIX_AMD64_STRUCT_PASSING
7998 /*****************************************************************************
7999 For struct return values, re-type the operand in the case where the ABI
8000 does not use a struct return buffer
8001 Note that this method is only call for !_TARGET_X86_
8004 GenTreePtr Compiler::impFixupStructReturnType(GenTreePtr op, CORINFO_CLASS_HANDLE retClsHnd)
8006 assert(varTypeIsStruct(info.compRetType));
8007 assert(info.compRetBuffArg == BAD_VAR_NUM);
8009 #if defined(_TARGET_XARCH_)
8011 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
8012 // No VarArgs for CoreCLR on x64 Unix
8013 assert(!info.compIsVarArgs);
8015 // Is method returning a multi-reg struct?
8016 if (varTypeIsStruct(info.compRetNativeType) && IsMultiRegReturnedType(retClsHnd))
8018 // In case of multi-reg struct return, we force IR to be one of the following:
8019 // GT_RETURN(lclvar) or GT_RETURN(call). If op is anything other than a
8020 // lclvar or call, it is assigned to a temp to create: temp = op and GT_RETURN(tmp).
8022 if (op->gtOper == GT_LCL_VAR)
8024 // Make sure that this struct stays in memory and doesn't get promoted.
8025 unsigned lclNum = op->gtLclVarCommon.gtLclNum;
8026 lvaTable[lclNum].lvIsMultiRegRet = true;
8028 // TODO-1stClassStructs: Handle constant propagation and CSE-ing of multireg returns.
8029 op->gtFlags |= GTF_DONT_CSE;
8034 if (op->gtOper == GT_CALL)
8039 return impAssignMultiRegTypeToVar(op, retClsHnd);
8041 #else // !FEATURE_UNIX_AMD64_STRUCT_PASSING
8042 assert(info.compRetNativeType != TYP_STRUCT);
8043 #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING
8045 #elif FEATURE_MULTIREG_RET && defined(_TARGET_ARM_)
8047 if (varTypeIsStruct(info.compRetNativeType) && !info.compIsVarArgs && IsHfa(retClsHnd))
8049 if (op->gtOper == GT_LCL_VAR)
8051 // This LCL_VAR is an HFA return value, it stays as a TYP_STRUCT
8052 unsigned lclNum = op->gtLclVarCommon.gtLclNum;
8053 // Make sure this struct type stays as struct so that we can return it as an HFA
8054 lvaTable[lclNum].lvIsMultiRegRet = true;
8056 // TODO-1stClassStructs: Handle constant propagation and CSE-ing of multireg returns.
8057 op->gtFlags |= GTF_DONT_CSE;
8062 if (op->gtOper == GT_CALL)
8064 if (op->gtCall.IsVarargs())
8066 // We cannot tail call because control needs to return to fixup the calling
8067 // convention for result return.
8068 op->gtCall.gtCallMoreFlags &= ~GTF_CALL_M_TAILCALL;
8069 op->gtCall.gtCallMoreFlags &= ~GTF_CALL_M_EXPLICIT_TAILCALL;
8076 return impAssignMultiRegTypeToVar(op, retClsHnd);
8079 #elif FEATURE_MULTIREG_RET && defined(_TARGET_ARM64_)
8081 // Is method returning a multi-reg struct?
8082 if (IsMultiRegReturnedType(retClsHnd))
8084 if (op->gtOper == GT_LCL_VAR)
8086 // This LCL_VAR stays as a TYP_STRUCT
8087 unsigned lclNum = op->gtLclVarCommon.gtLclNum;
8089 // Make sure this struct type is not struct promoted
8090 lvaTable[lclNum].lvIsMultiRegRet = true;
8092 // TODO-1stClassStructs: Handle constant propagation and CSE-ing of multireg returns.
8093 op->gtFlags |= GTF_DONT_CSE;
8098 if (op->gtOper == GT_CALL)
8100 if (op->gtCall.IsVarargs())
8102 // We cannot tail call because control needs to return to fixup the calling
8103 // convention for result return.
8104 op->gtCall.gtCallMoreFlags &= ~GTF_CALL_M_TAILCALL;
8105 op->gtCall.gtCallMoreFlags &= ~GTF_CALL_M_EXPLICIT_TAILCALL;
8112 return impAssignMultiRegTypeToVar(op, retClsHnd);
8115 #endif // FEATURE_MULTIREG_RET && FEATURE_HFA
8118 // adjust the type away from struct to integral
8119 // and no normalizing
8120 if (op->gtOper == GT_LCL_VAR)
8122 op->ChangeOper(GT_LCL_FLD);
8124 else if (op->gtOper == GT_OBJ)
8126 GenTreePtr op1 = op->AsObj()->Addr();
8128 // We will fold away OBJ/ADDR
8129 // except for OBJ/ADDR/INDEX
8130 // as the array type influences the array element's offset
8131 // Later in this method we change op->gtType to info.compRetNativeType
8132 // This is not correct when op is a GT_INDEX as the starting offset
8133 // for the array elements 'elemOffs' is different for an array of
8134 // TYP_REF than an array of TYP_STRUCT (which simply wraps a TYP_REF)
8135 // Also refer to the GTF_INX_REFARR_LAYOUT flag
8137 if ((op1->gtOper == GT_ADDR) && (op1->gtOp.gtOp1->gtOper != GT_INDEX))
8139 // Change '*(&X)' to 'X' and see if we can do better
8140 op = op1->gtOp.gtOp1;
8141 goto REDO_RETURN_NODE;
8143 op->gtObj.gtClass = NO_CLASS_HANDLE;
8144 op->ChangeOperUnchecked(GT_IND);
8145 op->gtFlags |= GTF_IND_TGTANYWHERE;
8147 else if (op->gtOper == GT_CALL)
8149 if (op->AsCall()->TreatAsHasRetBufArg(this))
8151 // This must be one of those 'special' helpers that don't
8152 // really have a return buffer, but instead use it as a way
8153 // to keep the trees cleaner with fewer address-taken temps.
8155 // Well now we have to materialize the the return buffer as
8156 // an address-taken temp. Then we can return the temp.
8158 // NOTE: this code assumes that since the call directly
8159 // feeds the return, then the call must be returning the
8160 // same structure/class/type.
8162 unsigned tmpNum = lvaGrabTemp(true DEBUGARG("pseudo return buffer"));
8164 // No need to spill anything as we're about to return.
8165 impAssignTempGen(tmpNum, op, info.compMethodInfo->args.retTypeClass, (unsigned)CHECK_SPILL_NONE);
8167 // Don't create both a GT_ADDR & GT_OBJ just to undo all of that; instead,
8168 // jump directly to a GT_LCL_FLD.
8169 op = gtNewLclvNode(tmpNum, info.compRetNativeType);
8170 op->ChangeOper(GT_LCL_FLD);
8174 assert(info.compRetNativeType == op->gtCall.gtReturnType);
8176 // Don't change the gtType of the node just yet, it will get changed later.
8180 else if (op->gtOper == GT_COMMA)
8182 op->gtOp.gtOp2 = impFixupStructReturnType(op->gtOp.gtOp2, retClsHnd);
8185 op->gtType = info.compRetNativeType;
8190 /*****************************************************************************
8191 CEE_LEAVE may be jumping out of a protected block, viz, a catch or a
8192 finally-protected try. We find the finally blocks protecting the current
8193 offset (in order) by walking over the complete exception table and
8194 finding enclosing clauses. This assumes that the table is sorted.
8195 This will create a series of BBJ_CALLFINALLY -> BBJ_CALLFINALLY ... -> BBJ_ALWAYS.
8197 If we are leaving a catch handler, we need to attach the
8198 CPX_ENDCATCHes to the correct BBJ_CALLFINALLY blocks.
8200 After this function, the BBJ_LEAVE block has been converted to a different type.
8203 #if !FEATURE_EH_FUNCLETS
8205 void Compiler::impImportLeave(BasicBlock* block)
8210 printf("\nBefore import CEE_LEAVE:\n");
8211 fgDispBasicBlocks();
8216 bool invalidatePreds = false; // If we create new blocks, invalidate the predecessor lists (if created)
8217 unsigned blkAddr = block->bbCodeOffs;
8218 BasicBlock* leaveTarget = block->bbJumpDest;
8219 unsigned jmpAddr = leaveTarget->bbCodeOffs;
8221 // LEAVE clears the stack, spill side effects, and set stack to 0
8223 impSpillSideEffects(true, (unsigned)CHECK_SPILL_ALL DEBUGARG("impImportLeave"));
8224 verCurrentState.esStackDepth = 0;
8226 assert(block->bbJumpKind == BBJ_LEAVE);
8227 assert(fgBBs == (BasicBlock**)0xCDCD || fgLookupBB(jmpAddr) != NULL); // should be a BB boundary
8229 BasicBlock* step = DUMMY_INIT(NULL);
8230 unsigned encFinallies = 0; // Number of enclosing finallies.
8231 GenTreePtr endCatches = NULL;
8232 GenTreePtr endLFin = NULL; // The statement tree to indicate the end of locally-invoked finally.
8237 for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++)
8239 // Grab the handler offsets
8241 IL_OFFSET tryBeg = HBtab->ebdTryBegOffs();
8242 IL_OFFSET tryEnd = HBtab->ebdTryEndOffs();
8243 IL_OFFSET hndBeg = HBtab->ebdHndBegOffs();
8244 IL_OFFSET hndEnd = HBtab->ebdHndEndOffs();
8246 /* Is this a catch-handler we are CEE_LEAVEing out of?
8247 * If so, we need to call CORINFO_HELP_ENDCATCH.
8250 if (jitIsBetween(blkAddr, hndBeg, hndEnd) && !jitIsBetween(jmpAddr, hndBeg, hndEnd))
8252 // Can't CEE_LEAVE out of a finally/fault handler
8253 if (HBtab->HasFinallyOrFaultHandler())
8254 BADCODE("leave out of fault/finally block");
8256 // Create the call to CORINFO_HELP_ENDCATCH
8257 GenTreePtr endCatch = gtNewHelperCallNode(CORINFO_HELP_ENDCATCH, TYP_VOID);
8259 // Make a list of all the currently pending endCatches
8261 endCatches = gtNewOperNode(GT_COMMA, TYP_VOID, endCatches, endCatch);
8263 endCatches = endCatch;
8268 printf("impImportLeave - BB%02u jumping out of catch handler EH#%u, adding call to "
8269 "CORINFO_HELP_ENDCATCH\n",
8270 block->bbNum, XTnum);
8274 else if (HBtab->HasFinallyHandler() && jitIsBetween(blkAddr, tryBeg, tryEnd) &&
8275 !jitIsBetween(jmpAddr, tryBeg, tryEnd))
8277 /* This is a finally-protected try we are jumping out of */
8279 /* If there are any pending endCatches, and we have already
8280 jumped out of a finally-protected try, then the endCatches
8281 have to be put in a block in an outer try for async
8282 exceptions to work correctly.
8283 Else, just use append to the original block */
8285 BasicBlock* callBlock;
8287 assert(!encFinallies == !endLFin); // if we have finallies, we better have an endLFin tree, and vice-versa
8289 if (encFinallies == 0)
8291 assert(step == DUMMY_INIT(NULL));
8293 callBlock->bbJumpKind = BBJ_CALLFINALLY; // convert the BBJ_LEAVE to BBJ_CALLFINALLY
8296 impAppendTree(endCatches, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
8301 printf("impImportLeave - jumping out of a finally-protected try, convert block to BBJ_CALLFINALLY "
8302 "block BB%02u [%08p]\n",
8303 callBlock->bbNum, dspPtr(callBlock));
8309 assert(step != DUMMY_INIT(NULL));
8311 /* Calling the finally block */
8312 callBlock = fgNewBBinRegion(BBJ_CALLFINALLY, XTnum + 1, 0, step);
8313 assert(step->bbJumpKind == BBJ_ALWAYS);
8314 step->bbJumpDest = callBlock; // the previous call to a finally returns to this call (to the next
8315 // finally in the chain)
8316 step->bbJumpDest->bbRefs++;
8318 /* The new block will inherit this block's weight */
8319 callBlock->setBBWeight(block->bbWeight);
8320 callBlock->bbFlags |= block->bbFlags & BBF_RUN_RARELY;
8325 printf("impImportLeave - jumping out of a finally-protected try, new BBJ_CALLFINALLY block BB%02u "
8327 callBlock->bbNum, dspPtr(callBlock));
8331 GenTreePtr lastStmt;
8335 lastStmt = gtNewStmt(endCatches);
8336 endLFin->gtNext = lastStmt;
8337 lastStmt->gtPrev = endLFin;
8344 // note that this sets BBF_IMPORTED on the block
8345 impEndTreeList(callBlock, endLFin, lastStmt);
8348 step = fgNewBBafter(BBJ_ALWAYS, callBlock, true);
8349 /* The new block will inherit this block's weight */
8350 step->setBBWeight(block->bbWeight);
8351 step->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED | BBF_KEEP_BBJ_ALWAYS;
8356 printf("impImportLeave - jumping out of a finally-protected try, created step (BBJ_ALWAYS) block "
8358 step->bbNum, dspPtr(step));
8362 unsigned finallyNesting = compHndBBtab[XTnum].ebdHandlerNestingLevel;
8363 assert(finallyNesting <= compHndBBtabCount);
8365 callBlock->bbJumpDest = HBtab->ebdHndBeg; // This callBlock will call the "finally" handler.
8366 endLFin = new (this, GT_END_LFIN) GenTreeVal(GT_END_LFIN, TYP_VOID, finallyNesting);
8367 endLFin = gtNewStmt(endLFin);
8372 invalidatePreds = true;
8376 /* Append any remaining endCatches, if any */
8378 assert(!encFinallies == !endLFin);
8380 if (encFinallies == 0)
8382 assert(step == DUMMY_INIT(NULL));
8383 block->bbJumpKind = BBJ_ALWAYS; // convert the BBJ_LEAVE to a BBJ_ALWAYS
8386 impAppendTree(endCatches, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
8391 printf("impImportLeave - no enclosing finally-protected try blocks; convert CEE_LEAVE block to BBJ_ALWAYS "
8392 "block BB%02u [%08p]\n",
8393 block->bbNum, dspPtr(block));
8399 // If leaveTarget is the start of another try block, we want to make sure that
8400 // we do not insert finalStep into that try block. Hence, we find the enclosing
8402 unsigned tryIndex = bbFindInnermostCommonTryRegion(step, leaveTarget);
8404 // Insert a new BB either in the try region indicated by tryIndex or
8405 // the handler region indicated by leaveTarget->bbHndIndex,
8406 // depending on which is the inner region.
8407 BasicBlock* finalStep = fgNewBBinRegion(BBJ_ALWAYS, tryIndex, leaveTarget->bbHndIndex, step);
8408 finalStep->bbFlags |= BBF_KEEP_BBJ_ALWAYS;
8409 step->bbJumpDest = finalStep;
8411 /* The new block will inherit this block's weight */
8412 finalStep->setBBWeight(block->bbWeight);
8413 finalStep->bbFlags |= block->bbFlags & BBF_RUN_RARELY;
8418 printf("impImportLeave - finalStep block required (encFinallies(%d) > 0), new block BB%02u [%08p]\n",
8419 encFinallies, finalStep->bbNum, dspPtr(finalStep));
8423 GenTreePtr lastStmt;
8427 lastStmt = gtNewStmt(endCatches);
8428 endLFin->gtNext = lastStmt;
8429 lastStmt->gtPrev = endLFin;
8436 impEndTreeList(finalStep, endLFin, lastStmt);
8438 finalStep->bbJumpDest = leaveTarget; // this is the ultimate destination of the LEAVE
8440 // Queue up the jump target for importing
8442 impImportBlockPending(leaveTarget);
8444 invalidatePreds = true;
8447 if (invalidatePreds && fgComputePredsDone)
8449 JITDUMP("\n**** impImportLeave - Removing preds after creating new blocks\n");
8454 fgVerifyHandlerTab();
8458 printf("\nAfter import CEE_LEAVE:\n");
8459 fgDispBasicBlocks();
8465 #else // FEATURE_EH_FUNCLETS
8467 void Compiler::impImportLeave(BasicBlock* block)
8472 printf("\nBefore import CEE_LEAVE in BB%02u (targetting BB%02u):\n", block->bbNum, block->bbJumpDest->bbNum);
8473 fgDispBasicBlocks();
8478 bool invalidatePreds = false; // If we create new blocks, invalidate the predecessor lists (if created)
8479 unsigned blkAddr = block->bbCodeOffs;
8480 BasicBlock* leaveTarget = block->bbJumpDest;
8481 unsigned jmpAddr = leaveTarget->bbCodeOffs;
8483 // LEAVE clears the stack, spill side effects, and set stack to 0
8485 impSpillSideEffects(true, (unsigned)CHECK_SPILL_ALL DEBUGARG("impImportLeave"));
8486 verCurrentState.esStackDepth = 0;
8488 assert(block->bbJumpKind == BBJ_LEAVE);
8489 assert(fgBBs == (BasicBlock**)0xCDCD || fgLookupBB(jmpAddr) != nullptr); // should be a BB boundary
8491 BasicBlock* step = nullptr;
8495 // No step type; step == NULL.
8498 // Is the step block the BBJ_ALWAYS block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair?
8499 // That is, is step->bbJumpDest where a finally will return to?
8502 // The step block is a catch return.
8505 // The step block is in a "try", created as the target for a finally return or the target for a catch return.
8508 StepType stepType = ST_None;
8513 for (XTnum = 0, HBtab = compHndBBtab; XTnum < compHndBBtabCount; XTnum++, HBtab++)
8515 // Grab the handler offsets
8517 IL_OFFSET tryBeg = HBtab->ebdTryBegOffs();
8518 IL_OFFSET tryEnd = HBtab->ebdTryEndOffs();
8519 IL_OFFSET hndBeg = HBtab->ebdHndBegOffs();
8520 IL_OFFSET hndEnd = HBtab->ebdHndEndOffs();
8522 /* Is this a catch-handler we are CEE_LEAVEing out of?
8525 if (jitIsBetween(blkAddr, hndBeg, hndEnd) && !jitIsBetween(jmpAddr, hndBeg, hndEnd))
8527 // Can't CEE_LEAVE out of a finally/fault handler
8528 if (HBtab->HasFinallyOrFaultHandler())
8530 BADCODE("leave out of fault/finally block");
8533 /* We are jumping out of a catch */
8535 if (step == nullptr)
8538 step->bbJumpKind = BBJ_EHCATCHRET; // convert the BBJ_LEAVE to BBJ_EHCATCHRET
8539 stepType = ST_Catch;
8544 printf("impImportLeave - jumping out of a catch (EH#%u), convert block BB%02u to BBJ_EHCATCHRET "
8546 XTnum, step->bbNum);
8552 BasicBlock* exitBlock;
8554 /* Create a new catch exit block in the catch region for the existing step block to jump to in this
8556 exitBlock = fgNewBBinRegion(BBJ_EHCATCHRET, 0, XTnum + 1, step);
8558 assert(step->bbJumpKind == BBJ_ALWAYS || step->bbJumpKind == BBJ_EHCATCHRET);
8559 step->bbJumpDest = exitBlock; // the previous step (maybe a call to a nested finally, or a nested catch
8560 // exit) returns to this block
8561 step->bbJumpDest->bbRefs++;
8563 #if defined(_TARGET_ARM_)
8564 if (stepType == ST_FinallyReturn)
8566 assert(step->bbJumpKind == BBJ_ALWAYS);
8567 // Mark the target of a finally return
8568 step->bbJumpDest->bbFlags |= BBF_FINALLY_TARGET;
8570 #endif // defined(_TARGET_ARM_)
8572 /* The new block will inherit this block's weight */
8573 exitBlock->setBBWeight(block->bbWeight);
8574 exitBlock->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED;
8576 /* This exit block is the new step */
8578 stepType = ST_Catch;
8580 invalidatePreds = true;
8585 printf("impImportLeave - jumping out of a catch (EH#%u), new BBJ_EHCATCHRET block BB%02u\n", XTnum,
8591 else if (HBtab->HasFinallyHandler() && jitIsBetween(blkAddr, tryBeg, tryEnd) &&
8592 !jitIsBetween(jmpAddr, tryBeg, tryEnd))
8594 /* We are jumping out of a finally-protected try */
8596 BasicBlock* callBlock;
8598 if (step == nullptr)
8600 #if FEATURE_EH_CALLFINALLY_THUNKS
8602 // Put the call to the finally in the enclosing region.
8603 unsigned callFinallyTryIndex =
8604 (HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) ? 0 : HBtab->ebdEnclosingTryIndex + 1;
8605 unsigned callFinallyHndIndex =
8606 (HBtab->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX) ? 0 : HBtab->ebdEnclosingHndIndex + 1;
8607 callBlock = fgNewBBinRegion(BBJ_CALLFINALLY, callFinallyTryIndex, callFinallyHndIndex, block);
8609 // Convert the BBJ_LEAVE to BBJ_ALWAYS, jumping to the new BBJ_CALLFINALLY. This is because
8610 // the new BBJ_CALLFINALLY is in a different EH region, thus it can't just replace the BBJ_LEAVE,
8611 // which might be in the middle of the "try". In most cases, the BBJ_ALWAYS will jump to the
8612 // next block, and flow optimizations will remove it.
8613 block->bbJumpKind = BBJ_ALWAYS;
8614 block->bbJumpDest = callBlock;
8615 block->bbJumpDest->bbRefs++;
8617 /* The new block will inherit this block's weight */
8618 callBlock->setBBWeight(block->bbWeight);
8619 callBlock->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED;
8624 printf("impImportLeave - jumping out of a finally-protected try (EH#%u), convert block BB%02u to "
8625 "BBJ_ALWAYS, add BBJ_CALLFINALLY block BB%02u\n",
8626 XTnum, block->bbNum, callBlock->bbNum);
8630 #else // !FEATURE_EH_CALLFINALLY_THUNKS
8633 callBlock->bbJumpKind = BBJ_CALLFINALLY; // convert the BBJ_LEAVE to BBJ_CALLFINALLY
8638 printf("impImportLeave - jumping out of a finally-protected try (EH#%u), convert block BB%02u to "
8639 "BBJ_CALLFINALLY block\n",
8640 XTnum, callBlock->bbNum);
8644 #endif // !FEATURE_EH_CALLFINALLY_THUNKS
8648 // Calling the finally block. We already have a step block that is either the call-to-finally from a
8649 // more nested try/finally (thus we are jumping out of multiple nested 'try' blocks, each protected by
8650 // a 'finally'), or the step block is the return from a catch.
8652 // Due to ThreadAbortException, we can't have the catch return target the call-to-finally block
8653 // directly. Note that if a 'catch' ends without resetting the ThreadAbortException, the VM will
8654 // automatically re-raise the exception, using the return address of the catch (that is, the target
8655 // block of the BBJ_EHCATCHRET) as the re-raise address. If this address is in a finally, the VM will
8656 // refuse to do the re-raise, and the ThreadAbortException will get eaten (and lost). On AMD64/ARM64,
8657 // we put the call-to-finally thunk in a special "cloned finally" EH region that does look like a
8658 // finally clause to the VM. Thus, on these platforms, we can't have BBJ_EHCATCHRET target a
8659 // BBJ_CALLFINALLY directly. (Note that on ARM32, we don't mark the thunk specially -- it lives directly
8660 // within the 'try' region protected by the finally, since we generate code in such a way that execution
8661 // never returns to the call-to-finally call, and the finally-protected 'try' region doesn't appear on
8664 assert(step->bbJumpKind == BBJ_ALWAYS || step->bbJumpKind == BBJ_EHCATCHRET);
8666 #if FEATURE_EH_CALLFINALLY_THUNKS
8667 if (step->bbJumpKind == BBJ_EHCATCHRET)
8669 // Need to create another step block in the 'try' region that will actually branch to the
8670 // call-to-finally thunk.
8671 BasicBlock* step2 = fgNewBBinRegion(BBJ_ALWAYS, XTnum + 1, 0, step);
8672 step->bbJumpDest = step2;
8673 step->bbJumpDest->bbRefs++;
8674 step2->setBBWeight(block->bbWeight);
8675 step2->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED;
8680 printf("impImportLeave - jumping out of a finally-protected try (EH#%u), step block is "
8681 "BBJ_EHCATCHRET (BB%02u), new BBJ_ALWAYS step-step block BB%02u\n",
8682 XTnum, step->bbNum, step2->bbNum);
8687 assert(stepType == ST_Catch); // Leave it as catch type for now.
8689 #endif // FEATURE_EH_CALLFINALLY_THUNKS
8691 #if FEATURE_EH_CALLFINALLY_THUNKS
8692 unsigned callFinallyTryIndex =
8693 (HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) ? 0 : HBtab->ebdEnclosingTryIndex + 1;
8694 unsigned callFinallyHndIndex =
8695 (HBtab->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX) ? 0 : HBtab->ebdEnclosingHndIndex + 1;
8696 #else // !FEATURE_EH_CALLFINALLY_THUNKS
8697 unsigned callFinallyTryIndex = XTnum + 1;
8698 unsigned callFinallyHndIndex = 0; // don't care
8699 #endif // !FEATURE_EH_CALLFINALLY_THUNKS
8701 callBlock = fgNewBBinRegion(BBJ_CALLFINALLY, callFinallyTryIndex, callFinallyHndIndex, step);
8702 step->bbJumpDest = callBlock; // the previous call to a finally returns to this call (to the next
8703 // finally in the chain)
8704 step->bbJumpDest->bbRefs++;
8706 #if defined(_TARGET_ARM_)
8707 if (stepType == ST_FinallyReturn)
8709 assert(step->bbJumpKind == BBJ_ALWAYS);
8710 // Mark the target of a finally return
8711 step->bbJumpDest->bbFlags |= BBF_FINALLY_TARGET;
8713 #endif // defined(_TARGET_ARM_)
8715 /* The new block will inherit this block's weight */
8716 callBlock->setBBWeight(block->bbWeight);
8717 callBlock->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED;
8722 printf("impImportLeave - jumping out of a finally-protected try (EH#%u), new BBJ_CALLFINALLY block "
8724 XTnum, callBlock->bbNum);
8729 step = fgNewBBafter(BBJ_ALWAYS, callBlock, true);
8730 stepType = ST_FinallyReturn;
8732 /* The new block will inherit this block's weight */
8733 step->setBBWeight(block->bbWeight);
8734 step->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED | BBF_KEEP_BBJ_ALWAYS;
8739 printf("impImportLeave - jumping out of a finally-protected try (EH#%u), created step (BBJ_ALWAYS) "
8741 XTnum, step->bbNum);
8745 callBlock->bbJumpDest = HBtab->ebdHndBeg; // This callBlock will call the "finally" handler.
8747 invalidatePreds = true;
8749 else if (HBtab->HasCatchHandler() && jitIsBetween(blkAddr, tryBeg, tryEnd) &&
8750 !jitIsBetween(jmpAddr, tryBeg, tryEnd))
8752 // We are jumping out of a catch-protected try.
8754 // If we are returning from a call to a finally, then we must have a step block within a try
8755 // that is protected by a catch. This is so when unwinding from that finally (e.g., if code within the
8756 // finally raises an exception), the VM will find this step block, notice that it is in a protected region,
8757 // and invoke the appropriate catch.
8759 // We also need to handle a special case with the handling of ThreadAbortException. If a try/catch
8760 // catches a ThreadAbortException (which might be because it catches a parent, e.g. System.Exception),
8761 // and the catch doesn't call System.Threading.Thread::ResetAbort(), then when the catch returns to the VM,
8762 // the VM will automatically re-raise the ThreadAbortException. When it does this, it uses the target
8763 // address of the catch return as the new exception address. That is, the re-raised exception appears to
8764 // occur at the catch return address. If this exception return address skips an enclosing try/catch that
8765 // catches ThreadAbortException, then the enclosing try/catch will not catch the exception, as it should.
8770 // // something here raises ThreadAbortException
8771 // LEAVE LABEL_1; // no need to stop at LABEL_2
8772 // } catch (Exception) {
8773 // // This catches ThreadAbortException, but doesn't call System.Threading.Thread::ResetAbort(), so
8774 // // ThreadAbortException is re-raised by the VM at the address specified by the LEAVE opcode.
8775 // // This is bad, since it means the outer try/catch won't get a chance to catch the re-raised
8776 // // ThreadAbortException. So, instead, create step block LABEL_2 and LEAVE to that. We only
8777 // // need to do this transformation if the current EH block is a try/catch that catches
8778 // // ThreadAbortException (or one of its parents), however we might not be able to find that
8779 // // information, so currently we do it for all catch types.
8780 // LEAVE LABEL_1; // Convert this to LEAVE LABEL2;
8782 // LABEL_2: LEAVE LABEL_1; // inserted by this step creation code
8783 // } catch (ThreadAbortException) {
8787 // Note that this pattern isn't theoretical: it occurs in ASP.NET, in IL code generated by the Roslyn C#
8790 if ((stepType == ST_FinallyReturn) || (stepType == ST_Catch))
8792 BasicBlock* catchStep;
8796 if (stepType == ST_FinallyReturn)
8798 assert(step->bbJumpKind == BBJ_ALWAYS);
8802 assert(stepType == ST_Catch);
8803 assert(step->bbJumpKind == BBJ_EHCATCHRET);
8806 /* Create a new exit block in the try region for the existing step block to jump to in this scope */
8807 catchStep = fgNewBBinRegion(BBJ_ALWAYS, XTnum + 1, 0, step);
8808 step->bbJumpDest = catchStep;
8809 step->bbJumpDest->bbRefs++;
8811 #if defined(_TARGET_ARM_)
8812 if (stepType == ST_FinallyReturn)
8814 // Mark the target of a finally return
8815 step->bbJumpDest->bbFlags |= BBF_FINALLY_TARGET;
8817 #endif // defined(_TARGET_ARM_)
8819 /* The new block will inherit this block's weight */
8820 catchStep->setBBWeight(block->bbWeight);
8821 catchStep->bbFlags |= (block->bbFlags & BBF_RUN_RARELY) | BBF_IMPORTED;
8826 if (stepType == ST_FinallyReturn)
8828 printf("impImportLeave - return from finally jumping out of a catch-protected try (EH#%u), new "
8829 "BBJ_ALWAYS block BB%02u\n",
8830 XTnum, catchStep->bbNum);
8834 assert(stepType == ST_Catch);
8835 printf("impImportLeave - return from catch jumping out of a catch-protected try (EH#%u), new "
8836 "BBJ_ALWAYS block BB%02u\n",
8837 XTnum, catchStep->bbNum);
8842 /* This block is the new step */
8846 invalidatePreds = true;
8851 if (step == nullptr)
8853 block->bbJumpKind = BBJ_ALWAYS; // convert the BBJ_LEAVE to a BBJ_ALWAYS
8858 printf("impImportLeave - no enclosing finally-protected try blocks or catch handlers; convert CEE_LEAVE "
8859 "block BB%02u to BBJ_ALWAYS\n",
8866 step->bbJumpDest = leaveTarget; // this is the ultimate destination of the LEAVE
8868 #if defined(_TARGET_ARM_)
8869 if (stepType == ST_FinallyReturn)
8871 assert(step->bbJumpKind == BBJ_ALWAYS);
8872 // Mark the target of a finally return
8873 step->bbJumpDest->bbFlags |= BBF_FINALLY_TARGET;
8875 #endif // defined(_TARGET_ARM_)
8880 printf("impImportLeave - final destination of step blocks set to BB%02u\n", leaveTarget->bbNum);
8884 // Queue up the jump target for importing
8886 impImportBlockPending(leaveTarget);
8889 if (invalidatePreds && fgComputePredsDone)
8891 JITDUMP("\n**** impImportLeave - Removing preds after creating new blocks\n");
8896 fgVerifyHandlerTab();
8900 printf("\nAfter import CEE_LEAVE:\n");
8901 fgDispBasicBlocks();
8907 #endif // FEATURE_EH_FUNCLETS
8909 /*****************************************************************************/
8910 // This is called when reimporting a leave block. It resets the JumpKind,
8911 // JumpDest, and bbNext to the original values
8913 void Compiler::impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr)
8915 #if FEATURE_EH_FUNCLETS
8916 // With EH Funclets, while importing leave opcode we create another block ending with BBJ_ALWAYS (call it B1)
8917 // and the block containing leave (say B0) is marked as BBJ_CALLFINALLY. Say for some reason we reimport B0,
8918 // it is reset (in this routine) by marking as ending with BBJ_LEAVE and further down when B0 is reimported, we
8919 // create another BBJ_ALWAYS (call it B2). In this process B1 gets orphaned and any blocks to which B1 is the
8920 // only predecessor are also considered orphans and attempted to be deleted.
8927 // leave OUTSIDE; // B0 is the block containing this leave, following this would be B1
8932 // In the above nested try-finally example, we create a step block (call it Bstep) which in branches to a block
8933 // where a finally would branch to (and such block is marked as finally target). Block B1 branches to step block.
8934 // Because of re-import of B0, Bstep is also orphaned. Since Bstep is a finally target it cannot be removed. To
8935 // work around this we will duplicate B0 (call it B0Dup) before reseting. B0Dup is marked as BBJ_CALLFINALLY and
8936 // only serves to pair up with B1 (BBJ_ALWAYS) that got orphaned. Now during orphan block deletion B0Dup and B1
8937 // will be treated as pair and handled correctly.
8938 if (block->bbJumpKind == BBJ_CALLFINALLY)
8940 BasicBlock* dupBlock = bbNewBasicBlock(block->bbJumpKind);
8941 dupBlock->bbFlags = block->bbFlags;
8942 dupBlock->bbJumpDest = block->bbJumpDest;
8943 dupBlock->copyEHRegion(block);
8944 dupBlock->bbCatchTyp = block->bbCatchTyp;
8946 // Mark this block as
8947 // a) not referenced by any other block to make sure that it gets deleted
8949 // c) prevent from being imported
8952 dupBlock->bbRefs = 0;
8953 dupBlock->bbWeight = 0;
8954 dupBlock->bbFlags |= BBF_IMPORTED | BBF_INTERNAL | BBF_RUN_RARELY;
8956 // Insert the block right after the block which is getting reset so that BBJ_CALLFINALLY and BBJ_ALWAYS
8957 // will be next to each other.
8958 fgInsertBBafter(block, dupBlock);
8963 printf("New Basic Block BB%02u duplicate of BB%02u created.\n", dupBlock->bbNum, block->bbNum);
8967 #endif // FEATURE_EH_FUNCLETS
8969 block->bbJumpKind = BBJ_LEAVE;
8971 block->bbJumpDest = fgLookupBB(jmpAddr);
8973 // We will leave the BBJ_ALWAYS block we introduced. When it's reimported
8974 // the BBJ_ALWAYS block will be unreachable, and will be removed after. The
8975 // reason we don't want to remove the block at this point is that if we call
8976 // fgInitBBLookup() again we will do it wrong as the BBJ_ALWAYS block won't be
8977 // added and the linked list length will be different than fgBBcount.
8980 /*****************************************************************************/
8981 // Get the first non-prefix opcode. Used for verification of valid combinations
8982 // of prefixes and actual opcodes.
8984 static OPCODE impGetNonPrefixOpcode(const BYTE* codeAddr, const BYTE* codeEndp)
8986 while (codeAddr < codeEndp)
8988 OPCODE opcode = (OPCODE)getU1LittleEndian(codeAddr);
8989 codeAddr += sizeof(__int8);
8991 if (opcode == CEE_PREFIX1)
8993 if (codeAddr >= codeEndp)
8997 opcode = (OPCODE)(getU1LittleEndian(codeAddr) + 256);
8998 codeAddr += sizeof(__int8);
9006 case CEE_CONSTRAINED:
9013 codeAddr += opcodeSizes[opcode];
9019 /*****************************************************************************/
9020 // Checks whether the opcode is a valid opcode for volatile. and unaligned. prefixes
9022 static void impValidateMemoryAccessOpcode(const BYTE* codeAddr, const BYTE* codeEndp, bool volatilePrefix)
9024 OPCODE opcode = impGetNonPrefixOpcode(codeAddr, codeEndp);
9027 // Opcode of all ldind and stdind happen to be in continuous, except stind.i.
9028 ((CEE_LDIND_I1 <= opcode) && (opcode <= CEE_STIND_R8)) || (opcode == CEE_STIND_I) ||
9029 (opcode == CEE_LDFLD) || (opcode == CEE_STFLD) || (opcode == CEE_LDOBJ) || (opcode == CEE_STOBJ) ||
9030 (opcode == CEE_INITBLK) || (opcode == CEE_CPBLK) ||
9031 // volatile. prefix is allowed with the ldsfld and stsfld
9032 (volatilePrefix && ((opcode == CEE_LDSFLD) || (opcode == CEE_STSFLD)))))
9034 BADCODE("Invalid opcode for unaligned. or volatile. prefix");
9038 /*****************************************************************************/
9042 #undef RETURN // undef contracts RETURN macro
9057 const static controlFlow_t controlFlow[] = {
9058 #define OPDEF(c, s, pop, push, args, type, l, s1, s2, flow) flow,
9059 #include "opcode.def"
9065 /*****************************************************************************
9066 * Determine the result type of an arithemetic operation
9067 * On 64-bit inserts upcasts when native int is mixed with int32
9069 var_types Compiler::impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTreePtr* pOp1, GenTreePtr* pOp2)
9071 var_types type = TYP_UNDEF;
9072 GenTreePtr op1 = *pOp1, op2 = *pOp2;
9074 // Arithemetic operations are generally only allowed with
9075 // primitive types, but certain operations are allowed
9078 if ((oper == GT_SUB) && (genActualType(op1->TypeGet()) == TYP_BYREF || genActualType(op2->TypeGet()) == TYP_BYREF))
9080 if ((genActualType(op1->TypeGet()) == TYP_BYREF) && (genActualType(op2->TypeGet()) == TYP_BYREF))
9082 // byref1-byref2 => gives a native int
9085 else if (genActualTypeIsIntOrI(op1->TypeGet()) && (genActualType(op2->TypeGet()) == TYP_BYREF))
9087 // [native] int - byref => gives a native int
9090 // The reason is that it is possible, in managed C++,
9091 // to have a tree like this:
9098 // const(h) int addr byref
9100 // <BUGNUM> VSW 318822 </BUGNUM>
9102 // So here we decide to make the resulting type to be a native int.
9103 CLANG_FORMAT_COMMENT_ANCHOR;
9105 #ifdef _TARGET_64BIT_
9106 if (genActualType(op1->TypeGet()) != TYP_I_IMPL)
9108 // insert an explicit upcast
9109 op1 = *pOp1 = gtNewCastNode(TYP_I_IMPL, op1, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9111 #endif // _TARGET_64BIT_
9117 // byref - [native] int => gives a byref
9118 assert(genActualType(op1->TypeGet()) == TYP_BYREF && genActualTypeIsIntOrI(op2->TypeGet()));
9120 #ifdef _TARGET_64BIT_
9121 if ((genActualType(op2->TypeGet()) != TYP_I_IMPL))
9123 // insert an explicit upcast
9124 op2 = *pOp2 = gtNewCastNode(TYP_I_IMPL, op2, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9126 #endif // _TARGET_64BIT_
9131 else if ((oper == GT_ADD) &&
9132 (genActualType(op1->TypeGet()) == TYP_BYREF || genActualType(op2->TypeGet()) == TYP_BYREF))
9134 // byref + [native] int => gives a byref
9136 // [native] int + byref => gives a byref
9138 // only one can be a byref : byref op byref not allowed
9139 assert(genActualType(op1->TypeGet()) != TYP_BYREF || genActualType(op2->TypeGet()) != TYP_BYREF);
9140 assert(genActualTypeIsIntOrI(op1->TypeGet()) || genActualTypeIsIntOrI(op2->TypeGet()));
9142 #ifdef _TARGET_64BIT_
9143 if (genActualType(op2->TypeGet()) == TYP_BYREF)
9145 if (genActualType(op1->TypeGet()) != TYP_I_IMPL)
9147 // insert an explicit upcast
9148 op1 = *pOp1 = gtNewCastNode(TYP_I_IMPL, op1, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9151 else if (genActualType(op2->TypeGet()) != TYP_I_IMPL)
9153 // insert an explicit upcast
9154 op2 = *pOp2 = gtNewCastNode(TYP_I_IMPL, op2, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9156 #endif // _TARGET_64BIT_
9160 #ifdef _TARGET_64BIT_
9161 else if (genActualType(op1->TypeGet()) == TYP_I_IMPL || genActualType(op2->TypeGet()) == TYP_I_IMPL)
9163 assert(!varTypeIsFloating(op1->gtType) && !varTypeIsFloating(op2->gtType));
9165 // int + long => gives long
9166 // long + int => gives long
9167 // we get this because in the IL the long isn't Int64, it's just IntPtr
9169 if (genActualType(op1->TypeGet()) != TYP_I_IMPL)
9171 // insert an explicit upcast
9172 op1 = *pOp1 = gtNewCastNode(TYP_I_IMPL, op1, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9174 else if (genActualType(op2->TypeGet()) != TYP_I_IMPL)
9176 // insert an explicit upcast
9177 op2 = *pOp2 = gtNewCastNode(TYP_I_IMPL, op2, (var_types)(fUnsigned ? TYP_U_IMPL : TYP_I_IMPL));
9182 #else // 32-bit TARGET
9183 else if (genActualType(op1->TypeGet()) == TYP_LONG || genActualType(op2->TypeGet()) == TYP_LONG)
9185 assert(!varTypeIsFloating(op1->gtType) && !varTypeIsFloating(op2->gtType));
9187 // int + long => gives long
9188 // long + int => gives long
9192 #endif // _TARGET_64BIT_
9195 // int + int => gives an int
9196 assert(genActualType(op1->TypeGet()) != TYP_BYREF && genActualType(op2->TypeGet()) != TYP_BYREF);
9198 assert(genActualType(op1->TypeGet()) == genActualType(op2->TypeGet()) ||
9199 varTypeIsFloating(op1->gtType) && varTypeIsFloating(op2->gtType));
9201 type = genActualType(op1->gtType);
9203 #if FEATURE_X87_DOUBLES
9205 // For x87, since we only have 1 size of registers, prefer double
9206 // For everybody else, be more precise
9207 if (type == TYP_FLOAT)
9210 #else // !FEATURE_X87_DOUBLES
9212 // If both operands are TYP_FLOAT, then leave it as TYP_FLOAT.
9213 // Otherwise, turn floats into doubles
9214 if ((type == TYP_FLOAT) && (genActualType(op2->gtType) != TYP_FLOAT))
9216 assert(genActualType(op2->gtType) == TYP_DOUBLE);
9220 #endif // FEATURE_X87_DOUBLES
9223 #if FEATURE_X87_DOUBLES
9224 assert(type == TYP_BYREF || type == TYP_DOUBLE || type == TYP_LONG || type == TYP_INT);
9225 #else // FEATURE_X87_DOUBLES
9226 assert(type == TYP_BYREF || type == TYP_DOUBLE || type == TYP_FLOAT || type == TYP_LONG || type == TYP_INT);
9227 #endif // FEATURE_X87_DOUBLES
9232 /*****************************************************************************
9233 * Casting Helper Function to service both CEE_CASTCLASS and CEE_ISINST
9235 * typeRef contains the token, op1 to contain the value being cast,
9236 * and op2 to contain code that creates the type handle corresponding to typeRef
9237 * isCastClass = true means CEE_CASTCLASS, false means CEE_ISINST
9239 GenTreePtr Compiler::impCastClassOrIsInstToTree(GenTreePtr op1,
9241 CORINFO_RESOLVED_TOKEN* pResolvedToken,
9246 assert(op1->TypeGet() == TYP_REF);
9248 CorInfoHelpFunc helper = info.compCompHnd->getCastingHelper(pResolvedToken, isCastClass);
9252 // We only want to expand inline the normal CHKCASTCLASS helper;
9253 expandInline = (helper == CORINFO_HELP_CHKCASTCLASS);
9257 if (helper == CORINFO_HELP_ISINSTANCEOFCLASS)
9259 // Get the Class Handle abd class attributes for the type we are casting to
9261 DWORD flags = info.compCompHnd->getClassAttribs(pResolvedToken->hClass);
9264 // If the class handle is marked as final we can also expand the IsInst check inline
9266 expandInline = ((flags & CORINFO_FLG_FINAL) != 0);
9269 // But don't expand inline these two cases
9271 if (flags & CORINFO_FLG_MARSHAL_BYREF)
9273 expandInline = false;
9275 else if (flags & CORINFO_FLG_CONTEXTFUL)
9277 expandInline = false;
9283 // We can't expand inline any other helpers
9285 expandInline = false;
9291 if (compCurBB->isRunRarely())
9293 expandInline = false; // not worth the code expansion in a rarely run block
9296 if ((op1->gtFlags & GTF_GLOB_EFFECT) && lvaHaveManyLocals())
9298 expandInline = false; // not worth creating an untracked local variable
9304 // If we CSE this class handle we prevent assertionProp from making SubType assertions
9305 // so instead we force the CSE logic to not consider CSE-ing this class handle.
9307 op2->gtFlags |= GTF_DONT_CSE;
9309 return gtNewHelperCallNode(helper, TYP_REF, 0, gtNewArgList(op2, op1));
9312 impSpillSideEffects(true, CHECK_SPILL_ALL DEBUGARG("bubbling QMark2"));
9317 // expand the methodtable match:
9321 // GT_IND op2 (typically CNS_INT)
9326 // This can replace op1 with a GT_COMMA that evaluates op1 into a local
9328 op1 = impCloneExpr(op1, &temp, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL, nullptr DEBUGARG("CASTCLASS eval op1"));
9330 // op1 is now known to be a non-complex tree
9331 // thus we can use gtClone(op1) from now on
9334 GenTreePtr op2Var = op2;
9337 op2Var = fgInsertCommaFormTemp(&op2);
9338 lvaTable[op2Var->AsLclVarCommon()->GetLclNum()].lvIsCSE = true;
9340 temp = gtNewOperNode(GT_IND, TYP_I_IMPL, temp);
9341 temp->gtFlags |= GTF_EXCEPT;
9342 condMT = gtNewOperNode(GT_NE, TYP_INT, temp, op2);
9344 GenTreePtr condNull;
9346 // expand the null check:
9348 // condNull ==> GT_EQ
9353 condNull = gtNewOperNode(GT_EQ, TYP_INT, gtClone(op1), gtNewIconNode(0, TYP_REF));
9356 // expand the true and false trees for the condMT
9358 GenTreePtr condFalse = gtClone(op1);
9359 GenTreePtr condTrue;
9363 // use the special helper that skips the cases checked by our inlined cast
9365 helper = CORINFO_HELP_CHKCASTCLASS_SPECIAL;
9367 condTrue = gtNewHelperCallNode(helper, TYP_REF, 0, gtNewArgList(op2Var, gtClone(op1)));
9371 condTrue = gtNewIconNode(0, TYP_REF);
9374 #define USE_QMARK_TREES
9376 #ifdef USE_QMARK_TREES
9379 // Generate first QMARK - COLON tree
9381 // qmarkMT ==> GT_QMARK
9385 // condFalse condTrue
9387 temp = new (this, GT_COLON) GenTreeColon(TYP_REF, condTrue, condFalse);
9388 qmarkMT = gtNewQmarkNode(TYP_REF, condMT, temp);
9389 condMT->gtFlags |= GTF_RELOP_QMARK;
9391 GenTreePtr qmarkNull;
9393 // Generate second QMARK - COLON tree
9395 // qmarkNull ==> GT_QMARK
9397 // condNull GT_COLON
9401 temp = new (this, GT_COLON) GenTreeColon(TYP_REF, gtClone(op1), qmarkMT);
9402 qmarkNull = gtNewQmarkNode(TYP_REF, condNull, temp);
9403 qmarkNull->gtFlags |= GTF_QMARK_CAST_INSTOF;
9404 condNull->gtFlags |= GTF_RELOP_QMARK;
9406 // Make QMark node a top level node by spilling it.
9407 unsigned tmp = lvaGrabTemp(true DEBUGARG("spilling QMark2"));
9408 impAssignTempGen(tmp, qmarkNull, (unsigned)CHECK_SPILL_NONE);
9409 return gtNewLclvNode(tmp, TYP_REF);
9414 #define assertImp(cond) ((void)0)
9416 #define assertImp(cond) \
9421 const int cchAssertImpBuf = 600; \
9422 char* assertImpBuf = (char*)alloca(cchAssertImpBuf); \
9423 _snprintf_s(assertImpBuf, cchAssertImpBuf, cchAssertImpBuf - 1, \
9424 "%s : Possibly bad IL with CEE_%s at offset %04Xh (op1=%s op2=%s stkDepth=%d)", #cond, \
9425 impCurOpcName, impCurOpcOffs, op1 ? varTypeName(op1->TypeGet()) : "NULL", \
9426 op2 ? varTypeName(op2->TypeGet()) : "NULL", verCurrentState.esStackDepth); \
9427 assertAbort(assertImpBuf, __FILE__, __LINE__); \
9433 #pragma warning(push)
9434 #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function
9436 /*****************************************************************************
9437 * Import the instr for the given basic block
9439 void Compiler::impImportBlockCode(BasicBlock* block)
9441 #define _impResolveToken(kind) impResolveToken(codeAddr, &resolvedToken, kind)
9447 printf("\nImporting BB%02u (PC=%03u) of '%s'", block->bbNum, block->bbCodeOffs, info.compFullName);
9451 unsigned nxtStmtIndex = impInitBlockLineInfo();
9452 IL_OFFSET nxtStmtOffs;
9454 GenTreePtr arrayNodeFrom, arrayNodeTo, arrayNodeToIndex;
9456 CorInfoHelpFunc helper;
9457 CorInfoIsAccessAllowedResult accessAllowedResult;
9458 CORINFO_HELPER_DESC calloutHelper;
9459 const BYTE* lastLoadToken = nullptr;
9461 // reject cyclic constraints
9462 if (tiVerificationNeeded)
9464 Verify(!info.hasCircularClassConstraints, "Method parent has circular class type parameter constraints.");
9465 Verify(!info.hasCircularMethodConstraints, "Method has circular method type parameter constraints.");
9468 /* Get the tree list started */
9472 /* Walk the opcodes that comprise the basic block */
9474 const BYTE* codeAddr = info.compCode + block->bbCodeOffs;
9475 const BYTE* codeEndp = info.compCode + block->bbCodeOffsEnd;
9477 IL_OFFSET opcodeOffs = block->bbCodeOffs;
9478 IL_OFFSET lastSpillOffs = opcodeOffs;
9482 /* remember the start of the delegate creation sequence (used for verification) */
9483 const BYTE* delegateCreateStart = nullptr;
9485 int prefixFlags = 0;
9486 bool explicitTailCall, constraintCall, readonlyCall;
9488 bool insertLdloc = false; // set by CEE_DUP and cleared by following store
9491 unsigned numArgs = info.compArgsCount;
9493 /* Now process all the opcodes in the block */
9495 var_types callTyp = TYP_COUNT;
9496 OPCODE prevOpcode = CEE_ILLEGAL;
9498 if (block->bbCatchTyp)
9500 if (info.compStmtOffsetsImplicit & ICorDebugInfo::CALL_SITE_BOUNDARIES)
9502 impCurStmtOffsSet(block->bbCodeOffs);
9505 // We will spill the GT_CATCH_ARG and the input of the BB_QMARK block
9506 // to a temp. This is a trade off for code simplicity
9507 impSpillSpecialSideEff();
9510 while (codeAddr < codeEndp)
9512 bool usingReadyToRunHelper = false;
9513 CORINFO_RESOLVED_TOKEN resolvedToken;
9514 CORINFO_RESOLVED_TOKEN constrainedResolvedToken;
9515 CORINFO_CALL_INFO callInfo;
9516 CORINFO_FIELD_INFO fieldInfo;
9518 tiRetVal = typeInfo(); // Default type info
9520 //---------------------------------------------------------------------
9522 /* We need to restrict the max tree depth as many of the Compiler
9523 functions are recursive. We do this by spilling the stack */
9525 if (verCurrentState.esStackDepth)
9527 /* Has it been a while since we last saw a non-empty stack (which
9528 guarantees that the tree depth isnt accumulating. */
9530 if ((opcodeOffs - lastSpillOffs) > 200)
9532 impSpillStackEnsure();
9533 lastSpillOffs = opcodeOffs;
9538 lastSpillOffs = opcodeOffs;
9539 impBoxTempInUse = false; // nothing on the stack, box temp OK to use again
9542 /* Compute the current instr offset */
9544 opcodeOffs = (IL_OFFSET)(codeAddr - info.compCode);
9547 if (opts.compDbgInfo)
9550 if (!compIsForInlining())
9553 (nxtStmtIndex < info.compStmtOffsetsCount) ? info.compStmtOffsets[nxtStmtIndex] : BAD_IL_OFFSET;
9555 /* Have we reached the next stmt boundary ? */
9557 if (nxtStmtOffs != BAD_IL_OFFSET && opcodeOffs >= nxtStmtOffs)
9559 assert(nxtStmtOffs == info.compStmtOffsets[nxtStmtIndex]);
9561 if (verCurrentState.esStackDepth != 0 && opts.compDbgCode)
9563 /* We need to provide accurate IP-mapping at this point.
9564 So spill anything on the stack so that it will form
9565 gtStmts with the correct stmt offset noted */
9567 impSpillStackEnsure(true);
9570 // Has impCurStmtOffs been reported in any tree?
9572 if (impCurStmtOffs != BAD_IL_OFFSET && opts.compDbgCode)
9574 GenTreePtr placeHolder = new (this, GT_NO_OP) GenTree(GT_NO_OP, TYP_VOID);
9575 impAppendTree(placeHolder, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
9577 assert(impCurStmtOffs == BAD_IL_OFFSET);
9580 if (impCurStmtOffs == BAD_IL_OFFSET)
9582 /* Make sure that nxtStmtIndex is in sync with opcodeOffs.
9583 If opcodeOffs has gone past nxtStmtIndex, catch up */
9585 while ((nxtStmtIndex + 1) < info.compStmtOffsetsCount &&
9586 info.compStmtOffsets[nxtStmtIndex + 1] <= opcodeOffs)
9591 /* Go to the new stmt */
9593 impCurStmtOffsSet(info.compStmtOffsets[nxtStmtIndex]);
9595 /* Update the stmt boundary index */
9598 assert(nxtStmtIndex <= info.compStmtOffsetsCount);
9600 /* Are there any more line# entries after this one? */
9602 if (nxtStmtIndex < info.compStmtOffsetsCount)
9604 /* Remember where the next line# starts */
9606 nxtStmtOffs = info.compStmtOffsets[nxtStmtIndex];
9610 /* No more line# entries */
9612 nxtStmtOffs = BAD_IL_OFFSET;
9616 else if ((info.compStmtOffsetsImplicit & ICorDebugInfo::STACK_EMPTY_BOUNDARIES) &&
9617 (verCurrentState.esStackDepth == 0))
9619 /* At stack-empty locations, we have already added the tree to
9620 the stmt list with the last offset. We just need to update
9624 impCurStmtOffsSet(opcodeOffs);
9626 else if ((info.compStmtOffsetsImplicit & ICorDebugInfo::CALL_SITE_BOUNDARIES) &&
9627 impOpcodeIsCallSiteBoundary(prevOpcode))
9629 /* Make sure we have a type cached */
9630 assert(callTyp != TYP_COUNT);
9632 if (callTyp == TYP_VOID)
9634 impCurStmtOffsSet(opcodeOffs);
9636 else if (opts.compDbgCode)
9638 impSpillStackEnsure(true);
9639 impCurStmtOffsSet(opcodeOffs);
9642 else if ((info.compStmtOffsetsImplicit & ICorDebugInfo::NOP_BOUNDARIES) && (prevOpcode == CEE_NOP))
9644 if (opts.compDbgCode)
9646 impSpillStackEnsure(true);
9649 impCurStmtOffsSet(opcodeOffs);
9652 assert(impCurStmtOffs == BAD_IL_OFFSET || nxtStmtOffs == BAD_IL_OFFSET ||
9653 jitGetILoffs(impCurStmtOffs) <= nxtStmtOffs);
9657 CORINFO_CLASS_HANDLE clsHnd = DUMMY_INIT(NULL);
9658 CORINFO_CLASS_HANDLE ldelemClsHnd = DUMMY_INIT(NULL);
9659 CORINFO_CLASS_HANDLE stelemClsHnd = DUMMY_INIT(NULL);
9661 var_types lclTyp, ovflType = TYP_UNKNOWN;
9662 GenTreePtr op1 = DUMMY_INIT(NULL);
9663 GenTreePtr op2 = DUMMY_INIT(NULL);
9664 GenTreeArgList* args = nullptr; // What good do these "DUMMY_INIT"s do?
9665 GenTreePtr newObjThisPtr = DUMMY_INIT(NULL);
9666 bool uns = DUMMY_INIT(false);
9668 /* Get the next opcode and the size of its parameters */
9670 OPCODE opcode = (OPCODE)getU1LittleEndian(codeAddr);
9671 codeAddr += sizeof(__int8);
9674 impCurOpcOffs = (IL_OFFSET)(codeAddr - info.compCode - 1);
9675 JITDUMP("\n [%2u] %3u (0x%03x) ", verCurrentState.esStackDepth, impCurOpcOffs, impCurOpcOffs);
9680 // Return if any previous code has caused inline to fail.
9681 if (compDonotInline())
9686 /* Get the size of additional parameters */
9688 signed int sz = opcodeSizes[opcode];
9691 clsHnd = NO_CLASS_HANDLE;
9693 callTyp = TYP_COUNT;
9695 impCurOpcOffs = (IL_OFFSET)(codeAddr - info.compCode - 1);
9696 impCurOpcName = opcodeNames[opcode];
9698 if (verbose && (opcode != CEE_PREFIX1))
9700 printf("%s", impCurOpcName);
9703 /* Use assertImp() to display the opcode */
9705 op1 = op2 = nullptr;
9708 /* See what kind of an opcode we have, then */
9710 unsigned mflags = 0;
9711 unsigned clsFlags = 0;
9724 CORINFO_SIG_INFO sig;
9727 bool ovfl, unordered, callNode;
9729 CORINFO_CLASS_HANDLE tokenType;
9739 opcode = (OPCODE)(getU1LittleEndian(codeAddr) + 256);
9740 codeAddr += sizeof(__int8);
9741 opcodeOffs = (IL_OFFSET)(codeAddr - info.compCode);
9746 // We need to call impSpillLclRefs() for a struct type lclVar.
9747 // This is done for non-block assignments in the handling of stloc.
9748 if ((op1->OperGet() == GT_ASG) && varTypeIsStruct(op1->gtOp.gtOp1) &&
9749 (op1->gtOp.gtOp1->gtOper == GT_LCL_VAR))
9751 impSpillLclRefs(op1->gtOp.gtOp1->AsLclVarCommon()->gtLclNum);
9754 /* Append 'op1' to the list of statements */
9755 impAppendTree(op1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
9760 /* Append 'op1' to the list of statements */
9762 impAppendTree(op1, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
9768 // Remember at which BC offset the tree was finished
9769 impNoteLastILoffs();
9774 impPushNullObjRefOnStack();
9787 cval.intVal = (opcode - CEE_LDC_I4_0);
9788 assert(-1 <= cval.intVal && cval.intVal <= 8);
9792 cval.intVal = getI1LittleEndian(codeAddr);
9795 cval.intVal = getI4LittleEndian(codeAddr);
9798 JITDUMP(" %d", cval.intVal);
9799 impPushOnStack(gtNewIconNode(cval.intVal), typeInfo(TI_INT));
9803 cval.lngVal = getI8LittleEndian(codeAddr);
9804 JITDUMP(" 0x%016llx", cval.lngVal);
9805 impPushOnStack(gtNewLconNode(cval.lngVal), typeInfo(TI_LONG));
9809 cval.dblVal = getR8LittleEndian(codeAddr);
9810 JITDUMP(" %#.17g", cval.dblVal);
9811 impPushOnStack(gtNewDconNode(cval.dblVal), typeInfo(TI_DOUBLE));
9815 cval.dblVal = getR4LittleEndian(codeAddr);
9816 JITDUMP(" %#.17g", cval.dblVal);
9818 GenTreePtr cnsOp = gtNewDconNode(cval.dblVal);
9819 #if !FEATURE_X87_DOUBLES
9820 // X87 stack doesn't differentiate between float/double
9821 // so R4 is treated as R8, but everybody else does
9822 cnsOp->gtType = TYP_FLOAT;
9823 #endif // FEATURE_X87_DOUBLES
9824 impPushOnStack(cnsOp, typeInfo(TI_DOUBLE));
9830 if (compIsForInlining())
9832 if (impInlineInfo->inlineCandidateInfo->dwRestrictions & INLINE_NO_CALLEE_LDSTR)
9834 compInlineResult->NoteFatal(InlineObservation::CALLSITE_HAS_LDSTR_RESTRICTION);
9839 val = getU4LittleEndian(codeAddr);
9840 JITDUMP(" %08X", val);
9841 if (tiVerificationNeeded)
9843 Verify(info.compCompHnd->isValidStringRef(info.compScopeHnd, val), "bad string");
9844 tiRetVal = typeInfo(TI_REF, impGetStringClass());
9846 impPushOnStack(gtNewSconNode(val, info.compScopeHnd), tiRetVal);
9851 lclNum = getU2LittleEndian(codeAddr);
9852 JITDUMP(" %u", lclNum);
9853 impLoadArg(lclNum, opcodeOffs + sz + 1);
9857 lclNum = getU1LittleEndian(codeAddr);
9858 JITDUMP(" %u", lclNum);
9859 impLoadArg(lclNum, opcodeOffs + sz + 1);
9866 lclNum = (opcode - CEE_LDARG_0);
9867 assert(lclNum >= 0 && lclNum < 4);
9868 impLoadArg(lclNum, opcodeOffs + sz + 1);
9872 lclNum = getU2LittleEndian(codeAddr);
9873 JITDUMP(" %u", lclNum);
9874 impLoadLoc(lclNum, opcodeOffs + sz + 1);
9878 lclNum = getU1LittleEndian(codeAddr);
9879 JITDUMP(" %u", lclNum);
9880 impLoadLoc(lclNum, opcodeOffs + sz + 1);
9887 lclNum = (opcode - CEE_LDLOC_0);
9888 assert(lclNum >= 0 && lclNum < 4);
9889 impLoadLoc(lclNum, opcodeOffs + sz + 1);
9893 lclNum = getU2LittleEndian(codeAddr);
9897 lclNum = getU1LittleEndian(codeAddr);
9899 JITDUMP(" %u", lclNum);
9901 if (tiVerificationNeeded)
9903 Verify(lclNum < info.compILargsCount, "bad arg num");
9906 if (compIsForInlining())
9908 op1 = impInlineFetchArg(lclNum, impInlineInfo->inlArgInfo, impInlineInfo->lclVarInfo);
9909 noway_assert(op1->gtOper == GT_LCL_VAR);
9910 lclNum = op1->AsLclVar()->gtLclNum;
9915 lclNum = compMapILargNum(lclNum); // account for possible hidden param
9916 assertImp(lclNum < numArgs);
9918 if (lclNum == info.compThisArg)
9920 lclNum = lvaArg0Var;
9922 lvaTable[lclNum].lvArgWrite = 1;
9924 if (tiVerificationNeeded)
9926 typeInfo& tiLclVar = lvaTable[lclNum].lvVerTypeInfo;
9927 Verify(tiCompatibleWith(impStackTop().seTypeInfo, NormaliseForStack(tiLclVar), true),
9930 if (verTrackObjCtorInitState && (verCurrentState.thisInitialized != TIS_Init))
9932 Verify(!tiLclVar.IsThisPtr(), "storing to uninit this ptr");
9939 lclNum = getU2LittleEndian(codeAddr);
9940 JITDUMP(" %u", lclNum);
9944 lclNum = getU1LittleEndian(codeAddr);
9945 JITDUMP(" %u", lclNum);
9952 lclNum = (opcode - CEE_STLOC_0);
9953 assert(lclNum >= 0 && lclNum < 4);
9956 if (tiVerificationNeeded)
9958 Verify(lclNum < info.compMethodInfo->locals.numArgs, "bad local num");
9959 Verify(tiCompatibleWith(impStackTop().seTypeInfo,
9960 NormaliseForStack(lvaTable[lclNum + numArgs].lvVerTypeInfo), true),
9964 if (compIsForInlining())
9966 lclTyp = impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclTypeInfo;
9968 /* Have we allocated a temp for this local? */
9970 lclNum = impInlineFetchLocal(lclNum DEBUGARG("Inline stloc first use temp"));
9979 if (lclNum >= info.compLocalsCount && lclNum != lvaArg0Var)
9981 assert(!tiVerificationNeeded); // We should have thrown the VerificationException before.
9987 /* if it is a struct assignment, make certain we don't overflow the buffer */
9988 assert(lclTyp != TYP_STRUCT || lvaLclSize(lclNum) >= info.compCompHnd->getClassSize(clsHnd));
9990 if (lvaTable[lclNum].lvNormalizeOnLoad())
9992 lclTyp = lvaGetRealType(lclNum);
9996 lclTyp = lvaGetActualType(lclNum);
10000 /* Pop the value being assigned */
10003 StackEntry se = impPopStack(clsHnd);
10005 tiRetVal = se.seTypeInfo;
10008 #ifdef FEATURE_SIMD
10009 if (varTypeIsSIMD(lclTyp) && (lclTyp != op1->TypeGet()))
10011 assert(op1->TypeGet() == TYP_STRUCT);
10012 op1->gtType = lclTyp;
10014 #endif // FEATURE_SIMD
10016 op1 = impImplicitIorI4Cast(op1, lclTyp);
10018 #ifdef _TARGET_64BIT_
10019 // Downcast the TYP_I_IMPL into a 32-bit Int for x86 JIT compatiblity
10020 if (varTypeIsI(op1->TypeGet()) && (genActualType(lclTyp) == TYP_INT))
10022 assert(!tiVerificationNeeded); // We should have thrown the VerificationException before.
10023 op1 = gtNewCastNode(TYP_INT, op1, TYP_INT);
10025 #endif // _TARGET_64BIT_
10027 // We had better assign it a value of the correct type
10029 genActualType(lclTyp) == genActualType(op1->gtType) ||
10030 genActualType(lclTyp) == TYP_I_IMPL && op1->IsVarAddr() ||
10031 (genActualType(lclTyp) == TYP_I_IMPL && (op1->gtType == TYP_BYREF || op1->gtType == TYP_REF)) ||
10032 (genActualType(op1->gtType) == TYP_I_IMPL && lclTyp == TYP_BYREF) ||
10033 (varTypeIsFloating(lclTyp) && varTypeIsFloating(op1->TypeGet())) ||
10034 ((genActualType(lclTyp) == TYP_BYREF) && genActualType(op1->TypeGet()) == TYP_REF));
10036 /* If op1 is "&var" then its type is the transient "*" and it can
10037 be used either as TYP_BYREF or TYP_I_IMPL */
10039 if (op1->IsVarAddr())
10041 assertImp(genActualType(lclTyp) == TYP_I_IMPL || lclTyp == TYP_BYREF);
10043 /* When "&var" is created, we assume it is a byref. If it is
10044 being assigned to a TYP_I_IMPL var, change the type to
10045 prevent unnecessary GC info */
10047 if (genActualType(lclTyp) == TYP_I_IMPL)
10049 op1->gtType = TYP_I_IMPL;
10053 /* Filter out simple assignments to itself */
10055 if (op1->gtOper == GT_LCL_VAR && lclNum == op1->gtLclVarCommon.gtLclNum)
10059 // This is a sequence of (ldloc, dup, stloc). Can simplify
10060 // to (ldloc, stloc). Goto LDVAR to reconstruct the ldloc node.
10061 CLANG_FORMAT_COMMENT_ANCHOR;
10064 if (tiVerificationNeeded)
10067 typeInfo::AreEquivalent(tiRetVal, NormaliseForStack(lvaTable[lclNum].lvVerTypeInfo)));
10072 insertLdloc = false;
10074 impLoadVar(lclNum, opcodeOffs + sz + 1);
10077 else if (opts.compDbgCode)
10079 op1 = gtNewNothingNode();
10088 /* Create the assignment node */
10090 op2 = gtNewLclvNode(lclNum, lclTyp, opcodeOffs + sz + 1);
10092 /* If the local is aliased, we need to spill calls and
10093 indirections from the stack. */
10095 if ((lvaTable[lclNum].lvAddrExposed || lvaTable[lclNum].lvHasLdAddrOp) &&
10096 verCurrentState.esStackDepth > 0)
10098 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG("Local could be aliased"));
10101 /* Spill any refs to the local from the stack */
10103 impSpillLclRefs(lclNum);
10105 #if !FEATURE_X87_DOUBLES
10106 // We can generate an assignment to a TYP_FLOAT from a TYP_DOUBLE
10107 // We insert a cast to the dest 'op2' type
10109 if ((op1->TypeGet() != op2->TypeGet()) && varTypeIsFloating(op1->gtType) &&
10110 varTypeIsFloating(op2->gtType))
10112 op1 = gtNewCastNode(op2->TypeGet(), op1, op2->TypeGet());
10114 #endif // !FEATURE_X87_DOUBLES
10116 if (varTypeIsStruct(lclTyp))
10118 op1 = impAssignStruct(op2, op1, clsHnd, (unsigned)CHECK_SPILL_ALL);
10122 // The code generator generates GC tracking information
10123 // based on the RHS of the assignment. Later the LHS (which is
10124 // is a BYREF) gets used and the emitter checks that that variable
10125 // is being tracked. It is not (since the RHS was an int and did
10126 // not need tracking). To keep this assert happy, we change the RHS
10127 if (lclTyp == TYP_BYREF && !varTypeIsGC(op1->gtType))
10129 op1->gtType = TYP_BYREF;
10131 op1 = gtNewAssignNode(op2, op1);
10134 /* If insertLdloc is true, then we need to insert a ldloc following the
10135 stloc. This is done when converting a (dup, stloc) sequence into
10136 a (stloc, ldloc) sequence. */
10140 // From SPILL_APPEND
10141 impAppendTree(op1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
10144 // From DONE_APPEND
10145 impNoteLastILoffs();
10148 insertLdloc = false;
10150 impLoadVar(lclNum, opcodeOffs + sz + 1, tiRetVal);
10157 lclNum = getU2LittleEndian(codeAddr);
10161 lclNum = getU1LittleEndian(codeAddr);
10163 JITDUMP(" %u", lclNum);
10164 if (tiVerificationNeeded)
10166 Verify(lclNum < info.compMethodInfo->locals.numArgs, "bad local num");
10167 Verify(info.compInitMem, "initLocals not set");
10170 if (compIsForInlining())
10172 // Get the local type
10173 lclTyp = impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclTypeInfo;
10175 /* Have we allocated a temp for this local? */
10177 lclNum = impInlineFetchLocal(lclNum DEBUGARG("Inline ldloca(s) first use temp"));
10179 op1 = gtNewLclvNode(lclNum, lvaGetActualType(lclNum));
10185 assertImp(lclNum < info.compLocalsCount);
10189 lclNum = getU2LittleEndian(codeAddr);
10193 lclNum = getU1LittleEndian(codeAddr);
10195 JITDUMP(" %u", lclNum);
10196 Verify(lclNum < info.compILargsCount, "bad arg num");
10198 if (compIsForInlining())
10200 // In IL, LDARGA(_S) is used to load the byref managed pointer of struct argument,
10201 // followed by a ldfld to load the field.
10203 op1 = impInlineFetchArg(lclNum, impInlineInfo->inlArgInfo, impInlineInfo->lclVarInfo);
10204 if (op1->gtOper != GT_LCL_VAR)
10206 compInlineResult->NoteFatal(InlineObservation::CALLSITE_LDARGA_NOT_LOCAL_VAR);
10210 assert(op1->gtOper == GT_LCL_VAR);
10215 lclNum = compMapILargNum(lclNum); // account for possible hidden param
10216 assertImp(lclNum < numArgs);
10218 if (lclNum == info.compThisArg)
10220 lclNum = lvaArg0Var;
10227 op1 = gtNewLclvNode(lclNum, lvaGetActualType(lclNum), opcodeOffs + sz + 1);
10230 assert(op1->gtOper == GT_LCL_VAR);
10232 /* Note that this is supposed to create the transient type "*"
10233 which may be used as a TYP_I_IMPL. However we catch places
10234 where it is used as a TYP_I_IMPL and change the node if needed.
10235 Thus we are pessimistic and may report byrefs in the GC info
10236 where it was not absolutely needed, but it is safer this way.
10238 op1 = gtNewOperNode(GT_ADDR, TYP_BYREF, op1);
10240 // &aliasedVar doesnt need GTF_GLOB_REF, though alisasedVar does
10241 assert((op1->gtFlags & GTF_GLOB_REF) == 0);
10243 tiRetVal = lvaTable[lclNum].lvVerTypeInfo;
10244 if (tiVerificationNeeded)
10246 // Don't allow taking address of uninit this ptr.
10247 if (verTrackObjCtorInitState && (verCurrentState.thisInitialized != TIS_Init))
10249 Verify(!tiRetVal.IsThisPtr(), "address of uninit this ptr");
10252 if (!tiRetVal.IsByRef())
10254 tiRetVal.MakeByRef();
10258 Verify(false, "byref to byref");
10262 impPushOnStack(op1, tiRetVal);
10267 if (!info.compIsVarArgs)
10269 BADCODE("arglist in non-vararg method");
10272 if (tiVerificationNeeded)
10274 tiRetVal = typeInfo(TI_STRUCT, impGetRuntimeArgumentHandle());
10276 assertImp((info.compMethodInfo->args.callConv & CORINFO_CALLCONV_MASK) == CORINFO_CALLCONV_VARARG);
10278 /* The ARGLIST cookie is a hidden 'last' parameter, we have already
10279 adjusted the arg count cos this is like fetching the last param */
10280 assertImp(0 < numArgs);
10281 assert(lvaTable[lvaVarargsHandleArg].lvAddrExposed);
10282 lclNum = lvaVarargsHandleArg;
10283 op1 = gtNewLclvNode(lclNum, TYP_I_IMPL, opcodeOffs + sz + 1);
10284 op1 = gtNewOperNode(GT_ADDR, TYP_BYREF, op1);
10285 impPushOnStack(op1, tiRetVal);
10288 case CEE_ENDFINALLY:
10290 if (compIsForInlining())
10292 assert(!"Shouldn't have exception handlers in the inliner!");
10293 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_ENDFINALLY);
10297 if (verCurrentState.esStackDepth > 0)
10299 impEvalSideEffects();
10302 if (info.compXcptnsCount == 0)
10304 BADCODE("endfinally outside finally");
10307 assert(verCurrentState.esStackDepth == 0);
10309 op1 = gtNewOperNode(GT_RETFILT, TYP_VOID, nullptr);
10312 case CEE_ENDFILTER:
10314 if (compIsForInlining())
10316 assert(!"Shouldn't have exception handlers in the inliner!");
10317 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_ENDFILTER);
10321 block->bbSetRunRarely(); // filters are rare
10323 if (info.compXcptnsCount == 0)
10325 BADCODE("endfilter outside filter");
10328 if (tiVerificationNeeded)
10330 Verify(impStackTop().seTypeInfo.IsType(TI_INT), "bad endfilt arg");
10333 op1 = impPopStack().val;
10334 assertImp(op1->gtType == TYP_INT);
10335 if (!bbInFilterILRange(block))
10337 BADCODE("EndFilter outside a filter handler");
10340 /* Mark current bb as end of filter */
10342 assert(compCurBB->bbFlags & BBF_DONT_REMOVE);
10343 assert(compCurBB->bbJumpKind == BBJ_EHFILTERRET);
10345 /* Mark catch handler as successor */
10347 op1 = gtNewOperNode(GT_RETFILT, op1->TypeGet(), op1);
10348 if (verCurrentState.esStackDepth != 0)
10350 verRaiseVerifyException(INDEBUG("stack must be 1 on end of filter") DEBUGARG(__FILE__)
10351 DEBUGARG(__LINE__));
10356 prefixFlags &= ~PREFIX_TAILCALL; // ret without call before it
10358 if (!impReturnInstruction(block, prefixFlags, opcode))
10369 assert(!compIsForInlining());
10371 if (tiVerificationNeeded)
10373 Verify(false, "Invalid opcode: CEE_JMP");
10376 if ((info.compFlags & CORINFO_FLG_SYNCH) || block->hasTryIndex() || block->hasHndIndex())
10378 /* CEE_JMP does not make sense in some "protected" regions. */
10380 BADCODE("Jmp not allowed in protected region");
10383 if (verCurrentState.esStackDepth != 0)
10385 BADCODE("Stack must be empty after CEE_JMPs");
10388 _impResolveToken(CORINFO_TOKENKIND_Method);
10390 JITDUMP(" %08X", resolvedToken.token);
10392 /* The signature of the target has to be identical to ours.
10393 At least check that argCnt and returnType match */
10395 eeGetMethodSig(resolvedToken.hMethod, &sig);
10396 if (sig.numArgs != info.compMethodInfo->args.numArgs ||
10397 sig.retType != info.compMethodInfo->args.retType ||
10398 sig.callConv != info.compMethodInfo->args.callConv)
10400 BADCODE("Incompatible target for CEE_JMPs");
10403 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARMARCH_)
10405 op1 = new (this, GT_JMP) GenTreeVal(GT_JMP, TYP_VOID, (size_t)resolvedToken.hMethod);
10407 /* Mark the basic block as being a JUMP instead of RETURN */
10409 block->bbFlags |= BBF_HAS_JMP;
10411 /* Set this flag to make sure register arguments have a location assigned
10412 * even if we don't use them inside the method */
10414 compJmpOpUsed = true;
10416 fgNoStructPromotion = true;
10420 #else // !_TARGET_XARCH_ && !_TARGET_ARMARCH_
10422 // Import this just like a series of LDARGs + tail. + call + ret
10424 if (info.compIsVarArgs)
10426 // For now we don't implement true tail calls, so this breaks varargs.
10427 // So warn the user instead of generating bad code.
10428 // This is a semi-temporary workaround for DevDiv 173860, until we can properly
10429 // implement true tail calls.
10430 IMPL_LIMITATION("varags + CEE_JMP doesn't work yet");
10433 // First load up the arguments (0 - N)
10434 for (unsigned argNum = 0; argNum < info.compILargsCount; argNum++)
10436 impLoadArg(argNum, opcodeOffs + sz + 1);
10439 // Now generate the tail call
10440 noway_assert(prefixFlags == 0);
10441 prefixFlags = PREFIX_TAILCALL_EXPLICIT;
10444 eeGetCallInfo(&resolvedToken, NULL,
10445 combine(CORINFO_CALLINFO_ALLOWINSTPARAM, CORINFO_CALLINFO_SECURITYCHECKS), &callInfo);
10447 // All calls and delegates need a security callout.
10448 impHandleAccessAllowed(callInfo.accessAllowed, &callInfo.callsiteCalloutHelper);
10450 callTyp = impImportCall(CEE_CALL, &resolvedToken, NULL, NULL, PREFIX_TAILCALL_EXPLICIT, &callInfo,
10453 // And finish with the ret
10456 #endif // _TARGET_XARCH_ || _TARGET_ARMARCH_
10459 assertImp(sz == sizeof(unsigned));
10461 _impResolveToken(CORINFO_TOKENKIND_Class);
10463 JITDUMP(" %08X", resolvedToken.token);
10465 ldelemClsHnd = resolvedToken.hClass;
10467 if (tiVerificationNeeded)
10469 typeInfo tiArray = impStackTop(1).seTypeInfo;
10470 typeInfo tiIndex = impStackTop().seTypeInfo;
10472 // As per ECMA 'index' specified can be either int32 or native int.
10473 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10475 typeInfo arrayElemType = verMakeTypeInfo(ldelemClsHnd);
10476 Verify(tiArray.IsNullObjRef() ||
10477 typeInfo::AreEquivalent(verGetArrayElemType(tiArray), arrayElemType),
10480 tiRetVal = arrayElemType;
10481 tiRetVal.MakeByRef();
10482 if (prefixFlags & PREFIX_READONLY)
10484 tiRetVal.SetIsReadonlyByRef();
10487 // an array interior pointer is always in the heap
10488 tiRetVal.SetIsPermanentHomeByRef();
10491 // If it's a value class array we just do a simple address-of
10492 if (eeIsValueClass(ldelemClsHnd))
10494 CorInfoType cit = info.compCompHnd->getTypeForPrimitiveValueClass(ldelemClsHnd);
10495 if (cit == CORINFO_TYPE_UNDEF)
10497 lclTyp = TYP_STRUCT;
10501 lclTyp = JITtype2varType(cit);
10503 goto ARR_LD_POST_VERIFY;
10506 // Similarly, if its a readonly access, we can do a simple address-of
10507 // without doing a runtime type-check
10508 if (prefixFlags & PREFIX_READONLY)
10511 goto ARR_LD_POST_VERIFY;
10514 // Otherwise we need the full helper function with run-time type check
10515 op1 = impTokenToHandle(&resolvedToken);
10516 if (op1 == nullptr)
10517 { // compDonotInline()
10521 args = gtNewArgList(op1); // Type
10522 args = gtNewListNode(impPopStack().val, args); // index
10523 args = gtNewListNode(impPopStack().val, args); // array
10524 op1 = gtNewHelperCallNode(CORINFO_HELP_LDELEMA_REF, TYP_BYREF, GTF_EXCEPT, args);
10526 impPushOnStack(op1, tiRetVal);
10529 // ldelem for reference and value types
10531 assertImp(sz == sizeof(unsigned));
10533 _impResolveToken(CORINFO_TOKENKIND_Class);
10535 JITDUMP(" %08X", resolvedToken.token);
10537 ldelemClsHnd = resolvedToken.hClass;
10539 if (tiVerificationNeeded)
10541 typeInfo tiArray = impStackTop(1).seTypeInfo;
10542 typeInfo tiIndex = impStackTop().seTypeInfo;
10544 // As per ECMA 'index' specified can be either int32 or native int.
10545 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10546 tiRetVal = verMakeTypeInfo(ldelemClsHnd);
10548 Verify(tiArray.IsNullObjRef() || tiCompatibleWith(verGetArrayElemType(tiArray), tiRetVal, false),
10549 "type of array incompatible with type operand");
10550 tiRetVal.NormaliseForStack();
10553 // If it's a reference type or generic variable type
10554 // then just generate code as though it's a ldelem.ref instruction
10555 if (!eeIsValueClass(ldelemClsHnd))
10558 opcode = CEE_LDELEM_REF;
10562 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(ldelemClsHnd);
10563 lclTyp = JITtype2varType(jitTyp);
10564 tiRetVal = verMakeTypeInfo(ldelemClsHnd); // precise type always needed for struct
10565 tiRetVal.NormaliseForStack();
10567 goto ARR_LD_POST_VERIFY;
10569 case CEE_LDELEM_I1:
10572 case CEE_LDELEM_I2:
10573 lclTyp = TYP_SHORT;
10576 lclTyp = TYP_I_IMPL;
10579 // Should be UINT, but since no platform widens 4->8 bytes it doesn't matter
10580 // and treating it as TYP_INT avoids other asserts.
10581 case CEE_LDELEM_U4:
10585 case CEE_LDELEM_I4:
10588 case CEE_LDELEM_I8:
10591 case CEE_LDELEM_REF:
10594 case CEE_LDELEM_R4:
10595 lclTyp = TYP_FLOAT;
10597 case CEE_LDELEM_R8:
10598 lclTyp = TYP_DOUBLE;
10600 case CEE_LDELEM_U1:
10601 lclTyp = TYP_UBYTE;
10603 case CEE_LDELEM_U2:
10609 if (tiVerificationNeeded)
10611 typeInfo tiArray = impStackTop(1).seTypeInfo;
10612 typeInfo tiIndex = impStackTop().seTypeInfo;
10614 // As per ECMA 'index' specified can be either int32 or native int.
10615 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10616 if (tiArray.IsNullObjRef())
10618 if (lclTyp == TYP_REF)
10619 { // we will say a deref of a null array yields a null ref
10620 tiRetVal = typeInfo(TI_NULL);
10624 tiRetVal = typeInfo(lclTyp);
10629 tiRetVal = verGetArrayElemType(tiArray);
10630 typeInfo arrayElemTi = typeInfo(lclTyp);
10631 #ifdef _TARGET_64BIT_
10632 if (opcode == CEE_LDELEM_I)
10634 arrayElemTi = typeInfo::nativeInt();
10637 if (lclTyp != TYP_REF && lclTyp != TYP_STRUCT)
10639 Verify(typeInfo::AreEquivalent(tiRetVal, arrayElemTi), "bad array");
10642 #endif // _TARGET_64BIT_
10644 Verify(tiRetVal.IsType(arrayElemTi.GetType()), "bad array");
10647 tiRetVal.NormaliseForStack();
10649 ARR_LD_POST_VERIFY:
10651 /* Pull the index value and array address */
10652 op2 = impPopStack().val;
10653 op1 = impPopStack().val;
10654 assertImp(op1->gtType == TYP_REF);
10656 /* Check for null pointer - in the inliner case we simply abort */
10658 if (compIsForInlining())
10660 if (op1->gtOper == GT_CNS_INT)
10662 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_NULL_FOR_LDELEM);
10667 op1 = impCheckForNullPointer(op1);
10669 /* Mark the block as containing an index expression */
10671 if (op1->gtOper == GT_LCL_VAR)
10673 if (op2->gtOper == GT_LCL_VAR || op2->gtOper == GT_CNS_INT || op2->gtOper == GT_ADD)
10675 block->bbFlags |= BBF_HAS_IDX_LEN;
10676 optMethodFlags |= OMF_HAS_ARRAYREF;
10680 /* Create the index node and push it on the stack */
10682 op1 = gtNewIndexRef(lclTyp, op1, op2);
10684 ldstruct = (opcode == CEE_LDELEM && lclTyp == TYP_STRUCT);
10686 if ((opcode == CEE_LDELEMA) || ldstruct ||
10687 (ldelemClsHnd != DUMMY_INIT(NULL) && eeIsValueClass(ldelemClsHnd)))
10689 assert(ldelemClsHnd != DUMMY_INIT(NULL));
10691 // remember the element size
10692 if (lclTyp == TYP_REF)
10694 op1->gtIndex.gtIndElemSize = sizeof(void*);
10698 // If ldElemClass is precisely a primitive type, use that, otherwise, preserve the struct type.
10699 if (info.compCompHnd->getTypeForPrimitiveValueClass(ldelemClsHnd) == CORINFO_TYPE_UNDEF)
10701 op1->gtIndex.gtStructElemClass = ldelemClsHnd;
10703 assert(lclTyp != TYP_STRUCT || op1->gtIndex.gtStructElemClass != nullptr);
10704 if (lclTyp == TYP_STRUCT)
10706 size = info.compCompHnd->getClassSize(ldelemClsHnd);
10707 op1->gtIndex.gtIndElemSize = size;
10708 op1->gtType = lclTyp;
10712 if ((opcode == CEE_LDELEMA) || ldstruct)
10715 lclTyp = TYP_BYREF;
10717 op1 = gtNewOperNode(GT_ADDR, lclTyp, op1);
10721 assert(lclTyp != TYP_STRUCT);
10727 // Create an OBJ for the result
10728 op1 = gtNewObjNode(ldelemClsHnd, op1);
10729 op1->gtFlags |= GTF_EXCEPT;
10731 impPushOnStack(op1, tiRetVal);
10734 // stelem for reference and value types
10737 assertImp(sz == sizeof(unsigned));
10739 _impResolveToken(CORINFO_TOKENKIND_Class);
10741 JITDUMP(" %08X", resolvedToken.token);
10743 stelemClsHnd = resolvedToken.hClass;
10745 if (tiVerificationNeeded)
10747 typeInfo tiArray = impStackTop(2).seTypeInfo;
10748 typeInfo tiIndex = impStackTop(1).seTypeInfo;
10749 typeInfo tiValue = impStackTop().seTypeInfo;
10751 // As per ECMA 'index' specified can be either int32 or native int.
10752 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10753 typeInfo arrayElem = verMakeTypeInfo(stelemClsHnd);
10755 Verify(tiArray.IsNullObjRef() || tiCompatibleWith(arrayElem, verGetArrayElemType(tiArray), false),
10756 "type operand incompatible with array element type");
10757 arrayElem.NormaliseForStack();
10758 Verify(tiCompatibleWith(tiValue, arrayElem, true), "value incompatible with type operand");
10761 // If it's a reference type just behave as though it's a stelem.ref instruction
10762 if (!eeIsValueClass(stelemClsHnd))
10764 goto STELEM_REF_POST_VERIFY;
10767 // Otherwise extract the type
10769 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(stelemClsHnd);
10770 lclTyp = JITtype2varType(jitTyp);
10771 goto ARR_ST_POST_VERIFY;
10774 case CEE_STELEM_REF:
10776 if (tiVerificationNeeded)
10778 typeInfo tiArray = impStackTop(2).seTypeInfo;
10779 typeInfo tiIndex = impStackTop(1).seTypeInfo;
10780 typeInfo tiValue = impStackTop().seTypeInfo;
10782 // As per ECMA 'index' specified can be either int32 or native int.
10783 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10784 Verify(tiValue.IsObjRef(), "bad value");
10786 // we only check that it is an object referece, The helper does additional checks
10787 Verify(tiArray.IsNullObjRef() || verGetArrayElemType(tiArray).IsType(TI_REF), "bad array");
10790 arrayNodeTo = impStackTop(2).val;
10791 arrayNodeToIndex = impStackTop(1).val;
10792 arrayNodeFrom = impStackTop().val;
10795 // Note that it is not legal to optimize away CORINFO_HELP_ARRADDR_ST in a
10796 // lot of cases because of covariance. ie. foo[] can be cast to object[].
10799 // Check for assignment to same array, ie. arrLcl[i] = arrLcl[j]
10800 // This does not need CORINFO_HELP_ARRADDR_ST
10802 if (arrayNodeFrom->OperGet() == GT_INDEX && arrayNodeFrom->gtOp.gtOp1->gtOper == GT_LCL_VAR &&
10803 arrayNodeTo->gtOper == GT_LCL_VAR &&
10804 arrayNodeTo->gtLclVarCommon.gtLclNum == arrayNodeFrom->gtOp.gtOp1->gtLclVarCommon.gtLclNum &&
10805 !lvaTable[arrayNodeTo->gtLclVarCommon.gtLclNum].lvAddrExposed)
10808 goto ARR_ST_POST_VERIFY;
10811 // Check for assignment of NULL. This does not need CORINFO_HELP_ARRADDR_ST
10813 if (arrayNodeFrom->OperGet() == GT_CNS_INT)
10815 assert(arrayNodeFrom->gtType == TYP_REF && arrayNodeFrom->gtIntCon.gtIconVal == 0);
10818 goto ARR_ST_POST_VERIFY;
10821 STELEM_REF_POST_VERIFY:
10823 /* Call a helper function to do the assignment */
10824 op1 = gtNewHelperCallNode(CORINFO_HELP_ARRADDR_ST, TYP_VOID, 0, impPopList(3, &flags, nullptr));
10828 case CEE_STELEM_I1:
10831 case CEE_STELEM_I2:
10832 lclTyp = TYP_SHORT;
10835 lclTyp = TYP_I_IMPL;
10837 case CEE_STELEM_I4:
10840 case CEE_STELEM_I8:
10843 case CEE_STELEM_R4:
10844 lclTyp = TYP_FLOAT;
10846 case CEE_STELEM_R8:
10847 lclTyp = TYP_DOUBLE;
10852 if (tiVerificationNeeded)
10854 typeInfo tiArray = impStackTop(2).seTypeInfo;
10855 typeInfo tiIndex = impStackTop(1).seTypeInfo;
10856 typeInfo tiValue = impStackTop().seTypeInfo;
10858 // As per ECMA 'index' specified can be either int32 or native int.
10859 Verify(tiIndex.IsIntOrNativeIntType(), "bad index");
10860 typeInfo arrayElem = typeInfo(lclTyp);
10861 #ifdef _TARGET_64BIT_
10862 if (opcode == CEE_STELEM_I)
10864 arrayElem = typeInfo::nativeInt();
10866 #endif // _TARGET_64BIT_
10867 Verify(tiArray.IsNullObjRef() || typeInfo::AreEquivalent(verGetArrayElemType(tiArray), arrayElem),
10870 Verify(tiCompatibleWith(NormaliseForStack(tiValue), arrayElem.NormaliseForStack(), true),
10874 ARR_ST_POST_VERIFY:
10875 /* The strict order of evaluation is LHS-operands, RHS-operands,
10876 range-check, and then assignment. However, codegen currently
10877 does the range-check before evaluation the RHS-operands. So to
10878 maintain strict ordering, we spill the stack. */
10880 if (impStackTop().val->gtFlags & GTF_SIDE_EFFECT)
10882 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG(
10883 "Strict ordering of exceptions for Array store"));
10886 /* Pull the new value from the stack */
10887 op2 = impPopStack().val;
10889 /* Pull the index value */
10890 op1 = impPopStack().val;
10892 /* Pull the array address */
10893 op3 = impPopStack().val;
10895 assertImp(op3->gtType == TYP_REF);
10896 if (op2->IsVarAddr())
10898 op2->gtType = TYP_I_IMPL;
10901 op3 = impCheckForNullPointer(op3);
10903 // Mark the block as containing an index expression
10905 if (op3->gtOper == GT_LCL_VAR)
10907 if (op1->gtOper == GT_LCL_VAR || op1->gtOper == GT_CNS_INT || op1->gtOper == GT_ADD)
10909 block->bbFlags |= BBF_HAS_IDX_LEN;
10910 optMethodFlags |= OMF_HAS_ARRAYREF;
10914 /* Create the index node */
10916 op1 = gtNewIndexRef(lclTyp, op3, op1);
10918 /* Create the assignment node and append it */
10920 if (lclTyp == TYP_STRUCT)
10922 assert(stelemClsHnd != DUMMY_INIT(NULL));
10924 op1->gtIndex.gtStructElemClass = stelemClsHnd;
10925 op1->gtIndex.gtIndElemSize = info.compCompHnd->getClassSize(stelemClsHnd);
10927 if (varTypeIsStruct(op1))
10929 op1 = impAssignStruct(op1, op2, stelemClsHnd, (unsigned)CHECK_SPILL_ALL);
10933 op2 = impImplicitR4orR8Cast(op2, op1->TypeGet());
10934 op1 = gtNewAssignNode(op1, op2);
10937 /* Mark the expression as containing an assignment */
10939 op1->gtFlags |= GTF_ASG;
10950 case CEE_ADD_OVF_UN:
10958 goto MATH_OP2_FLAGS;
10967 case CEE_SUB_OVF_UN:
10975 goto MATH_OP2_FLAGS;
10979 goto MATH_MAYBE_CALL_NO_OVF;
10984 case CEE_MUL_OVF_UN:
10991 goto MATH_MAYBE_CALL_OVF;
10993 // Other binary math operations
10997 goto MATH_MAYBE_CALL_NO_OVF;
11001 goto MATH_MAYBE_CALL_NO_OVF;
11005 goto MATH_MAYBE_CALL_NO_OVF;
11009 goto MATH_MAYBE_CALL_NO_OVF;
11011 MATH_MAYBE_CALL_NO_OVF:
11013 MATH_MAYBE_CALL_OVF:
11014 // Morpher has some complex logic about when to turn different
11015 // typed nodes on different platforms into helper calls. We
11016 // need to either duplicate that logic here, or just
11017 // pessimistically make all the nodes large enough to become
11018 // call nodes. Since call nodes aren't that much larger and
11019 // these opcodes are infrequent enough I chose the latter.
11021 goto MATH_OP2_FLAGS;
11033 MATH_OP2: // For default values of 'ovfl' and 'callNode'
11038 MATH_OP2_FLAGS: // If 'ovfl' and 'callNode' have already been set
11040 /* Pull two values and push back the result */
11042 if (tiVerificationNeeded)
11044 const typeInfo& tiOp1 = impStackTop(1).seTypeInfo;
11045 const typeInfo& tiOp2 = impStackTop().seTypeInfo;
11047 Verify(tiCompatibleWith(tiOp1, tiOp2, true), "different arg type");
11048 if (oper == GT_ADD || oper == GT_DIV || oper == GT_SUB || oper == GT_MUL || oper == GT_MOD)
11050 Verify(tiOp1.IsNumberType(), "not number");
11054 Verify(tiOp1.IsIntegerType(), "not integer");
11057 Verify(!ovfl || tiOp1.IsIntegerType(), "not integer");
11061 #ifdef _TARGET_64BIT_
11062 if (tiOp2.IsNativeIntType())
11066 #endif // _TARGET_64BIT_
11069 op2 = impPopStack().val;
11070 op1 = impPopStack().val;
11072 #if !CPU_HAS_FP_SUPPORT
11073 if (varTypeIsFloating(op1->gtType))
11078 /* Can't do arithmetic with references */
11079 assertImp(genActualType(op1->TypeGet()) != TYP_REF && genActualType(op2->TypeGet()) != TYP_REF);
11081 // Change both to TYP_I_IMPL (impBashVarAddrsToI won't change if its a true byref, only
11082 // if it is in the stack)
11083 impBashVarAddrsToI(op1, op2);
11085 type = impGetByRefResultType(oper, uns, &op1, &op2);
11087 assert(!ovfl || !varTypeIsFloating(op1->gtType));
11089 /* Special case: "int+0", "int-0", "int*1", "int/1" */
11091 if (op2->gtOper == GT_CNS_INT)
11093 if ((op2->IsIntegralConst(0) && (oper == GT_ADD || oper == GT_SUB)) ||
11094 (op2->IsIntegralConst(1) && (oper == GT_MUL || oper == GT_DIV)))
11097 impPushOnStack(op1, tiRetVal);
11102 #if !FEATURE_X87_DOUBLES
11103 // We can generate a TYP_FLOAT operation that has a TYP_DOUBLE operand
11105 if (varTypeIsFloating(type) && varTypeIsFloating(op1->gtType) && varTypeIsFloating(op2->gtType))
11107 if (op1->TypeGet() != type)
11109 // We insert a cast of op1 to 'type'
11110 op1 = gtNewCastNode(type, op1, type);
11112 if (op2->TypeGet() != type)
11114 // We insert a cast of op2 to 'type'
11115 op2 = gtNewCastNode(type, op2, type);
11118 #endif // !FEATURE_X87_DOUBLES
11120 #if SMALL_TREE_NODES
11123 /* These operators can later be transformed into 'GT_CALL' */
11125 assert(GenTree::s_gtNodeSizes[GT_CALL] > GenTree::s_gtNodeSizes[GT_MUL]);
11126 #ifndef _TARGET_ARM_
11127 assert(GenTree::s_gtNodeSizes[GT_CALL] > GenTree::s_gtNodeSizes[GT_DIV]);
11128 assert(GenTree::s_gtNodeSizes[GT_CALL] > GenTree::s_gtNodeSizes[GT_UDIV]);
11129 assert(GenTree::s_gtNodeSizes[GT_CALL] > GenTree::s_gtNodeSizes[GT_MOD]);
11130 assert(GenTree::s_gtNodeSizes[GT_CALL] > GenTree::s_gtNodeSizes[GT_UMOD]);
11132 // It's tempting to use LargeOpOpcode() here, but this logic is *not* saying
11133 // that we'll need to transform into a general large node, but rather specifically
11134 // to a call: by doing it this way, things keep working if there are multiple sizes,
11135 // and a CALL is no longer the largest.
11136 // That said, as of now it *is* a large node, so we'll do this with an assert rather
11138 assert(GenTree::s_gtNodeSizes[GT_CALL] == TREE_NODE_SZ_LARGE);
11139 op1 = new (this, GT_CALL) GenTreeOp(oper, type, op1, op2 DEBUGARG(/*largeNode*/ true));
11142 #endif // SMALL_TREE_NODES
11144 op1 = gtNewOperNode(oper, type, op1, op2);
11147 /* Special case: integer/long division may throw an exception */
11149 if (varTypeIsIntegral(op1->TypeGet()) && op1->OperMayThrow())
11151 op1->gtFlags |= GTF_EXCEPT;
11156 assert(oper == GT_ADD || oper == GT_SUB || oper == GT_MUL);
11157 if (ovflType != TYP_UNKNOWN)
11159 op1->gtType = ovflType;
11161 op1->gtFlags |= (GTF_EXCEPT | GTF_OVERFLOW);
11164 op1->gtFlags |= GTF_UNSIGNED;
11168 impPushOnStack(op1, tiRetVal);
11183 if (tiVerificationNeeded)
11185 const typeInfo& tiVal = impStackTop(1).seTypeInfo;
11186 const typeInfo& tiShift = impStackTop(0).seTypeInfo;
11187 Verify(tiVal.IsIntegerType() && tiShift.IsType(TI_INT), "Bad shift args");
11190 op2 = impPopStack().val;
11191 op1 = impPopStack().val; // operand to be shifted
11192 impBashVarAddrsToI(op1, op2);
11194 type = genActualType(op1->TypeGet());
11195 op1 = gtNewOperNode(oper, type, op1, op2);
11197 impPushOnStack(op1, tiRetVal);
11201 if (tiVerificationNeeded)
11203 tiRetVal = impStackTop().seTypeInfo;
11204 Verify(tiRetVal.IsIntegerType(), "bad int value");
11207 op1 = impPopStack().val;
11208 impBashVarAddrsToI(op1, nullptr);
11209 type = genActualType(op1->TypeGet());
11210 impPushOnStack(gtNewOperNode(GT_NOT, type, op1), tiRetVal);
11214 if (tiVerificationNeeded)
11216 tiRetVal = impStackTop().seTypeInfo;
11217 Verify(tiRetVal.IsType(TI_DOUBLE), "bad R value");
11219 op1 = impPopStack().val;
11220 type = op1->TypeGet();
11221 op1 = gtNewOperNode(GT_CKFINITE, type, op1);
11222 op1->gtFlags |= GTF_EXCEPT;
11224 impPushOnStack(op1, tiRetVal);
11229 val = getI4LittleEndian(codeAddr); // jump distance
11230 jmpAddr = (IL_OFFSET)((codeAddr - info.compCode + sizeof(__int32)) + val);
11234 val = getI1LittleEndian(codeAddr); // jump distance
11235 jmpAddr = (IL_OFFSET)((codeAddr - info.compCode + sizeof(__int8)) + val);
11239 if (compIsForInlining())
11241 compInlineResult->NoteFatal(InlineObservation::CALLEE_HAS_LEAVE);
11245 JITDUMP(" %04X", jmpAddr);
11246 if (block->bbJumpKind != BBJ_LEAVE)
11248 impResetLeaveBlock(block, jmpAddr);
11251 assert(jmpAddr == block->bbJumpDest->bbCodeOffs);
11252 impImportLeave(block);
11253 impNoteBranchOffs();
11259 jmpDist = (sz == 1) ? getI1LittleEndian(codeAddr) : getI4LittleEndian(codeAddr);
11261 if (compIsForInlining() && jmpDist == 0)
11266 impNoteBranchOffs();
11272 case CEE_BRFALSE_S:
11274 /* Pop the comparand (now there's a neat term) from the stack */
11275 if (tiVerificationNeeded)
11277 typeInfo& tiVal = impStackTop().seTypeInfo;
11278 Verify(tiVal.IsObjRef() || tiVal.IsByRef() || tiVal.IsIntegerType() || tiVal.IsMethod(),
11282 op1 = impPopStack().val;
11283 type = op1->TypeGet();
11285 // brfalse and brtrue is only allowed on I4, refs, and byrefs.
11286 if (!opts.MinOpts() && !opts.compDbgCode && block->bbJumpDest == block->bbNext)
11288 block->bbJumpKind = BBJ_NONE;
11290 if (op1->gtFlags & GTF_GLOB_EFFECT)
11292 op1 = gtUnusedValNode(op1);
11301 if (op1->OperIsCompare())
11303 if (opcode == CEE_BRFALSE || opcode == CEE_BRFALSE_S)
11305 // Flip the sense of the compare
11307 op1 = gtReverseCond(op1);
11312 /* We'll compare against an equally-sized integer 0 */
11313 /* For small types, we always compare against int */
11314 op2 = gtNewZeroConNode(genActualType(op1->gtType));
11316 /* Create the comparison operator and try to fold it */
11318 oper = (opcode == CEE_BRTRUE || opcode == CEE_BRTRUE_S) ? GT_NE : GT_EQ;
11319 op1 = gtNewOperNode(oper, TYP_INT, op1, op2);
11326 /* Fold comparison if we can */
11328 op1 = gtFoldExpr(op1);
11330 /* Try to fold the really simple cases like 'iconst *, ifne/ifeq'*/
11331 /* Don't make any blocks unreachable in import only mode */
11333 if ((op1->gtOper == GT_CNS_INT) && !compIsForImportOnly())
11335 /* gtFoldExpr() should prevent this as we don't want to make any blocks
11336 unreachable under compDbgCode */
11337 assert(!opts.compDbgCode);
11339 BBjumpKinds foldedJumpKind = (BBjumpKinds)(op1->gtIntCon.gtIconVal ? BBJ_ALWAYS : BBJ_NONE);
11340 assertImp((block->bbJumpKind == BBJ_COND) // normal case
11341 || (block->bbJumpKind == foldedJumpKind)); // this can happen if we are reimporting the
11342 // block for the second time
11344 block->bbJumpKind = foldedJumpKind;
11348 if (op1->gtIntCon.gtIconVal)
11350 printf("\nThe conditional jump becomes an unconditional jump to BB%02u\n",
11351 block->bbJumpDest->bbNum);
11355 printf("\nThe block falls through into the next BB%02u\n", block->bbNext->bbNum);
11362 op1 = gtNewOperNode(GT_JTRUE, TYP_VOID, op1);
11364 /* GT_JTRUE is handled specially for non-empty stacks. See 'addStmt'
11365 in impImportBlock(block). For correct line numbers, spill stack. */
11367 if (opts.compDbgCode && impCurStmtOffs != BAD_IL_OFFSET)
11369 impSpillStackEnsure(true);
11396 if (tiVerificationNeeded)
11398 verVerifyCond(impStackTop(1).seTypeInfo, impStackTop().seTypeInfo, opcode);
11399 tiRetVal = typeInfo(TI_INT);
11402 op2 = impPopStack().val;
11403 op1 = impPopStack().val;
11405 #ifdef _TARGET_64BIT_
11406 if (varTypeIsI(op1->TypeGet()) && (genActualType(op2->TypeGet()) == TYP_INT))
11408 op2 = gtNewCastNode(TYP_I_IMPL, op2, (var_types)(uns ? TYP_U_IMPL : TYP_I_IMPL));
11410 else if (varTypeIsI(op2->TypeGet()) && (genActualType(op1->TypeGet()) == TYP_INT))
11412 op1 = gtNewCastNode(TYP_I_IMPL, op1, (var_types)(uns ? TYP_U_IMPL : TYP_I_IMPL));
11414 #endif // _TARGET_64BIT_
11416 assertImp(genActualType(op1->TypeGet()) == genActualType(op2->TypeGet()) ||
11417 varTypeIsI(op1->TypeGet()) && varTypeIsI(op2->TypeGet()) ||
11418 varTypeIsFloating(op1->gtType) && varTypeIsFloating(op2->gtType));
11420 /* Create the comparison node */
11422 op1 = gtNewOperNode(oper, TYP_INT, op1, op2);
11424 /* TODO: setting both flags when only one is appropriate */
11425 if (opcode == CEE_CGT_UN || opcode == CEE_CLT_UN)
11427 op1->gtFlags |= GTF_RELOP_NAN_UN | GTF_UNSIGNED;
11430 impPushOnStack(op1, tiRetVal);
11436 goto CMP_2_OPs_AND_BR;
11441 goto CMP_2_OPs_AND_BR;
11446 goto CMP_2_OPs_AND_BR_UN;
11451 goto CMP_2_OPs_AND_BR;
11456 goto CMP_2_OPs_AND_BR_UN;
11461 goto CMP_2_OPs_AND_BR;
11466 goto CMP_2_OPs_AND_BR_UN;
11471 goto CMP_2_OPs_AND_BR;
11476 goto CMP_2_OPs_AND_BR_UN;
11481 goto CMP_2_OPs_AND_BR_UN;
11483 CMP_2_OPs_AND_BR_UN:
11486 goto CMP_2_OPs_AND_BR_ALL;
11490 goto CMP_2_OPs_AND_BR_ALL;
11491 CMP_2_OPs_AND_BR_ALL:
11493 if (tiVerificationNeeded)
11495 verVerifyCond(impStackTop(1).seTypeInfo, impStackTop().seTypeInfo, opcode);
11498 /* Pull two values */
11499 op2 = impPopStack().val;
11500 op1 = impPopStack().val;
11502 #ifdef _TARGET_64BIT_
11503 if ((op1->TypeGet() == TYP_I_IMPL) && (genActualType(op2->TypeGet()) == TYP_INT))
11505 op2 = gtNewCastNode(TYP_I_IMPL, op2, (var_types)(uns ? TYP_U_IMPL : TYP_I_IMPL));
11507 else if ((op2->TypeGet() == TYP_I_IMPL) && (genActualType(op1->TypeGet()) == TYP_INT))
11509 op1 = gtNewCastNode(TYP_I_IMPL, op1, (var_types)(uns ? TYP_U_IMPL : TYP_I_IMPL));
11511 #endif // _TARGET_64BIT_
11513 assertImp(genActualType(op1->TypeGet()) == genActualType(op2->TypeGet()) ||
11514 varTypeIsI(op1->TypeGet()) && varTypeIsI(op2->TypeGet()) ||
11515 varTypeIsFloating(op1->gtType) && varTypeIsFloating(op2->gtType));
11517 if (!opts.MinOpts() && !opts.compDbgCode && block->bbJumpDest == block->bbNext)
11519 block->bbJumpKind = BBJ_NONE;
11521 if (op1->gtFlags & GTF_GLOB_EFFECT)
11523 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG(
11524 "Branch to next Optimization, op1 side effect"));
11525 impAppendTree(gtUnusedValNode(op1), (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
11527 if (op2->gtFlags & GTF_GLOB_EFFECT)
11529 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG(
11530 "Branch to next Optimization, op2 side effect"));
11531 impAppendTree(gtUnusedValNode(op2), (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
11535 if ((op1->gtFlags | op2->gtFlags) & GTF_GLOB_EFFECT)
11537 impNoteLastILoffs();
11542 #if !FEATURE_X87_DOUBLES
11543 // We can generate an compare of different sized floating point op1 and op2
11544 // We insert a cast
11546 if (varTypeIsFloating(op1->TypeGet()))
11548 if (op1->TypeGet() != op2->TypeGet())
11550 assert(varTypeIsFloating(op2->TypeGet()));
11552 // say op1=double, op2=float. To avoid loss of precision
11553 // while comparing, op2 is converted to double and double
11554 // comparison is done.
11555 if (op1->TypeGet() == TYP_DOUBLE)
11557 // We insert a cast of op2 to TYP_DOUBLE
11558 op2 = gtNewCastNode(TYP_DOUBLE, op2, TYP_DOUBLE);
11560 else if (op2->TypeGet() == TYP_DOUBLE)
11562 // We insert a cast of op1 to TYP_DOUBLE
11563 op1 = gtNewCastNode(TYP_DOUBLE, op1, TYP_DOUBLE);
11567 #endif // !FEATURE_X87_DOUBLES
11569 /* Create and append the operator */
11571 op1 = gtNewOperNode(oper, TYP_INT, op1, op2);
11575 op1->gtFlags |= GTF_UNSIGNED;
11580 op1->gtFlags |= GTF_RELOP_NAN_UN;
11586 assert(!compIsForInlining());
11588 if (tiVerificationNeeded)
11590 Verify(impStackTop().seTypeInfo.IsType(TI_INT), "Bad switch val");
11592 /* Pop the switch value off the stack */
11593 op1 = impPopStack().val;
11594 assertImp(genActualTypeIsIntOrI(op1->TypeGet()));
11596 #ifdef _TARGET_64BIT_
11597 // Widen 'op1' on 64-bit targets
11598 if (op1->TypeGet() != TYP_I_IMPL)
11600 if (op1->OperGet() == GT_CNS_INT)
11602 op1->gtType = TYP_I_IMPL;
11606 op1 = gtNewCastNode(TYP_I_IMPL, op1, TYP_I_IMPL);
11609 #endif // _TARGET_64BIT_
11610 assert(genActualType(op1->TypeGet()) == TYP_I_IMPL);
11612 /* We can create a switch node */
11614 op1 = gtNewOperNode(GT_SWITCH, TYP_VOID, op1);
11616 val = (int)getU4LittleEndian(codeAddr);
11617 codeAddr += 4 + val * 4; // skip over the switch-table
11621 /************************** Casting OPCODES ***************************/
11623 case CEE_CONV_OVF_I1:
11626 case CEE_CONV_OVF_I2:
11627 lclTyp = TYP_SHORT;
11629 case CEE_CONV_OVF_I:
11630 lclTyp = TYP_I_IMPL;
11632 case CEE_CONV_OVF_I4:
11635 case CEE_CONV_OVF_I8:
11639 case CEE_CONV_OVF_U1:
11640 lclTyp = TYP_UBYTE;
11642 case CEE_CONV_OVF_U2:
11645 case CEE_CONV_OVF_U:
11646 lclTyp = TYP_U_IMPL;
11648 case CEE_CONV_OVF_U4:
11651 case CEE_CONV_OVF_U8:
11652 lclTyp = TYP_ULONG;
11655 case CEE_CONV_OVF_I1_UN:
11658 case CEE_CONV_OVF_I2_UN:
11659 lclTyp = TYP_SHORT;
11661 case CEE_CONV_OVF_I_UN:
11662 lclTyp = TYP_I_IMPL;
11664 case CEE_CONV_OVF_I4_UN:
11667 case CEE_CONV_OVF_I8_UN:
11671 case CEE_CONV_OVF_U1_UN:
11672 lclTyp = TYP_UBYTE;
11674 case CEE_CONV_OVF_U2_UN:
11677 case CEE_CONV_OVF_U_UN:
11678 lclTyp = TYP_U_IMPL;
11680 case CEE_CONV_OVF_U4_UN:
11683 case CEE_CONV_OVF_U8_UN:
11684 lclTyp = TYP_ULONG;
11689 goto CONV_OVF_COMMON;
11692 goto CONV_OVF_COMMON;
11702 lclTyp = TYP_SHORT;
11705 lclTyp = TYP_I_IMPL;
11715 lclTyp = TYP_UBYTE;
11720 #if (REGSIZE_BYTES == 8)
11722 lclTyp = TYP_U_IMPL;
11726 lclTyp = TYP_U_IMPL;
11733 lclTyp = TYP_ULONG;
11737 lclTyp = TYP_FLOAT;
11740 lclTyp = TYP_DOUBLE;
11743 case CEE_CONV_R_UN:
11744 lclTyp = TYP_DOUBLE;
11758 // just check that we have a number on the stack
11759 if (tiVerificationNeeded)
11761 const typeInfo& tiVal = impStackTop().seTypeInfo;
11762 Verify(tiVal.IsNumberType(), "bad arg");
11764 #ifdef _TARGET_64BIT_
11765 bool isNative = false;
11769 case CEE_CONV_OVF_I:
11770 case CEE_CONV_OVF_I_UN:
11772 case CEE_CONV_OVF_U:
11773 case CEE_CONV_OVF_U_UN:
11777 // leave 'isNative' = false;
11782 tiRetVal = typeInfo::nativeInt();
11785 #endif // _TARGET_64BIT_
11787 tiRetVal = typeInfo(lclTyp).NormaliseForStack();
11791 // only converts from FLOAT or DOUBLE to an integer type
11792 // and converts from ULONG (or LONG on ARM) to DOUBLE are morphed to calls
11794 if (varTypeIsFloating(lclTyp))
11796 callNode = varTypeIsLong(impStackTop().val) || uns // uint->dbl gets turned into uint->long->dbl
11797 #ifdef _TARGET_64BIT_
11798 // TODO-ARM64-Bug?: This was AMD64; I enabled it for ARM64 also. OK?
11799 // TYP_BYREF could be used as TYP_I_IMPL which is long.
11800 // TODO-CQ: remove this when we lower casts long/ulong --> float/double
11801 // and generate SSE2 code instead of going through helper calls.
11802 || (impStackTop().val->TypeGet() == TYP_BYREF)
11808 callNode = varTypeIsFloating(impStackTop().val->TypeGet());
11811 // At this point uns, ovf, callNode all set
11813 op1 = impPopStack().val;
11814 impBashVarAddrsToI(op1);
11816 if (varTypeIsSmall(lclTyp) && !ovfl && op1->gtType == TYP_INT && op1->gtOper == GT_AND)
11818 op2 = op1->gtOp.gtOp2;
11820 if (op2->gtOper == GT_CNS_INT)
11822 ssize_t ival = op2->gtIntCon.gtIconVal;
11823 ssize_t mask, umask;
11839 assert(!"unexpected type");
11843 if (((ival & umask) == ival) || ((ival & mask) == ival && uns))
11845 /* Toss the cast, it's a waste of time */
11847 impPushOnStack(op1, tiRetVal);
11850 else if (ival == mask)
11852 /* Toss the masking, it's a waste of time, since
11853 we sign-extend from the small value anyways */
11855 op1 = op1->gtOp.gtOp1;
11860 /* The 'op2' sub-operand of a cast is the 'real' type number,
11861 since the result of a cast to one of the 'small' integer
11862 types is an integer.
11865 type = genActualType(lclTyp);
11867 #if SMALL_TREE_NODES
11870 op1 = gtNewCastNodeL(type, op1, lclTyp);
11873 #endif // SMALL_TREE_NODES
11875 op1 = gtNewCastNode(type, op1, lclTyp);
11880 op1->gtFlags |= (GTF_OVERFLOW | GTF_EXCEPT);
11884 op1->gtFlags |= GTF_UNSIGNED;
11886 impPushOnStack(op1, tiRetVal);
11890 if (tiVerificationNeeded)
11892 tiRetVal = impStackTop().seTypeInfo;
11893 Verify(tiRetVal.IsNumberType(), "Bad arg");
11896 op1 = impPopStack().val;
11897 impBashVarAddrsToI(op1, nullptr);
11898 impPushOnStack(gtNewOperNode(GT_NEG, genActualType(op1->gtType), op1), tiRetVal);
11902 if (tiVerificationNeeded)
11907 /* Pull the top value from the stack */
11909 op1 = impPopStack(clsHnd).val;
11911 /* Get hold of the type of the value being duplicated */
11913 lclTyp = genActualType(op1->gtType);
11915 /* Does the value have any side effects? */
11917 if ((op1->gtFlags & GTF_SIDE_EFFECT) || opts.compDbgCode)
11919 // Since we are throwing away the value, just normalize
11920 // it to its address. This is more efficient.
11922 if (varTypeIsStruct(op1))
11924 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
11925 // Non-calls, such as obj or ret_expr, have to go through this.
11926 // Calls with large struct return value have to go through this.
11927 // Helper calls with small struct return value also have to go
11928 // through this since they do not follow Unix calling convention.
11929 if (op1->gtOper != GT_CALL || !IsMultiRegReturnedType(clsHnd) ||
11930 op1->AsCall()->gtCallType == CT_HELPER)
11931 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
11933 op1 = impGetStructAddr(op1, clsHnd, (unsigned)CHECK_SPILL_ALL, false);
11937 // If op1 is non-overflow cast, throw it away since it is useless.
11938 // Another reason for throwing away the useless cast is in the context of
11939 // implicit tail calls when the operand of pop is GT_CAST(GT_CALL(..)).
11940 // The cast gets added as part of importing GT_CALL, which gets in the way
11941 // of fgMorphCall() on the forms of tail call nodes that we assert.
11942 if ((op1->gtOper == GT_CAST) && !op1->gtOverflow())
11944 op1 = op1->gtOp.gtOp1;
11947 // If 'op1' is an expression, create an assignment node.
11948 // Helps analyses (like CSE) to work fine.
11950 if (op1->gtOper != GT_CALL)
11952 op1 = gtUnusedValNode(op1);
11955 /* Append the value to the tree list */
11959 /* No side effects - just throw the <BEEP> thing away */
11964 if (tiVerificationNeeded)
11966 // Dup could start the begining of delegate creation sequence, remember that
11967 delegateCreateStart = codeAddr - 1;
11971 // Convert a (dup, stloc) sequence into a (stloc, ldloc) sequence in the following cases:
11972 // - If this is non-debug code - so that CSE will recognize the two as equal.
11973 // This helps eliminate a redundant bounds check in cases such as:
11974 // ariba[i+3] += some_value;
11975 // - If the top of the stack is a non-leaf that may be expensive to clone.
11977 if (codeAddr < codeEndp)
11979 OPCODE nextOpcode = (OPCODE)getU1LittleEndian(codeAddr);
11980 if (impIsAnySTLOC(nextOpcode))
11982 if (!opts.compDbgCode)
11984 insertLdloc = true;
11987 GenTree* stackTop = impStackTop().val;
11988 if (!stackTop->IsIntegralConst(0) && !stackTop->IsFPZero() && !stackTop->IsLocal())
11990 insertLdloc = true;
11996 /* Pull the top value from the stack */
11997 op1 = impPopStack(tiRetVal);
11999 /* Clone the value */
12000 op1 = impCloneExpr(op1, &op2, tiRetVal.GetClassHandle(), (unsigned)CHECK_SPILL_ALL,
12001 nullptr DEBUGARG("DUP instruction"));
12003 /* Either the tree started with no global effects, or impCloneExpr
12004 evaluated the tree to a temp and returned two copies of that
12005 temp. Either way, neither op1 nor op2 should have side effects.
12007 assert(!(op1->gtFlags & GTF_GLOB_EFFECT) && !(op2->gtFlags & GTF_GLOB_EFFECT));
12009 /* Push the tree/temp back on the stack */
12010 impPushOnStack(op1, tiRetVal);
12012 /* Push the copy on the stack */
12013 impPushOnStack(op2, tiRetVal);
12021 lclTyp = TYP_SHORT;
12030 lclTyp = TYP_I_IMPL;
12032 case CEE_STIND_REF:
12036 lclTyp = TYP_FLOAT;
12039 lclTyp = TYP_DOUBLE;
12043 if (tiVerificationNeeded)
12045 typeInfo instrType(lclTyp);
12046 #ifdef _TARGET_64BIT_
12047 if (opcode == CEE_STIND_I)
12049 instrType = typeInfo::nativeInt();
12051 #endif // _TARGET_64BIT_
12052 verVerifySTIND(impStackTop(1).seTypeInfo, impStackTop(0).seTypeInfo, instrType);
12056 compUnsafeCastUsed = true; // Have to go conservative
12061 op2 = impPopStack().val; // value to store
12062 op1 = impPopStack().val; // address to store to
12064 // you can indirect off of a TYP_I_IMPL (if we are in C) or a BYREF
12065 assertImp(genActualType(op1->gtType) == TYP_I_IMPL || op1->gtType == TYP_BYREF);
12067 impBashVarAddrsToI(op1, op2);
12069 op2 = impImplicitR4orR8Cast(op2, lclTyp);
12071 #ifdef _TARGET_64BIT_
12072 // Automatic upcast for a GT_CNS_INT into TYP_I_IMPL
12073 if ((op2->OperGet() == GT_CNS_INT) && varTypeIsI(lclTyp) && !varTypeIsI(op2->gtType))
12075 op2->gtType = TYP_I_IMPL;
12079 // Allow a downcast of op2 from TYP_I_IMPL into a 32-bit Int for x86 JIT compatiblity
12081 if (varTypeIsI(op2->gtType) && (genActualType(lclTyp) == TYP_INT))
12083 assert(!tiVerificationNeeded); // We should have thrown the VerificationException before.
12084 op2 = gtNewCastNode(TYP_INT, op2, TYP_INT);
12086 // Allow an upcast of op2 from a 32-bit Int into TYP_I_IMPL for x86 JIT compatiblity
12088 if (varTypeIsI(lclTyp) && (genActualType(op2->gtType) == TYP_INT))
12090 assert(!tiVerificationNeeded); // We should have thrown the VerificationException before.
12091 op2 = gtNewCastNode(TYP_I_IMPL, op2, TYP_I_IMPL);
12094 #endif // _TARGET_64BIT_
12096 if (opcode == CEE_STIND_REF)
12098 // STIND_REF can be used to store TYP_INT, TYP_I_IMPL, TYP_REF, or TYP_BYREF
12099 assertImp(varTypeIsIntOrI(op2->gtType) || varTypeIsGC(op2->gtType));
12100 lclTyp = genActualType(op2->TypeGet());
12103 // Check target type.
12105 if (op2->gtType == TYP_BYREF || lclTyp == TYP_BYREF)
12107 if (op2->gtType == TYP_BYREF)
12109 assertImp(lclTyp == TYP_BYREF || lclTyp == TYP_I_IMPL);
12111 else if (lclTyp == TYP_BYREF)
12113 assertImp(op2->gtType == TYP_BYREF || varTypeIsIntOrI(op2->gtType));
12118 assertImp(genActualType(op2->gtType) == genActualType(lclTyp) ||
12119 ((lclTyp == TYP_I_IMPL) && (genActualType(op2->gtType) == TYP_INT)) ||
12120 (varTypeIsFloating(op2->gtType) && varTypeIsFloating(lclTyp)));
12124 op1 = gtNewOperNode(GT_IND, lclTyp, op1);
12126 // stind could point anywhere, example a boxed class static int
12127 op1->gtFlags |= GTF_IND_TGTANYWHERE;
12129 if (prefixFlags & PREFIX_VOLATILE)
12131 assert(op1->OperGet() == GT_IND);
12132 op1->gtFlags |= GTF_DONT_CSE; // Can't CSE a volatile
12133 op1->gtFlags |= GTF_ORDER_SIDEEFF; // Prevent this from being reordered
12134 op1->gtFlags |= GTF_IND_VOLATILE;
12137 if (prefixFlags & PREFIX_UNALIGNED)
12139 assert(op1->OperGet() == GT_IND);
12140 op1->gtFlags |= GTF_IND_UNALIGNED;
12143 op1 = gtNewAssignNode(op1, op2);
12144 op1->gtFlags |= GTF_EXCEPT | GTF_GLOB_REF;
12146 // Spill side-effects AND global-data-accesses
12147 if (verCurrentState.esStackDepth > 0)
12149 impSpillSideEffects(true, (unsigned)CHECK_SPILL_ALL DEBUGARG("spill side effects before STIND"));
12158 lclTyp = TYP_SHORT;
12167 case CEE_LDIND_REF:
12171 lclTyp = TYP_I_IMPL;
12174 lclTyp = TYP_FLOAT;
12177 lclTyp = TYP_DOUBLE;
12180 lclTyp = TYP_UBYTE;
12187 if (tiVerificationNeeded)
12189 typeInfo lclTiType(lclTyp);
12190 #ifdef _TARGET_64BIT_
12191 if (opcode == CEE_LDIND_I)
12193 lclTiType = typeInfo::nativeInt();
12195 #endif // _TARGET_64BIT_
12196 tiRetVal = verVerifyLDIND(impStackTop().seTypeInfo, lclTiType);
12197 tiRetVal.NormaliseForStack();
12201 compUnsafeCastUsed = true; // Have to go conservative
12206 op1 = impPopStack().val; // address to load from
12207 impBashVarAddrsToI(op1);
12209 #ifdef _TARGET_64BIT_
12210 // Allow an upcast of op1 from a 32-bit Int into TYP_I_IMPL for x86 JIT compatiblity
12212 if (genActualType(op1->gtType) == TYP_INT)
12214 assert(!tiVerificationNeeded); // We should have thrown the VerificationException before.
12215 op1 = gtNewCastNode(TYP_I_IMPL, op1, TYP_I_IMPL);
12219 assertImp(genActualType(op1->gtType) == TYP_I_IMPL || op1->gtType == TYP_BYREF);
12221 op1 = gtNewOperNode(GT_IND, lclTyp, op1);
12223 // ldind could point anywhere, example a boxed class static int
12224 op1->gtFlags |= (GTF_EXCEPT | GTF_GLOB_REF | GTF_IND_TGTANYWHERE);
12226 if (prefixFlags & PREFIX_VOLATILE)
12228 assert(op1->OperGet() == GT_IND);
12229 op1->gtFlags |= GTF_DONT_CSE; // Can't CSE a volatile
12230 op1->gtFlags |= GTF_ORDER_SIDEEFF; // Prevent this from being reordered
12231 op1->gtFlags |= GTF_IND_VOLATILE;
12234 if (prefixFlags & PREFIX_UNALIGNED)
12236 assert(op1->OperGet() == GT_IND);
12237 op1->gtFlags |= GTF_IND_UNALIGNED;
12240 impPushOnStack(op1, tiRetVal);
12244 case CEE_UNALIGNED:
12247 val = getU1LittleEndian(codeAddr);
12249 JITDUMP(" %u", val);
12250 if ((val != 1) && (val != 2) && (val != 4))
12252 BADCODE("Alignment unaligned. must be 1, 2, or 4");
12255 Verify(!(prefixFlags & PREFIX_UNALIGNED), "Multiple unaligned. prefixes");
12256 prefixFlags |= PREFIX_UNALIGNED;
12258 impValidateMemoryAccessOpcode(codeAddr, codeEndp, false);
12261 opcode = (OPCODE)getU1LittleEndian(codeAddr);
12262 codeAddr += sizeof(__int8);
12263 opcodeOffs = (IL_OFFSET)(codeAddr - info.compCode);
12264 goto DECODE_OPCODE;
12268 Verify(!(prefixFlags & PREFIX_VOLATILE), "Multiple volatile. prefixes");
12269 prefixFlags |= PREFIX_VOLATILE;
12271 impValidateMemoryAccessOpcode(codeAddr, codeEndp, true);
12278 // Need to do a lookup here so that we perform an access check
12279 // and do a NOWAY if protections are violated
12280 _impResolveToken(CORINFO_TOKENKIND_Method);
12282 JITDUMP(" %08X", resolvedToken.token);
12284 eeGetCallInfo(&resolvedToken, nullptr /* constraint typeRef*/,
12285 addVerifyFlag(combine(CORINFO_CALLINFO_SECURITYCHECKS, CORINFO_CALLINFO_LDFTN)),
12288 // This check really only applies to intrinsic Array.Address methods
12289 if (callInfo.sig.callConv & CORINFO_CALLCONV_PARAMTYPE)
12291 NO_WAY("Currently do not support LDFTN of Parameterized functions");
12294 // Do this before DO_LDFTN since CEE_LDVIRTFN does it on its own.
12295 impHandleAccessAllowed(callInfo.accessAllowed, &callInfo.callsiteCalloutHelper);
12297 if (tiVerificationNeeded)
12299 // LDFTN could start the begining of delegate creation sequence, remember that
12300 delegateCreateStart = codeAddr - 2;
12302 // check any constraints on the callee's class and type parameters
12303 VerifyOrReturn(info.compCompHnd->satisfiesClassConstraints(resolvedToken.hClass),
12304 "method has unsatisfied class constraints");
12305 VerifyOrReturn(info.compCompHnd->satisfiesMethodConstraints(resolvedToken.hClass,
12306 resolvedToken.hMethod),
12307 "method has unsatisfied method constraints");
12309 mflags = callInfo.verMethodFlags;
12310 Verify(!(mflags & CORINFO_FLG_CONSTRUCTOR), "LDFTN on a constructor");
12314 op1 = impMethodPointer(&resolvedToken, &callInfo);
12315 if (compDonotInline())
12320 impPushOnStack(op1, typeInfo(resolvedToken.hMethod));
12325 case CEE_LDVIRTFTN:
12327 /* Get the method token */
12329 _impResolveToken(CORINFO_TOKENKIND_Method);
12331 JITDUMP(" %08X", resolvedToken.token);
12333 eeGetCallInfo(&resolvedToken, nullptr /* constraint typeRef */,
12334 addVerifyFlag(combine(combine(CORINFO_CALLINFO_SECURITYCHECKS, CORINFO_CALLINFO_LDFTN),
12335 CORINFO_CALLINFO_CALLVIRT)),
12338 // This check really only applies to intrinsic Array.Address methods
12339 if (callInfo.sig.callConv & CORINFO_CALLCONV_PARAMTYPE)
12341 NO_WAY("Currently do not support LDFTN of Parameterized functions");
12344 mflags = callInfo.methodFlags;
12346 impHandleAccessAllowed(callInfo.accessAllowed, &callInfo.callsiteCalloutHelper);
12348 if (compIsForInlining())
12350 if (mflags & (CORINFO_FLG_FINAL | CORINFO_FLG_STATIC) || !(mflags & CORINFO_FLG_VIRTUAL))
12352 compInlineResult->NoteFatal(InlineObservation::CALLSITE_LDVIRTFN_ON_NON_VIRTUAL);
12357 CORINFO_SIG_INFO& ftnSig = callInfo.sig;
12359 if (tiVerificationNeeded)
12362 Verify(ftnSig.hasThis(), "ldvirtftn on a static method");
12363 Verify(!(mflags & CORINFO_FLG_CONSTRUCTOR), "LDVIRTFTN on a constructor");
12365 // JIT32 verifier rejects verifiable ldvirtftn pattern
12366 typeInfo declType =
12367 verMakeTypeInfo(resolvedToken.hClass, true); // Change TI_STRUCT to TI_REF when necessary
12369 typeInfo arg = impStackTop().seTypeInfo;
12370 Verify((arg.IsType(TI_REF) || arg.IsType(TI_NULL)) && tiCompatibleWith(arg, declType, true),
12373 CORINFO_CLASS_HANDLE instanceClassHnd = info.compClassHnd;
12374 if (!(arg.IsType(TI_NULL) || (mflags & CORINFO_FLG_STATIC)))
12376 instanceClassHnd = arg.GetClassHandleForObjRef();
12379 // check any constraints on the method's class and type parameters
12380 VerifyOrReturn(info.compCompHnd->satisfiesClassConstraints(resolvedToken.hClass),
12381 "method has unsatisfied class constraints");
12382 VerifyOrReturn(info.compCompHnd->satisfiesMethodConstraints(resolvedToken.hClass,
12383 resolvedToken.hMethod),
12384 "method has unsatisfied method constraints");
12386 if (mflags & CORINFO_FLG_PROTECTED)
12388 Verify(info.compCompHnd->canAccessFamily(info.compMethodHnd, instanceClassHnd),
12389 "Accessing protected method through wrong type.");
12393 /* Get the object-ref */
12394 op1 = impPopStack().val;
12395 assertImp(op1->gtType == TYP_REF);
12397 if (opts.IsReadyToRun())
12399 if (callInfo.kind != CORINFO_VIRTUALCALL_LDVIRTFTN)
12401 if (op1->gtFlags & GTF_SIDE_EFFECT)
12403 op1 = gtUnusedValNode(op1);
12404 impAppendTree(op1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
12409 else if (mflags & (CORINFO_FLG_FINAL | CORINFO_FLG_STATIC) || !(mflags & CORINFO_FLG_VIRTUAL))
12411 if (op1->gtFlags & GTF_SIDE_EFFECT)
12413 op1 = gtUnusedValNode(op1);
12414 impAppendTree(op1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
12419 GenTreePtr fptr = impImportLdvirtftn(op1, &resolvedToken, &callInfo);
12420 if (compDonotInline())
12425 impPushOnStack(fptr, typeInfo(resolvedToken.hMethod));
12430 case CEE_CONSTRAINED:
12432 assertImp(sz == sizeof(unsigned));
12433 impResolveToken(codeAddr, &constrainedResolvedToken, CORINFO_TOKENKIND_Constrained);
12434 codeAddr += sizeof(unsigned); // prefix instructions must increment codeAddr manually
12435 JITDUMP(" (%08X) ", constrainedResolvedToken.token);
12437 Verify(!(prefixFlags & PREFIX_CONSTRAINED), "Multiple constrained. prefixes");
12438 prefixFlags |= PREFIX_CONSTRAINED;
12441 OPCODE actualOpcode = impGetNonPrefixOpcode(codeAddr, codeEndp);
12442 if (actualOpcode != CEE_CALLVIRT)
12444 BADCODE("constrained. has to be followed by callvirt");
12451 JITDUMP(" readonly.");
12453 Verify(!(prefixFlags & PREFIX_READONLY), "Multiple readonly. prefixes");
12454 prefixFlags |= PREFIX_READONLY;
12457 OPCODE actualOpcode = impGetNonPrefixOpcode(codeAddr, codeEndp);
12458 if (actualOpcode != CEE_LDELEMA && !impOpcodeIsCallOpcode(actualOpcode))
12460 BADCODE("readonly. has to be followed by ldelema or call");
12470 Verify(!(prefixFlags & PREFIX_TAILCALL_EXPLICIT), "Multiple tailcall. prefixes");
12471 prefixFlags |= PREFIX_TAILCALL_EXPLICIT;
12474 OPCODE actualOpcode = impGetNonPrefixOpcode(codeAddr, codeEndp);
12475 if (!impOpcodeIsCallOpcode(actualOpcode))
12477 BADCODE("tailcall. has to be followed by call, callvirt or calli");
12485 /* Since we will implicitly insert newObjThisPtr at the start of the
12486 argument list, spill any GTF_ORDER_SIDEEFF */
12487 impSpillSpecialSideEff();
12489 /* NEWOBJ does not respond to TAIL */
12490 prefixFlags &= ~PREFIX_TAILCALL_EXPLICIT;
12492 /* NEWOBJ does not respond to CONSTRAINED */
12493 prefixFlags &= ~PREFIX_CONSTRAINED;
12495 #if COR_JIT_EE_VERSION > 460
12496 _impResolveToken(CORINFO_TOKENKIND_NewObj);
12498 _impResolveToken(CORINFO_TOKENKIND_Method);
12501 eeGetCallInfo(&resolvedToken, nullptr /* constraint typeRef*/,
12502 addVerifyFlag(combine(CORINFO_CALLINFO_SECURITYCHECKS, CORINFO_CALLINFO_ALLOWINSTPARAM)),
12505 if (compIsForInlining())
12507 if (impInlineInfo->inlineCandidateInfo->dwRestrictions & INLINE_RESPECT_BOUNDARY)
12509 // Check to see if this call violates the boundary.
12510 compInlineResult->NoteFatal(InlineObservation::CALLSITE_CROSS_BOUNDARY_SECURITY);
12515 mflags = callInfo.methodFlags;
12517 if ((mflags & (CORINFO_FLG_STATIC | CORINFO_FLG_ABSTRACT)) != 0)
12519 BADCODE("newobj on static or abstract method");
12522 // Insert the security callout before any actual code is generated
12523 impHandleAccessAllowed(callInfo.accessAllowed, &callInfo.callsiteCalloutHelper);
12525 // There are three different cases for new
12526 // Object size is variable (depends on arguments)
12527 // 1) Object is an array (arrays treated specially by the EE)
12528 // 2) Object is some other variable sized object (e.g. String)
12529 // 3) Class Size can be determined beforehand (normal case)
12530 // In the first case, we need to call a NEWOBJ helper (multinewarray)
12531 // in the second case we call the constructor with a '0' this pointer
12532 // In the third case we alloc the memory, then call the constuctor
12534 clsFlags = callInfo.classFlags;
12535 if (clsFlags & CORINFO_FLG_ARRAY)
12537 if (tiVerificationNeeded)
12539 CORINFO_CLASS_HANDLE elemTypeHnd;
12540 INDEBUG(CorInfoType corType =)
12541 info.compCompHnd->getChildType(resolvedToken.hClass, &elemTypeHnd);
12542 assert(!(elemTypeHnd == nullptr && corType == CORINFO_TYPE_VALUECLASS));
12543 Verify(elemTypeHnd == nullptr ||
12544 !(info.compCompHnd->getClassAttribs(elemTypeHnd) & CORINFO_FLG_CONTAINS_STACK_PTR),
12545 "newarr of byref-like objects");
12546 verVerifyCall(opcode, &resolvedToken, nullptr, ((prefixFlags & PREFIX_TAILCALL_EXPLICIT) != 0),
12547 ((prefixFlags & PREFIX_READONLY) != 0), delegateCreateStart, codeAddr - 1,
12548 &callInfo DEBUGARG(info.compFullName));
12550 // Arrays need to call the NEWOBJ helper.
12551 assertImp(clsFlags & CORINFO_FLG_VAROBJSIZE);
12553 impImportNewObjArray(&resolvedToken, &callInfo);
12554 if (compDonotInline())
12562 // At present this can only be String
12563 else if (clsFlags & CORINFO_FLG_VAROBJSIZE)
12565 if (IsTargetAbi(CORINFO_CORERT_ABI))
12567 // The dummy argument does not exist in CoreRT
12568 newObjThisPtr = nullptr;
12572 // This is the case for variable-sized objects that are not
12573 // arrays. In this case, call the constructor with a null 'this'
12575 newObjThisPtr = gtNewIconNode(0, TYP_REF);
12578 /* Remember that this basic block contains 'new' of an object */
12579 block->bbFlags |= BBF_HAS_NEWOBJ;
12580 optMethodFlags |= OMF_HAS_NEWOBJ;
12584 // This is the normal case where the size of the object is
12585 // fixed. Allocate the memory and call the constructor.
12587 // Note: We cannot add a peep to avoid use of temp here
12588 // becase we don't have enough interference info to detect when
12589 // sources and destination interfere, example: s = new S(ref);
12591 // TODO: We find the correct place to introduce a general
12592 // reverse copy prop for struct return values from newobj or
12593 // any function returning structs.
12595 /* get a temporary for the new object */
12596 lclNum = lvaGrabTemp(true DEBUGARG("NewObj constructor temp"));
12598 // In the value class case we only need clsHnd for size calcs.
12600 // The lookup of the code pointer will be handled by CALL in this case
12601 if (clsFlags & CORINFO_FLG_VALUECLASS)
12603 if (compIsForInlining())
12605 // If value class has GC fields, inform the inliner. It may choose to
12606 // bail out on the inline.
12607 DWORD typeFlags = info.compCompHnd->getClassAttribs(resolvedToken.hClass);
12608 if ((typeFlags & CORINFO_FLG_CONTAINS_GC_PTR) != 0)
12610 compInlineResult->Note(InlineObservation::CALLEE_HAS_GC_STRUCT);
12611 if (compInlineResult->IsFailure())
12616 // Do further notification in the case where the call site is rare;
12617 // some policies do not track the relative hotness of call sites for
12618 // "always" inline cases.
12619 if (impInlineInfo->iciBlock->isRunRarely())
12621 compInlineResult->Note(InlineObservation::CALLSITE_RARE_GC_STRUCT);
12622 if (compInlineResult->IsFailure())
12630 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(resolvedToken.hClass);
12631 unsigned size = info.compCompHnd->getClassSize(resolvedToken.hClass);
12633 if (impIsPrimitive(jitTyp))
12635 lvaTable[lclNum].lvType = JITtype2varType(jitTyp);
12639 // The local variable itself is the allocated space.
12640 // Here we need unsafe value cls check, since the address of struct is taken for further use
12641 // and potentially exploitable.
12642 lvaSetStruct(lclNum, resolvedToken.hClass, true /* unsafe value cls check */);
12645 // Append a tree to zero-out the temp
12646 newObjThisPtr = gtNewLclvNode(lclNum, lvaTable[lclNum].TypeGet());
12648 newObjThisPtr = gtNewBlkOpNode(newObjThisPtr, // Dest
12649 gtNewIconNode(0), // Value
12651 false, // isVolatile
12652 false); // not copyBlock
12653 impAppendTree(newObjThisPtr, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
12655 // Obtain the address of the temp
12657 gtNewOperNode(GT_ADDR, TYP_BYREF, gtNewLclvNode(lclNum, lvaTable[lclNum].TypeGet()));
12661 #ifdef FEATURE_READYTORUN_COMPILER
12662 if (opts.IsReadyToRun())
12664 op1 = impReadyToRunHelperToTree(&resolvedToken, CORINFO_HELP_READYTORUN_NEW, TYP_REF);
12665 usingReadyToRunHelper = (op1 != nullptr);
12668 if (!usingReadyToRunHelper)
12671 op1 = impParentClassTokenToHandle(&resolvedToken, nullptr, TRUE);
12672 if (op1 == nullptr)
12673 { // compDonotInline()
12677 // TODO: ReadyToRun: When generic dictionary lookups are necessary, replace the lookup call
12678 // and the newfast call with a single call to a dynamic R2R cell that will:
12679 // 1) Load the context
12680 // 2) Perform the generic dictionary lookup and caching, and generate the appropriate
12682 // 3) Allocate and return the new object
12683 // Reason: performance (today, we'll always use the slow helper for the R2R generics case)
12685 op1 = gtNewAllocObjNode(info.compCompHnd->getNewHelper(&resolvedToken, info.compMethodHnd),
12686 resolvedToken.hClass, TYP_REF, op1);
12689 // Remember that this basic block contains 'new' of an object
12690 block->bbFlags |= BBF_HAS_NEWOBJ;
12691 optMethodFlags |= OMF_HAS_NEWOBJ;
12693 // Append the assignment to the temp/local. Dont need to spill
12694 // at all as we are just calling an EE-Jit helper which can only
12695 // cause an (async) OutOfMemoryException.
12697 // We assign the newly allocated object (by a GT_ALLOCOBJ node)
12698 // to a temp. Note that the pattern "temp = allocObj" is required
12699 // by ObjectAllocator phase to be able to determine GT_ALLOCOBJ nodes
12700 // without exhaustive walk over all expressions.
12702 impAssignTempGen(lclNum, op1, (unsigned)CHECK_SPILL_NONE);
12704 newObjThisPtr = gtNewLclvNode(lclNum, TYP_REF);
12711 /* CALLI does not respond to CONSTRAINED */
12712 prefixFlags &= ~PREFIX_CONSTRAINED;
12714 if (compIsForInlining())
12716 // CALLI doesn't have a method handle, so assume the worst.
12717 if (impInlineInfo->inlineCandidateInfo->dwRestrictions & INLINE_RESPECT_BOUNDARY)
12719 compInlineResult->NoteFatal(InlineObservation::CALLSITE_CROSS_BOUNDARY_CALLI);
12729 // We can't call getCallInfo on the token from a CALLI, but we need it in
12730 // many other places. We unfortunately embed that knowledge here.
12731 if (opcode != CEE_CALLI)
12733 _impResolveToken(CORINFO_TOKENKIND_Method);
12735 eeGetCallInfo(&resolvedToken,
12736 (prefixFlags & PREFIX_CONSTRAINED) ? &constrainedResolvedToken : nullptr,
12737 // this is how impImportCall invokes getCallInfo
12739 combine(combine(CORINFO_CALLINFO_ALLOWINSTPARAM, CORINFO_CALLINFO_SECURITYCHECKS),
12740 (opcode == CEE_CALLVIRT) ? CORINFO_CALLINFO_CALLVIRT
12741 : CORINFO_CALLINFO_NONE)),
12746 // Suppress uninitialized use warning.
12747 memset(&resolvedToken, 0, sizeof(resolvedToken));
12748 memset(&callInfo, 0, sizeof(callInfo));
12750 resolvedToken.token = getU4LittleEndian(codeAddr);
12753 CALL: // memberRef should be set.
12754 // newObjThisPtr should be set for CEE_NEWOBJ
12756 JITDUMP(" %08X", resolvedToken.token);
12757 constraintCall = (prefixFlags & PREFIX_CONSTRAINED) != 0;
12759 bool newBBcreatedForTailcallStress;
12761 newBBcreatedForTailcallStress = false;
12763 if (compIsForInlining())
12765 if (compDonotInline())
12769 // We rule out inlinees with explicit tail calls in fgMakeBasicBlocks.
12770 assert((prefixFlags & PREFIX_TAILCALL_EXPLICIT) == 0);
12774 if (compTailCallStress())
12776 // Have we created a new BB after the "call" instruction in fgMakeBasicBlocks()?
12777 // Tail call stress only recognizes call+ret patterns and forces them to be
12778 // explicit tail prefixed calls. Also fgMakeBasicBlocks() under tail call stress
12779 // doesn't import 'ret' opcode following the call into the basic block containing
12780 // the call instead imports it to a new basic block. Note that fgMakeBasicBlocks()
12781 // is already checking that there is an opcode following call and hence it is
12782 // safe here to read next opcode without bounds check.
12783 newBBcreatedForTailcallStress =
12784 impOpcodeIsCallOpcode(opcode) && // Current opcode is a CALL, (not a CEE_NEWOBJ). So, don't
12785 // make it jump to RET.
12786 (OPCODE)getU1LittleEndian(codeAddr + sz) == CEE_RET; // Next opcode is a CEE_RET
12788 if (newBBcreatedForTailcallStress &&
12789 !(prefixFlags & PREFIX_TAILCALL_EXPLICIT) && // User hasn't set "tail." prefix yet.
12790 verCheckTailCallConstraint(opcode, &resolvedToken,
12791 constraintCall ? &constrainedResolvedToken : nullptr,
12792 true) // Is it legal to do talcall?
12795 // Stress the tailcall.
12796 JITDUMP(" (Tailcall stress: prefixFlags |= PREFIX_TAILCALL_EXPLICIT)");
12797 prefixFlags |= PREFIX_TAILCALL_EXPLICIT;
12802 // This is split up to avoid goto flow warnings.
12804 isRecursive = !compIsForInlining() && (callInfo.hMethod == info.compMethodHnd);
12806 // Note that when running under tail call stress, a call will be marked as explicit tail prefixed
12807 // hence will not be considered for implicit tail calling.
12808 if (impIsImplicitTailCallCandidate(opcode, codeAddr + sz, codeEndp, prefixFlags, isRecursive))
12810 if (compIsForInlining())
12812 #if FEATURE_TAILCALL_OPT_SHARED_RETURN
12813 // Are we inlining at an implicit tail call site? If so the we can flag
12814 // implicit tail call sites in the inline body. These call sites
12815 // often end up in non BBJ_RETURN blocks, so only flag them when
12816 // we're able to handle shared returns.
12817 if (impInlineInfo->iciCall->IsImplicitTailCall())
12819 JITDUMP(" (Inline Implicit Tail call: prefixFlags |= PREFIX_TAILCALL_IMPLICIT)");
12820 prefixFlags |= PREFIX_TAILCALL_IMPLICIT;
12822 #endif // FEATURE_TAILCALL_OPT_SHARED_RETURN
12826 JITDUMP(" (Implicit Tail call: prefixFlags |= PREFIX_TAILCALL_IMPLICIT)");
12827 prefixFlags |= PREFIX_TAILCALL_IMPLICIT;
12831 // Treat this call as tail call for verification only if "tail" prefixed (i.e. explicit tail call).
12832 explicitTailCall = (prefixFlags & PREFIX_TAILCALL_EXPLICIT) != 0;
12833 readonlyCall = (prefixFlags & PREFIX_READONLY) != 0;
12835 if (opcode != CEE_CALLI && opcode != CEE_NEWOBJ)
12837 // All calls and delegates need a security callout.
12838 // For delegates, this is the call to the delegate constructor, not the access check on the
12840 impHandleAccessAllowed(callInfo.accessAllowed, &callInfo.callsiteCalloutHelper);
12842 #if 0 // DevDiv 410397 - This breaks too many obfuscated apps to do this in an in-place release
12844 // DevDiv 291703 - we need to check for accessibility between the caller of InitializeArray
12845 // and the field it is reading, thus it is now unverifiable to not immediately precede with
12846 // ldtoken <filed token>, and we now check accessibility
12847 if ((callInfo.methodFlags & CORINFO_FLG_INTRINSIC) &&
12848 (info.compCompHnd->getIntrinsicID(callInfo.hMethod) == CORINFO_INTRINSIC_InitializeArray))
12850 if (prevOpcode != CEE_LDTOKEN)
12852 Verify(prevOpcode == CEE_LDTOKEN, "Need ldtoken for InitializeArray");
12856 assert(lastLoadToken != NULL);
12857 // Now that we know we have a token, verify that it is accessible for loading
12858 CORINFO_RESOLVED_TOKEN resolvedLoadField;
12859 impResolveToken(lastLoadToken, &resolvedLoadField, CORINFO_TOKENKIND_Field);
12860 eeGetFieldInfo(&resolvedLoadField, CORINFO_ACCESS_INIT_ARRAY, &fieldInfo);
12861 impHandleAccessAllowed(fieldInfo.accessAllowed, &fieldInfo.accessCalloutHelper);
12865 #endif // DevDiv 410397
12868 if (tiVerificationNeeded)
12870 verVerifyCall(opcode, &resolvedToken, constraintCall ? &constrainedResolvedToken : nullptr,
12871 explicitTailCall, readonlyCall, delegateCreateStart, codeAddr - 1,
12872 &callInfo DEBUGARG(info.compFullName));
12875 // Insert delegate callout here.
12876 if (opcode == CEE_NEWOBJ && (mflags & CORINFO_FLG_CONSTRUCTOR) && (clsFlags & CORINFO_FLG_DELEGATE))
12879 // We should do this only if verification is enabled
12880 // If verification is disabled, delegateCreateStart will not be initialized correctly
12881 if (tiVerificationNeeded)
12883 mdMemberRef delegateMethodRef = mdMemberRefNil;
12884 // We should get here only for well formed delegate creation.
12885 assert(verCheckDelegateCreation(delegateCreateStart, codeAddr - 1, delegateMethodRef));
12889 #ifdef FEATURE_CORECLR
12890 // In coreclr the delegate transparency rule needs to be enforced even if verification is disabled
12891 typeInfo tiActualFtn = impStackTop(0).seTypeInfo;
12892 CORINFO_METHOD_HANDLE delegateMethodHandle = tiActualFtn.GetMethod2();
12894 impInsertCalloutForDelegate(info.compMethodHnd, delegateMethodHandle, resolvedToken.hClass);
12895 #endif // FEATURE_CORECLR
12898 callTyp = impImportCall(opcode, &resolvedToken, constraintCall ? &constrainedResolvedToken : nullptr,
12899 newObjThisPtr, prefixFlags, &callInfo, opcodeOffs);
12900 if (compDonotInline())
12905 if (explicitTailCall || newBBcreatedForTailcallStress) // If newBBcreatedForTailcallStress is true, we
12906 // have created a new BB after the "call"
12907 // instruction in fgMakeBasicBlocks(). So we need to jump to RET regardless.
12909 assert(!compIsForInlining());
12921 BOOL isLoadAddress = (opcode == CEE_LDFLDA || opcode == CEE_LDSFLDA);
12922 BOOL isLoadStatic = (opcode == CEE_LDSFLD || opcode == CEE_LDSFLDA);
12924 /* Get the CP_Fieldref index */
12925 assertImp(sz == sizeof(unsigned));
12927 _impResolveToken(CORINFO_TOKENKIND_Field);
12929 JITDUMP(" %08X", resolvedToken.token);
12931 int aflags = isLoadAddress ? CORINFO_ACCESS_ADDRESS : CORINFO_ACCESS_GET;
12933 GenTreePtr obj = nullptr;
12934 typeInfo* tiObj = nullptr;
12935 CORINFO_CLASS_HANDLE objType = nullptr; // used for fields
12937 if (opcode == CEE_LDFLD || opcode == CEE_LDFLDA)
12939 tiObj = &impStackTop().seTypeInfo;
12940 obj = impPopStack(objType).val;
12942 if (impIsThis(obj))
12944 aflags |= CORINFO_ACCESS_THIS;
12946 // An optimization for Contextful classes:
12947 // we unwrap the proxy when we have a 'this reference'
12949 if (info.compUnwrapContextful)
12951 aflags |= CORINFO_ACCESS_UNWRAP;
12956 eeGetFieldInfo(&resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo);
12958 // Figure out the type of the member. We always call canAccessField, so you always need this
12960 CorInfoType ciType = fieldInfo.fieldType;
12961 clsHnd = fieldInfo.structType;
12963 lclTyp = JITtype2varType(ciType);
12965 #ifdef _TARGET_AMD64
12966 noway_assert(varTypeIsIntegralOrI(lclTyp) || varTypeIsFloating(lclTyp) || lclTyp == TYP_STRUCT);
12967 #endif // _TARGET_AMD64
12969 if (compIsForInlining())
12971 switch (fieldInfo.fieldAccessor)
12973 case CORINFO_FIELD_INSTANCE_HELPER:
12974 case CORINFO_FIELD_INSTANCE_ADDR_HELPER:
12975 case CORINFO_FIELD_STATIC_ADDR_HELPER:
12976 case CORINFO_FIELD_STATIC_TLS:
12978 compInlineResult->NoteFatal(InlineObservation::CALLEE_LDFLD_NEEDS_HELPER);
12981 case CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER:
12982 #if COR_JIT_EE_VERSION > 460
12983 case CORINFO_FIELD_STATIC_READYTORUN_HELPER:
12985 /* We may be able to inline the field accessors in specific instantiations of generic
12987 compInlineResult->NoteFatal(InlineObservation::CALLSITE_LDFLD_NEEDS_HELPER);
12994 if (!isLoadAddress && (fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC) && lclTyp == TYP_STRUCT &&
12997 if ((info.compCompHnd->getTypeForPrimitiveValueClass(clsHnd) == CORINFO_TYPE_UNDEF) &&
12998 !(info.compFlags & CORINFO_FLG_FORCEINLINE))
13000 // Loading a static valuetype field usually will cause a JitHelper to be called
13001 // for the static base. This will bloat the code.
13002 compInlineResult->Note(InlineObservation::CALLEE_LDFLD_STATIC_VALUECLASS);
13004 if (compInlineResult->IsFailure())
13012 tiRetVal = verMakeTypeInfo(ciType, clsHnd);
13015 tiRetVal.MakeByRef();
13019 tiRetVal.NormaliseForStack();
13022 // Perform this check always to ensure that we get field access exceptions even with
13023 // SkipVerification.
13024 impHandleAccessAllowed(fieldInfo.accessAllowed, &fieldInfo.accessCalloutHelper);
13026 if (tiVerificationNeeded)
13028 // You can also pass the unboxed struct to LDFLD
13029 BOOL bAllowPlainValueTypeAsThis = FALSE;
13030 if (opcode == CEE_LDFLD && impIsValueType(tiObj))
13032 bAllowPlainValueTypeAsThis = TRUE;
13035 verVerifyField(&resolvedToken, fieldInfo, tiObj, isLoadAddress, bAllowPlainValueTypeAsThis);
13037 // If we're doing this on a heap object or from a 'safe' byref
13038 // then the result is a safe byref too
13039 if (isLoadAddress) // load address
13041 if (fieldInfo.fieldFlags &
13042 CORINFO_FLG_FIELD_STATIC) // statics marked as safe will have permanent home
13044 if (fieldInfo.fieldFlags & CORINFO_FLG_FIELD_SAFESTATIC_BYREF_RETURN)
13046 tiRetVal.SetIsPermanentHomeByRef();
13049 else if (tiObj->IsObjRef() || tiObj->IsPermanentHomeByRef())
13051 // ldflda of byref is safe if done on a gc object or on a
13053 tiRetVal.SetIsPermanentHomeByRef();
13059 // tiVerificationNeeded is false.
13060 // Raise InvalidProgramException if static load accesses non-static field
13061 if (isLoadStatic && ((fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC) == 0))
13063 BADCODE("static access on an instance field");
13067 // We are using ldfld/a on a static field. We allow it, but need to get side-effect from obj.
13068 if ((fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC) && obj != nullptr)
13070 if (obj->gtFlags & GTF_SIDE_EFFECT)
13072 obj = gtUnusedValNode(obj);
13073 impAppendTree(obj, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
13078 /* Preserve 'small' int types */
13079 if (lclTyp > TYP_INT)
13081 lclTyp = genActualType(lclTyp);
13084 bool usesHelper = false;
13086 switch (fieldInfo.fieldAccessor)
13088 case CORINFO_FIELD_INSTANCE:
13089 #ifdef FEATURE_READYTORUN_COMPILER
13090 case CORINFO_FIELD_INSTANCE_WITH_BASE:
13093 bool nullcheckNeeded = false;
13095 obj = impCheckForNullPointer(obj);
13097 if (isLoadAddress && (obj->gtType == TYP_BYREF) && fgAddrCouldBeNull(obj))
13099 nullcheckNeeded = true;
13102 // If the object is a struct, what we really want is
13103 // for the field to operate on the address of the struct.
13104 if (!varTypeGCtype(obj->TypeGet()) && impIsValueType(tiObj))
13106 assert(opcode == CEE_LDFLD && objType != nullptr);
13108 obj = impGetStructAddr(obj, objType, (unsigned)CHECK_SPILL_ALL, true);
13111 /* Create the data member node */
13112 op1 = gtNewFieldRef(lclTyp, resolvedToken.hField, obj, fieldInfo.offset, nullcheckNeeded);
13114 #ifdef FEATURE_READYTORUN_COMPILER
13115 if (fieldInfo.fieldAccessor == CORINFO_FIELD_INSTANCE_WITH_BASE)
13117 op1->gtField.gtFieldLookup = fieldInfo.fieldLookup;
13121 op1->gtFlags |= (obj->gtFlags & GTF_GLOB_EFFECT);
13123 if (fgAddrCouldBeNull(obj))
13125 op1->gtFlags |= GTF_EXCEPT;
13128 // If gtFldObj is a BYREF then our target is a value class and
13129 // it could point anywhere, example a boxed class static int
13130 if (obj->gtType == TYP_BYREF)
13132 op1->gtFlags |= GTF_IND_TGTANYWHERE;
13135 DWORD typeFlags = info.compCompHnd->getClassAttribs(resolvedToken.hClass);
13136 if (StructHasOverlappingFields(typeFlags))
13138 op1->gtField.gtFldMayOverlap = true;
13141 // wrap it in a address of operator if necessary
13144 op1 = gtNewOperNode(GT_ADDR,
13145 (var_types)(varTypeIsGC(obj->TypeGet()) ? TYP_BYREF : TYP_I_IMPL), op1);
13149 if (compIsForInlining() &&
13150 impInlineIsGuaranteedThisDerefBeforeAnySideEffects(nullptr, obj,
13151 impInlineInfo->inlArgInfo))
13153 impInlineInfo->thisDereferencedFirst = true;
13159 case CORINFO_FIELD_STATIC_TLS:
13160 #ifdef _TARGET_X86_
13161 // Legacy TLS access is implemented as intrinsic on x86 only
13163 /* Create the data member node */
13164 op1 = gtNewFieldRef(lclTyp, resolvedToken.hField, NULL, fieldInfo.offset);
13165 op1->gtFlags |= GTF_IND_TLS_REF; // fgMorphField will handle the transformation
13169 op1 = gtNewOperNode(GT_ADDR, (var_types)TYP_I_IMPL, op1);
13173 fieldInfo.fieldAccessor = CORINFO_FIELD_STATIC_ADDR_HELPER;
13178 case CORINFO_FIELD_STATIC_ADDR_HELPER:
13179 case CORINFO_FIELD_INSTANCE_HELPER:
13180 case CORINFO_FIELD_INSTANCE_ADDR_HELPER:
13181 op1 = gtNewRefCOMfield(obj, &resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo, lclTyp,
13186 case CORINFO_FIELD_STATIC_ADDRESS:
13187 // Replace static read-only fields with constant if possible
13188 if ((aflags & CORINFO_ACCESS_GET) && (fieldInfo.fieldFlags & CORINFO_FLG_FIELD_FINAL) &&
13189 !(fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC_IN_HEAP) &&
13190 (varTypeIsIntegral(lclTyp) || varTypeIsFloating(lclTyp)))
13192 CorInfoInitClassResult initClassResult =
13193 info.compCompHnd->initClass(resolvedToken.hField, info.compMethodHnd,
13194 impTokenLookupContextHandle);
13196 if (initClassResult & CORINFO_INITCLASS_INITIALIZED)
13198 void** pFldAddr = nullptr;
13200 info.compCompHnd->getFieldAddress(resolvedToken.hField, (void**)&pFldAddr);
13202 // We should always be able to access this static's address directly
13203 assert(pFldAddr == nullptr);
13205 op1 = impImportStaticReadOnlyField(fldAddr, lclTyp);
13212 case CORINFO_FIELD_STATIC_RVA_ADDRESS:
13213 case CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER:
13214 case CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER:
13215 #if COR_JIT_EE_VERSION > 460
13216 case CORINFO_FIELD_STATIC_READYTORUN_HELPER:
13218 op1 = impImportStaticFieldAccess(&resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo,
13222 case CORINFO_FIELD_INTRINSIC_ZERO:
13224 assert(aflags & CORINFO_ACCESS_GET);
13225 op1 = gtNewIconNode(0, lclTyp);
13230 case CORINFO_FIELD_INTRINSIC_EMPTY_STRING:
13232 assert(aflags & CORINFO_ACCESS_GET);
13235 InfoAccessType iat = info.compCompHnd->emptyStringLiteral(&pValue);
13236 op1 = gtNewStringLiteralNode(iat, pValue);
13242 assert(!"Unexpected fieldAccessor");
13245 if (!isLoadAddress)
13248 if (prefixFlags & PREFIX_VOLATILE)
13250 op1->gtFlags |= GTF_DONT_CSE; // Can't CSE a volatile
13251 op1->gtFlags |= GTF_ORDER_SIDEEFF; // Prevent this from being reordered
13255 assert((op1->OperGet() == GT_FIELD) || (op1->OperGet() == GT_IND) ||
13256 (op1->OperGet() == GT_OBJ));
13257 op1->gtFlags |= GTF_IND_VOLATILE;
13261 if (prefixFlags & PREFIX_UNALIGNED)
13265 assert((op1->OperGet() == GT_FIELD) || (op1->OperGet() == GT_IND) ||
13266 (op1->OperGet() == GT_OBJ));
13267 op1->gtFlags |= GTF_IND_UNALIGNED;
13272 /* Check if the class needs explicit initialization */
13274 if (fieldInfo.fieldFlags & CORINFO_FLG_FIELD_INITCLASS)
13276 GenTreePtr helperNode = impInitClass(&resolvedToken);
13277 if (compDonotInline())
13281 if (helperNode != nullptr)
13283 op1 = gtNewOperNode(GT_COMMA, op1->TypeGet(), helperNode, op1);
13288 impPushOnStack(op1, tiRetVal);
13296 BOOL isStoreStatic = (opcode == CEE_STSFLD);
13298 CORINFO_CLASS_HANDLE fieldClsHnd; // class of the field (if it's a ref type)
13300 /* Get the CP_Fieldref index */
13302 assertImp(sz == sizeof(unsigned));
13304 _impResolveToken(CORINFO_TOKENKIND_Field);
13306 JITDUMP(" %08X", resolvedToken.token);
13308 int aflags = CORINFO_ACCESS_SET;
13309 GenTreePtr obj = nullptr;
13310 typeInfo* tiObj = nullptr;
13313 /* Pull the value from the stack */
13314 op2 = impPopStack(tiVal);
13315 clsHnd = tiVal.GetClassHandle();
13317 if (opcode == CEE_STFLD)
13319 tiObj = &impStackTop().seTypeInfo;
13320 obj = impPopStack().val;
13322 if (impIsThis(obj))
13324 aflags |= CORINFO_ACCESS_THIS;
13326 // An optimization for Contextful classes:
13327 // we unwrap the proxy when we have a 'this reference'
13329 if (info.compUnwrapContextful)
13331 aflags |= CORINFO_ACCESS_UNWRAP;
13336 eeGetFieldInfo(&resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo);
13338 // Figure out the type of the member. We always call canAccessField, so you always need this
13340 CorInfoType ciType = fieldInfo.fieldType;
13341 fieldClsHnd = fieldInfo.structType;
13343 lclTyp = JITtype2varType(ciType);
13345 if (compIsForInlining())
13347 /* Is this a 'special' (COM) field? or a TLS ref static field?, field stored int GC heap? or
13348 * per-inst static? */
13350 switch (fieldInfo.fieldAccessor)
13352 case CORINFO_FIELD_INSTANCE_HELPER:
13353 case CORINFO_FIELD_INSTANCE_ADDR_HELPER:
13354 case CORINFO_FIELD_STATIC_ADDR_HELPER:
13355 case CORINFO_FIELD_STATIC_TLS:
13357 compInlineResult->NoteFatal(InlineObservation::CALLEE_STFLD_NEEDS_HELPER);
13360 case CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER:
13361 #if COR_JIT_EE_VERSION > 460
13362 case CORINFO_FIELD_STATIC_READYTORUN_HELPER:
13365 /* We may be able to inline the field accessors in specific instantiations of generic
13367 compInlineResult->NoteFatal(InlineObservation::CALLSITE_STFLD_NEEDS_HELPER);
13375 impHandleAccessAllowed(fieldInfo.accessAllowed, &fieldInfo.accessCalloutHelper);
13377 if (tiVerificationNeeded)
13379 verVerifyField(&resolvedToken, fieldInfo, tiObj, TRUE);
13380 typeInfo fieldType = verMakeTypeInfo(ciType, fieldClsHnd);
13381 Verify(tiCompatibleWith(tiVal, fieldType.NormaliseForStack(), true), "type mismatch");
13385 // tiVerificationNeed is false.
13386 // Raise InvalidProgramException if static store accesses non-static field
13387 if (isStoreStatic && ((fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC) == 0))
13389 BADCODE("static access on an instance field");
13393 // We are using stfld on a static field.
13394 // We allow it, but need to eval any side-effects for obj
13395 if ((fieldInfo.fieldFlags & CORINFO_FLG_FIELD_STATIC) && obj != nullptr)
13397 if (obj->gtFlags & GTF_SIDE_EFFECT)
13399 obj = gtUnusedValNode(obj);
13400 impAppendTree(obj, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
13405 /* Preserve 'small' int types */
13406 if (lclTyp > TYP_INT)
13408 lclTyp = genActualType(lclTyp);
13411 switch (fieldInfo.fieldAccessor)
13413 case CORINFO_FIELD_INSTANCE:
13414 #ifdef FEATURE_READYTORUN_COMPILER
13415 case CORINFO_FIELD_INSTANCE_WITH_BASE:
13418 obj = impCheckForNullPointer(obj);
13420 /* Create the data member node */
13421 op1 = gtNewFieldRef(lclTyp, resolvedToken.hField, obj, fieldInfo.offset);
13422 DWORD typeFlags = info.compCompHnd->getClassAttribs(resolvedToken.hClass);
13423 if (StructHasOverlappingFields(typeFlags))
13425 op1->gtField.gtFldMayOverlap = true;
13428 #ifdef FEATURE_READYTORUN_COMPILER
13429 if (fieldInfo.fieldAccessor == CORINFO_FIELD_INSTANCE_WITH_BASE)
13431 op1->gtField.gtFieldLookup = fieldInfo.fieldLookup;
13435 op1->gtFlags |= (obj->gtFlags & GTF_GLOB_EFFECT);
13437 if (fgAddrCouldBeNull(obj))
13439 op1->gtFlags |= GTF_EXCEPT;
13442 // If gtFldObj is a BYREF then our target is a value class and
13443 // it could point anywhere, example a boxed class static int
13444 if (obj->gtType == TYP_BYREF)
13446 op1->gtFlags |= GTF_IND_TGTANYWHERE;
13449 if (compIsForInlining() &&
13450 impInlineIsGuaranteedThisDerefBeforeAnySideEffects(op2, obj, impInlineInfo->inlArgInfo))
13452 impInlineInfo->thisDereferencedFirst = true;
13457 case CORINFO_FIELD_STATIC_TLS:
13458 #ifdef _TARGET_X86_
13459 // Legacy TLS access is implemented as intrinsic on x86 only
13461 /* Create the data member node */
13462 op1 = gtNewFieldRef(lclTyp, resolvedToken.hField, NULL, fieldInfo.offset);
13463 op1->gtFlags |= GTF_IND_TLS_REF; // fgMorphField will handle the transformation
13467 fieldInfo.fieldAccessor = CORINFO_FIELD_STATIC_ADDR_HELPER;
13472 case CORINFO_FIELD_STATIC_ADDR_HELPER:
13473 case CORINFO_FIELD_INSTANCE_HELPER:
13474 case CORINFO_FIELD_INSTANCE_ADDR_HELPER:
13475 op1 = gtNewRefCOMfield(obj, &resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo, lclTyp,
13479 case CORINFO_FIELD_STATIC_ADDRESS:
13480 case CORINFO_FIELD_STATIC_RVA_ADDRESS:
13481 case CORINFO_FIELD_STATIC_SHARED_STATIC_HELPER:
13482 case CORINFO_FIELD_STATIC_GENERICS_STATIC_HELPER:
13483 #if COR_JIT_EE_VERSION > 460
13484 case CORINFO_FIELD_STATIC_READYTORUN_HELPER:
13486 op1 = impImportStaticFieldAccess(&resolvedToken, (CORINFO_ACCESS_FLAGS)aflags, &fieldInfo,
13491 assert(!"Unexpected fieldAccessor");
13494 // Create the member assignment, unless we have a struct.
13495 // TODO-1stClassStructs: This could be limited to TYP_STRUCT, to avoid extra copies.
13496 bool deferStructAssign = varTypeIsStruct(lclTyp);
13498 if (!deferStructAssign)
13500 if (prefixFlags & PREFIX_VOLATILE)
13502 assert((op1->OperGet() == GT_FIELD) || (op1->OperGet() == GT_IND));
13503 op1->gtFlags |= GTF_DONT_CSE; // Can't CSE a volatile
13504 op1->gtFlags |= GTF_ORDER_SIDEEFF; // Prevent this from being reordered
13505 op1->gtFlags |= GTF_IND_VOLATILE;
13507 if (prefixFlags & PREFIX_UNALIGNED)
13509 assert((op1->OperGet() == GT_FIELD) || (op1->OperGet() == GT_IND));
13510 op1->gtFlags |= GTF_IND_UNALIGNED;
13513 /* V4.0 allows assignment of i4 constant values to i8 type vars when IL verifier is bypassed (full
13515 apps). The reason this works is that JIT stores an i4 constant in Gentree union during
13517 and reads from the union as if it were a long during code generation. Though this can potentially
13518 read garbage, one can get lucky to have this working correctly.
13520 This code pattern is generated by Dev10 MC++ compiler while storing to fields when compiled with
13522 switch (default when compiling retail configs in Dev10) and a customer app has taken a dependency
13524 it. To be backward compatible, we will explicitly add an upward cast here so that it works
13528 Note that this is limited to x86 alone as thereis no back compat to be addressed for Arm JIT for
13531 CLANG_FORMAT_COMMENT_ANCHOR;
13533 #ifdef _TARGET_X86_
13534 if (op1->TypeGet() != op2->TypeGet() && op2->OperIsConst() && varTypeIsIntOrI(op2->TypeGet()) &&
13535 varTypeIsLong(op1->TypeGet()))
13537 op2 = gtNewCastNode(op1->TypeGet(), op2, op1->TypeGet());
13541 #ifdef _TARGET_64BIT_
13542 // Automatic upcast for a GT_CNS_INT into TYP_I_IMPL
13543 if ((op2->OperGet() == GT_CNS_INT) && varTypeIsI(lclTyp) && !varTypeIsI(op2->gtType))
13545 op2->gtType = TYP_I_IMPL;
13549 // Allow a downcast of op2 from TYP_I_IMPL into a 32-bit Int for x86 JIT compatiblity
13551 if (varTypeIsI(op2->gtType) && (genActualType(lclTyp) == TYP_INT))
13553 op2 = gtNewCastNode(TYP_INT, op2, TYP_INT);
13555 // Allow an upcast of op2 from a 32-bit Int into TYP_I_IMPL for x86 JIT compatiblity
13557 if (varTypeIsI(lclTyp) && (genActualType(op2->gtType) == TYP_INT))
13559 op2 = gtNewCastNode(TYP_I_IMPL, op2, TYP_I_IMPL);
13564 #if !FEATURE_X87_DOUBLES
13565 // We can generate an assignment to a TYP_FLOAT from a TYP_DOUBLE
13566 // We insert a cast to the dest 'op1' type
13568 if ((op1->TypeGet() != op2->TypeGet()) && varTypeIsFloating(op1->gtType) &&
13569 varTypeIsFloating(op2->gtType))
13571 op2 = gtNewCastNode(op1->TypeGet(), op2, op1->TypeGet());
13573 #endif // !FEATURE_X87_DOUBLES
13575 op1 = gtNewAssignNode(op1, op2);
13577 /* Mark the expression as containing an assignment */
13579 op1->gtFlags |= GTF_ASG;
13582 /* Check if the class needs explicit initialization */
13584 if (fieldInfo.fieldFlags & CORINFO_FLG_FIELD_INITCLASS)
13586 GenTreePtr helperNode = impInitClass(&resolvedToken);
13587 if (compDonotInline())
13591 if (helperNode != nullptr)
13593 op1 = gtNewOperNode(GT_COMMA, op1->TypeGet(), helperNode, op1);
13597 /* stfld can interfere with value classes (consider the sequence
13598 ldloc, ldloca, ..., stfld, stloc). We will be conservative and
13599 spill all value class references from the stack. */
13601 if (obj && ((obj->gtType == TYP_BYREF) || (obj->gtType == TYP_I_IMPL)))
13605 if (impIsValueType(tiObj))
13607 impSpillEvalStack();
13611 impSpillValueClasses();
13615 /* Spill any refs to the same member from the stack */
13617 impSpillLclRefs((ssize_t)resolvedToken.hField);
13619 /* stsfld also interferes with indirect accesses (for aliased
13620 statics) and calls. But don't need to spill other statics
13621 as we have explicitly spilled this particular static field. */
13623 impSpillSideEffects(false, (unsigned)CHECK_SPILL_ALL DEBUGARG("spill side effects before STFLD"));
13625 if (deferStructAssign)
13627 op1 = impAssignStruct(op1, op2, clsHnd, (unsigned)CHECK_SPILL_ALL);
13635 /* Get the class type index operand */
13637 _impResolveToken(CORINFO_TOKENKIND_Newarr);
13639 JITDUMP(" %08X", resolvedToken.token);
13641 if (!opts.IsReadyToRun())
13643 // Need to restore array classes before creating array objects on the heap
13644 op1 = impTokenToHandle(&resolvedToken, nullptr, TRUE /*mustRestoreHandle*/);
13645 if (op1 == nullptr)
13646 { // compDonotInline()
13651 if (tiVerificationNeeded)
13653 // As per ECMA 'numElems' specified can be either int32 or native int.
13654 Verify(impStackTop().seTypeInfo.IsIntOrNativeIntType(), "bad bound");
13656 CORINFO_CLASS_HANDLE elemTypeHnd;
13657 info.compCompHnd->getChildType(resolvedToken.hClass, &elemTypeHnd);
13658 Verify(elemTypeHnd == nullptr ||
13659 !(info.compCompHnd->getClassAttribs(elemTypeHnd) & CORINFO_FLG_CONTAINS_STACK_PTR),
13660 "array of byref-like type");
13661 tiRetVal = verMakeTypeInfo(resolvedToken.hClass);
13664 accessAllowedResult =
13665 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
13666 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
13668 /* Form the arglist: array class handle, size */
13669 op2 = impPopStack().val;
13670 assertImp(genActualTypeIsIntOrI(op2->gtType));
13672 #ifdef FEATURE_READYTORUN_COMPILER
13673 if (opts.IsReadyToRun())
13675 op1 = impReadyToRunHelperToTree(&resolvedToken, CORINFO_HELP_READYTORUN_NEWARR_1, TYP_REF,
13676 gtNewArgList(op2));
13677 usingReadyToRunHelper = (op1 != nullptr);
13679 if (!usingReadyToRunHelper)
13681 // TODO: ReadyToRun: When generic dictionary lookups are necessary, replace the lookup call
13682 // and the newarr call with a single call to a dynamic R2R cell that will:
13683 // 1) Load the context
13684 // 2) Perform the generic dictionary lookup and caching, and generate the appropriate stub
13685 // 3) Allocate the new array
13686 // Reason: performance (today, we'll always use the slow helper for the R2R generics case)
13688 // Need to restore array classes before creating array objects on the heap
13689 op1 = impTokenToHandle(&resolvedToken, nullptr, TRUE /*mustRestoreHandle*/);
13690 if (op1 == nullptr)
13691 { // compDonotInline()
13697 if (!usingReadyToRunHelper)
13700 args = gtNewArgList(op1, op2);
13702 /* Create a call to 'new' */
13704 // Note that this only works for shared generic code because the same helper is used for all
13705 // reference array types
13707 gtNewHelperCallNode(info.compCompHnd->getNewArrHelper(resolvedToken.hClass), TYP_REF, 0, args);
13710 op1->gtCall.compileTimeHelperArgumentHandle = (CORINFO_GENERIC_HANDLE)resolvedToken.hClass;
13712 /* Remember that this basic block contains 'new' of an sd array */
13714 block->bbFlags |= BBF_HAS_NEWARRAY;
13715 optMethodFlags |= OMF_HAS_NEWARRAY;
13717 /* Push the result of the call on the stack */
13719 impPushOnStack(op1, tiRetVal);
13726 assert(!compIsForInlining());
13728 if (tiVerificationNeeded)
13730 Verify(false, "bad opcode");
13733 // We don't allow locallocs inside handlers
13734 if (block->hasHndIndex())
13736 BADCODE("Localloc can't be inside handler");
13739 /* The FP register may not be back to the original value at the end
13740 of the method, even if the frame size is 0, as localloc may
13741 have modified it. So we will HAVE to reset it */
13743 compLocallocUsed = true;
13744 setNeedsGSSecurityCookie();
13746 // Get the size to allocate
13748 op2 = impPopStack().val;
13749 assertImp(genActualTypeIsIntOrI(op2->gtType));
13751 if (verCurrentState.esStackDepth != 0)
13753 BADCODE("Localloc can only be used when the stack is empty");
13756 op1 = gtNewOperNode(GT_LCLHEAP, TYP_I_IMPL, op2);
13758 // May throw a stack overflow exception. Obviously, we don't want locallocs to be CSE'd.
13760 op1->gtFlags |= (GTF_EXCEPT | GTF_DONT_CSE);
13762 impPushOnStack(op1, tiRetVal);
13767 /* Get the type token */
13768 assertImp(sz == sizeof(unsigned));
13770 _impResolveToken(CORINFO_TOKENKIND_Casting);
13772 JITDUMP(" %08X", resolvedToken.token);
13774 if (!opts.IsReadyToRun())
13776 op2 = impTokenToHandle(&resolvedToken, nullptr, FALSE);
13777 if (op2 == nullptr)
13778 { // compDonotInline()
13783 if (tiVerificationNeeded)
13785 Verify(impStackTop().seTypeInfo.IsObjRef(), "obj reference needed");
13786 // Even if this is a value class, we know it is boxed.
13787 tiRetVal = typeInfo(TI_REF, resolvedToken.hClass);
13789 accessAllowedResult =
13790 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
13791 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
13793 op1 = impPopStack().val;
13795 #ifdef FEATURE_READYTORUN_COMPILER
13796 if (opts.IsReadyToRun())
13798 GenTreePtr opLookup =
13799 impReadyToRunHelperToTree(&resolvedToken, CORINFO_HELP_READYTORUN_ISINSTANCEOF, TYP_REF,
13800 gtNewArgList(op1));
13801 usingReadyToRunHelper = (opLookup != nullptr);
13802 op1 = (usingReadyToRunHelper ? opLookup : op1);
13804 if (!usingReadyToRunHelper)
13806 // TODO: ReadyToRun: When generic dictionary lookups are necessary, replace the lookup call
13807 // and the isinstanceof_any call with a single call to a dynamic R2R cell that will:
13808 // 1) Load the context
13809 // 2) Perform the generic dictionary lookup and caching, and generate the appropriate stub
13810 // 3) Perform the 'is instance' check on the input object
13811 // Reason: performance (today, we'll always use the slow helper for the R2R generics case)
13813 op2 = impTokenToHandle(&resolvedToken, nullptr, FALSE);
13814 if (op2 == nullptr)
13815 { // compDonotInline()
13821 if (!usingReadyToRunHelper)
13824 op1 = impCastClassOrIsInstToTree(op1, op2, &resolvedToken, false);
13826 if (compDonotInline())
13831 impPushOnStack(op1, tiRetVal);
13835 case CEE_REFANYVAL:
13837 // get the class handle and make a ICON node out of it
13839 _impResolveToken(CORINFO_TOKENKIND_Class);
13841 JITDUMP(" %08X", resolvedToken.token);
13843 op2 = impTokenToHandle(&resolvedToken);
13844 if (op2 == nullptr)
13845 { // compDonotInline()
13849 if (tiVerificationNeeded)
13851 Verify(typeInfo::AreEquivalent(impStackTop().seTypeInfo, verMakeTypeInfo(impGetRefAnyClass())),
13853 tiRetVal = verMakeTypeInfo(resolvedToken.hClass).MakeByRef();
13856 op1 = impPopStack().val;
13857 // make certain it is normalized;
13858 op1 = impNormStructVal(op1, impGetRefAnyClass(), (unsigned)CHECK_SPILL_ALL);
13860 // Call helper GETREFANY(classHandle, op1);
13861 args = gtNewArgList(op2, op1);
13862 op1 = gtNewHelperCallNode(CORINFO_HELP_GETREFANY, TYP_BYREF, 0, args);
13864 impPushOnStack(op1, tiRetVal);
13867 case CEE_REFANYTYPE:
13869 if (tiVerificationNeeded)
13871 Verify(typeInfo::AreEquivalent(impStackTop().seTypeInfo, verMakeTypeInfo(impGetRefAnyClass())),
13875 op1 = impPopStack().val;
13877 // make certain it is normalized;
13878 op1 = impNormStructVal(op1, impGetRefAnyClass(), (unsigned)CHECK_SPILL_ALL);
13880 if (op1->gtOper == GT_OBJ)
13882 // Get the address of the refany
13883 op1 = op1->gtOp.gtOp1;
13885 // Fetch the type from the correct slot
13886 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1,
13887 gtNewIconNode(offsetof(CORINFO_RefAny, type), TYP_I_IMPL));
13888 op1 = gtNewOperNode(GT_IND, TYP_BYREF, op1);
13892 assertImp(op1->gtOper == GT_MKREFANY);
13894 // The pointer may have side-effects
13895 if (op1->gtOp.gtOp1->gtFlags & GTF_SIDE_EFFECT)
13897 impAppendTree(op1->gtOp.gtOp1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
13899 impNoteLastILoffs();
13903 // We already have the class handle
13904 op1 = op1->gtOp.gtOp2;
13907 // convert native TypeHandle to RuntimeTypeHandle
13909 GenTreeArgList* helperArgs = gtNewArgList(op1);
13911 op1 = gtNewHelperCallNode(CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE_MAYBENULL, TYP_STRUCT, GTF_EXCEPT,
13914 // The handle struct is returned in register
13915 op1->gtCall.gtReturnType = TYP_REF;
13917 tiRetVal = typeInfo(TI_STRUCT, impGetTypeHandleClass());
13920 impPushOnStack(op1, tiRetVal);
13925 /* Get the Class index */
13926 assertImp(sz == sizeof(unsigned));
13927 lastLoadToken = codeAddr;
13928 _impResolveToken(CORINFO_TOKENKIND_Ldtoken);
13930 tokenType = info.compCompHnd->getTokenTypeAsHandle(&resolvedToken);
13932 op1 = impTokenToHandle(&resolvedToken, nullptr, TRUE);
13933 if (op1 == nullptr)
13934 { // compDonotInline()
13938 helper = CORINFO_HELP_TYPEHANDLE_TO_RUNTIMETYPE;
13939 assert(resolvedToken.hClass != nullptr);
13941 if (resolvedToken.hMethod != nullptr)
13943 helper = CORINFO_HELP_METHODDESC_TO_STUBRUNTIMEMETHOD;
13945 else if (resolvedToken.hField != nullptr)
13947 helper = CORINFO_HELP_FIELDDESC_TO_STUBRUNTIMEFIELD;
13950 GenTreeArgList* helperArgs = gtNewArgList(op1);
13952 op1 = gtNewHelperCallNode(helper, TYP_STRUCT, GTF_EXCEPT, helperArgs);
13954 // The handle struct is returned in register
13955 op1->gtCall.gtReturnType = TYP_REF;
13957 tiRetVal = verMakeTypeInfo(tokenType);
13958 impPushOnStack(op1, tiRetVal);
13963 case CEE_UNBOX_ANY:
13965 /* Get the Class index */
13966 assertImp(sz == sizeof(unsigned));
13968 _impResolveToken(CORINFO_TOKENKIND_Class);
13970 JITDUMP(" %08X", resolvedToken.token);
13972 BOOL runtimeLookup;
13973 op2 = impTokenToHandle(&resolvedToken, &runtimeLookup);
13974 if (op2 == nullptr)
13975 { // compDonotInline()
13979 // Run this always so we can get access exceptions even with SkipVerification.
13980 accessAllowedResult =
13981 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
13982 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
13984 if (opcode == CEE_UNBOX_ANY && !eeIsValueClass(resolvedToken.hClass))
13986 if (tiVerificationNeeded)
13988 typeInfo tiUnbox = impStackTop().seTypeInfo;
13989 Verify(tiUnbox.IsObjRef(), "bad unbox.any arg");
13990 tiRetVal = verMakeTypeInfo(resolvedToken.hClass);
13991 tiRetVal.NormaliseForStack();
13993 op1 = impPopStack().val;
13997 /* Pop the object and create the unbox helper call */
13998 /* You might think that for UNBOX_ANY we need to push a different */
13999 /* (non-byref) type, but here we're making the tiRetVal that is used */
14000 /* for the intermediate pointer which we then transfer onto the OBJ */
14001 /* instruction. OBJ then creates the appropriate tiRetVal. */
14002 if (tiVerificationNeeded)
14004 typeInfo tiUnbox = impStackTop().seTypeInfo;
14005 Verify(tiUnbox.IsObjRef(), "Bad unbox arg");
14007 tiRetVal = verMakeTypeInfo(resolvedToken.hClass);
14008 Verify(tiRetVal.IsValueClass(), "not value class");
14009 tiRetVal.MakeByRef();
14011 // We always come from an objref, so this is safe byref
14012 tiRetVal.SetIsPermanentHomeByRef();
14013 tiRetVal.SetIsReadonlyByRef();
14016 op1 = impPopStack().val;
14017 assertImp(op1->gtType == TYP_REF);
14019 helper = info.compCompHnd->getUnBoxHelper(resolvedToken.hClass);
14020 assert(helper == CORINFO_HELP_UNBOX || helper == CORINFO_HELP_UNBOX_NULLABLE);
14022 // We only want to expand inline the normal UNBOX helper;
14023 expandInline = (helper == CORINFO_HELP_UNBOX);
14027 if (compCurBB->isRunRarely())
14029 expandInline = false; // not worth the code expansion
14035 // we are doing normal unboxing
14036 // inline the common case of the unbox helper
14037 // UNBOX(exp) morphs into
14038 // clone = pop(exp);
14039 // ((*clone == typeToken) ? nop : helper(clone, typeToken));
14040 // push(clone + sizeof(void*))
14042 GenTreePtr cloneOperand;
14043 op1 = impCloneExpr(op1, &cloneOperand, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
14044 nullptr DEBUGARG("inline UNBOX clone1"));
14045 op1 = gtNewOperNode(GT_IND, TYP_I_IMPL, op1);
14047 GenTreePtr condBox = gtNewOperNode(GT_EQ, TYP_INT, op1, op2);
14049 op1 = impCloneExpr(cloneOperand, &cloneOperand, NO_CLASS_HANDLE, (unsigned)CHECK_SPILL_ALL,
14050 nullptr DEBUGARG("inline UNBOX clone2"));
14051 op2 = impTokenToHandle(&resolvedToken);
14052 if (op2 == nullptr)
14053 { // compDonotInline()
14056 args = gtNewArgList(op2, op1);
14057 op1 = gtNewHelperCallNode(helper, TYP_VOID, 0, args);
14059 op1 = new (this, GT_COLON) GenTreeColon(TYP_VOID, gtNewNothingNode(), op1);
14060 op1 = gtNewQmarkNode(TYP_VOID, condBox, op1);
14061 condBox->gtFlags |= GTF_RELOP_QMARK;
14063 // QMARK nodes cannot reside on the evaluation stack. Because there
14064 // may be other trees on the evaluation stack that side-effect the
14065 // sources of the UNBOX operation we must spill the stack.
14067 impAppendTree(op1, (unsigned)CHECK_SPILL_ALL, impCurStmtOffs);
14069 // Create the address-expression to reference past the object header
14070 // to the beginning of the value-type. Today this means adjusting
14071 // past the base of the objects vtable field which is pointer sized.
14073 op2 = gtNewIconNode(sizeof(void*), TYP_I_IMPL);
14074 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, cloneOperand, op2);
14078 unsigned callFlags = (helper == CORINFO_HELP_UNBOX) ? 0 : GTF_EXCEPT;
14080 // Don't optimize, just call the helper and be done with it
14081 args = gtNewArgList(op2, op1);
14082 op1 = gtNewHelperCallNode(helper,
14083 (var_types)((helper == CORINFO_HELP_UNBOX) ? TYP_BYREF : TYP_STRUCT),
14087 assert(helper == CORINFO_HELP_UNBOX && op1->gtType == TYP_BYREF || // Unbox helper returns a byref.
14088 helper == CORINFO_HELP_UNBOX_NULLABLE &&
14089 varTypeIsStruct(op1) // UnboxNullable helper returns a struct.
14093 ----------------------------------------------------------------------
14096 | \ | CORINFO_HELP_UNBOX | CORINFO_HELP_UNBOX_NULLABLE |
14097 | \ | (which returns a BYREF) | (which returns a STRUCT) | |
14099 |---------------------------------------------------------------------
14100 | UNBOX | push the BYREF | spill the STRUCT to a local, |
14101 | | | push the BYREF to this local |
14102 |---------------------------------------------------------------------
14103 | UNBOX_ANY | push a GT_OBJ of | push the STRUCT |
14104 | | the BYREF | For Linux when the |
14105 | | | struct is returned in two |
14106 | | | registers create a temp |
14107 | | | which address is passed to |
14108 | | | the unbox_nullable helper. |
14109 |---------------------------------------------------------------------
14112 if (opcode == CEE_UNBOX)
14114 if (helper == CORINFO_HELP_UNBOX_NULLABLE)
14116 // Unbox nullable helper returns a struct type.
14117 // We need to spill it to a temp so than can take the address of it.
14118 // Here we need unsafe value cls check, since the address of struct is taken to be used
14119 // further along and potetially be exploitable.
14121 unsigned tmp = lvaGrabTemp(true DEBUGARG("UNBOXing a nullable"));
14122 lvaSetStruct(tmp, resolvedToken.hClass, true /* unsafe value cls check */);
14124 op2 = gtNewLclvNode(tmp, TYP_STRUCT);
14125 op1 = impAssignStruct(op2, op1, resolvedToken.hClass, (unsigned)CHECK_SPILL_ALL);
14126 assert(op1->gtType == TYP_VOID); // We must be assigning the return struct to the temp.
14128 op2 = gtNewLclvNode(tmp, TYP_STRUCT);
14129 op2 = gtNewOperNode(GT_ADDR, TYP_BYREF, op2);
14130 op1 = gtNewOperNode(GT_COMMA, TYP_BYREF, op1, op2);
14133 assert(op1->gtType == TYP_BYREF);
14134 assert(!tiVerificationNeeded || tiRetVal.IsByRef());
14138 assert(opcode == CEE_UNBOX_ANY);
14140 if (helper == CORINFO_HELP_UNBOX)
14142 // Normal unbox helper returns a TYP_BYREF.
14143 impPushOnStack(op1, tiRetVal);
14148 assert(helper == CORINFO_HELP_UNBOX_NULLABLE && "Make sure the helper is nullable!");
14150 #if FEATURE_MULTIREG_RET
14152 if (varTypeIsStruct(op1) && IsMultiRegReturnedType(resolvedToken.hClass))
14154 // Unbox nullable helper returns a TYP_STRUCT.
14155 // For the multi-reg case we need to spill it to a temp so that
14156 // we can pass the address to the unbox_nullable jit helper.
14158 unsigned tmp = lvaGrabTemp(true DEBUGARG("UNBOXing a register returnable nullable"));
14159 lvaTable[tmp].lvIsMultiRegArg = true;
14160 lvaSetStruct(tmp, resolvedToken.hClass, true /* unsafe value cls check */);
14162 op2 = gtNewLclvNode(tmp, TYP_STRUCT);
14163 op1 = impAssignStruct(op2, op1, resolvedToken.hClass, (unsigned)CHECK_SPILL_ALL);
14164 assert(op1->gtType == TYP_VOID); // We must be assigning the return struct to the temp.
14166 op2 = gtNewLclvNode(tmp, TYP_STRUCT);
14167 op2 = gtNewOperNode(GT_ADDR, TYP_BYREF, op2);
14168 op1 = gtNewOperNode(GT_COMMA, TYP_BYREF, op1, op2);
14170 // In this case the return value of the unbox helper is TYP_BYREF.
14171 // Make sure the right type is placed on the operand type stack.
14172 impPushOnStack(op1, tiRetVal);
14174 // Load the struct.
14177 assert(op1->gtType == TYP_BYREF);
14178 assert(!tiVerificationNeeded || tiRetVal.IsByRef());
14184 #endif // !FEATURE_MULTIREG_RET
14187 // If non register passable struct we have it materialized in the RetBuf.
14188 assert(op1->gtType == TYP_STRUCT);
14189 tiRetVal = verMakeTypeInfo(resolvedToken.hClass);
14190 assert(tiRetVal.IsValueClass());
14194 impPushOnStack(op1, tiRetVal);
14200 /* Get the Class index */
14201 assertImp(sz == sizeof(unsigned));
14203 _impResolveToken(CORINFO_TOKENKIND_Box);
14205 JITDUMP(" %08X", resolvedToken.token);
14207 if (tiVerificationNeeded)
14209 typeInfo tiActual = impStackTop().seTypeInfo;
14210 typeInfo tiBox = verMakeTypeInfo(resolvedToken.hClass);
14212 Verify(verIsBoxable(tiBox), "boxable type expected");
14214 // check the class constraints of the boxed type in case we are boxing an uninitialized value
14215 Verify(info.compCompHnd->satisfiesClassConstraints(resolvedToken.hClass),
14216 "boxed type has unsatisfied class constraints");
14218 Verify(tiCompatibleWith(tiActual, tiBox.NormaliseForStack(), true), "type mismatch");
14220 // Observation: the following code introduces a boxed value class on the stack, but,
14221 // according to the ECMA spec, one would simply expect: tiRetVal =
14222 // typeInfo(TI_REF,impGetObjectClass());
14224 // Push the result back on the stack,
14225 // even if clsHnd is a value class we want the TI_REF
14226 // we call back to the EE to get find out what hte type we should push (for nullable<T> we push T)
14227 tiRetVal = typeInfo(TI_REF, info.compCompHnd->getTypeForBox(resolvedToken.hClass));
14230 accessAllowedResult =
14231 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
14232 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
14234 // Note BOX can be used on things that are not value classes, in which
14235 // case we get a NOP. However the verifier's view of the type on the
14236 // stack changes (in generic code a 'T' becomes a 'boxed T')
14237 if (!eeIsValueClass(resolvedToken.hClass))
14239 verCurrentState.esStack[verCurrentState.esStackDepth - 1].seTypeInfo = tiRetVal;
14243 // Look ahead for unbox.any
14244 if (codeAddr + (sz + 1 + sizeof(mdToken)) <= codeEndp && codeAddr[sz] == CEE_UNBOX_ANY)
14246 DWORD classAttribs = info.compCompHnd->getClassAttribs(resolvedToken.hClass);
14247 if (!(classAttribs & CORINFO_FLG_SHAREDINST))
14249 CORINFO_RESOLVED_TOKEN unboxResolvedToken;
14251 impResolveToken(codeAddr + (sz + 1), &unboxResolvedToken, CORINFO_TOKENKIND_Class);
14253 if (unboxResolvedToken.hClass == resolvedToken.hClass)
14255 // Skip the next unbox.any instruction
14256 sz += sizeof(mdToken) + 1;
14262 impImportAndPushBox(&resolvedToken);
14263 if (compDonotInline())
14272 /* Get the Class index */
14273 assertImp(sz == sizeof(unsigned));
14275 _impResolveToken(CORINFO_TOKENKIND_Class);
14277 JITDUMP(" %08X", resolvedToken.token);
14279 if (tiVerificationNeeded)
14281 tiRetVal = typeInfo(TI_INT);
14284 op1 = gtNewIconNode(info.compCompHnd->getClassSize(resolvedToken.hClass));
14285 impPushOnStack(op1, tiRetVal);
14288 case CEE_CASTCLASS:
14290 /* Get the Class index */
14292 assertImp(sz == sizeof(unsigned));
14294 _impResolveToken(CORINFO_TOKENKIND_Casting);
14296 JITDUMP(" %08X", resolvedToken.token);
14298 if (!opts.IsReadyToRun())
14300 op2 = impTokenToHandle(&resolvedToken, nullptr, FALSE);
14301 if (op2 == nullptr)
14302 { // compDonotInline()
14307 if (tiVerificationNeeded)
14309 Verify(impStackTop().seTypeInfo.IsObjRef(), "object ref expected");
14311 tiRetVal = typeInfo(TI_REF, resolvedToken.hClass);
14314 accessAllowedResult =
14315 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
14316 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
14318 op1 = impPopStack().val;
14320 /* Pop the address and create the 'checked cast' helper call */
14322 // At this point we expect typeRef to contain the token, op1 to contain the value being cast,
14323 // and op2 to contain code that creates the type handle corresponding to typeRef
14326 #ifdef FEATURE_READYTORUN_COMPILER
14327 if (opts.IsReadyToRun())
14329 GenTreePtr opLookup = impReadyToRunHelperToTree(&resolvedToken, CORINFO_HELP_READYTORUN_CHKCAST,
14330 TYP_REF, gtNewArgList(op1));
14331 usingReadyToRunHelper = (opLookup != nullptr);
14332 op1 = (usingReadyToRunHelper ? opLookup : op1);
14334 if (!usingReadyToRunHelper)
14336 // TODO: ReadyToRun: When generic dictionary lookups are necessary, replace the lookup call
14337 // and the chkcastany call with a single call to a dynamic R2R cell that will:
14338 // 1) Load the context
14339 // 2) Perform the generic dictionary lookup and caching, and generate the appropriate stub
14340 // 3) Check the object on the stack for the type-cast
14341 // Reason: performance (today, we'll always use the slow helper for the R2R generics case)
14343 op2 = impTokenToHandle(&resolvedToken, nullptr, FALSE);
14344 if (op2 == nullptr)
14345 { // compDonotInline()
14351 if (!usingReadyToRunHelper)
14354 op1 = impCastClassOrIsInstToTree(op1, op2, &resolvedToken, true);
14356 if (compDonotInline())
14361 /* Push the result back on the stack */
14362 impPushOnStack(op1, tiRetVal);
14367 if (compIsForInlining())
14369 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
14370 // TODO: Will this be too strict, given that we will inline many basic blocks?
14371 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
14373 /* Do we have just the exception on the stack ?*/
14375 if (verCurrentState.esStackDepth != 1)
14377 /* if not, just don't inline the method */
14379 compInlineResult->NoteFatal(InlineObservation::CALLEE_THROW_WITH_INVALID_STACK);
14384 if (tiVerificationNeeded)
14386 tiRetVal = impStackTop().seTypeInfo;
14387 Verify(tiRetVal.IsObjRef(), "object ref expected");
14388 if (verTrackObjCtorInitState && (verCurrentState.thisInitialized != TIS_Init))
14390 Verify(!tiRetVal.IsThisPtr(), "throw uninitialized this");
14394 block->bbSetRunRarely(); // any block with a throw is rare
14395 /* Pop the exception object and create the 'throw' helper call */
14397 op1 = gtNewHelperCallNode(CORINFO_HELP_THROW, TYP_VOID, GTF_EXCEPT, gtNewArgList(impPopStack().val));
14400 if (verCurrentState.esStackDepth > 0)
14402 impEvalSideEffects();
14405 assert(verCurrentState.esStackDepth == 0);
14411 assert(!compIsForInlining());
14413 if (info.compXcptnsCount == 0)
14415 BADCODE("rethrow outside catch");
14418 if (tiVerificationNeeded)
14420 Verify(block->hasHndIndex(), "rethrow outside catch");
14421 if (block->hasHndIndex())
14423 EHblkDsc* HBtab = ehGetDsc(block->getHndIndex());
14424 Verify(!HBtab->HasFinallyOrFaultHandler(), "rethrow in finally or fault");
14425 if (HBtab->HasFilter())
14427 // we better be in the handler clause part, not the filter part
14428 Verify(jitIsBetween(compCurBB->bbCodeOffs, HBtab->ebdHndBegOffs(), HBtab->ebdHndEndOffs()),
14429 "rethrow in filter");
14434 /* Create the 'rethrow' helper call */
14436 op1 = gtNewHelperCallNode(CORINFO_HELP_RETHROW, TYP_VOID, GTF_EXCEPT);
14442 assertImp(sz == sizeof(unsigned));
14444 _impResolveToken(CORINFO_TOKENKIND_Class);
14446 JITDUMP(" %08X", resolvedToken.token);
14448 if (tiVerificationNeeded)
14450 typeInfo tiTo = impStackTop().seTypeInfo;
14451 typeInfo tiInstr = verMakeTypeInfo(resolvedToken.hClass);
14453 Verify(tiTo.IsByRef(), "byref expected");
14454 Verify(!tiTo.IsReadonlyByRef(), "write to readonly byref");
14456 Verify(tiCompatibleWith(tiInstr, tiTo.DereferenceByRef(), false),
14457 "type operand incompatible with type of address");
14460 size = info.compCompHnd->getClassSize(resolvedToken.hClass); // Size
14461 op2 = gtNewIconNode(0); // Value
14462 op1 = impPopStack().val; // Dest
14463 op1 = gtNewBlockVal(op1, size);
14464 op1 = gtNewBlkOpNode(op1, op2, size, (prefixFlags & PREFIX_VOLATILE) != 0, false);
14469 if (tiVerificationNeeded)
14471 Verify(false, "bad opcode");
14474 op3 = impPopStack().val; // Size
14475 op2 = impPopStack().val; // Value
14476 op1 = impPopStack().val; // Dest
14478 if (op3->IsCnsIntOrI())
14480 size = (unsigned)op3->AsIntConCommon()->IconValue();
14481 op1 = new (this, GT_BLK) GenTreeBlk(GT_BLK, TYP_STRUCT, op1, size);
14485 op1 = new (this, GT_DYN_BLK) GenTreeDynBlk(op1, op3);
14488 op1 = gtNewBlkOpNode(op1, op2, size, (prefixFlags & PREFIX_VOLATILE) != 0, false);
14494 if (tiVerificationNeeded)
14496 Verify(false, "bad opcode");
14498 op3 = impPopStack().val; // Size
14499 op2 = impPopStack().val; // Src
14500 op1 = impPopStack().val; // Dest
14502 if (op3->IsCnsIntOrI())
14504 size = (unsigned)op3->AsIntConCommon()->IconValue();
14505 op1 = new (this, GT_BLK) GenTreeBlk(GT_BLK, TYP_STRUCT, op1, size);
14509 op1 = new (this, GT_DYN_BLK) GenTreeDynBlk(op1, op3);
14512 if (op2->OperGet() == GT_ADDR)
14514 op2 = op2->gtOp.gtOp1;
14518 op2 = gtNewOperNode(GT_IND, TYP_STRUCT, op2);
14521 op1 = gtNewBlkOpNode(op1, op2, size, (prefixFlags & PREFIX_VOLATILE) != 0, true);
14526 assertImp(sz == sizeof(unsigned));
14528 _impResolveToken(CORINFO_TOKENKIND_Class);
14530 JITDUMP(" %08X", resolvedToken.token);
14532 if (tiVerificationNeeded)
14534 typeInfo tiFrom = impStackTop().seTypeInfo;
14535 typeInfo tiTo = impStackTop(1).seTypeInfo;
14536 typeInfo tiInstr = verMakeTypeInfo(resolvedToken.hClass);
14538 Verify(tiFrom.IsByRef(), "expected byref source");
14539 Verify(tiTo.IsByRef(), "expected byref destination");
14541 Verify(tiCompatibleWith(tiFrom.DereferenceByRef(), tiInstr, false),
14542 "type of source address incompatible with type operand");
14543 Verify(!tiTo.IsReadonlyByRef(), "write to readonly byref");
14544 Verify(tiCompatibleWith(tiInstr, tiTo.DereferenceByRef(), false),
14545 "type operand incompatible with type of destination address");
14548 if (!eeIsValueClass(resolvedToken.hClass))
14550 op1 = impPopStack().val; // address to load from
14552 impBashVarAddrsToI(op1);
14554 assertImp(genActualType(op1->gtType) == TYP_I_IMPL || op1->gtType == TYP_BYREF);
14556 op1 = gtNewOperNode(GT_IND, TYP_REF, op1);
14557 op1->gtFlags |= GTF_EXCEPT | GTF_GLOB_REF;
14559 impPushOnStackNoType(op1);
14560 opcode = CEE_STIND_REF;
14562 goto STIND_POST_VERIFY;
14565 op2 = impPopStack().val; // Src
14566 op1 = impPopStack().val; // Dest
14567 op1 = gtNewCpObjNode(op1, op2, resolvedToken.hClass, ((prefixFlags & PREFIX_VOLATILE) != 0));
14572 assertImp(sz == sizeof(unsigned));
14574 _impResolveToken(CORINFO_TOKENKIND_Class);
14576 JITDUMP(" %08X", resolvedToken.token);
14578 if (eeIsValueClass(resolvedToken.hClass))
14580 lclTyp = TYP_STRUCT;
14587 if (tiVerificationNeeded)
14590 typeInfo tiPtr = impStackTop(1).seTypeInfo;
14592 // Make sure we have a good looking byref
14593 Verify(tiPtr.IsByRef(), "pointer not byref");
14594 Verify(!tiPtr.IsReadonlyByRef(), "write to readonly byref");
14595 if (!tiPtr.IsByRef() || tiPtr.IsReadonlyByRef())
14597 compUnsafeCastUsed = true;
14600 typeInfo ptrVal = DereferenceByRef(tiPtr);
14601 typeInfo argVal = verMakeTypeInfo(resolvedToken.hClass);
14603 if (!tiCompatibleWith(impStackTop(0).seTypeInfo, NormaliseForStack(argVal), true))
14605 Verify(false, "type of value incompatible with type operand");
14606 compUnsafeCastUsed = true;
14609 if (!tiCompatibleWith(argVal, ptrVal, false))
14611 Verify(false, "type operand incompatible with type of address");
14612 compUnsafeCastUsed = true;
14617 compUnsafeCastUsed = true;
14620 if (lclTyp == TYP_REF)
14622 opcode = CEE_STIND_REF;
14623 goto STIND_POST_VERIFY;
14626 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(resolvedToken.hClass);
14627 if (impIsPrimitive(jitTyp))
14629 lclTyp = JITtype2varType(jitTyp);
14630 goto STIND_POST_VERIFY;
14633 op2 = impPopStack().val; // Value
14634 op1 = impPopStack().val; // Ptr
14636 assertImp(varTypeIsStruct(op2));
14638 op1 = impAssignStructPtr(op1, op2, resolvedToken.hClass, (unsigned)CHECK_SPILL_ALL);
14644 assert(!compIsForInlining());
14646 // Being lazy here. Refanys are tricky in terms of gc tracking.
14647 // Since it is uncommon, just don't perform struct promotion in any method that contains mkrefany.
14649 JITDUMP("disabling struct promotion because of mkrefany\n");
14650 fgNoStructPromotion = true;
14652 oper = GT_MKREFANY;
14653 assertImp(sz == sizeof(unsigned));
14655 _impResolveToken(CORINFO_TOKENKIND_Class);
14657 JITDUMP(" %08X", resolvedToken.token);
14659 op2 = impTokenToHandle(&resolvedToken, nullptr, TRUE);
14660 if (op2 == nullptr)
14661 { // compDonotInline()
14665 if (tiVerificationNeeded)
14667 typeInfo tiPtr = impStackTop().seTypeInfo;
14668 typeInfo tiInstr = verMakeTypeInfo(resolvedToken.hClass);
14670 Verify(!verIsByRefLike(tiInstr), "mkrefany of byref-like class");
14671 Verify(!tiPtr.IsReadonlyByRef(), "readonly byref used with mkrefany");
14672 Verify(typeInfo::AreEquivalent(tiPtr.DereferenceByRef(), tiInstr), "type mismatch");
14675 accessAllowedResult =
14676 info.compCompHnd->canAccessClass(&resolvedToken, info.compMethodHnd, &calloutHelper);
14677 impHandleAccessAllowed(accessAllowedResult, &calloutHelper);
14679 op1 = impPopStack().val;
14681 // @SPECVIOLATION: TYP_INT should not be allowed here by a strict reading of the spec.
14682 // But JIT32 allowed it, so we continue to allow it.
14683 assertImp(op1->TypeGet() == TYP_BYREF || op1->TypeGet() == TYP_I_IMPL || op1->TypeGet() == TYP_INT);
14685 // MKREFANY returns a struct. op2 is the class token.
14686 op1 = gtNewOperNode(oper, TYP_STRUCT, op1, op2);
14688 impPushOnStack(op1, verMakeTypeInfo(impGetRefAnyClass()));
14694 assertImp(sz == sizeof(unsigned));
14696 _impResolveToken(CORINFO_TOKENKIND_Class);
14698 JITDUMP(" %08X", resolvedToken.token);
14702 tiRetVal = verMakeTypeInfo(resolvedToken.hClass);
14704 if (tiVerificationNeeded)
14706 typeInfo tiPtr = impStackTop().seTypeInfo;
14708 // Make sure we have a byref
14709 if (!tiPtr.IsByRef())
14711 Verify(false, "pointer not byref");
14712 compUnsafeCastUsed = true;
14714 typeInfo tiPtrVal = DereferenceByRef(tiPtr);
14716 if (!tiCompatibleWith(tiPtrVal, tiRetVal, false))
14718 Verify(false, "type of address incompatible with type operand");
14719 compUnsafeCastUsed = true;
14721 tiRetVal.NormaliseForStack();
14725 compUnsafeCastUsed = true;
14728 if (eeIsValueClass(resolvedToken.hClass))
14730 lclTyp = TYP_STRUCT;
14735 opcode = CEE_LDIND_REF;
14736 goto LDIND_POST_VERIFY;
14739 op1 = impPopStack().val;
14741 assertImp(op1->TypeGet() == TYP_BYREF || op1->TypeGet() == TYP_I_IMPL);
14743 CorInfoType jitTyp = info.compCompHnd->asCorInfoType(resolvedToken.hClass);
14744 if (impIsPrimitive(jitTyp))
14746 op1 = gtNewOperNode(GT_IND, JITtype2varType(jitTyp), op1);
14748 // Could point anywhere, example a boxed class static int
14749 op1->gtFlags |= GTF_IND_TGTANYWHERE | GTF_GLOB_REF;
14750 assertImp(varTypeIsArithmetic(op1->gtType));
14754 // OBJ returns a struct
14755 // and an inline argument which is the class token of the loaded obj
14756 op1 = gtNewObjNode(resolvedToken.hClass, op1);
14758 op1->gtFlags |= GTF_EXCEPT;
14760 impPushOnStack(op1, tiRetVal);
14765 if (tiVerificationNeeded)
14767 typeInfo tiArray = impStackTop().seTypeInfo;
14768 Verify(verIsSDArray(tiArray), "bad array");
14769 tiRetVal = typeInfo(TI_INT);
14772 op1 = impPopStack().val;
14773 if (!opts.MinOpts() && !opts.compDbgCode)
14775 /* Use GT_ARR_LENGTH operator so rng check opts see this */
14776 GenTreeArrLen* arrLen =
14777 new (this, GT_ARR_LENGTH) GenTreeArrLen(TYP_INT, op1, offsetof(CORINFO_Array, length));
14779 /* Mark the block as containing a length expression */
14781 if (op1->gtOper == GT_LCL_VAR)
14783 block->bbFlags |= BBF_HAS_IDX_LEN;
14790 /* Create the expression "*(array_addr + ArrLenOffs)" */
14791 op1 = gtNewOperNode(GT_ADD, TYP_BYREF, op1,
14792 gtNewIconNode(offsetof(CORINFO_Array, length), TYP_I_IMPL));
14793 op1 = gtNewOperNode(GT_IND, TYP_INT, op1);
14794 op1->gtFlags |= GTF_IND_ARR_LEN;
14797 /* An indirection will cause a GPF if the address is null */
14798 op1->gtFlags |= GTF_EXCEPT;
14800 /* Push the result back on the stack */
14801 impPushOnStack(op1, tiRetVal);
14805 op1 = gtNewHelperCallNode(CORINFO_HELP_USER_BREAKPOINT, TYP_VOID);
14809 if (opts.compDbgCode)
14811 op1 = new (this, GT_NO_OP) GenTree(GT_NO_OP, TYP_VOID);
14816 /******************************** NYI *******************************/
14819 OutputDebugStringA("CLR: Invalid x86 breakpoint in IL stream\n");
14822 case CEE_MACRO_END:
14825 BADCODE3("unknown opcode", ": %02X", (int)opcode);
14829 prevOpcode = opcode;
14832 assert(!insertLdloc || opcode == CEE_DUP);
14835 assert(!insertLdloc);
14838 #undef _impResolveToken
14841 #pragma warning(pop)
14844 // Push a local/argument treeon the operand stack
14845 void Compiler::impPushVar(GenTree* op, typeInfo tiRetVal)
14847 tiRetVal.NormaliseForStack();
14849 if (verTrackObjCtorInitState && (verCurrentState.thisInitialized != TIS_Init) && tiRetVal.IsThisPtr())
14851 tiRetVal.SetUninitialisedObjRef();
14854 impPushOnStack(op, tiRetVal);
14857 // Load a local/argument on the operand stack
14858 // lclNum is an index into lvaTable *NOT* the arg/lcl index in the IL
14859 void Compiler::impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal)
14863 if (lvaTable[lclNum].lvNormalizeOnLoad())
14865 lclTyp = lvaGetRealType(lclNum);
14869 lclTyp = lvaGetActualType(lclNum);
14872 impPushVar(gtNewLclvNode(lclNum, lclTyp, offset), tiRetVal);
14875 // Load an argument on the operand stack
14876 // Shared by the various CEE_LDARG opcodes
14877 // ilArgNum is the argument index as specified in IL.
14878 // It will be mapped to the correct lvaTable index
14879 void Compiler::impLoadArg(unsigned ilArgNum, IL_OFFSET offset)
14881 Verify(ilArgNum < info.compILargsCount, "bad arg num");
14883 if (compIsForInlining())
14885 if (ilArgNum >= info.compArgsCount)
14887 compInlineResult->NoteFatal(InlineObservation::CALLEE_BAD_ARGUMENT_NUMBER);
14891 impPushVar(impInlineFetchArg(ilArgNum, impInlineInfo->inlArgInfo, impInlineInfo->lclVarInfo),
14892 impInlineInfo->lclVarInfo[ilArgNum].lclVerTypeInfo);
14896 if (ilArgNum >= info.compArgsCount)
14901 unsigned lclNum = compMapILargNum(ilArgNum); // account for possible hidden param
14903 if (lclNum == info.compThisArg)
14905 lclNum = lvaArg0Var;
14908 impLoadVar(lclNum, offset);
14912 // Load a local on the operand stack
14913 // Shared by the various CEE_LDLOC opcodes
14914 // ilLclNum is the local index as specified in IL.
14915 // It will be mapped to the correct lvaTable index
14916 void Compiler::impLoadLoc(unsigned ilLclNum, IL_OFFSET offset)
14918 if (tiVerificationNeeded)
14920 Verify(ilLclNum < info.compMethodInfo->locals.numArgs, "bad loc num");
14921 Verify(info.compInitMem, "initLocals not set");
14924 if (compIsForInlining())
14926 if (ilLclNum >= info.compMethodInfo->locals.numArgs)
14928 compInlineResult->NoteFatal(InlineObservation::CALLEE_BAD_LOCAL_NUMBER);
14932 // Get the local type
14933 var_types lclTyp = impInlineInfo->lclVarInfo[ilLclNum + impInlineInfo->argCnt].lclTypeInfo;
14935 typeInfo tiRetVal = impInlineInfo->lclVarInfo[ilLclNum + impInlineInfo->argCnt].lclVerTypeInfo;
14937 /* Have we allocated a temp for this local? */
14939 unsigned lclNum = impInlineFetchLocal(ilLclNum DEBUGARG("Inline ldloc first use temp"));
14941 // All vars of inlined methods should be !lvNormalizeOnLoad()
14943 assert(!lvaTable[lclNum].lvNormalizeOnLoad());
14944 lclTyp = genActualType(lclTyp);
14946 impPushVar(gtNewLclvNode(lclNum, lclTyp), tiRetVal);
14950 if (ilLclNum >= info.compMethodInfo->locals.numArgs)
14955 unsigned lclNum = info.compArgsCount + ilLclNum;
14957 impLoadVar(lclNum, offset);
14961 #ifdef _TARGET_ARM_
14962 /**************************************************************************************
14964 * When assigning a vararg call src to a HFA lcl dest, mark that we cannot promote the
14965 * dst struct, because struct promotion will turn it into a float/double variable while
14966 * the rhs will be an int/long variable. We don't code generate assignment of int into
14967 * a float, but there is nothing that might prevent us from doing so. The tree however
14968 * would like: (=, (typ_float, typ_int)) or (GT_TRANSFER, (typ_float, typ_int))
14970 * tmpNum - the lcl dst variable num that is a struct.
14971 * src - the src tree assigned to the dest that is a struct/int (when varargs call.)
14972 * hClass - the type handle for the struct variable.
14974 * TODO-ARM-CQ: [301608] This is a rare scenario with varargs and struct promotion coming into play,
14975 * however, we could do a codegen of transferring from int to float registers
14976 * (transfer, not a cast.)
14979 void Compiler::impMarkLclDstNotPromotable(unsigned tmpNum, GenTreePtr src, CORINFO_CLASS_HANDLE hClass)
14981 if (src->gtOper == GT_CALL && src->gtCall.IsVarargs() && IsHfa(hClass))
14983 int hfaSlots = GetHfaCount(hClass);
14984 var_types hfaType = GetHfaType(hClass);
14986 // If we have varargs we morph the method's return type to be "int" irrespective of its original
14987 // type: struct/float at importer because the ABI calls out return in integer registers.
14988 // We don't want struct promotion to replace an expression like this:
14989 // lclFld_int = callvar_int() into lclFld_float = callvar_int();
14990 // This means an int is getting assigned to a float without a cast. Prevent the promotion.
14991 if ((hfaType == TYP_DOUBLE && hfaSlots == sizeof(double) / REGSIZE_BYTES) ||
14992 (hfaType == TYP_FLOAT && hfaSlots == sizeof(float) / REGSIZE_BYTES))
14994 // Make sure this struct type stays as struct so we can receive the call in a struct.
14995 lvaTable[tmpNum].lvIsMultiRegRet = true;
14999 #endif // _TARGET_ARM_
15001 #if FEATURE_MULTIREG_RET
15002 GenTreePtr Compiler::impAssignMultiRegTypeToVar(GenTreePtr op, CORINFO_CLASS_HANDLE hClass)
15004 unsigned tmpNum = lvaGrabTemp(true DEBUGARG("Return value temp for multireg return."));
15005 impAssignTempGen(tmpNum, op, hClass, (unsigned)CHECK_SPILL_NONE);
15006 GenTreePtr ret = gtNewLclvNode(tmpNum, op->gtType);
15008 // TODO-1stClassStructs: Handle constant propagation and CSE-ing of multireg returns.
15009 ret->gtFlags |= GTF_DONT_CSE;
15011 assert(IsMultiRegReturnedType(hClass));
15013 // Mark the var so that fields are not promoted and stay together.
15014 lvaTable[tmpNum].lvIsMultiRegRet = true;
15018 #endif // FEATURE_MULTIREG_RET
15020 // do import for a return
15021 // returns false if inlining was aborted
15022 // opcode can be ret or call in the case of a tail.call
15023 bool Compiler::impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode)
15025 if (tiVerificationNeeded)
15027 verVerifyThisPtrInitialised();
15029 unsigned expectedStack = 0;
15030 if (info.compRetType != TYP_VOID)
15032 typeInfo tiVal = impStackTop().seTypeInfo;
15033 typeInfo tiDeclared =
15034 verMakeTypeInfo(info.compMethodInfo->args.retType, info.compMethodInfo->args.retTypeClass);
15036 Verify(!verIsByRefLike(tiDeclared) || verIsSafeToReturnByRef(tiVal), "byref return");
15038 Verify(tiCompatibleWith(tiVal, tiDeclared.NormaliseForStack(), true), "type mismatch");
15041 Verify(verCurrentState.esStackDepth == expectedStack, "stack non-empty on return");
15044 GenTree* op2 = nullptr;
15045 GenTree* op1 = nullptr;
15046 CORINFO_CLASS_HANDLE retClsHnd = nullptr;
15048 if (info.compRetType != TYP_VOID)
15050 StackEntry se = impPopStack(retClsHnd);
15053 if (!compIsForInlining())
15055 impBashVarAddrsToI(op2);
15056 op2 = impImplicitIorI4Cast(op2, info.compRetType);
15057 op2 = impImplicitR4orR8Cast(op2, info.compRetType);
15058 assertImp((genActualType(op2->TypeGet()) == genActualType(info.compRetType)) ||
15059 ((op2->TypeGet() == TYP_I_IMPL) && (info.compRetType == TYP_BYREF)) ||
15060 ((op2->TypeGet() == TYP_BYREF) && (info.compRetType == TYP_I_IMPL)) ||
15061 (varTypeIsFloating(op2->gtType) && varTypeIsFloating(info.compRetType)) ||
15062 (varTypeIsStruct(op2) && varTypeIsStruct(info.compRetType)));
15065 if (opts.compGcChecks && info.compRetType == TYP_REF)
15067 // DDB 3483 : JIT Stress: early termination of GC ref's life time in exception code path
15068 // VSW 440513: Incorrect gcinfo on the return value under COMPlus_JitGCChecks=1 for methods with
15071 assert(op2->gtType == TYP_REF);
15073 // confirm that the argument is a GC pointer (for debugging (GC stress))
15074 GenTreeArgList* args = gtNewArgList(op2);
15075 op2 = gtNewHelperCallNode(CORINFO_HELP_CHECK_OBJ, TYP_REF, 0, args);
15079 printf("\ncompGcChecks tree:\n");
15087 // inlinee's stack should be empty now.
15088 assert(verCurrentState.esStackDepth == 0);
15093 printf("\n\n Inlinee Return expression (before normalization) =>\n");
15098 // Make sure the type matches the original call.
15100 var_types returnType = genActualType(op2->gtType);
15101 var_types originalCallType = impInlineInfo->inlineCandidateInfo->fncRetType;
15102 if ((returnType != originalCallType) && (originalCallType == TYP_STRUCT))
15104 originalCallType = impNormStructType(impInlineInfo->inlineCandidateInfo->methInfo.args.retTypeClass);
15107 if (returnType != originalCallType)
15109 compInlineResult->NoteFatal(InlineObservation::CALLSITE_RETURN_TYPE_MISMATCH);
15113 // Below, we are going to set impInlineInfo->retExpr to the tree with the return
15114 // expression. At this point, retExpr could already be set if there are multiple
15115 // return blocks (meaning lvaInlineeReturnSpillTemp != BAD_VAR_NUM) and one of
15116 // the other blocks already set it. If there is only a single return block,
15117 // retExpr shouldn't be set. However, this is not true if we reimport a block
15118 // with a return. In that case, retExpr will be set, then the block will be
15119 // reimported, but retExpr won't get cleared as part of setting the block to
15120 // be reimported. The reimported retExpr value should be the same, so even if
15121 // we don't unconditionally overwrite it, it shouldn't matter.
15122 if (info.compRetNativeType != TYP_STRUCT)
15124 // compRetNativeType is not TYP_STRUCT.
15125 // This implies it could be either a scalar type or SIMD vector type or
15126 // a struct type that can be normalized to a scalar type.
15128 if (varTypeIsStruct(info.compRetType))
15130 noway_assert(info.compRetBuffArg == BAD_VAR_NUM);
15131 // adjust the type away from struct to integral
15132 // and no normalizing
15133 op2 = impFixupStructReturnType(op2, retClsHnd);
15137 // Do we have to normalize?
15138 var_types fncRealRetType = JITtype2varType(info.compMethodInfo->args.retType);
15139 if ((varTypeIsSmall(op2->TypeGet()) || varTypeIsSmall(fncRealRetType)) &&
15140 fgCastNeeded(op2, fncRealRetType))
15142 // Small-typed return values are normalized by the callee
15143 op2 = gtNewCastNode(TYP_INT, op2, fncRealRetType);
15147 if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM)
15149 assert(info.compRetNativeType != TYP_VOID &&
15150 (fgMoreThanOneReturnBlock() || impInlineInfo->hasPinnedLocals));
15152 // This is a bit of a workaround...
15153 // If we are inlining a call that returns a struct, where the actual "native" return type is
15154 // not a struct (for example, the struct is composed of exactly one int, and the native
15155 // return type is thus an int), and the inlinee has multiple return blocks (thus,
15156 // lvaInlineeReturnSpillTemp is != BAD_VAR_NUM, and is the index of a local var that is set
15157 // to the *native* return type), and at least one of the return blocks is the result of
15158 // a call, then we have a problem. The situation is like this (from a failed test case):
15161 // // Note: valuetype plinq_devtests.LazyTests/LIX is a struct with only a single int
15162 // call !!0 [mscorlib]System.Threading.LazyInitializer::EnsureInitialized<valuetype
15163 // plinq_devtests.LazyTests/LIX>(!!0&, bool&, object&, class [mscorlib]System.Func`1<!!0>)
15167 // ldobj !!T // this gets bashed to a GT_LCL_FLD, type TYP_INT
15170 // call !!0 System.Threading.LazyInitializer::EnsureInitializedCore<!!0>(!!0&, bool&,
15171 // object&, class System.Func`1<!!0>)
15174 // In the code above, when we call impFixupStructReturnType(), we will change the op2 return type
15175 // of the inlinee return node, but we don't do that for GT_CALL nodes, which we delay until
15176 // morphing when we call fgFixupStructReturn(). We do this, apparently, to handle nested
15177 // inlining properly by leaving the correct type on the GT_CALL node through importing.
15179 // To fix this, for this case, we temporarily change the GT_CALL node type to the
15180 // native return type, which is what it will be set to eventually. We generate the
15181 // assignment to the return temp, using the correct type, and then restore the GT_CALL
15182 // node type. During morphing, the GT_CALL will get the correct, final, native return type.
15184 bool restoreType = false;
15185 if ((op2->OperGet() == GT_CALL) && (info.compRetType == TYP_STRUCT))
15187 noway_assert(op2->TypeGet() == TYP_STRUCT);
15188 op2->gtType = info.compRetNativeType;
15189 restoreType = true;
15192 impAssignTempGen(lvaInlineeReturnSpillTemp, op2, se.seTypeInfo.GetClassHandle(),
15193 (unsigned)CHECK_SPILL_ALL);
15195 GenTreePtr tmpOp2 = gtNewLclvNode(lvaInlineeReturnSpillTemp, op2->TypeGet());
15199 op2->gtType = TYP_STRUCT; // restore it to what it was
15205 if (impInlineInfo->retExpr)
15207 // Some other block(s) have seen the CEE_RET first.
15208 // Better they spilled to the same temp.
15209 assert(impInlineInfo->retExpr->gtOper == GT_LCL_VAR);
15210 assert(impInlineInfo->retExpr->gtLclVarCommon.gtLclNum == op2->gtLclVarCommon.gtLclNum);
15218 printf("\n\n Inlinee Return expression (after normalization) =>\n");
15223 // Report the return expression
15224 impInlineInfo->retExpr = op2;
15228 // compRetNativeType is TYP_STRUCT.
15229 // This implies that struct return via RetBuf arg or multi-reg struct return
15231 GenTreePtr iciCall = impInlineInfo->iciCall;
15232 assert(iciCall->gtOper == GT_CALL);
15234 // Assign the inlinee return into a spill temp.
15235 // spill temp only exists if there are multiple return points
15236 if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM)
15238 // in this case we have to insert multiple struct copies to the temp
15239 // and the retexpr is just the temp.
15240 assert(info.compRetNativeType != TYP_VOID);
15241 assert(fgMoreThanOneReturnBlock() || impInlineInfo->hasPinnedLocals);
15243 impAssignTempGen(lvaInlineeReturnSpillTemp, op2, se.seTypeInfo.GetClassHandle(),
15244 (unsigned)CHECK_SPILL_ALL);
15247 #if defined(_TARGET_ARM_) || defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
15248 #if defined(_TARGET_ARM_)
15249 // TODO-ARM64-NYI: HFA
15250 // TODO-AMD64-Unix and TODO-ARM once the ARM64 functionality is implemented the
15251 // next ifdefs could be refactored in a single method with the ifdef inside.
15252 if (IsHfa(retClsHnd))
15254 // Same as !IsHfa but just don't bother with impAssignStructPtr.
15255 #else // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
15256 ReturnTypeDesc retTypeDesc;
15257 retTypeDesc.InitializeStructReturnType(this, retClsHnd);
15258 unsigned retRegCount = retTypeDesc.GetReturnRegCount();
15260 if (retRegCount != 0)
15262 // If single eightbyte, the return type would have been normalized and there won't be a temp var.
15263 // This code will be called only if the struct return has not been normalized (i.e. 2 eightbytes -
15265 assert(retRegCount == MAX_RET_REG_COUNT);
15266 // Same as !structDesc.passedInRegisters but just don't bother with impAssignStructPtr.
15267 CLANG_FORMAT_COMMENT_ANCHOR;
15268 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
15270 if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM)
15272 if (!impInlineInfo->retExpr)
15274 #if defined(_TARGET_ARM_)
15275 impInlineInfo->retExpr = gtNewLclvNode(lvaInlineeReturnSpillTemp, info.compRetType);
15276 #else // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
15277 // The inlinee compiler has figured out the type of the temp already. Use it here.
15278 impInlineInfo->retExpr =
15279 gtNewLclvNode(lvaInlineeReturnSpillTemp, lvaTable[lvaInlineeReturnSpillTemp].lvType);
15280 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
15285 impInlineInfo->retExpr = op2;
15289 #elif defined(_TARGET_ARM64_)
15290 ReturnTypeDesc retTypeDesc;
15291 retTypeDesc.InitializeStructReturnType(this, retClsHnd);
15292 unsigned retRegCount = retTypeDesc.GetReturnRegCount();
15294 if (retRegCount != 0)
15296 assert(!iciCall->AsCall()->HasRetBufArg());
15297 assert(retRegCount >= 2);
15298 if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM)
15300 if (!impInlineInfo->retExpr)
15302 // The inlinee compiler has figured out the type of the temp already. Use it here.
15303 impInlineInfo->retExpr =
15304 gtNewLclvNode(lvaInlineeReturnSpillTemp, lvaTable[lvaInlineeReturnSpillTemp].lvType);
15309 impInlineInfo->retExpr = op2;
15313 #endif // defined(_TARGET_ARM64_)
15315 assert(iciCall->AsCall()->HasRetBufArg());
15316 GenTreePtr dest = gtCloneExpr(iciCall->gtCall.gtCallArgs->gtOp.gtOp1);
15317 // spill temp only exists if there are multiple return points
15318 if (lvaInlineeReturnSpillTemp != BAD_VAR_NUM)
15320 // if this is the first return we have seen set the retExpr
15321 if (!impInlineInfo->retExpr)
15323 impInlineInfo->retExpr =
15324 impAssignStructPtr(dest, gtNewLclvNode(lvaInlineeReturnSpillTemp, info.compRetType),
15325 retClsHnd, (unsigned)CHECK_SPILL_ALL);
15330 impInlineInfo->retExpr = impAssignStructPtr(dest, op2, retClsHnd, (unsigned)CHECK_SPILL_ALL);
15337 if (compIsForInlining())
15342 if (info.compRetType == TYP_VOID)
15345 op1 = new (this, GT_RETURN) GenTreeOp(GT_RETURN, TYP_VOID);
15347 else if (info.compRetBuffArg != BAD_VAR_NUM)
15349 // Assign value to return buff (first param)
15350 GenTreePtr retBuffAddr = gtNewLclvNode(info.compRetBuffArg, TYP_BYREF, impCurStmtOffs);
15352 op2 = impAssignStructPtr(retBuffAddr, op2, retClsHnd, (unsigned)CHECK_SPILL_ALL);
15353 impAppendTree(op2, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
15355 // There are cases where the address of the implicit RetBuf should be returned explicitly (in RAX).
15356 CLANG_FORMAT_COMMENT_ANCHOR;
15358 #if defined(_TARGET_AMD64_)
15360 // x64 (System V and Win64) calling convention requires to
15361 // return the implicit return buffer explicitly (in RAX).
15362 // Change the return type to be BYREF.
15363 op1 = gtNewOperNode(GT_RETURN, TYP_BYREF, gtNewLclvNode(info.compRetBuffArg, TYP_BYREF));
15364 #else // !defined(_TARGET_AMD64_)
15365 // In case of non-AMD64 targets the profiler hook requires to return the implicit RetBuf explicitly (in RAX).
15366 // In such case the return value of the function is changed to BYREF.
15367 // If profiler hook is not needed the return type of the function is TYP_VOID.
15368 if (compIsProfilerHookNeeded())
15370 op1 = gtNewOperNode(GT_RETURN, TYP_BYREF, gtNewLclvNode(info.compRetBuffArg, TYP_BYREF));
15375 op1 = new (this, GT_RETURN) GenTreeOp(GT_RETURN, TYP_VOID);
15377 #endif // !defined(_TARGET_AMD64_)
15379 else if (varTypeIsStruct(info.compRetType))
15381 #if !FEATURE_MULTIREG_RET
15382 // For both ARM architectures the HFA native types are maintained as structs.
15383 // Also on System V AMD64 the multireg structs returns are also left as structs.
15384 noway_assert(info.compRetNativeType != TYP_STRUCT);
15386 op2 = impFixupStructReturnType(op2, retClsHnd);
15388 op1 = gtNewOperNode(GT_RETURN, genActualType(info.compRetNativeType), op2);
15393 op1 = gtNewOperNode(GT_RETURN, genActualType(info.compRetType), op2);
15396 // We must have imported a tailcall and jumped to RET
15397 if (prefixFlags & PREFIX_TAILCALL)
15399 #ifndef _TARGET_AMD64_
15401 // This cannot be asserted on Amd64 since we permit the following IL pattern:
15405 assert(verCurrentState.esStackDepth == 0 && impOpcodeIsCallOpcode(opcode));
15408 opcode = CEE_RET; // To prevent trying to spill if CALL_SITE_BOUNDARIES
15410 // impImportCall() would have already appended TYP_VOID calls
15411 if (info.compRetType == TYP_VOID)
15417 impAppendTree(op1, (unsigned)CHECK_SPILL_NONE, impCurStmtOffs);
15419 // Remember at which BC offset the tree was finished
15420 impNoteLastILoffs();
15425 /*****************************************************************************
15426 * Mark the block as unimported.
15427 * Note that the caller is responsible for calling impImportBlockPending(),
15428 * with the appropriate stack-state
15431 inline void Compiler::impReimportMarkBlock(BasicBlock* block)
15434 if (verbose && (block->bbFlags & BBF_IMPORTED))
15436 printf("\nBB%02u will be reimported\n", block->bbNum);
15440 block->bbFlags &= ~BBF_IMPORTED;
15443 /*****************************************************************************
15444 * Mark the successors of the given block as unimported.
15445 * Note that the caller is responsible for calling impImportBlockPending()
15446 * for all the successors, with the appropriate stack-state.
15449 void Compiler::impReimportMarkSuccessors(BasicBlock* block)
15451 for (unsigned i = 0; i < block->NumSucc(); i++)
15453 impReimportMarkBlock(block->GetSucc(i));
15457 /*****************************************************************************
15459 * Filter wrapper to handle only passed in exception code
15463 LONG FilterVerificationExceptions(PEXCEPTION_POINTERS pExceptionPointers, LPVOID lpvParam)
15465 if (pExceptionPointers->ExceptionRecord->ExceptionCode == SEH_VERIFICATION_EXCEPTION)
15467 return EXCEPTION_EXECUTE_HANDLER;
15470 return EXCEPTION_CONTINUE_SEARCH;
15473 void Compiler::impVerifyEHBlock(BasicBlock* block, bool isTryStart)
15475 assert(block->hasTryIndex());
15476 assert(!compIsForInlining());
15478 unsigned tryIndex = block->getTryIndex();
15479 EHblkDsc* HBtab = ehGetDsc(tryIndex);
15483 assert(block->bbFlags & BBF_TRY_BEG);
15485 // The Stack must be empty
15487 if (block->bbStkDepth != 0)
15489 BADCODE("Evaluation stack must be empty on entry into a try block");
15493 // Save the stack contents, we'll need to restore it later
15495 SavedStack blockState;
15496 impSaveStackState(&blockState, false);
15498 while (HBtab != nullptr)
15502 // Are we verifying that an instance constructor properly initializes it's 'this' pointer once?
15503 // We do not allow the 'this' pointer to be uninitialized when entering most kinds try regions
15505 if (verTrackObjCtorInitState && (verCurrentState.thisInitialized != TIS_Init))
15507 // We trigger an invalid program exception here unless we have a try/fault region.
15509 if (HBtab->HasCatchHandler() || HBtab->HasFinallyHandler() || HBtab->HasFilter())
15512 "The 'this' pointer of an instance constructor is not intialized upon entry to a try region");
15516 // Allow a try/fault region to proceed.
15517 assert(HBtab->HasFaultHandler());
15521 /* Recursively process the handler block */
15522 BasicBlock* hndBegBB = HBtab->ebdHndBeg;
15524 // Construct the proper verification stack state
15525 // either empty or one that contains just
15526 // the Exception Object that we are dealing with
15528 verCurrentState.esStackDepth = 0;
15530 if (handlerGetsXcptnObj(hndBegBB->bbCatchTyp))
15532 CORINFO_CLASS_HANDLE clsHnd;
15534 if (HBtab->HasFilter())
15536 clsHnd = impGetObjectClass();
15540 CORINFO_RESOLVED_TOKEN resolvedToken;
15542 resolvedToken.tokenContext = impTokenLookupContextHandle;
15543 resolvedToken.tokenScope = info.compScopeHnd;
15544 resolvedToken.token = HBtab->ebdTyp;
15545 resolvedToken.tokenType = CORINFO_TOKENKIND_Class;
15546 info.compCompHnd->resolveToken(&resolvedToken);
15548 clsHnd = resolvedToken.hClass;
15551 // push catch arg the stack, spill to a temp if necessary
15552 // Note: can update HBtab->ebdHndBeg!
15553 hndBegBB = impPushCatchArgOnStack(hndBegBB, clsHnd);
15556 // Queue up the handler for importing
15558 impImportBlockPending(hndBegBB);
15560 if (HBtab->HasFilter())
15562 /* @VERIFICATION : Ideally the end of filter state should get
15563 propagated to the catch handler, this is an incompleteness,
15564 but is not a security/compliance issue, since the only
15565 interesting state is the 'thisInit' state.
15568 verCurrentState.esStackDepth = 0;
15570 BasicBlock* filterBB = HBtab->ebdFilter;
15572 // push catch arg the stack, spill to a temp if necessary
15573 // Note: can update HBtab->ebdFilter!
15574 filterBB = impPushCatchArgOnStack(filterBB, impGetObjectClass());
15576 impImportBlockPending(filterBB);
15579 else if (verTrackObjCtorInitState && HBtab->HasFaultHandler())
15581 /* Recursively process the handler block */
15583 verCurrentState.esStackDepth = 0;
15585 // Queue up the fault handler for importing
15587 impImportBlockPending(HBtab->ebdHndBeg);
15590 // Now process our enclosing try index (if any)
15592 tryIndex = HBtab->ebdEnclosingTryIndex;
15593 if (tryIndex == EHblkDsc::NO_ENCLOSING_INDEX)
15599 HBtab = ehGetDsc(tryIndex);
15603 // Restore the stack contents
15604 impRestoreStackState(&blockState);
15607 //***************************************************************
15608 // Import the instructions for the given basic block. Perform
15609 // verification, throwing an exception on failure. Push any successor blocks that are enabled for the first
15610 // time, or whose verification pre-state is changed.
15613 #pragma warning(push)
15614 #pragma warning(disable : 21000) // Suppress PREFast warning about overly large function
15616 void Compiler::impImportBlock(BasicBlock* block)
15618 // BBF_INTERNAL blocks only exist during importation due to EH canonicalization. We need to
15619 // handle them specially. In particular, there is no IL to import for them, but we do need
15620 // to mark them as imported and put their successors on the pending import list.
15621 if (block->bbFlags & BBF_INTERNAL)
15623 JITDUMP("Marking BBF_INTERNAL block BB%02u as BBF_IMPORTED\n", block->bbNum);
15624 block->bbFlags |= BBF_IMPORTED;
15626 for (unsigned i = 0; i < block->NumSucc(); i++)
15628 impImportBlockPending(block->GetSucc(i));
15638 /* Make the block globaly available */
15643 /* Initialize the debug variables */
15644 impCurOpcName = "unknown";
15645 impCurOpcOffs = block->bbCodeOffs;
15648 /* Set the current stack state to the merged result */
15649 verResetCurrentState(block, &verCurrentState);
15651 /* Now walk the code and import the IL into GenTrees */
15653 struct FilterVerificationExceptionsParam
15658 FilterVerificationExceptionsParam param;
15660 param.pThis = this;
15661 param.block = block;
15663 PAL_TRY(FilterVerificationExceptionsParam*, pParam, ¶m)
15665 /* @VERIFICATION : For now, the only state propagation from try
15666 to it's handler is "thisInit" state (stack is empty at start of try).
15667 In general, for state that we track in verification, we need to
15668 model the possibility that an exception might happen at any IL
15669 instruction, so we really need to merge all states that obtain
15670 between IL instructions in a try block into the start states of
15673 However we do not allow the 'this' pointer to be uninitialized when
15674 entering most kinds try regions (only try/fault are allowed to have
15675 an uninitialized this pointer on entry to the try)
15677 Fortunately, the stack is thrown away when an exception
15678 leads to a handler, so we don't have to worry about that.
15679 We DO, however, have to worry about the "thisInit" state.
15680 But only for the try/fault case.
15682 The only allowed transition is from TIS_Uninit to TIS_Init.
15684 So for a try/fault region for the fault handler block
15685 we will merge the start state of the try begin
15686 and the post-state of each block that is part of this try region
15689 // merge the start state of the try begin
15691 if (pParam->block->bbFlags & BBF_TRY_BEG)
15693 pParam->pThis->impVerifyEHBlock(pParam->block, true);
15696 pParam->pThis->impImportBlockCode(pParam->block);
15698 // As discussed above:
15699 // merge the post-state of each block that is part of this try region
15701 if (pParam->block->hasTryIndex())
15703 pParam->pThis->impVerifyEHBlock(pParam->block, false);
15706 PAL_EXCEPT_FILTER(FilterVerificationExceptions)
15708 verHandleVerificationFailure(block DEBUGARG(false));
15712 if (compDonotInline())
15717 assert(!compDonotInline());
15719 markImport = false;
15723 unsigned baseTmp = NO_BASE_TMP; // input temps assigned to successor blocks
15724 bool reimportSpillClique = false;
15725 BasicBlock* tgtBlock = nullptr;
15727 /* If the stack is non-empty, we might have to spill its contents */
15729 if (verCurrentState.esStackDepth != 0)
15731 impBoxTemp = BAD_VAR_NUM; // if a box temp is used in a block that leaves something
15732 // on the stack, its lifetime is hard to determine, simply
15733 // don't reuse such temps.
15735 GenTreePtr addStmt = nullptr;
15737 /* Do the successors of 'block' have any other predecessors ?
15738 We do not want to do some of the optimizations related to multiRef
15739 if we can reimport blocks */
15741 unsigned multRef = impCanReimport ? unsigned(~0) : 0;
15743 switch (block->bbJumpKind)
15747 /* Temporarily remove the 'jtrue' from the end of the tree list */
15749 assert(impTreeLast);
15750 assert(impTreeLast->gtOper == GT_STMT);
15751 assert(impTreeLast->gtStmt.gtStmtExpr->gtOper == GT_JTRUE);
15753 addStmt = impTreeLast;
15754 impTreeLast = impTreeLast->gtPrev;
15756 /* Note if the next block has more than one ancestor */
15758 multRef |= block->bbNext->bbRefs;
15760 /* Does the next block have temps assigned? */
15762 baseTmp = block->bbNext->bbStkTempsIn;
15763 tgtBlock = block->bbNext;
15765 if (baseTmp != NO_BASE_TMP)
15770 /* Try the target of the jump then */
15772 multRef |= block->bbJumpDest->bbRefs;
15773 baseTmp = block->bbJumpDest->bbStkTempsIn;
15774 tgtBlock = block->bbJumpDest;
15778 multRef |= block->bbJumpDest->bbRefs;
15779 baseTmp = block->bbJumpDest->bbStkTempsIn;
15780 tgtBlock = block->bbJumpDest;
15784 multRef |= block->bbNext->bbRefs;
15785 baseTmp = block->bbNext->bbStkTempsIn;
15786 tgtBlock = block->bbNext;
15791 BasicBlock** jmpTab;
15794 /* Temporarily remove the GT_SWITCH from the end of the tree list */
15796 assert(impTreeLast);
15797 assert(impTreeLast->gtOper == GT_STMT);
15798 assert(impTreeLast->gtStmt.gtStmtExpr->gtOper == GT_SWITCH);
15800 addStmt = impTreeLast;
15801 impTreeLast = impTreeLast->gtPrev;
15803 jmpCnt = block->bbJumpSwt->bbsCount;
15804 jmpTab = block->bbJumpSwt->bbsDstTab;
15808 tgtBlock = (*jmpTab);
15810 multRef |= tgtBlock->bbRefs;
15812 // Thanks to spill cliques, we should have assigned all or none
15813 assert((baseTmp == NO_BASE_TMP) || (baseTmp == tgtBlock->bbStkTempsIn));
15814 baseTmp = tgtBlock->bbStkTempsIn;
15819 } while (++jmpTab, --jmpCnt);
15823 case BBJ_CALLFINALLY:
15824 case BBJ_EHCATCHRET:
15826 case BBJ_EHFINALLYRET:
15827 case BBJ_EHFILTERRET:
15829 NO_WAY("can't have 'unreached' end of BB with non-empty stack");
15833 noway_assert(!"Unexpected bbJumpKind");
15837 assert(multRef >= 1);
15839 /* Do we have a base temp number? */
15841 bool newTemps = (baseTmp == NO_BASE_TMP);
15845 /* Grab enough temps for the whole stack */
15846 baseTmp = impGetSpillTmpBase(block);
15849 /* Spill all stack entries into temps */
15850 unsigned level, tempNum;
15852 JITDUMP("\nSpilling stack entries into temps\n");
15853 for (level = 0, tempNum = baseTmp; level < verCurrentState.esStackDepth; level++, tempNum++)
15855 GenTreePtr tree = verCurrentState.esStack[level].val;
15857 /* VC generates code where it pushes a byref from one branch, and an int (ldc.i4 0) from
15858 the other. This should merge to a byref in unverifiable code.
15859 However, if the branch which leaves the TYP_I_IMPL on the stack is imported first, the
15860 successor would be imported assuming there was a TYP_I_IMPL on
15861 the stack. Thus the value would not get GC-tracked. Hence,
15862 change the temp to TYP_BYREF and reimport the successors.
15863 Note: We should only allow this in unverifiable code.
15865 if (tree->gtType == TYP_BYREF && lvaTable[tempNum].lvType == TYP_I_IMPL && !verNeedsVerification())
15867 lvaTable[tempNum].lvType = TYP_BYREF;
15868 impReimportMarkSuccessors(block);
15872 #ifdef _TARGET_64BIT_
15873 if (genActualType(tree->gtType) == TYP_I_IMPL && lvaTable[tempNum].lvType == TYP_INT)
15875 if (tiVerificationNeeded && tgtBlock->bbEntryState != nullptr &&
15876 (tgtBlock->bbFlags & BBF_FAILED_VERIFICATION) == 0)
15878 // Merge the current state into the entry state of block;
15879 // the call to verMergeEntryStates must have changed
15880 // the entry state of the block by merging the int local var
15881 // and the native-int stack entry.
15882 bool changed = false;
15883 if (verMergeEntryStates(tgtBlock, &changed))
15885 impRetypeEntryStateTemps(tgtBlock);
15886 impReimportBlockPending(tgtBlock);
15891 tgtBlock->bbFlags |= BBF_FAILED_VERIFICATION;
15896 // Some other block in the spill clique set this to "int", but now we have "native int".
15897 // Change the type and go back to re-import any blocks that used the wrong type.
15898 lvaTable[tempNum].lvType = TYP_I_IMPL;
15899 reimportSpillClique = true;
15901 else if (genActualType(tree->gtType) == TYP_INT && lvaTable[tempNum].lvType == TYP_I_IMPL)
15903 // Spill clique has decided this should be "native int", but this block only pushes an "int".
15904 // Insert a sign-extension to "native int" so we match the clique.
15905 verCurrentState.esStack[level].val = gtNewCastNode(TYP_I_IMPL, tree, TYP_I_IMPL);
15908 // Consider the case where one branch left a 'byref' on the stack and the other leaves
15909 // an 'int'. On 32-bit, this is allowed (in non-verifiable code) since they are the same
15910 // size. JIT64 managed to make this work on 64-bit. For compatibility, we support JIT64
15911 // behavior instead of asserting and then generating bad code (where we save/restore the
15912 // low 32 bits of a byref pointer to an 'int' sized local). If the 'int' side has been
15913 // imported already, we need to change the type of the local and reimport the spill clique.
15914 // If the 'byref' side has imported, we insert a cast from int to 'native int' to match
15915 // the 'byref' size.
15916 if (!tiVerificationNeeded)
15918 if (genActualType(tree->gtType) == TYP_BYREF && lvaTable[tempNum].lvType == TYP_INT)
15920 // Some other block in the spill clique set this to "int", but now we have "byref".
15921 // Change the type and go back to re-import any blocks that used the wrong type.
15922 lvaTable[tempNum].lvType = TYP_BYREF;
15923 reimportSpillClique = true;
15925 else if (genActualType(tree->gtType) == TYP_INT && lvaTable[tempNum].lvType == TYP_BYREF)
15927 // Spill clique has decided this should be "byref", but this block only pushes an "int".
15928 // Insert a sign-extension to "native int" so we match the clique size.
15929 verCurrentState.esStack[level].val = gtNewCastNode(TYP_I_IMPL, tree, TYP_I_IMPL);
15932 #endif // _TARGET_64BIT_
15934 #if FEATURE_X87_DOUBLES
15935 // X87 stack doesn't differentiate between float/double
15936 // so promoting is no big deal.
15937 // For everybody else keep it as float until we have a collision and then promote
15938 // Just like for x64's TYP_INT<->TYP_I_IMPL
15940 if (multRef > 1 && tree->gtType == TYP_FLOAT)
15942 verCurrentState.esStack[level].val = gtNewCastNode(TYP_DOUBLE, tree, TYP_DOUBLE);
15945 #else // !FEATURE_X87_DOUBLES
15947 if (tree->gtType == TYP_DOUBLE && lvaTable[tempNum].lvType == TYP_FLOAT)
15949 // Some other block in the spill clique set this to "float", but now we have "double".
15950 // Change the type and go back to re-import any blocks that used the wrong type.
15951 lvaTable[tempNum].lvType = TYP_DOUBLE;
15952 reimportSpillClique = true;
15954 else if (tree->gtType == TYP_FLOAT && lvaTable[tempNum].lvType == TYP_DOUBLE)
15956 // Spill clique has decided this should be "double", but this block only pushes a "float".
15957 // Insert a cast to "double" so we match the clique.
15958 verCurrentState.esStack[level].val = gtNewCastNode(TYP_DOUBLE, tree, TYP_DOUBLE);
15961 #endif // FEATURE_X87_DOUBLES
15963 /* If addStmt has a reference to tempNum (can only happen if we
15964 are spilling to the temps already used by a previous block),
15965 we need to spill addStmt */
15967 if (addStmt && !newTemps && gtHasRef(addStmt->gtStmt.gtStmtExpr, tempNum, false))
15969 GenTreePtr addTree = addStmt->gtStmt.gtStmtExpr;
15971 if (addTree->gtOper == GT_JTRUE)
15973 GenTreePtr relOp = addTree->gtOp.gtOp1;
15974 assert(relOp->OperIsCompare());
15976 var_types type = genActualType(relOp->gtOp.gtOp1->TypeGet());
15978 if (gtHasRef(relOp->gtOp.gtOp1, tempNum, false))
15980 unsigned temp = lvaGrabTemp(true DEBUGARG("spill addStmt JTRUE ref Op1"));
15981 impAssignTempGen(temp, relOp->gtOp.gtOp1, level);
15982 type = genActualType(lvaTable[temp].TypeGet());
15983 relOp->gtOp.gtOp1 = gtNewLclvNode(temp, type);
15986 if (gtHasRef(relOp->gtOp.gtOp2, tempNum, false))
15988 unsigned temp = lvaGrabTemp(true DEBUGARG("spill addStmt JTRUE ref Op2"));
15989 impAssignTempGen(temp, relOp->gtOp.gtOp2, level);
15990 type = genActualType(lvaTable[temp].TypeGet());
15991 relOp->gtOp.gtOp2 = gtNewLclvNode(temp, type);
15996 assert(addTree->gtOper == GT_SWITCH && genActualType(addTree->gtOp.gtOp1->gtType) == TYP_I_IMPL);
15998 unsigned temp = lvaGrabTemp(true DEBUGARG("spill addStmt SWITCH"));
15999 impAssignTempGen(temp, addTree->gtOp.gtOp1, level);
16000 addTree->gtOp.gtOp1 = gtNewLclvNode(temp, TYP_I_IMPL);
16004 /* Spill the stack entry, and replace with the temp */
16006 if (!impSpillStackEntry(level, tempNum
16009 true, "Spill Stack Entry"
16015 BADCODE("bad stack state");
16018 // Oops. Something went wrong when spilling. Bad code.
16019 verHandleVerificationFailure(block DEBUGARG(true));
16025 /* Put back the 'jtrue'/'switch' if we removed it earlier */
16029 impAppendStmt(addStmt, (unsigned)CHECK_SPILL_NONE);
16033 // Some of the append/spill logic works on compCurBB
16035 assert(compCurBB == block);
16037 /* Save the tree list in the block */
16038 impEndTreeList(block);
16040 // impEndTreeList sets BBF_IMPORTED on the block
16041 // We do *NOT* want to set it later than this because
16042 // impReimportSpillClique might clear it if this block is both a
16043 // predecessor and successor in the current spill clique
16044 assert(block->bbFlags & BBF_IMPORTED);
16046 // If we had a int/native int, or float/double collision, we need to re-import
16047 if (reimportSpillClique)
16049 // This will re-import all the successors of block (as well as each of their predecessors)
16050 impReimportSpillClique(block);
16052 // For blocks that haven't been imported yet, we still need to mark them as pending import.
16053 for (unsigned i = 0; i < block->NumSucc(); i++)
16055 BasicBlock* succ = block->GetSucc(i);
16056 if ((succ->bbFlags & BBF_IMPORTED) == 0)
16058 impImportBlockPending(succ);
16062 else // the normal case
16064 // otherwise just import the successors of block
16066 /* Does this block jump to any other blocks? */
16067 for (unsigned i = 0; i < block->NumSucc(); i++)
16069 impImportBlockPending(block->GetSucc(i));
16074 #pragma warning(pop)
16077 /*****************************************************************************/
16079 // Ensures that "block" is a member of the list of BBs waiting to be imported, pushing it on the list if
16080 // necessary (and ensures that it is a member of the set of BB's on the list, by setting its byte in
16081 // impPendingBlockMembers). Merges the current verification state into the verification state of "block"
16082 // (its "pre-state").
16084 void Compiler::impImportBlockPending(BasicBlock* block)
16089 printf("\nimpImportBlockPending for BB%02u\n", block->bbNum);
16093 // We will add a block to the pending set if it has not already been imported (or needs to be re-imported),
16094 // or if it has, but merging in a predecessor's post-state changes the block's pre-state.
16095 // (When we're doing verification, we always attempt the merge to detect verification errors.)
16097 // If the block has not been imported, add to pending set.
16098 bool addToPending = ((block->bbFlags & BBF_IMPORTED) == 0);
16100 // Initialize bbEntryState just the first time we try to add this block to the pending list
16101 // Just because bbEntryState is NULL, doesn't mean the pre-state wasn't previously set
16102 // We use NULL to indicate the 'common' state to avoid memory allocation
16103 if ((block->bbEntryState == nullptr) && ((block->bbFlags & (BBF_IMPORTED | BBF_FAILED_VERIFICATION)) == 0) &&
16104 (impGetPendingBlockMember(block) == 0))
16106 verInitBBEntryState(block, &verCurrentState);
16107 assert(block->bbStkDepth == 0);
16108 block->bbStkDepth = static_cast<unsigned short>(verCurrentState.esStackDepth);
16109 assert(addToPending);
16110 assert(impGetPendingBlockMember(block) == 0);
16114 // The stack should have the same height on entry to the block from all its predecessors.
16115 if (block->bbStkDepth != verCurrentState.esStackDepth)
16119 sprintf_s(buffer, sizeof(buffer),
16120 "Block at offset %4.4x to %4.4x in %s entered with different stack depths.\n"
16121 "Previous depth was %d, current depth is %d",
16122 block->bbCodeOffs, block->bbCodeOffsEnd, info.compFullName, block->bbStkDepth,
16123 verCurrentState.esStackDepth);
16124 buffer[400 - 1] = 0;
16127 NO_WAY("Block entered with different stack depths");
16131 // Additionally, if we need to verify, merge the verification state.
16132 if (tiVerificationNeeded)
16134 // Merge the current state into the entry state of block; if this does not change the entry state
16135 // by merging, do not add the block to the pending-list.
16136 bool changed = false;
16137 if (!verMergeEntryStates(block, &changed))
16139 block->bbFlags |= BBF_FAILED_VERIFICATION;
16140 addToPending = true; // We will pop it off, and check the flag set above.
16144 addToPending = true;
16146 JITDUMP("Adding BB%02u to pending set due to new merge result\n", block->bbNum);
16155 if (block->bbStkDepth > 0)
16157 // We need to fix the types of any spill temps that might have changed:
16158 // int->native int, float->double, int->byref, etc.
16159 impRetypeEntryStateTemps(block);
16162 // OK, we must add to the pending list, if it's not already in it.
16163 if (impGetPendingBlockMember(block) != 0)
16169 // Get an entry to add to the pending list
16173 if (impPendingFree)
16175 // We can reuse one of the freed up dscs.
16176 dsc = impPendingFree;
16177 impPendingFree = dsc->pdNext;
16181 // We have to create a new dsc
16182 dsc = new (this, CMK_Unknown) PendingDsc;
16186 dsc->pdSavedStack.ssDepth = verCurrentState.esStackDepth;
16187 dsc->pdThisPtrInit = verCurrentState.thisInitialized;
16189 // Save the stack trees for later
16191 if (verCurrentState.esStackDepth)
16193 impSaveStackState(&dsc->pdSavedStack, false);
16196 // Add the entry to the pending list
16198 dsc->pdNext = impPendingList;
16199 impPendingList = dsc;
16200 impSetPendingBlockMember(block, 1); // And indicate that it's now a member of the set.
16202 // Various assertions require us to now to consider the block as not imported (at least for
16203 // the final time...)
16204 block->bbFlags &= ~BBF_IMPORTED;
16209 printf("Added PendingDsc - %08p for BB%02u\n", dspPtr(dsc), block->bbNum);
16214 /*****************************************************************************/
16216 // Ensures that "block" is a member of the list of BBs waiting to be imported, pushing it on the list if
16217 // necessary (and ensures that it is a member of the set of BB's on the list, by setting its byte in
16218 // impPendingBlockMembers). Does *NOT* change the existing "pre-state" of the block.
16220 void Compiler::impReimportBlockPending(BasicBlock* block)
16222 JITDUMP("\nimpReimportBlockPending for BB%02u", block->bbNum);
16224 assert(block->bbFlags & BBF_IMPORTED);
16226 // OK, we must add to the pending list, if it's not already in it.
16227 if (impGetPendingBlockMember(block) != 0)
16232 // Get an entry to add to the pending list
16236 if (impPendingFree)
16238 // We can reuse one of the freed up dscs.
16239 dsc = impPendingFree;
16240 impPendingFree = dsc->pdNext;
16244 // We have to create a new dsc
16245 dsc = new (this, CMK_ImpStack) PendingDsc;
16250 if (block->bbEntryState)
16252 dsc->pdThisPtrInit = block->bbEntryState->thisInitialized;
16253 dsc->pdSavedStack.ssDepth = block->bbEntryState->esStackDepth;
16254 dsc->pdSavedStack.ssTrees = block->bbEntryState->esStack;
16258 dsc->pdThisPtrInit = TIS_Bottom;
16259 dsc->pdSavedStack.ssDepth = 0;
16260 dsc->pdSavedStack.ssTrees = nullptr;
16263 // Add the entry to the pending list
16265 dsc->pdNext = impPendingList;
16266 impPendingList = dsc;
16267 impSetPendingBlockMember(block, 1); // And indicate that it's now a member of the set.
16269 // Various assertions require us to now to consider the block as not imported (at least for
16270 // the final time...)
16271 block->bbFlags &= ~BBF_IMPORTED;
16276 printf("Added PendingDsc - %08p for BB%02u\n", dspPtr(dsc), block->bbNum);
16281 void* Compiler::BlockListNode::operator new(size_t sz, Compiler* comp)
16283 if (comp->impBlockListNodeFreeList == nullptr)
16285 return (BlockListNode*)comp->compGetMem(sizeof(BlockListNode), CMK_BasicBlock);
16289 BlockListNode* res = comp->impBlockListNodeFreeList;
16290 comp->impBlockListNodeFreeList = res->m_next;
16295 void Compiler::FreeBlockListNode(Compiler::BlockListNode* node)
16297 node->m_next = impBlockListNodeFreeList;
16298 impBlockListNodeFreeList = node;
16301 void Compiler::impWalkSpillCliqueFromPred(BasicBlock* block, SpillCliqueWalker* callback)
16305 noway_assert(!fgComputePredsDone);
16306 if (!fgCheapPredsValid)
16308 fgComputeCheapPreds();
16311 BlockListNode* succCliqueToDo = nullptr;
16312 BlockListNode* predCliqueToDo = new (this) BlockListNode(block);
16316 // Look at the successors of every member of the predecessor to-do list.
16317 while (predCliqueToDo != nullptr)
16319 BlockListNode* node = predCliqueToDo;
16320 predCliqueToDo = node->m_next;
16321 BasicBlock* blk = node->m_blk;
16322 FreeBlockListNode(node);
16324 for (unsigned succNum = 0; succNum < blk->NumSucc(); succNum++)
16326 BasicBlock* succ = blk->GetSucc(succNum);
16327 // If it's not already in the clique, add it, and also add it
16328 // as a member of the successor "toDo" set.
16329 if (impSpillCliqueGetMember(SpillCliqueSucc, succ) == 0)
16331 callback->Visit(SpillCliqueSucc, succ);
16332 impSpillCliqueSetMember(SpillCliqueSucc, succ, 1);
16333 succCliqueToDo = new (this) BlockListNode(succ, succCliqueToDo);
16338 // Look at the predecessors of every member of the successor to-do list.
16339 while (succCliqueToDo != nullptr)
16341 BlockListNode* node = succCliqueToDo;
16342 succCliqueToDo = node->m_next;
16343 BasicBlock* blk = node->m_blk;
16344 FreeBlockListNode(node);
16346 for (BasicBlockList* pred = blk->bbCheapPreds; pred != nullptr; pred = pred->next)
16348 BasicBlock* predBlock = pred->block;
16349 // If it's not already in the clique, add it, and also add it
16350 // as a member of the predecessor "toDo" set.
16351 if (impSpillCliqueGetMember(SpillCliquePred, predBlock) == 0)
16353 callback->Visit(SpillCliquePred, predBlock);
16354 impSpillCliqueSetMember(SpillCliquePred, predBlock, 1);
16355 predCliqueToDo = new (this) BlockListNode(predBlock, predCliqueToDo);
16362 // If this fails, it means we didn't walk the spill clique properly and somehow managed
16363 // miss walking back to include the predecessor we started from.
16364 // This most likely cause: missing or out of date bbPreds
16365 assert(impSpillCliqueGetMember(SpillCliquePred, block) != 0);
16368 void Compiler::SetSpillTempsBase::Visit(SpillCliqueDir predOrSucc, BasicBlock* blk)
16370 if (predOrSucc == SpillCliqueSucc)
16372 assert(blk->bbStkTempsIn == NO_BASE_TMP); // Should not already be a member of a clique as a successor.
16373 blk->bbStkTempsIn = m_baseTmp;
16377 assert(predOrSucc == SpillCliquePred);
16378 assert(blk->bbStkTempsOut == NO_BASE_TMP); // Should not already be a member of a clique as a predecessor.
16379 blk->bbStkTempsOut = m_baseTmp;
16383 void Compiler::ReimportSpillClique::Visit(SpillCliqueDir predOrSucc, BasicBlock* blk)
16385 // For Preds we could be a little smarter and just find the existing store
16386 // and re-type it/add a cast, but that is complicated and hopefully very rare, so
16387 // just re-import the whole block (just like we do for successors)
16389 if (((blk->bbFlags & BBF_IMPORTED) == 0) && (m_pComp->impGetPendingBlockMember(blk) == 0))
16391 // If we haven't imported this block and we're not going to (because it isn't on
16392 // the pending list) then just ignore it for now.
16394 // This block has either never been imported (EntryState == NULL) or it failed
16395 // verification. Neither state requires us to force it to be imported now.
16396 assert((blk->bbEntryState == nullptr) || (blk->bbFlags & BBF_FAILED_VERIFICATION));
16400 // For successors we have a valid verCurrentState, so just mark them for reimport
16401 // the 'normal' way
16402 // Unlike predecessors, we *DO* need to reimport the current block because the
16403 // initial import had the wrong entry state types.
16404 // Similarly, blocks that are currently on the pending list, still need to call
16405 // impImportBlockPending to fixup their entry state.
16406 if (predOrSucc == SpillCliqueSucc)
16408 m_pComp->impReimportMarkBlock(blk);
16410 // Set the current stack state to that of the blk->bbEntryState
16411 m_pComp->verResetCurrentState(blk, &m_pComp->verCurrentState);
16412 assert(m_pComp->verCurrentState.thisInitialized == blk->bbThisOnEntry());
16414 m_pComp->impImportBlockPending(blk);
16416 else if ((blk != m_pComp->compCurBB) && ((blk->bbFlags & BBF_IMPORTED) != 0))
16418 // As described above, we are only visiting predecessors so they can
16419 // add the appropriate casts, since we have already done that for the current
16420 // block, it does not need to be reimported.
16421 // Nor do we need to reimport blocks that are still pending, but not yet
16424 // For predecessors, we have no state to seed the EntryState, so we just have
16425 // to assume the existing one is correct.
16426 // If the block is also a successor, it will get the EntryState properly
16427 // updated when it is visited as a successor in the above "if" block.
16428 assert(predOrSucc == SpillCliquePred);
16429 m_pComp->impReimportBlockPending(blk);
16433 // Re-type the incoming lclVar nodes to match the varDsc.
16434 void Compiler::impRetypeEntryStateTemps(BasicBlock* blk)
16436 if (blk->bbEntryState != nullptr)
16438 EntryState* es = blk->bbEntryState;
16439 for (unsigned level = 0; level < es->esStackDepth; level++)
16441 GenTreePtr tree = es->esStack[level].val;
16442 if ((tree->gtOper == GT_LCL_VAR) || (tree->gtOper == GT_LCL_FLD))
16444 unsigned lclNum = tree->gtLclVarCommon.gtLclNum;
16445 noway_assert(lclNum < lvaCount);
16446 LclVarDsc* varDsc = lvaTable + lclNum;
16447 es->esStack[level].val->gtType = varDsc->TypeGet();
16453 unsigned Compiler::impGetSpillTmpBase(BasicBlock* block)
16455 if (block->bbStkTempsOut != NO_BASE_TMP)
16457 return block->bbStkTempsOut;
16463 printf("\n*************** In impGetSpillTmpBase(BB%02u)\n", block->bbNum);
16467 // Otherwise, choose one, and propagate to all members of the spill clique.
16468 // Grab enough temps for the whole stack.
16469 unsigned baseTmp = lvaGrabTemps(verCurrentState.esStackDepth DEBUGARG("IL Stack Entries"));
16470 SetSpillTempsBase callback(baseTmp);
16472 // We do *NOT* need to reset the SpillClique*Members because a block can only be the predecessor
16473 // to one spill clique, and similarly can only be the sucessor to one spill clique
16474 impWalkSpillCliqueFromPred(block, &callback);
16479 void Compiler::impReimportSpillClique(BasicBlock* block)
16484 printf("\n*************** In impReimportSpillClique(BB%02u)\n", block->bbNum);
16488 // If we get here, it is because this block is already part of a spill clique
16489 // and one predecessor had an outgoing live stack slot of type int, and this
16490 // block has an outgoing live stack slot of type native int.
16491 // We need to reset these before traversal because they have already been set
16492 // by the previous walk to determine all the members of the spill clique.
16493 impInlineRoot()->impSpillCliquePredMembers.Reset();
16494 impInlineRoot()->impSpillCliqueSuccMembers.Reset();
16496 ReimportSpillClique callback(this);
16498 impWalkSpillCliqueFromPred(block, &callback);
16501 // Set the pre-state of "block" (which should not have a pre-state allocated) to
16502 // a copy of "srcState", cloning tree pointers as required.
16503 void Compiler::verInitBBEntryState(BasicBlock* block, EntryState* srcState)
16505 if (srcState->esStackDepth == 0 && srcState->thisInitialized == TIS_Bottom)
16507 block->bbEntryState = nullptr;
16511 block->bbEntryState = (EntryState*)compGetMemA(sizeof(EntryState));
16513 // block->bbEntryState.esRefcount = 1;
16515 block->bbEntryState->esStackDepth = srcState->esStackDepth;
16516 block->bbEntryState->thisInitialized = TIS_Bottom;
16518 if (srcState->esStackDepth > 0)
16520 block->bbSetStack(new (this, CMK_Unknown) StackEntry[srcState->esStackDepth]);
16521 unsigned stackSize = srcState->esStackDepth * sizeof(StackEntry);
16523 memcpy(block->bbEntryState->esStack, srcState->esStack, stackSize);
16524 for (unsigned level = 0; level < srcState->esStackDepth; level++)
16526 GenTreePtr tree = srcState->esStack[level].val;
16527 block->bbEntryState->esStack[level].val = gtCloneExpr(tree);
16531 if (verTrackObjCtorInitState)
16533 verSetThisInit(block, srcState->thisInitialized);
16539 void Compiler::verSetThisInit(BasicBlock* block, ThisInitState tis)
16541 assert(tis != TIS_Bottom); // Precondition.
16542 if (block->bbEntryState == nullptr)
16544 block->bbEntryState = new (this, CMK_Unknown) EntryState();
16547 block->bbEntryState->thisInitialized = tis;
16551 * Resets the current state to the state at the start of the basic block
16553 void Compiler::verResetCurrentState(BasicBlock* block, EntryState* destState)
16556 if (block->bbEntryState == nullptr)
16558 destState->esStackDepth = 0;
16559 destState->thisInitialized = TIS_Bottom;
16563 destState->esStackDepth = block->bbEntryState->esStackDepth;
16565 if (destState->esStackDepth > 0)
16567 unsigned stackSize = destState->esStackDepth * sizeof(StackEntry);
16569 memcpy(destState->esStack, block->bbStackOnEntry(), stackSize);
16572 destState->thisInitialized = block->bbThisOnEntry();
16577 ThisInitState BasicBlock::bbThisOnEntry()
16579 return bbEntryState ? bbEntryState->thisInitialized : TIS_Bottom;
16582 unsigned BasicBlock::bbStackDepthOnEntry()
16584 return (bbEntryState ? bbEntryState->esStackDepth : 0);
16587 void BasicBlock::bbSetStack(void* stackBuffer)
16589 assert(bbEntryState);
16590 assert(stackBuffer);
16591 bbEntryState->esStack = (StackEntry*)stackBuffer;
16594 StackEntry* BasicBlock::bbStackOnEntry()
16596 assert(bbEntryState);
16597 return bbEntryState->esStack;
16600 void Compiler::verInitCurrentState()
16602 verTrackObjCtorInitState = FALSE;
16603 verCurrentState.thisInitialized = TIS_Bottom;
16605 if (tiVerificationNeeded)
16607 // Track this ptr initialization
16608 if (!info.compIsStatic && (info.compFlags & CORINFO_FLG_CONSTRUCTOR) && lvaTable[0].lvVerTypeInfo.IsObjRef())
16610 verTrackObjCtorInitState = TRUE;
16611 verCurrentState.thisInitialized = TIS_Uninit;
16615 // initialize stack info
16617 verCurrentState.esStackDepth = 0;
16618 assert(verCurrentState.esStack != nullptr);
16620 // copy current state to entry state of first BB
16621 verInitBBEntryState(fgFirstBB, &verCurrentState);
16624 Compiler* Compiler::impInlineRoot()
16626 if (impInlineInfo == nullptr)
16632 return impInlineInfo->InlineRoot;
16636 BYTE Compiler::impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk)
16638 if (predOrSucc == SpillCliquePred)
16640 return impInlineRoot()->impSpillCliquePredMembers.Get(blk->bbInd());
16644 assert(predOrSucc == SpillCliqueSucc);
16645 return impInlineRoot()->impSpillCliqueSuccMembers.Get(blk->bbInd());
16649 void Compiler::impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val)
16651 if (predOrSucc == SpillCliquePred)
16653 impInlineRoot()->impSpillCliquePredMembers.Set(blk->bbInd(), val);
16657 assert(predOrSucc == SpillCliqueSucc);
16658 impInlineRoot()->impSpillCliqueSuccMembers.Set(blk->bbInd(), val);
16662 /*****************************************************************************
16664 * Convert the instrs ("import") into our internal format (trees). The
16665 * basic flowgraph has already been constructed and is passed in.
16668 void Compiler::impImport(BasicBlock* method)
16673 printf("*************** In impImport() for %s\n", info.compFullName);
16677 /* Allocate the stack contents */
16679 if (info.compMaxStack <= sizeof(impSmallStack) / sizeof(impSmallStack[0]))
16681 /* Use local variable, don't waste time allocating on the heap */
16683 impStkSize = sizeof(impSmallStack) / sizeof(impSmallStack[0]);
16684 verCurrentState.esStack = impSmallStack;
16688 impStkSize = info.compMaxStack;
16689 verCurrentState.esStack = new (this, CMK_ImpStack) StackEntry[impStkSize];
16692 // initialize the entry state at start of method
16693 verInitCurrentState();
16695 // Initialize stuff related to figuring "spill cliques" (see spec comment for impGetSpillTmpBase).
16696 Compiler* inlineRoot = impInlineRoot();
16697 if (this == inlineRoot) // These are only used on the root of the inlining tree.
16699 // We have initialized these previously, but to size 0. Make them larger.
16700 impPendingBlockMembers.Init(getAllocator(), fgBBNumMax * 2);
16701 impSpillCliquePredMembers.Init(getAllocator(), fgBBNumMax * 2);
16702 impSpillCliqueSuccMembers.Init(getAllocator(), fgBBNumMax * 2);
16704 inlineRoot->impPendingBlockMembers.Reset(fgBBNumMax * 2);
16705 inlineRoot->impSpillCliquePredMembers.Reset(fgBBNumMax * 2);
16706 inlineRoot->impSpillCliqueSuccMembers.Reset(fgBBNumMax * 2);
16707 impBlockListNodeFreeList = nullptr;
16710 impLastILoffsStmt = nullptr;
16711 impNestedStackSpill = false;
16713 impBoxTemp = BAD_VAR_NUM;
16715 impPendingList = impPendingFree = nullptr;
16717 /* Add the entry-point to the worker-list */
16719 // Skip leading internal blocks. There can be one as a leading scratch BB, and more
16720 // from EH normalization.
16721 // NOTE: It might be possible to always just put fgFirstBB on the pending list, and let everything else just fall
16723 for (; method->bbFlags & BBF_INTERNAL; method = method->bbNext)
16725 // Treat these as imported.
16726 assert(method->bbJumpKind == BBJ_NONE); // We assume all the leading ones are fallthrough.
16727 JITDUMP("Marking leading BBF_INTERNAL block BB%02u as BBF_IMPORTED\n", method->bbNum);
16728 method->bbFlags |= BBF_IMPORTED;
16731 impImportBlockPending(method);
16733 /* Import blocks in the worker-list until there are no more */
16735 while (impPendingList)
16737 /* Remove the entry at the front of the list */
16739 PendingDsc* dsc = impPendingList;
16740 impPendingList = impPendingList->pdNext;
16741 impSetPendingBlockMember(dsc->pdBB, 0);
16743 /* Restore the stack state */
16745 verCurrentState.thisInitialized = dsc->pdThisPtrInit;
16746 verCurrentState.esStackDepth = dsc->pdSavedStack.ssDepth;
16747 if (verCurrentState.esStackDepth)
16749 impRestoreStackState(&dsc->pdSavedStack);
16752 /* Add the entry to the free list for reuse */
16754 dsc->pdNext = impPendingFree;
16755 impPendingFree = dsc;
16757 /* Now import the block */
16759 if (dsc->pdBB->bbFlags & BBF_FAILED_VERIFICATION)
16762 #ifdef _TARGET_64BIT_
16763 // On AMD64, during verification we have to match JIT64 behavior since the VM is very tighly
16764 // coupled with the JIT64 IL Verification logic. Look inside verHandleVerificationFailure
16765 // method for further explanation on why we raise this exception instead of making the jitted
16766 // code throw the verification exception during execution.
16767 if (tiVerificationNeeded && opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IMPORT_ONLY))
16769 BADCODE("Basic block marked as not verifiable");
16772 #endif // _TARGET_64BIT_
16774 verConvertBBToThrowVerificationException(dsc->pdBB DEBUGARG(true));
16775 impEndTreeList(dsc->pdBB);
16780 impImportBlock(dsc->pdBB);
16782 if (compDonotInline())
16786 if (compIsForImportOnly() && !tiVerificationNeeded)
16794 if (verbose && info.compXcptnsCount)
16796 printf("\nAfter impImport() added block for try,catch,finally");
16797 fgDispBasicBlocks();
16801 // Used in impImportBlockPending() for STRESS_CHK_REIMPORT
16802 for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
16804 block->bbFlags &= ~BBF_VISITED;
16808 assert(!compIsForInlining() || !tiVerificationNeeded);
16811 // Checks if a typeinfo (usually stored in the type stack) is a struct.
16812 // The invariant here is that if it's not a ref or a method and has a class handle
16813 // it's a valuetype
16814 bool Compiler::impIsValueType(typeInfo* pTypeInfo)
16816 if (pTypeInfo && pTypeInfo->IsValueClassWithClsHnd())
16826 /*****************************************************************************
16827 * Check to see if the tree is the address of a local or
16828 the address of a field in a local.
16830 *lclVarTreeOut will contain the GT_LCL_VAR tree when it returns TRUE.
16834 BOOL Compiler::impIsAddressInLocal(GenTreePtr tree, GenTreePtr* lclVarTreeOut)
16836 if (tree->gtOper != GT_ADDR)
16841 GenTreePtr op = tree->gtOp.gtOp1;
16842 while (op->gtOper == GT_FIELD)
16844 op = op->gtField.gtFldObj;
16845 if (op && op->gtOper == GT_ADDR) // Skip static fields where op will be NULL.
16847 op = op->gtOp.gtOp1;
16855 if (op->gtOper == GT_LCL_VAR)
16857 *lclVarTreeOut = op;
16866 //------------------------------------------------------------------------
16867 // impMakeDiscretionaryInlineObservations: make observations that help
16868 // determine the profitability of a discretionary inline
16871 // pInlineInfo -- InlineInfo for the inline, or null for the prejit root
16872 // inlineResult -- InlineResult accumulating information about this inline
16875 // If inlining or prejitting the root, this method also makes
16876 // various observations about the method that factor into inline
16877 // decisions. It sets `compNativeSizeEstimate` as a side effect.
16879 void Compiler::impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult)
16881 assert(pInlineInfo != nullptr && compIsForInlining() || // Perform the actual inlining.
16882 pInlineInfo == nullptr && !compIsForInlining() // Calculate the static inlining hint for ngen.
16885 // If we're really inlining, we should just have one result in play.
16886 assert((pInlineInfo == nullptr) || (inlineResult == pInlineInfo->inlineResult));
16888 // If this is a "forceinline" method, the JIT probably shouldn't have gone
16889 // to the trouble of estimating the native code size. Even if it did, it
16890 // shouldn't be relying on the result of this method.
16891 assert(inlineResult->GetObservation() == InlineObservation::CALLEE_IS_DISCRETIONARY_INLINE);
16893 // Note if the caller contains NEWOBJ or NEWARR.
16894 Compiler* rootCompiler = impInlineRoot();
16896 if ((rootCompiler->optMethodFlags & OMF_HAS_NEWARRAY) != 0)
16898 inlineResult->Note(InlineObservation::CALLER_HAS_NEWARRAY);
16901 if ((rootCompiler->optMethodFlags & OMF_HAS_NEWOBJ) != 0)
16903 inlineResult->Note(InlineObservation::CALLER_HAS_NEWOBJ);
16906 bool calleeIsStatic = (info.compFlags & CORINFO_FLG_STATIC) != 0;
16907 bool isSpecialMethod = (info.compFlags & CORINFO_FLG_CONSTRUCTOR) != 0;
16909 if (isSpecialMethod)
16911 if (calleeIsStatic)
16913 inlineResult->Note(InlineObservation::CALLEE_IS_CLASS_CTOR);
16917 inlineResult->Note(InlineObservation::CALLEE_IS_INSTANCE_CTOR);
16920 else if (!calleeIsStatic)
16922 // Callee is an instance method.
16924 // Check if the callee has the same 'this' as the root.
16925 if (pInlineInfo != nullptr)
16927 GenTreePtr thisArg = pInlineInfo->iciCall->gtCall.gtCallObjp;
16929 bool isSameThis = impIsThis(thisArg);
16930 inlineResult->NoteBool(InlineObservation::CALLSITE_IS_SAME_THIS, isSameThis);
16934 // Note if the callee's class is a promotable struct
16935 if ((info.compClassAttr & CORINFO_FLG_VALUECLASS) != 0)
16937 lvaStructPromotionInfo structPromotionInfo;
16938 lvaCanPromoteStructType(info.compClassHnd, &structPromotionInfo, false);
16939 if (structPromotionInfo.canPromote)
16941 inlineResult->Note(InlineObservation::CALLEE_CLASS_PROMOTABLE);
16945 #ifdef FEATURE_SIMD
16947 // Note if this method is has SIMD args or return value
16948 if (pInlineInfo != nullptr && pInlineInfo->hasSIMDTypeArgLocalOrReturn)
16950 inlineResult->Note(InlineObservation::CALLEE_HAS_SIMD);
16953 #endif // FEATURE_SIMD
16955 // Roughly classify callsite frequency.
16956 InlineCallsiteFrequency frequency = InlineCallsiteFrequency::UNUSED;
16958 // If this is a prejit root, or a maximally hot block...
16959 if ((pInlineInfo == nullptr) || (pInlineInfo->iciBlock->bbWeight >= BB_MAX_WEIGHT))
16961 frequency = InlineCallsiteFrequency::HOT;
16963 // No training data. Look for loop-like things.
16964 // We consider a recursive call loop-like. Do not give the inlining boost to the method itself.
16965 // However, give it to things nearby.
16966 else if ((pInlineInfo->iciBlock->bbFlags & BBF_BACKWARD_JUMP) &&
16967 (pInlineInfo->fncHandle != pInlineInfo->inlineCandidateInfo->ilCallerHandle))
16969 frequency = InlineCallsiteFrequency::LOOP;
16971 else if ((pInlineInfo->iciBlock->bbFlags & BBF_PROF_WEIGHT) && (pInlineInfo->iciBlock->bbWeight > BB_ZERO_WEIGHT))
16973 frequency = InlineCallsiteFrequency::WARM;
16975 // Now modify the multiplier based on where we're called from.
16976 else if (pInlineInfo->iciBlock->isRunRarely() || ((info.compFlags & FLG_CCTOR) == FLG_CCTOR))
16978 frequency = InlineCallsiteFrequency::RARE;
16982 frequency = InlineCallsiteFrequency::BORING;
16985 // Also capture the block weight of the call site. In the prejit
16986 // root case, assume there's some hot call site for this method.
16987 unsigned weight = 0;
16989 if (pInlineInfo != nullptr)
16991 weight = pInlineInfo->iciBlock->bbWeight;
16995 weight = BB_MAX_WEIGHT;
16998 inlineResult->NoteInt(InlineObservation::CALLSITE_FREQUENCY, static_cast<int>(frequency));
16999 inlineResult->NoteInt(InlineObservation::CALLSITE_WEIGHT, static_cast<int>(weight));
17002 /*****************************************************************************
17003 This method makes STATIC inlining decision based on the IL code.
17004 It should not make any inlining decision based on the context.
17005 If forceInline is true, then the inlining decision should not depend on
17006 performance heuristics (code size, etc.).
17009 void Compiler::impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
17010 CORINFO_METHOD_INFO* methInfo,
17012 InlineResult* inlineResult)
17014 unsigned codeSize = methInfo->ILCodeSize;
17016 // We shouldn't have made up our minds yet...
17017 assert(!inlineResult->IsDecided());
17019 if (methInfo->EHcount)
17021 inlineResult->NoteFatal(InlineObservation::CALLEE_HAS_EH);
17025 if ((methInfo->ILCode == nullptr) || (codeSize == 0))
17027 inlineResult->NoteFatal(InlineObservation::CALLEE_HAS_NO_BODY);
17031 // For now we don't inline varargs (import code can't handle it)
17033 if (methInfo->args.isVarArg())
17035 inlineResult->NoteFatal(InlineObservation::CALLEE_HAS_MANAGED_VARARGS);
17039 // Reject if it has too many locals.
17040 // This is currently an implementation limit due to fixed-size arrays in the
17041 // inline info, rather than a performance heuristic.
17043 inlineResult->NoteInt(InlineObservation::CALLEE_NUMBER_OF_LOCALS, methInfo->locals.numArgs);
17045 if (methInfo->locals.numArgs > MAX_INL_LCLS)
17047 inlineResult->NoteFatal(InlineObservation::CALLEE_TOO_MANY_LOCALS);
17051 // Make sure there aren't too many arguments.
17052 // This is currently an implementation limit due to fixed-size arrays in the
17053 // inline info, rather than a performance heuristic.
17055 inlineResult->NoteInt(InlineObservation::CALLEE_NUMBER_OF_ARGUMENTS, methInfo->args.numArgs);
17057 if (methInfo->args.numArgs > MAX_INL_ARGS)
17059 inlineResult->NoteFatal(InlineObservation::CALLEE_TOO_MANY_ARGUMENTS);
17063 // Note force inline state
17065 inlineResult->NoteBool(InlineObservation::CALLEE_IS_FORCE_INLINE, forceInline);
17067 // Note IL code size
17069 inlineResult->NoteInt(InlineObservation::CALLEE_IL_CODE_SIZE, codeSize);
17071 if (inlineResult->IsFailure())
17076 // Make sure maxstack is not too big
17078 inlineResult->NoteInt(InlineObservation::CALLEE_MAXSTACK, methInfo->maxStack);
17080 if (inlineResult->IsFailure())
17086 /*****************************************************************************
17089 void Compiler::impCheckCanInline(GenTreePtr call,
17090 CORINFO_METHOD_HANDLE fncHandle,
17092 CORINFO_CONTEXT_HANDLE exactContextHnd,
17093 InlineCandidateInfo** ppInlineCandidateInfo,
17094 InlineResult* inlineResult)
17096 // Either EE or JIT might throw exceptions below.
17097 // If that happens, just don't inline the method.
17103 CORINFO_METHOD_HANDLE fncHandle;
17105 CORINFO_CONTEXT_HANDLE exactContextHnd;
17106 InlineResult* result;
17107 InlineCandidateInfo** ppInlineCandidateInfo;
17108 } param = {nullptr};
17110 param.pThis = this;
17112 param.fncHandle = fncHandle;
17113 param.methAttr = methAttr;
17114 param.exactContextHnd = (exactContextHnd != nullptr) ? exactContextHnd : MAKE_METHODCONTEXT(fncHandle);
17115 param.result = inlineResult;
17116 param.ppInlineCandidateInfo = ppInlineCandidateInfo;
17118 bool success = eeRunWithErrorTrap<Param>(
17119 [](Param* pParam) {
17120 DWORD dwRestrictions = 0;
17121 CorInfoInitClassResult initClassResult;
17124 const char* methodName;
17125 const char* className;
17126 methodName = pParam->pThis->eeGetMethodName(pParam->fncHandle, &className);
17128 if (JitConfig.JitNoInline())
17130 pParam->result->NoteFatal(InlineObservation::CALLEE_IS_JIT_NOINLINE);
17135 /* Try to get the code address/size for the method */
17137 CORINFO_METHOD_INFO methInfo;
17138 if (!pParam->pThis->info.compCompHnd->getMethodInfo(pParam->fncHandle, &methInfo))
17140 pParam->result->NoteFatal(InlineObservation::CALLEE_NO_METHOD_INFO);
17145 forceInline = !!(pParam->methAttr & CORINFO_FLG_FORCEINLINE);
17147 pParam->pThis->impCanInlineIL(pParam->fncHandle, &methInfo, forceInline, pParam->result);
17149 if (pParam->result->IsFailure())
17151 assert(pParam->result->IsNever());
17155 // Speculatively check if initClass() can be done.
17156 // If it can be done, we will try to inline the method. If inlining
17157 // succeeds, then we will do the non-speculative initClass() and commit it.
17158 // If this speculative call to initClass() fails, there is no point
17159 // trying to inline this method.
17161 pParam->pThis->info.compCompHnd->initClass(nullptr /* field */, pParam->fncHandle /* method */,
17162 pParam->exactContextHnd /* context */,
17163 TRUE /* speculative */);
17165 if (initClassResult & CORINFO_INITCLASS_DONT_INLINE)
17167 pParam->result->NoteFatal(InlineObservation::CALLSITE_CLASS_INIT_FAILURE_SPEC);
17171 // Given the EE the final say in whether to inline or not.
17172 // This should be last since for verifiable code, this can be expensive
17174 /* VM Inline check also ensures that the method is verifiable if needed */
17175 CorInfoInline vmResult;
17176 vmResult = pParam->pThis->info.compCompHnd->canInline(pParam->pThis->info.compMethodHnd, pParam->fncHandle,
17179 if (vmResult == INLINE_FAIL)
17181 pParam->result->NoteFatal(InlineObservation::CALLSITE_IS_VM_NOINLINE);
17183 else if (vmResult == INLINE_NEVER)
17185 pParam->result->NoteFatal(InlineObservation::CALLEE_IS_VM_NOINLINE);
17188 if (pParam->result->IsFailure())
17190 // Make sure not to report this one. It was already reported by the VM.
17191 pParam->result->SetReported();
17195 // check for unsupported inlining restrictions
17196 assert((dwRestrictions & ~(INLINE_RESPECT_BOUNDARY | INLINE_NO_CALLEE_LDSTR | INLINE_SAME_THIS)) == 0);
17198 if (dwRestrictions & INLINE_SAME_THIS)
17200 GenTreePtr thisArg = pParam->call->gtCall.gtCallObjp;
17203 if (!pParam->pThis->impIsThis(thisArg))
17205 pParam->result->NoteFatal(InlineObservation::CALLSITE_REQUIRES_SAME_THIS);
17210 /* Get the method properties */
17212 CORINFO_CLASS_HANDLE clsHandle;
17213 clsHandle = pParam->pThis->info.compCompHnd->getMethodClass(pParam->fncHandle);
17215 clsAttr = pParam->pThis->info.compCompHnd->getClassAttribs(clsHandle);
17217 /* Get the return type */
17219 var_types fncRetType;
17220 fncRetType = pParam->call->TypeGet();
17223 var_types fncRealRetType;
17224 fncRealRetType = JITtype2varType(methInfo.args.retType);
17226 assert((genActualType(fncRealRetType) == genActualType(fncRetType)) ||
17227 // <BUGNUM> VSW 288602 </BUGNUM>
17228 // In case of IJW, we allow to assign a native pointer to a BYREF.
17229 (fncRetType == TYP_BYREF && methInfo.args.retType == CORINFO_TYPE_PTR) ||
17230 (varTypeIsStruct(fncRetType) && (fncRealRetType == TYP_STRUCT)));
17234 // Allocate an InlineCandidateInfo structure
17236 InlineCandidateInfo* pInfo;
17237 pInfo = new (pParam->pThis, CMK_Inlining) InlineCandidateInfo;
17239 pInfo->dwRestrictions = dwRestrictions;
17240 pInfo->methInfo = methInfo;
17241 pInfo->methAttr = pParam->methAttr;
17242 pInfo->clsHandle = clsHandle;
17243 pInfo->clsAttr = clsAttr;
17244 pInfo->fncRetType = fncRetType;
17245 pInfo->exactContextHnd = pParam->exactContextHnd;
17246 pInfo->ilCallerHandle = pParam->pThis->info.compMethodHnd;
17247 pInfo->initClassResult = initClassResult;
17249 *(pParam->ppInlineCandidateInfo) = pInfo;
17256 param.result->NoteFatal(InlineObservation::CALLSITE_COMPILATION_ERROR);
17260 void Compiler::impInlineRecordArgInfo(InlineInfo* pInlineInfo,
17261 GenTreePtr curArgVal,
17263 InlineResult* inlineResult)
17265 InlArgInfo* inlCurArgInfo = &pInlineInfo->inlArgInfo[argNum];
17267 if (curArgVal->gtOper == GT_MKREFANY)
17269 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_IS_MKREFANY);
17273 inlCurArgInfo->argNode = curArgVal;
17275 GenTreePtr lclVarTree;
17276 if (impIsAddressInLocal(curArgVal, &lclVarTree) && varTypeIsStruct(lclVarTree))
17278 inlCurArgInfo->argIsByRefToStructLocal = true;
17279 #ifdef FEATURE_SIMD
17280 if (lvaTable[lclVarTree->AsLclVarCommon()->gtLclNum].lvSIMDType)
17282 pInlineInfo->hasSIMDTypeArgLocalOrReturn = true;
17284 #endif // FEATURE_SIMD
17287 if (curArgVal->gtFlags & GTF_ALL_EFFECT)
17289 inlCurArgInfo->argHasGlobRef = (curArgVal->gtFlags & GTF_GLOB_REF) != 0;
17290 inlCurArgInfo->argHasSideEff = (curArgVal->gtFlags & (GTF_ALL_EFFECT & ~GTF_GLOB_REF)) != 0;
17293 if (curArgVal->gtOper == GT_LCL_VAR)
17295 inlCurArgInfo->argIsLclVar = true;
17297 /* Remember the "original" argument number */
17298 curArgVal->gtLclVar.gtLclILoffs = argNum;
17301 if ((curArgVal->OperKind() & GTK_CONST) ||
17302 ((curArgVal->gtOper == GT_ADDR) && (curArgVal->gtOp.gtOp1->gtOper == GT_LCL_VAR)))
17304 inlCurArgInfo->argIsInvariant = true;
17305 if (inlCurArgInfo->argIsThis && (curArgVal->gtOper == GT_CNS_INT) && (curArgVal->gtIntCon.gtIconVal == 0))
17307 /* Abort, but do not mark as not inlinable */
17308 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_HAS_NULL_THIS);
17313 if (!inlCurArgInfo->argIsInvariant && gtHasLocalsWithAddrOp(curArgVal))
17315 inlCurArgInfo->argHasLdargaOp = true;
17321 if (inlCurArgInfo->argIsThis)
17323 printf("thisArg:");
17327 printf("\nArgument #%u:", argNum);
17329 if (inlCurArgInfo->argIsLclVar)
17331 printf(" is a local var");
17333 if (inlCurArgInfo->argIsInvariant)
17335 printf(" is a constant");
17337 if (inlCurArgInfo->argHasGlobRef)
17339 printf(" has global refs");
17341 if (inlCurArgInfo->argHasSideEff)
17343 printf(" has side effects");
17345 if (inlCurArgInfo->argHasLdargaOp)
17347 printf(" has ldarga effect");
17349 if (inlCurArgInfo->argHasStargOp)
17351 printf(" has starg effect");
17353 if (inlCurArgInfo->argIsByRefToStructLocal)
17355 printf(" is byref to a struct local");
17359 gtDispTree(curArgVal);
17365 /*****************************************************************************
17369 void Compiler::impInlineInitVars(InlineInfo* pInlineInfo)
17371 assert(!compIsForInlining());
17373 GenTreePtr call = pInlineInfo->iciCall;
17374 CORINFO_METHOD_INFO* methInfo = &pInlineInfo->inlineCandidateInfo->methInfo;
17375 unsigned clsAttr = pInlineInfo->inlineCandidateInfo->clsAttr;
17376 InlArgInfo* inlArgInfo = pInlineInfo->inlArgInfo;
17377 InlLclVarInfo* lclVarInfo = pInlineInfo->lclVarInfo;
17378 InlineResult* inlineResult = pInlineInfo->inlineResult;
17380 const bool hasRetBuffArg = impMethodInfo_hasRetBuffArg(methInfo);
17382 /* init the argument stuct */
17384 memset(inlArgInfo, 0, (MAX_INL_ARGS + 1) * sizeof(inlArgInfo[0]));
17386 /* Get hold of the 'this' pointer and the argument list proper */
17388 GenTreePtr thisArg = call->gtCall.gtCallObjp;
17389 GenTreePtr argList = call->gtCall.gtCallArgs;
17390 unsigned argCnt = 0; // Count of the arguments
17392 assert((methInfo->args.hasThis()) == (thisArg != nullptr));
17396 inlArgInfo[0].argIsThis = true;
17398 impInlineRecordArgInfo(pInlineInfo, thisArg, argCnt, inlineResult);
17400 if (inlineResult->IsFailure())
17405 /* Increment the argument count */
17409 /* Record some information about each of the arguments */
17410 bool hasTypeCtxtArg = (methInfo->args.callConv & CORINFO_CALLCONV_PARAMTYPE) != 0;
17412 #if USER_ARGS_COME_LAST
17413 unsigned typeCtxtArg = thisArg ? 1 : 0;
17414 #else // USER_ARGS_COME_LAST
17415 unsigned typeCtxtArg = methInfo->args.totalILArgs();
17416 #endif // USER_ARGS_COME_LAST
17418 for (GenTreePtr argTmp = argList; argTmp; argTmp = argTmp->gtOp.gtOp2)
17420 if (argTmp == argList && hasRetBuffArg)
17425 // Ignore the type context argument
17426 if (hasTypeCtxtArg && (argCnt == typeCtxtArg))
17428 typeCtxtArg = 0xFFFFFFFF;
17432 assert(argTmp->gtOper == GT_LIST);
17433 GenTreePtr argVal = argTmp->gtOp.gtOp1;
17435 impInlineRecordArgInfo(pInlineInfo, argVal, argCnt, inlineResult);
17437 if (inlineResult->IsFailure())
17442 /* Increment the argument count */
17446 /* Make sure we got the arg number right */
17447 assert(argCnt == methInfo->args.totalILArgs());
17449 #ifdef FEATURE_SIMD
17450 bool foundSIMDType = pInlineInfo->hasSIMDTypeArgLocalOrReturn;
17451 #endif // FEATURE_SIMD
17453 /* We have typeless opcodes, get type information from the signature */
17459 if (clsAttr & CORINFO_FLG_VALUECLASS)
17461 sigType = TYP_BYREF;
17468 lclVarInfo[0].lclVerTypeInfo = verMakeTypeInfo(pInlineInfo->inlineCandidateInfo->clsHandle);
17469 lclVarInfo[0].lclHasLdlocaOp = false;
17471 #ifdef FEATURE_SIMD
17472 // We always want to check isSIMDClass, since we want to set foundSIMDType (to increase
17473 // the inlining multiplier) for anything in that assembly.
17474 // But we only need to normalize it if it is a TYP_STRUCT
17475 // (which we need to do even if we have already set foundSIMDType).
17476 if ((!foundSIMDType || (sigType == TYP_STRUCT)) && isSIMDClass(&(lclVarInfo[0].lclVerTypeInfo)))
17478 if (sigType == TYP_STRUCT)
17480 sigType = impNormStructType(lclVarInfo[0].lclVerTypeInfo.GetClassHandle());
17482 foundSIMDType = true;
17484 #endif // FEATURE_SIMD
17485 lclVarInfo[0].lclTypeInfo = sigType;
17487 assert(varTypeIsGC(thisArg->gtType) || // "this" is managed
17488 (thisArg->gtType == TYP_I_IMPL && // "this" is unmgd but the method's class doesnt care
17489 (clsAttr & CORINFO_FLG_VALUECLASS)));
17491 if (genActualType(thisArg->gtType) != genActualType(sigType))
17493 if (sigType == TYP_REF)
17495 /* The argument cannot be bashed into a ref (see bug 750871) */
17496 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_NO_BASH_TO_REF);
17500 /* This can only happen with byrefs <-> ints/shorts */
17502 assert(genActualType(sigType) == TYP_I_IMPL || sigType == TYP_BYREF);
17503 assert(genActualType(thisArg->gtType) == TYP_I_IMPL || thisArg->gtType == TYP_BYREF);
17505 if (sigType == TYP_BYREF)
17507 lclVarInfo[0].lclVerTypeInfo = typeInfo(varType2tiType(TYP_I_IMPL));
17509 else if (thisArg->gtType == TYP_BYREF)
17511 assert(sigType == TYP_I_IMPL);
17513 /* If possible change the BYREF to an int */
17514 if (thisArg->IsVarAddr())
17516 thisArg->gtType = TYP_I_IMPL;
17517 lclVarInfo[0].lclVerTypeInfo = typeInfo(varType2tiType(TYP_I_IMPL));
17521 /* Arguments 'int <- byref' cannot be bashed */
17522 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_NO_BASH_TO_INT);
17529 /* Init the types of the arguments and make sure the types
17530 * from the trees match the types in the signature */
17532 CORINFO_ARG_LIST_HANDLE argLst;
17533 argLst = methInfo->args.args;
17536 for (i = (thisArg ? 1 : 0); i < argCnt; i++, argLst = info.compCompHnd->getArgNext(argLst))
17538 var_types sigType = (var_types)eeGetArgType(argLst, &methInfo->args);
17540 lclVarInfo[i].lclVerTypeInfo = verParseArgSigToTypeInfo(&methInfo->args, argLst);
17542 #ifdef FEATURE_SIMD
17543 if ((!foundSIMDType || (sigType == TYP_STRUCT)) && isSIMDClass(&(lclVarInfo[i].lclVerTypeInfo)))
17545 // If this is a SIMD class (i.e. in the SIMD assembly), then we will consider that we've
17546 // found a SIMD type, even if this may not be a type we recognize (the assumption is that
17547 // it is likely to use a SIMD type, and therefore we want to increase the inlining multiplier).
17548 foundSIMDType = true;
17549 if (sigType == TYP_STRUCT)
17551 var_types structType = impNormStructType(lclVarInfo[i].lclVerTypeInfo.GetClassHandle());
17552 sigType = structType;
17555 #endif // FEATURE_SIMD
17557 lclVarInfo[i].lclTypeInfo = sigType;
17558 lclVarInfo[i].lclHasLdlocaOp = false;
17560 /* Does the tree type match the signature type? */
17562 GenTreePtr inlArgNode = inlArgInfo[i].argNode;
17564 if (sigType != inlArgNode->gtType)
17566 /* In valid IL, this can only happen for short integer types or byrefs <-> [native] ints,
17567 but in bad IL cases with caller-callee signature mismatches we can see other types.
17568 Intentionally reject cases with mismatches so the jit is more flexible when
17569 encountering bad IL. */
17571 bool isPlausibleTypeMatch = (genActualType(sigType) == genActualType(inlArgNode->gtType)) ||
17572 (genActualTypeIsIntOrI(sigType) && inlArgNode->gtType == TYP_BYREF) ||
17573 (sigType == TYP_BYREF && genActualTypeIsIntOrI(inlArgNode->gtType));
17575 if (!isPlausibleTypeMatch)
17577 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_TYPES_INCOMPATIBLE);
17581 /* Is it a narrowing or widening cast?
17582 * Widening casts are ok since the value computed is already
17583 * normalized to an int (on the IL stack) */
17585 if (genTypeSize(inlArgNode->gtType) >= genTypeSize(sigType))
17587 if (sigType == TYP_BYREF)
17589 lclVarInfo[i].lclVerTypeInfo = typeInfo(varType2tiType(TYP_I_IMPL));
17591 else if (inlArgNode->gtType == TYP_BYREF)
17593 assert(varTypeIsIntOrI(sigType));
17595 /* If possible bash the BYREF to an int */
17596 if (inlArgNode->IsVarAddr())
17598 inlArgNode->gtType = TYP_I_IMPL;
17599 lclVarInfo[i].lclVerTypeInfo = typeInfo(varType2tiType(TYP_I_IMPL));
17603 /* Arguments 'int <- byref' cannot be changed */
17604 inlineResult->NoteFatal(InlineObservation::CALLSITE_ARG_NO_BASH_TO_INT);
17608 else if (genTypeSize(sigType) < EA_PTRSIZE)
17610 /* Narrowing cast */
17612 if (inlArgNode->gtOper == GT_LCL_VAR &&
17613 !lvaTable[inlArgNode->gtLclVarCommon.gtLclNum].lvNormalizeOnLoad() &&
17614 sigType == lvaGetRealType(inlArgNode->gtLclVarCommon.gtLclNum))
17616 /* We don't need to insert a cast here as the variable
17617 was assigned a normalized value of the right type */
17622 inlArgNode = inlArgInfo[i].argNode = gtNewCastNode(TYP_INT, inlArgNode, sigType);
17624 inlArgInfo[i].argIsLclVar = false;
17626 /* Try to fold the node in case we have constant arguments */
17628 if (inlArgInfo[i].argIsInvariant)
17630 inlArgNode = gtFoldExprConst(inlArgNode);
17631 inlArgInfo[i].argNode = inlArgNode;
17632 assert(inlArgNode->OperIsConst());
17635 #ifdef _TARGET_64BIT_
17636 else if (genTypeSize(genActualType(inlArgNode->gtType)) < genTypeSize(sigType))
17638 // This should only happen for int -> native int widening
17639 inlArgNode = inlArgInfo[i].argNode = gtNewCastNode(genActualType(sigType), inlArgNode, sigType);
17641 inlArgInfo[i].argIsLclVar = false;
17643 /* Try to fold the node in case we have constant arguments */
17645 if (inlArgInfo[i].argIsInvariant)
17647 inlArgNode = gtFoldExprConst(inlArgNode);
17648 inlArgInfo[i].argNode = inlArgNode;
17649 assert(inlArgNode->OperIsConst());
17652 #endif // _TARGET_64BIT_
17657 /* Init the types of the local variables */
17659 CORINFO_ARG_LIST_HANDLE localsSig;
17660 localsSig = methInfo->locals.args;
17662 for (i = 0; i < methInfo->locals.numArgs; i++)
17665 var_types type = (var_types)eeGetArgType(localsSig, &methInfo->locals, &isPinned);
17667 lclVarInfo[i + argCnt].lclHasLdlocaOp = false;
17668 lclVarInfo[i + argCnt].lclIsPinned = isPinned;
17669 lclVarInfo[i + argCnt].lclTypeInfo = type;
17673 // Pinned locals may cause inlines to fail.
17674 inlineResult->Note(InlineObservation::CALLEE_HAS_PINNED_LOCALS);
17675 if (inlineResult->IsFailure())
17681 lclVarInfo[i + argCnt].lclVerTypeInfo = verParseArgSigToTypeInfo(&methInfo->locals, localsSig);
17683 // If this local is a struct type with GC fields, inform the inliner. It may choose to bail
17684 // out on the inline.
17685 if (type == TYP_STRUCT)
17687 CORINFO_CLASS_HANDLE lclHandle = lclVarInfo[i + argCnt].lclVerTypeInfo.GetClassHandle();
17688 DWORD typeFlags = info.compCompHnd->getClassAttribs(lclHandle);
17689 if ((typeFlags & CORINFO_FLG_CONTAINS_GC_PTR) != 0)
17691 inlineResult->Note(InlineObservation::CALLEE_HAS_GC_STRUCT);
17692 if (inlineResult->IsFailure())
17697 // Do further notification in the case where the call site is rare; some policies do
17698 // not track the relative hotness of call sites for "always" inline cases.
17699 if (pInlineInfo->iciBlock->isRunRarely())
17701 inlineResult->Note(InlineObservation::CALLSITE_RARE_GC_STRUCT);
17702 if (inlineResult->IsFailure())
17711 localsSig = info.compCompHnd->getArgNext(localsSig);
17713 #ifdef FEATURE_SIMD
17714 if ((!foundSIMDType || (type == TYP_STRUCT)) && isSIMDClass(&(lclVarInfo[i + argCnt].lclVerTypeInfo)))
17716 foundSIMDType = true;
17717 if (featureSIMD && type == TYP_STRUCT)
17719 var_types structType = impNormStructType(lclVarInfo[i + argCnt].lclVerTypeInfo.GetClassHandle());
17720 lclVarInfo[i + argCnt].lclTypeInfo = structType;
17723 #endif // FEATURE_SIMD
17726 #ifdef FEATURE_SIMD
17727 if (!foundSIMDType && (call->AsCall()->gtRetClsHnd != nullptr) && isSIMDClass(call->AsCall()->gtRetClsHnd))
17729 foundSIMDType = true;
17731 pInlineInfo->hasSIMDTypeArgLocalOrReturn = foundSIMDType;
17732 #endif // FEATURE_SIMD
17735 unsigned Compiler::impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason))
17737 assert(compIsForInlining());
17739 unsigned tmpNum = impInlineInfo->lclTmpNum[lclNum];
17741 if (tmpNum == BAD_VAR_NUM)
17743 var_types lclTyp = impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclTypeInfo;
17745 // The lifetime of this local might span multiple BBs.
17746 // So it is a long lifetime local.
17747 impInlineInfo->lclTmpNum[lclNum] = tmpNum = lvaGrabTemp(false DEBUGARG(reason));
17749 lvaTable[tmpNum].lvType = lclTyp;
17750 if (impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclHasLdlocaOp)
17752 lvaTable[tmpNum].lvHasLdAddrOp = 1;
17755 if (impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclIsPinned)
17757 lvaTable[tmpNum].lvPinned = 1;
17759 if (!impInlineInfo->hasPinnedLocals)
17761 // If the inlinee returns a value, use a spill temp
17762 // for the return value to ensure that even in case
17763 // where the return expression refers to one of the
17764 // pinned locals, we can unpin the local right after
17765 // the inlined method body.
17766 if ((info.compRetNativeType != TYP_VOID) && (lvaInlineeReturnSpillTemp == BAD_VAR_NUM))
17768 lvaInlineeReturnSpillTemp =
17769 lvaGrabTemp(false DEBUGARG("Inline candidate pinned local return spill temp"));
17770 lvaTable[lvaInlineeReturnSpillTemp].lvType = info.compRetNativeType;
17774 impInlineInfo->hasPinnedLocals = true;
17777 if (impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclVerTypeInfo.IsStruct())
17779 if (varTypeIsStruct(lclTyp))
17781 lvaSetStruct(tmpNum,
17782 impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclVerTypeInfo.GetClassHandle(),
17783 true /* unsafe value cls check */);
17787 // This is a wrapped primitive. Make sure the verstate knows that
17788 lvaTable[tmpNum].lvVerTypeInfo =
17789 impInlineInfo->lclVarInfo[lclNum + impInlineInfo->argCnt].lclVerTypeInfo;
17797 // A method used to return the GenTree (usually a GT_LCL_VAR) representing the arguments of the inlined method.
17798 // Only use this method for the arguments of the inlinee method.
17799 // !!! Do not use it for the locals of the inlinee method. !!!!
17801 GenTreePtr Compiler::impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclVarInfo)
17803 /* Get the argument type */
17804 var_types lclTyp = lclVarInfo[lclNum].lclTypeInfo;
17806 GenTreePtr op1 = nullptr;
17808 // constant or address of local
17809 if (inlArgInfo[lclNum].argIsInvariant && !inlArgInfo[lclNum].argHasLdargaOp && !inlArgInfo[lclNum].argHasStargOp)
17811 /* Clone the constant. Note that we cannot directly use argNode
17812 in the trees even if inlArgInfo[lclNum].argIsUsed==false as this
17813 would introduce aliasing between inlArgInfo[].argNode and
17814 impInlineExpr. Then gtFoldExpr() could change it, causing further
17815 references to the argument working off of the bashed copy. */
17817 op1 = gtCloneExpr(inlArgInfo[lclNum].argNode);
17818 PREFIX_ASSUME(op1 != nullptr);
17819 inlArgInfo[lclNum].argTmpNum = (unsigned)-1; // illegal temp
17821 else if (inlArgInfo[lclNum].argIsLclVar && !inlArgInfo[lclNum].argHasLdargaOp && !inlArgInfo[lclNum].argHasStargOp)
17823 /* Argument is a local variable (of the caller)
17824 * Can we re-use the passed argument node? */
17826 op1 = inlArgInfo[lclNum].argNode;
17827 inlArgInfo[lclNum].argTmpNum = op1->gtLclVarCommon.gtLclNum;
17829 if (inlArgInfo[lclNum].argIsUsed)
17831 assert(op1->gtOper == GT_LCL_VAR);
17832 assert(lclNum == op1->gtLclVar.gtLclILoffs);
17834 if (!lvaTable[op1->gtLclVarCommon.gtLclNum].lvNormalizeOnLoad())
17836 lclTyp = genActualType(lclTyp);
17839 /* Create a new lcl var node - remember the argument lclNum */
17840 op1 = gtNewLclvNode(op1->gtLclVarCommon.gtLclNum, lclTyp, op1->gtLclVar.gtLclILoffs);
17843 else if (inlArgInfo[lclNum].argIsByRefToStructLocal && !inlArgInfo[lclNum].argHasStargOp)
17845 /* Argument is a by-ref address to a struct, a normed struct, or its field.
17846 In these cases, don't spill the byref to a local, simply clone the tree and use it.
17847 This way we will increase the chance for this byref to be optimized away by
17848 a subsequent "dereference" operation.
17850 From Dev11 bug #139955: Argument node can also be TYP_I_IMPL if we've bashed the tree
17851 (in impInlineInitVars()), if the arg has argHasLdargaOp as well as argIsByRefToStructLocal.
17852 For example, if the caller is:
17853 ldloca.s V_1 // V_1 is a local struct
17854 call void Test.ILPart::RunLdargaOnPointerArg(int32*)
17855 and the callee being inlined has:
17856 .method public static void RunLdargaOnPointerArg(int32* ptrToInts) cil managed
17858 call void Test.FourInts::NotInlined_SetExpectedValuesThroughPointerToPointer(int32**)
17859 then we change the argument tree (of "ldloca.s V_1") to TYP_I_IMPL to match the callee signature. We'll
17860 soon afterwards reject the inlining anyway, since the tree we return isn't a GT_LCL_VAR.
17862 assert(inlArgInfo[lclNum].argNode->TypeGet() == TYP_BYREF ||
17863 inlArgInfo[lclNum].argNode->TypeGet() == TYP_I_IMPL);
17864 op1 = gtCloneExpr(inlArgInfo[lclNum].argNode);
17868 /* Argument is a complex expression - it must be evaluated into a temp */
17870 if (inlArgInfo[lclNum].argHasTmp)
17872 assert(inlArgInfo[lclNum].argIsUsed);
17873 assert(inlArgInfo[lclNum].argTmpNum < lvaCount);
17875 /* Create a new lcl var node - remember the argument lclNum */
17876 op1 = gtNewLclvNode(inlArgInfo[lclNum].argTmpNum, genActualType(lclTyp));
17878 /* This is the second or later use of the this argument,
17879 so we have to use the temp (instead of the actual arg) */
17880 inlArgInfo[lclNum].argBashTmpNode = nullptr;
17884 /* First time use */
17885 assert(inlArgInfo[lclNum].argIsUsed == false);
17887 /* Reserve a temp for the expression.
17888 * Use a large size node as we may change it later */
17890 unsigned tmpNum = lvaGrabTemp(true DEBUGARG("Inlining Arg"));
17892 lvaTable[tmpNum].lvType = lclTyp;
17893 assert(lvaTable[tmpNum].lvAddrExposed == 0);
17894 if (inlArgInfo[lclNum].argHasLdargaOp)
17896 lvaTable[tmpNum].lvHasLdAddrOp = 1;
17899 if (lclVarInfo[lclNum].lclVerTypeInfo.IsStruct())
17901 if (varTypeIsStruct(lclTyp))
17903 lvaSetStruct(tmpNum, impInlineInfo->lclVarInfo[lclNum].lclVerTypeInfo.GetClassHandle(),
17904 true /* unsafe value cls check */);
17908 // This is a wrapped primitive. Make sure the verstate knows that
17909 lvaTable[tmpNum].lvVerTypeInfo = impInlineInfo->lclVarInfo[lclNum].lclVerTypeInfo;
17913 inlArgInfo[lclNum].argHasTmp = true;
17914 inlArgInfo[lclNum].argTmpNum = tmpNum;
17916 // If we require strict exception order, then arguments must
17917 // be evaluated in sequence before the body of the inlined method.
17918 // So we need to evaluate them to a temp.
17919 // Also, if arguments have global references, we need to
17920 // evaluate them to a temp before the inlined body as the
17921 // inlined body may be modifying the global ref.
17922 // TODO-1stClassStructs: We currently do not reuse an existing lclVar
17923 // if it is a struct, because it requires some additional handling.
17925 if (!varTypeIsStruct(lclTyp) && (!inlArgInfo[lclNum].argHasSideEff) && (!inlArgInfo[lclNum].argHasGlobRef))
17927 /* Get a *LARGE* LCL_VAR node */
17928 op1 = gtNewLclLNode(tmpNum, genActualType(lclTyp), lclNum);
17930 /* Record op1 as the very first use of this argument.
17931 If there are no further uses of the arg, we may be
17932 able to use the actual arg node instead of the temp.
17933 If we do see any further uses, we will clear this. */
17934 inlArgInfo[lclNum].argBashTmpNode = op1;
17938 /* Get a small LCL_VAR node */
17939 op1 = gtNewLclvNode(tmpNum, genActualType(lclTyp));
17940 /* No bashing of this argument */
17941 inlArgInfo[lclNum].argBashTmpNode = nullptr;
17946 /* Mark the argument as used */
17948 inlArgInfo[lclNum].argIsUsed = true;
17953 /******************************************************************************
17954 Is this the original "this" argument to the call being inlined?
17956 Note that we do not inline methods with "starg 0", and so we do not need to
17960 BOOL Compiler::impInlineIsThis(GenTreePtr tree, InlArgInfo* inlArgInfo)
17962 assert(compIsForInlining());
17963 return (tree->gtOper == GT_LCL_VAR && tree->gtLclVarCommon.gtLclNum == inlArgInfo[0].argTmpNum);
17966 //-----------------------------------------------------------------------------
17967 // This function checks if a dereference in the inlinee can guarantee that
17968 // the "this" is non-NULL.
17969 // If we haven't hit a branch or a side effect, and we are dereferencing
17970 // from 'this' to access a field or make GTF_CALL_NULLCHECK call,
17971 // then we can avoid a separate null pointer check.
17973 // "additionalTreesToBeEvaluatedBefore"
17974 // is the set of pending trees that have not yet been added to the statement list,
17975 // and which have been removed from verCurrentState.esStack[]
17977 BOOL Compiler::impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTreePtr additionalTreesToBeEvaluatedBefore,
17978 GenTreePtr variableBeingDereferenced,
17979 InlArgInfo* inlArgInfo)
17981 assert(compIsForInlining());
17982 assert(opts.OptEnabled(CLFLG_INLINING));
17984 BasicBlock* block = compCurBB;
17989 if (block != fgFirstBB)
17994 if (!impInlineIsThis(variableBeingDereferenced, inlArgInfo))
17999 if (additionalTreesToBeEvaluatedBefore &&
18000 GTF_GLOBALLY_VISIBLE_SIDE_EFFECTS(additionalTreesToBeEvaluatedBefore->gtFlags))
18005 for (stmt = impTreeList->gtNext; stmt; stmt = stmt->gtNext)
18007 expr = stmt->gtStmt.gtStmtExpr;
18009 if (GTF_GLOBALLY_VISIBLE_SIDE_EFFECTS(expr->gtFlags))
18015 for (unsigned level = 0; level < verCurrentState.esStackDepth; level++)
18017 unsigned stackTreeFlags = verCurrentState.esStack[level].val->gtFlags;
18018 if (GTF_GLOBALLY_VISIBLE_SIDE_EFFECTS(stackTreeFlags))
18027 /******************************************************************************/
18028 // Check the inlining eligibility of this GT_CALL node.
18029 // Mark GTF_CALL_INLINE_CANDIDATE on the GT_CALL node
18031 // Todo: find a way to record the failure reasons in the IR (or
18032 // otherwise build tree context) so when we do the inlining pass we
18033 // can capture these reasons
18035 void Compiler::impMarkInlineCandidate(GenTreePtr callNode,
18036 CORINFO_CONTEXT_HANDLE exactContextHnd,
18037 CORINFO_CALL_INFO* callInfo)
18039 // Let the strategy know there's another call
18040 impInlineRoot()->m_inlineStrategy->NoteCall();
18042 if (!opts.OptEnabled(CLFLG_INLINING))
18044 /* XXX Mon 8/18/2008
18045 * This assert is misleading. The caller does not ensure that we have CLFLG_INLINING set before
18046 * calling impMarkInlineCandidate. However, if this assert trips it means that we're an inlinee and
18047 * CLFLG_MINOPT is set. That doesn't make a lot of sense. If you hit this assert, work back and
18048 * figure out why we did not set MAXOPT for this compile.
18050 assert(!compIsForInlining());
18054 if (compIsForImportOnly())
18056 // Don't bother creating the inline candidate during verification.
18057 // Otherwise the call to info.compCompHnd->canInline will trigger a recursive verification
18058 // that leads to the creation of multiple instances of Compiler.
18062 GenTreeCall* call = callNode->AsCall();
18063 InlineResult inlineResult(this, call, nullptr, "impMarkInlineCandidate");
18065 // Don't inline if not optimizing root method
18066 if (opts.compDbgCode)
18068 inlineResult.NoteFatal(InlineObservation::CALLER_DEBUG_CODEGEN);
18072 // Don't inline if inlining into root method is disabled.
18073 if (InlineStrategy::IsNoInline(info.compCompHnd, info.compMethodHnd))
18075 inlineResult.NoteFatal(InlineObservation::CALLER_IS_JIT_NOINLINE);
18079 // Inlining candidate determination needs to honor only IL tail prefix.
18080 // Inlining takes precedence over implicit tail call optimization (if the call is not directly recursive).
18081 if (call->IsTailPrefixedCall())
18083 inlineResult.NoteFatal(InlineObservation::CALLSITE_EXPLICIT_TAIL_PREFIX);
18087 // Tail recursion elimination takes precedence over inlining.
18088 // TODO: We may want to do some of the additional checks from fgMorphCall
18089 // here to reduce the chance we don't inline a call that won't be optimized
18090 // as a fast tail call or turned into a loop.
18091 if (gtIsRecursiveCall(call) && call->IsImplicitTailCall())
18093 inlineResult.NoteFatal(InlineObservation::CALLSITE_IMPLICIT_REC_TAIL_CALL);
18097 if ((call->gtFlags & GTF_CALL_VIRT_KIND_MASK) != GTF_CALL_NONVIRT)
18099 inlineResult.NoteFatal(InlineObservation::CALLSITE_IS_NOT_DIRECT);
18103 /* Ignore helper calls */
18105 if (call->gtCallType == CT_HELPER)
18107 inlineResult.NoteFatal(InlineObservation::CALLSITE_IS_CALL_TO_HELPER);
18111 /* Ignore indirect calls */
18112 if (call->gtCallType == CT_INDIRECT)
18114 inlineResult.NoteFatal(InlineObservation::CALLSITE_IS_NOT_DIRECT_MANAGED);
18118 /* I removed the check for BBJ_THROW. BBJ_THROW is usually marked as rarely run. This more or less
18119 * restricts the inliner to non-expanding inlines. I removed the check to allow for non-expanding
18120 * inlining in throw blocks. I should consider the same thing for catch and filter regions. */
18122 CORINFO_METHOD_HANDLE fncHandle = call->gtCallMethHnd;
18125 // Reuse method flags from the original callInfo if possible
18126 if (fncHandle == callInfo->hMethod)
18128 methAttr = callInfo->methodFlags;
18132 methAttr = info.compCompHnd->getMethodAttribs(fncHandle);
18136 if (compStressCompile(STRESS_FORCE_INLINE, 0))
18138 methAttr |= CORINFO_FLG_FORCEINLINE;
18142 // Check for COMPlus_AggressiveInlining
18143 if (compDoAggressiveInlining)
18145 methAttr |= CORINFO_FLG_FORCEINLINE;
18148 if (!(methAttr & CORINFO_FLG_FORCEINLINE))
18150 /* Don't bother inline blocks that are in the filter region */
18151 if (bbInCatchHandlerILRange(compCurBB))
18156 printf("\nWill not inline blocks that are in the catch handler region\n");
18161 inlineResult.NoteFatal(InlineObservation::CALLSITE_IS_WITHIN_CATCH);
18165 if (bbInFilterILRange(compCurBB))
18170 printf("\nWill not inline blocks that are in the filter region\n");
18174 inlineResult.NoteFatal(InlineObservation::CALLSITE_IS_WITHIN_FILTER);
18179 /* If the caller's stack frame is marked, then we can't do any inlining. Period. */
18181 if (opts.compNeedSecurityCheck)
18183 inlineResult.NoteFatal(InlineObservation::CALLER_NEEDS_SECURITY_CHECK);
18187 /* Check if we tried to inline this method before */
18189 if (methAttr & CORINFO_FLG_DONT_INLINE)
18191 inlineResult.NoteFatal(InlineObservation::CALLEE_IS_NOINLINE);
18195 /* Cannot inline synchronized methods */
18197 if (methAttr & CORINFO_FLG_SYNCH)
18199 inlineResult.NoteFatal(InlineObservation::CALLEE_IS_SYNCHRONIZED);
18203 /* Do not inline if callee needs security checks (since they would then mark the wrong frame) */
18205 if (methAttr & CORINFO_FLG_SECURITYCHECK)
18207 inlineResult.NoteFatal(InlineObservation::CALLEE_NEEDS_SECURITY_CHECK);
18211 InlineCandidateInfo* inlineCandidateInfo = nullptr;
18212 impCheckCanInline(call, fncHandle, methAttr, exactContextHnd, &inlineCandidateInfo, &inlineResult);
18214 if (inlineResult.IsFailure())
18219 // The old value should be NULL
18220 assert(call->gtInlineCandidateInfo == nullptr);
18222 call->gtInlineCandidateInfo = inlineCandidateInfo;
18224 // Mark the call node as inline candidate.
18225 call->gtFlags |= GTF_CALL_INLINE_CANDIDATE;
18227 // Let the strategy know there's another candidate.
18228 impInlineRoot()->m_inlineStrategy->NoteCandidate();
18230 // Since we're not actually inlining yet, and this call site is
18231 // still just an inline candidate, there's nothing to report.
18232 inlineResult.SetReported();
18235 /******************************************************************************/
18236 // Returns true if the given intrinsic will be implemented by target-specific
18239 bool Compiler::IsTargetIntrinsic(CorInfoIntrinsics intrinsicId)
18241 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && !defined(LEGACY_BACKEND))
18242 switch (intrinsicId)
18244 // Amd64 only has SSE2 instruction to directly compute sqrt/abs.
18246 // TODO: Because the x86 backend only targets SSE for floating-point code,
18247 // it does not treat Sine, Cosine, or Round as intrinsics (JIT32
18248 // implemented those intrinsics as x87 instructions). If this poses
18249 // a CQ problem, it may be necessary to change the implementation of
18250 // the helper calls to decrease call overhead or switch back to the
18251 // x87 instructions. This is tracked by #7097.
18252 case CORINFO_INTRINSIC_Sqrt:
18253 case CORINFO_INTRINSIC_Abs:
18259 #elif defined(_TARGET_ARM64_)
18260 switch (intrinsicId)
18262 case CORINFO_INTRINSIC_Sqrt:
18263 case CORINFO_INTRINSIC_Abs:
18264 case CORINFO_INTRINSIC_Round:
18270 #elif defined(_TARGET_ARM_)
18271 switch (intrinsicId)
18273 case CORINFO_INTRINSIC_Sqrt:
18274 case CORINFO_INTRINSIC_Abs:
18275 case CORINFO_INTRINSIC_Round:
18281 #elif defined(_TARGET_X86_)
18282 switch (intrinsicId)
18284 case CORINFO_INTRINSIC_Sin:
18285 case CORINFO_INTRINSIC_Cos:
18286 case CORINFO_INTRINSIC_Sqrt:
18287 case CORINFO_INTRINSIC_Abs:
18288 case CORINFO_INTRINSIC_Round:
18295 // TODO: This portion of logic is not implemented for other arch.
18296 // The reason for returning true is that on all other arch the only intrinsic
18297 // enabled are target intrinsics.
18299 #endif //_TARGET_AMD64_
18302 /******************************************************************************/
18303 // Returns true if the given intrinsic will be implemented by calling System.Math
18306 bool Compiler::IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId)
18308 // Currently, if an math intrisic is not implemented by target-specific
18309 // intructions, it will be implemented by a System.Math call. In the
18310 // future, if we turn to implementing some of them with helper callers,
18311 // this predicate needs to be revisited.
18312 return !IsTargetIntrinsic(intrinsicId);
18315 bool Compiler::IsMathIntrinsic(CorInfoIntrinsics intrinsicId)
18317 switch (intrinsicId)
18319 case CORINFO_INTRINSIC_Sin:
18320 case CORINFO_INTRINSIC_Sqrt:
18321 case CORINFO_INTRINSIC_Abs:
18322 case CORINFO_INTRINSIC_Cos:
18323 case CORINFO_INTRINSIC_Round:
18324 case CORINFO_INTRINSIC_Cosh:
18325 case CORINFO_INTRINSIC_Sinh:
18326 case CORINFO_INTRINSIC_Tan:
18327 case CORINFO_INTRINSIC_Tanh:
18328 case CORINFO_INTRINSIC_Asin:
18329 case CORINFO_INTRINSIC_Acos:
18330 case CORINFO_INTRINSIC_Atan:
18331 case CORINFO_INTRINSIC_Atan2:
18332 case CORINFO_INTRINSIC_Log10:
18333 case CORINFO_INTRINSIC_Pow:
18334 case CORINFO_INTRINSIC_Exp:
18335 case CORINFO_INTRINSIC_Ceiling:
18336 case CORINFO_INTRINSIC_Floor:
18343 bool Compiler::IsMathIntrinsic(GenTreePtr tree)
18345 return (tree->OperGet() == GT_INTRINSIC) && IsMathIntrinsic(tree->gtIntrinsic.gtIntrinsicId);
18347 /*****************************************************************************/