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