Fix reading Time zone rules using Julian days (#17672)
[platform/upstream/coreclr.git] / src / jit / compiler.h
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.
4
5 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7 XX                                                                           XX
8 XX                           Compiler                                        XX
9 XX                                                                           XX
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
15 XX                                                                           XX
16 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
17 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
18 */
19
20 /*****************************************************************************/
21 #ifndef _COMPILER_H_
22 #define _COMPILER_H_
23 /*****************************************************************************/
24
25 #include "jit.h"
26 #include "opcode.h"
27 #include "varset.h"
28 #include "jitstd.h"
29 #include "jithashtable.h"
30 #include "gentree.h"
31 #include "lir.h"
32 #include "block.h"
33 #include "inline.h"
34 #include "jiteh.h"
35 #include "instr.h"
36 #include "regalloc.h"
37 #include "sm.h"
38 #include "cycletimer.h"
39 #include "blockset.h"
40 #include "arraystack.h"
41 #include "hashbv.h"
42 #include "fp.h"
43 #include "jitexpandarray.h"
44 #include "tinyarray.h"
45 #include "valuenum.h"
46 #include "reglist.h"
47 #include "jittelemetry.h"
48 #include "namedintrinsiclist.h"
49 #ifdef LATE_DISASM
50 #include "disasm.h"
51 #endif
52
53 #include "codegeninterface.h"
54 #include "regset.h"
55 #include "jitgcinfo.h"
56
57 #if DUMP_GC_TABLES && defined(JIT32_GCENCODER)
58 #include "gcdump.h"
59 #endif
60
61 #include "emit.h"
62
63 #include "simd.h"
64
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
68
69 /*****************************************************************************
70  *                  Forward declarations
71  */
72
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
79 #if FEATURE_STACK_FP_X87
80 struct FlatFPStateX87; // defined in fp.h
81 #endif
82 #if FEATURE_ANYCSE
83 class CSE_DataFlow; // defined in OptCSE.cpp
84 #endif
85 #ifdef DEBUG
86 struct IndentStack;
87 #endif
88
89 #ifndef LEGACY_BACKEND
90 class Lowering; // defined in lower.h
91 #endif
92
93 // The following are defined in this file, Compiler.h
94
95 class Compiler;
96
97 /*****************************************************************************
98  *                  Unwind info
99  */
100
101 #include "unwind.h"
102
103 /*****************************************************************************/
104
105 //
106 // Declare global operator new overloads that use the Compiler::compGetMem() function for allocation.
107 //
108
109 // I wanted to make the second argument optional, with default = CMK_Unknown, but that
110 // caused these to be ambiguous with the global placement new operators.
111 void* __cdecl operator new(size_t n, Compiler* context, CompMemKind cmk);
112 void* __cdecl operator new[](size_t n, Compiler* context, CompMemKind cmk);
113 void* __cdecl operator new(size_t n, void* p, const jitstd::placement_t& syntax_difference);
114
115 // Requires the definitions of "operator new" so including "LoopCloning.h" after the definitions.
116 #include "loopcloning.h"
117
118 /*****************************************************************************/
119
120 /* This is included here and not earlier as it needs the definition of "CSE"
121  * which is defined in the section above */
122
123 /*****************************************************************************/
124
125 unsigned genLog2(unsigned value);
126 unsigned genLog2(unsigned __int64 value);
127
128 var_types genActualType(var_types type);
129 var_types genUnsignedType(var_types type);
130 var_types genSignedType(var_types type);
131
132 unsigned ReinterpretHexAsDecimal(unsigned);
133
134 /*****************************************************************************/
135
136 #if defined(FEATURE_SIMD)
137 #if defined(_TARGET_XARCH_)
138 const unsigned TEMP_MAX_SIZE = YMM_REGSIZE_BYTES;
139 #elif defined(_TARGET_ARM64_)
140 const unsigned TEMP_MAX_SIZE = FP_REGSIZE_BYTES;
141 #endif // defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
142 #else  // !FEATURE_SIMD
143 const unsigned TEMP_MAX_SIZE = sizeof(double);
144 #endif // !FEATURE_SIMD
145 const unsigned TEMP_SLOT_COUNT = (TEMP_MAX_SIZE / sizeof(int));
146
147 const unsigned FLG_CCTOR = (CORINFO_FLG_CONSTRUCTOR | CORINFO_FLG_STATIC);
148
149 #ifdef DEBUG
150 const int BAD_STK_OFFS = 0xBAADF00D; // for LclVarDsc::lvStkOffs
151 #endif
152
153 // The following holds the Local var info (scope information)
154 typedef const char* VarName; // Actual ASCII string
155 struct VarScopeDsc
156 {
157     IL_OFFSET vsdLifeBeg; // instr offset of beg of life
158     IL_OFFSET vsdLifeEnd; // instr offset of end of life
159     unsigned  vsdVarNum;  // (remapped) LclVarDsc number
160
161 #ifdef DEBUG
162     VarName vsdName; // name of the var
163 #endif
164
165     unsigned vsdLVnum; // 'which' in eeGetLVinfo().
166                        // Also, it is the index of this entry in the info.compVarScopes array,
167                        // which is useful since the array is also accessed via the
168                        // compEnterScopeList and compExitScopeList sorted arrays.
169 };
170
171 /*****************************************************************************
172  *
173  *  The following holds the local variable counts and the descriptor table.
174  */
175
176 // This is the location of a definition.
177 struct DefLoc
178 {
179     BasicBlock* m_blk;
180     GenTree*    m_tree;
181
182     DefLoc() : m_blk(nullptr), m_tree(nullptr)
183     {
184     }
185 };
186
187 // This class encapsulates all info about a local variable that may vary for different SSA names
188 // in the family.
189 class LclSsaVarDsc
190 {
191 public:
192     ValueNumPair m_vnPair;
193     DefLoc       m_defLoc;
194
195     LclSsaVarDsc()
196     {
197     }
198 };
199
200 typedef JitExpandArray<LclSsaVarDsc> PerSsaArray;
201
202 class LclVarDsc
203 {
204 public:
205     // The constructor. Most things can just be zero'ed.
206     LclVarDsc(Compiler* comp);
207
208     // note this only packs because var_types is a typedef of unsigned char
209     var_types lvType : 5; // TYP_INT/LONG/FLOAT/DOUBLE/REF
210
211     unsigned char lvIsParam : 1;           // is this a parameter?
212     unsigned char lvIsRegArg : 1;          // is this a register argument?
213     unsigned char lvFramePointerBased : 1; // 0 = off of REG_SPBASE (e.g., ESP), 1 = off of REG_FPBASE (e.g., EBP)
214
215     unsigned char lvStructGcCount : 3; // if struct, how many GC pointer (stop counting at 7). The only use of values >1
216                                        // is to help determine whether to use block init in the prolog.
217     unsigned char lvOnFrame : 1;       // (part of) the variable lives on the frame
218 #ifdef LEGACY_BACKEND
219     unsigned char lvDependReg : 1; // did the predictor depend upon this being enregistered
220 #endif
221     unsigned char lvRegister : 1; // assigned to live in a register? For RyuJIT backend, this is only set if the
222                                   // variable is in the same register for the entire function.
223     unsigned char lvTracked : 1;  // is this a tracked variable?
224     bool          lvTrackedNonStruct()
225     {
226         return lvTracked && lvType != TYP_STRUCT;
227     }
228     unsigned char lvPinned : 1; // is this a pinned variable?
229
230     unsigned char lvMustInit : 1;    // must be initialized
231     unsigned char lvAddrExposed : 1; // The address of this variable is "exposed" -- passed as an argument, stored in a
232                                      // global location, etc.
233                                      // We cannot reason reliably about the value of the variable.
234     unsigned char lvDoNotEnregister : 1; // Do not enregister this variable.
235     unsigned char lvFieldAccessed : 1;   // The var is a struct local, and a field of the variable is accessed.  Affects
236                                          // struct promotion.
237
238 #ifdef DEBUG
239     // These further document the reasons for setting "lvDoNotEnregister".  (Note that "lvAddrExposed" is one of the
240     // reasons;
241     // also, lvType == TYP_STRUCT prevents enregistration.  At least one of the reasons should be true.
242     unsigned char lvVMNeedsStackAddr : 1; // The VM may have access to a stack-relative address of the variable, and
243                                           // read/write its value.
244     unsigned char lvLiveInOutOfHndlr : 1; // The variable was live in or out of an exception handler, and this required
245                                           // the variable to be
246                                           // in the stack (at least at those boundaries.)
247     unsigned char lvLclFieldExpr : 1;     // The variable is not a struct, but was accessed like one (e.g., reading a
248                                           // particular byte from an int).
249     unsigned char lvLclBlockOpAddr : 1;   // The variable was written to via a block operation that took its address.
250     unsigned char lvLiveAcrossUCall : 1;  // The variable is live across an unmanaged call.
251 #endif
252     unsigned char lvIsCSE : 1; // Indicates if this LclVar is a CSE variable.
253 #ifdef LEGACY_BACKEND
254     unsigned char lvRefAssign : 1; // involved in pointer assignment
255 #endif
256     unsigned char lvHasLdAddrOp : 1; // has ldloca or ldarga opcode on this local.
257     unsigned char lvStackByref : 1;  // This is a compiler temporary of TYP_BYREF that is known to point into our local
258                                      // stack frame.
259
260     unsigned char lvHasILStoreOp : 1;         // there is at least one STLOC or STARG on this local
261     unsigned char lvHasMultipleILStoreOp : 1; // there is more than one STLOC on this local
262
263     unsigned char lvIsTemp : 1; // Short-lifetime compiler temp (if lvIsParam is false), or implicit byref parameter
264                                 // (if lvIsParam is true)
265 #if OPT_BOOL_OPS
266     unsigned char lvIsBoolean : 1; // set if variable is boolean
267 #endif
268 #if ASSERTION_PROP
269     unsigned char lvSingleDef : 1;    // variable has a single def
270     unsigned char lvDisqualify : 1;   // variable is no longer OK for add copy optimization
271     unsigned char lvVolatileHint : 1; // hint for AssertionProp
272 #endif
273
274 #ifdef LEGACY_BACKEND
275     unsigned char lvSpilled : 1; // enregistered variable was spilled
276 #endif
277 #ifndef _TARGET_64BIT_
278     unsigned char lvStructDoubleAlign : 1; // Must we double align this struct?
279 #endif                                     // !_TARGET_64BIT_
280 #ifdef _TARGET_64BIT_
281     unsigned char lvQuirkToLong : 1; // Quirk to allocate this LclVar as a 64-bit long
282 #endif
283 #ifdef DEBUG
284     unsigned char lvKeepType : 1;       // Don't change the type of this variable
285     unsigned char lvNoLclFldStress : 1; // Can't apply local field stress on this one
286 #endif
287     unsigned char lvIsPtr : 1; // Might this be used in an address computation? (used by buffer overflow security
288                                // checks)
289     unsigned char lvIsUnsafeBuffer : 1; // Does this contain an unsafe buffer requiring buffer overflow security checks?
290     unsigned char lvPromoted : 1; // True when this local is a promoted struct, a normed struct, or a "split" long on a
291                                   // 32-bit target.  For implicit byref parameters, this gets hijacked between
292                                   // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to indicate whether
293                                   // references to the arg are being rewritten as references to a promoted shadow local.
294     unsigned char lvIsStructField : 1;     // Is this local var a field of a promoted struct local?
295     unsigned char lvOverlappingFields : 1; // True when we have a struct with possibly overlapping fields
296     unsigned char lvContainsHoles : 1;     // True when we have a promoted struct that contains holes
297     unsigned char lvCustomLayout : 1;      // True when this struct has "CustomLayout"
298
299     unsigned char lvIsMultiRegArg : 1; // true if this is a multireg LclVar struct used in an argument context
300     unsigned char lvIsMultiRegRet : 1; // true if this is a multireg LclVar struct assigned from a multireg call
301
302 #ifdef FEATURE_HFA
303     unsigned char _lvIsHfa : 1;          // Is this a struct variable who's class handle is an HFA type
304     unsigned char _lvIsHfaRegArg : 1;    // Is this a HFA argument variable?    // TODO-CLEANUP: Remove this and replace
305                                          // with (lvIsRegArg && lvIsHfa())
306     unsigned char _lvHfaTypeIsFloat : 1; // Is the HFA type float or double?
307 #endif                                   // FEATURE_HFA
308
309 #ifdef DEBUG
310     // TODO-Cleanup: See the note on lvSize() - this flag is only in use by asserts that are checking for struct
311     // types, and is needed because of cases where TYP_STRUCT is bashed to an integral type.
312     // Consider cleaning this up so this workaround is not required.
313     unsigned char lvUnusedStruct : 1; // All references to this promoted struct are through its field locals.
314                                       // I.e. there is no longer any reference to the struct directly.
315                                       // In this case we can simply remove this struct local.
316 #endif
317 #ifndef LEGACY_BACKEND
318     unsigned char lvLRACandidate : 1; // Tracked for linear scan register allocation purposes
319 #endif                                // !LEGACY_BACKEND
320
321 #ifdef FEATURE_SIMD
322     // Note that both SIMD vector args and locals are marked as lvSIMDType = true, but the
323     // type of an arg node is TYP_BYREF and a local node is TYP_SIMD*.
324     unsigned char lvSIMDType : 1;            // This is a SIMD struct
325     unsigned char lvUsedInSIMDIntrinsic : 1; // This tells lclvar is used for simd intrinsic
326     var_types     lvBaseType : 5;            // Note: this only packs because var_types is a typedef of unsigned char
327 #endif                                       // FEATURE_SIMD
328     unsigned char lvRegStruct : 1;           // This is a reg-sized non-field-addressed struct.
329
330     unsigned char lvClassIsExact : 1; // lvClassHandle is the exact type
331
332 #ifdef DEBUG
333     unsigned char lvClassInfoUpdated : 1; // true if this var has updated class handle or exactness
334 #endif
335
336     union {
337         unsigned lvFieldLclStart; // The index of the local var representing the first field in the promoted struct
338                                   // local.  For implicit byref parameters, this gets hijacked between
339                                   // fgRetypeImplicitByRefArgs and fgMarkDemotedImplicitByRefArgs to point to the
340                                   // struct local created to model the parameter's struct promotion, if any.
341         unsigned lvParentLcl; // The index of the local var representing the parent (i.e. the promoted struct local).
342                               // Valid on promoted struct local fields.
343     };
344
345     unsigned char lvFieldCnt; //  Number of fields in the promoted VarDsc.
346     unsigned char lvFldOffset;
347     unsigned char lvFldOrdinal;
348
349 #if FEATURE_MULTIREG_ARGS
350     regNumber lvRegNumForSlot(unsigned slotNum)
351     {
352         if (slotNum == 0)
353         {
354             return lvArgReg;
355         }
356         else if (slotNum == 1)
357         {
358             return lvOtherArgReg;
359         }
360         else
361         {
362             assert(false && "Invalid slotNum!");
363         }
364
365         unreached();
366     }
367 #endif // FEATURE_MULTIREG_ARGS
368
369     bool lvIsHfa() const
370     {
371 #ifdef FEATURE_HFA
372         return _lvIsHfa;
373 #else
374         return false;
375 #endif
376     }
377
378     void lvSetIsHfa()
379     {
380 #ifdef FEATURE_HFA
381         _lvIsHfa = true;
382 #endif
383     }
384
385     bool lvIsHfaRegArg() const
386     {
387 #ifdef FEATURE_HFA
388         return _lvIsHfaRegArg;
389 #else
390         return false;
391 #endif
392     }
393
394     void lvSetIsHfaRegArg(bool value = true)
395     {
396 #ifdef FEATURE_HFA
397         _lvIsHfaRegArg = value;
398 #endif
399     }
400
401     bool lvHfaTypeIsFloat() const
402     {
403 #ifdef FEATURE_HFA
404         return _lvHfaTypeIsFloat;
405 #else
406         return false;
407 #endif
408     }
409
410     void lvSetHfaTypeIsFloat(bool value)
411     {
412 #ifdef FEATURE_HFA
413         _lvHfaTypeIsFloat = value;
414 #endif
415     }
416
417     // on Arm64 - Returns 1-4 indicating the number of register slots used by the HFA
418     // on Arm32 - Returns the total number of single FP register slots used by the HFA, max is 8
419     //
420     unsigned lvHfaSlots() const
421     {
422         assert(lvIsHfa());
423         assert(varTypeIsStruct(lvType));
424 #ifdef _TARGET_ARM_
425         return lvExactSize / sizeof(float);
426 #else  //  _TARGET_ARM64_
427         if (lvHfaTypeIsFloat())
428         {
429             return lvExactSize / sizeof(float);
430         }
431         else
432         {
433             return lvExactSize / sizeof(double);
434         }
435 #endif //  _TARGET_ARM64_
436     }
437
438     // lvIsMultiRegArgOrRet()
439     //     returns true if this is a multireg LclVar struct used in an argument context
440     //               or if this is a multireg LclVar struct assigned from a multireg call
441     bool lvIsMultiRegArgOrRet()
442     {
443         return lvIsMultiRegArg || lvIsMultiRegRet;
444     }
445
446 private:
447     regNumberSmall _lvRegNum; // Used to store the register this variable is in (or, the low register of a
448                               // register pair). For LEGACY_BACKEND, this is only set if lvRegister is
449                               // non-zero. For non-LEGACY_BACKEND, it is set during codegen any time the
450                               // variable is enregistered (in non-LEGACY_BACKEND, lvRegister is only set
451                               // to non-zero if the variable gets the same register assignment for its entire
452                               // lifetime).
453 #if !defined(_TARGET_64BIT_)
454     regNumberSmall _lvOtherReg; // Used for "upper half" of long var.
455 #endif                          // !defined(_TARGET_64BIT_)
456
457     regNumberSmall _lvArgReg; // The register in which this argument is passed.
458
459 #if FEATURE_MULTIREG_ARGS
460     regNumberSmall _lvOtherArgReg; // Used for the second part of the struct passed in a register.
461                                    // Note this is defined but not used by ARM32
462 #endif                             // FEATURE_MULTIREG_ARGS
463
464 #ifndef LEGACY_BACKEND
465     union {
466         regNumberSmall _lvArgInitReg;     // the register      into which the argument is moved at entry
467         regPairNoSmall _lvArgInitRegPair; // the register pair into which the argument is moved at entry
468     };
469 #endif // !LEGACY_BACKEND
470
471 public:
472     // The register number is stored in a small format (8 bits), but the getters return and the setters take
473     // a full-size (unsigned) format, to localize the casts here.
474
475     /////////////////////
476
477     __declspec(property(get = GetRegNum, put = SetRegNum)) regNumber lvRegNum;
478
479     regNumber GetRegNum() const
480     {
481         return (regNumber)_lvRegNum;
482     }
483
484     void SetRegNum(regNumber reg)
485     {
486         _lvRegNum = (regNumberSmall)reg;
487         assert(_lvRegNum == reg);
488     }
489
490 /////////////////////
491
492 #if defined(_TARGET_64BIT_)
493     __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
494
495     regNumber GetOtherReg() const
496     {
497         assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
498                                        // "unreachable code" warnings
499         return REG_NA;
500     }
501
502     void SetOtherReg(regNumber reg)
503     {
504         assert(!"shouldn't get here"); // can't use "unreached();" because it's NORETURN, which causes C4072
505                                        // "unreachable code" warnings
506     }
507 #else  // !_TARGET_64BIT_
508     __declspec(property(get = GetOtherReg, put = SetOtherReg)) regNumber lvOtherReg;
509
510     regNumber GetOtherReg() const
511     {
512         return (regNumber)_lvOtherReg;
513     }
514
515     void SetOtherReg(regNumber reg)
516     {
517         _lvOtherReg = (regNumberSmall)reg;
518         assert(_lvOtherReg == reg);
519     }
520 #endif // !_TARGET_64BIT_
521
522     /////////////////////
523
524     __declspec(property(get = GetArgReg, put = SetArgReg)) regNumber lvArgReg;
525
526     regNumber GetArgReg() const
527     {
528         return (regNumber)_lvArgReg;
529     }
530
531     void SetArgReg(regNumber reg)
532     {
533         _lvArgReg = (regNumberSmall)reg;
534         assert(_lvArgReg == reg);
535     }
536
537 #if FEATURE_MULTIREG_ARGS
538     __declspec(property(get = GetOtherArgReg, put = SetOtherArgReg)) regNumber lvOtherArgReg;
539
540     regNumber GetOtherArgReg() const
541     {
542         return (regNumber)_lvOtherArgReg;
543     }
544
545     void SetOtherArgReg(regNumber reg)
546     {
547         _lvOtherArgReg = (regNumberSmall)reg;
548         assert(_lvOtherArgReg == reg);
549     }
550 #endif // FEATURE_MULTIREG_ARGS
551
552 #ifdef FEATURE_SIMD
553     // Is this is a SIMD struct?
554     bool lvIsSIMDType() const
555     {
556         return lvSIMDType;
557     }
558
559     // Is this is a SIMD struct which is used for SIMD intrinsic?
560     bool lvIsUsedInSIMDIntrinsic() const
561     {
562         return lvUsedInSIMDIntrinsic;
563     }
564 #else
565     // If feature_simd not enabled, return false
566     bool lvIsSIMDType() const
567     {
568         return false;
569     }
570     bool lvIsUsedInSIMDIntrinsic() const
571     {
572         return false;
573     }
574 #endif
575
576 /////////////////////
577
578 #ifndef LEGACY_BACKEND
579     __declspec(property(get = GetArgInitReg, put = SetArgInitReg)) regNumber lvArgInitReg;
580
581     regNumber GetArgInitReg() const
582     {
583         return (regNumber)_lvArgInitReg;
584     }
585
586     void SetArgInitReg(regNumber reg)
587     {
588         _lvArgInitReg = (regNumberSmall)reg;
589         assert(_lvArgInitReg == reg);
590     }
591
592     /////////////////////
593
594     __declspec(property(get = GetArgInitRegPair, put = SetArgInitRegPair)) regPairNo lvArgInitRegPair;
595
596     regPairNo GetArgInitRegPair() const
597     {
598         regPairNo regPair = (regPairNo)_lvArgInitRegPair;
599         assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
600         return regPair;
601     }
602
603     void SetArgInitRegPair(regPairNo regPair)
604     {
605         assert(regPair >= REG_PAIR_FIRST && regPair <= REG_PAIR_LAST);
606         _lvArgInitRegPair = (regPairNoSmall)regPair;
607         assert(_lvArgInitRegPair == regPair);
608     }
609
610     /////////////////////
611
612     bool lvIsRegCandidate() const
613     {
614         return lvLRACandidate != 0;
615     }
616
617     bool lvIsInReg() const
618     {
619         return lvIsRegCandidate() && (lvRegNum != REG_STK);
620     }
621
622 #else // LEGACY_BACKEND
623
624     bool lvIsRegCandidate() const
625     {
626         return lvTracked != 0;
627     }
628
629     bool lvIsInReg() const
630     {
631         return lvRegister != 0;
632     }
633
634 #endif // LEGACY_BACKEND
635
636     regMaskTP lvRegMask() const
637     {
638         regMaskTP regMask = RBM_NONE;
639         if (varTypeIsFloating(TypeGet()))
640         {
641             if (lvRegNum != REG_STK)
642             {
643                 regMask = genRegMaskFloat(lvRegNum, TypeGet());
644             }
645         }
646         else
647         {
648             if (lvRegNum != REG_STK)
649             {
650                 regMask = genRegMask(lvRegNum);
651             }
652
653             // For longs we may have two regs
654             if (isRegPairType(lvType) && lvOtherReg != REG_STK)
655             {
656                 regMask |= genRegMask(lvOtherReg);
657             }
658         }
659         return regMask;
660     }
661
662     regMaskSmall lvPrefReg; // set of regs it prefers to live in
663
664     unsigned short lvVarIndex; // variable tracking index
665     unsigned short lvRefCnt;   // unweighted (real) reference count.  For implicit by reference
666                                // parameters, this gets hijacked from fgMarkImplicitByRefArgs
667                                // through fgMarkDemotedImplicitByRefArgs, to provide a static
668                                // appearance count (computed during address-exposed analysis)
669                                // that fgMakeOutgoingStructArgCopy consults during global morph
670                                // to determine if eliding its copy is legal.
671     unsigned lvRefCntWtd;      // weighted reference count
672     int      lvStkOffs;        // stack offset of home
673     unsigned lvExactSize;      // (exact) size of the type in bytes
674
675     // Is this a promoted struct?
676     // This method returns true only for structs (including SIMD structs), not for
677     // locals that are split on a 32-bit target.
678     // It is only necessary to use this:
679     //   1) if only structs are wanted, and
680     //   2) if Lowering has already been done.
681     // Otherwise lvPromoted is valid.
682     bool lvPromotedStruct()
683     {
684 #if !defined(_TARGET_64BIT_)
685         return (lvPromoted && !varTypeIsLong(lvType));
686 #else  // defined(_TARGET_64BIT_)
687         return lvPromoted;
688 #endif // defined(_TARGET_64BIT_)
689     }
690
691     unsigned lvSize() const // Size needed for storage representation. Only used for structs or TYP_BLK.
692     {
693         // TODO-Review: Sometimes we get called on ARM with HFA struct variables that have been promoted,
694         // where the struct itself is no longer used because all access is via its member fields.
695         // When that happens, the struct is marked as unused and its type has been changed to
696         // TYP_INT (to keep the GC tracking code from looking at it).
697         // See Compiler::raAssignVars() for details. For example:
698         //      N002 (  4,  3) [00EA067C] -------------               return    struct $346
699         //      N001 (  3,  2) [00EA0628] -------------                  lclVar    struct(U) V03 loc2
700         //                                                                        float  V03.f1 (offs=0x00) -> V12 tmp7
701         //                                                                        f8 (last use) (last use) $345
702         // Here, the "struct(U)" shows that the "V03 loc2" variable is unused. Not shown is that V03
703         // is now TYP_INT in the local variable table. It's not really unused, because it's in the tree.
704
705         assert(varTypeIsStruct(lvType) || (lvType == TYP_BLK) || (lvPromoted && lvUnusedStruct));
706
707 #if defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
708         // For 32-bit architectures, we make local variable SIMD12 types 16 bytes instead of just 12. We can't do
709         // this for arguments, which must be passed according the defined ABI. We don't want to do this for
710         // dependently promoted struct fields, but we don't know that here. See lvaMapSimd12ToSimd16().
711         if ((lvType == TYP_SIMD12) && !lvIsParam)
712         {
713             assert(lvExactSize == 12);
714             return 16;
715         }
716 #endif // defined(FEATURE_SIMD) && !defined(_TARGET_64BIT_)
717
718         return (unsigned)(roundUp(lvExactSize, TARGET_POINTER_SIZE));
719     }
720
721     const size_t lvArgStackSize() const;
722
723     unsigned lvSlotNum; // original slot # (if remapped)
724
725     typeInfo lvVerTypeInfo; // type info needed for verification
726
727     CORINFO_CLASS_HANDLE lvClassHnd; // class handle for the local, or null if not known
728
729     CORINFO_FIELD_HANDLE lvFieldHnd; // field handle for promoted struct fields
730
731     BYTE* lvGcLayout; // GC layout info for structs
732
733 #if ASSERTION_PROP
734     BlockSet lvRefBlks;          // Set of blocks that contain refs
735     GenTree* lvDefStmt;          // Pointer to the statement with the single definition
736     void     lvaDisqualifyVar(); // Call to disqualify a local variable from use in optAddCopies
737 #endif
738     var_types TypeGet() const
739     {
740         return (var_types)lvType;
741     }
742     bool lvStackAligned() const
743     {
744         assert(lvIsStructField);
745         return ((lvFldOffset % TARGET_POINTER_SIZE) == 0);
746     }
747     bool lvNormalizeOnLoad() const
748     {
749         return varTypeIsSmall(TypeGet()) &&
750                // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
751                (lvIsParam || lvAddrExposed || lvIsStructField);
752     }
753
754     bool lvNormalizeOnStore()
755     {
756         return varTypeIsSmall(TypeGet()) &&
757                // lvIsStructField is treated the same as the aliased local, see fgDoNormalizeOnStore.
758                !(lvIsParam || lvAddrExposed || lvIsStructField);
759     }
760
761     void lvaResetSortAgainFlag(Compiler* pComp);
762     void decRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
763     void incRefCnts(BasicBlock::weight_t weight, Compiler* pComp, bool propagate = true);
764     void setPrefReg(regNumber regNum, Compiler* pComp);
765     void addPrefReg(regMaskTP regMask, Compiler* pComp);
766     bool IsFloatRegType() const
767     {
768         return isFloatRegType(lvType) || lvIsHfaRegArg();
769     }
770     var_types GetHfaType() const
771     {
772         return lvIsHfa() ? (lvHfaTypeIsFloat() ? TYP_FLOAT : TYP_DOUBLE) : TYP_UNDEF;
773     }
774     void SetHfaType(var_types type)
775     {
776         assert(varTypeIsFloating(type));
777         lvSetHfaTypeIsFloat(type == TYP_FLOAT);
778     }
779
780 #ifndef LEGACY_BACKEND
781     var_types lvaArgType();
782 #endif
783
784     PerSsaArray lvPerSsaData;
785
786 #ifdef DEBUG
787     // Keep track of the # of SsaNames, for a bounds check.
788     unsigned lvNumSsaNames;
789 #endif
790
791     // Returns the address of the per-Ssa data for the given ssaNum (which is required
792     // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
793     // not an SSA variable).
794     LclSsaVarDsc* GetPerSsaData(unsigned ssaNum)
795     {
796         assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
797         assert(SsaConfig::RESERVED_SSA_NUM == 0);
798         unsigned zeroBased = ssaNum - SsaConfig::UNINIT_SSA_NUM;
799         assert(zeroBased < lvNumSsaNames);
800         return &lvPerSsaData.GetRef(zeroBased);
801     }
802
803 #ifdef DEBUG
804 public:
805     void PrintVarReg() const
806     {
807         if (isRegPairType(TypeGet()))
808         {
809             printf("%s:%s", getRegName(lvOtherReg), // hi32
810                    getRegName(lvRegNum));           // lo32
811         }
812         else
813         {
814             printf("%s", getRegName(lvRegNum));
815         }
816     }
817 #endif // DEBUG
818
819 }; // class LclVarDsc
820
821 /*
822 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
823 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
824 XX                                                                           XX
825 XX                           TempsInfo                                       XX
826 XX                                                                           XX
827 XX  The temporary lclVars allocated by the compiler for code generation      XX
828 XX                                                                           XX
829 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
830 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
831 */
832
833 /*****************************************************************************
834  *
835  *  The following keeps track of temporaries allocated in the stack frame
836  *  during code-generation (after register allocation). These spill-temps are
837  *  only used if we run out of registers while evaluating a tree.
838  *
839  *  These are different from the more common temps allocated by lvaGrabTemp().
840  */
841
842 class TempDsc
843 {
844 public:
845     TempDsc* tdNext;
846
847 private:
848     int tdOffs;
849 #ifdef DEBUG
850     static const int BAD_TEMP_OFFSET = 0xDDDDDDDD; // used as a sentinel "bad value" for tdOffs in DEBUG
851 #endif                                             // DEBUG
852
853     int       tdNum;
854     BYTE      tdSize;
855     var_types tdType;
856
857 public:
858     TempDsc(int _tdNum, unsigned _tdSize, var_types _tdType) : tdNum(_tdNum), tdSize((BYTE)_tdSize), tdType(_tdType)
859     {
860 #ifdef DEBUG
861         assert(tdNum <
862                0); // temps must have a negative number (so they have a different number from all local variables)
863         tdOffs = BAD_TEMP_OFFSET;
864 #endif // DEBUG
865         if (tdNum != _tdNum)
866         {
867             IMPL_LIMITATION("too many spill temps");
868         }
869     }
870
871 #ifdef DEBUG
872     bool tdLegalOffset() const
873     {
874         return tdOffs != BAD_TEMP_OFFSET;
875     }
876 #endif // DEBUG
877
878     int tdTempOffs() const
879     {
880         assert(tdLegalOffset());
881         return tdOffs;
882     }
883     void tdSetTempOffs(int offs)
884     {
885         tdOffs = offs;
886         assert(tdLegalOffset());
887     }
888     void tdAdjustTempOffs(int offs)
889     {
890         tdOffs += offs;
891         assert(tdLegalOffset());
892     }
893
894     int tdTempNum() const
895     {
896         assert(tdNum < 0);
897         return tdNum;
898     }
899     unsigned tdTempSize() const
900     {
901         return tdSize;
902     }
903     var_types tdTempType() const
904     {
905         return tdType;
906     }
907 };
908
909 // interface to hide linearscan implementation from rest of compiler
910 class LinearScanInterface
911 {
912 public:
913     virtual void doLinearScan()                                = 0;
914     virtual void recordVarLocationsAtStartOfBB(BasicBlock* bb) = 0;
915     virtual bool willEnregisterLocalVars() const               = 0;
916 };
917
918 LinearScanInterface* getLinearScanAllocator(Compiler* comp);
919
920 // Information about arrays: their element type and size, and the offset of the first element.
921 // We label GT_IND's that are array indices with GTF_IND_ARR_INDEX, and, for such nodes,
922 // associate an array info via the map retrieved by GetArrayInfoMap().  This information is used,
923 // for example, in value numbering of array index expressions.
924 struct ArrayInfo
925 {
926     var_types            m_elemType;
927     CORINFO_CLASS_HANDLE m_elemStructType;
928     unsigned             m_elemSize;
929     unsigned             m_elemOffset;
930
931     ArrayInfo() : m_elemType(TYP_UNDEF), m_elemStructType(nullptr), m_elemSize(0), m_elemOffset(0)
932     {
933     }
934
935     ArrayInfo(var_types elemType, unsigned elemSize, unsigned elemOffset, CORINFO_CLASS_HANDLE elemStructType)
936         : m_elemType(elemType), m_elemStructType(elemStructType), m_elemSize(elemSize), m_elemOffset(elemOffset)
937     {
938     }
939 };
940
941 // This enumeration names the phases into which we divide compilation.  The phases should completely
942 // partition a compilation.
943 enum Phases
944 {
945 #define CompPhaseNameMacro(enum_nm, string_nm, short_nm, hasChildren, parent, measureIR) enum_nm,
946 #include "compphases.h"
947     PHASE_NUMBER_OF
948 };
949
950 extern const char*   PhaseNames[];
951 extern const char*   PhaseEnums[];
952 extern const LPCWSTR PhaseShortNames[];
953
954 // The following enum provides a simple 1:1 mapping to CLR API's
955 enum API_ICorJitInfo_Names
956 {
957 #define DEF_CLR_API(name) API_##name,
958 #include "ICorJitInfo_API_names.h"
959     API_COUNT
960 };
961
962 //---------------------------------------------------------------
963 // Compilation time.
964 //
965
966 // A "CompTimeInfo" is a structure for tracking the compilation time of one or more methods.
967 // We divide a compilation into a sequence of contiguous phases, and track the total (per-thread) cycles
968 // of the compilation, as well as the cycles for each phase.  We also track the number of bytecodes.
969 // If there is a failure in reading a timer at any point, the "CompTimeInfo" becomes invalid, as indicated
970 // by "m_timerFailure" being true.
971 // If FEATURE_JIT_METHOD_PERF is not set, we define a minimal form of this, enough to let other code compile.
972 struct CompTimeInfo
973 {
974 #ifdef FEATURE_JIT_METHOD_PERF
975     // The string names of the phases.
976     static const char* PhaseNames[];
977
978     static bool PhaseHasChildren[];
979     static int  PhaseParent[];
980     static bool PhaseReportsIRSize[];
981
982     unsigned         m_byteCodeBytes;
983     unsigned __int64 m_totalCycles;
984     unsigned __int64 m_invokesByPhase[PHASE_NUMBER_OF];
985     unsigned __int64 m_cyclesByPhase[PHASE_NUMBER_OF];
986 #if MEASURE_CLRAPI_CALLS
987     unsigned __int64 m_CLRinvokesByPhase[PHASE_NUMBER_OF];
988     unsigned __int64 m_CLRcyclesByPhase[PHASE_NUMBER_OF];
989 #endif
990
991     unsigned m_nodeCountAfterPhase[PHASE_NUMBER_OF];
992
993     // For better documentation, we call EndPhase on
994     // non-leaf phases.  We should also call EndPhase on the
995     // last leaf subphase; obviously, the elapsed cycles between the EndPhase
996     // for the last leaf subphase and the EndPhase for an ancestor should be very small.
997     // We add all such "redundant end phase" intervals to this variable below; we print
998     // it out in a report, so we can verify that it is, indeed, very small.  If it ever
999     // isn't, this means that we're doing something significant between the end of the last
1000     // declared subphase and the end of its parent.
1001     unsigned __int64 m_parentPhaseEndSlop;
1002     bool             m_timerFailure;
1003
1004 #if MEASURE_CLRAPI_CALLS
1005     // The following measures the time spent inside each individual CLR API call.
1006     unsigned         m_allClrAPIcalls;
1007     unsigned         m_perClrAPIcalls[API_ICorJitInfo_Names::API_COUNT];
1008     unsigned __int64 m_allClrAPIcycles;
1009     unsigned __int64 m_perClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1010     unsigned __int32 m_maxClrAPIcycles[API_ICorJitInfo_Names::API_COUNT];
1011 #endif // MEASURE_CLRAPI_CALLS
1012
1013     CompTimeInfo(unsigned byteCodeBytes);
1014 #endif
1015 };
1016
1017 #ifdef FEATURE_JIT_METHOD_PERF
1018
1019 #if MEASURE_CLRAPI_CALLS
1020 struct WrapICorJitInfo;
1021 #endif
1022
1023 // This class summarizes the JIT time information over the course of a run: the number of methods compiled,
1024 // and the total and maximum timings.  (These are instances of the "CompTimeInfo" type described above).
1025 // The operation of adding a single method's timing to the summary may be performed concurrently by several
1026 // threads, so it is protected by a lock.
1027 // This class is intended to be used as a singleton type, with only a single instance.
1028 class CompTimeSummaryInfo
1029 {
1030     // This lock protects the fields of all CompTimeSummaryInfo(s) (of which we expect there to be one).
1031     static CritSecObject s_compTimeSummaryLock;
1032
1033     int          m_numMethods;
1034     int          m_totMethods;
1035     CompTimeInfo m_total;
1036     CompTimeInfo m_maximum;
1037
1038     int          m_numFilteredMethods;
1039     CompTimeInfo m_filtered;
1040
1041     // This method computes the number of cycles/sec for the current machine.  The cycles are those counted
1042     // by GetThreadCycleTime; we assume that these are of equal duration, though that is not necessarily true.
1043     // If any OS interaction fails, returns 0.0.
1044     double CyclesPerSecond();
1045
1046     // This can use what ever data you want to determine if the value to be added
1047     // belongs in the filtered section (it's always included in the unfiltered section)
1048     bool IncludedInFilteredData(CompTimeInfo& info);
1049
1050 public:
1051     // This is the unique CompTimeSummaryInfo object for this instance of the runtime.
1052     static CompTimeSummaryInfo s_compTimeSummary;
1053
1054     CompTimeSummaryInfo()
1055         : m_numMethods(0), m_totMethods(0), m_total(0), m_maximum(0), m_numFilteredMethods(0), m_filtered(0)
1056     {
1057     }
1058
1059     // Assumes that "info" is a completed CompTimeInfo for a compilation; adds it to the summary.
1060     // This is thread safe.
1061     void AddInfo(CompTimeInfo& info, bool includePhases);
1062
1063     // Print the summary information to "f".
1064     // This is not thread-safe; assumed to be called by only one thread.
1065     void Print(FILE* f);
1066 };
1067
1068 // A JitTimer encapsulates a CompTimeInfo for a single compilation. It also tracks the start of compilation,
1069 // and when the current phase started.  This is intended to be part of a Compilation object.  This is
1070 // disabled (FEATURE_JIT_METHOD_PERF not defined) when FEATURE_CORECLR is set, or on non-windows platforms.
1071 //
1072 class JitTimer
1073 {
1074     unsigned __int64 m_start;         // Start of the compilation.
1075     unsigned __int64 m_curPhaseStart; // Start of the current phase.
1076 #if MEASURE_CLRAPI_CALLS
1077     unsigned __int64 m_CLRcallStart;   // Start of the current CLR API call (if any).
1078     unsigned __int64 m_CLRcallInvokes; // CLR API invokes under current outer so far
1079     unsigned __int64 m_CLRcallCycles;  // CLR API  cycles under current outer so far.
1080     int              m_CLRcallAPInum;  // The enum/index of the current CLR API call (or -1).
1081     static double    s_cyclesPerSec;   // Cached for speedier measurements
1082 #endif
1083 #ifdef DEBUG
1084     Phases m_lastPhase; // The last phase that was completed (or (Phases)-1 to start).
1085 #endif
1086     CompTimeInfo m_info; // The CompTimeInfo for this compilation.
1087
1088     static CritSecObject s_csvLock; // Lock to protect the time log file.
1089     void PrintCsvMethodStats(Compiler* comp);
1090
1091 private:
1092     void* operator new(size_t);
1093     void* operator new[](size_t);
1094     void operator delete(void*);
1095     void operator delete[](void*);
1096
1097 public:
1098     // Initialized the timer instance
1099     JitTimer(unsigned byteCodeSize);
1100
1101     static JitTimer* Create(Compiler* comp, unsigned byteCodeSize)
1102     {
1103         return ::new (comp, CMK_Unknown) JitTimer(byteCodeSize);
1104     }
1105
1106     static void PrintCsvHeader();
1107
1108     // Ends the current phase (argument is for a redundant check).
1109     void EndPhase(Compiler* compiler, Phases phase);
1110
1111 #if MEASURE_CLRAPI_CALLS
1112     // Start and end a timed CLR API call.
1113     void CLRApiCallEnter(unsigned apix);
1114     void CLRApiCallLeave(unsigned apix);
1115 #endif // MEASURE_CLRAPI_CALLS
1116
1117     // Completes the timing of the current method, which is assumed to have "byteCodeBytes" bytes of bytecode,
1118     // and adds it to "sum".
1119     void Terminate(Compiler* comp, CompTimeSummaryInfo& sum, bool includePhases);
1120
1121     // Attempts to query the cycle counter of the current thread.  If successful, returns "true" and sets
1122     // *cycles to the cycle counter value.  Otherwise, returns false and sets the "m_timerFailure" flag of
1123     // "m_info" to true.
1124     bool GetThreadCycles(unsigned __int64* cycles)
1125     {
1126         bool res = CycleTimer::GetThreadCyclesS(cycles);
1127         if (!res)
1128         {
1129             m_info.m_timerFailure = true;
1130         }
1131         return res;
1132     }
1133 };
1134 #endif // FEATURE_JIT_METHOD_PERF
1135
1136 //------------------- Function/Funclet info -------------------------------
1137 enum FuncKind : BYTE
1138 {
1139     FUNC_ROOT,    // The main/root function (always id==0)
1140     FUNC_HANDLER, // a funclet associated with an EH handler (finally, fault, catch, filter handler)
1141     FUNC_FILTER,  // a funclet associated with an EH filter
1142     FUNC_COUNT
1143 };
1144
1145 class emitLocation;
1146
1147 struct FuncInfoDsc
1148 {
1149     FuncKind       funKind;
1150     BYTE           funFlags;   // Currently unused, just here for padding
1151     unsigned short funEHIndex; // index, into the ebd table, of innermost EH clause corresponding to this
1152                                // funclet. It is only valid if funKind field indicates this is a
1153                                // EH-related funclet: FUNC_HANDLER or FUNC_FILTER
1154
1155 #if defined(_TARGET_AMD64_)
1156
1157     // TODO-AMD64-Throughput: make the AMD64 info more like the ARM info to avoid having this large static array.
1158     emitLocation* startLoc;
1159     emitLocation* endLoc;
1160     emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1161     emitLocation* coldEndLoc;
1162     UNWIND_INFO   unwindHeader;
1163     // Maximum of 255 UNWIND_CODE 'nodes' and then the unwind header. If there are an odd
1164     // number of codes, the VM or Zapper will 4-byte align the whole thing.
1165     BYTE     unwindCodes[offsetof(UNWIND_INFO, UnwindCode) + (0xFF * sizeof(UNWIND_CODE))];
1166     unsigned unwindCodeSlot;
1167
1168 #elif defined(_TARGET_X86_)
1169
1170 #if defined(_TARGET_UNIX_)
1171     emitLocation* startLoc;
1172     emitLocation* endLoc;
1173     emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1174     emitLocation* coldEndLoc;
1175 #endif // _TARGET_UNIX_
1176
1177 #elif defined(_TARGET_ARMARCH_)
1178
1179     UnwindInfo  uwi;     // Unwind information for this function/funclet's hot  section
1180     UnwindInfo* uwiCold; // Unwind information for this function/funclet's cold section
1181                          //   Note: we only have a pointer here instead of the actual object,
1182                          //   to save memory in the JIT case (compared to the NGEN case),
1183                          //   where we don't have any cold section.
1184                          //   Note 2: we currently don't support hot/cold splitting in functions
1185                          //   with EH, so uwiCold will be NULL for all funclets.
1186
1187 #if defined(_TARGET_UNIX_)
1188     emitLocation* startLoc;
1189     emitLocation* endLoc;
1190     emitLocation* coldStartLoc; // locations for the cold section, if there is one.
1191     emitLocation* coldEndLoc;
1192 #endif // _TARGET_UNIX_
1193
1194 #endif // _TARGET_ARMARCH_
1195
1196 #if defined(_TARGET_UNIX_)
1197     jitstd::vector<CFI_CODE>* cfiCodes;
1198 #endif // _TARGET_UNIX_
1199
1200     // Eventually we may want to move rsModifiedRegsMask, lvaOutgoingArgSize, and anything else
1201     // that isn't shared between the main function body and funclets.
1202 };
1203
1204 struct fgArgTabEntry
1205 {
1206
1207 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1208     fgArgTabEntry()
1209     {
1210         otherRegNum = REG_NA;
1211         isStruct    = false; // is this a struct arg
1212     }
1213 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1214
1215     GenTree* node;   // Initially points at the Op1 field of 'parent', but if the argument is replaced with an GT_ASG or
1216                      // placeholder
1217                      //  it will point at the actual argument in the gtCallLateArgs list.
1218     GenTree* parent; // Points at the GT_LIST node in the gtCallArgs for this argument
1219
1220     unsigned argNum; // The original argument number, also specifies the required argument evaluation order from the IL
1221
1222     regNumber regNum; // The (first) register to use when passing this argument, set to REG_STK for arguments passed on
1223                       // the stack
1224     unsigned numRegs; // Count of number of registers that this argument uses
1225
1226     // A slot is a pointer sized region in the OutArg area.
1227     unsigned slotNum;  // When an argument is passed in the OutArg area this is the slot number in the OutArg area
1228     unsigned numSlots; // Count of number of slots that this argument uses
1229
1230     unsigned alignment;  // 1 or 2 (slots/registers)
1231     unsigned lateArgInx; // index into gtCallLateArgs list
1232     unsigned tmpNum;     // the LclVar number if we had to force evaluation of this arg
1233
1234     bool isSplit : 1;       // True when this argument is split between the registers and OutArg area
1235     bool needTmp : 1;       // True when we force this argument's evaluation into a temp LclVar
1236     bool needPlace : 1;     // True when we must replace this argument with a placeholder node
1237     bool isTmp : 1;         // True when we setup a temp LclVar for this argument due to size issues with the struct
1238     bool processed : 1;     // True when we have decided the evaluation order for this argument in the gtCallLateArgs
1239     bool isHfaRegArg : 1;   // True when the argument is passed as a HFA in FP registers.
1240     bool isBackFilled : 1;  // True when the argument fills a register slot skipped due to alignment requirements of
1241                             // previous arguments.
1242     bool isNonStandard : 1; // True if it is an arg that is passed in a reg other than a standard arg reg, or is forced
1243                             // to be on the stack despite its arg list position.
1244
1245 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
1246     bool isStruct : 1; // True if this is a struct arg
1247
1248     regNumber otherRegNum; // The (second) register to use when passing this argument.
1249
1250     SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR structDesc;
1251 #elif !defined(_TARGET_64BIT_)
1252     __declspec(property(get = getIsStruct)) bool isStruct;
1253     bool getIsStruct()
1254     {
1255         return varTypeIsStruct(node);
1256     }
1257 #endif // !_TARGET_64BIT_
1258
1259 #ifdef _TARGET_ARM_
1260     void SetIsHfaRegArg(bool hfaRegArg)
1261     {
1262         isHfaRegArg = hfaRegArg;
1263     }
1264
1265     void SetIsBackFilled(bool backFilled)
1266     {
1267         isBackFilled = backFilled;
1268     }
1269
1270     bool IsBackFilled() const
1271     {
1272         return isBackFilled;
1273     }
1274 #else  // !_TARGET_ARM_
1275     // To make the callers easier, we allow these calls (and the isHfaRegArg and isBackFilled data members) for all
1276     // platforms.
1277     void SetIsHfaRegArg(bool hfaRegArg)
1278     {
1279     }
1280
1281     void SetIsBackFilled(bool backFilled)
1282     {
1283     }
1284
1285     bool IsBackFilled() const
1286     {
1287         return false;
1288     }
1289 #endif // !_TARGET_ARM_
1290
1291 #ifdef DEBUG
1292     void Dump();
1293 #endif
1294 };
1295
1296 //-------------------------------------------------------------------------
1297 //
1298 //  The class fgArgInfo is used to handle the arguments
1299 //  when morphing a GT_CALL node.
1300 //
1301
1302 class fgArgInfo
1303 {
1304     Compiler*    compiler;    // Back pointer to the compiler instance so that we can allocate memory
1305     GenTreeCall* callTree;    // Back pointer to the GT_CALL node for this fgArgInfo
1306     unsigned     argCount;    // Updatable arg count value
1307     unsigned     nextSlotNum; // Updatable slot count value
1308     unsigned     stkLevel;    // Stack depth when we make this call (for x86)
1309
1310 #if defined(UNIX_X86_ABI)
1311     bool     alignmentDone; // Updateable flag, set to 'true' after we've done any required alignment.
1312     unsigned stkSizeBytes;  // Size of stack used by this call, in bytes. Calculated during fgMorphArgs().
1313     unsigned padStkAlign;   // Stack alignment in bytes required before arguments are pushed for this call.
1314                             // Computed dynamically during codegen, based on stkSizeBytes and the current
1315                             // stack level (genStackLevel) when the first stack adjustment is made for
1316                             // this call.
1317 #endif
1318
1319 #if FEATURE_FIXED_OUT_ARGS
1320     unsigned outArgSize; // Size of the out arg area for the call, will be at least MIN_ARG_AREA_FOR_CALL
1321 #endif
1322
1323     unsigned        argTableSize; // size of argTable array (equal to the argCount when done with fgMorphArgs)
1324     bool            hasRegArgs;   // true if we have one or more register arguments
1325     bool            hasStackArgs; // true if we have one or more stack arguments
1326     bool            argsComplete; // marker for state
1327     bool            argsSorted;   // marker for state
1328     fgArgTabEntry** argTable;     // variable sized array of per argument descrption: (i.e. argTable[argTableSize])
1329
1330 private:
1331     void AddArg(fgArgTabEntry* curArgTabEntry);
1332
1333 public:
1334     fgArgInfo(Compiler* comp, GenTreeCall* call, unsigned argCount);
1335     fgArgInfo(GenTreeCall* newCall, GenTreeCall* oldCall);
1336
1337     fgArgTabEntry* AddRegArg(
1338         unsigned argNum, GenTree* node, GenTree* parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1339
1340 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
1341     fgArgTabEntry* AddRegArg(unsigned                                                         argNum,
1342                              GenTree*                                                         node,
1343                              GenTree*                                                         parent,
1344                              regNumber                                                        regNum,
1345                              unsigned                                                         numRegs,
1346                              unsigned                                                         alignment,
1347                              const bool                                                       isStruct,
1348                              const regNumber                                                  otherRegNum   = REG_NA,
1349                              const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* const structDescPtr = nullptr);
1350 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
1351
1352     fgArgTabEntry* AddStkArg(unsigned argNum,
1353                              GenTree* node,
1354                              GenTree* parent,
1355                              unsigned numSlots,
1356                              unsigned alignment FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool isStruct));
1357
1358     void           RemorphReset();
1359     fgArgTabEntry* RemorphRegArg(
1360         unsigned argNum, GenTree* node, GenTree* parent, regNumber regNum, unsigned numRegs, unsigned alignment);
1361
1362     void RemorphStkArg(unsigned argNum, GenTree* node, GenTree* parent, unsigned numSlots, unsigned alignment);
1363
1364     void SplitArg(unsigned argNum, unsigned numRegs, unsigned numSlots);
1365
1366     void EvalToTmp(unsigned argNum, unsigned tmpNum, GenTree* newNode);
1367
1368     void ArgsComplete();
1369
1370     void SortArgs();
1371
1372     void EvalArgsToTemps();
1373
1374     void RecordStkLevel(unsigned stkLvl);
1375     unsigned RetrieveStkLevel();
1376
1377     unsigned ArgCount()
1378     {
1379         return argCount;
1380     }
1381     fgArgTabEntry** ArgTable()
1382     {
1383         return argTable;
1384     }
1385     unsigned GetNextSlotNum()
1386     {
1387         return nextSlotNum;
1388     }
1389     bool HasRegArgs()
1390     {
1391         return hasRegArgs;
1392     }
1393     bool HasStackArgs()
1394     {
1395         return hasStackArgs;
1396     }
1397     bool AreArgsComplete() const
1398     {
1399         return argsComplete;
1400     }
1401 #if FEATURE_FIXED_OUT_ARGS
1402     unsigned GetOutArgSize() const
1403     {
1404         return outArgSize;
1405     }
1406     void SetOutArgSize(unsigned newVal)
1407     {
1408         outArgSize = newVal;
1409     }
1410 #endif // FEATURE_FIXED_OUT_ARGS
1411
1412 #if defined(UNIX_X86_ABI)
1413     void ComputeStackAlignment(unsigned curStackLevelInBytes)
1414     {
1415         padStkAlign = AlignmentPad(curStackLevelInBytes, STACK_ALIGN);
1416     }
1417
1418     unsigned GetStkAlign()
1419     {
1420         return padStkAlign;
1421     }
1422
1423     void SetStkSizeBytes(unsigned newStkSizeBytes)
1424     {
1425         stkSizeBytes = newStkSizeBytes;
1426     }
1427
1428     unsigned GetStkSizeBytes() const
1429     {
1430         return stkSizeBytes;
1431     }
1432
1433     bool IsStkAlignmentDone() const
1434     {
1435         return alignmentDone;
1436     }
1437
1438     void SetStkAlignmentDone()
1439     {
1440         alignmentDone = true;
1441     }
1442 #endif // defined(UNIX_X86_ABI)
1443
1444     // Get the late arg for arg at position argIndex.  Caller must ensure this position has a late arg.
1445     GenTree* GetLateArg(unsigned argIndex);
1446
1447     void Dump(Compiler* compiler);
1448 };
1449
1450 #ifdef DEBUG
1451 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1452 // We have the ability to mark source expressions with "Test Labels."
1453 // These drive assertions within the JIT, or internal JIT testing.  For example, we could label expressions
1454 // that should be CSE defs, and other expressions that should uses of those defs, with a shared label.
1455
1456 enum TestLabel // This must be kept identical to System.Runtime.CompilerServices.JitTestLabel.TestLabel.
1457 {
1458     TL_SsaName,
1459     TL_VN,        // Defines a "VN equivalence class".  (For full VN, including exceptions thrown).
1460     TL_VNNorm,    // Like above, but uses the non-exceptional value of the expression.
1461     TL_CSE_Def,   //  This must be identified in the JIT as a CSE def
1462     TL_CSE_Use,   //  This must be identified in the JIT as a CSE use
1463     TL_LoopHoist, // Expression must (or must not) be hoisted out of the loop.
1464 };
1465
1466 struct TestLabelAndNum
1467 {
1468     TestLabel m_tl;
1469     ssize_t   m_num;
1470
1471     TestLabelAndNum() : m_tl(TestLabel(0)), m_num(0)
1472     {
1473     }
1474 };
1475
1476 typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, TestLabelAndNum> NodeToTestDataMap;
1477
1478 // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1479 #endif // DEBUG
1480
1481 /*
1482 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1483 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1484 XX                                                                           XX
1485 XX   The big guy. The sections are currently organized as :                  XX
1486 XX                                                                           XX
1487 XX    o  GenTree and BasicBlock                                              XX
1488 XX    o  LclVarsInfo                                                         XX
1489 XX    o  Importer                                                            XX
1490 XX    o  FlowGraph                                                           XX
1491 XX    o  Optimizer                                                           XX
1492 XX    o  RegAlloc                                                            XX
1493 XX    o  EEInterface                                                         XX
1494 XX    o  TempsInfo                                                           XX
1495 XX    o  RegSet                                                              XX
1496 XX    o  GCInfo                                                              XX
1497 XX    o  Instruction                                                         XX
1498 XX    o  ScopeInfo                                                           XX
1499 XX    o  PrologScopeInfo                                                     XX
1500 XX    o  CodeGenerator                                                       XX
1501 XX    o  UnwindInfo                                                          XX
1502 XX    o  Compiler                                                            XX
1503 XX    o  typeInfo                                                            XX
1504 XX                                                                           XX
1505 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1506 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1507 */
1508
1509 struct HWIntrinsicInfo;
1510
1511 class Compiler
1512 {
1513     friend class emitter;
1514     friend class UnwindInfo;
1515     friend class UnwindFragmentInfo;
1516     friend class UnwindEpilogInfo;
1517     friend class JitTimer;
1518     friend class LinearScan;
1519     friend class fgArgInfo;
1520     friend class Rationalizer;
1521     friend class Phase;
1522     friend class Lowering;
1523     friend class CSE_DataFlow;
1524     friend class CSE_Heuristic;
1525     friend class CodeGenInterface;
1526     friend class CodeGen;
1527     friend class LclVarDsc;
1528     friend class TempDsc;
1529     friend class LIR;
1530     friend class ObjectAllocator;
1531     friend struct GenTree;
1532
1533 #ifndef _TARGET_64BIT_
1534     friend class DecomposeLongs;
1535 #endif // !_TARGET_64BIT_
1536
1537     /*
1538     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1539     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1540     XX                                                                           XX
1541     XX  Misc structs definitions                                                 XX
1542     XX                                                                           XX
1543     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1544     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1545     */
1546
1547 public:
1548     hashBvGlobalData hbvGlobalData; // Used by the hashBv bitvector package.
1549
1550 #ifdef DEBUG
1551     bool    verbose;
1552     bool    dumpIR;
1553     bool    dumpIRNodes;
1554     bool    dumpIRTypes;
1555     bool    dumpIRKinds;
1556     bool    dumpIRLocals;
1557     bool    dumpIRRegs;
1558     bool    dumpIRSsa;
1559     bool    dumpIRValnums;
1560     bool    dumpIRCosts;
1561     bool    dumpIRFlags;
1562     bool    dumpIRNoLists;
1563     bool    dumpIRNoLeafs;
1564     bool    dumpIRNoStmts;
1565     bool    dumpIRTrees;
1566     bool    dumpIRLinear;
1567     bool    dumpIRDataflow;
1568     bool    dumpIRBlockHeaders;
1569     bool    dumpIRExit;
1570     LPCWSTR dumpIRPhase;
1571     LPCWSTR dumpIRFormat;
1572     bool    verboseTrees;
1573     bool    shouldUseVerboseTrees();
1574     bool    asciiTrees; // If true, dump trees using only ASCII characters
1575     bool    shouldDumpASCIITrees();
1576     bool    verboseSsa; // If true, produce especially verbose dump output in SSA construction.
1577     bool    shouldUseVerboseSsa();
1578     bool    treesBeforeAfterMorph; // If true, print trees before/after morphing (paired by an intra-compilation id:
1579     int     morphNum; // This counts the the trees that have been morphed, allowing us to label each uniquely.
1580
1581     const char* VarNameToStr(VarName name)
1582     {
1583         return name;
1584     }
1585
1586     DWORD expensiveDebugCheckLevel;
1587 #endif
1588
1589 #if FEATURE_MULTIREG_RET
1590     GenTree* impAssignMultiRegTypeToVar(GenTree* op, CORINFO_CLASS_HANDLE hClass);
1591 #endif // FEATURE_MULTIREG_RET
1592
1593 #ifdef ARM_SOFTFP
1594     bool isSingleFloat32Struct(CORINFO_CLASS_HANDLE hClass);
1595 #endif // ARM_SOFTFP
1596
1597     //-------------------------------------------------------------------------
1598     // Functions to handle homogeneous floating-point aggregates (HFAs) in ARM.
1599     // HFAs are one to four element structs where each element is the same
1600     // type, either all float or all double. They are treated specially
1601     // in the ARM Procedure Call Standard, specifically, they are passed in
1602     // floating-point registers instead of the general purpose registers.
1603     //
1604
1605     bool IsHfa(CORINFO_CLASS_HANDLE hClass);
1606     bool IsHfa(GenTree* tree);
1607
1608     var_types GetHfaType(GenTree* tree);
1609     unsigned GetHfaCount(GenTree* tree);
1610
1611     var_types GetHfaType(CORINFO_CLASS_HANDLE hClass);
1612     unsigned GetHfaCount(CORINFO_CLASS_HANDLE hClass);
1613
1614     bool IsMultiRegPassedType(CORINFO_CLASS_HANDLE hClass);
1615     bool IsMultiRegReturnedType(CORINFO_CLASS_HANDLE hClass);
1616
1617     //-------------------------------------------------------------------------
1618     // The following is used for validating format of EH table
1619     //
1620
1621     struct EHNodeDsc;
1622     typedef struct EHNodeDsc* pEHNodeDsc;
1623
1624     EHNodeDsc* ehnTree; // root of the tree comprising the EHnodes.
1625     EHNodeDsc* ehnNext; // root of the tree comprising the EHnodes.
1626
1627     struct EHNodeDsc
1628     {
1629         enum EHBlockType
1630         {
1631             TryNode,
1632             FilterNode,
1633             HandlerNode,
1634             FinallyNode,
1635             FaultNode
1636         };
1637
1638         EHBlockType ehnBlockType;   // kind of EH block
1639         IL_OFFSET   ehnStartOffset; // IL offset of start of the EH block
1640         IL_OFFSET ehnEndOffset; // IL offset past end of the EH block. (TODO: looks like verInsertEhNode() sets this to
1641                                 // the last IL offset, not "one past the last one", i.e., the range Start to End is
1642                                 // inclusive).
1643         pEHNodeDsc ehnNext;     // next (non-nested) block in sequential order
1644         pEHNodeDsc ehnChild;    // leftmost nested block
1645         union {
1646             pEHNodeDsc ehnTryNode;     // for filters and handlers, the corresponding try node
1647             pEHNodeDsc ehnHandlerNode; // for a try node, the corresponding handler node
1648         };
1649         pEHNodeDsc ehnFilterNode; // if this is a try node and has a filter, otherwise 0
1650         pEHNodeDsc ehnEquivalent; // if blockType=tryNode, start offset and end offset is same,
1651
1652         inline void ehnSetTryNodeType()
1653         {
1654             ehnBlockType = TryNode;
1655         }
1656         inline void ehnSetFilterNodeType()
1657         {
1658             ehnBlockType = FilterNode;
1659         }
1660         inline void ehnSetHandlerNodeType()
1661         {
1662             ehnBlockType = HandlerNode;
1663         }
1664         inline void ehnSetFinallyNodeType()
1665         {
1666             ehnBlockType = FinallyNode;
1667         }
1668         inline void ehnSetFaultNodeType()
1669         {
1670             ehnBlockType = FaultNode;
1671         }
1672
1673         inline BOOL ehnIsTryBlock()
1674         {
1675             return ehnBlockType == TryNode;
1676         }
1677         inline BOOL ehnIsFilterBlock()
1678         {
1679             return ehnBlockType == FilterNode;
1680         }
1681         inline BOOL ehnIsHandlerBlock()
1682         {
1683             return ehnBlockType == HandlerNode;
1684         }
1685         inline BOOL ehnIsFinallyBlock()
1686         {
1687             return ehnBlockType == FinallyNode;
1688         }
1689         inline BOOL ehnIsFaultBlock()
1690         {
1691             return ehnBlockType == FaultNode;
1692         }
1693
1694         // returns true if there is any overlap between the two nodes
1695         static inline BOOL ehnIsOverlap(pEHNodeDsc node1, pEHNodeDsc node2)
1696         {
1697             if (node1->ehnStartOffset < node2->ehnStartOffset)
1698             {
1699                 return (node1->ehnEndOffset >= node2->ehnStartOffset);
1700             }
1701             else
1702             {
1703                 return (node1->ehnStartOffset <= node2->ehnEndOffset);
1704             }
1705         }
1706
1707         // fails with BADCODE if inner is not completely nested inside outer
1708         static inline BOOL ehnIsNested(pEHNodeDsc inner, pEHNodeDsc outer)
1709         {
1710             return ((inner->ehnStartOffset >= outer->ehnStartOffset) && (inner->ehnEndOffset <= outer->ehnEndOffset));
1711         }
1712     };
1713
1714 //-------------------------------------------------------------------------
1715 // Exception handling functions
1716 //
1717
1718 #if !FEATURE_EH_FUNCLETS
1719
1720     bool ehNeedsShadowSPslots()
1721     {
1722         return (info.compXcptnsCount || opts.compDbgEnC);
1723     }
1724
1725     // 0 for methods with no EH
1726     // 1 for methods with non-nested EH, or where only the try blocks are nested
1727     // 2 for a method with a catch within a catch
1728     // etc.
1729     unsigned ehMaxHndNestingCount;
1730
1731 #endif // !FEATURE_EH_FUNCLETS
1732
1733     static bool jitIsBetween(unsigned value, unsigned start, unsigned end);
1734     static bool jitIsBetweenInclusive(unsigned value, unsigned start, unsigned end);
1735
1736     bool bbInCatchHandlerILRange(BasicBlock* blk);
1737     bool bbInFilterILRange(BasicBlock* blk);
1738     bool bbInTryRegions(unsigned regionIndex, BasicBlock* blk);
1739     bool bbInExnFlowRegions(unsigned regionIndex, BasicBlock* blk);
1740     bool bbInHandlerRegions(unsigned regionIndex, BasicBlock* blk);
1741     bool bbInCatchHandlerRegions(BasicBlock* tryBlk, BasicBlock* hndBlk);
1742     unsigned short bbFindInnermostCommonTryRegion(BasicBlock* bbOne, BasicBlock* bbTwo);
1743
1744     unsigned short bbFindInnermostTryRegionContainingHandlerRegion(unsigned handlerIndex);
1745     unsigned short bbFindInnermostHandlerRegionContainingTryRegion(unsigned tryIndex);
1746
1747     // Returns true if "block" is the start of a try region.
1748     bool bbIsTryBeg(BasicBlock* block);
1749
1750     // Returns true if "block" is the start of a handler or filter region.
1751     bool bbIsHandlerBeg(BasicBlock* block);
1752
1753     // Returns true iff "block" is where control flows if an exception is raised in the
1754     // try region, and sets "*regionIndex" to the index of the try for the handler.
1755     // Differs from "IsHandlerBeg" in the case of filters, where this is true for the first
1756     // block of the filter, but not for the filter's handler.
1757     bool bbIsExFlowBlock(BasicBlock* block, unsigned* regionIndex);
1758
1759     bool ehHasCallableHandlers();
1760
1761     // Return the EH descriptor for the given region index.
1762     EHblkDsc* ehGetDsc(unsigned regionIndex);
1763
1764     // Return the EH index given a region descriptor.
1765     unsigned ehGetIndex(EHblkDsc* ehDsc);
1766
1767     // Return the EH descriptor index of the enclosing try, for the given region index.
1768     unsigned ehGetEnclosingTryIndex(unsigned regionIndex);
1769
1770     // Return the EH descriptor index of the enclosing handler, for the given region index.
1771     unsigned ehGetEnclosingHndIndex(unsigned regionIndex);
1772
1773     // Return the EH descriptor for the most nested 'try' region this BasicBlock is a member of (or nullptr if this
1774     // block is not in a 'try' region).
1775     EHblkDsc* ehGetBlockTryDsc(BasicBlock* block);
1776
1777     // Return the EH descriptor for the most nested filter or handler region this BasicBlock is a member of (or nullptr
1778     // if this block is not in a filter or handler region).
1779     EHblkDsc* ehGetBlockHndDsc(BasicBlock* block);
1780
1781     // Return the EH descriptor for the most nested region that may handle exceptions raised in this BasicBlock (or
1782     // nullptr if this block's exceptions propagate to caller).
1783     EHblkDsc* ehGetBlockExnFlowDsc(BasicBlock* block);
1784
1785     EHblkDsc* ehIsBlockTryLast(BasicBlock* block);
1786     EHblkDsc* ehIsBlockHndLast(BasicBlock* block);
1787     bool ehIsBlockEHLast(BasicBlock* block);
1788
1789     bool ehBlockHasExnFlowDsc(BasicBlock* block);
1790
1791     // Return the region index of the most nested EH region this block is in.
1792     unsigned ehGetMostNestedRegionIndex(BasicBlock* block, bool* inTryRegion);
1793
1794     // Find the true enclosing try index, ignoring 'mutual protect' try. Uses IL ranges to check.
1795     unsigned ehTrueEnclosingTryIndexIL(unsigned regionIndex);
1796
1797     // Return the index of the most nested enclosing region for a particular EH region. Returns NO_ENCLOSING_INDEX
1798     // if there is no enclosing region. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion'
1799     // is set to 'true' if the enclosing region is a 'try', or 'false' if the enclosing region is a handler.
1800     // (It can never be a filter.)
1801     unsigned ehGetEnclosingRegionIndex(unsigned regionIndex, bool* inTryRegion);
1802
1803     // A block has been deleted. Update the EH table appropriately.
1804     void ehUpdateForDeletedBlock(BasicBlock* block);
1805
1806     // Determine whether a block can be deleted while preserving the EH normalization rules.
1807     bool ehCanDeleteEmptyBlock(BasicBlock* block);
1808
1809     // Update the 'last' pointers in the EH table to reflect new or deleted blocks in an EH region.
1810     void ehUpdateLastBlocks(BasicBlock* oldLast, BasicBlock* newLast);
1811
1812     // For a finally handler, find the region index that the BBJ_CALLFINALLY lives in that calls the handler,
1813     // or NO_ENCLOSING_INDEX if the BBJ_CALLFINALLY lives in the main function body. Normally, the index
1814     // is the same index as the handler (and the BBJ_CALLFINALLY lives in the 'try' region), but for AMD64 the
1815     // BBJ_CALLFINALLY lives in the enclosing try or handler region, whichever is more nested, or the main function
1816     // body. If the returned index is not NO_ENCLOSING_INDEX, then '*inTryRegion' is set to 'true' if the
1817     // BBJ_CALLFINALLY lives in the returned index's 'try' region, or 'false' if lives in the handler region. (It never
1818     // lives in a filter.)
1819     unsigned ehGetCallFinallyRegionIndex(unsigned finallyIndex, bool* inTryRegion);
1820
1821     // Find the range of basic blocks in which all BBJ_CALLFINALLY will be found that target the 'finallyIndex' region's
1822     // handler. Set begBlk to the first block, and endBlk to the block after the last block of the range
1823     // (nullptr if the last block is the last block in the program).
1824     // Precondition: 'finallyIndex' is the EH region of a try/finally clause.
1825     void ehGetCallFinallyBlockRange(unsigned finallyIndex, BasicBlock** begBlk, BasicBlock** endBlk);
1826
1827 #ifdef DEBUG
1828     // Given a BBJ_CALLFINALLY block and the EH region index of the finally it is calling, return
1829     // 'true' if the BBJ_CALLFINALLY is in the correct EH region.
1830     bool ehCallFinallyInCorrectRegion(BasicBlock* blockCallFinally, unsigned finallyIndex);
1831 #endif // DEBUG
1832
1833 #if FEATURE_EH_FUNCLETS
1834     // Do we need a PSPSym in the main function? For codegen purposes, we only need one
1835     // if there is a filter that protects a region with a nested EH clause (such as a
1836     // try/catch nested in the 'try' body of a try/filter/filter-handler). See
1837     // genFuncletProlog() for more details. However, the VM seems to use it for more
1838     // purposes, maybe including debugging. Until we are sure otherwise, always create
1839     // a PSPSym for functions with any EH.
1840     bool ehNeedsPSPSym() const
1841     {
1842 #ifdef _TARGET_X86_
1843         return false;
1844 #else  // _TARGET_X86_
1845         return compHndBBtabCount > 0;
1846 #endif // _TARGET_X86_
1847     }
1848
1849     bool     ehAnyFunclets();  // Are there any funclets in this function?
1850     unsigned ehFuncletCount(); // Return the count of funclets in the function
1851
1852     unsigned bbThrowIndex(BasicBlock* blk); // Get the index to use as the cache key for sharing throw blocks
1853 #else                                       // !FEATURE_EH_FUNCLETS
1854     bool ehAnyFunclets()
1855     {
1856         return false;
1857     }
1858     unsigned ehFuncletCount()
1859     {
1860         return 0;
1861     }
1862
1863     unsigned bbThrowIndex(BasicBlock* blk)
1864     {
1865         return blk->bbTryIndex;
1866     } // Get the index to use as the cache key for sharing throw blocks
1867 #endif                                      // !FEATURE_EH_FUNCLETS
1868
1869     // Returns a flowList representing the "EH predecessors" of "blk".  These are the normal predecessors of
1870     // "blk", plus one special case: if "blk" is the first block of a handler, considers the predecessor(s) of the first
1871     // first block of the corresponding try region to be "EH predecessors".  (If there is a single such predecessor,
1872     // for example, we want to consider that the immediate dominator of the catch clause start block, so it's
1873     // convenient to also consider it a predecessor.)
1874     flowList* BlockPredsWithEH(BasicBlock* blk);
1875
1876     // This table is useful for memoization of the method above.
1877     typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, flowList*> BlockToFlowListMap;
1878     BlockToFlowListMap* m_blockToEHPreds;
1879     BlockToFlowListMap* GetBlockToEHPreds()
1880     {
1881         if (m_blockToEHPreds == nullptr)
1882         {
1883             m_blockToEHPreds = new (getAllocator()) BlockToFlowListMap(getAllocator());
1884         }
1885         return m_blockToEHPreds;
1886     }
1887
1888     void* ehEmitCookie(BasicBlock* block);
1889     UNATIVE_OFFSET ehCodeOffset(BasicBlock* block);
1890
1891     EHblkDsc* ehInitHndRange(BasicBlock* src, IL_OFFSET* hndBeg, IL_OFFSET* hndEnd, bool* inFilter);
1892
1893     EHblkDsc* ehInitTryRange(BasicBlock* src, IL_OFFSET* tryBeg, IL_OFFSET* tryEnd);
1894
1895     EHblkDsc* ehInitHndBlockRange(BasicBlock* blk, BasicBlock** hndBeg, BasicBlock** hndLast, bool* inFilter);
1896
1897     EHblkDsc* ehInitTryBlockRange(BasicBlock* blk, BasicBlock** tryBeg, BasicBlock** tryLast);
1898
1899     void fgSetTryEnd(EHblkDsc* handlerTab, BasicBlock* newTryLast);
1900
1901     void fgSetHndEnd(EHblkDsc* handlerTab, BasicBlock* newHndLast);
1902
1903     void fgSkipRmvdBlocks(EHblkDsc* handlerTab);
1904
1905     void fgAllocEHTable();
1906
1907     void fgRemoveEHTableEntry(unsigned XTnum);
1908
1909 #if FEATURE_EH_FUNCLETS
1910
1911     EHblkDsc* fgAddEHTableEntry(unsigned XTnum);
1912
1913 #endif // FEATURE_EH_FUNCLETS
1914
1915 #if !FEATURE_EH
1916     void fgRemoveEH();
1917 #endif // !FEATURE_EH
1918
1919     void fgSortEHTable();
1920
1921     // Causes the EH table to obey some well-formedness conditions, by inserting
1922     // empty BB's when necessary:
1923     //   * No block is both the first block of a handler and the first block of a try.
1924     //   * No block is the first block of multiple 'try' regions.
1925     //   * No block is the last block of multiple EH regions.
1926     void fgNormalizeEH();
1927     bool fgNormalizeEHCase1();
1928     bool fgNormalizeEHCase2();
1929     bool fgNormalizeEHCase3();
1930
1931 #ifdef DEBUG
1932     void dispIncomingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1933     void dispOutgoingEHClause(unsigned num, const CORINFO_EH_CLAUSE& clause);
1934     void fgVerifyHandlerTab();
1935     void fgDispHandlerTab();
1936 #endif // DEBUG
1937
1938     bool fgNeedToSortEHTable;
1939
1940     void verInitEHTree(unsigned numEHClauses);
1941     void verInsertEhNode(CORINFO_EH_CLAUSE* clause, EHblkDsc* handlerTab);
1942     void verInsertEhNodeInTree(EHNodeDsc** ppRoot, EHNodeDsc* node);
1943     void verInsertEhNodeParent(EHNodeDsc** ppRoot, EHNodeDsc* node);
1944     void verCheckNestingLevel(EHNodeDsc* initRoot);
1945
1946     /*
1947     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1948     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1949     XX                                                                           XX
1950     XX                        GenTree and BasicBlock                             XX
1951     XX                                                                           XX
1952     XX  Functions to allocate and display the GenTrees and BasicBlocks           XX
1953     XX                                                                           XX
1954     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1955     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
1956     */
1957
1958     // Functions to create nodes
1959     GenTreeStmt* gtNewStmt(GenTree* expr = nullptr, IL_OFFSETX offset = BAD_IL_OFFSET);
1960
1961     // For unary opers.
1962     GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, bool doSimplifications = TRUE);
1963
1964     // For binary opers.
1965     GenTree* gtNewOperNode(genTreeOps oper, var_types type, GenTree* op1, GenTree* op2);
1966
1967     GenTree* gtNewQmarkNode(var_types type, GenTree* cond, GenTree* colon);
1968
1969     GenTree* gtNewLargeOperNode(genTreeOps oper,
1970                                 var_types  type = TYP_I_IMPL,
1971                                 GenTree*   op1  = nullptr,
1972                                 GenTree*   op2  = nullptr);
1973
1974     GenTreeIntCon* gtNewIconNode(ssize_t value, var_types type = TYP_INT);
1975
1976     GenTree* gtNewPhysRegNode(regNumber reg, var_types type);
1977
1978     GenTree* gtNewJmpTableNode();
1979
1980     GenTree* gtNewIndOfIconHandleNode(var_types indType, size_t value, unsigned iconFlags, bool isInvariant);
1981
1982     GenTree* gtNewIconHandleNode(size_t value, unsigned flags, FieldSeqNode* fields = nullptr);
1983
1984     unsigned gtTokenToIconFlags(unsigned token);
1985
1986     GenTree* gtNewIconEmbHndNode(void* value, void* pValue, unsigned flags, void* compileTimeHandle);
1987
1988     GenTree* gtNewIconEmbScpHndNode(CORINFO_MODULE_HANDLE scpHnd);
1989     GenTree* gtNewIconEmbClsHndNode(CORINFO_CLASS_HANDLE clsHnd);
1990     GenTree* gtNewIconEmbMethHndNode(CORINFO_METHOD_HANDLE methHnd);
1991     GenTree* gtNewIconEmbFldHndNode(CORINFO_FIELD_HANDLE fldHnd);
1992
1993     GenTree* gtNewStringLiteralNode(InfoAccessType iat, void* pValue);
1994
1995     GenTree* gtNewLconNode(__int64 value);
1996
1997     GenTree* gtNewDconNode(double value);
1998
1999     GenTree* gtNewSconNode(int CPX, CORINFO_MODULE_HANDLE scpHandle);
2000
2001     GenTree* gtNewZeroConNode(var_types type);
2002
2003     GenTree* gtNewOneConNode(var_types type);
2004
2005 #ifdef FEATURE_SIMD
2006     GenTree* gtNewSIMDVectorZero(var_types simdType, var_types baseType, unsigned size);
2007     GenTree* gtNewSIMDVectorOne(var_types simdType, var_types baseType, unsigned size);
2008 #endif
2009
2010     GenTreeBlk* gtNewBlkOpNode(
2011         genTreeOps oper, GenTree* dst, GenTree* srcOrFillVal, GenTree* sizeOrClsTok, bool isVolatile);
2012
2013     GenTree* gtNewBlkOpNode(GenTree* dst, GenTree* srcOrFillVal, unsigned size, bool isVolatile, bool isCopyBlock);
2014
2015     GenTree* gtNewPutArgReg(var_types type, GenTree* arg, regNumber argReg);
2016
2017     GenTree* gtNewBitCastNode(var_types type, GenTree* arg);
2018
2019 protected:
2020     void gtBlockOpInit(GenTree* result, GenTree* dst, GenTree* srcOrFillVal, bool isVolatile);
2021
2022 public:
2023     GenTree* gtNewObjNode(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2024     void gtSetObjGcInfo(GenTreeObj* objNode);
2025     GenTree* gtNewStructVal(CORINFO_CLASS_HANDLE structHnd, GenTree* addr);
2026     GenTree* gtNewBlockVal(GenTree* addr, unsigned size);
2027
2028     GenTree* gtNewCpObjNode(GenTree* dst, GenTree* src, CORINFO_CLASS_HANDLE structHnd, bool isVolatile);
2029
2030     GenTreeArgList* gtNewListNode(GenTree* op1, GenTreeArgList* op2);
2031
2032     GenTreeCall* gtNewCallNode(gtCallTypes           callType,
2033                                CORINFO_METHOD_HANDLE handle,
2034                                var_types             type,
2035                                GenTreeArgList*       args,
2036                                IL_OFFSETX            ilOffset = BAD_IL_OFFSET);
2037
2038     GenTreeCall* gtNewIndCallNode(GenTree*        addr,
2039                                   var_types       type,
2040                                   GenTreeArgList* args,
2041                                   IL_OFFSETX      ilOffset = BAD_IL_OFFSET);
2042
2043     GenTreeCall* gtNewHelperCallNode(unsigned helper, var_types type, GenTreeArgList* args = nullptr);
2044
2045     GenTree* gtNewLclvNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
2046
2047 #ifdef FEATURE_SIMD
2048     GenTreeSIMD* gtNewSIMDNode(
2049         var_types type, GenTree* op1, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2050     GenTreeSIMD* gtNewSIMDNode(
2051         var_types type, GenTree* op1, GenTree* op2, SIMDIntrinsicID simdIntrinsicID, var_types baseType, unsigned size);
2052     void SetOpLclRelatedToSIMDIntrinsic(GenTree* op);
2053 #endif
2054
2055 #ifdef FEATURE_HW_INTRINSICS
2056     GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
2057                                                  NamedIntrinsic hwIntrinsicID,
2058                                                  var_types      baseType,
2059                                                  unsigned       size);
2060     GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2061         var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2062     GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(
2063         var_types type, GenTree* op1, GenTree* op2, NamedIntrinsic hwIntrinsicID, var_types baseType, unsigned size);
2064     GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
2065                                                  GenTree*       op1,
2066                                                  GenTree*       op2,
2067                                                  GenTree*       op3,
2068                                                  NamedIntrinsic hwIntrinsicID,
2069                                                  var_types      baseType,
2070                                                  unsigned       size);
2071     GenTreeHWIntrinsic* gtNewSimdHWIntrinsicNode(var_types      type,
2072                                                  GenTree*       op1,
2073                                                  GenTree*       op2,
2074                                                  GenTree*       op3,
2075                                                  GenTree*       op4,
2076                                                  NamedIntrinsic hwIntrinsicID,
2077                                                  var_types      baseType,
2078                                                  unsigned       size);
2079     GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types type, GenTree* op1, NamedIntrinsic hwIntrinsicID);
2080     GenTreeHWIntrinsic* gtNewScalarHWIntrinsicNode(var_types      type,
2081                                                    GenTree*       op1,
2082                                                    GenTree*       op2,
2083                                                    NamedIntrinsic hwIntrinsicID);
2084     GenTree* gtNewMustThrowException(unsigned helper, var_types type, CORINFO_CLASS_HANDLE clsHnd);
2085     CORINFO_CLASS_HANDLE gtGetStructHandleForHWSIMD(var_types simdType, var_types simdBaseType);
2086 #endif // FEATURE_HW_INTRINSICS
2087
2088     GenTree* gtNewLclLNode(unsigned lnum, var_types type, IL_OFFSETX ILoffs = BAD_IL_OFFSET);
2089     GenTreeLclFld* gtNewLclFldNode(unsigned lnum, var_types type, unsigned offset);
2090     GenTree* gtNewInlineCandidateReturnExpr(GenTree* inlineCandidate, var_types type);
2091
2092     GenTree* gtNewCodeRef(BasicBlock* block);
2093
2094     GenTree* gtNewFieldRef(
2095         var_types typ, CORINFO_FIELD_HANDLE fldHnd, GenTree* obj = nullptr, DWORD offset = 0, bool nullcheck = false);
2096
2097     GenTree* gtNewIndexRef(var_types typ, GenTree* arrayOp, GenTree* indexOp);
2098
2099     GenTreeArrLen* gtNewArrLen(var_types typ, GenTree* arrayOp, int lenOffset);
2100
2101     GenTree* gtNewIndir(var_types typ, GenTree* addr);
2102
2103     GenTreeArgList* gtNewArgList(GenTree* op);
2104     GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2);
2105     GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3);
2106     GenTreeArgList* gtNewArgList(GenTree* op1, GenTree* op2, GenTree* op3, GenTree* op4);
2107
2108     static fgArgTabEntry* gtArgEntryByArgNum(GenTreeCall* call, unsigned argNum);
2109     static fgArgTabEntry* gtArgEntryByNode(GenTreeCall* call, GenTree* node);
2110     fgArgTabEntry* gtArgEntryByLateArgIndex(GenTreeCall* call, unsigned lateArgInx);
2111     bool gtArgIsThisPtr(fgArgTabEntry* argEntry);
2112
2113     GenTree* gtNewAssignNode(GenTree* dst, GenTree* src);
2114
2115     GenTree* gtNewTempAssign(unsigned tmp, GenTree* val);
2116
2117     GenTree* gtNewRefCOMfield(GenTree*                objPtr,
2118                               CORINFO_RESOLVED_TOKEN* pResolvedToken,
2119                               CORINFO_ACCESS_FLAGS    access,
2120                               CORINFO_FIELD_INFO*     pFieldInfo,
2121                               var_types               lclTyp,
2122                               CORINFO_CLASS_HANDLE    structType,
2123                               GenTree*                assg);
2124
2125     GenTree* gtNewNothingNode();
2126
2127     GenTree* gtNewArgPlaceHolderNode(var_types type, CORINFO_CLASS_HANDLE clsHnd);
2128
2129     GenTree* gtUnusedValNode(GenTree* expr);
2130
2131     GenTreeCast* gtNewCastNode(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2132
2133     GenTreeCast* gtNewCastNodeL(var_types typ, GenTree* op1, bool fromUnsigned, var_types castType);
2134
2135     GenTree* gtNewAllocObjNode(unsigned int helper, CORINFO_CLASS_HANDLE clsHnd, var_types type, GenTree* op1);
2136
2137     GenTree* gtNewRuntimeLookup(CORINFO_GENERIC_HANDLE hnd, CorInfoGenericHandleType hndTyp, GenTree* lookupTree);
2138
2139     //------------------------------------------------------------------------
2140     // Other GenTree functions
2141
2142     GenTree* gtClone(GenTree* tree, bool complexOK = false);
2143
2144     // If `tree` is a lclVar with lclNum `varNum`, return an IntCns with value `varVal`; otherwise,
2145     // create a copy of `tree`, adding specified flags, replacing uses of lclVar `deepVarNum` with
2146     // IntCnses with value `deepVarVal`.
2147     GenTree* gtCloneExpr(
2148         GenTree* tree, unsigned addFlags, unsigned varNum, int varVal, unsigned deepVarNum, int deepVarVal);
2149
2150     // Create a copy of `tree`, optionally adding specifed flags, and optionally mapping uses of local
2151     // `varNum` to int constants with value `varVal`.
2152     GenTree* gtCloneExpr(GenTree* tree, unsigned addFlags = 0, unsigned varNum = (unsigned)-1, int varVal = 0)
2153     {
2154         return gtCloneExpr(tree, addFlags, varNum, varVal, varNum, varVal);
2155     }
2156
2157     GenTree* gtReplaceTree(GenTree* stmt, GenTree* tree, GenTree* replacementTree);
2158
2159     void gtUpdateSideEffects(GenTree* stmt, GenTree* tree);
2160
2161     void gtUpdateTreeAncestorsSideEffects(GenTree* tree);
2162
2163     void gtUpdateStmtSideEffects(GenTree* stmt);
2164
2165     void gtUpdateNodeSideEffects(GenTree* tree);
2166
2167     void gtUpdateNodeOperSideEffects(GenTree* tree);
2168
2169     // Returns "true" iff the complexity (not formally defined, but first interpretation
2170     // is #of nodes in subtree) of "tree" is greater than "limit".
2171     // (This is somewhat redundant with the "gtCostEx/gtCostSz" fields, but can be used
2172     // before they have been set.)
2173     bool gtComplexityExceeds(GenTree** tree, unsigned limit);
2174
2175     bool gtCompareTree(GenTree* op1, GenTree* op2);
2176
2177     GenTree* gtReverseCond(GenTree* tree);
2178
2179     bool gtHasRef(GenTree* tree, ssize_t lclNum, bool defOnly);
2180
2181     bool gtHasLocalsWithAddrOp(GenTree* tree);
2182
2183     unsigned gtSetListOrder(GenTree* list, bool regs, bool isListCallArgs);
2184
2185     void gtWalkOp(GenTree** op1, GenTree** op2, GenTree* base, bool constOnly);
2186
2187 #ifdef DEBUG
2188     unsigned gtHashValue(GenTree* tree);
2189
2190     GenTree* gtWalkOpEffectiveVal(GenTree* op);
2191 #endif
2192
2193     void gtPrepareCost(GenTree* tree);
2194     bool gtIsLikelyRegVar(GenTree* tree);
2195
2196     unsigned gtSetEvalOrderAndRestoreFPstkLevel(GenTree* tree);
2197
2198     // Returns true iff the secondNode can be swapped with firstNode.
2199     bool gtCanSwapOrder(GenTree* firstNode, GenTree* secondNode);
2200
2201     unsigned gtSetEvalOrder(GenTree* tree);
2202
2203 #if FEATURE_STACK_FP_X87
2204     bool gtFPstLvlRedo;
2205     void gtComputeFPlvls(GenTree* tree);
2206 #endif // FEATURE_STACK_FP_X87
2207
2208     void gtSetStmtInfo(GenTree* stmt);
2209
2210     // Returns "true" iff "node" has any of the side effects in "flags".
2211     bool gtNodeHasSideEffects(GenTree* node, unsigned flags);
2212
2213     // Returns "true" iff "tree" or its (transitive) children have any of the side effects in "flags".
2214     bool gtTreeHasSideEffects(GenTree* tree, unsigned flags);
2215
2216     // Appends 'expr' in front of 'list'
2217     //    'list' will typically start off as 'nullptr'
2218     //    when 'list' is non-null a GT_COMMA node is used to insert 'expr'
2219     GenTree* gtBuildCommaList(GenTree* list, GenTree* expr);
2220
2221     void gtExtractSideEffList(GenTree*  expr,
2222                               GenTree** pList,
2223                               unsigned  flags      = GTF_SIDE_EFFECT,
2224                               bool      ignoreRoot = false);
2225
2226     GenTree* gtGetThisArg(GenTreeCall* call);
2227
2228     // Static fields of struct types (and sometimes the types that those are reduced to) are represented by having the
2229     // static field contain an object pointer to the boxed struct.  This simplifies the GC implementation...but
2230     // complicates the JIT somewhat.  This predicate returns "true" iff a node with type "fieldNodeType", representing
2231     // the given "fldHnd", is such an object pointer.
2232     bool gtIsStaticFieldPtrToBoxedStruct(var_types fieldNodeType, CORINFO_FIELD_HANDLE fldHnd);
2233
2234     // Return true if call is a recursive call; return false otherwise.
2235     // Note when inlining, this looks for calls back to the root method.
2236     bool gtIsRecursiveCall(GenTreeCall* call)
2237     {
2238         return gtIsRecursiveCall(call->gtCallMethHnd);
2239     }
2240
2241     bool gtIsRecursiveCall(CORINFO_METHOD_HANDLE callMethodHandle)
2242     {
2243         return (callMethodHandle == impInlineRoot()->info.compMethodHnd);
2244     }
2245
2246     //-------------------------------------------------------------------------
2247
2248     GenTree* gtFoldExpr(GenTree* tree);
2249     GenTree*
2250 #ifdef __clang__
2251         // TODO-Amd64-Unix: Remove this when the clang optimizer is fixed and/or the method implementation is
2252         // refactored in a simpler code. This is a workaround for a bug in the clang-3.5 optimizer. The issue is that in
2253         // release build the optimizer is mistyping (or just wrongly decides to use 32 bit operation for a corner case
2254         // of MIN_LONG) the args of the (ltemp / lval2) to int (it does a 32 bit div operation instead of 64 bit) - see
2255         // the implementation of the method in gentree.cpp. For the case of lval1 and lval2 equal to MIN_LONG
2256         // (0x8000000000000000) this results in raising a SIGFPE. The method implementation is rather complex. Disable
2257         // optimizations for now.
2258         __attribute__((optnone))
2259 #endif // __clang__
2260         gtFoldExprConst(GenTree* tree);
2261     GenTree* gtFoldExprSpecial(GenTree* tree);
2262     GenTree* gtFoldExprCompare(GenTree* tree);
2263     GenTree* gtFoldExprCall(GenTreeCall* call);
2264     GenTree* gtFoldTypeCompare(GenTree* tree);
2265     GenTree* gtFoldTypeEqualityCall(CorInfoIntrinsics methodID, GenTree* op1, GenTree* op2);
2266
2267     // Options to control behavior of gtTryRemoveBoxUpstreamEffects
2268     enum BoxRemovalOptions
2269     {
2270         BR_REMOVE_AND_NARROW, // remove effects, minimize remaining work, return possibly narrowed source tree
2271         BR_REMOVE_AND_NARROW_WANT_TYPE_HANDLE, // remove effects and minimize remaining work, return type handle tree
2272         BR_REMOVE_BUT_NOT_NARROW,              // remove effects, return original source tree
2273         BR_DONT_REMOVE,                        // check if removal is possible, return copy source tree
2274         BR_DONT_REMOVE_WANT_TYPE_HANDLE,       // check if removal is possible, return type handle tree
2275         BR_MAKE_LOCAL_COPY                     // revise box to copy to temp local and return local's address
2276     };
2277
2278     GenTree* gtTryRemoveBoxUpstreamEffects(GenTree* tree, BoxRemovalOptions options = BR_REMOVE_AND_NARROW);
2279     GenTree* gtOptimizeEnumHasFlag(GenTree* thisOp, GenTree* flagOp);
2280
2281     //-------------------------------------------------------------------------
2282     // Get the handle, if any.
2283     CORINFO_CLASS_HANDLE gtGetStructHandleIfPresent(GenTree* tree);
2284     // Get the handle, and assert if not found.
2285     CORINFO_CLASS_HANDLE gtGetStructHandle(GenTree* tree);
2286     // Get the handle for a ref type.
2287     CORINFO_CLASS_HANDLE gtGetClassHandle(GenTree* tree, bool* isExact, bool* isNonNull);
2288
2289 //-------------------------------------------------------------------------
2290 // Functions to display the trees
2291
2292 #ifdef DEBUG
2293     void gtDispNode(GenTree* tree, IndentStack* indentStack, __in_z const char* msg, bool isLIR);
2294
2295     void gtDispVN(GenTree* tree);
2296     void gtDispConst(GenTree* tree);
2297     void gtDispLeaf(GenTree* tree, IndentStack* indentStack);
2298     void gtDispNodeName(GenTree* tree);
2299     void gtDispRegVal(GenTree* tree);
2300
2301     enum IndentInfo
2302     {
2303         IINone,
2304         IIArc,
2305         IIArcTop,
2306         IIArcBottom,
2307         IIEmbedded,
2308         IIError,
2309         IndentInfoCount
2310     };
2311     void gtDispChild(GenTree*             child,
2312                      IndentStack*         indentStack,
2313                      IndentInfo           arcType,
2314                      __in_opt const char* msg     = nullptr,
2315                      bool                 topOnly = false);
2316     void gtDispTree(GenTree*             tree,
2317                     IndentStack*         indentStack = nullptr,
2318                     __in_opt const char* msg         = nullptr,
2319                     bool                 topOnly     = false,
2320                     bool                 isLIR       = false);
2321     void gtGetLclVarNameInfo(unsigned lclNum, const char** ilKindOut, const char** ilNameOut, unsigned* ilNumOut);
2322     int gtGetLclVarName(unsigned lclNum, char* buf, unsigned buf_remaining);
2323     char* gtGetLclVarName(unsigned lclNum);
2324     void gtDispLclVar(unsigned varNum, bool padForBiggestDisp = true);
2325     void gtDispTreeList(GenTree* tree, IndentStack* indentStack = nullptr);
2326     void gtGetArgMsg(GenTreeCall* call, GenTree* arg, unsigned argNum, int listCount, char* bufp, unsigned bufLength);
2327     void gtGetLateArgMsg(GenTreeCall* call, GenTree* arg, int argNum, int listCount, char* bufp, unsigned bufLength);
2328     void gtDispArgList(GenTreeCall* call, IndentStack* indentStack);
2329     void gtDispFieldSeq(FieldSeqNode* pfsn);
2330
2331     void gtDispRange(LIR::ReadOnlyRange const& range);
2332
2333     void gtDispTreeRange(LIR::Range& containingRange, GenTree* tree);
2334
2335     void gtDispLIRNode(GenTree* node, const char* prefixMsg = nullptr);
2336 #endif
2337
2338     // For tree walks
2339
2340     enum fgWalkResult
2341     {
2342         WALK_CONTINUE,
2343         WALK_SKIP_SUBTREES,
2344         WALK_ABORT
2345     };
2346     struct fgWalkData;
2347     typedef fgWalkResult(fgWalkPreFn)(GenTree** pTree, fgWalkData* data);
2348     typedef fgWalkResult(fgWalkPostFn)(GenTree** pTree, fgWalkData* data);
2349
2350 #ifdef DEBUG
2351     static fgWalkPreFn gtAssertColonCond;
2352 #endif
2353     static fgWalkPreFn gtMarkColonCond;
2354     static fgWalkPreFn gtClearColonCond;
2355
2356     GenTree** gtFindLink(GenTree* stmt, GenTree* node);
2357     bool gtHasCatchArg(GenTree* tree);
2358     bool gtHasUnmanagedCall(GenTree* tree);
2359
2360     typedef ArrayStack<GenTree*> GenTreeStack;
2361
2362     static bool gtHasCallOnStack(GenTreeStack* parentStack);
2363     void gtCheckQuirkAddrExposedLclVar(GenTree* argTree, GenTreeStack* parentStack);
2364
2365 //=========================================================================
2366 // BasicBlock functions
2367 #ifdef DEBUG
2368     // This is a debug flag we will use to assert when creating block during codegen
2369     // as this interferes with procedure splitting. If you know what you're doing, set
2370     // it to true before creating the block. (DEBUG only)
2371     bool fgSafeBasicBlockCreation;
2372 #endif
2373
2374     BasicBlock* bbNewBasicBlock(BBjumpKinds jumpKind);
2375
2376     /*
2377     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2378     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2379     XX                                                                           XX
2380     XX                           LclVarsInfo                                     XX
2381     XX                                                                           XX
2382     XX   The variables to be used by the code generator.                         XX
2383     XX                                                                           XX
2384     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2385     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2386     */
2387
2388     //
2389     // For both PROMOTION_TYPE_NONE and PROMOTION_TYPE_DEPENDENT the struct will
2390     // be placed in the stack frame and it's fields must be laid out sequentially.
2391     //
2392     // For PROMOTION_TYPE_INDEPENDENT each of the struct's fields is replaced by
2393     //  a local variable that can be enregistered or placed in the stack frame.
2394     //  The fields do not need to be laid out sequentially
2395     //
2396     enum lvaPromotionType
2397     {
2398         PROMOTION_TYPE_NONE,        // The struct local is not promoted
2399         PROMOTION_TYPE_INDEPENDENT, // The struct local is promoted,
2400                                     //   and its field locals are independent of its parent struct local.
2401         PROMOTION_TYPE_DEPENDENT    // The struct local is promoted,
2402                                     //   but its field locals depend on its parent struct local.
2403     };
2404
2405     static int __cdecl RefCntCmp(const void* op1, const void* op2);
2406     static int __cdecl WtdRefCntCmp(const void* op1, const void* op2);
2407
2408     /*****************************************************************************/
2409
2410     enum FrameLayoutState
2411     {
2412         NO_FRAME_LAYOUT,
2413         INITIAL_FRAME_LAYOUT,
2414         PRE_REGALLOC_FRAME_LAYOUT,
2415         REGALLOC_FRAME_LAYOUT,
2416         TENTATIVE_FRAME_LAYOUT,
2417         FINAL_FRAME_LAYOUT
2418     };
2419
2420 public:
2421     bool     lvaRefCountingStarted; // Set to true when we have started counting the local vars
2422     bool     lvaLocalVarRefCounted; // Set to true after we have called lvaMarkLocalVars()
2423     bool     lvaSortAgain;          // true: We need to sort the lvaTable
2424     bool     lvaTrackedFixed;       // true: We cannot add new 'tracked' variable
2425     unsigned lvaCount;              // total number of locals
2426
2427     unsigned   lvaRefCount; // total number of references to locals
2428     LclVarDsc* lvaTable;    // variable descriptor table
2429     unsigned   lvaTableCnt; // lvaTable size (>= lvaCount)
2430
2431     LclVarDsc** lvaRefSorted; // table sorted by refcount
2432
2433     unsigned short lvaTrackedCount;       // actual # of locals being tracked
2434     unsigned lvaTrackedCountInSizeTUnits; // min # of size_t's sufficient to hold a bit for all the locals being tracked
2435
2436 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
2437     // Only for AMD64 System V cache the first caller stack homed argument.
2438     unsigned lvaFirstStackIncomingArgNum; // First argument with stack slot in the caller.
2439 #endif                                    // !FEATURE_UNIX_AMD64_STRUCT_PASSING
2440
2441 #ifdef DEBUG
2442     VARSET_TP lvaTrackedVars; // set of tracked variables
2443 #endif
2444 #ifndef _TARGET_64BIT_
2445     VARSET_TP lvaLongVars; // set of long (64-bit) variables
2446 #endif
2447     VARSET_TP lvaFloatVars; // set of floating-point (32-bit and 64-bit) variables
2448
2449     unsigned lvaCurEpoch; // VarSets are relative to a specific set of tracked var indices.
2450                           // It that changes, this changes.  VarSets from different epochs
2451                           // cannot be meaningfully combined.
2452
2453     unsigned GetCurLVEpoch()
2454     {
2455         return lvaCurEpoch;
2456     }
2457
2458     // reverse map of tracked number to var number
2459     unsigned lvaTrackedToVarNum[lclMAX_TRACKED];
2460
2461 #ifdef LEGACY_BACKEND
2462     // variable interference graph
2463     VARSET_TP lvaVarIntf[lclMAX_TRACKED];
2464
2465     // variable preference graph
2466     VARSET_TP lvaVarPref[lclMAX_TRACKED];
2467 #endif
2468 #if DOUBLE_ALIGN
2469 #ifdef DEBUG
2470     // # of procs compiled a with double-aligned stack
2471     static unsigned s_lvaDoubleAlignedProcsCount;
2472 #endif
2473 #endif
2474
2475     // Getters and setters for address-exposed and do-not-enregister local var properties.
2476     bool lvaVarAddrExposed(unsigned varNum);
2477     void lvaSetVarAddrExposed(unsigned varNum);
2478     bool lvaVarDoNotEnregister(unsigned varNum);
2479 #ifdef DEBUG
2480     // Reasons why we can't enregister.  Some of these correspond to debug properties of local vars.
2481     enum DoNotEnregisterReason
2482     {
2483         DNER_AddrExposed,
2484         DNER_IsStruct,
2485         DNER_LocalField,
2486         DNER_VMNeedsStackAddr,
2487         DNER_LiveInOutOfHandler,
2488         DNER_LiveAcrossUnmanagedCall,
2489         DNER_BlockOp,     // Is read or written via a block operation that explicitly takes the address.
2490         DNER_IsStructArg, // Is a struct passed as an argument in a way that requires a stack location.
2491         DNER_DepField,    // It is a field of a dependently promoted struct
2492         DNER_NoRegVars,   // opts.compFlags & CLFLG_REGVAR is not set
2493         DNER_MinOptsGC,   // It is a GC Ref and we are compiling MinOpts
2494 #if !defined(LEGACY_BACKEND) && !defined(_TARGET_64BIT_)
2495         DNER_LongParamField, // It is a decomposed field of a long parameter.
2496 #endif
2497 #ifdef JIT32_GCENCODER
2498         DNER_PinningRef,
2499 #endif
2500     };
2501 #endif
2502     void lvaSetVarDoNotEnregister(unsigned varNum DEBUGARG(DoNotEnregisterReason reason));
2503
2504     unsigned lvaVarargsHandleArg;
2505 #ifdef _TARGET_X86_
2506     unsigned lvaVarargsBaseOfStkArgs; // Pointer (computed based on incoming varargs handle) to the start of the stack
2507                                       // arguments
2508 #endif                                // _TARGET_X86_
2509
2510     unsigned lvaInlinedPInvokeFrameVar; // variable representing the InlinedCallFrame
2511     unsigned lvaReversePInvokeFrameVar; // variable representing the reverse PInvoke frame
2512 #if FEATURE_FIXED_OUT_ARGS
2513     unsigned lvaPInvokeFrameRegSaveVar; // variable representing the RegSave for PInvoke inlining.
2514 #endif
2515     unsigned lvaMonAcquired; // boolean variable introduced into in synchronized methods
2516                              // that tracks whether the lock has been taken
2517
2518     unsigned lvaArg0Var; // The lclNum of arg0. Normally this will be info.compThisArg.
2519                          // However, if there is a "ldarga 0" or "starg 0" in the IL,
2520                          // we will redirect all "ldarg(a) 0" and "starg 0" to this temp.
2521
2522     unsigned lvaInlineeReturnSpillTemp; // The temp to spill the non-VOID return expression
2523                                         // in case there are multiple BBJ_RETURN blocks in the inlinee
2524                                         // or if the inlinee has GC ref locals.
2525
2526 #if FEATURE_FIXED_OUT_ARGS
2527     unsigned            lvaOutgoingArgSpaceVar;  // dummy TYP_LCLBLK var for fixed outgoing argument space
2528     PhasedVar<unsigned> lvaOutgoingArgSpaceSize; // size of fixed outgoing argument space
2529 #endif                                           // FEATURE_FIXED_OUT_ARGS
2530
2531 #ifdef _TARGET_ARM_
2532     // On architectures whose ABIs allow structs to be passed in registers, struct promotion will sometimes
2533     // require us to "rematerialize" a struct from it's separate constituent field variables.  Packing several sub-word
2534     // field variables into an argument register is a hard problem.  It's easier to reserve a word of memory into which
2535     // such field can be copied, after which the assembled memory word can be read into the register.  We will allocate
2536     // this variable to be this scratch word whenever struct promotion occurs.
2537     unsigned lvaPromotedStructAssemblyScratchVar;
2538 #endif // _TARGET_ARM_
2539
2540 #ifdef DEBUG
2541     unsigned lvaReturnEspCheck; // confirms ESP not corrupted on return
2542     unsigned lvaCallEspCheck;   // confirms ESP not corrupted after a call
2543 #endif
2544
2545     unsigned lvaGenericsContextUseCount;
2546
2547     bool lvaKeepAliveAndReportThis(); // Synchronized instance method of a reference type, or
2548                                       // CORINFO_GENERICS_CTXT_FROM_THIS?
2549     bool lvaReportParamTypeArg();     // Exceptions and CORINFO_GENERICS_CTXT_FROM_PARAMTYPEARG?
2550
2551 //-------------------------------------------------------------------------
2552 // All these frame offsets are inter-related and must be kept in sync
2553
2554 #if !FEATURE_EH_FUNCLETS
2555     // This is used for the callable handlers
2556     unsigned lvaShadowSPslotsVar; // TYP_BLK variable for all the shadow SP slots
2557 #endif                            // FEATURE_EH_FUNCLETS
2558
2559     int lvaCachedGenericContextArgOffs;
2560     int lvaCachedGenericContextArgOffset(); // For CORINFO_CALLCONV_PARAMTYPE and if generic context is passed as
2561                                             // THIS pointer
2562
2563     unsigned lvaLocAllocSPvar; // variable which has the result of the last alloca/localloc
2564
2565     unsigned lvaNewObjArrayArgs; // variable with arguments for new MD array helper
2566
2567     // TODO-Review: Prior to reg predict we reserve 24 bytes for Spill temps.
2568     //              after the reg predict we will use a computed maxTmpSize
2569     //              which is based upon the number of spill temps predicted by reg predict
2570     //              All this is necessary because if we under-estimate the size of the spill
2571     //              temps we could fail when encoding instructions that reference stack offsets for ARM.
2572     //
2573     // Pre codegen max spill temp size.
2574     static const unsigned MAX_SPILL_TEMP_SIZE = 24;
2575
2576     //-------------------------------------------------------------------------
2577
2578     unsigned lvaGetMaxSpillTempSize();
2579 #ifdef _TARGET_ARM_
2580     bool lvaIsPreSpilled(unsigned lclNum, regMaskTP preSpillMask);
2581 #endif // _TARGET_ARM_
2582     void lvaAssignFrameOffsets(FrameLayoutState curState);
2583     void lvaFixVirtualFrameOffsets();
2584
2585 #ifndef LEGACY_BACKEND
2586     void lvaUpdateArgsWithInitialReg();
2587 #endif // !LEGACY_BACKEND
2588
2589     void lvaAssignVirtualFrameOffsetsToArgs();
2590 #ifdef UNIX_AMD64_ABI
2591     int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs, int* callerArgOffset);
2592 #else  // !UNIX_AMD64_ABI
2593     int lvaAssignVirtualFrameOffsetToArg(unsigned lclNum, unsigned argSize, int argOffs);
2594 #endif // !UNIX_AMD64_ABI
2595     void lvaAssignVirtualFrameOffsetsToLocals();
2596     int lvaAllocLocalAndSetVirtualOffset(unsigned lclNum, unsigned size, int stkOffs);
2597 #ifdef _TARGET_AMD64_
2598     // Returns true if compCalleeRegsPushed (including RBP if used as frame pointer) is even.
2599     bool lvaIsCalleeSavedIntRegCountEven();
2600 #endif
2601     void lvaAlignFrame();
2602     void lvaAssignFrameOffsetsToPromotedStructs();
2603     int lvaAllocateTemps(int stkOffs, bool mustDoubleAlign);
2604
2605 #ifdef DEBUG
2606     void lvaDumpRegLocation(unsigned lclNum);
2607     void lvaDumpFrameLocation(unsigned lclNum);
2608     void lvaDumpEntry(unsigned lclNum, FrameLayoutState curState, size_t refCntWtdWidth = 6);
2609     void lvaTableDump(FrameLayoutState curState = NO_FRAME_LAYOUT); // NO_FRAME_LAYOUT means use the current frame
2610                                                                     // layout state defined by lvaDoneFrameLayout
2611 #endif
2612
2613 // Limit frames size to 1GB. The maximum is 2GB in theory - make it intentionally smaller
2614 // to avoid bugs from borderline cases.
2615 #define MAX_FrameSize 0x3FFFFFFF
2616     void lvaIncrementFrameSize(unsigned size);
2617
2618     unsigned lvaFrameSize(FrameLayoutState curState);
2619
2620     // Returns the caller-SP-relative offset for the SP/FP relative offset determined by FP based.
2621     int lvaToCallerSPRelativeOffset(int offs, bool isFpBased);
2622
2623     // Returns the caller-SP-relative offset for the local variable "varNum."
2624     int lvaGetCallerSPRelativeOffset(unsigned varNum);
2625
2626     // Returns the SP-relative offset for the local variable "varNum". Illegal to ask this for functions with localloc.
2627     int lvaGetSPRelativeOffset(unsigned varNum);
2628
2629     int lvaToInitialSPRelativeOffset(unsigned offset, bool isFpBased);
2630     int lvaGetInitialSPRelativeOffset(unsigned varNum);
2631
2632     //------------------------ For splitting types ----------------------------
2633
2634     void lvaInitTypeRef();
2635
2636     void lvaInitArgs(InitVarDscInfo* varDscInfo);
2637     void lvaInitThisPtr(InitVarDscInfo* varDscInfo);
2638     void lvaInitRetBuffArg(InitVarDscInfo* varDscInfo);
2639     void lvaInitUserArgs(InitVarDscInfo* varDscInfo);
2640     void lvaInitGenericsCtxt(InitVarDscInfo* varDscInfo);
2641     void lvaInitVarArgsHandle(InitVarDscInfo* varDscInfo);
2642
2643     void lvaInitVarDsc(LclVarDsc*              varDsc,
2644                        unsigned                varNum,
2645                        CorInfoType             corInfoType,
2646                        CORINFO_CLASS_HANDLE    typeHnd,
2647                        CORINFO_ARG_LIST_HANDLE varList,
2648                        CORINFO_SIG_INFO*       varSig);
2649
2650     static unsigned lvaTypeRefMask(var_types type);
2651
2652     var_types lvaGetActualType(unsigned lclNum);
2653     var_types lvaGetRealType(unsigned lclNum);
2654
2655     //-------------------------------------------------------------------------
2656
2657     void lvaInit();
2658
2659     unsigned lvaLclSize(unsigned varNum);
2660     unsigned lvaLclExactSize(unsigned varNum);
2661
2662     bool lvaLclVarRefs(GenTree* tree, GenTree** findPtr, varRefKinds* refsPtr, void* result);
2663
2664     // Call lvaLclVarRefs on "true"; accumulate "*result" into whichever of
2665     // "allVars" and "trkdVars" is indiated by the nullness of "findPtr"; return
2666     // the return result.
2667     bool lvaLclVarRefsAccum(
2668         GenTree* tree, GenTree** findPtr, varRefKinds* refsPtr, ALLVARSET_TP* allVars, VARSET_TP* trkdVars);
2669
2670     // If "findPtr" is non-NULL, assumes "result" is an "ALLVARSET_TP*", and
2671     // (destructively) unions "allVars" into "*result".  Otherwise, assumes "result" is a "VARSET_TP*",
2672     // and (destructively) unions "trkedVars" into "*result".
2673     void lvaLclVarRefsAccumIntoRes(GenTree**           findPtr,
2674                                    void*               result,
2675                                    ALLVARSET_VALARG_TP allVars,
2676                                    VARSET_VALARG_TP    trkdVars);
2677
2678     bool lvaHaveManyLocals() const;
2679
2680     unsigned lvaGrabTemp(bool shortLifetime DEBUGARG(const char* reason));
2681     unsigned lvaGrabTemps(unsigned cnt DEBUGARG(const char* reason));
2682     unsigned lvaGrabTempWithImplicitUse(bool shortLifetime DEBUGARG(const char* reason));
2683
2684     void lvaSortOnly();
2685     void lvaSortByRefCount();
2686     void lvaDumpRefCounts();
2687
2688     void lvaMarkLocalVars(BasicBlock* block);
2689
2690     void lvaMarkLocalVars(); // Local variable ref-counting
2691
2692     void lvaAllocOutgoingArgSpaceVar(); // Set up lvaOutgoingArgSpaceVar
2693
2694     VARSET_VALRET_TP lvaStmtLclMask(GenTree* stmt);
2695
2696     void lvaIncRefCnts(GenTree* tree);
2697     void lvaDecRefCnts(GenTree* tree);
2698
2699     void lvaDecRefCnts(BasicBlock* basicBlock, GenTree* tree);
2700     void lvaRecursiveDecRefCounts(GenTree* tree);
2701     void lvaRecursiveIncRefCounts(GenTree* tree);
2702
2703 #ifdef DEBUG
2704     struct lvaStressLclFldArgs
2705     {
2706         Compiler* m_pCompiler;
2707         bool      m_bFirstPass;
2708     };
2709
2710     static fgWalkPreFn lvaStressLclFldCB;
2711     void               lvaStressLclFld();
2712
2713     void lvaDispVarSet(VARSET_VALARG_TP set, VARSET_VALARG_TP allVars);
2714     void lvaDispVarSet(VARSET_VALARG_TP set);
2715
2716 #endif
2717
2718 #ifdef _TARGET_ARM_
2719     int lvaFrameAddress(int varNum, bool mustBeFPBased, regNumber* pBaseReg, int addrModeOffset);
2720 #else
2721     int lvaFrameAddress(int varNum, bool* pFPbased);
2722 #endif
2723
2724     bool lvaIsParameter(unsigned varNum);
2725     bool lvaIsRegArgument(unsigned varNum);
2726     BOOL lvaIsOriginalThisArg(unsigned varNum); // Is this varNum the original this argument?
2727     BOOL lvaIsOriginalThisReadOnly();           // return TRUE if there is no place in the code
2728                                                 // that writes to arg0
2729
2730     // Struct parameters that are passed by reference are marked as both lvIsParam and lvIsTemp
2731     // (this is an overload of lvIsTemp because there are no temp parameters).
2732     // For x64 this is 3, 5, 6, 7, >8 byte structs that are passed by reference.
2733     // For ARM64, this is structs larger than 16 bytes that are passed by reference.
2734     bool lvaIsImplicitByRefLocal(unsigned varNum)
2735     {
2736 #if defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2737         LclVarDsc* varDsc = &(lvaTable[varNum]);
2738         if (varDsc->lvIsParam && varDsc->lvIsTemp)
2739         {
2740             assert(varTypeIsStruct(varDsc) || (varDsc->lvType == TYP_BYREF));
2741             return true;
2742         }
2743 #endif // defined(_TARGET_AMD64_) || defined(_TARGET_ARM64_)
2744         return false;
2745     }
2746
2747     // Returns true if this local var is a multireg struct
2748     bool lvaIsMultiregStruct(LclVarDsc* varDsc);
2749
2750     // If the local is a TYP_STRUCT, get/set a class handle describing it
2751     CORINFO_CLASS_HANDLE lvaGetStruct(unsigned varNum);
2752     void lvaSetStruct(unsigned varNum, CORINFO_CLASS_HANDLE typeHnd, bool unsafeValueClsCheck, bool setTypeInfo = true);
2753
2754     // If the local is TYP_REF, set or update the associated class information.
2755     void lvaSetClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
2756     void lvaSetClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
2757     void lvaUpdateClass(unsigned varNum, CORINFO_CLASS_HANDLE clsHnd, bool isExact = false);
2758     void lvaUpdateClass(unsigned varNum, GenTree* tree, CORINFO_CLASS_HANDLE stackHandle = nullptr);
2759
2760 #define MAX_NumOfFieldsInPromotableStruct 4 // Maximum number of fields in promotable struct
2761
2762     // Info about struct fields
2763     struct lvaStructFieldInfo
2764     {
2765         CORINFO_FIELD_HANDLE fldHnd;
2766         unsigned char        fldOffset;
2767         unsigned char        fldOrdinal;
2768         var_types            fldType;
2769         unsigned             fldSize;
2770         CORINFO_CLASS_HANDLE fldTypeHnd;
2771     };
2772
2773     // Info about struct to be promoted.
2774     struct lvaStructPromotionInfo
2775     {
2776         CORINFO_CLASS_HANDLE typeHnd;
2777         bool                 canPromote;
2778         bool                 requiresScratchVar;
2779         bool                 containsHoles;
2780         bool                 customLayout;
2781         unsigned char        fieldCnt;
2782         lvaStructFieldInfo   fields[MAX_NumOfFieldsInPromotableStruct];
2783
2784         lvaStructPromotionInfo()
2785             : typeHnd(nullptr), canPromote(false), requiresScratchVar(false), containsHoles(false), customLayout(false)
2786         {
2787         }
2788     };
2789
2790     static int __cdecl lvaFieldOffsetCmp(const void* field1, const void* field2);
2791     void lvaCanPromoteStructType(CORINFO_CLASS_HANDLE    typeHnd,
2792                                  lvaStructPromotionInfo* StructPromotionInfo,
2793                                  bool                    sortFields);
2794     void lvaCanPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2795     bool lvaShouldPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* structPromotionInfo);
2796     void lvaPromoteStructVar(unsigned lclNum, lvaStructPromotionInfo* StructPromotionInfo);
2797 #if !defined(_TARGET_64BIT_)
2798     void lvaPromoteLongVars();
2799 #endif // !defined(_TARGET_64BIT_)
2800     unsigned lvaGetFieldLocal(LclVarDsc* varDsc, unsigned int fldOffset);
2801     lvaPromotionType lvaGetPromotionType(const LclVarDsc* varDsc);
2802     lvaPromotionType lvaGetPromotionType(unsigned varNum);
2803     lvaPromotionType lvaGetParentPromotionType(const LclVarDsc* varDsc);
2804     lvaPromotionType lvaGetParentPromotionType(unsigned varNum);
2805     bool lvaIsFieldOfDependentlyPromotedStruct(const LclVarDsc* varDsc);
2806     bool lvaIsGCTracked(const LclVarDsc* varDsc);
2807
2808 #if defined(FEATURE_SIMD)
2809     bool lvaMapSimd12ToSimd16(const LclVarDsc* varDsc)
2810     {
2811         assert(varDsc->lvType == TYP_SIMD12);
2812         assert(varDsc->lvExactSize == 12);
2813
2814 #if defined(_TARGET_64BIT_)
2815         assert(varDsc->lvSize() == 16);
2816 #endif // defined(_TARGET_64BIT_)
2817
2818         // We make local variable SIMD12 types 16 bytes instead of just 12. lvSize()
2819         // already does this calculation. However, we also need to prevent mapping types if the var is a
2820         // dependently promoted struct field, which must remain its exact size within its parent struct.
2821         // However, we don't know this until late, so we may have already pretended the field is bigger
2822         // before that.
2823         if ((varDsc->lvSize() == 16) && !lvaIsFieldOfDependentlyPromotedStruct(varDsc))
2824         {
2825             return true;
2826         }
2827         else
2828         {
2829             return false;
2830         }
2831     }
2832 #endif // defined(FEATURE_SIMD)
2833
2834     BYTE* lvaGetGcLayout(unsigned varNum);
2835     bool lvaTypeIsGC(unsigned varNum);
2836     unsigned lvaGSSecurityCookie; // LclVar number
2837     bool     lvaTempsHaveLargerOffsetThanVars();
2838
2839     unsigned lvaSecurityObject;  // variable representing the security object on the stack
2840     unsigned lvaStubArgumentVar; // variable representing the secret stub argument coming in EAX
2841
2842 #if FEATURE_EH_FUNCLETS
2843     unsigned lvaPSPSym; // variable representing the PSPSym
2844 #endif
2845
2846     InlineInfo*     impInlineInfo;
2847     InlineStrategy* m_inlineStrategy;
2848
2849     // The Compiler* that is the root of the inlining tree of which "this" is a member.
2850     Compiler* impInlineRoot();
2851
2852 #if defined(DEBUG) || defined(INLINE_DATA)
2853     unsigned __int64 getInlineCycleCount()
2854     {
2855         return m_compCycles;
2856     }
2857 #endif // defined(DEBUG) || defined(INLINE_DATA)
2858
2859     bool fgNoStructPromotion;      // Set to TRUE to turn off struct promotion for this method.
2860     bool fgNoStructParamPromotion; // Set to TRUE to turn off struct promotion for parameters this method.
2861
2862     //=========================================================================
2863     //                          PROTECTED
2864     //=========================================================================
2865
2866 protected:
2867 //---------------- Local variable ref-counting ----------------------------
2868
2869 #if ASSERTION_PROP
2870     BasicBlock* lvaMarkRefsCurBlock;
2871     GenTree*    lvaMarkRefsCurStmt;
2872 #endif
2873     BasicBlock::weight_t lvaMarkRefsWeight;
2874
2875     void lvaMarkLclRefs(GenTree* tree);
2876
2877     bool IsDominatedByExceptionalEntry(BasicBlock* block);
2878     void SetVolatileHint(LclVarDsc* varDsc);
2879
2880     // Keeps the mapping from SSA #'s to VN's for the implicit memory variables.
2881     PerSsaArray lvMemoryPerSsaData;
2882     unsigned    lvMemoryNumSsaNames;
2883
2884 public:
2885     // Returns the address of the per-Ssa data for memory at the given ssaNum (which is required
2886     // not to be the SsaConfig::RESERVED_SSA_NUM, which indicates that the variable is
2887     // not an SSA variable).
2888     LclSsaVarDsc* GetMemoryPerSsaData(unsigned ssaNum)
2889     {
2890         assert(ssaNum != SsaConfig::RESERVED_SSA_NUM);
2891         assert(SsaConfig::RESERVED_SSA_NUM == 0);
2892         ssaNum--;
2893         assert(ssaNum < lvMemoryNumSsaNames);
2894         return &lvMemoryPerSsaData.GetRef(ssaNum);
2895     }
2896
2897     /*
2898     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2899     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2900     XX                                                                           XX
2901     XX                           Importer                                        XX
2902     XX                                                                           XX
2903     XX   Imports the given method and converts it to semantic trees              XX
2904     XX                                                                           XX
2905     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2906     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
2907     */
2908
2909 public:
2910     void impInit();
2911
2912     void impImport(BasicBlock* method);
2913
2914     CORINFO_CLASS_HANDLE impGetRefAnyClass();
2915     CORINFO_CLASS_HANDLE impGetRuntimeArgumentHandle();
2916     CORINFO_CLASS_HANDLE impGetTypeHandleClass();
2917     CORINFO_CLASS_HANDLE impGetStringClass();
2918     CORINFO_CLASS_HANDLE impGetObjectClass();
2919
2920     // Returns underlying type of handles returned by ldtoken instruction
2921     inline var_types GetRuntimeHandleUnderlyingType()
2922     {
2923         // RuntimeTypeHandle is backed by raw pointer on CoreRT and by object reference on other runtimes
2924         return IsTargetAbi(CORINFO_CORERT_ABI) ? TYP_I_IMPL : TYP_REF;
2925     }
2926
2927     //=========================================================================
2928     //                          PROTECTED
2929     //=========================================================================
2930
2931 protected:
2932     //-------------------- Stack manipulation ---------------------------------
2933
2934     unsigned impStkSize; // Size of the full stack
2935
2936 #define SMALL_STACK_SIZE 16 // number of elements in impSmallStack
2937
2938     StackEntry impSmallStack[SMALL_STACK_SIZE]; // Use this array if possible
2939
2940     struct SavedStack // used to save/restore stack contents.
2941     {
2942         unsigned    ssDepth; // number of values on stack
2943         StackEntry* ssTrees; // saved tree values
2944     };
2945
2946     bool impIsPrimitive(CorInfoType type);
2947     bool impILConsumesAddr(const BYTE* codeAddr, CORINFO_METHOD_HANDLE fncHandle, CORINFO_MODULE_HANDLE scpHandle);
2948
2949     void impResolveToken(const BYTE* addr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CorInfoTokenKind kind);
2950
2951     void impPushOnStack(GenTree* tree, typeInfo ti);
2952     void        impPushNullObjRefOnStack();
2953     StackEntry  impPopStack();
2954     StackEntry& impStackTop(unsigned n = 0);
2955     unsigned impStackHeight();
2956
2957     void impSaveStackState(SavedStack* savePtr, bool copy);
2958     void impRestoreStackState(SavedStack* savePtr);
2959
2960     GenTree* impImportLdvirtftn(GenTree* thisPtr, CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2961
2962     void impImportAndPushBox(CORINFO_RESOLVED_TOKEN* pResolvedToken);
2963
2964     void impImportNewObjArray(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
2965
2966     bool impCanPInvokeInline();
2967     bool impCanPInvokeInlineCallSite(BasicBlock* block);
2968     void impCheckForPInvokeCall(
2969         GenTreeCall* call, CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* sig, unsigned mflags, BasicBlock* block);
2970     GenTreeCall* impImportIndirectCall(CORINFO_SIG_INFO* sig, IL_OFFSETX ilOffset = BAD_IL_OFFSET);
2971     void impPopArgsForUnmanagedCall(GenTree* call, CORINFO_SIG_INFO* sig);
2972
2973     void impInsertHelperCall(CORINFO_HELPER_DESC* helperCall);
2974     void impHandleAccessAllowed(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2975     void impHandleAccessAllowedInternal(CorInfoIsAccessAllowedResult result, CORINFO_HELPER_DESC* helperCall);
2976
2977     var_types impImportCall(OPCODE                  opcode,
2978                             CORINFO_RESOLVED_TOKEN* pResolvedToken,
2979                             CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call on a
2980                                                                                // type parameter?
2981                             GenTree*           newobjThis,
2982                             int                prefixFlags,
2983                             CORINFO_CALL_INFO* callInfo,
2984                             IL_OFFSET          rawILOffset);
2985
2986     void impDevirtualizeCall(GenTreeCall*            call,
2987                              CORINFO_METHOD_HANDLE*  method,
2988                              unsigned*               methodFlags,
2989                              CORINFO_CONTEXT_HANDLE* contextHandle,
2990                              CORINFO_CONTEXT_HANDLE* exactContextHandle);
2991
2992     CORINFO_CLASS_HANDLE impGetSpecialIntrinsicExactReturnType(CORINFO_METHOD_HANDLE specialIntrinsicHandle);
2993
2994     bool impMethodInfo_hasRetBuffArg(CORINFO_METHOD_INFO* methInfo);
2995
2996     GenTree* impFixupCallStructReturn(GenTreeCall* call, CORINFO_CLASS_HANDLE retClsHnd);
2997
2998     GenTree* impFixupStructReturnType(GenTree* op, CORINFO_CLASS_HANDLE retClsHnd);
2999
3000 #ifdef DEBUG
3001     var_types impImportJitTestLabelMark(int numArgs);
3002 #endif // DEBUG
3003
3004     GenTree* impInitClass(CORINFO_RESOLVED_TOKEN* pResolvedToken);
3005
3006     GenTree* impImportStaticReadOnlyField(void* fldAddr, var_types lclTyp);
3007
3008     GenTree* impImportStaticFieldAccess(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3009                                         CORINFO_ACCESS_FLAGS    access,
3010                                         CORINFO_FIELD_INFO*     pFieldInfo,
3011                                         var_types               lclTyp);
3012
3013     static void impBashVarAddrsToI(GenTree* tree1, GenTree* tree2 = nullptr);
3014
3015     GenTree* impImplicitIorI4Cast(GenTree* tree, var_types dstTyp);
3016
3017     GenTree* impImplicitR4orR8Cast(GenTree* tree, var_types dstTyp);
3018
3019     void impImportLeave(BasicBlock* block);
3020     void impResetLeaveBlock(BasicBlock* block, unsigned jmpAddr);
3021     GenTree* impIntrinsic(GenTree*                newobjThis,
3022                           CORINFO_CLASS_HANDLE    clsHnd,
3023                           CORINFO_METHOD_HANDLE   method,
3024                           CORINFO_SIG_INFO*       sig,
3025                           unsigned                methodFlags,
3026                           int                     memberRef,
3027                           bool                    readonlyCall,
3028                           bool                    tailCall,
3029                           CORINFO_RESOLVED_TOKEN* pContstrainedResolvedToken,
3030                           CORINFO_THIS_TRANSFORM  constraintCallThisTransform,
3031                           CorInfoIntrinsics*      pIntrinsicID,
3032                           bool*                   isSpecialIntrinsic = nullptr);
3033     GenTree* impMathIntrinsic(CORINFO_METHOD_HANDLE method,
3034                               CORINFO_SIG_INFO*     sig,
3035                               var_types             callType,
3036                               CorInfoIntrinsics     intrinsicID,
3037                               bool                  tailCall);
3038     NamedIntrinsic lookupNamedIntrinsic(CORINFO_METHOD_HANDLE method);
3039
3040 #ifdef FEATURE_HW_INTRINSICS
3041     GenTree* impHWIntrinsic(NamedIntrinsic        intrinsic,
3042                             CORINFO_METHOD_HANDLE method,
3043                             CORINFO_SIG_INFO*     sig,
3044                             bool                  mustExpand);
3045     GenTree* impUnsupportedHWIntrinsic(unsigned              helper,
3046                                        CORINFO_METHOD_HANDLE method,
3047                                        CORINFO_SIG_INFO*     sig,
3048                                        bool                  mustExpand);
3049 #ifdef _TARGET_XARCH_
3050     static InstructionSet lookupHWIntrinsicISA(const char* className);
3051     static NamedIntrinsic lookupHWIntrinsic(const char* methodName, InstructionSet isa);
3052     static InstructionSet isaOfHWIntrinsic(NamedIntrinsic intrinsic);
3053     static bool isIntrinsicAnIsSupportedPropertyGetter(NamedIntrinsic intrinsic);
3054     static bool isFullyImplmentedISAClass(InstructionSet isa);
3055     GenTree* impSSEIntrinsic(NamedIntrinsic        intrinsic,
3056                              CORINFO_METHOD_HANDLE method,
3057                              CORINFO_SIG_INFO*     sig,
3058                              bool                  mustExpand);
3059     GenTree* impSSE2Intrinsic(NamedIntrinsic        intrinsic,
3060                               CORINFO_METHOD_HANDLE method,
3061                               CORINFO_SIG_INFO*     sig,
3062                               bool                  mustExpand);
3063     GenTree* impSSE42Intrinsic(NamedIntrinsic        intrinsic,
3064                                CORINFO_METHOD_HANDLE method,
3065                                CORINFO_SIG_INFO*     sig,
3066                                bool                  mustExpand);
3067     GenTree* impAvxOrAvx2Intrinsic(NamedIntrinsic        intrinsic,
3068                                    CORINFO_METHOD_HANDLE method,
3069                                    CORINFO_SIG_INFO*     sig,
3070                                    bool                  mustExpand);
3071     GenTree* impAESIntrinsic(NamedIntrinsic        intrinsic,
3072                              CORINFO_METHOD_HANDLE method,
3073                              CORINFO_SIG_INFO*     sig,
3074                              bool                  mustExpand);
3075     GenTree* impBMI1Intrinsic(NamedIntrinsic        intrinsic,
3076                               CORINFO_METHOD_HANDLE method,
3077                               CORINFO_SIG_INFO*     sig,
3078                               bool                  mustExpand);
3079     GenTree* impBMI2Intrinsic(NamedIntrinsic        intrinsic,
3080                               CORINFO_METHOD_HANDLE method,
3081                               CORINFO_SIG_INFO*     sig,
3082                               bool                  mustExpand);
3083     GenTree* impFMAIntrinsic(NamedIntrinsic        intrinsic,
3084                              CORINFO_METHOD_HANDLE method,
3085                              CORINFO_SIG_INFO*     sig,
3086                              bool                  mustExpand);
3087     GenTree* impLZCNTIntrinsic(NamedIntrinsic        intrinsic,
3088                                CORINFO_METHOD_HANDLE method,
3089                                CORINFO_SIG_INFO*     sig,
3090                                bool                  mustExpand);
3091     GenTree* impPCLMULQDQIntrinsic(NamedIntrinsic        intrinsic,
3092                                    CORINFO_METHOD_HANDLE method,
3093                                    CORINFO_SIG_INFO*     sig,
3094                                    bool                  mustExpand);
3095     GenTree* impPOPCNTIntrinsic(NamedIntrinsic        intrinsic,
3096                                 CORINFO_METHOD_HANDLE method,
3097                                 CORINFO_SIG_INFO*     sig,
3098                                 bool                  mustExpand);
3099     bool compSupportsHWIntrinsic(InstructionSet isa);
3100     bool isScalarISA(InstructionSet isa);
3101     static int ivalOfHWIntrinsic(NamedIntrinsic intrinsic);
3102     unsigned simdSizeOfHWIntrinsic(NamedIntrinsic intrinsic, CORINFO_SIG_INFO* sig);
3103     static GenTree* lastOpOfHWIntrinsic(GenTreeHWIntrinsic* node, int numArgs);
3104     static instruction insOfHWIntrinsic(NamedIntrinsic intrinsic, var_types type);
3105
3106 public:
3107     static HWIntrinsicCategory categoryOfHWIntrinsic(NamedIntrinsic intrinsic);
3108     static int numArgsOfHWIntrinsic(GenTreeHWIntrinsic* node);
3109
3110 protected:
3111     static HWIntrinsicFlag flagsOfHWIntrinsic(NamedIntrinsic intrinsic);
3112     GenTree* getArgForHWIntrinsic(var_types argType, CORINFO_CLASS_HANDLE argClass);
3113     static int immUpperBoundOfHWIntrinsic(NamedIntrinsic intrinsic);
3114     GenTree* impNonConstFallback(NamedIntrinsic intrinsic, var_types simdType, var_types baseType);
3115     static bool isImmHWIntrinsic(NamedIntrinsic intrinsic, GenTree* lastOp);
3116     GenTree* addRangeCheckIfNeeded(NamedIntrinsic intrinsic, GenTree* lastOp, bool mustExpand);
3117     bool hwIntrinsicSignatureTypeSupported(var_types retType, CORINFO_SIG_INFO* sig, HWIntrinsicFlag flags);
3118 #endif // _TARGET_XARCH_
3119 #ifdef _TARGET_ARM64_
3120     InstructionSet lookupHWIntrinsicISA(const char* className);
3121     NamedIntrinsic lookupHWIntrinsic(const char* className, const char* methodName);
3122     bool impCheckImmediate(GenTree* immediateOp, unsigned int max);
3123     const HWIntrinsicInfo& getHWIntrinsicInfo(NamedIntrinsic);
3124 #endif // _TARGET_ARM64_
3125 #endif // FEATURE_HW_INTRINSICS
3126     GenTree* impArrayAccessIntrinsic(CORINFO_CLASS_HANDLE clsHnd,
3127                                      CORINFO_SIG_INFO*    sig,
3128                                      int                  memberRef,
3129                                      bool                 readonlyCall,
3130                                      CorInfoIntrinsics    intrinsicID);
3131     GenTree* impInitializeArrayIntrinsic(CORINFO_SIG_INFO* sig);
3132
3133     GenTree* impMethodPointer(CORINFO_RESOLVED_TOKEN* pResolvedToken, CORINFO_CALL_INFO* pCallInfo);
3134
3135     GenTree* impTransformThis(GenTree*                thisPtr,
3136                               CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
3137                               CORINFO_THIS_TRANSFORM  transform);
3138
3139     //----------------- Manipulating the trees and stmts ----------------------
3140
3141     GenTree* impTreeList; // Trees for the BB being imported
3142     GenTree* impTreeLast; // The last tree for the current BB
3143
3144 public:
3145     enum
3146     {
3147         CHECK_SPILL_ALL  = -1,
3148         CHECK_SPILL_NONE = -2
3149     };
3150
3151     void impBeginTreeList();
3152     void impEndTreeList(BasicBlock* block, GenTree* firstStmt, GenTree* lastStmt);
3153     void impEndTreeList(BasicBlock* block);
3154     void impAppendStmtCheck(GenTree* stmt, unsigned chkLevel);
3155     void impAppendStmt(GenTree* stmt, unsigned chkLevel);
3156     void impInsertStmtBefore(GenTree* stmt, GenTree* stmtBefore);
3157     GenTree* impAppendTree(GenTree* tree, unsigned chkLevel, IL_OFFSETX offset);
3158     void impInsertTreeBefore(GenTree* tree, IL_OFFSETX offset, GenTree* stmtBefore);
3159     void impAssignTempGen(unsigned    tmp,
3160                           GenTree*    val,
3161                           unsigned    curLevel,
3162                           GenTree**   pAfterStmt = nullptr,
3163                           IL_OFFSETX  ilOffset   = BAD_IL_OFFSET,
3164                           BasicBlock* block      = nullptr);
3165     void impAssignTempGen(unsigned             tmpNum,
3166                           GenTree*             val,
3167                           CORINFO_CLASS_HANDLE structHnd,
3168                           unsigned             curLevel,
3169                           GenTree**            pAfterStmt = nullptr,
3170                           IL_OFFSETX           ilOffset   = BAD_IL_OFFSET,
3171                           BasicBlock*          block      = nullptr);
3172     GenTree* impCloneExpr(GenTree*             tree,
3173                           GenTree**            clone,
3174                           CORINFO_CLASS_HANDLE structHnd,
3175                           unsigned             curLevel,
3176                           GenTree** pAfterStmt DEBUGARG(const char* reason));
3177     GenTree* impAssignStruct(GenTree*             dest,
3178                              GenTree*             src,
3179                              CORINFO_CLASS_HANDLE structHnd,
3180                              unsigned             curLevel,
3181                              GenTree**            pAfterStmt = nullptr,
3182                              BasicBlock*          block      = nullptr);
3183     GenTree* impAssignStructPtr(GenTree*             dest,
3184                                 GenTree*             src,
3185                                 CORINFO_CLASS_HANDLE structHnd,
3186                                 unsigned             curLevel,
3187                                 GenTree**            pAfterStmt = nullptr,
3188                                 BasicBlock*          block      = nullptr);
3189
3190     GenTree* impGetStructAddr(GenTree* structVal, CORINFO_CLASS_HANDLE structHnd, unsigned curLevel, bool willDeref);
3191
3192     var_types impNormStructType(CORINFO_CLASS_HANDLE structHnd,
3193                                 BYTE*                gcLayout     = nullptr,
3194                                 unsigned*            numGCVars    = nullptr,
3195                                 var_types*           simdBaseType = nullptr);
3196
3197     GenTree* impNormStructVal(GenTree*             structVal,
3198                               CORINFO_CLASS_HANDLE structHnd,
3199                               unsigned             curLevel,
3200                               bool                 forceNormalization = false);
3201
3202     GenTree* impTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3203                               BOOL*                   pRuntimeLookup    = nullptr,
3204                               BOOL                    mustRestoreHandle = FALSE,
3205                               BOOL                    importParent      = FALSE);
3206
3207     GenTree* impParentClassTokenToHandle(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3208                                          BOOL*                   pRuntimeLookup    = nullptr,
3209                                          BOOL                    mustRestoreHandle = FALSE)
3210     {
3211         return impTokenToHandle(pResolvedToken, pRuntimeLookup, mustRestoreHandle, TRUE);
3212     }
3213
3214     GenTree* impLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3215                              CORINFO_LOOKUP*         pLookup,
3216                              unsigned                flags,
3217                              void*                   compileTimeHandle);
3218
3219     GenTree* getRuntimeContextTree(CORINFO_RUNTIME_LOOKUP_KIND kind);
3220
3221     GenTree* impRuntimeLookupToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3222                                     CORINFO_LOOKUP*         pLookup,
3223                                     void*                   compileTimeHandle);
3224
3225     GenTree* impReadyToRunLookupToTree(CORINFO_CONST_LOOKUP* pLookup, unsigned flags, void* compileTimeHandle);
3226
3227     GenTreeCall* impReadyToRunHelperToTree(CORINFO_RESOLVED_TOKEN* pResolvedToken,
3228                                            CorInfoHelpFunc         helper,
3229                                            var_types               type,
3230                                            GenTreeArgList*         arg                = nullptr,
3231                                            CORINFO_LOOKUP_KIND*    pGenericLookupKind = nullptr);
3232
3233     GenTree* impCastClassOrIsInstToTree(GenTree*                op1,
3234                                         GenTree*                op2,
3235                                         CORINFO_RESOLVED_TOKEN* pResolvedToken,
3236                                         bool                    isCastClass);
3237
3238     GenTree* impOptimizeCastClassOrIsInst(GenTree* op1, CORINFO_RESOLVED_TOKEN* pResolvedToken, bool isCastClass);
3239
3240     bool VarTypeIsMultiByteAndCanEnreg(var_types            type,
3241                                        CORINFO_CLASS_HANDLE typeClass,
3242                                        unsigned*            typeSize,
3243                                        bool                 forReturn);
3244
3245     bool IsIntrinsicImplementedByUserCall(CorInfoIntrinsics intrinsicId);
3246     bool IsTargetIntrinsic(CorInfoIntrinsics intrinsicId);
3247     bool IsMathIntrinsic(CorInfoIntrinsics intrinsicId);
3248     bool IsMathIntrinsic(GenTree* tree);
3249
3250 private:
3251     //----------------- Importing the method ----------------------------------
3252
3253     CORINFO_CONTEXT_HANDLE impTokenLookupContextHandle; // The context used for looking up tokens.
3254
3255 #ifdef DEBUG
3256     unsigned    impCurOpcOffs;
3257     const char* impCurOpcName;
3258     bool        impNestedStackSpill;
3259
3260     // For displaying instrs with generated native code (-n:B)
3261     GenTree* impLastILoffsStmt; // oldest stmt added for which we did not gtStmtLastILoffs
3262     void     impNoteLastILoffs();
3263 #endif
3264
3265     /* IL offset of the stmt currently being imported. It gets set to
3266        BAD_IL_OFFSET after it has been set in the appended trees. Then it gets
3267        updated at IL offsets for which we have to report mapping info.
3268        It also includes flag bits, so use jitGetILoffs()
3269        to get the actual IL offset value.
3270     */
3271
3272     IL_OFFSETX impCurStmtOffs;
3273     void impCurStmtOffsSet(IL_OFFSET offs);
3274
3275     void impNoteBranchOffs();
3276
3277     unsigned impInitBlockLineInfo();
3278
3279     GenTree* impCheckForNullPointer(GenTree* obj);
3280     bool impIsThis(GenTree* obj);
3281     bool impIsLDFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3282     bool impIsDUP_LDVIRTFTN_TOKEN(const BYTE* delegateCreateStart, const BYTE* newobjCodeAddr);
3283     bool impIsAnySTLOC(OPCODE opcode)
3284     {
3285         return ((opcode == CEE_STLOC) || (opcode == CEE_STLOC_S) ||
3286                 ((opcode >= CEE_STLOC_0) && (opcode <= CEE_STLOC_3)));
3287     }
3288
3289     GenTreeArgList* impPopList(unsigned count, CORINFO_SIG_INFO* sig, GenTreeArgList* prefixTree = nullptr);
3290
3291     GenTreeArgList* impPopRevList(unsigned count, CORINFO_SIG_INFO* sig, unsigned skipReverseCount = 0);
3292
3293     /*
3294      * Get current IL offset with stack-empty info incoporated
3295      */
3296     IL_OFFSETX impCurILOffset(IL_OFFSET offs, bool callInstruction = false);
3297
3298     //---------------- Spilling the importer stack ----------------------------
3299
3300     // The maximum number of bytes of IL processed without clean stack state.
3301     // It allows to limit the maximum tree size and depth.
3302     static const unsigned MAX_TREE_SIZE = 200;
3303     bool impCanSpillNow(OPCODE prevOpcode);
3304
3305     struct PendingDsc
3306     {
3307         PendingDsc*   pdNext;
3308         BasicBlock*   pdBB;
3309         SavedStack    pdSavedStack;
3310         ThisInitState pdThisPtrInit;
3311     };
3312
3313     PendingDsc* impPendingList; // list of BBs currently waiting to be imported.
3314     PendingDsc* impPendingFree; // Freed up dscs that can be reused
3315
3316     // We keep a byte-per-block map (dynamically extended) in the top-level Compiler object of a compilation.
3317     JitExpandArray<BYTE> impPendingBlockMembers;
3318
3319     // Return the byte for "b" (allocating/extending impPendingBlockMembers if necessary.)
3320     // Operates on the map in the top-level ancestor.
3321     BYTE impGetPendingBlockMember(BasicBlock* blk)
3322     {
3323         return impInlineRoot()->impPendingBlockMembers.Get(blk->bbInd());
3324     }
3325
3326     // Set the byte for "b" to "val" (allocating/extending impPendingBlockMembers if necessary.)
3327     // Operates on the map in the top-level ancestor.
3328     void impSetPendingBlockMember(BasicBlock* blk, BYTE val)
3329     {
3330         impInlineRoot()->impPendingBlockMembers.Set(blk->bbInd(), val);
3331     }
3332
3333     bool impCanReimport;
3334
3335     bool impSpillStackEntry(unsigned level,
3336                             unsigned varNum
3337 #ifdef DEBUG
3338                             ,
3339                             bool        bAssertOnRecursion,
3340                             const char* reason
3341 #endif
3342                             );
3343
3344     void impSpillStackEnsure(bool spillLeaves = false);
3345     void impEvalSideEffects();
3346     void impSpillSpecialSideEff();
3347     void impSpillSideEffects(bool spillGlobEffects, unsigned chkLevel DEBUGARG(const char* reason));
3348     void               impSpillValueClasses();
3349     void               impSpillEvalStack();
3350     static fgWalkPreFn impFindValueClasses;
3351     void impSpillLclRefs(ssize_t lclNum);
3352
3353     BasicBlock* impPushCatchArgOnStack(BasicBlock* hndBlk, CORINFO_CLASS_HANDLE clsHnd, bool isSingleBlockFilter);
3354
3355     void impImportBlockCode(BasicBlock* block);
3356
3357     void impReimportMarkBlock(BasicBlock* block);
3358     void impReimportMarkSuccessors(BasicBlock* block);
3359
3360     void impVerifyEHBlock(BasicBlock* block, bool isTryStart);
3361
3362     void impImportBlockPending(BasicBlock* block);
3363
3364     // Similar to impImportBlockPending, but assumes that block has already been imported once and is being
3365     // reimported for some reason.  It specifically does *not* look at verCurrentState to set the EntryState
3366     // for the block, but instead, just re-uses the block's existing EntryState.
3367     void impReimportBlockPending(BasicBlock* block);
3368
3369     var_types impGetByRefResultType(genTreeOps oper, bool fUnsigned, GenTree** pOp1, GenTree** pOp2);
3370
3371     void impImportBlock(BasicBlock* block);
3372
3373     // Assumes that "block" is a basic block that completes with a non-empty stack. We will assign the values
3374     // on the stack to local variables (the "spill temp" variables). The successor blocks will assume that
3375     // its incoming stack contents are in those locals. This requires "block" and its successors to agree on
3376     // the variables that will be used -- and for all the predecessors of those successors, and the
3377     // successors of those predecessors, etc. Call such a set of blocks closed under alternating
3378     // successor/predecessor edges a "spill clique." A block is a "predecessor" or "successor" member of the
3379     // clique (or, conceivably, both). Each block has a specified sequence of incoming and outgoing spill
3380     // temps. If "block" already has its outgoing spill temps assigned (they are always a contiguous series
3381     // of local variable numbers, so we represent them with the base local variable number), returns that.
3382     // Otherwise, picks a set of spill temps, and propagates this choice to all blocks in the spill clique of
3383     // which "block" is a member (asserting, in debug mode, that no block in this clique had its spill temps
3384     // chosen already. More precisely, that the incoming or outgoing spill temps are not chosen, depending
3385     // on which kind of member of the clique the block is).
3386     unsigned impGetSpillTmpBase(BasicBlock* block);
3387
3388     // Assumes that "block" is a basic block that completes with a non-empty stack. We have previously
3389     // assigned the values on the stack to local variables (the "spill temp" variables). The successor blocks
3390     // will assume that its incoming stack contents are in those locals. This requires "block" and its
3391     // successors to agree on the variables and their types that will be used.  The CLI spec allows implicit
3392     // conversions between 'int' and 'native int' or 'float' and 'double' stack types. So one predecessor can
3393     // push an int and another can push a native int.  For 64-bit we have chosen to implement this by typing
3394     // the "spill temp" as native int, and then importing (or re-importing as needed) so that all the
3395     // predecessors in the "spill clique" push a native int (sign-extending if needed), and all the
3396     // successors receive a native int. Similarly float and double are unified to double.
3397     // This routine is called after a type-mismatch is detected, and it will walk the spill clique to mark
3398     // blocks for re-importation as appropriate (both successors, so they get the right incoming type, and
3399     // predecessors, so they insert an upcast if needed).
3400     void impReimportSpillClique(BasicBlock* block);
3401
3402     // When we compute a "spill clique" (see above) these byte-maps are allocated to have a byte per basic
3403     // block, and represent the predecessor and successor members of the clique currently being computed.
3404     // *** Access to these will need to be locked in a parallel compiler.
3405     JitExpandArray<BYTE> impSpillCliquePredMembers;
3406     JitExpandArray<BYTE> impSpillCliqueSuccMembers;
3407
3408     enum SpillCliqueDir
3409     {
3410         SpillCliquePred,
3411         SpillCliqueSucc
3412     };
3413
3414     // Abstract class for receiving a callback while walking a spill clique
3415     class SpillCliqueWalker
3416     {
3417     public:
3418         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk) = 0;
3419     };
3420
3421     // This class is used for setting the bbStkTempsIn and bbStkTempsOut on the blocks within a spill clique
3422     class SetSpillTempsBase : public SpillCliqueWalker
3423     {
3424         unsigned m_baseTmp;
3425
3426     public:
3427         SetSpillTempsBase(unsigned baseTmp) : m_baseTmp(baseTmp)
3428         {
3429         }
3430         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3431     };
3432
3433     // This class is used for implementing impReimportSpillClique part on each block within the spill clique
3434     class ReimportSpillClique : public SpillCliqueWalker
3435     {
3436         Compiler* m_pComp;
3437
3438     public:
3439         ReimportSpillClique(Compiler* pComp) : m_pComp(pComp)
3440         {
3441         }
3442         virtual void Visit(SpillCliqueDir predOrSucc, BasicBlock* blk);
3443     };
3444
3445     // This is the heart of the algorithm for walking spill cliques. It invokes callback->Visit for each
3446     // predecessor or successor within the spill clique
3447     void impWalkSpillCliqueFromPred(BasicBlock* pred, SpillCliqueWalker* callback);
3448
3449     // For a BasicBlock that has already been imported, the EntryState has an array of GenTrees for the
3450     // incoming locals. This walks that list an resets the types of the GenTrees to match the types of
3451     // the VarDscs. They get out of sync when we have int/native int issues (see impReimportSpillClique).
3452     void impRetypeEntryStateTemps(BasicBlock* blk);
3453
3454     BYTE impSpillCliqueGetMember(SpillCliqueDir predOrSucc, BasicBlock* blk);
3455     void impSpillCliqueSetMember(SpillCliqueDir predOrSucc, BasicBlock* blk, BYTE val);
3456
3457     void impPushVar(GenTree* op, typeInfo tiRetVal);
3458     void impLoadVar(unsigned lclNum, IL_OFFSET offset, typeInfo tiRetVal);
3459     void impLoadVar(unsigned lclNum, IL_OFFSET offset)
3460     {
3461         impLoadVar(lclNum, offset, lvaTable[lclNum].lvVerTypeInfo);
3462     }
3463     void impLoadArg(unsigned ilArgNum, IL_OFFSET offset);
3464     void impLoadLoc(unsigned ilLclNum, IL_OFFSET offset);
3465     bool impReturnInstruction(BasicBlock* block, int prefixFlags, OPCODE& opcode);
3466
3467 #ifdef _TARGET_ARM_
3468     void impMarkLclDstNotPromotable(unsigned tmpNum, GenTree* op, CORINFO_CLASS_HANDLE hClass);
3469 #endif
3470
3471     // A free list of linked list nodes used to represent to-do stacks of basic blocks.
3472     struct BlockListNode
3473     {
3474         BasicBlock*    m_blk;
3475         BlockListNode* m_next;
3476         BlockListNode(BasicBlock* blk, BlockListNode* next = nullptr) : m_blk(blk), m_next(next)
3477         {
3478         }
3479         void* operator new(size_t sz, Compiler* comp);
3480     };
3481     BlockListNode* impBlockListNodeFreeList;
3482
3483     BlockListNode* AllocBlockListNode();
3484     void FreeBlockListNode(BlockListNode* node);
3485
3486     bool impIsValueType(typeInfo* pTypeInfo);
3487     var_types mangleVarArgsType(var_types type);
3488
3489 #if FEATURE_VARARG
3490     regNumber getCallArgIntRegister(regNumber floatReg);
3491     regNumber getCallArgFloatRegister(regNumber intReg);
3492 #endif // FEATURE_VARARG
3493
3494 #if defined(DEBUG)
3495     static unsigned jitTotalMethodCompiled;
3496 #endif
3497
3498 #ifdef DEBUG
3499     static LONG jitNestingLevel;
3500 #endif // DEBUG
3501
3502     static BOOL impIsAddressInLocal(GenTree* tree, GenTree** lclVarTreeOut);
3503
3504     void impMakeDiscretionaryInlineObservations(InlineInfo* pInlineInfo, InlineResult* inlineResult);
3505
3506     // STATIC inlining decision based on the IL code.
3507     void impCanInlineIL(CORINFO_METHOD_HANDLE fncHandle,
3508                         CORINFO_METHOD_INFO*  methInfo,
3509                         bool                  forceInline,
3510                         InlineResult*         inlineResult);
3511
3512     void impCheckCanInline(GenTree*               call,
3513                            CORINFO_METHOD_HANDLE  fncHandle,
3514                            unsigned               methAttr,
3515                            CORINFO_CONTEXT_HANDLE exactContextHnd,
3516                            InlineCandidateInfo**  ppInlineCandidateInfo,
3517                            InlineResult*          inlineResult);
3518
3519     void impInlineRecordArgInfo(InlineInfo*   pInlineInfo,
3520                                 GenTree*      curArgVal,
3521                                 unsigned      argNum,
3522                                 InlineResult* inlineResult);
3523
3524     void impInlineInitVars(InlineInfo* pInlineInfo);
3525
3526     unsigned impInlineFetchLocal(unsigned lclNum DEBUGARG(const char* reason));
3527
3528     GenTree* impInlineFetchArg(unsigned lclNum, InlArgInfo* inlArgInfo, InlLclVarInfo* lclTypeInfo);
3529
3530     BOOL impInlineIsThis(GenTree* tree, InlArgInfo* inlArgInfo);
3531
3532     BOOL impInlineIsGuaranteedThisDerefBeforeAnySideEffects(GenTree*    additionalTreesToBeEvaluatedBefore,
3533                                                             GenTree*    variableBeingDereferenced,
3534                                                             InlArgInfo* inlArgInfo);
3535
3536     void impMarkInlineCandidate(GenTree*               call,
3537                                 CORINFO_CONTEXT_HANDLE exactContextHnd,
3538                                 bool                   exactContextNeedsRuntimeLookup,
3539                                 CORINFO_CALL_INFO*     callInfo);
3540
3541     bool impTailCallRetTypeCompatible(var_types            callerRetType,
3542                                       CORINFO_CLASS_HANDLE callerRetTypeClass,
3543                                       var_types            calleeRetType,
3544                                       CORINFO_CLASS_HANDLE calleeRetTypeClass);
3545
3546     bool impIsTailCallILPattern(bool        tailPrefixed,
3547                                 OPCODE      curOpcode,
3548                                 const BYTE* codeAddrOfNextOpcode,
3549                                 const BYTE* codeEnd,
3550                                 bool        isRecursive,
3551                                 bool*       IsCallPopRet = nullptr);
3552
3553     bool impIsImplicitTailCallCandidate(
3554         OPCODE curOpcode, const BYTE* codeAddrOfNextOpcode, const BYTE* codeEnd, int prefixFlags, bool isRecursive);
3555
3556     CORINFO_RESOLVED_TOKEN* impAllocateToken(CORINFO_RESOLVED_TOKEN token);
3557
3558     /*
3559     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3560     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3561     XX                                                                           XX
3562     XX                           FlowGraph                                       XX
3563     XX                                                                           XX
3564     XX   Info about the basic-blocks, their contents and the flow analysis       XX
3565     XX                                                                           XX
3566     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3567     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
3568     */
3569
3570 public:
3571     BasicBlock* fgFirstBB;        // Beginning of the basic block list
3572     BasicBlock* fgLastBB;         // End of the basic block list
3573     BasicBlock* fgFirstColdBlock; // First block to be placed in the cold section
3574 #if FEATURE_EH_FUNCLETS
3575     BasicBlock* fgFirstFuncletBB; // First block of outlined funclets (to allow block insertion before the funclets)
3576 #endif
3577     BasicBlock* fgFirstBBScratch;   // Block inserted for initialization stuff. Is nullptr if no such block has been
3578                                     // created.
3579     BasicBlockList* fgReturnBlocks; // list of BBJ_RETURN blocks
3580     unsigned        fgEdgeCount;    // # of control flow edges between the BBs
3581     unsigned        fgBBcount;      // # of BBs in the method
3582 #ifdef DEBUG
3583     unsigned fgBBcountAtCodegen; // # of BBs in the method at the start of codegen
3584 #endif
3585     unsigned     fgBBNumMax;       // The max bbNum that has been assigned to basic blocks
3586     unsigned     fgDomBBcount;     // # of BBs for which we have dominator and reachability information
3587     BasicBlock** fgBBInvPostOrder; // The flow graph stored in an array sorted in topological order, needed to compute
3588                                    // dominance. Indexed by block number. Size: fgBBNumMax + 1.
3589
3590     // After the dominance tree is computed, we cache a DFS preorder number and DFS postorder number to compute
3591     // dominance queries in O(1). fgDomTreePreOrder and fgDomTreePostOrder are arrays giving the block's preorder and
3592     // postorder number, respectively. The arrays are indexed by basic block number. (Note that blocks are numbered
3593     // starting from one. Thus, we always waste element zero. This makes debugging easier and makes the code less likely
3594     // to suffer from bugs stemming from forgetting to add or subtract one from the block number to form an array
3595     // index). The arrays are of size fgBBNumMax + 1.
3596     unsigned* fgDomTreePreOrder;
3597     unsigned* fgDomTreePostOrder;
3598
3599     bool fgBBVarSetsInited;
3600
3601     // Allocate array like T* a = new T[fgBBNumMax + 1];
3602     // Using helper so we don't keep forgetting +1.
3603     template <typename T>
3604     T* fgAllocateTypeForEachBlk(CompMemKind cmk = CMK_Unknown)
3605     {
3606         return (T*)compGetMem((fgBBNumMax + 1) * sizeof(T), cmk);
3607     }
3608
3609     // BlockSets are relative to a specific set of BasicBlock numbers. If that changes
3610     // (if the blocks are renumbered), this changes. BlockSets from different epochs
3611     // cannot be meaningfully combined. Note that new blocks can be created with higher
3612     // block numbers without changing the basic block epoch. These blocks *cannot*
3613     // participate in a block set until the blocks are all renumbered, causing the epoch
3614     // to change. This is useful if continuing to use previous block sets is valuable.
3615     // If the epoch is zero, then it is uninitialized, and block sets can't be used.
3616     unsigned fgCurBBEpoch;
3617
3618     unsigned GetCurBasicBlockEpoch()
3619     {
3620         return fgCurBBEpoch;
3621     }
3622
3623     // The number of basic blocks in the current epoch. When the blocks are renumbered,
3624     // this is fgBBcount. As blocks are added, fgBBcount increases, fgCurBBEpochSize remains
3625     // the same, until a new BasicBlock epoch is created, such as when the blocks are all renumbered.
3626     unsigned fgCurBBEpochSize;
3627
3628     // The number of "size_t" elements required to hold a bitset large enough for fgCurBBEpochSize
3629     // bits. This is precomputed to avoid doing math every time BasicBlockBitSetTraits::GetArrSize() is called.
3630     unsigned fgBBSetCountInSizeTUnits;
3631
3632     void NewBasicBlockEpoch()
3633     {
3634         INDEBUG(unsigned oldEpochArrSize = fgBBSetCountInSizeTUnits);
3635
3636         // We have a new epoch. Compute and cache the size needed for new BlockSets.
3637         fgCurBBEpoch++;
3638         fgCurBBEpochSize = fgBBNumMax + 1;
3639         fgBBSetCountInSizeTUnits =
3640             unsigned(roundUp(fgCurBBEpochSize, sizeof(size_t) * 8)) / unsigned(sizeof(size_t) * 8);
3641
3642 #ifdef DEBUG
3643         // All BlockSet objects are now invalid!
3644         fgReachabilitySetsValid = false; // the bbReach sets are now invalid!
3645         fgEnterBlksSetValid     = false; // the fgEnterBlks set is now invalid!
3646
3647         if (verbose)
3648         {
3649             unsigned epochArrSize = BasicBlockBitSetTraits::GetArrSize(this, sizeof(size_t));
3650             printf("\nNew BlockSet epoch %d, # of blocks (including unused BB00): %u, bitset array size: %u (%s)",
3651                    fgCurBBEpoch, fgCurBBEpochSize, epochArrSize, (epochArrSize <= 1) ? "short" : "long");
3652             if ((fgCurBBEpoch != 1) && ((oldEpochArrSize <= 1) != (epochArrSize <= 1)))
3653             {
3654                 // If we're not just establishing the first epoch, and the epoch array size has changed such that we're
3655                 // going to change our bitset representation from short (just a size_t bitset) to long (a pointer to an
3656                 // array of size_t bitsets), then print that out.
3657                 printf("; NOTE: BlockSet size was previously %s!", (oldEpochArrSize <= 1) ? "short" : "long");
3658             }
3659             printf("\n");
3660         }
3661 #endif // DEBUG
3662     }
3663
3664     void EnsureBasicBlockEpoch()
3665     {
3666         if (fgCurBBEpochSize != fgBBNumMax + 1)
3667         {
3668             NewBasicBlockEpoch();
3669         }
3670     }
3671
3672     BasicBlock* fgNewBasicBlock(BBjumpKinds jumpKind);
3673     void fgEnsureFirstBBisScratch();
3674     bool fgFirstBBisScratch();
3675     bool fgBBisScratch(BasicBlock* block);
3676
3677     void fgExtendEHRegionBefore(BasicBlock* block);
3678     void fgExtendEHRegionAfter(BasicBlock* block);
3679
3680     BasicBlock* fgNewBBbefore(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3681
3682     BasicBlock* fgNewBBafter(BBjumpKinds jumpKind, BasicBlock* block, bool extendRegion);
3683
3684     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3685                                 unsigned    tryIndex,
3686                                 unsigned    hndIndex,
3687                                 BasicBlock* nearBlk,
3688                                 bool        putInFilter = false,
3689                                 bool        runRarely   = false,
3690                                 bool        insertAtEnd = false);
3691
3692     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind,
3693                                 BasicBlock* srcBlk,
3694                                 bool        runRarely   = false,
3695                                 bool        insertAtEnd = false);
3696
3697     BasicBlock* fgNewBBinRegion(BBjumpKinds jumpKind);
3698
3699     BasicBlock* fgNewBBinRegionWorker(BBjumpKinds jumpKind,
3700                                       BasicBlock* afterBlk,
3701                                       unsigned    xcptnIndex,
3702                                       bool        putInTryRegion);
3703
3704     void fgInsertBBbefore(BasicBlock* insertBeforeBlk, BasicBlock* newBlk);
3705     void fgInsertBBafter(BasicBlock* insertAfterBlk, BasicBlock* newBlk);
3706     void fgUnlinkBlock(BasicBlock* block);
3707
3708     unsigned fgMeasureIR();
3709
3710 #if OPT_BOOL_OPS // Used to detect multiple logical "not" assignments.
3711     bool fgMultipleNots;
3712 #endif
3713
3714     bool fgModified;         // True if the flow graph has been modified recently
3715     bool fgComputePredsDone; // Have we computed the bbPreds list
3716     bool fgCheapPredsValid;  // Is the bbCheapPreds list valid?
3717     bool fgDomsComputed;     // Have we computed the dominator sets?
3718     bool fgOptimizedFinally; // Did we optimize any try-finallys?
3719
3720     bool     fgHasSwitch;  // any BBJ_SWITCH jumps?
3721     bool     fgHasPostfix; // any postfix ++/-- found?
3722     unsigned fgIncrCount;  // number of increment nodes found
3723
3724     BlockSet fgEnterBlks; // Set of blocks which have a special transfer of control; the "entry" blocks plus EH handler
3725                           // begin blocks.
3726
3727 #ifdef DEBUG
3728     bool fgReachabilitySetsValid; // Are the bbReach sets valid?
3729     bool fgEnterBlksSetValid;     // Is the fgEnterBlks set valid?
3730 #endif                            // DEBUG
3731
3732     bool fgRemoveRestOfBlock; // true if we know that we will throw
3733     bool fgStmtRemoved;       // true if we remove statements -> need new DFA
3734
3735     // There are two modes for ordering of the trees.
3736     //  - In FGOrderTree, the dominant ordering is the tree order, and the nodes contained in
3737     //    each tree and sub-tree are contiguous, and can be traversed (in gtNext/gtPrev order)
3738     //    by traversing the tree according to the order of the operands.
3739     //  - In FGOrderLinear, the dominant ordering is the linear order.
3740
3741     enum FlowGraphOrder
3742     {
3743         FGOrderTree,
3744         FGOrderLinear
3745     };
3746     FlowGraphOrder fgOrder;
3747
3748     // The following are boolean flags that keep track of the state of internal data structures
3749
3750     bool                 fgStmtListThreaded;       // true if the node list is now threaded
3751     bool                 fgCanRelocateEHRegions;   // true if we are allowed to relocate the EH regions
3752     bool                 fgEdgeWeightsComputed;    // true after we have called fgComputeEdgeWeights
3753     bool                 fgHaveValidEdgeWeights;   // true if we were successful in computing all of the edge weights
3754     bool                 fgSlopUsedInEdgeWeights;  // true if their was some slop used when computing the edge weights
3755     bool                 fgRangeUsedInEdgeWeights; // true if some of the edgeWeight are expressed in Min..Max form
3756     bool                 fgNeedsUpdateFlowGraph;   // true if we need to run fgUpdateFlowGraph
3757     BasicBlock::weight_t fgCalledCount;            // count of the number of times this method was called
3758                                                    // This is derived from the profile data
3759                                                    // or is BB_UNITY_WEIGHT when we don't have profile data
3760
3761 #if FEATURE_EH_FUNCLETS
3762     bool fgFuncletsCreated; // true if the funclet creation phase has been run
3763 #endif                      // FEATURE_EH_FUNCLETS
3764
3765     bool fgGlobalMorph; // indicates if we are during the global morphing phase
3766                         // since fgMorphTree can be called from several places
3767
3768     bool     impBoxTempInUse; // the temp below is valid and available
3769     unsigned impBoxTemp;      // a temporary that is used for boxing
3770
3771 #ifdef DEBUG
3772     bool jitFallbackCompile; // Are we doing a fallback compile? That is, have we executed a NO_WAY assert,
3773                              //   and we are trying to compile again in a "safer", minopts mode?
3774 #endif
3775
3776 #if defined(DEBUG)
3777     unsigned impInlinedCodeSize;
3778 #endif
3779
3780     //-------------------------------------------------------------------------
3781
3782     void fgInit();
3783
3784     void fgImport();
3785
3786     void fgTransformFatCalli();
3787
3788     void fgInline();
3789
3790     void fgRemoveEmptyTry();
3791
3792     void fgRemoveEmptyFinally();
3793
3794     void fgMergeFinallyChains();
3795
3796     void fgCloneFinally();
3797
3798     void fgCleanupContinuation(BasicBlock* continuation);
3799
3800     void fgUpdateFinallyTargetFlags();
3801
3802     void fgClearAllFinallyTargetBits();
3803
3804     void fgAddFinallyTargetFlags();
3805
3806 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3807     // Sometimes we need to defer updating the BBF_FINALLY_TARGET bit. fgNeedToAddFinallyTargetBits signals
3808     // when this is necessary.
3809     bool fgNeedToAddFinallyTargetBits;
3810 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3811
3812     bool fgRetargetBranchesToCanonicalCallFinally(BasicBlock*      block,
3813                                                   BasicBlock*      handler,
3814                                                   BlockToBlockMap& continuationMap);
3815
3816     GenTree* fgGetCritSectOfStaticMethod();
3817
3818 #if FEATURE_EH_FUNCLETS
3819
3820     void fgAddSyncMethodEnterExit();
3821
3822     GenTree* fgCreateMonitorTree(unsigned lvaMonitorBool, unsigned lvaThisVar, BasicBlock* block, bool enter);
3823
3824     void fgConvertSyncReturnToLeave(BasicBlock* block);
3825
3826 #endif // FEATURE_EH_FUNCLETS
3827
3828     void fgAddReversePInvokeEnterExit();
3829
3830     bool fgMoreThanOneReturnBlock();
3831
3832     // The number of separate return points in the method.
3833     unsigned fgReturnCount;
3834
3835     void fgAddInternal();
3836
3837     bool fgFoldConditional(BasicBlock* block);
3838
3839 #ifdef LEGACY_BACKEND
3840     void fgMorphStmts(BasicBlock* block, bool* mult, bool* lnot, bool* loadw);
3841 #else
3842     void fgMorphStmts(BasicBlock* block, bool* lnot, bool* loadw);
3843 #endif
3844     void fgMorphBlocks();
3845
3846     bool fgMorphBlockStmt(BasicBlock* block, GenTreeStmt* stmt DEBUGARG(const char* msg));
3847
3848     void fgCheckArgCnt();
3849     void fgSetOptions();
3850
3851 #ifdef DEBUG
3852     static fgWalkPreFn fgAssertNoQmark;
3853     void fgPreExpandQmarkChecks(GenTree* expr);
3854     void        fgPostExpandQmarkChecks();
3855     static void fgCheckQmarkAllowedForm(GenTree* tree);
3856 #endif
3857
3858     IL_OFFSET fgFindBlockILOffset(BasicBlock* block);
3859
3860     BasicBlock* fgSplitBlockAtBeginning(BasicBlock* curr);
3861     BasicBlock* fgSplitBlockAtEnd(BasicBlock* curr);
3862     BasicBlock* fgSplitBlockAfterStatement(BasicBlock* curr, GenTree* stmt);
3863     BasicBlock* fgSplitBlockAfterNode(BasicBlock* curr, GenTree* node); // for LIR
3864     BasicBlock* fgSplitEdge(BasicBlock* curr, BasicBlock* succ);
3865
3866     GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block, IL_OFFSETX offs);
3867     GenTreeStmt* fgNewStmtFromTree(GenTree* tree);
3868     GenTreeStmt* fgNewStmtFromTree(GenTree* tree, BasicBlock* block);
3869     GenTreeStmt* fgNewStmtFromTree(GenTree* tree, IL_OFFSETX offs);
3870
3871     GenTree* fgGetTopLevelQmark(GenTree* expr, GenTree** ppDst = nullptr);
3872     void fgExpandQmarkForCastInstOf(BasicBlock* block, GenTree* stmt);
3873     void fgExpandQmarkStmt(BasicBlock* block, GenTree* expr);
3874     void fgExpandQmarkNodes();
3875
3876     void fgMorph();
3877
3878     // Do "simple lowering."  This functionality is (conceptually) part of "general"
3879     // lowering that is distributed between fgMorph and the lowering phase of LSRA.
3880     void fgSimpleLowering();
3881
3882 #ifdef LEGACY_BACKEND
3883     bool fgShouldCreateAssignOp(GenTree* tree, bool* bReverse);
3884 #endif
3885
3886     GenTree* fgInitThisClass();
3887
3888     GenTreeCall* fgGetStaticsCCtorHelper(CORINFO_CLASS_HANDLE cls, CorInfoHelpFunc helper);
3889
3890     GenTreeCall* fgGetSharedCCtor(CORINFO_CLASS_HANDLE cls);
3891
3892     inline bool backendRequiresLocalVarLifetimes()
3893     {
3894 #if defined(LEGACY_BACKEND)
3895         return true;
3896 #else
3897         return !opts.MinOpts() || m_pLinearScan->willEnregisterLocalVars();
3898 #endif
3899     }
3900
3901     void fgLocalVarLiveness();
3902
3903     void fgLocalVarLivenessInit();
3904
3905 #ifdef LEGACY_BACKEND
3906     GenTree* fgLegacyPerStatementLocalVarLiveness(GenTree* startNode, GenTree* relopNode);
3907 #else
3908     void fgPerNodeLocalVarLiveness(GenTree* node);
3909 #endif
3910     void fgPerBlockLocalVarLiveness();
3911
3912     VARSET_VALRET_TP fgGetHandlerLiveVars(BasicBlock* block);
3913
3914     void fgLiveVarAnalysis(bool updateInternalOnly = false);
3915
3916     // This is used in the liveness computation, as a temporary.  When we use the
3917     // arbitrary-length VarSet representation, it is better not to allocate a new one
3918     // at each call.
3919     VARSET_TP fgMarkIntfUnionVS;
3920
3921     bool fgMarkIntf(VARSET_VALARG_TP varSet);
3922
3923     bool fgMarkIntf(VARSET_VALARG_TP varSet1, VARSET_VALARG_TP varSet2);
3924
3925     bool fgMarkIntf(VARSET_VALARG_TP varSet1, unsigned varIndex);
3926
3927     void fgUpdateRefCntForClone(BasicBlock* addedToBlock, GenTree* clonedTree);
3928
3929     void fgUpdateRefCntForExtract(GenTree* wholeTree, GenTree* keptTree);
3930
3931     void fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call);
3932
3933     void fgComputeLifeTrackedLocalUse(VARSET_TP& life, LclVarDsc& varDsc, GenTreeLclVarCommon* node);
3934     bool fgComputeLifeTrackedLocalDef(VARSET_TP&           life,
3935                                       VARSET_VALARG_TP     keepAliveVars,
3936                                       LclVarDsc&           varDsc,
3937                                       GenTreeLclVarCommon* node);
3938     void fgComputeLifeUntrackedLocal(VARSET_TP&           life,
3939                                      VARSET_VALARG_TP     keepAliveVars,
3940                                      LclVarDsc&           varDsc,
3941                                      GenTreeLclVarCommon* lclVarNode,
3942                                      GenTree*             node);
3943     bool fgComputeLifeLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, GenTree* lclVarNode, GenTree* node);
3944
3945     void fgComputeLife(VARSET_TP&       life,
3946                        GenTree*         startNode,
3947                        GenTree*         endNode,
3948                        VARSET_VALARG_TP volatileVars,
3949                        bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3950
3951     void fgComputeLifeLIR(VARSET_TP& life, BasicBlock* block, VARSET_VALARG_TP volatileVars);
3952
3953     bool fgRemoveDeadStore(GenTree**        pTree,
3954                            LclVarDsc*       varDsc,
3955                            VARSET_VALARG_TP life,
3956                            bool*            doAgain,
3957                            bool* pStmtInfoDirty DEBUGARG(bool* treeModf));
3958
3959     // For updating liveset during traversal AFTER fgComputeLife has completed
3960     VARSET_VALRET_TP fgGetVarBits(GenTree* tree);
3961     VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree);
3962
3963     // Returns the set of live variables after endTree,
3964     // assuming that liveSet is the set of live variables BEFORE tree.
3965     // Requires that fgComputeLife has completed, and that tree is in the same
3966     // statement as endTree, and that it comes before endTree in execution order
3967
3968     VARSET_VALRET_TP fgUpdateLiveSet(VARSET_VALARG_TP liveSet, GenTree* tree, GenTree* endTree)
3969     {
3970         VARSET_TP newLiveSet(VarSetOps::MakeCopy(this, liveSet));
3971         while (tree != nullptr && tree != endTree->gtNext)
3972         {
3973             VarSetOps::AssignNoCopy(this, newLiveSet, fgUpdateLiveSet(newLiveSet, tree));
3974             tree = tree->gtNext;
3975         }
3976         assert(tree == endTree->gtNext);
3977         return newLiveSet;
3978     }
3979
3980     void fgInterBlockLocalVarLiveness();
3981
3982     // The presence of "x op= y" operations presents some difficulties for SSA: this is both a use of some SSA name of
3983     // "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
3984     // whether to treat that as the use or def.  It chooses the "use", and thus the old SSA name.  This map allows us
3985     // to record/recover the "def" SSA number, given the lcl var node for "x" in such a tree.
3986     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, unsigned> NodeToUnsignedMap;
3987     NodeToUnsignedMap* m_opAsgnVarDefSsaNums;
3988     NodeToUnsignedMap* GetOpAsgnVarDefSsaNums()
3989     {
3990         if (m_opAsgnVarDefSsaNums == nullptr)
3991         {
3992             m_opAsgnVarDefSsaNums = new (getAllocator()) NodeToUnsignedMap(getAllocator());
3993         }
3994         return m_opAsgnVarDefSsaNums;
3995     }
3996
3997     // Requires value numbering phase to have completed. Returns the value number ("gtVN") of the
3998     // "tree," EXCEPT in the case of GTF_VAR_USEASG, because the tree node's gtVN member is the
3999     // "use" VN. Performs a lookup into the map of (use asg tree -> def VN.) to return the "def's"
4000     // VN.
4001     inline ValueNum GetUseAsgDefVNOrTreeVN(GenTree* tree);
4002
4003     // Requires that "lcl" has the GTF_VAR_DEF flag set.  Returns the SSA number of "lcl".
4004     // Except: assumes that lcl is a def, and if it is
4005     // a def appearing in "lcl op= rhs" (GTF_VAR_USEASG), looks up and returns the SSA number for the "def",
4006     // rather than the "use" SSA number recorded in the tree "lcl".
4007     inline unsigned GetSsaNumForLocalVarDef(GenTree* lcl);
4008
4009     // Some assignments assign to a local "indirectly": they are part of a comma expression that takes the address
4010     // of the local (or a field thereof), assigns this address to a temp, and uses an indirection of this temp as
4011     // the LHS of the assignment.  This actually arises in exactly one situation.  At the source level we assign one
4012     // struct local to another: "s1 = s2".  This becomes a copyblk.  If "s2" is promoted into  field variables "s2f0",
4013     // ..."s2fn", then the copyblk will morph to a comma expression that takes the address of "s1" and does field-wise
4014     // assignments:
4015     //   (byref addrS1 = &s1,
4016     //    *(addrS1 * offsetof(f0)) = s2f0,
4017     //    ...
4018     //    *(addrS1 * offsetof(fn)) = s2fn)
4019     //
4020     // It would be a shame, given the simple form at the source level, to be unable to track the values in the
4021     // fields of "s1" after this.  But "s1" does not appear in the assignments that modify it.  How, then, to
4022     // give it SSA names and value numbers?
4023     //
4024     // The solution is to use the side table described below to annotate each of the field-wise assignments at the
4025     // end with an instance of the structure below, whose fields are described in the declaration.
4026     struct IndirectAssignmentAnnotation
4027     {
4028         unsigned      m_lclNum;   // The local num that is being indirectly assigned.
4029         FieldSeqNode* m_fieldSeq; // If the LHS of the struct assignment is itself a struct field dereference,
4030                                   // as in "s0.g = s2", then "m_lclNum" would be "s0", and "m_fieldSeq" would
4031                                   // be the singleton field sequence "g".  The individual assignments would
4032                                   // further append the fields of "s.g" to that.
4033         bool m_isEntire;          // True iff this assignment writes all of m_lclNum.  (This can occur if the
4034                                   // structure has a single field).
4035         unsigned m_defSsaNum;     // The new SSA number of "m_lclNum" after the assignment.
4036         unsigned m_useSsaNum;     // Only valid if "m_isEntire" is false; if so, the SSA number of "m_lclNum" before the
4037                                   // assignment.
4038
4039         IndirectAssignmentAnnotation(unsigned      lclNum,
4040                                      FieldSeqNode* fldSeq,
4041                                      bool          isEntire,
4042                                      unsigned      defSsaNum = SsaConfig::RESERVED_SSA_NUM,
4043                                      unsigned      useSsaNum = SsaConfig::RESERVED_SSA_NUM)
4044             : m_lclNum(lclNum), m_fieldSeq(fldSeq), m_isEntire(isEntire), m_defSsaNum(defSsaNum), m_useSsaNum(useSsaNum)
4045         {
4046         }
4047     };
4048     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, IndirectAssignmentAnnotation*> NodeToIndirAssignMap;
4049     NodeToIndirAssignMap* m_indirAssignMap;
4050     NodeToIndirAssignMap* GetIndirAssignMap()
4051     {
4052         if (m_indirAssignMap == nullptr)
4053         {
4054             // Create a CompAllocator that labels sub-structure with CMK_IndirAssignMap, and use that for allocation.
4055             CompAllocator* ialloc = new (this, CMK_IndirAssignMap) CompAllocator(this, CMK_IndirAssignMap);
4056             m_indirAssignMap      = new (ialloc) NodeToIndirAssignMap(ialloc);
4057         }
4058         return m_indirAssignMap;
4059     }
4060
4061     // Performs SSA conversion.
4062     void fgSsaBuild();
4063
4064     // Reset any data structures to the state expected by "fgSsaBuild", so it can be run again.
4065     void fgResetForSsa();
4066
4067     unsigned fgSsaPassesCompleted; // Number of times fgSsaBuild has been run.
4068
4069     // Returns "true" iff lcl "lclNum" should be excluded from SSA.
4070     inline bool fgExcludeFromSsa(unsigned lclNum);
4071
4072     // Returns "true" if a struct temp of the given type requires needs zero init in this block
4073     inline bool fgStructTempNeedsExplicitZeroInit(LclVarDsc* varDsc, BasicBlock* block);
4074
4075     // The value numbers for this compilation.
4076     ValueNumStore* vnStore;
4077
4078 public:
4079     ValueNumStore* GetValueNumStore()
4080     {
4081         return vnStore;
4082     }
4083
4084     // Do value numbering (assign a value number to each
4085     // tree node).
4086     void fgValueNumber();
4087
4088     // Computes new GcHeap VN via the assignment H[elemTypeEq][arrVN][inx][fldSeq] = rhsVN.
4089     // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4090     // The 'indType' is the indirection type of the lhs of the assignment and will typically
4091     // match the element type of the array or fldSeq.  When this type doesn't match
4092     // or if the fldSeq is 'NotAField' we invalidate the array contents H[elemTypeEq][arrVN]
4093     //
4094     ValueNum fgValueNumberArrIndexAssign(CORINFO_CLASS_HANDLE elemTypeEq,
4095                                          ValueNum             arrVN,
4096                                          ValueNum             inxVN,
4097                                          FieldSeqNode*        fldSeq,
4098                                          ValueNum             rhsVN,
4099                                          var_types            indType);
4100
4101     // Requires that "tree" is a GT_IND marked as an array index, and that its address argument
4102     // has been parsed to yield the other input arguments.  If evaluation of the address
4103     // can raise exceptions, those should be captured in the exception set "excVN."
4104     // Assumes that "elemTypeEq" is the (equivalence class rep) of the array element type.
4105     // Marks "tree" with the VN for H[elemTypeEq][arrVN][inx][fldSeq] (for the liberal VN; a new unique
4106     // VN for the conservative VN.)  Also marks the tree's argument as the address of an array element.
4107     // The type tree->TypeGet() will typically match the element type of the array or fldSeq.
4108     // When this type doesn't match or if the fldSeq is 'NotAField' we return a new unique VN
4109     //
4110     ValueNum fgValueNumberArrIndexVal(GenTree*             tree,
4111                                       CORINFO_CLASS_HANDLE elemTypeEq,
4112                                       ValueNum             arrVN,
4113                                       ValueNum             inxVN,
4114                                       ValueNum             excVN,
4115                                       FieldSeqNode*        fldSeq);
4116
4117     // Requires "funcApp" to be a VNF_PtrToArrElem, and "addrXvn" to represent the exception set thrown
4118     // by evaluating the array index expression "tree".  Returns the value number resulting from
4119     // dereferencing the array in the current GcHeap state.  If "tree" is non-null, it must be the
4120     // "GT_IND" that does the dereference, and it is given the returned value number.
4121     ValueNum fgValueNumberArrIndexVal(GenTree* tree, struct VNFuncApp* funcApp, ValueNum addrXvn);
4122
4123     // Compute the value number for a byref-exposed load of the given type via the given pointerVN.
4124     ValueNum fgValueNumberByrefExposedLoad(var_types type, ValueNum pointerVN);
4125
4126     unsigned fgVNPassesCompleted; // Number of times fgValueNumber has been run.
4127
4128     // Utility functions for fgValueNumber.
4129
4130     // Perform value-numbering for the trees in "blk".
4131     void fgValueNumberBlock(BasicBlock* blk);
4132
4133     // Requires that "entryBlock" is the entry block of loop "loopNum", and that "loopNum" is the
4134     // innermost loop of which "entryBlock" is the entry.  Returns the value number that should be
4135     // assumed for the memoryKind at the start "entryBlk".
4136     ValueNum fgMemoryVNForLoopSideEffects(MemoryKind memoryKind, BasicBlock* entryBlock, unsigned loopNum);
4137
4138     // Called when an operation (performed by "tree", described by "msg") may cause the GcHeap to be mutated.
4139     // As GcHeap is a subset of ByrefExposed, this will also annotate the ByrefExposed mutation.
4140     void fgMutateGcHeap(GenTree* tree DEBUGARG(const char* msg));
4141
4142     // Called when an operation (performed by "tree", described by "msg") may cause an address-exposed local to be
4143     // mutated.
4144     void fgMutateAddressExposedLocal(GenTree* tree DEBUGARG(const char* msg));
4145
4146     // For a GC heap store at curTree, record the new curMemoryVN's and update curTree's MemorySsaMap.
4147     // As GcHeap is a subset of ByrefExposed, this will also record the ByrefExposed store.
4148     void recordGcHeapStore(GenTree* curTree, ValueNum gcHeapVN DEBUGARG(const char* msg));
4149
4150     // For a store to an address-exposed local at curTree, record the new curMemoryVN and update curTree's MemorySsaMap.
4151     void recordAddressExposedLocalStore(GenTree* curTree, ValueNum memoryVN DEBUGARG(const char* msg));
4152
4153     // Tree caused an update in the current memory VN.  If "tree" has an associated heap SSA #, record that
4154     // value in that SSA #.
4155     void fgValueNumberRecordMemorySsa(MemoryKind memoryKind, GenTree* tree);
4156
4157     // The input 'tree' is a leaf node that is a constant
4158     // Assign the proper value number to the tree
4159     void fgValueNumberTreeConst(GenTree* tree);
4160
4161     // Assumes that all inputs to "tree" have had value numbers assigned; assigns a VN to tree.
4162     // (With some exceptions: the VN of the lhs of an assignment is assigned as part of the
4163     // assignment.)
4164     // If "evalAsgLhsInd" is true, evaluate a GT_IND node, even if it's labeled as the LHS of
4165     // an assignment.
4166     void fgValueNumberTree(GenTree* tree, bool evalAsgLhsInd = false);
4167
4168     // Does value-numbering for a block assignment.
4169     void fgValueNumberBlockAssignment(GenTree* tree, bool evalAsgLhsInd);
4170
4171     // Does value-numbering for a cast tree.
4172     void fgValueNumberCastTree(GenTree* tree);
4173
4174     // Does value-numbering for an intrinsic tree.
4175     void fgValueNumberIntrinsic(GenTree* tree);
4176
4177     // Does value-numbering for a call.  We interpret some helper calls.
4178     void fgValueNumberCall(GenTreeCall* call);
4179
4180     // The VN of some nodes in "args" may have changed -- reassign VNs to the arg list nodes.
4181     void fgUpdateArgListVNs(GenTreeArgList* args);
4182
4183     // Does value-numbering for a helper "call" that has a VN function symbol "vnf".
4184     void fgValueNumberHelperCallFunc(GenTreeCall* call, VNFunc vnf, ValueNumPair vnpExc);
4185
4186     // Requires "helpCall" to be a helper call.  Assigns it a value number;
4187     // we understand the semantics of some of the calls.  Returns "true" if
4188     // the call may modify the heap (we assume arbitrary memory side effects if so).
4189     bool fgValueNumberHelperCall(GenTreeCall* helpCall);
4190
4191     // Requires "helpFunc" to be pure.  Returns the corresponding VNFunc.
4192     VNFunc fgValueNumberHelperMethVNFunc(CorInfoHelpFunc helpFunc);
4193
4194     // These are the current value number for the memory implicit variables while
4195     // doing value numbering.  These are the value numbers under the "liberal" interpretation
4196     // of memory values; the "conservative" interpretation needs no VN, since every access of
4197     // memory yields an unknown value.
4198     ValueNum fgCurMemoryVN[MemoryKindCount];
4199
4200     // Return a "pseudo"-class handle for an array element type.  If "elemType" is TYP_STRUCT,
4201     // requires "elemStructType" to be non-null (and to have a low-order zero).  Otherwise, low order bit
4202     // is 1, and the rest is an encoding of "elemTyp".
4203     static CORINFO_CLASS_HANDLE EncodeElemType(var_types elemTyp, CORINFO_CLASS_HANDLE elemStructType)
4204     {
4205         if (elemStructType != nullptr)
4206         {
4207             assert(varTypeIsStruct(elemTyp) || elemTyp == TYP_REF || elemTyp == TYP_BYREF ||
4208                    varTypeIsIntegral(elemTyp));
4209             assert((size_t(elemStructType) & 0x1) == 0x0); // Make sure the encoding below is valid.
4210             return elemStructType;
4211         }
4212         else
4213         {
4214             elemTyp = varTypeUnsignedToSigned(elemTyp);
4215             return CORINFO_CLASS_HANDLE(size_t(elemTyp) << 1 | 0x1);
4216         }
4217     }
4218     // If "clsHnd" is the result of an "EncodePrim" call, returns true and sets "*pPrimType" to the
4219     // var_types it represents.  Otherwise, returns TYP_STRUCT (on the assumption that "clsHnd" is
4220     // the struct type of the element).
4221     static var_types DecodeElemType(CORINFO_CLASS_HANDLE clsHnd)
4222     {
4223         size_t clsHndVal = size_t(clsHnd);
4224         if (clsHndVal & 0x1)
4225         {
4226             return var_types(clsHndVal >> 1);
4227         }
4228         else
4229         {
4230             return TYP_STRUCT;
4231         }
4232     }
4233
4234     // Convert a BYTE which represents the VM's CorInfoGCtype to the JIT's var_types
4235     var_types getJitGCType(BYTE gcType);
4236
4237     enum structPassingKind
4238     {
4239         SPK_Unknown,       // Invalid value, never returned
4240         SPK_PrimitiveType, // The struct is passed/returned using a primitive type.
4241         SPK_ByValue,       // The struct is passed/returned by value (using the ABI rules)
4242                            //  for ARM64 and UNIX_X64 in multiple registers. (when all of the
4243                            //   parameters registers are used, then the stack will be used)
4244                            //  for X86 passed on the stack, for ARM32 passed in registers
4245                            //   or the stack or split between registers and the stack.
4246         SPK_ByValueAsHfa,  // The struct is passed/returned as an HFA in multiple registers.
4247         SPK_ByReference
4248     }; // The struct is passed/returned by reference to a copy/buffer.
4249
4250     // Get the "primitive" type that is is used when we are given a struct of size 'structSize'.
4251     // For pointer sized structs the 'clsHnd' is used to determine if the struct contains GC ref.
4252     // A "primitive" type is one of the scalar types: byte, short, int, long, ref, float, double
4253     // If we can't or shouldn't use a "primitive" type then TYP_UNKNOWN is returned.
4254     //
4255     var_types getPrimitiveTypeForStruct(unsigned structSize, CORINFO_CLASS_HANDLE clsHnd);
4256
4257     // Get the type that is used to pass values of the given struct type.
4258     // If you have already retrieved the struct size then pass it as the optional third argument
4259     //
4260     var_types getArgTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4261                                   structPassingKind*   wbPassStruct,
4262                                   unsigned             structSize = 0);
4263
4264     // Get the type that is used to return values of the given struct type.
4265     // If you have already retrieved the struct size then pass it as the optional third argument
4266     //
4267     var_types getReturnTypeForStruct(CORINFO_CLASS_HANDLE clsHnd,
4268                                      structPassingKind*   wbPassStruct = nullptr,
4269                                      unsigned             structSize   = 0);
4270
4271 #ifdef DEBUG
4272     // Print a representation of "vnp" or "vn" on standard output.
4273     // If "level" is non-zero, we also print out a partial expansion of the value.
4274     void vnpPrint(ValueNumPair vnp, unsigned level);
4275     void vnPrint(ValueNum vn, unsigned level);
4276 #endif
4277
4278     bool fgDominate(BasicBlock* b1, BasicBlock* b2); // Return true if b1 dominates b2
4279
4280     // Dominator computation member functions
4281     // Not exposed outside Compiler
4282 protected:
4283     bool fgReachable(BasicBlock* b1, BasicBlock* b2); // Returns true if block b1 can reach block b2
4284
4285     void fgComputeDoms(); // Computes the immediate dominators for each basic block in the
4286                           // flow graph.  We first assume the fields bbIDom on each
4287                           // basic block are invalid. This computation is needed later
4288                           // by fgBuildDomTree to build the dominance tree structure.
4289                           // Based on: A Simple, Fast Dominance Algorithm
4290                           // by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy
4291
4292     void fgCompDominatedByExceptionalEntryBlocks();
4293
4294     BlockSet_ValRet_T fgGetDominatorSet(BasicBlock* block); // Returns a set of blocks that dominate the given block.
4295     // Note: this is relatively slow compared to calling fgDominate(),
4296     // especially if dealing with a single block versus block check.
4297
4298     void fgComputeReachabilitySets(); // Compute bbReach sets. (Also sets BBF_GC_SAFE_POINT flag on blocks.)
4299
4300     void fgComputeEnterBlocksSet(); // Compute the set of entry blocks, 'fgEnterBlks'.
4301
4302     bool fgRemoveUnreachableBlocks(); // Remove blocks determined to be unreachable by the bbReach sets.
4303
4304     void fgComputeReachability(); // Perform flow graph node reachability analysis.
4305
4306     BasicBlock* fgIntersectDom(BasicBlock* a, BasicBlock* b); // Intersect two immediate dominator sets.
4307
4308     void fgDfsInvPostOrder(); // In order to compute dominance using fgIntersectDom, the flow graph nodes must be
4309                               // processed in topological sort, this function takes care of that.
4310
4311     void fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count);
4312
4313     BlockSet_ValRet_T fgDomFindStartNodes(); // Computes which basic blocks don't have incoming edges in the flow graph.
4314                                              // Returns this as a set.
4315
4316     BlockSet_ValRet_T fgDomTreeEntryNodes(BasicBlockList** domTree); // Computes which nodes in the dominance forest are
4317                                                                      // root nodes. Returns this as a set.
4318
4319 #ifdef DEBUG
4320     void fgDispDomTree(BasicBlockList** domTree); // Helper that prints out the Dominator Tree in debug builds.
4321 #endif                                            // DEBUG
4322
4323     void fgBuildDomTree(); // Once we compute all the immediate dominator sets for each node in the flow graph
4324                            // (performed by fgComputeDoms), this procedure builds the dominance tree represented
4325                            // adjacency lists.
4326
4327     // In order to speed up the queries of the form 'Does A dominates B', we can perform a DFS preorder and postorder
4328     // traversal of the dominance tree and the dominance query will become A dominates B iif preOrder(A) <= preOrder(B)
4329     // && postOrder(A) >= postOrder(B) making the computation O(1).
4330     void fgTraverseDomTree(unsigned bbNum, BasicBlockList** domTree, unsigned* preNum, unsigned* postNum);
4331
4332     // When the flow graph changes, we need to update the block numbers, predecessor lists, reachability sets, and
4333     // dominators.
4334     void fgUpdateChangedFlowGraph();
4335
4336 public:
4337     // Compute the predecessors of the blocks in the control flow graph.
4338     void fgComputePreds();
4339
4340     // Remove all predecessor information.
4341     void fgRemovePreds();
4342
4343     // Compute the cheap flow graph predecessors lists. This is used in some early phases
4344     // before the full predecessors lists are computed.
4345     void fgComputeCheapPreds();
4346
4347 private:
4348     void fgAddCheapPred(BasicBlock* block, BasicBlock* blockPred);
4349
4350     void fgRemoveCheapPred(BasicBlock* block, BasicBlock* blockPred);
4351
4352 public:
4353     enum GCPollType
4354     {
4355         GCPOLL_NONE,
4356         GCPOLL_CALL,
4357         GCPOLL_INLINE
4358     };
4359
4360     // Initialize the per-block variable sets (used for liveness analysis).
4361     void fgInitBlockVarSets();
4362
4363     // true if we've gone through and created GC Poll calls.
4364     bool fgGCPollsCreated;
4365     void fgMarkGCPollBlocks();
4366     void fgCreateGCPolls();
4367     bool fgCreateGCPoll(GCPollType pollType, BasicBlock* block);
4368
4369     // Requires that "block" is a block that returns from
4370     // a finally.  Returns the number of successors (jump targets of
4371     // of blocks in the covered "try" that did a "LEAVE".)
4372     unsigned fgNSuccsOfFinallyRet(BasicBlock* block);
4373
4374     // Requires that "block" is a block that returns (in the sense of BBJ_EHFINALLYRET) from
4375     // a finally.  Returns its "i"th successor (jump targets of
4376     // of blocks in the covered "try" that did a "LEAVE".)
4377     // Requires that "i" < fgNSuccsOfFinallyRet(block).
4378     BasicBlock* fgSuccOfFinallyRet(BasicBlock* block, unsigned i);
4379
4380 private:
4381     // Factor out common portions of the impls of the methods above.
4382     void fgSuccOfFinallyRetWork(BasicBlock* block, unsigned i, BasicBlock** bres, unsigned* nres);
4383
4384 public:
4385     // For many purposes, it is desirable to be able to enumerate the *distinct* targets of a switch statement,
4386     // skipping duplicate targets.  (E.g., in flow analyses that are only interested in the set of possible targets.)
4387     // SwitchUniqueSuccSet contains the non-duplicated switch targets.
4388     // (Code that modifies the jump table of a switch has an obligation to call Compiler::UpdateSwitchTableTarget,
4389     // which in turn will call the "UpdateTarget" method of this type if a SwitchUniqueSuccSet has already
4390     // been computed for the switch block.  If a switch block is deleted or is transformed into a non-switch,
4391     // we leave the entry associated with the block, but it will no longer be accessed.)
4392     struct SwitchUniqueSuccSet
4393     {
4394         unsigned     numDistinctSuccs; // Number of distinct targets of the switch.
4395         BasicBlock** nonDuplicates;    // Array of "numDistinctSuccs", containing all the distinct switch target
4396                                        // successors.
4397
4398         // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4399         // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4400         // remove it from "this", and ensure that "to" is a member.  Use "alloc" to do any required allocation.
4401         void UpdateTarget(CompAllocator* alloc, BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4402     };
4403
4404     typedef JitHashTable<BasicBlock*, JitPtrKeyFuncs<BasicBlock>, SwitchUniqueSuccSet> BlockToSwitchDescMap;
4405
4406 private:
4407     // Maps BasicBlock*'s that end in switch statements to SwitchUniqueSuccSets that allow
4408     // iteration over only the distinct successors.
4409     BlockToSwitchDescMap* m_switchDescMap;
4410
4411 public:
4412     BlockToSwitchDescMap* GetSwitchDescMap(bool createIfNull = true)
4413     {
4414         if ((m_switchDescMap == nullptr) && createIfNull)
4415         {
4416             m_switchDescMap = new (getAllocator()) BlockToSwitchDescMap(getAllocator());
4417         }
4418         return m_switchDescMap;
4419     }
4420
4421     // Invalidate the map of unique switch block successors. For example, since the hash key of the map
4422     // depends on block numbers, we must invalidate the map when the blocks are renumbered, to ensure that
4423     // we don't accidentally look up and return the wrong switch data.
4424     void InvalidateUniqueSwitchSuccMap()
4425     {
4426         m_switchDescMap = nullptr;
4427     }
4428
4429     // Requires "switchBlock" to be a block that ends in a switch.  Returns
4430     // the corresponding SwitchUniqueSuccSet.
4431     SwitchUniqueSuccSet GetDescriptorForSwitch(BasicBlock* switchBlk);
4432
4433     // The switch block "switchBlk" just had an entry with value "from" modified to the value "to".
4434     // Update "this" as necessary: if "from" is no longer an element of the jump table of "switchBlk",
4435     // remove it from "this", and ensure that "to" is a member.
4436     void UpdateSwitchTableTarget(BasicBlock* switchBlk, BasicBlock* from, BasicBlock* to);
4437
4438     // Remove the "SwitchUniqueSuccSet" of "switchBlk" in the BlockToSwitchDescMap.
4439     void fgInvalidateSwitchDescMapEntry(BasicBlock* switchBlk);
4440
4441     BasicBlock* fgFirstBlockOfHandler(BasicBlock* block);
4442
4443     flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred);
4444
4445     flowList* fgGetPredForBlock(BasicBlock* block, BasicBlock* blockPred, flowList*** ptrToPred);
4446
4447     flowList* fgSpliceOutPred(BasicBlock* block, BasicBlock* blockPred);
4448
4449     flowList* fgRemoveRefPred(BasicBlock* block, BasicBlock* blockPred);
4450
4451     flowList* fgRemoveAllRefPreds(BasicBlock* block, BasicBlock* blockPred);
4452
4453     flowList* fgRemoveAllRefPreds(BasicBlock* block, flowList** ptrToPred);
4454
4455     void fgRemoveBlockAsPred(BasicBlock* block);
4456
4457     void fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock);
4458
4459     void fgReplaceSwitchJumpTarget(BasicBlock* blockSwitch, BasicBlock* newTarget, BasicBlock* oldTarget);
4460
4461     void fgReplaceJumpTarget(BasicBlock* block, BasicBlock* newTarget, BasicBlock* oldTarget);
4462
4463     void fgReplacePred(BasicBlock* block, BasicBlock* oldPred, BasicBlock* newPred);
4464
4465     flowList* fgAddRefPred(BasicBlock* block,
4466                            BasicBlock* blockPred,
4467                            flowList*   oldEdge           = nullptr,
4468                            bool        initializingPreds = false); // Only set to 'true' when we are computing preds in
4469                                                                    // fgComputePreds()
4470
4471     void fgFindBasicBlocks();
4472
4473     bool fgIsBetterFallThrough(BasicBlock* bCur, BasicBlock* bAlt);
4474
4475     bool fgCheckEHCanInsertAfterBlock(BasicBlock* blk, unsigned regionIndex, bool putInTryRegion);
4476
4477     BasicBlock* fgFindInsertPoint(unsigned    regionIndex,
4478                                   bool        putInTryRegion,
4479                                   BasicBlock* startBlk,
4480                                   BasicBlock* endBlk,
4481                                   BasicBlock* nearBlk,
4482                                   BasicBlock* jumpBlk,
4483                                   bool        runRarely);
4484
4485     unsigned fgGetNestingLevel(BasicBlock* block, unsigned* pFinallyNesting = nullptr);
4486
4487     void fgRemoveEmptyBlocks();
4488
4489     void fgRemoveStmt(BasicBlock* block, GenTree* stmt, bool updateRefCnt = true);
4490
4491     bool fgCheckRemoveStmt(BasicBlock* block, GenTree* stmt);
4492
4493     void fgCreateLoopPreHeader(unsigned lnum);
4494
4495     void fgUnreachableBlock(BasicBlock* block);
4496
4497     void fgRemoveConditionalJump(BasicBlock* block);
4498
4499     BasicBlock* fgLastBBInMainFunction();
4500
4501     BasicBlock* fgEndBBAfterMainFunction();
4502
4503     void fgUnlinkRange(BasicBlock* bBeg, BasicBlock* bEnd);
4504
4505     void fgRemoveBlock(BasicBlock* block, bool unreachable);
4506
4507     bool fgCanCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4508
4509     void fgCompactBlocks(BasicBlock* block, BasicBlock* bNext);
4510
4511     void fgUpdateLoopsAfterCompacting(BasicBlock* block, BasicBlock* bNext);
4512
4513     BasicBlock* fgConnectFallThrough(BasicBlock* bSrc, BasicBlock* bDst);
4514
4515     bool fgRenumberBlocks();
4516
4517     bool fgExpandRarelyRunBlocks();
4518
4519     bool fgEhAllowsMoveBlock(BasicBlock* bBefore, BasicBlock* bAfter);
4520
4521     void fgMoveBlocksAfter(BasicBlock* bStart, BasicBlock* bEnd, BasicBlock* insertAfterBlk);
4522
4523     enum FG_RELOCATE_TYPE
4524     {
4525         FG_RELOCATE_TRY,    // relocate the 'try' region
4526         FG_RELOCATE_HANDLER // relocate the handler region (including the filter if necessary)
4527     };
4528     BasicBlock* fgRelocateEHRange(unsigned regionIndex, FG_RELOCATE_TYPE relocateType);
4529
4530 #if FEATURE_EH_FUNCLETS
4531 #if defined(_TARGET_ARM_)
4532     void fgClearFinallyTargetBit(BasicBlock* block);
4533 #endif // defined(_TARGET_ARM_)
4534     bool fgIsIntraHandlerPred(BasicBlock* predBlock, BasicBlock* block);
4535     bool fgAnyIntraHandlerPreds(BasicBlock* block);
4536     void fgInsertFuncletPrologBlock(BasicBlock* block);
4537     void fgCreateFuncletPrologBlocks();
4538     void fgCreateFunclets();
4539 #else  // !FEATURE_EH_FUNCLETS
4540     bool fgRelocateEHRegions();
4541 #endif // !FEATURE_EH_FUNCLETS
4542
4543     bool fgOptimizeUncondBranchToSimpleCond(BasicBlock* block, BasicBlock* target);
4544
4545     bool fgBlockEndFavorsTailDuplication(BasicBlock* block);
4546
4547     bool fgBlockIsGoodTailDuplicationCandidate(BasicBlock* block);
4548
4549     bool fgOptimizeFallthroughTailDup(BasicBlock* block, BasicBlock* target);
4550
4551     bool fgOptimizeEmptyBlock(BasicBlock* block);
4552
4553     bool fgOptimizeBranchToEmptyUnconditional(BasicBlock* block, BasicBlock* bDest);
4554
4555     bool fgOptimizeBranch(BasicBlock* bJump);
4556
4557     bool fgOptimizeSwitchBranches(BasicBlock* block);
4558
4559     bool fgOptimizeBranchToNext(BasicBlock* block, BasicBlock* bNext, BasicBlock* bPrev);
4560
4561     bool fgOptimizeSwitchJumps();
4562 #ifdef DEBUG
4563     void fgPrintEdgeWeights();
4564 #endif
4565     void fgComputeEdgeWeights();
4566
4567     void fgReorderBlocks();
4568
4569     void fgDetermineFirstColdBlock();
4570
4571     bool fgIsForwardBranch(BasicBlock* bJump, BasicBlock* bSrc = nullptr);
4572
4573     bool fgUpdateFlowGraph(bool doTailDup = false);
4574
4575     void fgFindOperOrder();
4576
4577     // method that returns if you should split here
4578     typedef bool(fgSplitPredicate)(GenTree* tree, GenTree* parent, fgWalkData* data);
4579
4580     void fgSetBlockOrder();
4581
4582     void fgRemoveReturnBlock(BasicBlock* block);
4583
4584     /* Helper code that has been factored out */
4585     inline void fgConvertBBToThrowBB(BasicBlock* block);
4586
4587     bool fgCastNeeded(GenTree* tree, var_types toType);
4588     GenTree* fgDoNormalizeOnStore(GenTree* tree);
4589     GenTree* fgMakeTmpArgNode(
4590         unsigned tmpVarNum FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(const bool passedInRegisters));
4591
4592     // The following check for loops that don't execute calls
4593     bool fgLoopCallMarked;
4594
4595     void fgLoopCallTest(BasicBlock* srcBB, BasicBlock* dstBB);
4596     void fgLoopCallMark();
4597
4598     void fgMarkLoopHead(BasicBlock* block);
4599
4600     unsigned fgGetCodeEstimate(BasicBlock* block);
4601
4602 #if DUMP_FLOWGRAPHS
4603     const char* fgProcessEscapes(const char* nameIn, escapeMapping_t* map);
4604     FILE* fgOpenFlowGraphFile(bool* wbDontClose, Phases phase, LPCWSTR type);
4605     bool fgDumpFlowGraph(Phases phase);
4606
4607 #endif // DUMP_FLOWGRAPHS
4608
4609 #ifdef DEBUG
4610     void fgDispDoms();
4611     void fgDispReach();
4612     void fgDispBBLiveness(BasicBlock* block);
4613     void fgDispBBLiveness();
4614     void fgTableDispBasicBlock(BasicBlock* block, int ibcColWidth = 0);
4615     void fgDispBasicBlocks(BasicBlock* firstBlock, BasicBlock* lastBlock, bool dumpTrees);
4616     void fgDispBasicBlocks(bool dumpTrees = false);
4617     void fgDumpStmtTree(GenTree* stmt, unsigned bbNum);
4618     void fgDumpBlock(BasicBlock* block);
4619     void fgDumpTrees(BasicBlock* firstBlock, BasicBlock* lastBlock);
4620
4621     static fgWalkPreFn fgStress64RsltMulCB;
4622     void               fgStress64RsltMul();
4623     void               fgDebugCheckUpdate();
4624     void fgDebugCheckBBlist(bool checkBBNum = false, bool checkBBRefs = true);
4625     void fgDebugCheckBlockLinks();
4626     void fgDebugCheckLinks(bool morphTrees = false);
4627     void fgDebugCheckStmtsList(BasicBlock* block, bool morphTrees);
4628     void fgDebugCheckNodeLinks(BasicBlock* block, GenTree* stmt);
4629     void fgDebugCheckNodesUniqueness();
4630
4631     void fgDebugCheckFlags(GenTree* tree);
4632     void fgDebugCheckFlagsHelper(GenTree* tree, unsigned treeFlags, unsigned chkFlags);
4633     void fgDebugCheckTryFinallyExits();
4634 #endif
4635
4636 #ifdef LEGACY_BACKEND
4637     static void fgOrderBlockOps(GenTree*   tree,
4638                                 regMaskTP  reg0,
4639                                 regMaskTP  reg1,
4640                                 regMaskTP  reg2,
4641                                 GenTree**  opsPtr,   // OUT
4642                                 regMaskTP* regsPtr); // OUT
4643 #endif                                               // LEGACY_BACKEND
4644
4645     static GenTree* fgGetFirstNode(GenTree* tree);
4646     static bool fgTreeIsInStmt(GenTree* tree, GenTreeStmt* stmt);
4647     void fgTraverseRPO();
4648
4649     //--------------------- Walking the trees in the IR -----------------------
4650
4651     struct fgWalkData
4652     {
4653         Compiler*     compiler;
4654         fgWalkPreFn*  wtprVisitorFn;
4655         fgWalkPostFn* wtpoVisitorFn;
4656         void*         pCallbackData; // user-provided data
4657         bool          wtprLclsOnly;  // whether to only visit lclvar nodes
4658         GenTree*      parent;        // parent of current node, provided to callback
4659         GenTreeStack* parentStack;   // stack of parent nodes, if asked for
4660 #ifdef DEBUG
4661         bool printModified; // callback can use this
4662 #endif
4663     };
4664
4665     fgWalkResult fgWalkTreePre(GenTree**    pTree,
4666                                fgWalkPreFn* visitor,
4667                                void*        pCallBackData = nullptr,
4668                                bool         lclVarsOnly   = false,
4669                                bool         computeStack  = false);
4670
4671     fgWalkResult fgWalkTree(GenTree**     pTree,
4672                             fgWalkPreFn*  preVisitor,
4673                             fgWalkPostFn* postVisitor,
4674                             void*         pCallBackData = nullptr);
4675
4676     void fgWalkAllTreesPre(fgWalkPreFn* visitor, void* pCallBackData);
4677
4678     //----- Postorder
4679
4680     fgWalkResult fgWalkTreePost(GenTree**     pTree,
4681                                 fgWalkPostFn* visitor,
4682                                 void*         pCallBackData = nullptr,
4683                                 bool          computeStack  = false);
4684
4685     // An fgWalkPreFn that looks for expressions that have inline throws in
4686     // minopts mode. Basically it looks for tress with gtOverflowEx() or
4687     // GTF_IND_RNGCHK.  It returns WALK_ABORT if one is found.  It
4688     // returns WALK_SKIP_SUBTREES if GTF_EXCEPT is not set (assumes flags
4689     // properly propagated to parent trees).  It returns WALK_CONTINUE
4690     // otherwise.
4691     static fgWalkResult fgChkThrowCB(GenTree** pTree, Compiler::fgWalkData* data);
4692     static fgWalkResult fgChkLocAllocCB(GenTree** pTree, Compiler::fgWalkData* data);
4693     static fgWalkResult fgChkQmarkCB(GenTree** pTree, Compiler::fgWalkData* data);
4694
4695     /**************************************************************************
4696      *                          PROTECTED
4697      *************************************************************************/
4698
4699 protected:
4700     friend class SsaBuilder;
4701     friend struct ValueNumberState;
4702
4703     //--------------------- Detect the basic blocks ---------------------------
4704
4705     BasicBlock** fgBBs; // Table of pointers to the BBs
4706
4707     void        fgInitBBLookup();
4708     BasicBlock* fgLookupBB(unsigned addr);
4709
4710     void fgMarkJumpTarget(BYTE* jumpTarget, IL_OFFSET offs);
4711
4712     void fgFindJumpTargets(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4713
4714     void fgMarkBackwardJump(BasicBlock* startBlock, BasicBlock* endBlock);
4715
4716     void fgLinkBasicBlocks();
4717
4718     unsigned fgMakeBasicBlocks(const BYTE* codeAddr, IL_OFFSET codeSize, BYTE* jumpTarget);
4719
4720     void fgCheckBasicBlockControlFlow();
4721
4722     void fgControlFlowPermitted(BasicBlock* blkSrc,
4723                                 BasicBlock* blkDest,
4724                                 BOOL        IsLeave = false /* is the src a leave block */);
4725
4726     bool fgFlowToFirstBlockOfInnerTry(BasicBlock* blkSrc, BasicBlock* blkDest, bool sibling);
4727
4728     void fgObserveInlineConstants(OPCODE opcode, const FgStack& stack, bool isInlining);
4729
4730     void fgAdjustForAddressExposedOrWrittenThis();
4731
4732     bool                        fgProfileData_ILSizeMismatch;
4733     ICorJitInfo::ProfileBuffer* fgProfileBuffer;
4734     ULONG                       fgProfileBufferCount;
4735     ULONG                       fgNumProfileRuns;
4736
4737     unsigned fgStressBBProf()
4738     {
4739 #ifdef DEBUG
4740         unsigned result = JitConfig.JitStressBBProf();
4741         if (result == 0)
4742         {
4743             if (compStressCompile(STRESS_BB_PROFILE, 15))
4744             {
4745                 result = 1;
4746             }
4747         }
4748         return result;
4749 #else
4750         return 0;
4751 #endif
4752     }
4753
4754     bool fgHaveProfileData();
4755     bool fgGetProfileWeightForBasicBlock(IL_OFFSET offset, unsigned* weight);
4756     void fgInstrumentMethod();
4757
4758 public:
4759     // fgIsUsingProfileWeights - returns true if we have real profile data for this method
4760     //                           or if we have some fake profile data for the stress mode
4761     bool fgIsUsingProfileWeights()
4762     {
4763         return (fgHaveProfileData() || fgStressBBProf());
4764     }
4765
4766     // fgProfileRunsCount - returns total number of scenario runs for the profile data
4767     //                      or BB_UNITY_WEIGHT when we aren't using profile data.
4768     unsigned fgProfileRunsCount()
4769     {
4770         return fgIsUsingProfileWeights() ? fgNumProfileRuns : BB_UNITY_WEIGHT;
4771     }
4772
4773 //-------- Insert a statement at the start or end of a basic block --------
4774
4775 #ifdef DEBUG
4776 public:
4777     static bool fgBlockContainsStatementBounded(BasicBlock* block, GenTree* stmt, bool answerOnBoundExceeded = true);
4778 #endif
4779
4780 public:
4781     GenTreeStmt* fgInsertStmtAtEnd(BasicBlock* block, GenTree* node);
4782
4783 public: // Used by linear scan register allocation
4784     GenTreeStmt* fgInsertStmtNearEnd(BasicBlock* block, GenTree* node);
4785
4786 private:
4787     GenTree* fgInsertStmtAtBeg(BasicBlock* block, GenTree* stmt);
4788     GenTree* fgInsertStmtAfter(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
4789
4790 public: // Used by linear scan register allocation
4791     GenTree* fgInsertStmtBefore(BasicBlock* block, GenTree* insertionPoint, GenTree* stmt);
4792
4793 private:
4794     GenTree* fgInsertStmtListAfter(BasicBlock* block, GenTree* stmtAfter, GenTree* stmtList);
4795
4796     GenTree* fgMorphSplitTree(GenTree** splitPoint, GenTree* stmt, BasicBlock* blk);
4797
4798     //                  Create a new temporary variable to hold the result of *ppTree,
4799     //                  and transform the graph accordingly.
4800     GenTree* fgInsertCommaFormTemp(GenTree** ppTree, CORINFO_CLASS_HANDLE structType = nullptr);
4801     GenTree* fgMakeMultiUse(GenTree** ppTree);
4802
4803 private:
4804     //                  Recognize a bitwise rotation pattern and convert into a GT_ROL or a GT_ROR node.
4805     GenTree* fgRecognizeAndMorphBitwiseRotation(GenTree* tree);
4806     bool fgOperIsBitwiseRotationRoot(genTreeOps oper);
4807
4808     //-------- Determine the order in which the trees will be evaluated -------
4809
4810     unsigned fgTreeSeqNum;
4811     GenTree* fgTreeSeqLst;
4812     GenTree* fgTreeSeqBeg;
4813
4814     GenTree* fgSetTreeSeq(GenTree* tree, GenTree* prev = nullptr, bool isLIR = false);
4815     void fgSetTreeSeqHelper(GenTree* tree, bool isLIR);
4816     void fgSetTreeSeqFinish(GenTree* tree, bool isLIR);
4817     void fgSetStmtSeq(GenTree* tree);
4818     void fgSetBlockOrder(BasicBlock* block);
4819
4820     //------------------------- Morphing --------------------------------------
4821
4822     unsigned fgPtrArgCntCur;
4823     unsigned fgPtrArgCntMax;
4824
4825 public:
4826     //------------------------------------------------------------------------
4827     // fgGetPtrArgCntMax: Return the maximum number of pointer-sized stack arguments that calls inside this method
4828     // can push on the stack. This value is calculated during morph.
4829     //
4830     // Return Value:
4831     //    Returns fgPtrArgCntMax, that is a private field.
4832     //
4833     unsigned fgGetPtrArgCntMax() const
4834     {
4835         return fgPtrArgCntMax;
4836     }
4837
4838     //------------------------------------------------------------------------
4839     // fgSetPtrArgCntMax: Set the maximum number of pointer-sized stack arguments that calls inside this method
4840     // can push on the stack. This function is used during StackLevelSetter to fix incorrect morph calculations.
4841     //
4842     void fgSetPtrArgCntMax(unsigned argCntMax)
4843     {
4844         fgPtrArgCntMax = argCntMax;
4845     }
4846
4847 private:
4848     hashBv* fgOutgoingArgTemps;
4849     hashBv* fgCurrentlyInUseArgTemps;
4850
4851     bool compCanEncodePtrArgCntMax();
4852
4853     void fgSetRngChkTarget(GenTree* tree, bool delay = true);
4854
4855     BasicBlock* fgSetRngChkTargetInner(SpecialCodeKind kind, bool delay, unsigned* stkDepth);
4856
4857 #if REARRANGE_ADDS
4858     void fgMoveOpsLeft(GenTree* tree);
4859 #endif
4860
4861     bool fgIsCommaThrow(GenTree* tree, bool forFolding = false);
4862
4863     bool fgIsThrow(GenTree* tree);
4864
4865     bool fgInDifferentRegions(BasicBlock* blk1, BasicBlock* blk2);
4866     bool fgIsBlockCold(BasicBlock* block);
4867
4868     GenTree* fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper);
4869
4870     GenTree* fgMorphIntoHelperCall(GenTree* tree, int helper, GenTreeArgList* args);
4871
4872     GenTree* fgMorphStackArgForVarArgs(unsigned lclNum, var_types varType, unsigned lclOffs);
4873
4874     bool fgMorphRelopToQmark(GenTree* tree);
4875
4876     // A "MorphAddrContext" carries information from the surrounding context.  If we are evaluating a byref address,
4877     // it is useful to know whether the address will be immediately dereferenced, or whether the address value will
4878     // be used, perhaps by passing it as an argument to a called method.  This affects how null checking is done:
4879     // for sufficiently small offsets, we can rely on OS page protection to implicitly null-check addresses that we
4880     // know will be dereferenced.  To know that reliance on implicit null checking is sound, we must further know that
4881     // all offsets between the top-level indirection and the bottom are constant, and that their sum is sufficiently
4882     // small; hence the other fields of MorphAddrContext.
4883     enum MorphAddrContextKind
4884     {
4885         MACK_Ind,
4886         MACK_Addr,
4887     };
4888     struct MorphAddrContext
4889     {
4890         MorphAddrContextKind m_kind;
4891         bool                 m_allConstantOffsets; // Valid only for "m_kind == MACK_Ind".  True iff all offsets between
4892                                                    // top-level indirection and here have been constants.
4893         size_t m_totalOffset; // Valid only for "m_kind == MACK_Ind", and if "m_allConstantOffsets" is true.
4894                               // In that case, is the sum of those constant offsets.
4895
4896         MorphAddrContext(MorphAddrContextKind kind) : m_kind(kind), m_allConstantOffsets(true), m_totalOffset(0)
4897         {
4898         }
4899     };
4900
4901     // A MACK_CopyBlock context is immutable, so we can just make one of these and share it.
4902     static MorphAddrContext s_CopyBlockMAC;
4903
4904 #ifdef FEATURE_SIMD
4905     GenTree* getSIMDStructFromField(GenTree*   tree,
4906                                     var_types* baseTypeOut,
4907                                     unsigned*  indexOut,
4908                                     unsigned*  simdSizeOut,
4909                                     bool       ignoreUsedInSIMDIntrinsic = false);
4910     GenTree* fgMorphFieldAssignToSIMDIntrinsicSet(GenTree* tree);
4911     GenTree* fgMorphFieldToSIMDIntrinsicGet(GenTree* tree);
4912     bool fgMorphCombineSIMDFieldAssignments(BasicBlock* block, GenTree* stmt);
4913     void impMarkContiguousSIMDFieldAssignments(GenTree* stmt);
4914
4915     // fgPreviousCandidateSIMDFieldAsgStmt is only used for tracking previous simd field assignment
4916     // in function: Complier::impMarkContiguousSIMDFieldAssignments.
4917     GenTree* fgPreviousCandidateSIMDFieldAsgStmt;
4918
4919 #endif // FEATURE_SIMD
4920     GenTree* fgMorphArrayIndex(GenTree* tree);
4921     GenTree* fgMorphCast(GenTree* tree);
4922     GenTree* fgUnwrapProxy(GenTree* objRef);
4923     GenTreeCall* fgMorphArgs(GenTreeCall* call);
4924
4925     void fgMakeOutgoingStructArgCopy(GenTreeCall*         call,
4926                                      GenTree*             args,
4927                                      unsigned             argIndex,
4928                                      CORINFO_CLASS_HANDLE copyBlkClass FEATURE_UNIX_AMD64_STRUCT_PASSING_ONLY_ARG(
4929                                          const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structDescPtr));
4930
4931     void fgFixupStructReturn(GenTree* call);
4932     GenTree* fgMorphLocalVar(GenTree* tree, bool forceRemorph);
4933
4934 public:
4935     bool fgAddrCouldBeNull(GenTree* addr);
4936
4937 private:
4938     GenTree* fgMorphField(GenTree* tree, MorphAddrContext* mac);
4939     bool fgCanFastTailCall(GenTreeCall* call);
4940     bool fgCheckStmtAfterTailCall();
4941     void fgMorphTailCall(GenTreeCall* call);
4942     GenTree* fgGetStubAddrArg(GenTreeCall* call);
4943     void fgMorphRecursiveFastTailCallIntoLoop(BasicBlock* block, GenTreeCall* recursiveTailCall);
4944     GenTree* fgAssignRecursiveCallArgToCallerParam(GenTree*       arg,
4945                                                    fgArgTabEntry* argTabEntry,
4946                                                    BasicBlock*    block,
4947                                                    IL_OFFSETX     callILOffset,
4948                                                    GenTree*       tmpAssignmentInsertionPoint,
4949                                                    GenTree*       paramAssignmentInsertionPoint);
4950     static int fgEstimateCallStackSize(GenTreeCall* call);
4951     GenTree* fgMorphCall(GenTreeCall* call);
4952     void fgMorphCallInline(GenTreeCall* call, InlineResult* result);
4953     void fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result);
4954 #if DEBUG
4955     void fgNoteNonInlineCandidate(GenTreeStmt* stmt, GenTreeCall* call);
4956     static fgWalkPreFn fgFindNonInlineCandidate;
4957 #endif
4958     GenTree* fgOptimizeDelegateConstructor(GenTreeCall*            call,
4959                                            CORINFO_CONTEXT_HANDLE* ExactContextHnd,
4960                                            CORINFO_RESOLVED_TOKEN* ldftnToken);
4961     GenTree* fgMorphLeaf(GenTree* tree);
4962     void fgAssignSetVarDef(GenTree* tree);
4963     GenTree* fgMorphOneAsgBlockOp(GenTree* tree);
4964     GenTree* fgMorphInitBlock(GenTree* tree);
4965     GenTree* fgMorphBlkToInd(GenTreeBlk* tree, var_types type);
4966     GenTree* fgMorphGetStructAddr(GenTree** pTree, CORINFO_CLASS_HANDLE clsHnd, bool isRValue = false);
4967     GenTree* fgMorphBlkNode(GenTree* tree, bool isDest);
4968     GenTree* fgMorphBlockOperand(GenTree* tree, var_types asgType, unsigned blockWidth, bool isDest);
4969     void fgMorphUnsafeBlk(GenTreeObj* obj);
4970     GenTree* fgMorphCopyBlock(GenTree* tree);
4971     GenTree* fgMorphForRegisterFP(GenTree* tree);
4972     GenTree* fgMorphSmpOp(GenTree* tree, MorphAddrContext* mac = nullptr);
4973     GenTree* fgMorphSmpOpPre(GenTree* tree);
4974     GenTree* fgMorphModToSubMulDiv(GenTreeOp* tree);
4975     GenTree* fgMorphSmpOpOptional(GenTreeOp* tree);
4976     GenTree* fgMorphRecognizeBoxNullable(GenTree* compare);
4977
4978     GenTree* fgMorphToEmulatedFP(GenTree* tree);
4979     GenTree* fgMorphConst(GenTree* tree);
4980
4981 public:
4982     GenTree* fgMorphTree(GenTree* tree, MorphAddrContext* mac = nullptr);
4983
4984 private:
4985 #if LOCAL_ASSERTION_PROP
4986     void fgKillDependentAssertionsSingle(unsigned lclNum DEBUGARG(GenTree* tree));
4987     void fgKillDependentAssertions(unsigned lclNum DEBUGARG(GenTree* tree));
4988 #endif
4989     void fgMorphTreeDone(GenTree* tree, GenTree* oldTree = nullptr DEBUGARG(int morphNum = 0));
4990
4991     GenTreeStmt* fgMorphStmt;
4992
4993     unsigned fgGetBigOffsetMorphingTemp(var_types type); // We cache one temp per type to be
4994                                                          // used when morphing big offset.
4995
4996     //----------------------- Liveness analysis -------------------------------
4997
4998     VARSET_TP fgCurUseSet; // vars used     by block (before an assignment)
4999     VARSET_TP fgCurDefSet; // vars assigned by block (before a use)
5000
5001     MemoryKindSet fgCurMemoryUse;   // True iff the current basic block uses memory.
5002     MemoryKindSet fgCurMemoryDef;   // True iff the current basic block modifies memory.
5003     MemoryKindSet fgCurMemoryHavoc; // True if  the current basic block is known to set memory to a "havoc" value.
5004
5005     bool byrefStatesMatchGcHeapStates; // True iff GcHeap and ByrefExposed memory have all the same def points.
5006
5007     void fgMarkUseDef(GenTreeLclVarCommon* tree);
5008
5009     void fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5010     void fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var);
5011
5012     void fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope);
5013     void fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope);
5014
5015     void fgExtendDbgScopes();
5016     void fgExtendDbgLifetimes();
5017
5018 #ifdef DEBUG
5019     void fgDispDebugScopes();
5020 #endif // DEBUG
5021
5022     //-------------------------------------------------------------------------
5023     //
5024     //  The following keeps track of any code we've added for things like array
5025     //  range checking or explicit calls to enable GC, and so on.
5026     //
5027 public:
5028     struct AddCodeDsc
5029     {
5030         AddCodeDsc*     acdNext;
5031         BasicBlock*     acdDstBlk; // block  to  which we jump
5032         unsigned        acdData;
5033         SpecialCodeKind acdKind; // what kind of a special block is this?
5034 #if !FEATURE_FIXED_OUT_ARGS
5035         bool     acdStkLvlInit; // has acdStkLvl value been already set?
5036         unsigned acdStkLvl;
5037 #endif // !FEATURE_FIXED_OUT_ARGS
5038     };
5039
5040 private:
5041     static unsigned acdHelper(SpecialCodeKind codeKind);
5042
5043     AddCodeDsc* fgAddCodeList;
5044     bool        fgAddCodeModf;
5045     bool        fgRngChkThrowAdded;
5046     AddCodeDsc* fgExcptnTargetCache[SCK_COUNT];
5047
5048     BasicBlock* fgRngChkTarget(BasicBlock* block, unsigned stkDepth, SpecialCodeKind kind);
5049
5050     BasicBlock* fgAddCodeRef(BasicBlock* srcBlk, unsigned refData, SpecialCodeKind kind, unsigned stkDepth = 0);
5051
5052 public:
5053     AddCodeDsc* fgFindExcptnTarget(SpecialCodeKind kind, unsigned refData);
5054
5055     bool fgUseThrowHelperBlocks();
5056
5057     AddCodeDsc* fgGetAdditionalCodeDescriptors()
5058     {
5059         return fgAddCodeList;
5060     }
5061
5062 private:
5063     bool fgIsCodeAdded();
5064
5065     bool fgIsThrowHlpBlk(BasicBlock* block);
5066
5067 #if !FEATURE_FIXED_OUT_ARGS
5068     unsigned fgThrowHlpBlkStkLevel(BasicBlock* block);
5069 #endif // !FEATURE_FIXED_OUT_ARGS
5070
5071     unsigned fgBigOffsetMorphingTemps[TYP_COUNT];
5072
5073     unsigned fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo);
5074     void fgInvokeInlineeCompiler(GenTreeCall* call, InlineResult* result);
5075     void fgInsertInlineeBlocks(InlineInfo* pInlineInfo);
5076     GenTree* fgInlinePrependStatements(InlineInfo* inlineInfo);
5077     void fgInlineAppendStatements(InlineInfo* inlineInfo, BasicBlock* block, GenTree* stmt);
5078
5079 #if FEATURE_MULTIREG_RET
5080     GenTree* fgGetStructAsStructPtr(GenTree* tree);
5081     GenTree* fgAssignStructInlineeToVar(GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5082     void fgAttachStructInlineeToAsg(GenTree* tree, GenTree* child, CORINFO_CLASS_HANDLE retClsHnd);
5083 #endif // FEATURE_MULTIREG_RET
5084
5085     static fgWalkPreFn fgUpdateInlineReturnExpressionPlaceHolder;
5086
5087 #ifdef DEBUG
5088     static fgWalkPreFn fgDebugCheckInlineCandidates;
5089
5090     void               CheckNoFatPointerCandidatesLeft();
5091     static fgWalkPreFn fgDebugCheckFatPointerCandidates;
5092 #endif
5093
5094     void         fgPromoteStructs();
5095     fgWalkResult fgMorphStructField(GenTree* tree, fgWalkData* fgWalkPre);
5096     fgWalkResult fgMorphLocalField(GenTree* tree, fgWalkData* fgWalkPre);
5097
5098     // Identify which parameters are implicit byrefs, and flag their LclVarDscs.
5099     void fgMarkImplicitByRefArgs();
5100
5101     // Change implicit byrefs' types from struct to pointer, and for any that were
5102     // promoted, create new promoted struct temps.
5103     void fgRetypeImplicitByRefArgs();
5104
5105     // Rewrite appearances of implicit byrefs (manifest the implied additional level of indirection).
5106     bool fgMorphImplicitByRefArgs(GenTree* tree);
5107     GenTree* fgMorphImplicitByRefArgs(GenTree* tree, bool isAddr);
5108
5109     // Clear up annotations for any struct promotion temps created for implicit byrefs.
5110     void fgMarkDemotedImplicitByRefArgs();
5111
5112     static fgWalkPreFn  fgMarkAddrTakenLocalsPreCB;
5113     static fgWalkPostFn fgMarkAddrTakenLocalsPostCB;
5114     void                fgMarkAddressExposedLocals();
5115     bool fgNodesMayInterfere(GenTree* store, GenTree* load);
5116
5117     static fgWalkPreFn  fgUpdateSideEffectsPre;
5118     static fgWalkPostFn fgUpdateSideEffectsPost;
5119
5120     // Returns true if the type of tree is of size at least "width", or if "tree" is not a
5121     // local variable.
5122     bool fgFitsInOrNotLoc(GenTree* tree, unsigned width);
5123
5124     // The given local variable, required to be a struct variable, is being assigned via
5125     // a "lclField", to make it masquerade as an integral type in the ABI.  Make sure that
5126     // the variable is not enregistered, and is therefore not promoted independently.
5127     void fgLclFldAssign(unsigned lclNum);
5128
5129     static fgWalkPreFn gtHasLocalsWithAddrOpCB;
5130
5131     enum TypeProducerKind
5132     {
5133         TPK_Unknown = 0, // May not be a RuntimeType
5134         TPK_Handle  = 1, // RuntimeType via handle
5135         TPK_GetType = 2, // RuntimeType via Object.get_Type()
5136         TPK_Null    = 3, // Tree value is null
5137         TPK_Other   = 4  // RuntimeType via other means
5138     };
5139
5140     TypeProducerKind gtGetTypeProducerKind(GenTree* tree);
5141     bool gtIsTypeHandleToRuntimeTypeHelper(GenTreeCall* call);
5142     bool gtIsActiveCSE_Candidate(GenTree* tree);
5143
5144 #ifdef DEBUG
5145     bool fgPrintInlinedMethods;
5146 #endif
5147
5148     bool fgIsBigOffset(size_t offset);
5149
5150 #if defined(LEGACY_BACKEND)
5151     // The following are used when morphing special cases of integer div/mod operations and also by codegen
5152     bool fgIsSignedDivOptimizable(GenTree* divisor);
5153     bool fgIsUnsignedDivOptimizable(GenTree* divisor);
5154     bool fgIsSignedModOptimizable(GenTree* divisor);
5155     bool fgIsUnsignedModOptimizable(GenTree* divisor);
5156 #endif // LEGACY_BACKEND
5157
5158     bool fgNeedReturnSpillTemp();
5159
5160     /*
5161     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5162     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5163     XX                                                                           XX
5164     XX                           Optimizer                                       XX
5165     XX                                                                           XX
5166     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5167     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
5168     */
5169
5170 public:
5171     void optInit();
5172
5173 protected:
5174     LclVarDsc* optIsTrackedLocal(GenTree* tree);
5175
5176 public:
5177     void optRemoveRangeCheck(GenTree* tree, GenTree* stmt);
5178     bool optIsRangeCheckRemovable(GenTree* tree);
5179
5180 protected:
5181     static fgWalkPreFn optValidRangeCheckIndex;
5182     static fgWalkPreFn optRemoveTreeVisitor; // Helper passed to Compiler::fgWalkAllTreesPre() to decrement the LclVar
5183                                              // usage counts
5184
5185     void optRemoveTree(GenTree* deadTree, GenTree* keepList);
5186
5187     /**************************************************************************
5188      *
5189      *************************************************************************/
5190
5191 protected:
5192     // Do hoisting for all loops.
5193     void optHoistLoopCode();
5194
5195     // To represent sets of VN's that have already been hoisted in outer loops.
5196     typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, bool> VNToBoolMap;
5197     typedef VNToBoolMap VNSet;
5198
5199     struct LoopHoistContext
5200     {
5201     private:
5202         // The set of variables hoisted in the current loop (or nullptr if there are none).
5203         VNSet* m_pHoistedInCurLoop;
5204
5205     public:
5206         // Value numbers of expressions that have been hoisted in parent loops in the loop nest.
5207         VNSet m_hoistedInParentLoops;
5208         // Value numbers of expressions that have been hoisted in the current (or most recent) loop in the nest.
5209         // Previous decisions on loop-invariance of value numbers in the current loop.
5210         VNToBoolMap m_curLoopVnInvariantCache;
5211
5212         VNSet* GetHoistedInCurLoop(Compiler* comp)
5213         {
5214             if (m_pHoistedInCurLoop == nullptr)
5215             {
5216                 m_pHoistedInCurLoop = new (comp->getAllocatorLoopHoist()) VNSet(comp->getAllocatorLoopHoist());
5217             }
5218             return m_pHoistedInCurLoop;
5219         }
5220
5221         VNSet* ExtractHoistedInCurLoop()
5222         {
5223             VNSet* res          = m_pHoistedInCurLoop;
5224             m_pHoistedInCurLoop = nullptr;
5225             return res;
5226         }
5227
5228         LoopHoistContext(Compiler* comp)
5229             : m_pHoistedInCurLoop(nullptr)
5230             , m_hoistedInParentLoops(comp->getAllocatorLoopHoist())
5231             , m_curLoopVnInvariantCache(comp->getAllocatorLoopHoist())
5232         {
5233         }
5234     };
5235
5236     // Do hoisting for loop "lnum" (an index into the optLoopTable), and all loops nested within it.
5237     // Tracks the expressions that have been hoisted by containing loops by temporary recording their
5238     // value numbers in "m_hoistedInParentLoops".  This set is not modified by the call.
5239     void optHoistLoopNest(unsigned lnum, LoopHoistContext* hoistCtxt);
5240
5241     // Do hoisting for a particular loop ("lnum" is an index into the optLoopTable.)
5242     // Assumes that expressions have been hoisted in containing loops if their value numbers are in
5243     // "m_hoistedInParentLoops".
5244     //
5245     void optHoistThisLoop(unsigned lnum, LoopHoistContext* hoistCtxt);
5246
5247     // Hoist all expressions in "blk" that are invariant in loop "lnum" (an index into the optLoopTable)
5248     // outside of that loop.  Exempt expressions whose value number is in "m_hoistedInParentLoops"; add VN's of hoisted
5249     // expressions to "hoistInLoop".
5250     void optHoistLoopExprsForBlock(BasicBlock* blk, unsigned lnum, LoopHoistContext* hoistCtxt);
5251
5252     // Return true if the tree looks profitable to hoist out of loop 'lnum'.
5253     bool optIsProfitableToHoistableTree(GenTree* tree, unsigned lnum);
5254
5255     // Hoist all proper sub-expressions of "tree" (which occurs in "stmt", which occurs in "blk")
5256     // that are invariant in loop "lnum" (an index into the optLoopTable)
5257     // outside of that loop.  Exempt expressions whose value number is in "hoistedInParents"; add VN's of hoisted
5258     // expressions to "hoistInLoop".
5259     // Returns "true" iff "tree" is loop-invariant (wrt "lnum").
5260     // Assumes that the value of "*firstBlockAndBeforeSideEffect" indicates that we're in the first block, and before
5261     // any possible globally visible side effects.  Assume is called in evaluation order, and updates this.
5262     bool optHoistLoopExprsForTree(GenTree*          tree,
5263                                   unsigned          lnum,
5264                                   LoopHoistContext* hoistCtxt,
5265                                   bool*             firstBlockAndBeforeSideEffect,
5266                                   bool*             pHoistable,
5267                                   bool*             pCctorDependent);
5268
5269     // Performs the hoisting 'tree' into the PreHeader for loop 'lnum'
5270     void optHoistCandidate(GenTree* tree, unsigned lnum, LoopHoistContext* hoistCtxt);
5271
5272     // Returns true iff the ValueNum "vn" represents a value that is loop-invariant in "lnum".
5273     //   Constants and init values are always loop invariant.
5274     //   VNPhi's connect VN's to the SSA definition, so we can know if the SSA def occurs in the loop.
5275     bool optVNIsLoopInvariant(ValueNum vn, unsigned lnum, VNToBoolMap* recordedVNs);
5276
5277     // Returns "true" iff "tree" is valid at the head of loop "lnum", in the context of the hoist substitution
5278     // "subst".  If "tree" is a local SSA var, it is valid if its SSA definition occurs outside of the loop, or
5279     // if it is in the domain of "subst" (meaning that it's definition has been previously hoisted, with a "standin"
5280     // local.)  If tree is a constant, it is valid.  Otherwise, if it is an operator, it is valid iff its children are.
5281     bool optTreeIsValidAtLoopHead(GenTree* tree, unsigned lnum);
5282
5283     // If "blk" is the entry block of a natural loop, returns true and sets "*pLnum" to the index of the loop
5284     // in the loop table.
5285     bool optBlockIsLoopEntry(BasicBlock* blk, unsigned* pLnum);
5286
5287     // Records the set of "side effects" of all loops: fields (object instance and static)
5288     // written to, and SZ-array element type equivalence classes updated.
5289     void optComputeLoopSideEffects();
5290
5291 private:
5292     // Requires "lnum" to be the index of an outermost loop in the loop table.  Traverses the body of that loop,
5293     // including all nested loops, and records the set of "side effects" of the loop: fields (object instance and
5294     // static) written to, and SZ-array element type equivalence classes updated.
5295     void optComputeLoopNestSideEffects(unsigned lnum);
5296
5297     // Add the side effects of "blk" (which is required to be within a loop) to all loops of which it is a part.
5298     void optComputeLoopSideEffectsOfBlock(BasicBlock* blk);
5299
5300     // Hoist the expression "expr" out of loop "lnum".
5301     void optPerformHoistExpr(GenTree* expr, unsigned lnum);
5302
5303 public:
5304     void optOptimizeBools();
5305
5306 private:
5307     GenTree* optIsBoolCond(GenTree* condBranch, GenTree** compPtr, bool* boolPtr);
5308 #ifdef DEBUG
5309     void optOptimizeBoolsGcStress(BasicBlock* condBlock);
5310 #endif
5311 public:
5312     void optOptimizeLayout(); // Optimize the BasicBlock layout of the method
5313
5314     void optOptimizeLoops(); // for "while-do" loops duplicates simple loop conditions and transforms
5315                              // the loop into a "do-while" loop
5316                              // Also finds all natural loops and records them in the loop table
5317
5318     // Optionally clone loops in the loop table.
5319     void optCloneLoops();
5320
5321     // Clone loop "loopInd" in the loop table.
5322     void optCloneLoop(unsigned loopInd, LoopCloneContext* context);
5323
5324     // Ensure that loop "loopInd" has a unique head block.  (If the existing entry has
5325     // non-loop predecessors other than the head entry, create a new, empty block that goes (only) to the entry,
5326     // and redirects the preds of the entry to this new block.)  Sets the weight of the newly created block to
5327     // "ambientWeight".
5328     void optEnsureUniqueHead(unsigned loopInd, unsigned ambientWeight);
5329
5330     void optUnrollLoops(); // Unrolls loops (needs to have cost info)
5331
5332 protected:
5333     // This enumeration describes what is killed by a call.
5334
5335     enum callInterf
5336     {
5337         CALLINT_NONE,       // no interference                               (most helpers)
5338         CALLINT_REF_INDIRS, // kills GC ref indirections                     (SETFIELD OBJ)
5339         CALLINT_SCL_INDIRS, // kills non GC ref indirections                 (SETFIELD non-OBJ)
5340         CALLINT_ALL_INDIRS, // kills both GC ref and non GC ref indirections (SETFIELD STRUCT)
5341         CALLINT_ALL,        // kills everything                              (normal method call)
5342     };
5343
5344 public:
5345     // A "LoopDsc" describes a ("natural") loop.  We (currently) require the body of a loop to be a contiguous (in
5346     // bbNext order) sequence of basic blocks.  (At times, we may require the blocks in a loop to be "properly numbered"
5347     // in bbNext order; we use comparisons on the bbNum to decide order.)
5348     // The blocks that define the body are
5349     //   first <= top <= entry <= bottom   .
5350     // The "head" of the loop is a block outside the loop that has "entry" as a successor. We only support loops with a
5351     // single 'head' block. The meanings of these blocks are given in the definitions below. Also see the picture at
5352     // Compiler::optFindNaturalLoops().
5353     struct LoopDsc
5354     {
5355         BasicBlock* lpHead;  // HEAD of the loop (not part of the looping of the loop) -- has ENTRY as a successor.
5356         BasicBlock* lpFirst; // FIRST block (in bbNext order) reachable within this loop.  (May be part of a nested
5357                              // loop, but not the outer loop.)
5358         BasicBlock* lpTop;   // loop TOP (the back edge from lpBottom reaches here) (in most cases FIRST and TOP are the
5359                              // same)
5360         BasicBlock* lpEntry; // the ENTRY in the loop (in most cases TOP or BOTTOM)
5361         BasicBlock* lpBottom; // loop BOTTOM (from here we have a back edge to the TOP)
5362         BasicBlock* lpExit;   // if a single exit loop this is the EXIT (in most cases BOTTOM)
5363
5364         callInterf   lpAsgCall;     // "callInterf" for calls in the loop
5365         ALLVARSET_TP lpAsgVars;     // set of vars assigned within the loop (all vars, not just tracked)
5366         varRefKinds  lpAsgInds : 8; // set of inds modified within the loop
5367
5368         unsigned short lpFlags; // Mask of the LPFLG_* constants
5369
5370         unsigned char lpExitCnt; // number of exits from the loop
5371
5372         unsigned char lpParent;  // The index of the most-nested loop that completely contains this one,
5373                                  // or else BasicBlock::NOT_IN_LOOP if no such loop exists.
5374         unsigned char lpChild;   // The index of a nested loop, or else BasicBlock::NOT_IN_LOOP if no child exists.
5375                                  // (Actually, an "immediately" nested loop --
5376                                  // no other child of this loop is a parent of lpChild.)
5377         unsigned char lpSibling; // The index of another loop that is an immediate child of lpParent,
5378                                  // or else BasicBlock::NOT_IN_LOOP.  One can enumerate all the children of a loop
5379                                  // by following "lpChild" then "lpSibling" links.
5380
5381 #define LPFLG_DO_WHILE 0x0001 // it's a do-while loop (i.e ENTRY is at the TOP)
5382 #define LPFLG_ONE_EXIT 0x0002 // the loop has only one exit
5383
5384 #define LPFLG_ITER 0x0004      // for (i = icon or lclVar; test_condition(); i++)
5385 #define LPFLG_HOISTABLE 0x0008 // the loop is in a form that is suitable for hoisting expressions
5386 #define LPFLG_CONST 0x0010     // for (i=icon;i<icon;i++){ ... } - constant loop
5387
5388 #define LPFLG_VAR_INIT 0x0020   // iterator is initialized with a local var (var # found in lpVarInit)
5389 #define LPFLG_CONST_INIT 0x0040 // iterator is initialized with a constant (found in lpConstInit)
5390
5391 #define LPFLG_VAR_LIMIT 0x0100    // iterator is compared with a local var (var # found in lpVarLimit)
5392 #define LPFLG_CONST_LIMIT 0x0200  // iterator is compared with a constant (found in lpConstLimit)
5393 #define LPFLG_ARRLEN_LIMIT 0x0400 // iterator is compared with a.len or a[i].len (found in lpArrLenLimit)
5394 #define LPFLG_SIMD_LIMIT 0x0080   // iterator is compared with Vector<T>.Count (found in lpConstLimit)
5395
5396 #define LPFLG_HAS_PREHEAD 0x0800 // lpHead is known to be a preHead for this loop
5397 #define LPFLG_REMOVED 0x1000     // has been removed from the loop table (unrolled or optimized away)
5398 #define LPFLG_DONT_UNROLL 0x2000 // do not unroll this loop
5399
5400 #define LPFLG_ASGVARS_YES 0x4000 // "lpAsgVars" has been  computed
5401 #define LPFLG_ASGVARS_INC 0x8000 // "lpAsgVars" is incomplete -- vars beyond those representable in an AllVarSet
5402                                  // type are assigned to.
5403
5404         bool lpLoopHasMemoryHavoc[MemoryKindCount]; // The loop contains an operation that we assume has arbitrary
5405                                                     // memory side effects.  If this is set, the fields below
5406                                                     // may not be accurate (since they become irrelevant.)
5407         bool lpContainsCall;                        // True if executing the loop body *may* execute a call
5408
5409         VARSET_TP lpVarInOut;  // The set of variables that are IN or OUT during the execution of this loop
5410         VARSET_TP lpVarUseDef; // The set of variables that are USE or DEF during the execution of this loop
5411
5412         int lpHoistedExprCount; // The register count for the non-FP expressions from inside this loop that have been
5413                                 // hoisted
5414         int lpLoopVarCount;     // The register count for the non-FP LclVars that are read/written inside this loop
5415         int lpVarInOutCount;    // The register count for the non-FP LclVars that are alive inside or accross this loop
5416
5417         int lpHoistedFPExprCount; // The register count for the FP expressions from inside this loop that have been
5418                                   // hoisted
5419         int lpLoopVarFPCount;     // The register count for the FP LclVars that are read/written inside this loop
5420         int lpVarInOutFPCount;    // The register count for the FP LclVars that are alive inside or accross this loop
5421
5422         typedef JitHashTable<CORINFO_FIELD_HANDLE, JitPtrKeyFuncs<struct CORINFO_FIELD_STRUCT_>, bool> FieldHandleSet;
5423         FieldHandleSet* lpFieldsModified; // This has entries (mappings to "true") for all static field and object
5424                                           // instance fields modified
5425                                           // in the loop.
5426
5427         typedef JitHashTable<CORINFO_CLASS_HANDLE, JitPtrKeyFuncs<struct CORINFO_CLASS_STRUCT_>, bool> ClassHandleSet;
5428         ClassHandleSet* lpArrayElemTypesModified; // Bits set indicate the set of sz array element types such that
5429                                                   // arrays of that type are modified
5430                                                   // in the loop.
5431
5432         // Adds the variable liveness information for 'blk' to 'this' LoopDsc
5433         void AddVariableLiveness(Compiler* comp, BasicBlock* blk);
5434
5435         inline void AddModifiedField(Compiler* comp, CORINFO_FIELD_HANDLE fldHnd);
5436         // This doesn't *always* take a class handle -- it can also take primitive types, encoded as class handles
5437         // (shifted left, with a low-order bit set to distinguish.)
5438         // Use the {Encode/Decode}ElemType methods to construct/destruct these.
5439         inline void AddModifiedElemType(Compiler* comp, CORINFO_CLASS_HANDLE structHnd);
5440
5441         /* The following values are set only for iterator loops, i.e. has the flag LPFLG_ITER set */
5442
5443         GenTree*   lpIterTree;    // The "i <op>= const" tree
5444         unsigned   lpIterVar();   // iterator variable #
5445         int        lpIterConst(); // the constant with which the iterator is incremented
5446         genTreeOps lpIterOper();  // the type of the operation on the iterator (ASG_ADD, ASG_SUB, etc.)
5447         void       VERIFY_lpIterTree();
5448
5449         var_types lpIterOperType(); // For overflow instructions
5450
5451         union {
5452             int lpConstInit; // initial constant value of iterator                           : Valid if LPFLG_CONST_INIT
5453             unsigned lpVarInit; // initial local var number to which we initialize the iterator : Valid if
5454                                 // LPFLG_VAR_INIT
5455         };
5456
5457         /* The following is for LPFLG_ITER loops only (i.e. the loop condition is "i RELOP const or var" */
5458
5459         GenTree*   lpTestTree;   // pointer to the node containing the loop test
5460         genTreeOps lpTestOper(); // the type of the comparison between the iterator and the limit (GT_LE, GT_GE, etc.)
5461         void       VERIFY_lpTestTree();
5462
5463         bool     lpIsReversed(); // true if the iterator node is the second operand in the loop condition
5464         GenTree* lpIterator();   // the iterator node in the loop test
5465         GenTree* lpLimit();      // the limit node in the loop test
5466
5467         int lpConstLimit();    // limit   constant value of iterator - loop condition is "i RELOP const" : Valid if
5468                                // LPFLG_CONST_LIMIT
5469         unsigned lpVarLimit(); // the lclVar # in the loop condition ( "i RELOP lclVar" )                : Valid if
5470                                // LPFLG_VAR_LIMIT
5471         bool lpArrLenLimit(Compiler* comp, ArrIndex* index); // The array length in the loop condition ( "i RELOP
5472                                                              // arr.len" or "i RELOP arr[i][j].len" )  : Valid if
5473                                                              // LPFLG_ARRLEN_LIMIT
5474
5475         // Returns "true" iff "*this" contains the blk.
5476         bool lpContains(BasicBlock* blk)
5477         {
5478             return lpFirst->bbNum <= blk->bbNum && blk->bbNum <= lpBottom->bbNum;
5479         }
5480         // Returns "true" iff "*this" (properly) contains the range [first, bottom] (allowing firsts
5481         // to be equal, but requiring bottoms to be different.)
5482         bool lpContains(BasicBlock* first, BasicBlock* bottom)
5483         {
5484             return lpFirst->bbNum <= first->bbNum && bottom->bbNum < lpBottom->bbNum;
5485         }
5486
5487         // Returns "true" iff "*this" (properly) contains "lp2" (allowing firsts to be equal, but requiring
5488         // bottoms to be different.)
5489         bool lpContains(const LoopDsc& lp2)
5490         {
5491             return lpContains(lp2.lpFirst, lp2.lpBottom);
5492         }
5493
5494         // Returns "true" iff "*this" is (properly) contained by the range [first, bottom]
5495         // (allowing firsts to be equal, but requiring bottoms to be different.)
5496         bool lpContainedBy(BasicBlock* first, BasicBlock* bottom)
5497         {
5498             return first->bbNum <= lpFirst->bbNum && lpBottom->bbNum < bottom->bbNum;
5499         }
5500
5501         // Returns "true" iff "*this" is (properly) contained by "lp2"
5502         // (allowing firsts to be equal, but requiring bottoms to be different.)
5503         bool lpContainedBy(const LoopDsc& lp2)
5504         {
5505             return lpContains(lp2.lpFirst, lp2.lpBottom);
5506         }
5507
5508         // Returns "true" iff "*this" is disjoint from the range [top, bottom].
5509         bool lpDisjoint(BasicBlock* first, BasicBlock* bottom)
5510         {
5511             return bottom->bbNum < lpFirst->bbNum || lpBottom->bbNum < first->bbNum;
5512         }
5513         // Returns "true" iff "*this" is disjoint from "lp2".
5514         bool lpDisjoint(const LoopDsc& lp2)
5515         {
5516             return lpDisjoint(lp2.lpFirst, lp2.lpBottom);
5517         }
5518         // Returns "true" iff the loop is well-formed (see code for defn).
5519         bool lpWellFormed()
5520         {
5521             return lpFirst->bbNum <= lpTop->bbNum && lpTop->bbNum <= lpEntry->bbNum &&
5522                    lpEntry->bbNum <= lpBottom->bbNum &&
5523                    (lpHead->bbNum < lpTop->bbNum || lpHead->bbNum > lpBottom->bbNum);
5524         }
5525     };
5526
5527 protected:
5528     bool fgMightHaveLoop(); // returns true if there are any backedges
5529     bool fgHasLoops;        // True if this method has any loops, set in fgComputeReachability
5530
5531 public:
5532     LoopDsc       optLoopTable[MAX_LOOP_NUM]; // loop descriptor table
5533     unsigned char optLoopCount;               // number of tracked loops
5534
5535     bool optRecordLoop(BasicBlock*   head,
5536                        BasicBlock*   first,
5537                        BasicBlock*   top,
5538                        BasicBlock*   entry,
5539                        BasicBlock*   bottom,
5540                        BasicBlock*   exit,
5541                        unsigned char exitCnt);
5542
5543 protected:
5544     unsigned optCallCount;         // number of calls made in the method
5545     unsigned optIndirectCallCount; // number of virtual, interface and indirect calls made in the method
5546     unsigned optNativeCallCount;   // number of Pinvoke/Native calls made in the method
5547     unsigned optLoopsCloned;       // number of loops cloned in the current method.
5548
5549 #ifdef DEBUG
5550     unsigned optFindLoopNumberFromBeginBlock(BasicBlock* begBlk);
5551     void optPrintLoopInfo(unsigned      loopNum,
5552                           BasicBlock*   lpHead,
5553                           BasicBlock*   lpFirst,
5554                           BasicBlock*   lpTop,
5555                           BasicBlock*   lpEntry,
5556                           BasicBlock*   lpBottom,
5557                           unsigned char lpExitCnt,
5558                           BasicBlock*   lpExit,
5559                           unsigned      parentLoop = BasicBlock::NOT_IN_LOOP);
5560     void optPrintLoopInfo(unsigned lnum);
5561     void optPrintLoopRecording(unsigned lnum);
5562
5563     void optCheckPreds();
5564 #endif
5565
5566     void optSetBlockWeights();
5567
5568     void optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk);
5569
5570     void optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk);
5571
5572     void optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop = false);
5573
5574     bool optIsLoopTestEvalIntoTemp(GenTree* test, GenTree** newTest);
5575     unsigned optIsLoopIncrTree(GenTree* incr);
5576     bool optCheckIterInLoopTest(unsigned loopInd, GenTree* test, BasicBlock* from, BasicBlock* to, unsigned iterVar);
5577     bool optComputeIterInfo(GenTree* incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar);
5578     bool optPopulateInitInfo(unsigned loopInd, GenTree* init, unsigned iterVar);
5579     bool optExtractInitTestIncr(
5580         BasicBlock* head, BasicBlock* bottom, BasicBlock* exit, GenTree** ppInit, GenTree** ppTest, GenTree** ppIncr);
5581
5582     void optFindNaturalLoops();
5583
5584     // Ensures that all the loops in the loop nest rooted at "loopInd" (an index into the loop table) are 'canonical' --
5585     // each loop has a unique "top."  Returns "true" iff the flowgraph has been modified.
5586     bool optCanonicalizeLoopNest(unsigned char loopInd);
5587
5588     // Ensures that the loop "loopInd" (an index into the loop table) is 'canonical' -- it has a unique "top,"
5589     // unshared with any other loop.  Returns "true" iff the flowgraph has been modified
5590     bool optCanonicalizeLoop(unsigned char loopInd);
5591
5592     // Requires "l1" to be a valid loop table index, and not "BasicBlock::NOT_IN_LOOP".  Requires "l2" to be
5593     // a valid loop table index, or else "BasicBlock::NOT_IN_LOOP".  Returns true
5594     // iff "l2" is not NOT_IN_LOOP, and "l1" contains "l2".
5595     bool optLoopContains(unsigned l1, unsigned l2);
5596
5597     // Requires "loopInd" to be a valid index into the loop table.
5598     // Updates the loop table by changing loop "loopInd", whose head is required
5599     // to be "from", to be "to".  Also performs this transformation for any
5600     // loop nested in "loopInd" that shares the same head as "loopInd".
5601     void optUpdateLoopHead(unsigned loopInd, BasicBlock* from, BasicBlock* to);
5602
5603     // Updates the successors of "blk": if "blk2" is a successor of "blk", and there is a mapping for "blk2->blk3" in
5604     // "redirectMap", change "blk" so that "blk3" is this successor. Note that the predecessor lists are not updated.
5605     void optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap);
5606
5607     // Marks the containsCall information to "lnum" and any parent loops.
5608     void AddContainsCallAllContainingLoops(unsigned lnum);
5609     // Adds the variable liveness information from 'blk' to "lnum" and any parent loops.
5610     void AddVariableLivenessAllContainingLoops(unsigned lnum, BasicBlock* blk);
5611     // Adds "fldHnd" to the set of modified fields of "lnum" and any parent loops.
5612     void AddModifiedFieldAllContainingLoops(unsigned lnum, CORINFO_FIELD_HANDLE fldHnd);
5613     // Adds "elemType" to the set of modified array element types of "lnum" and any parent loops.
5614     void AddModifiedElemTypeAllContainingLoops(unsigned lnum, CORINFO_CLASS_HANDLE elemType);
5615
5616     // Requires that "from" and "to" have the same "bbJumpKind" (perhaps because "to" is a clone
5617     // of "from".)  Copies the jump destination from "from" to "to".
5618     void optCopyBlkDest(BasicBlock* from, BasicBlock* to);
5619
5620     // The depth of the loop described by "lnum" (an index into the loop table.) (0 == top level)
5621     unsigned optLoopDepth(unsigned lnum)
5622     {
5623         unsigned par = optLoopTable[lnum].lpParent;
5624         if (par == BasicBlock::NOT_IN_LOOP)
5625         {
5626             return 0;
5627         }
5628         else
5629         {
5630             return 1 + optLoopDepth(par);
5631         }
5632     }
5633
5634     void fgOptWhileLoop(BasicBlock* block);
5635
5636     bool optComputeLoopRep(int        constInit,
5637                            int        constLimit,
5638                            int        iterInc,
5639                            genTreeOps iterOper,
5640                            var_types  iterType,
5641                            genTreeOps testOper,
5642                            bool       unsignedTest,
5643                            bool       dupCond,
5644                            unsigned*  iterCount);
5645 #if FEATURE_STACK_FP_X87
5646
5647 public:
5648     VARSET_TP optAllFloatVars; // mask of all tracked      FP variables
5649     VARSET_TP optAllFPregVars; // mask of all enregistered FP variables
5650     VARSET_TP optAllNonFPvars; // mask of all tracked  non-FP variables
5651 #endif                         // FEATURE_STACK_FP_X87
5652
5653 private:
5654     static fgWalkPreFn optIsVarAssgCB;
5655
5656 protected:
5657     bool optIsVarAssigned(BasicBlock* beg, BasicBlock* end, GenTree* skip, unsigned var);
5658
5659     bool optIsVarAssgLoop(unsigned lnum, unsigned var);
5660
5661     int optIsSetAssgLoop(unsigned lnum, ALLVARSET_VALARG_TP vars, varRefKinds inds = VR_NONE);
5662
5663     bool optNarrowTree(GenTree* tree, var_types srct, var_types dstt, ValueNumPair vnpNarrow, bool doit);
5664
5665     /**************************************************************************
5666      *                       Optimization conditions
5667      *************************************************************************/
5668
5669     bool optFastCodeOrBlendedLoop(BasicBlock::weight_t bbWeight);
5670     bool optPentium4(void);
5671     bool optAvoidIncDec(BasicBlock::weight_t bbWeight);
5672     bool optAvoidIntMult(void);
5673
5674 #if FEATURE_ANYCSE
5675
5676 protected:
5677     //  The following is the upper limit on how many expressions we'll keep track
5678     //  of for the CSE analysis.
5679     //
5680     static const unsigned MAX_CSE_CNT = EXPSET_SZ;
5681
5682     static const int MIN_CSE_COST = 2;
5683
5684     // Keeps tracked cse indices
5685     BitVecTraits* cseTraits;
5686     EXPSET_TP     cseFull;
5687
5688     /* Generic list of nodes - used by the CSE logic */
5689
5690     struct treeLst
5691     {
5692         treeLst* tlNext;
5693         GenTree* tlTree;
5694     };
5695
5696     struct treeStmtLst
5697     {
5698         treeStmtLst* tslNext;
5699         GenTree*     tslTree;  // tree node
5700         GenTree*     tslStmt;  // statement containing the tree
5701         BasicBlock*  tslBlock; // block containing the statement
5702     };
5703
5704     // The following logic keeps track of expressions via a simple hash table.
5705
5706     struct CSEdsc
5707     {
5708         CSEdsc* csdNextInBucket; // used by the hash table
5709
5710         unsigned csdHashValue; // the orginal hashkey
5711
5712         unsigned csdIndex;          // 1..optCSECandidateCount
5713         char     csdLiveAcrossCall; // 0 or 1
5714
5715         unsigned short csdDefCount; // definition   count
5716         unsigned short csdUseCount; // use          count  (excluding the implicit uses at defs)
5717
5718         unsigned csdDefWtCnt; // weighted def count
5719         unsigned csdUseWtCnt; // weighted use count  (excluding the implicit uses at defs)
5720
5721         GenTree*    csdTree;  // treenode containing the 1st occurance
5722         GenTree*    csdStmt;  // stmt containing the 1st occurance
5723         BasicBlock* csdBlock; // block containing the 1st occurance
5724
5725         treeStmtLst* csdTreeList; // list of matching tree nodes: head
5726         treeStmtLst* csdTreeLast; // list of matching tree nodes: tail
5727
5728         ValueNum defConservativeVN; // if all def occurrences share the same conservative value
5729                                     // number, this will reflect it; otherwise, NoVN.
5730     };
5731
5732     static const size_t s_optCSEhashSize;
5733     CSEdsc**            optCSEhash;
5734     CSEdsc**            optCSEtab;
5735
5736     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, GenTree*> NodeToNodeMap;
5737
5738     NodeToNodeMap* optCseCheckedBoundMap; // Maps bound nodes to ancestor compares that should be
5739                                           // re-numbered with the bound to improve range check elimination
5740
5741     // Given a compare, look for a cse candidate checked bound feeding it and add a map entry if found.
5742     void optCseUpdateCheckedBoundMap(GenTree* compare);
5743
5744     void optCSEstop();
5745
5746     CSEdsc* optCSEfindDsc(unsigned index);
5747     bool optUnmarkCSE(GenTree* tree);
5748
5749     // user defined callback data for the tree walk function optCSE_MaskHelper()
5750     struct optCSE_MaskData
5751     {
5752         EXPSET_TP CSE_defMask;
5753         EXPSET_TP CSE_useMask;
5754     };
5755
5756     // Treewalk helper for optCSE_DefMask and optCSE_UseMask
5757     static fgWalkPreFn optCSE_MaskHelper;
5758
5759     // This function walks all the node for an given tree
5760     // and return the mask of CSE definitions and uses for the tree
5761     //
5762     void optCSE_GetMaskData(GenTree* tree, optCSE_MaskData* pMaskData);
5763
5764     // Given a binary tree node return true if it is safe to swap the order of evaluation for op1 and op2.
5765     bool optCSE_canSwap(GenTree* firstNode, GenTree* secondNode);
5766     bool optCSE_canSwap(GenTree* tree);
5767
5768     static fgWalkPostFn optPropagateNonCSE;
5769     static fgWalkPreFn  optHasNonCSEChild;
5770
5771     static fgWalkPreFn optUnmarkCSEs;
5772     static fgWalkPreFn optHasCSEdefWithSideeffect;
5773
5774     static int __cdecl optCSEcostCmpEx(const void* op1, const void* op2);
5775     static int __cdecl optCSEcostCmpSz(const void* op1, const void* op2);
5776
5777     void optCleanupCSEs();
5778
5779 #ifdef DEBUG
5780     void optEnsureClearCSEInfo();
5781 #endif // DEBUG
5782
5783 #endif // FEATURE_ANYCSE
5784
5785 #if FEATURE_VALNUM_CSE
5786     /**************************************************************************
5787      *                   Value Number based CSEs
5788      *************************************************************************/
5789
5790 public:
5791     void optOptimizeValnumCSEs();
5792
5793 protected:
5794     void     optValnumCSE_Init();
5795     unsigned optValnumCSE_Index(GenTree* tree, GenTree* stmt);
5796     unsigned optValnumCSE_Locate();
5797     void     optValnumCSE_InitDataFlow();
5798     void     optValnumCSE_DataFlow();
5799     void     optValnumCSE_Availablity();
5800     void     optValnumCSE_Heuristic();
5801     bool optValnumCSE_UnmarkCSEs(GenTree* deadTree, GenTree** wbKeepList);
5802
5803 #endif // FEATURE_VALNUM_CSE
5804
5805 #if FEATURE_ANYCSE
5806     bool     optDoCSE;             // True when we have found a duplicate CSE tree
5807     bool     optValnumCSE_phase;   // True when we are executing the optValnumCSE_phase
5808     unsigned optCSECandidateTotal; // Grand total of CSE candidates for both Lexical and ValNum
5809     unsigned optCSECandidateCount; // Count of CSE's candidates, reset for Lexical and ValNum CSE's
5810     unsigned optCSEstart;          // The first local variable number that is a CSE
5811     unsigned optCSEcount;          // The total count of CSE's introduced.
5812     unsigned optCSEweight;         // The weight of the current block when we are
5813                                    // scanning for CSE expressions
5814
5815     bool optIsCSEcandidate(GenTree* tree);
5816
5817     // lclNumIsTrueCSE returns true if the LclVar was introduced by the CSE phase of the compiler
5818     //
5819     bool lclNumIsTrueCSE(unsigned lclNum) const
5820     {
5821         return ((optCSEcount > 0) && (lclNum >= optCSEstart) && (lclNum < optCSEstart + optCSEcount));
5822     }
5823
5824     //  lclNumIsCSE returns true if the LclVar should be treated like a CSE with regards to constant prop.
5825     //
5826     bool lclNumIsCSE(unsigned lclNum) const
5827     {
5828         return lvaTable[lclNum].lvIsCSE;
5829     }
5830
5831 #ifdef DEBUG
5832     bool optConfigDisableCSE();
5833     bool optConfigDisableCSE2();
5834 #endif
5835     void optOptimizeCSEs();
5836
5837 #endif // FEATURE_ANYCSE
5838
5839     struct isVarAssgDsc
5840     {
5841         GenTree* ivaSkip;
5842 #ifdef DEBUG
5843         void* ivaSelf;
5844 #endif
5845         unsigned     ivaVar;            // Variable we are interested in, or -1
5846         ALLVARSET_TP ivaMaskVal;        // Set of variables assigned to.  This is a set of all vars, not tracked vars.
5847         bool         ivaMaskIncomplete; // Variables not representable in ivaMaskVal were assigned to.
5848         varRefKinds  ivaMaskInd;        // What kind of indirect assignments are there?
5849         callInterf   ivaMaskCall;       // What kind of calls are there?
5850     };
5851
5852     static callInterf optCallInterf(GenTreeCall* call);
5853
5854 public:
5855     // VN based copy propagation.
5856     typedef ArrayStack<GenTree*> GenTreePtrStack;
5857     typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, GenTreePtrStack*> LclNumToGenTreePtrStack;
5858
5859     // Kill set to track variables with intervening definitions.
5860     VARSET_TP optCopyPropKillSet;
5861
5862     // Copy propagation functions.
5863     void optCopyProp(BasicBlock* block, GenTree* stmt, GenTree* tree, LclNumToGenTreePtrStack* curSsaName);
5864     void optBlockCopyPropPopStacks(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5865     void optBlockCopyProp(BasicBlock* block, LclNumToGenTreePtrStack* curSsaName);
5866     bool optIsSsaLocal(GenTree* tree);
5867     int optCopyProp_LclVarScore(LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc, bool preferOp2);
5868     void optVnCopyProp();
5869     INDEBUG(void optDumpCopyPropStack(LclNumToGenTreePtrStack* curSsaName));
5870
5871     /**************************************************************************
5872     *               Early value propagation
5873     *************************************************************************/
5874     struct SSAName
5875     {
5876         unsigned m_lvNum;
5877         unsigned m_ssaNum;
5878
5879         SSAName(unsigned lvNum, unsigned ssaNum) : m_lvNum(lvNum), m_ssaNum(ssaNum)
5880         {
5881         }
5882
5883         static unsigned GetHashCode(SSAName ssaNm)
5884         {
5885             return (ssaNm.m_lvNum << 16) | (ssaNm.m_ssaNum);
5886         }
5887
5888         static bool Equals(SSAName ssaNm1, SSAName ssaNm2)
5889         {
5890             return (ssaNm1.m_lvNum == ssaNm2.m_lvNum) && (ssaNm1.m_ssaNum == ssaNm2.m_ssaNum);
5891         }
5892     };
5893
5894 #define OMF_HAS_NEWARRAY 0x00000001   // Method contains 'new' of an array
5895 #define OMF_HAS_NEWOBJ 0x00000002     // Method contains 'new' of an object type.
5896 #define OMF_HAS_ARRAYREF 0x00000004   // Method contains array element loads or stores.
5897 #define OMF_HAS_VTABLEREF 0x00000008  // Method contains method table reference.
5898 #define OMF_HAS_NULLCHECK 0x00000010  // Method contains null check.
5899 #define OMF_HAS_FATPOINTER 0x00000020 // Method contains call, that needs fat pointer transformation.
5900
5901     bool doesMethodHaveFatPointer()
5902     {
5903         return (optMethodFlags & OMF_HAS_FATPOINTER) != 0;
5904     }
5905
5906     void setMethodHasFatPointer()
5907     {
5908         optMethodFlags |= OMF_HAS_FATPOINTER;
5909     }
5910
5911     void clearMethodHasFatPointer()
5912     {
5913         optMethodFlags &= ~OMF_HAS_FATPOINTER;
5914     }
5915
5916     void addFatPointerCandidate(GenTreeCall* call);
5917
5918     unsigned optMethodFlags;
5919
5920     // Recursion bound controls how far we can go backwards tracking for a SSA value.
5921     // No throughput diff was found with backward walk bound between 3-8.
5922     static const int optEarlyPropRecurBound = 5;
5923
5924     enum class optPropKind
5925     {
5926         OPK_INVALID,
5927         OPK_ARRAYLEN,
5928         OPK_OBJ_GETTYPE,
5929         OPK_NULLCHECK
5930     };
5931
5932     bool gtIsVtableRef(GenTree* tree);
5933     GenTree* getArrayLengthFromAllocation(GenTree* tree);
5934     GenTree* getObjectHandleNodeFromAllocation(GenTree* tree);
5935     GenTree* optPropGetValueRec(unsigned lclNum, unsigned ssaNum, optPropKind valueKind, int walkDepth);
5936     GenTree* optPropGetValue(unsigned lclNum, unsigned ssaNum, optPropKind valueKind);
5937     GenTree* optEarlyPropRewriteTree(GenTree* tree);
5938     bool optDoEarlyPropForBlock(BasicBlock* block);
5939     bool optDoEarlyPropForFunc();
5940     void optEarlyProp();
5941     void optFoldNullCheck(GenTree* tree);
5942     bool optCanMoveNullCheckPastTree(GenTree* tree, bool isInsideTry);
5943
5944 #if ASSERTION_PROP
5945     /**************************************************************************
5946      *               Value/Assertion propagation
5947      *************************************************************************/
5948 public:
5949     // Data structures for assertion prop
5950     BitVecTraits* apTraits;
5951     ASSERT_TP     apFull;
5952
5953     enum optAssertionKind
5954     {
5955         OAK_INVALID,
5956         OAK_EQUAL,
5957         OAK_NOT_EQUAL,
5958         OAK_SUBRANGE,
5959         OAK_NO_THROW,
5960         OAK_COUNT
5961     };
5962
5963     enum optOp1Kind
5964     {
5965         O1K_INVALID,
5966         O1K_LCLVAR,
5967         O1K_ARR_BND,
5968         O1K_BOUND_OPER_BND,
5969         O1K_BOUND_LOOP_BND,
5970         O1K_CONSTANT_LOOP_BND,
5971         O1K_EXACT_TYPE,
5972         O1K_SUBTYPE,
5973         O1K_VALUE_NUMBER,
5974         O1K_COUNT
5975     };
5976
5977     enum optOp2Kind
5978     {
5979         O2K_INVALID,
5980         O2K_LCLVAR_COPY,
5981         O2K_IND_CNS_INT,
5982         O2K_CONST_INT,
5983         O2K_CONST_LONG,
5984         O2K_CONST_DOUBLE,
5985         O2K_ARR_LEN,
5986         O2K_SUBRANGE,
5987         O2K_COUNT
5988     };
5989     struct AssertionDsc
5990     {
5991         optAssertionKind assertionKind;
5992         struct SsaVar
5993         {
5994             unsigned lclNum; // assigned to or property of this local var number
5995             unsigned ssaNum;
5996         };
5997         struct ArrBnd
5998         {
5999             ValueNum vnIdx;
6000             ValueNum vnLen;
6001         };
6002         struct AssertionDscOp1
6003         {
6004             optOp1Kind kind; // a normal LclVar, or Exact-type or Subtype
6005             ValueNum   vn;
6006             union {
6007                 SsaVar lcl;
6008                 ArrBnd bnd;
6009             };
6010         } op1;
6011         struct AssertionDscOp2
6012         {
6013             optOp2Kind kind; // a const or copy assignment
6014             ValueNum   vn;
6015             struct IntVal
6016             {
6017                 ssize_t  iconVal;   // integer
6018                 unsigned iconFlags; // gtFlags
6019             };
6020             struct Range // integer subrange
6021             {
6022                 ssize_t loBound;
6023                 ssize_t hiBound;
6024             };
6025             union {
6026                 SsaVar  lcl;
6027                 IntVal  u1;
6028                 __int64 lconVal;
6029                 double  dconVal;
6030                 Range   u2;
6031             };
6032         } op2;
6033
6034         bool IsCheckedBoundArithBound()
6035         {
6036             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_OPER_BND);
6037         }
6038         bool IsCheckedBoundBound()
6039         {
6040             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) && op1.kind == O1K_BOUND_LOOP_BND);
6041         }
6042         bool IsConstantBound()
6043         {
6044             return ((assertionKind == OAK_EQUAL || assertionKind == OAK_NOT_EQUAL) &&
6045                     op1.kind == O1K_CONSTANT_LOOP_BND);
6046         }
6047         bool IsBoundsCheckNoThrow()
6048         {
6049             return ((assertionKind == OAK_NO_THROW) && (op1.kind == O1K_ARR_BND));
6050         }
6051
6052         bool IsCopyAssertion()
6053         {
6054             return ((assertionKind == OAK_EQUAL) && (op1.kind == O1K_LCLVAR) && (op2.kind == O2K_LCLVAR_COPY));
6055         }
6056
6057         static bool SameKind(AssertionDsc* a1, AssertionDsc* a2)
6058         {
6059             return a1->assertionKind == a2->assertionKind && a1->op1.kind == a2->op1.kind &&
6060                    a1->op2.kind == a2->op2.kind;
6061         }
6062
6063         static bool ComplementaryKind(optAssertionKind kind, optAssertionKind kind2)
6064         {
6065             if (kind == OAK_EQUAL)
6066             {
6067                 return kind2 == OAK_NOT_EQUAL;
6068             }
6069             else if (kind == OAK_NOT_EQUAL)
6070             {
6071                 return kind2 == OAK_EQUAL;
6072             }
6073             return false;
6074         }
6075
6076         static ssize_t GetLowerBoundForIntegralType(var_types type)
6077         {
6078             switch (type)
6079             {
6080                 case TYP_BYTE:
6081                     return SCHAR_MIN;
6082                 case TYP_SHORT:
6083                     return SHRT_MIN;
6084                 case TYP_INT:
6085                     return INT_MIN;
6086                 case TYP_BOOL:
6087                 case TYP_UBYTE:
6088                 case TYP_USHORT:
6089                 case TYP_UINT:
6090                     return 0;
6091                 default:
6092                     unreached();
6093             }
6094         }
6095         static ssize_t GetUpperBoundForIntegralType(var_types type)
6096         {
6097             switch (type)
6098             {
6099                 case TYP_BOOL:
6100                     return 1;
6101                 case TYP_BYTE:
6102                     return SCHAR_MAX;
6103                 case TYP_SHORT:
6104                     return SHRT_MAX;
6105                 case TYP_INT:
6106                     return INT_MAX;
6107                 case TYP_UBYTE:
6108                     return UCHAR_MAX;
6109                 case TYP_USHORT:
6110                     return USHRT_MAX;
6111                 case TYP_UINT:
6112                     return UINT_MAX;
6113                 default:
6114                     unreached();
6115             }
6116         }
6117
6118         bool HasSameOp1(AssertionDsc* that, bool vnBased)
6119         {
6120             if (op1.kind != that->op1.kind)
6121             {
6122                 return false;
6123             }
6124             else if (op1.kind == O1K_ARR_BND)
6125             {
6126                 assert(vnBased);
6127                 return (op1.bnd.vnIdx == that->op1.bnd.vnIdx) && (op1.bnd.vnLen == that->op1.bnd.vnLen);
6128             }
6129             else
6130             {
6131                 return ((vnBased && (op1.vn == that->op1.vn)) ||
6132                         (!vnBased && (op1.lcl.lclNum == that->op1.lcl.lclNum)));
6133             }
6134         }
6135
6136         bool HasSameOp2(AssertionDsc* that, bool vnBased)
6137         {
6138             if (op2.kind != that->op2.kind)
6139             {
6140                 return false;
6141             }
6142             switch (op2.kind)
6143             {
6144                 case O2K_IND_CNS_INT:
6145                 case O2K_CONST_INT:
6146                     return ((op2.u1.iconVal == that->op2.u1.iconVal) && (op2.u1.iconFlags == that->op2.u1.iconFlags));
6147
6148                 case O2K_CONST_LONG:
6149                     return (op2.lconVal == that->op2.lconVal);
6150
6151                 case O2K_CONST_DOUBLE:
6152                     // exact match because of positive and negative zero.
6153                     return (memcmp(&op2.dconVal, &that->op2.dconVal, sizeof(double)) == 0);
6154
6155                 case O2K_LCLVAR_COPY:
6156                 case O2K_ARR_LEN:
6157                     return (op2.lcl.lclNum == that->op2.lcl.lclNum) &&
6158                            (!vnBased || op2.lcl.ssaNum == that->op2.lcl.ssaNum);
6159
6160                 case O2K_SUBRANGE:
6161                     return ((op2.u2.loBound == that->op2.u2.loBound) && (op2.u2.hiBound == that->op2.u2.hiBound));
6162
6163                 case O2K_INVALID:
6164                     // we will return false
6165                     break;
6166
6167                 default:
6168                     assert(!"Unexpected value for op2.kind in AssertionDsc.");
6169                     break;
6170             }
6171             return false;
6172         }
6173
6174         bool Complementary(AssertionDsc* that, bool vnBased)
6175         {
6176             return ComplementaryKind(assertionKind, that->assertionKind) && HasSameOp1(that, vnBased) &&
6177                    HasSameOp2(that, vnBased);
6178         }
6179
6180         bool Equals(AssertionDsc* that, bool vnBased)
6181         {
6182             if (assertionKind != that->assertionKind)
6183             {
6184                 return false;
6185             }
6186             else if (assertionKind == OAK_NO_THROW)
6187             {
6188                 assert(op2.kind == O2K_INVALID);
6189                 return HasSameOp1(that, vnBased);
6190             }
6191             else
6192             {
6193                 return HasSameOp1(that, vnBased) && HasSameOp2(that, vnBased);
6194             }
6195         }
6196     };
6197
6198 protected:
6199     static fgWalkPreFn optAddCopiesCallback;
6200     static fgWalkPreFn optVNAssertionPropCurStmtVisitor;
6201     unsigned           optAddCopyLclNum;
6202     GenTree*           optAddCopyAsgnNode;
6203
6204     bool optLocalAssertionProp;  // indicates that we are performing local assertion prop
6205     bool optAssertionPropagated; // set to true if we modified the trees
6206     bool optAssertionPropagatedCurrentStmt;
6207 #ifdef DEBUG
6208     GenTree* optAssertionPropCurrentTree;
6209 #endif
6210     AssertionIndex*            optComplementaryAssertionMap;
6211     JitExpandArray<ASSERT_TP>* optAssertionDep; // table that holds dependent assertions (assertions
6212                                                 // using the value of a local var) for each local var
6213     AssertionDsc*  optAssertionTabPrivate;      // table that holds info about value assignments
6214     AssertionIndex optAssertionCount;           // total number of assertions in the assertion table
6215     AssertionIndex optMaxAssertionCount;
6216
6217 public:
6218     void optVnNonNullPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6219     fgWalkResult optVNConstantPropCurStmt(BasicBlock* block, GenTree* stmt, GenTree* tree);
6220     GenTree* optVNConstantPropOnRelOp(GenTree* tree);
6221     GenTree* optVNConstantPropOnJTrue(BasicBlock* block, GenTree* stmt, GenTree* test);
6222     GenTree* optVNConstantPropOnTree(BasicBlock* block, GenTree* stmt, GenTree* tree);
6223     GenTree* optPrepareTreeForReplacement(GenTree* extractTree, GenTree* replaceTree);
6224
6225     AssertionIndex GetAssertionCount()
6226     {
6227         return optAssertionCount;
6228     }
6229     ASSERT_TP* bbJtrueAssertionOut;
6230     typedef JitHashTable<ValueNum, JitSmallPrimitiveKeyFuncs<ValueNum>, ASSERT_TP> ValueNumToAssertsMap;
6231     ValueNumToAssertsMap* optValueNumToAsserts;
6232
6233     // Assertion prop helpers.
6234     ASSERT_TP& GetAssertionDep(unsigned lclNum);
6235     AssertionDsc* optGetAssertion(AssertionIndex assertIndex);
6236     void optAssertionInit(bool isLocalProp);
6237     void optAssertionTraitsInit(AssertionIndex assertionCount);
6238 #if LOCAL_ASSERTION_PROP
6239     void optAssertionReset(AssertionIndex limit);
6240     void optAssertionRemove(AssertionIndex index);
6241 #endif
6242
6243     // Assertion prop data flow functions.
6244     void     optAssertionPropMain();
6245     GenTree* optVNAssertionPropCurStmt(BasicBlock* block, GenTree* stmt);
6246     bool optIsTreeKnownIntValue(bool vnBased, GenTree* tree, ssize_t* pConstant, unsigned* pIconFlags);
6247     ASSERT_TP* optInitAssertionDataflowFlags();
6248     ASSERT_TP* optComputeAssertionGen();
6249
6250     // Assertion Gen functions.
6251     void optAssertionGen(GenTree* tree);
6252     AssertionIndex optAssertionGenPhiDefn(GenTree* tree);
6253     AssertionInfo optCreateJTrueBoundsAssertion(GenTree* tree);
6254     AssertionInfo optAssertionGenJtrue(GenTree* tree);
6255     AssertionIndex optCreateJtrueAssertions(GenTree* op1, GenTree* op2, Compiler::optAssertionKind assertionKind);
6256     AssertionIndex optFindComplementary(AssertionIndex assertionIndex);
6257     void optMapComplementary(AssertionIndex assertionIndex, AssertionIndex index);
6258
6259     // Assertion creation functions.
6260     AssertionIndex optCreateAssertion(GenTree* op1, GenTree* op2, optAssertionKind assertionKind);
6261     AssertionIndex optCreateAssertion(GenTree*         op1,
6262                                       GenTree*         op2,
6263                                       optAssertionKind assertionKind,
6264                                       AssertionDsc*    assertion);
6265     void optCreateComplementaryAssertion(AssertionIndex assertionIndex, GenTree* op1, GenTree* op2);
6266
6267     bool optAssertionVnInvolvesNan(AssertionDsc* assertion);
6268     AssertionIndex optAddAssertion(AssertionDsc* assertion);
6269     void optAddVnAssertionMapping(ValueNum vn, AssertionIndex index);
6270 #ifdef DEBUG
6271     void optPrintVnAssertionMapping();
6272 #endif
6273     ASSERT_TP optGetVnMappedAssertions(ValueNum vn);
6274
6275     // Used for respective assertion propagations.
6276     AssertionIndex optAssertionIsSubrange(GenTree* tree, var_types toType, ASSERT_VALARG_TP assertions);
6277     AssertionIndex optAssertionIsSubtype(GenTree* tree, GenTree* methodTableArg, ASSERT_VALARG_TP assertions);
6278     AssertionIndex optAssertionIsNonNullInternal(GenTree* op, ASSERT_VALARG_TP assertions);
6279     bool optAssertionIsNonNull(GenTree*         op,
6280                                ASSERT_VALARG_TP assertions DEBUGARG(bool* pVnBased) DEBUGARG(AssertionIndex* pIndex));
6281
6282     // Used for Relop propagation.
6283     AssertionIndex optGlobalAssertionIsEqualOrNotEqual(ASSERT_VALARG_TP assertions, GenTree* op1, GenTree* op2);
6284     AssertionIndex optLocalAssertionIsEqualOrNotEqual(
6285         optOp1Kind op1Kind, unsigned lclNum, optOp2Kind op2Kind, ssize_t cnsVal, ASSERT_VALARG_TP assertions);
6286
6287     // Assertion prop for lcl var functions.
6288     bool optAssertionProp_LclVarTypeCheck(GenTree* tree, LclVarDsc* lclVarDsc, LclVarDsc* copyVarDsc);
6289     GenTree* optCopyAssertionProp(AssertionDsc* curAssertion,
6290                                   GenTree*      tree,
6291                                   GenTree* stmt DEBUGARG(AssertionIndex index));
6292     GenTree* optConstantAssertionProp(AssertionDsc* curAssertion,
6293                                       GenTree*      tree,
6294                                       GenTree* stmt DEBUGARG(AssertionIndex index));
6295     GenTree* optVnConstantAssertionProp(GenTree* tree, GenTree* stmt);
6296
6297     // Assertion propagation functions.
6298     GenTree* optAssertionProp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6299     GenTree* optAssertionProp_LclVar(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6300     GenTree* optAssertionProp_Ind(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6301     GenTree* optAssertionProp_Cast(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6302     GenTree* optAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6303     GenTree* optAssertionProp_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6304     GenTree* optAssertionProp_Comma(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6305     GenTree* optAssertionProp_BndsChk(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6306     GenTree* optAssertionPropGlobal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6307     GenTree* optAssertionPropLocal_RelOp(ASSERT_VALARG_TP assertions, GenTree* tree, GenTree* stmt);
6308     GenTree* optAssertionProp_Update(GenTree* newTree, GenTree* tree, GenTree* stmt);
6309     GenTree* optNonNullAssertionProp_Call(ASSERT_VALARG_TP assertions, GenTreeCall* call, GenTree* stmt);
6310
6311     // Implied assertion functions.
6312     void optImpliedAssertions(AssertionIndex assertionIndex, ASSERT_TP& activeAssertions);
6313     void optImpliedByTypeOfAssertions(ASSERT_TP& activeAssertions);
6314     void optImpliedByCopyAssertion(AssertionDsc* copyAssertion, AssertionDsc* depAssertion, ASSERT_TP& result);
6315     void optImpliedByConstAssertion(AssertionDsc* curAssertion, ASSERT_TP& result);
6316
6317 #ifdef DEBUG
6318     void optPrintAssertion(AssertionDsc* newAssertion, AssertionIndex assertionIndex = 0);
6319     void optDebugCheckAssertion(AssertionDsc* assertion);
6320     void optDebugCheckAssertions(AssertionIndex AssertionIndex);
6321 #endif
6322     void optAddCopies();
6323 #endif // ASSERTION_PROP
6324
6325     /**************************************************************************
6326      *                          Range checks
6327      *************************************************************************/
6328
6329 public:
6330     struct LoopCloneVisitorInfo
6331     {
6332         LoopCloneContext* context;
6333         unsigned          loopNum;
6334         GenTree*          stmt;
6335         LoopCloneVisitorInfo(LoopCloneContext* context, unsigned loopNum, GenTree* stmt)
6336             : context(context), loopNum(loopNum), stmt(nullptr)
6337         {
6338         }
6339     };
6340
6341     bool optIsStackLocalInvariant(unsigned loopNum, unsigned lclNum);
6342     bool optExtractArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6343     bool optReconstructArrIndex(GenTree* tree, ArrIndex* result, unsigned lhsNum);
6344     bool optIdentifyLoopOptInfo(unsigned loopNum, LoopCloneContext* context);
6345     static fgWalkPreFn optCanOptimizeByLoopCloningVisitor;
6346     fgWalkResult optCanOptimizeByLoopCloning(GenTree* tree, LoopCloneVisitorInfo* info);
6347     void optObtainLoopCloningOpts(LoopCloneContext* context);
6348     bool optIsLoopClonable(unsigned loopInd);
6349
6350     bool optCanCloneLoops();
6351
6352 #ifdef DEBUG
6353     void optDebugLogLoopCloning(BasicBlock* block, GenTree* insertBefore);
6354 #endif
6355     void optPerformStaticOptimizations(unsigned loopNum, LoopCloneContext* context DEBUGARG(bool fastPath));
6356     bool optComputeDerefConditions(unsigned loopNum, LoopCloneContext* context);
6357     bool optDeriveLoopCloningConditions(unsigned loopNum, LoopCloneContext* context);
6358     BasicBlock* optInsertLoopChoiceConditions(LoopCloneContext* context,
6359                                               unsigned          loopNum,
6360                                               BasicBlock*       head,
6361                                               BasicBlock*       slow);
6362     void optInsertLoopCloningStress(BasicBlock* head);
6363
6364 #if COUNT_RANGECHECKS
6365     static unsigned optRangeChkRmv;
6366     static unsigned optRangeChkAll;
6367 #endif
6368
6369 protected:
6370     struct arraySizes
6371     {
6372         unsigned arrayVar;
6373         int      arrayDim;
6374
6375 #define MAX_ARRAYS 4 // a magic max number of arrays tracked for bounds check elimination
6376     };
6377
6378     struct RngChkDsc
6379     {
6380         RngChkDsc* rcdNextInBucket; // used by the hash table
6381
6382         unsigned short rcdHashValue; // to make matching faster
6383         unsigned short rcdIndex;     // 0..optRngChkCount-1
6384
6385         GenTree* rcdTree; // the array index tree
6386     };
6387
6388     unsigned            optRngChkCount;
6389     static const size_t optRngChkHashSize;
6390
6391     ssize_t optGetArrayRefScaleAndIndex(GenTree* mul, GenTree** pIndex DEBUGARG(bool bRngChk));
6392     GenTree* optFindLocalInit(BasicBlock* block, GenTree* local, VARSET_TP* pKilledInOut, bool* isKilledAfterInit);
6393
6394     bool optReachWithoutCall(BasicBlock* srcBB, BasicBlock* dstBB);
6395
6396 protected:
6397     bool optLoopsMarked;
6398
6399     /*
6400     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6401     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6402     XX                                                                           XX
6403     XX                           RegAlloc                                        XX
6404     XX                                                                           XX
6405     XX  Does the register allocation and puts the remaining lclVars on the stack XX
6406     XX                                                                           XX
6407     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6408     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6409     */
6410
6411 public:
6412 #ifndef LEGACY_BACKEND
6413     bool doLSRA() const
6414     {
6415         return true;
6416     }
6417 #else  // LEGACY_BACKEND
6418     bool doLSRA() const
6419     {
6420         return false;
6421     }
6422 #endif // LEGACY_BACKEND
6423
6424 #ifdef LEGACY_BACKEND
6425     void raInit();
6426     void raAssignVars(); // register allocation
6427 #endif                   // LEGACY_BACKEND
6428
6429     VARSET_TP raRegVarsMask; // Set of all enregistered variables (not including FEATURE_STACK_FP_X87 enregistered
6430                              // variables)
6431     regNumber raUpdateRegStateForArg(RegState* regState, LclVarDsc* argDsc);
6432
6433     void raMarkStkVars();
6434
6435 protected:
6436     // Some things are used by both LSRA and regpredict allocators.
6437
6438     FrameType rpFrameType;
6439     bool      rpMustCreateEBPCalled; // Set to true after we have called rpMustCreateEBPFrame once
6440
6441 #ifdef LEGACY_BACKEND
6442     regMaskTP rpMaskPInvokeEpilogIntf; // pinvoke epilog trashes esi/edi holding stack args needed to setup tail call's
6443                                        // args
6444 #endif                                 // LEGACY_BACKEND
6445
6446     bool rpMustCreateEBPFrame(INDEBUG(const char** wbReason));
6447
6448 #if FEATURE_FP_REGALLOC
6449     enum enumConfigRegisterFP
6450     {
6451         CONFIG_REGISTER_FP_NONE         = 0x0,
6452         CONFIG_REGISTER_FP_CALLEE_TRASH = 0x1,
6453         CONFIG_REGISTER_FP_CALLEE_SAVED = 0x2,
6454         CONFIG_REGISTER_FP_FULL         = 0x3,
6455     };
6456     enumConfigRegisterFP raConfigRegisterFP();
6457 #endif // FEATURE_FP_REGALLOC
6458
6459 public:
6460     regMaskTP raConfigRestrictMaskFP();
6461
6462 private:
6463 #ifndef LEGACY_BACKEND
6464     Lowering*            m_pLowering;   // Lowering; needed to Lower IR that's added or modified after Lowering.
6465     LinearScanInterface* m_pLinearScan; // Linear Scan allocator
6466 #else                                   // LEGACY_BACKEND
6467     unsigned  raAvoidArgRegMask;       // Mask of incoming argument registers that we may need to avoid
6468     VARSET_TP raLclRegIntf[REG_COUNT]; // variable to register interference graph
6469     bool      raNewBlocks;             // True is we added killing blocks for FPU registers
6470     unsigned  rpPasses;                // Number of passes made by the register predicter
6471     unsigned  rpPassesMax;             // Maximum number of passes made by the register predicter
6472     unsigned  rpPassesPessimize;       // Number of passes non-pessimizing made by the register predicter
6473     unsigned rpStkPredict; // Weighted count of variables were predicted STK (lower means register allocation is better)
6474     unsigned rpPredictSpillCnt;     // Predicted number of integer spill tmps for the current tree
6475     regMaskTP rpPredictAssignMask;  // Mask of registers to consider in rpPredictAssignRegVars()
6476     VARSET_TP rpLastUseVars;        // Set of last use variables in rpPredictTreeRegUse
6477     VARSET_TP rpUseInPlace;         // Set of variables that we used in place
6478     int       rpAsgVarNum;          // VarNum for the target of GT_ASG node
6479     bool      rpPredictAssignAgain; // Must rerun the rpPredictAssignRegVars()
6480     bool      rpAddedVarIntf;       // Set to true if we need to add a new var intf
6481     bool      rpLostEnreg;          // Set to true if we lost an enregister var that had lvDependReg set
6482     bool      rpReverseEBPenreg;    // Decided to reverse the enregistration of EBP
6483 public:
6484     bool rpRegAllocDone; // Set to true after we have completed register allocation
6485 private:
6486     regMaskTP rpPredictMap[PREDICT_COUNT]; // Holds the regMaskTP for each of the enum values
6487
6488     void raSetupArgMasks(RegState* r);
6489
6490     const regNumber* raGetRegVarOrder(var_types regType, unsigned* wbVarOrderSize);
6491 #ifdef DEBUG
6492     void raDumpVarIntf(); // Dump the variable to variable interference graph
6493     void raDumpRegIntf(); // Dump the variable to register interference graph
6494 #endif
6495     void raAdjustVarIntf();
6496
6497     regMaskTP rpPredictRegMask(rpPredictReg predictReg, var_types type);
6498
6499     bool rpRecordRegIntf(regMaskTP regMask, VARSET_VALARG_TP life DEBUGARG(const char* msg));
6500
6501     bool rpRecordVarIntf(unsigned varNum, VARSET_VALARG_TP intfVar DEBUGARG(const char* msg));
6502     regMaskTP rpPredictRegPick(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
6503
6504     regMaskTP rpPredictGrabReg(var_types type, rpPredictReg predictReg, regMaskTP lockedRegs);
6505
6506     static fgWalkPreFn rpMarkRegIntf;
6507
6508     regMaskTP rpPredictAddressMode(
6509         GenTree* tree, var_types type, regMaskTP lockedRegs, regMaskTP rsvdRegs, GenTree* lenCSE);
6510
6511     void rpPredictRefAssign(unsigned lclNum);
6512
6513     regMaskTP rpPredictBlkAsgRegUse(GenTree* tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
6514
6515     regMaskTP rpPredictTreeRegUse(GenTree* tree, rpPredictReg predictReg, regMaskTP lockedRegs, regMaskTP rsvdRegs);
6516
6517     regMaskTP rpPredictAssignRegVars(regMaskTP regAvail);
6518
6519     void rpPredictRegUse(); // Entry point
6520
6521     unsigned raPredictTreeRegUse(GenTree* tree);
6522     unsigned raPredictListRegUse(GenTree* list);
6523
6524     void raSetRegVarOrder(var_types  regType,
6525                           regNumber* customVarOrder,
6526                           unsigned*  customVarOrderSize,
6527                           regMaskTP  prefReg,
6528                           regMaskTP  avoidReg);
6529
6530     // We use (unsigned)-1 as an uninitialized sentinel for rpStkPredict and
6531     // also as the maximum value of lvRefCntWtd. Don't allow overflow, and
6532     // saturate at UINT_MAX - 1, to avoid using the sentinel.
6533     void raAddToStkPredict(unsigned val)
6534     {
6535         unsigned newStkPredict = rpStkPredict + val;
6536         if ((newStkPredict < rpStkPredict) || (newStkPredict == UINT_MAX))
6537             rpStkPredict = UINT_MAX - 1;
6538         else
6539             rpStkPredict = newStkPredict;
6540     }
6541
6542 #ifdef DEBUG
6543 #if !FEATURE_FP_REGALLOC
6544     void raDispFPlifeInfo();
6545 #endif
6546 #endif
6547
6548     regMaskTP genReturnRegForTree(GenTree* tree);
6549 #endif // LEGACY_BACKEND
6550
6551     /* raIsVarargsStackArg is called by raMaskStkVars and by
6552        lvaSortByRefCount.  It identifies the special case
6553        where a varargs function has a parameter passed on the
6554        stack, other than the special varargs handle.  Such parameters
6555        require special treatment, because they cannot be tracked
6556        by the GC (their offsets in the stack are not known
6557        at compile time).
6558     */
6559
6560     bool raIsVarargsStackArg(unsigned lclNum)
6561     {
6562 #ifdef _TARGET_X86_
6563
6564         LclVarDsc* varDsc = &lvaTable[lclNum];
6565
6566         assert(varDsc->lvIsParam);
6567
6568         return (info.compIsVarArgs && !varDsc->lvIsRegArg && (lclNum != lvaVarargsHandleArg));
6569
6570 #else // _TARGET_X86_
6571
6572         return false;
6573
6574 #endif // _TARGET_X86_
6575     }
6576
6577 #ifdef LEGACY_BACKEND
6578     // Records the current prediction, if it's better than any previous recorded prediction.
6579     void rpRecordPrediction();
6580     // Applies the best recorded prediction, if one exists and is better than the current prediction.
6581     void rpUseRecordedPredictionIfBetter();
6582
6583     // Data members used in the methods above.
6584     unsigned rpBestRecordedStkPredict;
6585     struct VarRegPrediction
6586     {
6587         bool           m_isEnregistered;
6588         regNumberSmall m_regNum;
6589         regNumberSmall m_otherReg;
6590     };
6591     VarRegPrediction* rpBestRecordedPrediction;
6592 #endif // LEGACY_BACKEND
6593
6594     /*
6595     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6596     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6597     XX                                                                           XX
6598     XX                           EEInterface                                     XX
6599     XX                                                                           XX
6600     XX   Get to the class and method info from the Execution Engine given        XX
6601     XX   tokens for the class and method                                         XX
6602     XX                                                                           XX
6603     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6604     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
6605     */
6606
6607 public:
6608     /* These are the different addressing modes used to access a local var.
6609      * The JIT has to report the location of the locals back to the EE
6610      * for debugging purposes.
6611      */
6612
6613     enum siVarLocType
6614     {
6615         VLT_REG,
6616         VLT_REG_BYREF, // this type is currently only used for value types on X64
6617         VLT_REG_FP,
6618         VLT_STK,
6619         VLT_STK_BYREF, // this type is currently only used for value types on X64
6620         VLT_REG_REG,
6621         VLT_REG_STK,
6622         VLT_STK_REG,
6623         VLT_STK2,
6624         VLT_FPSTK,
6625         VLT_FIXED_VA,
6626
6627         VLT_COUNT,
6628         VLT_INVALID
6629     };
6630
6631     struct siVarLoc
6632     {
6633         siVarLocType vlType;
6634
6635         union {
6636             // VLT_REG/VLT_REG_FP -- Any pointer-sized enregistered value (TYP_INT, TYP_REF, etc)
6637             // eg. EAX
6638             // VLT_REG_BYREF -- the specified register contains the address of the variable
6639             // eg. [EAX]
6640
6641             struct
6642             {
6643                 regNumber vlrReg;
6644             } vlReg;
6645
6646             // VLT_STK       -- Any 32 bit value which is on the stack
6647             // eg. [ESP+0x20], or [EBP-0x28]
6648             // VLT_STK_BYREF -- the specified stack location contains the address of the variable
6649             // eg. mov EAX, [ESP+0x20]; [EAX]
6650
6651             struct
6652             {
6653                 regNumber     vlsBaseReg;
6654                 NATIVE_OFFSET vlsOffset;
6655             } vlStk;
6656
6657             // VLT_REG_REG -- TYP_LONG/TYP_DOUBLE with both DWords enregistered
6658             // eg. RBM_EAXEDX
6659
6660             struct
6661             {
6662                 regNumber vlrrReg1;
6663                 regNumber vlrrReg2;
6664             } vlRegReg;
6665
6666             // VLT_REG_STK -- Partly enregistered TYP_LONG/TYP_DOUBLE
6667             // eg { LowerDWord=EAX UpperDWord=[ESP+0x8] }
6668
6669             struct
6670             {
6671                 regNumber vlrsReg;
6672
6673                 struct
6674                 {
6675                     regNumber     vlrssBaseReg;
6676                     NATIVE_OFFSET vlrssOffset;
6677                 } vlrsStk;
6678             } vlRegStk;
6679
6680             // VLT_STK_REG -- Partly enregistered TYP_LONG/TYP_DOUBLE
6681             // eg { LowerDWord=[ESP+0x8] UpperDWord=EAX }
6682
6683             struct
6684             {
6685                 struct
6686                 {
6687                     regNumber     vlsrsBaseReg;
6688                     NATIVE_OFFSET vlsrsOffset;
6689                 } vlsrStk;
6690
6691                 regNumber vlsrReg;
6692             } vlStkReg;
6693
6694             // VLT_STK2 -- Any 64 bit value which is on the stack, in 2 successsive DWords
6695             // eg 2 DWords at [ESP+0x10]
6696
6697             struct
6698             {
6699                 regNumber     vls2BaseReg;
6700                 NATIVE_OFFSET vls2Offset;
6701             } vlStk2;
6702
6703             // VLT_FPSTK -- enregisterd TYP_DOUBLE (on the FP stack)
6704             // eg. ST(3). Actually it is ST("FPstkHeight - vpFpStk")
6705
6706             struct
6707             {
6708                 unsigned vlfReg;
6709             } vlFPstk;
6710
6711             // VLT_FIXED_VA -- fixed argument of a varargs function.
6712             // The argument location depends on the size of the variable
6713             // arguments (...). Inspecting the VARARGS_HANDLE indicates the
6714             // location of the first arg. This argument can then be accessed
6715             // relative to the position of the first arg
6716
6717             struct
6718             {
6719                 unsigned vlfvOffset;
6720             } vlFixedVarArg;
6721
6722             // VLT_MEMORY
6723
6724             struct
6725             {
6726                 void* rpValue; // pointer to the in-process
6727                                // location of the value.
6728             } vlMemory;
6729         };
6730
6731         // Helper functions
6732
6733         bool vlIsInReg(regNumber reg);
6734         bool vlIsOnStk(regNumber reg, signed offset);
6735     };
6736
6737     /*************************************************************************/
6738
6739 public:
6740     // Get handles
6741
6742     void eeGetCallInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6743                        CORINFO_RESOLVED_TOKEN* pConstrainedToken,
6744                        CORINFO_CALLINFO_FLAGS  flags,
6745                        CORINFO_CALL_INFO*      pResult);
6746     inline CORINFO_CALLINFO_FLAGS addVerifyFlag(CORINFO_CALLINFO_FLAGS flags);
6747
6748     void eeGetFieldInfo(CORINFO_RESOLVED_TOKEN* pResolvedToken,
6749                         CORINFO_ACCESS_FLAGS    flags,
6750                         CORINFO_FIELD_INFO*     pResult);
6751
6752     // Get the flags
6753
6754     BOOL eeIsValueClass(CORINFO_CLASS_HANDLE clsHnd);
6755
6756 #if defined(DEBUG) || defined(FEATURE_JIT_METHOD_PERF) || defined(FEATURE_SIMD) || defined(TRACK_LSRA_STATS)
6757
6758     bool IsSuperPMIException(unsigned code)
6759     {
6760         // Copied from NDP\clr\src\ToolBox\SuperPMI\SuperPMI-Shared\ErrorHandling.h
6761
6762         const unsigned EXCEPTIONCODE_DebugBreakorAV = 0xe0421000;
6763         const unsigned EXCEPTIONCODE_MC             = 0xe0422000;
6764         const unsigned EXCEPTIONCODE_LWM            = 0xe0423000;
6765         const unsigned EXCEPTIONCODE_SASM           = 0xe0424000;
6766         const unsigned EXCEPTIONCODE_SSYM           = 0xe0425000;
6767         const unsigned EXCEPTIONCODE_CALLUTILS      = 0xe0426000;
6768         const unsigned EXCEPTIONCODE_TYPEUTILS      = 0xe0427000;
6769         const unsigned EXCEPTIONCODE_ASSERT         = 0xe0440000;
6770
6771         switch (code)
6772         {
6773             case EXCEPTIONCODE_DebugBreakorAV:
6774             case EXCEPTIONCODE_MC:
6775             case EXCEPTIONCODE_LWM:
6776             case EXCEPTIONCODE_SASM:
6777             case EXCEPTIONCODE_SSYM:
6778             case EXCEPTIONCODE_CALLUTILS:
6779             case EXCEPTIONCODE_TYPEUTILS:
6780             case EXCEPTIONCODE_ASSERT:
6781                 return true;
6782             default:
6783                 return false;
6784         }
6785     }
6786
6787     const char* eeGetMethodName(CORINFO_METHOD_HANDLE hnd, const char** className);
6788     const char* eeGetMethodFullName(CORINFO_METHOD_HANDLE hnd);
6789
6790     bool eeIsNativeMethod(CORINFO_METHOD_HANDLE method);
6791     CORINFO_METHOD_HANDLE eeGetMethodHandleForNative(CORINFO_METHOD_HANDLE method);
6792 #endif
6793
6794     var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6795     var_types eeGetArgType(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig, bool* isPinned);
6796     unsigned eeGetArgSize(CORINFO_ARG_LIST_HANDLE list, CORINFO_SIG_INFO* sig);
6797
6798     // VOM info, method sigs
6799
6800     void eeGetSig(unsigned               sigTok,
6801                   CORINFO_MODULE_HANDLE  scope,
6802                   CORINFO_CONTEXT_HANDLE context,
6803                   CORINFO_SIG_INFO*      retSig);
6804
6805     void eeGetCallSiteSig(unsigned               sigTok,
6806                           CORINFO_MODULE_HANDLE  scope,
6807                           CORINFO_CONTEXT_HANDLE context,
6808                           CORINFO_SIG_INFO*      retSig);
6809
6810     void eeGetMethodSig(CORINFO_METHOD_HANDLE methHnd, CORINFO_SIG_INFO* retSig, CORINFO_CLASS_HANDLE owner = nullptr);
6811
6812     // Method entry-points, instrs
6813
6814     void* eeGetFieldAddress(CORINFO_FIELD_HANDLE handle, void*** ppIndir);
6815
6816     CORINFO_METHOD_HANDLE eeMarkNativeTarget(CORINFO_METHOD_HANDLE method);
6817
6818     CORINFO_EE_INFO eeInfo;
6819     bool            eeInfoInitialized;
6820
6821     CORINFO_EE_INFO* eeGetEEInfo();
6822
6823     // Gets the offset of a SDArray's first element
6824     unsigned eeGetArrayDataOffset(var_types type);
6825     // Gets the offset of a MDArray's first element
6826     unsigned eeGetMDArrayDataOffset(var_types type, unsigned rank);
6827
6828     GenTree* eeGetPInvokeCookie(CORINFO_SIG_INFO* szMetaSig);
6829
6830     // Returns the page size for the target machine as reported by the EE.
6831     inline size_t eeGetPageSize()
6832     {
6833         return eeGetEEInfo()->osPageSize;
6834     }
6835
6836     // Returns the frame size at which we will generate a loop to probe the stack.
6837     inline size_t getVeryLargeFrameSize()
6838     {
6839 #ifdef _TARGET_ARM_
6840         // The looping probe code is 40 bytes, whereas the straight-line probing for
6841         // the (0x2000..0x3000) case is 44, so use looping for anything 0x2000 bytes
6842         // or greater, to generate smaller code.
6843         return 2 * eeGetPageSize();
6844 #else
6845         return 3 * eeGetPageSize();
6846 #endif
6847     }
6848
6849     //------------------------------------------------------------------------
6850     // VirtualStubParam: virtual stub dispatch extra parameter (slot address).
6851     //
6852     // It represents Abi and target specific registers for the parameter.
6853     //
6854     class VirtualStubParamInfo
6855     {
6856     public:
6857         VirtualStubParamInfo(bool isCoreRTABI)
6858         {
6859 #if defined(_TARGET_X86_)
6860             reg     = REG_EAX;
6861             regMask = RBM_EAX;
6862 #elif defined(_TARGET_AMD64_)
6863             if (isCoreRTABI)
6864             {
6865                 reg     = REG_R10;
6866                 regMask = RBM_R10;
6867             }
6868             else
6869             {
6870                 reg     = REG_R11;
6871                 regMask = RBM_R11;
6872             }
6873 #elif defined(_TARGET_ARM_)
6874             if (isCoreRTABI)
6875             {
6876                 reg     = REG_R12;
6877                 regMask = RBM_R12;
6878             }
6879             else
6880             {
6881                 reg     = REG_R4;
6882                 regMask = RBM_R4;
6883             }
6884 #elif defined(_TARGET_ARM64_)
6885             reg     = REG_R11;
6886             regMask = RBM_R11;
6887 #else
6888 #error Unsupported or unset target architecture
6889 #endif
6890
6891 #ifdef LEGACY_BACKEND
6892 #if defined(_TARGET_X86_)
6893             predict = PREDICT_REG_EAX;
6894 #elif defined(_TARGET_ARM_)
6895             predict = PREDICT_REG_R4;
6896 #else
6897 #error Unsupported or unset target architecture
6898 #endif
6899 #endif // LEGACY_BACKEND
6900         }
6901
6902         regNumber GetReg() const
6903         {
6904             return reg;
6905         }
6906
6907         _regMask_enum GetRegMask() const
6908         {
6909             return regMask;
6910         }
6911
6912 #ifdef LEGACY_BACKEND
6913         rpPredictReg GetPredict() const
6914         {
6915             return predict;
6916         }
6917 #endif
6918
6919     private:
6920         regNumber     reg;
6921         _regMask_enum regMask;
6922
6923 #ifdef LEGACY_BACKEND
6924         rpPredictReg predict;
6925 #endif
6926     };
6927
6928     VirtualStubParamInfo* virtualStubParamInfo;
6929
6930     inline bool IsTargetAbi(CORINFO_RUNTIME_ABI abi)
6931     {
6932         return eeGetEEInfo()->targetAbi == abi;
6933     }
6934
6935     inline bool generateCFIUnwindCodes()
6936     {
6937 #if defined(_TARGET_UNIX_)
6938         return IsTargetAbi(CORINFO_CORERT_ABI);
6939 #else
6940         return false;
6941 #endif
6942     }
6943
6944     // Exceptions
6945
6946     unsigned eeGetEHcount(CORINFO_METHOD_HANDLE handle);
6947
6948     // Debugging support - Line number info
6949
6950     void eeGetStmtOffsets();
6951
6952     unsigned eeBoundariesCount;
6953
6954     struct boundariesDsc
6955     {
6956         UNATIVE_OFFSET nativeIP;
6957         IL_OFFSET      ilOffset;
6958         unsigned       sourceReason;
6959     } * eeBoundaries; // Boundaries to report to EE
6960     void eeSetLIcount(unsigned count);
6961     void eeSetLIinfo(unsigned which, UNATIVE_OFFSET offs, unsigned srcIP, bool stkEmpty, bool callInstruction);
6962     void eeSetLIdone();
6963
6964 #ifdef DEBUG
6965     static void eeDispILOffs(IL_OFFSET offs);
6966     static void eeDispLineInfo(const boundariesDsc* line);
6967     void eeDispLineInfos();
6968 #endif // DEBUG
6969
6970     // Debugging support - Local var info
6971
6972     void eeGetVars();
6973
6974     unsigned eeVarsCount;
6975
6976     struct VarResultInfo
6977     {
6978         UNATIVE_OFFSET startOffset;
6979         UNATIVE_OFFSET endOffset;
6980         DWORD          varNumber;
6981         siVarLoc       loc;
6982     } * eeVars;
6983     void eeSetLVcount(unsigned count);
6984     void eeSetLVinfo(unsigned        which,
6985                      UNATIVE_OFFSET  startOffs,
6986                      UNATIVE_OFFSET  length,
6987                      unsigned        varNum,
6988                      unsigned        LVnum,
6989                      VarName         namex,
6990                      bool            avail,
6991                      const siVarLoc& loc);
6992     void eeSetLVdone();
6993
6994 #ifdef DEBUG
6995     void eeDispVar(ICorDebugInfo::NativeVarInfo* var);
6996     void eeDispVars(CORINFO_METHOD_HANDLE ftn, ULONG32 cVars, ICorDebugInfo::NativeVarInfo* vars);
6997 #endif // DEBUG
6998
6999     // ICorJitInfo wrappers
7000
7001     void eeReserveUnwindInfo(BOOL isFunclet, BOOL isColdCode, ULONG unwindSize);
7002
7003     void eeAllocUnwindInfo(BYTE*          pHotCode,
7004                            BYTE*          pColdCode,
7005                            ULONG          startOffset,
7006                            ULONG          endOffset,
7007                            ULONG          unwindSize,
7008                            BYTE*          pUnwindBlock,
7009                            CorJitFuncKind funcKind);
7010
7011     void eeSetEHcount(unsigned cEH);
7012
7013     void eeSetEHinfo(unsigned EHnumber, const CORINFO_EH_CLAUSE* clause);
7014
7015     WORD eeGetRelocTypeHint(void* target);
7016
7017     // ICorStaticInfo wrapper functions
7018
7019     bool eeTryResolveToken(CORINFO_RESOLVED_TOKEN* resolvedToken);
7020
7021 #if defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
7022 #ifdef DEBUG
7023     static void dumpSystemVClassificationType(SystemVClassificationType ct);
7024 #endif // DEBUG
7025
7026     void eeGetSystemVAmd64PassStructInRegisterDescriptor(
7027         /*IN*/ CORINFO_CLASS_HANDLE                                  structHnd,
7028         /*OUT*/ SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR* structPassInRegDescPtr);
7029 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
7030
7031     template <typename ParamType>
7032     bool eeRunWithErrorTrap(void (*function)(ParamType*), ParamType* param)
7033     {
7034         return eeRunWithErrorTrapImp(reinterpret_cast<void (*)(void*)>(function), reinterpret_cast<void*>(param));
7035     }
7036
7037     bool eeRunWithErrorTrapImp(void (*function)(void*), void* param);
7038
7039     // Utility functions
7040
7041     const char* eeGetFieldName(CORINFO_FIELD_HANDLE fieldHnd, const char** classNamePtr = nullptr);
7042
7043 #if defined(DEBUG)
7044     const wchar_t* eeGetCPString(size_t stringHandle);
7045 #endif
7046
7047     const char* eeGetClassName(CORINFO_CLASS_HANDLE clsHnd);
7048
7049     static CORINFO_METHOD_HANDLE eeFindHelper(unsigned helper);
7050     static CorInfoHelpFunc eeGetHelperNum(CORINFO_METHOD_HANDLE method);
7051
7052     static fgWalkPreFn CountSharedStaticHelper;
7053     static bool IsSharedStaticHelper(GenTree* tree);
7054     static bool IsTreeAlwaysHoistable(GenTree* tree);
7055     static bool IsGcSafePoint(GenTree* tree);
7056
7057     static CORINFO_FIELD_HANDLE eeFindJitDataOffs(unsigned jitDataOffs);
7058     // returns true/false if 'field' is a Jit Data offset
7059     static bool eeIsJitDataOffs(CORINFO_FIELD_HANDLE field);
7060     // returns a number < 0 if 'field' is not a Jit Data offset, otherwise the data offset (limited to 2GB)
7061     static int eeGetJitDataOffs(CORINFO_FIELD_HANDLE field);
7062
7063     /*****************************************************************************/
7064
7065 public:
7066     void tmpInit();
7067
7068     enum TEMP_USAGE_TYPE
7069     {
7070         TEMP_USAGE_FREE,
7071         TEMP_USAGE_USED
7072     };
7073
7074     static var_types tmpNormalizeType(var_types type);
7075     TempDsc* tmpGetTemp(var_types type); // get temp for the given type
7076     void tmpRlsTemp(TempDsc* temp);
7077     TempDsc* tmpFindNum(int temp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
7078
7079     void     tmpEnd();
7080     TempDsc* tmpListBeg(TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
7081     TempDsc* tmpListNxt(TempDsc* curTemp, TEMP_USAGE_TYPE usageType = TEMP_USAGE_FREE) const;
7082     void tmpDone();
7083
7084 #ifdef DEBUG
7085     bool tmpAllFree() const;
7086 #endif // DEBUG
7087
7088 #ifndef LEGACY_BACKEND
7089     void tmpPreAllocateTemps(var_types type, unsigned count);
7090 #endif // !LEGACY_BACKEND
7091
7092 protected:
7093 #ifdef LEGACY_BACKEND
7094     unsigned tmpIntSpillMax;    // number of int-sized spill temps
7095     unsigned tmpDoubleSpillMax; // number of double-sized spill temps
7096 #endif                          // LEGACY_BACKEND
7097
7098     unsigned tmpCount; // Number of temps
7099     unsigned tmpSize;  // Size of all the temps
7100 #ifdef DEBUG
7101 public:
7102     // Used by RegSet::rsSpillChk()
7103     unsigned tmpGetCount; // Temps which haven't been released yet
7104 #endif
7105 private:
7106     static unsigned tmpSlot(unsigned size); // which slot in tmpFree[] or tmpUsed[] to use
7107
7108     TempDsc* tmpFree[TEMP_MAX_SIZE / sizeof(int)];
7109     TempDsc* tmpUsed[TEMP_MAX_SIZE / sizeof(int)];
7110
7111     /*
7112     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7113     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7114     XX                                                                           XX
7115     XX                           CodeGenerator                                   XX
7116     XX                                                                           XX
7117     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7118     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7119     */
7120
7121 public:
7122     CodeGenInterface* codeGen;
7123
7124     //  The following holds information about instr offsets in terms of generated code.
7125
7126     struct IPmappingDsc
7127     {
7128         IPmappingDsc* ipmdNext;      // next line# record
7129         IL_OFFSETX    ipmdILoffsx;   // the instr offset
7130         emitLocation  ipmdNativeLoc; // the emitter location of the native code corresponding to the IL offset
7131         bool          ipmdIsLabel;   // Can this code be a branch label?
7132     };
7133
7134     // Record the instr offset mapping to the generated code
7135
7136     IPmappingDsc* genIPmappingList;
7137     IPmappingDsc* genIPmappingLast;
7138
7139     // Managed RetVal - A side hash table meant to record the mapping from a
7140     // GT_CALL node to its IL offset.  This info is used to emit sequence points
7141     // that can be used by debugger to determine the native offset at which the
7142     // managed RetVal will be available.
7143     //
7144     // In fact we can store IL offset in a GT_CALL node.  This was ruled out in
7145     // favor of a side table for two reasons: 1) We need IL offset for only those
7146     // GT_CALL nodes (created during importation) that correspond to an IL call and
7147     // whose return type is other than TYP_VOID. 2) GT_CALL node is a frequently used
7148     // structure and IL offset is needed only when generating debuggable code. Therefore
7149     // it is desirable to avoid memory size penalty in retail scenarios.
7150     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, IL_OFFSETX> CallSiteILOffsetTable;
7151     CallSiteILOffsetTable* genCallSite2ILOffsetMap;
7152
7153     unsigned    genReturnLocal; // Local number for the return value when applicable.
7154     BasicBlock* genReturnBB;    // jumped to when not optimizing for speed.
7155
7156     // The following properties are part of CodeGenContext.  Getters are provided here for
7157     // convenience and backward compatibility, but the properties can only be set by invoking
7158     // the setter on CodeGenContext directly.
7159
7160     __declspec(property(get = getEmitter)) emitter* genEmitter;
7161     emitter* getEmitter()
7162     {
7163         return codeGen->getEmitter();
7164     }
7165
7166     const bool isFramePointerUsed()
7167     {
7168         return codeGen->isFramePointerUsed();
7169     }
7170
7171     __declspec(property(get = getInterruptible, put = setInterruptible)) bool genInterruptible;
7172     bool getInterruptible()
7173     {
7174         return codeGen->genInterruptible;
7175     }
7176     void setInterruptible(bool value)
7177     {
7178         codeGen->setInterruptible(value);
7179     }
7180
7181 #ifdef _TARGET_ARMARCH_
7182     __declspec(property(get = getHasTailCalls, put = setHasTailCalls)) bool hasTailCalls;
7183     bool getHasTailCalls()
7184     {
7185         return codeGen->hasTailCalls;
7186     }
7187     void setHasTailCalls(bool value)
7188     {
7189         codeGen->setHasTailCalls(value);
7190     }
7191 #endif // _TARGET_ARMARCH_
7192
7193 #if DOUBLE_ALIGN
7194     const bool genDoubleAlign()
7195     {
7196         return codeGen->doDoubleAlign();
7197     }
7198     DWORD getCanDoubleAlign();
7199     bool shouldDoubleAlign(unsigned refCntStk,
7200                            unsigned refCntReg,
7201                            unsigned refCntWtdReg,
7202                            unsigned refCntStkParam,
7203                            unsigned refCntWtdStkDbl);
7204 #endif // DOUBLE_ALIGN
7205
7206     __declspec(property(get = getFullPtrRegMap, put = setFullPtrRegMap)) bool genFullPtrRegMap;
7207     bool getFullPtrRegMap()
7208     {
7209         return codeGen->genFullPtrRegMap;
7210     }
7211     void setFullPtrRegMap(bool value)
7212     {
7213         codeGen->setFullPtrRegMap(value);
7214     }
7215
7216 // Things that MAY belong either in CodeGen or CodeGenContext
7217
7218 #if FEATURE_EH_FUNCLETS
7219     FuncInfoDsc*   compFuncInfos;
7220     unsigned short compCurrFuncIdx;
7221     unsigned short compFuncInfoCount;
7222
7223     unsigned short compFuncCount()
7224     {
7225         assert(fgFuncletsCreated);
7226         return compFuncInfoCount;
7227     }
7228
7229 #else // !FEATURE_EH_FUNCLETS
7230
7231     // This is a no-op when there are no funclets!
7232     void genUpdateCurrentFunclet(BasicBlock* block)
7233     {
7234         return;
7235     }
7236
7237     FuncInfoDsc compFuncInfoRoot;
7238
7239     static const unsigned compCurrFuncIdx = 0;
7240
7241     unsigned short compFuncCount()
7242     {
7243         return 1;
7244     }
7245
7246 #endif // !FEATURE_EH_FUNCLETS
7247
7248     FuncInfoDsc* funCurrentFunc();
7249     void funSetCurrentFunc(unsigned funcIdx);
7250     FuncInfoDsc* funGetFunc(unsigned funcIdx);
7251     unsigned int funGetFuncIdx(BasicBlock* block);
7252
7253     // LIVENESS
7254
7255     VARSET_TP compCurLife;     // current live variables
7256     GenTree*  compCurLifeTree; // node after which compCurLife has been computed
7257
7258     template <bool ForCodeGen>
7259     void compChangeLife(VARSET_VALARG_TP newLife);
7260
7261     void genChangeLife(VARSET_VALARG_TP newLife)
7262     {
7263         compChangeLife</*ForCodeGen*/ true>(newLife);
7264     }
7265
7266     template <bool ForCodeGen>
7267     void compUpdateLife(GenTree* tree);
7268
7269     // Updates "compCurLife" to its state after evaluate of "true".  If "pLastUseVars" is
7270     // non-null, sets "*pLastUseVars" to the set of tracked variables for which "tree" was a last
7271     // use.  (Can be more than one var in the case of dependently promoted struct vars.)
7272     template <bool ForCodeGen>
7273     void compUpdateLifeVar(GenTree* tree, VARSET_TP* pLastUseVars = nullptr);
7274
7275     template <bool ForCodeGen>
7276     inline void compUpdateLife(VARSET_VALARG_TP newLife);
7277
7278     // Gets a register mask that represent the kill set for a helper call since
7279     // not all JIT Helper calls follow the standard ABI on the target architecture.
7280     regMaskTP compHelperCallKillSet(CorInfoHelpFunc helper);
7281
7282     // Gets a register mask that represent the kill set for a NoGC helper call.
7283     regMaskTP compNoGCHelperCallKillSet(CorInfoHelpFunc helper);
7284
7285 #ifdef _TARGET_ARM_
7286     // Requires that "varDsc" be a promoted struct local variable being passed as an argument, beginning at
7287     // "firstArgRegNum", which is assumed to have already been aligned to the register alignment restriction of the
7288     // struct type. Adds bits to "*pArgSkippedRegMask" for any argument registers *not* used in passing "varDsc" --
7289     // i.e., internal "holes" caused by internal alignment constraints.  For example, if the struct contained an int and
7290     // a double, and we at R0 (on ARM), then R1 would be skipped, and the bit for R1 would be added to the mask.
7291     void fgAddSkippedRegsInPromotedStructArg(LclVarDsc* varDsc, unsigned firstArgRegNum, regMaskTP* pArgSkippedRegMask);
7292 #endif // _TARGET_ARM_
7293
7294     // 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
7295     // node, else NULL.
7296     static GenTree* fgIsIndirOfAddrOfLocal(GenTree* tree);
7297
7298     // This is indexed by GT_OBJ nodes that are address of promoted struct variables, which
7299     // have been annotated with the GTF_VAR_DEATH flag.  If such a node is *not* mapped in this
7300     // table, one may assume that all the (tracked) field vars die at this point.  Otherwise,
7301     // the node maps to a pointer to a VARSET_TP, containing set bits for each of the tracked field
7302     // vars of the promoted struct local that go dead at the given node (the set bits are the bits
7303     // for the tracked var indices of the field vars, as in a live var set).
7304     NodeToVarsetPtrMap* m_promotedStructDeathVars;
7305
7306     NodeToVarsetPtrMap* GetPromotedStructDeathVars()
7307     {
7308         if (m_promotedStructDeathVars == nullptr)
7309         {
7310             m_promotedStructDeathVars = new (getAllocator()) NodeToVarsetPtrMap(getAllocator());
7311         }
7312         return m_promotedStructDeathVars;
7313     }
7314
7315 /*
7316 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7317 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7318 XX                                                                           XX
7319 XX                           UnwindInfo                                      XX
7320 XX                                                                           XX
7321 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7322 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7323 */
7324
7325 #if !defined(__GNUC__)
7326 #pragma region Unwind information
7327 #endif
7328
7329 public:
7330     //
7331     // Infrastructure functions: start/stop/reserve/emit.
7332     //
7333
7334     void unwindBegProlog();
7335     void unwindEndProlog();
7336     void unwindBegEpilog();
7337     void unwindEndEpilog();
7338     void unwindReserve();
7339     void unwindEmit(void* pHotCode, void* pColdCode);
7340
7341     //
7342     // Specific unwind information functions: called by code generation to indicate a particular
7343     // prolog or epilog unwindable instruction has been generated.
7344     //
7345
7346     void unwindPush(regNumber reg);
7347     void unwindAllocStack(unsigned size);
7348     void unwindSetFrameReg(regNumber reg, unsigned offset);
7349     void unwindSaveReg(regNumber reg, unsigned offset);
7350
7351 #if defined(_TARGET_ARM_)
7352     void unwindPushMaskInt(regMaskTP mask);
7353     void unwindPushMaskFloat(regMaskTP mask);
7354     void unwindPopMaskInt(regMaskTP mask);
7355     void unwindPopMaskFloat(regMaskTP mask);
7356     void unwindBranch16();                    // The epilog terminates with a 16-bit branch (e.g., "bx lr")
7357     void unwindNop(unsigned codeSizeInBytes); // Generate unwind NOP code. 'codeSizeInBytes' is 2 or 4 bytes. Only
7358                                               // called via unwindPadding().
7359     void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7360                           // instruction and the current location.
7361 #endif                    // _TARGET_ARM_
7362
7363 #if defined(_TARGET_ARM64_)
7364     void unwindNop();
7365     void unwindPadding(); // Generate a sequence of unwind NOP codes representing instructions between the last
7366                           // instruction and the current location.
7367     void unwindSaveReg(regNumber reg, int offset);                                // str reg, [sp, #offset]
7368     void unwindSaveRegPreindexed(regNumber reg, int offset);                      // str reg, [sp, #offset]!
7369     void unwindSaveRegPair(regNumber reg1, regNumber reg2, int offset);           // stp reg1, reg2, [sp, #offset]
7370     void unwindSaveRegPairPreindexed(regNumber reg1, regNumber reg2, int offset); // stp reg1, reg2, [sp, #offset]!
7371     void unwindSaveNext();                                                        // unwind code: save_next
7372     void unwindReturn(regNumber reg);                                             // ret lr
7373 #endif                                                                            // defined(_TARGET_ARM64_)
7374
7375     //
7376     // Private "helper" functions for the unwind implementation.
7377     //
7378
7379 private:
7380 #if FEATURE_EH_FUNCLETS
7381     void unwindGetFuncLocations(FuncInfoDsc*             func,
7382                                 bool                     getHotSectionData,
7383                                 /* OUT */ emitLocation** ppStartLoc,
7384                                 /* OUT */ emitLocation** ppEndLoc);
7385 #endif // FEATURE_EH_FUNCLETS
7386
7387     void unwindReserveFunc(FuncInfoDsc* func);
7388     void unwindEmitFunc(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7389
7390 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && FEATURE_EH_FUNCLETS)
7391
7392     void unwindReserveFuncHelper(FuncInfoDsc* func, bool isHotCode);
7393     void unwindEmitFuncHelper(FuncInfoDsc* func, void* pHotCode, void* pColdCode, bool isHotCode);
7394
7395 #endif // _TARGET_AMD64_ || (_TARGET_X86_ && FEATURE_EH_FUNCLETS)
7396
7397     UNATIVE_OFFSET unwindGetCurrentOffset(FuncInfoDsc* func);
7398
7399 #if defined(_TARGET_AMD64_)
7400
7401     void unwindBegPrologWindows();
7402     void unwindPushWindows(regNumber reg);
7403     void unwindAllocStackWindows(unsigned size);
7404     void unwindSetFrameRegWindows(regNumber reg, unsigned offset);
7405     void unwindSaveRegWindows(regNumber reg, unsigned offset);
7406
7407 #ifdef UNIX_AMD64_ABI
7408     void unwindSaveRegCFI(regNumber reg, unsigned offset);
7409 #endif // UNIX_AMD64_ABI
7410 #elif defined(_TARGET_ARM_)
7411
7412     void unwindPushPopMaskInt(regMaskTP mask, bool useOpsize16);
7413     void unwindPushPopMaskFloat(regMaskTP mask);
7414     void unwindSplit(FuncInfoDsc* func);
7415
7416 #endif // _TARGET_ARM_
7417
7418 #if defined(_TARGET_UNIX_)
7419     int mapRegNumToDwarfReg(regNumber reg);
7420     void createCfiCode(FuncInfoDsc* func, UCHAR codeOffset, UCHAR opcode, USHORT dwarfReg, INT offset = 0);
7421     void unwindPushPopCFI(regNumber reg);
7422     void unwindBegPrologCFI();
7423     void unwindPushPopMaskCFI(regMaskTP regMask, bool isFloat);
7424     void unwindAllocStackCFI(unsigned size);
7425     void unwindSetFrameRegCFI(regNumber reg, unsigned offset);
7426     void unwindEmitFuncCFI(FuncInfoDsc* func, void* pHotCode, void* pColdCode);
7427 #ifdef DEBUG
7428     void DumpCfiInfo(bool                  isHotCode,
7429                      UNATIVE_OFFSET        startOffset,
7430                      UNATIVE_OFFSET        endOffset,
7431                      DWORD                 cfiCodeBytes,
7432                      const CFI_CODE* const pCfiCode);
7433 #endif
7434
7435 #endif // _TARGET_UNIX_
7436
7437 #if !defined(__GNUC__)
7438 #pragma endregion // Note: region is NOT under !defined(__GNUC__)
7439 #endif
7440
7441     /*
7442     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7443     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7444     XX                                                                           XX
7445     XX                               SIMD                                        XX
7446     XX                                                                           XX
7447     XX   Info about SIMD types, methods and the SIMD assembly (i.e. the assembly XX
7448     XX   that contains the distinguished, well-known SIMD type definitions).     XX
7449     XX                                                                           XX
7450     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7451     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
7452     */
7453
7454     // Get highest available level for SIMD codegen
7455     SIMDLevel getSIMDSupportLevel()
7456     {
7457 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7458         if (compSupports(InstructionSet_AVX2))
7459         {
7460             return SIMD_AVX2_Supported;
7461         }
7462
7463         // SIMD_SSE4_Supported actually requires all of SSE3, SSSE3, SSE4.1, and SSE4.2
7464         // to be supported. We can only enable it if all four are enabled in the compiler
7465         if (compSupports(InstructionSet_SSE42) && compSupports(InstructionSet_SSE41) &&
7466             compSupports(InstructionSet_SSSE3) && compSupports(InstructionSet_SSE3))
7467         {
7468             return SIMD_SSE4_Supported;
7469         }
7470
7471         // min bar is SSE2
7472         assert(canUseSSE2());
7473         return SIMD_SSE2_Supported;
7474 #else
7475         assert(!"Available instruction set(s) for SIMD codegen is not defined for target arch");
7476         unreached();
7477         return SIMD_Not_Supported;
7478 #endif
7479     }
7480
7481 #ifdef FEATURE_SIMD
7482
7483     // Should we support SIMD intrinsics?
7484     bool featureSIMD;
7485
7486     // Have we identified any SIMD types?
7487     // This is currently used by struct promotion to avoid getting type information for a struct
7488     // field to see if it is a SIMD type, if we haven't seen any SIMD types or operations in
7489     // the method.
7490     bool _usesSIMDTypes;
7491     bool usesSIMDTypes()
7492     {
7493         return _usesSIMDTypes;
7494     }
7495     void setUsesSIMDTypes(bool value)
7496     {
7497         _usesSIMDTypes = value;
7498     }
7499
7500     // This is a temp lclVar allocated on the stack as TYP_SIMD.  It is used to implement intrinsics
7501     // that require indexed access to the individual fields of the vector, which is not well supported
7502     // by the hardware.  It is allocated when/if such situations are encountered during Lowering.
7503     unsigned lvaSIMDInitTempVarNum;
7504
7505     // SIMD Types
7506     CORINFO_CLASS_HANDLE SIMDFloatHandle;
7507     CORINFO_CLASS_HANDLE SIMDDoubleHandle;
7508     CORINFO_CLASS_HANDLE SIMDIntHandle;
7509     CORINFO_CLASS_HANDLE SIMDUShortHandle;
7510     CORINFO_CLASS_HANDLE SIMDUByteHandle;
7511     CORINFO_CLASS_HANDLE SIMDShortHandle;
7512     CORINFO_CLASS_HANDLE SIMDByteHandle;
7513     CORINFO_CLASS_HANDLE SIMDLongHandle;
7514     CORINFO_CLASS_HANDLE SIMDUIntHandle;
7515     CORINFO_CLASS_HANDLE SIMDULongHandle;
7516     CORINFO_CLASS_HANDLE SIMDVector2Handle;
7517     CORINFO_CLASS_HANDLE SIMDVector3Handle;
7518     CORINFO_CLASS_HANDLE SIMDVector4Handle;
7519     CORINFO_CLASS_HANDLE SIMDVectorHandle;
7520
7521 #ifdef FEATURE_HW_INTRINSICS
7522 #if defined(_TARGET_ARM64_)
7523     CORINFO_CLASS_HANDLE Vector64FloatHandle;
7524     CORINFO_CLASS_HANDLE Vector64UIntHandle;
7525     CORINFO_CLASS_HANDLE Vector64UShortHandle;
7526     CORINFO_CLASS_HANDLE Vector64UByteHandle;
7527     CORINFO_CLASS_HANDLE Vector64ShortHandle;
7528     CORINFO_CLASS_HANDLE Vector64ByteHandle;
7529     CORINFO_CLASS_HANDLE Vector64IntHandle;
7530 #endif // defined(_TARGET_ARM64_)
7531     CORINFO_CLASS_HANDLE Vector128FloatHandle;
7532     CORINFO_CLASS_HANDLE Vector128DoubleHandle;
7533     CORINFO_CLASS_HANDLE Vector128IntHandle;
7534     CORINFO_CLASS_HANDLE Vector128UShortHandle;
7535     CORINFO_CLASS_HANDLE Vector128UByteHandle;
7536     CORINFO_CLASS_HANDLE Vector128ShortHandle;
7537     CORINFO_CLASS_HANDLE Vector128ByteHandle;
7538     CORINFO_CLASS_HANDLE Vector128LongHandle;
7539     CORINFO_CLASS_HANDLE Vector128UIntHandle;
7540     CORINFO_CLASS_HANDLE Vector128ULongHandle;
7541 #if defined(_TARGET_XARCH_)
7542     CORINFO_CLASS_HANDLE Vector256FloatHandle;
7543     CORINFO_CLASS_HANDLE Vector256DoubleHandle;
7544     CORINFO_CLASS_HANDLE Vector256IntHandle;
7545     CORINFO_CLASS_HANDLE Vector256UShortHandle;
7546     CORINFO_CLASS_HANDLE Vector256UByteHandle;
7547     CORINFO_CLASS_HANDLE Vector256ShortHandle;
7548     CORINFO_CLASS_HANDLE Vector256ByteHandle;
7549     CORINFO_CLASS_HANDLE Vector256LongHandle;
7550     CORINFO_CLASS_HANDLE Vector256UIntHandle;
7551     CORINFO_CLASS_HANDLE Vector256ULongHandle;
7552 #endif // defined(_TARGET_XARCH_)
7553 #endif // FEATURE_HW_INTRINSICS
7554
7555     // Get the handle for a SIMD type.
7556     CORINFO_CLASS_HANDLE gtGetStructHandleForSIMD(var_types simdType, var_types simdBaseType)
7557     {
7558         if (simdBaseType == TYP_FLOAT)
7559         {
7560             switch (simdType)
7561             {
7562                 case TYP_SIMD8:
7563                     return SIMDVector2Handle;
7564                 case TYP_SIMD12:
7565                     return SIMDVector3Handle;
7566                 case TYP_SIMD16:
7567                     if ((getSIMDVectorType() == TYP_SIMD32) || (SIMDVector4Handle != NO_CLASS_HANDLE))
7568                     {
7569                         return SIMDVector4Handle;
7570                     }
7571                     break;
7572                 case TYP_SIMD32:
7573                     break;
7574                 default:
7575                     unreached();
7576             }
7577         }
7578         assert(simdType == getSIMDVectorType());
7579         switch (simdBaseType)
7580         {
7581             case TYP_FLOAT:
7582                 return SIMDFloatHandle;
7583             case TYP_DOUBLE:
7584                 return SIMDDoubleHandle;
7585             case TYP_INT:
7586                 return SIMDIntHandle;
7587             case TYP_USHORT:
7588                 return SIMDUShortHandle;
7589             case TYP_UBYTE:
7590                 return SIMDUByteHandle;
7591             case TYP_SHORT:
7592                 return SIMDShortHandle;
7593             case TYP_BYTE:
7594                 return SIMDByteHandle;
7595             case TYP_LONG:
7596                 return SIMDLongHandle;
7597             case TYP_UINT:
7598                 return SIMDUIntHandle;
7599             case TYP_ULONG:
7600                 return SIMDULongHandle;
7601             default:
7602                 assert(!"Didn't find a class handle for simdType");
7603         }
7604         return NO_CLASS_HANDLE;
7605     }
7606
7607     // SIMD Methods
7608     CORINFO_METHOD_HANDLE SIMDVectorFloat_set_Item;
7609     CORINFO_METHOD_HANDLE SIMDVectorFloat_get_Length;
7610     CORINFO_METHOD_HANDLE SIMDVectorFloat_op_Addition;
7611
7612     // Returns true if the tree corresponds to a TYP_SIMD lcl var.
7613     // Note that both SIMD vector args and locals are mared as lvSIMDType = true, but
7614     // type of an arg node is TYP_BYREF and a local node is TYP_SIMD or TYP_STRUCT.
7615     bool isSIMDTypeLocal(GenTree* tree)
7616     {
7617         return tree->OperIsLocal() && lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7618     }
7619
7620     // Returns true if the type of the tree is a byref of TYP_SIMD
7621     bool isAddrOfSIMDType(GenTree* tree)
7622     {
7623         if (tree->TypeGet() == TYP_BYREF || tree->TypeGet() == TYP_I_IMPL)
7624         {
7625             switch (tree->OperGet())
7626             {
7627                 case GT_ADDR:
7628                     return varTypeIsSIMD(tree->gtGetOp1());
7629
7630                 case GT_LCL_VAR_ADDR:
7631                     return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvSIMDType;
7632
7633                 default:
7634                     return isSIMDTypeLocal(tree);
7635             }
7636         }
7637
7638         return false;
7639     }
7640
7641     static bool isRelOpSIMDIntrinsic(SIMDIntrinsicID intrinsicId)
7642     {
7643         return (intrinsicId == SIMDIntrinsicEqual || intrinsicId == SIMDIntrinsicLessThan ||
7644                 intrinsicId == SIMDIntrinsicLessThanOrEqual || intrinsicId == SIMDIntrinsicGreaterThan ||
7645                 intrinsicId == SIMDIntrinsicGreaterThanOrEqual);
7646     }
7647
7648     // Returns base type of a TYP_SIMD local.
7649     // Returns TYP_UNKNOWN if the local is not TYP_SIMD.
7650     var_types getBaseTypeOfSIMDLocal(GenTree* tree)
7651     {
7652         if (isSIMDTypeLocal(tree))
7653         {
7654             return lvaTable[tree->AsLclVarCommon()->gtLclNum].lvBaseType;
7655         }
7656
7657         return TYP_UNKNOWN;
7658     }
7659
7660     bool isSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7661     {
7662         return info.compCompHnd->isInSIMDModule(clsHnd);
7663     }
7664
7665     bool isIntrinsicType(CORINFO_CLASS_HANDLE clsHnd)
7666     {
7667         return (info.compCompHnd->getClassAttribs(clsHnd) & CORINFO_FLG_INTRINSIC_TYPE) != 0;
7668     }
7669
7670     const char* getClassNameFromMetadata(CORINFO_CLASS_HANDLE cls, const char** namespaceName)
7671     {
7672         return info.compCompHnd->getClassNameFromMetadata(cls, namespaceName);
7673     }
7674
7675     CORINFO_CLASS_HANDLE getTypeInstantiationArgument(CORINFO_CLASS_HANDLE cls, unsigned index)
7676     {
7677         return info.compCompHnd->getTypeInstantiationArgument(cls, index);
7678     }
7679
7680     bool isSIMDClass(typeInfo* pTypeInfo)
7681     {
7682         return pTypeInfo->IsStruct() && isSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7683     }
7684
7685     bool isHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7686     {
7687 #ifdef FEATURE_HW_INTRINSICS
7688         if (isIntrinsicType(clsHnd))
7689         {
7690             const char* namespaceName = nullptr;
7691             (void)getClassNameFromMetadata(clsHnd, &namespaceName);
7692             return strcmp(namespaceName, "System.Runtime.Intrinsics") == 0;
7693         }
7694 #endif // FEATURE_HW_INTRINSICS
7695         return false;
7696     }
7697
7698     bool isHWSIMDClass(typeInfo* pTypeInfo)
7699     {
7700 #ifdef FEATURE_HW_INTRINSICS
7701         return pTypeInfo->IsStruct() && isHWSIMDClass(pTypeInfo->GetClassHandleForValueClass());
7702 #else
7703         return false;
7704 #endif
7705     }
7706
7707     bool isSIMDorHWSIMDClass(CORINFO_CLASS_HANDLE clsHnd)
7708     {
7709         return isSIMDClass(clsHnd) || isHWSIMDClass(clsHnd);
7710     }
7711
7712     bool isSIMDorHWSIMDClass(typeInfo* pTypeInfo)
7713     {
7714         return isSIMDClass(pTypeInfo) || isHWSIMDClass(pTypeInfo);
7715     }
7716
7717     // Get the base (element) type and size in bytes for a SIMD type. Returns TYP_UNKNOWN
7718     // if it is not a SIMD type or is an unsupported base type.
7719     var_types getBaseTypeAndSizeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd, unsigned* sizeBytes = nullptr);
7720
7721     var_types getBaseTypeOfSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7722     {
7723         return getBaseTypeAndSizeOfSIMDType(typeHnd, nullptr);
7724     }
7725
7726     // Get SIMD Intrinsic info given the method handle.
7727     // Also sets typeHnd, argCount, baseType and sizeBytes out params.
7728     const SIMDIntrinsicInfo* getSIMDIntrinsicInfo(CORINFO_CLASS_HANDLE* typeHnd,
7729                                                   CORINFO_METHOD_HANDLE methodHnd,
7730                                                   CORINFO_SIG_INFO*     sig,
7731                                                   bool                  isNewObj,
7732                                                   unsigned*             argCount,
7733                                                   var_types*            baseType,
7734                                                   unsigned*             sizeBytes);
7735
7736     // Pops and returns GenTree node from importers type stack.
7737     // Normalizes TYP_STRUCT value in case of GT_CALL, GT_RET_EXPR and arg nodes.
7738     GenTree* impSIMDPopStack(var_types type, bool expectAddr = false);
7739
7740     // Create a GT_SIMD tree for a Get property of SIMD vector with a fixed index.
7741     GenTreeSIMD* impSIMDGetFixed(var_types simdType, var_types baseType, unsigned simdSize, int index);
7742
7743     // Creates a GT_SIMD tree for Select operation
7744     GenTree* impSIMDSelect(CORINFO_CLASS_HANDLE typeHnd,
7745                            var_types            baseType,
7746                            unsigned             simdVectorSize,
7747                            GenTree*             op1,
7748                            GenTree*             op2,
7749                            GenTree*             op3);
7750
7751     // Creates a GT_SIMD tree for Min/Max operation
7752     GenTree* impSIMDMinMax(SIMDIntrinsicID      intrinsicId,
7753                            CORINFO_CLASS_HANDLE typeHnd,
7754                            var_types            baseType,
7755                            unsigned             simdVectorSize,
7756                            GenTree*             op1,
7757                            GenTree*             op2);
7758
7759     // Transforms operands and returns the SIMD intrinsic to be applied on
7760     // transformed operands to obtain given relop result.
7761     SIMDIntrinsicID impSIMDRelOp(SIMDIntrinsicID      relOpIntrinsicId,
7762                                  CORINFO_CLASS_HANDLE typeHnd,
7763                                  unsigned             simdVectorSize,
7764                                  var_types*           baseType,
7765                                  GenTree**            op1,
7766                                  GenTree**            op2);
7767
7768     // Creates a GT_SIMD tree for Abs intrinsic.
7769     GenTree* impSIMDAbs(CORINFO_CLASS_HANDLE typeHnd, var_types baseType, unsigned simdVectorSize, GenTree* op1);
7770
7771 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7772     // Transforms operands and returns the SIMD intrinsic to be applied on
7773     // transformed operands to obtain == comparison result.
7774     SIMDIntrinsicID impSIMDLongRelOpEqual(CORINFO_CLASS_HANDLE typeHnd,
7775                                           unsigned             simdVectorSize,
7776                                           GenTree**            op1,
7777                                           GenTree**            op2);
7778
7779     // Transforms operands and returns the SIMD intrinsic to be applied on
7780     // transformed operands to obtain > comparison result.
7781     SIMDIntrinsicID impSIMDLongRelOpGreaterThan(CORINFO_CLASS_HANDLE typeHnd,
7782                                                 unsigned             simdVectorSize,
7783                                                 GenTree**            op1,
7784                                                 GenTree**            op2);
7785
7786     // Transforms operands and returns the SIMD intrinsic to be applied on
7787     // transformed operands to obtain >= comparison result.
7788     SIMDIntrinsicID impSIMDLongRelOpGreaterThanOrEqual(CORINFO_CLASS_HANDLE typeHnd,
7789                                                        unsigned             simdVectorSize,
7790                                                        GenTree**            op1,
7791                                                        GenTree**            op2);
7792
7793     // Transforms operands and returns the SIMD intrinsic to be applied on
7794     // transformed operands to obtain >= comparison result in case of int32
7795     // and small int base type vectors.
7796     SIMDIntrinsicID impSIMDIntegralRelOpGreaterThanOrEqual(
7797         CORINFO_CLASS_HANDLE typeHnd, unsigned simdVectorSize, var_types baseType, GenTree** op1, GenTree** op2);
7798 #endif // defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7799
7800     void setLclRelatedToSIMDIntrinsic(GenTree* tree);
7801     bool areFieldsContiguous(GenTree* op1, GenTree* op2);
7802     bool areArrayElementsContiguous(GenTree* op1, GenTree* op2);
7803     bool areArgumentsContiguous(GenTree* op1, GenTree* op2);
7804     GenTree* createAddressNodeForSIMDInit(GenTree* tree, unsigned simdSize);
7805
7806     // check methodHnd to see if it is a SIMD method that is expanded as an intrinsic in the JIT.
7807     GenTree* impSIMDIntrinsic(OPCODE                opcode,
7808                               GenTree*              newobjThis,
7809                               CORINFO_CLASS_HANDLE  clsHnd,
7810                               CORINFO_METHOD_HANDLE method,
7811                               CORINFO_SIG_INFO*     sig,
7812                               int                   memberRef);
7813
7814     GenTree* getOp1ForConstructor(OPCODE opcode, GenTree* newobjThis, CORINFO_CLASS_HANDLE clsHnd);
7815
7816     // Whether SIMD vector occupies part of SIMD register.
7817     // SSE2: vector2f/3f are considered sub register SIMD types.
7818     // AVX: vector2f, 3f and 4f are all considered sub register SIMD types.
7819     bool isSubRegisterSIMDType(CORINFO_CLASS_HANDLE typeHnd)
7820     {
7821         unsigned  sizeBytes = 0;
7822         var_types baseType  = getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7823         return (baseType == TYP_FLOAT) && (sizeBytes < getSIMDVectorRegisterByteLength());
7824     }
7825
7826     bool isSubRegisterSIMDType(GenTreeSIMD* simdNode)
7827     {
7828         return (simdNode->gtSIMDSize < getSIMDVectorRegisterByteLength());
7829     }
7830
7831     // Get the type for the hardware SIMD vector.
7832     // This is the maximum SIMD type supported for this target.
7833     var_types getSIMDVectorType()
7834     {
7835 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7836         if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7837         {
7838             return TYP_SIMD32;
7839         }
7840         else
7841         {
7842             assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7843             return TYP_SIMD16;
7844         }
7845 #elif defined(_TARGET_ARM64_)
7846         return TYP_SIMD16;
7847 #else
7848         assert(!"getSIMDVectorType() unimplemented on target arch");
7849         unreached();
7850 #endif
7851     }
7852
7853     // Get the size of the SIMD type in bytes
7854     int getSIMDTypeSizeInBytes(CORINFO_CLASS_HANDLE typeHnd)
7855     {
7856         unsigned sizeBytes = 0;
7857         (void)getBaseTypeAndSizeOfSIMDType(typeHnd, &sizeBytes);
7858         return sizeBytes;
7859     }
7860
7861     // Get the the number of elements of basetype of SIMD vector given by its size and baseType
7862     static int getSIMDVectorLength(unsigned simdSize, var_types baseType);
7863
7864     // Get the the number of elements of basetype of SIMD vector given by its type handle
7865     int getSIMDVectorLength(CORINFO_CLASS_HANDLE typeHnd);
7866
7867     // Get preferred alignment of SIMD type.
7868     int getSIMDTypeAlignment(var_types simdType);
7869
7870     // Get the number of bytes in a System.Numeric.Vector<T> for the current compilation.
7871     // Note - cannot be used for System.Runtime.Intrinsic
7872     unsigned getSIMDVectorRegisterByteLength()
7873     {
7874 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
7875         if (getSIMDSupportLevel() == SIMD_AVX2_Supported)
7876         {
7877             return YMM_REGSIZE_BYTES;
7878         }
7879         else
7880         {
7881             assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7882             return XMM_REGSIZE_BYTES;
7883         }
7884 #elif defined(_TARGET_ARM64_)
7885         return FP_REGSIZE_BYTES;
7886 #else
7887         assert(!"getSIMDVectorRegisterByteLength() unimplemented on target arch");
7888         unreached();
7889 #endif
7890     }
7891
7892     // The minimum and maximum possible number of bytes in a SIMD vector.
7893
7894     // maxSIMDStructBytes
7895     // The minimum SIMD size supported by System.Numeric.Vectors or System.Runtime.Intrinsic
7896     // SSE:  16-byte Vector<T> and Vector128<T>
7897     // AVX:  32-byte Vector256<T> (Vector<T> is 16-byte)
7898     // AVX2: 32-byte Vector<T> and Vector256<T>
7899     unsigned int maxSIMDStructBytes()
7900     {
7901 #if defined(FEATURE_HW_INTRINSICS) && defined(_TARGET_XARCH_)
7902         if (compSupports(InstructionSet_AVX))
7903         {
7904             return YMM_REGSIZE_BYTES;
7905         }
7906         else
7907         {
7908             assert(getSIMDSupportLevel() >= SIMD_SSE2_Supported);
7909             return XMM_REGSIZE_BYTES;
7910         }
7911 #else
7912         return getSIMDVectorRegisterByteLength();
7913 #endif
7914     }
7915     unsigned int minSIMDStructBytes()
7916     {
7917         return emitTypeSize(TYP_SIMD8);
7918     }
7919
7920     // Returns the codegen type for a given SIMD size.
7921     var_types getSIMDTypeForSize(unsigned size)
7922     {
7923         var_types simdType = TYP_UNDEF;
7924         if (size == 8)
7925         {
7926             simdType = TYP_SIMD8;
7927         }
7928         else if (size == 12)
7929         {
7930             simdType = TYP_SIMD12;
7931         }
7932         else if (size == 16)
7933         {
7934             simdType = TYP_SIMD16;
7935         }
7936         else if (size == 32)
7937         {
7938             simdType = TYP_SIMD32;
7939         }
7940         else
7941         {
7942             noway_assert(!"Unexpected size for SIMD type");
7943         }
7944         return simdType;
7945     }
7946
7947     unsigned getSIMDInitTempVarNum()
7948     {
7949         if (lvaSIMDInitTempVarNum == BAD_VAR_NUM)
7950         {
7951             lvaSIMDInitTempVarNum                  = lvaGrabTempWithImplicitUse(false DEBUGARG("SIMDInitTempVar"));
7952             lvaTable[lvaSIMDInitTempVarNum].lvType = getSIMDVectorType();
7953         }
7954         return lvaSIMDInitTempVarNum;
7955     }
7956
7957 #endif // FEATURE_SIMD
7958
7959 public:
7960     //------------------------------------------------------------------------
7961     // largestEnregisterableStruct: The size in bytes of the largest struct that can be enregistered.
7962     //
7963     // Notes: It is not guaranteed that the struct of this size or smaller WILL be a
7964     //        candidate for enregistration.
7965
7966     unsigned largestEnregisterableStructSize()
7967     {
7968 #ifdef FEATURE_SIMD
7969         unsigned vectorRegSize = getSIMDVectorRegisterByteLength();
7970         if (vectorRegSize > TARGET_POINTER_SIZE)
7971         {
7972             return vectorRegSize;
7973         }
7974         else
7975 #endif // FEATURE_SIMD
7976         {
7977             return TARGET_POINTER_SIZE;
7978         }
7979     }
7980
7981 private:
7982     // These routines need not be enclosed under FEATURE_SIMD since lvIsSIMDType()
7983     // is defined for both FEATURE_SIMD and !FEATURE_SIMD apropriately. The use
7984     // of this routines also avoids the need of #ifdef FEATURE_SIMD specific code.
7985
7986     // Is this var is of type simd struct?
7987     bool lclVarIsSIMDType(unsigned varNum)
7988     {
7989         LclVarDsc* varDsc = lvaTable + varNum;
7990         return varDsc->lvIsSIMDType();
7991     }
7992
7993     // Is this Local node a SIMD local?
7994     bool lclVarIsSIMDType(GenTreeLclVarCommon* lclVarTree)
7995     {
7996         return lclVarIsSIMDType(lclVarTree->gtLclNum);
7997     }
7998
7999     // Returns true if the TYP_SIMD locals on stack are aligned at their
8000     // preferred byte boundary specified by getSIMDTypeAlignment().
8001     //
8002     // As per the Intel manual, the preferred alignment for AVX vectors is 32-bytes. On Amd64,
8003     // RSP/EBP is aligned at 16-bytes, therefore to align SIMD types at 32-bytes we need even
8004     // RSP/EBP to be 32-byte aligned. It is not clear whether additional stack space used in
8005     // aligning stack is worth the benefit and for now will use 16-byte alignment for AVX
8006     // 256-bit vectors with unaligned load/stores to/from memory. On x86, the stack frame
8007     // is aligned to 4 bytes. We need to extend existing support for double (8-byte) alignment
8008     // to 16 or 32 byte alignment for frames with local SIMD vars, if that is determined to be
8009     // profitable.
8010     //
8011     bool isSIMDTypeLocalAligned(unsigned varNum)
8012     {
8013 #if defined(FEATURE_SIMD) && ALIGN_SIMD_TYPES
8014         if (lclVarIsSIMDType(varNum) && lvaTable[varNum].lvType != TYP_BYREF)
8015         {
8016             bool ebpBased;
8017             int  off = lvaFrameAddress(varNum, &ebpBased);
8018             // TODO-Cleanup: Can't this use the lvExactSize on the varDsc?
8019             int  alignment = getSIMDTypeAlignment(lvaTable[varNum].lvType);
8020             bool isAligned = (alignment <= STACK_ALIGN) && ((off % alignment) == 0);
8021             return isAligned;
8022         }
8023 #endif // FEATURE_SIMD
8024
8025         return false;
8026     }
8027
8028     // Whether SSE and SSE2 is available
8029     bool canUseSSE2() const
8030     {
8031 #ifdef _TARGET_XARCH_
8032         return opts.compCanUseSSE2;
8033 #else
8034         return false;
8035 #endif
8036     }
8037
8038     bool compSupports(InstructionSet isa) const
8039     {
8040 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8041         return (opts.compSupportsISA & (1ULL << isa)) != 0;
8042 #else
8043         return false;
8044 #endif
8045     }
8046
8047     bool canUseVexEncoding() const
8048     {
8049 #ifdef _TARGET_XARCH_
8050         return compSupports(InstructionSet_AVX);
8051 #else
8052         return false;
8053 #endif
8054     }
8055
8056     /*
8057     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8058     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8059     XX                                                                           XX
8060     XX                           Compiler                                        XX
8061     XX                                                                           XX
8062     XX   Generic info about the compilation and the method being compiled.       XX
8063     XX   It is responsible for driving the other phases.                         XX
8064     XX   It is also responsible for all the memory management.                   XX
8065     XX                                                                           XX
8066     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8067     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
8068     */
8069
8070 public:
8071     Compiler* InlineeCompiler; // The Compiler instance for the inlinee
8072
8073     InlineResult* compInlineResult; // The result of importing the inlinee method.
8074
8075     bool compDoAggressiveInlining; // If true, mark every method as CORINFO_FLG_FORCEINLINE
8076     bool compJmpOpUsed;            // Does the method do a JMP
8077     bool compLongUsed;             // Does the method use TYP_LONG
8078     bool compFloatingPointUsed;    // Does the method use TYP_FLOAT or TYP_DOUBLE
8079     bool compTailCallUsed;         // Does the method do a tailcall
8080     bool compLocallocUsed;         // Does the method use localloc.
8081     bool compLocallocOptimized;    // Does the method have an optimized localloc
8082     bool compQmarkUsed;            // Does the method use GT_QMARK/GT_COLON
8083     bool compQmarkRationalized;    // Is it allowed to use a GT_QMARK/GT_COLON node.
8084     bool compUnsafeCastUsed;       // Does the method use LDIND/STIND to cast between scalar/refernce types
8085
8086 // NOTE: These values are only reliable after
8087 //       the importing is completely finished.
8088
8089 #ifdef LEGACY_BACKEND
8090     JitExpandArrayStack<GenTree*>* compQMarks; // The set of QMark nodes created in the current compilation, so
8091                                                // we can iterate over these efficiently.
8092 #endif
8093
8094 #if CPU_USES_BLOCK_MOVE
8095     bool compBlkOpUsed; // Does the method do a COPYBLK or INITBLK
8096 #endif
8097
8098 #ifdef DEBUG
8099     // State information - which phases have completed?
8100     // These are kept together for easy discoverability
8101
8102     bool    bRangeAllowStress;
8103     bool    compCodeGenDone;
8104     int64_t compNumStatementLinksTraversed; // # of links traversed while doing debug checks
8105     bool    fgNormalizeEHDone;              // Has the flowgraph EH normalization phase been done?
8106     size_t  compSizeEstimate;               // The estimated size of the method as per `gtSetEvalOrder`.
8107     size_t  compCycleEstimate;              // The estimated cycle count of the method as per `gtSetEvalOrder`
8108 #endif                                      // DEBUG
8109
8110     bool fgLocalVarLivenessDone; // Note that this one is used outside of debug.
8111     bool fgLocalVarLivenessChanged;
8112 #if STACK_PROBES
8113     bool compStackProbePrologDone;
8114 #endif
8115 #ifndef LEGACY_BACKEND
8116     bool compLSRADone;
8117 #endif // !LEGACY_BACKEND
8118     bool compRationalIRForm;
8119
8120     bool compUsesThrowHelper; // There is a call to a THOROW_HELPER for the compiled method.
8121
8122     bool compGeneratingProlog;
8123     bool compGeneratingEpilog;
8124     bool compNeedsGSSecurityCookie; // There is an unsafe buffer (or localloc) on the stack.
8125                                     // Insert cookie on frame and code to check the cookie, like VC++ -GS.
8126     bool compGSReorderStackLayout;  // There is an unsafe buffer on the stack, reorder locals and make local
8127     // copies of susceptible parameters to avoid buffer overrun attacks through locals/params
8128     bool getNeedsGSSecurityCookie() const
8129     {
8130         return compNeedsGSSecurityCookie;
8131     }
8132     void setNeedsGSSecurityCookie()
8133     {
8134         compNeedsGSSecurityCookie = true;
8135     }
8136
8137     FrameLayoutState lvaDoneFrameLayout; // The highest frame layout state that we've completed. During
8138                                          // frame layout calculations, this is the level we are currently
8139                                          // computing.
8140
8141     //---------------------------- JITing options -----------------------------
8142
8143     enum codeOptimize
8144     {
8145         BLENDED_CODE,
8146         SMALL_CODE,
8147         FAST_CODE,
8148
8149         COUNT_OPT_CODE
8150     };
8151
8152     struct Options
8153     {
8154         JitFlags* jitFlags;  // all flags passed from the EE
8155         unsigned  compFlags; // method attributes
8156
8157         codeOptimize compCodeOpt; // what type of code optimizations
8158
8159         bool compUseFCOMI;
8160         bool compUseCMOV;
8161 #ifdef _TARGET_XARCH_
8162         bool compCanUseSSE2; // Allow CodeGen to use "movq XMM" instructions
8163 #endif                       // _TARGET_XARCH_
8164
8165 #if defined(_TARGET_XARCH_) || defined(_TARGET_ARM64_)
8166         uint64_t compSupportsISA;
8167         void setSupportedISA(InstructionSet isa)
8168         {
8169             compSupportsISA |= 1ULL << isa;
8170         }
8171 #endif
8172
8173 // optimize maximally and/or favor speed over size?
8174
8175 #define DEFAULT_MIN_OPTS_CODE_SIZE 60000
8176 #define DEFAULT_MIN_OPTS_INSTR_COUNT 20000
8177 #define DEFAULT_MIN_OPTS_BB_COUNT 2000
8178 #define DEFAULT_MIN_OPTS_LV_NUM_COUNT 2000
8179 #define DEFAULT_MIN_OPTS_LV_REF_COUNT 8000
8180
8181 // Maximun number of locals before turning off the inlining
8182 #define MAX_LV_NUM_COUNT_FOR_INLINING 512
8183
8184         bool     compMinOpts;
8185         unsigned instrCount;
8186         unsigned lvRefCount;
8187         bool     compMinOptsIsSet;
8188 #ifdef DEBUG
8189         bool compMinOptsIsUsed;
8190
8191         inline bool MinOpts()
8192         {
8193             assert(compMinOptsIsSet);
8194             compMinOptsIsUsed = true;
8195             return compMinOpts;
8196         }
8197         inline bool IsMinOptsSet()
8198         {
8199             return compMinOptsIsSet;
8200         }
8201 #else  // !DEBUG
8202         inline bool MinOpts()
8203         {
8204             return compMinOpts;
8205         }
8206         inline bool IsMinOptsSet()
8207         {
8208             return compMinOptsIsSet;
8209         }
8210 #endif // !DEBUG
8211         inline void SetMinOpts(bool val)
8212         {
8213             assert(!compMinOptsIsUsed);
8214             assert(!compMinOptsIsSet || (compMinOpts == val));
8215             compMinOpts      = val;
8216             compMinOptsIsSet = true;
8217         }
8218
8219         // true if the CLFLG_* for an optimization is set.
8220         inline bool OptEnabled(unsigned optFlag)
8221         {
8222             return !!(compFlags & optFlag);
8223         }
8224
8225 #ifdef FEATURE_READYTORUN_COMPILER
8226         inline bool IsReadyToRun()
8227         {
8228             return jitFlags->IsSet(JitFlags::JIT_FLAG_READYTORUN);
8229         }
8230 #else
8231         inline bool IsReadyToRun()
8232         {
8233             return false;
8234         }
8235 #endif
8236
8237         // true if we should use the PINVOKE_{BEGIN,END} helpers instead of generating
8238         // PInvoke transitions inline (e.g. when targeting CoreRT).
8239         inline bool ShouldUsePInvokeHelpers()
8240         {
8241             return jitFlags->IsSet(JitFlags::JIT_FLAG_USE_PINVOKE_HELPERS);
8242         }
8243
8244         // true if we should use insert the REVERSE_PINVOKE_{ENTER,EXIT} helpers in the method
8245         // prolog/epilog
8246         inline bool IsReversePInvoke()
8247         {
8248             return jitFlags->IsSet(JitFlags::JIT_FLAG_REVERSE_PINVOKE);
8249         }
8250
8251         // true if we must generate code compatible with JIT32 quirks
8252         inline bool IsJit32Compat()
8253         {
8254 #if defined(_TARGET_X86_)
8255             return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8256 #else
8257             return false;
8258 #endif
8259         }
8260
8261         // true if we must generate code compatible with Jit64 quirks
8262         inline bool IsJit64Compat()
8263         {
8264 #if defined(_TARGET_AMD64_)
8265             return jitFlags->IsSet(JitFlags::JIT_FLAG_DESKTOP_QUIRKS);
8266 #elif !defined(FEATURE_CORECLR)
8267             return true;
8268 #else
8269             return false;
8270 #endif
8271         }
8272
8273         bool compScopeInfo; // Generate the LocalVar info ?
8274         bool compDbgCode;   // Generate debugger-friendly code?
8275         bool compDbgInfo;   // Gather debugging info?
8276         bool compDbgEnC;
8277
8278 #ifdef PROFILING_SUPPORTED
8279         bool compNoPInvokeInlineCB;
8280 #else
8281         static const bool compNoPInvokeInlineCB;
8282 #endif
8283
8284 #ifdef DEBUG
8285         bool compGcChecks;         // Check arguments and return values to ensure they are sane
8286         bool compStackCheckOnRet;  // Check ESP on return to ensure it is correct
8287         bool compStackCheckOnCall; // Check ESP after every call to ensure it is correct
8288
8289 #endif
8290
8291         bool compNeedSecurityCheck; // This flag really means where or not a security object needs
8292                                     // to be allocated on the stack.
8293                                     // It will be set to true in the following cases:
8294                                     //   1. When the method being compiled has a declarative security
8295                                     //        (i.e. when CORINFO_FLG_NOSECURITYWRAP is reset for the current method).
8296                                     //        This is also the case when we inject a prolog and epilog in the method.
8297                                     //   (or)
8298                                     //   2. When the method being compiled has imperative security (i.e. the method
8299                                     //        calls into another method that has CORINFO_FLG_SECURITYCHECK flag set).
8300                                     //   (or)
8301                                     //   3. When opts.compDbgEnC is true. (See also Compiler::compCompile).
8302                                     //
8303         // When this flag is set, jit will allocate a gc-reference local variable (lvaSecurityObject),
8304         // which gets reported as a GC root to stackwalker.
8305         // (See also ICodeManager::GetAddrOfSecurityObject.)
8306
8307         bool compReloc; // Generate relocs for pointers in code, true for all ngen/prejit codegen
8308
8309 #ifdef DEBUG
8310 #if defined(_TARGET_XARCH_) && !defined(LEGACY_BACKEND)
8311         bool compEnablePCRelAddr; // Whether absolute addr be encoded as PC-rel offset by RyuJIT where possible
8312 #endif
8313 #endif // DEBUG
8314
8315 #ifdef UNIX_AMD64_ABI
8316         // This flag  is indicating if there is a need to align the frame.
8317         // On AMD64-Windows, if there are calls, 4 slots for the outgoing ars are allocated, except for
8318         // FastTailCall. This slots makes the frame size non-zero, so alignment logic will be called.
8319         // On AMD64-Unix, there are no such slots. There is a possibility to have calls in the method with frame size of
8320         // 0. The frame alignment logic won't kick in. This flags takes care of the AMD64-Unix case by remembering that
8321         // there are calls and making sure the frame alignment logic is executed.
8322         bool compNeedToAlignFrame;
8323 #endif // UNIX_AMD64_ABI
8324
8325         bool compProcedureSplitting; // Separate cold code from hot code
8326
8327         bool genFPorder; // Preserve FP order (operations are non-commutative)
8328         bool genFPopt;   // Can we do frame-pointer-omission optimization?
8329         bool altJit;     // True if we are an altjit and are compiling this method
8330
8331 #ifdef OPT_CONFIG
8332         bool optRepeat; // Repeat optimizer phases k times
8333 #endif
8334
8335 #ifdef DEBUG
8336         bool compProcedureSplittingEH; // Separate cold code from hot code for functions with EH
8337         bool dspCode;                  // Display native code generated
8338         bool dspEHTable;               // Display the EH table reported to the VM
8339         bool dspInstrs;                // Display the IL instructions intermixed with the native code output
8340         bool dspEmit;                  // Display emitter output
8341         bool dspLines;                 // Display source-code lines intermixed with native code output
8342         bool dmpHex;                   // Display raw bytes in hex of native code output
8343         bool varNames;                 // Display variables names in native code output
8344         bool disAsm;                   // Display native code as it is generated
8345         bool disAsmSpilled;            // Display native code when any register spilling occurs
8346         bool disDiffable;              // Makes the Disassembly code 'diff-able'
8347         bool disAsm2;                  // Display native code after it is generated using external disassembler
8348         bool dspOrder;                 // Display names of each of the methods that we ngen/jit
8349         bool dspUnwind;                // Display the unwind info output
8350         bool dspDiffable;     // Makes the Jit Dump 'diff-able' (currently uses same COMPlus_* flag as disDiffable)
8351         bool compLongAddress; // Force using large pseudo instructions for long address
8352                               // (IF_LARGEJMP/IF_LARGEADR/IF_LARGLDC)
8353         bool dspGCtbls;       // Display the GC tables
8354 #endif
8355
8356 #ifdef LATE_DISASM
8357         bool doLateDisasm; // Run the late disassembler
8358 #endif                     // LATE_DISASM
8359
8360 #if DUMP_GC_TABLES && !defined(DEBUG) && defined(JIT32_GCENCODER)
8361 // Only the JIT32_GCENCODER implements GC dumping in non-DEBUG code.
8362 #pragma message("NOTE: this non-debug build has GC ptr table dumping always enabled!")
8363         static const bool dspGCtbls = true;
8364 #endif
8365
8366         // We need stack probes to guarantee that we won't trigger a stack overflow
8367         // when calling unmanaged code until they get a chance to set up a frame, because
8368         // the EE will have no idea where it is.
8369         //
8370         // We will only be doing this currently for hosted environments. Unfortunately
8371         // we need to take care of stubs, so potentially, we will have to do the probes
8372         // for any call. We have a plan for not needing for stubs though
8373         bool compNeedStackProbes;
8374
8375 #ifdef PROFILING_SUPPORTED
8376         // Whether to emit Enter/Leave/TailCall hooks using a dummy stub (DummyProfilerELTStub()).
8377         // This option helps make the JIT behave as if it is running under a profiler.
8378         bool compJitELTHookEnabled;
8379 #endif // PROFILING_SUPPORTED
8380
8381 #if FEATURE_TAILCALL_OPT
8382         // Whether opportunistic or implicit tail call optimization is enabled.
8383         bool compTailCallOpt;
8384         // Whether optimization of transforming a recursive tail call into a loop is enabled.
8385         bool compTailCallLoopOpt;
8386 #endif
8387
8388 #ifdef ARM_SOFTFP
8389         static const bool compUseSoftFP = true;
8390 #else // !ARM_SOFTFP
8391         static const bool compUseSoftFP = false;
8392 #endif
8393
8394         GCPollType compGCPollType;
8395     } opts;
8396
8397 #ifdef ALT_JIT
8398     static bool                s_pAltJitExcludeAssembliesListInitialized;
8399     static AssemblyNamesList2* s_pAltJitExcludeAssembliesList;
8400 #endif // ALT_JIT
8401
8402 #ifdef DEBUG
8403
8404     template <typename T>
8405     T dspPtr(T p)
8406     {
8407         return (p == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : p);
8408     }
8409
8410     template <typename T>
8411     T dspOffset(T o)
8412     {
8413         return (o == ZERO) ? ZERO : (opts.dspDiffable ? T(0xD1FFAB1E) : o);
8414     }
8415
8416     static int dspTreeID(GenTree* tree)
8417     {
8418         return tree->gtTreeID;
8419     }
8420     static void printTreeID(GenTree* tree)
8421     {
8422         if (tree == nullptr)
8423         {
8424             printf("[------]");
8425         }
8426         else
8427         {
8428             printf("[%06d]", dspTreeID(tree));
8429         }
8430     }
8431
8432 #endif // DEBUG
8433
8434 // clang-format off
8435 #define STRESS_MODES                                                                            \
8436                                                                                                 \
8437         STRESS_MODE(NONE)                                                                       \
8438                                                                                                 \
8439         /* "Variations" stress areas which we try to mix up with each other. */                 \
8440         /* These should not be exhaustively used as they might */                               \
8441         /* hide/trivialize other areas */                                                       \
8442                                                                                                 \
8443         STRESS_MODE(REGS)                                                                       \
8444         STRESS_MODE(DBL_ALN)                                                                    \
8445         STRESS_MODE(LCL_FLDS)                                                                   \
8446         STRESS_MODE(UNROLL_LOOPS)                                                               \
8447         STRESS_MODE(MAKE_CSE)                                                                   \
8448         STRESS_MODE(LEGACY_INLINE)                                                              \
8449         STRESS_MODE(CLONE_EXPR)                                                                 \
8450         STRESS_MODE(USE_FCOMI)                                                                  \
8451         STRESS_MODE(USE_CMOV)                                                                   \
8452         STRESS_MODE(FOLD)                                                                       \
8453         STRESS_MODE(BB_PROFILE)                                                                 \
8454         STRESS_MODE(OPT_BOOLS_GC)                                                               \
8455         STRESS_MODE(REMORPH_TREES)                                                              \
8456         STRESS_MODE(64RSLT_MUL)                                                                 \
8457         STRESS_MODE(DO_WHILE_LOOPS)                                                             \
8458         STRESS_MODE(MIN_OPTS)                                                                   \
8459         STRESS_MODE(REVERSE_FLAG)     /* Will set GTF_REVERSE_OPS whenever we can */            \
8460         STRESS_MODE(REVERSE_COMMA)    /* Will reverse commas created  with gtNewCommaNode */    \
8461         STRESS_MODE(TAILCALL)         /* Will make the call as a tailcall whenever legal */     \
8462         STRESS_MODE(CATCH_ARG)        /* Will spill catch arg */                                \
8463         STRESS_MODE(UNSAFE_BUFFER_CHECKS)                                                       \
8464         STRESS_MODE(NULL_OBJECT_CHECK)                                                          \
8465         STRESS_MODE(PINVOKE_RESTORE_ESP)                                                        \
8466         STRESS_MODE(RANDOM_INLINE)                                                              \
8467         STRESS_MODE(SWITCH_CMP_BR_EXPANSION)                                                    \
8468         STRESS_MODE(GENERIC_VARN)                                                               \
8469                                                                                                 \
8470         /* After COUNT_VARN, stress level 2 does all of these all the time */                   \
8471                                                                                                 \
8472         STRESS_MODE(COUNT_VARN)                                                                 \
8473                                                                                                 \
8474         /* "Check" stress areas that can be exhaustively used if we */                          \
8475         /*  dont care about performance at all */                                               \
8476                                                                                                 \
8477         STRESS_MODE(FORCE_INLINE) /* Treat every method as AggressiveInlining */                \
8478         STRESS_MODE(CHK_FLOW_UPDATE)                                                            \
8479         STRESS_MODE(EMITTER)                                                                    \
8480         STRESS_MODE(CHK_REIMPORT)                                                               \
8481         STRESS_MODE(FLATFP)                                                                     \
8482         STRESS_MODE(GENERIC_CHECK)                                                              \
8483         STRESS_MODE(COUNT)
8484
8485     enum                compStressArea
8486     {
8487 #define STRESS_MODE(mode) STRESS_##mode,
8488         STRESS_MODES
8489 #undef STRESS_MODE
8490     };
8491 // clang-format on
8492
8493 #ifdef DEBUG
8494     static const LPCWSTR s_compStressModeNames[STRESS_COUNT + 1];
8495     BYTE                 compActiveStressModes[STRESS_COUNT];
8496 #endif // DEBUG
8497
8498 #define MAX_STRESS_WEIGHT 100
8499
8500     bool compStressCompile(compStressArea stressArea, unsigned weightPercentage);
8501
8502 #ifdef DEBUG
8503
8504     bool compInlineStress()
8505     {
8506         return compStressCompile(STRESS_LEGACY_INLINE, 50);
8507     }
8508
8509     bool compRandomInlineStress()
8510     {
8511         return compStressCompile(STRESS_RANDOM_INLINE, 50);
8512     }
8513
8514 #endif // DEBUG
8515
8516     bool compTailCallStress()
8517     {
8518 #ifdef DEBUG
8519         return (JitConfig.TailcallStress() != 0 || compStressCompile(STRESS_TAILCALL, 5));
8520 #else
8521         return false;
8522 #endif
8523     }
8524
8525     codeOptimize compCodeOpt()
8526     {
8527 #if 0
8528         // Switching between size & speed has measurable throughput impact
8529         // (3.5% on NGen mscorlib when measured). It used to be enabled for
8530         // DEBUG, but should generate identical code between CHK & RET builds,
8531         // so that's not acceptable.
8532         // TODO-Throughput: Figure out what to do about size vs. speed & throughput.
8533         //                  Investigate the cause of the throughput regression.
8534
8535         return opts.compCodeOpt;
8536 #else
8537         return BLENDED_CODE;
8538 #endif
8539     }
8540
8541     //--------------------- Info about the procedure --------------------------
8542
8543     struct Info
8544     {
8545         COMP_HANDLE           compCompHnd;
8546         CORINFO_MODULE_HANDLE compScopeHnd;
8547         CORINFO_CLASS_HANDLE  compClassHnd;
8548         CORINFO_METHOD_HANDLE compMethodHnd;
8549         CORINFO_METHOD_INFO*  compMethodInfo;
8550
8551         BOOL hasCircularClassConstraints;
8552         BOOL hasCircularMethodConstraints;
8553
8554 #if defined(DEBUG) || defined(LATE_DISASM)
8555         const char* compMethodName;
8556         const char* compClassName;
8557         const char* compFullName;
8558 #endif // defined(DEBUG) || defined(LATE_DISASM)
8559
8560 #if defined(DEBUG) || defined(INLINE_DATA)
8561         // Method hash is logcally const, but computed
8562         // on first demand.
8563         mutable unsigned compMethodHashPrivate;
8564         unsigned         compMethodHash() const;
8565 #endif // defined(DEBUG) || defined(INLINE_DATA)
8566
8567 #ifdef PSEUDORANDOM_NOP_INSERTION
8568         // things for pseudorandom nop insertion
8569         unsigned  compChecksum;
8570         CLRRandom compRNG;
8571 #endif
8572
8573         // The following holds the FLG_xxxx flags for the method we're compiling.
8574         unsigned compFlags;
8575
8576         // The following holds the class attributes for the method we're compiling.
8577         unsigned compClassAttr;
8578
8579         const BYTE*    compCode;
8580         IL_OFFSET      compILCodeSize;     // The IL code size
8581         UNATIVE_OFFSET compNativeCodeSize; // The native code size, after instructions are issued. This
8582                                            // is less than (compTotalHotCodeSize + compTotalColdCodeSize) only if:
8583         // (1) the code is not hot/cold split, and we issued less code than we expected, or
8584         // (2) the code is hot/cold split, and we issued less code than we expected
8585         // in the cold section (the hot section will always be padded out to compTotalHotCodeSize).
8586
8587         bool compIsStatic : 1;         // Is the method static (no 'this' pointer)?
8588         bool compIsVarArgs : 1;        // Does the method have varargs parameters?
8589         bool compIsContextful : 1;     // contextful method
8590         bool compInitMem : 1;          // Is the CORINFO_OPT_INIT_LOCALS bit set in the method info options?
8591         bool compUnwrapContextful : 1; // JIT should unwrap proxies when possible
8592         bool compProfilerCallback : 1; // JIT inserted a profiler Enter callback
8593         bool compPublishStubParam : 1; // EAX captured in prolog will be available through an instrinsic
8594         bool compRetBuffDefStack : 1;  // The ret buff argument definitely points into the stack.
8595
8596         var_types compRetType;       // Return type of the method as declared in IL
8597         var_types compRetNativeType; // Normalized return type as per target arch ABI
8598         unsigned  compILargsCount;   // Number of arguments (incl. implicit but not hidden)
8599         unsigned  compArgsCount;     // Number of arguments (incl. implicit and     hidden)
8600
8601 #if FEATURE_FASTTAILCALL
8602         size_t compArgStackSize; // Incoming argument stack size in bytes
8603 #endif                           // FEATURE_FASTTAILCALL
8604
8605         unsigned compRetBuffArg; // position of hidden return param var (0, 1) (BAD_VAR_NUM means not present);
8606         int compTypeCtxtArg; // position of hidden param for type context for generic code (CORINFO_CALLCONV_PARAMTYPE)
8607         unsigned       compThisArg; // position of implicit this pointer param (not to be confused with lvaArg0Var)
8608         unsigned       compILlocalsCount; // Number of vars : args + locals (incl. implicit but not hidden)
8609         unsigned       compLocalsCount;   // Number of vars : args + locals (incl. implicit and     hidden)
8610         unsigned       compMaxStack;
8611         UNATIVE_OFFSET compTotalHotCodeSize;  // Total number of bytes of Hot Code in the method
8612         UNATIVE_OFFSET compTotalColdCodeSize; // Total number of bytes of Cold Code in the method
8613
8614         unsigned compCallUnmanaged;   // count of unmanaged calls
8615         unsigned compLvFrameListRoot; // lclNum for the Frame root
8616         unsigned compXcptnsCount;     // Number of exception-handling clauses read in the method's IL.
8617                                       // You should generally use compHndBBtabCount instead: it is the
8618                                       // current number of EH clauses (after additions like synchronized
8619                                       // methods and funclets, and removals like unreachable code deletion).
8620
8621         bool compMatchedVM; // true if the VM is "matched": either the JIT is a cross-compiler
8622                             // and the VM expects that, or the JIT is a "self-host" compiler
8623                             // (e.g., x86 hosted targeting x86) and the VM expects that.
8624
8625         /*  The following holds IL scope information about local variables.
8626          */
8627
8628         unsigned     compVarScopesCount;
8629         VarScopeDsc* compVarScopes;
8630
8631         /* The following holds information about instr offsets for
8632          * which we need to report IP-mappings
8633          */
8634
8635         IL_OFFSET*                   compStmtOffsets; // sorted
8636         unsigned                     compStmtOffsetsCount;
8637         ICorDebugInfo::BoundaryTypes compStmtOffsetsImplicit;
8638
8639 #define CPU_X86 0x0100 // The generic X86 CPU
8640 #define CPU_X86_PENTIUM_4 0x0110
8641
8642 #define CPU_X64 0x0200       // The generic x64 CPU
8643 #define CPU_AMD_X64 0x0210   // AMD x64 CPU
8644 #define CPU_INTEL_X64 0x0240 // Intel x64 CPU
8645
8646 #define CPU_ARM 0x0300 // The generic ARM CPU
8647
8648         unsigned genCPU; // What CPU are we running on
8649     } info;
8650
8651     // Returns true if the method being compiled returns a non-void and non-struct value.
8652     // Note that lvaInitTypeRef() normalizes compRetNativeType for struct returns in a
8653     // single register as per target arch ABI (e.g on Amd64 Windows structs of size 1, 2,
8654     // 4 or 8 gets normalized to TYP_BYTE/TYP_SHORT/TYP_INT/TYP_LONG; On Arm HFA structs).
8655     // Methods returning such structs are considered to return non-struct return value and
8656     // this method returns true in that case.
8657     bool compMethodReturnsNativeScalarType()
8658     {
8659         return (info.compRetType != TYP_VOID) && !varTypeIsStruct(info.compRetNativeType);
8660     }
8661
8662     // Returns true if the method being compiled returns RetBuf addr as its return value
8663     bool compMethodReturnsRetBufAddr()
8664     {
8665         // There are cases where implicit RetBuf argument should be explicitly returned in a register.
8666         // In such cases the return type is changed to TYP_BYREF and appropriate IR is generated.
8667         // These cases are:
8668         // 1. Profiler Leave calllback expects the address of retbuf as return value for
8669         //    methods with hidden RetBuf argument.  impReturnInstruction() when profiler
8670         //    callbacks are needed creates GT_RETURN(TYP_BYREF, op1 = Addr of RetBuf) for
8671         //    methods with hidden RetBufArg.
8672         //
8673         // 2. As per the System V ABI, the address of RetBuf needs to be returned by
8674         //    methods with hidden RetBufArg in RAX. In such case GT_RETURN is of TYP_BYREF,
8675         //    returning the address of RetBuf.
8676         //
8677         // 3. Windows 64-bit native calling convention also requires the address of RetBuff
8678         //    to be returned in RAX.
8679         CLANG_FORMAT_COMMENT_ANCHOR;
8680
8681 #ifdef _TARGET_AMD64_
8682         return (info.compRetBuffArg != BAD_VAR_NUM);
8683 #else  // !_TARGET_AMD64_
8684         return (compIsProfilerHookNeeded()) && (info.compRetBuffArg != BAD_VAR_NUM);
8685 #endif // !_TARGET_AMD64_
8686     }
8687
8688     // Returns true if the method returns a value in more than one return register
8689     // TODO-ARM-Bug: Deal with multi-register genReturnLocaled structs?
8690     // TODO-ARM64: Does this apply for ARM64 too?
8691     bool compMethodReturnsMultiRegRetType()
8692     {
8693 #if FEATURE_MULTIREG_RET
8694 #if defined(_TARGET_X86_)
8695         // On x86 only 64-bit longs are returned in multiple registers
8696         return varTypeIsLong(info.compRetNativeType);
8697 #else  // targets: X64-UNIX, ARM64 or ARM32
8698         // On all other targets that support multireg return values:
8699         // Methods returning a struct in multiple registers have a return value of TYP_STRUCT.
8700         // Such method's compRetNativeType is TYP_STRUCT without a hidden RetBufArg
8701         return varTypeIsStruct(info.compRetNativeType) && (info.compRetBuffArg == BAD_VAR_NUM);
8702 #endif // TARGET_XXX
8703
8704 #else // not FEATURE_MULTIREG_RET
8705
8706         // For this architecture there are no multireg returns
8707         return false;
8708
8709 #endif // FEATURE_MULTIREG_RET
8710     }
8711
8712 #if FEATURE_MULTIREG_ARGS
8713     // Given a GenTree node of TYP_STRUCT that represents a pass by value argument
8714     // return the gcPtr layout for the pointers sized fields
8715     void getStructGcPtrsFromOp(GenTree* op, BYTE* gcPtrsOut);
8716 #endif // FEATURE_MULTIREG_ARGS
8717
8718     // Returns true if the method being compiled returns a value
8719     bool compMethodHasRetVal()
8720     {
8721         return compMethodReturnsNativeScalarType() || compMethodReturnsRetBufAddr() ||
8722                compMethodReturnsMultiRegRetType();
8723     }
8724
8725 #if defined(DEBUG)
8726
8727     void compDispLocalVars();
8728
8729 #endif // DEBUG
8730
8731 //-------------------------- Global Compiler Data ------------------------------------
8732
8733 #ifdef DEBUG
8734     static unsigned s_compMethodsCount; // to produce unique label names
8735     unsigned        compGenTreeID;
8736     unsigned        compBasicBlockID;
8737 #endif
8738
8739     BasicBlock* compCurBB;   // the current basic block in process
8740     GenTree*    compCurStmt; // the current statement in process
8741 #ifdef DEBUG
8742     unsigned compCurStmtNum; // to give all statements an increasing StmtNum when printing dumps
8743 #endif
8744
8745     //  The following is used to create the 'method JIT info' block.
8746     size_t compInfoBlkSize;
8747     BYTE*  compInfoBlkAddr;
8748
8749     EHblkDsc* compHndBBtab;           // array of EH data
8750     unsigned  compHndBBtabCount;      // element count of used elements in EH data array
8751     unsigned  compHndBBtabAllocCount; // element count of allocated elements in EH data array
8752
8753 #if defined(_TARGET_X86_)
8754
8755     //-------------------------------------------------------------------------
8756     //  Tracking of region covered by the monitor in synchronized methods
8757     void* syncStartEmitCookie; // the emitter cookie for first instruction after the call to MON_ENTER
8758     void* syncEndEmitCookie;   // the emitter cookie for first instruction after the call to MON_EXIT
8759
8760 #endif // !_TARGET_X86_
8761
8762     Phases previousCompletedPhase; // the most recently completed phase
8763
8764     //-------------------------------------------------------------------------
8765     //  The following keeps track of how many bytes of local frame space we've
8766     //  grabbed so far in the current function, and how many argument bytes we
8767     //  need to pop when we return.
8768     //
8769
8770     unsigned compLclFrameSize; // secObject+lclBlk+locals+temps
8771
8772     // Count of callee-saved regs we pushed in the prolog.
8773     // Does not include EBP for isFramePointerUsed() and double-aligned frames.
8774     // In case of Amd64 this doesn't include float regs saved on stack.
8775     unsigned compCalleeRegsPushed;
8776
8777 #if defined(_TARGET_XARCH_) && !FEATURE_STACK_FP_X87
8778     // Mask of callee saved float regs on stack.
8779     regMaskTP compCalleeFPRegsSavedMask;
8780 #endif
8781 #ifdef _TARGET_AMD64_
8782 // Quirk for VS debug-launch scenario to work:
8783 // Bytes of padding between save-reg area and locals.
8784 #define VSQUIRK_STACK_PAD (2 * REGSIZE_BYTES)
8785     unsigned compVSQuirkStackPaddingNeeded;
8786     bool     compQuirkForPPPflag;
8787 #endif
8788
8789     unsigned compArgSize; // total size of arguments in bytes (including register args (lvIsRegArg))
8790
8791     unsigned compMapILargNum(unsigned ILargNum); // map accounting for hidden args
8792     unsigned compMapILvarNum(unsigned ILvarNum); // map accounting for hidden args
8793     unsigned compMap2ILvarNum(unsigned varNum);  // map accounting for hidden args
8794
8795     //-------------------------------------------------------------------------
8796
8797     static void compStartup();  // One-time initialization
8798     static void compShutdown(); // One-time finalization
8799
8800     void compInit(ArenaAllocator* pAlloc, InlineInfo* inlineInfo);
8801     void compDone();
8802
8803     static void compDisplayStaticSizes(FILE* fout);
8804
8805     //------------ Some utility functions --------------
8806
8807     void* compGetHelperFtn(CorInfoHelpFunc ftnNum,         /* IN  */
8808                            void**          ppIndirection); /* OUT */
8809
8810     // Several JIT/EE interface functions return a CorInfoType, and also return a
8811     // class handle as an out parameter if the type is a value class.  Returns the
8812     // size of the type these describe.
8813     unsigned compGetTypeSize(CorInfoType cit, CORINFO_CLASS_HANDLE clsHnd);
8814
8815 #ifdef DEBUG
8816     // Components used by the compiler may write unit test suites, and
8817     // have them run within this method.  They will be run only once per process, and only
8818     // in debug.  (Perhaps should be under the control of a COMPlus_ flag.)
8819     // These should fail by asserting.
8820     void compDoComponentUnitTestsOnce();
8821 #endif // DEBUG
8822
8823     int compCompile(CORINFO_METHOD_HANDLE methodHnd,
8824                     CORINFO_MODULE_HANDLE classPtr,
8825                     COMP_HANDLE           compHnd,
8826                     CORINFO_METHOD_INFO*  methodInfo,
8827                     void**                methodCodePtr,
8828                     ULONG*                methodCodeSize,
8829                     JitFlags*             compileFlags);
8830     void compCompileFinish();
8831     int compCompileHelper(CORINFO_MODULE_HANDLE            classPtr,
8832                           COMP_HANDLE                      compHnd,
8833                           CORINFO_METHOD_INFO*             methodInfo,
8834                           void**                           methodCodePtr,
8835                           ULONG*                           methodCodeSize,
8836                           JitFlags*                        compileFlags,
8837                           CorInfoInstantiationVerification instVerInfo);
8838
8839     ArenaAllocator* compGetAllocator();
8840
8841 #if MEASURE_MEM_ALLOC
8842
8843     static bool s_dspMemStats; // Display per-phase memory statistics for every function
8844
8845     struct MemStats
8846     {
8847         unsigned allocCnt;                 // # of allocs
8848         UINT64   allocSz;                  // total size of those alloc.
8849         UINT64   allocSzMax;               // Maximum single allocation.
8850         UINT64   allocSzByKind[CMK_Count]; // Classified by "kind".
8851         UINT64   nraTotalSizeAlloc;
8852         UINT64   nraTotalSizeUsed;
8853
8854         static const char* s_CompMemKindNames[]; // Names of the kinds.
8855
8856         MemStats() : allocCnt(0), allocSz(0), allocSzMax(0), nraTotalSizeAlloc(0), nraTotalSizeUsed(0)
8857         {
8858             for (int i = 0; i < CMK_Count; i++)
8859             {
8860                 allocSzByKind[i] = 0;
8861             }
8862         }
8863         MemStats(const MemStats& ms)
8864             : allocCnt(ms.allocCnt)
8865             , allocSz(ms.allocSz)
8866             , allocSzMax(ms.allocSzMax)
8867             , nraTotalSizeAlloc(ms.nraTotalSizeAlloc)
8868             , nraTotalSizeUsed(ms.nraTotalSizeUsed)
8869         {
8870             for (int i = 0; i < CMK_Count; i++)
8871             {
8872                 allocSzByKind[i] = ms.allocSzByKind[i];
8873             }
8874         }
8875
8876         // Until we have ubiquitous constructors.
8877         void Init()
8878         {
8879             this->MemStats::MemStats();
8880         }
8881
8882         void AddAlloc(size_t sz, CompMemKind cmk)
8883         {
8884             allocCnt += 1;
8885             allocSz += sz;
8886             if (sz > allocSzMax)
8887             {
8888                 allocSzMax = sz;
8889             }
8890             allocSzByKind[cmk] += sz;
8891         }
8892
8893         void Print(FILE* f);       // Print these stats to f.
8894         void PrintByKind(FILE* f); // Do just the by-kind histogram part.
8895     };
8896     MemStats genMemStats;
8897
8898     struct AggregateMemStats : public MemStats
8899     {
8900         unsigned nMethods;
8901
8902         AggregateMemStats() : MemStats(), nMethods(0)
8903         {
8904         }
8905
8906         void Add(const MemStats& ms)
8907         {
8908             nMethods++;
8909             allocCnt += ms.allocCnt;
8910             allocSz += ms.allocSz;
8911             allocSzMax = max(allocSzMax, ms.allocSzMax);
8912             for (int i = 0; i < CMK_Count; i++)
8913             {
8914                 allocSzByKind[i] += ms.allocSzByKind[i];
8915             }
8916             nraTotalSizeAlloc += ms.nraTotalSizeAlloc;
8917             nraTotalSizeUsed += ms.nraTotalSizeUsed;
8918         }
8919
8920         void Print(FILE* f); // Print these stats to jitstdout.
8921     };
8922
8923     static CritSecObject     s_memStatsLock;    // This lock protects the data structures below.
8924     static MemStats          s_maxCompMemStats; // Stats for the compilation with the largest amount allocated.
8925     static AggregateMemStats s_aggMemStats;     // Aggregates statistics for all compilations.
8926
8927 #endif // MEASURE_MEM_ALLOC
8928
8929 #if LOOP_HOIST_STATS
8930     unsigned m_loopsConsidered;
8931     bool     m_curLoopHasHoistedExpression;
8932     unsigned m_loopsWithHoistedExpressions;
8933     unsigned m_totalHoistedExpressions;
8934
8935     void AddLoopHoistStats();
8936     void PrintPerMethodLoopHoistStats();
8937
8938     static CritSecObject s_loopHoistStatsLock; // This lock protects the data structures below.
8939     static unsigned      s_loopsConsidered;
8940     static unsigned      s_loopsWithHoistedExpressions;
8941     static unsigned      s_totalHoistedExpressions;
8942
8943     static void PrintAggregateLoopHoistStats(FILE* f);
8944 #endif // LOOP_HOIST_STATS
8945
8946     void* compGetMemArray(size_t numElem, size_t elemSize, CompMemKind cmk = CMK_Unknown);
8947     void* compGetMem(size_t sz, CompMemKind cmk = CMK_Unknown);
8948     void compFreeMem(void*);
8949
8950     bool compIsForImportOnly();
8951     bool compIsForInlining();
8952     bool compDonotInline();
8953
8954 #ifdef DEBUG
8955     unsigned char compGetJitDefaultFill(); // Get the default fill char value
8956                                            // we randomize this value when JitStress is enabled
8957
8958     const char* compLocalVarName(unsigned varNum, unsigned offs);
8959     VarName compVarName(regNumber reg, bool isFloatReg = false);
8960     const char* compRegVarName(regNumber reg, bool displayVar = false, bool isFloatReg = false);
8961     const char* compRegPairName(regPairNo regPair);
8962     const char* compRegNameForSize(regNumber reg, size_t size);
8963     const char* compFPregVarName(unsigned fpReg, bool displayVar = false);
8964     void compDspSrcLinesByNativeIP(UNATIVE_OFFSET curIP);
8965     void compDspSrcLinesByLineNum(unsigned line, bool seek = false);
8966 #endif // DEBUG
8967
8968     //-------------------------------------------------------------------------
8969
8970     struct VarScopeListNode
8971     {
8972         VarScopeDsc*             data;
8973         VarScopeListNode*        next;
8974         static VarScopeListNode* Create(VarScopeDsc* value, CompAllocator* alloc)
8975         {
8976             VarScopeListNode* node = new (alloc) VarScopeListNode;
8977             node->data             = value;
8978             node->next             = nullptr;
8979             return node;
8980         }
8981     };
8982
8983     struct VarScopeMapInfo
8984     {
8985         VarScopeListNode*       head;
8986         VarScopeListNode*       tail;
8987         static VarScopeMapInfo* Create(VarScopeListNode* node, CompAllocator* alloc)
8988         {
8989             VarScopeMapInfo* info = new (alloc) VarScopeMapInfo;
8990             info->head            = node;
8991             info->tail            = node;
8992             return info;
8993         }
8994     };
8995
8996     // Max value of scope count for which we would use linear search; for larger values we would use hashtable lookup.
8997     static const unsigned MAX_LINEAR_FIND_LCL_SCOPELIST = 32;
8998
8999     typedef JitHashTable<unsigned, JitSmallPrimitiveKeyFuncs<unsigned>, VarScopeMapInfo*> VarNumToScopeDscMap;
9000
9001     // Map to keep variables' scope indexed by varNum containing it's scope dscs at the index.
9002     VarNumToScopeDscMap* compVarScopeMap;
9003
9004     VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned lifeBeg, unsigned lifeEnd);
9005
9006     VarScopeDsc* compFindLocalVar(unsigned varNum, unsigned offs);
9007
9008     VarScopeDsc* compFindLocalVarLinear(unsigned varNum, unsigned offs);
9009
9010     void compInitVarScopeMap();
9011
9012     VarScopeDsc** compEnterScopeList; // List has the offsets where variables
9013                                       // enter scope, sorted by instr offset
9014     unsigned compNextEnterScope;
9015
9016     VarScopeDsc** compExitScopeList; // List has the offsets where variables
9017                                      // go out of scope, sorted by instr offset
9018     unsigned compNextExitScope;
9019
9020     void compInitScopeLists();
9021
9022     void compResetScopeLists();
9023
9024     VarScopeDsc* compGetNextEnterScope(unsigned offs, bool scan = false);
9025
9026     VarScopeDsc* compGetNextExitScope(unsigned offs, bool scan = false);
9027
9028     void compProcessScopesUntil(unsigned   offset,
9029                                 VARSET_TP* inScope,
9030                                 void (Compiler::*enterScopeFn)(VARSET_TP* inScope, VarScopeDsc*),
9031                                 void (Compiler::*exitScopeFn)(VARSET_TP* inScope, VarScopeDsc*));
9032
9033 #ifdef DEBUG
9034     void compDispScopeLists();
9035 #endif // DEBUG
9036
9037     bool compIsProfilerHookNeeded();
9038
9039     //-------------------------------------------------------------------------
9040     /*               Statistical Data Gathering                               */
9041
9042     void compJitStats(); // call this function and enable
9043                          // various ifdef's below for statistical data
9044
9045 #if CALL_ARG_STATS
9046     void        compCallArgStats();
9047     static void compDispCallArgStats(FILE* fout);
9048 #endif
9049
9050     //-------------------------------------------------------------------------
9051
9052 protected:
9053 #ifdef DEBUG
9054     bool skipMethod();
9055 #endif
9056
9057     ArenaAllocator* compAllocator;
9058
9059 public:
9060     CompAllocator* compAllocatorGeneric; // An allocator that uses the CMK_Generic tracker.
9061 #if MEASURE_MEM_ALLOC
9062     CompAllocator* compAllocatorBitset;    // An allocator that uses the CMK_bitset tracker.
9063     CompAllocator* compAllocatorGC;        // An allocator that uses the CMK_GC tracker.
9064     CompAllocator* compAllocatorLoopHoist; // An allocator that uses the CMK_LoopHoist tracker.
9065 #ifdef DEBUG
9066     CompAllocator* compAllocatorDebugOnly; // An allocator that uses the CMK_DebugOnly tracker.
9067 #endif                                     // DEBUG
9068 #endif                                     // MEASURE_MEM_ALLOC
9069
9070     void compFunctionTraceStart();
9071     void compFunctionTraceEnd(void* methodCodePtr, ULONG methodCodeSize, bool isNYI);
9072
9073 protected:
9074     size_t compMaxUncheckedOffsetForNullObject;
9075
9076     void compInitOptions(JitFlags* compileFlags);
9077
9078     void compSetProcessor();
9079     void compInitDebuggingInfo();
9080     void compSetOptimizationLevel();
9081 #ifdef _TARGET_ARMARCH_
9082     bool compRsvdRegCheck(FrameLayoutState curState);
9083 #endif
9084     void compCompile(void** methodCodePtr, ULONG* methodCodeSize, JitFlags* compileFlags);
9085
9086     // Clear annotations produced during optimizations; to be used between iterations when repeating opts.
9087     void ResetOptAnnotations();
9088
9089     // Regenerate loop descriptors; to be used between iterations when repeating opts.
9090     void RecomputeLoopInfo();
9091
9092 #ifdef PROFILING_SUPPORTED
9093     // Data required for generating profiler Enter/Leave/TailCall hooks
9094
9095     bool  compProfilerHookNeeded; // Whether profiler Enter/Leave/TailCall hook needs to be generated for the method
9096     void* compProfilerMethHnd;    // Profiler handle of the method being compiled. Passed as param to ELT callbacks
9097     bool  compProfilerMethHndIndirected; // Whether compProfilerHandle is pointer to the handle or is an actual handle
9098 #endif
9099
9100 #ifdef _TARGET_AMD64_
9101     bool compQuirkForPPP(); // Check if this method should be Quirked for the PPP issue
9102 #endif
9103 public:
9104     // Assumes called as part of process shutdown; does any compiler-specific work associated with that.
9105     static void ProcessShutdownWork(ICorStaticInfo* statInfo);
9106
9107     CompAllocator* getAllocator()
9108     {
9109         return compAllocatorGeneric;
9110     }
9111
9112 #if MEASURE_MEM_ALLOC
9113     CompAllocator* getAllocatorBitset()
9114     {
9115         return compAllocatorBitset;
9116     }
9117     CompAllocator* getAllocatorGC()
9118     {
9119         return compAllocatorGC;
9120     }
9121     CompAllocator* getAllocatorLoopHoist()
9122     {
9123         return compAllocatorLoopHoist;
9124     }
9125 #else  // !MEASURE_MEM_ALLOC
9126     CompAllocator* getAllocatorBitset()
9127     {
9128         return compAllocatorGeneric;
9129     }
9130     CompAllocator* getAllocatorGC()
9131     {
9132         return compAllocatorGeneric;
9133     }
9134     CompAllocator* getAllocatorLoopHoist()
9135     {
9136         return compAllocatorGeneric;
9137     }
9138 #endif // !MEASURE_MEM_ALLOC
9139
9140 #ifdef DEBUG
9141     CompAllocator* getAllocatorDebugOnly()
9142     {
9143 #if MEASURE_MEM_ALLOC
9144         return compAllocatorDebugOnly;
9145 #else  // !MEASURE_MEM_ALLOC
9146         return compAllocatorGeneric;
9147 #endif // !MEASURE_MEM_ALLOC
9148     }
9149 #endif // DEBUG
9150
9151     /*
9152     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9153     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9154     XX                                                                           XX
9155     XX                           typeInfo                                        XX
9156     XX                                                                           XX
9157     XX   Checks for type compatibility and merges types                          XX
9158     XX                                                                           XX
9159     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9160     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9161     */
9162
9163 public:
9164     // Set to TRUE if verification cannot be skipped for this method
9165     // If we detect unverifiable code, we will lazily check
9166     // canSkipMethodVerification() to see if verification is REALLY needed.
9167     BOOL tiVerificationNeeded;
9168
9169     // It it initially TRUE, and it gets set to FALSE if we run into unverifiable code
9170     // Note that this is valid only if tiVerificationNeeded was ever TRUE.
9171     BOOL tiIsVerifiableCode;
9172
9173     // Set to TRUE if runtime callout is needed for this method
9174     BOOL tiRuntimeCalloutNeeded;
9175
9176     // Set to TRUE if security prolog/epilog callout is needed for this method
9177     // Note: This flag is different than compNeedSecurityCheck.
9178     //     compNeedSecurityCheck means whether or not a security object needs
9179     //         to be allocated on the stack, which is currently true for EnC as well.
9180     //     tiSecurityCalloutNeeded means whether or not security callouts need
9181     //         to be inserted in the jitted code.
9182     BOOL tiSecurityCalloutNeeded;
9183
9184     // Returns TRUE if child is equal to or a subtype of parent for merge purposes
9185     // This support is necessary to suport attributes that are not described in
9186     // for example, signatures. For example, the permanent home byref (byref that
9187     // points to the gc heap), isn't a property of method signatures, therefore,
9188     // it is safe to have mismatches here (that tiCompatibleWith will not flag),
9189     // but when deciding if we need to reimport a block, we need to take these
9190     // in account
9191     BOOL tiMergeCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9192
9193     // Returns TRUE if child is equal to or a subtype of parent.
9194     // normalisedForStack indicates that both types are normalised for the stack
9195     BOOL tiCompatibleWith(const typeInfo& pChild, const typeInfo& pParent, bool normalisedForStack) const;
9196
9197     // Merges pDest and pSrc. Returns FALSE if merge is undefined.
9198     // *pDest is modified to represent the merged type.  Sets "*changed" to true
9199     // if this changes "*pDest".
9200     BOOL tiMergeToCommonParent(typeInfo* pDest, const typeInfo* pSrc, bool* changed) const;
9201
9202     // Set pDest from the primitive value type.
9203     // Eg. System.Int32 -> ELEMENT_TYPE_I4
9204
9205     BOOL tiFromPrimitiveValueClass(typeInfo* pDest, const typeInfo* pVC) const;
9206
9207 #ifdef DEBUG
9208     // <BUGNUM> VSW 471305
9209     // IJW allows assigning REF to BYREF. The following allows us to temporarily
9210     // bypass the assert check in gcMarkRegSetGCref and gcMarkRegSetByref
9211     // We use a "short" as we need to push/pop this scope.
9212     // </BUGNUM>
9213     short compRegSetCheckLevel;
9214 #endif
9215
9216     /*
9217     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9218     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9219     XX                                                                           XX
9220     XX                           IL verification stuff                           XX
9221     XX                                                                           XX
9222     XX                                                                           XX
9223     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9224     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9225     */
9226
9227 public:
9228     // The following is used to track liveness of local variables, initialization
9229     // of valueclass constructors, and type safe use of IL instructions.
9230
9231     // dynamic state info needed for verification
9232     EntryState verCurrentState;
9233
9234     // this ptr of object type .ctors are considered intited only after
9235     // the base class ctor is called, or an alternate ctor is called.
9236     // An uninited this ptr can be used to access fields, but cannot
9237     // be used to call a member function.
9238     BOOL verTrackObjCtorInitState;
9239
9240     void verInitBBEntryState(BasicBlock* block, EntryState* currentState);
9241
9242     // Requires that "tis" is not TIS_Bottom -- it's a definite init/uninit state.
9243     void verSetThisInit(BasicBlock* block, ThisInitState tis);
9244     void verInitCurrentState();
9245     void verResetCurrentState(BasicBlock* block, EntryState* currentState);
9246
9247     // Merges the current verification state into the entry state of "block", return FALSE if that merge fails,
9248     // TRUE if it succeeds.  Further sets "*changed" to true if this changes the entry state of "block".
9249     BOOL verMergeEntryStates(BasicBlock* block, bool* changed);
9250
9251     void verConvertBBToThrowVerificationException(BasicBlock* block DEBUGARG(bool logMsg));
9252     void verHandleVerificationFailure(BasicBlock* block DEBUGARG(bool logMsg));
9253     typeInfo verMakeTypeInfo(CORINFO_CLASS_HANDLE clsHnd,
9254                              bool bashStructToRef = false); // converts from jit type representation to typeInfo
9255     typeInfo verMakeTypeInfo(CorInfoType          ciType,
9256                              CORINFO_CLASS_HANDLE clsHnd); // converts from jit type representation to typeInfo
9257     BOOL verIsSDArray(typeInfo ti);
9258     typeInfo verGetArrayElemType(typeInfo ti);
9259
9260     typeInfo verParseArgSigToTypeInfo(CORINFO_SIG_INFO* sig, CORINFO_ARG_LIST_HANDLE args);
9261     BOOL verNeedsVerification();
9262     BOOL verIsByRefLike(const typeInfo& ti);
9263     BOOL verIsSafeToReturnByRef(const typeInfo& ti);
9264
9265     // generic type variables range over types that satisfy IsBoxable
9266     BOOL verIsBoxable(const typeInfo& ti);
9267
9268     void DECLSPEC_NORETURN verRaiseVerifyException(INDEBUG(const char* reason) DEBUGARG(const char* file)
9269                                                        DEBUGARG(unsigned line));
9270     void verRaiseVerifyExceptionIfNeeded(INDEBUG(const char* reason) DEBUGARG(const char* file)
9271                                              DEBUGARG(unsigned line));
9272     bool verCheckTailCallConstraint(OPCODE                  opcode,
9273                                     CORINFO_RESOLVED_TOKEN* pResolvedToken,
9274                                     CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken, // Is this a "constrained." call
9275                                                                                        // on a type parameter?
9276                                     bool speculative // If true, won't throw if verificatoin fails. Instead it will
9277                                                      // return false to the caller.
9278                                                      // If false, it will throw.
9279                                     );
9280     bool verIsBoxedValueType(typeInfo ti);
9281
9282     void verVerifyCall(OPCODE                  opcode,
9283                        CORINFO_RESOLVED_TOKEN* pResolvedToken,
9284                        CORINFO_RESOLVED_TOKEN* pConstrainedResolvedToken,
9285                        bool                    tailCall,
9286                        bool                    readonlyCall, // is this a "readonly." call?
9287                        const BYTE*             delegateCreateStart,
9288                        const BYTE*             codeAddr,
9289                        CORINFO_CALL_INFO* callInfo DEBUGARG(const char* methodName));
9290
9291     BOOL verCheckDelegateCreation(const BYTE* delegateCreateStart, const BYTE* codeAddr, mdMemberRef& targetMemberRef);
9292
9293     typeInfo verVerifySTIND(const typeInfo& ptr, const typeInfo& value, const typeInfo& instrType);
9294     typeInfo verVerifyLDIND(const typeInfo& ptr, const typeInfo& instrType);
9295     void verVerifyField(CORINFO_RESOLVED_TOKEN*   pResolvedToken,
9296                         const CORINFO_FIELD_INFO& fieldInfo,
9297                         const typeInfo*           tiThis,
9298                         BOOL                      mutator,
9299                         BOOL                      allowPlainStructAsThis = FALSE);
9300     void verVerifyCond(const typeInfo& tiOp1, const typeInfo& tiOp2, unsigned opcode);
9301     void verVerifyThisPtrInitialised();
9302     BOOL verIsCallToInitThisPtr(CORINFO_CLASS_HANDLE context, CORINFO_CLASS_HANDLE target);
9303
9304     // Register allocator
9305     void raInitStackFP();
9306     void raEnregisterVarsPrePassStackFP();
9307     void raSetRegLclBirthDeath(GenTree* tree, VARSET_VALARG_TP lastlife, bool fromLDOBJ);
9308     void raEnregisterVarsPostPassStackFP();
9309     void raGenerateFPRefCounts();
9310     void raEnregisterVarsStackFP();
9311     void raUpdateHeightsForVarsStackFP(VARSET_VALARG_TP mask);
9312
9313     regNumber raRegForVarStackFP(unsigned varTrackedIndex);
9314     void raAddPayloadStackFP(VARSET_VALARG_TP mask, unsigned weight);
9315
9316     // returns true if enregistering v1 would save more mem accesses than v2
9317     bool raVarIsGreaterValueStackFP(LclVarDsc* lv1, LclVarDsc* lv2);
9318
9319 #ifdef DEBUG
9320     void raDumpHeightsStackFP();
9321     void raDumpVariableRegIntfFloat();
9322 #endif
9323
9324 #if FEATURE_STACK_FP_X87
9325
9326     // Currently, we use FP transition blocks in only 2 situations:
9327     //
9328     //      -conditional jump on longs where FP stack differs with target: it's not strictly
9329     //       necessary, but its low frequency and the code would get complicated if we try to
9330     //       inline the FP stack adjustment, as we have a lot of special casing going on to try
9331     //       minimize the way we generate the jump code.
9332     //      -case statements of switch where the FP stack differs with the one of evaluating the switch () statement
9333     //       We do this as we want to codegen switch as a jumptable. Again, this is low frequency.
9334     //
9335     //      However, transition blocks have 2 problems
9336     //
9337     //          - Procedure splitting: current implementation of procedure splitting requires all basic blocks to
9338     //            be known at codegen time, as it generates all hot blocks first and cold blocks later. This ties
9339     //            us up in codegen and is a solvable problem (we could make procedure splitting generate blocks
9340     //            in the right place without preordering them), this causes us to have to generate the transition
9341     //            blocks in the cold area if we want procedure splitting.
9342     //
9343     //
9344     //          - Thread abort exceptions and transition blocks. Transition blocks were designed under the assumption
9345     //            that no exceptions can happen inside them. Unfortunately Thread.Abort can happen in any instruction,
9346     //            and if we have handlers we will have to try to call them. Fixing this the right way would imply
9347     //            having multiple try native code regions for a single try il region. This is doable and shouldnt be
9348     //            a big change in the exception.
9349     //
9350     //      Given the low frequency of the cases where we have transition blocks, I've decided to dumb down
9351     //      optimizations. For these 2 cases:
9352     //
9353     //          - When there is a chance that we will have FP transition blocks, we won't do procedure splitting.
9354     //          - When a method has a handler, it won't enregister any FP variables that go thru a conditional long or
9355     //          a switch statement.
9356     //
9357     //      If at any point we find we need to optimize this, we should throw work at unblocking the restrictions our
9358     //      current procedure splitting and exception code have.
9359     bool compMayHaveTransitionBlocks;
9360
9361     VARSET_TP raMaskDontEnregFloat; // mask for additional restrictions
9362
9363     VARSET_TP raLclRegIntfFloat[REG_FPCOUNT];
9364
9365     unsigned raCntStkStackFP;
9366     unsigned raCntWtdStkDblStackFP;
9367     unsigned raCntStkParamDblStackFP;
9368
9369     // Payload in mem accesses for enregistering a variable (we dont want to mix with refcounts)
9370     // TODO: Do we want to put this in LclVarDsc?
9371     unsigned raPayloadStackFP[lclMAX_TRACKED];
9372     unsigned raHeightsStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
9373 #ifdef DEBUG
9374     // Useful for debugging
9375     unsigned raHeightsNonWeightedStackFP[lclMAX_TRACKED][FP_VIRTUALREGISTERS + 1];
9376 #endif
9377 #endif // FEATURE_STACK_FP_X87
9378
9379 #ifdef DEBUG
9380     // One line log function. Default level is 0. Increasing it gives you
9381     // more log information
9382
9383     // levels are currently unused: #define JITDUMP(level,...)                     ();
9384     void JitLogEE(unsigned level, const char* fmt, ...);
9385
9386     bool compDebugBreak;
9387
9388     bool compJitHaltMethod();
9389
9390 #endif
9391
9392     /*
9393     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9394     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9395     XX                                                                           XX
9396     XX                   GS Security checks for unsafe buffers                   XX
9397     XX                                                                           XX
9398     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9399     XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
9400     */
9401 public:
9402     struct ShadowParamVarInfo
9403     {
9404         FixedBitVect* assignGroup; // the closure set of variables whose values depend on each other
9405         unsigned      shadowCopy;  // Lcl var num, valid only if not set to NO_SHADOW_COPY
9406
9407         static bool mayNeedShadowCopy(LclVarDsc* varDsc)
9408         {
9409 #if defined(_TARGET_AMD64_) && !defined(LEGACY_BACKEND)
9410             // GS cookie logic to create shadow slots, create trees to copy reg args to shadow
9411             // slots and update all trees to refer to shadow slots is done immediately after
9412             // fgMorph().  Lsra could potentially mark a param as DoNotEnregister after JIT determines
9413             // not to shadow a parameter.  Also, LSRA could potentially spill a param which is passed
9414             // in register. Therefore, conservatively all params may need a shadow copy.  Note that
9415             // GS cookie logic further checks whether the param is a ptr or an unsafe buffer before
9416             // creating a shadow slot even though this routine returns true.
9417             //
9418             // TODO-AMD64-CQ: Revisit this conservative approach as it could create more shadow slots than
9419             // required. There are two cases under which a reg arg could potentially be used from its
9420             // home location:
9421             //   a) LSRA marks it as DoNotEnregister (see LinearScan::identifyCandidates())
9422             //   b) LSRA spills it
9423             //
9424             // Possible solution to address case (a)
9425             //   - The conditions under which LSRA marks a varDsc as DoNotEnregister could be checked
9426             //     in this routine.  Note that live out of exception handler is something we may not be
9427             //     able to do it here since GS cookie logic is invoked ahead of liveness computation.
9428             //     Therefore, for methods with exception handling and need GS cookie check we might have
9429             //     to take conservative approach.
9430             //
9431             // Possible solution to address case (b)
9432             //   - Whenver a parameter passed in an argument register needs to be spilled by LSRA, we
9433             //     create a new spill temp if the method needs GS cookie check.
9434             return varDsc->lvIsParam;
9435 #else // !(defined(_TARGET_AMD64_) && defined(LEGACY_BACKEND))
9436             return varDsc->lvIsParam && !varDsc->lvIsRegArg;
9437 #endif
9438         }
9439
9440 #ifdef DEBUG
9441         void Print()
9442         {
9443             printf("assignGroup [%p]; shadowCopy: [%d];\n", assignGroup, shadowCopy);
9444         }
9445 #endif
9446     };
9447
9448     GSCookie*           gsGlobalSecurityCookieAddr; // Address of global cookie for unsafe buffer checks
9449     GSCookie            gsGlobalSecurityCookieVal;  // Value of global cookie if addr is NULL
9450     ShadowParamVarInfo* gsShadowVarInfo;            // Table used by shadow param analysis code
9451
9452     void gsGSChecksInitCookie();   // Grabs cookie variable
9453     void gsCopyShadowParams();     // Identify vulnerable params and create dhadow copies
9454     bool gsFindVulnerableParams(); // Shadow param analysis code
9455     void gsParamsToShadows();      // Insert copy code and replave param uses by shadow
9456
9457     static fgWalkPreFn gsMarkPtrsAndAssignGroups; // Shadow param analysis tree-walk
9458     static fgWalkPreFn gsReplaceShadowParams;     // Shadow param replacement tree-walk
9459
9460 #define DEFAULT_MAX_INLINE_SIZE 100 // Methods with >  DEFAULT_MAX_INLINE_SIZE IL bytes will never be inlined.
9461                                     // This can be overwritten by setting complus_JITInlineSize env variable.
9462
9463 #define DEFAULT_MAX_INLINE_DEPTH 20 // Methods at more than this level deep will not be inlined
9464
9465 #define DEFAULT_MAX_LOCALLOC_TO_LOCAL_SIZE 32 // fixed locallocs of this size or smaller will convert to local buffers
9466
9467 private:
9468 #ifdef FEATURE_JIT_METHOD_PERF
9469     JitTimer*                  pCompJitTimer;         // Timer data structure (by phases) for current compilation.
9470     static CompTimeSummaryInfo s_compJitTimerSummary; // Summary of the Timer information for the whole run.
9471
9472     static LPCWSTR JitTimeLogCsv();        // Retrieve the file name for CSV from ConfigDWORD.
9473     static LPCWSTR compJitTimeLogFilename; // If a log file for JIT time is desired, filename to write it to.
9474 #endif
9475     inline void EndPhase(Phases phase); // Indicate the end of the given phase.
9476
9477 #if MEASURE_CLRAPI_CALLS
9478     // Thin wrappers that call into JitTimer (if present).
9479     inline void CLRApiCallEnter(unsigned apix);
9480     inline void CLRApiCallLeave(unsigned apix);
9481
9482 public:
9483     inline void CLR_API_Enter(API_ICorJitInfo_Names ename);
9484     inline void CLR_API_Leave(API_ICorJitInfo_Names ename);
9485
9486 private:
9487 #endif
9488
9489 #if defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9490     // These variables are associated with maintaining SQM data about compile time.
9491     unsigned __int64 m_compCyclesAtEndOfInlining; // The thread-virtualized cycle count at the end of the inlining phase
9492                                                   // in the current compilation.
9493     unsigned __int64 m_compCycles;                // Net cycle count for current compilation
9494     DWORD m_compTickCountAtEndOfInlining; // The result of GetTickCount() (# ms since some epoch marker) at the end of
9495                                           // the inlining phase in the current compilation.
9496 #endif                                    // defined(DEBUG) || defined(INLINE_DATA) || defined(FEATURE_CLRSQM)
9497
9498     // Records the SQM-relevant (cycles and tick count).  Should be called after inlining is complete.
9499     // (We do this after inlining because this marks the last point at which the JIT is likely to cause
9500     // type-loading and class initialization).
9501     void RecordStateAtEndOfInlining();
9502     // Assumes being called at the end of compilation.  Update the SQM state.
9503     void RecordStateAtEndOfCompilation();
9504
9505 #ifdef FEATURE_CLRSQM
9506     // Does anything SQM related necessary at process shutdown time.
9507     static void ProcessShutdownSQMWork(ICorStaticInfo* statInfo);
9508 #endif // FEATURE_CLRSQM
9509
9510 public:
9511 #if FUNC_INFO_LOGGING
9512     static LPCWSTR compJitFuncInfoFilename; // If a log file for per-function information is required, this is the
9513                                             // filename to write it to.
9514     static FILE* compJitFuncInfoFile;       // And this is the actual FILE* to write to.
9515 #endif                                      // FUNC_INFO_LOGGING
9516
9517     Compiler* prevCompiler; // Previous compiler on stack for TLS Compiler* linked list for reentrant compilers.
9518
9519     // Is the compilation in a full trust context?
9520     bool compIsFullTrust();
9521
9522 #if MEASURE_NOWAY
9523     void RecordNowayAssert(const char* filename, unsigned line, const char* condStr);
9524 #endif // MEASURE_NOWAY
9525
9526 #ifndef FEATURE_TRACELOGGING
9527     // Should we actually fire the noway assert body and the exception handler?
9528     bool compShouldThrowOnNoway();
9529 #else  // FEATURE_TRACELOGGING
9530     // Should we actually fire the noway assert body and the exception handler?
9531     bool compShouldThrowOnNoway(const char* filename, unsigned line);
9532
9533     // Telemetry instance to use per method compilation.
9534     JitTelemetry compJitTelemetry;
9535
9536     // Get common parameters that have to be logged with most telemetry data.
9537     void compGetTelemetryDefaults(const char** assemblyName,
9538                                   const char** scopeName,
9539                                   const char** methodName,
9540                                   unsigned*    methodHash);
9541 #endif // !FEATURE_TRACELOGGING
9542
9543 #ifdef DEBUG
9544 private:
9545     NodeToTestDataMap* m_nodeTestData;
9546
9547     static const unsigned FIRST_LOOP_HOIST_CSE_CLASS = 1000;
9548     unsigned              m_loopHoistCSEClass; // LoopHoist test annotations turn into CSE requirements; we
9549                                                // label them with CSE Class #'s starting at FIRST_LOOP_HOIST_CSE_CLASS.
9550                                                // Current kept in this.
9551 public:
9552     NodeToTestDataMap* GetNodeTestData()
9553     {
9554         Compiler* compRoot = impInlineRoot();
9555         if (compRoot->m_nodeTestData == nullptr)
9556         {
9557             compRoot->m_nodeTestData = new (getAllocatorDebugOnly()) NodeToTestDataMap(getAllocatorDebugOnly());
9558         }
9559         return compRoot->m_nodeTestData;
9560     }
9561
9562     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, int> NodeToIntMap;
9563
9564     // Returns the set (i.e., the domain of the result map) of nodes that are keys in m_nodeTestData, and
9565     // currently occur in the AST graph.
9566     NodeToIntMap* FindReachableNodesInNodeTestData();
9567
9568     // Node "from" is being eliminated, and being replaced by node "to".  If "from" had any associated
9569     // test data, associate that data with "to".
9570     void TransferTestDataToNode(GenTree* from, GenTree* to);
9571
9572     // Requires that "to" is a clone of "from".  If any nodes in the "from" tree
9573     // have annotations, attach similar annotations to the corresponding nodes in "to".
9574     void CopyTestDataToCloneTree(GenTree* from, GenTree* to);
9575
9576     // These are the methods that test that the various conditions implied by the
9577     // test attributes are satisfied.
9578     void JitTestCheckSSA(); // SSA builder tests.
9579     void JitTestCheckVN();  // Value numbering tests.
9580 #endif                      // DEBUG
9581
9582     // The "FieldSeqStore", for canonicalizing field sequences.  See the definition of FieldSeqStore for
9583     // operations.
9584     FieldSeqStore* m_fieldSeqStore;
9585
9586     FieldSeqStore* GetFieldSeqStore()
9587     {
9588         Compiler* compRoot = impInlineRoot();
9589         if (compRoot->m_fieldSeqStore == nullptr)
9590         {
9591             // Create a CompAllocator that labels sub-structure with CMK_FieldSeqStore, and use that for allocation.
9592             CompAllocator* ialloc     = new (this, CMK_FieldSeqStore) CompAllocator(this, CMK_FieldSeqStore);
9593             compRoot->m_fieldSeqStore = new (ialloc) FieldSeqStore(ialloc);
9594         }
9595         return compRoot->m_fieldSeqStore;
9596     }
9597
9598     typedef JitHashTable<GenTree*, JitPtrKeyFuncs<GenTree>, FieldSeqNode*> NodeToFieldSeqMap;
9599
9600     // Some nodes of "TYP_BYREF" or "TYP_I_IMPL" actually represent the address of a field within a struct, but since
9601     // the offset of the field is zero, there's no "GT_ADD" node.  We normally attach a field sequence to the constant
9602     // that is added, but what do we do when that constant is zero, and is thus not present?  We use this mechanism to
9603     // attach the field sequence directly to the address node.
9604     NodeToFieldSeqMap* m_zeroOffsetFieldMap;
9605
9606     NodeToFieldSeqMap* GetZeroOffsetFieldMap()
9607     {
9608         // Don't need to worry about inlining here
9609         if (m_zeroOffsetFieldMap == nullptr)
9610         {
9611             // Create a CompAllocator that labels sub-structure with CMK_ZeroOffsetFieldMap, and use that for
9612             // allocation.
9613             CompAllocator* ialloc = new (this, CMK_ZeroOffsetFieldMap) CompAllocator(this, CMK_ZeroOffsetFieldMap);
9614             m_zeroOffsetFieldMap  = new (ialloc) NodeToFieldSeqMap(ialloc);
9615         }
9616         return m_zeroOffsetFieldMap;
9617     }
9618
9619     // Requires that "op1" is a node of type "TYP_BYREF" or "TYP_I_IMPL".  We are dereferencing this with the fields in
9620     // "fieldSeq", whose offsets are required all to be zero.  Ensures that any field sequence annotation currently on
9621     // "op1" or its components is augmented by appending "fieldSeq".  In practice, if "op1" is a GT_LCL_FLD, it has
9622     // a field sequence as a member; otherwise, it may be the addition of an a byref and a constant, where the const
9623     // has a field sequence -- in this case "fieldSeq" is appended to that of the constant; otherwise, we
9624     // record the the field sequence using the ZeroOffsetFieldMap described above.
9625     //
9626     // One exception above is that "op1" is a node of type "TYP_REF" where "op1" is a GT_LCL_VAR.
9627     // This happens when System.Object vtable pointer is a regular field at offset 0 in System.Private.CoreLib in
9628     // CoreRT. Such case is handled same as the default case.
9629     void fgAddFieldSeqForZeroOffset(GenTree* op1, FieldSeqNode* fieldSeq);
9630
9631     typedef JitHashTable<const GenTree*, JitPtrKeyFuncs<GenTree>, ArrayInfo> NodeToArrayInfoMap;
9632     NodeToArrayInfoMap* m_arrayInfoMap;
9633
9634     NodeToArrayInfoMap* GetArrayInfoMap()
9635     {
9636         Compiler* compRoot = impInlineRoot();
9637         if (compRoot->m_arrayInfoMap == nullptr)
9638         {
9639             // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9640             CompAllocator* ialloc    = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
9641             compRoot->m_arrayInfoMap = new (ialloc) NodeToArrayInfoMap(ialloc);
9642         }
9643         return compRoot->m_arrayInfoMap;
9644     }
9645
9646     //-----------------------------------------------------------------------------------------------------------------
9647     // Compiler::TryGetArrayInfo:
9648     //    Given an indirection node, checks to see whether or not that indirection represents an array access, and
9649     //    if so returns information about the array.
9650     //
9651     // Arguments:
9652     //    indir           - The `GT_IND` node.
9653     //    arrayInfo (out) - Information about the accessed array if this function returns true. Undefined otherwise.
9654     //
9655     // Returns:
9656     //    True if the `GT_IND` node represents an array access; false otherwise.
9657     inline bool TryGetArrayInfo(GenTreeIndir* indir, ArrayInfo* arrayInfo)
9658     {
9659         if ((indir->gtFlags & GTF_IND_ARR_INDEX) == 0)
9660         {
9661             return false;
9662         }
9663
9664         if (indir->gtOp1->OperIs(GT_INDEX_ADDR))
9665         {
9666             GenTreeIndexAddr* const indexAddr = indir->gtOp1->AsIndexAddr();
9667             *arrayInfo = ArrayInfo(indexAddr->gtElemType, indexAddr->gtElemSize, indexAddr->gtElemOffset,
9668                                    indexAddr->gtStructElemClass);
9669             return true;
9670         }
9671
9672         bool found = GetArrayInfoMap()->Lookup(indir, arrayInfo);
9673         assert(found);
9674         return true;
9675     }
9676
9677     NodeToUnsignedMap* m_memorySsaMap[MemoryKindCount];
9678
9679     // In some cases, we want to assign intermediate SSA #'s to memory states, and know what nodes create those memory
9680     // states. (We do this for try blocks, where, if the try block doesn't do a call that loses track of the memory
9681     // state, all the possible memory states are possible initial states of the corresponding catch block(s).)
9682     NodeToUnsignedMap* GetMemorySsaMap(MemoryKind memoryKind)
9683     {
9684         if (memoryKind == GcHeap && byrefStatesMatchGcHeapStates)
9685         {
9686             // Use the same map for GCHeap and ByrefExposed when their states match.
9687             memoryKind = ByrefExposed;
9688         }
9689
9690         assert(memoryKind < MemoryKindCount);
9691         Compiler* compRoot = impInlineRoot();
9692         if (compRoot->m_memorySsaMap[memoryKind] == nullptr)
9693         {
9694             // Create a CompAllocator that labels sub-structure with CMK_ArrayInfoMap, and use that for allocation.
9695             CompAllocator* ialloc                = new (this, CMK_ArrayInfoMap) CompAllocator(this, CMK_ArrayInfoMap);
9696             compRoot->m_memorySsaMap[memoryKind] = new (ialloc) NodeToUnsignedMap(ialloc);
9697         }
9698         return compRoot->m_memorySsaMap[memoryKind];
9699     }
9700
9701     // The Refany type is the only struct type whose structure is implicitly assumed by IL.  We need its fields.
9702     CORINFO_CLASS_HANDLE m_refAnyClass;
9703     CORINFO_FIELD_HANDLE GetRefanyDataField()
9704     {
9705         if (m_refAnyClass == nullptr)
9706         {
9707             m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9708         }
9709         return info.compCompHnd->getFieldInClass(m_refAnyClass, 0);
9710     }
9711     CORINFO_FIELD_HANDLE GetRefanyTypeField()
9712     {
9713         if (m_refAnyClass == nullptr)
9714         {
9715             m_refAnyClass = info.compCompHnd->getBuiltinClass(CLASSID_TYPED_BYREF);
9716         }
9717         return info.compCompHnd->getFieldInClass(m_refAnyClass, 1);
9718     }
9719
9720 #if VARSET_COUNTOPS
9721     static BitSetSupport::BitSetOpCounter m_varsetOpCounter;
9722 #endif
9723 #if ALLVARSET_COUNTOPS
9724     static BitSetSupport::BitSetOpCounter m_allvarsetOpCounter;
9725 #endif
9726
9727     static HelperCallProperties s_helperCallProperties;
9728
9729 #ifdef FEATURE_UNIX_AMD64_STRUCT_PASSING
9730     static var_types GetTypeFromClassificationAndSizes(SystemVClassificationType classType, int size);
9731     static var_types GetEightByteType(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9732                                       unsigned                                                   slotNum);
9733
9734     static void GetStructTypeOffset(const SYSTEMV_AMD64_CORINFO_STRUCT_REG_PASSING_DESCRIPTOR& structDesc,
9735                                     var_types*                                                 type0,
9736                                     var_types*                                                 type1,
9737                                     unsigned __int8*                                           offset0,
9738                                     unsigned __int8*                                           offset1);
9739
9740     void GetStructTypeOffset(CORINFO_CLASS_HANDLE typeHnd,
9741                              var_types*           type0,
9742                              var_types*           type1,
9743                              unsigned __int8*     offset0,
9744                              unsigned __int8*     offset1);
9745
9746     void fgMorphSystemVStructArgs(GenTreeCall* call, bool hasStructArgument);
9747 #endif // defined(FEATURE_UNIX_AMD64_STRUCT_PASSING)
9748
9749     void fgMorphMultiregStructArgs(GenTreeCall* call);
9750     GenTree* fgMorphMultiregStructArg(GenTree* arg, fgArgTabEntry* fgEntryPtr);
9751
9752     bool killGCRefs(GenTree* tree);
9753
9754 }; // end of class Compiler
9755
9756 // Inline methods of CompAllocator.
9757 void* CompAllocator::Alloc(size_t sz)
9758 {
9759 #if MEASURE_MEM_ALLOC
9760     return m_comp->compGetMem(sz, m_cmk);
9761 #else
9762     return m_comp->compGetMem(sz);
9763 #endif
9764 }
9765
9766 void* CompAllocator::ArrayAlloc(size_t elems, size_t elemSize)
9767 {
9768 #if MEASURE_MEM_ALLOC
9769     return m_comp->compGetMemArray(elems, elemSize, m_cmk);
9770 #else
9771     return m_comp->compGetMemArray(elems, elemSize);
9772 #endif
9773 }
9774
9775 // LclVarDsc constructor. Uses Compiler, so must come after Compiler definition.
9776 inline LclVarDsc::LclVarDsc(Compiler* comp)
9777     : // Initialize the ArgRegs to REG_STK.
9778     // The morph will do the right thing to change
9779     // to the right register if passed in register.
9780     _lvArgReg(REG_STK)
9781     ,
9782 #if FEATURE_MULTIREG_ARGS
9783     _lvOtherArgReg(REG_STK)
9784     ,
9785 #endif // FEATURE_MULTIREG_ARGS
9786 #if ASSERTION_PROP
9787     lvRefBlks(BlockSetOps::UninitVal())
9788     ,
9789 #endif // ASSERTION_PROP
9790     lvPerSsaData(comp->getAllocator())
9791 {
9792 }
9793
9794 //---------------------------------------------------------------------------------------------------------------------
9795 // GenTreeVisitor: a flexible tree walker implemented using the curiosly-recurring-template pattern.
9796 //
9797 // This class implements a configurable walker for IR trees. There are five configuration options (defaults values are
9798 // shown in parentheses):
9799 //
9800 // - ComputeStack (false): when true, the walker will push each node onto the `m_ancestors` stack. "Ancestors" is a bit
9801 //                         of a misnomer, as the first entry will always be the current node.
9802 //
9803 // - DoPreOrder (false): when true, the walker will invoke `TVisitor::PreOrderVisit` with the current node as an
9804 //                       argument before visiting the node's operands.
9805 //
9806 // - DoPostOrder (false): when true, the walker will invoke `TVisitor::PostOrderVisit` with the current node as an
9807 //                        argument after visiting the node's operands.
9808 //
9809 // - DoLclVarsOnly (false): when true, the walker will only invoke `TVisitor::PreOrderVisit` for lclVar nodes.
9810 //                          `DoPreOrder` must be true if this option is true.
9811 //
9812 // - UseExecutionOrder (false): when true, then walker will visit a node's operands in execution order (e.g. if a
9813 //                              binary operator has the `GTF_REVERSE_OPS` flag set, the second operand will be
9814 //                              visited before the first).
9815 //
9816 // At least one of `DoPreOrder` and `DoPostOrder` must be specified.
9817 //
9818 // A simple pre-order visitor might look something like the following:
9819 //
9820 //     class CountingVisitor final : public GenTreeVisitor<CountingVisitor>
9821 //     {
9822 //     public:
9823 //         enum
9824 //         {
9825 //             DoPreOrder = true
9826 //         };
9827 //
9828 //         unsigned m_count;
9829 //
9830 //         CountingVisitor(Compiler* compiler)
9831 //             : GenTreeVisitor<CountingVisitor>(compiler), m_count(0)
9832 //         {
9833 //         }
9834 //
9835 //         Compiler::fgWalkResult PreOrderVisit(GenTree* node)
9836 //         {
9837 //             m_count++;
9838 //         }
9839 //     };
9840 //
9841 // This visitor would then be used like so:
9842 //
9843 //     CountingVisitor countingVisitor(compiler);
9844 //     countingVisitor.WalkTree(root);
9845 //
9846 template <typename TVisitor>
9847 class GenTreeVisitor
9848 {
9849 protected:
9850     typedef Compiler::fgWalkResult fgWalkResult;
9851
9852     enum
9853     {
9854         ComputeStack      = false,
9855         DoPreOrder        = false,
9856         DoPostOrder       = false,
9857         DoLclVarsOnly     = false,
9858         UseExecutionOrder = false,
9859     };
9860
9861     Compiler*            m_compiler;
9862     ArrayStack<GenTree*> m_ancestors;
9863
9864     GenTreeVisitor(Compiler* compiler) : m_compiler(compiler), m_ancestors(compiler)
9865     {
9866         assert(compiler != nullptr);
9867
9868         static_assert_no_msg(TVisitor::DoPreOrder || TVisitor::DoPostOrder);
9869         static_assert_no_msg(!TVisitor::DoLclVarsOnly || TVisitor::DoPreOrder);
9870     }
9871
9872     fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
9873     {
9874         return fgWalkResult::WALK_CONTINUE;
9875     }
9876
9877     fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
9878     {
9879         return fgWalkResult::WALK_CONTINUE;
9880     }
9881
9882 public:
9883     fgWalkResult WalkTree(GenTree** use, GenTree* user)
9884     {
9885         assert(use != nullptr);
9886
9887         GenTree* node = *use;
9888
9889         if (TVisitor::ComputeStack)
9890         {
9891             m_ancestors.Push(node);
9892         }
9893
9894         fgWalkResult result = fgWalkResult::WALK_CONTINUE;
9895         if (TVisitor::DoPreOrder && !TVisitor::DoLclVarsOnly)
9896         {
9897             result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9898             if (result == fgWalkResult::WALK_ABORT)
9899             {
9900                 return result;
9901             }
9902
9903             node = *use;
9904             if ((node == nullptr) || (result == fgWalkResult::WALK_SKIP_SUBTREES))
9905             {
9906                 goto DONE;
9907             }
9908         }
9909
9910         switch (node->OperGet())
9911         {
9912             // Leaf lclVars
9913             case GT_LCL_VAR:
9914             case GT_LCL_FLD:
9915             case GT_LCL_VAR_ADDR:
9916             case GT_LCL_FLD_ADDR:
9917                 if (TVisitor::DoLclVarsOnly)
9918                 {
9919                     result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9920                     if (result == fgWalkResult::WALK_ABORT)
9921                     {
9922                         return result;
9923                     }
9924                 }
9925                 __fallthrough;
9926
9927             // Leaf nodes
9928             case GT_CATCH_ARG:
9929             case GT_LABEL:
9930             case GT_FTN_ADDR:
9931             case GT_RET_EXPR:
9932             case GT_CNS_INT:
9933             case GT_CNS_LNG:
9934             case GT_CNS_DBL:
9935             case GT_CNS_STR:
9936             case GT_MEMORYBARRIER:
9937             case GT_JMP:
9938             case GT_JCC:
9939             case GT_SETCC:
9940             case GT_NO_OP:
9941             case GT_START_NONGC:
9942             case GT_PROF_HOOK:
9943 #if !FEATURE_EH_FUNCLETS
9944             case GT_END_LFIN:
9945 #endif // !FEATURE_EH_FUNCLETS
9946             case GT_PHI_ARG:
9947 #ifndef LEGACY_BACKEND
9948             case GT_JMPTABLE:
9949 #endif // LEGACY_BACKEND
9950             case GT_REG_VAR:
9951             case GT_CLS_VAR:
9952             case GT_CLS_VAR_ADDR:
9953             case GT_ARGPLACE:
9954             case GT_PHYSREG:
9955             case GT_EMITNOP:
9956             case GT_PINVOKE_PROLOG:
9957             case GT_PINVOKE_EPILOG:
9958             case GT_IL_OFFSET:
9959                 break;
9960
9961             // Lclvar unary operators
9962             case GT_STORE_LCL_VAR:
9963             case GT_STORE_LCL_FLD:
9964                 if (TVisitor::DoLclVarsOnly)
9965                 {
9966                     result = reinterpret_cast<TVisitor*>(this)->PreOrderVisit(use, user);
9967                     if (result == fgWalkResult::WALK_ABORT)
9968                     {
9969                         return result;
9970                     }
9971                 }
9972                 __fallthrough;
9973
9974             // Standard unary operators
9975             case GT_NOT:
9976             case GT_NEG:
9977             case GT_COPY:
9978             case GT_RELOAD:
9979             case GT_ARR_LENGTH:
9980             case GT_CAST:
9981             case GT_BITCAST:
9982             case GT_CKFINITE:
9983             case GT_LCLHEAP:
9984             case GT_ADDR:
9985             case GT_IND:
9986             case GT_OBJ:
9987             case GT_BLK:
9988             case GT_BOX:
9989             case GT_ALLOCOBJ:
9990             case GT_INIT_VAL:
9991             case GT_JTRUE:
9992             case GT_SWITCH:
9993             case GT_NULLCHECK:
9994             case GT_PUTARG_REG:
9995             case GT_PUTARG_STK:
9996             case GT_RETURNTRAP:
9997             case GT_NOP:
9998             case GT_RETURN:
9999             case GT_RETFILT:
10000             case GT_PHI:
10001             case GT_RUNTIMELOOKUP:
10002             {
10003                 GenTreeUnOp* const unOp = node->AsUnOp();
10004                 if (unOp->gtOp1 != nullptr)
10005                 {
10006                     result = WalkTree(&unOp->gtOp1, unOp);
10007                     if (result == fgWalkResult::WALK_ABORT)
10008                     {
10009                         return result;
10010                     }
10011                 }
10012                 break;
10013             }
10014
10015             // Special nodes
10016             case GT_CMPXCHG:
10017             {
10018                 GenTreeCmpXchg* const cmpXchg = node->AsCmpXchg();
10019
10020                 result = WalkTree(&cmpXchg->gtOpComparand, cmpXchg);
10021                 if (result == fgWalkResult::WALK_ABORT)
10022                 {
10023                     return result;
10024                 }
10025                 result = WalkTree(&cmpXchg->gtOpValue, cmpXchg);
10026                 if (result == fgWalkResult::WALK_ABORT)
10027                 {
10028                     return result;
10029                 }
10030                 result = WalkTree(&cmpXchg->gtOpLocation, cmpXchg);
10031                 if (result == fgWalkResult::WALK_ABORT)
10032                 {
10033                     return result;
10034                 }
10035                 break;
10036             }
10037
10038             case GT_ARR_BOUNDS_CHECK:
10039 #ifdef FEATURE_SIMD
10040             case GT_SIMD_CHK:
10041 #endif // FEATURE_SIMD
10042 #ifdef FEATURE_HW_INTRINSICS
10043             case GT_HW_INTRINSIC_CHK:
10044 #endif // FEATURE_HW_INTRINSICS
10045             {
10046                 GenTreeBoundsChk* const boundsChk = node->AsBoundsChk();
10047
10048                 result = WalkTree(&boundsChk->gtIndex, boundsChk);
10049                 if (result == fgWalkResult::WALK_ABORT)
10050                 {
10051                     return result;
10052                 }
10053                 result = WalkTree(&boundsChk->gtArrLen, boundsChk);
10054                 if (result == fgWalkResult::WALK_ABORT)
10055                 {
10056                     return result;
10057                 }
10058                 break;
10059             }
10060
10061             case GT_FIELD:
10062             {
10063                 GenTreeField* const field = node->AsField();
10064
10065                 if (field->gtFldObj != nullptr)
10066                 {
10067                     result = WalkTree(&field->gtFldObj, field);
10068                     if (result == fgWalkResult::WALK_ABORT)
10069                     {
10070                         return result;
10071                     }
10072                 }
10073                 break;
10074             }
10075
10076             case GT_ARR_ELEM:
10077             {
10078                 GenTreeArrElem* const arrElem = node->AsArrElem();
10079
10080                 result = WalkTree(&arrElem->gtArrObj, arrElem);
10081                 if (result == fgWalkResult::WALK_ABORT)
10082                 {
10083                     return result;
10084                 }
10085
10086                 const unsigned rank = arrElem->gtArrRank;
10087                 for (unsigned dim = 0; dim < rank; dim++)
10088                 {
10089                     result = WalkTree(&arrElem->gtArrInds[dim], arrElem);
10090                     if (result == fgWalkResult::WALK_ABORT)
10091                     {
10092                         return result;
10093                     }
10094                 }
10095                 break;
10096             }
10097
10098             case GT_ARR_OFFSET:
10099             {
10100                 GenTreeArrOffs* const arrOffs = node->AsArrOffs();
10101
10102                 result = WalkTree(&arrOffs->gtOffset, arrOffs);
10103                 if (result == fgWalkResult::WALK_ABORT)
10104                 {
10105                     return result;
10106                 }
10107                 result = WalkTree(&arrOffs->gtIndex, arrOffs);
10108                 if (result == fgWalkResult::WALK_ABORT)
10109                 {
10110                     return result;
10111                 }
10112                 result = WalkTree(&arrOffs->gtArrObj, arrOffs);
10113                 if (result == fgWalkResult::WALK_ABORT)
10114                 {
10115                     return result;
10116                 }
10117                 break;
10118             }
10119
10120             case GT_DYN_BLK:
10121             {
10122                 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
10123
10124                 GenTree** op1Use = &dynBlock->gtOp1;
10125                 GenTree** op2Use = &dynBlock->gtDynamicSize;
10126
10127                 if (TVisitor::UseExecutionOrder && dynBlock->gtEvalSizeFirst)
10128                 {
10129                     std::swap(op1Use, op2Use);
10130                 }
10131
10132                 result = WalkTree(op1Use, dynBlock);
10133                 if (result == fgWalkResult::WALK_ABORT)
10134                 {
10135                     return result;
10136                 }
10137                 result = WalkTree(op2Use, dynBlock);
10138                 if (result == fgWalkResult::WALK_ABORT)
10139                 {
10140                     return result;
10141                 }
10142                 break;
10143             }
10144
10145             case GT_STORE_DYN_BLK:
10146             {
10147                 GenTreeDynBlk* const dynBlock = node->AsDynBlk();
10148
10149                 GenTree** op1Use = &dynBlock->gtOp1;
10150                 GenTree** op2Use = &dynBlock->gtOp2;
10151                 GenTree** op3Use = &dynBlock->gtDynamicSize;
10152
10153                 if (TVisitor::UseExecutionOrder)
10154                 {
10155                     if (dynBlock->IsReverseOp())
10156                     {
10157                         std::swap(op1Use, op2Use);
10158                     }
10159                     if (dynBlock->gtEvalSizeFirst)
10160                     {
10161                         std::swap(op3Use, op2Use);
10162                         std::swap(op2Use, op1Use);
10163                     }
10164                 }
10165
10166                 result = WalkTree(op1Use, dynBlock);
10167                 if (result == fgWalkResult::WALK_ABORT)
10168                 {
10169                     return result;
10170                 }
10171                 result = WalkTree(op2Use, dynBlock);
10172                 if (result == fgWalkResult::WALK_ABORT)
10173                 {
10174                     return result;
10175                 }
10176                 result = WalkTree(op3Use, dynBlock);
10177                 if (result == fgWalkResult::WALK_ABORT)
10178                 {
10179                     return result;
10180                 }
10181                 break;
10182             }
10183
10184             case GT_CALL:
10185             {
10186                 GenTreeCall* const call = node->AsCall();
10187
10188                 if (call->gtCallObjp != nullptr)
10189                 {
10190                     result = WalkTree(&call->gtCallObjp, call);
10191                     if (result == fgWalkResult::WALK_ABORT)
10192                     {
10193                         return result;
10194                     }
10195                 }
10196
10197                 for (GenTreeArgList* args = call->gtCallArgs; args != nullptr; args = args->Rest())
10198                 {
10199                     result = WalkTree(args->pCurrent(), call);
10200                     if (result == fgWalkResult::WALK_ABORT)
10201                     {
10202                         return result;
10203                     }
10204                 }
10205
10206                 for (GenTreeArgList* args = call->gtCallLateArgs; args != nullptr; args = args->Rest())
10207                 {
10208                     result = WalkTree(args->pCurrent(), call);
10209                     if (result == fgWalkResult::WALK_ABORT)
10210                     {
10211                         return result;
10212                     }
10213                 }
10214
10215                 if (call->gtCallType == CT_INDIRECT)
10216                 {
10217                     if (call->gtCallCookie != nullptr)
10218                     {
10219                         result = WalkTree(&call->gtCallCookie, call);
10220                         if (result == fgWalkResult::WALK_ABORT)
10221                         {
10222                             return result;
10223                         }
10224                     }
10225
10226                     result = WalkTree(&call->gtCallAddr, call);
10227                     if (result == fgWalkResult::WALK_ABORT)
10228                     {
10229                         return result;
10230                     }
10231                 }
10232
10233                 if (call->gtControlExpr != nullptr)
10234                 {
10235                     result = WalkTree(&call->gtControlExpr, call);
10236                     if (result == fgWalkResult::WALK_ABORT)
10237                     {
10238                         return result;
10239                     }
10240                 }
10241
10242                 break;
10243             }
10244
10245             // Binary nodes
10246             default:
10247             {
10248                 assert(node->OperIsBinary());
10249
10250                 GenTreeOp* const op = node->AsOp();
10251
10252                 GenTree** op1Use = &op->gtOp1;
10253                 GenTree** op2Use = &op->gtOp2;
10254
10255                 if (TVisitor::UseExecutionOrder && node->IsReverseOp())
10256                 {
10257                     std::swap(op1Use, op2Use);
10258                 }
10259
10260                 if (*op1Use != nullptr)
10261                 {
10262                     result = WalkTree(op1Use, op);
10263                     if (result == fgWalkResult::WALK_ABORT)
10264                     {
10265                         return result;
10266                     }
10267                 }
10268
10269                 if (*op2Use != nullptr)
10270                 {
10271                     result = WalkTree(op2Use, op);
10272                     if (result == fgWalkResult::WALK_ABORT)
10273                     {
10274                         return result;
10275                     }
10276                 }
10277                 break;
10278             }
10279         }
10280
10281     DONE:
10282         // Finally, visit the current node
10283         if (TVisitor::DoPostOrder)
10284         {
10285             result = reinterpret_cast<TVisitor*>(this)->PostOrderVisit(use, user);
10286         }
10287
10288         if (TVisitor::ComputeStack)
10289         {
10290             m_ancestors.Pop();
10291         }
10292
10293         return result;
10294     }
10295 };
10296
10297 template <bool computeStack, bool doPreOrder, bool doPostOrder, bool doLclVarsOnly, bool useExecutionOrder>
10298 class GenericTreeWalker final
10299     : public GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>
10300 {
10301 public:
10302     enum
10303     {
10304         ComputeStack      = computeStack,
10305         DoPreOrder        = doPreOrder,
10306         DoPostOrder       = doPostOrder,
10307         DoLclVarsOnly     = doLclVarsOnly,
10308         UseExecutionOrder = useExecutionOrder,
10309     };
10310
10311 private:
10312     Compiler::fgWalkData* m_walkData;
10313
10314 public:
10315     GenericTreeWalker(Compiler::fgWalkData* walkData)
10316         : GenTreeVisitor<GenericTreeWalker<computeStack, doPreOrder, doPostOrder, doLclVarsOnly, useExecutionOrder>>(
10317               walkData->compiler)
10318         , m_walkData(walkData)
10319     {
10320         assert(walkData != nullptr);
10321
10322         if (computeStack)
10323         {
10324             walkData->parentStack = &this->m_ancestors;
10325         }
10326     }
10327
10328     Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
10329     {
10330         m_walkData->parent = user;
10331         return m_walkData->wtprVisitorFn(use, m_walkData);
10332     }
10333
10334     Compiler::fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
10335     {
10336         m_walkData->parent = user;
10337         return m_walkData->wtpoVisitorFn(use, m_walkData);
10338     }
10339 };
10340
10341 class IncLclVarRefCountsVisitor final : public GenTreeVisitor<IncLclVarRefCountsVisitor>
10342 {
10343 public:
10344     enum
10345     {
10346         DoPreOrder    = true,
10347         DoLclVarsOnly = true
10348     };
10349
10350     IncLclVarRefCountsVisitor(Compiler* compiler);
10351     Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user);
10352
10353     static Compiler::fgWalkResult WalkTree(Compiler* compiler, GenTree* tree);
10354 };
10355
10356 class DecLclVarRefCountsVisitor final : public GenTreeVisitor<DecLclVarRefCountsVisitor>
10357 {
10358 public:
10359     enum
10360     {
10361         DoPreOrder    = true,
10362         DoLclVarsOnly = true
10363     };
10364
10365     DecLclVarRefCountsVisitor(Compiler* compiler);
10366     Compiler::fgWalkResult PreOrderVisit(GenTree** use, GenTree* user);
10367
10368     static Compiler::fgWalkResult WalkTree(Compiler* compiler, GenTree* tree);
10369 };
10370
10371 /*
10372 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10373 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10374 XX                                                                           XX
10375 XX                   Miscellaneous Compiler stuff                            XX
10376 XX                                                                           XX
10377 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10378 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10379 */
10380
10381 // Values used to mark the types a stack slot is used for
10382
10383 const unsigned TYPE_REF_INT      = 0x01; // slot used as a 32-bit int
10384 const unsigned TYPE_REF_LNG      = 0x02; // slot used as a 64-bit long
10385 const unsigned TYPE_REF_FLT      = 0x04; // slot used as a 32-bit float
10386 const unsigned TYPE_REF_DBL      = 0x08; // slot used as a 64-bit float
10387 const unsigned TYPE_REF_PTR      = 0x10; // slot used as a 32-bit pointer
10388 const unsigned TYPE_REF_BYR      = 0x20; // slot used as a byref pointer
10389 const unsigned TYPE_REF_STC      = 0x40; // slot used as a struct
10390 const unsigned TYPE_REF_TYPEMASK = 0x7F; // bits that represent the type
10391
10392 // const unsigned TYPE_REF_ADDR_TAKEN  = 0x80; // slots address was taken
10393
10394 /*****************************************************************************
10395  *
10396  *  Variables to keep track of total code amounts.
10397  */
10398
10399 #if DISPLAY_SIZES
10400
10401 extern size_t grossVMsize;
10402 extern size_t grossNCsize;
10403 extern size_t totalNCsize;
10404
10405 extern unsigned genMethodICnt;
10406 extern unsigned genMethodNCnt;
10407 extern size_t   gcHeaderISize;
10408 extern size_t   gcPtrMapISize;
10409 extern size_t   gcHeaderNSize;
10410 extern size_t   gcPtrMapNSize;
10411
10412 #endif // DISPLAY_SIZES
10413
10414 /*****************************************************************************
10415  *
10416  *  Variables to keep track of basic block counts (more data on 1 BB methods)
10417  */
10418
10419 #if COUNT_BASIC_BLOCKS
10420 extern Histogram bbCntTable;
10421 extern Histogram bbOneBBSizeTable;
10422 #endif
10423
10424 /*****************************************************************************
10425  *
10426  *  Used by optFindNaturalLoops to gather statistical information such as
10427  *   - total number of natural loops
10428  *   - number of loops with 1, 2, ... exit conditions
10429  *   - number of loops that have an iterator (for like)
10430  *   - number of loops that have a constant iterator
10431  */
10432
10433 #if COUNT_LOOPS
10434
10435 extern unsigned totalLoopMethods;        // counts the total number of methods that have natural loops
10436 extern unsigned maxLoopsPerMethod;       // counts the maximum number of loops a method has
10437 extern unsigned totalLoopOverflows;      // # of methods that identified more loops than we can represent
10438 extern unsigned totalLoopCount;          // counts the total number of natural loops
10439 extern unsigned totalUnnatLoopCount;     // counts the total number of (not-necessarily natural) loops
10440 extern unsigned totalUnnatLoopOverflows; // # of methods that identified more unnatural loops than we can represent
10441 extern unsigned iterLoopCount;           // counts the # of loops with an iterator (for like)
10442 extern unsigned simpleTestLoopCount;     // counts the # of loops with an iterator and a simple loop condition (iter <
10443                                          // const)
10444 extern unsigned  constIterLoopCount;     // counts the # of loops with a constant iterator (for like)
10445 extern bool      hasMethodLoops;         // flag to keep track if we already counted a method as having loops
10446 extern unsigned  loopsThisMethod;        // counts the number of loops in the current method
10447 extern bool      loopOverflowThisMethod; // True if we exceeded the max # of loops in the method.
10448 extern Histogram loopCountTable;         // Histogram of loop counts
10449 extern Histogram loopExitCountTable;     // Histogram of loop exit counts
10450
10451 #endif // COUNT_LOOPS
10452
10453 /*****************************************************************************
10454  * variables to keep track of how many iterations we go in a dataflow pass
10455  */
10456
10457 #if DATAFLOW_ITER
10458
10459 extern unsigned CSEiterCount; // counts the # of iteration for the CSE dataflow
10460 extern unsigned CFiterCount;  // counts the # of iteration for the Const Folding dataflow
10461
10462 #endif // DATAFLOW_ITER
10463
10464 #if MEASURE_BLOCK_SIZE
10465 extern size_t genFlowNodeSize;
10466 extern size_t genFlowNodeCnt;
10467 #endif // MEASURE_BLOCK_SIZE
10468
10469 #if MEASURE_NODE_SIZE
10470 struct NodeSizeStats
10471 {
10472     void Init()
10473     {
10474         genTreeNodeCnt        = 0;
10475         genTreeNodeSize       = 0;
10476         genTreeNodeActualSize = 0;
10477     }
10478
10479     // Count of tree nodes allocated.
10480     unsigned __int64 genTreeNodeCnt;
10481
10482     // The size we allocate.
10483     unsigned __int64 genTreeNodeSize;
10484
10485     // The actual size of the node. Note that the actual size will likely be smaller
10486     // than the allocated size, but we sometimes use SetOper()/ChangeOper() to change
10487     // a smaller node to a larger one. TODO-Cleanup: add stats on
10488     // SetOper()/ChangeOper() usage to quantify this.
10489     unsigned __int64 genTreeNodeActualSize;
10490 };
10491 extern NodeSizeStats genNodeSizeStats;        // Total node size stats
10492 extern NodeSizeStats genNodeSizeStatsPerFunc; // Per-function node size stats
10493 extern Histogram     genTreeNcntHist;
10494 extern Histogram     genTreeNsizHist;
10495 #endif // MEASURE_NODE_SIZE
10496
10497 /*****************************************************************************
10498  *  Count fatal errors (including noway_asserts).
10499  */
10500
10501 #if MEASURE_FATAL
10502 extern unsigned fatal_badCode;
10503 extern unsigned fatal_noWay;
10504 extern unsigned fatal_NOMEM;
10505 extern unsigned fatal_noWayAssertBody;
10506 #ifdef DEBUG
10507 extern unsigned fatal_noWayAssertBodyArgs;
10508 #endif // DEBUG
10509 extern unsigned fatal_NYI;
10510 #endif // MEASURE_FATAL
10511
10512 /*****************************************************************************
10513  * Codegen
10514  */
10515
10516 #ifdef _TARGET_XARCH_
10517
10518 const instruction INS_SHIFT_LEFT_LOGICAL  = INS_shl;
10519 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_shr;
10520 const instruction INS_SHIFT_RIGHT_ARITHM  = INS_sar;
10521
10522 const instruction INS_AND             = INS_and;
10523 const instruction INS_OR              = INS_or;
10524 const instruction INS_XOR             = INS_xor;
10525 const instruction INS_NEG             = INS_neg;
10526 const instruction INS_TEST            = INS_test;
10527 const instruction INS_MUL             = INS_imul;
10528 const instruction INS_SIGNED_DIVIDE   = INS_idiv;
10529 const instruction INS_UNSIGNED_DIVIDE = INS_div;
10530 const instruction INS_BREAKPOINT      = INS_int3;
10531 const instruction INS_ADDC            = INS_adc;
10532 const instruction INS_SUBC            = INS_sbb;
10533 const instruction INS_NOT             = INS_not;
10534
10535 #endif // _TARGET_XARCH_
10536
10537 #ifdef _TARGET_ARM_
10538
10539 const instruction INS_SHIFT_LEFT_LOGICAL  = INS_lsl;
10540 const instruction INS_SHIFT_RIGHT_LOGICAL = INS_lsr;
10541 const instruction INS_SHIFT_RIGHT_ARITHM  = INS_asr;
10542
10543 const instruction INS_AND             = INS_and;
10544 const instruction INS_OR              = INS_orr;
10545 const instruction INS_XOR             = INS_eor;
10546 const instruction INS_NEG             = INS_rsb;
10547 const instruction INS_TEST            = INS_tst;
10548 const instruction INS_MUL             = INS_mul;
10549 const instruction INS_MULADD          = INS_mla;
10550 const instruction INS_SIGNED_DIVIDE   = INS_sdiv;
10551 const instruction INS_UNSIGNED_DIVIDE = INS_udiv;
10552 const instruction INS_BREAKPOINT      = INS_bkpt;
10553 const instruction INS_ADDC            = INS_adc;
10554 const instruction INS_SUBC            = INS_sbc;
10555 const instruction INS_NOT             = INS_mvn;
10556
10557 const instruction INS_ABS  = INS_vabs;
10558 const instruction INS_SQRT = INS_vsqrt;
10559
10560 #endif // _TARGET_ARM_
10561
10562 #ifdef _TARGET_ARM64_
10563
10564 const instruction INS_MULADD     = INS_madd;
10565 const instruction INS_BREAKPOINT = INS_bkpt;
10566
10567 const instruction INS_ABS  = INS_fabs;
10568 const instruction INS_SQRT = INS_fsqrt;
10569
10570 #endif // _TARGET_ARM64_
10571
10572 /*****************************************************************************/
10573
10574 extern const BYTE genTypeSizes[];
10575 extern const BYTE genTypeAlignments[];
10576 extern const BYTE genTypeStSzs[];
10577 extern const BYTE genActualTypes[];
10578
10579 /*****************************************************************************/
10580
10581 // VERY_LARGE_FRAME_SIZE_REG_MASK is the set of registers we need to use for
10582 // the probing loop generated for very large stack frames (see `getVeryLargeFrameSize`).
10583
10584 #ifdef _TARGET_ARM_
10585 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R4 | RBM_R5 | RBM_R6)
10586 #elif defined(_TARGET_ARM64_)
10587 #define VERY_LARGE_FRAME_SIZE_REG_MASK (RBM_R9 | RBM_R10 | RBM_R11)
10588 #endif
10589
10590 /*****************************************************************************/
10591
10592 #define REG_CORRUPT regNumber(REG_NA + 1)
10593 #define RBM_CORRUPT (RBM_ILLEGAL | regMaskTP(1))
10594 #define REG_PAIR_CORRUPT regPairNo(REG_PAIR_NONE + 1)
10595
10596 /*****************************************************************************/
10597
10598 extern BasicBlock dummyBB;
10599
10600 /*****************************************************************************/
10601 /*****************************************************************************/
10602
10603 // foreach_treenode_execution_order: An iterator that iterates through all the tree
10604 // nodes of a statement in execution order.
10605 //      __stmt: a GT_STMT type GenTree*
10606 //      __node: a GenTree*, already declared, that gets updated with each node in the statement, in execution order
10607
10608 #define foreach_treenode_execution_order(__node, __stmt)                                                               \
10609     for ((__node) = (__stmt)->gtStmt.gtStmtList; (__node); (__node) = (__node)->gtNext)
10610
10611 // foreach_block: An iterator over all blocks in the function.
10612 //    __compiler: the Compiler* object
10613 //    __block   : a BasicBlock*, already declared, that gets updated each iteration.
10614
10615 #define foreach_block(__compiler, __block)                                                                             \
10616     for ((__block) = (__compiler)->fgFirstBB; (__block); (__block) = (__block)->bbNext)
10617
10618 /*****************************************************************************/
10619 /*****************************************************************************/
10620
10621 #ifdef DEBUG
10622
10623 void dumpConvertedVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10624
10625 /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10626 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10627 XX                                                                           XX
10628 XX                          Debugging helpers                                XX
10629 XX                                                                           XX
10630 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10631 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
10632 */
10633
10634 /*****************************************************************************/
10635 /* The following functions are intended to be called from the debugger, to dump
10636  * various data structures. The can be used in the debugger Watch or Quick Watch
10637  * windows. They are designed to be short to type and take as few arguments as
10638  * possible. The 'c' versions take a Compiler*, whereas the 'd' versions use the TlsCompiler.
10639  * See the function definition comment for more details.
10640  */
10641
10642 void cBlock(Compiler* comp, BasicBlock* block);
10643 void cBlocks(Compiler* comp);
10644 void cBlocksV(Compiler* comp);
10645 void cTree(Compiler* comp, GenTree* tree);
10646 void cTrees(Compiler* comp);
10647 void cEH(Compiler* comp);
10648 void cVar(Compiler* comp, unsigned lclNum);
10649 void cVarDsc(Compiler* comp, LclVarDsc* varDsc);
10650 void cVars(Compiler* comp);
10651 void cVarsFinal(Compiler* comp);
10652 void cBlockPreds(Compiler* comp, BasicBlock* block);
10653 void cReach(Compiler* comp);
10654 void cDoms(Compiler* comp);
10655 void cLiveness(Compiler* comp);
10656 void cCVarSet(Compiler* comp, VARSET_VALARG_TP vars);
10657
10658 void cFuncIR(Compiler* comp);
10659 void cBlockIR(Compiler* comp, BasicBlock* block);
10660 void cLoopIR(Compiler* comp, Compiler::LoopDsc* loop);
10661 void cTreeIR(Compiler* comp, GenTree* tree);
10662 int cTreeTypeIR(Compiler* comp, GenTree* tree);
10663 int cTreeKindsIR(Compiler* comp, GenTree* tree);
10664 int cTreeFlagsIR(Compiler* comp, GenTree* tree);
10665 int cOperandIR(Compiler* comp, GenTree* operand);
10666 int cLeafIR(Compiler* comp, GenTree* tree);
10667 int cIndirIR(Compiler* comp, GenTree* tree);
10668 int cListIR(Compiler* comp, GenTree* list);
10669 int cSsaNumIR(Compiler* comp, GenTree* tree);
10670 int cValNumIR(Compiler* comp, GenTree* tree);
10671 int cDependsIR(Compiler* comp, GenTree* comma, bool* first);
10672
10673 void dBlock(BasicBlock* block);
10674 void dBlocks();
10675 void dBlocksV();
10676 void dTree(GenTree* tree);
10677 void dTrees();
10678 void dEH();
10679 void dVar(unsigned lclNum);
10680 void dVarDsc(LclVarDsc* varDsc);
10681 void dVars();
10682 void dVarsFinal();
10683 void dBlockPreds(BasicBlock* block);
10684 void dReach();
10685 void dDoms();
10686 void dLiveness();
10687 void dCVarSet(VARSET_VALARG_TP vars);
10688
10689 void dVarSet(VARSET_VALARG_TP vars);
10690 void dRegMask(regMaskTP mask);
10691
10692 void dFuncIR();
10693 void dBlockIR(BasicBlock* block);
10694 void dTreeIR(GenTree* tree);
10695 void dLoopIR(Compiler::LoopDsc* loop);
10696 void dLoopNumIR(unsigned loopNum);
10697 int dTabStopIR(int curr, int tabstop);
10698 int dTreeTypeIR(GenTree* tree);
10699 int dTreeKindsIR(GenTree* tree);
10700 int dTreeFlagsIR(GenTree* tree);
10701 int dOperandIR(GenTree* operand);
10702 int dLeafIR(GenTree* tree);
10703 int dIndirIR(GenTree* tree);
10704 int dListIR(GenTree* list);
10705 int dSsaNumIR(GenTree* tree);
10706 int dValNumIR(GenTree* tree);
10707 int dDependsIR(GenTree* comma);
10708 void dFormatIR();
10709
10710 GenTree* dFindTree(GenTree* tree, unsigned id);
10711 GenTree* dFindTree(unsigned id);
10712 GenTreeStmt* dFindStmt(unsigned id);
10713 BasicBlock* dFindBlock(unsigned bbNum);
10714
10715 #endif // DEBUG
10716
10717 #include "compiler.hpp" // All the shared inline functions
10718
10719 /*****************************************************************************/
10720 #endif //_COMPILER_H_
10721 /*****************************************************************************/