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 /*****************************************************************************/
29 #include "jithashtable.h"
38 #include "cycletimer.h"
40 #include "arraystack.h"
42 #include "jitexpandarray.h"
43 #include "tinyarray.h"
46 #include "jittelemetry.h"
47 #include "namedintrinsiclist.h"
52 #include "codegeninterface.h"
54 #include "jitgcinfo.h"
56 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
62 #include "hwintrinsic.h"
65 // This is only used locally in the JIT to indicate that
66 // a verification block should be inserted
67 #define SEH_VERIFICATION_EXCEPTION 0xe0564552 // VER
69 /*****************************************************************************
70 * Forward declarations
73 struct InfoHdr; // defined in GCInfo.h
74 struct escapeMapping_t; // defined in flowgraph.cpp
75 class emitter; // defined in emit.h
76 struct ShadowParamVarInfo; // defined in GSChecks.cpp
77 struct InitVarDscInfo; // defined in register_arg_convention.h
78 class FgStack; // defined in flowgraph.cpp
80 class CSE_DataFlow; // defined in OptCSE.cpp
86 class Lowering; // defined in lower.h
88 // The following are defined in this file, Compiler.h
92 /*****************************************************************************
98 /*****************************************************************************/
101 // Declare global operator new overloads that use the compiler's arena allocator
104 // I wanted to make the second argument optional, with default = CMK_Unknown, but that
105 // caused these to be ambiguous with the global placement new operators.
106 void* __cdecl operator new(size_t n, Compiler* context, CompMemKind cmk);
107 void* __cdecl operator new[](size_t n, Compiler* context, CompMemKind cmk);
108 void* __cdecl operator new(size_t n, void* p, const jitstd::placement_t& syntax_difference);
110 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
111 #include "loopcloning.h"
113 /*****************************************************************************/
115 /* This is included here and not earlier as it needs the definition of "CSE"
116 * which is defined in the section above */
118 /*****************************************************************************/
120 unsigned genLog2(unsigned value);
121 unsigned genLog2(unsigned __int64 value);
123 var_types genActualType(var_types type);
124 var_types genUnsignedType(var_types type);
125 var_types genSignedType(var_types type);
127 unsigned ReinterpretHexAsDecimal(unsigned);
129 /*****************************************************************************/
131 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
134 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
137 // The following holds the Local var info (scope information)
138 typedef const char* VarName; // Actual ASCII string
141 IL_OFFSET vsdLifeBeg; // instr offset of beg of life
142 IL_OFFSET vsdLifeEnd; // instr offset of end of life
143 unsigned vsdVarNum; // (remapped) LclVarDsc number
146 VarName vsdName; // name of the var
149 unsigned vsdLVnum; // 'which' in eeGetLVinfo().
150 // Also, it is the index of this entry in the info.compVarScopes array,
151 // which is useful since the array is also accessed via the
152 // compEnterScopeList and compExitScopeList sorted arrays.
155 // This is the location of a SSA definition.
161 DefLoc() : m_blk(nullptr), m_tree(nullptr)
165 DefLoc(BasicBlock* block, GenTree* tree) : m_blk(block), m_tree(tree)
170 // This class stores information associated with a LclVar SSA definition.
178 LclSsaVarDsc(BasicBlock* block, GenTree* tree) : m_defLoc(block, tree)
182 ValueNumPair m_vnPair;
186 // This class stores information associated with a memory SSA definition.
190 ValueNumPair m_vnPair;
193 //------------------------------------------------------------------------
194 // SsaDefArray: A resizable array of SSA definitions.
196 // Unlike an ordinary resizable array implementation, this allows only element
197 // addition (by calling AllocSsaNum) and has special handling for RESERVED_SSA_NUM
198 // (basically it's a 1-based array). The array doesn't impose any particular
199 // requirements on the elements it stores and AllocSsaNum forwards its arguments
200 // to the array element constructor, this way the array supports both LclSsaVarDsc
201 // and SsaMemDef elements.
203 template <typename T>
207 unsigned m_arraySize;
210 static_assert_no_msg(SsaConfig::RESERVED_SSA_NUM == 0);
211 static_assert_no_msg(SsaConfig::FIRST_SSA_NUM == 1);
213 // Get the minimum valid SSA number.
214 unsigned GetMinSsaNum() const
216 return SsaConfig::FIRST_SSA_NUM;
219 // Increase (double) the size of the array.
220 void GrowArray(CompAllocator alloc)
222 unsigned oldSize = m_arraySize;
223 unsigned newSize = max(2, oldSize * 2);
225 T* newArray = alloc.allocate<T>(newSize);
227 for (unsigned i = 0; i < oldSize; i++)
229 newArray[i] = m_array[i];
233 m_arraySize = newSize;
237 // Construct an empty SsaDefArray.
238 SsaDefArray() : m_array(nullptr), m_arraySize(0), m_count(0)
242 // Reset the array (used only if the SSA form is reconstructed).
248 // Allocate a new SSA number (starting with SsaConfig::FIRST_SSA_NUM).
249 template <class... Args>
250 unsigned AllocSsaNum(CompAllocator alloc, Args&&... args)
252 if (m_count == m_arraySize)
257 unsigned ssaNum = GetMinSsaNum() + m_count;
258 m_array[m_count++] = T(jitstd::forward<Args>(args)...);
260 // Ensure that the first SSA number we allocate is SsaConfig::FIRST_SSA_NUM
261 assert((ssaNum == SsaConfig::FIRST_SSA_NUM) || (m_count > 1));
266 // Get the number of SSA definitions in the array.
267 unsigned GetCount() const
272 // Get a pointer to the SSA definition at the specified index.
273 T* GetSsaDefByIndex(unsigned index)
275 assert(index < m_count);
276 return &m_array[index];
279 // Check if the specified SSA number is valid.
280 bool IsValidSsaNum(unsigned ssaNum) const
282 return (GetMinSsaNum() <= ssaNum) && (ssaNum < (GetMinSsaNum() + m_count));
285 // Get a pointer to the SSA definition associated with the specified SSA number.
286 T* GetSsaDef(unsigned ssaNum)
288 assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
289 return GetSsaDefByIndex(ssaNum - GetMinSsaNum());
295 RCS_INVALID, // not valid to get/set ref counts
296 RCS_EARLY, // early counts for struct promotion and struct passing
297 RCS_NORMAL, // normal ref counts (from lvaMarkRefs onward)
303 // The constructor. Most things can just be zero'ed.
305 // Initialize the ArgRegs to REG_STK.
306 // Morph will update if this local is passed in a register.
310 #if FEATURE_MULTIREG_ARGS
311 _lvOtherArgReg(REG_STK)
313 #endif // FEATURE_MULTIREG_ARGS
315 lvRefBlks(BlockSetOps::UninitVal())
317 #endif // ASSERTION_PROP
322 // note this only packs because var_types is a typedef of unsigned char
323 var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF
325 unsigned char lvIsParam : 1; // is this a parameter?
326 unsigned char lvIsRegArg : 1; // is this a register argument?
327 unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)
329 unsigned char lvStructGcCount : 3; // if struct, how many GC pointer (stop counting at 7). The only use of values >1
330 // is to help determine whether to use block init in the prolog.
331 unsigned char lvOnFrame : 1; // (part of) the variable lives on the frame
332 unsigned char lvRegister : 1; // assigned to live in a register? For RyuJIT backend, this is only set if the
333 // variable is in the same register for the entire function.
334 unsigned char lvTracked : 1; // is this a tracked variable?
335 bool lvTrackedNonStruct()
337 return lvTracked && lvType != TYP_STRUCT;
339 unsigned char lvPinned : 1; // is this a pinned variable?
341 unsigned char lvMustInit : 1; // must be initialized
342 unsigned char lvAddrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
343 // global location, etc.
344 // We cannot reason reliably about the value of the variable.
345 unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
346 unsigned char lvFieldAccessed : 1; // The var is a struct local, and a field of the variable is accessed. Affects
349 unsigned char lvInSsa : 1; // The variable is in SSA form (set by SsaBuilder)
352 // These further document the reasons for setting "lvDoNotEnregister". (Note that "lvAddrExposed" is one of the
354 // also, lvType == TYP_STRUCT prevents enregistration. At least one of the reasons should be true.
355 unsigned char lvVMNeedsStackAddr : 1; // The VM may have access to a stack-relative address of the variable, and
356 // read/write its value.
357 unsigned char lvLiveInOutOfHndlr : 1; // The variable was live in or out of an exception handler, and this required
358 // the variable to be
359 // in the stack (at least at those boundaries.)
360 unsigned char lvLclFieldExpr : 1; // The variable is not a struct, but was accessed like one (e.g., reading a
361 // particular byte from an int).
362 unsigned char lvLclBlockOpAddr : 1; // The variable was written to via a block operation that took its address.
363 unsigned char lvLiveAcrossUCall : 1; // The variable is live across an unmanaged call.
365 unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable.
366 unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.
367 unsigned char lvStackByref : 1; // This is a compiler temporary of TYP_BYREF that is known to point into our local
370 unsigned char lvHasILStoreOp : 1; // there is at least one STLOC or STARG on this local
371 unsigned char lvHasMultipleILStoreOp : 1; // there is more than one STLOC on this local
373 unsigned char lvIsTemp : 1; // Short-lifetime compiler temp (if lvIsParam is false), or implicit byref parameter
374 // (if lvIsParam is true)
376 unsigned char lvIsBoolean : 1; // set if variable is boolean
378 unsigned char lvSingleDef : 1; // variable has a single def
379 // before lvaMarkLocalVars: identifies ref type locals that can get type updates
380 // after lvaMarkLocalVars: identifies locals that are suitable for optAddCopies
383 unsigned char lvDisqualify : 1; // variable is no longer OK for add copy optimization
384 unsigned char lvVolatileHint : 1; // hint for AssertionProp
387 #ifndef _TARGET_64BIT_
388 unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
389 #endif // !_TARGET_64BIT_
390 #ifdef _TARGET_64BIT_
391 unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
394 unsigned char lvKeepType : 1; // Don't change the type of this variable
395 unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
397 unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
399 unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
400 unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
401 // 32-bit target. For implicit byref parameters, this gets hijacked between
402 // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to indicate whether
403 // references to the arg are being rewritten as references to a promoted shadow local.
404 unsigned char lvIsStructField : 1; // Is this local var a field of a promoted struct local?
405 unsigned char lvOverlappingFields : 1; // True when we have a struct with possibly overlapping fields
406 unsigned char lvContainsHoles : 1; // True when we have a promoted struct that contains holes
407 unsigned char lvCustomLayout : 1; // True when this struct has "CustomLayout"
409 unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
410 unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call
413 unsigned char _lvIsHfa : 1; // Is this a struct variable who's class handle is an HFA type
414 unsigned char _lvIsHfaRegArg : 1; // Is this a HFA argument variable? // TODO-CLEANUP: Remove this and replace
415 // with (lvIsRegArg && lvIsHfa())
416 unsigned char _lvHfaTypeIsFloat : 1; // Is the HFA type float or double?
417 #endif // FEATURE_HFA
420 // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
421 // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
422 // Consider cleaning this up so this workaround is not required.
423 unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
424 // I.e. there is no longer any reference to the struct directly.
425 // In this case we can simply remove this struct local.
428 unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
431 // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
432 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
433 unsigned char lvSIMDType : 1; // This is a SIMD struct
434 unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
435 var_types lvBaseType : 5; // Note: this only packs because var_types is a typedef of unsigned char
436 #endif // FEATURE_SIMD
437 unsigned char lvRegStruct : 1; // This is a reg-sized non-field-addressed struct.
439 unsigned char lvClassIsExact : 1; // lvClassHandle is the exact type
442 unsigned char lvClassInfoUpdated : 1; // true if this var has updated class handle or exactness
445 unsigned char lvImplicitlyReferenced : 1; // true if there are non-IR references to this local (prolog, epilog, gc,
449 unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
450 // local. For implicit byref parameters, this gets hijacked between
451 // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to point to the
452 // struct local created to model the parameter's struct promotion, if any.
453 unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
454 // Valid on promoted struct local fields.
457 unsigned char lvFieldCnt; // Number of fields in the promoted VarDsc.
458 unsigned char lvFldOffset;
459 unsigned char lvFldOrdinal;
461 #if FEATURE_MULTIREG_ARGS
462 regNumber lvRegNumForSlot(unsigned slotNum)
468 else if (slotNum == 1)
470 return lvOtherArgReg;
474 assert(false && "Invalid slotNum!");
479 #endif // FEATURE_MULTIREG_ARGS
497 bool lvIsHfaRegArg() const
500 return _lvIsHfaRegArg;
506 void lvSetIsHfaRegArg(bool value = true)
509 _lvIsHfaRegArg = value;
513 bool lvHfaTypeIsFloat() const
516 return _lvHfaTypeIsFloat;
522 void lvSetHfaTypeIsFloat(bool value)
525 _lvHfaTypeIsFloat = value;
529 // on Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
530 // on Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
532 unsigned lvHfaSlots() const
535 assert(varTypeIsStruct(lvType));
537 return lvExactSize / sizeof(float);
538 #else // _TARGET_ARM64_
539 if (lvHfaTypeIsFloat())
541 return lvExactSize / sizeof(float);
545 return lvExactSize / sizeof(double);
547 #endif // _TARGET_ARM64_
550 // lvIsMultiRegArgOrRet()
551 // returns true if this is a multireg LclVar struct used in an argument context
552 // or if this is a multireg LclVar struct assigned from a multireg call
553 bool lvIsMultiRegArgOrRet()
555 return lvIsMultiRegArg || lvIsMultiRegRet;
559 regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
560 // register pair). It is set during codegen any time the
561 // variable is enregistered (lvRegister is only set
562 // to non-zero if the variable gets the same register assignment for its entire
564 #if !defined(_TARGET_64BIT_)
565 regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
566 #endif // !defined(_TARGET_64BIT_)
568 regNumberSmall _lvArgReg; // The register in which this argument is passed.
570 #if FEATURE_MULTIREG_ARGS
571 regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
572 // Note this is defined but not used by ARM32
573 #endif // FEATURE_MULTIREG_ARGS
575 regNumberSmall _lvArgInitReg; // the register into which the argument is moved at entry
578 // The register number is stored in a small format (8 bits), but the getters return and the setters take
579 // a full-size (unsigned) format, to localize the casts here.
581 /////////////////////
583 __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
585 regNumber GetRegNum() const
587 return (regNumber)_lvRegNum;
590 void SetRegNum(regNumber reg)
592 _lvRegNum = (regNumberSmall)reg;
593 assert(_lvRegNum == reg);
596 /////////////////////
598 #if defined(_TARGET_64BIT_)
599 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
601 regNumber GetOtherReg() const
603 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
604 // "unreachable code" warnings
608 void SetOtherReg(regNumber reg)
610 assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
611 // "unreachable code" warnings
613 #else // !_TARGET_64BIT_
614 __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
616 regNumber GetOtherReg() const
618 return (regNumber)_lvOtherReg;
621 void SetOtherReg(regNumber reg)
623 _lvOtherReg = (regNumberSmall)reg;
624 assert(_lvOtherReg == reg);
626 #endif // !_TARGET_64BIT_
628 /////////////////////
630 __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
632 regNumber GetArgReg() const
634 return (regNumber)_lvArgReg;
637 void SetArgReg(regNumber reg)
639 _lvArgReg = (regNumberSmall)reg;
640 assert(_lvArgReg == reg);
643 #if FEATURE_MULTIREG_ARGS
644 __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
646 regNumber GetOtherArgReg() const
648 return (regNumber)_lvOtherArgReg;
651 void SetOtherArgReg(regNumber reg)
653 _lvOtherArgReg = (regNumberSmall)reg;
654 assert(_lvOtherArgReg == reg);
656 #endif // FEATURE_MULTIREG_ARGS
659 // Is this is a SIMD struct?
660 bool lvIsSIMDType() const
665 // Is this is a SIMD struct which is used for SIMD intrinsic?
666 bool lvIsUsedInSIMDIntrinsic() const
668 return lvUsedInSIMDIntrinsic;
671 // If feature_simd not enabled, return false
672 bool lvIsSIMDType() const
676 bool lvIsUsedInSIMDIntrinsic() const
682 /////////////////////
684 __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
686 regNumber GetArgInitReg() const
688 return (regNumber)_lvArgInitReg;
691 void SetArgInitReg(regNumber reg)
693 _lvArgInitReg = (regNumberSmall)reg;
694 assert(_lvArgInitReg == reg);
697 /////////////////////
699 bool lvIsRegCandidate() const
701 return lvLRACandidate != 0;
704 bool lvIsInReg() const
706 return lvIsRegCandidate() && (lvRegNum != REG_STK);
709 regMaskTP lvRegMask() const
711 regMaskTP regMask = RBM_NONE;
712 if (varTypeIsFloating(TypeGet()))
714 if (lvRegNum != REG_STK)
716 regMask = genRegMaskFloat(lvRegNum, TypeGet());
721 if (lvRegNum != REG_STK)
723 regMask = genRegMask(lvRegNum);
729 unsigned short lvVarIndex; // variable tracking index
732 unsigned short m_lvRefCnt; // unweighted (real) reference count. For implicit by reference
733 // parameters, this gets hijacked from fgMarkImplicitByRefArgs
734 // through fgMarkDemotedImplicitByRefArgs, to provide a static
735 // appearance count (computed during address-exposed analysis)
736 // that fgMakeOutgoingStructArgCopy consults during global morph
737 // to determine if eliding its copy is legal.
739 BasicBlock::weight_t m_lvRefCntWtd; // weighted reference count
742 unsigned short lvRefCnt(RefCountState state = RCS_NORMAL) const;
743 void incLvRefCnt(unsigned short delta, RefCountState state = RCS_NORMAL);
744 void setLvRefCnt(unsigned short newValue, RefCountState state = RCS_NORMAL);
746 BasicBlock::weight_t lvRefCntWtd(RefCountState state = RCS_NORMAL) const;
747 void incLvRefCntWtd(BasicBlock::weight_t delta, RefCountState state = RCS_NORMAL);
748 void setLvRefCntWtd(BasicBlock::weight_t newValue, RefCountState state = RCS_NORMAL);
750 int lvStkOffs; // stack offset of home
751 unsigned lvExactSize; // (exact) size of the type in bytes
753 // Is this a promoted struct?
754 // This method returns true only for structs (including SIMD structs), not for
755 // locals that are split on a 32-bit target.
756 // It is only necessary to use this:
757 // 1) if only structs are wanted, and
758 // 2) if Lowering has already been done.
759 // Otherwise lvPromoted is valid.
760 bool lvPromotedStruct()
762 #if !defined(_TARGET_64BIT_)
763 return (lvPromoted && !varTypeIsLong(lvType));
764 #else // defined(_TARGET_64BIT_)
766 #endif // defined(_TARGET_64BIT_)
769 unsigned lvSize() const // Size needed for storage representation. Only used for structs or TYP_BLK.
771 // TODO-Review: Sometimes we get called on ARM with HFA struct variables that have been promoted,
772 // where the struct itself is no longer used because all access is via its member fields.
773 // When that happens, the struct is marked as unused and its type has been changed to
774 // TYP_INT (to keep the GC tracking code from looking at it).
775 // See Compiler::raAssignVars() for details. For example:
776 // N002 ( 4, 3) [00EA067C] ------------- return struct $346
777 // N001 ( 3, 2) [00EA0628] ------------- lclVar struct(U) V03 loc2
778 // float V03.f1 (offs=0x00) -> V12 tmp7
779 // f8 (last use) (last use) $345
780 // Here, the "struct(U)" shows that the "V03 loc2" variable is unused. Not shown is that V03
781 // is now TYP_INT in the local variable table. It's not really unused, because it's in the tree.
783 assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
785 #if defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
786 // For 32-bit architectures, we make local variable SIMD12 types 16 bytes instead of just 12. We can't do
787 // this for arguments, which must be passed according the defined ABI. We don't want to do this for
788 // dependently promoted struct fields, but we don't know that here. See lvaMapSimd12ToSimd16().
789 // (Note that for 64-bits, we are already rounding up to 16.)
790 if ((lvType == TYP_SIMD12) && !lvIsParam)
792 assert(lvExactSize == 12);
795 #endif // defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
797 return roundUp(lvExactSize, TARGET_POINTER_SIZE);
800 size_t lvArgStackSize() const;
802 unsigned lvSlotNum; // original slot # (if remapped)
804 typeInfo lvVerTypeInfo; // type info needed for verification
806 CORINFO_CLASS_HANDLE lvClassHnd; // class handle for the local, or null if not known
808 CORINFO_FIELD_HANDLE lvFieldHnd; // field handle for promoted struct fields
810 BYTE* lvGcLayout; // GC layout info for structs
813 BlockSet lvRefBlks; // Set of blocks that contain refs
814 GenTree* lvDefStmt; // Pointer to the statement with the single definition
815 void lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies
817 var_types TypeGet() const
819 return (var_types)lvType;
821 bool lvStackAligned() const
823 assert(lvIsStructField);
824 return ((lvFldOffset % TARGET_POINTER_SIZE) == 0);
826 bool lvNormalizeOnLoad() const
828 return varTypeIsSmall(TypeGet()) &&
829 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
830 (lvIsParam || lvAddrExposed || lvIsStructField);
833 bool lvNormalizeOnStore()
835 return varTypeIsSmall(TypeGet()) &&
836 // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
837 !(lvIsParam || lvAddrExposed || lvIsStructField);
840 void incRefCnts(BasicBlock::weight_t weight,
842 RefCountState state = RCS_NORMAL,
843 bool propagate = true);
844 bool IsFloatRegType() const
846 return isFloatRegType(lvType) || lvIsHfaRegArg();
848 var_types GetHfaType() const
850 return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
852 void SetHfaType(var_types type)
854 assert(varTypeIsFloating(type));
855 lvSetHfaTypeIsFloat(type == TYP_FLOAT);
858 var_types lvaArgType();
860 SsaDefArray<LclSsaVarDsc> lvPerSsaData;
862 // Returns the address of the per-Ssa data for the given ssaNum (which is required
863 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
864 // not an SSA variable).
865 LclSsaVarDsc* GetPerSsaData(unsigned ssaNum)
867 return lvPerSsaData.GetSsaDef(ssaNum);
872 const char* lvReason;
874 void PrintVarReg() const
876 printf("%s", getRegName(lvRegNum));
880 }; // class LclVarDsc
883 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
884 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
888 XX The temporary lclVars allocated by the compiler for code generation XX
890 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
891 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
894 /*****************************************************************************
896 * The following keeps track of temporaries allocated in the stack frame
897 * during code-generation (after register allocation). These spill-temps are
898 * only used if we run out of registers while evaluating a tree.
900 * These are different from the more common temps allocated by lvaGrabTemp().
911 static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
919 TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
923 0); // temps must have a negative number (so they have a different number from all local variables)
924 tdOffs = BAD_TEMP_OFFSET;
928 IMPL_LIMITATION("too many spill temps");
933 bool tdLegalOffset() const
935 return tdOffs != BAD_TEMP_OFFSET;
939 int tdTempOffs() const
941 assert(tdLegalOffset());
944 void tdSetTempOffs(int offs)
947 assert(tdLegalOffset());
949 void tdAdjustTempOffs(int offs)
952 assert(tdLegalOffset());
955 int tdTempNum() const
960 unsigned tdTempSize() const
964 var_types tdTempType() const
970 // interface to hide linearscan implementation from rest of compiler
971 class LinearScanInterface
974 virtual void doLinearScan() = 0;
975 virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
976 virtual bool willEnregisterLocalVars() const = 0;
979 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
981 // Information about arrays: their element type and size, and the offset of the first element.
982 // We label GT_IND's that are array indices with GTF_IND_ARR_INDEX, and, for such nodes,
983 // associate an array info via the map retrieved by GetArrayInfoMap(). This information is used,
984 // for example, in value numbering of array index expressions.
987 var_types m_elemType;
988 CORINFO_CLASS_HANDLE m_elemStructType;
990 unsigned m_elemOffset;
992 ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
996 ArrayInfo(var_types elemType, unsigned elemSize, unsigned elemOffset, CORINFO_CLASS_HANDLE elemStructType)
997 : m_elemType(elemType), m_elemStructType(elemStructType), m_elemSize(elemSize), m_elemOffset(elemOffset)
1002 // This enumeration names the phases into which we divide compilation. The phases should completely
1003 // partition a compilation.
1006 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent, measureIR) enum_nm,
1007 #include "compphases.h"
1011 extern const char* PhaseNames[];
1012 extern const char* PhaseEnums[];
1013 extern const LPCWSTR PhaseShortNames[];
1015 // The following enum provides a simple 1:1 mapping to CLR API's
1016 enum API_ICorJitInfo_Names
1018 #define DEF_CLR_API(name) API_##name,
1019 #include "ICorJitInfo_API_names.h"
1023 //---------------------------------------------------------------
1024 // Compilation time.
1027 // A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
1028 // We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
1029 // of the compilation, as well as the cycles for each phase. We also track the number of bytecodes.
1030 // If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
1031 // by "m_timerFailure" being true.
1032 // If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
1035 #ifdef FEATURE_JIT_METHOD_PERF
1036 // The string names of the phases.
1037 static const char* PhaseNames[];
1039 static bool PhaseHasChildren[];
1040 static int PhaseParent[];
1041 static bool PhaseReportsIRSize[];
1043 unsigned m_byteCodeBytes;
1044 unsigned __int64 m_totalCycles;
1045 unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
1046 unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
1047 #if MEASURE_CLRAPI_CALLS
1048 unsigned __int64 m_CLRinvokesByPhase[PHASE_NUMBER_OF];
1049 unsigned __int64 m_CLRcyclesByPhase[PHASE_NUMBER_OF];
1052 unsigned m_nodeCountAfterPhase[PHASE_NUMBER_OF];
1054 // For better documentation, we call EndPhase on
1055 // non-leaf phases. We should also call EndPhase on the
1056 // last leaf subphase; obviously, the elapsed cycles between the EndPhase
1057 // for the last leaf subphase and the EndPhase for an ancestor should be very small.
1058 // We add all such "redundant end phase" intervals to this variable below; we print
1059 // it out in a report, so we can verify that it is, indeed, very small. If it ever
1060 // isn't, this means that we're doing something significant between the end of the last
1061 // declared subphase and the end of its parent.
1062 unsigned __int64 m_parentPhaseEndSlop;
1063 bool m_timerFailure;
1065 #if MEASURE_CLRAPI_CALLS
1066 // The following measures the time spent inside each individual CLR API call.
1067 unsigned m_allClrAPIcalls;
1068 unsigned m_perClrAPIcalls[API_ICorJitInfo_Names::API_COUNT];
1069 unsigned __int64 m_allClrAPIcycles;
1070 unsigned __int64 m_perClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1071 unsigned __int32 m_maxClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1072 #endif // MEASURE_CLRAPI_CALLS
1074 CompTimeInfo(unsigned byteCodeBytes);
1078 #ifdef FEATURE_JIT_METHOD_PERF
1080 #if MEASURE_CLRAPI_CALLS
1081 struct WrapICorJitInfo;
1084 // This class summarizes the JIT time information over the course of a run: the number of methods compiled,
1085 // and the total and maximum timings. (These are instances of the "CompTimeInfo" type described above).
1086 // The operation of adding a single method's timing to the summary may be performed concurrently by several
1087 // threads, so it is protected by a lock.
1088 // This class is intended to be used as a singleton type, with only a single instance.
1089 class CompTimeSummaryInfo
1091 // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
1092 static CritSecObject s_compTimeSummaryLock;
1096 CompTimeInfo m_total;
1097 CompTimeInfo m_maximum;
1099 int m_numFilteredMethods;
1100 CompTimeInfo m_filtered;
1102 // This can use what ever data you want to determine if the value to be added
1103 // belongs in the filtered section (it's always included in the unfiltered section)
1104 bool IncludedInFilteredData(CompTimeInfo& info);
1107 // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
1108 static CompTimeSummaryInfo s_compTimeSummary;
1110 CompTimeSummaryInfo()
1111 : m_numMethods(0), m_totMethods(0), m_total(0), m_maximum(0), m_numFilteredMethods(0), m_filtered(0)
1115 // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
1116 // This is thread safe.
1117 void AddInfo(CompTimeInfo& info, bool includePhases);
1119 // Print the summary information to "f".
1120 // This is not thread-safe; assumed to be called by only one thread.
1121 void Print(FILE* f);
1124 // A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
1125 // and when the current phase started. This is intended to be part of a Compilation object. This is
1126 // disabled (FEATURE_JIT_METHOD_PERF not defined) when FEATURE_CORECLR is set, or on non-windows platforms.
1130 unsigned __int64 m_start; // Start of the compilation.
1131 unsigned __int64 m_curPhaseStart; // Start of the current phase.
1132 #if MEASURE_CLRAPI_CALLS
1133 unsigned __int64 m_CLRcallStart; // Start of the current CLR API call (if any).
1134 unsigned __int64 m_CLRcallInvokes; // CLR API invokes under current outer so far
1135 unsigned __int64 m_CLRcallCycles; // CLR API cycles under current outer so far.
1136 int m_CLRcallAPInum; // The enum/index of the current CLR API call (or -1).
1137 static double s_cyclesPerSec; // Cached for speedier measurements
1140 Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1142 CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1144 static CritSecObject s_csvLock; // Lock to protect the time log file.
1145 void PrintCsvMethodStats(Compiler* comp);
1148 void* operator new(size_t);
1149 void* operator new[](size_t);
1150 void operator delete(void*);
1151 void operator delete[](void*);
1154 // Initialized the timer instance
1155 JitTimer(unsigned byteCodeSize);
1157 static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1159 return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1162 static void PrintCsvHeader();
1164 // Ends the current phase (argument is for a redundant check).
1165 void EndPhase(Compiler* compiler, Phases phase);
1167 #if MEASURE_CLRAPI_CALLS
1168 // Start and end a timed CLR API call.
1169 void CLRApiCallEnter(unsigned apix);
1170 void CLRApiCallLeave(unsigned apix);
1171 #endif // MEASURE_CLRAPI_CALLS
1173 // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
1174 // and adds it to "sum".
1175 void Terminate(Compiler* comp, CompTimeSummaryInfo& sum, bool includePhases);
1177 // Attempts to query the cycle counter of the current thread. If successful, returns "true" and sets
1178 // *cycles to the cycle counter value. Otherwise, returns false and sets the "m_timerFailure" flag of
1179 // "m_info" to true.
1180 bool GetThreadCycles(unsigned __int64* cycles)
1182 bool res = CycleTimer::GetThreadCyclesS(cycles);
1185 m_info.m_timerFailure = true;
1190 #endif // FEATURE_JIT_METHOD_PERF
1192 //------------------- Function/Funclet info -------------------------------
1193 enum FuncKind : BYTE
1195 FUNC_ROOT, // The main/root function (always id==0)
1196 FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
1197 FUNC_FILTER, // a funclet associated with an EH filter
1206 BYTE funFlags; // Currently unused, just here for padding
1207 unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
1208 // funclet. It is only valid if funKind field indicates this is a
1209 // EH-related funclet: FUNC_HANDLER or FUNC_FILTER
1211 #if defined(_TARGET_AMD64_)
1213 // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
1214 emitLocation* startLoc;
1215 emitLocation* endLoc;
1216 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1217 emitLocation* coldEndLoc;
1218 UNWIND_INFO unwindHeader;
1219 // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
1220 // number of codes, the VM or Zapper will 4-byte align the whole thing.
1221 BYTE unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
1222 unsigned unwindCodeSlot;
1224 #elif defined(_TARGET_X86_)
1226 #if defined(_TARGET_UNIX_)
1227 emitLocation* startLoc;
1228 emitLocation* endLoc;
1229 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1230 emitLocation* coldEndLoc;
1231 #endif // _TARGET_UNIX_
1233 #elif defined(_TARGET_ARMARCH_)
1235 UnwindInfo uwi; // Unwind information for this function/funclet's hot section
1236 UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
1237 // Note: we only have a pointer here instead of the actual object,
1238 // to save memory in the JIT case (compared to the NGEN case),
1239 // where we don't have any cold section.
1240 // Note 2: we currently don't support hot/cold splitting in functions
1241 // with EH, so uwiCold will be NULL for all funclets.
1243 #if defined(_TARGET_UNIX_)
1244 emitLocation* startLoc;
1245 emitLocation* endLoc;
1246 emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1247 emitLocation* coldEndLoc;
1248 #endif // _TARGET_UNIX_
1250 #endif // _TARGET_ARMARCH_
1252 #if defined(_TARGET_UNIX_)
1253 jitstd::vector<CFI_CODE>* cfiCodes;
1254 #endif // _TARGET_UNIX_
1256 // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1257 // that isn't shared between the main function body and funclets.
1260 struct fgArgTabEntry
1262 GenTree* node; // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
1263 // placeholder it will point at the actual argument in the gtCallLateArgs list.
1264 GenTree* parent; // Points at the GT_LIST node in the gtCallArgs for this argument
1266 unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1269 regNumberSmall regNums[MAX_ARG_REG_COUNT]; // The registers to use when passing this argument, set to REG_STK for
1270 // arguments passed on the stack
1272 unsigned numRegs; // Count of number of registers that this argument uses.
1273 // Note that on ARM, if we have a double hfa, this reflects the number
1274 // of DOUBLE registers.
1276 // A slot is a pointer sized region in the OutArg area.
1277 unsigned slotNum; // When an argument is passed in the OutArg area this is the slot number in the OutArg area
1278 unsigned numSlots; // Count of number of slots that this argument uses
1280 unsigned alignment; // 1 or 2 (slots/registers)
1282 unsigned _lateArgInx; // index into gtCallLateArgs list; UINT_MAX if this is not a late arg.
1284 unsigned tmpNum; // the LclVar number if we had to force evaluation of this arg
1286 var_types argType; // The type used to pass this argument. This is generally the original argument type, but when a
1287 // struct is passed as a scalar type, this is that type.
1288 // Note that if a struct is passed by reference, this will still be the struct type.
1290 bool needTmp : 1; // True when we force this argument's evaluation into a temp LclVar
1291 bool needPlace : 1; // True when we must replace this argument with a placeholder node
1292 bool isTmp : 1; // True when we setup a temp LclVar for this argument due to size issues with the struct
1293 bool processed : 1; // True when we have decided the evaluation order for this argument in the gtCallLateArgs
1294 bool isBackFilled : 1; // True when the argument fills a register slot skipped due to alignment requirements of
1295 // previous arguments.
1296 bool isNonStandard : 1; // True if it is an arg that is passed in a reg other than a standard arg reg, or is forced
1297 // to be on the stack despite its arg list position.
1298 bool isStruct : 1; // True if this is a struct arg
1299 bool _isVararg : 1; // True if the argument is in a vararg context.
1300 bool passedByRef : 1; // True iff the argument is passed by reference.
1301 #ifdef FEATURE_ARG_SPLIT
1302 bool _isSplit : 1; // True when this argument is split between the registers and OutArg area
1303 #endif // FEATURE_ARG_SPLIT
1305 bool _isHfaArg : 1; // True when the argument is an HFA type.
1306 bool _isDoubleHfa : 1; // True when the argument is an HFA, with an element type of DOUBLE.
1311 bool isLate = (_lateArgInx != UINT_MAX);
1315 __declspec(property(get = getLateArgInx, put = setLateArgInx)) unsigned lateArgInx;
1316 unsigned getLateArgInx()
1318 assert(isLateArg());
1321 void setLateArgInx(unsigned inx)
1325 __declspec(property(get = getRegNum)) regNumber regNum;
1326 regNumber getRegNum()
1328 return (regNumber)regNums[0];
1330 __declspec(property(get = getOtherRegNum)) regNumber otherRegNum;
1331 regNumber getOtherRegNum()
1333 return (regNumber)regNums[1];
1336 #if defined(UNIX_AMD64_ABI)
1337 SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1340 void setRegNum(unsigned int i, regNumber regNum)
1342 assert(i < MAX_ARG_REG_COUNT);
1343 regNums[i] = (regNumberSmall)regNum;
1345 regNumber getRegNum(unsigned int i)
1347 assert(i < MAX_ARG_REG_COUNT);
1348 return (regNumber)regNums[i];
1351 __declspec(property(get = getIsSplit, put = setIsSplit)) bool isSplit;
1354 #ifdef FEATURE_ARG_SPLIT
1356 #else // FEATURE_ARG_SPLIT
1360 void setIsSplit(bool value)
1362 #ifdef FEATURE_ARG_SPLIT
1367 __declspec(property(get = getIsVararg, put = setIsVararg)) bool isVararg;
1370 #ifdef FEATURE_VARARG
1376 void setIsVararg(bool value)
1378 #ifdef FEATURE_VARARG
1380 #endif // FEATURE_VARARG
1383 __declspec(property(get = getIsHfaArg)) bool isHfaArg;
1393 __declspec(property(get = getIsHfaRegArg)) bool isHfaRegArg;
1394 bool getIsHfaRegArg()
1397 return _isHfaArg && isPassedInRegisters();
1403 __declspec(property(get = getHfaType)) var_types hfaType;
1404 var_types getHfaType()
1407 return _isHfaArg ? (_isDoubleHfa ? TYP_DOUBLE : TYP_FLOAT) : TYP_UNDEF;
1413 void setHfaType(var_types type, unsigned hfaSlots)
1416 if (type != TYP_UNDEF)
1418 // We must already have set the passing mode.
1419 assert(numRegs != 0 || numSlots != 0);
1420 // We originally set numRegs according to the size of the struct, but if the size of the
1421 // hfaType is not the same as the pointer size, we need to correct it.
1422 // Note that hfaSlots is the number of registers we will use. For ARM, that is twice
1423 // the number of "double registers".
1424 unsigned numHfaRegs = hfaSlots;
1425 if (isPassedInRegisters())
1428 if (type == TYP_DOUBLE)
1430 // Must be an even number of registers.
1431 assert((numRegs & 1) == 0);
1432 numHfaRegs = hfaSlots / 2;
1434 #endif // _TARGET_ARM_
1437 // This should already be set correctly.
1438 assert(numRegs == numHfaRegs);
1439 assert(_isDoubleHfa == (type == TYP_DOUBLE));
1443 numRegs = numHfaRegs;
1446 _isDoubleHfa = (type == TYP_DOUBLE);
1449 #endif // FEATURE_HFA
1453 void SetIsBackFilled(bool backFilled)
1455 isBackFilled = backFilled;
1458 bool IsBackFilled() const
1460 return isBackFilled;
1462 #else // !_TARGET_ARM_
1463 void SetIsBackFilled(bool backFilled)
1467 bool IsBackFilled() const
1471 #endif // !_TARGET_ARM_
1473 bool isPassedInRegisters()
1475 return !isSplit && (numRegs != 0);
1478 bool isPassedInFloatRegisters()
1483 return isValidFloatArgReg(regNum);
1487 bool isSingleRegOrSlot()
1489 return !isSplit && ((numRegs == 1) || (numSlots == 1));
1492 // Returns the number of "slots" used, where for this purpose a
1493 // register counts as a slot.
1494 unsigned getSlotCount()
1498 assert(isPassedInRegisters());
1499 assert(numRegs == 1);
1501 else if (regNum == REG_STK)
1503 assert(!isPassedInRegisters());
1504 assert(numRegs == 0);
1508 assert(numRegs > 0);
1510 return numSlots + numRegs;
1513 // Returns the size as a multiple of pointer-size.
1514 // For targets without HFAs, this is the same as getSlotCount().
1517 unsigned size = getSlotCount();
1520 // We counted the number of regs, but if they are DOUBLE hfa regs we have to double the size.
1521 if (isHfaRegArg && (hfaType == TYP_DOUBLE))
1526 #elif defined(_TARGET_ARM64_)
1527 // We counted the number of regs, but if they are FLOAT hfa regs we have to halve the size.
1528 if (isHfaRegArg && (hfaType == TYP_FLOAT))
1530 // Round up in case of odd HFA count.
1531 size = (size + 1) >> 1;
1533 #endif // _TARGET_ARM64_
1538 // Set the register numbers for a multireg argument.
1539 // There's nothing to do on x64/Ux because the structDesc has already been used to set the
1540 // register numbers.
1541 void SetMultiRegNums()
1543 #if FEATURE_MULTIREG_ARGS && !defined(UNIX_AMD64_ABI)
1549 regNumber argReg = getRegNum(0);
1551 unsigned int regSize = (hfaType == TYP_DOUBLE) ? 2 : 1;
1553 unsigned int regSize = 1;
1555 for (unsigned int regIndex = 1; regIndex < numRegs; regIndex++)
1557 argReg = (regNumber)(argReg + regSize);
1558 setRegNum(regIndex, argReg);
1560 #endif // FEATURE_MULTIREG_ARGS && !defined(UNIX_AMD64_ABI)
1563 // Check that the value of 'isStruct' is consistent.
1564 // A struct arg must be one of the following:
1565 // - A node of struct type,
1566 // - A GT_FIELD_LIST, or
1567 // - A node of a scalar type, passed in a single register or slot
1568 // (or two slots in the case of a struct pass on the stack as TYP_DOUBLE).
1570 void checkIsStruct()
1574 if (!varTypeIsStruct(node) && !node->OperIs(GT_FIELD_LIST))
1576 // This is the case where we are passing a struct as a primitive type.
1577 // On most targets, this is always a single register or slot.
1578 // However, on ARM this could be two slots if it is TYP_DOUBLE.
1579 bool isPassedAsPrimitiveType = ((numRegs == 1) || ((numRegs == 0) && (numSlots == 1)));
1581 if (!isPassedAsPrimitiveType)
1583 if (node->TypeGet() == TYP_DOUBLE && numRegs == 0 && (numSlots == 2))
1585 isPassedAsPrimitiveType = true;
1588 #endif // _TARGET_ARM_
1589 assert(isPassedAsPrimitiveType);
1594 assert(!varTypeIsStruct(node));
1603 //-------------------------------------------------------------------------
1605 // The class fgArgInfo is used to handle the arguments
1606 // when morphing a GT_CALL node.
1611 Compiler* compiler; // Back pointer to the compiler instance so that we can allocate memory
1612 GenTreeCall* callTree; // Back pointer to the GT_CALL node for this fgArgInfo
1613 unsigned argCount; // Updatable arg count value
1614 unsigned nextSlotNum; // Updatable slot count value
1615 unsigned stkLevel; // Stack depth when we make this call (for x86)
1617 #if defined(UNIX_X86_ABI)
1618 bool alignmentDone; // Updateable flag, set to 'true' after we've done any required alignment.
1619 unsigned stkSizeBytes; // Size of stack used by this call, in bytes. Calculated during fgMorphArgs().
1620 unsigned padStkAlign; // Stack alignment in bytes required before arguments are pushed for this call.
1621 // Computed dynamically during codegen, based on stkSizeBytes and the current
1622 // stack level (genStackLevel) when the first stack adjustment is made for
1626 #if FEATURE_FIXED_OUT_ARGS
1627 unsigned outArgSize; // Size of the out arg area for the call, will be at least MIN_ARG_AREA_FOR_CALL
1630 unsigned argTableSize; // size of argTable array (equal to the argCount when done with fgMorphArgs)
1631 bool hasRegArgs; // true if we have one or more register arguments
1632 bool hasStackArgs; // true if we have one or more stack arguments
1633 bool argsComplete; // marker for state
1634 bool argsSorted; // marker for state
1635 fgArgTabEntry** argTable; // variable sized array of per argument descrption: (i.e. argTable[argTableSize])
1638 void AddArg(fgArgTabEntry* curArgTabEntry);
1641 fgArgInfo(Compiler* comp, GenTreeCall* call, unsigned argCount);
1642 fgArgInfo(GenTreeCall* newCall, GenTreeCall* oldCall);
1644 fgArgTabEntry* AddRegArg(unsigned argNum,
1651 bool isVararg = false);
1653 #ifdef UNIX_AMD64_ABI
1654 fgArgTabEntry* AddRegArg(unsigned argNum,
1660 const bool isStruct,
1661 const bool isVararg,
1662 const regNumber otherRegNum,
1663 const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr = nullptr);
1664 #endif // UNIX_AMD64_ABI
1666 fgArgTabEntry* AddStkArg(unsigned argNum,
1672 bool isVararg = false);
1674 void RemorphReset();
1675 void UpdateRegArg(fgArgTabEntry* argEntry, GenTree* node, bool reMorphing);
1676 void UpdateStkArg(fgArgTabEntry* argEntry, GenTree* node, bool reMorphing);
1678 void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1680 void EvalToTmp(fgArgTabEntry* curArgTabEntry, unsigned tmpNum, GenTree* newNode);
1682 void ArgsComplete();
1686 void EvalArgsToTemps();
1692 fgArgTabEntry** ArgTable()
1696 unsigned GetNextSlotNum()
1706 return hasStackArgs;
1708 bool AreArgsComplete() const
1710 return argsComplete;
1712 #if FEATURE_FIXED_OUT_ARGS
1713 unsigned GetOutArgSize() const
1717 void SetOutArgSize(unsigned newVal)
1719 outArgSize = newVal;
1721 #endif // FEATURE_FIXED_OUT_ARGS
1723 #if defined(UNIX_X86_ABI)
1724 void ComputeStackAlignment(unsigned curStackLevelInBytes)
1726 padStkAlign = AlignmentPad(curStackLevelInBytes, STACK_ALIGN);
1729 unsigned GetStkAlign()
1734 void SetStkSizeBytes(unsigned newStkSizeBytes)
1736 stkSizeBytes = newStkSizeBytes;
1739 unsigned GetStkSizeBytes() const
1741 return stkSizeBytes;
1744 bool IsStkAlignmentDone() const
1746 return alignmentDone;
1749 void SetStkAlignmentDone()
1751 alignmentDone = true;
1753 #endif // defined(UNIX_X86_ABI)
1755 // Get the fgArgTabEntry for the arg at position argNum.
1756 fgArgTabEntry* GetArgEntry(unsigned argNum, bool reMorphing = true)
1758 fgArgTabEntry* curArgTabEntry = nullptr;
1762 // The arg table has not yet been sorted.
1763 curArgTabEntry = argTable[argNum];
1764 assert(curArgTabEntry->argNum == argNum);
1765 return curArgTabEntry;
1768 for (unsigned i = 0; i < argCount; i++)
1770 curArgTabEntry = argTable[i];
1771 if (curArgTabEntry->argNum == argNum)
1773 return curArgTabEntry;
1776 noway_assert(!"GetArgEntry: argNum not found");
1780 // Get the node for the arg at position argIndex.
1781 // Caller must ensure that this index is a valid arg index.
1782 GenTree* GetArgNode(unsigned argIndex)
1784 return GetArgEntry(argIndex)->node;
1787 void Dump(Compiler* compiler);
1791 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1792 // We have the ability to mark source expressions with "Test Labels."
1793 // These drive assertions within the JIT, or internal JIT testing. For example, we could label expressions
1794 // that should be CSE defs, and other expressions that should uses of those defs, with a shared label.
1796 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
1799 TL_VN, // Defines a "VN equivalence class". (For full VN, including exceptions thrown).
1800 TL_VNNorm, // Like above, but uses the non-exceptional value of the expression.
1801 TL_CSE_Def, // This must be identified in the JIT as a CSE def
1802 TL_CSE_Use, // This must be identified in the JIT as a CSE use
1803 TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
1806 struct TestLabelAndNum
1811 TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1816 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, TestLabelAndNum> NodeToTestDataMap;
1818 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1822 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1823 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1825 XX The big guy. The sections are currently organized as : XX
1827 XX o GenTree and BasicBlock XX
1839 XX o PrologScopeInfo XX
1840 XX o CodeGenerator XX
1845 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1846 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1849 struct HWIntrinsicInfo;
1853 friend class emitter;
1854 friend class UnwindInfo;
1855 friend class UnwindFragmentInfo;
1856 friend class UnwindEpilogInfo;
1857 friend class JitTimer;
1858 friend class LinearScan;
1859 friend class fgArgInfo;
1860 friend class Rationalizer;
1862 friend class Lowering;
1863 friend class CSE_DataFlow;
1864 friend class CSE_Heuristic;
1865 friend class CodeGenInterface;
1866 friend class CodeGen;
1867 friend class LclVarDsc;
1868 friend class TempDsc;
1870 friend class ObjectAllocator;
1871 friend class LocalAddressVisitor;
1872 friend struct GenTree;
1874 #ifdef FEATURE_HW_INTRINSICS
1875 friend struct HWIntrinsicInfo;
1876 #endif // FEATURE_HW_INTRINSICS
1878 #ifndef _TARGET_64BIT_
1879 friend class DecomposeLongs;
1880 #endif // !_TARGET_64BIT_
1883 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1884 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1886 XX Misc structs definitions XX
1888 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1889 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1893 hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1912 bool dumpIRDataflow;
1913 bool dumpIRBlockHeaders;
1915 LPCWSTR dumpIRPhase;
1916 LPCWSTR dumpIRFormat;
1918 bool shouldUseVerboseTrees();
1919 bool asciiTrees; // If true, dump trees using only ASCII characters
1920 bool shouldDumpASCIITrees();
1921 bool verboseSsa; // If true, produce especially verbose dump output in SSA construction.
1922 bool shouldUseVerboseSsa();
1923 bool treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
1924 int morphNum; // This counts the the trees that have been morphed, allowing us to label each uniquely.
1926 const char* VarNameToStr(VarName name)
1931 DWORD expensiveDebugCheckLevel;
1934 #if FEATURE_MULTIREG_RET
1935 GenTree* impAssignMultiRegTypeToVar(GenTree* op, CORINFO_CLASS_HANDLE hClass);
1936 #endif // FEATURE_MULTIREG_RET
1938 GenTree* impAssignSmallStructTypeToVar(GenTree* op, CORINFO_CLASS_HANDLE hClass);
1941 bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1942 #endif // ARM_SOFTFP
1944 //-------------------------------------------------------------------------
1945 // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM.
1946 // HFAs are one to four element structs where each element is the same
1947 // type, either all float or all double. They are treated specially
1948 // in the ARM Procedure Call Standard, specifically, they are passed in
1949 // floating-point registers instead of the general purpose registers.
1952 bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1953 bool IsHfa(GenTree* tree);
1955 var_types GetHfaType(GenTree* tree);
1956 unsigned GetHfaCount(GenTree* tree);
1958 var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1959 unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1961 bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1963 //-------------------------------------------------------------------------
1964 // The following is used for validating format of EH table
1968 typedef struct EHNodeDsc* pEHNodeDsc;
1970 EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1971 EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
1984 EHBlockType ehnBlockType; // kind of EH block
1985 IL_OFFSET ehnStartOffset; // IL offset of start of the EH block
1986 IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
1987 // the last IL offset, not "one past the last one", i.e., the range Start to End is
1989 pEHNodeDsc ehnNext; // next (non-nested) block in sequential order
1990 pEHNodeDsc ehnChild; // leftmost nested block
1992 pEHNodeDsc ehnTryNode; // for filters and handlers, the corresponding try node
1993 pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
1995 pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
1996 pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,
1998 void ehnSetTryNodeType()
2000 ehnBlockType = TryNode;
2002 void ehnSetFilterNodeType()
2004 ehnBlockType = FilterNode;
2006 void ehnSetHandlerNodeType()
2008 ehnBlockType = HandlerNode;
2010 void ehnSetFinallyNodeType()
2012 ehnBlockType = FinallyNode;
2014 void ehnSetFaultNodeType()
2016 ehnBlockType = FaultNode;
2019 BOOL ehnIsTryBlock()
2021 return ehnBlockType == TryNode;
2023 BOOL ehnIsFilterBlock()
2025 return ehnBlockType == FilterNode;
2027 BOOL ehnIsHandlerBlock()
2029 return ehnBlockType == HandlerNode;
2031 BOOL ehnIsFinallyBlock()
2033 return ehnBlockType == FinallyNode;
2035 BOOL ehnIsFaultBlock()
2037 return ehnBlockType == FaultNode;
2040 // returns true if there is any overlap between the two nodes
2041 static BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
2043 if (node1->ehnStartOffset < node2->ehnStartOffset)
2045 return (node1->ehnEndOffset >= node2->ehnStartOffset);
2049 return (node1->ehnStartOffset <= node2->ehnEndOffset);
2053 // fails with BADCODE if inner is not completely nested inside outer
2054 static BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
2056 return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
2060 //-------------------------------------------------------------------------
2061 // Exception handling functions
2064 #if !FEATURE_EH_FUNCLETS
2066 bool ehNeedsShadowSPslots()
2068 return (info.compXcptnsCount || opts.compDbgEnC);
2071 // 0 for methods with no EH
2072 // 1 for methods with non-nested EH, or where only the try blocks are nested
2073 // 2 for a method with a catch within a catch
2075 unsigned ehMaxHndNestingCount;
2077 #endif // !FEATURE_EH_FUNCLETS
2079 static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
2080 static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
2082 bool bbInCatchHandlerILRange(BasicBlock* blk);
2083 bool bbInFilterILRange(BasicBlock* blk);
2084 bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
2085 bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
2086 bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
2087 bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
2088 unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);
2090 unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
2091 unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
2093 // Returns true if "block" is the start of a try region.
2094 bool bbIsTryBeg(BasicBlock* block);
2096 // Returns true if "block" is the start of a handler or filter region.
2097 bool bbIsHandlerBeg(BasicBlock* block);
2099 // Returns true iff "block" is where control flows if an exception is raised in the
2100 // try region, and sets "*regionIndex" to the index of the try for the handler.
2101 // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
2102 // block of the filter, but not for the filter's handler.
2103 bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);
2105 bool ehHasCallableHandlers();
2107 // Return the EH descriptor for the given region index.
2108 EHblkDsc* ehGetDsc(unsigned regionIndex);
2110 // Return the EH index given a region descriptor.
2111 unsigned ehGetIndex(EHblkDsc* ehDsc);
2113 // Return the EH descriptor index of the enclosing try, for the given region index.
2114 unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
2116 // Return the EH descriptor index of the enclosing handler, for the given region index.
2117 unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
2119 // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
2120 // block is not in a 'try' region).
2121 EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);
2123 // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
2124 // if this block is not in a filter or handler region).
2125 EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);
2127 // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
2128 // nullptr if this block's exceptions propagate to caller).
2129 EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);
2131 EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
2132 EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
2133 bool ehIsBlockEHLast(BasicBlock* block);
2135 bool ehBlockHasExnFlowDsc(BasicBlock* block);
2137 // Return the region index of the most nested EH region this block is in.
2138 unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
2140 // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
2141 unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
2143 // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
2144 // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
2145 // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
2146 // (It can never be a filter.)
2147 unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);
2149 // A block has been deleted. Update the EH table appropriately.
2150 void ehUpdateForDeletedBlock(BasicBlock* block);
2152 // Determine whether a block can be deleted while preserving the EH normalization rules.
2153 bool ehCanDeleteEmptyBlock(BasicBlock* block);
2155 // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
2156 void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);
2158 // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
2159 // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
2160 // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
2161 // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
2162 // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
2163 // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
2164 // lives in a filter.)
2165 unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);
2167 // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
2168 // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
2169 // (nullptr if the last block is the last block in the program).
2170 // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
2171 void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);
2174 // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
2175 // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
2176 bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
2179 #if FEATURE_EH_FUNCLETS
2180 // Do we need a PSPSym in the main function? For codegen purposes, we only need one
2181 // if there is a filter that protects a region with a nested EH clause (such as a
2182 // try/catch nested in the 'try' body of a try/filter/filter-handler). See
2183 // genFuncletProlog() for more details. However, the VM seems to use it for more
2184 // purposes, maybe including debugging. Until we are sure otherwise, always create
2185 // a PSPSym for functions with any EH.
2186 bool ehNeedsPSPSym() const
2190 #else // _TARGET_X86_
2191 return compHndBBtabCount > 0;
2192 #endif // _TARGET_X86_
2195 bool ehAnyFunclets(); // Are there any funclets in this function?
2196 unsigned ehFuncletCount(); // Return the count of funclets in the function
2198 unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks
2199 #else // !FEATURE_EH_FUNCLETS
2200 bool ehAnyFunclets()
2204 unsigned ehFuncletCount()
2209 unsigned bbThrowIndex(BasicBlock* blk)
2211 return blk->bbTryIndex;
2212 } // Get the index to use as the cache key for sharing throw blocks
2213 #endif // !FEATURE_EH_FUNCLETS
2215 // Returns a flowList representing the "EH predecessors" of "blk". These are the normal predecessors of
2216 // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
2217 // first block of the corresponding try region to be "EH predecessors". (If there is a single such predecessor,
2218 // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
2219 // convenient to also consider it a predecessor.)
2220 flowList* BlockPredsWithEH(BasicBlock* blk);
2222 // This table is useful for memoization of the method above.
2223 typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, flowList*> BlockToFlowListMap;
2224 BlockToFlowListMap* m_blockToEHPreds;
2225 BlockToFlowListMap* GetBlockToEHPreds()
2227 if (m_blockToEHPreds == nullptr)
2229 m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
2231 return m_blockToEHPreds;
2234 void* ehEmitCookie(BasicBlock* block);
2235 UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
2237 EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
2239 EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
2241 EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
2243 EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
2245 void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
2247 void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
2249 void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
2251 void fgAllocEHTable();
2253 void fgRemoveEHTableEntry(unsigned XTnum);
2255 #if FEATURE_EH_FUNCLETS
2257 EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
2259 #endif // FEATURE_EH_FUNCLETS
2263 #endif // !FEATURE_EH
2265 void fgSortEHTable();
2267 // Causes the EH table to obey some well-formedness conditions, by inserting
2268 // empty BB's when necessary:
2269 // * No block is both the first block of a handler and the first block of a try.
2270 // * No block is the first block of multiple 'try' regions.
2271 // * No block is the last block of multiple EH regions.
2272 void fgNormalizeEH();
2273 bool fgNormalizeEHCase1();
2274 bool fgNormalizeEHCase2();
2275 bool fgNormalizeEHCase3();
2278 void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
2279 void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
2280 void fgVerifyHandlerTab();
2281 void fgDispHandlerTab();
2284 bool fgNeedToSortEHTable;
2286 void verInitEHTree(unsigned numEHClauses);
2287 void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
2288 void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
2289 void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
2290 void verCheckNestingLevel(EHNodeDsc* initRoot);
2293 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2294 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2296 XX GenTree and BasicBlock XX
2298 XX Functions to allocate and display the GenTrees and BasicBlocks XX
2300 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2301 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2304 // Functions to create nodes
2305 GenTreeStmt* gtNewStmt(GenTree* expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
2308 GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, bool doSimplifications = TRUE);
2310 // For binary opers.
2311 GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, GenTree* op2);
2313 GenTree* gtNewQmarkNode(var_types type, GenTree* cond, GenTree* colon);
2315 GenTree* gtNewLargeOperNode(genTreeOps oper,
2316 var_types type = TYP_I_IMPL,
2317 GenTree* op1 = nullptr,
2318 GenTree* op2 = nullptr);
2320 GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
2322 GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
2324 GenTree* gtNewJmpTableNode();
2326 GenTree* gtNewIndOfIconHandleNode(var_types indType, size_t value, unsigned iconFlags, bool isInvariant);
2328 GenTree* gtNewIconHandleNode(size_t value, unsigned flags, FieldSeqNode* fields = nullptr);
2330 unsigned gtTokenToIconFlags(unsigned token);
2332 GenTree* gtNewIconEmbHndNode(void* value, void* pValue, unsigned flags, void* compileTimeHandle);
2334 GenTree* gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd);
2335 GenTree* gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd);
2336 GenTree* gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd);
2337 GenTree* gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd);
2339 GenTree* gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
2341 GenTree* gtNewLconNode(__int64 value);
2343 GenTree* gtNewDconNode(double value);
2345 GenTree* gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
2347 GenTree* gtNewZeroConNode(var_types type);
2349 GenTree* gtNewOneConNode(var_types type);
2352 GenTree* gtNewSIMDVectorZero(var_types simdType, var_types baseType, unsigned size);
2353 GenTree* gtNewSIMDVectorOne(var_types simdType, var_types baseType, unsigned size);
2356 GenTree* gtNewBlkOpNode(GenTree* dst, GenTree* srcOrFillVal, unsigned size, bool isVolatile, bool isCopyBlock);
2358 GenTree* gtNewPutArgReg(var_types type, GenTree* arg, regNumber argReg);
2360 GenTree* gtNewBitCastNode(var_types type, GenTree* arg);
2363 void gtBlockOpInit(GenTree* result, GenTree* dst, GenTree* srcOrFillVal, bool isVolatile);
2366 GenTree* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2367 void gtSetObjGcInfo(GenTreeObj* objNode);
2368 GenTree* gtNewStructVal(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2369 GenTree* gtNewBlockVal(GenTree* addr, unsigned size);
2371 GenTree* gtNewCpObjNode(GenTree* dst, GenTree* src, CORINFO_CLASS_HANDLE structHnd, bool isVolatile);
2373 GenTreeArgList* gtNewListNode(GenTree* op1, GenTreeArgList* op2);
2375 GenTreeCall* gtNewCallNode(gtCallTypes callType,
2376 CORINFO_METHOD_HANDLE handle,
2378 GenTreeArgList* args,
2379 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2381 GenTreeCall* gtNewIndCallNode(GenTree* addr,
2383 GenTreeArgList* args,
2384 IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2386 GenTreeCall* gtNewHelperCallNode(unsigned helper, var_types type, GenTreeArgList* args = nullptr);
2388 GenTree* gtNewLclvNode(unsigned lnum, var_types type DEBUGARG(IL_OFFSETX ILoffs = BAD_IL_OFFSET));
2389 GenTree* gtNewLclLNode(unsigned lnum, var_types type DEBUGARG(IL_OFFSETX ILoffs = BAD_IL_OFFSET));
2392 GenTreeSIMD* gtNewSIMDNode(
2393 var_types type, GenTree* op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2394 GenTreeSIMD* gtNewSIMDNode(
2395 var_types type, GenTree* op1, GenTree* op2, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2396 void SetOpLclRelatedToSIMDIntrinsic(GenTree* op);
2399 #ifdef FEATURE_HW_INTRINSICS
2400 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2401 NamedIntrinsic hwIntrinsicID,
2404 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2405 var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2406 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2407 var_types type, GenTree* op1, GenTree* op2, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2408 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2412 NamedIntrinsic hwIntrinsicID,
2415 GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types type,
2420 NamedIntrinsic hwIntrinsicID,
2423 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID);
2424 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type,
2427 NamedIntrinsic hwIntrinsicID);
2428 GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(
2429 var_types type, GenTree* op1, GenTree* op2, GenTree* op3, NamedIntrinsic hwIntrinsicID);
2430 GenTree* gtNewMustThrowException(unsigned helper, var_types type, CORINFO_CLASS_HANDLE clsHnd);
2431 CORINFO_CLASS_HANDLE gtGetStructHandleForHWSIMD(var_types simdType, var_types simdBaseType);
2432 #endif // FEATURE_HW_INTRINSICS
2434 GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
2435 GenTree* gtNewInlineCandidateReturnExpr(GenTree* inlineCandidate, var_types type);
2437 GenTree* gtNewFieldRef(var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0);
2439 GenTree* gtNewIndexRef(var_types typ, GenTree* arrayOp, GenTree* indexOp);
2441 GenTreeArrLen* gtNewArrLen(var_types typ, GenTree* arrayOp, int lenOffset);
2443 GenTree* gtNewIndir(var_types typ, GenTree* addr);
2445 GenTreeArgList* gtNewArgList(GenTree* op);
2446 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2);
2447 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3);
2448 GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3, GenTree* op4);
2450 static fgArgTabEntry* gtArgEntryByArgNum(GenTreeCall* call, unsigned argNum);
2451 static fgArgTabEntry* gtArgEntryByNode(GenTreeCall* call, GenTree* node);
2452 fgArgTabEntry* gtArgEntryByLateArgIndex(GenTreeCall* call, unsigned lateArgInx);
2453 static GenTree* gtArgNodeByLateArgInx(GenTreeCall* call, unsigned lateArgInx);
2454 bool gtArgIsThisPtr(fgArgTabEntry* argEntry);
2456 GenTree* gtNewAssignNode(GenTree* dst, GenTree* src);
2458 GenTree* gtNewTempAssign(unsigned tmp,
2460 GenTree** pAfterStmt = nullptr,
2461 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
2462 BasicBlock* block = nullptr);
2464 GenTree* gtNewRefCOMfield(GenTree* objPtr,
2465 CORINFO_RESOLVED_TOKEN* pResolvedToken,
2466 CORINFO_ACCESS_FLAGS access,
2467 CORINFO_FIELD_INFO* pFieldInfo,
2469 CORINFO_CLASS_HANDLE structType,
2472 GenTree* gtNewNothingNode();
2474 GenTree* gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
2476 GenTree* gtUnusedValNode(GenTree* expr);
2478 GenTreeCast* gtNewCastNode(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2480 GenTreeCast* gtNewCastNodeL(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2482 GenTreeAllocObj* gtNewAllocObjNode(
2483 unsigned int helper, bool helperHasSideEffects, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTree* op1);
2485 GenTreeAllocObj* gtNewAllocObjNode(CORINFO_RESOLVED_TOKEN* pResolvedToken, BOOL useParent);
2487 GenTree* gtNewRuntimeLookup(CORINFO_GENERIC_HANDLE hnd, CorInfoGenericHandleType hndTyp, GenTree* lookupTree);
2489 //------------------------------------------------------------------------
2490 // Other GenTree functions
2492 GenTree* gtClone(GenTree* tree, bool complexOK = false);
2494 // If `tree` is a lclVar with lclNum `varNum`, return an IntCns with value `varVal`; otherwise,
2495 // create a copy of `tree`, adding specified flags, replacing uses of lclVar `deepVarNum` with
2496 // IntCnses with value `deepVarVal`.
2497 GenTree* gtCloneExpr(
2498 GenTree* tree, unsigned addFlags, unsigned varNum, int varVal, unsigned deepVarNum, int deepVarVal);
2500 // Create a copy of `tree`, optionally adding specifed flags, and optionally mapping uses of local
2501 // `varNum` to int constants with value `varVal`.
2502 GenTree* gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = BAD_VAR_NUM, int varVal = 0)
2504 return gtCloneExpr(tree, addFlags, varNum, varVal, varNum, varVal);
2507 // Internal helper for cloning a call
2508 GenTreeCall* gtCloneExprCallHelper(GenTreeCall* call,
2509 unsigned addFlags = 0,
2510 unsigned deepVarNum = BAD_VAR_NUM,
2511 int deepVarVal = 0);
2513 // Create copy of an inline or guarded devirtualization candidate tree.
2514 GenTreeCall* gtCloneCandidateCall(GenTreeCall* call);
2516 GenTree* gtReplaceTree(GenTree* stmt, GenTree* tree, GenTree* replacementTree);
2518 void gtUpdateSideEffects(GenTree* stmt, GenTree* tree);
2520 void gtUpdateTreeAncestorsSideEffects(GenTree* tree);
2522 void gtUpdateStmtSideEffects(GenTree* stmt);
2524 void gtUpdateNodeSideEffects(GenTree* tree);
2526 void gtUpdateNodeOperSideEffects(GenTree* tree);
2528 // Returns "true" iff the complexity (not formally defined, but first interpretation
2529 // is #of nodes in subtree) of "tree" is greater than "limit".
2530 // (This is somewhat redundant with the "gtCostEx/gtCostSz" fields, but can be used
2531 // before they have been set.)
2532 bool gtComplexityExceeds(GenTree** tree, unsigned limit);
2534 bool gtCompareTree(GenTree* op1, GenTree* op2);
2536 GenTree* gtReverseCond(GenTree* tree);
2538 bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
2540 bool gtHasLocalsWithAddrOp(GenTree* tree);
2542 unsigned gtSetListOrder(GenTree* list, bool regs, bool isListCallArgs);
2544 void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* base, bool constOnly);
2547 unsigned gtHashValue(GenTree* tree);
2549 GenTree* gtWalkOpEffectiveVal(GenTree* op);
2552 void gtPrepareCost(GenTree* tree);
2553 bool gtIsLikelyRegVar(GenTree* tree);
2555 // Returns true iff the secondNode can be swapped with firstNode.
2556 bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2558 unsigned gtSetEvalOrder(GenTree* tree);
2560 void gtSetStmtInfo(GenTree* stmt);
2562 // Returns "true" iff "node" has any of the side effects in "flags".
2563 bool gtNodeHasSideEffects(GenTree* node, unsigned flags);
2565 // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2566 bool gtTreeHasSideEffects(GenTree* tree, unsigned flags);
2568 // Appends 'expr' in front of 'list'
2569 // 'list' will typically start off as 'nullptr'
2570 // when 'list' is non-null a GT_COMMA node is used to insert 'expr'
2571 GenTree* gtBuildCommaList(GenTree* list, GenTree* expr);
2573 void gtExtractSideEffList(GenTree* expr,
2575 unsigned flags = GTF_SIDE_EFFECT,
2576 bool ignoreRoot = false);
2578 GenTree* gtGetThisArg(GenTreeCall* call);
2580 // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
2581 // static field contain an object pointer to the boxed struct. This simplifies the GC implementation...but
2582 // complicates the JIT somewhat. This predicate returns "true" iff a node with type "fieldNodeType", representing
2583 // the given "fldHnd", is such an object pointer.
2584 bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);
2586 // Return true if call is a recursive call; return false otherwise.
2587 // Note when inlining, this looks for calls back to the root method.
2588 bool gtIsRecursiveCall(GenTreeCall* call)
2590 return gtIsRecursiveCall(call->gtCallMethHnd);
2593 bool gtIsRecursiveCall(CORINFO_METHOD_HANDLE callMethodHandle)
2595 return (callMethodHandle == impInlineRoot()->info.compMethodHnd);
2598 //-------------------------------------------------------------------------
2600 GenTree* gtFoldExpr(GenTree* tree);
2603 // TODO-Amd64-Unix: Remove this when the clang optimizer is fixed and/or the method implementation is
2604 // refactored in a simpler code. This is a workaround for a bug in the clang-3.5 optimizer. The issue is that in
2605 // release build the optimizer is mistyping (or just wrongly decides to use 32 bit operation for a corner case
2606 // of MIN_LONG) the args of the (ltemp / lval2) to int (it does a 32 bit div operation instead of 64 bit) - see
2607 // the implementation of the method in gentree.cpp. For the case of lval1 and lval2 equal to MIN_LONG
2608 // (0x8000000000000000) this results in raising a SIGFPE. The method implementation is rather complex. Disable
2609 // optimizations for now.
2610 __attribute__((optnone))
2612 gtFoldExprConst(GenTree* tree);
2613 GenTree* gtFoldExprSpecial(GenTree* tree);
2614 GenTree* gtFoldExprCompare(GenTree* tree);
2615 GenTree* gtCreateHandleCompare(genTreeOps oper,
2618 CorInfoInlineTypeCheck typeCheckInliningResult);
2619 GenTree* gtFoldExprCall(GenTreeCall* call);
2620 GenTree* gtFoldTypeCompare(GenTree* tree);
2621 GenTree* gtFoldTypeEqualityCall(CorInfoIntrinsics methodID, GenTree* op1, GenTree* op2);
2623 // Options to control behavior of gtTryRemoveBoxUpstreamEffects
2624 enum BoxRemovalOptions
2626 BR_REMOVE_AND_NARROW, // remove effects, minimize remaining work, return possibly narrowed source tree
2627 BR_REMOVE_AND_NARROW_WANT_TYPE_HANDLE, // remove effects and minimize remaining work, return type handle tree
2628 BR_REMOVE_BUT_NOT_NARROW, // remove effects, return original source tree
2629 BR_DONT_REMOVE, // check if removal is possible, return copy source tree
2630 BR_DONT_REMOVE_WANT_TYPE_HANDLE, // check if removal is possible, return type handle tree
2631 BR_MAKE_LOCAL_COPY // revise box to copy to temp local and return local's address
2634 GenTree* gtTryRemoveBoxUpstreamEffects(GenTree* tree, BoxRemovalOptions options = BR_REMOVE_AND_NARROW);
2635 GenTree* gtOptimizeEnumHasFlag(GenTree* thisOp, GenTree* flagOp);
2637 //-------------------------------------------------------------------------
2638 // Get the handle, if any.
2639 CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTree* tree);
2640 // Get the handle, and assert if not found.
2641 CORINFO_CLASS_HANDLE gtGetStructHandle(GenTree* tree);
2642 // Get the handle for a ref type.
2643 CORINFO_CLASS_HANDLE gtGetClassHandle(GenTree* tree, bool* pIsExact, bool* pIsNonNull);
2644 // Get the class handle for an helper call
2645 CORINFO_CLASS_HANDLE gtGetHelperCallClassHandle(GenTreeCall* call, bool* pIsExact, bool* pIsNonNull);
2646 // Get the element handle for an array of ref type.
2647 CORINFO_CLASS_HANDLE gtGetArrayElementClassHandle(GenTree* array);
2648 // Get a class handle from a helper call argument
2649 CORINFO_CLASS_HANDLE gtGetHelperArgClassHandle(GenTree* array,
2650 unsigned* runtimeLookupCount = nullptr,
2651 GenTree** handleTree = nullptr);
2652 // Get the class handle for a field
2653 CORINFO_CLASS_HANDLE gtGetFieldClassHandle(CORINFO_FIELD_HANDLE fieldHnd, bool* pIsExact, bool* pIsNonNull);
2654 // Check if this tree is a gc static base helper call
2655 bool gtIsStaticGCBaseHelperCall(GenTree* tree);
2657 //-------------------------------------------------------------------------
2658 // Functions to display the trees
2661 void gtDispNode(GenTree* tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
2663 void gtDispVN(GenTree* tree);
2664 void gtDispConst(GenTree* tree);
2665 void gtDispLeaf(GenTree* tree, IndentStack* indentStack);
2666 void gtDispNodeName(GenTree* tree);
2667 void gtDispRegVal(GenTree* tree);
2679 void gtDispChild(GenTree* child,
2680 IndentStack* indentStack,
2682 __in_opt const char* msg = nullptr,
2683 bool topOnly = false);
2684 void gtDispTree(GenTree* tree,
2685 IndentStack* indentStack = nullptr,
2686 __in_opt const char* msg = nullptr,
2687 bool topOnly = false,
2688 bool isLIR = false);
2689 void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
2690 int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
2691 char* gtGetLclVarName(unsigned lclNum);
2692 void gtDispLclVar(unsigned varNum, bool padForBiggestDisp = true);
2693 void gtDispTreeList(GenTree* tree, IndentStack* indentStack = nullptr);
2694 void gtGetArgMsg(GenTreeCall* call, GenTree* arg, unsigned argNum, int listCount, char* bufp, unsigned bufLength);
2695 void gtGetLateArgMsg(GenTreeCall* call, GenTree* arg, int argNum, int listCount, char* bufp, unsigned bufLength);
2696 void gtDispArgList(GenTreeCall* call, IndentStack* indentStack);
2697 void gtDispFieldSeq(FieldSeqNode* pfsn);
2699 void gtDispRange(LIR::ReadOnlyRange const& range);
2701 void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2703 void gtDispLIRNode(GenTree* node, const char* prefixMsg = nullptr);
2715 typedef fgWalkResult(fgWalkPreFn)(GenTree** pTree, fgWalkData* data);
2716 typedef fgWalkResult(fgWalkPostFn)(GenTree** pTree, fgWalkData* data);
2719 static fgWalkPreFn gtAssertColonCond;
2721 static fgWalkPreFn gtMarkColonCond;
2722 static fgWalkPreFn gtClearColonCond;
2724 GenTree** gtFindLink(GenTree* stmt, GenTree* node);
2725 bool gtHasCatchArg(GenTree* tree);
2727 typedef ArrayStack<GenTree*> GenTreeStack;
2729 static bool gtHasCallOnStack(GenTreeStack* parentStack);
2731 //=========================================================================
2732 // BasicBlock functions
2734 // This is a debug flag we will use to assert when creating block during codegen
2735 // as this interferes with procedure splitting. If you know what you're doing, set
2736 // it to true before creating the block. (DEBUG only)
2737 bool fgSafeBasicBlockCreation;
2740 BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2743 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2744 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2748 XX The variables to be used by the code generator. XX
2750 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2751 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2755 // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
2756 // be placed in the stack frame and it's fields must be laid out sequentially.
2758 // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
2759 // a local variable that can be enregistered or placed in the stack frame.
2760 // The fields do not need to be laid out sequentially
2762 enum lvaPromotionType
2764 PROMOTION_TYPE_NONE, // The struct local is not promoted
2765 PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
2766 // and its field locals are independent of its parent struct local.
2767 PROMOTION_TYPE_DEPENDENT // The struct local is promoted,
2768 // but its field locals depend on its parent struct local.
2771 static int __cdecl RefCntCmp(const void* op1, const void* op2);
2772 static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2774 /*****************************************************************************/
2776 enum FrameLayoutState
2779 INITIAL_FRAME_LAYOUT,
2780 PRE_REGALLOC_FRAME_LAYOUT,
2781 REGALLOC_FRAME_LAYOUT,
2782 TENTATIVE_FRAME_LAYOUT,
2787 RefCountState lvaRefCountState; // Current local ref count state
2789 bool lvaLocalVarRefCounted() const
2791 return lvaRefCountState == RCS_NORMAL;
2794 bool lvaTrackedFixed; // true: We cannot add new 'tracked' variable
2795 unsigned lvaCount; // total number of locals
2797 unsigned lvaRefCount; // total number of references to locals
2798 LclVarDsc* lvaTable; // variable descriptor table
2799 unsigned lvaTableCnt; // lvaTable size (>= lvaCount)
2801 LclVarDsc** lvaRefSorted; // table sorted by refcount
2803 unsigned short lvaTrackedCount; // actual # of locals being tracked
2804 unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked
2807 VARSET_TP lvaTrackedVars; // set of tracked variables
2809 #ifndef _TARGET_64BIT_
2810 VARSET_TP lvaLongVars; // set of long (64-bit) variables
2812 VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
2814 unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
2815 // It that changes, this changes. VarSets from different epochs
2816 // cannot be meaningfully combined.
2818 unsigned GetCurLVEpoch()
2823 // reverse map of tracked number to var number
2824 unsigned* lvaTrackedToVarNum;
2828 // # of procs compiled a with double-aligned stack
2829 static unsigned s_lvaDoubleAlignedProcsCount;
2833 // Getters and setters for address-exposed and do-not-enregister local var properties.
2834 bool lvaVarAddrExposed(unsigned varNum);
2835 void lvaSetVarAddrExposed(unsigned varNum);
2836 bool lvaVarDoNotEnregister(unsigned varNum);
2838 // Reasons why we can't enregister. Some of these correspond to debug properties of local vars.
2839 enum DoNotEnregisterReason
2844 DNER_VMNeedsStackAddr,
2845 DNER_LiveInOutOfHandler,
2846 DNER_LiveAcrossUnmanagedCall,
2847 DNER_BlockOp, // Is read or written via a block operation that explicitly takes the address.
2848 DNER_IsStructArg, // Is a struct passed as an argument in a way that requires a stack location.
2849 DNER_DepField, // It is a field of a dependently promoted struct
2850 DNER_NoRegVars, // opts.compFlags & CLFLG_REGVAR is not set
2851 DNER_MinOptsGC, // It is a GC Ref and we are compiling MinOpts
2852 #if !defined(_TARGET_64BIT_)
2853 DNER_LongParamField, // It is a decomposed field of a long parameter.
2855 #ifdef JIT32_GCENCODER
2860 void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2862 unsigned lvaVarargsHandleArg;
2864 unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2866 #endif // _TARGET_X86_
2868 unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
2869 unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
2870 #if FEATURE_FIXED_OUT_ARGS
2871 unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
2873 unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2874 // that tracks whether the lock has been taken
2876 unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
2877 // However, if there is a "ldarga 0" or "starg 0" in the IL,
2878 // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.
2880 unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2881 // in case there are multiple BBJ_RETURN blocks in the inlinee
2882 // or if the inlinee has GC ref locals.
2884 #if FEATURE_FIXED_OUT_ARGS
2885 unsigned lvaOutgoingArgSpaceVar; // dummy TYP_LCLBLK var for fixed outgoing argument space
2886 PhasedVar<unsigned> lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
2887 #endif // FEATURE_FIXED_OUT_ARGS
2890 // On architectures whose ABIs allow structs to be passed in registers, struct promotion will sometimes
2891 // require us to "rematerialize" a struct from it's separate constituent field variables. Packing several sub-word
2892 // field variables into an argument register is a hard problem. It's easier to reserve a word of memory into which
2893 // such field can be copied, after which the assembled memory word can be read into the register. We will allocate
2894 // this variable to be this scratch word whenever struct promotion occurs.
2895 unsigned lvaPromotedStructAssemblyScratchVar;
2896 #endif // _TARGET_ARM_
2898 #if defined(DEBUG) && defined(_TARGET_XARCH_)
2900 unsigned lvaReturnSpCheck; // Stores SP to confirm it is not corrupted on return.
2902 #endif // defined(DEBUG) && defined(_TARGET_XARCH_)
2904 #if defined(DEBUG) && defined(_TARGET_X86_)
2906 unsigned lvaCallSpCheck; // Stores SP to confirm it is not corrupted after every call.
2908 #endif // defined(DEBUG) && defined(_TARGET_X86_)
2910 unsigned lvaGenericsContextUseCount;
2912 bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
2913 // CORINFO_GENERICS_CTXT_FROM_THIS?
2914 bool lvaReportParamTypeArg(); // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?
2916 //-------------------------------------------------------------------------
2917 // All these frame offsets are inter-related and must be kept in sync
2919 #if !FEATURE_EH_FUNCLETS
2920 // This is used for the callable handlers
2921 unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
2922 #endif // FEATURE_EH_FUNCLETS
2924 int lvaCachedGenericContextArgOffs;
2925 int lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2928 #ifdef JIT32_GCENCODER
2930 unsigned lvaLocAllocSPvar; // variable which stores the value of ESP after the the last alloca/localloc
2932 #endif // JIT32_GCENCODER
2934 unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
2936 // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
2937 // after the reg predict we will use a computed maxTmpSize
2938 // which is based upon the number of spill temps predicted by reg predict
2939 // All this is necessary because if we under-estimate the size of the spill
2940 // temps we could fail when encoding instructions that reference stack offsets for ARM.
2942 // Pre codegen max spill temp size.
2943 static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2945 //-------------------------------------------------------------------------
2947 unsigned lvaGetMaxSpillTempSize();
2949 bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2950 #endif // _TARGET_ARM_
2951 void lvaAssignFrameOffsets(FrameLayoutState curState);
2952 void lvaFixVirtualFrameOffsets();
2953 void lvaUpdateArgsWithInitialReg();
2954 void lvaAssignVirtualFrameOffsetsToArgs();
2955 #ifdef UNIX_AMD64_ABI
2956 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
2957 #else // !UNIX_AMD64_ABI
2958 int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
2959 #endif // !UNIX_AMD64_ABI
2960 void lvaAssignVirtualFrameOffsetsToLocals();
2961 int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
2962 #ifdef _TARGET_AMD64_
2963 // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
2964 bool lvaIsCalleeSavedIntRegCountEven();
2966 void lvaAlignFrame();
2967 void lvaAssignFrameOffsetsToPromotedStructs();
2968 int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
2971 void lvaDumpRegLocation(unsigned lclNum);
2972 void lvaDumpFrameLocation(unsigned lclNum);
2973 void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
2974 void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
2975 // layout state defined by lvaDoneFrameLayout
2978 // Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
2979 // to avoid bugs from borderline cases.
2980 #define MAX_FrameSize 0x3FFFFFFF
2981 void lvaIncrementFrameSize(unsigned size);
2983 unsigned lvaFrameSize(FrameLayoutState curState);
2985 // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2986 int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2988 // Returns the caller-SP-relative offset for the local variable "varNum."
2989 int lvaGetCallerSPRelativeOffset(unsigned varNum);
2991 // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2992 int lvaGetSPRelativeOffset(unsigned varNum);
2994 int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2995 int lvaGetInitialSPRelativeOffset(unsigned varNum);
2997 //------------------------ For splitting types ----------------------------
2999 void lvaInitTypeRef();
3001 void lvaInitArgs(InitVarDscInfo* varDscInfo);
3002 void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
3003 void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo);
3004 void lvaInitUserArgs(InitVarDscInfo* varDscInfo);
3005 void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
3006 void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);
3008 void lvaInitVarDsc(LclVarDsc* varDsc,
3010 CorInfoType corInfoType,
3011 CORINFO_CLASS_HANDLE typeHnd,
3012 CORINFO_ARG_LIST_HANDLE varList,
3013 CORINFO_SIG_INFO* varSig);
3015 static unsigned lvaTypeRefMask(var_types type);
3017 var_types lvaGetActualType(unsigned lclNum);
3018 var_types lvaGetRealType(unsigned lclNum);
3020 //-------------------------------------------------------------------------
3024 LclVarDsc* lvaGetDesc(unsigned lclNum)
3026 assert(lclNum < lvaCount);
3027 return &lvaTable[lclNum];
3030 LclVarDsc* lvaGetDesc(GenTreeLclVarCommon* lclVar)
3032 assert(lclVar->GetLclNum() < lvaCount);
3033 return &lvaTable[lclVar->GetLclNum()];
3036 unsigned lvaLclSize(unsigned varNum);
3037 unsigned lvaLclExactSize(unsigned varNum);
3039 bool lvaHaveManyLocals() const;
3041 unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
3042 unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
3043 unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));
3046 void lvaSortByRefCount();
3047 void lvaDumpRefCounts();
3049 void lvaMarkLocalVars(); // Local variable ref-counting
3050 void lvaComputeRefCounts(bool isRecompute, bool setSlotNumbers);
3051 void lvaMarkLocalVars(BasicBlock* block, bool isRecompute);
3053 void lvaAllocOutgoingArgSpaceVar(); // Set up lvaOutgoingArgSpaceVar
3055 VARSET_VALRET_TP lvaStmtLclMask(GenTree* stmt);
3058 struct lvaStressLclFldArgs
3060 Compiler* m_pCompiler;
3064 static fgWalkPreFn lvaStressLclFldCB;
3065 void lvaStressLclFld();
3067 void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
3068 void lvaDispVarSet(VARSET_VALARG_TP set);
3073 int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset, bool isFloatUsage);
3075 int lvaFrameAddress(int varNum, bool* pFPbased);
3078 bool lvaIsParameter(unsigned varNum);
3079 bool lvaIsRegArgument(unsigned varNum);
3080 BOOL lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
3081 BOOL lvaIsOriginalThisReadOnly(); // return TRUE if there is no place in the code
3082 // that writes to arg0
3084 // Struct parameters that are passed by reference are marked as both lvIsParam and lvIsTemp
3085 // (this is an overload of lvIsTemp because there are no temp parameters).
3086 // For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference.
3087 // For ARM64, this is structs larger than 16 bytes that are passed by reference.
3088 bool lvaIsImplicitByRefLocal(unsigned varNum)
3090 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
3091 LclVarDsc* varDsc = &(lvaTable[varNum]);
3092 if (varDsc->lvIsParam && varDsc->lvIsTemp)
3094 assert(varTypeIsStruct(varDsc) || (varDsc->lvType == TYP_BYREF));
3097 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
3101 // Returns true if this local var is a multireg struct
3102 bool lvaIsMultiregStruct(LclVarDsc* varDsc, bool isVararg);
3104 // If the local is a TYP_STRUCT, get/set a class handle describing it
3105 CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
3106 void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
3107 void lvaSetStructUsedAsVarArg(unsigned varNum);
3109 // If the local is TYP_REF, set or update the associated class information.
3110 void lvaSetClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
3111 void lvaSetClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
3112 void lvaUpdateClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
3113 void lvaUpdateClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
3115 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
3117 // Info about struct type fields.
3118 struct lvaStructFieldInfo
3120 CORINFO_FIELD_HANDLE fldHnd;
3121 unsigned char fldOffset;
3122 unsigned char fldOrdinal;
3125 CORINFO_CLASS_HANDLE fldTypeHnd;
3127 lvaStructFieldInfo()
3128 : fldHnd(nullptr), fldOffset(0), fldOrdinal(0), fldType(TYP_UNDEF), fldSize(0), fldTypeHnd(nullptr)
3133 // Info about a struct type, instances of which may be candidates for promotion.
3134 struct lvaStructPromotionInfo
3136 CORINFO_CLASS_HANDLE typeHnd;
3141 unsigned char fieldCnt;
3142 lvaStructFieldInfo fields[MAX_NumOfFieldsInPromotableStruct];
3144 lvaStructPromotionInfo(CORINFO_CLASS_HANDLE typeHnd = nullptr)
3147 , containsHoles(false)
3148 , customLayout(false)
3149 , fieldsSorted(false)
3155 static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
3157 // This class is responsible for checking validity and profitability of struct promotion.
3158 // If it is both legal and profitable, then TryPromoteStructVar promotes the struct and initializes
3159 // nessesary information for fgMorphStructField to use.
3160 class StructPromotionHelper
3163 StructPromotionHelper(Compiler* compiler);
3165 bool CanPromoteStructType(CORINFO_CLASS_HANDLE typeHnd);
3166 bool TryPromoteStructVar(unsigned lclNum);
3169 void CheckRetypedAsScalar(CORINFO_FIELD_HANDLE fieldHnd, var_types requestedType);
3173 bool GetRequiresScratchVar();
3174 #endif // _TARGET_ARM_
3177 bool CanPromoteStructVar(unsigned lclNum);
3178 bool ShouldPromoteStructVar(unsigned lclNum);
3179 void PromoteStructVar(unsigned lclNum);
3180 void SortStructFields();
3182 lvaStructFieldInfo GetFieldInfo(CORINFO_FIELD_HANDLE fieldHnd, BYTE ordinal);
3183 bool TryPromoteStructField(lvaStructFieldInfo& outerFieldInfo);
3187 lvaStructPromotionInfo structPromotionInfo;
3190 bool requiresScratchVar;
3191 #endif // _TARGET_ARM_
3194 typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<CORINFO_FIELD_STRUCT_>, var_types>
3195 RetypedAsScalarFieldsMap;
3196 RetypedAsScalarFieldsMap retypedFieldsMap;
3200 StructPromotionHelper* structPromotionHelper;
3202 #if !defined(_TARGET_64BIT_)
3203 void lvaPromoteLongVars();
3204 #endif // !defined(_TARGET_64BIT_)
3205 unsigned lvaGetFieldLocal(const LclVarDsc* varDsc, unsigned int fldOffset);
3206 lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
3207 lvaPromotionType lvaGetPromotionType(unsigned varNum);
3208 lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
3209 lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
3210 bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
3211 bool lvaIsGCTracked(const LclVarDsc* varDsc);
3213 #if defined(FEATURE_SIMD)
3214 bool lvaMapSimd12ToSimd16(const LclVarDsc* varDsc)
3216 assert(varDsc->lvType == TYP_SIMD12);
3217 assert(varDsc->lvExactSize == 12);
3219 #if defined(_TARGET_64BIT_)
3220 assert(varDsc->lvSize() == 16);
3221 #endif // defined(_TARGET_64BIT_)
3223 // We make local variable SIMD12 types 16 bytes instead of just 12. lvSize()
3224 // already does this calculation. However, we also need to prevent mapping types if the var is a
3225 // dependently promoted struct field, which must remain its exact size within its parent struct.
3226 // However, we don't know this until late, so we may have already pretended the field is bigger
3228 if ((varDsc->lvSize() == 16) && !lvaIsFieldOfDependentlyPromotedStruct(varDsc))
3237 #endif // defined(FEATURE_SIMD)
3239 BYTE* lvaGetGcLayout(unsigned varNum);
3240 bool lvaTypeIsGC(unsigned varNum);
3241 unsigned lvaGSSecurityCookie; // LclVar number
3242 bool lvaTempsHaveLargerOffsetThanVars();
3244 // Returns "true" iff local variable "lclNum" is in SSA form.
3245 bool lvaInSsa(unsigned lclNum)
3247 assert(lclNum < lvaCount);
3248 return lvaTable[lclNum].lvInSsa;
3251 unsigned lvaSecurityObject; // variable representing the security object on the stack
3252 unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
3254 #if FEATURE_EH_FUNCLETS
3255 unsigned lvaPSPSym; // variable representing the PSPSym
3258 InlineInfo* impInlineInfo;
3259 InlineStrategy* m_inlineStrategy;
3261 // The Compiler* that is the root of the inlining tree of which "this" is a member.
3262 Compiler* impInlineRoot();
3264 #if defined(DEBUG) || defined(INLINE_DATA)
3265 unsigned __int64 getInlineCycleCount()
3267 return m_compCycles;
3269 #endif // defined(DEBUG) || defined(INLINE_DATA)
3271 bool fgNoStructPromotion; // Set to TRUE to turn off struct promotion for this method.
3272 bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.
3274 //=========================================================================
3276 //=========================================================================
3279 //---------------- Local variable ref-counting ----------------------------
3281 void lvaMarkLclRefs(GenTree* tree, BasicBlock* block, GenTreeStmt* stmt, bool isRecompute);
3282 bool IsDominatedByExceptionalEntry(BasicBlock* block);
3283 void SetVolatileHint(LclVarDsc* varDsc);
3285 // Keeps the mapping from SSA #'s to VN's for the implicit memory variables.
3286 SsaDefArray<SsaMemDef> lvMemoryPerSsaData;
3289 // Returns the address of the per-Ssa data for memory at the given ssaNum (which is required
3290 // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
3291 // not an SSA variable).
3292 SsaMemDef* GetMemoryPerSsaData(unsigned ssaNum)
3294 return lvMemoryPerSsaData.GetSsaDef(ssaNum);
3298 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3299 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3303 XX Imports the given method and converts it to semantic trees XX
3305 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3306 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3312 void impImport(BasicBlock* method);
3314 CORINFO_CLASS_HANDLE impGetRefAnyClass();
3315 CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
3316 CORINFO_CLASS_HANDLE impGetTypeHandleClass();
3317 CORINFO_CLASS_HANDLE impGetStringClass();
3318 CORINFO_CLASS_HANDLE impGetObjectClass();
3320 // Returns underlying type of handles returned by ldtoken instruction
3321 var_types GetRuntimeHandleUnderlyingType()
3323 // RuntimeTypeHandle is backed by raw pointer on CoreRT and by object reference on other runtimes
3324 return IsTargetAbi(CORINFO_CORERT_ABI) ? TYP_I_IMPL : TYP_REF;
3327 void impDevirtualizeCall(GenTreeCall* call,
3328 CORINFO_METHOD_HANDLE* method,
3329 unsigned* methodFlags,
3330 CORINFO_CONTEXT_HANDLE* contextHandle,
3331 CORINFO_CONTEXT_HANDLE* exactContextHandle,
3332 bool isLateDevirtualization);
3334 //=========================================================================
3336 //=========================================================================
3339 //-------------------- Stack manipulation ---------------------------------
3341 unsigned impStkSize; // Size of the full stack
3343 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
3345 struct SavedStack // used to save/restore stack contents.
3347 unsigned ssDepth; // number of values on stack
3348 StackEntry* ssTrees; // saved tree values
3351 bool impIsPrimitive(CorInfoType type);
3352 bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
3354 void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
3356 void impPushOnStack(GenTree* tree, typeInfo ti);
3357 void impPushNullObjRefOnStack();
3358 StackEntry impPopStack();
3359 StackEntry& impStackTop(unsigned n = 0);
3360 unsigned impStackHeight();
3362 void impSaveStackState(SavedStack* savePtr, bool copy);
3363 void impRestoreStackState(SavedStack* savePtr);
3365 GenTree* impImportLdvirtftn(GenTree* thisPtr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3367 void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
3369 void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3371 bool impCanPInvokeInline();
3372 bool impCanPInvokeInlineCallSite(BasicBlock* block);
3373 void impCheckForPInvokeCall(
3374 GenTreeCall* call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags, BasicBlock* block);
3375 GenTreeCall* impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset = BAD_IL_OFFSET);
3376 void impPopArgsForUnmanagedCall(GenTree* call, CORINFO_SIG_INFO* sig);
3378 void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
3379 void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
3380 void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
3382 var_types impImportCall(OPCODE opcode,
3383 CORINFO_RESOLVED_TOKEN* pResolvedToken,
3384 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
3386 GenTree* newobjThis,
3388 CORINFO_CALL_INFO* callInfo,
3389 IL_OFFSET rawILOffset);
3391 CORINFO_CLASS_HANDLE impGetSpecialIntrinsicExactReturnType(CORINFO_METHOD_HANDLE specialIntrinsicHandle);
3393 bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
3395 GenTree* impFixupCallStructReturn(GenTreeCall* call, CORINFO_CLASS_HANDLE retClsHnd);
3397 GenTree* impFixupStructReturnType(GenTree* op, CORINFO_CLASS_HANDLE retClsHnd);
3400 var_types impImportJitTestLabelMark(int numArgs);
3403 GenTree* impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
3405 GenTree* impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
3407 GenTree* impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3408 CORINFO_ACCESS_FLAGS access,
3409 CORINFO_FIELD_INFO* pFieldInfo,
3412 static void impBashVarAddrsToI(GenTree* tree1, GenTree* tree2 = nullptr);
3414 GenTree* impImplicitIorI4Cast(GenTree* tree, var_types dstTyp);
3416 GenTree* impImplicitR4orR8Cast(GenTree* tree, var_types dstTyp);
3418 void impImportLeave(BasicBlock* block);
3419 void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
3420 GenTree* impIntrinsic(GenTree* newobjThis,
3421 CORINFO_CLASS_HANDLE clsHnd,
3422 CORINFO_METHOD_HANDLE method,
3423 CORINFO_SIG_INFO* sig,
3424 unsigned methodFlags,
3428 CORINFO_RESOLVED_TOKEN* pContstrainedResolvedToken,
3429 CORINFO_THIS_TRANSFORM constraintCallThisTransform,
3430 CorInfoIntrinsics* pIntrinsicID,
3431 bool* isSpecialIntrinsic = nullptr);
3432 GenTree* impMathIntrinsic(CORINFO_METHOD_HANDLE method,
3433 CORINFO_SIG_INFO* sig,
3435 CorInfoIntrinsics intrinsicID,
3437 NamedIntrinsic lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method);
3439 #ifdef FEATURE_HW_INTRINSICS
3440 GenTree* impBaseIntrinsic(NamedIntrinsic intrinsic,
3441 CORINFO_CLASS_HANDLE clsHnd,
3442 CORINFO_METHOD_HANDLE method,
3443 CORINFO_SIG_INFO* sig);
3444 GenTree* impHWIntrinsic(NamedIntrinsic intrinsic,
3445 CORINFO_METHOD_HANDLE method,
3446 CORINFO_SIG_INFO* sig,
3448 GenTree* impUnsupportedHWIntrinsic(unsigned helper,
3449 CORINFO_METHOD_HANDLE method,
3450 CORINFO_SIG_INFO* sig,
3454 bool compSupportsHWIntrinsic(InstructionSet isa);
3456 #ifdef _TARGET_XARCH_
3457 GenTree* impSSEIntrinsic(NamedIntrinsic intrinsic,
3458 CORINFO_METHOD_HANDLE method,
3459 CORINFO_SIG_INFO* sig,
3461 GenTree* impSSE2Intrinsic(NamedIntrinsic intrinsic,
3462 CORINFO_METHOD_HANDLE method,
3463 CORINFO_SIG_INFO* sig,
3465 GenTree* impSSE42Intrinsic(NamedIntrinsic intrinsic,
3466 CORINFO_METHOD_HANDLE method,
3467 CORINFO_SIG_INFO* sig,
3469 GenTree* impAvxOrAvx2Intrinsic(NamedIntrinsic intrinsic,
3470 CORINFO_METHOD_HANDLE method,
3471 CORINFO_SIG_INFO* sig,
3473 GenTree* impAESIntrinsic(NamedIntrinsic intrinsic,
3474 CORINFO_METHOD_HANDLE method,
3475 CORINFO_SIG_INFO* sig,
3477 GenTree* impBMI1OrBMI2Intrinsic(NamedIntrinsic intrinsic,
3478 CORINFO_METHOD_HANDLE method,
3479 CORINFO_SIG_INFO* sig,
3481 GenTree* impFMAIntrinsic(NamedIntrinsic intrinsic,
3482 CORINFO_METHOD_HANDLE method,
3483 CORINFO_SIG_INFO* sig,
3485 GenTree* impLZCNTIntrinsic(NamedIntrinsic intrinsic,
3486 CORINFO_METHOD_HANDLE method,
3487 CORINFO_SIG_INFO* sig,
3489 GenTree* impPCLMULQDQIntrinsic(NamedIntrinsic intrinsic,
3490 CORINFO_METHOD_HANDLE method,
3491 CORINFO_SIG_INFO* sig,
3493 GenTree* impPOPCNTIntrinsic(NamedIntrinsic intrinsic,
3494 CORINFO_METHOD_HANDLE method,
3495 CORINFO_SIG_INFO* sig,
3499 GenTree* getArgForHWIntrinsic(var_types argType, CORINFO_CLASS_HANDLE argClass);
3500 GenTree* impNonConstFallback(NamedIntrinsic intrinsic, var_types simdType, var_types baseType);
3501 GenTree* addRangeCheckIfNeeded(NamedIntrinsic intrinsic, GenTree* lastOp, bool mustExpand);
3502 #endif // _TARGET_XARCH_
3503 #ifdef _TARGET_ARM64_
3504 InstructionSet lookupHWIntrinsicISA(const char* className);
3505 NamedIntrinsic lookupHWIntrinsic(const char* className, const char* methodName);
3506 bool impCheckImmediate(GenTree* immediateOp, unsigned int max);
3507 #endif // _TARGET_ARM64_
3508 #endif // FEATURE_HW_INTRINSICS
3509 GenTree* impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
3510 CORINFO_SIG_INFO* sig,
3513 CorInfoIntrinsics intrinsicID);
3514 GenTree* impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
3516 GenTree* impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3518 GenTree* impTransformThis(GenTree* thisPtr,
3519 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
3520 CORINFO_THIS_TRANSFORM transform);
3522 //----------------- Manipulating the trees and stmts ----------------------
3524 GenTree* impTreeList; // Trees for the BB being imported
3525 GenTree* impTreeLast; // The last tree for the current BB
3530 CHECK_SPILL_ALL = -1,
3531 CHECK_SPILL_NONE = -2
3534 void impBeginTreeList();
3535 void impEndTreeList(BasicBlock* block, GenTree* firstStmt, GenTree* lastStmt);
3536 void impEndTreeList(BasicBlock* block);
3537 void impAppendStmtCheck(GenTree* stmt, unsigned chkLevel);
3538 void impAppendStmt(GenTree* stmt, unsigned chkLevel);
3539 void impInsertStmtBefore(GenTree* stmt, GenTree* stmtBefore);
3540 GenTree* impAppendTree(GenTree* tree, unsigned chkLevel, IL_OFFSETX offset);
3541 void impInsertTreeBefore(GenTree* tree, IL_OFFSETX offset, GenTree* stmtBefore);
3542 void impAssignTempGen(unsigned tmp,
3545 GenTree** pAfterStmt = nullptr,
3546 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3547 BasicBlock* block = nullptr);
3548 void impAssignTempGen(unsigned tmpNum,
3550 CORINFO_CLASS_HANDLE structHnd,
3552 GenTree** pAfterStmt = nullptr,
3553 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3554 BasicBlock* block = nullptr);
3555 GenTree* impCloneExpr(GenTree* tree,
3557 CORINFO_CLASS_HANDLE structHnd,
3559 GenTree** pAfterStmt DEBUGARG(const char* reason));
3560 GenTree* impAssignStruct(GenTree* dest,
3562 CORINFO_CLASS_HANDLE structHnd,
3564 GenTree** pAfterStmt = nullptr,
3565 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3566 BasicBlock* block = nullptr);
3567 GenTree* impAssignStructPtr(GenTree* dest,
3569 CORINFO_CLASS_HANDLE structHnd,
3571 GenTree** pAfterStmt = nullptr,
3572 IL_OFFSETX ilOffset = BAD_IL_OFFSET,
3573 BasicBlock* block = nullptr);
3575 GenTree* impGetStructAddr(GenTree* structVal, CORINFO_CLASS_HANDLE structHnd, unsigned curLevel, bool willDeref);
3577 var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
3578 BYTE* gcLayout = nullptr,
3579 unsigned* numGCVars = nullptr,
3580 var_types* simdBaseType = nullptr);
3582 GenTree* impNormStructVal(GenTree* structVal,
3583 CORINFO_CLASS_HANDLE structHnd,
3585 bool forceNormalization = false);
3587 GenTree* impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3588 BOOL* pRuntimeLookup = nullptr,
3589 BOOL mustRestoreHandle = FALSE,
3590 BOOL importParent = FALSE);
3592 GenTree* impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3593 BOOL* pRuntimeLookup = nullptr,
3594 BOOL mustRestoreHandle = FALSE)
3596 return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
3599 GenTree* impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3600 CORINFO_LOOKUP* pLookup,
3602 void* compileTimeHandle);
3604 GenTree* getRuntimeContextTree(CORINFO_RUNTIME_LOOKUP_KIND kind);
3606 GenTree* impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3607 CORINFO_LOOKUP* pLookup,
3608 void* compileTimeHandle);
3610 GenTree* impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
3612 GenTreeCall* impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3613 CorInfoHelpFunc helper,
3615 GenTreeArgList* arg = nullptr,
3616 CORINFO_LOOKUP_KIND* pGenericLookupKind = nullptr);
3618 GenTree* impCastClassOrIsInstToTree(GenTree* op1,
3620 CORINFO_RESOLVED_TOKEN* pResolvedToken,
3623 GenTree* impOptimizeCastClassOrIsInst(GenTree* op1, CORINFO_RESOLVED_TOKEN* pResolvedToken, bool isCastClass);
3625 bool VarTypeIsMultiByteAndCanEnreg(
3626 var_types type, CORINFO_CLASS_HANDLE typeClass, unsigned* typeSize, bool forReturn, bool isVarArg);
3628 bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
3629 bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
3630 bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
3631 bool IsMathIntrinsic(GenTree* tree);
3634 //----------------- Importing the method ----------------------------------
3636 CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
3639 unsigned impCurOpcOffs;
3640 const char* impCurOpcName;
3641 bool impNestedStackSpill;
3643 // For displaying instrs with generated native code (-n:B)
3644 GenTree* impLastILoffsStmt; // oldest stmt added for which we did not gtStmtLastILoffs
3645 void impNoteLastILoffs();
3648 /* IL offset of the stmt currently being imported. It gets set to
3649 BAD_IL_OFFSET after it has been set in the appended trees. Then it gets
3650 updated at IL offsets for which we have to report mapping info.
3651 It also includes flag bits, so use jitGetILoffs()
3652 to get the actual IL offset value.
3655 IL_OFFSETX impCurStmtOffs;
3656 void impCurStmtOffsSet(IL_OFFSET offs);
3658 void impNoteBranchOffs();
3660 unsigned impInitBlockLineInfo();
3662 GenTree* impCheckForNullPointer(GenTree* obj);
3663 bool impIsThis(GenTree* obj);
3664 bool impIsLDFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3665 bool impIsDUP_LDVIRTFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3666 bool impIsAnySTLOC(OPCODE opcode)
3668 return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
3669 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
3672 GenTreeArgList* impPopList(unsigned count, CORINFO_SIG_INFO* sig, GenTreeArgList* prefixTree = nullptr);
3674 GenTreeArgList* impPopRevList(unsigned count, CORINFO_SIG_INFO* sig, unsigned skipReverseCount = 0);
3677 * Get current IL offset with stack-empty info incoporated
3679 IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
3681 //---------------- Spilling the importer stack ----------------------------
3683 // The maximum number of bytes of IL processed without clean stack state.
3684 // It allows to limit the maximum tree size and depth.
3685 static const unsigned MAX_TREE_SIZE = 200;
3686 bool impCanSpillNow(OPCODE prevOpcode);
3692 SavedStack pdSavedStack;
3693 ThisInitState pdThisPtrInit;
3696 PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
3697 PendingDsc* impPendingFree; // Freed up dscs that can be reused
3699 // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
3700 JitExpandArray<BYTE> impPendingBlockMembers;
3702 // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
3703 // Operates on the map in the top-level ancestor.
3704 BYTE impGetPendingBlockMember(BasicBlock* blk)
3706 return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
3709 // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
3710 // Operates on the map in the top-level ancestor.
3711 void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
3713 impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
3716 bool impCanReimport;
3718 bool impSpillStackEntry(unsigned level,
3722 bool bAssertOnRecursion,
3727 void impSpillStackEnsure(bool spillLeaves = false);
3728 void impEvalSideEffects();
3729 void impSpillSpecialSideEff();
3730 void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
3731 void impSpillValueClasses();
3732 void impSpillEvalStack();
3733 static fgWalkPreFn impFindValueClasses;
3734 void impSpillLclRefs(ssize_t lclNum);
3736 BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd, bool isSingleBlockFilter);
3738 void impImportBlockCode(BasicBlock* block);
3740 void impReimportMarkBlock(BasicBlock* block);
3741 void impReimportMarkSuccessors(BasicBlock* block);
3743 void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3745 void impImportBlockPending(BasicBlock* block);
3747 // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
3748 // reimported for some reason. It specifically does *not* look at verCurrentState to set the EntryState
3749 // for the block, but instead, just re-uses the block's existing EntryState.
3750 void impReimportBlockPending(BasicBlock* block);
3752 var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTree** pOp1, GenTree** pOp2);
3754 void impImportBlock(BasicBlock* block);
3756 // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
3757 // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
3758 // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
3759 // the variables that will be used -- and for all the predecessors of those successors, and the
3760 // successors of those predecessors, etc. Call such a set of blocks closed under alternating
3761 // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
3762 // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
3763 // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
3764 // of local variable numbers, so we represent them with the base local variable number), returns that.
3765 // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
3766 // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
3767 // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
3768 // on which kind of member of the clique the block is).
3769 unsigned impGetSpillTmpBase(BasicBlock* block);
3771 // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
3772 // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
3773 // will assume that its incoming stack contents are in those locals. This requires "block" and its
3774 // successors to agree on the variables and their types that will be used. The CLI spec allows implicit
3775 // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
3776 // push an int and another can push a native int. For 64-bit we have chosen to implement this by typing
3777 // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
3778 // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
3779 // successors receive a native int. Similarly float and double are unified to double.
3780 // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
3781 // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
3782 // predecessors, so they insert an upcast if needed).
3783 void impReimportSpillClique(BasicBlock* block);
3785 // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
3786 // block, and represent the predecessor and successor members of the clique currently being computed.
3787 // *** Access to these will need to be locked in a parallel compiler.
3788 JitExpandArray<BYTE> impSpillCliquePredMembers;
3789 JitExpandArray<BYTE> impSpillCliqueSuccMembers;
3797 // Abstract class for receiving a callback while walking a spill clique
3798 class SpillCliqueWalker
3801 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3804 // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3805 class SetSpillTempsBase : public SpillCliqueWalker
3810 SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3813 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3816 // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3817 class ReimportSpillClique : public SpillCliqueWalker
3822 ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3825 virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3828 // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
3829 // predecessor or successor within the spill clique
3830 void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);
3832 // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
3833 // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
3834 // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
3835 void impRetypeEntryStateTemps(BasicBlock* blk);
3837 BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3838 void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
3840 void impPushVar(GenTree* op, typeInfo tiRetVal);
3841 void impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal);
3842 void impLoadVar(unsigned lclNum, IL_OFFSET offset)
3844 impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
3846 void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
3847 void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
3848 bool impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode);
3851 void impMarkLclDstNotPromotable(unsigned tmpNum, GenTree* op, CORINFO_CLASS_HANDLE hClass);
3854 // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3855 struct BlockListNode
3858 BlockListNode* m_next;
3859 BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3862 void* operator new(size_t sz, Compiler* comp);
3864 BlockListNode* impBlockListNodeFreeList;
3866 void FreeBlockListNode(BlockListNode* node);
3868 bool impIsValueType(typeInfo* pTypeInfo);
3869 var_types mangleVarArgsType(var_types type);
3872 regNumber getCallArgIntRegister(regNumber floatReg);
3873 regNumber getCallArgFloatRegister(regNumber intReg);
3874 #endif // FEATURE_VARARG
3877 static unsigned jitTotalMethodCompiled;
3881 static LONG jitNestingLevel;
3884 static BOOL impIsAddressInLocal(GenTree* tree, GenTree** lclVarTreeOut);
3886 void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3888 // STATIC inlining decision based on the IL code.
3889 void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3890 CORINFO_METHOD_INFO* methInfo,
3892 InlineResult* inlineResult);
3894 void impCheckCanInline(GenTreeCall* call,
3895 CORINFO_METHOD_HANDLE fncHandle,
3897 CORINFO_CONTEXT_HANDLE exactContextHnd,
3898 InlineCandidateInfo** ppInlineCandidateInfo,
3899 InlineResult* inlineResult);
3901 void impInlineRecordArgInfo(InlineInfo* pInlineInfo,
3904 InlineResult* inlineResult);
3906 void impInlineInitVars(InlineInfo* pInlineInfo);
3908 unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3910 GenTree* impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3912 BOOL impInlineIsThis(GenTree* tree, InlArgInfo* inlArgInfo);
3914 BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTree* additionalTreesToBeEvaluatedBefore,
3915 GenTree* variableBeingDereferenced,
3916 InlArgInfo* inlArgInfo);
3918 void impMarkInlineCandidate(GenTree* call,
3919 CORINFO_CONTEXT_HANDLE exactContextHnd,
3920 bool exactContextNeedsRuntimeLookup,
3921 CORINFO_CALL_INFO* callInfo);
3923 void impMarkInlineCandidateHelper(GenTreeCall* call,
3924 CORINFO_CONTEXT_HANDLE exactContextHnd,
3925 bool exactContextNeedsRuntimeLookup,
3926 CORINFO_CALL_INFO* callInfo);
3928 bool impTailCallRetTypeCompatible(var_types callerRetType,
3929 CORINFO_CLASS_HANDLE callerRetTypeClass,
3930 var_types calleeRetType,
3931 CORINFO_CLASS_HANDLE calleeRetTypeClass);
3933 bool impIsTailCallILPattern(bool tailPrefixed,
3935 const BYTE* codeAddrOfNextOpcode,
3936 const BYTE* codeEnd,
3938 bool* IsCallPopRet = nullptr);
3940 bool impIsImplicitTailCallCandidate(
3941 OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3943 CORINFO_RESOLVED_TOKEN* impAllocateToken(CORINFO_RESOLVED_TOKEN token);
3946 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3947 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3951 XX Info about the basic-blocks, their contents and the flow analysis XX
3953 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3954 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3958 BasicBlock* fgFirstBB; // Beginning of the basic block list
3959 BasicBlock* fgLastBB; // End of the basic block list
3960 BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
3961 #if FEATURE_EH_FUNCLETS
3962 BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
3964 BasicBlock* fgFirstBBScratch; // Block inserted for initialization stuff. Is nullptr if no such block has been
3966 BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
3967 unsigned fgEdgeCount; // # of control flow edges between the BBs
3968 unsigned fgBBcount; // # of BBs in the method
3970 unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
3972 unsigned fgBBNumMax; // The max bbNum that has been assigned to basic blocks
3973 unsigned fgDomBBcount; // # of BBs for which we have dominator and reachability information
3974 BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
3975 // dominance. Indexed by block number. Size: fgBBNumMax + 1.
3977 // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
3978 // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
3979 // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
3980 // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
3981 // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
3982 // index). The arrays are of size fgBBNumMax + 1.
3983 unsigned* fgDomTreePreOrder;
3984 unsigned* fgDomTreePostOrder;
3986 bool fgBBVarSetsInited;
3988 // Allocate array like T* a = new T[fgBBNumMax + 1];
3989 // Using helper so we don't keep forgetting +1.
3990 template <typename T>
3991 T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
3993 return getAllocator(cmk).allocate<T>(fgBBNumMax + 1);
3996 // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
3997 // (if the blocks are renumbered), this changes. BlockSets from different epochs
3998 // cannot be meaningfully combined. Note that new blocks can be created with higher
3999 // block numbers without changing the basic block epoch. These blocks *cannot*
4000 // participate in a block set until the blocks are all renumbered, causing the epoch
4001 // to change. This is useful if continuing to use previous block sets is valuable.
4002 // If the epoch is zero, then it is uninitialized, and block sets can't be used.
4003 unsigned fgCurBBEpoch;
4005 unsigned GetCurBasicBlockEpoch()
4007 return fgCurBBEpoch;
4010 // The number of basic blocks in the current epoch. When the blocks are renumbered,
4011 // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
4012 // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
4013 unsigned fgCurBBEpochSize;
4015 // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
4016 // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
4017 unsigned fgBBSetCountInSizeTUnits;
4019 void NewBasicBlockEpoch()
4021 INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
4023 // We have a new epoch. Compute and cache the size needed for new BlockSets.
4025 fgCurBBEpochSize = fgBBNumMax + 1;
4026 fgBBSetCountInSizeTUnits =
4027 roundUp(fgCurBBEpochSize, (unsigned)(sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
4030 // All BlockSet objects are now invalid!
4031 fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
4032 fgEnterBlksSetValid = false; // the fgEnterBlks set is now invalid!
4036 unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this, sizeof(size_t));
4037 printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
4038 fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
4039 if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
4041 // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
4042 // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
4043 // array of size_t bitsets), then print that out.
4044 printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
4051 void EnsureBasicBlockEpoch()
4053 if (fgCurBBEpochSize != fgBBNumMax + 1)
4055 NewBasicBlockEpoch();
4059 BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
4060 void fgEnsureFirstBBisScratch();
4061 bool fgFirstBBisScratch();
4062 bool fgBBisScratch(BasicBlock* block);
4064 void fgExtendEHRegionBefore(BasicBlock* block);
4065 void fgExtendEHRegionAfter(BasicBlock* block);
4067 BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
4069 BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
4071 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
4074 BasicBlock* nearBlk,
4075 bool putInFilter = false,
4076 bool runRarely = false,
4077 bool insertAtEnd = false);
4079 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
4081 bool runRarely = false,
4082 bool insertAtEnd = false);
4084 BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
4086 BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
4087 BasicBlock* afterBlk,
4088 unsigned xcptnIndex,
4089 bool putInTryRegion);
4091 void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
4092 void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
4093 void fgUnlinkBlock(BasicBlock* block);
4095 unsigned fgMeasureIR();
4097 bool fgModified; // True if the flow graph has been modified recently
4098 bool fgComputePredsDone; // Have we computed the bbPreds list
4099 bool fgCheapPredsValid; // Is the bbCheapPreds list valid?
4100 bool fgDomsComputed; // Have we computed the dominator sets?
4101 bool fgOptimizedFinally; // Did we optimize any try-finallys?
4103 bool fgHasSwitch; // any BBJ_SWITCH jumps?
4105 BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
4109 bool fgReachabilitySetsValid; // Are the bbReach sets valid?
4110 bool fgEnterBlksSetValid; // Is the fgEnterBlks set valid?
4113 bool fgRemoveRestOfBlock; // true if we know that we will throw
4114 bool fgStmtRemoved; // true if we remove statements -> need new DFA
4116 // There are two modes for ordering of the trees.
4117 // - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
4118 // each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
4119 // by traversing the tree according to the order of the operands.
4120 // - In FGOrderLinear, the dominant ordering is the linear order.
4127 FlowGraphOrder fgOrder;
4129 // The following are boolean flags that keep track of the state of internal data structures
4131 bool fgStmtListThreaded; // true if the node list is now threaded
4132 bool fgCanRelocateEHRegions; // true if we are allowed to relocate the EH regions
4133 bool fgEdgeWeightsComputed; // true after we have called fgComputeEdgeWeights
4134 bool fgHaveValidEdgeWeights; // true if we were successful in computing all of the edge weights
4135 bool fgSlopUsedInEdgeWeights; // true if their was some slop used when computing the edge weights
4136 bool fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
4137 bool fgNeedsUpdateFlowGraph; // true if we need to run fgUpdateFlowGraph
4138 BasicBlock::weight_t fgCalledCount; // count of the number of times this method was called
4139 // This is derived from the profile data
4140 // or is BB_UNITY_WEIGHT when we don't have profile data
4142 #if FEATURE_EH_FUNCLETS
4143 bool fgFuncletsCreated; // true if the funclet creation phase has been run
4144 #endif // FEATURE_EH_FUNCLETS
4146 bool fgGlobalMorph; // indicates if we are during the global morphing phase
4147 // since fgMorphTree can be called from several places
4149 bool impBoxTempInUse; // the temp below is valid and available
4150 unsigned impBoxTemp; // a temporary that is used for boxing
4153 bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
4154 // and we are trying to compile again in a "safer", minopts mode?
4158 unsigned impInlinedCodeSize;
4161 //-------------------------------------------------------------------------
4167 void fgTransformIndirectCalls();
4171 void fgRemoveEmptyTry();
4173 void fgRemoveEmptyFinally();
4175 void fgMergeFinallyChains();
4177 void fgCloneFinally();
4179 void fgCleanupContinuation(BasicBlock* continuation);
4181 void fgUpdateFinallyTargetFlags();
4183 void fgClearAllFinallyTargetBits();
4185 void fgAddFinallyTargetFlags();
4187 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
4188 // Sometimes we need to defer updating the BBF_FINALLY_TARGET bit. fgNeedToAddFinallyTargetBits signals
4189 // when this is necessary.
4190 bool fgNeedToAddFinallyTargetBits;
4191 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
4193 bool fgRetargetBranchesToCanonicalCallFinally(BasicBlock* block,
4194 BasicBlock* handler,
4195 BlockToBlockMap& continuationMap);
4197 GenTree* fgGetCritSectOfStaticMethod();
4199 #if FEATURE_EH_FUNCLETS
4201 void fgAddSyncMethodEnterExit();
4203 GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
4205 void fgConvertSyncReturnToLeave(BasicBlock* block);
4207 #endif // FEATURE_EH_FUNCLETS
4209 void fgAddReversePInvokeEnterExit();
4211 bool fgMoreThanOneReturnBlock();
4213 // The number of separate return points in the method.
4214 unsigned fgReturnCount;
4216 void fgAddInternal();
4218 bool fgFoldConditional(BasicBlock* block);
4220 void fgMorphStmts(BasicBlock* block, bool* lnot, bool* loadw);
4221 void fgMorphBlocks();
4223 bool fgMorphBlockStmt(BasicBlock* block, GenTreeStmt* stmt DEBUGARG(const char* msg));
4225 void fgSetOptions();
4228 static fgWalkPreFn fgAssertNoQmark;
4229 void fgPreExpandQmarkChecks(GenTree* expr);
4230 void fgPostExpandQmarkChecks();
4231 static void fgCheckQmarkAllowedForm(GenTree* tree);
4234 IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
4236 BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
4237 BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
4238 BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, GenTree* stmt);
4239 BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
4240 BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);
4242 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block, IL_OFFSETX offs);
4243 GenTreeStmt* fgNewStmtFromTree(GenTree* tree);
4244 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block);
4245 GenTreeStmt* fgNewStmtFromTree(GenTree* tree, IL_OFFSETX offs);
4247 GenTree* fgGetTopLevelQmark(GenTree* expr, GenTree** ppDst = nullptr);
4248 void fgExpandQmarkForCastInstOf(BasicBlock* block, GenTree* stmt);
4249 void fgExpandQmarkStmt(BasicBlock* block, GenTree* expr);
4250 void fgExpandQmarkNodes();
4254 // Do "simple lowering." This functionality is (conceptually) part of "general"
4255 // lowering that is distributed between fgMorph and the lowering phase of LSRA.
4256 void fgSimpleLowering();
4258 GenTree* fgInitThisClass();
4260 GenTreeCall* fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
4262 GenTreeCall* fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
4264 bool backendRequiresLocalVarLifetimes()
4266 return !opts.MinOpts() || m_pLinearScan->willEnregisterLocalVars();
4269 void fgLocalVarLiveness();
4271 void fgLocalVarLivenessInit();
4273 void fgPerNodeLocalVarLiveness(GenTree* node);
4274 void fgPerBlockLocalVarLiveness();
4276 VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
4278 void fgLiveVarAnalysis(bool updateInternalOnly = false);
4280 void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
4282 void fgComputeLifeTrackedLocalUse(VARSET_TP& life, LclVarDsc& varDsc, GenTreeLclVarCommon* node);
4283 bool fgComputeLifeTrackedLocalDef(VARSET_TP& life,
4284 VARSET_VALARG_TP keepAliveVars,
4286 GenTreeLclVarCommon* node);
4287 void fgComputeLifeUntrackedLocal(VARSET_TP& life,
4288 VARSET_VALARG_TP keepAliveVars,
4290 GenTreeLclVarCommon* lclVarNode);
4291 bool fgComputeLifeLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, GenTree* lclVarNode);
4293 void fgComputeLife(VARSET_TP& life,
4296 VARSET_VALARG_TP volatileVars,
4297 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
4299 void fgComputeLifeLIR(VARSET_TP& life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
4301 bool fgRemoveDeadStore(GenTree** pTree,
4303 VARSET_VALARG_TP life,
4305 bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
4307 // For updating liveset during traversal AFTER fgComputeLife has completed
4308 VARSET_VALRET_TP fgGetVarBits(GenTree* tree);
4309 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree);
4311 // Returns the set of live variables after endTree,
4312 // assuming that liveSet is the set of live variables BEFORE tree.
4313 // Requires that fgComputeLife has completed, and that tree is in the same
4314 // statement as endTree, and that it comes before endTree in execution order
4316 VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree, GenTree* endTree)
4318 VARSET_TP newLiveSet(VarSetOps::MakeCopy(this, liveSet));
4319 while (tree != nullptr && tree != endTree->gtNext)
4321 VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
4322 tree = tree->gtNext;
4324 assert(tree == endTree->gtNext);
4328 void fgInterBlockLocalVarLiveness();
4330 // The presence of a partial definition presents some difficulties for SSA: this is both a use of some SSA name
4331 // of "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
4332 // whether to treat that as the use or def. It chooses the "use", and thus the old SSA name. This map allows us
4333 // to record/recover the "def" SSA number, given the lcl var node for "x" in such a tree.
4334 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, unsigned> NodeToUnsignedMap;
4335 NodeToUnsignedMap* m_opAsgnVarDefSsaNums;
4336 NodeToUnsignedMap* GetOpAsgnVarDefSsaNums()
4338 if (m_opAsgnVarDefSsaNums == nullptr)
4340 m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
4342 return m_opAsgnVarDefSsaNums;
4345 // Requires value numbering phase to have completed. Returns the value number ("gtVN") of the
4346 // "tree," EXCEPT in the case of GTF_VAR_USEASG, because the tree node's gtVN member is the
4347 // "use" VN. Performs a lookup into the map of (use asg tree -> def VN.) to return the "def's"
4349 inline ValueNum GetUseAsgDefVNOrTreeVN(GenTree* tree);
4351 // Requires that "lcl" has the GTF_VAR_DEF flag set. Returns the SSA number of "lcl".
4352 // Except: assumes that lcl is a def, and if it is
4353 // a partial def (GTF_VAR_USEASG), looks up and returns the SSA number for the "def",
4354 // rather than the "use" SSA number recorded in the tree "lcl".
4355 inline unsigned GetSsaNumForLocalVarDef(GenTree* lcl);
4357 // Performs SSA conversion.
4360 // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
4361 void fgResetForSsa();
4363 unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
4365 // Returns "true" if a struct temp of the given type requires needs zero init in this block
4366 inline bool fgStructTempNeedsExplicitZeroInit(LclVarDsc* varDsc, BasicBlock* block);
4368 // The value numbers for this compilation.
4369 ValueNumStore* vnStore;
4372 ValueNumStore* GetValueNumStore()
4377 // Do value numbering (assign a value number to each
4379 void fgValueNumber();
4381 // Computes new GcHeap VN via the assignment H[elemTypeEq][arrVN][inx][fldSeq] = rhsVN.
4382 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4383 // The 'indType' is the indirection type of the lhs of the assignment and will typically
4384 // match the element type of the array or fldSeq. When this type doesn't match
4385 // or if the fldSeq is 'NotAField' we invalidate the array contents H[elemTypeEq][arrVN]
4387 ValueNum fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
4390 FieldSeqNode* fldSeq,
4394 // Requires that "tree" is a GT_IND marked as an array index, and that its address argument
4395 // has been parsed to yield the other input arguments. If evaluation of the address
4396 // can raise exceptions, those should be captured in the exception set "excVN."
4397 // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4398 // Marks "tree" with the VN for H[elemTypeEq][arrVN][inx][fldSeq] (for the liberal VN; a new unique
4399 // VN for the conservative VN.) Also marks the tree's argument as the address of an array element.
4400 // The type tree->TypeGet() will typically match the element type of the array or fldSeq.
4401 // When this type doesn't match or if the fldSeq is 'NotAField' we return a new unique VN
4403 ValueNum fgValueNumberArrIndexVal(GenTree* tree,
4404 CORINFO_CLASS_HANDLE elemTypeEq,
4408 FieldSeqNode* fldSeq);
4410 // Requires "funcApp" to be a VNF_PtrToArrElem, and "addrXvn" to represent the exception set thrown
4411 // by evaluating the array index expression "tree". Returns the value number resulting from
4412 // dereferencing the array in the current GcHeap state. If "tree" is non-null, it must be the
4413 // "GT_IND" that does the dereference, and it is given the returned value number.
4414 ValueNum fgValueNumberArrIndexVal(GenTree* tree, struct VNFuncApp* funcApp, ValueNum addrXvn);
4416 // Compute the value number for a byref-exposed load of the given type via the given pointerVN.
4417 ValueNum fgValueNumberByrefExposedLoad(var_types type, ValueNum pointerVN);
4419 unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
4421 // Utility functions for fgValueNumber.
4423 // Perform value-numbering for the trees in "blk".
4424 void fgValueNumberBlock(BasicBlock* blk);
4426 // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
4427 // innermost loop of which "entryBlock" is the entry. Returns the value number that should be
4428 // assumed for the memoryKind at the start "entryBlk".
4429 ValueNum fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, BasicBlock* entryBlock, unsigned loopNum);
4431 // Called when an operation (performed by "tree", described by "msg") may cause the GcHeap to be mutated.
4432 // As GcHeap is a subset of ByrefExposed, this will also annotate the ByrefExposed mutation.
4433 void fgMutateGcHeap(GenTree* tree DEBUGARG(const char* msg));
4435 // Called when an operation (performed by "tree", described by "msg") may cause an address-exposed local to be
4437 void fgMutateAddressExposedLocal(GenTree* tree DEBUGARG(const char* msg));
4439 // For a GC heap store at curTree, record the new curMemoryVN's and update curTree's MemorySsaMap.
4440 // As GcHeap is a subset of ByrefExposed, this will also record the ByrefExposed store.
4441 void recordGcHeapStore(GenTree* curTree, ValueNum gcHeapVN DEBUGARG(const char* msg));
4443 // For a store to an address-exposed local at curTree, record the new curMemoryVN and update curTree's MemorySsaMap.
4444 void recordAddressExposedLocalStore(GenTree* curTree, ValueNum memoryVN DEBUGARG(const char* msg));
4446 // Tree caused an update in the current memory VN. If "tree" has an associated heap SSA #, record that
4447 // value in that SSA #.
4448 void fgValueNumberRecordMemorySsa(MemoryKind memoryKind, GenTree* tree);
4450 // The input 'tree' is a leaf node that is a constant
4451 // Assign the proper value number to the tree
4452 void fgValueNumberTreeConst(GenTree* tree);
4454 // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
4455 // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
4457 void fgValueNumberTree(GenTree* tree);
4459 // Does value-numbering for a block assignment.
4460 void fgValueNumberBlockAssignment(GenTree* tree);
4462 // Does value-numbering for a cast tree.
4463 void fgValueNumberCastTree(GenTree* tree);
4465 // Does value-numbering for an intrinsic tree.
4466 void fgValueNumberIntrinsic(GenTree* tree);
4468 // Does value-numbering for a call. We interpret some helper calls.
4469 void fgValueNumberCall(GenTreeCall* call);
4471 // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
4472 void fgUpdateArgListVNs(GenTreeArgList* args);
4474 // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
4475 void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
4477 // Requires "helpCall" to be a helper call. Assigns it a value number;
4478 // we understand the semantics of some of the calls. Returns "true" if
4479 // the call may modify the heap (we assume arbitrary memory side effects if so).
4480 bool fgValueNumberHelperCall(GenTreeCall* helpCall);
4482 // Requires that "helpFunc" is one of the pure Jit Helper methods.
4483 // Returns the corresponding VNFunc to use for value numbering
4484 VNFunc fgValueNumberJitHelperMethodVNFunc(CorInfoHelpFunc helpFunc);
4486 // Adds the exception set for the current tree node which has a memory indirection operation
4487 void fgValueNumberAddExceptionSetForIndirection(GenTree* tree, GenTree* baseAddr);
4489 // Adds the exception sets for the current tree node which is performing a division or modulus operation
4490 void fgValueNumberAddExceptionSetForDivision(GenTree* tree);
4492 // Adds the exception set for the current tree node which is performing a overflow checking operation
4493 void fgValueNumberAddExceptionSetForOverflow(GenTree* tree);
4495 // Adds the exception set for the current tree node which is performing a ckfinite operation
4496 void fgValueNumberAddExceptionSetForCkFinite(GenTree* tree);
4498 // Adds the exception sets for the current tree node
4499 void fgValueNumberAddExceptionSet(GenTree* tree);
4501 // These are the current value number for the memory implicit variables while
4502 // doing value numbering. These are the value numbers under the "liberal" interpretation
4503 // of memory values; the "conservative" interpretation needs no VN, since every access of
4504 // memory yields an unknown value.
4505 ValueNum fgCurMemoryVN[MemoryKindCount];
4507 // Return a "pseudo"-class handle for an array element type. If "elemType" is TYP_STRUCT,
4508 // requires "elemStructType" to be non-null (and to have a low-order zero). Otherwise, low order bit
4509 // is 1, and the rest is an encoding of "elemTyp".
4510 static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
4512 if (elemStructType != nullptr)
4514 assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
4515 varTypeIsIntegral(elemTyp));
4516 assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
4517 return elemStructType;
4521 assert(elemTyp != TYP_STRUCT);
4522 elemTyp = varTypeUnsignedToSigned(elemTyp);
4523 return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
4526 // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
4527 // var_types it represents. Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
4528 // the struct type of the element).
4529 static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
4531 size_t clsHndVal = size_t(clsHnd);
4532 if (clsHndVal & 0x1)
4534 return var_types(clsHndVal >> 1);
4542 // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
4543 var_types getJitGCType(BYTE gcType);
4545 enum structPassingKind
4547 SPK_Unknown, // Invalid value, never returned
4548 SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
4549 SPK_EnclosingType, // Like SPK_Primitive type, but used for return types that
4550 // require a primitive type temp that is larger than the struct size.
4551 // Currently used for structs of size 3, 5, 6, or 7 bytes.
4552 SPK_ByValue, // The struct is passed/returned by value (using the ABI rules)
4553 // for ARM64 and UNIX_X64 in multiple registers. (when all of the
4554 // parameters registers are used, then the stack will be used)
4555 // for X86 passed on the stack, for ARM32 passed in registers
4556 // or the stack or split between registers and the stack.
4557 SPK_ByValueAsHfa, // The struct is passed/returned as an HFA in multiple registers.
4559 }; // The struct is passed/returned by reference to a copy/buffer.
4561 // Get the "primitive" type that is is used when we are given a struct of size 'structSize'.
4562 // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
4563 // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
4564 // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
4566 // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
4569 var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd, bool isVarArg);
4571 // Get the type that is used to pass values of the given struct type.
4572 // isVarArg is passed for use on Windows Arm64 to change the decision returned regarding
4575 var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4576 structPassingKind* wbPassStruct,
4578 unsigned structSize);
4580 // Get the type that is used to return values of the given struct type.
4581 // If the size is unknown, pass 0 and it will be determined from 'clsHnd'.
4582 var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4583 structPassingKind* wbPassStruct = nullptr,
4584 unsigned structSize = 0);
4587 // Print a representation of "vnp" or "vn" on standard output.
4588 // If "level" is non-zero, we also print out a partial expansion of the value.
4589 void vnpPrint(ValueNumPair vnp, unsigned level);
4590 void vnPrint(ValueNum vn, unsigned level);
4593 bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
4595 // Dominator computation member functions
4596 // Not exposed outside Compiler
4598 bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
4600 void fgComputeDoms(); // Computes the immediate dominators for each basic block in the
4601 // flow graph. We first assume the fields bbIDom on each
4602 // basic block are invalid. This computation is needed later
4603 // by fgBuildDomTree to build the dominance tree structure.
4604 // Based on: A Simple, Fast Dominance Algorithm
4605 // by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
4607 void fgCompDominatedByExceptionalEntryBlocks();
4609 BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
4610 // Note: this is relatively slow compared to calling fgDominate(),
4611 // especially if dealing with a single block versus block check.
4613 void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
4615 void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
4617 bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
4619 void fgComputeReachability(); // Perform flow graph node reachability analysis.
4621 BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
4623 void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
4624 // processed in topological sort, this function takes care of that.
4626 void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
4628 BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
4629 // Returns this as a set.
4631 BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
4632 // root nodes. Returns this as a set.
4635 void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
4638 void fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
4639 // (performed by fgComputeDoms), this procedure builds the dominance tree represented
4642 // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
4643 // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
4644 // && postOrder(A) >= postOrder(B) making the computation O(1).
4645 void fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum);
4647 // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
4649 void fgUpdateChangedFlowGraph();
4652 // Compute the predecessors of the blocks in the control flow graph.
4653 void fgComputePreds();
4655 // Remove all predecessor information.
4656 void fgRemovePreds();
4658 // Compute the cheap flow graph predecessors lists. This is used in some early phases
4659 // before the full predecessors lists are computed.
4660 void fgComputeCheapPreds();
4663 void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
4665 void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
4675 // Initialize the per-block variable sets (used for liveness analysis).
4676 void fgInitBlockVarSets();
4678 // true if we've gone through and created GC Poll calls.
4679 bool fgGCPollsCreated;
4680 void fgMarkGCPollBlocks();
4681 void fgCreateGCPolls();
4682 bool fgCreateGCPoll(GCPollType pollType, BasicBlock* block);
4684 // Requires that "block" is a block that returns from
4685 // a finally. Returns the number of successors (jump targets of
4686 // of blocks in the covered "try" that did a "LEAVE".)
4687 unsigned fgNSuccsOfFinallyRet(BasicBlock* block);
4689 // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
4690 // a finally. Returns its "i"th successor (jump targets of
4691 // of blocks in the covered "try" that did a "LEAVE".)
4692 // Requires that "i" < fgNSuccsOfFinallyRet(block).
4693 BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);
4696 // Factor out common portions of the impls of the methods above.
4697 void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
4700 // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
4701 // skipping duplicate targets. (E.g., in flow analyses that are only interested in the set of possible targets.)
4702 // SwitchUniqueSuccSet contains the non-duplicated switch targets.
4703 // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
4704 // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
4705 // been computed for the switch block. If a switch block is deleted or is transformed into a non-switch,
4706 // we leave the entry associated with the block, but it will no longer be accessed.)
4707 struct SwitchUniqueSuccSet
4709 unsigned numDistinctSuccs; // Number of distinct targets of the switch.
4710 BasicBlock** nonDuplicates; // Array of "numDistinctSuccs", containing all the distinct switch target
4713 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4714 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4715 // remove it from "this", and ensure that "to" is a member. Use "alloc" to do any required allocation.
4716 void UpdateTarget(CompAllocator alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4719 typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet> BlockToSwitchDescMap;
4722 // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
4723 // iteration over only the distinct successors.
4724 BlockToSwitchDescMap* m_switchDescMap;
4727 BlockToSwitchDescMap* GetSwitchDescMap(bool createIfNull = true)
4729 if ((m_switchDescMap == nullptr) && createIfNull)
4731 m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
4733 return m_switchDescMap;
4736 // Invalidate the map of unique switch block successors. For example, since the hash key of the map
4737 // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
4738 // we don't accidentally look up and return the wrong switch data.
4739 void InvalidateUniqueSwitchSuccMap()
4741 m_switchDescMap = nullptr;
4744 // Requires "switchBlock" to be a block that ends in a switch. Returns
4745 // the corresponding SwitchUniqueSuccSet.
4746 SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
4748 // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4749 // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4750 // remove it from "this", and ensure that "to" is a member.
4751 void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4753 // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4754 void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4756 BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4758 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4760 flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4762 flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4764 flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4766 flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4768 flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4770 void fgRemoveBlockAsPred(BasicBlock* block);
4772 void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4774 void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4776 void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4778 void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
4780 flowList* fgAddRefPred(BasicBlock* block,
4781 BasicBlock* blockPred,
4782 flowList* oldEdge = nullptr,
4783 bool initializingPreds = false); // Only set to 'true' when we are computing preds in
4786 void fgFindBasicBlocks();
4788 bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4790 bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4792 BasicBlock* fgFindInsertPoint(unsigned regionIndex,
4793 bool putInTryRegion,
4794 BasicBlock* startBlk,
4796 BasicBlock* nearBlk,
4797 BasicBlock* jumpBlk,
4800 unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4802 void fgRemoveEmptyBlocks();
4804 void fgRemoveStmt(BasicBlock* block, GenTree* stmt);
4806 bool fgCheckRemoveStmt(BasicBlock* block, GenTree* stmt);
4808 void fgCreateLoopPreHeader(unsigned lnum);
4810 void fgUnreachableBlock(BasicBlock* block);
4812 void fgRemoveConditionalJump(BasicBlock* block);
4814 BasicBlock* fgLastBBInMainFunction();
4816 BasicBlock* fgEndBBAfterMainFunction();
4818 void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4820 void fgRemoveBlock(BasicBlock* block, bool unreachable);
4822 bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4824 void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4826 void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4828 BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4830 bool fgRenumberBlocks();
4832 bool fgExpandRarelyRunBlocks();
4834 bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4836 void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4838 enum FG_RELOCATE_TYPE
4840 FG_RELOCATE_TRY, // relocate the 'try' region
4841 FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4843 BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
4845 #if FEATURE_EH_FUNCLETS
4846 #if defined(_TARGET_ARM_)
4847 void fgClearFinallyTargetBit(BasicBlock* block);
4848 #endif // defined(_TARGET_ARM_)
4849 bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
4850 bool fgAnyIntraHandlerPreds(BasicBlock* block);
4851 void fgInsertFuncletPrologBlock(BasicBlock* block);
4852 void fgCreateFuncletPrologBlocks();
4853 void fgCreateFunclets();
4854 #else // !FEATURE_EH_FUNCLETS
4855 bool fgRelocateEHRegions();
4856 #endif // !FEATURE_EH_FUNCLETS
4858 bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4860 bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4862 bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4864 bool fgOptimizeEmptyBlock(BasicBlock* block);
4866 bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4868 bool fgOptimizeBranch(BasicBlock* bJump);
4870 bool fgOptimizeSwitchBranches(BasicBlock* block);
4872 bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4874 bool fgOptimizeSwitchJumps();
4876 void fgPrintEdgeWeights();
4878 void fgComputeBlockAndEdgeWeights();
4879 BasicBlock::weight_t fgComputeMissingBlockWeights();
4880 void fgComputeCalledCount(BasicBlock::weight_t returnWeight);
4881 void fgComputeEdgeWeights();
4883 void fgReorderBlocks();
4885 void fgDetermineFirstColdBlock();
4887 bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4889 bool fgUpdateFlowGraph(bool doTailDup = false);
4891 void fgFindOperOrder();
4893 // method that returns if you should split here
4894 typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4896 void fgSetBlockOrder();
4898 void fgRemoveReturnBlock(BasicBlock* block);
4900 /* Helper code that has been factored out */
4901 inline void fgConvertBBToThrowBB(BasicBlock* block);
4903 bool fgCastNeeded(GenTree* tree, var_types toType);
4904 GenTree* fgDoNormalizeOnStore(GenTree* tree);
4905 GenTree* fgMakeTmpArgNode(fgArgTabEntry* curArgTabEntry);
4907 // The following check for loops that don't execute calls
4908 bool fgLoopCallMarked;
4910 void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4911 void fgLoopCallMark();
4913 void fgMarkLoopHead(BasicBlock* block);
4915 unsigned fgGetCodeEstimate(BasicBlock* block);
4918 const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4919 FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4920 bool fgDumpFlowGraph(Phases phase);
4922 #endif // DUMP_FLOWGRAPHS
4927 void fgDispBBLiveness(BasicBlock* block);
4928 void fgDispBBLiveness();
4929 void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
4930 void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
4931 void fgDispBasicBlocks(bool dumpTrees = false);
4932 void fgDumpStmtTree(GenTree* stmt, unsigned bbNum);
4933 void fgDumpBlock(BasicBlock* block);
4934 void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);
4936 static fgWalkPreFn fgStress64RsltMulCB;
4937 void fgStress64RsltMul();
4938 void fgDebugCheckUpdate();
4939 void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
4940 void fgDebugCheckBlockLinks();
4941 void fgDebugCheckLinks(bool morphTrees = false);
4942 void fgDebugCheckStmtsList(BasicBlock* block, bool morphTrees);
4943 void fgDebugCheckNodeLinks(BasicBlock* block, GenTree* stmt);
4944 void fgDebugCheckNodesUniqueness();
4946 void fgDebugCheckFlags(GenTree* tree);
4947 void fgDebugCheckFlagsHelper(GenTree* tree, unsigned treeFlags, unsigned chkFlags);
4948 void fgDebugCheckTryFinallyExits();
4951 static GenTree* fgGetFirstNode(GenTree* tree);
4953 //--------------------- Walking the trees in the IR -----------------------
4958 fgWalkPreFn* wtprVisitorFn;
4959 fgWalkPostFn* wtpoVisitorFn;
4960 void* pCallbackData; // user-provided data
4961 bool wtprLclsOnly; // whether to only visit lclvar nodes
4962 GenTree* parent; // parent of current node, provided to callback
4963 GenTreeStack* parentStack; // stack of parent nodes, if asked for
4965 bool printModified; // callback can use this
4969 fgWalkResult fgWalkTreePre(GenTree** pTree,
4970 fgWalkPreFn* visitor,
4971 void* pCallBackData = nullptr,
4972 bool lclVarsOnly = false,
4973 bool computeStack = false);
4975 fgWalkResult fgWalkTree(GenTree** pTree,
4976 fgWalkPreFn* preVisitor,
4977 fgWalkPostFn* postVisitor,
4978 void* pCallBackData = nullptr);
4980 void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4984 fgWalkResult fgWalkTreePost(GenTree** pTree,
4985 fgWalkPostFn* visitor,
4986 void* pCallBackData = nullptr,
4987 bool computeStack = false);
4989 // An fgWalkPreFn that looks for expressions that have inline throws in
4990 // minopts mode. Basically it looks for tress with gtOverflowEx() or
4991 // GTF_IND_RNGCHK. It returns WALK_ABORT if one is found. It
4992 // returns WALK_SKIP_SUBTREES if GTF_EXCEPT is not set (assumes flags
4993 // properly propagated to parent trees). It returns WALK_CONTINUE
4995 static fgWalkResult fgChkThrowCB(GenTree** pTree, Compiler::fgWalkData* data);
4996 static fgWalkResult fgChkLocAllocCB(GenTree** pTree, Compiler::fgWalkData* data);
4997 static fgWalkResult fgChkQmarkCB(GenTree** pTree, Compiler::fgWalkData* data);
4999 /**************************************************************************
5001 *************************************************************************/
5004 friend class SsaBuilder;
5005 friend struct ValueNumberState;
5007 //--------------------- Detect the basic blocks ---------------------------
5009 BasicBlock** fgBBs; // Table of pointers to the BBs
5011 void fgInitBBLookup();
5012 BasicBlock* fgLookupBB(unsigned addr);
5014 void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);
5016 void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
5018 void fgLinkBasicBlocks();
5020 unsigned fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, FixedBitVect* jumpTarget);
5022 void fgCheckBasicBlockControlFlow();
5024 void fgControlFlowPermitted(BasicBlock* blkSrc,
5025 BasicBlock* blkDest,
5026 BOOL IsLeave = false /* is the src a leave block */);
5028 bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
5030 void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
5032 void fgAdjustForAddressExposedOrWrittenThis();
5034 bool fgProfileData_ILSizeMismatch;
5035 ICorJitInfo::ProfileBuffer* fgProfileBuffer;
5036 ULONG fgProfileBufferCount;
5037 ULONG fgNumProfileRuns;
5039 unsigned fgStressBBProf()
5042 unsigned result = JitConfig.JitStressBBProf();
5045 if (compStressCompile(STRESS_BB_PROFILE, 15))
5056 bool fgHaveProfileData();
5057 bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
5058 void fgInstrumentMethod();
5061 // fgIsUsingProfileWeights - returns true if we have real profile data for this method
5062 // or if we have some fake profile data for the stress mode
5063 bool fgIsUsingProfileWeights()
5065 return (fgHaveProfileData() || fgStressBBProf());
5068 // fgProfileRunsCount - returns total number of scenario runs for the profile data
5069 // or BB_UNITY_WEIGHT when we aren't using profile data.
5070 unsigned fgProfileRunsCount()
5072 return fgIsUsingProfileWeights() ? fgNumProfileRuns : BB_UNITY_WEIGHT;
5075 //-------- Insert a statement at the start or end of a basic block --------
5079 static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
5083 GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTree* node);
5085 public: // Used by linear scan register allocation
5086 GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTree* node);
5089 GenTree* fgInsertStmtAtBeg(BasicBlock* block, GenTree* stmt);
5090 GenTree* fgInsertStmtAfter(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
5092 public: // Used by linear scan register allocation
5093 GenTree* fgInsertStmtBefore(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
5096 GenTree* fgInsertStmtListAfter(BasicBlock* block, GenTree* stmtAfter, GenTree* stmtList);
5098 // Create a new temporary variable to hold the result of *ppTree,
5099 // and transform the graph accordingly.
5100 GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
5101 GenTree* fgMakeMultiUse(GenTree** ppTree);
5104 // Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
5105 GenTree* fgRecognizeAndMorphBitwiseRotation(GenTree* tree);
5106 bool fgOperIsBitwiseRotationRoot(genTreeOps oper);
5108 //-------- Determine the order in which the trees will be evaluated -------
5110 unsigned fgTreeSeqNum;
5111 GenTree* fgTreeSeqLst;
5112 GenTree* fgTreeSeqBeg;
5114 GenTree* fgSetTreeSeq(GenTree* tree, GenTree* prev = nullptr, bool isLIR = false);
5115 void fgSetTreeSeqHelper(GenTree* tree, bool isLIR);
5116 void fgSetTreeSeqFinish(GenTree* tree, bool isLIR);
5117 void fgSetStmtSeq(GenTree* tree);
5118 void fgSetBlockOrder(BasicBlock* block);
5120 //------------------------- Morphing --------------------------------------
5122 unsigned fgPtrArgCntMax;
5125 //------------------------------------------------------------------------
5126 // fgGetPtrArgCntMax: Return the maximum number of pointer-sized stack arguments that calls inside this method
5127 // can push on the stack. This value is calculated during morph.
5130 // Returns fgPtrArgCntMax, that is a private field.
5132 unsigned fgGetPtrArgCntMax() const
5134 return fgPtrArgCntMax;
5137 //------------------------------------------------------------------------
5138 // fgSetPtrArgCntMax: Set the maximum number of pointer-sized stack arguments that calls inside this method
5139 // can push on the stack. This function is used during StackLevelSetter to fix incorrect morph calculations.
5141 void fgSetPtrArgCntMax(unsigned argCntMax)
5143 fgPtrArgCntMax = argCntMax;
5146 bool compCanEncodePtrArgCntMax();
5149 hashBv* fgOutgoingArgTemps;
5150 hashBv* fgCurrentlyInUseArgTemps;
5152 void fgSetRngChkTarget(GenTree* tree, bool delay = true);
5154 BasicBlock* fgSetRngChkTargetInner(SpecialCodeKind kind, bool delay);
5157 void fgMoveOpsLeft(GenTree* tree);
5160 bool fgIsCommaThrow(GenTree* tree, bool forFolding = false);
5162 bool fgIsThrow(GenTree* tree);
5164 bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
5165 bool fgIsBlockCold(BasicBlock* block);
5167 GenTree* fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper);
5169 GenTree* fgMorphIntoHelperCall(GenTree* tree, int helper, GenTreeArgList* args, bool morphArgs = true);
5171 GenTree* fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
5173 // A "MorphAddrContext" carries information from the surrounding context. If we are evaluating a byref address,
5174 // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
5175 // be used, perhaps by passing it as an argument to a called method. This affects how null checking is done:
5176 // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
5177 // know will be dereferenced. To know that reliance on implicit null checking is sound, we must further know that
5178 // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
5179 // small; hence the other fields of MorphAddrContext.
5180 enum MorphAddrContextKind
5185 struct MorphAddrContext
5187 MorphAddrContextKind m_kind;
5188 bool m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind". True iff all offsets between
5189 // top-level indirection and here have been constants.
5190 size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
5191 // In that case, is the sum of those constant offsets.
5193 MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
5198 // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
5199 static MorphAddrContext s_CopyBlockMAC;
5202 GenTree* getSIMDStructFromField(GenTree* tree,
5203 var_types* baseTypeOut,
5205 unsigned* simdSizeOut,
5206 bool ignoreUsedInSIMDIntrinsic = false);
5207 GenTree* fgMorphFieldAssignToSIMDIntrinsicSet(GenTree* tree);
5208 GenTree* fgMorphFieldToSIMDIntrinsicGet(GenTree* tree);
5209 bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTree* stmt);
5210 void impMarkContiguousSIMDFieldAssignments(GenTree* stmt);
5212 // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
5213 // in function: Complier::impMarkContiguousSIMDFieldAssignments.
5214 GenTree* fgPreviousCandidateSIMDFieldAsgStmt;
5216 #endif // FEATURE_SIMD
5217 GenTree* fgMorphArrayIndex(GenTree* tree);
5218 GenTree* fgMorphCast(GenTree* tree);
5219 GenTree* fgUnwrapProxy(GenTree* objRef);
5220 GenTreeFieldList* fgMorphLclArgToFieldlist(GenTreeLclVarCommon* lcl);
5221 void fgInitArgInfo(GenTreeCall* call);
5222 GenTreeCall* fgMorphArgs(GenTreeCall* call);
5223 GenTreeArgList* fgMorphArgList(GenTreeArgList* args, MorphAddrContext* mac);
5225 void fgMakeOutgoingStructArgCopy(GenTreeCall* call,
5228 CORINFO_CLASS_HANDLE copyBlkClass);
5230 void fgFixupStructReturn(GenTree* call);
5231 GenTree* fgMorphLocalVar(GenTree* tree, bool forceRemorph);
5234 bool fgAddrCouldBeNull(GenTree* addr);
5237 GenTree* fgMorphField(GenTree* tree, MorphAddrContext* mac);
5238 bool fgCanFastTailCall(GenTreeCall* call);
5239 bool fgCheckStmtAfterTailCall();
5240 void fgMorphTailCall(GenTreeCall* call, void* pfnCopyArgs);
5241 GenTree* fgGetStubAddrArg(GenTreeCall* call);
5242 void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
5243 GenTree* fgAssignRecursiveCallArgToCallerParam(GenTree* arg,
5244 fgArgTabEntry* argTabEntry,
5246 IL_OFFSETX callILOffset,
5247 GenTree* tmpAssignmentInsertionPoint,
5248 GenTree* paramAssignmentInsertionPoint);
5249 static int fgEstimateCallStackSize(GenTreeCall* call);
5250 GenTree* fgMorphCall(GenTreeCall* call);
5251 void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
5252 void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result);
5254 void fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call);
5255 static fgWalkPreFn fgFindNonInlineCandidate;
5257 GenTree* fgOptimizeDelegateConstructor(GenTreeCall* call,
5258 CORINFO_CONTEXT_HANDLE* ExactContextHnd,
5259 CORINFO_RESOLVED_TOKEN* ldftnToken);
5260 GenTree* fgMorphLeaf(GenTree* tree);
5261 void fgAssignSetVarDef(GenTree* tree);
5262 GenTree* fgMorphOneAsgBlockOp(GenTree* tree);
5263 GenTree* fgMorphInitBlock(GenTree* tree);
5264 GenTree* fgMorphBlkToInd(GenTreeBlk* tree, var_types type);
5265 GenTree* fgMorphGetStructAddr(GenTree** pTree, CORINFO_CLASS_HANDLE clsHnd, bool isRValue = false);
5266 GenTree* fgMorphBlkNode(GenTree* tree, bool isDest);
5267 GenTree* fgMorphBlockOperand(GenTree* tree, var_types asgType, unsigned blockWidth, bool isDest);
5268 void fgMorphUnsafeBlk(GenTreeObj* obj);
5269 GenTree* fgMorphCopyBlock(GenTree* tree);
5270 GenTree* fgMorphForRegisterFP(GenTree* tree);
5271 GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac = nullptr);
5272 GenTree* fgMorphModToSubMulDiv(GenTreeOp* tree);
5273 GenTree* fgMorphSmpOpOptional(GenTreeOp* tree);
5274 GenTree* fgMorphRecognizeBoxNullable(GenTree* compare);
5276 GenTree* fgMorphToEmulatedFP(GenTree* tree);
5277 GenTree* fgMorphConst(GenTree* tree);
5280 GenTree* fgMorphTree(GenTree* tree, MorphAddrContext* mac = nullptr);
5283 #if LOCAL_ASSERTION_PROP
5284 void fgKillDependentAssertionsSingle(unsigned lclNum DEBUGARG(GenTree* tree));
5285 void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree));
5287 void fgMorphTreeDone(GenTree* tree, GenTree* oldTree = nullptr DEBUGARG(int morphNum = 0));
5289 GenTreeStmt* fgMorphStmt;
5291 unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
5292 // used when morphing big offset.
5294 //----------------------- Liveness analysis -------------------------------
5296 VARSET_TP fgCurUseSet; // vars used by block (before an assignment)
5297 VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
5299 MemoryKindSet fgCurMemoryUse; // True iff the current basic block uses memory.
5300 MemoryKindSet fgCurMemoryDef; // True iff the current basic block modifies memory.
5301 MemoryKindSet fgCurMemoryHavoc; // True if the current basic block is known to set memory to a "havoc" value.
5303 bool byrefStatesMatchGcHeapStates; // True iff GcHeap and ByrefExposed memory have all the same def points.
5305 void fgMarkUseDef(GenTreeLclVarCommon* tree);
5307 void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5308 void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5310 void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
5311 void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
5313 void fgExtendDbgScopes();
5314 void fgExtendDbgLifetimes();
5317 void fgDispDebugScopes();
5320 //-------------------------------------------------------------------------
5322 // The following keeps track of any code we've added for things like array
5323 // range checking or explicit calls to enable GC, and so on.
5328 AddCodeDsc* acdNext;
5329 BasicBlock* acdDstBlk; // block to which we jump
5331 SpecialCodeKind acdKind; // what kind of a special block is this?
5332 #if !FEATURE_FIXED_OUT_ARGS
5333 bool acdStkLvlInit; // has acdStkLvl value been already set?
5335 #endif // !FEATURE_FIXED_OUT_ARGS
5339 static unsigned acdHelper(SpecialCodeKind codeKind);
5341 AddCodeDsc* fgAddCodeList;
5343 bool fgRngChkThrowAdded;
5344 AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
5346 BasicBlock* fgRngChkTarget(BasicBlock* block, SpecialCodeKind kind);
5348 BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind);
5351 AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
5353 bool fgUseThrowHelperBlocks();
5355 AddCodeDsc* fgGetAdditionalCodeDescriptors()
5357 return fgAddCodeList;
5361 bool fgIsCodeAdded();
5363 bool fgIsThrowHlpBlk(BasicBlock* block);
5365 #if !FEATURE_FIXED_OUT_ARGS
5366 unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
5367 #endif // !FEATURE_FIXED_OUT_ARGS
5369 unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
5371 unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
5372 void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
5373 void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
5374 GenTree* fgInlinePrependStatements(InlineInfo* inlineInfo);
5375 void fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* block, GenTree* stmt);
5377 #if FEATURE_MULTIREG_RET
5378 GenTree* fgGetStructAsStructPtr(GenTree* tree);
5379 GenTree* fgAssignStructInlineeToVar(GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5380 void fgAttachStructInlineeToAsg(GenTree* tree, GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5381 #endif // FEATURE_MULTIREG_RET
5383 static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
5384 static fgWalkPostFn fgLateDevirtualization;
5387 static fgWalkPreFn fgDebugCheckInlineCandidates;
5389 void CheckNoTransformableIndirectCallsRemain();
5390 static fgWalkPreFn fgDebugCheckForTransformableIndirectCalls;
5393 void fgPromoteStructs();
5394 void fgMorphStructField(GenTree* tree, GenTree* parent);
5395 void fgMorphLocalField(GenTree* tree, GenTree* parent);
5397 // Identify which parameters are implicit byrefs, and flag their LclVarDscs.
5398 void fgMarkImplicitByRefArgs();
5400 // Change implicit byrefs' types from struct to pointer, and for any that were
5401 // promoted, create new promoted struct temps.
5402 void fgRetypeImplicitByRefArgs();
5404 // Rewrite appearances of implicit byrefs (manifest the implied additional level of indirection).
5405 bool fgMorphImplicitByRefArgs(GenTree* tree);
5406 GenTree* fgMorphImplicitByRefArgs(GenTree* tree, bool isAddr);
5408 // Clear up annotations for any struct promotion temps created for implicit byrefs.
5409 void fgMarkDemotedImplicitByRefArgs();
5411 void fgMarkAddressExposedLocals();
5413 static fgWalkPreFn fgUpdateSideEffectsPre;
5414 static fgWalkPostFn fgUpdateSideEffectsPost;
5416 // The given local variable, required to be a struct variable, is being assigned via
5417 // a "lclField", to make it masquerade as an integral type in the ABI. Make sure that
5418 // the variable is not enregistered, and is therefore not promoted independently.
5419 void fgLclFldAssign(unsigned lclNum);
5421 static fgWalkPreFn gtHasLocalsWithAddrOpCB;
5423 enum TypeProducerKind
5425 TPK_Unknown = 0, // May not be a RuntimeType
5426 TPK_Handle = 1, // RuntimeType via handle
5427 TPK_GetType = 2, // RuntimeType via Object.get_Type()
5428 TPK_Null = 3, // Tree value is null
5429 TPK_Other = 4 // RuntimeType via other means
5432 TypeProducerKind gtGetTypeProducerKind(GenTree* tree);
5433 bool gtIsTypeHandleToRuntimeTypeHelper(GenTreeCall* call);
5434 bool gtIsTypeHandleToRuntimeTypeHandleHelper(GenTreeCall* call, CorInfoHelpFunc* pHelper = nullptr);
5435 bool gtIsActiveCSE_Candidate(GenTree* tree);
5438 bool fgPrintInlinedMethods;
5441 bool fgIsBigOffset(size_t offset);
5443 bool fgNeedReturnSpillTemp();
5446 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5447 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5451 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5452 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5458 void optRemoveRangeCheck(GenTree* tree, GenTree* stmt);
5459 bool optIsRangeCheckRemovable(GenTree* tree);
5462 static fgWalkPreFn optValidRangeCheckIndex;
5463 static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
5466 void optRemoveTree(GenTree* deadTree, GenTree* keepList);
5468 /**************************************************************************
5470 *************************************************************************/
5473 // Do hoisting for all loops.
5474 void optHoistLoopCode();
5476 // To represent sets of VN's that have already been hoisted in outer loops.
5477 typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, bool> VNToBoolMap;
5478 typedef VNToBoolMap VNSet;
5480 struct LoopHoistContext
5483 // The set of variables hoisted in the current loop (or nullptr if there are none).
5484 VNSet* m_pHoistedInCurLoop;
5487 // Value numbers of expressions that have been hoisted in parent loops in the loop nest.
5488 VNSet m_hoistedInParentLoops;
5489 // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
5490 // Previous decisions on loop-invariance of value numbers in the current loop.
5491 VNToBoolMap m_curLoopVnInvariantCache;
5493 VNSet* GetHoistedInCurLoop(Compiler* comp)
5495 if (m_pHoistedInCurLoop == nullptr)
5497 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
5499 return m_pHoistedInCurLoop;
5502 VNSet* ExtractHoistedInCurLoop()
5504 VNSet* res = m_pHoistedInCurLoop;
5505 m_pHoistedInCurLoop = nullptr;
5509 LoopHoistContext(Compiler* comp)
5510 : m_pHoistedInCurLoop(nullptr)
5511 , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
5512 , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
5517 // Do hoisting for loop "lnum" (an index into the optLoopTable), and all loops nested within it.
5518 // Tracks the expressions that have been hoisted by containing loops by temporary recording their
5519 // value numbers in "m_hoistedInParentLoops". This set is not modified by the call.
5520 void optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);
5522 // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
5523 // Assumes that expressions have been hoisted in containing loops if their value numbers are in
5524 // "m_hoistedInParentLoops".
5526 void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
5528 // Hoist all expressions in "blk" that are invariant in loop "lnum" (an index into the optLoopTable)
5529 // outside of that loop. Exempt expressions whose value number is in "m_hoistedInParentLoops"; add VN's of hoisted
5530 // expressions to "hoistInLoop".
5531 void optHoistLoopExprsForBlock(BasicBlock* blk, unsigned lnum, LoopHoistContext* hoistCtxt);
5533 // Return true if the tree looks profitable to hoist out of loop 'lnum'.
5534 bool optIsProfitableToHoistableTree(GenTree* tree, unsigned lnum);
5536 // Hoist all proper sub-expressions of "tree" (which occurs in "stmt", which occurs in "blk")
5537 // that are invariant in loop "lnum" (an index into the optLoopTable)
5538 // outside of that loop. Exempt expressions whose value number is in "hoistedInParents"; add VN's of hoisted
5539 // expressions to "hoistInLoop".
5540 // Returns "true" iff "tree" is loop-invariant (wrt "lnum").
5541 // Assumes that the value of "*firstBlockAndBeforeSideEffect" indicates that we're in the first block, and before
5542 // any possible globally visible side effects. Assume is called in evaluation order, and updates this.
5543 bool optHoistLoopExprsForTree(GenTree* tree,
5545 LoopHoistContext* hoistCtxt,
5546 bool* firstBlockAndBeforeSideEffect,
5548 bool* pCctorDependent);
5550 // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
5551 void optHoistCandidate(GenTree* tree, unsigned lnum, LoopHoistContext* hoistCtxt);
5553 // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
5554 // Constants and init values are always loop invariant.
5555 // VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
5556 bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNToBoolMap* recordedVNs);
5558 // Returns "true" iff "tree" is valid at the head of loop "lnum", in the context of the hoist substitution
5559 // "subst". If "tree" is a local SSA var, it is valid if its SSA definition occurs outside of the loop, or
5560 // if it is in the domain of "subst" (meaning that it's definition has been previously hoisted, with a "standin"
5561 // local.) If tree is a constant, it is valid. Otherwise, if it is an operator, it is valid iff its children are.
5562 bool optTreeIsValidAtLoopHead(GenTree* tree, unsigned lnum);
5564 // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
5565 // in the loop table.
5566 bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);
5568 // Records the set of "side effects" of all loops: fields (object instance and static)
5569 // written to, and SZ-array element type equivalence classes updated.
5570 void optComputeLoopSideEffects();
5573 // Requires "lnum" to be the index of an outermost loop in the loop table. Traverses the body of that loop,
5574 // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
5575 // static) written to, and SZ-array element type equivalence classes updated.
5576 void optComputeLoopNestSideEffects(unsigned lnum);
5578 // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
5579 void optComputeLoopSideEffectsOfBlock(BasicBlock* blk);
5581 // Hoist the expression "expr" out of loop "lnum".
5582 void optPerformHoistExpr(GenTree* expr, unsigned lnum);
5585 void optOptimizeBools();
5588 GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
5590 void optOptimizeBoolsGcStress(BasicBlock* condBlock);
5593 void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
5595 void optOptimizeLoops(); // for "while-do" loops duplicates simple loop conditions and transforms
5596 // the loop into a "do-while" loop
5597 // Also finds all natural loops and records them in the loop table
5599 // Optionally clone loops in the loop table.
5600 void optCloneLoops();
5602 // Clone loop "loopInd" in the loop table.
5603 void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
5605 // Ensure that loop "loopInd" has a unique head block. (If the existing entry has
5606 // non-loop predecessors other than the head entry, create a new, empty block that goes (only) to the entry,
5607 // and redirects the preds of the entry to this new block.) Sets the weight of the newly created block to
5609 void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
5611 void optUnrollLoops(); // Unrolls loops (needs to have cost info)
5614 // This enumeration describes what is killed by a call.
5618 CALLINT_NONE, // no interference (most helpers)
5619 CALLINT_REF_INDIRS, // kills GC ref indirections (SETFIELD OBJ)
5620 CALLINT_SCL_INDIRS, // kills non GC ref indirections (SETFIELD non-OBJ)
5621 CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
5622 CALLINT_ALL, // kills everything (normal method call)
5626 // A "LoopDsc" describes a ("natural") loop. We (currently) require the body of a loop to be a contiguous (in
5627 // bbNext order) sequence of basic blocks. (At times, we may require the blocks in a loop to be "properly numbered"
5628 // in bbNext order; we use comparisons on the bbNum to decide order.)
5629 // The blocks that define the body are
5630 // first <= top <= entry <= bottom .
5631 // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
5632 // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
5633 // Compiler::optFindNaturalLoops().
5636 BasicBlock* lpHead; // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
5637 BasicBlock* lpFirst; // FIRST block (in bbNext order) reachable within this loop. (May be part of a nested
5638 // loop, but not the outer loop.)
5639 BasicBlock* lpTop; // loop TOP (the back edge from lpBottom reaches here) (in most cases FIRST and TOP are the
5641 BasicBlock* lpEntry; // the ENTRY in the loop (in most cases TOP or BOTTOM)
5642 BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
5643 BasicBlock* lpExit; // if a single exit loop this is the EXIT (in most cases BOTTOM)
5645 callInterf lpAsgCall; // "callInterf" for calls in the loop
5646 ALLVARSET_TP lpAsgVars; // set of vars assigned within the loop (all vars, not just tracked)
5647 varRefKinds lpAsgInds : 8; // set of inds modified within the loop
5649 unsigned short lpFlags; // Mask of the LPFLG_* constants
5651 unsigned char lpExitCnt; // number of exits from the loop
5653 unsigned char lpParent; // The index of the most-nested loop that completely contains this one,
5654 // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
5655 unsigned char lpChild; // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
5656 // (Actually, an "immediately" nested loop --
5657 // no other child of this loop is a parent of lpChild.)
5658 unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
5659 // or else BasicBlock::NOT_IN_LOOP. One can enumerate all the children of a loop
5660 // by following "lpChild" then "lpSibling" links.
5662 #define LPFLG_DO_WHILE 0x0001 // it's a do-while loop (i.e ENTRY is at the TOP)
5663 #define LPFLG_ONE_EXIT 0x0002 // the loop has only one exit
5665 #define LPFLG_ITER 0x0004 // for (i = icon or lclVar; test_condition(); i++)
5666 #define LPFLG_HOISTABLE 0x0008 // the loop is in a form that is suitable for hoisting expressions
5667 #define LPFLG_CONST 0x0010 // for (i=icon;i<icon;i++){ ... } - constant loop
5669 #define LPFLG_VAR_INIT 0x0020 // iterator is initialized with a local var (var # found in lpVarInit)
5670 #define LPFLG_CONST_INIT 0x0040 // iterator is initialized with a constant (found in lpConstInit)
5672 #define LPFLG_VAR_LIMIT 0x0100 // iterator is compared with a local var (var # found in lpVarLimit)
5673 #define LPFLG_CONST_LIMIT 0x0200 // iterator is compared with a constant (found in lpConstLimit)
5674 #define LPFLG_ARRLEN_LIMIT 0x0400 // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
5675 #define LPFLG_SIMD_LIMIT 0x0080 // iterator is compared with Vector<T>.Count (found in lpConstLimit)
5677 #define LPFLG_HAS_PREHEAD 0x0800 // lpHead is known to be a preHead for this loop
5678 #define LPFLG_REMOVED 0x1000 // has been removed from the loop table (unrolled or optimized away)
5679 #define LPFLG_DONT_UNROLL 0x2000 // do not unroll this loop
5681 #define LPFLG_ASGVARS_YES 0x4000 // "lpAsgVars" has been computed
5682 #define LPFLG_ASGVARS_INC 0x8000 // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
5683 // type are assigned to.
5685 bool lpLoopHasMemoryHavoc[MemoryKindCount]; // The loop contains an operation that we assume has arbitrary
5686 // memory side effects. If this is set, the fields below
5687 // may not be accurate (since they become irrelevant.)
5688 bool lpContainsCall; // True if executing the loop body *may* execute a call
5690 VARSET_TP lpVarInOut; // The set of variables that are IN or OUT during the execution of this loop
5691 VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop
5693 int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
5695 int lpLoopVarCount; // The register count for the non-FP LclVars that are read/written inside this loop
5696 int lpVarInOutCount; // The register count for the non-FP LclVars that are alive inside or accross this loop
5698 int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
5700 int lpLoopVarFPCount; // The register count for the FP LclVars that are read/written inside this loop
5701 int lpVarInOutFPCount; // The register count for the FP LclVars that are alive inside or accross this loop
5703 typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>, bool> FieldHandleSet;
5704 FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
5705 // instance fields modified
5708 typedef JitHashTable<CORINFO_CLASS_HANDLE, JitPtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>, bool> ClassHandleSet;
5709 ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
5710 // arrays of that type are modified
5713 // Adds the variable liveness information for 'blk' to 'this' LoopDsc
5714 void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
5716 inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd);
5717 // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
5718 // (shifted left, with a low-order bit set to distinguish.)
5719 // Use the {Encode/Decode}ElemType methods to construct/destruct these.
5720 inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);
5722 /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
5724 GenTree* lpIterTree; // The "i = i <op> const" tree
5725 unsigned lpIterVar(); // iterator variable #
5726 int lpIterConst(); // the constant with which the iterator is incremented
5727 genTreeOps lpIterOper(); // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
5728 void VERIFY_lpIterTree();
5730 var_types lpIterOperType(); // For overflow instructions
5733 int lpConstInit; // initial constant value of iterator : Valid if LPFLG_CONST_INIT
5734 unsigned lpVarInit; // initial local var number to which we initialize the iterator : Valid if
5738 /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
5740 GenTree* lpTestTree; // pointer to the node containing the loop test
5741 genTreeOps lpTestOper(); // the type of the comparison between the iterator and the limit (GT_LE, GT_GE, etc.)
5742 void VERIFY_lpTestTree();
5744 bool lpIsReversed(); // true if the iterator node is the second operand in the loop condition
5745 GenTree* lpIterator(); // the iterator node in the loop test
5746 GenTree* lpLimit(); // the limit node in the loop test
5748 int lpConstLimit(); // limit constant value of iterator - loop condition is "i RELOP const" : Valid if
5749 // LPFLG_CONST_LIMIT
5750 unsigned lpVarLimit(); // the lclVar # in the loop condition ( "i RELOP lclVar" ) : Valid if
5752 bool lpArrLenLimit(Compiler* comp, ArrIndex* index); // The array length in the loop condition ( "i RELOP
5753 // arr.len" or "i RELOP arr[i][j].len" ) : Valid if
5754 // LPFLG_ARRLEN_LIMIT
5756 // Returns "true" iff "*this" contains the blk.
5757 bool lpContains(BasicBlock* blk)
5759 return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
5761 // Returns "true" iff "*this" (properly) contains the range [first, bottom] (allowing firsts
5762 // to be equal, but requiring bottoms to be different.)
5763 bool lpContains(BasicBlock* first, BasicBlock* bottom)
5765 return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
5768 // Returns "true" iff "*this" (properly) contains "lp2" (allowing firsts to be equal, but requiring
5769 // bottoms to be different.)
5770 bool lpContains(const LoopDsc& lp2)
5772 return lpContains(lp2.lpFirst, lp2.lpBottom);
5775 // Returns "true" iff "*this" is (properly) contained by the range [first, bottom]
5776 // (allowing firsts to be equal, but requiring bottoms to be different.)
5777 bool lpContainedBy(BasicBlock* first, BasicBlock* bottom)
5779 return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
5782 // Returns "true" iff "*this" is (properly) contained by "lp2"
5783 // (allowing firsts to be equal, but requiring bottoms to be different.)
5784 bool lpContainedBy(const LoopDsc& lp2)
5786 return lpContains(lp2.lpFirst, lp2.lpBottom);
5789 // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5790 bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5792 return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5794 // Returns "true" iff "*this" is disjoint from "lp2".
5795 bool lpDisjoint(const LoopDsc& lp2)
5797 return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5799 // Returns "true" iff the loop is well-formed (see code for defn).
5802 return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5803 lpEntry->bbNum <= lpBottom->bbNum &&
5804 (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5809 bool fgMightHaveLoop(); // returns true if there are any backedges
5810 bool fgHasLoops; // True if this method has any loops, set in fgComputeReachability
5813 LoopDsc* optLoopTable; // loop descriptor table
5814 unsigned char optLoopCount; // number of tracked loops
5816 bool optRecordLoop(BasicBlock* head,
5822 unsigned char exitCnt);
5825 unsigned optCallCount; // number of calls made in the method
5826 unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
5827 unsigned optNativeCallCount; // number of Pinvoke/Native calls made in the method
5828 unsigned optLoopsCloned; // number of loops cloned in the current method.
5831 unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5832 void optPrintLoopInfo(unsigned loopNum,
5834 BasicBlock* lpFirst,
5836 BasicBlock* lpEntry,
5837 BasicBlock* lpBottom,
5838 unsigned char lpExitCnt,
5840 unsigned parentLoop = BasicBlock::NOT_IN_LOOP);
5841 void optPrintLoopInfo(unsigned lnum);
5842 void optPrintLoopRecording(unsigned lnum);
5844 void optCheckPreds();
5847 void optSetBlockWeights();
5849 void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5851 void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5853 void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
5855 bool optIsLoopTestEvalIntoTemp(GenTree* test, GenTree** newTest);
5856 unsigned optIsLoopIncrTree(GenTree* incr);
5857 bool optCheckIterInLoopTest(unsigned loopInd, GenTree* test, BasicBlock* from, BasicBlock* to, unsigned iterVar);
5858 bool optComputeIterInfo(GenTree* incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
5859 bool optPopulateInitInfo(unsigned loopInd, GenTree* init, unsigned iterVar);
5860 bool optExtractInitTestIncr(
5861 BasicBlock* head, BasicBlock* bottom, BasicBlock* exit, GenTree** ppInit, GenTree** ppTest, GenTree** ppIncr);
5863 void optFindNaturalLoops();
5865 // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
5866 // each loop has a unique "top." Returns "true" iff the flowgraph has been modified.
5867 bool optCanonicalizeLoopNest(unsigned char loopInd);
5869 // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
5870 // unshared with any other loop. Returns "true" iff the flowgraph has been modified
5871 bool optCanonicalizeLoop(unsigned char loopInd);
5873 // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP". Requires "l2" to be
5874 // a valid loop table index, or else "BasicBlock::NOT_IN_LOOP". Returns true
5875 // iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
5876 bool optLoopContains(unsigned l1, unsigned l2);
5878 // Requires "loopInd" to be a valid index into the loop table.
5879 // Updates the loop table by changing loop "loopInd", whose head is required
5880 // to be "from", to be "to". Also performs this transformation for any
5881 // loop nested in "loopInd" that shares the same head as "loopInd".
5882 void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);
5884 // Updates the successors of "blk": if "blk2" is a successor of "blk", and there is a mapping for "blk2->blk3" in
5885 // "redirectMap", change "blk" so that "blk3" is this successor. Note that the predecessor lists are not updated.
5886 void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap);
5888 // Marks the containsCall information to "lnum" and any parent loops.
5889 void AddContainsCallAllContainingLoops(unsigned lnum);
5890 // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
5891 void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);
5892 // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
5893 void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd);
5894 // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
5895 void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);
5897 // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
5898 // of "from".) Copies the jump destination from "from" to "to".
5899 void optCopyBlkDest(BasicBlock* from, BasicBlock* to);
5901 // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5902 unsigned optLoopDepth(unsigned lnum)
5904 unsigned par = optLoopTable[lnum].lpParent;
5905 if (par == BasicBlock::NOT_IN_LOOP)
5911 return 1 + optLoopDepth(par);
5915 void fgOptWhileLoop(BasicBlock* block);
5917 bool optComputeLoopRep(int constInit,
5920 genTreeOps iterOper,
5922 genTreeOps testOper,
5925 unsigned* iterCount);
5928 static fgWalkPreFn optIsVarAssgCB;
5931 bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTree* skip, unsigned var);
5933 bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5935 int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5937 bool optNarrowTree(GenTree* tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5939 /**************************************************************************
5940 * Optimization conditions
5941 *************************************************************************/
5943 bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5944 bool optPentium4(void);
5945 bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5946 bool optAvoidIntMult(void);
5951 // The following is the upper limit on how many expressions we'll keep track
5952 // of for the CSE analysis.
5954 static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5956 static const int MIN_CSE_COST = 2;
5958 // Keeps tracked cse indices
5959 BitVecTraits* cseTraits;
5962 /* Generic list of nodes - used by the CSE logic */
5972 treeStmtLst* tslNext;
5973 GenTree* tslTree; // tree node
5974 GenTree* tslStmt; // statement containing the tree
5975 BasicBlock* tslBlock; // block containing the statement
5978 // The following logic keeps track of expressions via a simple hash table.
5982 CSEdsc* csdNextInBucket; // used by the hash table
5984 unsigned csdHashKey; // the orginal hashkey
5986 unsigned csdIndex; // 1..optCSECandidateCount
5987 char csdLiveAcrossCall; // 0 or 1
5989 unsigned short csdDefCount; // definition count
5990 unsigned short csdUseCount; // use count (excluding the implicit uses at defs)
5992 unsigned csdDefWtCnt; // weighted def count
5993 unsigned csdUseWtCnt; // weighted use count (excluding the implicit uses at defs)
5995 GenTree* csdTree; // treenode containing the 1st occurance
5996 GenTree* csdStmt; // stmt containing the 1st occurance
5997 BasicBlock* csdBlock; // block containing the 1st occurance
5999 treeStmtLst* csdTreeList; // list of matching tree nodes: head
6000 treeStmtLst* csdTreeLast; // list of matching tree nodes: tail
6002 ValueNum defExcSetPromise; // The exception set that is now required for all defs of this CSE.
6003 // This will be set to NoVN if we decide to abandon this CSE
6005 ValueNum defExcSetCurrent; // The set of exceptions we currently can use for CSE uses.
6007 ValueNum defConservNormVN; // if all def occurrences share the same conservative normal value
6008 // number, this will reflect it; otherwise, NoVN.
6011 static const size_t s_optCSEhashSize;
6012 CSEdsc** optCSEhash;
6015 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, GenTree*> NodeToNodeMap;
6017 NodeToNodeMap* optCseCheckedBoundMap; // Maps bound nodes to ancestor compares that should be
6018 // re-numbered with the bound to improve range check elimination
6020 // Given a compare, look for a cse candidate checked bound feeding it and add a map entry if found.
6021 void optCseUpdateCheckedBoundMap(GenTree* compare);
6025 CSEdsc* optCSEfindDsc(unsigned index);
6026 bool optUnmarkCSE(GenTree* tree);
6028 // user defined callback data for the tree walk function optCSE_MaskHelper()
6029 struct optCSE_MaskData
6031 EXPSET_TP CSE_defMask;
6032 EXPSET_TP CSE_useMask;
6035 // Treewalk helper for optCSE_DefMask and optCSE_UseMask
6036 static fgWalkPreFn optCSE_MaskHelper;
6038 // This function walks all the node for an given tree
6039 // and return the mask of CSE definitions and uses for the tree
6041 void optCSE_GetMaskData(GenTree* tree, optCSE_MaskData* pMaskData);
6043 // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
6044 bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);
6045 bool optCSE_canSwap(GenTree* tree);
6047 static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
6048 static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
6050 void optCleanupCSEs();
6053 void optEnsureClearCSEInfo();
6056 #endif // FEATURE_ANYCSE
6058 #if FEATURE_VALNUM_CSE
6059 /**************************************************************************
6060 * Value Number based CSEs
6061 *************************************************************************/
6064 void optOptimizeValnumCSEs();
6067 void optValnumCSE_Init();
6068 unsigned optValnumCSE_Index(GenTree* tree, GenTree* stmt);
6069 unsigned optValnumCSE_Locate();
6070 void optValnumCSE_InitDataFlow();
6071 void optValnumCSE_DataFlow();
6072 void optValnumCSE_Availablity();
6073 void optValnumCSE_Heuristic();
6075 #endif // FEATURE_VALNUM_CSE
6078 bool optDoCSE; // True when we have found a duplicate CSE tree
6079 bool optValnumCSE_phase; // True when we are executing the optValnumCSE_phase
6080 unsigned optCSECandidateTotal; // Grand total of CSE candidates for both Lexical and ValNum
6081 unsigned optCSECandidateCount; // Count of CSE's candidates, reset for Lexical and ValNum CSE's
6082 unsigned optCSEstart; // The first local variable number that is a CSE
6083 unsigned optCSEcount; // The total count of CSE's introduced.
6084 unsigned optCSEweight; // The weight of the current block when we are
6085 // scanning for CSE expressions
6087 bool optIsCSEcandidate(GenTree* tree);
6089 // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
6091 bool lclNumIsTrueCSE(unsigned lclNum) const
6093 return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
6096 // lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
6098 bool lclNumIsCSE(unsigned lclNum) const
6100 return lvaTable[lclNum].lvIsCSE;
6104 bool optConfigDisableCSE();
6105 bool optConfigDisableCSE2();
6107 void optOptimizeCSEs();
6109 #endif // FEATURE_ANYCSE
6117 unsigned ivaVar; // Variable we are interested in, or -1
6118 ALLVARSET_TP ivaMaskVal; // Set of variables assigned to. This is a set of all vars, not tracked vars.
6119 bool ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
6120 varRefKinds ivaMaskInd; // What kind of indirect assignments are there?
6121 callInterf ivaMaskCall; // What kind of calls are there?
6124 static callInterf optCallInterf(GenTreeCall* call);
6127 // VN based copy propagation.
6128 typedef ArrayStack<GenTree*> GenTreePtrStack;
6129 typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*> LclNumToGenTreePtrStack;
6131 // Kill set to track variables with intervening definitions.
6132 VARSET_TP optCopyPropKillSet;
6134 // Copy propagation functions.
6135 void optCopyProp(BasicBlock* block, GenTree* stmt, GenTree* tree, LclNumToGenTreePtrStack* curSsaName);
6136 void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
6137 void optBlockCopyProp(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
6138 bool optIsSsaLocal(GenTree* tree);
6139 int optCopyProp_LclVarScore(LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc, bool preferOp2);
6140 void optVnCopyProp();
6141 INDEBUG(void optDumpCopyPropStack(LclNumToGenTreePtrStack* curSsaName));
6143 /**************************************************************************
6144 * Early value propagation
6145 *************************************************************************/
6151 SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
6155 static unsigned GetHashCode(SSAName ssaNm)
6157 return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
6160 static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
6162 return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
6166 #define OMF_HAS_NEWARRAY 0x00000001 // Method contains 'new' of an array
6167 #define OMF_HAS_NEWOBJ 0x00000002 // Method contains 'new' of an object type.
6168 #define OMF_HAS_ARRAYREF 0x00000004 // Method contains array element loads or stores.
6169 #define OMF_HAS_VTABLEREF 0x00000008 // Method contains method table reference.
6170 #define OMF_HAS_NULLCHECK 0x00000010 // Method contains null check.
6171 #define OMF_HAS_FATPOINTER 0x00000020 // Method contains call, that needs fat pointer transformation.
6172 #define OMF_HAS_OBJSTACKALLOC 0x00000040 // Method contains an object allocated on the stack.
6173 #define OMF_HAS_GUARDEDDEVIRT 0x00000080 // Method contains guarded devirtualization candidate
6175 bool doesMethodHaveFatPointer()
6177 return (optMethodFlags & OMF_HAS_FATPOINTER) != 0;
6180 void setMethodHasFatPointer()
6182 optMethodFlags |= OMF_HAS_FATPOINTER;
6185 void clearMethodHasFatPointer()
6187 optMethodFlags &= ~OMF_HAS_FATPOINTER;
6190 void addFatPointerCandidate(GenTreeCall* call);
6192 bool doesMethodHaveGuardedDevirtualization()
6194 return (optMethodFlags & OMF_HAS_GUARDEDDEVIRT) != 0;
6197 void setMethodHasGuardedDevirtualization()
6199 optMethodFlags |= OMF_HAS_GUARDEDDEVIRT;
6202 void clearMethodHasGuardedDevirtualization()
6204 optMethodFlags &= ~OMF_HAS_GUARDEDDEVIRT;
6207 void addGuardedDevirtualizationCandidate(GenTreeCall* call,
6208 CORINFO_METHOD_HANDLE methodHandle,
6209 CORINFO_CLASS_HANDLE classHandle,
6210 unsigned methodAttr,
6211 unsigned classAttr);
6213 unsigned optMethodFlags;
6215 // Recursion bound controls how far we can go backwards tracking for a SSA value.
6216 // No throughput diff was found with backward walk bound between 3-8.
6217 static const int optEarlyPropRecurBound = 5;
6219 enum class optPropKind
6227 bool gtIsVtableRef(GenTree* tree);
6228 GenTree* getArrayLengthFromAllocation(GenTree* tree);
6229 GenTree* getObjectHandleNodeFromAllocation(GenTree* tree);
6230 GenTree* optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
6231 GenTree* optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
6232 GenTree* optEarlyPropRewriteTree(GenTree* tree);
6233 bool optDoEarlyPropForBlock(BasicBlock* block);
6234 bool optDoEarlyPropForFunc();
6235 void optEarlyProp();
6236 void optFoldNullCheck(GenTree* tree);
6237 bool optCanMoveNullCheckPastTree(GenTree* tree, bool isInsideTry);
6240 /**************************************************************************
6241 * Value/Assertion propagation
6242 *************************************************************************/
6244 // Data structures for assertion prop
6245 BitVecTraits* apTraits;
6248 enum optAssertionKind
6265 O1K_CONSTANT_LOOP_BND,
6286 optAssertionKind assertionKind;
6289 unsigned lclNum; // assigned to or property of this local var number
6297 struct AssertionDscOp1
6299 optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
6306 struct AssertionDscOp2
6308 optOp2Kind kind; // a const or copy assignment
6312 ssize_t iconVal; // integer
6313 unsigned iconFlags; // gtFlags
6315 struct Range // integer subrange
6329 bool IsCheckedBoundArithBound()
6331 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_OPER_BND);
6333 bool IsCheckedBoundBound()
6335 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_LOOP_BND);
6337 bool IsConstantBound()
6339 return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
6340 op1.kind == O1K_CONSTANT_LOOP_BND);
6342 bool IsBoundsCheckNoThrow()
6344 return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
6347 bool IsCopyAssertion()
6349 return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
6352 static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
6354 return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
6355 a1->op2.kind == a2->op2.kind;
6358 static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
6360 if (kind == OAK_EQUAL)
6362 return kind2 == OAK_NOT_EQUAL;
6364 else if (kind == OAK_NOT_EQUAL)
6366 return kind2 == OAK_EQUAL;
6371 static ssize_t GetLowerBoundForIntegralType(var_types type)
6390 static ssize_t GetUpperBoundForIntegralType(var_types type)
6413 bool HasSameOp1(AssertionDsc* that, bool vnBased)
6415 if (op1.kind != that->op1.kind)
6419 else if (op1.kind == O1K_ARR_BND)
6422 return (op1.bnd.vnIdx == that->op1.bnd.vnIdx) && (op1.bnd.vnLen == that->op1.bnd.vnLen);
6426 return ((vnBased && (op1.vn == that->op1.vn)) ||
6427 (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
6431 bool HasSameOp2(AssertionDsc* that, bool vnBased)
6433 if (op2.kind != that->op2.kind)
6439 case O2K_IND_CNS_INT:
6441 return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
6443 case O2K_CONST_LONG:
6444 return (op2.lconVal == that->op2.lconVal);
6446 case O2K_CONST_DOUBLE:
6447 // exact match because of positive and negative zero.
6448 return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);
6450 case O2K_LCLVAR_COPY:
6452 return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
6453 (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
6456 return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
6459 // we will return false
6463 assert(!"Unexpected value for op2.kind in AssertionDsc.");
6469 bool Complementary(AssertionDsc* that, bool vnBased)
6471 return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
6472 HasSameOp2(that, vnBased);
6475 bool Equals(AssertionDsc* that, bool vnBased)
6477 if (assertionKind != that->assertionKind)
6481 else if (assertionKind == OAK_NO_THROW)
6483 assert(op2.kind == O2K_INVALID);
6484 return HasSameOp1(that, vnBased);
6488 return HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
6494 static fgWalkPreFn optAddCopiesCallback;
6495 static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
6496 unsigned optAddCopyLclNum;
6497 GenTree* optAddCopyAsgnNode;
6499 bool optLocalAssertionProp; // indicates that we are performing local assertion prop
6500 bool optAssertionPropagated; // set to true if we modified the trees
6501 bool optAssertionPropagatedCurrentStmt;
6503 GenTree* optAssertionPropCurrentTree;
6505 AssertionIndex* optComplementaryAssertionMap;
6506 JitExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
6507 // using the value of a local var) for each local var
6508 AssertionDsc* optAssertionTabPrivate; // table that holds info about value assignments
6509 AssertionIndex optAssertionCount; // total number of assertions in the assertion table
6510 AssertionIndex optMaxAssertionCount;
6513 void optVnNonNullPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6514 fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6515 GenTree* optVNConstantPropOnJTrue(BasicBlock* block, GenTree* stmt, GenTree* test);
6516 GenTree* optVNConstantPropOnTree(BasicBlock* block, GenTree* stmt, GenTree* tree);
6517 GenTree* optPrepareTreeForReplacement(GenTree* extractTree, GenTree* replaceTree);
6519 AssertionIndex GetAssertionCount()
6521 return optAssertionCount;
6523 ASSERT_TP* bbJtrueAssertionOut;
6524 typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP> ValueNumToAssertsMap;
6525 ValueNumToAssertsMap* optValueNumToAsserts;
6527 // Assertion prop helpers.
6528 ASSERT_TP& GetAssertionDep(unsigned lclNum);
6529 AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
6530 void optAssertionInit(bool isLocalProp);
6531 void optAssertionTraitsInit(AssertionIndex assertionCount);
6532 #if LOCAL_ASSERTION_PROP
6533 void optAssertionReset(AssertionIndex limit);
6534 void optAssertionRemove(AssertionIndex index);
6537 // Assertion prop data flow functions.
6538 void optAssertionPropMain();
6539 GenTree* optVNAssertionPropCurStmt(BasicBlock* block, GenTree* stmt);
6540 bool optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, unsigned* pIconFlags);
6541 ASSERT_TP* optInitAssertionDataflowFlags();
6542 ASSERT_TP* optComputeAssertionGen();
6544 // Assertion Gen functions.
6545 void optAssertionGen(GenTree* tree);
6546 AssertionIndex optAssertionGenPhiDefn(GenTree* tree);
6547 AssertionInfo optCreateJTrueBoundsAssertion(GenTree* tree);
6548 AssertionInfo optAssertionGenJtrue(GenTree* tree);
6549 AssertionIndex optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind);
6550 AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
6551 void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);
6553 // Assertion creation functions.
6554 AssertionIndex optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind);
6555 AssertionIndex optCreateAssertion(GenTree* op1,
6557 optAssertionKind assertionKind,
6558 AssertionDsc* assertion);
6559 void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2);
6561 bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
6562 AssertionIndex optAddAssertion(AssertionDsc* assertion);
6563 void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
6565 void optPrintVnAssertionMapping();
6567 ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
6569 // Used for respective assertion propagations.
6570 AssertionIndex optAssertionIsSubrange(GenTree* tree, var_types toType, ASSERT_VALARG_TP assertions);
6571 AssertionIndex optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions);
6572 AssertionIndex optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions);
6573 bool optAssertionIsNonNull(GenTree* op,
6574 ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));
6576 // Used for Relop propagation.
6577 AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2);
6578 AssertionIndex optGlobalAssertionIsEqualOrNotEqualZero(ASSERT_VALARG_TP assertions, GenTree* op1);
6579 AssertionIndex optLocalAssertionIsEqualOrNotEqual(
6580 optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);
6582 // Assertion prop for lcl var functions.
6583 bool optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
6584 GenTree* optCopyAssertionProp(AssertionDsc* curAssertion,
6586 GenTree* stmt DEBUGARG(AssertionIndex index));
6587 GenTree* optConstantAssertionProp(AssertionDsc* curAssertion,
6589 GenTree* stmt DEBUGARG(AssertionIndex index));
6591 // Assertion propagation functions.
6592 GenTree* optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6593 GenTree* optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6594 GenTree* optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6595 GenTree* optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6596 GenTree* optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6597 GenTree* optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6598 GenTree* optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6599 GenTree* optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6600 GenTree* optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6601 GenTree* optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6602 GenTree* optAssertionProp_Update(GenTree* newTree, GenTree* tree, GenTree* stmt);
6603 GenTree* optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6605 // Implied assertion functions.
6606 void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
6607 void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
6608 void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
6609 void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);
6612 void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
6613 void optDebugCheckAssertion(AssertionDsc* assertion);
6614 void optDebugCheckAssertions(AssertionIndex AssertionIndex);
6616 void optAddCopies();
6617 #endif // ASSERTION_PROP
6619 /**************************************************************************
6621 *************************************************************************/
6624 struct LoopCloneVisitorInfo
6626 LoopCloneContext* context;
6629 LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTree* stmt)
6630 : context(context), loopNum(loopNum), stmt(nullptr)
6635 bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
6636 bool optExtractArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6637 bool optReconstructArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6638 bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
6639 static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
6640 fgWalkResult optCanOptimizeByLoopCloning(GenTree* tree, LoopCloneVisitorInfo* info);
6641 void optObtainLoopCloningOpts(LoopCloneContext* context);
6642 bool optIsLoopClonable(unsigned loopInd);
6644 bool optCanCloneLoops();
6647 void optDebugLogLoopCloning(BasicBlock* block, GenTree* insertBefore);
6649 void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
6650 bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
6651 bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
6652 BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
6658 ssize_t optGetArrayRefScaleAndIndex(GenTree* mul, GenTree** pIndex DEBUGARG(bool bRngChk));
6660 bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
6663 bool optLoopsMarked;
6666 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6667 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6671 XX Does the register allocation and puts the remaining lclVars on the stack XX
6673 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6674 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6678 regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
6680 void raMarkStkVars();
6683 // Some things are used by both LSRA and regpredict allocators.
6685 FrameType rpFrameType;
6686 bool rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
6688 bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
6691 Lowering* m_pLowering; // Lowering; needed to Lower IR that's added or modified after Lowering.
6692 LinearScanInterface* m_pLinearScan; // Linear Scan allocator
6694 /* raIsVarargsStackArg is called by raMaskStkVars and by
6695 lvaSortByRefCount. It identifies the special case
6696 where a varargs function has a parameter passed on the
6697 stack, other than the special varargs handle. Such parameters
6698 require special treatment, because they cannot be tracked
6699 by the GC (their offsets in the stack are not known
6703 bool raIsVarargsStackArg(unsigned lclNum)
6707 LclVarDsc* varDsc = &lvaTable[lclNum];
6709 assert(varDsc->lvIsParam);
6711 return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6713 #else // _TARGET_X86_
6717 #endif // _TARGET_X86_
6721 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6722 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6726 XX Get to the class and method info from the Execution Engine given XX
6727 XX tokens for the class and method XX
6729 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6730 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6734 /* These are the different addressing modes used to access a local var.
6735 * The JIT has to report the location of the locals back to the EE
6736 * for debugging purposes.
6742 VLT_REG_BYREF, // this type is currently only used for value types on X64
6745 VLT_STK_BYREF, // this type is currently only used for value types on X64
6759 siVarLocType vlType;
6762 // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6764 // VLT_REG_BYREF -- the specified register contains the address of the variable
6772 // VLT_STK -- Any 32 bit value which is on the stack
6773 // eg. [ESP+0x20], or [EBP-0x28]
6774 // VLT_STK_BYREF -- the specified stack location contains the address of the variable
6775 // eg. mov EAX, [ESP+0x20]; [EAX]
6779 regNumber vlsBaseReg;
6780 NATIVE_OFFSET vlsOffset;
6783 // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6792 // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6793 // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6801 regNumber vlrssBaseReg;
6802 NATIVE_OFFSET vlrssOffset;
6806 // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6807 // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6813 regNumber vlsrsBaseReg;
6814 NATIVE_OFFSET vlsrsOffset;
6820 // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6821 // eg 2 DWords at [ESP+0x10]
6825 regNumber vls2BaseReg;
6826 NATIVE_OFFSET vls2Offset;
6829 // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6830 // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
6837 // VLT_FIXED_VA -- fixed argument of a varargs function.
6838 // The argument location depends on the size of the variable
6839 // arguments (...). Inspecting the VARARGS_HANDLE indicates the
6840 // location of the first arg. This argument can then be accessed
6841 // relative to the position of the first arg
6845 unsigned vlfvOffset;
6852 void* rpValue; // pointer to the in-process
6853 // location of the value.
6859 bool vlIsInReg(regNumber reg);
6860 bool vlIsOnStk(regNumber reg, signed offset);
6863 /*************************************************************************/
6868 void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6869 CORINFO_RESOLVED_TOKEN* pConstrainedToken,
6870 CORINFO_CALLINFO_FLAGS flags,
6871 CORINFO_CALL_INFO* pResult);
6872 inline CORINFO_CALLINFO_FLAGS addVerifyFlag(CORINFO_CALLINFO_FLAGS flags);
6874 void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6875 CORINFO_ACCESS_FLAGS flags,
6876 CORINFO_FIELD_INFO* pResult);
6880 BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6882 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS)
6884 bool IsSuperPMIException(unsigned code)
6886 // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
6888 const unsigned EXCEPTIONCODE_DebugBreakorAV = 0xe0421000;
6889 const unsigned EXCEPTIONCODE_MC = 0xe0422000;
6890 const unsigned EXCEPTIONCODE_LWM = 0xe0423000;
6891 const unsigned EXCEPTIONCODE_SASM = 0xe0424000;
6892 const unsigned EXCEPTIONCODE_SSYM = 0xe0425000;
6893 const unsigned EXCEPTIONCODE_CALLUTILS = 0xe0426000;
6894 const unsigned EXCEPTIONCODE_TYPEUTILS = 0xe0427000;
6895 const unsigned EXCEPTIONCODE_ASSERT = 0xe0440000;
6899 case EXCEPTIONCODE_DebugBreakorAV:
6900 case EXCEPTIONCODE_MC:
6901 case EXCEPTIONCODE_LWM:
6902 case EXCEPTIONCODE_SASM:
6903 case EXCEPTIONCODE_SSYM:
6904 case EXCEPTIONCODE_CALLUTILS:
6905 case EXCEPTIONCODE_TYPEUTILS:
6906 case EXCEPTIONCODE_ASSERT:
6913 const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6914 const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6916 bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6917 CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
6920 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6921 var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
6922 unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6924 // VOM info, method sigs
6926 void eeGetSig(unsigned sigTok,
6927 CORINFO_MODULE_HANDLE scope,
6928 CORINFO_CONTEXT_HANDLE context,
6929 CORINFO_SIG_INFO* retSig);
6931 void eeGetCallSiteSig(unsigned sigTok,
6932 CORINFO_MODULE_HANDLE scope,
6933 CORINFO_CONTEXT_HANDLE context,
6934 CORINFO_SIG_INFO* retSig);
6936 void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6938 // Method entry-points, instrs
6940 CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6942 CORINFO_EE_INFO eeInfo;
6943 bool eeInfoInitialized;
6945 CORINFO_EE_INFO* eeGetEEInfo();
6947 // Gets the offset of a SDArray's first element
6948 unsigned eeGetArrayDataOffset(var_types type);
6949 // Gets the offset of a MDArray's first element
6950 unsigned eeGetMDArrayDataOffset(var_types type, unsigned rank);
6952 GenTree* eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6954 // Returns the page size for the target machine as reported by the EE.
6955 target_size_t eeGetPageSize()
6957 return (target_size_t)eeGetEEInfo()->osPageSize;
6960 // Returns the frame size at which we will generate a loop to probe the stack.
6961 target_size_t getVeryLargeFrameSize()
6964 // The looping probe code is 40 bytes, whereas the straight-line probing for
6965 // the (0x2000..0x3000) case is 44, so use looping for anything 0x2000 bytes
6966 // or greater, to generate smaller code.
6967 return 2 * eeGetPageSize();
6969 return 3 * eeGetPageSize();
6973 //------------------------------------------------------------------------
6974 // VirtualStubParam: virtual stub dispatch extra parameter (slot address).
6976 // It represents Abi and target specific registers for the parameter.
6978 class VirtualStubParamInfo
6981 VirtualStubParamInfo(bool isCoreRTABI)
6983 #if defined(_TARGET_X86_)
6986 #elif defined(_TARGET_AMD64_)
6997 #elif defined(_TARGET_ARM_)
7008 #elif defined(_TARGET_ARM64_)
7012 #error Unsupported or unset target architecture
7016 regNumber GetReg() const
7021 _regMask_enum GetRegMask() const
7028 _regMask_enum regMask;
7031 VirtualStubParamInfo* virtualStubParamInfo;
7033 bool IsTargetAbi(CORINFO_RUNTIME_ABI abi)
7035 return eeGetEEInfo()->targetAbi == abi;
7038 bool generateCFIUnwindCodes()
7040 #if defined(_TARGET_UNIX_)
7041 return IsTargetAbi(CORINFO_CORERT_ABI);
7047 // Debugging support - Line number info
7049 void eeGetStmtOffsets();
7051 unsigned eeBoundariesCount;
7053 struct boundariesDsc
7055 UNATIVE_OFFSET nativeIP;
7057 unsigned sourceReason;
7058 } * eeBoundaries; // Boundaries to report to EE
7059 void eeSetLIcount(unsigned count);
7060 void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, unsigned srcIP, bool stkEmpty, bool callInstruction);
7064 static void eeDispILOffs(IL_OFFSET offs);
7065 static void eeDispLineInfo(const boundariesDsc* line);
7066 void eeDispLineInfos();
7069 // Debugging support - Local var info
7073 unsigned eeVarsCount;
7075 struct VarResultInfo
7077 UNATIVE_OFFSET startOffset;
7078 UNATIVE_OFFSET endOffset;
7082 void eeSetLVcount(unsigned count);
7083 void eeSetLVinfo(unsigned which,
7084 UNATIVE_OFFSET startOffs,
7085 UNATIVE_OFFSET length,
7090 const siVarLoc& loc);
7094 void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
7095 void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
7098 // ICorJitInfo wrappers
7100 void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
7102 void eeAllocUnwindInfo(BYTE* pHotCode,
7108 CorJitFuncKind funcKind);
7110 void eeSetEHcount(unsigned cEH);
7112 void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
7114 WORD eeGetRelocTypeHint(void* target);
7116 // ICorStaticInfo wrapper functions
7118 bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
7120 #if defined(UNIX_AMD64_ABI)
7122 static void dumpSystemVClassificationType(SystemVClassificationType ct);
7125 void eeGetSystemVAmd64PassStructInRegisterDescriptor(
7126 /*IN*/ CORINFO_CLASS_HANDLE structHnd,
7127 /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
7128 #endif // UNIX_AMD64_ABI
7130 template <typename ParamType>
7131 bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
7133 return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
7136 bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
7138 // Utility functions
7140 const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
7143 const wchar_t* eeGetCPString(size_t stringHandle);
7146 const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
7148 static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
7149 static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
7151 static fgWalkPreFn CountSharedStaticHelper;
7152 static bool IsSharedStaticHelper(GenTree* tree);
7153 static bool IsTreeAlwaysHoistable(GenTree* tree);
7154 static bool IsGcSafePoint(GenTree* tree);
7156 static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
7157 // returns true/false if 'field' is a Jit Data offset
7158 static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
7159 // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
7160 static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);
7162 /*****************************************************************************/
7165 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7166 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7170 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7171 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7175 CodeGenInterface* codeGen;
7177 // The following holds information about instr offsets in terms of generated code.
7181 IPmappingDsc* ipmdNext; // next line# record
7182 IL_OFFSETX ipmdILoffsx; // the instr offset
7183 emitLocation ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
7184 bool ipmdIsLabel; // Can this code be a branch label?
7187 // Record the instr offset mapping to the generated code
7189 IPmappingDsc* genIPmappingList;
7190 IPmappingDsc* genIPmappingLast;
7192 // Managed RetVal - A side hash table meant to record the mapping from a
7193 // GT_CALL node to its IL offset. This info is used to emit sequence points
7194 // that can be used by debugger to determine the native offset at which the
7195 // managed RetVal will be available.
7197 // In fact we can store IL offset in a GT_CALL node. This was ruled out in
7198 // favor of a side table for two reasons: 1) We need IL offset for only those
7199 // GT_CALL nodes (created during importation) that correspond to an IL call and
7200 // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
7201 // structure and IL offset is needed only when generating debuggable code. Therefore
7202 // it is desirable to avoid memory size penalty in retail scenarios.
7203 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, IL_OFFSETX> CallSiteILOffsetTable;
7204 CallSiteILOffsetTable* genCallSite2ILOffsetMap;
7206 unsigned genReturnLocal; // Local number for the return value when applicable.
7207 BasicBlock* genReturnBB; // jumped to when not optimizing for speed.
7209 // The following properties are part of CodeGenContext. Getters are provided here for
7210 // convenience and backward compatibility, but the properties can only be set by invoking
7211 // the setter on CodeGenContext directly.
7213 __declspec(property(get = getEmitter)) emitter* genEmitter;
7214 emitter* getEmitter()
7216 return codeGen->getEmitter();
7219 bool isFramePointerUsed()
7221 return codeGen->isFramePointerUsed();
7224 __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
7225 bool getInterruptible()
7227 return codeGen->genInterruptible;
7229 void setInterruptible(bool value)
7231 codeGen->setInterruptible(value);
7234 #ifdef _TARGET_ARMARCH_
7235 __declspec(property(get = getHasTailCalls, put = setHasTailCalls)) bool hasTailCalls;
7236 bool getHasTailCalls()
7238 return codeGen->hasTailCalls;
7240 void setHasTailCalls(bool value)
7242 codeGen->setHasTailCalls(value);
7244 #endif // _TARGET_ARMARCH_
7247 const bool genDoubleAlign()
7249 return codeGen->doDoubleAlign();
7251 DWORD getCanDoubleAlign();
7252 bool shouldDoubleAlign(unsigned refCntStk,
7254 unsigned refCntWtdReg,
7255 unsigned refCntStkParam,
7256 unsigned refCntWtdStkDbl);
7257 #endif // DOUBLE_ALIGN
7259 __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
7260 bool getFullPtrRegMap()
7262 return codeGen->genFullPtrRegMap;
7264 void setFullPtrRegMap(bool value)
7266 codeGen->setFullPtrRegMap(value);
7269 // Things that MAY belong either in CodeGen or CodeGenContext
7271 #if FEATURE_EH_FUNCLETS
7272 FuncInfoDsc* compFuncInfos;
7273 unsigned short compCurrFuncIdx;
7274 unsigned short compFuncInfoCount;
7276 unsigned short compFuncCount()
7278 assert(fgFuncletsCreated);
7279 return compFuncInfoCount;
7282 #else // !FEATURE_EH_FUNCLETS
7284 // This is a no-op when there are no funclets!
7285 void genUpdateCurrentFunclet(BasicBlock* block)
7290 FuncInfoDsc compFuncInfoRoot;
7292 static const unsigned compCurrFuncIdx = 0;
7294 unsigned short compFuncCount()
7299 #endif // !FEATURE_EH_FUNCLETS
7301 FuncInfoDsc* funCurrentFunc();
7302 void funSetCurrentFunc(unsigned funcIdx);
7303 FuncInfoDsc* funGetFunc(unsigned funcIdx);
7304 unsigned int funGetFuncIdx(BasicBlock* block);
7308 VARSET_TP compCurLife; // current live variables
7309 GenTree* compCurLifeTree; // node after which compCurLife has been computed
7311 template <bool ForCodeGen>
7312 void compChangeLife(VARSET_VALARG_TP newLife);
7314 void genChangeLife(VARSET_VALARG_TP newLife)
7316 compChangeLife</*ForCodeGen*/ true>(newLife);
7319 template <bool ForCodeGen>
7320 inline void compUpdateLife(VARSET_VALARG_TP newLife);
7322 // Gets a register mask that represent the kill set for a helper call since
7323 // not all JIT Helper calls follow the standard ABI on the target architecture.
7324 regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);
7326 // Gets a register mask that represent the kill set for a NoGC helper call.
7327 regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
7330 // Requires that "varDsc" be a promoted struct local variable being passed as an argument, beginning at
7331 // "firstArgRegNum", which is assumed to have already been aligned to the register alignment restriction of the
7332 // struct type. Adds bits to "*pArgSkippedRegMask" for any argument registers *not* used in passing "varDsc" --
7333 // i.e., internal "holes" caused by internal alignment constraints. For example, if the struct contained an int and
7334 // a double, and we at R0 (on ARM), then R1 would be skipped, and the bit for R1 would be added to the mask.
7335 void fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask);
7336 #endif // _TARGET_ARM_
7338 // 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
7340 static GenTree* fgIsIndirOfAddrOfLocal(GenTree* tree);
7342 // This map is indexed by GT_OBJ nodes that are address of promoted struct variables, which
7343 // have been annotated with the GTF_VAR_DEATH flag. If such a node is *not* mapped in this
7344 // table, one may assume that all the (tracked) field vars die at this GT_OBJ. Otherwise,
7345 // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
7346 // vars of the promoted struct local that go dead at the given node (the set bits are the bits
7347 // for the tracked var indices of the field vars, as in a live var set).
7349 // The map is allocated on demand so all map operations should use one of the following three
7352 NodeToVarsetPtrMap* m_promotedStructDeathVars;
7354 NodeToVarsetPtrMap* GetPromotedStructDeathVars()
7356 if (m_promotedStructDeathVars == nullptr)
7358 m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
7360 return m_promotedStructDeathVars;
7363 void ClearPromotedStructDeathVars()
7365 if (m_promotedStructDeathVars != nullptr)
7367 m_promotedStructDeathVars->RemoveAll();
7371 bool LookupPromotedStructDeathVars(GenTree* tree, VARSET_TP** bits)
7374 bool result = false;
7376 if (m_promotedStructDeathVars != nullptr)
7378 result = m_promotedStructDeathVars->Lookup(tree, bits);
7385 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7386 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7390 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7391 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7394 #if !defined(__GNUC__)
7395 #pragma region Unwind information
7400 // Infrastructure functions: start/stop/reserve/emit.
7403 void unwindBegProlog();
7404 void unwindEndProlog();
7405 void unwindBegEpilog();
7406 void unwindEndEpilog();
7407 void unwindReserve();
7408 void unwindEmit(void* pHotCode, void* pColdCode);
7411 // Specific unwind information functions: called by code generation to indicate a particular
7412 // prolog or epilog unwindable instruction has been generated.
7415 void unwindPush(regNumber reg);
7416 void unwindAllocStack(unsigned size);
7417 void unwindSetFrameReg(regNumber reg, unsigned offset);
7418 void unwindSaveReg(regNumber reg, unsigned offset);
7420 #if defined(_TARGET_ARM_)
7421 void unwindPushMaskInt(regMaskTP mask);
7422 void unwindPushMaskFloat(regMaskTP mask);
7423 void unwindPopMaskInt(regMaskTP mask);
7424 void unwindPopMaskFloat(regMaskTP mask);
7425 void unwindBranch16(); // The epilog terminates with a 16-bit branch (e.g., "bx lr")
7426 void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
7427 // called via unwindPadding().
7428 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7429 // instruction and the current location.
7430 #endif // _TARGET_ARM_
7432 #if defined(_TARGET_ARM64_)
7434 void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7435 // instruction and the current location.
7436 void unwindSaveReg(regNumber reg, int offset); // str reg, [sp, #offset]
7437 void unwindSaveRegPreindexed(regNumber reg, int offset); // str reg, [sp, #offset]!
7438 void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]
7439 void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
7440 void unwindSaveNext(); // unwind code: save_next
7441 void unwindReturn(regNumber reg); // ret lr
7442 #endif // defined(_TARGET_ARM64_)
7445 // Private "helper" functions for the unwind implementation.
7449 #if FEATURE_EH_FUNCLETS
7450 void unwindGetFuncLocations(FuncInfoDsc* func,
7451 bool getHotSectionData,
7452 /* OUT */ emitLocation** ppStartLoc,
7453 /* OUT */ emitLocation** ppEndLoc);
7454 #endif // FEATURE_EH_FUNCLETS
7456 void unwindReserveFunc(FuncInfoDsc* func);
7457 void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7459 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && FEATURE_EH_FUNCLETS)
7461 void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
7462 void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
7464 #endif // _TARGET_AMD64_ || (_TARGET_X86_ && FEATURE_EH_FUNCLETS)
7466 UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
7468 #if defined(_TARGET_AMD64_)
7470 void unwindBegPrologWindows();
7471 void unwindPushWindows(regNumber reg);
7472 void unwindAllocStackWindows(unsigned size);
7473 void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
7474 void unwindSaveRegWindows(regNumber reg, unsigned offset);
7476 #ifdef UNIX_AMD64_ABI
7477 void unwindSaveRegCFI(regNumber reg, unsigned offset);
7478 #endif // UNIX_AMD64_ABI
7479 #elif defined(_TARGET_ARM_)
7481 void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
7482 void unwindPushPopMaskFloat(regMaskTP mask);
7484 #endif // _TARGET_ARM_
7486 #if defined(_TARGET_UNIX_)
7487 int mapRegNumToDwarfReg(regNumber reg);
7488 void createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR opcode, USHORT dwarfReg, INT offset = 0);
7489 void unwindPushPopCFI(regNumber reg);
7490 void unwindBegPrologCFI();
7491 void unwindPushPopMaskCFI(regMaskTP regMask, bool isFloat);
7492 void unwindAllocStackCFI(unsigned size);
7493 void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
7494 void unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7496 void DumpCfiInfo(bool isHotCode,
7497 UNATIVE_OFFSET startOffset,
7498 UNATIVE_OFFSET endOffset,
7500 const CFI_CODE* const pCfiCode);
7503 #endif // _TARGET_UNIX_
7505 #if !defined(__GNUC__)
7506 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
7510 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7511 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7515 XX Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
7516 XX that contains the distinguished, well-known SIMD type definitions). XX
7518 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7519 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7522 // Get highest available level for SIMD codegen
7523 SIMDLevel getSIMDSupportLevel()
7525 #if defined(_TARGET_XARCH_)
7526 if (compSupports(InstructionSet_AVX2))
7528 return SIMD_AVX2_Supported;
7531 if (compSupports(InstructionSet_SSE42))
7533 return SIMD_SSE4_Supported;
7537 return SIMD_SSE2_Supported;
7539 assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
7541 return SIMD_Not_Supported;
7547 // Should we support SIMD intrinsics?
7550 // Have we identified any SIMD types?
7551 // This is currently used by struct promotion to avoid getting type information for a struct
7552 // field to see if it is a SIMD type, if we haven't seen any SIMD types or operations in
7554 bool _usesSIMDTypes;
7555 bool usesSIMDTypes()
7557 return _usesSIMDTypes;
7559 void setUsesSIMDTypes(bool value)
7561 _usesSIMDTypes = value;
7564 // This is a temp lclVar allocated on the stack as TYP_SIMD. It is used to implement intrinsics
7565 // that require indexed access to the individual fields of the vector, which is not well supported
7566 // by the hardware. It is allocated when/if such situations are encountered during Lowering.
7567 unsigned lvaSIMDInitTempVarNum;
7569 struct SIMDHandlesCache
7572 CORINFO_CLASS_HANDLE SIMDFloatHandle;
7573 CORINFO_CLASS_HANDLE SIMDDoubleHandle;
7574 CORINFO_CLASS_HANDLE SIMDIntHandle;
7575 CORINFO_CLASS_HANDLE SIMDUShortHandle;
7576 CORINFO_CLASS_HANDLE SIMDUByteHandle;
7577 CORINFO_CLASS_HANDLE SIMDShortHandle;
7578 CORINFO_CLASS_HANDLE SIMDByteHandle;
7579 CORINFO_CLASS_HANDLE SIMDLongHandle;
7580 CORINFO_CLASS_HANDLE SIMDUIntHandle;
7581 CORINFO_CLASS_HANDLE SIMDULongHandle;
7582 CORINFO_CLASS_HANDLE SIMDVector2Handle;
7583 CORINFO_CLASS_HANDLE SIMDVector3Handle;
7584 CORINFO_CLASS_HANDLE SIMDVector4Handle;
7585 CORINFO_CLASS_HANDLE SIMDVectorHandle;
7587 #ifdef FEATURE_HW_INTRINSICS
7588 #if defined(_TARGET_ARM64_)
7589 CORINFO_CLASS_HANDLE Vector64FloatHandle;
7590 CORINFO_CLASS_HANDLE Vector64IntHandle;
7591 CORINFO_CLASS_HANDLE Vector64UShortHandle;
7592 CORINFO_CLASS_HANDLE Vector64UByteHandle;
7593 CORINFO_CLASS_HANDLE Vector64ShortHandle;
7594 CORINFO_CLASS_HANDLE Vector64ByteHandle;
7595 CORINFO_CLASS_HANDLE Vector64UIntHandle;
7596 #endif // defined(_TARGET_ARM64_)
7597 CORINFO_CLASS_HANDLE Vector128FloatHandle;
7598 CORINFO_CLASS_HANDLE Vector128DoubleHandle;
7599 CORINFO_CLASS_HANDLE Vector128IntHandle;
7600 CORINFO_CLASS_HANDLE Vector128UShortHandle;
7601 CORINFO_CLASS_HANDLE Vector128UByteHandle;
7602 CORINFO_CLASS_HANDLE Vector128ShortHandle;
7603 CORINFO_CLASS_HANDLE Vector128ByteHandle;
7604 CORINFO_CLASS_HANDLE Vector128LongHandle;
7605 CORINFO_CLASS_HANDLE Vector128UIntHandle;
7606 CORINFO_CLASS_HANDLE Vector128ULongHandle;
7607 #if defined(_TARGET_XARCH_)
7608 CORINFO_CLASS_HANDLE Vector256FloatHandle;
7609 CORINFO_CLASS_HANDLE Vector256DoubleHandle;
7610 CORINFO_CLASS_HANDLE Vector256IntHandle;
7611 CORINFO_CLASS_HANDLE Vector256UShortHandle;
7612 CORINFO_CLASS_HANDLE Vector256UByteHandle;
7613 CORINFO_CLASS_HANDLE Vector256ShortHandle;
7614 CORINFO_CLASS_HANDLE Vector256ByteHandle;
7615 CORINFO_CLASS_HANDLE Vector256LongHandle;
7616 CORINFO_CLASS_HANDLE Vector256UIntHandle;
7617 CORINFO_CLASS_HANDLE Vector256ULongHandle;
7618 #endif // defined(_TARGET_XARCH_)
7619 #endif // FEATURE_HW_INTRINSICS
7623 memset(this, 0, sizeof(*this));
7627 SIMDHandlesCache* m_simdHandleCache;
7629 // Get an appropriate "zero" for the given type and class handle.
7630 GenTree* gtGetSIMDZero(var_types simdType, var_types baseType, CORINFO_CLASS_HANDLE simdHandle);
7632 // Get the handle for a SIMD type.
7633 CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
7635 if (m_simdHandleCache == nullptr)
7637 // This may happen if the JIT generates SIMD node on its own, without importing them.
7638 // Otherwise getBaseTypeAndSizeOfSIMDType should have created the cache.
7639 return NO_CLASS_HANDLE;
7642 if (simdBaseType == TYP_FLOAT)
7647 return m_simdHandleCache->SIMDVector2Handle;
7649 return m_simdHandleCache->SIMDVector3Handle;
7651 if ((getSIMDVectorType() == TYP_SIMD32) ||
7652 (m_simdHandleCache->SIMDVector4Handle != NO_CLASS_HANDLE))
7654 return m_simdHandleCache->SIMDVector4Handle;
7663 assert(emitTypeSize(simdType) <= maxSIMDStructBytes());
7664 switch (simdBaseType)
7667 return m_simdHandleCache->SIMDFloatHandle;
7669 return m_simdHandleCache->SIMDDoubleHandle;
7671 return m_simdHandleCache->SIMDIntHandle;
7673 return m_simdHandleCache->SIMDUShortHandle;
7675 return m_simdHandleCache->SIMDUByteHandle;
7677 return m_simdHandleCache->SIMDShortHandle;
7679 return m_simdHandleCache->SIMDByteHandle;
7681 return m_simdHandleCache->SIMDLongHandle;
7683 return m_simdHandleCache->SIMDUIntHandle;
7685 return m_simdHandleCache->SIMDULongHandle;
7687 assert(!"Didn't find a class handle for simdType");
7689 return NO_CLASS_HANDLE;
7692 // Returns true if this is a SIMD type that should be considered an opaque
7693 // vector type (i.e. do not analyze or promote its fields).
7694 // Note that all but the fixed vector types are opaque, even though they may
7695 // actually be declared as having fields.
7696 bool isOpaqueSIMDType(CORINFO_CLASS_HANDLE structHandle)
7698 return ((m_simdHandleCache != nullptr) && (structHandle != m_simdHandleCache->SIMDVector2Handle) &&
7699 (structHandle != m_simdHandleCache->SIMDVector3Handle) &&
7700 (structHandle != m_simdHandleCache->SIMDVector4Handle));
7703 // Returns true if the tree corresponds to a TYP_SIMD lcl var.
7704 // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
7705 // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
7706 bool isSIMDTypeLocal(GenTree* tree)
7708 return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7711 // Returns true if the lclVar is an opaque SIMD type.
7712 bool isOpaqueSIMDLclVar(LclVarDsc* varDsc)
7714 if (!varDsc->lvSIMDType)
7718 return isOpaqueSIMDType(varDsc->lvVerTypeInfo.GetClassHandle());
7721 // Returns true if the type of the tree is a byref of TYP_SIMD
7722 bool isAddrOfSIMDType(GenTree* tree)
7724 if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
7726 switch (tree->OperGet())
7729 return varTypeIsSIMD(tree->gtGetOp1());
7731 case GT_LCL_VAR_ADDR:
7732 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7735 return isSIMDTypeLocal(tree);
7742 static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
7744 return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
7745 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
7746 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
7749 // Returns base type of a TYP_SIMD local.
7750 // Returns TYP_UNKNOWN if the local is not TYP_SIMD.
7751 var_types getBaseTypeOfSIMDLocal(GenTree* tree)
7753 if (isSIMDTypeLocal(tree))
7755 return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
7761 bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7763 return info.compCompHnd->isInSIMDModule(clsHnd);
7766 bool isIntrinsicType(CORINFO_CLASS_HANDLE clsHnd)
7768 return (info.compCompHnd->getClassAttribs(clsHnd) & CORINFO_FLG_INTRINSIC_TYPE) != 0;
7771 const char* getClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, const char** namespaceName)
7773 return info.compCompHnd->getClassNameFromMetadata(cls, namespaceName);
7776 CORINFO_CLASS_HANDLE getTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index)
7778 return info.compCompHnd->getTypeInstantiationArgument(cls, index);
7781 bool isSIMDClass(typeInfo* pTypeInfo)
7783 return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7786 bool isHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7788 #ifdef FEATURE_HW_INTRINSICS
7789 if (isIntrinsicType(clsHnd))
7791 const char* namespaceName = nullptr;
7792 (void)getClassNameFromMetadata(clsHnd, &namespaceName);
7793 return strcmp(namespaceName, "System.Runtime.Intrinsics") == 0;
7795 #endif // FEATURE_HW_INTRINSICS
7799 bool isHWSIMDClass(typeInfo* pTypeInfo)
7801 #ifdef FEATURE_HW_INTRINSICS
7802 return pTypeInfo->IsStruct() && isHWSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7808 bool isSIMDorHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7810 return isSIMDClass(clsHnd) || isHWSIMDClass(clsHnd);
7813 bool isSIMDorHWSIMDClass(typeInfo* pTypeInfo)
7815 return isSIMDClass(pTypeInfo) || isHWSIMDClass(pTypeInfo);
7818 // Get the base (element) type and size in bytes for a SIMD type. Returns TYP_UNKNOWN
7819 // if it is not a SIMD type or is an unsupported base type.
7820 var_types getBaseTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);
7822 var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7824 return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
7827 // Get SIMD Intrinsic info given the method handle.
7828 // Also sets typeHnd, argCount, baseType and sizeBytes out params.
7829 const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
7830 CORINFO_METHOD_HANDLE methodHnd,
7831 CORINFO_SIG_INFO* sig,
7834 var_types* baseType,
7835 unsigned* sizeBytes);
7837 // Pops and returns GenTree node from importers type stack.
7838 // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
7839 GenTree* impSIMDPopStack(var_types type, bool expectAddr = false, CORINFO_CLASS_HANDLE structType = nullptr);
7841 // Create a GT_SIMD tree for a Get property of SIMD vector with a fixed index.
7842 GenTreeSIMD* impSIMDGetFixed(var_types simdType, var_types baseType, unsigned simdSize, int index);
7844 // Creates a GT_SIMD tree for Select operation
7845 GenTree* impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7847 unsigned simdVectorSize,
7852 // Creates a GT_SIMD tree for Min/Max operation
7853 GenTree* impSIMDMinMax(SIMDIntrinsicID intrinsicId,
7854 CORINFO_CLASS_HANDLE typeHnd,
7856 unsigned simdVectorSize,
7860 // Transforms operands and returns the SIMD intrinsic to be applied on
7861 // transformed operands to obtain given relop result.
7862 SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID relOpIntrinsicId,
7863 CORINFO_CLASS_HANDLE typeHnd,
7864 unsigned simdVectorSize,
7865 var_types* baseType,
7869 // Creates a GT_SIMD tree for Abs intrinsic.
7870 GenTree* impSIMDAbs(CORINFO_CLASS_HANDLE typeHnd, var_types baseType, unsigned simdVectorSize, GenTree* op1);
7872 #if defined(_TARGET_XARCH_)
7874 // Transforms operands and returns the SIMD intrinsic to be applied on
7875 // transformed operands to obtain == comparison result.
7876 SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
7877 unsigned simdVectorSize,
7881 // Transforms operands and returns the SIMD intrinsic to be applied on
7882 // transformed operands to obtain > comparison result.
7883 SIMDIntrinsicID impSIMDLongRelOpGreaterThan(CORINFO_CLASS_HANDLE typeHnd,
7884 unsigned simdVectorSize,
7888 // Transforms operands and returns the SIMD intrinsic to be applied on
7889 // transformed operands to obtain >= comparison result.
7890 SIMDIntrinsicID impSIMDLongRelOpGreaterThanOrEqual(CORINFO_CLASS_HANDLE typeHnd,
7891 unsigned simdVectorSize,
7895 // Transforms operands and returns the SIMD intrinsic to be applied on
7896 // transformed operands to obtain >= comparison result in case of int32
7897 // and small int base type vectors.
7898 SIMDIntrinsicID impSIMDIntegralRelOpGreaterThanOrEqual(
7899 CORINFO_CLASS_HANDLE typeHnd, unsigned simdVectorSize, var_types baseType, GenTree** op1, GenTree** op2);
7901 #endif // defined(_TARGET_XARCH_)
7903 void setLclRelatedToSIMDIntrinsic(GenTree* tree);
7904 bool areFieldsContiguous(GenTree* op1, GenTree* op2);
7905 bool areArrayElementsContiguous(GenTree* op1, GenTree* op2);
7906 bool areArgumentsContiguous(GenTree* op1, GenTree* op2);
7907 GenTree* createAddressNodeForSIMDInit(GenTree* tree, unsigned simdSize);
7909 // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
7910 GenTree* impSIMDIntrinsic(OPCODE opcode,
7911 GenTree* newobjThis,
7912 CORINFO_CLASS_HANDLE clsHnd,
7913 CORINFO_METHOD_HANDLE method,
7914 CORINFO_SIG_INFO* sig,
7915 unsigned methodFlags,
7918 GenTree* getOp1ForConstructor(OPCODE opcode, GenTree* newobjThis, CORINFO_CLASS_HANDLE clsHnd);
7920 // Whether SIMD vector occupies part of SIMD register.
7921 // SSE2: vector2f/3f are considered sub register SIMD types.
7922 // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
7923 bool isSubRegisterSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7925 unsigned sizeBytes = 0;
7926 var_types baseType = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7927 return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7930 bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7932 return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7935 // Get the type for the hardware SIMD vector.
7936 // This is the maximum SIMD type supported for this target.
7937 var_types getSIMDVectorType()
7939 #if defined(_TARGET_XARCH_)
7940 if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7946 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7949 #elif defined(_TARGET_ARM64_)
7952 assert(!"getSIMDVectorType() unimplemented on target arch");
7957 // Get the size of the SIMD type in bytes
7958 int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7960 unsigned sizeBytes = 0;
7961 (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7965 // Get the the number of elements of basetype of SIMD vector given by its size and baseType
7966 static int getSIMDVectorLength(unsigned simdSize, var_types baseType);
7968 // Get the the number of elements of basetype of SIMD vector given by its type handle
7969 int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7971 // Get preferred alignment of SIMD type.
7972 int getSIMDTypeAlignment(var_types simdType);
7974 // Get the number of bytes in a System.Numeric.Vector<T> for the current compilation.
7975 // Note - cannot be used for System.Runtime.Intrinsic
7976 unsigned getSIMDVectorRegisterByteLength()
7978 #if defined(_TARGET_XARCH_)
7979 if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7981 return YMM_REGSIZE_BYTES;
7985 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7986 return XMM_REGSIZE_BYTES;
7988 #elif defined(_TARGET_ARM64_)
7989 return FP_REGSIZE_BYTES;
7991 assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7996 // The minimum and maximum possible number of bytes in a SIMD vector.
7998 // maxSIMDStructBytes
7999 // The minimum SIMD size supported by System.Numeric.Vectors or System.Runtime.Intrinsic
8000 // SSE: 16-byte Vector<T> and Vector128<T>
8001 // AVX: 32-byte Vector256<T> (Vector<T> is 16-byte)
8002 // AVX2: 32-byte Vector<T> and Vector256<T>
8003 unsigned int maxSIMDStructBytes()
8005 #if defined(FEATURE_HW_INTRINSICS) && defined(_TARGET_XARCH_)
8006 if (compSupports(InstructionSet_AVX))
8008 return YMM_REGSIZE_BYTES;
8012 assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
8013 return XMM_REGSIZE_BYTES;
8016 return getSIMDVectorRegisterByteLength();
8019 unsigned int minSIMDStructBytes()
8021 return emitTypeSize(TYP_SIMD8);
8024 // Returns the codegen type for a given SIMD size.
8025 var_types getSIMDTypeForSize(unsigned size)
8027 var_types simdType = TYP_UNDEF;
8030 simdType = TYP_SIMD8;
8032 else if (size == 12)
8034 simdType = TYP_SIMD12;
8036 else if (size == 16)
8038 simdType = TYP_SIMD16;
8040 else if (size == 32)
8042 simdType = TYP_SIMD32;
8046 noway_assert(!"Unexpected size for SIMD type");
8051 unsigned getSIMDInitTempVarNum()
8053 if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
8055 lvaSIMDInitTempVarNum = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
8056 lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
8058 return lvaSIMDInitTempVarNum;
8061 #else // !FEATURE_SIMD
8062 bool isOpaqueSIMDLclVar(LclVarDsc* varDsc)
8066 #endif // FEATURE_SIMD
8069 //------------------------------------------------------------------------
8070 // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
8072 // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
8073 // candidate for enregistration.
8075 unsigned largestEnregisterableStructSize()
8078 unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
8079 if (vectorRegSize > TARGET_POINTER_SIZE)
8081 return vectorRegSize;
8084 #endif // FEATURE_SIMD
8086 return TARGET_POINTER_SIZE;
8091 // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
8092 // is defined for both FEATURE_SIMD and !FEATURE_SIMD apropriately. The use
8093 // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.
8095 // Is this var is of type simd struct?
8096 bool lclVarIsSIMDType(unsigned varNum)
8098 LclVarDsc* varDsc = lvaTable + varNum;
8099 return varDsc->lvIsSIMDType();
8102 // Is this Local node a SIMD local?
8103 bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
8105 return lclVarIsSIMDType(lclVarTree->gtLclNum);
8108 // Returns true if the TYP_SIMD locals on stack are aligned at their
8109 // preferred byte boundary specified by getSIMDTypeAlignment().
8111 // As per the Intel manual, the preferred alignment for AVX vectors is 32-bytes. On Amd64,
8112 // RSP/EBP is aligned at 16-bytes, therefore to align SIMD types at 32-bytes we need even
8113 // RSP/EBP to be 32-byte aligned. It is not clear whether additional stack space used in
8114 // aligning stack is worth the benefit and for now will use 16-byte alignment for AVX
8115 // 256-bit vectors with unaligned load/stores to/from memory. On x86, the stack frame
8116 // is aligned to 4 bytes. We need to extend existing support for double (8-byte) alignment
8117 // to 16 or 32 byte alignment for frames with local SIMD vars, if that is determined to be
8120 bool isSIMDTypeLocalAligned(unsigned varNum)
8122 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
8123 if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
8126 int off = lvaFrameAddress(varNum, &ebpBased);
8127 // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
8128 int alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
8129 bool isAligned = (alignment <= STACK_ALIGN) && ((off % alignment) == 0);
8132 #endif // FEATURE_SIMD
8137 bool compSupports(InstructionSet isa) const
8139 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8140 return (opts.compSupportsISA & (1ULL << isa)) != 0;
8146 bool canUseVexEncoding() const
8148 #ifdef _TARGET_XARCH_
8149 return compSupports(InstructionSet_AVX);
8156 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8157 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8161 XX Generic info about the compilation and the method being compiled. XX
8162 XX It is responsible for driving the other phases. XX
8163 XX It is also responsible for all the memory management. XX
8165 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8166 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8170 Compiler* InlineeCompiler; // The Compiler instance for the inlinee
8172 InlineResult* compInlineResult; // The result of importing the inlinee method.
8174 bool compDoAggressiveInlining; // If true, mark every method as CORINFO_FLG_FORCEINLINE
8175 bool compJmpOpUsed; // Does the method do a JMP
8176 bool compLongUsed; // Does the method use TYP_LONG
8177 bool compFloatingPointUsed; // Does the method use TYP_FLOAT or TYP_DOUBLE
8178 bool compTailCallUsed; // Does the method do a tailcall
8179 bool compLocallocUsed; // Does the method use localloc.
8180 bool compLocallocOptimized; // Does the method have an optimized localloc
8181 bool compQmarkUsed; // Does the method use GT_QMARK/GT_COLON
8182 bool compQmarkRationalized; // Is it allowed to use a GT_QMARK/GT_COLON node.
8183 bool compUnsafeCastUsed; // Does the method use LDIND/STIND to cast between scalar/refernce types
8185 // NOTE: These values are only reliable after
8186 // the importing is completely finished.
8189 // State information - which phases have completed?
8190 // These are kept together for easy discoverability
8192 bool bRangeAllowStress;
8193 bool compCodeGenDone;
8194 int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
8195 bool fgNormalizeEHDone; // Has the flowgraph EH normalization phase been done?
8196 size_t compSizeEstimate; // The estimated size of the method as per `gtSetEvalOrder`.
8197 size_t compCycleEstimate; // The estimated cycle count of the method as per `gtSetEvalOrder`
8200 bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
8201 bool fgLocalVarLivenessChanged;
8203 bool compStackProbePrologDone;
8206 bool compRationalIRForm;
8208 bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
8210 bool compGeneratingProlog;
8211 bool compGeneratingEpilog;
8212 bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
8213 // Insert cookie on frame and code to check the cookie, like VC++ -GS.
8214 bool compGSReorderStackLayout; // There is an unsafe buffer on the stack, reorder locals and make local
8215 // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
8216 bool getNeedsGSSecurityCookie() const
8218 return compNeedsGSSecurityCookie;
8220 void setNeedsGSSecurityCookie()
8222 compNeedsGSSecurityCookie = true;
8225 FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
8226 // frame layout calculations, this is the level we are currently
8229 //---------------------------- JITing options -----------------------------
8242 JitFlags* jitFlags; // all flags passed from the EE
8243 unsigned compFlags; // method attributes
8245 codeOptimize compCodeOpt; // what type of code optimizations
8250 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8251 uint64_t compSupportsISA;
8252 void setSupportedISA(InstructionSet isa)
8254 compSupportsISA |= 1ULL << isa;
8258 // optimize maximally and/or favor speed over size?
8260 #define DEFAULT_MIN_OPTS_CODE_SIZE 60000
8261 #define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
8262 #define DEFAULT_MIN_OPTS_BB_COUNT 2000
8263 #define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
8264 #define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000
8266 // Maximun number of locals before turning off the inlining
8267 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
8270 unsigned instrCount;
8271 unsigned lvRefCount;
8272 bool compMinOptsIsSet;
8274 bool compMinOptsIsUsed;
8278 assert(compMinOptsIsSet);
8279 compMinOptsIsUsed = true;
8284 return compMinOptsIsSet;
8293 return compMinOptsIsSet;
8297 bool OptimizationDisabled()
8299 return MinOpts() || compDbgCode;
8301 bool OptimizationEnabled()
8303 return !OptimizationDisabled();
8306 void SetMinOpts(bool val)
8308 assert(!compMinOptsIsUsed);
8309 assert(!compMinOptsIsSet || (compMinOpts == val));
8311 compMinOptsIsSet = true;
8314 // true if the CLFLG_* for an optimization is set.
8315 bool OptEnabled(unsigned optFlag)
8317 return !!(compFlags & optFlag);
8320 #ifdef FEATURE_READYTORUN_COMPILER
8323 return jitFlags->IsSet(JitFlags::JIT_FLAG_READYTORUN);
8332 // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
8333 // PInvoke transitions inline (e.g. when targeting CoreRT).
8334 bool ShouldUsePInvokeHelpers()
8336 return jitFlags->IsSet(JitFlags::JIT_FLAG_USE_PINVOKE_HELPERS);
8339 // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
8341 bool IsReversePInvoke()
8343 return jitFlags->IsSet(JitFlags::JIT_FLAG_REVERSE_PINVOKE);
8346 // true if we must generate code compatible with JIT32 quirks
8347 bool IsJit32Compat()
8349 #if defined(_TARGET_X86_)
8350 return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8356 // true if we must generate code compatible with Jit64 quirks
8357 bool IsJit64Compat()
8359 #if defined(_TARGET_AMD64_)
8360 return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8361 #elif !defined(FEATURE_CORECLR)
8368 bool compScopeInfo; // Generate the LocalVar info ?
8369 bool compDbgCode; // Generate debugger-friendly code?
8370 bool compDbgInfo; // Gather debugging info?
8373 #ifdef PROFILING_SUPPORTED
8374 bool compNoPInvokeInlineCB;
8376 static const bool compNoPInvokeInlineCB;
8380 bool compGcChecks; // Check arguments and return values to ensure they are sane
8383 #if defined(DEBUG) && defined(_TARGET_XARCH_)
8385 bool compStackCheckOnRet; // Check stack pointer on return to ensure it is correct.
8387 #endif // defined(DEBUG) && defined(_TARGET_XARCH_)
8389 #if defined(DEBUG) && defined(_TARGET_X86_)
8391 bool compStackCheckOnCall; // Check stack pointer after call to ensure it is correct. Only for x86.
8393 #endif // defined(DEBUG) && defined(_TARGET_X86_)
8395 bool compNeedSecurityCheck; // This flag really means where or not a security object needs
8396 // to be allocated on the stack.
8397 // It will be set to true in the following cases:
8398 // 1. When the method being compiled has a declarative security
8399 // (i.e. when CORINFO_FLG_NOSECURITYWRAP is reset for the current method).
8400 // This is also the case when we inject a prolog and epilog in the method.
8402 // 2. When the method being compiled has imperative security (i.e. the method
8403 // calls into another method that has CORINFO_FLG_SECURITYCHECK flag set).
8405 // 3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
8407 // When this flag is set, jit will allocate a gc-reference local variable (lvaSecurityObject),
8408 // which gets reported as a GC root to stackwalker.
8409 // (See also ICodeManager::GetAddrOfSecurityObject.)
8411 bool compReloc; // Generate relocs for pointers in code, true for all ngen/prejit codegen
8414 #if defined(_TARGET_XARCH_)
8415 bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
8419 #ifdef UNIX_AMD64_ABI
8420 // This flag is indicating if there is a need to align the frame.
8421 // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
8422 // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
8423 // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
8424 // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
8425 // there are calls and making sure the frame alignment logic is executed.
8426 bool compNeedToAlignFrame;
8427 #endif // UNIX_AMD64_ABI
8429 bool compProcedureSplitting; // Separate cold code from hot code
8431 bool genFPorder; // Preserve FP order (operations are non-commutative)
8432 bool genFPopt; // Can we do frame-pointer-omission optimization?
8433 bool altJit; // True if we are an altjit and are compiling this method
8436 bool optRepeat; // Repeat optimizer phases k times
8440 bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
8441 bool dspCode; // Display native code generated
8442 bool dspEHTable; // Display the EH table reported to the VM
8443 bool dspDebugInfo; // Display the Debug info reported to the VM
8444 bool dspInstrs; // Display the IL instructions intermixed with the native code output
8445 bool dspEmit; // Display emitter output
8446 bool dspLines; // Display source-code lines intermixed with native code output
8447 bool dmpHex; // Display raw bytes in hex of native code output
8448 bool varNames; // Display variables names in native code output
8449 bool disAsm; // Display native code as it is generated
8450 bool disAsmSpilled; // Display native code when any register spilling occurs
8451 bool disDiffable; // Makes the Disassembly code 'diff-able'
8452 bool disAsm2; // Display native code after it is generated using external disassembler
8453 bool dspOrder; // Display names of each of the methods that we ngen/jit
8454 bool dspUnwind; // Display the unwind info output
8455 bool dspDiffable; // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
8456 bool compLongAddress; // Force using large pseudo instructions for long address
8457 // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
8458 bool dspGCtbls; // Display the GC tables
8462 bool doLateDisasm; // Run the late disassembler
8463 #endif // LATE_DISASM
8465 #if DUMP_GC_TABLES && !defined(DEBUG) && defined(JIT32_GCENCODER)
8466 // Only the JIT32_GCENCODER implements GC dumping in non-DEBUG code.
8467 #pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
8468 static const bool dspGCtbls = true;
8471 // We need stack probes to guarantee that we won't trigger a stack overflow
8472 // when calling unmanaged code until they get a chance to set up a frame, because
8473 // the EE will have no idea where it is.
8475 // We will only be doing this currently for hosted environments. Unfortunately
8476 // we need to take care of stubs, so potentially, we will have to do the probes
8477 // for any call. We have a plan for not needing for stubs though
8478 bool compNeedStackProbes;
8480 #ifdef PROFILING_SUPPORTED
8481 // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub()).
8482 // This option helps make the JIT behave as if it is running under a profiler.
8483 bool compJitELTHookEnabled;
8484 #endif // PROFILING_SUPPORTED
8486 #if FEATURE_TAILCALL_OPT
8487 // Whether opportunistic or implicit tail call optimization is enabled.
8488 bool compTailCallOpt;
8489 // Whether optimization of transforming a recursive tail call into a loop is enabled.
8490 bool compTailCallLoopOpt;
8494 static const bool compUseSoftFP = true;
8495 #else // !ARM_SOFTFP
8496 static const bool compUseSoftFP = false;
8499 GCPollType compGCPollType;
8503 static bool s_pAltJitExcludeAssembliesListInitialized;
8504 static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
8508 static bool s_pJitDisasmIncludeAssembliesListInitialized;
8509 static AssemblyNamesList2* s_pJitDisasmIncludeAssembliesList;
8513 // silence warning of cast to greater size. It is easier to silence than construct code the compiler is happy with, and
8514 // it is safe in this case
8515 #pragma warning(push)
8516 #pragma warning(disable : 4312)
8518 template <typename T>
8521 return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
8524 template <typename T>
8527 return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
8529 #pragma warning(pop)
8531 static int dspTreeID(GenTree* tree)
8533 return tree->gtTreeID;
8535 static void printTreeID(GenTree* tree)
8537 if (tree == nullptr)
8543 printf("[%06d]", dspTreeID(tree));
8550 #define STRESS_MODES \
8554 /* "Variations" stress areas which we try to mix up with each other. */ \
8555 /* These should not be exhaustively used as they might */ \
8556 /* hide/trivialize other areas */ \
8559 STRESS_MODE(DBL_ALN) \
8560 STRESS_MODE(LCL_FLDS) \
8561 STRESS_MODE(UNROLL_LOOPS) \
8562 STRESS_MODE(MAKE_CSE) \
8563 STRESS_MODE(LEGACY_INLINE) \
8564 STRESS_MODE(CLONE_EXPR) \
8565 STRESS_MODE(USE_FCOMI) \
8566 STRESS_MODE(USE_CMOV) \
8568 STRESS_MODE(BB_PROFILE) \
8569 STRESS_MODE(OPT_BOOLS_GC) \
8570 STRESS_MODE(REMORPH_TREES) \
8571 STRESS_MODE(64RSLT_MUL) \
8572 STRESS_MODE(DO_WHILE_LOOPS) \
8573 STRESS_MODE(MIN_OPTS) \
8574 STRESS_MODE(REVERSE_FLAG) /* Will set GTF_REVERSE_OPS whenever we can */ \
8575 STRESS_MODE(REVERSE_COMMA) /* Will reverse commas created with gtNewCommaNode */ \
8576 STRESS_MODE(TAILCALL) /* Will make the call as a tailcall whenever legal */ \
8577 STRESS_MODE(CATCH_ARG) /* Will spill catch arg */ \
8578 STRESS_MODE(UNSAFE_BUFFER_CHECKS) \
8579 STRESS_MODE(NULL_OBJECT_CHECK) \
8580 STRESS_MODE(PINVOKE_RESTORE_ESP) \
8581 STRESS_MODE(RANDOM_INLINE) \
8582 STRESS_MODE(SWITCH_CMP_BR_EXPANSION) \
8583 STRESS_MODE(GENERIC_VARN) \
8585 /* After COUNT_VARN, stress level 2 does all of these all the time */ \
8587 STRESS_MODE(COUNT_VARN) \
8589 /* "Check" stress areas that can be exhaustively used if we */ \
8590 /* dont care about performance at all */ \
8592 STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */ \
8593 STRESS_MODE(CHK_FLOW_UPDATE) \
8594 STRESS_MODE(EMITTER) \
8595 STRESS_MODE(CHK_REIMPORT) \
8596 STRESS_MODE(FLATFP) \
8597 STRESS_MODE(GENERIC_CHECK) \
8602 #define STRESS_MODE(mode) STRESS_##mode,
8609 static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
8610 BYTE compActiveStressModes[STRESS_COUNT];
8613 #define MAX_STRESS_WEIGHT 100
8615 bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
8619 bool compInlineStress()
8621 return compStressCompile(STRESS_LEGACY_INLINE, 50);
8624 bool compRandomInlineStress()
8626 return compStressCompile(STRESS_RANDOM_INLINE, 50);
8631 bool compTailCallStress()
8634 return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
8640 codeOptimize compCodeOpt()
8643 // Switching between size & speed has measurable throughput impact
8644 // (3.5% on NGen mscorlib when measured). It used to be enabled for
8645 // DEBUG, but should generate identical code between CHK & RET builds,
8646 // so that's not acceptable.
8647 // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
8648 // Investigate the cause of the throughput regression.
8650 return opts.compCodeOpt;
8652 return BLENDED_CODE;
8656 //--------------------- Info about the procedure --------------------------
8660 COMP_HANDLE compCompHnd;
8661 CORINFO_MODULE_HANDLE compScopeHnd;
8662 CORINFO_CLASS_HANDLE compClassHnd;
8663 CORINFO_METHOD_HANDLE compMethodHnd;
8664 CORINFO_METHOD_INFO* compMethodInfo;
8666 BOOL hasCircularClassConstraints;
8667 BOOL hasCircularMethodConstraints;
8669 #if defined(DEBUG) || defined(LATE_DISASM)
8670 const char* compMethodName;
8671 const char* compClassName;
8672 const char* compFullName;
8673 #endif // defined(DEBUG) || defined(LATE_DISASM)
8675 #if defined(DEBUG) || defined(INLINE_DATA)
8676 // Method hash is logcally const, but computed
8678 mutable unsigned compMethodHashPrivate;
8679 unsigned compMethodHash() const;
8680 #endif // defined(DEBUG) || defined(INLINE_DATA)
8682 #ifdef PSEUDORANDOM_NOP_INSERTION
8683 // things for pseudorandom nop insertion
8684 unsigned compChecksum;
8688 // The following holds the FLG_xxxx flags for the method we're compiling.
8691 // The following holds the class attributes for the method we're compiling.
8692 unsigned compClassAttr;
8694 const BYTE* compCode;
8695 IL_OFFSET compILCodeSize; // The IL code size
8696 IL_OFFSET compILImportSize; // Estimated amount of IL actually imported
8697 UNATIVE_OFFSET compNativeCodeSize; // The native code size, after instructions are issued. This
8698 // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
8699 // (1) the code is not hot/cold split, and we issued less code than we expected, or
8700 // (2) the code is hot/cold split, and we issued less code than we expected
8701 // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).
8703 bool compIsStatic : 1; // Is the method static (no 'this' pointer)?
8704 bool compIsVarArgs : 1; // Does the method have varargs parameters?
8705 bool compIsContextful : 1; // contextful method
8706 bool compInitMem : 1; // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
8707 bool compUnwrapContextful : 1; // JIT should unwrap proxies when possible
8708 bool compProfilerCallback : 1; // JIT inserted a profiler Enter callback
8709 bool compPublishStubParam : 1; // EAX captured in prolog will be available through an instrinsic
8710 bool compRetBuffDefStack : 1; // The ret buff argument definitely points into the stack.
8712 var_types compRetType; // Return type of the method as declared in IL
8713 var_types compRetNativeType; // Normalized return type as per target arch ABI
8714 unsigned compILargsCount; // Number of arguments (incl. implicit but not hidden)
8715 unsigned compArgsCount; // Number of arguments (incl. implicit and hidden)
8717 #if FEATURE_FASTTAILCALL
8718 size_t compArgStackSize; // Incoming argument stack size in bytes
8719 #endif // FEATURE_FASTTAILCALL
8721 unsigned compRetBuffArg; // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
8722 int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
8723 unsigned compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
8724 unsigned compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
8725 unsigned compLocalsCount; // Number of vars : args + locals (incl. implicit and hidden)
8726 unsigned compMaxStack;
8727 UNATIVE_OFFSET compTotalHotCodeSize; // Total number of bytes of Hot Code in the method
8728 UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method
8730 unsigned compCallUnmanaged; // count of unmanaged calls
8731 unsigned compLvFrameListRoot; // lclNum for the Frame root
8732 unsigned compXcptnsCount; // Number of exception-handling clauses read in the method's IL.
8733 // You should generally use compHndBBtabCount instead: it is the
8734 // current number of EH clauses (after additions like synchronized
8735 // methods and funclets, and removals like unreachable code deletion).
8737 bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
8738 // and the VM expects that, or the JIT is a "self-host" compiler
8739 // (e.g., x86 hosted targeting x86) and the VM expects that.
8741 /* The following holds IL scope information about local variables.
8744 unsigned compVarScopesCount;
8745 VarScopeDsc* compVarScopes;
8747 /* The following holds information about instr offsets for
8748 * which we need to report IP-mappings
8751 IL_OFFSET* compStmtOffsets; // sorted
8752 unsigned compStmtOffsetsCount;
8753 ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
8755 #define CPU_X86 0x0100 // The generic X86 CPU
8756 #define CPU_X86_PENTIUM_4 0x0110
8758 #define CPU_X64 0x0200 // The generic x64 CPU
8759 #define CPU_AMD_X64 0x0210 // AMD x64 CPU
8760 #define CPU_INTEL_X64 0x0240 // Intel x64 CPU
8762 #define CPU_ARM 0x0300 // The generic ARM CPU
8763 #define CPU_ARM64 0x0400 // The generic ARM64 CPU
8765 unsigned genCPU; // What CPU are we running on
8768 // Returns true if the method being compiled returns a non-void and non-struct value.
8769 // Note that lvaInitTypeRef() normalizes compRetNativeType for struct returns in a
8770 // single register as per target arch ABI (e.g on Amd64 Windows structs of size 1, 2,
8771 // 4 or 8 gets normalized to TYP_BYTE/TYP_SHORT/TYP_INT/TYP_LONG; On Arm HFA structs).
8772 // Methods returning such structs are considered to return non-struct return value and
8773 // this method returns true in that case.
8774 bool compMethodReturnsNativeScalarType()
8776 return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
8779 // Returns true if the method being compiled returns RetBuf addr as its return value
8780 bool compMethodReturnsRetBufAddr()
8782 // There are cases where implicit RetBuf argument should be explicitly returned in a register.
8783 // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
8785 // 1. Profiler Leave calllback expects the address of retbuf as return value for
8786 // methods with hidden RetBuf argument. impReturnInstruction() when profiler
8787 // callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
8788 // methods with hidden RetBufArg.
8790 // 2. As per the System V ABI, the address of RetBuf needs to be returned by
8791 // methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
8792 // returning the address of RetBuf.
8794 // 3. Windows 64-bit native calling convention also requires the address of RetBuff
8795 // to be returned in RAX.
8796 CLANG_FORMAT_COMMENT_ANCHOR;
8798 #ifdef _TARGET_AMD64_
8799 return (info.compRetBuffArg != BAD_VAR_NUM);
8800 #else // !_TARGET_AMD64_
8801 return (compIsProfilerHookNeeded()) && (info.compRetBuffArg != BAD_VAR_NUM);
8802 #endif // !_TARGET_AMD64_
8805 // Returns true if the method returns a value in more than one return register
8806 // TODO-ARM-Bug: Deal with multi-register genReturnLocaled structs?
8807 // TODO-ARM64: Does this apply for ARM64 too?
8808 bool compMethodReturnsMultiRegRetType()
8810 #if FEATURE_MULTIREG_RET
8811 #if defined(_TARGET_X86_)
8812 // On x86 only 64-bit longs are returned in multiple registers
8813 return varTypeIsLong(info.compRetNativeType);
8814 #else // targets: X64-UNIX, ARM64 or ARM32
8815 // On all other targets that support multireg return values:
8816 // Methods returning a struct in multiple registers have a return value of TYP_STRUCT.
8817 // Such method's compRetNativeType is TYP_STRUCT without a hidden RetBufArg
8818 return varTypeIsStruct(info.compRetNativeType) && (info.compRetBuffArg == BAD_VAR_NUM);
8819 #endif // TARGET_XXX
8821 #else // not FEATURE_MULTIREG_RET
8823 // For this architecture there are no multireg returns
8826 #endif // FEATURE_MULTIREG_RET
8829 #if FEATURE_MULTIREG_ARGS
8830 // Given a GenTree node of TYP_STRUCT that represents a pass by value argument
8831 // return the gcPtr layout for the pointers sized fields
8832 void getStructGcPtrsFromOp(GenTree* op, BYTE* gcPtrsOut);
8833 #endif // FEATURE_MULTIREG_ARGS
8835 // Returns true if the method being compiled returns a value
8836 bool compMethodHasRetVal()
8838 return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
8839 compMethodReturnsMultiRegRetType();
8844 void compDispLocalVars();
8848 //-------------------------- Global Compiler Data ------------------------------------
8851 static unsigned s_compMethodsCount; // to produce unique label names
8852 unsigned compGenTreeID;
8853 unsigned compBasicBlockID;
8856 BasicBlock* compCurBB; // the current basic block in process
8857 GenTree* compCurStmt; // the current statement in process
8859 unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
8862 // The following is used to create the 'method JIT info' block.
8863 size_t compInfoBlkSize;
8864 BYTE* compInfoBlkAddr;
8866 EHblkDsc* compHndBBtab; // array of EH data
8867 unsigned compHndBBtabCount; // element count of used elements in EH data array
8868 unsigned compHndBBtabAllocCount; // element count of allocated elements in EH data array
8870 #if defined(_TARGET_X86_)
8872 //-------------------------------------------------------------------------
8873 // Tracking of region covered by the monitor in synchronized methods
8874 void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
8875 void* syncEndEmitCookie; // the emitter cookie for first instruction after the call to MON_EXIT
8877 #endif // !_TARGET_X86_
8879 Phases previousCompletedPhase; // the most recently completed phase
8881 //-------------------------------------------------------------------------
8882 // The following keeps track of how many bytes of local frame space we've
8883 // grabbed so far in the current function, and how many argument bytes we
8884 // need to pop when we return.
8887 unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
8889 // Count of callee-saved regs we pushed in the prolog.
8890 // Does not include EBP for isFramePointerUsed() and double-aligned frames.
8891 // In case of Amd64 this doesn't include float regs saved on stack.
8892 unsigned compCalleeRegsPushed;
8894 #if defined(_TARGET_XARCH_)
8895 // Mask of callee saved float regs on stack.
8896 regMaskTP compCalleeFPRegsSavedMask;
8898 #ifdef _TARGET_AMD64_
8899 // Quirk for VS debug-launch scenario to work:
8900 // Bytes of padding between save-reg area and locals.
8901 #define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
8902 unsigned compVSQuirkStackPaddingNeeded;
8903 bool compQuirkForPPPflag;
8906 unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
8908 unsigned compMapILargNum(unsigned ILargNum); // map accounting for hidden args
8909 unsigned compMapILvarNum(unsigned ILvarNum); // map accounting for hidden args
8910 unsigned compMap2ILvarNum(unsigned varNum); // map accounting for hidden args
8912 //-------------------------------------------------------------------------
8914 static void compStartup(); // One-time initialization
8915 static void compShutdown(); // One-time finalization
8917 void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8920 static void compDisplayStaticSizes(FILE* fout);
8922 //------------ Some utility functions --------------
8924 void* compGetHelperFtn(CorInfoHelpFunc ftnNum, /* IN */
8925 void** ppIndirection); /* OUT */
8927 // Several JIT/EE interface functions return a CorInfoType, and also return a
8928 // class handle as an out parameter if the type is a value class. Returns the
8929 // size of the type these describe.
8930 unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);
8933 // Components used by the compiler may write unit test suites, and
8934 // have them run within this method. They will be run only once per process, and only
8935 // in debug. (Perhaps should be under the control of a COMPlus_ flag.)
8936 // These should fail by asserting.
8937 void compDoComponentUnitTestsOnce();
8940 int compCompile(CORINFO_METHOD_HANDLE methodHnd,
8941 CORINFO_MODULE_HANDLE classPtr,
8942 COMP_HANDLE compHnd,
8943 CORINFO_METHOD_INFO* methodInfo,
8944 void** methodCodePtr,
8945 ULONG* methodCodeSize,
8946 JitFlags* compileFlags);
8947 void compCompileFinish();
8948 int compCompileHelper(CORINFO_MODULE_HANDLE classPtr,
8949 COMP_HANDLE compHnd,
8950 CORINFO_METHOD_INFO* methodInfo,
8951 void** methodCodePtr,
8952 ULONG* methodCodeSize,
8953 JitFlags* compileFlags,
8954 CorInfoInstantiationVerification instVerInfo);
8956 ArenaAllocator* compGetArenaAllocator();
8958 #if MEASURE_MEM_ALLOC
8959 static bool s_dspMemStats; // Display per-phase memory statistics for every function
8960 #endif // MEASURE_MEM_ALLOC
8962 #if LOOP_HOIST_STATS
8963 unsigned m_loopsConsidered;
8964 bool m_curLoopHasHoistedExpression;
8965 unsigned m_loopsWithHoistedExpressions;
8966 unsigned m_totalHoistedExpressions;
8968 void AddLoopHoistStats();
8969 void PrintPerMethodLoopHoistStats();
8971 static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
8972 static unsigned s_loopsConsidered;
8973 static unsigned s_loopsWithHoistedExpressions;
8974 static unsigned s_totalHoistedExpressions;
8976 static void PrintAggregateLoopHoistStats(FILE* f);
8977 #endif // LOOP_HOIST_STATS
8979 bool compIsForImportOnly();
8980 bool compIsForInlining();
8981 bool compDonotInline();
8984 unsigned char compGetJitDefaultFill(); // Get the default fill char value
8985 // we randomize this value when JitStress is enabled
8987 const char* compLocalVarName(unsigned varNum, unsigned offs);
8988 VarName compVarName(regNumber reg, bool isFloatReg = false);
8989 const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);
8990 const char* compRegNameForSize(regNumber reg, size_t size);
8991 const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
8992 void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
8993 void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
8996 //-------------------------------------------------------------------------
8998 struct VarScopeListNode
9001 VarScopeListNode* next;
9002 static VarScopeListNode* Create(VarScopeDsc* value, CompAllocator alloc)
9004 VarScopeListNode* node = new (alloc) VarScopeListNode;
9006 node->next = nullptr;
9011 struct VarScopeMapInfo
9013 VarScopeListNode* head;
9014 VarScopeListNode* tail;
9015 static VarScopeMapInfo* Create(VarScopeListNode* node, CompAllocator alloc)
9017 VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
9024 // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
9025 static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;
9027 typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*> VarNumToScopeDscMap;
9029 // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
9030 VarNumToScopeDscMap* compVarScopeMap;
9032 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
9034 VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
9036 VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
9038 void compInitVarScopeMap();
9040 VarScopeDsc** compEnterScopeList; // List has the offsets where variables
9041 // enter scope, sorted by instr offset
9042 unsigned compNextEnterScope;
9044 VarScopeDsc** compExitScopeList; // List has the offsets where variables
9045 // go out of scope, sorted by instr offset
9046 unsigned compNextExitScope;
9048 void compInitScopeLists();
9050 void compResetScopeLists();
9052 VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
9054 VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
9056 void compProcessScopesUntil(unsigned offset,
9058 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
9059 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
9062 void compDispScopeLists();
9065 bool compIsProfilerHookNeeded();
9067 //-------------------------------------------------------------------------
9068 /* Statistical Data Gathering */
9070 void compJitStats(); // call this function and enable
9071 // various ifdef's below for statistical data
9074 void compCallArgStats();
9075 static void compDispCallArgStats(FILE* fout);
9078 //-------------------------------------------------------------------------
9085 ArenaAllocator* compArenaAllocator;
9088 void compFunctionTraceStart();
9089 void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
9092 size_t compMaxUncheckedOffsetForNullObject;
9094 void compInitOptions(JitFlags* compileFlags);
9096 void compSetProcessor();
9097 void compInitDebuggingInfo();
9098 void compSetOptimizationLevel();
9099 #ifdef _TARGET_ARMARCH_
9100 bool compRsvdRegCheck(FrameLayoutState curState);
9102 void compCompile(void** methodCodePtr, ULONG* methodCodeSize, JitFlags* compileFlags);
9104 // Clear annotations produced during optimizations; to be used between iterations when repeating opts.
9105 void ResetOptAnnotations();
9107 // Regenerate loop descriptors; to be used between iterations when repeating opts.
9108 void RecomputeLoopInfo();
9110 #ifdef PROFILING_SUPPORTED
9111 // Data required for generating profiler Enter/Leave/TailCall hooks
9113 bool compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
9114 void* compProfilerMethHnd; // Profiler handle of the method being compiled. Passed as param to ELT callbacks
9115 bool compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
9118 #ifdef _TARGET_AMD64_
9119 bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
9122 // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
9123 static void ProcessShutdownWork(ICorStaticInfo* statInfo);
9125 CompAllocator getAllocator(CompMemKind cmk = CMK_Generic)
9127 return CompAllocator(compArenaAllocator, cmk);
9130 CompAllocator getAllocatorGC()
9132 return getAllocator(CMK_GC);
9135 CompAllocator getAllocatorLoopHoist()
9137 return getAllocator(CMK_LoopHoist);
9141 CompAllocator getAllocatorDebugOnly()
9143 return getAllocator(CMK_DebugOnly);
9148 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9149 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9153 XX Checks for type compatibility and merges types XX
9155 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9156 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9160 // Set to TRUE if verification cannot be skipped for this method
9161 // If we detect unverifiable code, we will lazily check
9162 // canSkipMethodVerification() to see if verification is REALLY needed.
9163 BOOL tiVerificationNeeded;
9165 // It it initially TRUE, and it gets set to FALSE if we run into unverifiable code
9166 // Note that this is valid only if tiVerificationNeeded was ever TRUE.
9167 BOOL tiIsVerifiableCode;
9169 // Set to TRUE if runtime callout is needed for this method
9170 BOOL tiRuntimeCalloutNeeded;
9172 // Set to TRUE if security prolog/epilog callout is needed for this method
9173 // Note: This flag is different than compNeedSecurityCheck.
9174 // compNeedSecurityCheck means whether or not a security object needs
9175 // to be allocated on the stack, which is currently true for EnC as well.
9176 // tiSecurityCalloutNeeded means whether or not security callouts need
9177 // to be inserted in the jitted code.
9178 BOOL tiSecurityCalloutNeeded;
9180 // Returns TRUE if child is equal to or a subtype of parent for merge purposes
9181 // This support is necessary to suport attributes that are not described in
9182 // for example, signatures. For example, the permanent home byref (byref that
9183 // points to the gc heap), isn't a property of method signatures, therefore,
9184 // it is safe to have mismatches here (that tiCompatibleWith will not flag),
9185 // but when deciding if we need to reimport a block, we need to take these
9187 BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9189 // Returns TRUE if child is equal to or a subtype of parent.
9190 // normalisedForStack indicates that both types are normalised for the stack
9191 BOOL tiCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9193 // Merges pDest and pSrc. Returns FALSE if merge is undefined.
9194 // *pDest is modified to represent the merged type. Sets "*changed" to true
9195 // if this changes "*pDest".
9196 BOOL tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const;
9199 // <BUGNUM> VSW 471305
9200 // IJW allows assigning REF to BYREF. The following allows us to temporarily
9201 // bypass the assert check in gcMarkRegSetGCref and gcMarkRegSetByref
9202 // We use a "short" as we need to push/pop this scope.
9204 short compRegSetCheckLevel;
9208 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9209 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9211 XX IL verification stuff XX
9214 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9215 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9219 // The following is used to track liveness of local variables, initialization
9220 // of valueclass constructors, and type safe use of IL instructions.
9222 // dynamic state info needed for verification
9223 EntryState verCurrentState;
9225 // this ptr of object type .ctors are considered intited only after
9226 // the base class ctor is called, or an alternate ctor is called.
9227 // An uninited this ptr can be used to access fields, but cannot
9228 // be used to call a member function.
9229 BOOL verTrackObjCtorInitState;
9231 void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
9233 // Requires that "tis" is not TIS_Bottom -- it's a definite init/uninit state.
9234 void verSetThisInit(BasicBlock* block, ThisInitState tis);
9235 void verInitCurrentState();
9236 void verResetCurrentState(BasicBlock* block, EntryState* currentState);
9238 // Merges the current verification state into the entry state of "block", return FALSE if that merge fails,
9239 // TRUE if it succeeds. Further sets "*changed" to true if this changes the entry state of "block".
9240 BOOL verMergeEntryStates(BasicBlock* block, bool* changed);
9242 void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
9243 void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
9244 typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd,
9245 bool bashStructToRef = false); // converts from jit type representation to typeInfo
9246 typeInfo verMakeTypeInfo(CorInfoType ciType,
9247 CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
9248 BOOL verIsSDArray(typeInfo ti);
9249 typeInfo verGetArrayElemType(typeInfo ti);
9251 typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
9252 BOOL verNeedsVerification();
9253 BOOL verIsByRefLike(const typeInfo& ti);
9254 BOOL verIsSafeToReturnByRef(const typeInfo& ti);
9256 // generic type variables range over types that satisfy IsBoxable
9257 BOOL verIsBoxable(const typeInfo& ti);
9259 void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
9260 DEBUGARG(unsigned line));
9261 void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
9262 DEBUGARG(unsigned line));
9263 bool verCheckTailCallConstraint(OPCODE opcode,
9264 CORINFO_RESOLVED_TOKEN* pResolvedToken,
9265 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call
9266 // on a type parameter?
9267 bool speculative // If true, won't throw if verificatoin fails. Instead it will
9268 // return false to the caller.
9269 // If false, it will throw.
9271 bool verIsBoxedValueType(typeInfo ti);
9273 void verVerifyCall(OPCODE opcode,
9274 CORINFO_RESOLVED_TOKEN* pResolvedToken,
9275 CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
9277 bool readonlyCall, // is this a "readonly." call?
9278 const BYTE* delegateCreateStart,
9279 const BYTE* codeAddr,
9280 CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName));
9282 BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
9284 typeInfo verVerifySTIND(const typeInfo& ptr, const typeInfo& value, const typeInfo& instrType);
9285 typeInfo verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType);
9286 void verVerifyField(CORINFO_RESOLVED_TOKEN* pResolvedToken,
9287 const CORINFO_FIELD_INFO& fieldInfo,
9288 const typeInfo* tiThis,
9290 BOOL allowPlainStructAsThis = FALSE);
9291 void verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode);
9292 void verVerifyThisPtrInitialised();
9293 BOOL verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target);
9297 // One line log function. Default level is 0. Increasing it gives you
9298 // more log information
9300 // levels are currently unused: #define JITDUMP(level,...) ();
9301 void JitLogEE(unsigned level, const char* fmt, ...);
9303 bool compDebugBreak;
9305 bool compJitHaltMethod();
9310 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9311 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9313 XX GS Security checks for unsafe buffers XX
9315 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9316 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9319 struct ShadowParamVarInfo
9321 FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
9322 unsigned shadowCopy; // Lcl var num, valid only if not set to NO_SHADOW_COPY
9324 static bool mayNeedShadowCopy(LclVarDsc* varDsc)
9326 #if defined(_TARGET_AMD64_)
9327 // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
9328 // slots and update all trees to refer to shadow slots is done immediately after
9329 // fgMorph(). Lsra could potentially mark a param as DoNotEnregister after JIT determines
9330 // not to shadow a parameter. Also, LSRA could potentially spill a param which is passed
9331 // in register. Therefore, conservatively all params may need a shadow copy. Note that
9332 // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
9333 // creating a shadow slot even though this routine returns true.
9335 // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
9336 // required. There are two cases under which a reg arg could potentially be used from its
9338 // a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
9339 // b) LSRA spills it
9341 // Possible solution to address case (a)
9342 // - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
9343 // in this routine. Note that live out of exception handler is something we may not be
9344 // able to do it here since GS cookie logic is invoked ahead of liveness computation.
9345 // Therefore, for methods with exception handling and need GS cookie check we might have
9346 // to take conservative approach.
9348 // Possible solution to address case (b)
9349 // - Whenver a parameter passed in an argument register needs to be spilled by LSRA, we
9350 // create a new spill temp if the method needs GS cookie check.
9351 return varDsc->lvIsParam;
9352 #else // !defined(_TARGET_AMD64_)
9353 return varDsc->lvIsParam && !varDsc->lvIsRegArg;
9360 printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
9365 GSCookie* gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
9366 GSCookie gsGlobalSecurityCookieVal; // Value of global cookie if addr is NULL
9367 ShadowParamVarInfo* gsShadowVarInfo; // Table used by shadow param analysis code
9369 void gsGSChecksInitCookie(); // Grabs cookie variable
9370 void gsCopyShadowParams(); // Identify vulnerable params and create dhadow copies
9371 bool gsFindVulnerableParams(); // Shadow param analysis code
9372 void gsParamsToShadows(); // Insert copy code and replave param uses by shadow
9374 static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
9375 static fgWalkPreFn gsReplaceShadowParams; // Shadow param replacement tree-walk
9377 #define DEFAULT_MAX_INLINE_SIZE 100 // Methods with > DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
9378 // This can be overwritten by setting complus_JITInlineSize env variable.
9380 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
9382 #define DEFAULT_MAX_LOCALLOC_TO_LOCAL_SIZE 32 // fixed locallocs of this size or smaller will convert to local buffers
9385 #ifdef FEATURE_JIT_METHOD_PERF
9386 JitTimer* pCompJitTimer; // Timer data structure (by phases) for current compilation.
9387 static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.
9389 static LPCWSTR JitTimeLogCsv(); // Retrieve the file name for CSV from ConfigDWORD.
9390 static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
9392 inline void EndPhase(Phases phase); // Indicate the end of the given phase.
9394 #if MEASURE_CLRAPI_CALLS
9395 // Thin wrappers that call into JitTimer (if present).
9396 inline void CLRApiCallEnter(unsigned apix);
9397 inline void CLRApiCallLeave(unsigned apix);
9400 inline void CLR_API_Enter(API_ICorJitInfo_Names ename);
9401 inline void CLR_API_Leave(API_ICorJitInfo_Names ename);
9406 #if defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9407 // These variables are associated with maintaining SQM data about compile time.
9408 unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
9409 // in the current compilation.
9410 unsigned __int64 m_compCycles; // Net cycle count for current compilation
9411 DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
9412 // the inlining phase in the current compilation.
9413 #endif // defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9415 // Records the SQM-relevant (cycles and tick count). Should be called after inlining is complete.
9416 // (We do this after inlining because this marks the last point at which the JIT is likely to cause
9417 // type-loading and class initialization).
9418 void RecordStateAtEndOfInlining();
9419 // Assumes being called at the end of compilation. Update the SQM state.
9420 void RecordStateAtEndOfCompilation();
9422 #ifdef FEATURE_CLRSQM
9423 // Does anything SQM related necessary at process shutdown time.
9424 static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
9425 #endif // FEATURE_CLRSQM
9428 #if FUNC_INFO_LOGGING
9429 static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
9430 // filename to write it to.
9431 static FILE* compJitFuncInfoFile; // And this is the actual FILE* to write to.
9432 #endif // FUNC_INFO_LOGGING
9434 Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
9436 // Is the compilation in a full trust context?
9437 bool compIsFullTrust();
9440 void RecordNowayAssert(const char* filename, unsigned line, const char* condStr);
9441 #endif // MEASURE_NOWAY
9443 #ifndef FEATURE_TRACELOGGING
9444 // Should we actually fire the noway assert body and the exception handler?
9445 bool compShouldThrowOnNoway();
9446 #else // FEATURE_TRACELOGGING
9447 // Should we actually fire the noway assert body and the exception handler?
9448 bool compShouldThrowOnNoway(const char* filename, unsigned line);
9450 // Telemetry instance to use per method compilation.
9451 JitTelemetry compJitTelemetry;
9453 // Get common parameters that have to be logged with most telemetry data.
9454 void compGetTelemetryDefaults(const char** assemblyName,
9455 const char** scopeName,
9456 const char** methodName,
9457 unsigned* methodHash);
9458 #endif // !FEATURE_TRACELOGGING
9462 NodeToTestDataMap* m_nodeTestData;
9464 static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
9465 unsigned m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
9466 // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
9467 // Current kept in this.
9469 NodeToTestDataMap* GetNodeTestData()
9471 Compiler* compRoot = impInlineRoot();
9472 if (compRoot->m_nodeTestData == nullptr)
9474 compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
9476 return compRoot->m_nodeTestData;
9479 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, int> NodeToIntMap;
9481 // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
9482 // currently occur in the AST graph.
9483 NodeToIntMap* FindReachableNodesInNodeTestData();
9485 // Node "from" is being eliminated, and being replaced by node "to". If "from" had any associated
9486 // test data, associate that data with "to".
9487 void TransferTestDataToNode(GenTree* from, GenTree* to);
9489 // Requires that "to" is a clone of "from". If any nodes in the "from" tree
9490 // have annotations, attach similar annotations to the corresponding nodes in "to".
9491 void CopyTestDataToCloneTree(GenTree* from, GenTree* to);
9493 // These are the methods that test that the various conditions implied by the
9494 // test attributes are satisfied.
9495 void JitTestCheckSSA(); // SSA builder tests.
9496 void JitTestCheckVN(); // Value numbering tests.
9499 // The "FieldSeqStore", for canonicalizing field sequences. See the definition of FieldSeqStore for
9501 FieldSeqStore* m_fieldSeqStore;
9503 FieldSeqStore* GetFieldSeqStore()
9505 Compiler* compRoot = impInlineRoot();
9506 if (compRoot->m_fieldSeqStore == nullptr)
9508 // Create a CompAllocator that labels sub-structure with CMK_FieldSeqStore, and use that for allocation.
9509 CompAllocator ialloc(getAllocator(CMK_FieldSeqStore));
9510 compRoot->m_fieldSeqStore = new (ialloc) FieldSeqStore(ialloc);
9512 return compRoot->m_fieldSeqStore;
9515 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, FieldSeqNode*> NodeToFieldSeqMap;
9517 // Some nodes of "TYP_BYREF" or "TYP_I_IMPL" actually represent the address of a field within a struct, but since
9518 // the offset of the field is zero, there's no "GT_ADD" node. We normally attach a field sequence to the constant
9519 // that is added, but what do we do when that constant is zero, and is thus not present? We use this mechanism to
9520 // attach the field sequence directly to the address node.
9521 NodeToFieldSeqMap* m_zeroOffsetFieldMap;
9523 NodeToFieldSeqMap* GetZeroOffsetFieldMap()
9525 // Don't need to worry about inlining here
9526 if (m_zeroOffsetFieldMap == nullptr)
9528 // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
9530 CompAllocator ialloc(getAllocator(CMK_ZeroOffsetFieldMap));
9531 m_zeroOffsetFieldMap = new (ialloc) NodeToFieldSeqMap(ialloc);
9533 return m_zeroOffsetFieldMap;
9536 // Requires that "op1" is a node of type "TYP_BYREF" or "TYP_I_IMPL". We are dereferencing this with the fields in
9537 // "fieldSeq", whose offsets are required all to be zero. Ensures that any field sequence annotation currently on
9538 // "op1" or its components is augmented by appending "fieldSeq". In practice, if "op1" is a GT_LCL_FLD, it has
9539 // a field sequence as a member; otherwise, it may be the addition of an a byref and a constant, where the const
9540 // has a field sequence -- in this case "fieldSeq" is appended to that of the constant; otherwise, we
9541 // record the the field sequence using the ZeroOffsetFieldMap described above.
9543 // One exception above is that "op1" is a node of type "TYP_REF" where "op1" is a GT_LCL_VAR.
9544 // This happens when System.Object vtable pointer is a regular field at offset 0 in System.Private.CoreLib in
9545 // CoreRT. Such case is handled same as the default case.
9546 void fgAddFieldSeqForZeroOffset(GenTree* op1, FieldSeqNode* fieldSeq);
9548 typedef JitHashTable<const GenTree*, JitPtrKeyFuncs<GenTree>, ArrayInfo> NodeToArrayInfoMap;
9549 NodeToArrayInfoMap* m_arrayInfoMap;
9551 NodeToArrayInfoMap* GetArrayInfoMap()
9553 Compiler* compRoot = impInlineRoot();
9554 if (compRoot->m_arrayInfoMap == nullptr)
9556 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9557 CompAllocator ialloc(getAllocator(CMK_ArrayInfoMap));
9558 compRoot->m_arrayInfoMap = new (ialloc) NodeToArrayInfoMap(ialloc);
9560 return compRoot->m_arrayInfoMap;
9563 //-----------------------------------------------------------------------------------------------------------------
9564 // Compiler::TryGetArrayInfo:
9565 // Given an indirection node, checks to see whether or not that indirection represents an array access, and
9566 // if so returns information about the array.
9569 // indir - The `GT_IND` node.
9570 // arrayInfo (out) - Information about the accessed array if this function returns true. Undefined otherwise.
9573 // True if the `GT_IND` node represents an array access; false otherwise.
9574 bool TryGetArrayInfo(GenTreeIndir* indir, ArrayInfo* arrayInfo)
9576 if ((indir->gtFlags & GTF_IND_ARR_INDEX) == 0)
9581 if (indir->gtOp1->OperIs(GT_INDEX_ADDR))
9583 GenTreeIndexAddr* const indexAddr = indir->gtOp1->AsIndexAddr();
9584 *arrayInfo = ArrayInfo(indexAddr->gtElemType, indexAddr->gtElemSize, indexAddr->gtElemOffset,
9585 indexAddr->gtStructElemClass);
9589 bool found = GetArrayInfoMap()->Lookup(indir, arrayInfo);
9594 NodeToUnsignedMap* m_memorySsaMap[MemoryKindCount];
9596 // In some cases, we want to assign intermediate SSA #'s to memory states, and know what nodes create those memory
9597 // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the memory
9598 // state, all the possible memory states are possible initial states of the corresponding catch block(s).)
9599 NodeToUnsignedMap* GetMemorySsaMap(MemoryKind memoryKind)
9601 if (memoryKind == GcHeap && byrefStatesMatchGcHeapStates)
9603 // Use the same map for GCHeap and ByrefExposed when their states match.
9604 memoryKind = ByrefExposed;
9607 assert(memoryKind < MemoryKindCount);
9608 Compiler* compRoot = impInlineRoot();
9609 if (compRoot->m_memorySsaMap[memoryKind] == nullptr)
9611 // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9612 CompAllocator ialloc(getAllocator(CMK_ArrayInfoMap));
9613 compRoot->m_memorySsaMap[memoryKind] = new (ialloc) NodeToUnsignedMap(ialloc);
9615 return compRoot->m_memorySsaMap[memoryKind];
9618 // The Refany type is the only struct type whose structure is implicitly assumed by IL. We need its fields.
9619 CORINFO_CLASS_HANDLE m_refAnyClass;
9620 CORINFO_FIELD_HANDLE GetRefanyDataField()
9622 if (m_refAnyClass == nullptr)
9624 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9626 return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
9628 CORINFO_FIELD_HANDLE GetRefanyTypeField()
9630 if (m_refAnyClass == nullptr)
9632 m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9634 return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
9638 static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
9640 #if ALLVARSET_COUNTOPS
9641 static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
9644 static HelperCallProperties s_helperCallProperties;
9646 #ifdef UNIX_AMD64_ABI
9647 static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
9648 static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9651 static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9654 unsigned __int8* offset0,
9655 unsigned __int8* offset1);
9657 void GetStructTypeOffset(CORINFO_CLASS_HANDLE typeHnd,
9660 unsigned __int8* offset0,
9661 unsigned __int8* offset1);
9663 #endif // defined(UNIX_AMD64_ABI)
9665 void fgMorphMultiregStructArgs(GenTreeCall* call);
9666 GenTree* fgMorphMultiregStructArg(GenTree* arg, fgArgTabEntry* fgEntryPtr);
9668 bool killGCRefs(GenTree* tree);
9670 }; // end of class Compiler
9672 //---------------------------------------------------------------------------------------------------------------------
9673 // GenTreeVisitor: a flexible tree walker implemented using the curiosly-recurring-template pattern.
9675 // This class implements a configurable walker for IR trees. There are five configuration options (defaults values are
9676 // shown in parentheses):
9678 // - ComputeStack (false): when true, the walker will push each node onto the `m_ancestors` stack. "Ancestors" is a bit
9679 // of a misnomer, as the first entry will always be the current node.
9681 // - DoPreOrder (false): when true, the walker will invoke `TVisitor::PreOrderVisit` with the current node as an
9682 // argument before visiting the node's operands.
9684 // - DoPostOrder (false): when true, the walker will invoke `TVisitor::PostOrderVisit` with the current node as an
9685 // argument after visiting the node's operands.
9687 // - DoLclVarsOnly (false): when true, the walker will only invoke `TVisitor::PreOrderVisit` for lclVar nodes.
9688 // `DoPreOrder` must be true if this option is true.
9690 // - UseExecutionOrder (false): when true, then walker will visit a node's operands in execution order (e.g. if a
9691 // binary operator has the `GTF_REVERSE_OPS` flag set, the second operand will be
9692 // visited before the first).
9694 // At least one of `DoPreOrder` and `DoPostOrder` must be specified.
9696 // A simple pre-order visitor might look something like the following:
9698 // class CountingVisitor final : public GenTreeVisitor<CountingVisitor>
9703 // DoPreOrder = true
9706 // unsigned m_count;
9708 // CountingVisitor(Compiler* compiler)
9709 // : GenTreeVisitor<CountingVisitor>(compiler), m_count(0)
9713 // Compiler::fgWalkResult PreOrderVisit(GenTree* node)
9719 // This visitor would then be used like so:
9721 // CountingVisitor countingVisitor(compiler);
9722 // countingVisitor.WalkTree(root);
9724 template <typename TVisitor>
9725 class GenTreeVisitor
9728 typedef Compiler::fgWalkResult fgWalkResult;
9732 ComputeStack = false,
9734 DoPostOrder = false,
9735 DoLclVarsOnly = false,
9736 UseExecutionOrder = false,
9739 Compiler* m_compiler;
9740 ArrayStack<GenTree*> m_ancestors;
9742 GenTreeVisitor(Compiler* compiler) : m_compiler(compiler), m_ancestors(compiler->getAllocator(CMK_ArrayStack))
9744 assert(compiler != nullptr);
9746 static_assert_no_msg(TVisitor::DoPreOrder || TVisitor::DoPostOrder);
9747 static_assert_no_msg(!TVisitor::DoLclVarsOnly || TVisitor::DoPreOrder);
9750 fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
9752 return fgWalkResult::WALK_CONTINUE;
9755 fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
9757 return fgWalkResult::WALK_CONTINUE;
9761 fgWalkResult WalkTree(GenTree** use, GenTree* user)
9763 assert(use != nullptr);
9765 GenTree* node = *use;
9767 if (TVisitor::ComputeStack)
9769 m_ancestors.Push(node);
9772 fgWalkResult result = fgWalkResult::WALK_CONTINUE;
9773 if (TVisitor::DoPreOrder && !TVisitor::DoLclVarsOnly)
9775 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9776 if (result == fgWalkResult::WALK_ABORT)
9782 if ((node == nullptr) || (result == fgWalkResult::WALK_SKIP_SUBTREES))
9788 switch (node->OperGet())
9793 case GT_LCL_VAR_ADDR:
9794 case GT_LCL_FLD_ADDR:
9795 if (TVisitor::DoLclVarsOnly)
9797 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9798 if (result == fgWalkResult::WALK_ABORT)
9814 case GT_MEMORYBARRIER:
9819 case GT_START_NONGC:
9821 #if !FEATURE_EH_FUNCLETS
9823 #endif // !FEATURE_EH_FUNCLETS
9827 case GT_CLS_VAR_ADDR:
9831 case GT_PINVOKE_PROLOG:
9832 case GT_PINVOKE_EPILOG:
9836 // Lclvar unary operators
9837 case GT_STORE_LCL_VAR:
9838 case GT_STORE_LCL_FLD:
9839 if (TVisitor::DoLclVarsOnly)
9841 result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9842 if (result == fgWalkResult::WALK_ABORT)
9849 // Standard unary operators
9878 case GT_RUNTIMELOOKUP:
9880 GenTreeUnOp* const unOp = node->AsUnOp();
9881 if (unOp->gtOp1 != nullptr)
9883 result = WalkTree(&unOp->gtOp1, unOp);
9884 if (result == fgWalkResult::WALK_ABORT)
9895 GenTreeCmpXchg* const cmpXchg = node->AsCmpXchg();
9897 result = WalkTree(&cmpXchg->gtOpLocation, cmpXchg);
9898 if (result == fgWalkResult::WALK_ABORT)
9902 result = WalkTree(&cmpXchg->gtOpValue, cmpXchg);
9903 if (result == fgWalkResult::WALK_ABORT)
9907 result = WalkTree(&cmpXchg->gtOpComparand, cmpXchg);
9908 if (result == fgWalkResult::WALK_ABORT)
9915 case GT_ARR_BOUNDS_CHECK:
9918 #endif // FEATURE_SIMD
9919 #ifdef FEATURE_HW_INTRINSICS
9920 case GT_HW_INTRINSIC_CHK:
9921 #endif // FEATURE_HW_INTRINSICS
9923 GenTreeBoundsChk* const boundsChk = node->AsBoundsChk();
9925 result = WalkTree(&boundsChk->gtIndex, boundsChk);
9926 if (result == fgWalkResult::WALK_ABORT)
9930 result = WalkTree(&boundsChk->gtArrLen, boundsChk);
9931 if (result == fgWalkResult::WALK_ABORT)
9940 GenTreeField* const field = node->AsField();
9942 if (field->gtFldObj != nullptr)
9944 result = WalkTree(&field->gtFldObj, field);
9945 if (result == fgWalkResult::WALK_ABORT)
9955 GenTreeArrElem* const arrElem = node->AsArrElem();
9957 result = WalkTree(&arrElem->gtArrObj, arrElem);
9958 if (result == fgWalkResult::WALK_ABORT)
9963 const unsigned rank = arrElem->gtArrRank;
9964 for (unsigned dim = 0; dim < rank; dim++)
9966 result = WalkTree(&arrElem->gtArrInds[dim], arrElem);
9967 if (result == fgWalkResult::WALK_ABORT)
9977 GenTreeArrOffs* const arrOffs = node->AsArrOffs();
9979 result = WalkTree(&arrOffs->gtOffset, arrOffs);
9980 if (result == fgWalkResult::WALK_ABORT)
9984 result = WalkTree(&arrOffs->gtIndex, arrOffs);
9985 if (result == fgWalkResult::WALK_ABORT)
9989 result = WalkTree(&arrOffs->gtArrObj, arrOffs);
9990 if (result == fgWalkResult::WALK_ABORT)
9999 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
10001 GenTree** op1Use = &dynBlock->gtOp1;
10002 GenTree** op2Use = &dynBlock->gtDynamicSize;
10004 if (TVisitor::UseExecutionOrder && dynBlock->gtEvalSizeFirst)
10006 std::swap(op1Use, op2Use);
10009 result = WalkTree(op1Use, dynBlock);
10010 if (result == fgWalkResult::WALK_ABORT)
10014 result = WalkTree(op2Use, dynBlock);
10015 if (result == fgWalkResult::WALK_ABORT)
10022 case GT_STORE_DYN_BLK:
10024 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
10026 GenTree** op1Use = &dynBlock->gtOp1;
10027 GenTree** op2Use = &dynBlock->gtOp2;
10028 GenTree** op3Use = &dynBlock->gtDynamicSize;
10030 if (TVisitor::UseExecutionOrder)
10032 if (dynBlock->IsReverseOp())
10034 std::swap(op1Use, op2Use);
10036 if (dynBlock->gtEvalSizeFirst)
10038 std::swap(op3Use, op2Use);
10039 std::swap(op2Use, op1Use);
10043 result = WalkTree(op1Use, dynBlock);
10044 if (result == fgWalkResult::WALK_ABORT)
10048 result = WalkTree(op2Use, dynBlock);
10049 if (result == fgWalkResult::WALK_ABORT)
10053 result = WalkTree(op3Use, dynBlock);
10054 if (result == fgWalkResult::WALK_ABORT)
10063 GenTreeCall* const call = node->AsCall();
10065 if (call->gtCallObjp != nullptr)
10067 result = WalkTree(&call->gtCallObjp, call);
10068 if (result == fgWalkResult::WALK_ABORT)
10074 for (GenTreeArgList* args = call->gtCallArgs; args != nullptr; args = args->Rest())
10076 result = WalkTree(args->pCurrent(), call);
10077 if (result == fgWalkResult::WALK_ABORT)
10083 for (GenTreeArgList* args = call->gtCallLateArgs; args != nullptr; args = args->Rest())
10085 result = WalkTree(args->pCurrent(), call);
10086 if (result == fgWalkResult::WALK_ABORT)
10092 if (call->gtCallType == CT_INDIRECT)
10094 if (call->gtCallCookie != nullptr)
10096 result = WalkTree(&call->gtCallCookie, call);
10097 if (result == fgWalkResult::WALK_ABORT)
10103 result = WalkTree(&call->gtCallAddr, call);
10104 if (result == fgWalkResult::WALK_ABORT)
10110 if (call->gtControlExpr != nullptr)
10112 result = WalkTree(&call->gtControlExpr, call);
10113 if (result == fgWalkResult::WALK_ABORT)
10125 assert(node->OperIsBinary());
10127 GenTreeOp* const op = node->AsOp();
10129 GenTree** op1Use = &op->gtOp1;
10130 GenTree** op2Use = &op->gtOp2;
10132 if (TVisitor::UseExecutionOrder && node->IsReverseOp())
10134 std::swap(op1Use, op2Use);
10137 if (*op1Use != nullptr)
10139 result = WalkTree(op1Use, op);
10140 if (result == fgWalkResult::WALK_ABORT)
10146 if (*op2Use != nullptr)
10148 result = WalkTree(op2Use, op);
10149 if (result == fgWalkResult::WALK_ABORT)
10159 // Finally, visit the current node
10160 if (TVisitor::DoPostOrder)
10162 result = reinterpret_cast<TVisitor*>(this)->PostOrderVisit(use, user);
10165 if (TVisitor::ComputeStack)
10174 template <bool computeStack, bool doPreOrder, bool doPostOrder, bool doLclVarsOnly, bool useExecutionOrder>
10175 class GenericTreeWalker final
10176 : public GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>
10181 ComputeStack = computeStack,
10182 DoPreOrder = doPreOrder,
10183 DoPostOrder = doPostOrder,
10184 DoLclVarsOnly = doLclVarsOnly,
10185 UseExecutionOrder = useExecutionOrder,
10189 Compiler::fgWalkData* m_walkData;
10192 GenericTreeWalker(Compiler::fgWalkData* walkData)
10193 : GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>(
10194 walkData->compiler)
10195 , m_walkData(walkData)
10197 assert(walkData != nullptr);
10201 walkData->parentStack = &this->m_ancestors;
10205 Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
10207 m_walkData->parent = user;
10208 return m_walkData->wtprVisitorFn(use, m_walkData);
10211 Compiler::fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
10213 m_walkData->parent = user;
10214 return m_walkData->wtpoVisitorFn(use, m_walkData);
10219 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10220 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10222 XX Miscellaneous Compiler stuff XX
10224 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10225 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10228 // Values used to mark the types a stack slot is used for
10230 const unsigned TYPE_REF_INT = 0x01; // slot used as a 32-bit int
10231 const unsigned TYPE_REF_LNG = 0x02; // slot used as a 64-bit long
10232 const unsigned TYPE_REF_FLT = 0x04; // slot used as a 32-bit float
10233 const unsigned TYPE_REF_DBL = 0x08; // slot used as a 64-bit float
10234 const unsigned TYPE_REF_PTR = 0x10; // slot used as a 32-bit pointer
10235 const unsigned TYPE_REF_BYR = 0x20; // slot used as a byref pointer
10236 const unsigned TYPE_REF_STC = 0x40; // slot used as a struct
10237 const unsigned TYPE_REF_TYPEMASK = 0x7F; // bits that represent the type
10239 // const unsigned TYPE_REF_ADDR_TAKEN = 0x80; // slots address was taken
10241 /*****************************************************************************
10243 * Variables to keep track of total code amounts.
10248 extern size_t grossVMsize;
10249 extern size_t grossNCsize;
10250 extern size_t totalNCsize;
10252 extern unsigned genMethodICnt;
10253 extern unsigned genMethodNCnt;
10254 extern size_t gcHeaderISize;
10255 extern size_t gcPtrMapISize;
10256 extern size_t gcHeaderNSize;
10257 extern size_t gcPtrMapNSize;
10259 #endif // DISPLAY_SIZES
10261 /*****************************************************************************
10263 * Variables to keep track of basic block counts (more data on 1 BB methods)
10266 #if COUNT_BASIC_BLOCKS
10267 extern Histogram bbCntTable;
10268 extern Histogram bbOneBBSizeTable;
10271 /*****************************************************************************
10273 * Used by optFindNaturalLoops to gather statistical information such as
10274 * - total number of natural loops
10275 * - number of loops with 1, 2, ... exit conditions
10276 * - number of loops that have an iterator (for like)
10277 * - number of loops that have a constant iterator
10282 extern unsigned totalLoopMethods; // counts the total number of methods that have natural loops
10283 extern unsigned maxLoopsPerMethod; // counts the maximum number of loops a method has
10284 extern unsigned totalLoopOverflows; // # of methods that identified more loops than we can represent
10285 extern unsigned totalLoopCount; // counts the total number of natural loops
10286 extern unsigned totalUnnatLoopCount; // counts the total number of (not-necessarily natural) loops
10287 extern unsigned totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
10288 extern unsigned iterLoopCount; // counts the # of loops with an iterator (for like)
10289 extern unsigned simpleTestLoopCount; // counts the # of loops with an iterator and a simple loop condition (iter <
10291 extern unsigned constIterLoopCount; // counts the # of loops with a constant iterator (for like)
10292 extern bool hasMethodLoops; // flag to keep track if we already counted a method as having loops
10293 extern unsigned loopsThisMethod; // counts the number of loops in the current method
10294 extern bool loopOverflowThisMethod; // True if we exceeded the max # of loops in the method.
10295 extern Histogram loopCountTable; // Histogram of loop counts
10296 extern Histogram loopExitCountTable; // Histogram of loop exit counts
10298 #endif // COUNT_LOOPS
10300 /*****************************************************************************
10301 * variables to keep track of how many iterations we go in a dataflow pass
10306 extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
10307 extern unsigned CFiterCount; // counts the # of iteration for the Const Folding dataflow
10309 #endif // DATAFLOW_ITER
10311 #if MEASURE_BLOCK_SIZE
10312 extern size_t genFlowNodeSize;
10313 extern size_t genFlowNodeCnt;
10314 #endif // MEASURE_BLOCK_SIZE
10316 #if MEASURE_NODE_SIZE
10317 struct NodeSizeStats
10321 genTreeNodeCnt = 0;
10322 genTreeNodeSize = 0;
10323 genTreeNodeActualSize = 0;
10326 // Count of tree nodes allocated.
10327 unsigned __int64 genTreeNodeCnt;
10329 // The size we allocate.
10330 unsigned __int64 genTreeNodeSize;
10332 // The actual size of the node. Note that the actual size will likely be smaller
10333 // than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
10334 // a smaller node to a larger one. TODO-Cleanup: add stats on
10335 // SetOper()/ChangeOper() usage to quantify this.
10336 unsigned __int64 genTreeNodeActualSize;
10338 extern NodeSizeStats genNodeSizeStats; // Total node size stats
10339 extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
10340 extern Histogram genTreeNcntHist;
10341 extern Histogram genTreeNsizHist;
10342 #endif // MEASURE_NODE_SIZE
10344 /*****************************************************************************
10345 * Count fatal errors (including noway_asserts).
10349 extern unsigned fatal_badCode;
10350 extern unsigned fatal_noWay;
10351 extern unsigned fatal_NOMEM;
10352 extern unsigned fatal_noWayAssertBody;
10354 extern unsigned fatal_noWayAssertBodyArgs;
10356 extern unsigned fatal_NYI;
10357 #endif // MEASURE_FATAL
10359 /*****************************************************************************
10363 #ifdef _TARGET_XARCH_
10365 const instruction INS_SHIFT_LEFT_LOGICAL = INS_shl;
10366 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
10367 const instruction INS_SHIFT_RIGHT_ARITHM = INS_sar;
10369 const instruction INS_AND = INS_and;
10370 const instruction INS_OR = INS_or;
10371 const instruction INS_XOR = INS_xor;
10372 const instruction INS_NEG = INS_neg;
10373 const instruction INS_TEST = INS_test;
10374 const instruction INS_MUL = INS_imul;
10375 const instruction INS_SIGNED_DIVIDE = INS_idiv;
10376 const instruction INS_UNSIGNED_DIVIDE = INS_div;
10377 const instruction INS_BREAKPOINT = INS_int3;
10378 const instruction INS_ADDC = INS_adc;
10379 const instruction INS_SUBC = INS_sbb;
10380 const instruction INS_NOT = INS_not;
10382 #endif // _TARGET_XARCH_
10384 #ifdef _TARGET_ARM_
10386 const instruction INS_SHIFT_LEFT_LOGICAL = INS_lsl;
10387 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
10388 const instruction INS_SHIFT_RIGHT_ARITHM = INS_asr;
10390 const instruction INS_AND = INS_and;
10391 const instruction INS_OR = INS_orr;
10392 const instruction INS_XOR = INS_eor;
10393 const instruction INS_NEG = INS_rsb;
10394 const instruction INS_TEST = INS_tst;
10395 const instruction INS_MUL = INS_mul;
10396 const instruction INS_MULADD = INS_mla;
10397 const instruction INS_SIGNED_DIVIDE = INS_sdiv;
10398 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
10399 const instruction INS_BREAKPOINT = INS_bkpt;
10400 const instruction INS_ADDC = INS_adc;
10401 const instruction INS_SUBC = INS_sbc;
10402 const instruction INS_NOT = INS_mvn;
10404 const instruction INS_ABS = INS_vabs;
10405 const instruction INS_SQRT = INS_vsqrt;
10407 #endif // _TARGET_ARM_
10409 #ifdef _TARGET_ARM64_
10411 const instruction INS_MULADD = INS_madd;
10412 const instruction INS_BREAKPOINT = INS_bkpt;
10414 const instruction INS_ABS = INS_fabs;
10415 const instruction INS_SQRT = INS_fsqrt;
10417 #endif // _TARGET_ARM64_
10419 /*****************************************************************************/
10421 extern const BYTE genTypeSizes[];
10422 extern const BYTE genTypeAlignments[];
10423 extern const BYTE genTypeStSzs[];
10424 extern const BYTE genActualTypes[];
10426 /*****************************************************************************/
10428 // VERY_LARGE_FRAME_SIZE_REG_MASK is the set of registers we need to use for
10429 // the probing loop generated for very large stack frames (see `getVeryLargeFrameSize`).
10431 #ifdef _TARGET_ARM_
10432 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R4 | RBM_R5 | RBM_R6)
10433 #elif defined(_TARGET_ARM64_)
10434 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R9 | RBM_R10 | RBM_R11)
10437 /*****************************************************************************/
10439 extern BasicBlock dummyBB;
10441 /*****************************************************************************/
10442 /*****************************************************************************/
10444 // foreach_treenode_execution_order: An iterator that iterates through all the tree
10445 // nodes of a statement in execution order.
10446 // __stmt: a GT_STMT type GenTree*
10447 // __node: a GenTree*, already declared, that gets updated with each node in the statement, in execution order
10449 #define foreach_treenode_execution_order(__node, __stmt) \
10450 for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
10452 // foreach_block: An iterator over all blocks in the function.
10453 // __compiler: the Compiler* object
10454 // __block : a BasicBlock*, already declared, that gets updated each iteration.
10456 #define foreach_block(__compiler, __block) \
10457 for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
10459 /*****************************************************************************/
10460 /*****************************************************************************/
10464 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10466 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10467 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10469 XX Debugging helpers XX
10471 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10472 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10475 /*****************************************************************************/
10476 /* The following functions are intended to be called from the debugger, to dump
10477 * various data structures. The can be used in the debugger Watch or Quick Watch
10478 * windows. They are designed to be short to type and take as few arguments as
10479 * possible. The 'c' versions take a Compiler*, whereas the 'd' versions use the TlsCompiler.
10480 * See the function definition comment for more details.
10483 void cBlock(Compiler* comp, BasicBlock* block);
10484 void cBlocks(Compiler* comp);
10485 void cBlocksV(Compiler* comp);
10486 void cTree(Compiler* comp, GenTree* tree);
10487 void cTrees(Compiler* comp);
10488 void cEH(Compiler* comp);
10489 void cVar(Compiler* comp, unsigned lclNum);
10490 void cVarDsc(Compiler* comp, LclVarDsc* varDsc);
10491 void cVars(Compiler* comp);
10492 void cVarsFinal(Compiler* comp);
10493 void cBlockPreds(Compiler* comp, BasicBlock* block);
10494 void cReach(Compiler* comp);
10495 void cDoms(Compiler* comp);
10496 void cLiveness(Compiler* comp);
10497 void cCVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10499 void cFuncIR(Compiler* comp);
10500 void cBlockIR(Compiler* comp, BasicBlock* block);
10501 void cLoopIR(Compiler* comp, Compiler::LoopDsc* loop);
10502 void cTreeIR(Compiler* comp, GenTree* tree);
10503 int cTreeTypeIR(Compiler* comp, GenTree* tree);
10504 int cTreeKindsIR(Compiler* comp, GenTree* tree);
10505 int cTreeFlagsIR(Compiler* comp, GenTree* tree);
10506 int cOperandIR(Compiler* comp, GenTree* operand);
10507 int cLeafIR(Compiler* comp, GenTree* tree);
10508 int cIndirIR(Compiler* comp, GenTree* tree);
10509 int cListIR(Compiler* comp, GenTree* list);
10510 int cSsaNumIR(Compiler* comp, GenTree* tree);
10511 int cValNumIR(Compiler* comp, GenTree* tree);
10512 int cDependsIR(Compiler* comp, GenTree* comma, bool* first);
10514 void dBlock(BasicBlock* block);
10517 void dTree(GenTree* tree);
10520 void dVar(unsigned lclNum);
10521 void dVarDsc(LclVarDsc* varDsc);
10524 void dBlockPreds(BasicBlock* block);
10528 void dCVarSet(VARSET_VALARG_TP vars);
10530 void dRegMask(regMaskTP mask);
10533 void dBlockIR(BasicBlock* block);
10534 void dTreeIR(GenTree* tree);
10535 void dLoopIR(Compiler::LoopDsc* loop);
10536 void dLoopNumIR(unsigned loopNum);
10537 int dTabStopIR(int curr, int tabstop);
10538 int dTreeTypeIR(GenTree* tree);
10539 int dTreeKindsIR(GenTree* tree);
10540 int dTreeFlagsIR(GenTree* tree);
10541 int dOperandIR(GenTree* operand);
10542 int dLeafIR(GenTree* tree);
10543 int dIndirIR(GenTree* tree);
10544 int dListIR(GenTree* list);
10545 int dSsaNumIR(GenTree* tree);
10546 int dValNumIR(GenTree* tree);
10547 int dDependsIR(GenTree* comma);
10550 GenTree* dFindTree(GenTree* tree, unsigned id);
10551 GenTree* dFindTree(unsigned id);
10552 GenTreeStmt* dFindStmt(unsigned id);
10553 BasicBlock* dFindBlock(unsigned bbNum);
10557 #include "compiler.hpp" // All the shared inline functions
10559 /*****************************************************************************/
10560 #endif //_COMPILER_H_
10561 /*****************************************************************************/