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