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