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 Represents the method data we are currently JIT-compiling. XX
11 XX An instance of this class is created for every method we JIT. XX
12 XX This contains all the info needed for the method. So allocating a XX
13 XX a new instance per method makes it thread-safe. XX
14 XX It should be used to do all the memory management for the compiler run. XX
16 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
17 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
20 /*****************************************************************************/
23 /*****************************************************************************/
36 #include "simplerhash.h"
37 #include "cycletimer.h"
40 #include "arraystack.h"
43 #include "expandarray.h"
44 #include "tinyarray.h"
47 #include "jittelemetry.h"
52 #include "codegeninterface.h"
54 #include "jitgcinfo.h"
56 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
64 // This is only used locally in the JIT to indicate that
65 // a verification block should be inserted
66 #define SEH_VERIFICATION_EXCEPTION 0xe0564552 // VER
68 /*****************************************************************************
69 * Forward declarations
72 struct InfoHdr; // defined in GCInfo.h
73 struct escapeMapping_t; // defined in flowgraph.cpp
74 class emitter; // defined in emit.h
75 struct ShadowParamVarInfo; // defined in GSChecks.cpp
76 struct InitVarDscInfo; // defined in register_arg_convention.h
77 class FgStack; // defined in flowgraph.cpp
78 #if FEATURE_STACK_FP_X87
79 struct FlatFPStateX87; // defined in fp.h
82 class CSE_DataFlow; // defined in OptCSE.cpp
88 // The following are defined in this file, Compiler.h
92 /*****************************************************************************
98 /*****************************************************************************/
101 // Declare global operator new overloads that use the Compiler::compGetMem() function for allocation.
104 // Or the more-general IAllocator interface.
105 void* __cdecl operator new(size_t n, IAllocator* alloc);
106 void* __cdecl operator new[](size_t n, IAllocator* alloc);
108 // I wanted to make the second argument optional, with default = CMK_Unknown, but that
109 // caused these to be ambiguous with the global placement new operators.
110 void* __cdecl operator new(size_t n, Compiler* context, CompMemKind cmk);
111 void* __cdecl operator new[](size_t n, Compiler* context, CompMemKind cmk);
112 void* __cdecl operator new(size_t n, void* p, const jitstd::placement_t& syntax_difference);
114 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
115 #include "loopcloning.h"
117 /*****************************************************************************/
119 /* This is included here and not earlier as it needs the definition of "CSE"
120 * which is defined in the section above */
122 /*****************************************************************************/
124 unsigned genLog2(unsigned value);
125 unsigned genLog2(unsigned __int64 value);
127 var_types genActualType(var_types type);
128 var_types genUnsignedType(var_types type);
129 var_types genSignedType(var_types type);
131 unsigned ReinterpretHexAsDecimal(unsigned);
133 /*****************************************************************************/
136 #ifdef FEATURE_AVX_SUPPORT
137 const unsigned TEMP_MAX_SIZE = YMM_REGSIZE_BYTES;
138 #else // !FEATURE_AVX_SUPPORT
139 const unsigned TEMP_MAX_SIZE = XMM_REGSIZE_BYTES;
140 #endif // !FEATURE_AVX_SUPPORT
141 #else // !FEATURE_SIMD
142 const unsigned TEMP_MAX_SIZE = sizeof(double);
143 #endif // !FEATURE_SIMD
144 const unsigned TEMP_SLOT_COUNT = (TEMP_MAX_SIZE / sizeof(int));
146 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
149 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
152 // The following holds the Local var info (scope information)
153 typedef const char* VarName; // Actual ASCII string
156 IL_OFFSET vsdLifeBeg; // instr offset of beg of life
157 IL_OFFSET vsdLifeEnd; // instr offset of end of life
158 unsigned vsdVarNum; // (remapped) LclVarDsc number
161 VarName vsdName; // name of the var
164 unsigned vsdLVnum; // 'which' in eeGetLVinfo().
165 // Also, it is the index of this entry in the info.compVarScopes array,
166 // which is useful since the array is also accessed via the
167 // compEnterScopeList and compExitScopeList sorted arrays.
170 /*****************************************************************************
172 * The following holds the local variable counts and the descriptor table.
175 // This is the location of a definition.
181 DefLoc() : m_blk(nullptr), m_tree(nullptr)
186 // This class encapsulates all info about a local variable that may vary for different SSA names
191 ValueNumPair m_vnPair;
199 typedef ExpandArray<LclSsaVarDsc> PerSsaArray;
204 // The constructor. Most things can just be zero'ed.
205 LclVarDsc(Compiler* comp);
207 // note this only packs because var_types is a typedef of unsigned char
208 var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF
210 unsigned char lvIsParam : 1; // is this a parameter?
211 unsigned char lvIsRegArg : 1; // is this a register argument?
212 unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)
214 unsigned char lvStructGcCount : 3; // if struct, how many GC pointer (stop counting at 7). The only use of values >1
215 // is to help determine whether to use block init in the prolog.
216 unsigned char lvOnFrame : 1; // (part of) the variable lives on the frame
217 unsigned char lvDependReg : 1; // did the predictor depend upon this being enregistered
218 unsigned char lvRegister : 1; // assigned to live in a register? For RyuJIT backend, this is only set if the
219 // variable is in the same register for the entire function.
220 unsigned char lvTracked : 1; // is this a tracked variable?
221 bool lvTrackedNonStruct()
223 return lvTracked && lvType != TYP_STRUCT;
225 unsigned char lvPinned : 1; // is this a pinned variable?
227 unsigned char lvMustInit : 1; // must be initialized
228 unsigned char lvAddrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
229 // global location, etc.
230 // We cannot reason reliably about the value of the variable.
231 unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
232 unsigned char lvFieldAccessed : 1; // The var is a struct local, and a field of the variable is accessed. Affects
236 // These further document the reasons for setting "lvDoNotEnregister". (Note that "lvAddrExposed" is one of the
238 // also, lvType == TYP_STRUCT prevents enregistration. At least one of the reasons should be true.
239 unsigned char lvVMNeedsStackAddr : 1; // The VM may have access to a stack-relative address of the variable, and
240 // read/write its value.
241 unsigned char lvLiveInOutOfHndlr : 1; // The variable was live in or out of an exception handler, and this required
242 // the variable to be
243 // in the stack (at least at those boundaries.)
244 unsigned char lvLclFieldExpr : 1; // The variable is not a struct, but was accessed like one (e.g., reading a
245 // particular byte from an int).
246 unsigned char lvLclBlockOpAddr : 1; // The variable was written to via a block operation that took its address.
247 unsigned char lvLiveAcrossUCall : 1; // The variable is live across an unmanaged call.
249 unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable.
250 unsigned char lvRefAssign : 1; // involved in pointer assignment
251 unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.
252 unsigned char lvStackByref : 1; // This is a compiler temporary of TYP_BYREF that is known to point into our local
255 unsigned char lvArgWrite : 1; // variable is a parameter and STARG was used on it
256 unsigned char lvIsTemp : 1; // Short-lifetime compiler temp
258 unsigned char lvIsBoolean : 1; // set if variable is boolean
260 unsigned char lvRngOptDone : 1; // considered for range check opt?
261 unsigned char lvLoopInc : 1; // incremented in the loop?
262 unsigned char lvLoopAsg : 1; // reassigned in the loop (other than a monotonic inc/dec for the index var)?
263 unsigned char lvArrIndx : 1; // used as an array index?
264 unsigned char lvArrIndxOff : 1; // used as an array index with an offset?
265 unsigned char lvArrIndxDom : 1; // index dominates loop exit
267 unsigned char lvSingleDef : 1; // variable has a single def
268 unsigned char lvDisqualify : 1; // variable is no longer OK for add copy optimization
269 unsigned char lvVolatileHint : 1; // hint for AssertionProp
272 unsigned char lvAssignOne : 1; // assigned at least once?
273 unsigned char lvAssignTwo : 1; // assigned at least twice?
276 unsigned char lvSpilled : 1; // enregistered variable was spilled
277 #ifndef _TARGET_64BIT_
278 unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
279 #endif // !_TARGET_64BIT_
280 #ifdef _TARGET_64BIT_
281 unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
284 unsigned char lvKeepType : 1; // Don't change the type of this variable
285 unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
287 unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
289 unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
290 unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
292 unsigned char lvIsStructField : 1; // Is this local var a field of a promoted struct local?
293 unsigned char lvContainsFloatingFields : 1; // Does this struct contains floating point fields?
294 unsigned char lvOverlappingFields : 1; // True when we have a struct with possibly overlapping fields
295 unsigned char lvContainsHoles : 1; // True when we have a promoted struct that contains holes
296 unsigned char lvCustomLayout : 1; // True when this struct has "CustomLayout"
298 unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
299 unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call
302 unsigned char _lvIsHfa : 1; // Is this a struct variable who's class handle is an HFA type
303 unsigned char _lvIsHfaRegArg : 1; // Is this a HFA argument variable? // TODO-CLEANUP: Remove this and replace
304 // with (lvIsRegArg && lvIsHfa())
305 unsigned char _lvHfaTypeIsFloat : 1; // Is the HFA type float or double?
306 #endif // FEATURE_HFA
309 // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
310 // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
311 // Consider cleaning this up so this workaround is not required.
312 unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
313 // I.e. there is no longer any reference to the struct directly.
314 // In this case we can simply remove this struct local.
316 #ifndef LEGACY_BACKEND
317 unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
318 #endif // !LEGACY_BACKEND
321 // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
322 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
323 unsigned char lvSIMDType : 1; // This is a SIMD struct
324 unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
325 #endif // FEATURE_SIMD
326 unsigned char lvRegStruct : 1; // This is a reg-sized non-field-addressed struct.
329 unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
331 unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
332 // Valid on promoted struct local fields.
334 var_types lvBaseType; // The base type of a SIMD local var. Valid on TYP_SIMD locals.
335 #endif // FEATURE_SIMD
338 unsigned char lvFieldCnt; // Number of fields in the promoted VarDsc.
339 unsigned char lvFldOffset;
340 unsigned char lvFldOrdinal;
342 #if FEATURE_MULTIREG_ARGS
343 regNumber lvRegNumForSlot(unsigned slotNum)
349 else if (slotNum == 1)
351 return lvOtherArgReg;
355 assert(false && "Invalid slotNum!");
360 #endif // FEATURE_MULTIREG_ARGS
378 bool lvIsHfaRegArg() const
381 return _lvIsHfaRegArg;
387 void lvSetIsHfaRegArg()
390 _lvIsHfaRegArg = true;
394 bool lvHfaTypeIsFloat() const
397 return _lvHfaTypeIsFloat;
403 void lvSetHfaTypeIsFloat(bool value)
406 _lvHfaTypeIsFloat = value;
410 // on Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
411 // on Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
413 unsigned lvHfaSlots() const
416 assert(lvType == TYP_STRUCT);
418 return lvExactSize / sizeof(float);
419 #else // _TARGET_ARM64_
420 if (lvHfaTypeIsFloat())
422 return lvExactSize / sizeof(float);
426 return lvExactSize / sizeof(double);
428 #endif // _TARGET_ARM64_
431 // lvIsMultiRegArgOrRet()
432 // returns true if this is a multireg LclVar struct used in an argument context
433 // or if this is a multireg LclVar struct assigned from a multireg call
434 bool lvIsMultiRegArgOrRet()
436 return lvIsMultiRegArg || lvIsMultiRegRet;
440 regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
441 // register pair). For LEGACY_BACKEND, this is only set if lvRegister is
442 // non-zero. For non-LEGACY_BACKEND, it is set during codegen any time the
443 // variable is enregistered (in non-LEGACY_BACKEND, lvRegister is only set
444 // to non-zero if the variable gets the same register assignment for its entire
446 #if !defined(_TARGET_64BIT_)
447 regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
448 #endif // !defined(_TARGET_64BIT_)
450 regNumberSmall _lvArgReg; // The register in which this argument is passed.
452 #if FEATURE_MULTIREG_ARGS
453 regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
454 // Note this is defined but not used by ARM32
455 #endif // FEATURE_MULTIREG_ARGS
457 #ifndef LEGACY_BACKEND
459 regNumberSmall _lvArgInitReg; // the register into which the argument is moved at entry
460 regPairNoSmall _lvArgInitRegPair; // the register pair into which the argument is moved at entry
462 #endif // !LEGACY_BACKEND
465 // The register number is stored in a small format (8 bits), but the getters return and the setters take
466 // a full-size (unsigned) format, to localize the casts here.
468 /////////////////////
470 __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
472 regNumber GetRegNum() const
474 return (regNumber)_lvRegNum;
477 void SetRegNum(regNumber reg)
479 _lvRegNum = (regNumberSmall)reg;
480 assert(_lvRegNum == reg);
483 /////////////////////
485 #if defined(_TARGET_64BIT_)
486 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
488 regNumber GetOtherReg() const
490 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
491 // "unreachable code" warnings
495 void SetOtherReg(regNumber reg)
497 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
498 // "unreachable code" warnings
500 #else // !_TARGET_64BIT_
501 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
503 regNumber GetOtherReg() const
505 return (regNumber)_lvOtherReg;
508 void SetOtherReg(regNumber reg)
510 _lvOtherReg = (regNumberSmall)reg;
511 assert(_lvOtherReg == reg);
513 #endif // !_TARGET_64BIT_
515 /////////////////////
517 __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
519 regNumber GetArgReg() const
521 return (regNumber)_lvArgReg;
524 void SetArgReg(regNumber reg)
526 _lvArgReg = (regNumberSmall)reg;
527 assert(_lvArgReg == reg);
530 #if FEATURE_MULTIREG_ARGS
531 __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
533 regNumber GetOtherArgReg() const
535 return (regNumber)_lvOtherArgReg;
538 void SetOtherArgReg(regNumber reg)
540 _lvOtherArgReg = (regNumberSmall)reg;
541 assert(_lvOtherArgReg == reg);
543 #endif // FEATURE_MULTIREG_ARGS
546 // Is this is a SIMD struct?
547 bool lvIsSIMDType() const
552 // Is this is a SIMD struct which is used for SIMD intrinsic?
553 bool lvIsUsedInSIMDIntrinsic() const
555 return lvUsedInSIMDIntrinsic;
558 // If feature_simd not enabled, return false
559 bool lvIsSIMDType() const
563 bool lvIsUsedInSIMDIntrinsic() const
569 /////////////////////
571 #ifndef LEGACY_BACKEND
572 __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
574 regNumber GetArgInitReg() const
576 return (regNumber)_lvArgInitReg;
579 void SetArgInitReg(regNumber reg)
581 _lvArgInitReg = (regNumberSmall)reg;
582 assert(_lvArgInitReg == reg);
585 /////////////////////
587 __declspec(property(get = GetArgInitRegPair, put = SetArgInitRegPair)) regPairNo lvArgInitRegPair;
589 regPairNo GetArgInitRegPair() const
591 regPairNo regPair = (regPairNo)_lvArgInitRegPair;
592 assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
596 void SetArgInitRegPair(regPairNo regPair)
598 assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
599 _lvArgInitRegPair = (regPairNoSmall)regPair;
600 assert(_lvArgInitRegPair == regPair);
603 /////////////////////
605 bool lvIsRegCandidate() const
607 return lvLRACandidate != 0;
610 bool lvIsInReg() const
612 return lvIsRegCandidate() && (lvRegNum != REG_STK);
615 #else // LEGACY_BACKEND
617 bool lvIsRegCandidate() const
619 return lvTracked != 0;
622 bool lvIsInReg() const
624 return lvRegister != 0;
627 #endif // LEGACY_BACKEND
629 regMaskTP lvRegMask() const
631 regMaskTP regMask = RBM_NONE;
632 if (varTypeIsFloating(TypeGet()))
634 if (lvRegNum != REG_STK)
636 regMask = genRegMaskFloat(lvRegNum, TypeGet());
641 if (lvRegNum != REG_STK)
643 regMask = genRegMask(lvRegNum);
646 // For longs we may have two regs
647 if (isRegPairType(lvType) && lvOtherReg != REG_STK)
649 regMask |= genRegMask(lvOtherReg);
655 regMaskSmall lvPrefReg; // set of regs it prefers to live in
657 unsigned short lvVarIndex; // variable tracking index
658 unsigned short lvRefCnt; // unweighted (real) reference count
659 unsigned lvRefCntWtd; // weighted reference count
660 int lvStkOffs; // stack offset of home
661 unsigned lvExactSize; // (exact) size of the type in bytes
663 // Is this a promoted struct?
664 // This method returns true only for structs (including SIMD structs), not for
665 // locals that are split on a 32-bit target.
666 // It is only necessary to use this:
667 // 1) if only structs are wanted, and
668 // 2) if Lowering has already been done.
669 // Otherwise lvPromoted is valid.
670 bool lvPromotedStruct()
672 #if !defined(_TARGET_64BIT_)
673 return (lvPromoted && !varTypeIsLong(lvType));
674 #else // defined(_TARGET_64BIT_)
676 #endif // defined(_TARGET_64BIT_)
679 unsigned lvSize() // Size needed for storage representation. Only used for structs or TYP_BLK.
681 // TODO-Review: Sometimes we get called on ARM with HFA struct variables that have been promoted,
682 // where the struct itself is no longer used because all access is via its member fields.
683 // When that happens, the struct is marked as unused and its type has been changed to
684 // TYP_INT (to keep the GC tracking code from looking at it).
685 // See Compiler::raAssignVars() for details. For example:
686 // N002 ( 4, 3) [00EA067C] ------------- return struct $346
687 // N001 ( 3, 2) [00EA0628] ------------- lclVar struct(U) V03 loc2
688 // float V03.f1 (offs=0x00) -> V12 tmp7
689 // f8 (last use) (last use) $345
690 // Here, the "struct(U)" shows that the "V03 loc2" variable is unused. Not shown is that V03
691 // is now TYP_INT in the local variable table. It's not really unused, because it's in the tree.
693 assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
694 return (unsigned)(roundUp(lvExactSize, TARGET_POINTER_SIZE));
697 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
698 unsigned lvSlotNum; // original slot # (if remapped)
701 typeInfo lvVerTypeInfo; // type info needed for verification
703 BYTE* lvGcLayout; // GC layout info for structs
706 GenTreePtr lvKnownDim; // array size if known
710 BlockSet lvRefBlks; // Set of blocks that contain refs
711 GenTreePtr lvDefStmt; // Pointer to the statement with the single definition
712 void lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies
714 var_types TypeGet() const
716 return (var_types)lvType;
718 bool lvStackAligned() const
720 assert(lvIsStructField);
721 return ((lvFldOffset % sizeof(void*)) == 0);
723 bool lvNormalizeOnLoad() const
725 return varTypeIsSmall(TypeGet()) &&
726 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
727 (lvIsParam || lvAddrExposed || lvIsStructField);
730 bool lvNormalizeOnStore()
732 return varTypeIsSmall(TypeGet()) &&
733 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
734 !(lvIsParam || lvAddrExposed || lvIsStructField);
737 void lvaResetSortAgainFlag(Compiler* pComp);
738 void decRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
739 void incRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
740 void setPrefReg(regNumber regNum, Compiler* pComp);
741 void addPrefReg(regMaskTP regMask, Compiler* pComp);
742 bool IsFloatRegType() const
744 return isFloatRegType(lvType) || lvIsHfaRegArg();
746 var_types GetHfaType() const
748 return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
750 void SetHfaType(var_types type)
752 assert(varTypeIsFloating(type));
753 lvSetHfaTypeIsFloat(type == TYP_FLOAT);
756 #ifndef LEGACY_BACKEND
757 var_types lvaArgType();
760 PerSsaArray lvPerSsaData;
763 // Keep track of the # of SsaNames, for a bounds check.
764 unsigned lvNumSsaNames;
767 // Returns the address of the per-Ssa data for the given ssaNum (which is required
768 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
769 // not an SSA variable).
770 LclSsaVarDsc* GetPerSsaData(unsigned ssaNum)
772 assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
773 assert(SsaConfig::RESERVED_SSA_NUM == 0);
774 unsigned zeroBased = ssaNum - SsaConfig::UNINIT_SSA_NUM;
775 assert(zeroBased < lvNumSsaNames);
776 return &lvPerSsaData.GetRef(zeroBased);
781 void PrintVarReg() const
783 if (isRegPairType(TypeGet()))
785 printf("%s:%s", getRegName(lvOtherReg), // hi32
786 getRegName(lvRegNum)); // lo32
790 printf("%s", getRegName(lvRegNum));
795 }; // class LclVarDsc
798 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
799 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
803 XX The temporary lclVars allocated by the compiler for code generation XX
805 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
806 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
809 /*****************************************************************************
811 * The following keeps track of temporaries allocated in the stack frame
812 * during code-generation (after register allocation). These spill-temps are
813 * only used if we run out of registers while evaluating a tree.
815 * These are different from the more common temps allocated by lvaGrabTemp().
826 static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
834 TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
838 0); // temps must have a negative number (so they have a different number from all local variables)
839 tdOffs = BAD_TEMP_OFFSET;
843 IMPL_LIMITATION("too many spill temps");
848 bool tdLegalOffset() const
850 return tdOffs != BAD_TEMP_OFFSET;
854 int tdTempOffs() const
856 assert(tdLegalOffset());
859 void tdSetTempOffs(int offs)
862 assert(tdLegalOffset());
864 void tdAdjustTempOffs(int offs)
867 assert(tdLegalOffset());
870 int tdTempNum() const
875 unsigned tdTempSize() const
879 var_types tdTempType() const
885 // interface to hide linearscan implementation from rest of compiler
886 class LinearScanInterface
889 virtual void doLinearScan() = 0;
890 virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
893 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
895 // Information about arrays: their element type and size, and the offset of the first element.
896 // We label GT_IND's that are array indices with GTF_IND_ARR_INDEX, and, for such nodes,
897 // associate an array info via the map retrieved by GetArrayInfoMap(). This information is used,
898 // for example, in value numbering of array index expressions.
901 var_types m_elemType;
902 CORINFO_CLASS_HANDLE m_elemStructType;
904 unsigned m_elemOffset;
906 ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
910 ArrayInfo(var_types elemType, unsigned elemSize, unsigned elemOffset, CORINFO_CLASS_HANDLE elemStructType)
911 : m_elemType(elemType), m_elemStructType(elemStructType), m_elemSize(elemSize), m_elemOffset(elemOffset)
916 // This enumeration names the phases into which we divide compilation. The phases should completely
917 // partition a compilation.
920 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent) enum_nm,
921 #include "compphases.h"
925 extern const char* PhaseNames[];
926 extern const char* PhaseEnums[];
927 extern const LPCWSTR PhaseShortNames[];
929 //---------------------------------------------------------------
933 // A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
934 // We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
935 // of the compilation, as well as the cycles for each phase. We also track the number of bytecodes.
936 // If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
937 // by "m_timerFailure" being true.
938 // If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
941 #ifdef FEATURE_JIT_METHOD_PERF
942 // The string names of the phases.
943 static const char* PhaseNames[];
945 static bool PhaseHasChildren[];
946 static int PhaseParent[];
948 unsigned m_byteCodeBytes;
949 unsigned __int64 m_totalCycles;
950 unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
951 unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
952 // For better documentation, we call EndPhase on
953 // non-leaf phases. We should also call EndPhase on the
954 // last leaf subphase; obviously, the elapsed cycles between the EndPhase
955 // for the last leaf subphase and the EndPhase for an ancestor should be very small.
956 // We add all such "redundant end phase" intervals to this variable below; we print
957 // it out in a report, so we can verify that it is, indeed, very small. If it ever
958 // isn't, this means that we're doing something significant between the end of the last
959 // declared subphase and the end of its parent.
960 unsigned __int64 m_parentPhaseEndSlop;
963 CompTimeInfo(unsigned byteCodeBytes);
967 #ifdef FEATURE_JIT_METHOD_PERF
969 // This class summarizes the JIT time information over the course of a run: the number of methods compiled,
970 // and the total and maximum timings. (These are instances of the "CompTimeInfo" type described above).
971 // The operation of adding a single method's timing to the summary may be performed concurrently by several
972 // threads, so it is protected by a lock.
973 // This class is intended to be used as a singleton type, with only a single instance.
974 class CompTimeSummaryInfo
976 // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
977 static CritSecObject s_compTimeSummaryLock;
980 CompTimeInfo m_total;
981 CompTimeInfo m_maximum;
983 int m_numFilteredMethods;
984 CompTimeInfo m_filtered;
986 // This method computes the number of cycles/sec for the current machine. The cycles are those counted
987 // by GetThreadCycleTime; we assume that these are of equal duration, though that is not necessarily true.
988 // If any OS interaction fails, returns 0.0.
989 double CyclesPerSecond();
991 // This can use what ever data you want to determine if the value to be added
992 // belongs in the filtered section (it's always included in the unfiltered section)
993 bool IncludedInFilteredData(CompTimeInfo& info);
996 // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
997 static CompTimeSummaryInfo s_compTimeSummary;
999 CompTimeSummaryInfo() : m_total(0), m_maximum(0), m_numMethods(0), m_filtered(0), m_numFilteredMethods(0)
1003 // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
1004 // This is thread safe.
1005 void AddInfo(CompTimeInfo& info);
1007 // Print the summary information to "f".
1008 // This is not thread-safe; assumed to be called by only one thread.
1009 void Print(FILE* f);
1012 // A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
1013 // and when the current phase started. This is intended to be part of a Compilation object. This is
1014 // disabled (FEATURE_JIT_METHOD_PERF not defined) when FEATURE_CORECLR is set, or on non-windows platforms.
1018 unsigned __int64 m_start; // Start of the compilation.
1019 unsigned __int64 m_curPhaseStart; // Start of the current phase.
1021 Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1023 CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1025 static CritSecObject s_csvLock; // Lock to protect the time log file.
1026 void PrintCsvMethodStats(Compiler* comp);
1029 void* operator new(size_t);
1030 void* operator new[](size_t);
1031 void operator delete(void*);
1032 void operator delete[](void*);
1035 // Initialized the timer instance
1036 JitTimer(unsigned byteCodeSize);
1038 static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1040 return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1043 static void PrintCsvHeader();
1045 // Ends the current phase (argument is for a redundant check).
1046 void EndPhase(Phases phase);
1048 // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
1049 // and adds it to "sum".
1050 void Terminate(Compiler* comp, CompTimeSummaryInfo& sum);
1052 // Attempts to query the cycle counter of the current thread. If successful, returns "true" and sets
1053 // *cycles to the cycle counter value. Otherwise, returns false and sets the "m_timerFailure" flag of
1054 // "m_info" to true.
1055 bool GetThreadCycles(unsigned __int64* cycles)
1057 bool res = CycleTimer::GetThreadCyclesS(cycles);
1060 m_info.m_timerFailure = true;
1065 #endif // FEATURE_JIT_METHOD_PERF
1067 //------------------- Function/Funclet info -------------------------------
1068 DECLARE_TYPED_ENUM(FuncKind, BYTE)
1070 FUNC_ROOT, // The main/root function (always id==0)
1071 FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
1072 FUNC_FILTER, // a funclet associated with an EH filter
1075 END_DECLARE_TYPED_ENUM(FuncKind, BYTE)
1082 BYTE funFlags; // Currently unused, just here for padding
1083 unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
1084 // funclet. It is only valid if funKind field indicates this is a
1085 // EH-related funclet: FUNC_HANDLER or FUNC_FILTER
1087 #if defined(_TARGET_AMD64_)
1089 // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
1090 emitLocation* startLoc;
1091 emitLocation* endLoc;
1092 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1093 emitLocation* coldEndLoc;
1094 UNWIND_INFO unwindHeader;
1095 // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
1096 // number of codes, the VM or Zapper will 4-byte align the whole thing.
1097 BYTE unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
1098 unsigned unwindCodeSlot;
1100 #ifdef UNIX_AMD64_ABI
1101 jitstd::vector<CFI_CODE>* cfiCodes;
1102 #endif // UNIX_AMD64_ABI
1104 #elif defined(_TARGET_ARMARCH_)
1106 UnwindInfo uwi; // Unwind information for this function/funclet's hot section
1107 UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
1108 // Note: we only have a pointer here instead of the actual object,
1109 // to save memory in the JIT case (compared to the NGEN case),
1110 // where we don't have any cold section.
1111 // Note 2: we currently don't support hot/cold splitting in functions
1112 // with EH, so uwiCold will be NULL for all funclets.
1114 #endif // _TARGET_ARMARCH_
1116 // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1117 // that isn't shared between the main function body and funclets.
1120 struct fgArgTabEntry
1123 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1126 otherRegNum = REG_NA;
1127 isStruct = false; // is this a struct arg
1129 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1131 GenTreePtr node; // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
1133 // it will point at the actual argument in the gtCallLateArgs list.
1134 GenTreePtr parent; // Points at the GT_LIST node in the gtCallArgs for this argument
1136 unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1138 regNumber regNum; // The (first) register to use when passing this argument, set to REG_STK for arguments passed on
1140 unsigned numRegs; // Count of number of registers that this argument uses
1142 // A slot is a pointer sized region in the OutArg area.
1143 unsigned slotNum; // When an argument is passed in the OutArg area this is the slot number in the OutArg area
1144 unsigned numSlots; // Count of number of slots that this argument uses
1146 unsigned alignment; // 1 or 2 (slots/registers)
1147 unsigned lateArgInx; // index into gtCallLateArgs list
1148 unsigned tmpNum; // the LclVar number if we had to force evaluation of this arg
1150 bool isSplit : 1; // True when this argument is split between the registers and OutArg area
1151 bool needTmp : 1; // True when we force this argument's evaluation into a temp LclVar
1152 bool needPlace : 1; // True when we must replace this argument with a placeholder node
1153 bool isTmp : 1; // True when we setup a temp LclVar for this argument due to size issues with the struct
1154 bool processed : 1; // True when we have decided the evaluation order for this argument in the gtCallLateArgs
1155 bool isHfaRegArg : 1; // True when the argument is passed as a HFA in FP registers.
1156 bool isBackFilled : 1; // True when the argument fills a register slot skipped due to alignment requirements of
1157 // previous arguments.
1158 bool isNonStandard : 1; // True if it is an arg that is passed in a reg other than a standard arg reg, or is forced
1159 // to be on the stack despite its arg list position.
1161 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1162 bool isStruct : 1; // True if this is a struct arg
1164 regNumber otherRegNum; // The (second) register to use when passing this argument.
1166 SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1167 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1170 void SetIsHfaRegArg(bool hfaRegArg)
1172 isHfaRegArg = hfaRegArg;
1175 void SetIsBackFilled(bool backFilled)
1177 isBackFilled = backFilled;
1180 bool IsBackFilled() const
1182 return isBackFilled;
1184 #else // !_TARGET_ARM_
1185 // To make the callers easier, we allow these calls (and the isHfaRegArg and isBackFilled data members) for all
1187 void SetIsHfaRegArg(bool hfaRegArg)
1191 void SetIsBackFilled(bool backFilled)
1195 bool IsBackFilled() const
1199 #endif // !_TARGET_ARM_
1205 typedef struct fgArgTabEntry* fgArgTabEntryPtr;
1207 //-------------------------------------------------------------------------
1209 // The class fgArgInfo is used to handle the arguments
1210 // when morphing a GT_CALL node.
1215 Compiler* compiler; // Back pointer to the compiler instance so that we can allocate memory
1216 GenTreePtr callTree; // Back pointer to the GT_CALL node for this fgArgInfo
1217 unsigned argCount; // Updatable arg count value
1218 unsigned nextSlotNum; // Updatable slot count value
1219 unsigned stkLevel; // Stack depth when we make this call (for x86)
1221 unsigned argTableSize; // size of argTable array (equal to the argCount when done with fgMorphArgs)
1222 bool hasRegArgs; // true if we have one or more register arguments
1223 bool hasStackArgs; // true if we have one or more stack arguments
1224 bool argsComplete; // marker for state
1225 bool argsSorted; // marker for state
1226 fgArgTabEntryPtr* argTable; // variable sized array of per argument descrption: (i.e. argTable[argTableSize])
1229 void AddArg(fgArgTabEntryPtr curArgTabEntry);
1232 fgArgInfo(Compiler* comp, GenTreePtr call, unsigned argCount);
1233 fgArgInfo(GenTreePtr newCall, GenTreePtr oldCall);
1235 fgArgTabEntryPtr AddRegArg(
1236 unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1238 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
1239 fgArgTabEntryPtr AddRegArg(
1246 const bool isStruct,
1247 const regNumber otherRegNum = REG_NA,
1248 const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr = nullptr);
1249 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
1251 fgArgTabEntryPtr AddStkArg(unsigned argNum,
1255 unsigned alignment FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool isStruct));
1257 void RemorphReset();
1258 fgArgTabEntryPtr RemorphRegArg(
1259 unsigned argNum, GenTreePtr node, GenTreePtr parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1261 void RemorphStkArg(unsigned argNum, GenTreePtr node, GenTreePtr parent, unsigned numSlots, unsigned alignment);
1263 void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1265 void EvalToTmp(unsigned argNum, unsigned tmpNum, GenTreePtr newNode);
1267 void ArgsComplete();
1271 void EvalArgsToTemps();
1273 void RecordStkLevel(unsigned stkLvl);
1274 unsigned RetrieveStkLevel();
1280 fgArgTabEntryPtr* ArgTable()
1284 unsigned GetNextSlotNum()
1294 return hasStackArgs;
1299 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1300 // We have the ability to mark source expressions with "Test Labels."
1301 // These drive assertions within the JIT, or internal JIT testing. For example, we could label expressions
1302 // that should be CSE defs, and other expressions that should uses of those defs, with a shared label.
1304 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
1307 TL_VN, // Defines a "VN equivalence class". (For full VN, including exceptions thrown).
1308 TL_VNNorm, // Like above, but uses the non-exceptional value of the expression.
1309 TL_CSE_Def, // This must be identified in the JIT as a CSE def
1310 TL_CSE_Use, // This must be identified in the JIT as a CSE use
1311 TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
1314 struct TestLabelAndNum
1319 TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1324 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, TestLabelAndNum, JitSimplerHashBehavior> NodeToTestDataMap;
1326 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1329 // This class implements the "IAllocator" interface, so that we can use
1330 // utilcode collection classes in the JIT, and have them use the JIT's allocator.
1332 class CompAllocator : public IAllocator
1335 #if MEASURE_MEM_ALLOC
1339 CompAllocator(Compiler* comp, CompMemKind cmk)
1341 #if MEASURE_MEM_ALLOC
1347 inline void* Alloc(size_t sz);
1349 inline void* ArrayAlloc(size_t elems, size_t elemSize);
1351 // For the compiler's no-release allocator, free operations are no-ops.
1358 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1359 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1361 XX The big guy. The sections are currently organized as : XX
1363 XX o GenTree and BasicBlock XX
1375 XX o PrologScopeInfo XX
1376 XX o CodeGenerator XX
1381 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1382 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1387 friend class emitter;
1388 friend class UnwindInfo;
1389 friend class UnwindFragmentInfo;
1390 friend class UnwindEpilogInfo;
1391 friend class JitTimer;
1392 friend class LinearScan;
1393 friend class fgArgInfo;
1394 friend class Rationalizer;
1396 friend class Lowering;
1397 friend class CSE_DataFlow;
1398 friend class CSE_Heuristic;
1399 friend class CodeGenInterface;
1400 friend class CodeGen;
1401 friend class LclVarDsc;
1402 friend class TempDsc;
1404 friend class ObjectAllocator;
1406 #ifndef _TARGET_64BIT_
1407 friend class DecomposeLongs;
1408 #endif // !_TARGET_64BIT_
1411 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1412 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1414 XX Misc structs definitions XX
1416 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1417 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1421 hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1440 bool dumpIRDataflow;
1441 bool dumpIRBlockHeaders;
1443 LPCWSTR dumpIRPhase;
1444 LPCWSTR dumpIRFormat;
1446 bool shouldUseVerboseTrees();
1447 bool asciiTrees; // If true, dump trees using only ASCII characters
1448 bool shouldDumpASCIITrees();
1449 bool verboseSsa; // If true, produce especially verbose dump output in SSA construction.
1450 bool shouldUseVerboseSsa();
1451 bool treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
1452 int morphNum; // This counts the the trees that have been morphed, allowing us to label each uniquely.
1454 const char* VarNameToStr(VarName name)
1459 DWORD expensiveDebugCheckLevel;
1462 #if FEATURE_MULTIREG_RET
1463 GenTreePtr impAssignMultiRegTypeToVar(GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
1464 #endif // FEATURE_MULTIREG_RET
1467 bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1468 #endif // ARM_SOFTFP
1470 //-------------------------------------------------------------------------
1471 // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM.
1472 // HFAs are one to four element structs where each element is the same
1473 // type, either all float or all double. They are treated specially
1474 // in the ARM Procedure Call Standard, specifically, they are passed in
1475 // floating-point registers instead of the general purpose registers.
1478 bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1479 bool IsHfa(GenTreePtr tree);
1481 var_types GetHfaType(GenTreePtr tree);
1482 unsigned GetHfaCount(GenTreePtr tree);
1484 var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1485 unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1487 bool IsMultiRegPassedType(CORINFO_CLASS_HANDLE hClass);
1488 bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1490 //-------------------------------------------------------------------------
1491 // The following is used for validating format of EH table
1495 typedef struct EHNodeDsc* pEHNodeDsc;
1497 EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1498 EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
1511 EHBlockType ehnBlockType; // kind of EH block
1512 IL_OFFSET ehnStartOffset; // IL offset of start of the EH block
1513 IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
1514 // the last IL offset, not "one past the last one", i.e., the range Start to End is
1516 pEHNodeDsc ehnNext; // next (non-nested) block in sequential order
1517 pEHNodeDsc ehnChild; // leftmost nested block
1519 pEHNodeDsc ehnTryNode; // for filters and handlers, the corresponding try node
1520 pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
1522 pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
1523 pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,
1525 inline void ehnSetTryNodeType()
1527 ehnBlockType = TryNode;
1529 inline void ehnSetFilterNodeType()
1531 ehnBlockType = FilterNode;
1533 inline void ehnSetHandlerNodeType()
1535 ehnBlockType = HandlerNode;
1537 inline void ehnSetFinallyNodeType()
1539 ehnBlockType = FinallyNode;
1541 inline void ehnSetFaultNodeType()
1543 ehnBlockType = FaultNode;
1546 inline BOOL ehnIsTryBlock()
1548 return ehnBlockType == TryNode;
1550 inline BOOL ehnIsFilterBlock()
1552 return ehnBlockType == FilterNode;
1554 inline BOOL ehnIsHandlerBlock()
1556 return ehnBlockType == HandlerNode;
1558 inline BOOL ehnIsFinallyBlock()
1560 return ehnBlockType == FinallyNode;
1562 inline BOOL ehnIsFaultBlock()
1564 return ehnBlockType == FaultNode;
1567 // returns true if there is any overlap between the two nodes
1568 static inline BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
1570 if (node1->ehnStartOffset < node2->ehnStartOffset)
1572 return (node1->ehnEndOffset >= node2->ehnStartOffset);
1576 return (node1->ehnStartOffset <= node2->ehnEndOffset);
1580 // fails with BADCODE if inner is not completely nested inside outer
1581 static inline BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
1583 return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
1587 //-------------------------------------------------------------------------
1588 // Exception handling functions
1591 #if !FEATURE_EH_FUNCLETS
1593 bool ehNeedsShadowSPslots()
1595 return (info.compXcptnsCount || opts.compDbgEnC);
1598 // 0 for methods with no EH
1599 // 1 for methods with non-nested EH, or where only the try blocks are nested
1600 // 2 for a method with a catch within a catch
1602 unsigned ehMaxHndNestingCount;
1604 #endif // !FEATURE_EH_FUNCLETS
1606 static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
1607 static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
1609 bool bbInCatchHandlerILRange(BasicBlock* blk);
1610 bool bbInFilterILRange(BasicBlock* blk);
1611 bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
1612 bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
1613 bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
1614 bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
1615 unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);
1617 unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
1618 unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
1620 // Returns true if "block" is the start of a try region.
1621 bool bbIsTryBeg(BasicBlock* block);
1623 // Returns true if "block" is the start of a handler or filter region.
1624 bool bbIsHandlerBeg(BasicBlock* block);
1626 // Returns true iff "block" is where control flows if an exception is raised in the
1627 // try region, and sets "*regionIndex" to the index of the try for the handler.
1628 // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
1629 // block of the filter, but not for the filter's handler.
1630 bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);
1632 bool ehHasCallableHandlers();
1634 // Return the EH descriptor for the given region index.
1635 EHblkDsc* ehGetDsc(unsigned regionIndex);
1637 // Return the EH index given a region descriptor.
1638 unsigned ehGetIndex(EHblkDsc* ehDsc);
1640 // Return the EH descriptor index of the enclosing try, for the given region index.
1641 unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
1643 // Return the EH descriptor index of the enclosing handler, for the given region index.
1644 unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
1646 // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
1647 // block is not in a 'try' region).
1648 EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);
1650 // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
1651 // if this block is not in a filter or handler region).
1652 EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);
1654 // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
1655 // nullptr if this block's exceptions propagate to caller).
1656 EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);
1658 EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
1659 EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
1660 bool ehIsBlockEHLast(BasicBlock* block);
1662 bool ehBlockHasExnFlowDsc(BasicBlock* block);
1664 // Return the region index of the most nested EH region this block is in.
1665 unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
1667 // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
1668 unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
1670 // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
1671 // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
1672 // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
1673 // (It can never be a filter.)
1674 unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);
1676 // A block has been deleted. Update the EH table appropriately.
1677 void ehUpdateForDeletedBlock(BasicBlock* block);
1679 // Determine whether a block can be deleted while preserving the EH normalization rules.
1680 bool ehCanDeleteEmptyBlock(BasicBlock* block);
1682 // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
1683 void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);
1685 // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
1686 // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
1687 // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
1688 // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
1689 // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
1690 // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
1691 // lives in a filter.)
1692 unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);
1694 // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
1695 // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
1696 // (nullptr if the last block is the last block in the program).
1697 // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
1698 void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);
1701 // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
1702 // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
1703 bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
1706 #if FEATURE_EH_FUNCLETS
1707 // Do we need a PSPSym in the main function? For codegen purposes, we only need one
1708 // if there is a filter that protects a region with a nested EH clause (such as a
1709 // try/catch nested in the 'try' body of a try/filter/filter-handler). See
1710 // genFuncletProlog() for more details. However, the VM seems to use it for more
1711 // purposes, maybe including debugging. Until we are sure otherwise, always create
1712 // a PSPSym for functions with any EH.
1713 bool ehNeedsPSPSym() const
1715 return compHndBBtabCount > 0;
1718 bool ehAnyFunclets(); // Are there any funclets in this function?
1719 unsigned ehFuncletCount(); // Return the count of funclets in the function
1721 unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks
1722 #else // !FEATURE_EH_FUNCLETS
1723 bool ehAnyFunclets()
1727 unsigned ehFuncletCount()
1732 unsigned bbThrowIndex(BasicBlock* blk)
1734 return blk->bbTryIndex;
1735 } // Get the index to use as the cache key for sharing throw blocks
1736 #endif // !FEATURE_EH_FUNCLETS
1738 // Returns a flowList representing the "EH predecessors" of "blk". These are the normal predecessors of
1739 // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
1740 // first block of the corresponding try region to be "EH predecessors". (If there is a single such predecessor,
1741 // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
1742 // convenient to also consider it a predecessor.)
1743 flowList* BlockPredsWithEH(BasicBlock* blk);
1745 // This table is useful for memoization of the method above.
1746 typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, flowList*, JitSimplerHashBehavior>
1748 BlockToFlowListMap* m_blockToEHPreds;
1749 BlockToFlowListMap* GetBlockToEHPreds()
1751 if (m_blockToEHPreds == nullptr)
1753 m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
1755 return m_blockToEHPreds;
1758 void* ehEmitCookie(BasicBlock* block);
1759 UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
1761 EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
1763 EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
1765 EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
1767 EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
1769 void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
1771 void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
1773 void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
1775 void fgAllocEHTable();
1777 void fgRemoveEHTableEntry(unsigned XTnum);
1779 #if FEATURE_EH_FUNCLETS
1781 EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
1783 #endif // FEATURE_EH_FUNCLETS
1787 #endif // !FEATURE_EH
1789 void fgSortEHTable();
1791 // Causes the EH table to obey some well-formedness conditions, by inserting
1792 // empty BB's when necessary:
1793 // * No block is both the first block of a handler and the first block of a try.
1794 // * No block is the first block of multiple 'try' regions.
1795 // * No block is the last block of multiple EH regions.
1796 void fgNormalizeEH();
1797 bool fgNormalizeEHCase1();
1798 bool fgNormalizeEHCase2();
1799 bool fgNormalizeEHCase3();
1802 void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1803 void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1804 void fgVerifyHandlerTab();
1805 void fgDispHandlerTab();
1808 bool fgNeedToSortEHTable;
1810 void verInitEHTree(unsigned numEHClauses);
1811 void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
1812 void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
1813 void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
1814 void verCheckNestingLevel(EHNodeDsc* initRoot);
1817 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1818 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1820 XX GenTree and BasicBlock XX
1822 XX Functions to allocate and display the GenTrees and BasicBlocks XX
1824 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1825 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1828 // Functions to create nodes
1829 GenTreeStmt* gtNewStmt(GenTreePtr expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
1832 GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, bool doSimplifications = TRUE);
1834 // For binary opers.
1835 GenTreePtr gtNewOperNode(genTreeOps oper, var_types type, GenTreePtr op1, GenTreePtr op2);
1837 GenTreePtr gtNewQmarkNode(var_types type, GenTreePtr cond, GenTreePtr colon);
1839 GenTreePtr gtNewLargeOperNode(genTreeOps oper,
1840 var_types type = TYP_I_IMPL,
1841 GenTreePtr op1 = nullptr,
1842 GenTreePtr op2 = nullptr);
1844 GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
1846 GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
1848 GenTree* gtNewPhysRegNode(regNumber reg, GenTree* src);
1850 GenTreePtr gtNewJmpTableNode();
1851 GenTreePtr gtNewIconHandleNode(
1852 size_t value, unsigned flags, FieldSeqNode* fields = nullptr, unsigned handle1 = 0, void* handle2 = nullptr);
1854 unsigned gtTokenToIconFlags(unsigned token);
1856 GenTreePtr gtNewIconEmbHndNode(void* value,
1859 unsigned handle1 = 0,
1860 void* handle2 = nullptr,
1861 void* compileTimeHandle = nullptr);
1863 GenTreePtr gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1864 GenTreePtr gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1865 GenTreePtr gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1866 GenTreePtr gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd, unsigned hnd1 = 0, void* hnd2 = nullptr);
1868 GenTreePtr gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
1870 GenTreePtr gtNewLconNode(__int64 value);
1872 GenTreePtr gtNewDconNode(double value);
1874 GenTreePtr gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
1876 GenTreePtr gtNewZeroConNode(var_types type);
1878 GenTreePtr gtNewOneConNode(var_types type);
1880 GenTreeBlkOp* gtNewBlkOpNode(
1881 genTreeOps oper, GenTreePtr dst, GenTreePtr srcOrFillVal, GenTreePtr sizeOrClsTok, bool volatil);
1884 void gtBlockOpInit(GenTreePtr node, genTreeOps oper, GenTreePtr dst, GenTreePtr src, GenTreePtr size, bool volatil);
1887 GenTreeObj* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTreePtr addr);
1889 GenTreeBlkOp* gtNewCpObjNode(GenTreePtr dst, GenTreePtr src, CORINFO_CLASS_HANDLE structHnd, bool volatil);
1891 GenTreeBlkOp* gtCloneCpObjNode(GenTreeCpObj* source);
1893 GenTreeArgList* gtNewListNode(GenTreePtr op1, GenTreeArgList* op2);
1895 GenTreeCall* gtNewCallNode(gtCallTypes callType,
1896 CORINFO_METHOD_HANDLE handle,
1898 GenTreeArgList* args,
1899 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
1901 GenTreeCall* gtNewIndCallNode(GenTreePtr addr,
1903 GenTreeArgList* args,
1904 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
1906 GenTreeCall* gtNewHelperCallNode(unsigned helper,
1909 GenTreeArgList* args = nullptr);
1911 GenTreePtr gtNewLclvNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
1914 GenTreeSIMD* gtNewSIMDNode(
1915 var_types type, GenTreePtr op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
1916 GenTreeSIMD* gtNewSIMDNode(var_types type,
1919 SIMDIntrinsicID simdIntrinsicID,
1924 GenTreePtr gtNewLclLNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
1925 GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
1926 GenTreePtr gtNewInlineCandidateReturnExpr(GenTreePtr inlineCandidate, var_types type);
1928 GenTreePtr gtNewCodeRef(BasicBlock* block);
1930 GenTreePtr gtNewFieldRef(
1931 var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTreePtr obj = nullptr, DWORD offset = 0, bool nullcheck = false);
1933 GenTreePtr gtNewIndexRef(var_types typ, GenTreePtr arrayOp, GenTreePtr indexOp);
1935 GenTreeArgList* gtNewArgList(GenTreePtr op);
1936 GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2);
1937 GenTreeArgList* gtNewArgList(GenTreePtr op1, GenTreePtr op2, GenTreePtr op3);
1939 GenTreeArgList* gtNewAggregate(GenTree* element);
1941 static fgArgTabEntryPtr gtArgEntryByArgNum(GenTreePtr call, unsigned argNum);
1942 static fgArgTabEntryPtr gtArgEntryByNode(GenTreePtr call, GenTreePtr node);
1943 fgArgTabEntryPtr gtArgEntryByLateArgIndex(GenTreePtr call, unsigned lateArgInx);
1944 bool gtArgIsThisPtr(fgArgTabEntryPtr argEntry);
1946 GenTreePtr gtNewAssignNode(GenTreePtr dst, GenTreePtr src);
1948 GenTreePtr gtNewTempAssign(unsigned tmp, GenTreePtr val);
1950 GenTreePtr gtNewRefCOMfield(GenTreePtr objPtr,
1951 CORINFO_RESOLVED_TOKEN* pResolvedToken,
1952 CORINFO_ACCESS_FLAGS access,
1953 CORINFO_FIELD_INFO* pFieldInfo,
1955 CORINFO_CLASS_HANDLE structType,
1958 GenTreePtr gtNewNothingNode();
1960 GenTreePtr gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
1962 GenTreePtr gtUnusedValNode(GenTreePtr expr);
1964 GenTreePtr gtNewCastNode(var_types typ, GenTreePtr op1, var_types castType);
1966 GenTreePtr gtNewCastNodeL(var_types typ, GenTreePtr op1, var_types castType);
1968 GenTreePtr gtNewAllocObjNode(unsigned int helper, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTreePtr op1);
1970 //------------------------------------------------------------------------
1971 // Other GenTree functions
1973 GenTreePtr gtClone(GenTree* tree, bool complexOK = false);
1975 GenTreePtr gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = (unsigned)-1, int varVal = 0);
1977 GenTreePtr gtReplaceTree(GenTreePtr stmt, GenTreePtr tree, GenTreePtr replacementTree);
1979 void gtUpdateSideEffects(GenTreePtr tree, unsigned oldGtFlags, unsigned newGtFlags);
1981 // Returns "true" iff the complexity (not formally defined, but first interpretation
1982 // is #of nodes in subtree) of "tree" is greater than "limit".
1983 // (This is somewhat redundant with the "gtCostEx/gtCostSz" fields, but can be used
1984 // before they have been set.)
1985 bool gtComplexityExceeds(GenTreePtr* tree, unsigned limit);
1987 bool gtCompareTree(GenTree* op1, GenTree* op2);
1989 GenTreePtr gtReverseCond(GenTree* tree);
1991 bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
1993 bool gtHasLocalsWithAddrOp(GenTreePtr tree);
1995 unsigned gtHashValue(GenTree* tree);
1997 unsigned gtSetListOrder(GenTree* list, bool regs);
1999 void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* adr, bool constOnly);
2002 GenTreePtr gtWalkOpEffectiveVal(GenTreePtr op);
2005 void gtPrepareCost(GenTree* tree);
2006 bool gtIsLikelyRegVar(GenTree* tree);
2008 unsigned gtSetEvalOrderAndRestoreFPstkLevel(GenTree* tree);
2010 // Returns true iff the secondNode can be swapped with firstNode.
2011 bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2013 unsigned gtSetEvalOrder(GenTree* tree);
2015 #if FEATURE_STACK_FP_X87
2017 void gtComputeFPlvls(GenTreePtr tree);
2018 #endif // FEATURE_STACK_FP_X87
2020 void gtSetStmtInfo(GenTree* stmt);
2022 // Returns "true" iff "node" has any of the side effects in "flags".
2023 bool gtNodeHasSideEffects(GenTreePtr node, unsigned flags);
2025 // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2026 bool gtTreeHasSideEffects(GenTreePtr tree, unsigned flags);
2028 // Appends 'expr' in front of 'list'
2029 // 'list' will typically start off as 'nullptr'
2030 // when 'list' is non-null a GT_COMMA node is used to insert 'expr'
2031 GenTreePtr gtBuildCommaList(GenTreePtr list, GenTreePtr expr);
2033 void gtExtractSideEffList(GenTreePtr expr,
2035 unsigned flags = GTF_SIDE_EFFECT,
2036 bool ignoreRoot = false);
2038 GenTreePtr gtGetThisArg(GenTreePtr call);
2040 // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
2041 // static field contain an object pointer to the boxed struct. This simplifies the GC implementation...but
2042 // complicates the JIT somewhat. This predicate returns "true" iff a node with type "fieldNodeType", representing
2043 // the given "fldHnd", is such an object pointer.
2044 bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);
2046 // Return true if call is a recursive call; return false otherwise.
2047 bool gtIsRecursiveCall(GenTreeCall* call)
2049 return (call->gtCallMethHnd == info.compMethodHnd);
2052 //-------------------------------------------------------------------------
2054 GenTreePtr gtFoldExpr(GenTreePtr tree);
2057 // TODO-Amd64-Unix: Remove this when the clang optimizer is fixed and/or the method implementation is
2058 // refactored in a simpler code. This is a workaround for a bug in the clang-3.5 optimizer. The issue is that in
2059 // release build the optimizer is mistyping (or just wrongly decides to use 32 bit operation for a corner case
2060 // of MIN_LONG) the args of the (ltemp / lval2) to int (it does a 32 bit div operation instead of 64 bit) - see
2061 // the implementation of the method in gentree.cpp. For the case of lval1 and lval2 equal to MIN_LONG
2062 // (0x8000000000000000) this results in raising a SIGFPE. The method implementation is rather complex. Disable
2063 // optimizations for now.
2064 __attribute__((optnone))
2066 gtFoldExprConst(GenTreePtr tree);
2067 GenTreePtr gtFoldExprSpecial(GenTreePtr tree);
2068 GenTreePtr gtFoldExprCompare(GenTreePtr tree);
2070 //-------------------------------------------------------------------------
2071 // Get the handle, if any.
2072 CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTreePtr tree);
2073 // Get the handle, and assert if not found.
2074 CORINFO_CLASS_HANDLE gtGetStructHandle(GenTreePtr tree);
2076 //-------------------------------------------------------------------------
2077 // Functions to display the trees
2080 void gtDispNode(GenTreePtr tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
2082 void gtDispVN(GenTreePtr tree);
2083 void gtDispConst(GenTreePtr tree);
2084 void gtDispLeaf(GenTreePtr tree, IndentStack* indentStack);
2085 void gtDispNodeName(GenTreePtr tree);
2086 void gtDispRegVal(GenTreePtr tree);
2098 void gtDispChild(GenTreePtr child,
2099 IndentStack* indentStack,
2101 __in_opt const char* msg = nullptr,
2102 bool topOnly = false);
2103 void gtDispTree(GenTreePtr tree,
2104 IndentStack* indentStack = nullptr,
2105 __in_opt const char* msg = nullptr,
2106 bool topOnly = false,
2107 bool isLIR = false);
2108 void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
2109 int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
2110 char* gtGetLclVarName(unsigned lclNum);
2111 void gtDispLclVar(unsigned varNum, bool padForBiggestDisp = true);
2112 void gtDispTreeList(GenTreePtr tree, IndentStack* indentStack = nullptr);
2113 void gtGetArgMsg(GenTreePtr call, GenTreePtr arg, unsigned argNum, int listCount, char* bufp, unsigned bufLength);
2114 void gtGetLateArgMsg(GenTreePtr call, GenTreePtr arg, int argNum, int listCount, char* bufp, unsigned bufLength);
2115 void gtDispArgList(GenTreePtr tree, IndentStack* indentStack);
2116 void gtDispFieldSeq(FieldSeqNode* pfsn);
2118 void gtDispRange(LIR::ReadOnlyRange const& range);
2120 void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2122 void gtDispLIRNode(GenTree* node);
2134 typedef fgWalkResult(fgWalkPreFn)(GenTreePtr* pTree, fgWalkData* data);
2135 typedef fgWalkResult(fgWalkPostFn)(GenTreePtr* pTree, fgWalkData* data);
2138 static fgWalkPreFn gtAssertColonCond;
2140 static fgWalkPreFn gtMarkColonCond;
2141 static fgWalkPreFn gtClearColonCond;
2143 GenTreePtr* gtFindLink(GenTreePtr stmt, GenTreePtr node);
2144 bool gtHasCatchArg(GenTreePtr tree);
2145 bool gtHasUnmanagedCall(GenTreePtr tree);
2147 typedef ArrayStack<GenTree*> GenTreeStack;
2149 static bool gtHasCallOnStack(GenTreeStack* parentStack);
2150 void gtCheckQuirkAddrExposedLclVar(GenTreePtr argTree, GenTreeStack* parentStack);
2152 //=========================================================================
2153 // BasicBlock functions
2155 // This is a debug flag we will use to assert when creating block during codegen
2156 // as this interferes with procedure splitting. If you know what you're doing, set
2157 // it to true before creating the block. (DEBUG only)
2158 bool fgSafeBasicBlockCreation;
2161 BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2164 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2165 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2169 XX The variables to be used by the code generator. XX
2171 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2172 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2176 // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
2177 // be placed in the stack frame and it's fields must be laid out sequentially.
2179 // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
2180 // a local variable that can be enregistered or placed in the stack frame.
2181 // The fields do not need to be laid out sequentially
2183 enum lvaPromotionType
2185 PROMOTION_TYPE_NONE, // The struct local is not promoted
2186 PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
2187 // and its field locals are independent of its parent struct local.
2188 PROMOTION_TYPE_DEPENDENT // The struct local is promoted,
2189 // but its field locals depend on its parent struct local.
2192 static int __cdecl RefCntCmp(const void* op1, const void* op2);
2193 static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2195 /*****************************************************************************/
2197 enum FrameLayoutState
2200 INITIAL_FRAME_LAYOUT,
2201 PRE_REGALLOC_FRAME_LAYOUT,
2202 REGALLOC_FRAME_LAYOUT,
2203 TENTATIVE_FRAME_LAYOUT,
2208 bool lvaRefCountingStarted; // Set to true when we have started counting the local vars
2209 bool lvaLocalVarRefCounted; // Set to true after we have called lvaMarkLocalVars()
2210 bool lvaSortAgain; // true: We need to sort the lvaTable
2211 bool lvaTrackedFixed; // true: We cannot add new 'tracked' variable
2212 unsigned lvaCount; // total number of locals
2214 unsigned lvaRefCount; // total number of references to locals
2215 LclVarDsc* lvaTable; // variable descriptor table
2216 unsigned lvaTableCnt; // lvaTable size (>= lvaCount)
2218 LclVarDsc** lvaRefSorted; // table sorted by refcount
2220 unsigned short lvaTrackedCount; // actual # of locals being tracked
2221 unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked
2223 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
2224 // Only for AMD64 System V cache the first caller stack homed argument.
2225 unsigned lvaFirstStackIncomingArgNum; // First argument with stack slot in the caller.
2226 #endif // !FEATURE_UNIX_AMD64_STRUCT_PASSING
2229 VARSET_TP lvaTrackedVars; // set of tracked variables
2231 #ifndef _TARGET_64BIT_
2232 VARSET_TP lvaLongVars; // set of long (64-bit) variables
2234 VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
2236 unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
2237 // It that changes, this changes. VarSets from different epochs
2238 // cannot be meaningfully combined.
2240 unsigned GetCurLVEpoch()
2245 // reverse map of tracked number to var number
2246 unsigned lvaTrackedToVarNum[lclMAX_TRACKED];
2248 #ifdef LEGACY_BACKEND
2249 // variable interference graph
2250 VARSET_TP lvaVarIntf[lclMAX_TRACKED];
2253 // variable preference graph
2254 VARSET_TP lvaVarPref[lclMAX_TRACKED];
2258 // # of procs compiled a with double-aligned stack
2259 static unsigned s_lvaDoubleAlignedProcsCount;
2263 // Getters and setters for address-exposed and do-not-enregister local var properties.
2264 bool lvaVarAddrExposed(unsigned varNum);
2265 void lvaSetVarAddrExposed(unsigned varNum);
2266 bool lvaVarDoNotEnregister(unsigned varNum);
2268 // Reasons why we can't enregister. Some of these correspond to debug properties of local vars.
2269 enum DoNotEnregisterReason
2274 DNER_VMNeedsStackAddr,
2275 DNER_LiveInOutOfHandler,
2276 DNER_LiveAcrossUnmanagedCall,
2277 DNER_BlockOp, // Is read or written via a block operation that explicitly takes the address.
2278 #ifdef JIT32_GCENCODER
2283 void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2285 unsigned lvaVarargsHandleArg;
2287 unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2289 #endif // _TARGET_X86_
2291 unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
2292 unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
2293 #if FEATURE_FIXED_OUT_ARGS
2294 unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
2296 unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2297 // that tracks whether the lock has been taken
2299 unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
2300 // However, if there is a "ldarga 0" or "starg 0" in the IL,
2301 // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.
2303 unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2304 // in case there are multiple BBJ_RETURN blocks in the inlinee.
2306 #if FEATURE_FIXED_OUT_ARGS
2307 unsigned lvaOutgoingArgSpaceVar; // dummy TYP_LCLBLK var for fixed outgoing argument space
2308 unsigned lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
2309 #endif // FEATURE_FIXED_OUT_ARGS
2312 // On architectures whose ABIs allow structs to be passed in registers, struct promotion will sometimes
2313 // require us to "rematerialize" a struct from it's separate constituent field variables. Packing several sub-word
2314 // field variables into an argument register is a hard problem. It's easier to reserve a word of memory into which
2315 // such field can be copied, after which the assembled memory word can be read into the register. We will allocate
2316 // this variable to be this scratch word whenever struct promotion occurs.
2317 unsigned lvaPromotedStructAssemblyScratchVar;
2318 #endif // _TARGET_ARM_
2321 unsigned lvaReturnEspCheck; // confirms ESP not corrupted on return
2322 unsigned lvaCallEspCheck; // confirms ESP not corrupted after a call
2325 bool lvaGenericsContextUsed;
2327 bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
2328 // CORINFO_GENERICS_CTXT_FROM_THIS?
2329 bool lvaReportParamTypeArg(); // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?
2331 //-------------------------------------------------------------------------
2332 // All these frame offsets are inter-related and must be kept in sync
2334 #if !FEATURE_EH_FUNCLETS
2335 // This is used for the callable handlers
2336 unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
2337 #endif // FEATURE_EH_FUNCLETS
2339 unsigned lvaCachedGenericContextArgOffs;
2340 unsigned lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2343 unsigned lvaLocAllocSPvar; // variable which has the result of the last alloca/localloc
2345 unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
2347 // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
2348 // after the reg predict we will use a computed maxTmpSize
2349 // which is based upon the number of spill temps predicted by reg predict
2350 // All this is necessary because if we under-estimate the size of the spill
2351 // temps we could fail when encoding instructions that reference stack offsets for ARM.
2353 // Pre codegen max spill temp size.
2354 static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2356 //-------------------------------------------------------------------------
2358 unsigned lvaGetMaxSpillTempSize();
2360 bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2361 #endif // _TARGET_ARM_
2362 void lvaAssignFrameOffsets(FrameLayoutState curState);
2363 void lvaFixVirtualFrameOffsets();
2365 #ifndef LEGACY_BACKEND
2366 void lvaUpdateArgsWithInitialReg();
2367 #endif // !LEGACY_BACKEND
2369 void lvaAssignVirtualFrameOffsetsToArgs();
2370 #ifdef UNIX_AMD64_ABI
2371 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
2372 #else // !UNIX_AMD64_ABI
2373 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
2374 #endif // !UNIX_AMD64_ABI
2375 void lvaAssignVirtualFrameOffsetsToLocals();
2376 int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
2377 #ifdef _TARGET_AMD64_
2378 // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
2379 bool lvaIsCalleeSavedIntRegCountEven();
2381 void lvaAlignFrame();
2382 void lvaAssignFrameOffsetsToPromotedStructs();
2383 int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
2386 void lvaDumpRegLocation(unsigned lclNum);
2387 void lvaDumpFrameLocation(unsigned lclNum);
2388 void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
2389 void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
2390 // layout state defined by lvaDoneFrameLayout
2393 // Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
2394 // to avoid bugs from borderline cases.
2395 #define MAX_FrameSize 0x3FFFFFFF
2396 void lvaIncrementFrameSize(unsigned size);
2398 unsigned lvaFrameSize(FrameLayoutState curState);
2400 // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2401 int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2403 // Returns the caller-SP-relative offset for the local variable "varNum."
2404 int lvaGetCallerSPRelativeOffset(unsigned varNum);
2406 // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2407 int lvaGetSPRelativeOffset(unsigned varNum);
2409 int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2410 int lvaGetInitialSPRelativeOffset(unsigned varNum);
2412 //------------------------ For splitting types ----------------------------
2414 void lvaInitTypeRef();
2416 void lvaInitArgs(InitVarDscInfo* varDscInfo);
2417 void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
2418 void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo);
2419 void lvaInitUserArgs(InitVarDscInfo* varDscInfo);
2420 void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
2421 void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);
2423 void lvaInitVarDsc(LclVarDsc* varDsc,
2425 CorInfoType corInfoType,
2426 CORINFO_CLASS_HANDLE typeHnd,
2427 CORINFO_ARG_LIST_HANDLE varList,
2428 CORINFO_SIG_INFO* varSig);
2430 static unsigned lvaTypeRefMask(var_types type);
2432 var_types lvaGetActualType(unsigned lclNum);
2433 var_types lvaGetRealType(unsigned lclNum);
2435 //-------------------------------------------------------------------------
2439 unsigned lvaArgSize(const void* argTok);
2440 unsigned lvaLclSize(unsigned varNum);
2441 unsigned lvaLclExactSize(unsigned varNum);
2443 bool lvaLclVarRefs(GenTreePtr tree, GenTreePtr* findPtr, varRefKinds* refsPtr, void* result);
2445 // Call lvaLclVarRefs on "true"; accumulate "*result" into whichever of
2446 // "allVars" and "trkdVars" is indiated by the nullness of "findPtr"; return
2447 // the return result.
2448 bool lvaLclVarRefsAccum(
2449 GenTreePtr tree, GenTreePtr* findPtr, varRefKinds* refsPtr, ALLVARSET_TP* allVars, VARSET_TP* trkdVars);
2451 // If "findPtr" is non-NULL, assumes "result" is an "ALLVARSET_TP*", and
2452 // (destructively) unions "allVars" into "*result". Otherwise, assumes "result" is a "VARSET_TP*",
2453 // and (destructively) unions "trkedVars" into "*result".
2454 void lvaLclVarRefsAccumIntoRes(GenTreePtr* findPtr,
2456 ALLVARSET_VALARG_TP allVars,
2457 VARSET_VALARG_TP trkdVars);
2459 bool lvaHaveManyLocals() const;
2461 unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
2462 unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
2463 unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));
2466 void lvaSortByRefCount();
2467 void lvaDumpRefCounts();
2469 void lvaMarkLocalVars(BasicBlock* block);
2471 void lvaMarkLocalVars(); // Local variable ref-counting
2473 void lvaAllocOutgoingArgSpace(); // 'Commit' lvaOutgoingArgSpaceSize and lvaOutgoingArgSpaceVar
2475 VARSET_VALRET_TP lvaStmtLclMask(GenTreePtr stmt);
2477 static fgWalkPreFn lvaIncRefCntsCB;
2478 void lvaIncRefCnts(GenTreePtr tree);
2480 static fgWalkPreFn lvaDecRefCntsCB;
2481 void lvaDecRefCnts(GenTreePtr tree);
2482 void lvaDecRefCnts(BasicBlock* basicBlock, GenTreePtr tree);
2483 void lvaRecursiveDecRefCounts(GenTreePtr tree);
2484 void lvaRecursiveIncRefCounts(GenTreePtr tree);
2487 struct lvaStressLclFldArgs
2489 Compiler* m_pCompiler;
2493 static fgWalkPreFn lvaStressLclFldCB;
2494 void lvaStressLclFld();
2496 void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
2497 void lvaDispVarSet(VARSET_VALARG_TP set);
2502 int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset);
2504 int lvaFrameAddress(int varNum, bool* pFPbased);
2507 bool lvaIsParameter(unsigned varNum);
2508 bool lvaIsRegArgument(unsigned varNum);
2509 BOOL lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
2510 BOOL lvaIsOriginalThisReadOnly(); // return TRUE if there is no place in the code
2511 // that writes to arg0
2513 // Struct parameters that are passed by reference are marked as both lvIsParam and lvIsTemp
2514 // (this is an overload of lvIsTemp because there are no temp parameters).
2515 // For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference.
2516 // For ARM64, this is structs larger than 16 bytes that are passed by reference.
2517 bool lvaIsImplicitByRefLocal(unsigned varNum)
2519 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2520 LclVarDsc* varDsc = &(lvaTable[varNum]);
2521 if (varDsc->lvIsParam && varDsc->lvIsTemp)
2523 assert((varDsc->lvType == TYP_STRUCT) || (varDsc->lvType == TYP_BYREF));
2526 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2530 // Returns true if this local var is a multireg struct
2531 bool lvaIsMultiregStruct(LclVarDsc* varDsc);
2533 // If the class is a TYP_STRUCT, get/set a class handle describing it
2535 CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
2536 void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
2538 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
2540 // Info about struct fields
2541 struct lvaStructFieldInfo
2543 CORINFO_FIELD_HANDLE fldHnd;
2544 unsigned char fldOffset;
2545 unsigned char fldOrdinal;
2548 CORINFO_CLASS_HANDLE fldTypeHnd;
2551 // Info about struct to be promoted.
2552 struct lvaStructPromotionInfo
2554 CORINFO_CLASS_HANDLE typeHnd;
2556 bool requiresScratchVar;
2559 unsigned char fieldCnt;
2560 lvaStructFieldInfo fields[MAX_NumOfFieldsInPromotableStruct];
2562 lvaStructPromotionInfo()
2563 : typeHnd(nullptr), canPromote(false), requiresScratchVar(false), containsHoles(false), customLayout(false)
2568 static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
2569 void lvaCanPromoteStructType(CORINFO_CLASS_HANDLE typeHnd,
2570 lvaStructPromotionInfo* StructPromotionInfo,
2572 void lvaCanPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2573 void lvaPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2574 #if !defined(_TARGET_64BIT_)
2575 void lvaPromoteLongVars();
2576 #endif // !defined(_TARGET_64BIT_)
2577 unsigned lvaGetFieldLocal(LclVarDsc* varDsc, unsigned int fldOffset);
2578 lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
2579 lvaPromotionType lvaGetPromotionType(unsigned varNum);
2580 lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
2581 lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
2582 bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
2583 bool lvaIsGCTracked(const LclVarDsc* varDsc);
2585 BYTE* lvaGetGcLayout(unsigned varNum);
2586 bool lvaTypeIsGC(unsigned varNum);
2587 unsigned lvaGSSecurityCookie; // LclVar number
2588 bool lvaTempsHaveLargerOffsetThanVars();
2590 unsigned lvaSecurityObject; // variable representing the security object on the stack
2591 unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
2593 #if FEATURE_EH_FUNCLETS
2594 unsigned lvaPSPSym; // variable representing the PSPSym
2597 InlineInfo* impInlineInfo;
2598 InlineStrategy* m_inlineStrategy;
2600 // The Compiler* that is the root of the inlining tree of which "this" is a member.
2601 Compiler* impInlineRoot();
2603 #if defined(DEBUG) || defined(INLINE_DATA)
2604 unsigned __int64 getInlineCycleCount()
2606 return m_compCycles;
2608 #endif // defined(DEBUG) || defined(INLINE_DATA)
2610 bool fgNoStructPromotion; // Set to TRUE to turn off struct promotion for this method.
2611 bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.
2613 //=========================================================================
2615 //=========================================================================
2618 //---------------- Local variable ref-counting ----------------------------
2621 BasicBlock* lvaMarkRefsCurBlock;
2622 GenTreePtr lvaMarkRefsCurStmt;
2624 BasicBlock::weight_t lvaMarkRefsWeight;
2626 static fgWalkPreFn lvaMarkLclRefsCallback;
2627 void lvaMarkLclRefs(GenTreePtr tree);
2629 // Keeps the mapping from SSA #'s to VN's for the implicit "Heap" variable.
2630 PerSsaArray lvHeapPerSsaData;
2631 unsigned lvHeapNumSsaNames;
2634 // Returns the address of the per-Ssa data for "Heap" at the given ssaNum (which is required
2635 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
2636 // not an SSA variable).
2637 LclSsaVarDsc* GetHeapPerSsaData(unsigned ssaNum)
2639 assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
2640 assert(SsaConfig::RESERVED_SSA_NUM == 0);
2642 assert(ssaNum < lvHeapNumSsaNames);
2643 return &lvHeapPerSsaData.GetRef(ssaNum);
2647 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2648 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2652 XX Imports the given method and converts it to semantic trees XX
2654 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2655 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2661 void impImport(BasicBlock* method);
2663 CORINFO_CLASS_HANDLE impGetRefAnyClass();
2664 CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
2665 CORINFO_CLASS_HANDLE impGetTypeHandleClass();
2666 CORINFO_CLASS_HANDLE impGetStringClass();
2667 CORINFO_CLASS_HANDLE impGetObjectClass();
2669 //=========================================================================
2671 //=========================================================================
2674 //-------------------- Stack manipulation ---------------------------------
2676 unsigned impStkSize; // Size of the full stack
2678 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
2680 StackEntry impSmallStack[SMALL_STACK_SIZE]; // Use this array if possible
2682 struct SavedStack // used to save/restore stack contents.
2684 unsigned ssDepth; // number of values on stack
2685 StackEntry* ssTrees; // saved tree values
2688 bool impIsPrimitive(CorInfoType type);
2689 bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
2691 void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
2692 void impPushOnStackNoType(GenTreePtr tree);
2694 void impPushOnStack(GenTreePtr tree, typeInfo ti);
2695 void impPushNullObjRefOnStack();
2696 StackEntry impPopStack();
2697 StackEntry impPopStack(CORINFO_CLASS_HANDLE& structTypeRet);
2698 GenTreePtr impPopStack(typeInfo& ti);
2699 StackEntry& impStackTop(unsigned n = 0);
2701 void impSaveStackState(SavedStack* savePtr, bool copy);
2702 void impRestoreStackState(SavedStack* savePtr);
2704 GenTreePtr impImportLdvirtftn(GenTreePtr thisPtr,
2705 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2706 CORINFO_CALL_INFO* pCallInfo);
2708 void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2710 void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2712 bool impCanPInvokeInline(var_types callRetTyp);
2713 bool impCanPInvokeInlineCallSite(var_types callRetTyp);
2714 void impCheckForPInvokeCall(GenTreePtr call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags);
2715 GenTreePtr impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2716 void impPopArgsForUnmanagedCall(GenTreePtr call, CORINFO_SIG_INFO* sig);
2718 void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
2719 void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2720 void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2722 void impInsertCalloutForDelegate(CORINFO_METHOD_HANDLE callerMethodHnd,
2723 CORINFO_METHOD_HANDLE calleeMethodHnd,
2724 CORINFO_CLASS_HANDLE delegateTypeHnd);
2726 var_types impImportCall(OPCODE opcode,
2727 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2728 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
2730 GenTreePtr newobjThis,
2732 CORINFO_CALL_INFO* callInfo,
2733 IL_OFFSET rawILOffset);
2735 bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
2737 GenTreePtr impFixupCallStructReturn(GenTreePtr call, CORINFO_CLASS_HANDLE retClsHnd);
2739 GenTreePtr impInitCallLongReturn(GenTreePtr call);
2741 GenTreePtr impFixupStructReturnType(GenTreePtr op, CORINFO_CLASS_HANDLE retClsHnd);
2744 var_types impImportJitTestLabelMark(int numArgs);
2747 GenTreePtr impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2749 GenTreePtr impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
2751 GenTreePtr impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2752 CORINFO_ACCESS_FLAGS access,
2753 CORINFO_FIELD_INFO* pFieldInfo,
2756 static void impBashVarAddrsToI(GenTreePtr tree1, GenTreePtr tree2 = nullptr);
2758 GenTreePtr impImplicitIorI4Cast(GenTreePtr tree, var_types dstTyp);
2760 GenTreePtr impImplicitR4orR8Cast(GenTreePtr tree, var_types dstTyp);
2762 void impImportLeave(BasicBlock* block);
2763 void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
2764 BOOL impLocAllocOnStack();
2765 GenTreePtr impIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
2766 CORINFO_METHOD_HANDLE method,
2767 CORINFO_SIG_INFO* sig,
2771 CorInfoIntrinsics* pIntrinsicID);
2772 GenTreePtr impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
2773 CORINFO_SIG_INFO* sig,
2776 CorInfoIntrinsics intrinsicID);
2777 GenTreePtr impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
2779 GenTreePtr impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2781 GenTreePtr impTransformThis(GenTreePtr thisPtr,
2782 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
2783 CORINFO_THIS_TRANSFORM transform);
2785 //----------------- Manipulating the trees and stmts ----------------------
2787 GenTreePtr impTreeList; // Trees for the BB being imported
2788 GenTreePtr impTreeLast; // The last tree for the current BB
2792 CHECK_SPILL_ALL = -1,
2793 CHECK_SPILL_NONE = -2
2797 void impBeginTreeList();
2798 void impEndTreeList(BasicBlock* block, GenTreePtr firstStmt, GenTreePtr lastStmt);
2799 void impEndTreeList(BasicBlock* block);
2800 void impAppendStmtCheck(GenTreePtr stmt, unsigned chkLevel);
2801 void impAppendStmt(GenTreePtr stmt, unsigned chkLevel);
2802 void impInsertStmtBefore(GenTreePtr stmt, GenTreePtr stmtBefore);
2803 GenTreePtr impAppendTree(GenTreePtr tree, unsigned chkLevel, IL_OFFSETX offset);
2804 void impInsertTreeBefore(GenTreePtr tree, IL_OFFSETX offset, GenTreePtr stmtBefore);
2805 void impAssignTempGen(unsigned tmp,
2808 GenTreePtr* pAfterStmt = nullptr,
2809 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
2810 BasicBlock* block = nullptr);
2811 void impAssignTempGen(unsigned tmpNum,
2813 CORINFO_CLASS_HANDLE structHnd,
2815 GenTreePtr* pAfterStmt = nullptr,
2816 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
2817 BasicBlock* block = nullptr);
2818 GenTreePtr impCloneExpr(GenTreePtr tree,
2820 CORINFO_CLASS_HANDLE structHnd,
2822 GenTreePtr* pAfterStmt DEBUGARG(const char* reason));
2823 GenTreePtr impAssignStruct(GenTreePtr dest,
2825 CORINFO_CLASS_HANDLE structHnd,
2827 GenTreePtr* pAfterStmt = nullptr,
2828 BasicBlock* block = nullptr);
2829 GenTreePtr impAssignStructPtr(GenTreePtr dest,
2831 CORINFO_CLASS_HANDLE structHnd,
2833 GenTreePtr* pAfterStmt = nullptr,
2834 BasicBlock* block = nullptr);
2836 GenTreePtr impGetStructAddr(GenTreePtr structVal,
2837 CORINFO_CLASS_HANDLE structHnd,
2841 var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
2842 BYTE* gcLayout = nullptr,
2843 unsigned* numGCVars = nullptr,
2844 var_types* simdBaseType = nullptr);
2846 GenTreePtr impNormStructVal(GenTreePtr structVal,
2847 CORINFO_CLASS_HANDLE structHnd,
2849 bool forceNormalization = false);
2851 GenTreePtr impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2852 BOOL* pRuntimeLookup = nullptr,
2853 BOOL mustRestoreHandle = FALSE,
2854 BOOL importParent = FALSE);
2856 GenTreePtr impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2857 BOOL* pRuntimeLookup = nullptr,
2858 BOOL mustRestoreHandle = FALSE)
2860 return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
2863 GenTreePtr impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2864 CORINFO_LOOKUP* pLookup,
2866 void* compileTimeHandle);
2868 GenTreePtr impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2869 CORINFO_LOOKUP* pLookup,
2870 void* compileTimeHandle);
2872 GenTreePtr impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
2874 GenTreePtr impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
2875 CorInfoHelpFunc helper,
2877 GenTreeArgList* arg = nullptr,
2878 CORINFO_LOOKUP_KIND* pGenericLookupKind = nullptr);
2880 GenTreePtr impCastClassOrIsInstToTree(GenTreePtr op1,
2882 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2885 bool VarTypeIsMultiByteAndCanEnreg(var_types type,
2886 CORINFO_CLASS_HANDLE typeClass,
2890 static bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
2891 static bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
2892 static bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
2893 static bool IsMathIntrinsic(GenTreePtr tree);
2896 //----------------- Importing the method ----------------------------------
2898 CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
2901 unsigned impCurOpcOffs;
2902 const char* impCurOpcName;
2903 bool impNestedStackSpill;
2905 // For displaying instrs with generated native code (-n:B)
2906 GenTreePtr impLastILoffsStmt; // oldest stmt added for which we did not gtStmtLastILoffs
2907 void impNoteLastILoffs();
2910 /* IL offset of the stmt currently being imported. It gets set to
2911 BAD_IL_OFFSET after it has been set in the appended trees. Then it gets
2912 updated at IL offsets for which we have to report mapping info.
2913 It also includes flag bits, so use jitGetILoffs()
2914 to get the actual IL offset value.
2917 IL_OFFSETX impCurStmtOffs;
2918 void impCurStmtOffsSet(IL_OFFSET offs);
2920 void impNoteBranchOffs();
2922 unsigned impInitBlockLineInfo();
2924 GenTreePtr impCheckForNullPointer(GenTreePtr obj);
2925 bool impIsThis(GenTreePtr obj);
2926 bool impIsLDFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
2927 bool impIsDUP_LDVIRTFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
2928 bool impIsAnySTLOC(OPCODE opcode)
2930 return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
2931 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
2934 GenTreeArgList* impPopList(unsigned count,
2936 CORINFO_SIG_INFO* sig,
2937 GenTreeArgList* prefixTree = nullptr);
2939 GenTreeArgList* impPopRevList(unsigned count,
2941 CORINFO_SIG_INFO* sig,
2942 unsigned skipReverseCount = 0);
2945 * Get current IL offset with stack-empty info incoporated
2947 IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
2949 //---------------- Spilling the importer stack ----------------------------
2955 SavedStack pdSavedStack;
2956 ThisInitState pdThisPtrInit;
2959 PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
2960 PendingDsc* impPendingFree; // Freed up dscs that can be reused
2962 // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
2963 ExpandArray<BYTE> impPendingBlockMembers;
2965 // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
2966 // Operates on the map in the top-level ancestor.
2967 BYTE impGetPendingBlockMember(BasicBlock* blk)
2969 return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
2972 // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
2973 // Operates on the map in the top-level ancestor.
2974 void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
2976 impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
2979 bool impCanReimport;
2981 bool impSpillStackEntry(unsigned level,
2985 bool bAssertOnRecursion,
2990 void impSpillStackEnsure(bool spillLeaves = false);
2991 void impEvalSideEffects();
2992 void impSpillSpecialSideEff();
2993 void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
2994 void impSpillValueClasses();
2995 void impSpillEvalStack();
2996 static fgWalkPreFn impFindValueClasses;
2997 void impSpillLclRefs(ssize_t lclNum);
2999 BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd);
3001 void impImportBlockCode(BasicBlock* block);
3003 void impReimportMarkBlock(BasicBlock* block);
3004 void impReimportMarkSuccessors(BasicBlock* block);
3006 void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3008 void impImportBlockPending(BasicBlock* block);
3010 // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
3011 // reimported for some reason. It specifically does *not* look at verCurrentState to set the EntryState
3012 // for the block, but instead, just re-uses the block's existing EntryState.
3013 void impReimportBlockPending(BasicBlock* block);
3015 var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTreePtr* pOp1, GenTreePtr* pOp2);
3017 void impImportBlock(BasicBlock* block);
3019 // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
3020 // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
3021 // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
3022 // the variables that will be used -- and for all the predecessors of those successors, and the
3023 // successors of those predecessors, etc. Call such a set of blocks closed under alternating
3024 // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
3025 // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
3026 // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
3027 // of local variable numbers, so we represent them with the base local variable number), returns that.
3028 // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
3029 // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
3030 // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
3031 // on which kind of member of the clique the block is).
3032 unsigned impGetSpillTmpBase(BasicBlock* block);
3034 // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
3035 // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
3036 // will assume that its incoming stack contents are in those locals. This requires "block" and its
3037 // successors to agree on the variables and their types that will be used. The CLI spec allows implicit
3038 // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
3039 // push an int and another can push a native int. For 64-bit we have chosen to implement this by typing
3040 // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
3041 // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
3042 // successors receive a native int. Similarly float and double are unified to double.
3043 // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
3044 // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
3045 // predecessors, so they insert an upcast if needed).
3046 void impReimportSpillClique(BasicBlock* block);
3048 // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
3049 // block, and represent the predecessor and successor members of the clique currently being computed.
3050 // *** Access to these will need to be locked in a parallel compiler.
3051 ExpandArray<BYTE> impSpillCliquePredMembers;
3052 ExpandArray<BYTE> impSpillCliqueSuccMembers;
3060 // Abstract class for receiving a callback while walking a spill clique
3061 class SpillCliqueWalker
3064 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3067 // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3068 class SetSpillTempsBase : public SpillCliqueWalker
3073 SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3076 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3079 // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3080 class ReimportSpillClique : public SpillCliqueWalker
3085 ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3088 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3091 // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
3092 // predecessor or successor within the spill clique
3093 void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);
3095 // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
3096 // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
3097 // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
3098 void impRetypeEntryStateTemps(BasicBlock* blk);
3100 BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3101 void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
3103 void impPushVar(GenTree* op, typeInfo tiRetVal);
3104 void impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal);
3105 void impLoadVar(unsigned lclNum, IL_OFFSET offset)
3107 impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
3109 void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
3110 void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
3111 bool impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode);
3114 void impMarkLclDstNotPromotable(unsigned tmpNum, GenTreePtr op, CORINFO_CLASS_HANDLE hClass);
3117 // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3118 struct BlockListNode
3121 BlockListNode* m_next;
3122 BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3125 void* operator new(size_t sz, Compiler* comp);
3127 BlockListNode* impBlockListNodeFreeList;
3129 BlockListNode* AllocBlockListNode();
3130 void FreeBlockListNode(BlockListNode* node);
3132 bool impIsValueType(typeInfo* pTypeInfo);
3133 var_types mangleVarArgsType(var_types type);
3136 regNumber getCallArgIntRegister(regNumber floatReg);
3137 regNumber getCallArgFloatRegister(regNumber intReg);
3138 #endif // FEATURE_VARARG
3141 static unsigned jitTotalMethodCompiled;
3145 static LONG jitNestingLevel;
3148 bool seenConditionalJump;
3150 static BOOL impIsAddressInLocal(GenTreePtr tree, GenTreePtr* lclVarTreeOut);
3152 void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3154 // STATIC inlining decision based on the IL code.
3155 void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3156 CORINFO_METHOD_INFO* methInfo,
3158 InlineResult* inlineResult);
3160 void impCheckCanInline(GenTreePtr call,
3161 CORINFO_METHOD_HANDLE fncHandle,
3163 CORINFO_CONTEXT_HANDLE exactContextHnd,
3164 InlineCandidateInfo** ppInlineCandidateInfo,
3165 InlineResult* inlineResult);
3167 void impInlineRecordArgInfo(InlineInfo* pInlineInfo,
3168 GenTreePtr curArgVal,
3170 InlineResult* inlineResult);
3172 void impInlineInitVars(InlineInfo* pInlineInfo);
3174 unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3176 GenTreePtr impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3178 BOOL impInlineIsThis(GenTreePtr tree, InlArgInfo* inlArgInfo);
3180 BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTreePtr additionalTreesToBeEvaluatedBefore,
3181 GenTreePtr variableBeingDereferenced,
3182 InlArgInfo* inlArgInfo);
3184 void impMarkInlineCandidate(GenTreePtr call, CORINFO_CONTEXT_HANDLE exactContextHnd, CORINFO_CALL_INFO* callInfo);
3186 bool impTailCallRetTypeCompatible(var_types callerRetType,
3187 CORINFO_CLASS_HANDLE callerRetTypeClass,
3188 var_types calleeRetType,
3189 CORINFO_CLASS_HANDLE calleeRetTypeClass);
3191 bool impIsTailCallILPattern(bool tailPrefixed,
3193 const BYTE* codeAddrOfNextOpcode,
3194 const BYTE* codeEnd,
3196 bool* IsCallPopRet = nullptr);
3198 bool impIsImplicitTailCallCandidate(
3199 OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3202 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3203 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3207 XX Info about the basic-blocks, their contents and the flow analysis XX
3209 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3210 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3214 BasicBlock* fgFirstBB; // Beginning of the basic block list
3215 BasicBlock* fgLastBB; // End of the basic block list
3216 BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
3217 #if FEATURE_EH_FUNCLETS
3218 BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
3220 BasicBlock* fgFirstBBScratch; // Block inserted for initialization stuff. Is nullptr if no such block has been
3222 BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
3223 unsigned fgEdgeCount; // # of control flow edges between the BBs
3224 unsigned fgBBcount; // # of BBs in the method
3226 unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
3228 unsigned fgBBNumMax; // The max bbNum that has been assigned to basic blocks
3229 unsigned fgDomBBcount; // # of BBs for which we have dominator and reachability information
3230 BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
3231 // dominance. Indexed by block number. Size: fgBBNumMax + 1.
3233 // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
3234 // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
3235 // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
3236 // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
3237 // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
3238 // index). The arrays are of size fgBBNumMax + 1.
3239 unsigned* fgDomTreePreOrder;
3240 unsigned* fgDomTreePostOrder;
3242 bool fgBBVarSetsInited;
3244 // Allocate array like T* a = new T[fgBBNumMax + 1];
3245 // Using helper so we don't keep forgetting +1.
3246 template <typename T>
3247 T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
3249 return (T*)compGetMem((fgBBNumMax + 1) * sizeof(T), cmk);
3252 // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
3253 // (if the blocks are renumbered), this changes. BlockSets from different epochs
3254 // cannot be meaningfully combined. Note that new blocks can be created with higher
3255 // block numbers without changing the basic block epoch. These blocks *cannot*
3256 // participate in a block set until the blocks are all renumbered, causing the epoch
3257 // to change. This is useful if continuing to use previous block sets is valuable.
3258 // If the epoch is zero, then it is uninitialized, and block sets can't be used.
3259 unsigned fgCurBBEpoch;
3261 unsigned GetCurBasicBlockEpoch()
3263 return fgCurBBEpoch;
3266 // The number of basic blocks in the current epoch. When the blocks are renumbered,
3267 // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
3268 // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
3269 unsigned fgCurBBEpochSize;
3271 // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
3272 // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
3273 unsigned fgBBSetCountInSizeTUnits;
3275 void NewBasicBlockEpoch()
3277 INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
3279 // We have a new epoch. Compute and cache the size needed for new BlockSets.
3281 fgCurBBEpochSize = fgBBNumMax + 1;
3282 fgBBSetCountInSizeTUnits =
3283 unsigned(roundUp(fgCurBBEpochSize, sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
3286 // All BlockSet objects are now invalid!
3287 fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
3288 fgEnterBlksSetValid = false; // the fgEnterBlks set is now invalid!
3292 unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this, sizeof(size_t));
3293 printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
3294 fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
3295 if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
3297 // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
3298 // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
3299 // array of size_t bitsets), then print that out.
3300 printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
3307 void EnsureBasicBlockEpoch()
3309 if (fgCurBBEpochSize != fgBBNumMax + 1)
3311 NewBasicBlockEpoch();
3315 BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
3316 void fgEnsureFirstBBisScratch();
3317 bool fgFirstBBisScratch();
3318 bool fgBBisScratch(BasicBlock* block);
3320 void fgExtendEHRegionBefore(BasicBlock* block);
3321 void fgExtendEHRegionAfter(BasicBlock* block);
3323 BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3325 BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3327 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3330 BasicBlock* nearBlk,
3331 bool putInFilter = false,
3332 bool runRarely = false,
3333 bool insertAtEnd = false);
3335 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3337 bool runRarely = false,
3338 bool insertAtEnd = false);
3340 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
3342 BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
3343 BasicBlock* afterBlk,
3344 unsigned xcptnIndex,
3345 bool putInTryRegion);
3347 void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
3348 void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
3349 void fgUnlinkBlock(BasicBlock* block);
3351 #if OPT_BOOL_OPS // Used to detect multiple logical "not" assignments.
3352 bool fgMultipleNots;
3355 bool fgModified; // True if the flow graph has been modified recently
3356 bool fgComputePredsDone; // Have we computed the bbPreds list
3357 bool fgCheapPredsValid; // Is the bbCheapPreds list valid?
3358 bool fgDomsComputed; // Have we computed the dominator sets?
3360 bool fgHasSwitch; // any BBJ_SWITCH jumps?
3361 bool fgHasPostfix; // any postfix ++/-- found?
3362 unsigned fgIncrCount; // number of increment nodes found
3364 BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
3368 bool fgReachabilitySetsValid; // Are the bbReach sets valid?
3369 bool fgEnterBlksSetValid; // Is the fgEnterBlks set valid?
3372 bool fgRemoveRestOfBlock; // true if we know that we will throw
3373 bool fgStmtRemoved; // true if we remove statements -> need new DFA
3375 // There are two modes for ordering of the trees.
3376 // - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
3377 // each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
3378 // by traversing the tree according to the order of the operands.
3379 // - In FGOrderLinear, the dominant ordering is the linear order.
3386 FlowGraphOrder fgOrder;
3388 // The following are boolean flags that keep track of the state of internal data structures
3390 bool fgStmtListThreaded;
3391 bool fgCanRelocateEHRegions; // true if we are allowed to relocate the EH regions
3392 bool fgEdgeWeightsComputed; // true after we have called fgComputeEdgeWeights
3393 bool fgHaveValidEdgeWeights; // true if we were successful in computing all of the edge weights
3394 bool fgSlopUsedInEdgeWeights; // true if their was some slop used when computing the edge weights
3395 bool fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
3396 bool fgNeedsUpdateFlowGraph; // true if we need to run fgUpdateFlowGraph
3397 BasicBlock::weight_t fgCalledWeight; // count of the number of times this method was called
3398 // This is derived from the profile data
3399 // or is BB_UNITY_WEIGHT when we don't have profile data
3401 #if FEATURE_EH_FUNCLETS
3402 bool fgFuncletsCreated; // true if the funclet creation phase has been run
3403 #endif // FEATURE_EH_FUNCLETS
3405 bool fgGlobalMorph; // indicates if we are during the global morphing phase
3406 // since fgMorphTree can be called from several places
3407 bool fgExpandInline; // indicates that we are creating tree for the inliner
3409 bool impBoxTempInUse; // the temp below is valid and available
3410 unsigned impBoxTemp; // a temporary that is used for boxing
3413 bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
3414 // and we are trying to compile again in a "safer", minopts mode?
3418 unsigned impInlinedCodeSize;
3421 //-------------------------------------------------------------------------
3429 GenTreePtr fgGetCritSectOfStaticMethod();
3431 #if !defined(_TARGET_X86_)
3433 void fgAddSyncMethodEnterExit();
3435 GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
3437 void fgConvertSyncReturnToLeave(BasicBlock* block);
3439 #endif // !_TARGET_X86_
3441 void fgAddReversePInvokeEnterExit();
3443 bool fgMoreThanOneReturnBlock();
3445 // The number of separate return points in the method.
3446 unsigned fgReturnCount;
3448 void fgAddInternal();
3450 bool fgFoldConditional(BasicBlock* block);
3452 void fgMorphStmts(BasicBlock* block, bool* mult, bool* lnot, bool* loadw);
3453 void fgMorphBlocks();
3455 bool fgMorphBlockStmt(BasicBlock* block, GenTreePtr stmt DEBUGARG(const char* msg));
3457 void fgSetOptions();
3460 static fgWalkPreFn fgAssertNoQmark;
3461 void fgPreExpandQmarkChecks(GenTreePtr expr);
3462 void fgPostExpandQmarkChecks();
3463 static void fgCheckQmarkAllowedForm(GenTreePtr tree);
3466 IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
3468 BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
3469 BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
3470 BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, GenTree* stmt);
3471 BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
3472 BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);
3474 GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, BasicBlock* block, IL_OFFSETX offs);
3475 GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree);
3476 GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, BasicBlock* block);
3477 GenTreeStmt* fgNewStmtFromTree(GenTreePtr tree, IL_OFFSETX offs);
3479 GenTreePtr fgGetTopLevelQmark(GenTreePtr expr, GenTreePtr* ppDst = nullptr);
3480 void fgExpandQmarkForCastInstOf(BasicBlock* block, GenTreePtr stmt);
3481 void fgExpandQmarkStmt(BasicBlock* block, GenTreePtr expr);
3482 void fgExpandQmarkNodes();
3486 // Do "simple lowering." This functionality is (conceptually) part of "general"
3487 // lowering that is distributed between fgMorph and the lowering phase of LSRA.
3488 void fgSimpleLowering();
3490 bool fgShouldCreateAssignOp(GenTreePtr tree, bool* bReverse);
3492 GenTreePtr fgInitThisClass();
3494 GenTreePtr fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
3496 GenTreePtr fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
3498 void fgLocalVarLiveness();
3500 void fgLocalVarLivenessInit();
3502 #ifdef LEGACY_BACKEND
3503 GenTreePtr fgLegacyPerStatementLocalVarLiveness(GenTreePtr startNode, GenTreePtr relopNode, GenTreePtr asgdLclVar);
3505 void fgPerNodeLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3506 void fgPerStatementLocalVarLiveness(GenTree* node, GenTree* asgdLclVar);
3508 void fgPerBlockLocalVarLiveness();
3510 VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
3512 void fgLiveVarAnalysis(bool updateInternalOnly = false);
3514 // This is used in the liveness computation, as a temporary. When we use the
3515 // arbitrary-length VarSet representation, it is better not to allocate a new one
3517 VARSET_TP fgMarkIntfUnionVS;
3519 bool fgMarkIntf(VARSET_VALARG_TP varSet);
3521 bool fgMarkIntf(VARSET_VALARG_TP varSet1, VARSET_VALARG_TP varSet2);
3523 void fgUpdateRefCntForClone(BasicBlock* addedToBlock, GenTreePtr clonedTree);
3525 void fgUpdateRefCntForExtract(GenTreePtr wholeTree, GenTreePtr keptTree);
3527 void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
3529 bool fgComputeLifeLocal(VARSET_TP& life, VARSET_TP& keepAliveVars, GenTree* lclVarNode, GenTree* node);
3531 VARSET_VALRET_TP fgComputeLife(VARSET_VALARG_TP life,
3532 GenTreePtr startNode,
3534 VARSET_VALARG_TP volatileVars,
3535 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3537 VARSET_VALRET_TP fgComputeLifeLIR(VARSET_VALARG_TP life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
3539 bool fgRemoveDeadStore(GenTree** pTree,
3543 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3545 bool fgTryRemoveDeadLIRStore(LIR::Range& blockRange, GenTree* node, GenTree** next);
3547 // For updating liveset during traversal AFTER fgComputeLife has completed
3548 VARSET_VALRET_TP fgGetVarBits(GenTreePtr tree);
3549 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTreePtr tree);
3551 // Returns the set of live variables after endTree,
3552 // assuming that liveSet is the set of live variables BEFORE tree.
3553 // Requires that fgComputeLife has completed, and that tree is in the same
3554 // statement as endTree, and that it comes before endTree in execution order
3556 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTreePtr tree, GenTreePtr endTree)
3558 VARSET_TP VARSET_INIT(this, newLiveSet, liveSet);
3559 while (tree != nullptr && tree != endTree->gtNext)
3561 VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
3562 tree = tree->gtNext;
3564 assert(tree == endTree->gtNext);
3568 void fgInterBlockLocalVarLiveness();
3570 // The presence of "x op= y" operations presents some difficulties for SSA: this is both a use of some SSA name of
3571 // "x", and a def of a new SSA name for "x". The tree only has one local variable for "x", so it has to choose
3572 // whether to treat that as the use or def. It chooses the "use", and thus the old SSA name. This map allows us
3573 // to record/recover the "def" SSA number, given the lcl var node for "x" in such a tree.
3574 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, unsigned, JitSimplerHashBehavior> NodeToUnsignedMap;
3575 NodeToUnsignedMap* m_opAsgnVarDefSsaNums;
3576 NodeToUnsignedMap* GetOpAsgnVarDefSsaNums()
3578 if (m_opAsgnVarDefSsaNums == nullptr)
3580 m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
3582 return m_opAsgnVarDefSsaNums;
3585 // Requires value numbering phase to have completed. Returns the value number ("gtVN") of the
3586 // "tree," EXCEPT in the case of GTF_VAR_USEASG, because the tree node's gtVN member is the
3587 // "use" VN. Performs a lookup into the map of (use asg tree -> def VN.) to return the "def's"
3589 inline ValueNum GetUseAsgDefVNOrTreeVN(GenTreePtr tree);
3591 // Requires that "lcl" has the GTF_VAR_DEF flag set. Returns the SSA number of "lcl".
3592 // Except: assumes that lcl is a def, and if it is
3593 // a def appearing in "lcl op= rhs" (GTF_VAR_USEASG), looks up and returns the SSA number for the "def",
3594 // rather than the "use" SSA number recorded in the tree "lcl".
3595 inline unsigned GetSsaNumForLocalVarDef(GenTreePtr lcl);
3597 // Some assignments assign to a local "indirectly": they are part of a comma expression that takes the address
3598 // of the local (or a field thereof), assigns this address to a temp, and uses an indirection of this temp as
3599 // the LHS of the assignment. This actually arises in exactly one situation. At the source level we assign one
3600 // struct local to another: "s1 = s2". This becomes a copyblk. If "s2" is promoted into field variables "s2f0",
3601 // ..."s2fn", then the copyblk will morph to a comma expression that takes the address of "s1" and does field-wise
3603 // (byref addrS1 = &s1,
3604 // *(addrS1 * offsetof(f0)) = s2f0,
3606 // *(addrS1 * offsetof(fn)) = s2fn)
3608 // It would be a shame, given the simple form at the source level, to be unable to track the values in the
3609 // fields of "s1" after this. But "s1" does not appear in the assignments that modify it. How, then, to
3610 // give it SSA names and value numbers?
3612 // The solution is to use the side table described below to annotate each of the field-wise assignments at the
3613 // end with an instance of the structure below, whose fields are described in the declaration.
3614 struct IndirectAssignmentAnnotation
3616 unsigned m_lclNum; // The local num that is being indirectly assigned.
3617 FieldSeqNode* m_fieldSeq; // If the LHS of the struct assignment is itself a struct field dereference,
3618 // as in "s0.g = s2", then "m_lclNum" would be "s0", and "m_fieldSeq" would
3619 // be the singleton field sequence "g". The individual assignments would
3620 // further append the fields of "s.g" to that.
3621 bool m_isEntire; // True iff this assignment writes all of m_lclNum. (This can occur if the
3622 // structure has a single field).
3623 unsigned m_defSsaNum; // The new SSA number of "m_lclNum" after the assignment.
3624 unsigned m_useSsaNum; // Only valid if "m_isEntire" is false; if so, the SSA number of "m_lclNum" before the
3627 IndirectAssignmentAnnotation(unsigned lclNum,
3628 FieldSeqNode* fldSeq,
3630 unsigned defSsaNum = SsaConfig::RESERVED_SSA_NUM,
3631 unsigned useSsaNum = SsaConfig::RESERVED_SSA_NUM)
3632 : m_lclNum(lclNum), m_fieldSeq(fldSeq), m_isEntire(isEntire), m_defSsaNum(defSsaNum), m_useSsaNum(useSsaNum)
3636 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, IndirectAssignmentAnnotation*, JitSimplerHashBehavior>
3637 NodeToIndirAssignMap;
3638 NodeToIndirAssignMap* m_indirAssignMap;
3639 NodeToIndirAssignMap* GetIndirAssignMap()
3641 if (m_indirAssignMap == nullptr)
3643 // Create a CompAllocator that labels sub-structure with CMK_IndirAssignMap, and use that for allocation.
3644 IAllocator* ialloc = new (this, CMK_IndirAssignMap) CompAllocator(this, CMK_IndirAssignMap);
3645 m_indirAssignMap = new (ialloc) NodeToIndirAssignMap(ialloc);
3647 return m_indirAssignMap;
3650 // Performs SSA conversion.
3653 // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
3654 void fgResetForSsa();
3656 unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
3658 // Returns "true" iff lcl "lclNum" should be excluded from SSA.
3659 inline bool fgExcludeFromSsa(unsigned lclNum);
3661 // The value numbers for this compilation.
3662 ValueNumStore* vnStore;
3665 ValueNumStore* GetValueNumStore()
3670 // Do value numbering (assign a value number to each
3672 void fgValueNumber();
3674 // Updates "fgCurHeap" via the assignment H[elemTypeEq][arrVN][inx][fldSeq] = rhsVN.
3675 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
3676 // The 'indType' is the indirection type of the lhs of the assignment and will typically
3677 // match the element type of the array or fldSeq. When this type doesn't match
3678 // or if the fldSeq is 'NotAField' we invalidate the array contents H[elemTypeEq][arrVN]
3680 void fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
3683 FieldSeqNode* fldSeq,
3687 // Requires that "tree" is a GT_IND marked as an array index, and that its address argument
3688 // has been parsed to yield the other input arguments. If evaluation of the address
3689 // can raise exceptions, those should be captured in the exception set "excVN."
3690 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
3691 // Marks "tree" with the VN for H[elemTypeEq][arrVN][inx][fldSeq] (for the liberal VN; a new unique
3692 // VN for the conservative VN.) Also marks the tree's argument as the address of an array element.
3693 // The type tree->TypeGet() will typically match the element type of the array or fldSeq.
3694 // When this type doesn't match or if the fldSeq is 'NotAField' we return a new unique VN
3696 ValueNum fgValueNumberArrIndexVal(GenTreePtr tree,
3697 CORINFO_CLASS_HANDLE elemTypeEq,
3701 FieldSeqNode* fldSeq);
3703 // Requires "funcApp" to be a VNF_PtrToArrElem, and "addrXvn" to represent the exception set thrown
3704 // by evaluating the array index expression "tree". Returns the value number resulting from
3705 // dereferencing the array in the current heap state. If "tree" is non-null, it must be the
3706 // "GT_IND" that does the dereference, and it is given the returned value number.
3707 ValueNum fgValueNumberArrIndexVal(GenTreePtr tree, struct VNFuncApp* funcApp, ValueNum addrXvn);
3709 unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
3711 // Utility functions for fgValueNumber.
3713 // Perform value-numbering for the trees in "blk". When giving VN's to the SSA
3714 // names defined by phi definitions at the start of "blk", "newVNsForPhis" indicates
3715 // that these should be given new VN's, irrespective of the values of the LHS.
3716 // If "false", then we may assume that all inputs to phi RHS's of such definitions
3717 // have already been assigned value numbers; if they are all assigned the *same* value
3718 // number, then the LHS SSA name gets the same VN.
3719 void fgValueNumberBlock(BasicBlock* blk, bool newVNsForPhis);
3721 // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
3722 // innermost loop of which "entryBlock" is the entry. Returns the value number that should be
3723 // assumed for the heap at the start "entryBlk".
3724 ValueNum fgHeapVNForLoopSideEffects(BasicBlock* entryBlock, unsigned loopNum);
3726 // Called when an operation (performed by "tree", described by "msg") may cause the global Heap to be mutated.
3727 void fgMutateHeap(GenTreePtr tree DEBUGARG(const char* msg));
3729 // Tree caused an update in the current heap VN. If "tree" has an associated heap SSA #, record that
3730 // value in that SSA #.
3731 void fgValueNumberRecordHeapSsa(GenTreePtr tree);
3733 // The input 'tree' is a leaf node that is a constant
3734 // Assign the proper value number to the tree
3735 void fgValueNumberTreeConst(GenTreePtr tree);
3737 // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
3738 // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
3740 // If "evalAsgLhsInd" is true, evaluate a GT_IND node, even if it's labeled as the LHS of
3742 void fgValueNumberTree(GenTreePtr tree, bool evalAsgLhsInd = false);
3744 // Does value-numbering for a block assignment.
3745 void fgValueNumberBlockAssignment(GenTreePtr tree, bool evalAsgLhsInd);
3747 // Does value-numbering for a cast tree.
3748 void fgValueNumberCastTree(GenTreePtr tree);
3750 // Does value-numbering for an intrinsic tree.
3751 void fgValueNumberIntrinsic(GenTreePtr tree);
3753 // Does value-numbering for a call. We interpret some helper calls.
3754 void fgValueNumberCall(GenTreeCall* call);
3756 // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
3757 void fgUpdateArgListVNs(GenTreeArgList* args);
3759 // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
3760 void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
3762 // Requires "helpCall" to be a helper call. Assigns it a value number;
3763 // we understand the semantics of some of the calls. Returns "true" if
3764 // the call may modify the heap (we assume arbitrary memory side effects if so).
3765 bool fgValueNumberHelperCall(GenTreeCall* helpCall);
3767 // Requires "helpFunc" to be pure. Returns the corresponding VNFunc.
3768 VNFunc fgValueNumberHelperMethVNFunc(CorInfoHelpFunc helpFunc);
3770 // This is the current value number for the "Heap" implicit variable while
3771 // doing value numbering. This is the value number under the "liberal" interpretation
3772 // of heap values; the "conservative" interpretation needs no VN, since every access of
3773 // the heap yields an unknown value.
3774 ValueNum fgCurHeapVN;
3776 // Return a "pseudo"-class handle for an array element type. If "elemType" is TYP_STRUCT,
3777 // requires "elemStructType" to be non-null (and to have a low-order zero). Otherwise, low order bit
3778 // is 1, and the rest is an encoding of "elemTyp".
3779 static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
3781 if (elemStructType != nullptr)
3783 assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
3784 varTypeIsIntegral(elemTyp));
3785 assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
3786 return elemStructType;
3790 elemTyp = varTypeUnsignedToSigned(elemTyp);
3791 return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
3794 // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
3795 // var_types it represents. Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
3796 // the struct type of the element).
3797 static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
3799 size_t clsHndVal = size_t(clsHnd);
3800 if (clsHndVal & 0x1)
3802 return var_types(clsHndVal >> 1);
3810 // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
3811 var_types getJitGCType(BYTE gcType);
3813 enum structPassingKind
3815 SPK_Unknown, // Invalid value, never returned
3816 SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
3817 SPK_ByValue, // The struct is passed/returned by value (using the ABI rules)
3818 // for ARM64 and UNIX_X64 in multiple registers. (when all of the
3819 // parameters registers are used, then the stack will be used)
3820 // for X86 passed on the stack, for ARM32 passed in registers
3821 // or the stack or split between registers and the stack.
3822 SPK_ByValueAsHfa, // The struct is passed/returned as an HFA in multiple registers.
3824 }; // The struct is passed/returned by reference to a copy/buffer.
3826 // Get the "primitive" type that is is used when we are given a struct of size 'structSize'.
3827 // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
3828 // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
3829 // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
3831 var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd);
3833 // Get the type that is used to pass values of the given struct type.
3834 // If you have already retrieved the struct size then pass it as the optional third argument
3836 var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3837 structPassingKind* wbPassStruct,
3838 unsigned structSize = 0);
3840 // Get the type that is used to return values of the given struct type.
3841 // If you have already retrieved the struct size then pass it as the optional third argument
3843 var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
3844 structPassingKind* wbPassStruct = nullptr,
3845 unsigned structSize = 0);
3848 // Print a representation of "vnp" or "vn" on standard output.
3849 // If "level" is non-zero, we also print out a partial expansion of the value.
3850 void vnpPrint(ValueNumPair vnp, unsigned level);
3851 void vnPrint(ValueNum vn, unsigned level);
3854 // Dominator computation member functions
3855 // Not exposed outside Compiler
3857 bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
3859 bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
3861 void fgComputeDoms(); // Computes the immediate dominators for each basic block in the
3862 // flow graph. We first assume the fields bbIDom on each
3863 // basic block are invalid. This computation is needed later
3864 // by fgBuildDomTree to build the dominance tree structure.
3865 // Based on: A Simple, Fast Dominance Algorithm
3866 // by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
3868 BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
3869 // Note: this is relatively slow compared to calling fgDominate(),
3870 // especially if dealing with a single block versus block check.
3872 void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
3874 void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
3876 bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
3878 void fgComputeReachability(); // Perform flow graph node reachability analysis.
3880 BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
3882 void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
3883 // processed in topological sort, this function takes care of that.
3885 void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
3887 BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
3888 // Returns this as a set.
3890 BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
3891 // root nodes. Returns this as a set.
3894 void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
3897 void fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
3898 // (performed by fgComputeDoms), this procedure builds the dominance tree represented
3901 // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
3902 // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
3903 // && postOrder(A) >= postOrder(B) making the computation O(1).
3904 void fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum);
3906 // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
3908 void fgUpdateChangedFlowGraph();
3911 // Compute the predecessors of the blocks in the control flow graph.
3912 void fgComputePreds();
3914 // Remove all predecessor information.
3915 void fgRemovePreds();
3917 // Compute the cheap flow graph predecessors lists. This is used in some early phases
3918 // before the full predecessors lists are computed.
3919 void fgComputeCheapPreds();
3922 void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
3924 void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
3934 // Initialize the per-block variable sets (used for liveness analysis).
3935 void fgInitBlockVarSets();
3937 // true if we've gone through and created GC Poll calls.
3938 bool fgGCPollsCreated;
3939 void fgMarkGCPollBlocks();
3940 void fgCreateGCPolls();
3941 bool fgCreateGCPoll(GCPollType pollType, BasicBlock* block);
3943 // Requires that "block" is a block that returns from
3944 // a finally. Returns the number of successors (jump targets of
3945 // of blocks in the covered "try" that did a "LEAVE".)
3946 unsigned fgNSuccsOfFinallyRet(BasicBlock* block);
3948 // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
3949 // a finally. Returns its "i"th successor (jump targets of
3950 // of blocks in the covered "try" that did a "LEAVE".)
3951 // Requires that "i" < fgNSuccsOfFinallyRet(block).
3952 BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);
3955 // Factor out common portions of the impls of the methods above.
3956 void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
3959 // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
3960 // skipping duplicate targets. (E.g., in flow analyses that are only interested in the set of possible targets.)
3961 // SwitchUniqueSuccSet contains the non-duplicated switch targets.
3962 // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
3963 // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
3964 // been computed for the switch block. If a switch block is deleted or is transformed into a non-switch,
3965 // we leave the entry associated with the block, but it will no longer be accessed.)
3966 struct SwitchUniqueSuccSet
3968 unsigned numDistinctSuccs; // Number of distinct targets of the switch.
3969 BasicBlock** nonDuplicates; // Array of "numDistinctSuccs", containing all the distinct switch target
3972 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
3973 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
3974 // remove it from "this", and ensure that "to" is a member. Use "alloc" to do any required allocation.
3975 void UpdateTarget(IAllocator* alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
3978 typedef SimplerHashTable<BasicBlock*, PtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet, JitSimplerHashBehavior>
3979 BlockToSwitchDescMap;
3982 // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
3983 // iteration over only the distinct successors.
3984 BlockToSwitchDescMap* m_switchDescMap;
3987 BlockToSwitchDescMap* GetSwitchDescMap()
3989 if (m_switchDescMap == nullptr)
3991 m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
3993 return m_switchDescMap;
3996 // Invalidate the map of unique switch block successors. For example, since the hash key of the map
3997 // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
3998 // we don't accidentally look up and return the wrong switch data.
3999 void InvalidateUniqueSwitchSuccMap()
4001 m_switchDescMap = nullptr;
4004 // Requires "switchBlock" to be a block that ends in a switch. Returns
4005 // the corresponding SwitchUniqueSuccSet.
4006 SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
4008 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4009 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4010 // remove it from "this", and ensure that "to" is a member.
4011 void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4013 // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4014 void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4016 BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4018 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4020 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4022 flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4024 flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4026 flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4028 flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4030 void fgRemoveBlockAsPred(BasicBlock* block);
4032 void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4034 void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4036 void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4038 void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
4040 flowList* fgAddRefPred(BasicBlock* block,
4041 BasicBlock* blockPred,
4042 flowList* oldEdge = nullptr,
4043 bool initializingPreds = false); // Only set to 'true' when we are computing preds in
4046 void fgFindBasicBlocks();
4048 bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4050 bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4052 BasicBlock* fgFindInsertPoint(unsigned regionIndex,
4053 bool putInTryRegion,
4054 BasicBlock* startBlk,
4056 BasicBlock* nearBlk,
4057 BasicBlock* jumpBlk,
4060 unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4062 void fgRemoveEmptyBlocks();
4064 void fgRemoveStmt(BasicBlock* block, GenTreePtr stmt, bool updateRefCnt = true);
4066 bool fgCheckRemoveStmt(BasicBlock* block, GenTreePtr stmt);
4068 void fgCreateLoopPreHeader(unsigned lnum);
4070 void fgUnreachableBlock(BasicBlock* block);
4072 void fgRemoveJTrue(BasicBlock* block);
4074 BasicBlock* fgLastBBInMainFunction();
4076 BasicBlock* fgEndBBAfterMainFunction();
4078 void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4080 void fgRemoveBlock(BasicBlock* block, bool unreachable);
4082 bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4084 void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4086 void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4088 BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4090 bool fgRenumberBlocks();
4092 bool fgExpandRarelyRunBlocks();
4094 bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4096 void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4098 enum FG_RELOCATE_TYPE
4100 FG_RELOCATE_TRY, // relocate the 'try' region
4101 FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4103 BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
4105 #if FEATURE_EH_FUNCLETS
4106 #if defined(_TARGET_ARM_)
4107 void fgClearFinallyTargetBit(BasicBlock* block);
4108 #endif // defined(_TARGET_ARM_)
4109 bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
4110 bool fgAnyIntraHandlerPreds(BasicBlock* block);
4111 void fgInsertFuncletPrologBlock(BasicBlock* block);
4112 void fgCreateFuncletPrologBlocks();
4113 void fgCreateFunclets();
4114 #else // !FEATURE_EH_FUNCLETS
4115 bool fgRelocateEHRegions();
4116 #endif // !FEATURE_EH_FUNCLETS
4118 bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4120 bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4122 bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4124 bool fgOptimizeFallthroughTailDup(BasicBlock* block, BasicBlock* target);
4126 bool fgOptimizeEmptyBlock(BasicBlock* block);
4128 bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4130 bool fgOptimizeBranch(BasicBlock* bJump);
4132 bool fgOptimizeSwitchBranches(BasicBlock* block);
4134 bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4136 bool fgOptimizeSwitchJumps();
4138 void fgPrintEdgeWeights();
4140 void fgComputeEdgeWeights();
4142 void fgReorderBlocks();
4144 void fgDetermineFirstColdBlock();
4146 bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4148 bool fgUpdateFlowGraph(bool doTailDup = false);
4150 void fgFindOperOrder();
4152 // method that returns if you should split here
4153 typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4155 void fgSetBlockOrder();
4157 void fgRemoveReturnBlock(BasicBlock* block);
4159 /* Helper code that has been factored out */
4160 inline void fgConvertBBToThrowBB(BasicBlock* block);
4162 bool fgCastNeeded(GenTreePtr tree, var_types toType);
4163 GenTreePtr fgDoNormalizeOnStore(GenTreePtr tree);
4164 GenTreePtr fgMakeTmpArgNode(
4165 unsigned tmpVarNum FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool passedInRegisters));
4167 // The following check for loops that don't execute calls
4168 bool fgLoopCallMarked;
4170 void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4171 void fgLoopCallMark();
4173 void fgMarkLoopHead(BasicBlock* block);
4175 unsigned fgGetCodeEstimate(BasicBlock* block);
4178 const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4179 FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4180 bool fgDumpFlowGraph(Phases phase);
4182 #endif // DUMP_FLOWGRAPHS
4187 void fgDispBBLiveness(BasicBlock* block);
4188 void fgDispBBLiveness();
4189 void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
4190 void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
4191 void fgDispBasicBlocks(bool dumpTrees = false);
4192 void fgDumpStmtTree(GenTreePtr stmt, unsigned blkNum);
4193 void fgDumpBlock(BasicBlock* block);
4194 void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);
4196 static fgWalkPreFn fgStress64RsltMulCB;
4197 void fgStress64RsltMul();
4198 void fgDebugCheckUpdate();
4199 void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
4200 void fgDebugCheckBlockLinks();
4201 void fgDebugCheckLinks(bool morphTrees = false);
4202 void fgDebugCheckNodeLinks(BasicBlock* block, GenTreePtr stmt);
4203 void fgDebugCheckFlags(GenTreePtr tree);
4206 #ifdef LEGACY_BACKEND
4207 static void fgOrderBlockOps(GenTreePtr tree,
4211 GenTreePtr* opsPtr, // OUT
4212 regMaskTP* regsPtr); // OUT
4213 #endif // LEGACY_BACKEND
4215 static GenTreePtr fgGetFirstNode(GenTreePtr tree);
4216 static bool fgTreeIsInStmt(GenTree* tree, GenTreeStmt* stmt);
4218 inline bool fgIsInlining()
4220 return fgExpandInline;
4223 void fgTraverseRPO();
4225 //--------------------- Walking the trees in the IR -----------------------
4230 fgWalkPreFn* wtprVisitorFn;
4231 fgWalkPostFn* wtpoVisitorFn;
4232 void* pCallbackData; // user-provided data
4233 bool wtprLclsOnly; // whether to only visit lclvar nodes
4234 GenTreePtr parent; // parent of current node, provided to callback
4235 GenTreeStack* parentStack; // stack of parent nodes, if asked for
4237 bool printModified; // callback can use this
4241 template <bool computeStack>
4242 static fgWalkResult fgWalkTreePreRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4244 // general purpose tree-walker that is capable of doing pre- and post- order
4245 // callbacks at the same time
4246 template <bool doPreOrder, bool doPostOrder>
4247 static fgWalkResult fgWalkTreeRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4249 fgWalkResult fgWalkTreePre(GenTreePtr* pTree,
4250 fgWalkPreFn* visitor,
4251 void* pCallBackData = nullptr,
4252 bool lclVarsOnly = false,
4253 bool computeStack = false);
4255 fgWalkResult fgWalkTree(GenTreePtr* pTree,
4256 fgWalkPreFn* preVisitor,
4257 fgWalkPostFn* postVisitor,
4258 void* pCallBackData = nullptr);
4260 void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4264 template <bool computeStack>
4265 static fgWalkResult fgWalkTreePostRec(GenTreePtr* pTree, fgWalkData* fgWalkPre);
4267 fgWalkResult fgWalkTreePost(GenTreePtr* pTree,
4268 fgWalkPostFn* visitor,
4269 void* pCallBackData = nullptr,
4270 bool computeStack = false);
4272 // An fgWalkPreFn that looks for expressions that have inline throws in
4273 // minopts mode. Basically it looks for tress with gtOverflowEx() or
4274 // GTF_IND_RNGCHK. It returns WALK_ABORT if one is found. It
4275 // returns WALK_SKIP_SUBTREES if GTF_EXCEPT is not set (assumes flags
4276 // properly propagated to parent trees). It returns WALK_CONTINUE
4278 static fgWalkResult fgChkThrowCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4279 static fgWalkResult fgChkLocAllocCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4280 static fgWalkResult fgChkQmarkCB(GenTreePtr* pTree, Compiler::fgWalkData* data);
4282 /**************************************************************************
4284 *************************************************************************/
4287 friend class SsaBuilder;
4288 friend struct ValueNumberState;
4290 //--------------------- Detect the basic blocks ---------------------------
4292 BasicBlock** fgBBs; // Table of pointers to the BBs
4294 void fgInitBBLookup();
4295 BasicBlock* fgLookupBB(unsigned addr);
4297 void fgMarkJumpTarget(BYTE* jumpTarget, IL_OFFSET offs);
4299 void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4301 void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
4303 void fgLinkBasicBlocks();
4305 void fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4307 void fgCheckBasicBlockControlFlow();
4309 void fgControlFlowPermitted(BasicBlock* blkSrc,
4310 BasicBlock* blkDest,
4311 BOOL IsLeave = false /* is the src a leave block */);
4313 bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
4315 void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
4317 void fgAdjustForAddressExposedOrWrittenThis();
4319 bool fgProfileData_ILSizeMismatch;
4320 ICorJitInfo::ProfileBuffer* fgProfileBuffer;
4321 ULONG fgProfileBufferCount;
4322 ULONG fgNumProfileRuns;
4324 unsigned fgStressBBProf()
4327 unsigned result = JitConfig.JitStressBBProf();
4330 if (compStressCompile(STRESS_BB_PROFILE, 15))
4341 bool fgHaveProfileData();
4342 bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
4344 bool fgIsUsingProfileWeights()
4346 return (fgHaveProfileData() || fgStressBBProf());
4348 void fgInstrumentMethod();
4350 //-------- Insert a statement at the start or end of a basic block --------
4354 static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
4358 GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTreePtr node);
4360 public: // Used by linear scan register allocation
4361 GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTreePtr node);
4364 GenTreePtr fgInsertStmtAtBeg(BasicBlock* block, GenTreePtr stmt);
4365 GenTreePtr fgInsertStmtAfter(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4367 public: // Used by linear scan register allocation
4368 GenTreePtr fgInsertStmtBefore(BasicBlock* block, GenTreePtr insertionPoint, GenTreePtr stmt);
4371 GenTreePtr fgInsertStmtListAfter(BasicBlock* block, GenTreePtr stmtAfter, GenTreePtr stmtList);
4373 GenTreePtr fgMorphSplitTree(GenTree** splitPoint, GenTree* stmt, BasicBlock* blk);
4375 // Create a new temporary variable to hold the result of *ppTree,
4376 // and transform the graph accordingly.
4377 GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
4378 GenTree* fgMakeMultiUse(GenTree** ppTree);
4380 // After replacing oldChild with newChild, fixup the fgArgTabEntryPtr
4381 // if it happens to be an argument to a call.
4382 void fgFixupIfCallArg(ArrayStack<GenTree*>* parentStack, GenTree* oldChild, GenTree* newChild);
4385 void fgFixupArgTabEntryPtr(GenTreePtr parentCall, GenTreePtr oldArg, GenTreePtr newArg);
4388 // Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
4389 GenTreePtr fgRecognizeAndMorphBitwiseRotation(GenTreePtr tree);
4390 bool fgOperIsBitwiseRotationRoot(genTreeOps oper);
4392 //-------- Determine the order in which the trees will be evaluated -------
4394 unsigned fgTreeSeqNum;
4395 GenTree* fgTreeSeqLst;
4396 GenTree* fgTreeSeqBeg;
4398 GenTree* fgSetTreeSeq(GenTree* tree, GenTree* prev = nullptr, bool isLIR = false);
4399 void fgSetTreeSeqHelper(GenTree* tree, bool isLIR);
4400 void fgSetTreeSeqFinish(GenTreePtr tree, bool isLIR);
4401 void fgSetStmtSeq(GenTree* tree);
4402 void fgSetBlockOrder(BasicBlock* block);
4404 //------------------------- Morphing --------------------------------------
4406 unsigned fgPtrArgCntCur;
4407 unsigned fgPtrArgCntMax;
4408 hashBv* fgOutgoingArgTemps;
4409 hashBv* fgCurrentlyInUseArgTemps;
4411 bool compCanEncodePtrArgCntMax();
4413 void fgSetRngChkTarget(GenTreePtr tree, bool delay = true);
4416 void fgMoveOpsLeft(GenTreePtr tree);
4419 bool fgIsCommaThrow(GenTreePtr tree, bool forFolding = false);
4421 bool fgIsThrow(GenTreePtr tree);
4423 bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
4424 bool fgIsBlockCold(BasicBlock* block);
4426 GenTreePtr fgMorphCastIntoHelper(GenTreePtr tree, int helper, GenTreePtr oper);
4428 GenTreePtr fgMorphIntoHelperCall(GenTreePtr tree, int helper, GenTreeArgList* args);
4430 GenTreePtr fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
4432 bool fgMorphRelopToQmark(GenTreePtr tree);
4434 // A "MorphAddrContext" carries information from the surrounding context. If we are evaluating a byref address,
4435 // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
4436 // be used, perhaps by passing it as an argument to a called method. This affects how null checking is done:
4437 // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
4438 // know will be dereferenced. To know that reliance on implicit null checking is sound, we must further know that
4439 // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
4440 // small; hence the other fields of MorphAddrContext. Finally, the odd structure of GT_COPYBLK, in which the second
4441 // argument is a GT_LIST, requires us to "tell" that List node that its parent is a GT_COPYBLK, so it "knows" that
4442 // each of its arguments should be evaluated in MACK_Ind contexts. (This would not be true for GT_LIST nodes
4443 // representing method call argument lists.)
4444 enum MorphAddrContextKind
4448 MACK_CopyBlock, // This is necessary so we know we have to start a new "Ind" context for each of the
4449 // addresses in the arg list.
4451 struct MorphAddrContext
4453 MorphAddrContextKind m_kind;
4454 bool m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind". True iff all offsets between
4455 // top-level indirection and here have been constants.
4456 size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
4457 // In that case, is the sum of those constant offsets.
4459 MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
4464 // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
4465 static MorphAddrContext s_CopyBlockMAC;
4468 GenTreePtr fgCopySIMDNode(GenTreeSIMD* simdNode);
4469 GenTreePtr getSIMDStructFromField(GenTreePtr tree,
4470 var_types* baseTypeOut,
4472 unsigned* simdSizeOut,
4473 bool ignoreUsedInSIMDIntrinsic = false);
4474 GenTreePtr fgMorphFieldAssignToSIMDIntrinsicSet(GenTreePtr tree);
4475 GenTreePtr fgMorphFieldToSIMDIntrinsicGet(GenTreePtr tree);
4476 bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTreePtr stmt);
4477 void impMarkContiguousSIMDFieldAssignments(GenTreePtr stmt);
4479 // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
4480 // in function: Complier::impMarkContiguousSIMDFieldAssignments.
4481 GenTreePtr fgPreviousCandidateSIMDFieldAsgStmt;
4483 #endif // FEATURE_SIMD
4484 GenTreePtr fgMorphArrayIndex(GenTreePtr tree);
4485 GenTreePtr fgMorphCast(GenTreePtr tree);
4486 GenTreePtr fgUnwrapProxy(GenTreePtr objRef);
4487 GenTreeCall* fgMorphArgs(GenTreeCall* call);
4489 void fgMakeOutgoingStructArgCopy(GenTreeCall* call,
4492 CORINFO_CLASS_HANDLE copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(
4493 const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structDescPtr));
4495 void fgFixupStructReturn(GenTreePtr call);
4496 GenTreePtr fgMorphLocalVar(GenTreePtr tree);
4497 bool fgAddrCouldBeNull(GenTreePtr addr);
4498 GenTreePtr fgMorphField(GenTreePtr tree, MorphAddrContext* mac);
4499 bool fgCanFastTailCall(GenTreeCall* call);
4500 void fgMorphTailCall(GenTreeCall* call);
4501 void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
4502 GenTreePtr fgAssignRecursiveCallArgToCallerParam(GenTreePtr arg,
4503 fgArgTabEntryPtr argTabEntry,
4505 IL_OFFSETX callILOffset,
4506 GenTreePtr tmpAssignmentInsertionPoint,
4507 GenTreePtr paramAssignmentInsertionPoint);
4508 static int fgEstimateCallStackSize(GenTreeCall* call);
4509 GenTreePtr fgMorphCall(GenTreeCall* call);
4510 void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
4511 void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result);
4513 void fgNoteNonInlineCandidate(GenTreePtr tree, GenTreeCall* call);
4514 static fgWalkPreFn fgFindNonInlineCandidate;
4516 GenTreePtr fgOptimizeDelegateConstructor(GenTreePtr call, CORINFO_CONTEXT_HANDLE* ExactContextHnd);
4517 GenTreePtr fgMorphLeaf(GenTreePtr tree);
4518 void fgAssignSetVarDef(GenTreePtr tree);
4519 GenTreePtr fgMorphOneAsgBlockOp(GenTreePtr tree);
4520 GenTreePtr fgMorphInitBlock(GenTreePtr tree);
4521 GenTreePtr fgMorphCopyBlock(GenTreePtr tree);
4522 GenTreePtr fgMorphForRegisterFP(GenTreePtr tree);
4523 GenTreePtr fgMorphSmpOp(GenTreePtr tree, MorphAddrContext* mac = nullptr);
4524 GenTreePtr fgMorphSmpOpPre(GenTreePtr tree);
4525 GenTreePtr fgMorphDivByConst(GenTreeOp* tree);
4526 GenTreePtr fgMorphModByConst(GenTreeOp* tree);
4527 GenTreePtr fgMorphModToSubMulDiv(GenTreeOp* tree);
4528 GenTreePtr fgMorphSmpOpOptional(GenTreeOp* tree);
4529 GenTreePtr fgMorphRecognizeBoxNullable(GenTree* compare);
4530 bool fgShouldUseMagicNumberDivide(GenTreeOp* tree);
4532 GenTreePtr fgMorphToEmulatedFP(GenTreePtr tree);
4533 GenTreePtr fgMorphConst(GenTreePtr tree);
4536 GenTreePtr fgMorphTree(GenTreePtr tree, MorphAddrContext* mac = nullptr);
4539 #if LOCAL_ASSERTION_PROP
4540 void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTreePtr tree));
4542 void fgMorphTreeDone(GenTreePtr tree, GenTreePtr oldTree = nullptr DEBUGARG(int morphNum = 0));
4544 GenTreePtr fgMorphStmt;
4546 unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
4547 // used when morphing big offset.
4549 //----------------------- Liveness analysis -------------------------------
4551 VARSET_TP fgCurUseSet; // vars used by block (before an assignment)
4552 VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
4554 bool fgCurHeapUse; // True iff the current basic block uses the heap before defining it.
4555 bool fgCurHeapDef; // True iff the current basic block defines the heap.
4556 bool fgCurHeapHavoc; // True if the current basic block is known to set the heap to a "havoc" value.
4558 void fgMarkUseDef(GenTreeLclVarCommon* tree, GenTree* asgdLclVar = nullptr);
4560 #ifdef DEBUGGING_SUPPORT
4561 void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4562 void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
4564 void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
4565 void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
4567 void fgExtendDbgScopes();
4568 void fgExtendDbgLifetimes();
4571 void fgDispDebugScopes();
4574 #endif // DEBUGGING_SUPPORT
4576 //-------------------------------------------------------------------------
4578 // The following keeps track of any code we've added for things like array
4579 // range checking or explicit calls to enable GC, and so on.
4584 AddCodeDsc* acdNext;
4585 BasicBlock* acdDstBlk; // block to which we jump
4587 SpecialCodeKind acdKind; // what kind of a special block is this?
4588 unsigned short acdStkLvl;
4592 static unsigned acdHelper(SpecialCodeKind codeKind);
4594 AddCodeDsc* fgAddCodeList;
4596 bool fgRngChkThrowAdded;
4597 AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
4599 BasicBlock* fgRngChkTarget(BasicBlock* block, unsigned stkDepth, SpecialCodeKind kind);
4601 BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind, unsigned stkDepth = 0);
4604 AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
4607 bool fgIsCodeAdded();
4609 bool fgIsThrowHlpBlk(BasicBlock* block);
4610 unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
4612 unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
4614 unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
4615 void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
4616 void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
4617 GenTreePtr fgInlinePrependStatements(InlineInfo* inlineInfo);
4619 #if FEATURE_MULTIREG_RET
4620 GenTreePtr fgGetStructAsStructPtr(GenTreePtr tree);
4621 GenTreePtr fgAssignStructInlineeToVar(GenTreePtr child, CORINFO_CLASS_HANDLE retClsHnd);
4622 void fgAttachStructInlineeToAsg(GenTreePtr tree, GenTreePtr child, CORINFO_CLASS_HANDLE retClsHnd);
4623 #endif // FEATURE_MULTIREG_RET
4625 static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
4628 static fgWalkPreFn fgDebugCheckInlineCandidates;
4631 void fgPromoteStructs();
4632 fgWalkResult fgMorphStructField(GenTreePtr tree, fgWalkData* fgWalkPre);
4633 fgWalkResult fgMorphLocalField(GenTreePtr tree, fgWalkData* fgWalkPre);
4634 void fgMarkImplicitByRefArgs();
4635 bool fgMorphImplicitByRefArgs(GenTree** pTree, fgWalkData* fgWalkPre);
4636 static fgWalkPreFn fgMarkAddrTakenLocalsPreCB;
4637 static fgWalkPostFn fgMarkAddrTakenLocalsPostCB;
4638 void fgMarkAddressExposedLocals();
4639 bool fgNodesMayInterfere(GenTree* store, GenTree* load);
4641 // Returns true if the type of tree is of size at least "width", or if "tree" is not a
4643 bool fgFitsInOrNotLoc(GenTreePtr tree, unsigned width);
4645 // The given local variable, required to be a struct variable, is being assigned via
4646 // a "lclField", to make it masquerade as an integral type in the ABI. Make sure that
4647 // the variable is not enregistered, and is therefore not promoted independently.
4648 void fgLclFldAssign(unsigned lclNum);
4650 static fgWalkPreFn gtHasLocalsWithAddrOpCB;
4651 bool gtCanOptimizeTypeEquality(GenTreePtr tree);
4652 bool gtIsTypeHandleToRuntimeTypeHelper(GenTreePtr tree);
4653 bool gtIsActiveCSE_Candidate(GenTreePtr tree);
4656 bool fgPrintInlinedMethods;
4659 bool fgIsBigOffset(size_t offset);
4661 // The following are used when morphing special cases of integer div/mod operations and also by codegen
4662 bool fgIsSignedDivOptimizable(GenTreePtr divisor);
4663 bool fgIsUnsignedDivOptimizable(GenTreePtr divisor);
4664 bool fgIsSignedModOptimizable(GenTreePtr divisor);
4665 bool fgIsUnsignedModOptimizable(GenTreePtr divisor);
4668 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4669 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4673 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4674 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
4681 LclVarDsc* optIsTrackedLocal(GenTreePtr tree);
4684 void optRemoveRangeCheck(
4685 GenTreePtr tree, GenTreePtr stmt, bool updateCSEcounts, unsigned sideEffFlags = 0, bool forceRemove = false);
4686 bool optIsRangeCheckRemovable(GenTreePtr tree);
4689 static fgWalkPreFn optValidRangeCheckIndex;
4690 static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
4693 void optRemoveTree(GenTreePtr deadTree, GenTreePtr keepList);
4695 /**************************************************************************
4697 *************************************************************************/
4700 // Do hoisting for all loops.
4701 void optHoistLoopCode();
4703 // To represent sets of VN's that have already been hoisted in outer loops.
4704 typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, bool, JitSimplerHashBehavior> VNToBoolMap;
4705 typedef VNToBoolMap VNSet;
4707 struct LoopHoistContext
4710 // The set of variables hoisted in the current loop (or nullptr if there are none).
4711 VNSet* m_pHoistedInCurLoop;
4714 // Value numbers of expressions that have been hoisted in parent loops in the loop nest.
4715 VNSet m_hoistedInParentLoops;
4716 // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
4717 // Previous decisions on loop-invariance of value numbers in the current loop.
4718 VNToBoolMap m_curLoopVnInvariantCache;
4720 VNSet* GetHoistedInCurLoop(Compiler* comp)
4722 if (m_pHoistedInCurLoop == nullptr)
4724 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
4726 return m_pHoistedInCurLoop;
4729 VNSet* ExtractHoistedInCurLoop()
4731 VNSet* res = m_pHoistedInCurLoop;
4732 m_pHoistedInCurLoop = nullptr;
4736 LoopHoistContext(Compiler* comp)
4737 : m_pHoistedInCurLoop(nullptr)
4738 , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
4739 , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
4744 // Do hoisting for loop "lnum" (an index into the optLoopTable), and all loops nested within it.
4745 // Tracks the expressions that have been hoisted by containing loops by temporary recording their
4746 // value numbers in "m_hoistedInParentLoops". This set is not modified by the call.
4747 void optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);
4749 // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
4750 // Assumes that expressions have been hoisted in containing loops if their value numbers are in
4751 // "m_hoistedInParentLoops".
4753 void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
4755 // Hoist all expressions in "blk" that are invariant in loop "lnum" (an index into the optLoopTable)
4756 // outside of that loop. Exempt expressions whose value number is in "m_hoistedInParentLoops"; add VN's of hoisted
4757 // expressions to "hoistInLoop".
4758 void optHoistLoopExprsForBlock(BasicBlock* blk, unsigned lnum, LoopHoistContext* hoistCtxt);
4760 // Return true if the tree looks profitable to hoist out of loop 'lnum'.
4761 bool optIsProfitableToHoistableTree(GenTreePtr tree, unsigned lnum);
4763 // Hoist all proper sub-expressions of "tree" (which occurs in "stmt", which occurs in "blk")
4764 // that are invariant in loop "lnum" (an index into the optLoopTable)
4765 // outside of that loop. Exempt expressions whose value number is in "hoistedInParents"; add VN's of hoisted
4766 // expressions to "hoistInLoop".
4767 // Returns "true" iff "tree" is loop-invariant (wrt "lnum").
4768 // Assumes that the value of "*firstBlockAndBeforeSideEffect" indicates that we're in the first block, and before
4769 // any possible globally visible side effects. Assume is called in evaluation order, and updates this.
4770 bool optHoistLoopExprsForTree(GenTreePtr tree,
4772 LoopHoistContext* hoistCtxt,
4773 bool* firstBlockAndBeforeSideEffect,
4776 // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
4777 void optHoistCandidate(GenTreePtr tree, unsigned lnum, LoopHoistContext* hoistCtxt);
4779 // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
4780 // Constants and init values are always loop invariant.
4781 // VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
4782 bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNToBoolMap* recordedVNs);
4784 // Returns "true" iff "tree" is valid at the head of loop "lnum", in the context of the hoist substitution
4785 // "subst". If "tree" is a local SSA var, it is valid if its SSA definition occurs outside of the loop, or
4786 // if it is in the domain of "subst" (meaning that it's definition has been previously hoisted, with a "standin"
4787 // local.) If tree is a constant, it is valid. Otherwise, if it is an operator, it is valid iff its children are.
4788 bool optTreeIsValidAtLoopHead(GenTreePtr tree, unsigned lnum);
4790 // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
4791 // in the loop table.
4792 bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);
4794 // Records the set of "side effects" of all loops: fields (object instance and static)
4795 // written to, and SZ-array element type equivalence classes updated.
4796 void optComputeLoopSideEffects();
4799 // Requires "lnum" to be the index of an outermost loop in the loop table. Traverses the body of that loop,
4800 // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
4801 // static) written to, and SZ-array element type equivalence classes updated.
4802 void optComputeLoopNestSideEffects(unsigned lnum);
4804 // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
4805 void optComputeLoopSideEffectsOfBlock(BasicBlock* blk);
4807 // Hoist the expression "expr" out of loop "lnum".
4808 void optPerformHoistExpr(GenTreePtr expr, unsigned lnum);
4811 void optOptimizeBools();
4814 GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
4816 void optOptimizeBoolsGcStress(BasicBlock* condBlock);
4819 void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
4821 void optOptimizeLoops(); // for "while-do" loops duplicates simple loop conditions and transforms
4822 // the loop into a "do-while" loop
4823 // Also finds all natural loops and records them in the loop table
4825 // Optionally clone loops in the loop table.
4826 void optCloneLoops();
4828 // Clone loop "loopInd" in the loop table.
4829 void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
4831 // Ensure that loop "loopInd" has a unique head block. (If the existing entry has
4832 // non-loop predecessors other than the head entry, create a new, empty block that goes (only) to the entry,
4833 // and redirects the preds of the entry to this new block.) Sets the weight of the newly created block to
4835 void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
4837 void optUnrollLoops(); // Unrolls loops (needs to have cost info)
4840 // This enumeration describes what is killed by a call.
4844 CALLINT_NONE, // no interference (most helpers)
4845 CALLINT_REF_INDIRS, // kills GC ref indirections (SETFIELD OBJ)
4846 CALLINT_SCL_INDIRS, // kills non GC ref indirections (SETFIELD non-OBJ)
4847 CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
4848 CALLINT_ALL, // kills everything (normal method call)
4852 // A "LoopDsc" describes a ("natural") loop. We (currently) require the body of a loop to be a contiguous (in
4853 // bbNext order) sequence of basic blocks. (At times, we may require the blocks in a loop to be "properly numbered"
4854 // in bbNext order; we use comparisons on the bbNum to decide order.)
4855 // The blocks that define the body are
4856 // first <= top <= entry <= bottom .
4857 // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
4858 // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
4859 // Compiler::optFindNaturalLoops().
4862 BasicBlock* lpHead; // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
4863 BasicBlock* lpFirst; // FIRST block (in bbNext order) reachable within this loop. (May be part of a nested
4864 // loop, but not the outer loop.)
4865 BasicBlock* lpTop; // loop TOP (the back edge from lpBottom reaches here) (in most cases FIRST and TOP are the
4867 BasicBlock* lpEntry; // the ENTRY in the loop (in most cases TOP or BOTTOM)
4868 BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
4869 BasicBlock* lpExit; // if a single exit loop this is the EXIT (in most cases BOTTOM)
4871 callInterf lpAsgCall; // "callInterf" for calls in the loop
4872 ALLVARSET_TP lpAsgVars; // set of vars assigned within the loop (all vars, not just tracked)
4873 varRefKinds lpAsgInds : 8; // set of inds modified within the loop
4875 unsigned short lpFlags; // Mask of the LPFLG_* constants
4877 unsigned char lpExitCnt; // number of exits from the loop
4879 unsigned char lpParent; // The index of the most-nested loop that completely contains this one,
4880 // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
4881 unsigned char lpChild; // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
4882 // (Actually, an "immediately" nested loop --
4883 // no other child of this loop is a parent of lpChild.)
4884 unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
4885 // or else BasicBlock::NOT_IN_LOOP. One can enumerate all the children of a loop
4886 // by following "lpChild" then "lpSibling" links.
4888 #define LPFLG_DO_WHILE 0x0001 // it's a do-while loop (i.e ENTRY is at the TOP)
4889 #define LPFLG_ONE_EXIT 0x0002 // the loop has only one exit
4891 #define LPFLG_ITER 0x0004 // for (i = icon or lclVar; test_condition(); i++)
4892 #define LPFLG_HOISTABLE 0x0008 // the loop is in a form that is suitable for hoisting expressions
4893 #define LPFLG_CONST 0x0010 // for (i=icon;i<icon;i++){ ... } - constant loop
4895 #define LPFLG_VAR_INIT 0x0020 // iterator is initialized with a local var (var # found in lpVarInit)
4896 #define LPFLG_CONST_INIT 0x0040 // iterator is initialized with a constant (found in lpConstInit)
4898 #define LPFLG_VAR_LIMIT 0x0100 // iterator is compared with a local var (var # found in lpVarLimit)
4899 #define LPFLG_CONST_LIMIT 0x0200 // iterator is compared with a constant (found in lpConstLimit)
4900 #define LPFLG_ARRLEN_LIMIT 0x0400 // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
4902 #define LPFLG_HAS_PREHEAD 0x0800 // lpHead is known to be a preHead for this loop
4903 #define LPFLG_REMOVED 0x1000 // has been removed from the loop table (unrolled or optimized away)
4904 #define LPFLG_DONT_UNROLL 0x2000 // do not unroll this loop
4906 #define LPFLG_ASGVARS_YES 0x4000 // "lpAsgVars" has been computed
4907 #define LPFLG_ASGVARS_INC 0x8000 // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
4908 // type are assigned to.
4910 bool lpLoopHasHeapHavoc; // The loop contains an operation that we assume has arbitrary heap side effects.
4911 // If this is set, the fields below may not be accurate (since they become irrelevant.)
4912 bool lpContainsCall; // True if executing the loop body *may* execute a call
4914 VARSET_TP lpVarInOut; // The set of variables that are IN or OUT during the execution of this loop
4915 VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop
4917 int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
4919 int lpLoopVarCount; // The register count for the non-FP LclVars that are read/written inside this loop
4920 int lpVarInOutCount; // The register count for the non-FP LclVars that are alive inside or accross this loop
4922 int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
4924 int lpLoopVarFPCount; // The register count for the FP LclVars that are read/written inside this loop
4925 int lpVarInOutFPCount; // The register count for the FP LclVars that are alive inside or accross this loop
4927 typedef SimplerHashTable<CORINFO_FIELD_HANDLE,
4928 PtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>,
4930 JitSimplerHashBehavior>
4932 FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
4933 // instance fields modified
4936 typedef SimplerHashTable<CORINFO_CLASS_HANDLE,
4937 PtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>,
4939 JitSimplerHashBehavior>
4941 ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
4942 // arrays of that type are modified
4945 // Adds the variable liveness information for 'blk' to 'this' LoopDsc
4946 void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
4948 inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd);
4949 // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
4950 // (shifted left, with a low-order bit set to distinguish.)
4951 // Use the {Encode/Decode}ElemType methods to construct/destruct these.
4952 inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);
4954 /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
4956 GenTreePtr lpIterTree; // The "i <op>= const" tree
4957 unsigned lpIterVar(); // iterator variable #
4958 int lpIterConst(); // the constant with which the iterator is incremented
4959 genTreeOps lpIterOper(); // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
4960 void VERIFY_lpIterTree();
4962 var_types lpIterOperType(); // For overflow instructions
4965 int lpConstInit; // initial constant value of iterator : Valid if LPFLG_CONST_INIT
4966 unsigned lpVarInit; // initial local var number to which we initialize the iterator : Valid if
4970 /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
4972 GenTreePtr lpTestTree; // pointer to the node containing the loop test
4973 genTreeOps lpTestOper(); // the type of the comparison between the iterator and the limit (GT_LE, GT_GE, etc.)
4974 void VERIFY_lpTestTree();
4976 bool lpIsReversed(); // true if the iterator node is the second operand in the loop condition
4977 GenTreePtr lpIterator(); // the iterator node in the loop test
4978 GenTreePtr lpLimit(); // the limit node in the loop test
4980 int lpConstLimit(); // limit constant value of iterator - loop condition is "i RELOP const" : Valid if
4981 // LPFLG_CONST_LIMIT
4982 unsigned lpVarLimit(); // the lclVar # in the loop condition ( "i RELOP lclVar" ) : Valid if
4984 bool lpArrLenLimit(Compiler* comp, ArrIndex* index); // The array length in the loop condition ( "i RELOP
4985 // arr.len" or "i RELOP arr[i][j].len" ) : Valid if
4986 // LPFLG_ARRLEN_LIMIT
4988 // Returns "true" iff "*this" contains the blk.
4989 bool lpContains(BasicBlock* blk)
4991 return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
4993 // Returns "true" iff "*this" (properly) contains the range [first, bottom] (allowing firsts
4994 // to be equal, but requiring bottoms to be different.)
4995 bool lpContains(BasicBlock* first, BasicBlock* bottom)
4997 return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
5000 // Returns "true" iff "*this" (properly) contains "lp2" (allowing firsts to be equal, but requiring
5001 // bottoms to be different.)
5002 bool lpContains(const LoopDsc& lp2)
5004 return lpContains(lp2.lpFirst, lp2.lpBottom);
5007 // Returns "true" iff "*this" is (properly) contained by the range [first, bottom]
5008 // (allowing firsts to be equal, but requiring bottoms to be different.)
5009 bool lpContainedBy(BasicBlock* first, BasicBlock* bottom)
5011 return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
5014 // Returns "true" iff "*this" is (properly) contained by "lp2"
5015 // (allowing firsts to be equal, but requiring bottoms to be different.)
5016 bool lpContainedBy(const LoopDsc& lp2)
5018 return lpContains(lp2.lpFirst, lp2.lpBottom);
5021 // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5022 bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5024 return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5026 // Returns "true" iff "*this" is disjoint from "lp2".
5027 bool lpDisjoint(const LoopDsc& lp2)
5029 return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5031 // Returns "true" iff the loop is well-formed (see code for defn).
5034 return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5035 lpEntry->bbNum <= lpBottom->bbNum &&
5036 (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5041 bool fgMightHaveLoop(); // returns true if there are any backedges
5042 bool fgHasLoops; // True if this method has any loops, set in fgComputeReachability
5045 LoopDsc optLoopTable[MAX_LOOP_NUM]; // loop descriptor table
5046 unsigned char optLoopCount; // number of tracked loops
5049 unsigned optCallCount; // number of calls made in the method
5050 unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
5051 unsigned optNativeCallCount; // number of Pinvoke/Native calls made in the method
5052 unsigned optLoopsCloned; // number of loops cloned in the current method.
5055 unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5056 void optPrintLoopInfo(unsigned loopNum,
5058 BasicBlock* lpFirst,
5060 BasicBlock* lpEntry,
5061 BasicBlock* lpBottom,
5062 unsigned char lpExitCnt,
5064 unsigned parentLoop = BasicBlock::NOT_IN_LOOP);
5065 void optPrintLoopInfo(unsigned lnum);
5066 void optPrintLoopRecording(unsigned lnum);
5068 void optCheckPreds();
5071 void optSetBlockWeights();
5073 void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5075 void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5077 void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
5079 bool optIsLoopTestEvalIntoTemp(GenTreePtr test, GenTreePtr* newTest);
5080 unsigned optIsLoopIncrTree(GenTreePtr incr);
5081 bool optCheckIterInLoopTest(unsigned loopInd, GenTreePtr test, BasicBlock* from, BasicBlock* to, unsigned iterVar);
5082 bool optComputeIterInfo(GenTreePtr incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
5083 bool optPopulateInitInfo(unsigned loopInd, GenTreePtr init, unsigned iterVar);
5084 bool optExtractInitTestIncr(BasicBlock* head,
5089 GenTreePtr* ppIncr);
5091 void optRecordLoop(BasicBlock* head,
5097 unsigned char exitCnt);
5099 void optFindNaturalLoops();
5101 // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
5102 // each loop has a unique "top." Returns "true" iff the flowgraph has been modified.
5103 bool optCanonicalizeLoopNest(unsigned char loopInd);
5105 // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
5106 // unshared with any other loop. Returns "true" iff the flowgraph has been modified
5107 bool optCanonicalizeLoop(unsigned char loopInd);
5109 // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP". Requires "l2" to be
5110 // a valid loop table index, or else "BasicBlock::NOT_IN_LOOP". Returns true
5111 // iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
5112 bool optLoopContains(unsigned l1, unsigned l2);
5114 // Requires "loopInd" to be a valid index into the loop table.
5115 // Updates the loop table by changing loop "loopInd", whose head is required
5116 // to be "from", to be "to". Also performs this transformation for any
5117 // loop nested in "loopInd" that shares the same head as "loopInd".
5118 void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);
5120 // Updates the successors of "blk": if "blk2" is a successor of "blk", and there is a mapping for "blk2->blk3" in
5121 // "redirectMap", change "blk" so that "blk3" is this successor. Note that the predecessor lists are not updated.
5122 void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap);
5124 // Marks the containsCall information to "lnum" and any parent loops.
5125 void AddContainsCallAllContainingLoops(unsigned lnum);
5126 // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
5127 void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);
5128 // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
5129 void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd);
5130 // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
5131 void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);
5133 // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
5134 // of "from".) Copies the jump destination from "from" to "to".
5135 void optCopyBlkDest(BasicBlock* from, BasicBlock* to);
5137 // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5138 unsigned optLoopDepth(unsigned lnum)
5140 unsigned par = optLoopTable[lnum].lpParent;
5141 if (par == BasicBlock::NOT_IN_LOOP)
5147 return 1 + optLoopDepth(par);
5151 void fgOptWhileLoop(BasicBlock* block);
5153 bool optComputeLoopRep(int constInit,
5156 genTreeOps iterOper,
5158 genTreeOps testOper,
5161 unsigned* iterCount);
5162 #if FEATURE_STACK_FP_X87
5165 VARSET_TP optAllFloatVars; // mask of all tracked FP variables
5166 VARSET_TP optAllFPregVars; // mask of all enregistered FP variables
5167 VARSET_TP optAllNonFPvars; // mask of all tracked non-FP variables
5168 #endif // FEATURE_STACK_FP_X87
5171 static fgWalkPreFn optIsVarAssgCB;
5174 bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTreePtr skip, unsigned var);
5176 bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5178 int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5180 bool optNarrowTree(GenTreePtr tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5182 /**************************************************************************
5183 * Optimization conditions
5184 *************************************************************************/
5186 bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5187 bool optPentium4(void);
5188 bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5189 bool optAvoidIntMult(void);
5194 // The following is the upper limit on how many expressions we'll keep track
5195 // of for the CSE analysis.
5197 static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5199 static const int MIN_CSE_COST = 2;
5201 /* Generic list of nodes - used by the CSE logic */
5209 typedef struct treeLst* treeLstPtr;
5213 treeStmtLst* tslNext;
5214 GenTreePtr tslTree; // tree node
5215 GenTreePtr tslStmt; // statement containing the tree
5216 BasicBlock* tslBlock; // block containing the statement
5219 typedef struct treeStmtLst* treeStmtLstPtr;
5221 // The following logic keeps track of expressions via a simple hash table.
5225 CSEdsc* csdNextInBucket; // used by the hash table
5227 unsigned csdHashValue; // the orginal hashkey
5229 unsigned csdIndex; // 1..optCSECandidateCount
5230 char csdLiveAcrossCall; // 0 or 1
5232 unsigned short csdDefCount; // definition count
5233 unsigned short csdUseCount; // use count (excluding the implicit uses at defs)
5235 unsigned csdDefWtCnt; // weighted def count
5236 unsigned csdUseWtCnt; // weighted use count (excluding the implicit uses at defs)
5238 GenTreePtr csdTree; // treenode containing the 1st occurance
5239 GenTreePtr csdStmt; // stmt containing the 1st occurance
5240 BasicBlock* csdBlock; // block containing the 1st occurance
5242 treeStmtLstPtr csdTreeList; // list of matching tree nodes: head
5243 treeStmtLstPtr csdTreeLast; // list of matching tree nodes: tail
5246 static const size_t s_optCSEhashSize;
5247 CSEdsc** optCSEhash;
5252 CSEdsc* optCSEfindDsc(unsigned index);
5253 void optUnmarkCSE(GenTreePtr tree);
5255 // user defined callback data for the tree walk function optCSE_MaskHelper()
5256 struct optCSE_MaskData
5258 EXPSET_TP CSE_defMask;
5259 EXPSET_TP CSE_useMask;
5262 // Treewalk helper for optCSE_DefMask and optCSE_UseMask
5263 static fgWalkPreFn optCSE_MaskHelper;
5265 // This function walks all the node for an given tree
5266 // and return the mask of CSE definitions and uses for the tree
5268 void optCSE_GetMaskData(GenTreePtr tree, optCSE_MaskData* pMaskData);
5270 // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
5271 bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);
5272 bool optCSE_canSwap(GenTree* tree);
5274 static fgWalkPostFn optPropagateNonCSE;
5275 static fgWalkPreFn optHasNonCSEChild;
5277 static fgWalkPreFn optUnmarkCSEs;
5279 static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
5280 static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
5282 void optCleanupCSEs();
5285 void optEnsureClearCSEInfo();
5288 #endif // FEATURE_ANYCSE
5290 #if FEATURE_VALNUM_CSE
5291 /**************************************************************************
5292 * Value Number based CSEs
5293 *************************************************************************/
5296 void optOptimizeValnumCSEs();
5299 void optValnumCSE_Init();
5300 unsigned optValnumCSE_Index(GenTreePtr tree, GenTreePtr stmt);
5301 unsigned optValnumCSE_Locate();
5302 void optValnumCSE_InitDataFlow();
5303 void optValnumCSE_DataFlow();
5304 void optValnumCSE_Availablity();
5305 void optValnumCSE_Heuristic();
5306 void optValnumCSE_UnmarkCSEs(GenTreePtr deadTree, GenTreePtr keepList);
5308 #endif // FEATURE_VALNUM_CSE
5311 bool optDoCSE; // True when we have found a duplicate CSE tree
5312 bool optValnumCSE_phase; // True when we are executing the optValnumCSE_phase
5313 unsigned optCSECandidateTotal; // Grand total of CSE candidates for both Lexical and ValNum
5314 unsigned optCSECandidateCount; // Count of CSE's candidates, reset for Lexical and ValNum CSE's
5315 unsigned optCSEstart; // The first local variable number that is a CSE
5316 unsigned optCSEcount; // The total count of CSE's introduced.
5317 unsigned optCSEweight; // The weight of the current block when we are
5318 // scanning for CSE expressions
5320 bool optIsCSEcandidate(GenTreePtr tree);
5322 // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
5324 bool lclNumIsTrueCSE(unsigned lclNum) const
5326 return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
5329 // lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
5331 bool lclNumIsCSE(unsigned lclNum) const
5333 return lvaTable[lclNum].lvIsCSE;
5337 bool optConfigDisableCSE();
5338 bool optConfigDisableCSE2();
5340 void optOptimizeCSEs();
5342 #endif // FEATURE_ANYCSE
5350 unsigned ivaVar; // Variable we are interested in, or -1
5351 ALLVARSET_TP ivaMaskVal; // Set of variables assigned to. This is a set of all vars, not tracked vars.
5352 bool ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
5353 varRefKinds ivaMaskInd; // What kind of indirect assignments are there?
5354 callInterf ivaMaskCall; // What kind of calls are there?
5357 static callInterf optCallInterf(GenTreePtr call);
5360 // VN based copy propagation.
5361 typedef ArrayStack<GenTreePtr> GenTreePtrStack;
5362 typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*, JitSimplerHashBehavior>
5363 LclNumToGenTreePtrStack;
5365 // Kill set to track variables with intervening definitions.
5366 VARSET_TP optCopyPropKillSet;
5368 // Copy propagation functions.
5369 void optCopyProp(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree, LclNumToGenTreePtrStack* curSsaName);
5370 void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5371 void optBlockCopyProp(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5372 bool optIsSsaLocal(GenTreePtr tree);
5373 int optCopyProp_LclVarScore(LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc, bool preferOp2);
5374 void optVnCopyProp();
5376 /**************************************************************************
5377 * Early value propagation
5378 *************************************************************************/
5384 SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
5388 static unsigned GetHashCode(SSAName ssaNm)
5390 return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
5393 static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
5395 return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
5399 #define OMF_HAS_NEWARRAY 0x00000001 // Method contains 'new' of an array
5400 #define OMF_HAS_NEWOBJ 0x00000002 // Method contains 'new' of an object type.
5401 #define OMF_HAS_ARRAYREF 0x00000004 // Method contains array element loads or stores.
5402 #define OMF_HAS_VTABLEREF 0x00000008 // Method contains method table reference.
5403 #define OMF_HAS_NULLCHECK 0x00000010 // Method contains null check.
5405 unsigned optMethodFlags;
5407 // Recursion bound controls how far we can go backwards tracking for a SSA value.
5408 // No throughput diff was found with backward walk bound between 3-8.
5409 static const int optEarlyPropRecurBound = 5;
5411 enum class optPropKind
5419 bool gtIsVtableRef(GenTreePtr tree);
5420 GenTreePtr getArrayLengthFromAllocation(GenTreePtr tree);
5421 GenTreePtr getObjectHandleNodeFromAllocation(GenTreePtr tree);
5422 GenTreePtr optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
5423 GenTreePtr optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
5424 bool optEarlyPropRewriteTree(GenTreePtr tree);
5425 bool optDoEarlyPropForBlock(BasicBlock* block);
5426 bool optDoEarlyPropForFunc();
5427 void optEarlyProp();
5428 void optFoldNullCheck(GenTreePtr tree);
5429 bool optCanMoveNullCheckPastTree(GenTreePtr tree, bool isInsideTry);
5432 /**************************************************************************
5433 * Value/Assertion propagation
5434 *************************************************************************/
5436 // Data structures for assertion prop
5437 BitVecTraits* apTraits;
5441 enum optAssertionKind
5456 O1K_ARRLEN_OPER_BND,
5457 O1K_ARRLEN_LOOP_BND,
5458 O1K_CONSTANT_LOOP_BND,
5479 optAssertionKind assertionKind;
5482 unsigned lclNum; // assigned to or property of this local var number
5490 struct AssertionDscOp1
5492 optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
5499 struct AssertionDscOp2
5501 optOp2Kind kind; // a const or copy assignment
5505 ssize_t iconVal; // integer
5506 unsigned iconFlags; // gtFlags
5508 struct Range // integer subrange
5522 bool IsArrLenArithBound()
5524 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_OPER_BND);
5526 bool IsArrLenBound()
5528 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_ARRLEN_LOOP_BND);
5530 bool IsConstantBound()
5532 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
5533 op1.kind == O1K_CONSTANT_LOOP_BND);
5535 bool IsBoundsCheckNoThrow()
5537 return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
5540 bool IsCopyAssertion()
5542 return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
5545 static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
5547 return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
5548 a1->op2.kind == a2->op2.kind;
5551 static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
5553 if (kind == OAK_EQUAL)
5555 return kind2 == OAK_NOT_EQUAL;
5557 else if (kind == OAK_NOT_EQUAL)
5559 return kind2 == OAK_EQUAL;
5564 static ssize_t GetLowerBoundForIntegralType(var_types type)
5584 static ssize_t GetUpperBoundForIntegralType(var_types type)
5608 bool HasSameOp1(AssertionDsc* that, bool vnBased)
5610 return (op1.kind == that->op1.kind) &&
5611 ((vnBased && (op1.vn == that->op1.vn)) || (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
5614 bool HasSameOp2(AssertionDsc* that, bool vnBased)
5616 if (op2.kind != that->op2.kind)
5622 case O2K_IND_CNS_INT:
5624 return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
5626 case O2K_CONST_LONG:
5627 return (op2.lconVal == that->op2.lconVal);
5629 case O2K_CONST_DOUBLE:
5630 // exact match because of positive and negative zero.
5631 return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);
5633 case O2K_LCLVAR_COPY:
5635 return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
5636 (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
5639 return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
5642 // we will return false
5646 assert(!"Unexpected value for op2.kind in AssertionDsc.");
5652 bool Complementary(AssertionDsc* that, bool vnBased)
5654 return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
5655 HasSameOp2(that, vnBased);
5658 bool Equals(AssertionDsc* that, bool vnBased)
5660 return (assertionKind == that->assertionKind) && HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
5664 typedef unsigned short AssertionIndex;
5667 static fgWalkPreFn optAddCopiesCallback;
5668 static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
5669 unsigned optAddCopyLclNum;
5670 GenTreePtr optAddCopyAsgnNode;
5672 bool optLocalAssertionProp; // indicates that we are performing local assertion prop
5673 bool optAssertionPropagated; // set to true if we modified the trees
5674 bool optAssertionPropagatedCurrentStmt;
5676 GenTreePtr optAssertionPropCurrentTree;
5678 AssertionIndex* optComplementaryAssertionMap;
5679 ExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
5680 // using the value of a local var) for each local var
5681 AssertionDsc* optAssertionTabPrivate; // table that holds info about value assignments
5682 AssertionIndex optAssertionCount; // total number of assertions in the assertion table
5683 AssertionIndex optMaxAssertionCount;
5686 void optVnNonNullPropCurStmt(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5687 fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5688 GenTreePtr optVNConstantPropOnRelOp(GenTreePtr tree);
5689 GenTreePtr optVNConstantPropOnJTrue(BasicBlock* block, GenTreePtr stmt, GenTreePtr test);
5690 GenTreePtr optVNConstantPropOnTree(BasicBlock* block, GenTreePtr stmt, GenTreePtr tree);
5691 GenTreePtr optPrepareTreeForReplacement(GenTreePtr extractTree, GenTreePtr replaceTree);
5693 AssertionIndex GetAssertionCount()
5695 return optAssertionCount;
5697 ASSERT_TP* bbJtrueAssertionOut;
5698 typedef SimplerHashTable<ValueNum, SmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP, JitSimplerHashBehavior>
5699 ValueNumToAssertsMap;
5700 ValueNumToAssertsMap* optValueNumToAsserts;
5702 static const AssertionIndex NO_ASSERTION_INDEX = 0;
5704 // Assertion prop helpers.
5705 ASSERT_TP& GetAssertionDep(unsigned lclNum);
5706 AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
5707 void optAssertionInit(bool isLocalProp);
5708 void optAssertionTraitsInit(AssertionIndex assertionCount);
5709 #if LOCAL_ASSERTION_PROP
5710 void optAssertionReset(AssertionIndex limit);
5711 void optAssertionRemove(AssertionIndex index);
5714 // Assertion prop data flow functions.
5715 void optAssertionPropMain();
5716 GenTreePtr optVNAssertionPropCurStmt(BasicBlock* block, GenTreePtr stmt);
5717 bool optIsTreeKnownIntValue(bool vnBased, GenTreePtr tree, ssize_t* pConstant, unsigned* pIconFlags);
5718 ASSERT_TP* optInitAssertionDataflowFlags();
5719 ASSERT_TP* optComputeAssertionGen();
5721 // Assertion Gen functions.
5722 void optAssertionGen(GenTreePtr tree);
5723 AssertionIndex optAssertionGenPhiDefn(GenTreePtr tree);
5724 AssertionIndex optCreateJTrueBoundsAssertion(GenTreePtr tree);
5725 AssertionIndex optAssertionGenJtrue(GenTreePtr tree);
5726 AssertionIndex optCreateJtrueAssertions(GenTreePtr op1, GenTreePtr op2, Compiler::optAssertionKind assertionKind);
5727 AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
5728 void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);
5730 // Assertion creation functions.
5731 AssertionIndex optCreateAssertion(GenTreePtr op1, GenTreePtr op2, optAssertionKind assertionKind);
5732 AssertionIndex optCreateAssertion(GenTreePtr op1,
5734 optAssertionKind assertionKind,
5735 AssertionDsc* assertion);
5736 void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTreePtr op1, GenTreePtr op2);
5738 bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
5739 AssertionIndex optAddAssertion(AssertionDsc* assertion);
5740 void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
5742 void optPrintVnAssertionMapping();
5744 ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
5746 // Used for respective assertion propagations.
5747 AssertionIndex optAssertionIsSubrange(GenTreePtr tree, var_types toType, ASSERT_VALARG_TP assertions);
5748 AssertionIndex optAssertionIsSubtype(GenTreePtr tree, GenTreePtr methodTableArg, ASSERT_VALARG_TP assertions);
5749 AssertionIndex optAssertionIsNonNullInternal(GenTreePtr op, ASSERT_VALARG_TP assertions);
5750 bool optAssertionIsNonNull(GenTreePtr op,
5751 ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));
5753 // Used for Relop propagation.
5754 AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTreePtr op1, GenTreePtr op2);
5755 AssertionIndex optLocalAssertionIsEqualOrNotEqual(
5756 optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);
5758 // Assertion prop for lcl var functions.
5759 bool optAssertionProp_LclVarTypeCheck(GenTreePtr tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
5760 GenTreePtr optCopyAssertionProp(AssertionDsc* curAssertion,
5762 GenTreePtr stmt DEBUGARG(AssertionIndex index));
5763 GenTreePtr optConstantAssertionProp(AssertionDsc* curAssertion,
5764 const GenTreePtr tree,
5765 const GenTreePtr stmt DEBUGARG(AssertionIndex index));
5766 GenTreePtr optVnConstantAssertionProp(const GenTreePtr tree, const GenTreePtr stmt);
5768 // Assertion propagation functions.
5769 GenTreePtr optAssertionProp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5770 GenTreePtr optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5771 GenTreePtr optAssertionProp_Ind(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5772 GenTreePtr optAssertionProp_Cast(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5773 GenTreePtr optAssertionProp_Call(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5774 GenTreePtr optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5775 GenTreePtr optAssertionProp_Comma(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5776 GenTreePtr optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5777 GenTreePtr optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5778 GenTreePtr optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5779 GenTreePtr optAssertionProp_Update(const GenTreePtr newTree, const GenTreePtr tree, const GenTreePtr stmt);
5780 GenTreePtr optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, const GenTreePtr tree, const GenTreePtr stmt);
5782 // Implied assertion functions.
5783 void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
5784 void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
5785 void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
5786 void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);
5788 ASSERT_VALRET_TP optNewFullAssertSet();
5789 ASSERT_VALRET_TP optNewEmptyAssertSet();
5792 void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
5793 void optDebugCheckAssertion(AssertionDsc* assertion);
5794 void optDebugCheckAssertions(AssertionIndex AssertionIndex);
5796 void optAddCopies();
5797 #endif // ASSERTION_PROP
5799 /**************************************************************************
5801 *************************************************************************/
5804 struct LoopCloneVisitorInfo
5806 LoopCloneContext* context;
5809 LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTreePtr stmt)
5810 : context(context), loopNum(loopNum), stmt(nullptr)
5815 bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
5816 bool optExtractArrIndex(GenTreePtr tree, ArrIndex* result, unsigned lhsNum);
5817 bool optReconstructArrIndex(GenTreePtr tree, ArrIndex* result, unsigned lhsNum);
5818 bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
5819 static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
5820 fgWalkResult optCanOptimizeByLoopCloning(GenTreePtr tree, LoopCloneVisitorInfo* info);
5821 void optObtainLoopCloningOpts(LoopCloneContext* context);
5822 bool optIsLoopClonable(unsigned loopInd);
5824 bool optCanCloneLoops();
5827 void optDebugLogLoopCloning(BasicBlock* block, GenTreePtr insertBefore);
5829 void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
5830 bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
5831 bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
5832 BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
5836 void optInsertLoopCloningStress(BasicBlock* head);
5838 #if COUNT_RANGECHECKS
5839 static unsigned optRangeChkRmv;
5840 static unsigned optRangeChkAll;
5849 #define MAX_ARRAYS 4 // a magic max number of arrays tracked for bounds check elimination
5854 RngChkDsc* rcdNextInBucket; // used by the hash table
5856 unsigned short rcdHashValue; // to make matching faster
5857 unsigned short rcdIndex; // 0..optRngChkCount-1
5859 GenTreePtr rcdTree; // the array index tree
5862 unsigned optRngChkCount;
5863 static const size_t optRngChkHashSize;
5865 ssize_t optGetArrayRefScaleAndIndex(GenTreePtr mul, GenTreePtr* pIndex DEBUGARG(bool bRngChk));
5866 GenTreePtr optFindLocalInit(BasicBlock* block, GenTreePtr local, VARSET_TP* pKilledInOut, bool* isKilledAfterInit);
5869 bool optIsNoMore(GenTreePtr op1, GenTreePtr op2, int add1 = 0, int add2 = 0);
5872 bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
5875 bool optLoopsMarked;
5878 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5879 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5883 XX Does the register allocation and puts the remaining lclVars on the stack XX
5885 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5886 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5890 #ifndef LEGACY_BACKEND
5895 #else // LEGACY_BACKEND
5900 #endif // LEGACY_BACKEND
5902 #ifdef LEGACY_BACKEND
5904 void raAssignVars(); // register allocation
5905 #endif // LEGACY_BACKEND
5907 VARSET_TP raRegVarsMask; // Set of all enregistered variables (not including FEATURE_STACK_FP_X87 enregistered
5909 regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
5911 void raMarkStkVars();
5914 // Some things are used by both LSRA and regpredict allocators.
5916 FrameType rpFrameType;
5917 bool rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
5919 #ifdef LEGACY_BACKEND
5920 regMaskTP rpMaskPInvokeEpilogIntf; // pinvoke epilog trashes esi/edi holding stack args needed to setup tail call's
5922 #endif // LEGACY_BACKEND
5924 bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
5926 #if FEATURE_FP_REGALLOC
5927 enum enumConfigRegisterFP
5929 CONFIG_REGISTER_FP_NONE = 0x0,
5930 CONFIG_REGISTER_FP_CALLEE_TRASH = 0x1,
5931 CONFIG_REGISTER_FP_CALLEE_SAVED = 0x2,
5932 CONFIG_REGISTER_FP_FULL = 0x3,
5934 enumConfigRegisterFP raConfigRegisterFP();
5935 #endif // FEATURE_FP_REGALLOC
5938 regMaskTP raConfigRestrictMaskFP();
5941 #ifndef LEGACY_BACKEND
5942 LinearScanInterface* m_pLinearScan; // Linear Scan allocator
5943 #else // LEGACY_BACKEND
5944 unsigned raAvoidArgRegMask; // Mask of incoming argument registers that we may need to avoid
5945 VARSET_TP raLclRegIntf[REG_COUNT]; // variable to register interference graph
5946 bool raNewBlocks; // True is we added killing blocks for FPU registers
5947 unsigned rpPasses; // Number of passes made by the register predicter
5948 unsigned rpPassesMax; // Maximum number of passes made by the register predicter
5949 unsigned rpPassesPessimize; // Number of passes non-pessimizing made by the register predicter
5950 unsigned rpStkPredict; // Weighted count of variables were predicted STK (lower means register allocation is better)
5951 unsigned rpPredictSpillCnt; // Predicted number of integer spill tmps for the current tree
5952 regMaskTP rpPredictAssignMask; // Mask of registers to consider in rpPredictAssignRegVars()
5953 VARSET_TP rpLastUseVars; // Set of last use variables in rpPredictTreeRegUse
5954 VARSET_TP rpUseInPlace; // Set of variables that we used in place
5955 int rpAsgVarNum; // VarNum for the target of GT_ASG node
5956 bool rpPredictAssignAgain; // Must rerun the rpPredictAssignRegVars()
5957 bool rpAddedVarIntf; // Set to true if we need to add a new var intf
5958 bool rpLostEnreg; // Set to true if we lost an enregister var that had lvDependReg set
5959 bool rpReverseEBPenreg; // Decided to reverse the enregistration of EBP
5961 bool rpRegAllocDone; // Set to true after we have completed register allocation
5963 regMaskTP rpPredictMap[PREDICT_COUNT]; // Holds the regMaskTP for each of the enum values
5965 void raSetupArgMasks(RegState* r);
5967 const regNumber* raGetRegVarOrder(var_types regType, unsigned* wbVarOrderSize);
5969 void raDumpVarIntf(); // Dump the variable to variable interference graph
5970 void raDumpRegIntf(); // Dump the variable to register interference graph
5972 void raAdjustVarIntf();
5974 regMaskTP rpPredictRegMask(rpPredictReg predictReg, var_types type);
5976 bool rpRecordRegIntf(regMaskTP regMask, VARSET_VALARG_TP life DEBUGARG(const char* msg));
5978 bool rpRecordVarIntf(unsigned varNum, VARSET_VALARG_TP intfVar DEBUGARG(const char* msg));
5979 regMaskTP rpPredictRegPick(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5981 regMaskTP rpPredictGrabReg(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
5983 static fgWalkPreFn rpMarkRegIntf;
5985 regMaskTP rpPredictAddressMode(
5986 GenTreePtr tree, var_types type, regMaskTP lockedRegs, regMaskTP rsvdRegs, GenTreePtr lenCSE);
5988 void rpPredictRefAssign(unsigned lclNum);
5990 regMaskTP rpPredictBlkAsgRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5992 regMaskTP rpPredictTreeRegUse(GenTreePtr tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
5994 regMaskTP rpPredictAssignRegVars(regMaskTP regAvail);
5996 void rpPredictRegUse(); // Entry point
5998 unsigned raPredictTreeRegUse(GenTreePtr tree);
5999 unsigned raPredictListRegUse(GenTreePtr list);
6001 void raSetRegVarOrder(var_types regType,
6002 regNumber* customVarOrder,
6003 unsigned* customVarOrderSize,
6005 regMaskTP avoidReg);
6007 // We use (unsigned)-1 as an uninitialized sentinel for rpStkPredict and
6008 // also as the maximum value of lvRefCntWtd. Don't allow overflow, and
6009 // saturate at UINT_MAX - 1, to avoid using the sentinel.
6010 void raAddToStkPredict(unsigned val)
6012 unsigned newStkPredict = rpStkPredict + val;
6013 if ((newStkPredict < rpStkPredict) || (newStkPredict == UINT_MAX))
6014 rpStkPredict = UINT_MAX - 1;
6016 rpStkPredict = newStkPredict;
6020 #if !FEATURE_FP_REGALLOC
6021 void raDispFPlifeInfo();
6025 regMaskTP genReturnRegForTree(GenTreePtr tree);
6026 #endif // LEGACY_BACKEND
6028 /* raIsVarargsStackArg is called by raMaskStkVars and by
6029 lvaSortByRefCount. It identifies the special case
6030 where a varargs function has a parameter passed on the
6031 stack, other than the special varargs handle. Such parameters
6032 require special treatment, because they cannot be tracked
6033 by the GC (their offsets in the stack are not known
6037 bool raIsVarargsStackArg(unsigned lclNum)
6041 LclVarDsc* varDsc = &lvaTable[lclNum];
6043 assert(varDsc->lvIsParam);
6045 return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6047 #else // _TARGET_X86_
6051 #endif // _TARGET_X86_
6054 #ifdef LEGACY_BACKEND
6055 // Records the current prediction, if it's better than any previous recorded prediction.
6056 void rpRecordPrediction();
6057 // Applies the best recorded prediction, if one exists and is better than the current prediction.
6058 void rpUseRecordedPredictionIfBetter();
6060 // Data members used in the methods above.
6061 unsigned rpBestRecordedStkPredict;
6062 struct VarRegPrediction
6064 bool m_isEnregistered;
6065 regNumberSmall m_regNum;
6066 regNumberSmall m_otherReg;
6068 VarRegPrediction* rpBestRecordedPrediction;
6069 #endif // LEGACY_BACKEND
6072 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6073 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6077 XX Get to the class and method info from the Execution Engine given XX
6078 XX tokens for the class and method XX
6080 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6081 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6085 /* These are the different addressing modes used to access a local var.
6086 * The JIT has to report the location of the locals back to the EE
6087 * for debugging purposes.
6093 VLT_REG_BYREF, // this type is currently only used for value types on X64
6096 VLT_STK_BYREF, // this type is currently only used for value types on X64
6110 siVarLocType vlType;
6113 // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6115 // VLT_REG_BYREF -- the specified register contains the address of the variable
6123 // VLT_STK -- Any 32 bit value which is on the stack
6124 // eg. [ESP+0x20], or [EBP-0x28]
6125 // VLT_STK_BYREF -- the specified stack location contains the address of the variable
6126 // eg. mov EAX, [ESP+0x20]; [EAX]
6130 regNumber vlsBaseReg;
6131 NATIVE_OFFSET vlsOffset;
6134 // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6143 // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6144 // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6152 regNumber vlrssBaseReg;
6153 NATIVE_OFFSET vlrssOffset;
6157 // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6158 // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6164 regNumber vlsrsBaseReg;
6165 NATIVE_OFFSET vlsrsOffset;
6171 // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6172 // eg 2 DWords at [ESP+0x10]
6176 regNumber vls2BaseReg;
6177 NATIVE_OFFSET vls2Offset;
6180 // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6181 // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
6188 // VLT_FIXED_VA -- fixed argument of a varargs function.
6189 // The argument location depends on the size of the variable
6190 // arguments (...). Inspecting the VARARGS_HANDLE indicates the
6191 // location of the first arg. This argument can then be accessed
6192 // relative to the position of the first arg
6196 unsigned vlfvOffset;
6203 void* rpValue; // pointer to the in-process
6204 // location of the value.
6210 bool vlIsInReg(regNumber reg);
6211 bool vlIsOnStk(regNumber reg, signed offset);
6214 /*************************************************************************/
6219 void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6220 CORINFO_RESOLVED_TOKEN* pConstrainedToken,
6221 CORINFO_CALLINFO_FLAGS flags,
6222 CORINFO_CALL_INFO* pResult);
6223 inline CORINFO_CALLINFO_FLAGS addVerifyFlag(CORINFO_CALLINFO_FLAGS flags);
6225 void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6226 CORINFO_ACCESS_FLAGS flags,
6227 CORINFO_FIELD_INFO* pResult);
6231 BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6233 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD)
6235 bool IsSuperPMIException(unsigned code)
6237 // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
6239 const unsigned EXCEPTIONCODE_DebugBreakorAV = 0xe0421000;
6240 const unsigned EXCEPTIONCODE_MC = 0xe0422000;
6241 const unsigned EXCEPTIONCODE_LWM = 0xe0423000;
6242 const unsigned EXCEPTIONCODE_SASM = 0xe0424000;
6243 const unsigned EXCEPTIONCODE_SSYM = 0xe0425000;
6244 const unsigned EXCEPTIONCODE_CALLUTILS = 0xe0426000;
6245 const unsigned EXCEPTIONCODE_TYPEUTILS = 0xe0427000;
6246 const unsigned EXCEPTIONCODE_ASSERT = 0xe0440000;
6250 case EXCEPTIONCODE_DebugBreakorAV:
6251 case EXCEPTIONCODE_MC:
6252 case EXCEPTIONCODE_LWM:
6253 case EXCEPTIONCODE_SASM:
6254 case EXCEPTIONCODE_SSYM:
6255 case EXCEPTIONCODE_CALLUTILS:
6256 case EXCEPTIONCODE_TYPEUTILS:
6257 case EXCEPTIONCODE_ASSERT:
6264 const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6265 const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6267 bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6268 CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
6271 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6272 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
6273 unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6275 // VOM info, method sigs
6277 void eeGetSig(unsigned sigTok,
6278 CORINFO_MODULE_HANDLE scope,
6279 CORINFO_CONTEXT_HANDLE context,
6280 CORINFO_SIG_INFO* retSig);
6282 void eeGetCallSiteSig(unsigned sigTok,
6283 CORINFO_MODULE_HANDLE scope,
6284 CORINFO_CONTEXT_HANDLE context,
6285 CORINFO_SIG_INFO* retSig);
6287 void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6289 // Method entry-points, instrs
6291 void* eeGetFieldAddress(CORINFO_FIELD_HANDLE handle, void*** ppIndir);
6293 CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6295 CORINFO_EE_INFO eeInfo;
6296 bool eeInfoInitialized;
6298 CORINFO_EE_INFO* eeGetEEInfo();
6300 // Gets the offset of a SDArray's first element
6301 unsigned eeGetArrayDataOffset(var_types type);
6302 // Gets the offset of a MDArray's first element
6303 unsigned eeGetMDArrayDataOffset(var_types type, unsigned rank);
6305 GenTreePtr eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6307 // Returns the page size for the target machine as reported by the EE.
6308 inline size_t eeGetPageSize()
6310 #if COR_JIT_EE_VERSION > 460
6311 return eeGetEEInfo()->osPageSize;
6312 #else // COR_JIT_EE_VERSION <= 460
6313 return CORINFO_PAGE_SIZE;
6314 #endif // COR_JIT_EE_VERSION > 460
6317 // Returns the frame size at which we will generate a loop to probe the stack.
6318 inline size_t getVeryLargeFrameSize()
6321 // The looping probe code is 40 bytes, whereas the straight-line probing for
6322 // the (0x2000..0x3000) case is 44, so use looping for anything 0x2000 bytes
6323 // or greater, to generate smaller code.
6324 return 2 * eeGetPageSize();
6326 return 3 * eeGetPageSize();
6330 inline bool generateCFIUnwindCodes()
6332 #if COR_JIT_EE_VERSION > 460 && defined(UNIX_AMD64_ABI)
6333 return eeGetEEInfo()->targetAbi == CORINFO_CORERT_ABI;
6341 unsigned eeGetEHcount(CORINFO_METHOD_HANDLE handle);
6343 // Debugging support - Line number info
6345 void eeGetStmtOffsets();
6347 unsigned eeBoundariesCount;
6349 struct boundariesDsc
6351 UNATIVE_OFFSET nativeIP;
6353 unsigned sourceReason;
6354 } * eeBoundaries; // Boundaries to report to EE
6355 void eeSetLIcount(unsigned count);
6356 void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, unsigned srcIP, bool stkEmpty, bool callInstruction);
6360 static void eeDispILOffs(IL_OFFSET offs);
6361 static void eeDispLineInfo(const boundariesDsc* line);
6362 void eeDispLineInfos();
6365 // Debugging support - Local var info
6369 unsigned eeVarsCount;
6371 struct VarResultInfo
6373 UNATIVE_OFFSET startOffset;
6374 UNATIVE_OFFSET endOffset;
6378 void eeSetLVcount(unsigned count);
6379 void eeSetLVinfo(unsigned which,
6380 UNATIVE_OFFSET startOffs,
6381 UNATIVE_OFFSET length,
6386 const siVarLoc& loc);
6390 void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
6391 void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
6394 // ICorJitInfo wrappers
6396 void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
6398 void eeAllocUnwindInfo(BYTE* pHotCode,
6404 CorJitFuncKind funcKind);
6406 void eeSetEHcount(unsigned cEH);
6408 void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
6410 WORD eeGetRelocTypeHint(void* target);
6412 // ICorStaticInfo wrapper functions
6414 bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
6416 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
6418 static void dumpSystemVClassificationType(SystemVClassificationType ct);
6421 void eeGetSystemVAmd64PassStructInRegisterDescriptor(
6422 /*IN*/ CORINFO_CLASS_HANDLE structHnd,
6423 /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
6424 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
6426 template <typename ParamType>
6427 bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
6429 return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
6432 bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
6434 // Utility functions
6436 const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
6439 const wchar_t* eeGetCPString(size_t stringHandle);
6442 const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
6444 static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
6445 static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
6447 static fgWalkPreFn CountSharedStaticHelper;
6448 static bool IsSharedStaticHelper(GenTreePtr tree);
6449 static bool IsTreeAlwaysHoistable(GenTreePtr tree);
6451 static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
6452 // returns true/false if 'field' is a Jit Data offset
6453 static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
6454 // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
6455 static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);
6457 /*****************************************************************************/
6462 enum TEMP_USAGE_TYPE
6468 static var_types tmpNormalizeType(var_types type);
6469 TempDsc* tmpGetTemp(var_types type); // get temp for the given type
6470 void tmpRlsTemp(TempDsc* temp);
6471 TempDsc* tmpFindNum(int temp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6474 TempDsc* tmpListBeg(TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6475 TempDsc* tmpListNxt(TempDsc* curTemp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
6479 bool tmpAllFree() const;
6482 #ifndef LEGACY_BACKEND
6483 void tmpPreAllocateTemps(var_types type, unsigned count);
6484 #endif // !LEGACY_BACKEND
6487 #ifdef LEGACY_BACKEND
6488 unsigned tmpIntSpillMax; // number of int-sized spill temps
6489 unsigned tmpDoubleSpillMax; // number of double-sized spill temps
6490 #endif // LEGACY_BACKEND
6492 unsigned tmpCount; // Number of temps
6493 unsigned tmpSize; // Size of all the temps
6496 // Used by RegSet::rsSpillChk()
6497 unsigned tmpGetCount; // Temps which haven't been released yet
6500 static unsigned tmpSlot(unsigned size); // which slot in tmpFree[] or tmpUsed[] to use
6502 TempDsc* tmpFree[TEMP_MAX_SIZE / sizeof(int)];
6503 TempDsc* tmpUsed[TEMP_MAX_SIZE / sizeof(int)];
6506 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6507 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6511 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6512 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6516 CodeGenInterface* codeGen;
6518 #ifdef DEBUGGING_SUPPORT
6520 // The following holds information about instr offsets in terms of generated code.
6524 IPmappingDsc* ipmdNext; // next line# record
6525 IL_OFFSETX ipmdILoffsx; // the instr offset
6526 emitLocation ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
6527 bool ipmdIsLabel; // Can this code be a branch label?
6530 // Record the instr offset mapping to the generated code
6532 IPmappingDsc* genIPmappingList;
6533 IPmappingDsc* genIPmappingLast;
6535 // Managed RetVal - A side hash table meant to record the mapping from a
6536 // GT_CALL node to its IL offset. This info is used to emit sequence points
6537 // that can be used by debugger to determine the native offset at which the
6538 // managed RetVal will be available.
6540 // In fact we can store IL offset in a GT_CALL node. This was ruled out in
6541 // favor of a side table for two reasons: 1) We need IL offset for only those
6542 // GT_CALL nodes (created during importation) that correspond to an IL call and
6543 // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
6544 // structure and IL offset is needed only when generating debuggable code. Therefore
6545 // it is desirable to avoid memory size penalty in retail scenarios.
6546 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, IL_OFFSETX, JitSimplerHashBehavior>
6547 CallSiteILOffsetTable;
6548 CallSiteILOffsetTable* genCallSite2ILOffsetMap;
6549 #endif // DEBUGGING_SUPPORT
6551 unsigned genReturnLocal; // Local number for the return value when applicable.
6552 BasicBlock* genReturnBB; // jumped to when not optimizing for speed.
6554 // The following properties are part of CodeGenContext. Getters are provided here for
6555 // convenience and backward compatibility, but the properties can only be set by invoking
6556 // the setter on CodeGenContext directly.
6558 __declspec(property(get = getEmitter)) emitter* genEmitter;
6559 emitter* getEmitter()
6561 return codeGen->getEmitter();
6564 const bool isFramePointerUsed()
6566 return codeGen->isFramePointerUsed();
6569 __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
6570 bool getInterruptible()
6572 return codeGen->genInterruptible;
6574 void setInterruptible(bool value)
6576 codeGen->setInterruptible(value);
6580 const bool genDoubleAlign()
6582 return codeGen->doDoubleAlign();
6584 DWORD getCanDoubleAlign(); // Defined & used only by RegAlloc
6585 #endif // DOUBLE_ALIGN
6586 __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
6587 bool getFullPtrRegMap()
6589 return codeGen->genFullPtrRegMap;
6591 void setFullPtrRegMap(bool value)
6593 codeGen->setFullPtrRegMap(value);
6596 // Things that MAY belong either in CodeGen or CodeGenContext
6598 #if FEATURE_EH_FUNCLETS
6599 FuncInfoDsc* compFuncInfos;
6600 unsigned short compCurrFuncIdx;
6601 unsigned short compFuncInfoCount;
6603 unsigned short compFuncCount()
6605 assert(fgFuncletsCreated);
6606 return compFuncInfoCount;
6609 #else // !FEATURE_EH_FUNCLETS
6611 // This is a no-op when there are no funclets!
6612 void genUpdateCurrentFunclet(BasicBlock* block)
6617 FuncInfoDsc compFuncInfoRoot;
6619 static const unsigned compCurrFuncIdx = 0;
6621 unsigned short compFuncCount()
6626 #endif // !FEATURE_EH_FUNCLETS
6628 FuncInfoDsc* funCurrentFunc();
6629 void funSetCurrentFunc(unsigned funcIdx);
6630 FuncInfoDsc* funGetFunc(unsigned funcIdx);
6631 unsigned int funGetFuncIdx(BasicBlock* block);
6635 VARSET_TP compCurLife; // current live variables
6636 GenTreePtr compCurLifeTree; // node after which compCurLife has been computed
6638 template <bool ForCodeGen>
6639 void compChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree));
6641 void genChangeLife(VARSET_VALARG_TP newLife DEBUGARG(GenTreePtr tree))
6643 compChangeLife</*ForCodeGen*/ true>(newLife DEBUGARG(tree));
6646 template <bool ForCodeGen>
6647 void compUpdateLife(GenTreePtr tree);
6649 // Updates "compCurLife" to its state after evaluate of "true". If "pLastUseVars" is
6650 // non-null, sets "*pLastUseVars" to the set of tracked variables for which "tree" was a last
6651 // use. (Can be more than one var in the case of dependently promoted struct vars.)
6652 template <bool ForCodeGen>
6653 void compUpdateLifeVar(GenTreePtr tree, VARSET_TP* pLastUseVars = nullptr);
6655 template <bool ForCodeGen>
6656 inline void compUpdateLife(VARSET_VALARG_TP newLife);
6658 // Gets a register mask that represent the kill set for a helper call since
6659 // not all JIT Helper calls follow the standard ABI on the target architecture.
6660 regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);
6662 // Gets a register mask that represent the kill set for a NoGC helper call.
6663 regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
6666 // Requires that "varDsc" be a promoted struct local variable being passed as an argument, beginning at
6667 // "firstArgRegNum", which is assumed to have already been aligned to the register alignment restriction of the
6668 // struct type. Adds bits to "*pArgSkippedRegMask" for any argument registers *not* used in passing "varDsc" --
6669 // i.e., internal "holes" caused by internal alignment constraints. For example, if the struct contained an int and
6670 // a double, and we at R0 (on ARM), then R1 would be skipped, and the bit for R1 would be added to the mask.
6671 void fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask);
6672 #endif // _TARGET_ARM_
6674 // If "tree" is a indirection (GT_IND, or GT_OBJ) whose arg is an ADDR, whose arg is a LCL_VAR, return that LCL_VAR
6676 static GenTreePtr fgIsIndirOfAddrOfLocal(GenTreePtr tree);
6678 // This is indexed by GT_OBJ nodes that are address of promoted struct variables, which
6679 // have been annotated with the GTF_VAR_DEATH flag. If such a node is *not* mapped in this
6680 // table, one may assume that all the (tracked) field vars die at this point. Otherwise,
6681 // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
6682 // vars of the promoted struct local that go dead at the given node (the set bits are the bits
6683 // for the tracked var indices of the field vars, as in a live var set).
6684 NodeToVarsetPtrMap* m_promotedStructDeathVars;
6686 NodeToVarsetPtrMap* GetPromotedStructDeathVars()
6688 if (m_promotedStructDeathVars == nullptr)
6690 m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
6692 return m_promotedStructDeathVars;
6696 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6697 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6701 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6702 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6705 #if !defined(__GNUC__)
6706 #pragma region Unwind information
6711 // Infrastructure functions: start/stop/reserve/emit.
6714 void unwindBegProlog();
6715 void unwindEndProlog();
6716 void unwindBegEpilog();
6717 void unwindEndEpilog();
6718 void unwindReserve();
6719 void unwindEmit(void* pHotCode, void* pColdCode);
6722 // Specific unwind information functions: called by code generation to indicate a particular
6723 // prolog or epilog unwindable instruction has been generated.
6726 void unwindPush(regNumber reg);
6727 void unwindAllocStack(unsigned size);
6728 void unwindSetFrameReg(regNumber reg, unsigned offset);
6729 void unwindSaveReg(regNumber reg, unsigned offset);
6731 #if defined(_TARGET_ARM_)
6732 void unwindPushMaskInt(regMaskTP mask);
6733 void unwindPushMaskFloat(regMaskTP mask);
6734 void unwindPopMaskInt(regMaskTP mask);
6735 void unwindPopMaskFloat(regMaskTP mask);
6736 void unwindBranch16(); // The epilog terminates with a 16-bit branch (e.g., "bx lr")
6737 void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
6738 // called via unwindPadding().
6739 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
6740 // instruction and the current location.
6741 #endif // _TARGET_ARM_
6743 #if defined(_TARGET_ARM64_)
6745 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
6746 // instruction and the current location.
6747 void unwindSaveReg(regNumber reg, int offset); // str reg, [sp, #offset]
6748 void unwindSaveRegPreindexed(regNumber reg, int offset); // str reg, [sp, #offset]!
6749 void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]
6750 void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
6751 void unwindSaveNext(); // unwind code: save_next
6752 void unwindReturn(regNumber reg); // ret lr
6753 #endif // defined(_TARGET_ARM64_)
6756 // Private "helper" functions for the unwind implementation.
6760 #if FEATURE_EH_FUNCLETS
6761 void unwindGetFuncLocations(FuncInfoDsc* func,
6762 bool getHotSectionData,
6763 /* OUT */ emitLocation** ppStartLoc,
6764 /* OUT */ emitLocation** ppEndLoc);
6765 #endif // FEATURE_EH_FUNCLETS
6767 void unwindReserveFunc(FuncInfoDsc* func);
6768 void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
6770 #if defined(_TARGET_AMD64_)
6772 void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
6773 void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
6774 UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
6776 void unwindBegPrologWindows();
6777 void unwindPushWindows(regNumber reg);
6778 void unwindAllocStackWindows(unsigned size);
6779 void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
6780 void unwindSaveRegWindows(regNumber reg, unsigned offset);
6782 #ifdef UNIX_AMD64_ABI
6783 void unwindBegPrologCFI();
6784 void unwindPushCFI(regNumber reg);
6785 void unwindAllocStackCFI(unsigned size);
6786 void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
6787 void unwindSaveRegCFI(regNumber reg, unsigned offset);
6788 int mapRegNumToDwarfReg(regNumber reg);
6789 void createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR opcode, USHORT dwarfReg, INT offset = 0);
6790 #endif // UNIX_AMD64_ABI
6791 #elif defined(_TARGET_ARM_)
6793 void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
6794 void unwindPushPopMaskFloat(regMaskTP mask);
6795 void unwindSplit(FuncInfoDsc* func);
6797 #endif // _TARGET_ARM_
6799 #if !defined(__GNUC__)
6800 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
6804 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6805 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6809 XX Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
6810 XX that contains the distinguished, well-known SIMD type definitions). XX
6812 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6813 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6816 // Get highest available instruction set for floating point codegen
6817 InstructionSet getFloatingPointInstructionSet()
6819 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6822 return InstructionSet_AVX;
6826 assert(canUseSSE2());
6827 return InstructionSet_SSE2;
6829 assert(!"getFPInstructionSet() is not implemented for target arch");
6831 return InstructionSet_NONE;
6835 // Get highest available instruction set for SIMD codegen
6836 InstructionSet getSIMDInstructionSet()
6838 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
6839 return getFloatingPointInstructionSet();
6841 assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
6843 return InstructionSet_NONE;
6849 // Should we support SIMD intrinsics?
6852 // This is a temp lclVar allocated on the stack as TYP_SIMD. It is used to implement intrinsics
6853 // that require indexed access to the individual fields of the vector, which is not well supported
6854 // by the hardware. It is allocated when/if such situations are encountered during Lowering.
6855 unsigned lvaSIMDInitTempVarNum;
6858 CORINFO_CLASS_HANDLE SIMDFloatHandle;
6859 CORINFO_CLASS_HANDLE SIMDDoubleHandle;
6860 CORINFO_CLASS_HANDLE SIMDIntHandle;
6861 CORINFO_CLASS_HANDLE SIMDUShortHandle;
6862 CORINFO_CLASS_HANDLE SIMDUByteHandle;
6863 CORINFO_CLASS_HANDLE SIMDShortHandle;
6864 CORINFO_CLASS_HANDLE SIMDByteHandle;
6865 CORINFO_CLASS_HANDLE SIMDLongHandle;
6866 CORINFO_CLASS_HANDLE SIMDUIntHandle;
6867 CORINFO_CLASS_HANDLE SIMDULongHandle;
6868 CORINFO_CLASS_HANDLE SIMDVector2Handle;
6869 CORINFO_CLASS_HANDLE SIMDVector3Handle;
6870 CORINFO_CLASS_HANDLE SIMDVector4Handle;
6871 CORINFO_CLASS_HANDLE SIMDVectorHandle;
6873 // Get the handle for a SIMD type.
6874 CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
6876 if (simdBaseType == TYP_FLOAT)
6881 return SIMDVector2Handle;
6883 return SIMDVector3Handle;
6885 if ((getSIMDVectorType() == TYP_SIMD32) || (SIMDVector4Handle != NO_CLASS_HANDLE))
6887 return SIMDVector4Handle;
6896 assert(simdType == getSIMDVectorType());
6897 switch (simdBaseType)
6900 return SIMDFloatHandle;
6902 return SIMDDoubleHandle;
6904 return SIMDIntHandle;
6906 return SIMDUShortHandle;
6908 return SIMDUShortHandle;
6910 return SIMDUByteHandle;
6912 return SIMDShortHandle;
6914 return SIMDByteHandle;
6916 return SIMDLongHandle;
6918 return SIMDUIntHandle;
6920 return SIMDULongHandle;
6922 assert(!"Didn't find a class handle for simdType");
6924 return NO_CLASS_HANDLE;
6928 CORINFO_METHOD_HANDLE SIMDVectorFloat_set_Item;
6929 CORINFO_METHOD_HANDLE SIMDVectorFloat_get_Length;
6930 CORINFO_METHOD_HANDLE SIMDVectorFloat_op_Addition;
6932 // Returns true if the tree corresponds to a TYP_SIMD lcl var.
6933 // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
6934 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
6935 bool isSIMDTypeLocal(GenTree* tree)
6937 return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6940 // Returns true if the type of the tree is a byref of TYP_SIMD
6941 bool isAddrOfSIMDType(GenTree* tree)
6943 if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
6945 switch (tree->OperGet())
6948 return varTypeIsSIMD(tree->gtGetOp1());
6950 case GT_LCL_VAR_ADDR:
6951 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
6954 return isSIMDTypeLocal(tree);
6961 static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
6963 return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
6964 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
6965 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
6968 // Returns base type of a TYP_SIMD local.
6969 // Returns TYP_UNKNOWN if the local is not TYP_SIMD.
6970 var_types getBaseTypeOfSIMDLocal(GenTree* tree)
6972 if (isSIMDTypeLocal(tree))
6974 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
6980 bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
6982 return info.compCompHnd->isInSIMDModule(clsHnd);
6985 bool isSIMDClass(typeInfo* pTypeInfo)
6987 return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
6990 // Get the base (element) type and size in bytes for a SIMD type. Returns TYP_UNKNOWN
6991 // if it is not a SIMD type or is an unsupported base type.
6992 var_types getBaseTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);
6994 var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
6996 return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
6999 // Get SIMD Intrinsic info given the method handle.
7000 // Also sets typeHnd, argCount, baseType and sizeBytes out params.
7001 const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
7002 CORINFO_METHOD_HANDLE methodHnd,
7003 CORINFO_SIG_INFO* sig,
7006 var_types* baseType,
7007 unsigned* sizeBytes);
7009 // Pops and returns GenTree node from importers type stack.
7010 // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
7011 GenTreePtr impSIMDPopStack(var_types type, bool expectAddr = false);
7013 // Create a GT_SIMD tree for a Get property of SIMD vector with a fixed index.
7014 GenTreeSIMD* impSIMDGetFixed(var_types simdType, var_types baseType, unsigned simdSize, int index);
7016 // Creates a GT_SIMD tree for Select operation
7017 GenTreePtr impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7019 unsigned simdVectorSize,
7024 // Creates a GT_SIMD tree for Min/Max operation
7025 GenTreePtr impSIMDMinMax(SIMDIntrinsicID intrinsicId,
7026 CORINFO_CLASS_HANDLE typeHnd,
7028 unsigned simdVectorSize,
7032 // Transforms operands and returns the SIMD intrinsic to be applied on
7033 // transformed operands to obtain given relop result.
7034 SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID relOpIntrinsicId,
7035 CORINFO_CLASS_HANDLE typeHnd,
7036 unsigned simdVectorSize,
7037 var_types* baseType,
7041 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7042 // Transforms operands and returns the SIMD intrinsic to be applied on
7043 // transformed operands to obtain == comparison result.
7044 SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
7045 unsigned simdVectorSize,
7049 // Transforms operands and returns the SIMD intrinsic to be applied on
7050 // transformed operands to obtain > comparison result.
7051 SIMDIntrinsicID impSIMDLongRelOpGreaterThan(CORINFO_CLASS_HANDLE typeHnd,
7052 unsigned simdVectorSize,
7056 // Transforms operands and returns the SIMD intrinsic to be applied on
7057 // transformed operands to obtain >= comparison result.
7058 SIMDIntrinsicID impSIMDLongRelOpGreaterThanOrEqual(CORINFO_CLASS_HANDLE typeHnd,
7059 unsigned simdVectorSize,
7063 // Transforms operands and returns the SIMD intrinsic to be applied on
7064 // transformed operands to obtain >= comparison result in case of int32
7065 // and small int base type vectors.
7066 SIMDIntrinsicID impSIMDIntegralRelOpGreaterThanOrEqual(
7067 CORINFO_CLASS_HANDLE typeHnd, unsigned simdVectorSize, var_types baseType, GenTree** op1, GenTree** op2);
7068 #endif // defined(_TARGET_AMD64_) && !defined(LEGACY_BACKEND)
7070 void setLclRelatedToSIMDIntrinsic(GenTreePtr tree);
7071 bool areFieldsContiguous(GenTreePtr op1, GenTreePtr op2);
7072 bool areArrayElementsContiguous(GenTreePtr op1, GenTreePtr op2);
7073 bool areArgumentsContiguous(GenTreePtr op1, GenTreePtr op2);
7074 GenTreePtr createAddressNodeForSIMDInit(GenTreePtr tree, unsigned simdSize);
7076 // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
7077 GenTreePtr impSIMDIntrinsic(OPCODE opcode,
7078 GenTreePtr newobjThis,
7079 CORINFO_CLASS_HANDLE clsHnd,
7080 CORINFO_METHOD_HANDLE method,
7081 CORINFO_SIG_INFO* sig,
7084 GenTreePtr getOp1ForConstructor(OPCODE opcode, GenTreePtr newobjThis, CORINFO_CLASS_HANDLE clsHnd);
7086 // Whether SIMD vector occupies part of SIMD register.
7087 // SSE2: vector2f/3f are considered sub register SIMD types.
7088 // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
7089 bool isSubRegisterSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7091 unsigned sizeBytes = 0;
7092 var_types baseType = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7093 return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7096 bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7098 return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7101 // Get the type for the hardware SIMD vector.
7102 // This is the maximum SIMD type supported for this target.
7103 var_types getSIMDVectorType()
7105 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7112 assert(canUseSSE2());
7116 assert(!"getSIMDVectorType() unimplemented on target arch");
7121 // Get the size of the SIMD type in bytes
7122 int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7124 unsigned sizeBytes = 0;
7125 (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7129 // Get the the number of elements of basetype of SIMD vector given by its size and baseType
7130 static int getSIMDVectorLength(unsigned simdSize, var_types baseType);
7132 // Get the the number of elements of basetype of SIMD vector given by its type handle
7133 int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7135 // Get preferred alignment of SIMD type.
7136 int getSIMDTypeAlignment(var_types simdType);
7138 // Get the number of bytes in a SIMD Vector for the current compilation.
7139 unsigned getSIMDVectorRegisterByteLength()
7141 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7144 return YMM_REGSIZE_BYTES;
7148 assert(canUseSSE2());
7149 return XMM_REGSIZE_BYTES;
7152 assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7157 // The minimum and maximum possible number of bytes in a SIMD vector.
7158 unsigned int maxSIMDStructBytes()
7160 return getSIMDVectorRegisterByteLength();
7162 unsigned int minSIMDStructBytes()
7164 return emitTypeSize(TYP_SIMD8);
7167 #ifdef FEATURE_AVX_SUPPORT
7168 // (maxPossibleSIMDStructBytes is for use in a context that requires a compile-time constant.)
7169 static const unsigned maxPossibleSIMDStructBytes = 32;
7170 #else // !FEATURE_AVX_SUPPORT
7171 static const unsigned maxPossibleSIMDStructBytes = 16;
7172 #endif // !FEATURE_AVX_SUPPORT
7174 // Returns the codegen type for a given SIMD size.
7175 var_types getSIMDTypeForSize(unsigned size)
7177 var_types simdType = TYP_UNDEF;
7180 simdType = TYP_SIMD8;
7182 else if (size == 12)
7184 simdType = TYP_SIMD12;
7186 else if (size == 16)
7188 simdType = TYP_SIMD16;
7190 #ifdef FEATURE_AVX_SUPPORT
7191 else if (size == 32)
7193 simdType = TYP_SIMD32;
7195 #endif // FEATURE_AVX_SUPPORT
7198 noway_assert(!"Unexpected size for SIMD type");
7203 unsigned getSIMDInitTempVarNum()
7205 if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
7207 lvaSIMDInitTempVarNum = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
7208 lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
7210 return lvaSIMDInitTempVarNum;
7213 #endif // FEATURE_SIMD
7216 //------------------------------------------------------------------------
7217 // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
7219 // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
7220 // candidate for enregistration.
7222 unsigned largestEnregisterableStructSize()
7225 unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
7226 if (vectorRegSize > TARGET_POINTER_SIZE)
7228 return vectorRegSize;
7231 #endif // FEATURE_SIMD
7233 return TARGET_POINTER_SIZE;
7238 // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
7239 // is defined for both FEATURE_SIMD and !FEATURE_SIMD apropriately. The use
7240 // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.
7242 // Is this var is of type simd struct?
7243 bool lclVarIsSIMDType(unsigned varNum)
7245 LclVarDsc* varDsc = lvaTable + varNum;
7246 return varDsc->lvIsSIMDType();
7249 // Is this Local node a SIMD local?
7250 bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
7252 return lclVarIsSIMDType(lclVarTree->gtLclNum);
7255 // Returns true if the TYP_SIMD locals on stack are aligned at their
7256 // preferred byte boundary specified by getSIMDTypeAlignment().
7257 bool isSIMDTypeLocalAligned(unsigned varNum)
7259 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
7260 if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
7263 int off = lvaFrameAddress(varNum, &ebpBased);
7264 // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
7265 int alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
7266 bool isAligned = ((off % alignment) == 0);
7267 noway_assert(isAligned || lvaTable[varNum].lvIsParam);
7270 #endif // FEATURE_SIMD
7275 // Whether SSE2 is available
7276 bool canUseSSE2() const
7278 #ifdef _TARGET_XARCH_
7279 return opts.compCanUseSSE2;
7285 bool canUseAVX() const
7287 #ifdef FEATURE_AVX_SUPPORT
7288 return opts.compCanUseAVX;
7295 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7296 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7300 XX Generic info about the compilation and the method being compiled. XX
7301 XX It is responsible for driving the other phases. XX
7302 XX It is also responsible for all the memory management. XX
7304 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7305 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7309 Compiler* InlineeCompiler; // The Compiler instance for the inlinee
7311 InlineResult* compInlineResult; // The result of importing the inlinee method.
7313 bool compDoAggressiveInlining; // If true, mark every method as CORINFO_FLG_FORCEINLINE
7314 bool compJmpOpUsed; // Does the method do a JMP
7315 bool compLongUsed; // Does the method use TYP_LONG
7316 bool compFloatingPointUsed; // Does the method use TYP_FLOAT or TYP_DOUBLE
7317 bool compTailCallUsed; // Does the method do a tailcall
7318 bool compLocallocUsed; // Does the method use localloc.
7319 bool compQmarkUsed; // Does the method use GT_QMARK/GT_COLON
7320 bool compQmarkRationalized; // Is it allowed to use a GT_QMARK/GT_COLON node.
7321 bool compUnsafeCastUsed; // Does the method use LDIND/STIND to cast between scalar/refernce types
7323 // NOTE: These values are only reliable after
7324 // the importing is completely finished.
7326 ExpandArrayStack<GenTreePtr>* compQMarks; // The set of QMark nodes created in the current compilation, so
7327 // we can iterate over these efficiently.
7329 #if CPU_USES_BLOCK_MOVE
7330 bool compBlkOpUsed; // Does the method do a COPYBLK or INITBLK
7334 // State information - which phases have completed?
7335 // These are kept together for easy discoverability
7337 bool bRangeAllowStress;
7338 bool compCodeGenDone;
7339 int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
7340 bool fgNormalizeEHDone; // Has the flowgraph EH normalization phase been done?
7341 size_t compSizeEstimate; // The estimated size of the method as per `gtSetEvalOrder`.
7342 size_t compCycleEstimate; // The estimated cycle count of the method as per `gtSetEvalOrder`
7345 bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
7346 bool fgLocalVarLivenessChanged;
7348 bool compStackProbePrologDone;
7350 #ifndef LEGACY_BACKEND
7352 #endif // !LEGACY_BACKEND
7353 bool compRationalIRForm;
7355 bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
7357 bool compGeneratingProlog;
7358 bool compGeneratingEpilog;
7359 bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
7360 // Insert cookie on frame and code to check the cookie, like VC++ -GS.
7361 bool compGSReorderStackLayout; // There is an unsafe buffer on the stack, reorder locals and make local
7362 // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
7363 bool getNeedsGSSecurityCookie() const
7365 return compNeedsGSSecurityCookie;
7367 void setNeedsGSSecurityCookie()
7369 compNeedsGSSecurityCookie = true;
7372 FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
7373 // frame layout calculations, this is the level we are currently
7376 //---------------------------- JITing options -----------------------------
7389 CORJIT_FLAGS* jitFlags; // all flags passed from the EE
7390 unsigned eeFlags; // CorJitFlag flags passed from the EE
7391 unsigned compFlags; // method attributes
7393 codeOptimize compCodeOpt; // what type of code optimizations
7397 #ifdef _TARGET_XARCH_
7398 bool compCanUseSSE2; // Allow CodeGen to use "movq XMM" instructions
7400 #ifdef FEATURE_AVX_SUPPORT
7401 bool compCanUseAVX; // Allow CodeGen to use AVX 256-bit vectors for SIMD operations
7405 // optimize maximally and/or favor speed over size?
7407 #define DEFAULT_MIN_OPTS_CODE_SIZE 60000
7408 #define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
7409 #define DEFAULT_MIN_OPTS_BB_COUNT 2000
7410 #define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
7411 #define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000
7413 // Maximun number of locals before turning off the inlining
7414 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
7417 unsigned instrCount;
7418 unsigned lvRefCount;
7419 bool compMinOptsIsSet;
7421 bool compMinOptsIsUsed;
7423 inline bool MinOpts()
7425 assert(compMinOptsIsSet);
7426 compMinOptsIsUsed = true;
7429 inline bool IsMinOptsSet()
7431 return compMinOptsIsSet;
7434 inline bool MinOpts()
7438 inline bool IsMinOptsSet()
7440 return compMinOptsIsSet;
7443 inline void SetMinOpts(bool val)
7445 assert(!compMinOptsIsUsed);
7446 assert(!compMinOptsIsSet || (compMinOpts == val));
7448 compMinOptsIsSet = true;
7451 // true if the CLFLG_* for an optimization is set.
7452 inline bool OptEnabled(unsigned optFlag)
7454 return !!(compFlags & optFlag);
7457 #ifdef FEATURE_READYTORUN_COMPILER
7458 inline bool IsReadyToRun()
7460 return (eeFlags & CORJIT_FLG_READYTORUN) != 0;
7463 inline bool IsReadyToRun()
7469 // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
7470 // PInvoke transitions inline (e.g. when targeting CoreRT).
7471 inline bool ShouldUsePInvokeHelpers()
7473 #if COR_JIT_EE_VERSION > 460
7474 return (jitFlags->corJitFlags2 & CORJIT_FLG2_USE_PINVOKE_HELPERS) != 0;
7480 // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
7482 inline bool IsReversePInvoke()
7484 #if COR_JIT_EE_VERSION > 460
7485 return (jitFlags->corJitFlags2 & CORJIT_FLG2_REVERSE_PINVOKE) != 0;
7491 // true if we must generate code compatible with JIT32 quirks
7492 inline bool IsJit32Compat()
7494 #if defined(_TARGET_X86_) && COR_JIT_EE_VERSION > 460
7495 return (jitFlags->corJitFlags2 & CORJIT_FLG2_DESKTOP_QUIRKS) != 0;
7501 // true if we must generate code compatible with Jit64 quirks
7502 inline bool IsJit64Compat()
7504 #if defined(_TARGET_AMD64_) && COR_JIT_EE_VERSION > 460
7505 return (jitFlags->corJitFlags2 & CORJIT_FLG2_DESKTOP_QUIRKS) != 0;
7506 #elif defined(_TARGET_AMD64_) && !defined(FEATURE_CORECLR)
7513 #ifdef DEBUGGING_SUPPORT
7514 bool compScopeInfo; // Generate the LocalVar info ?
7515 bool compDbgCode; // Generate debugger-friendly code?
7516 bool compDbgInfo; // Gather debugging info?
7519 static const bool compDbgCode;
7522 #ifdef PROFILING_SUPPORTED
7523 bool compNoPInvokeInlineCB;
7525 static const bool compNoPInvokeInlineCB;
7528 bool compMustInlinePInvokeCalli; // Unmanaged CALLI in IL stubs must be inlined
7531 bool compGcChecks; // Check arguments and return values to ensure they are sane
7532 bool compStackCheckOnRet; // Check ESP on return to ensure it is correct
7533 bool compStackCheckOnCall; // Check ESP after every call to ensure it is correct
7537 bool compNeedSecurityCheck; // This flag really means where or not a security object needs
7538 // to be allocated on the stack.
7539 // It will be set to true in the following cases:
7540 // 1. When the method being compiled has a declarative security
7541 // (i.e. when CORINFO_FLG_NOSECURITYWRAP is reset for the current method).
7542 // This is also the case when we inject a prolog and epilog in the method.
7544 // 2. When the method being compiled has imperative security (i.e. the method
7545 // calls into another method that has CORINFO_FLG_SECURITYCHECK flag set).
7547 // 3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
7549 // When this flag is set, jit will allocate a gc-reference local variable (lvaSecurityObject),
7550 // which gets reported as a GC root to stackwalker.
7551 // (See also ICodeManager::GetAddrOfSecurityObject.)
7558 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7559 bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
7563 #ifdef UNIX_AMD64_ABI
7564 // This flag is indicating if there is a need to align the frame.
7565 // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
7566 // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
7567 // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
7568 // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
7569 // there are calls and making sure the frame alignment logic is executed.
7570 bool compNeedToAlignFrame;
7571 #endif // UNIX_AMD64_ABI
7573 bool compProcedureSplitting; // Separate cold code from hot code
7575 bool genFPorder; // Preserve FP order (operations are non-commutative)
7576 bool genFPopt; // Can we do frame-pointer-omission optimization?
7577 bool altJit; // True if we are an altjit and are compiling this method
7580 bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
7581 bool dspCode; // Display native code generated
7582 bool dspEHTable; // Display the EH table reported to the VM
7583 bool dspInstrs; // Display the IL instructions intermixed with the native code output
7584 bool dspEmit; // Display emitter output
7585 bool dspLines; // Display source-code lines intermixed with native code output
7586 bool dmpHex; // Display raw bytes in hex of native code output
7587 bool varNames; // Display variables names in native code output
7588 bool disAsm; // Display native code as it is generated
7589 bool disAsmSpilled; // Display native code when any register spilling occurs
7590 bool disDiffable; // Makes the Disassembly code 'diff-able'
7591 bool disAsm2; // Display native code after it is generated using external disassembler
7592 bool dspOrder; // Display names of each of the methods that we ngen/jit
7593 bool dspUnwind; // Display the unwind info output
7594 bool dspDiffable; // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
7595 bool compLongAddress; // Force using large pseudo instructions for long address
7596 // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
7597 bool dspGCtbls; // Display the GC tables
7601 bool doLateDisasm; // Run the late disassembler
7602 #endif // LATE_DISASM
7604 #if DUMP_GC_TABLES && !defined(DEBUG) && defined(JIT32_GCENCODER)
7605 // Only the JIT32_GCENCODER implements GC dumping in non-DEBUG code.
7606 #pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
7607 static const bool dspGCtbls = true;
7610 // We need stack probes to guarantee that we won't trigger a stack overflow
7611 // when calling unmanaged code until they get a chance to set up a frame, because
7612 // the EE will have no idea where it is.
7614 // We will only be doing this currently for hosted environments. Unfortunately
7615 // we need to take care of stubs, so potentially, we will have to do the probes
7616 // for any call. We have a plan for not needing for stubs though
7617 bool compNeedStackProbes;
7619 // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub())
7620 // This options helps one to make JIT behave as if it is under profiler.
7621 bool compJitELTHookEnabled;
7623 #if FEATURE_TAILCALL_OPT
7624 // Whether opportunistic or implicit tail call optimization is enabled.
7625 bool compTailCallOpt;
7626 // Whether optimization of transforming a recursive tail call into a loop is enabled.
7627 bool compTailCallLoopOpt;
7631 static const bool compUseSoftFP = true;
7632 #else // !ARM_SOFTFP
7633 static const bool compUseSoftFP = false;
7636 GCPollType compGCPollType;
7640 static bool s_pAltJitExcludeAssembliesListInitialized;
7641 static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
7646 static bool s_dspMemStats; // Display per-phase memory statistics for every function
7648 template <typename T>
7651 return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
7654 template <typename T>
7657 return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
7660 static int dspTreeID(GenTree* tree)
7662 return tree->gtTreeID;
7664 static void printTreeID(GenTree* tree)
7666 if (tree == nullptr)
7672 printf("[%06d]", dspTreeID(tree));
7679 #define STRESS_MODES \
7683 /* "Variations" stress areas which we try to mix up with each other. */ \
7684 /* These should not be exhaustively used as they might */ \
7685 /* hide/trivialize other areas */ \
7687 STRESS_MODE(REGS) STRESS_MODE(DBL_ALN) STRESS_MODE(LCL_FLDS) STRESS_MODE(UNROLL_LOOPS) \
7688 STRESS_MODE(MAKE_CSE) STRESS_MODE(LEGACY_INLINE) STRESS_MODE(CLONE_EXPR) \
7689 STRESS_MODE(USE_FCOMI) STRESS_MODE(USE_CMOV) STRESS_MODE(FOLD) \
7690 STRESS_MODE(BB_PROFILE) STRESS_MODE(OPT_BOOLS_GC) STRESS_MODE(REMORPH_TREES) \
7691 STRESS_MODE(64RSLT_MUL) STRESS_MODE(DO_WHILE_LOOPS) STRESS_MODE(MIN_OPTS) \
7692 STRESS_MODE(REVERSE_FLAG) /* Will set GTF_REVERSE_OPS whenever we can */ \
7693 STRESS_MODE(REVERSE_COMMA) /* Will reverse commas created with gtNewCommaNode */ \
7694 STRESS_MODE(TAILCALL) /* Will make the call as a tailcall whenever legal */ \
7695 STRESS_MODE(CATCH_ARG) /* Will spill catch arg */ \
7696 STRESS_MODE(UNSAFE_BUFFER_CHECKS) \
7697 STRESS_MODE(NULL_OBJECT_CHECK) \
7698 STRESS_MODE(PINVOKE_RESTORE_ESP) \
7699 STRESS_MODE(RANDOM_INLINE) \
7701 STRESS_MODE(GENERIC_VARN) STRESS_MODE(COUNT_VARN) \
7703 /* "Check" stress areas that can be exhaustively used if we */ \
7704 /* dont care about performance at all */ \
7706 STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */ \
7707 STRESS_MODE(CHK_FLOW_UPDATE) \
7708 STRESS_MODE(EMITTER) STRESS_MODE(CHK_REIMPORT) STRESS_MODE(FLATFP) \
7710 STRESS_MODE(GENERIC_CHECK) STRESS_MODE(COUNT) \
7714 #define STRESS_MODE(mode) STRESS_##mode,
7721 static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
7722 BYTE compActiveStressModes[STRESS_COUNT];
7725 #define MAX_STRESS_WEIGHT 100
7727 bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
7731 bool compInlineStress()
7733 return compStressCompile(STRESS_LEGACY_INLINE, 50);
7736 bool compRandomInlineStress()
7738 return compStressCompile(STRESS_RANDOM_INLINE, 50);
7743 bool compTailCallStress()
7746 return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
7752 codeOptimize compCodeOpt()
7755 // Switching between size & speed has measurable throughput impact
7756 // (3.5% on NGen mscorlib when measured). It used to be enabled for
7757 // DEBUG, but should generate identical code between CHK & RET builds,
7758 // so that's not acceptable.
7759 // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
7760 // Investigate the cause of the throughput regression.
7762 return opts.compCodeOpt;
7764 return BLENDED_CODE;
7772 //--------------------- Info about the procedure --------------------------
7776 COMP_HANDLE compCompHnd;
7777 CORINFO_MODULE_HANDLE compScopeHnd;
7778 CORINFO_CLASS_HANDLE compClassHnd;
7779 CORINFO_METHOD_HANDLE compMethodHnd;
7780 CORINFO_METHOD_INFO* compMethodInfo;
7782 BOOL hasCircularClassConstraints;
7783 BOOL hasCircularMethodConstraints;
7785 #if defined(DEBUG) || defined(LATE_DISASM)
7786 const char* compMethodName;
7787 const char* compClassName;
7788 const char* compFullName;
7789 #endif // defined(DEBUG) || defined(LATE_DISASM)
7791 #if defined(DEBUG) || defined(INLINE_DATA)
7792 // Method hash is logcally const, but computed
7794 mutable unsigned compMethodHashPrivate;
7795 unsigned compMethodHash() const;
7796 #endif // defined(DEBUG) || defined(INLINE_DATA)
7798 #ifdef PSEUDORANDOM_NOP_INSERTION
7799 // things for pseudorandom nop insertion
7800 unsigned compChecksum;
7804 // The following holds the FLG_xxxx flags for the method we're compiling.
7807 // The following holds the class attributes for the method we're compiling.
7808 unsigned compClassAttr;
7810 const BYTE* compCode;
7811 IL_OFFSET compILCodeSize; // The IL code size
7812 UNATIVE_OFFSET compNativeCodeSize; // The native code size, after instructions are issued. This
7813 // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
7814 // (1) the code is not hot/cold split, and we issued less code than we expected, or
7815 // (2) the code is hot/cold split, and we issued less code than we expected
7816 // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).
7818 bool compIsStatic : 1; // Is the method static (no 'this' pointer)?
7819 bool compIsVarArgs : 1; // Does the method have varargs parameters?
7820 bool compIsContextful : 1; // contextful method
7821 bool compInitMem : 1; // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
7822 bool compUnwrapContextful : 1; // JIT should unwrap proxies when possible
7823 bool compProfilerCallback : 1; // JIT inserted a profiler Enter callback
7824 bool compPublishStubParam : 1; // EAX captured in prolog will be available through an instrinsic
7825 bool compRetBuffDefStack : 1; // The ret buff argument definitely points into the stack.
7827 var_types compRetType; // Return type of the method as declared in IL
7828 var_types compRetNativeType; // Normalized return type as per target arch ABI
7829 unsigned compILargsCount; // Number of arguments (incl. implicit but not hidden)
7830 unsigned compArgsCount; // Number of arguments (incl. implicit and hidden)
7831 unsigned compRetBuffArg; // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
7832 int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
7833 unsigned compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
7834 unsigned compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
7835 unsigned compLocalsCount; // Number of vars : args + locals (incl. implicit and hidden)
7836 unsigned compMaxStack;
7837 UNATIVE_OFFSET compTotalHotCodeSize; // Total number of bytes of Hot Code in the method
7838 UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method
7840 unsigned compCallUnmanaged; // count of unmanaged calls
7841 unsigned compLvFrameListRoot; // lclNum for the Frame root
7842 unsigned compXcptnsCount; // Number of exception-handling clauses read in the method's IL.
7843 // You should generally use compHndBBtabCount instead: it is the
7844 // current number of EH clauses (after additions like synchronized
7845 // methods and funclets, and removals like unreachable code deletion).
7847 bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
7848 // and the VM expects that, or the JIT is a "self-host" compiler
7849 // (e.g., x86 hosted targeting x86) and the VM expects that.
7851 #if defined(DEBUGGING_SUPPORT) || defined(DEBUG)
7853 /* The following holds IL scope information about local variables.
7856 unsigned compVarScopesCount;
7857 VarScopeDsc* compVarScopes;
7859 /* The following holds information about instr offsets for
7860 * which we need to report IP-mappings
7863 IL_OFFSET* compStmtOffsets; // sorted
7864 unsigned compStmtOffsetsCount;
7865 ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
7867 #endif // DEBUGGING_SUPPORT || DEBUG
7869 #define CPU_X86 0x0100 // The generic X86 CPU
7870 #define CPU_X86_PENTIUM_4 0x0110
7872 #define CPU_X64 0x0200 // The generic x64 CPU
7873 #define CPU_AMD_X64 0x0210 // AMD x64 CPU
7874 #define CPU_INTEL_X64 0x0240 // Intel x64 CPU
7876 #define CPU_ARM 0x0300 // The generic ARM CPU
7878 unsigned genCPU; // What CPU are we running on
7881 // Returns true if the method being compiled returns a non-void and non-struct value.
7882 // Note that lvaInitTypeRef() normalizes compRetNativeType for struct returns in a
7883 // single register as per target arch ABI (e.g on Amd64 Windows structs of size 1, 2,
7884 // 4 or 8 gets normalized to TYP_BYTE/TYP_SHORT/TYP_INT/TYP_LONG; On Arm HFA structs).
7885 // Methods returning such structs are considered to return non-struct return value and
7886 // this method returns true in that case.
7887 bool compMethodReturnsNativeScalarType()
7889 return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
7892 // Returns true if the method being compiled returns RetBuf addr as its return value
7893 bool compMethodReturnsRetBufAddr()
7895 // There are cases where implicit RetBuf argument should be explicitly returned in a register.
7896 // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
7898 // 1. Profiler Leave calllback expects the address of retbuf as return value for
7899 // methods with hidden RetBuf argument. impReturnInstruction() when profiler
7900 // callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
7901 // methods with hidden RetBufArg.
7903 // 2. As per the System V ABI, the address of RetBuf needs to be returned by
7904 // methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
7905 // returning the address of RetBuf.
7907 // 3. Windows 64-bit native calling convention also requires the address of RetBuff
7908 // to be returned in RAX.
7909 CLANG_FORMAT_COMMENT_ANCHOR;
7911 #ifdef _TARGET_AMD64_
7912 return (info.compRetBuffArg != BAD_VAR_NUM);
7913 #else // !_TARGET_AMD64_
7914 return (compIsProfilerHookNeeded()) && (info.compRetBuffArg != BAD_VAR_NUM);
7915 #endif // !_TARGET_AMD64_
7918 // Returns true if the method returns a value in more than one return register
7919 // TODO-ARM-Bug: Deal with multi-register genReturnLocaled structs?
7920 // TODO-ARM64: Does this apply for ARM64 too?
7921 bool compMethodReturnsMultiRegRetType()
7923 #if FEATURE_MULTIREG_RET
7924 #if defined(_TARGET_X86_)
7925 // On x86 only 64-bit longs are returned in multiple registers
7926 return varTypeIsLong(info.compRetNativeType);
7927 #else // targets: X64-UNIX, ARM64 or ARM32
7928 // On all other targets that support multireg return values:
7929 // Methods returning a struct in multiple registers have a return value of TYP_STRUCT.
7930 // Such method's compRetNativeType is TYP_STRUCT without a hidden RetBufArg
7931 return varTypeIsStruct(info.compRetNativeType) && (info.compRetBuffArg == BAD_VAR_NUM);
7932 #endif // TARGET_XXX
7933 #else // not FEATURE_MULTIREG_RET
7934 // For this architecture there are no multireg returns
7936 #endif // FEATURE_MULTIREG_RET
7939 #if FEATURE_MULTIREG_ARGS
7940 // Given a GenTree node of TYP_STRUCT that represents a pass by value argument
7941 // return the gcPtr layout for the pointers sized fields
7942 void getStructGcPtrsFromOp(GenTreePtr op, BYTE* gcPtrsOut);
7943 #endif // FEATURE_MULTIREG_ARGS
7945 // Returns true if the method being compiled returns a value
7946 bool compMethodHasRetVal()
7948 return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
7949 compMethodReturnsMultiRegRetType();
7954 void compDispLocalVars();
7956 #endif // DEBUGGING_SUPPORT || DEBUG
7958 //-------------------------- Global Compiler Data ------------------------------------
7961 static unsigned s_compMethodsCount; // to produce unique label names
7962 unsigned compGenTreeID;
7965 BasicBlock* compCurBB; // the current basic block in process
7966 GenTreePtr compCurStmt; // the current statement in process
7968 unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
7971 // The following is used to create the 'method JIT info' block.
7972 size_t compInfoBlkSize;
7973 BYTE* compInfoBlkAddr;
7975 EHblkDsc* compHndBBtab; // array of EH data
7976 unsigned compHndBBtabCount; // element count of used elements in EH data array
7977 unsigned compHndBBtabAllocCount; // element count of allocated elements in EH data array
7979 #if defined(_TARGET_X86_)
7981 //-------------------------------------------------------------------------
7982 // Tracking of region covered by the monitor in synchronized methods
7983 void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
7984 void* syncEndEmitCookie; // the emitter cookie for first instruction after the call to MON_EXIT
7986 #endif // !_TARGET_X86_
7988 Phases previousCompletedPhase; // the most recently completed phase
7990 //-------------------------------------------------------------------------
7991 // The following keeps track of how many bytes of local frame space we've
7992 // grabbed so far in the current function, and how many argument bytes we
7993 // need to pop when we return.
7996 unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
7998 // Count of callee-saved regs we pushed in the prolog.
7999 // Does not include EBP for isFramePointerUsed() and double-aligned frames.
8000 // In case of Amd64 this doesn't include float regs saved on stack.
8001 unsigned compCalleeRegsPushed;
8003 #if defined(_TARGET_XARCH_) && !FEATURE_STACK_FP_X87
8004 // Mask of callee saved float regs on stack.
8005 regMaskTP compCalleeFPRegsSavedMask;
8007 #ifdef _TARGET_AMD64_
8008 // Quirk for VS debug-launch scenario to work:
8009 // Bytes of padding between save-reg area and locals.
8010 #define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
8011 unsigned compVSQuirkStackPaddingNeeded;
8012 bool compQuirkForPPPflag;
8015 unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
8017 unsigned compMapILargNum(unsigned ILargNum); // map accounting for hidden args
8018 unsigned compMapILvarNum(unsigned ILvarNum); // map accounting for hidden args
8019 unsigned compMap2ILvarNum(unsigned varNum); // map accounting for hidden args
8021 //-------------------------------------------------------------------------
8023 static void compStartup(); // One-time initialization
8024 static void compShutdown(); // One-time finalization
8026 void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8029 static void compDisplayStaticSizes(FILE* fout);
8031 //------------ Some utility functions --------------
8033 void* compGetHelperFtn(CorInfoHelpFunc ftnNum, /* IN */
8034 void** ppIndirection); /* OUT */
8036 // Several JIT/EE interface functions return a CorInfoType, and also return a
8037 // class handle as an out parameter if the type is a value class. Returns the
8038 // size of the type these describe.
8039 unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);
8042 // Components used by the compiler may write unit test suites, and
8043 // have them run within this method. They will be run only once per process, and only
8044 // in debug. (Perhaps should be under the control of a COMPlus_ flag.)
8045 // These should fail by asserting.
8046 void compDoComponentUnitTestsOnce();
8049 int compCompile(CORINFO_METHOD_HANDLE methodHnd,
8050 CORINFO_MODULE_HANDLE classPtr,
8051 COMP_HANDLE compHnd,
8052 CORINFO_METHOD_INFO* methodInfo,
8053 void** methodCodePtr,
8054 ULONG* methodCodeSize,
8055 CORJIT_FLAGS* compileFlags);
8056 void compCompileFinish();
8057 int compCompileHelper(CORINFO_MODULE_HANDLE classPtr,
8058 COMP_HANDLE compHnd,
8059 CORINFO_METHOD_INFO* methodInfo,
8060 void** methodCodePtr,
8061 ULONG* methodCodeSize,
8062 CORJIT_FLAGS* compileFlags,
8063 CorInfoInstantiationVerification instVerInfo);
8065 ArenaAllocator* compGetAllocator();
8067 #if MEASURE_MEM_ALLOC
8070 unsigned allocCnt; // # of allocs
8071 UINT64 allocSz; // total size of those alloc.
8072 UINT64 allocSzMax; // Maximum single allocation.
8073 UINT64 allocSzByKind[CMK_Count]; // Classified by "kind".
8074 UINT64 nraTotalSizeAlloc;
8075 UINT64 nraTotalSizeUsed;
8077 static const char* s_CompMemKindNames[]; // Names of the kinds.
8079 MemStats() : allocCnt(0), allocSz(0), allocSzMax(0), nraTotalSizeAlloc(0), nraTotalSizeUsed(0)
8081 for (int i = 0; i < CMK_Count; i++)
8083 allocSzByKind[i] = 0;
8086 MemStats(const MemStats& ms)
8087 : allocCnt(ms.allocCnt)
8088 , allocSz(ms.allocSz)
8089 , allocSzMax(ms.allocSzMax)
8090 , nraTotalSizeAlloc(ms.nraTotalSizeAlloc)
8091 , nraTotalSizeUsed(ms.nraTotalSizeUsed)
8093 for (int i = 0; i < CMK_Count; i++)
8095 allocSzByKind[i] = ms.allocSzByKind[i];
8099 // Until we have ubiquitous constructors.
8102 this->MemStats::MemStats();
8105 void AddAlloc(size_t sz, CompMemKind cmk)
8109 if (sz > allocSzMax)
8113 allocSzByKind[cmk] += sz;
8116 void Print(FILE* f); // Print these stats to f.
8117 void PrintByKind(FILE* f); // Do just the by-kind histogram part.
8119 MemStats genMemStats;
8121 struct AggregateMemStats : public MemStats
8125 AggregateMemStats() : MemStats(), nMethods(0)
8129 void Add(const MemStats& ms)
8132 allocCnt += ms.allocCnt;
8133 allocSz += ms.allocSz;
8134 allocSzMax = max(allocSzMax, ms.allocSzMax);
8135 for (int i = 0; i < CMK_Count; i++)
8137 allocSzByKind[i] += ms.allocSzByKind[i];
8139 nraTotalSizeAlloc += ms.nraTotalSizeAlloc;
8140 nraTotalSizeUsed += ms.nraTotalSizeUsed;
8143 void Print(FILE* f); // Print these stats to jitstdout.
8146 static CritSecObject s_memStatsLock; // This lock protects the data structures below.
8147 static MemStats s_maxCompMemStats; // Stats for the compilation with the largest amount allocated.
8148 static AggregateMemStats s_aggMemStats; // Aggregates statistics for all compilations.
8150 #endif // MEASURE_MEM_ALLOC
8152 #if LOOP_HOIST_STATS
8153 unsigned m_loopsConsidered;
8154 bool m_curLoopHasHoistedExpression;
8155 unsigned m_loopsWithHoistedExpressions;
8156 unsigned m_totalHoistedExpressions;
8158 void AddLoopHoistStats();
8159 void PrintPerMethodLoopHoistStats();
8161 static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
8162 static unsigned s_loopsConsidered;
8163 static unsigned s_loopsWithHoistedExpressions;
8164 static unsigned s_totalHoistedExpressions;
8166 static void PrintAggregateLoopHoistStats(FILE* f);
8167 #endif // LOOP_HOIST_STATS
8169 void* compGetMemArray(size_t numElem, size_t elemSize, CompMemKind cmk = CMK_Unknown);
8170 void* compGetMemArrayA(size_t numElem, size_t elemSize, CompMemKind cmk = CMK_Unknown);
8171 void* compGetMem(size_t sz, CompMemKind cmk = CMK_Unknown);
8172 void* compGetMemA(size_t sz, CompMemKind cmk = CMK_Unknown);
8173 static void* compGetMemCallback(void*, size_t, CompMemKind cmk = CMK_Unknown);
8174 void compFreeMem(void*);
8176 bool compIsForImportOnly();
8177 bool compIsForInlining();
8178 bool compDonotInline();
8181 const char* compLocalVarName(unsigned varNum, unsigned offs);
8182 VarName compVarName(regNumber reg, bool isFloatReg = false);
8183 const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);
8184 const char* compRegPairName(regPairNo regPair);
8185 const char* compRegNameForSize(regNumber reg, size_t size);
8186 const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
8187 void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
8188 void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
8191 //-------------------------------------------------------------------------
8193 #ifdef DEBUGGING_SUPPORT
8194 typedef ListNode<VarScopeDsc*> VarScopeListNode;
8196 struct VarScopeMapInfo
8198 VarScopeListNode* head;
8199 VarScopeListNode* tail;
8200 static VarScopeMapInfo* Create(VarScopeListNode* node, IAllocator* alloc)
8202 VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
8209 // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
8210 static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;
8212 typedef SimplerHashTable<unsigned, SmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*, JitSimplerHashBehavior>
8213 VarNumToScopeDscMap;
8215 // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
8216 VarNumToScopeDscMap* compVarScopeMap;
8218 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
8220 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
8222 VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
8224 void compInitVarScopeMap();
8226 VarScopeDsc** compEnterScopeList; // List has the offsets where variables
8227 // enter scope, sorted by instr offset
8228 unsigned compNextEnterScope;
8230 VarScopeDsc** compExitScopeList; // List has the offsets where variables
8231 // go out of scope, sorted by instr offset
8232 unsigned compNextExitScope;
8234 void compInitScopeLists();
8236 void compResetScopeLists();
8238 VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
8240 VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
8242 void compProcessScopesUntil(unsigned offset,
8244 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
8245 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
8248 void compDispScopeLists();
8251 #endif // DEBUGGING_SUPPORT
8253 bool compIsProfilerHookNeeded();
8255 //-------------------------------------------------------------------------
8256 /* Statistical Data Gathering */
8258 void compJitStats(); // call this function and enable
8259 // various ifdef's below for statistical data
8262 void compCallArgStats();
8263 static void compDispCallArgStats(FILE* fout);
8266 //-------------------------------------------------------------------------
8273 ArenaAllocator* compAllocator;
8276 // This one presents an implementation of the "IAllocator" abstract class that uses "compAllocator",
8277 // suitable for use by utilcode collection types.
8278 IAllocator* compAsIAllocator;
8280 #if MEASURE_MEM_ALLOC
8281 IAllocator* compAsIAllocatorBitset; // An allocator that uses the CMK_bitset tracker.
8282 IAllocator* compAsIAllocatorGC; // An allocator that uses the CMK_GC tracker.
8283 IAllocator* compAsIAllocatorLoopHoist; // An allocator that uses the CMK_LoopHoist tracker.
8285 IAllocator* compAsIAllocatorDebugOnly; // An allocator that uses the CMK_DebugOnly tracker.
8287 #endif // MEASURE_MEM_ALLOC
8289 void compFunctionTraceStart();
8290 void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
8293 size_t compMaxUncheckedOffsetForNullObject;
8295 void compInitOptions(CORJIT_FLAGS* compileFlags);
8297 void compSetProcessor();
8298 void compInitDebuggingInfo();
8299 void compSetOptimizationLevel();
8300 #ifdef _TARGET_ARMARCH_
8301 bool compRsvdRegCheck(FrameLayoutState curState);
8303 void compCompile(void** methodCodePtr, ULONG* methodCodeSize, CORJIT_FLAGS* compileFlags);
8305 // Data required for generating profiler Enter/Leave/TailCall hooks
8306 CLANG_FORMAT_COMMENT_ANCHOR;
8308 #ifdef PROFILING_SUPPORTED
8309 bool compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
8310 void* compProfilerMethHnd; // Profiler handle of the method being compiled. Passed as param to ELT callbacks
8311 bool compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
8313 #ifdef _TARGET_AMD64_
8314 bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
8317 // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
8318 static void ProcessShutdownWork(ICorStaticInfo* statInfo);
8320 IAllocator* getAllocator()
8322 return compAsIAllocator;
8325 #if MEASURE_MEM_ALLOC
8326 IAllocator* getAllocatorBitset()
8328 return compAsIAllocatorBitset;
8330 IAllocator* getAllocatorGC()
8332 return compAsIAllocatorGC;
8334 IAllocator* getAllocatorLoopHoist()
8336 return compAsIAllocatorLoopHoist;
8338 #else // !MEASURE_MEM_ALLOC
8339 IAllocator* getAllocatorBitset()
8341 return compAsIAllocator;
8343 IAllocator* getAllocatorGC()
8345 return compAsIAllocator;
8347 IAllocator* getAllocatorLoopHoist()
8349 return compAsIAllocator;
8351 #endif // !MEASURE_MEM_ALLOC
8354 IAllocator* getAllocatorDebugOnly()
8356 #if MEASURE_MEM_ALLOC
8357 return compAsIAllocatorDebugOnly;
8358 #else // !MEASURE_MEM_ALLOC
8359 return compAsIAllocator;
8360 #endif // !MEASURE_MEM_ALLOC
8365 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8366 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8370 XX Checks for type compatibility and merges types XX
8372 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8373 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8377 // Set to TRUE if verification cannot be skipped for this method
8378 // If we detect unverifiable code, we will lazily check
8379 // canSkipMethodVerification() to see if verification is REALLY needed.
8380 BOOL tiVerificationNeeded;
8382 // It it initially TRUE, and it gets set to FALSE if we run into unverifiable code
8383 // Note that this is valid only if tiVerificationNeeded was ever TRUE.
8384 BOOL tiIsVerifiableCode;
8386 // Set to TRUE if runtime callout is needed for this method
8387 BOOL tiRuntimeCalloutNeeded;
8389 // Set to TRUE if security prolog/epilog callout is needed for this method
8390 // Note: This flag is different than compNeedSecurityCheck.
8391 // compNeedSecurityCheck means whether or not a security object needs
8392 // to be allocated on the stack, which is currently true for EnC as well.
8393 // tiSecurityCalloutNeeded means whether or not security callouts need
8394 // to be inserted in the jitted code.
8395 BOOL tiSecurityCalloutNeeded;
8397 // Returns TRUE if child is equal to or a subtype of parent for merge purposes
8398 // This support is necessary to suport attributes that are not described in
8399 // for example, signatures. For example, the permanent home byref (byref that
8400 // points to the gc heap), isn't a property of method signatures, therefore,
8401 // it is safe to have mismatches here (that tiCompatibleWith will not flag),
8402 // but when deciding if we need to reimport a block, we need to take these
8404 BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
8406 // Returns TRUE if child is equal to or a subtype of parent.
8407 // normalisedForStack indicates that both types are normalised for the stack
8408 BOOL tiCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
8410 // Merges pDest and pSrc. Returns FALSE if merge is undefined.
8411 // *pDest is modified to represent the merged type. Sets "*changed" to true
8412 // if this changes "*pDest".
8413 BOOL tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const;
8415 // Set pDest from the primitive value type.
8416 // Eg. System.Int32 -> ELEMENT_TYPE_I4
8418 BOOL tiFromPrimitiveValueClass(typeInfo* pDest, const typeInfo* pVC) const;
8421 // <BUGNUM> VSW 471305
8422 // IJW allows assigning REF to BYREF. The following allows us to temporarily
8423 // bypass the assert check in gcMarkRegSetGCref and gcMarkRegSetByref
8424 // We use a "short" as we need to push/pop this scope.
8426 short compRegSetCheckLevel;
8430 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8431 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8433 XX IL verification stuff XX
8436 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8437 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8441 // The following is used to track liveness of local variables, initialization
8442 // of valueclass constructors, and type safe use of IL instructions.
8444 // dynamic state info needed for verification
8445 EntryState verCurrentState;
8447 // this ptr of object type .ctors are considered intited only after
8448 // the base class ctor is called, or an alternate ctor is called.
8449 // An uninited this ptr can be used to access fields, but cannot
8450 // be used to call a member function.
8451 BOOL verTrackObjCtorInitState;
8453 void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
8455 // Requires that "tis" is not TIS_Bottom -- it's a definite init/uninit state.
8456 void verSetThisInit(BasicBlock* block, ThisInitState tis);
8457 void verInitCurrentState();
8458 void verResetCurrentState(BasicBlock* block, EntryState* currentState);
8460 // Merges the current verification state into the entry state of "block", return FALSE if that merge fails,
8461 // TRUE if it succeeds. Further sets "*changed" to true if this changes the entry state of "block".
8462 BOOL verMergeEntryStates(BasicBlock* block, bool* changed);
8464 void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
8465 void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
8466 typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd,
8467 bool bashStructToRef = false); // converts from jit type representation to typeInfo
8468 typeInfo verMakeTypeInfo(CorInfoType ciType,
8469 CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
8470 BOOL verIsSDArray(typeInfo ti);
8471 typeInfo verGetArrayElemType(typeInfo ti);
8473 typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
8474 BOOL verNeedsVerification();
8475 BOOL verIsByRefLike(const typeInfo& ti);
8476 BOOL verIsSafeToReturnByRef(const typeInfo& ti);
8478 // generic type variables range over types that satisfy IsBoxable
8479 BOOL verIsBoxable(const typeInfo& ti);
8481 void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
8482 DEBUGARG(unsigned line));
8483 void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
8484 DEBUGARG(unsigned line));
8485 bool verCheckTailCallConstraint(OPCODE opcode,
8486 CORINFO_RESOLVED_TOKEN* pResolvedToken,
8487 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call
8488 // on a type parameter?
8489 bool speculative // If true, won't throw if verificatoin fails. Instead it will
8490 // return false to the caller.
8491 // If false, it will throw.
8493 bool verIsBoxedValueType(typeInfo ti);
8495 void verVerifyCall(OPCODE opcode,
8496 CORINFO_RESOLVED_TOKEN* pResolvedToken,
8497 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
8499 bool readonlyCall, // is this a "readonly." call?
8500 const BYTE* delegateCreateStart,
8501 const BYTE* codeAddr,
8502 CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName));
8504 BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
8506 typeInfo verVerifySTIND(const typeInfo& ptr, const typeInfo& value, const typeInfo& instrType);
8507 typeInfo verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType);
8508 void verVerifyField(CORINFO_RESOLVED_TOKEN* pResolvedToken,
8509 const CORINFO_FIELD_INFO& fieldInfo,
8510 const typeInfo* tiThis,
8512 BOOL allowPlainStructAsThis = FALSE);
8513 void verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode);
8514 void verVerifyThisPtrInitialised();
8515 BOOL verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target);
8517 // Register allocator
8518 void raInitStackFP();
8519 void raEnregisterVarsPrePassStackFP();
8520 void raSetRegLclBirthDeath(GenTreePtr tree, VARSET_VALARG_TP lastlife, bool fromLDOBJ);
8521 void raEnregisterVarsPostPassStackFP();
8522 void raGenerateFPRefCounts();
8523 void raEnregisterVarsStackFP();
8524 void raUpdateHeightsForVarsStackFP(VARSET_VALARG_TP mask);
8526 regNumber raRegForVarStackFP(unsigned varTrackedIndex);
8527 void raAddPayloadStackFP(VARSET_VALARG_TP mask, unsigned weight);
8529 // returns true if enregistering v1 would save more mem accesses than v2
8530 bool raVarIsGreaterValueStackFP(LclVarDsc* lv1, LclVarDsc* lv2);
8533 void raDumpHeightsStackFP();
8534 void raDumpVariableRegIntfFloat();
8537 #if FEATURE_STACK_FP_X87
8539 // Currently, we use FP transition blocks in only 2 situations:
8541 // -conditional jump on longs where FP stack differs with target: it's not strictly
8542 // necessary, but its low frequency and the code would get complicated if we try to
8543 // inline the FP stack adjustment, as we have a lot of special casing going on to try
8544 // minimize the way we generate the jump code.
8545 // -case statements of switch where the FP stack differs with the one of evaluating the switch () statement
8546 // We do this as we want to codegen switch as a jumptable. Again, this is low frequency.
8548 // However, transition blocks have 2 problems
8550 // - Procedure splitting: current implementation of procedure splitting requires all basic blocks to
8551 // be known at codegen time, as it generates all hot blocks first and cold blocks later. This ties
8552 // us up in codegen and is a solvable problem (we could make procedure splitting generate blocks
8553 // in the right place without preordering them), this causes us to have to generate the transition
8554 // blocks in the cold area if we want procedure splitting.
8557 // - Thread abort exceptions and transition blocks. Transition blocks were designed under the assumption
8558 // that no exceptions can happen inside them. Unfortunately Thread.Abort can happen in any instruction,
8559 // and if we have handlers we will have to try to call them. Fixing this the right way would imply
8560 // having multiple try native code regions for a single try il region. This is doable and shouldnt be
8561 // a big change in the exception.
8563 // Given the low frequency of the cases where we have transition blocks, I've decided to dumb down
8564 // optimizations. For these 2 cases:
8566 // - When there is a chance that we will have FP transition blocks, we won't do procedure splitting.
8567 // - When a method has a handler, it won't enregister any FP variables that go thru a conditional long or
8568 // a switch statement.
8570 // If at any point we find we need to optimize this, we should throw work at unblocking the restrictions our
8571 // current procedure splitting and exception code have.
8572 bool compMayHaveTransitionBlocks;
8574 VARSET_TP raMaskDontEnregFloat; // mask for additional restrictions
8576 VARSET_TP raLclRegIntfFloat[REG_FPCOUNT];
8578 unsigned raCntStkStackFP;
8579 unsigned raCntWtdStkDblStackFP;
8580 unsigned raCntStkParamDblStackFP;
8582 // Payload in mem accesses for enregistering a variable (we dont want to mix with refcounts)
8583 // TODO: Do we want to put this in LclVarDsc?
8584 unsigned raPayloadStackFP[lclMAX_TRACKED];
8585 unsigned raHeightsStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
8587 // Useful for debugging
8588 unsigned raHeightsNonWeightedStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
8590 #endif // FEATURE_STACK_FP_X87
8593 // One line log function. Default level is 0. Increasing it gives you
8594 // more log information
8596 // levels are currently unused: #define JITDUMP(level,...) ();
8597 void JitLogEE(unsigned level, const char* fmt, ...);
8599 bool compDebugBreak;
8601 bool compJitHaltMethod();
8606 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8607 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8609 XX GS Security checks for unsafe buffers XX
8611 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8612 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8615 struct ShadowParamVarInfo
8617 FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
8618 unsigned shadowCopy; // Lcl var num, valid only if not set to NO_SHADOW_COPY
8620 static bool mayNeedShadowCopy(LclVarDsc* varDsc)
8622 #if defined(_TARGET_AMD64_) && !defined(LEGACY_BACKEND)
8623 // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
8624 // slots and update all trees to refer to shadow slots is done immediately after
8625 // fgMorph(). Lsra could potentially mark a param as DoNotEnregister after JIT determines
8626 // not to shadow a parameter. Also, LSRA could potentially spill a param which is passed
8627 // in register. Therefore, conservatively all params may need a shadow copy. Note that
8628 // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
8629 // creating a shadow slot even though this routine returns true.
8631 // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
8632 // required. There are two cases under which a reg arg could potentially be used from its
8634 // a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
8635 // b) LSRA spills it
8637 // Possible solution to address case (a)
8638 // - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
8639 // in this routine. Note that live out of exception handler is something we may not be
8640 // able to do it here since GS cookie logic is invoked ahead of liveness computation.
8641 // Therefore, for methods with exception handling and need GS cookie check we might have
8642 // to take conservative approach.
8644 // Possible solution to address case (b)
8645 // - Whenver a parameter passed in an argument register needs to be spilled by LSRA, we
8646 // create a new spill temp if the method needs GS cookie check.
8647 return varDsc->lvIsParam;
8648 #else // !(defined(_TARGET_AMD64_) && defined(LEGACY_BACKEND))
8649 return varDsc->lvIsParam && !varDsc->lvIsRegArg;
8656 printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
8661 GSCookie* gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
8662 GSCookie gsGlobalSecurityCookieVal; // Value of global cookie if addr is NULL
8663 ShadowParamVarInfo* gsShadowVarInfo; // Table used by shadow param analysis code
8665 void gsGSChecksInitCookie(); // Grabs cookie variable
8666 void gsCopyShadowParams(); // Identify vulnerable params and create dhadow copies
8667 bool gsFindVulnerableParams(); // Shadow param analysis code
8668 void gsParamsToShadows(); // Insert copy code and replave param uses by shadow
8670 static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
8671 static fgWalkPreFn gsReplaceShadowParams; // Shadow param replacement tree-walk
8673 #define DEFAULT_MAX_INLINE_SIZE 100 // Methods with > DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
8674 // This can be overwritten by setting complus_JITInlineSize env variable.
8676 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
8679 #ifdef FEATURE_JIT_METHOD_PERF
8680 JitTimer* pCompJitTimer; // Timer data structure (by phases) for current compilation.
8681 static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.
8683 static LPCWSTR JitTimeLogCsv(); // Retrieve the file name for CSV from ConfigDWORD.
8684 static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
8686 inline void EndPhase(Phases phase); // Indicate the end of the given phase.
8688 #if defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
8689 // These variables are associated with maintaining SQM data about compile time.
8690 unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
8691 // in the current compilation.
8692 unsigned __int64 m_compCycles; // Net cycle count for current compilation
8693 DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
8694 // the inlining phase in the current compilation.
8695 #endif // defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
8697 // Records the SQM-relevant (cycles and tick count). Should be called after inlining is complete.
8698 // (We do this after inlining because this marks the last point at which the JIT is likely to cause
8699 // type-loading and class initialization).
8700 void RecordStateAtEndOfInlining();
8701 // Assumes being called at the end of compilation. Update the SQM state.
8702 void RecordStateAtEndOfCompilation();
8704 #ifdef FEATURE_CLRSQM
8705 // Does anything SQM related necessary at process shutdown time.
8706 static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
8707 #endif // FEATURE_CLRSQM
8710 #if FUNC_INFO_LOGGING
8711 static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
8712 // filename to write it to.
8713 static FILE* compJitFuncInfoFile; // And this is the actual FILE* to write to.
8714 #endif // FUNC_INFO_LOGGING
8716 Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
8718 // Is the compilation in a full trust context?
8719 bool compIsFullTrust();
8721 #ifndef FEATURE_TRACELOGGING
8722 // Should we actually fire the noway assert body and the exception handler?
8723 bool compShouldThrowOnNoway();
8724 #else // FEATURE_TRACELOGGING
8725 // Should we actually fire the noway assert body and the exception handler?
8726 bool compShouldThrowOnNoway(const char* filename, unsigned line);
8728 // Telemetry instance to use per method compilation.
8729 JitTelemetry compJitTelemetry;
8731 // Get common parameters that have to be logged with most telemetry data.
8732 void compGetTelemetryDefaults(const char** assemblyName,
8733 const char** scopeName,
8734 const char** methodName,
8735 unsigned* methodHash);
8736 #endif // !FEATURE_TRACELOGGING
8740 NodeToTestDataMap* m_nodeTestData;
8742 static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
8743 unsigned m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
8744 // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
8745 // Current kept in this.
8747 NodeToTestDataMap* GetNodeTestData()
8749 Compiler* compRoot = impInlineRoot();
8750 if (compRoot->m_nodeTestData == nullptr)
8752 compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
8754 return compRoot->m_nodeTestData;
8757 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, int, JitSimplerHashBehavior> NodeToIntMap;
8759 // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
8760 // currently occur in the AST graph.
8761 NodeToIntMap* FindReachableNodesInNodeTestData();
8763 // Node "from" is being eliminated, and being replaced by node "to". If "from" had any associated
8764 // test data, associate that data with "to".
8765 void TransferTestDataToNode(GenTreePtr from, GenTreePtr to);
8767 // Requires that "to" is a clone of "from". If any nodes in the "from" tree
8768 // have annotations, attach similar annotations to the corresponding nodes in "to".
8769 void CopyTestDataToCloneTree(GenTreePtr from, GenTreePtr to);
8771 // These are the methods that test that the various conditions implied by the
8772 // test attributes are satisfied.
8773 void JitTestCheckSSA(); // SSA builder tests.
8774 void JitTestCheckVN(); // Value numbering tests.
8777 // The "FieldSeqStore", for canonicalizing field sequences. See the definition of FieldSeqStore for
8779 FieldSeqStore* m_fieldSeqStore;
8781 FieldSeqStore* GetFieldSeqStore()
8783 Compiler* compRoot = impInlineRoot();
8784 if (compRoot->m_fieldSeqStore == nullptr)
8786 // Create a CompAllocator that labels sub-structure with CMK_FieldSeqStore, and use that for allocation.
8787 IAllocator* ialloc = new (this, CMK_FieldSeqStore) CompAllocator(this, CMK_FieldSeqStore);
8788 compRoot->m_fieldSeqStore = new (ialloc) FieldSeqStore(ialloc);
8790 return compRoot->m_fieldSeqStore;
8793 typedef SimplerHashTable<GenTreePtr, PtrKeyFuncs<GenTree>, FieldSeqNode*, JitSimplerHashBehavior> NodeToFieldSeqMap;
8795 // Some nodes of "TYP_BYREF" or "TYP_I_IMPL" actually represent the address of a field within a struct, but since
8796 // the offset of the field is zero, there's no "GT_ADD" node. We normally attach a field sequence to the constant
8797 // that is added, but what do we do when that constant is zero, and is thus not present? We use this mechanism to
8798 // attach the field sequence directly to the address node.
8799 NodeToFieldSeqMap* m_zeroOffsetFieldMap;
8801 NodeToFieldSeqMap* GetZeroOffsetFieldMap()
8803 // Don't need to worry about inlining here
8804 if (m_zeroOffsetFieldMap == nullptr)
8806 // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
8808 IAllocator* ialloc = new (this, CMK_ZeroOffsetFieldMap) CompAllocator(this, CMK_ZeroOffsetFieldMap);
8809 m_zeroOffsetFieldMap = new (ialloc) NodeToFieldSeqMap(ialloc);
8811 return m_zeroOffsetFieldMap;
8814 // Requires that "op1" is a node of type "TYP_BYREF" or "TYP_I_IMPL". We are dereferencing this with the fields in
8815 // "fieldSeq", whose offsets are required all to be zero. Ensures that any field sequence annotation currently on
8816 // "op1" or its components is augmented by appending "fieldSeq". In practice, if "op1" is a GT_LCL_FLD, it has
8817 // a field sequence as a member; otherwise, it may be the addition of an a byref and a constant, where the const
8818 // has a field sequence -- in this case "fieldSeq" is appended to that of the constant; otherwise, we
8819 // record the the field sequence using the ZeroOffsetFieldMap described above.
8821 // One exception above is that "op1" is a node of type "TYP_REF" where "op1" is a GT_LCL_VAR.
8822 // This happens when System.Object vtable pointer is a regular field at offset 0 in System.Private.CoreLib in
8823 // CoreRT. Such case is handled same as the default case.
8824 void fgAddFieldSeqForZeroOffset(GenTreePtr op1, FieldSeqNode* fieldSeq);
8826 typedef SimplerHashTable<const GenTree*, PtrKeyFuncs<GenTree>, ArrayInfo, JitSimplerHashBehavior>
8828 NodeToArrayInfoMap* m_arrayInfoMap;
8830 NodeToArrayInfoMap* GetArrayInfoMap()
8832 Compiler* compRoot = impInlineRoot();
8833 if (compRoot->m_arrayInfoMap == nullptr)
8835 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
8836 IAllocator* ialloc = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
8837 compRoot->m_arrayInfoMap = new (ialloc) NodeToArrayInfoMap(ialloc);
8839 return compRoot->m_arrayInfoMap;
8842 NodeToUnsignedMap* m_heapSsaMap;
8844 // In some cases, we want to assign intermediate SSA #'s to heap states, and know what nodes create those heap
8845 // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the heap state,
8846 // all the possible heap states are possible initial states of the corresponding catch block(s).)
8847 NodeToUnsignedMap* GetHeapSsaMap()
8849 Compiler* compRoot = impInlineRoot();
8850 if (compRoot->m_heapSsaMap == nullptr)
8852 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
8853 IAllocator* ialloc = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
8854 compRoot->m_heapSsaMap = new (ialloc) NodeToUnsignedMap(ialloc);
8856 return compRoot->m_heapSsaMap;
8859 // The Refany type is the only struct type whose structure is implicitly assumed by IL. We need its fields.
8860 CORINFO_CLASS_HANDLE m_refAnyClass;
8861 CORINFO_FIELD_HANDLE GetRefanyDataField()
8863 if (m_refAnyClass == nullptr)
8865 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8867 return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
8869 CORINFO_FIELD_HANDLE GetRefanyTypeField()
8871 if (m_refAnyClass == nullptr)
8873 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
8875 return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
8879 static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
8881 #if ALLVARSET_COUNTOPS
8882 static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
8885 static HelperCallProperties s_helperCallProperties;
8887 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
8888 static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
8889 static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
8891 static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
8894 unsigned __int8* offset0,
8895 unsigned __int8* offset1);
8896 void fgMorphSystemVStructArgs(GenTreeCall* call, bool hasStructArgument);
8897 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
8899 void fgMorphMultiregStructArgs(GenTreeCall* call);
8900 GenTreePtr fgMorphMultiregStructArg(GenTreePtr arg, fgArgTabEntryPtr fgEntryPtr);
8902 }; // end of class Compiler
8904 // Inline methods of CompAllocator.
8905 void* CompAllocator::Alloc(size_t sz)
8907 #if MEASURE_MEM_ALLOC
8908 return m_comp->compGetMem(sz, m_cmk);
8910 return m_comp->compGetMem(sz);
8914 void* CompAllocator::ArrayAlloc(size_t elems, size_t elemSize)
8916 #if MEASURE_MEM_ALLOC
8917 return m_comp->compGetMemArray(elems, elemSize, m_cmk);
8919 return m_comp->compGetMemArray(elems, elemSize);
8923 // LclVarDsc constructor. Uses Compiler, so must come after Compiler definition.
8924 inline LclVarDsc::LclVarDsc(Compiler* comp)
8925 : // Initialize the ArgRegs to REG_STK.
8926 // The morph will do the right thing to change
8927 // to the right register if passed in register.
8930 #if FEATURE_MULTIREG_ARGS
8931 _lvOtherArgReg(REG_STK)
8933 #endif // FEATURE_MULTIREG_ARGS
8935 lvRefBlks(BlockSetOps::UninitVal())
8937 #endif // ASSERTION_PROP
8938 lvPerSsaData(comp->getAllocator())
8943 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8944 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8946 XX Miscellaneous Compiler stuff XX
8948 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8949 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8952 // Values used to mark the types a stack slot is used for
8954 const unsigned TYPE_REF_INT = 0x01; // slot used as a 32-bit int
8955 const unsigned TYPE_REF_LNG = 0x02; // slot used as a 64-bit long
8956 const unsigned TYPE_REF_FLT = 0x04; // slot used as a 32-bit float
8957 const unsigned TYPE_REF_DBL = 0x08; // slot used as a 64-bit float
8958 const unsigned TYPE_REF_PTR = 0x10; // slot used as a 32-bit pointer
8959 const unsigned TYPE_REF_BYR = 0x20; // slot used as a byref pointer
8960 const unsigned TYPE_REF_STC = 0x40; // slot used as a struct
8961 const unsigned TYPE_REF_TYPEMASK = 0x7F; // bits that represent the type
8963 // const unsigned TYPE_REF_ADDR_TAKEN = 0x80; // slots address was taken
8965 /*****************************************************************************
8967 * Variables to keep track of total code amounts.
8972 extern size_t grossVMsize;
8973 extern size_t grossNCsize;
8974 extern size_t totalNCsize;
8976 extern unsigned genMethodICnt;
8977 extern unsigned genMethodNCnt;
8978 extern size_t gcHeaderISize;
8979 extern size_t gcPtrMapISize;
8980 extern size_t gcHeaderNSize;
8981 extern size_t gcPtrMapNSize;
8983 #endif // DISPLAY_SIZES
8985 /*****************************************************************************
8987 * Variables to keep track of basic block counts (more data on 1 BB methods)
8990 #if COUNT_BASIC_BLOCKS
8991 extern Histogram bbCntTable;
8992 extern Histogram bbOneBBSizeTable;
8995 /*****************************************************************************
8997 * Used by optFindNaturalLoops to gather statistical information such as
8998 * - total number of natural loops
8999 * - number of loops with 1, 2, ... exit conditions
9000 * - number of loops that have an iterator (for like)
9001 * - number of loops that have a constant iterator
9006 extern unsigned totalLoopMethods; // counts the total number of methods that have natural loops
9007 extern unsigned maxLoopsPerMethod; // counts the maximum number of loops a method has
9008 extern unsigned totalLoopOverflows; // # of methods that identified more loops than we can represent
9009 extern unsigned totalLoopCount; // counts the total number of natural loops
9010 extern unsigned totalUnnatLoopCount; // counts the total number of (not-necessarily natural) loops
9011 extern unsigned totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
9012 extern unsigned iterLoopCount; // counts the # of loops with an iterator (for like)
9013 extern unsigned simpleTestLoopCount; // counts the # of loops with an iterator and a simple loop condition (iter <
9015 extern unsigned constIterLoopCount; // counts the # of loops with a constant iterator (for like)
9016 extern bool hasMethodLoops; // flag to keep track if we already counted a method as having loops
9017 extern unsigned loopsThisMethod; // counts the number of loops in the current method
9018 extern bool loopOverflowThisMethod; // True if we exceeded the max # of loops in the method.
9019 extern Histogram loopCountTable; // Histogram of loop counts
9020 extern Histogram loopExitCountTable; // Histogram of loop exit counts
9022 #endif // COUNT_LOOPS
9024 /*****************************************************************************
9025 * variables to keep track of how many iterations we go in a dataflow pass
9030 extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
9031 extern unsigned CFiterCount; // counts the # of iteration for the Const Folding dataflow
9033 #endif // DATAFLOW_ITER
9035 #if MEASURE_BLOCK_SIZE
9036 extern size_t genFlowNodeSize;
9037 extern size_t genFlowNodeCnt;
9038 #endif // MEASURE_BLOCK_SIZE
9040 #if MEASURE_NODE_SIZE
9041 struct NodeSizeStats
9046 genTreeNodeSize = 0;
9047 genTreeNodeActualSize = 0;
9050 size_t genTreeNodeCnt;
9051 size_t genTreeNodeSize; // The size we allocate
9052 size_t genTreeNodeActualSize; // The actual size of the node. Note that the actual size will likely be smaller
9053 // than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
9054 // a smaller node to a larger one. TODO-Cleanup: add stats on
9055 // SetOper()/ChangeOper() usage to quanitfy this.
9057 extern NodeSizeStats genNodeSizeStats; // Total node size stats
9058 extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
9059 extern Histogram genTreeNcntHist;
9060 extern Histogram genTreeNsizHist;
9061 #endif // MEASURE_NODE_SIZE
9063 /*****************************************************************************
9064 * Count fatal errors (including noway_asserts).
9068 extern unsigned fatal_badCode;
9069 extern unsigned fatal_noWay;
9070 extern unsigned fatal_NOMEM;
9071 extern unsigned fatal_noWayAssertBody;
9073 extern unsigned fatal_noWayAssertBodyArgs;
9075 extern unsigned fatal_NYI;
9076 #endif // MEASURE_FATAL
9078 /*****************************************************************************
9082 #ifdef _TARGET_XARCH_
9084 const instruction INS_SHIFT_LEFT_LOGICAL = INS_shl;
9085 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
9086 const instruction INS_SHIFT_RIGHT_ARITHM = INS_sar;
9088 const instruction INS_AND = INS_and;
9089 const instruction INS_OR = INS_or;
9090 const instruction INS_XOR = INS_xor;
9091 const instruction INS_NEG = INS_neg;
9092 const instruction INS_TEST = INS_test;
9093 const instruction INS_MUL = INS_imul;
9094 const instruction INS_SIGNED_DIVIDE = INS_idiv;
9095 const instruction INS_UNSIGNED_DIVIDE = INS_div;
9096 const instruction INS_BREAKPOINT = INS_int3;
9097 const instruction INS_ADDC = INS_adc;
9098 const instruction INS_SUBC = INS_sbb;
9099 const instruction INS_NOT = INS_not;
9105 const instruction INS_SHIFT_LEFT_LOGICAL = INS_lsl;
9106 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
9107 const instruction INS_SHIFT_RIGHT_ARITHM = INS_asr;
9109 const instruction INS_AND = INS_and;
9110 const instruction INS_OR = INS_orr;
9111 const instruction INS_XOR = INS_eor;
9112 const instruction INS_NEG = INS_rsb;
9113 const instruction INS_TEST = INS_tst;
9114 const instruction INS_MUL = INS_mul;
9115 const instruction INS_SIGNED_DIVIDE = INS_sdiv;
9116 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
9117 const instruction INS_BREAKPOINT = INS_bkpt;
9118 const instruction INS_ADDC = INS_adc;
9119 const instruction INS_SUBC = INS_sbc;
9120 const instruction INS_NOT = INS_mvn;
9124 #ifdef _TARGET_ARM64_
9126 const instruction INS_SHIFT_LEFT_LOGICAL = INS_lsl;
9127 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
9128 const instruction INS_SHIFT_RIGHT_ARITHM = INS_asr;
9130 const instruction INS_AND = INS_and;
9131 const instruction INS_OR = INS_orr;
9132 const instruction INS_XOR = INS_eor;
9133 const instruction INS_NEG = INS_neg;
9134 const instruction INS_TEST = INS_tst;
9135 const instruction INS_MUL = INS_mul;
9136 const instruction INS_SIGNED_DIVIDE = INS_sdiv;
9137 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
9138 const instruction INS_BREAKPOINT = INS_bkpt;
9139 const instruction INS_ADDC = INS_adc;
9140 const instruction INS_SUBC = INS_sbc;
9141 const instruction INS_NOT = INS_mvn;
9145 /*****************************************************************************/
9147 extern const BYTE genTypeSizes[];
9148 extern const BYTE genTypeAlignments[];
9149 extern const BYTE genTypeStSzs[];
9150 extern const BYTE genActualTypes[];
9152 /*****************************************************************************/
9154 // VERY_LARGE_FRAME_SIZE_REG_MASK is the set of registers we need to use for
9155 // the probing loop generated for very large stack frames (see `getVeryLargeFrameSize`).
9158 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R4 | RBM_R5 | RBM_R6)
9159 #elif defined(_TARGET_ARM64_)
9160 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R9 | RBM_R10 | RBM_R11)
9163 /*****************************************************************************/
9165 #define REG_CORRUPT regNumber(REG_NA + 1)
9166 #define RBM_CORRUPT (RBM_ILLEGAL | regMaskTP(1))
9167 #define REG_PAIR_CORRUPT regPairNo(REG_PAIR_NONE + 1)
9169 /*****************************************************************************/
9171 extern BasicBlock dummyBB;
9173 /*****************************************************************************/
9174 /*****************************************************************************/
9176 // foreach_treenode_execution_order: An iterator that iterates through all the tree
9177 // nodes of a statement in execution order.
9178 // __stmt: a GT_STMT type GenTree*
9179 // __node: a GenTree*, already declared, that gets updated with each node in the statement, in execution order
9181 #define foreach_treenode_execution_order(__node, __stmt) \
9182 for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
9184 // foreach_block: An iterator over all blocks in the function.
9185 // __compiler: the Compiler* object
9186 // __block : a BasicBlock*, already declared, that gets updated each iteration.
9188 #define foreach_block(__compiler, __block) \
9189 for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
9191 /*****************************************************************************/
9192 /*****************************************************************************/
9196 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
9198 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9199 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9201 XX Debugging helpers XX
9203 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9204 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9207 /*****************************************************************************/
9208 /* The following functions are intended to be called from the debugger, to dump
9209 * various data structures. The can be used in the debugger Watch or Quick Watch
9210 * windows. They are designed to be short to type and take as few arguments as
9211 * possible. The 'c' versions take a Compiler*, whereas the 'd' versions use the TlsCompiler.
9212 * See the function definition comment for more details.
9215 void cBlock(Compiler* comp, BasicBlock* block);
9216 void cBlocks(Compiler* comp);
9217 void cBlocksV(Compiler* comp);
9218 void cTree(Compiler* comp, GenTree* tree);
9219 void cTrees(Compiler* comp);
9220 void cEH(Compiler* comp);
9221 void cVar(Compiler* comp, unsigned lclNum);
9222 void cVarDsc(Compiler* comp, LclVarDsc* varDsc);
9223 void cVars(Compiler* comp);
9224 void cVarsFinal(Compiler* comp);
9225 void cBlockPreds(Compiler* comp, BasicBlock* block);
9226 void cReach(Compiler* comp);
9227 void cDoms(Compiler* comp);
9228 void cLiveness(Compiler* comp);
9229 void cCVarSet(Compiler* comp, VARSET_VALARG_TP vars);
9231 void cFuncIR(Compiler* comp);
9232 void cBlockIR(Compiler* comp, BasicBlock* block);
9233 void cLoopIR(Compiler* comp, Compiler::LoopDsc* loop);
9234 void cTreeIR(Compiler* comp, GenTree* tree);
9235 int cTreeTypeIR(Compiler* comp, GenTree* tree);
9236 int cTreeKindsIR(Compiler* comp, GenTree* tree);
9237 int cTreeFlagsIR(Compiler* comp, GenTree* tree);
9238 int cOperandIR(Compiler* comp, GenTree* operand);
9239 int cLeafIR(Compiler* comp, GenTree* tree);
9240 int cIndirIR(Compiler* comp, GenTree* tree);
9241 int cListIR(Compiler* comp, GenTree* list);
9242 int cSsaNumIR(Compiler* comp, GenTree* tree);
9243 int cValNumIR(Compiler* comp, GenTree* tree);
9244 int cDependsIR(Compiler* comp, GenTree* comma, bool* first);
9246 void dBlock(BasicBlock* block);
9249 void dTree(GenTree* tree);
9252 void dVar(unsigned lclNum);
9253 void dVarDsc(LclVarDsc* varDsc);
9256 void dBlockPreds(BasicBlock* block);
9260 void dCVarSet(VARSET_VALARG_TP vars);
9262 void dVarSet(VARSET_VALARG_TP vars);
9263 void dRegMask(regMaskTP mask);
9266 void dBlockIR(BasicBlock* block);
9267 void dTreeIR(GenTree* tree);
9268 void dLoopIR(Compiler::LoopDsc* loop);
9269 void dLoopNumIR(unsigned loopNum);
9270 int dTabStopIR(int curr, int tabstop);
9271 int dTreeTypeIR(GenTree* tree);
9272 int dTreeKindsIR(GenTree* tree);
9273 int dTreeFlagsIR(GenTree* tree);
9274 int dOperandIR(GenTree* operand);
9275 int dLeafIR(GenTree* tree);
9276 int dIndirIR(GenTree* tree);
9277 int dListIR(GenTree* list);
9278 int dSsaNumIR(GenTree* tree);
9279 int dValNumIR(GenTree* tree);
9280 int dDependsIR(GenTree* comma);
9283 GenTree* dFindTree(GenTree* tree, unsigned id);
9284 GenTree* dFindTree(unsigned id);
9285 GenTreeStmt* dFindStmt(unsigned id);
9286 BasicBlock* dFindBlock(unsigned bbNum);
9290 #include "compiler.hpp" // All the shared inline functions
9292 /*****************************************************************************/
9293 #endif //_COMPILER_H_
9294 /*****************************************************************************/