Merge pull request #14658 from mikedn/legacy-reg-track
[platform/upstream/coreclr.git] / src / jit / emit.cpp
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                              emit.cpp                                     XX
9 XX                                                                           XX
10 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
11 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
12 */
13
14 #include "jitpch.h"
15 #ifdef _MSC_VER
16 #pragma hdrstop
17 #endif
18
19 #include "hostallocator.h"
20 #include "instr.h"
21 #include "emit.h"
22 #include "codegen.h"
23
24 /*****************************************************************************
25  *
26  *  Represent an emitter location.
27  */
28
29 void emitLocation::CaptureLocation(emitter* emit)
30 {
31     ig      = emit->emitCurIG;
32     codePos = emit->emitCurOffset();
33
34     assert(Valid());
35 }
36
37 bool emitLocation::IsCurrentLocation(emitter* emit) const
38 {
39     assert(Valid());
40     return (ig == emit->emitCurIG) && (codePos == emit->emitCurOffset());
41 }
42
43 UNATIVE_OFFSET emitLocation::CodeOffset(emitter* emit) const
44 {
45     assert(Valid());
46     return emit->emitCodeOffset(ig, codePos);
47 }
48
49 int emitLocation::GetInsNum() const
50 {
51     return emitGetInsNumFromCodePos(codePos);
52 }
53
54 #ifdef _TARGET_AMD64_
55 // Get the instruction offset in the current instruction group, which must be a funclet prolog group.
56 // This is used to find an instruction offset used in unwind data.
57 // TODO-AMD64-Bug?: We only support a single main function prolog group, but allow for multiple funclet prolog
58 // groups (not that we actually use that flexibility, since the funclet prolog will be small). How to
59 // handle that?
60 UNATIVE_OFFSET emitLocation::GetFuncletPrologOffset(emitter* emit) const
61 {
62     assert(ig->igFuncIdx != 0);
63     assert((ig->igFlags & IGF_FUNCLET_PROLOG) != 0);
64     assert(ig == emit->emitCurIG);
65
66     return emit->emitCurIGsize;
67 }
68 #endif // _TARGET_AMD64_
69
70 #ifdef DEBUG
71 void emitLocation::Print() const
72 {
73     unsigned insNum = emitGetInsNumFromCodePos(codePos);
74     unsigned insOfs = emitGetInsOfsFromCodePos(codePos);
75     printf("(G_M%03u_IG%02u,ins#%d,ofs#%d)", Compiler::s_compMethodsCount, ig->igNum, insNum, insOfs);
76 }
77 #endif // DEBUG
78
79 /*****************************************************************************
80  *
81  *  Return the name of an instruction format.
82  */
83
84 #if defined(DEBUG) || EMITTER_STATS
85
86 const char* emitter::emitIfName(unsigned f)
87 {
88     static const char* const ifNames[] = {
89 #define IF_DEF(en, op1, op2) "IF_" #en,
90 #include "emitfmts.h"
91     };
92
93     static char errBuff[32];
94
95     if (f < sizeof(ifNames) / sizeof(*ifNames))
96     {
97         return ifNames[f];
98     }
99
100     sprintf_s(errBuff, sizeof(errBuff), "??%u??", f);
101     return errBuff;
102 }
103
104 #endif
105
106 #ifdef TRANSLATE_PDB
107
108 /* these are protected */
109
110 AddrMap*  emitter::emitPDBOffsetTable = 0;
111 LocalMap* emitter::emitPDBLocalTable  = 0;
112 bool      emitter::emitIsPDBEnabled   = true;
113 BYTE*     emitter::emitILBaseOfCode   = 0;
114 BYTE*     emitter::emitILMethodBase   = 0;
115 BYTE*     emitter::emitILMethodStart  = 0;
116 BYTE*     emitter::emitImgBaseOfCode  = 0;
117
118 void emitter::MapCode(int ilOffset, BYTE* imgDest)
119 {
120     if (emitIsPDBEnabled)
121     {
122         emitPDBOffsetTable->MapSrcToDest(ilOffset, (int)(imgDest - emitImgBaseOfCode));
123     }
124 }
125
126 void emitter::MapFunc(int                imgOff,
127                       int                procLen,
128                       int                dbgStart,
129                       int                dbgEnd,
130                       short              frameReg,
131                       int                stkAdjust,
132                       int                lvaCount,
133                       OptJit::LclVarDsc* lvaTable,
134                       bool               framePtr)
135 {
136     if (emitIsPDBEnabled)
137     {
138         // this code stores information about local symbols for the PDB translation
139
140         assert(lvaCount >= 0); // don't allow a negative count
141
142         LvaDesc* rgLvaDesc = 0;
143
144         if (lvaCount > 0)
145         {
146             rgLvaDesc = new LvaDesc[lvaCount];
147
148             if (!rgLvaDesc)
149             {
150                 NOMEM();
151             }
152
153             LvaDesc*           pDst = rgLvaDesc;
154             OptJit::LclVarDsc* pSrc = lvaTable;
155             for (int i = 0; i < lvaCount; ++i, ++pDst, ++pSrc)
156             {
157                 pDst->slotNum = pSrc->lvSlotNum;
158                 pDst->isReg   = pSrc->lvRegister;
159                 pDst->reg     = (pSrc->lvRegister ? pSrc->lvRegNum : frameReg);
160                 pDst->off     = pSrc->lvStkOffs + stkAdjust;
161             }
162         }
163
164         emitPDBLocalTable->AddFunc((int)(emitILMethodBase - emitILBaseOfCode), imgOff - (int)emitImgBaseOfCode, procLen,
165                                    dbgStart - imgOff, dbgEnd - imgOff, lvaCount, rgLvaDesc, framePtr);
166         // do not delete rgLvaDesc here -- responsibility is now on emitPDBLocalTable destructor
167     }
168 }
169
170 /* these are public */
171
172 void emitter::SetILBaseOfCode(BYTE* pTextBase)
173 {
174     emitILBaseOfCode = pTextBase;
175 }
176
177 void emitter::SetILMethodBase(BYTE* pMethodEntry)
178 {
179     emitILMethodBase = pMethodEntry;
180 }
181
182 void emitter::SetILMethodStart(BYTE* pMethodCode)
183 {
184     emitILMethodStart = pMethodCode;
185 }
186
187 void emitter::SetImgBaseOfCode(BYTE* pTextBase)
188 {
189     emitImgBaseOfCode = pTextBase;
190 }
191
192 void emitter::SetIDBaseToProlog()
193 {
194     emitInstrDescILBase = (int)(emitILMethodBase - emitILBaseOfCode);
195 }
196
197 void emitter::SetIDBaseToOffset(int methodOffset)
198 {
199     emitInstrDescILBase = methodOffset + (int)(emitILMethodStart - emitILBaseOfCode);
200 }
201
202 void emitter::DisablePDBTranslation()
203 {
204     // this function should disable PDB translation code
205     emitIsPDBEnabled = false;
206 }
207
208 bool emitter::IsPDBEnabled()
209 {
210     return emitIsPDBEnabled;
211 }
212
213 void emitter::InitTranslationMaps(int ilCodeSize)
214 {
215     if (emitIsPDBEnabled)
216     {
217         emitPDBOffsetTable = AddrMap::Create(ilCodeSize);
218         emitPDBLocalTable  = LocalMap::Create();
219     }
220 }
221
222 void emitter::DeleteTranslationMaps()
223 {
224     if (emitPDBOffsetTable)
225     {
226         delete emitPDBOffsetTable;
227         emitPDBOffsetTable = 0;
228     }
229     if (emitPDBLocalTable)
230     {
231         delete emitPDBLocalTable;
232         emitPDBLocalTable = 0;
233     }
234 }
235
236 void emitter::InitTranslator(PDBRewriter* pPDB, int* rgSecMap, IMAGE_SECTION_HEADER** rgpHeader, int numSections)
237 {
238     if (emitIsPDBEnabled)
239     {
240         pPDB->InitMaps(rgSecMap,           // new PE section header order
241                        rgpHeader,          // array of section headers
242                        numSections,        // number of sections
243                        emitPDBOffsetTable, // code offset translation table
244                        emitPDBLocalTable); // slot variable translation table
245     }
246 }
247
248 #endif // TRANSLATE_PDB
249
250 /*****************************************************************************/
251
252 #if EMITTER_STATS
253
254 static unsigned totAllocdSize;
255 static unsigned totActualSize;
256
257 unsigned emitter::emitIFcounts[emitter::IF_COUNT];
258
259 static unsigned  emitSizeBuckets[] = {100, 1024 * 1, 1024 * 2, 1024 * 3, 1024 * 4, 1024 * 5, 1024 * 10, 0};
260 static Histogram emitSizeTable(HostAllocator::getHostAllocator(), emitSizeBuckets);
261
262 static unsigned  GCrefsBuckets[] = {0, 1, 2, 5, 10, 20, 50, 128, 256, 512, 1024, 0};
263 static Histogram GCrefsTable(HostAllocator::getHostAllocator(), GCrefsBuckets);
264
265 static unsigned  stkDepthBuckets[] = {0, 1, 2, 5, 10, 16, 32, 128, 1024, 0};
266 static Histogram stkDepthTable(HostAllocator::getHostAllocator(), stkDepthBuckets);
267
268 size_t emitter::emitSizeMethod;
269
270 size_t   emitter::emitTotMemAlloc;
271 unsigned emitter::emitTotalInsCnt;
272 unsigned emitter::emitTotalIGcnt;
273 unsigned emitter::emitTotalPhIGcnt;
274 unsigned emitter::emitTotalIGjmps;
275 unsigned emitter::emitTotalIGptrs;
276 unsigned emitter::emitTotalIGicnt;
277 size_t   emitter::emitTotalIGsize;
278 unsigned emitter::emitTotalIGmcnt;
279
280 unsigned emitter::emitSmallDspCnt;
281 unsigned emitter::emitLargeDspCnt;
282
283 unsigned emitter::emitSmallCnsCnt;
284 unsigned emitter::emitLargeCnsCnt;
285 unsigned emitter::emitSmallCns[SMALL_CNS_TSZ];
286
287 void emitterStaticStats(FILE* fout)
288 {
289     // insGroup members
290
291     fprintf(fout, "\n");
292     fprintf(fout, "insGroup:\n");
293     fprintf(fout, "Offset of igNext              = %2u\n", offsetof(insGroup, igNext));
294 #ifdef DEBUG
295     fprintf(fout, "Offset of igSelf              = %2u\n", offsetof(insGroup, igSelf));
296 #endif
297     fprintf(fout, "Offset of igNum               = %2u\n", offsetof(insGroup, igNum));
298     fprintf(fout, "Offset of igOffs              = %2u\n", offsetof(insGroup, igOffs));
299     fprintf(fout, "Offset of igFuncIdx           = %2u\n", offsetof(insGroup, igFuncIdx));
300     fprintf(fout, "Offset of igFlags             = %2u\n", offsetof(insGroup, igFlags));
301     fprintf(fout, "Offset of igSize              = %2u\n", offsetof(insGroup, igSize));
302     fprintf(fout, "Offset of igData              = %2u\n", offsetof(insGroup, igData));
303 #if EMIT_TRACK_STACK_DEPTH
304     fprintf(fout, "Offset of igStkLvl            = %2u\n", offsetof(insGroup, igStkLvl));
305 #endif
306     fprintf(fout, "Offset of igGCregs            = %2u\n", offsetof(insGroup, igGCregs));
307     fprintf(fout, "Offset of igInsCnt            = %2u\n", offsetof(insGroup, igInsCnt));
308     fprintf(fout, "Size   of insGroup            = %u\n", sizeof(insGroup));
309
310     // insPlaceholderGroupData members
311
312     fprintf(fout, "\n");
313     fprintf(fout, "insPlaceholderGroupData:\n");
314     fprintf(fout, "Offset of igPhNext                = %2u\n", offsetof(insPlaceholderGroupData, igPhNext));
315     fprintf(fout, "Offset of igPhBB                  = %2u\n", offsetof(insPlaceholderGroupData, igPhBB));
316     fprintf(fout, "Offset of igPhInitGCrefVars       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitGCrefVars));
317     fprintf(fout, "Offset of igPhInitGCrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitGCrefRegs));
318     fprintf(fout, "Offset of igPhInitByrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhInitByrefRegs));
319     fprintf(fout, "Offset of igPhPrevGCrefVars       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevGCrefVars));
320     fprintf(fout, "Offset of igPhPrevGCrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevGCrefRegs));
321     fprintf(fout, "Offset of igPhPrevByrefRegs       = %2u\n", offsetof(insPlaceholderGroupData, igPhPrevByrefRegs));
322     fprintf(fout, "Offset of igPhType                = %2u\n", offsetof(insPlaceholderGroupData, igPhType));
323     fprintf(fout, "Size   of insPlaceholderGroupData = %u\n", sizeof(insPlaceholderGroupData));
324
325     fprintf(fout, "\n");
326     fprintf(fout, "Size   of tinyID      = %2u\n", TINY_IDSC_SIZE);
327     fprintf(fout, "Size   of instrDesc   = %2u\n", sizeof(emitter::instrDesc));
328     // fprintf(fout, "Offset of _idIns      = %2u\n", offsetof(emitter::instrDesc, _idIns      ));
329     // fprintf(fout, "Offset of _idInsFmt   = %2u\n", offsetof(emitter::instrDesc, _idInsFmt   ));
330     // fprintf(fout, "Offset of _idOpSize   = %2u\n", offsetof(emitter::instrDesc, _idOpSize   ));
331     // fprintf(fout, "Offset of idSmallCns  = %2u\n", offsetof(emitter::instrDesc, idSmallCns  ));
332     // fprintf(fout, "Offset of _idAddrUnion= %2u\n", offsetof(emitter::instrDesc, _idAddrUnion));
333     // fprintf(fout, "\n");
334     // fprintf(fout, "Size   of _idAddrUnion= %2u\n", sizeof(((emitter::instrDesc*)0)->_idAddrUnion));
335
336     fprintf(fout, "\n");
337     fprintf(fout, "GCInfo::regPtrDsc:\n");
338     fprintf(fout, "Offset of rpdNext           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdNext));
339     fprintf(fout, "Offset of rpdOffs           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdOffs));
340     fprintf(fout, "Offset of <union>           = %2u\n", offsetof(GCInfo::regPtrDsc, rpdPtrArg));
341     fprintf(fout, "Size   of GCInfo::regPtrDsc = %2u\n", sizeof(GCInfo::regPtrDsc));
342
343     fprintf(fout, "\n");
344 }
345
346 void emitterStats(FILE* fout)
347 {
348     if (totAllocdSize > 0)
349     {
350         assert(totActualSize <= totAllocdSize);
351
352         fprintf(fout, "\nTotal allocated code size = %u\n", totAllocdSize);
353
354         if (totActualSize < totAllocdSize)
355         {
356             fprintf(fout, "Total generated code size = %u  ", totActualSize);
357
358             fprintf(fout, "(%4.3f%% waste)", 100 * ((totAllocdSize - totActualSize) / (double)totActualSize));
359             fprintf(fout, "\n");
360         }
361
362         assert(emitter::emitTotalInsCnt);
363
364         fprintf(fout, "Average of %4.2f bytes of code generated per instruction\n",
365                 (double)totActualSize / emitter::emitTotalInsCnt);
366     }
367
368     fprintf(fout, "\nInstruction format frequency table:\n\n");
369
370     unsigned f, ic = 0, dc = 0;
371
372     for (f = 0; f < emitter::IF_COUNT; f++)
373     {
374         ic += emitter::emitIFcounts[f];
375     }
376
377     for (f = 0; f < emitter::IF_COUNT; f++)
378     {
379         unsigned c = emitter::emitIFcounts[f];
380
381         if ((c > 0) && (1000 * c >= ic))
382         {
383             dc += c;
384             fprintf(fout, "          %-13s %8u (%5.2f%%)\n", emitter::emitIfName(f), c, 100.0 * c / ic);
385         }
386     }
387
388     fprintf(fout, "         --------------------------------\n");
389     fprintf(fout, "          %-13s %8u (%5.2f%%)\n", "Total shown", dc, 100.0 * dc / ic);
390
391     if (emitter::emitTotalIGmcnt)
392     {
393         fprintf(fout, "Total of %8u methods\n", emitter::emitTotalIGmcnt);
394         fprintf(fout, "Total of %8u insGroup\n", emitter::emitTotalIGcnt);
395         fprintf(fout, "Total of %8u insPlaceholderGroupData\n", emitter::emitTotalPhIGcnt);
396         fprintf(fout, "Total of %8u instructions\n", emitter::emitTotalIGicnt);
397         fprintf(fout, "Total of %8u jumps\n", emitter::emitTotalIGjmps);
398         fprintf(fout, "Total of %8u GC livesets\n", emitter::emitTotalIGptrs);
399         fprintf(fout, "\n");
400         fprintf(fout, "Average of %8.1lf insGroup     per method\n",
401                 (double)emitter::emitTotalIGcnt / emitter::emitTotalIGmcnt);
402         fprintf(fout, "Average of %8.1lf insPhGroup   per method\n",
403                 (double)emitter::emitTotalPhIGcnt / emitter::emitTotalIGmcnt);
404         fprintf(fout, "Average of %8.1lf instructions per method\n",
405                 (double)emitter::emitTotalIGicnt / emitter::emitTotalIGmcnt);
406         fprintf(fout, "Average of %8.1lf desc.  bytes per method\n",
407                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGmcnt);
408         fprintf(fout, "Average of %8.1lf jumps        per method\n",
409                 (double)emitter::emitTotalIGjmps / emitter::emitTotalIGmcnt);
410         fprintf(fout, "Average of %8.1lf GC livesets  per method\n",
411                 (double)emitter::emitTotalIGptrs / emitter::emitTotalIGmcnt);
412         fprintf(fout, "\n");
413         fprintf(fout, "Average of %8.1lf instructions per group \n",
414                 (double)emitter::emitTotalIGicnt / emitter::emitTotalIGcnt);
415         fprintf(fout, "Average of %8.1lf desc.  bytes per group \n",
416                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGcnt);
417         fprintf(fout, "Average of %8.1lf jumps        per group \n",
418                 (double)emitter::emitTotalIGjmps / emitter::emitTotalIGcnt);
419         fprintf(fout, "\n");
420         fprintf(fout, "Average of %8.1lf bytes        per instrDesc\n",
421                 (double)emitter::emitTotalIGsize / emitter::emitTotalIGicnt);
422         fprintf(fout, "\n");
423         fprintf(fout, "A total of %8u desc.  bytes\n", emitter::emitTotalIGsize);
424         fprintf(fout, "\n");
425     }
426
427     fprintf(fout, "Descriptor size distribution:\n");
428     emitSizeTable.dump(fout);
429     fprintf(fout, "\n");
430
431     fprintf(fout, "GC ref frame variable counts:\n");
432     GCrefsTable.dump(fout);
433     fprintf(fout, "\n");
434
435     fprintf(fout, "Max. stack depth distribution:\n");
436     stkDepthTable.dump(fout);
437     fprintf(fout, "\n");
438
439     int      i;
440     unsigned c;
441     unsigned m;
442
443     if (emitter::emitSmallCnsCnt || emitter::emitLargeCnsCnt)
444     {
445         fprintf(fout, "SmallCnsCnt = %6u\n", emitter::emitSmallCnsCnt);
446         fprintf(fout, "LargeCnsCnt = %6u (%3u %% of total)\n", emitter::emitLargeCnsCnt,
447                 100 * emitter::emitLargeCnsCnt / (emitter::emitLargeCnsCnt + emitter::emitSmallCnsCnt));
448     }
449
450 #if 0
451     // TODO-Cleanup: WHy is this in #if 0 - Is EMITTER_STATS ever used? Fix or delete this.
452     if  (emitter::emitSmallCnsCnt)
453     {
454         fprintf(fout, "\n");
455
456         m = emitter::emitSmallCnsCnt/1000 + 1;
457
458         for (i = ID_MIN_SMALL_CNS; i < ID_MAX_SMALL_CNS; i++)
459         {
460             c = emitter::emitSmallCns[i-ID_MIN_SMALL_CNS];
461             if  (c >= m)
462                 fprintf(fout, "cns[%4d] = %u\n", i, c);
463         }
464     }
465 #endif // 0
466
467     fprintf(fout, "%8u bytes allocated in the emitter\n", emitter::emitTotMemAlloc);
468 }
469
470 #endif // EMITTER_STATS
471
472 /*****************************************************************************/
473
474 const unsigned short emitTypeSizes[] = {
475 #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) sze,
476 #include "typelist.h"
477 #undef DEF_TP
478 };
479
480 const unsigned short emitTypeActSz[] = {
481 #define DEF_TP(tn, nm, jitType, verType, sz, sze, asze, st, al, tf, howUsed) asze,
482 #include "typelist.h"
483 #undef DEF_TP
484 };
485
486 /*****************************************************************************/
487 /*****************************************************************************
488  *
489  *  Initialize the emitter - called once, at DLL load time.
490  */
491
492 void emitter::emitInit()
493 {
494 }
495
496 /*****************************************************************************
497  *
498  *  Shut down the emitter - called once, at DLL exit time.
499  */
500
501 void emitter::emitDone()
502 {
503 }
504
505 /*****************************************************************************
506  *
507  *  Allocate memory.
508  */
509
510 void* emitter::emitGetMem(size_t sz)
511 {
512     assert(sz % sizeof(int) == 0);
513
514 #if EMITTER_STATS
515     emitTotMemAlloc += sz;
516 #endif
517
518     return emitComp->compGetMem(sz, CMK_InstDesc);
519 }
520
521 /*****************************************************************************
522  *
523  *  emitLclVarAddr support methods
524  */
525 void emitLclVarAddr::initLclVarAddr(int varNum, unsigned offset)
526 {
527     if (varNum < 32768)
528     {
529         if (varNum >= 0)
530         {
531             if (offset < 32768)
532             {
533                 _lvaTag    = LVA_STANDARD_ENCODING;
534                 _lvaExtra  = offset;           // offset known to be in [0..32767]
535                 _lvaVarNum = (unsigned)varNum; // varNum known to be in [0..32767]
536             }
537             else // offset >= 32768
538             {
539                 // We could support larger local offsets here at the cost of less varNums
540                 if (offset >= 65536)
541                 {
542                     IMPL_LIMITATION("JIT doesn't support offsets larger than 65535 into valuetypes\n");
543                 }
544
545                 _lvaTag    = LVA_LARGE_OFFSET;
546                 _lvaExtra  = (offset - 32768); // (offset-32768) is known to be in [0..32767]
547                 _lvaVarNum = (unsigned)varNum; // varNum known to be in [0..32767]
548             }
549         }
550         else // varNum < 0, These are used for Compiler spill temps
551         {
552             if (varNum < -32767)
553             {
554                 IMPL_LIMITATION("JIT doesn't support more than 32767 Compiler Spill temps\n");
555             }
556             if (offset > 32767)
557             {
558                 IMPL_LIMITATION(
559                     "JIT doesn't support offsets larger than 32767 into valuetypes for Compiler Spill temps\n");
560             }
561
562             _lvaTag    = LVA_COMPILER_TEMP;
563             _lvaExtra  = offset;              //  offset known to be in [0..32767]
564             _lvaVarNum = (unsigned)(-varNum); // -varNum known to be in [1..32767]
565         }
566     }
567     else // varNum >= 32768
568     {
569         if (offset >= 256)
570         {
571             IMPL_LIMITATION("JIT doesn't support offsets larger than 255 into valuetypes for local vars > 32767\n");
572         }
573         if (varNum >= 0x00400000)
574         { // 0x00400000 == 2^22
575             IMPL_LIMITATION("JIT doesn't support more than 2^22 variables\n");
576         }
577
578         _lvaTag    = LVA_LARGE_VARNUM;
579         _lvaVarNum = varNum & 0x00007FFF;         // varNum bits 14 to 0
580         _lvaExtra  = (varNum & 0x003F8000) >> 15; // varNum bits 21 to 15 in _lvaExtra bits  6 to 0, 7 bits total
581         _lvaExtra |= (offset << 7);               // offset bits  7 to 0  in _lvaExtra bits 14 to 7, 8 bits total
582     }
583 }
584
585 // Returns the variable to access. Note that it returns a negative number for compiler spill temps.
586 int emitLclVarAddr::lvaVarNum()
587 {
588     switch (_lvaTag)
589     {
590         case LVA_COMPILER_TEMP:
591             return -((int)_lvaVarNum);
592         case LVA_LARGE_VARNUM:
593             return (int)(((_lvaExtra & 0x007F) << 15) + _lvaVarNum);
594         default: // LVA_STANDARD_ENCODING or LVA_LARGE_OFFSET
595             assert((_lvaTag == LVA_STANDARD_ENCODING) || (_lvaTag == LVA_LARGE_OFFSET));
596             return (int)_lvaVarNum;
597     }
598 }
599
600 unsigned emitLclVarAddr::lvaOffset() // returns the offset into the variable to access
601 {
602     switch (_lvaTag)
603     {
604         case LVA_LARGE_OFFSET:
605             return (32768 + _lvaExtra);
606         case LVA_LARGE_VARNUM:
607             return (_lvaExtra & 0x7F80) >> 7;
608         default: // LVA_STANDARD_ENCODING or LVA_COMPILER_TEMP
609             assert((_lvaTag == LVA_STANDARD_ENCODING) || (_lvaTag == LVA_COMPILER_TEMP));
610             return _lvaExtra;
611     }
612 }
613
614 /*****************************************************************************
615  *
616  *  Record some info about the method about to be emitted.
617  */
618
619 void emitter::emitBegCG(Compiler* comp, COMP_HANDLE cmpHandle)
620 {
621     emitComp      = comp;
622     emitCmpHandle = cmpHandle;
623 }
624
625 void emitter::emitEndCG()
626 {
627 }
628
629 /*****************************************************************************
630  *
631  *  Prepare the given IG for emission of code.
632  */
633
634 void emitter::emitGenIG(insGroup* ig)
635 {
636     /* Set the "current IG" value */
637
638     emitCurIG = ig;
639
640 #if EMIT_TRACK_STACK_DEPTH
641
642     /* Record the stack level on entry to this group */
643
644     ig->igStkLvl = emitCurStackLvl;
645
646     // If we don't have enough bits in igStkLvl, refuse to compile
647
648     if (ig->igStkLvl != emitCurStackLvl)
649     {
650         IMPL_LIMITATION("Too many arguments pushed on stack");
651     }
652
653 //  printf("Start IG #%02u [stk=%02u]\n", ig->igNum, emitCurStackLvl);
654
655 #endif
656
657     if (emitNoGCIG)
658     {
659         ig->igFlags |= IGF_NOGCINTERRUPT;
660     }
661
662     /* Prepare to issue instructions */
663
664     emitCurIGinsCnt = 0;
665     emitCurIGsize   = 0;
666
667     assert(emitCurIGjmpList == nullptr);
668
669     /* Allocate the temp instruction buffer if we haven't done so */
670
671     if (emitCurIGfreeBase == nullptr)
672     {
673         emitIGbuffSize    = SC_IG_BUFFER_SIZE;
674         emitCurIGfreeBase = (BYTE*)emitGetMem(emitIGbuffSize);
675     }
676
677     emitCurIGfreeNext = emitCurIGfreeBase;
678     emitCurIGfreeEndp = emitCurIGfreeBase + emitIGbuffSize;
679 }
680
681 /*****************************************************************************
682  *
683  *  Finish and save the current IG.
684  */
685
686 insGroup* emitter::emitSavIG(bool emitAdd)
687 {
688     insGroup* ig;
689     BYTE*     id;
690
691     size_t sz;
692     size_t gs;
693
694     assert(emitCurIGfreeNext <= emitCurIGfreeEndp);
695
696     /* Get hold of the IG descriptor */
697
698     ig = emitCurIG;
699     assert(ig);
700
701     /* Compute how much code we've generated */
702
703     sz = emitCurIGfreeNext - emitCurIGfreeBase;
704
705     /* Compute the total size we need to allocate */
706
707     gs = roundUp(sz);
708
709     /* Do we need space for GC? */
710
711     if (!(ig->igFlags & IGF_EMIT_ADD))
712     {
713         /* Is the initial set of live GC vars different from the previous one? */
714
715         if (emitForceStoreGCState || !VarSetOps::Equal(emitComp, emitPrevGCrefVars, emitInitGCrefVars))
716         {
717             /* Remember that we will have a new set of live GC variables */
718
719             ig->igFlags |= IGF_GC_VARS;
720
721 #if EMITTER_STATS
722             emitTotalIGptrs++;
723 #endif
724
725             /* We'll allocate extra space to record the liveset */
726
727             gs += sizeof(VARSET_TP);
728         }
729
730         /* Is the initial set of live Byref regs different from the previous one? */
731
732         /* Remember that we will have a new set of live GC variables */
733
734         ig->igFlags |= IGF_BYREF_REGS;
735
736         /* We'll allocate extra space (DWORD aligned) to record the GC regs */
737
738         gs += sizeof(int);
739     }
740
741     /* Allocate space for the instructions and optional liveset */
742
743     id = (BYTE*)emitGetMem(gs);
744
745     /* Do we need to store the byref regs */
746
747     if (ig->igFlags & IGF_BYREF_REGS)
748     {
749         /* Record the byref regs in front the of the instructions */
750
751         *castto(id, unsigned*)++ = (unsigned)emitInitByrefRegs;
752     }
753
754     /* Do we need to store the liveset? */
755
756     if (ig->igFlags & IGF_GC_VARS)
757     {
758         /* Record the liveset in front the of the instructions */
759         VarSetOps::AssignNoCopy(emitComp, (*castto(id, VARSET_TP*)), VarSetOps::MakeEmpty(emitComp));
760         VarSetOps::Assign(emitComp, (*castto(id, VARSET_TP*)++), emitInitGCrefVars);
761     }
762
763     /* Record the collected instructions */
764
765     assert((ig->igFlags & IGF_PLACEHOLDER) == 0);
766     ig->igData = id;
767
768     memcpy(id, emitCurIGfreeBase, sz);
769
770 #ifdef DEBUG
771     if (false && emitComp->verbose) // this is not useful in normal dumps (hence it is normally under if (false)
772     {
773         // If there's an error during emission, we may want to connect the post-copy address
774         // of an instrDesc with the pre-copy address (the one that was originally created).  This
775         // printing enables that.
776         printf("copying instruction group from [0x%x..0x%x) to [0x%x..0x%x).\n", dspPtr(emitCurIGfreeBase),
777                dspPtr(emitCurIGfreeBase + sz), dspPtr(id), dspPtr(id + sz));
778     }
779 #endif
780
781     /* Record how many instructions and bytes of code this group contains */
782
783     noway_assert((BYTE)emitCurIGinsCnt == emitCurIGinsCnt);
784     noway_assert((unsigned short)emitCurIGsize == emitCurIGsize);
785
786     ig->igInsCnt = (BYTE)emitCurIGinsCnt;
787     ig->igSize   = (unsigned short)emitCurIGsize;
788     emitCurCodeOffset += emitCurIGsize;
789     assert(IsCodeAligned(emitCurCodeOffset));
790
791 #if EMITTER_STATS
792     emitTotalIGicnt += emitCurIGinsCnt;
793     emitTotalIGsize += sz;
794     emitSizeMethod += sz;
795 #endif
796
797     // printf("Group [%08X]%3u has %2u instructions (%4u bytes at %08X)\n", ig, ig->igNum, emitCurIGinsCnt, sz, id);
798
799     /* Record the live GC register set - if and only if it is not an emitter added block */
800
801     if (!(ig->igFlags & IGF_EMIT_ADD))
802     {
803         ig->igGCregs = (regMaskSmall)emitInitGCrefRegs;
804     }
805
806     if (!emitAdd)
807     {
808         /* Update the previous recorded live GC ref sets, but not if
809            if we are starting an "overflow" buffer. Note that this is
810            only used to determine whether we need to store or not store
811            the GC ref sets for the next IG, which is dependent on exactly
812            what the state of the emitter GC ref sets will be when the
813            next IG is processed in the emitter.
814          */
815
816         VarSetOps::Assign(emitComp, emitPrevGCrefVars, emitThisGCrefVars);
817         emitPrevGCrefRegs = emitThisGCrefRegs;
818         emitPrevByrefRegs = emitThisByrefRegs;
819
820         emitForceStoreGCState = false;
821     }
822
823 #ifdef DEBUG
824     if (emitComp->opts.dspCode)
825     {
826         printf("\n      G_M%03u_IG%02u:", Compiler::s_compMethodsCount, ig->igNum);
827         if (emitComp->verbose)
828         {
829             printf("        ; offs=%06XH, funclet=%02u", ig->igOffs, ig->igFuncIdx);
830         }
831         else
832         {
833             printf("        ; funclet=%02u", ig->igFuncIdx);
834         }
835         printf("\n");
836     }
837 #endif
838
839     /* Did we have any jumps in this group? */
840
841     if (emitCurIGjmpList)
842     {
843         instrDescJmp* list = nullptr;
844         instrDescJmp* last = nullptr;
845
846         /* Move jumps to the global list, update their 'next' links */
847
848         do
849         {
850             /* Grab the jump and remove it from the list */
851
852             instrDescJmp* oj = emitCurIGjmpList;
853             emitCurIGjmpList = oj->idjNext;
854
855             /* Figure out the address of where the jump got copied */
856
857             size_t        of = (BYTE*)oj - emitCurIGfreeBase;
858             instrDescJmp* nj = (instrDescJmp*)(ig->igData + of);
859
860             // printf("Jump moved from %08X to %08X\n", oj, nj);
861             // printf("jmp [%08X] at %08X + %03u\n", nj, ig, nj->idjOffs);
862
863             assert(nj->idjIG == ig);
864             assert(nj->idIns() == oj->idIns());
865             assert(nj->idjNext == oj->idjNext);
866
867             /* Make sure the jumps are correctly ordered */
868
869             assert(last == nullptr || last->idjOffs > nj->idjOffs);
870
871             if (ig->igFlags & IGF_FUNCLET_PROLOG)
872             {
873                 // Our funclet prologs have short jumps, if the prolog would ever have
874                 // long jumps, then we'd have to insert the list in sorted order than
875                 // just append to the emitJumpList.
876                 noway_assert(nj->idjShort);
877                 if (nj->idjShort)
878                 {
879                     continue;
880                 }
881             }
882
883             /* Append the new jump to the list */
884
885             nj->idjNext = list;
886             list        = nj;
887
888             if (last == nullptr)
889             {
890                 last = nj;
891             }
892         } while (emitCurIGjmpList);
893
894         if (last != nullptr)
895         {
896             /* Append the jump(s) from this IG to the global list */
897             bool prologJump = (ig == emitPrologIG);
898             if ((emitJumpList == nullptr) || prologJump)
899             {
900                 last->idjNext = emitJumpList;
901                 emitJumpList  = list;
902             }
903             else
904             {
905                 last->idjNext         = nullptr;
906                 emitJumpLast->idjNext = list;
907             }
908
909             if (!prologJump || (emitJumpLast == nullptr))
910             {
911                 emitJumpLast = last;
912             }
913         }
914     }
915
916     /* Fix the last instruction field */
917
918     if (sz != 0)
919     {
920         assert(emitLastIns != nullptr);
921         assert(emitCurIGfreeBase <= (BYTE*)emitLastIns);
922         assert((BYTE*)emitLastIns < emitCurIGfreeBase + sz);
923         emitLastIns = (instrDesc*)((BYTE*)id + ((BYTE*)emitLastIns - (BYTE*)emitCurIGfreeBase));
924     }
925
926     /* Reset the buffer free pointers */
927
928     emitCurIGfreeNext = emitCurIGfreeBase;
929
930     return ig;
931 }
932
933 #ifdef LEGACY_BACKEND
934 void emitter::emitTmpSizeChanged(unsigned tmpSize)
935 {
936     assert(emitGrowableMaxByteOffs <= SCHAR_MAX);
937
938 #ifdef DEBUG
939     // Workaround for FP code
940     bool bAssert = JitConfig.JitMaxTempAssert() ? true : false;
941
942     if (tmpSize > emitMaxTmpSize && bAssert)
943     {
944         // TODO-Review: We have a known issue involving floating point code and this assert.
945         // The generated code will be ok, This is only a warning.
946         // To not receive this assert again you can set the registry key: JITMaxTempAssert=0.
947         //
948         assert(!"Incorrect max tmp size set.");
949     }
950 #endif
951
952     if (tmpSize <= emitMaxTmpSize)
953         return;
954
955     unsigned change = tmpSize - emitMaxTmpSize;
956
957     /* If we have used a small offset to access a variable, growing the
958        temp size is a problem if we should have used a large offset instead.
959        Detect if such a situation happens and bail */
960
961     if (emitGrowableMaxByteOffs <= SCHAR_MAX && (emitGrowableMaxByteOffs + change) > SCHAR_MAX)
962     {
963 #ifdef DEBUG
964         if (emitComp->verbose)
965             printf("Under-estimated var offset encoding size for ins #%Xh\n", emitMaxByteOffsIdNum);
966 #endif
967         IMPL_LIMITATION("Should have used large offset to access var");
968     }
969
970     emitMaxTmpSize = tmpSize;
971     emitGrowableMaxByteOffs += change;
972 }
973 #endif // LEGACY_BACKEND
974
975 /*****************************************************************************
976  *
977  *  Start generating code to be scheduled; called once per method.
978  */
979
980 void emitter::emitBegFN(bool hasFramePtr
981 #if defined(DEBUG)
982                         ,
983                         bool chkAlign
984 #endif
985 #ifdef LEGACY_BACKEND
986                         ,
987                         unsigned lclSize
988 #endif // LEGACY_BACKEND
989                         ,
990                         unsigned maxTmpSize)
991 {
992     insGroup* ig;
993
994     /* Assume we won't need the temp instruction buffer */
995
996     emitCurIGfreeBase = nullptr;
997     emitIGbuffSize    = 0;
998
999     /* Record stack frame info (the temp size is just an estimate) */
1000
1001     emitHasFramePtr = hasFramePtr;
1002
1003     emitMaxTmpSize = maxTmpSize;
1004
1005 #ifdef LEGACY_BACKEND
1006     emitLclSize             = lclSize;
1007     emitGrowableMaxByteOffs = 0;
1008 #ifdef DEBUG
1009     emitMaxByteOffsIdNum = (unsigned)-1;
1010 #endif // DEBUG
1011 #endif // LEGACY_BACKEND
1012
1013 #ifdef DEBUG
1014     emitChkAlign = chkAlign;
1015 #endif
1016
1017     /* We have no epilogs yet */
1018
1019     emitEpilogSize = 0;
1020     emitEpilogCnt  = 0;
1021
1022 #ifdef _TARGET_XARCH_
1023     emitExitSeqBegLoc.Init();
1024     emitExitSeqSize = INT_MAX;
1025 #endif // _TARGET_XARCH_
1026
1027     emitPlaceholderList = emitPlaceholderLast = nullptr;
1028
1029 #ifdef JIT32_GCENCODER
1030     emitEpilogList = emitEpilogLast = nullptr;
1031 #endif // JIT32_GCENCODER
1032
1033     /* We don't have any jumps */
1034
1035     emitJumpList = emitJumpLast = nullptr;
1036     emitCurIGjmpList            = nullptr;
1037
1038     emitFwdJumps   = false;
1039     emitNoGCIG     = false;
1040     emitForceNewIG = false;
1041
1042     /* We have not recorded any live sets */
1043
1044     assert(VarSetOps::IsEmpty(emitComp, emitThisGCrefVars));
1045     assert(VarSetOps::IsEmpty(emitComp, emitInitGCrefVars));
1046     assert(VarSetOps::IsEmpty(emitComp, emitPrevGCrefVars));
1047     emitThisGCrefRegs = RBM_NONE;
1048     emitInitGCrefRegs = RBM_NONE;
1049     emitPrevGCrefRegs = RBM_NONE;
1050     emitThisByrefRegs = RBM_NONE;
1051     emitInitByrefRegs = RBM_NONE;
1052     emitPrevByrefRegs = RBM_NONE;
1053
1054     emitForceStoreGCState = false;
1055
1056 #ifdef DEBUG
1057
1058     emitIssuing = false;
1059
1060 #endif
1061
1062     /* Assume there will be no GC ref variables */
1063
1064     emitGCrFrameOffsMin = emitGCrFrameOffsMax = emitGCrFrameOffsCnt = 0;
1065 #ifdef DEBUG
1066     emitGCrFrameLiveTab = nullptr;
1067 #endif
1068
1069     /* We have no groups / code at this point */
1070
1071     emitIGlist = emitIGlast = nullptr;
1072
1073     emitCurCodeOffset = 0;
1074     emitFirstColdIG   = nullptr;
1075     emitTotalCodeSize = 0;
1076
1077 #if EMITTER_STATS
1078     emitTotalIGmcnt++;
1079     emitSizeMethod = 0;
1080 #endif
1081
1082     emitInsCount = 0;
1083
1084     /* The stack is empty now */
1085
1086     emitCurStackLvl = 0;
1087
1088 #if EMIT_TRACK_STACK_DEPTH
1089     emitMaxStackDepth = 0;
1090     emitCntStackDepth = sizeof(int);
1091 #endif
1092
1093     /* No data sections have been created */
1094
1095     emitDataSecCur = nullptr;
1096
1097     memset(&emitConsDsc, 0, sizeof(emitConsDsc));
1098
1099 #ifdef PSEUDORANDOM_NOP_INSERTION
1100     // for random NOP insertion
1101
1102     emitEnableRandomNops();
1103     emitComp->info.compRNG.Init(emitComp->info.compChecksum);
1104     emitNextNop           = emitNextRandomNop();
1105     emitInInstrumentation = false;
1106 #endif // PSEUDORANDOM_NOP_INSERTION
1107
1108     /* Create the first IG, it will be used for the prolog */
1109
1110     emitNxtIGnum = 1;
1111
1112     emitPrologIG = emitIGlist = emitIGlast = emitCurIG = ig = emitAllocIG();
1113
1114     emitLastIns = nullptr;
1115
1116     ig->igNext = nullptr;
1117
1118 #ifdef DEBUG
1119     emitScratchSigInfo = nullptr;
1120 #endif // DEBUG
1121
1122     /* Append another group, to start generating the method body */
1123
1124     emitNewIG();
1125 }
1126
1127 #ifdef PSEUDORANDOM_NOP_INSERTION
1128 int emitter::emitNextRandomNop()
1129 {
1130     return emitComp->info.compRNG.Next(1, 9);
1131 }
1132 #endif
1133
1134 /*****************************************************************************
1135  *
1136  *  Done generating code to be scheduled; called once per method.
1137  */
1138
1139 void emitter::emitEndFN()
1140 {
1141 }
1142
1143 // member function iiaIsJitDataOffset for idAddrUnion, defers to Compiler::eeIsJitDataOffs
1144 bool emitter::instrDesc::idAddrUnion::iiaIsJitDataOffset() const
1145 {
1146     return Compiler::eeIsJitDataOffs(iiaFieldHnd);
1147 }
1148
1149 // member function iiaGetJitDataOffset for idAddrUnion, defers to Compiler::eeGetJitDataOffs
1150 int emitter::instrDesc::idAddrUnion::iiaGetJitDataOffset() const
1151 {
1152     assert(iiaIsJitDataOffset());
1153     return Compiler::eeGetJitDataOffs(iiaFieldHnd);
1154 }
1155
1156 void emitter::dispIns(instrDesc* id)
1157 {
1158 #ifdef DEBUG
1159     emitInsSanityCheck(id);
1160
1161     if (emitComp->opts.dspCode)
1162     {
1163         emitDispIns(id, true, false, false);
1164     }
1165
1166 #if EMIT_TRACK_STACK_DEPTH
1167     assert((int)emitCurStackLvl >= 0);
1168 #endif
1169     size_t sz = emitSizeOfInsDsc(id);
1170     assert(id->idDebugOnlyInfo()->idSize == sz);
1171 #endif // DEBUG
1172
1173 #if EMITTER_STATS
1174     emitIFcounts[id->idInsFmt()]++;
1175 #endif
1176 }
1177
1178 void emitter::appendToCurIG(instrDesc* id)
1179 {
1180     emitCurIGsize += id->idCodeSize();
1181 }
1182
1183 /*****************************************************************************
1184  *
1185  *  Display (optionally) an instruction offset.
1186  */
1187
1188 #ifdef DEBUG
1189
1190 void emitter::emitDispInsOffs(unsigned offs, bool doffs)
1191 {
1192     if (doffs)
1193     {
1194         printf("%06X", offs);
1195     }
1196     else
1197     {
1198         printf("      ");
1199     }
1200 }
1201
1202 #endif // DEBUG
1203
1204 #ifdef JIT32_GCENCODER
1205
1206 /*****************************************************************************
1207  *
1208  *  Call the specified function pointer for each epilog block in the current
1209  *  method with the epilog's relative code offset. Returns the sum of the
1210  *  values returned by the callback.
1211  */
1212
1213 size_t emitter::emitGenEpilogLst(size_t (*fp)(void*, unsigned), void* cp)
1214 {
1215     EpilogList* el;
1216     size_t      sz;
1217
1218     for (el = emitEpilogList, sz = 0; el != nullptr; el = el->elNext)
1219     {
1220         assert(el->elLoc.GetIG()->igFlags & IGF_EPILOG);
1221
1222         // The epilog starts at the location recorded in the epilog list.
1223         sz += fp(cp, el->elLoc.CodeOffset(this));
1224     }
1225
1226     return sz;
1227 }
1228
1229 #endif // JIT32_GCENCODER
1230
1231 /*****************************************************************************
1232  *
1233  *  The following series of methods allocates instruction descriptors.
1234  */
1235
1236 void* emitter::emitAllocInstr(size_t sz, emitAttr opsz)
1237 {
1238     instrDesc* id;
1239
1240 #ifdef DEBUG
1241     // Under STRESS_EMITTER, put every instruction in its own instruction group.
1242     // We can't do this for a prolog, epilog, funclet prolog, or funclet epilog,
1243     // because those are generated out of order. We currently have a limitation
1244     // where the jump shortening pass uses the instruction group number to determine
1245     // if something is earlier or later in the code stream. This implies that
1246     // these groups cannot be more than a single instruction group. Note that
1247     // the prolog/epilog placeholder groups ARE generated in order, and are
1248     // re-used. But generating additional groups would not work.
1249     if (emitComp->compStressCompile(Compiler::STRESS_EMITTER, 1) && emitCurIGinsCnt && !emitIGisInProlog(emitCurIG) &&
1250         !emitIGisInEpilog(emitCurIG)
1251 #if FEATURE_EH_FUNCLETS
1252         && !emitIGisInFuncletProlog(emitCurIG) && !emitIGisInFuncletEpilog(emitCurIG)
1253 #endif // FEATURE_EH_FUNCLETS
1254             )
1255     {
1256         emitNxtIG(true);
1257     }
1258 #endif
1259
1260 #ifdef PSEUDORANDOM_NOP_INSERTION
1261     // TODO-ARM-Bug?: PSEUDORANDOM_NOP_INSERTION is not defined for _TARGET_ARM_
1262     //     ARM - This is currently broken on _TARGET_ARM_
1263     //     When nopSize is odd we misalign emitCurIGsize
1264     //
1265     if (!emitComp->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT) && !emitInInstrumentation &&
1266         !emitIGisInProlog(emitCurIG) && // don't do this in prolog or epilog
1267         !emitIGisInEpilog(emitCurIG) &&
1268         emitRandomNops // sometimes we turn off where exact codegen is needed (pinvoke inline)
1269         )
1270     {
1271         if (emitNextNop == 0)
1272         {
1273             int nopSize           = 4;
1274             emitInInstrumentation = true;
1275             instrDesc* idnop      = emitNewInstr();
1276             emitInInstrumentation = false;
1277             idnop->idInsFmt(IF_NONE);
1278             idnop->idIns(INS_nop);
1279 #if defined(_TARGET_XARCH_)
1280             idnop->idCodeSize(nopSize);
1281 #else
1282 #error "Undefined target for pseudorandom NOP insertion"
1283 #endif
1284
1285             emitCurIGsize += nopSize;
1286             emitNextNop = emitNextRandomNop();
1287         }
1288         else
1289             emitNextNop--;
1290     }
1291 #endif // PSEUDORANDOM_NOP_INSERTION
1292
1293     assert(IsCodeAligned(emitCurIGsize));
1294
1295     /* Make sure we have enough space for the new instruction */
1296
1297     if ((emitCurIGfreeNext + sz >= emitCurIGfreeEndp) || emitForceNewIG)
1298     {
1299         emitNxtIG(true);
1300     }
1301
1302     /* Grab the space for the instruction */
1303
1304     emitLastIns = id = (instrDesc*)emitCurIGfreeNext;
1305     emitCurIGfreeNext += sz;
1306
1307     assert(sz >= sizeof(void*));
1308     memset(id, 0, sz);
1309
1310     // These fields should have been zero-ed by the above
1311     assert(id->idReg1() == regNumber(0));
1312     assert(id->idReg2() == regNumber(0));
1313 #ifdef _TARGET_XARCH_
1314     assert(id->idCodeSize() == 0);
1315 #endif
1316
1317 #if HAS_TINY_DESC
1318     /* Is the second area to be cleared actually present? */
1319     if (sz >= SMALL_IDSC_SIZE)
1320     {
1321         /* Clear the second 4 bytes, or the 'SMALL' part */
1322         *(int*)((BYTE*)id + (SMALL_IDSC_SIZE - sizeof(int))) = 0;
1323
1324         // These fields should have been zero-ed by the above
1325         assert(id->idIsLargeCns() == false);
1326         assert(id->idIsLargeDsp() == false);
1327         assert(id->idIsLargeCall() == false);
1328     }
1329 #endif
1330
1331     // Make sure that idAddrUnion is just a union of various pointer sized things
1332     C_ASSERT(sizeof(CORINFO_FIELD_HANDLE) <= sizeof(void*));
1333     C_ASSERT(sizeof(CORINFO_METHOD_HANDLE) <= sizeof(void*));
1334     C_ASSERT(sizeof(emitter::emitAddrMode) <= sizeof(void*));
1335     C_ASSERT(sizeof(emitLclVarAddr) <= sizeof(void*));
1336     C_ASSERT(sizeof(emitter::instrDesc) == (SMALL_IDSC_SIZE + sizeof(void*)));
1337
1338     emitInsCount++;
1339
1340 #if defined(DEBUG)
1341     /* In debug mode we clear/set some additional fields */
1342
1343     instrDescDebugInfo* info = (instrDescDebugInfo*)emitGetMem(sizeof(*info));
1344
1345     info->idNum        = emitInsCount;
1346     info->idSize       = sz;
1347     info->idVarRefOffs = 0;
1348     info->idMemCookie  = 0;
1349 #ifdef TRANSLATE_PDB
1350     info->idilStart = emitInstrDescILBase;
1351 #endif
1352     info->idFinallyCall = false;
1353     info->idCatchRet    = false;
1354     info->idCallSig     = nullptr;
1355
1356     id->idDebugOnlyInfo(info);
1357
1358 #endif // defined(DEBUG)
1359
1360     /* Store the size and handle the two special values
1361        that indicate GCref and ByRef */
1362
1363     if (EA_IS_GCREF(opsz))
1364     {
1365         /* A special value indicates a GCref pointer value */
1366
1367         id->idGCref(GCT_GCREF);
1368         id->idOpSize(EA_PTRSIZE);
1369     }
1370     else if (EA_IS_BYREF(opsz))
1371     {
1372         /* A special value indicates a Byref pointer value */
1373
1374         id->idGCref(GCT_BYREF);
1375         id->idOpSize(EA_PTRSIZE);
1376     }
1377     else
1378     {
1379         id->idGCref(GCT_NONE);
1380         id->idOpSize(EA_SIZE(opsz));
1381     }
1382
1383     // Amd64: ip-relative addressing is supported even when not generating relocatable ngen code
1384     if (EA_IS_DSP_RELOC(opsz)
1385 #ifndef _TARGET_AMD64_
1386         && emitComp->opts.compReloc
1387 #endif //_TARGET_AMD64_
1388         )
1389     {
1390         /* Mark idInfo()->idDspReloc to remember that the            */
1391         /* address mode has a displacement that is relocatable       */
1392         id->idSetIsDspReloc();
1393     }
1394
1395     if (EA_IS_CNS_RELOC(opsz) && emitComp->opts.compReloc)
1396     {
1397         /* Mark idInfo()->idCnsReloc to remember that the            */
1398         /* instruction has an immediate constant that is relocatable */
1399         id->idSetIsCnsReloc();
1400     }
1401
1402 #if EMITTER_STATS
1403     emitTotalInsCnt++;
1404 #endif
1405
1406     /* Update the instruction count */
1407
1408     emitCurIGinsCnt++;
1409
1410     return id;
1411 }
1412
1413 #ifdef DEBUG
1414
1415 /*****************************************************************************
1416  *
1417  *  Make sure the code offsets of all instruction groups look reasonable.
1418  */
1419 void emitter::emitCheckIGoffsets()
1420 {
1421     insGroup* tempIG;
1422     size_t    offsIG;
1423
1424     for (tempIG = emitIGlist, offsIG = 0; tempIG; tempIG = tempIG->igNext)
1425     {
1426         if (tempIG->igOffs != offsIG)
1427         {
1428             printf("Block #%u has offset %08X, expected %08X\n", tempIG->igNum, tempIG->igOffs, offsIG);
1429             assert(!"bad block offset");
1430         }
1431
1432         offsIG += tempIG->igSize;
1433     }
1434
1435     if (emitTotalCodeSize && emitTotalCodeSize != offsIG)
1436     {
1437         printf("Total code size is %08X, expected %08X\n", emitTotalCodeSize, offsIG);
1438
1439         assert(!"bad total code size");
1440     }
1441 }
1442
1443 #endif // DEBUG
1444
1445 /*****************************************************************************
1446  *
1447  *  Begin generating a method prolog.
1448  */
1449
1450 void emitter::emitBegProlog()
1451 {
1452     assert(emitComp->compGeneratingProlog);
1453
1454 #if EMIT_TRACK_STACK_DEPTH
1455
1456     /* Don't measure stack depth inside the prolog, it's misleading */
1457
1458     emitCntStackDepth = 0;
1459
1460     assert(emitCurStackLvl == 0);
1461
1462 #endif
1463
1464     emitNoGCIG     = true;
1465     emitForceNewIG = false;
1466
1467     /* Switch to the pre-allocated prolog IG */
1468
1469     emitGenIG(emitPrologIG);
1470
1471     /* Nothing is live on entry to the prolog */
1472
1473     // These were initialized to Empty at the start of compilation.
1474     VarSetOps::OldStyleClearD(emitComp, emitInitGCrefVars);
1475     VarSetOps::OldStyleClearD(emitComp, emitPrevGCrefVars);
1476     emitInitGCrefRegs = RBM_NONE;
1477     emitPrevGCrefRegs = RBM_NONE;
1478     emitInitByrefRegs = RBM_NONE;
1479     emitPrevByrefRegs = RBM_NONE;
1480 }
1481
1482 /*****************************************************************************
1483  *
1484  *  Return the code offset of the current location in the prolog.
1485  */
1486
1487 unsigned emitter::emitGetPrologOffsetEstimate()
1488 {
1489     /* For now only allow a single prolog ins group */
1490
1491     assert(emitPrologIG);
1492     assert(emitPrologIG == emitCurIG);
1493
1494     return emitCurIGsize;
1495 }
1496
1497 /*****************************************************************************
1498  *
1499  *  Mark the code offset of the current location as the end of the prolog,
1500  *  so it can be used later to compute the actual size of the prolog.
1501  */
1502
1503 void emitter::emitMarkPrologEnd()
1504 {
1505     assert(emitComp->compGeneratingProlog);
1506
1507     /* For now only allow a single prolog ins group */
1508
1509     assert(emitPrologIG);
1510     assert(emitPrologIG == emitCurIG);
1511
1512     emitPrologEndPos = emitCurOffset();
1513 }
1514
1515 /*****************************************************************************
1516  *
1517  *  Finish generating a method prolog.
1518  */
1519
1520 void emitter::emitEndProlog()
1521 {
1522     assert(emitComp->compGeneratingProlog);
1523
1524     size_t prolSz;
1525
1526     insGroup* tempIG;
1527
1528     emitNoGCIG = false;
1529
1530     /* Save the prolog IG if non-empty or if only one block */
1531
1532     if (emitCurIGnonEmpty() || emitCurIG == emitPrologIG)
1533     {
1534         emitSavIG();
1535     }
1536
1537 #if EMIT_TRACK_STACK_DEPTH
1538     /* Reset the stack depth values */
1539
1540     emitCurStackLvl   = 0;
1541     emitCntStackDepth = sizeof(int);
1542 #endif
1543 }
1544
1545 /*****************************************************************************
1546  *
1547  *  Create a placeholder instruction group to be used by a prolog or epilog,
1548  *  either for the main function, or a funclet.
1549  */
1550
1551 void emitter::emitCreatePlaceholderIG(insGroupPlaceholderType igType,
1552                                       BasicBlock*             igBB,
1553                                       VARSET_VALARG_TP        GCvars,
1554                                       regMaskTP               gcrefRegs,
1555                                       regMaskTP               byrefRegs,
1556                                       bool                    last)
1557 {
1558     assert(igBB != nullptr);
1559
1560     bool emitAdd = false;
1561
1562     if (igType == IGPT_EPILOG
1563 #if FEATURE_EH_FUNCLETS
1564         || igType == IGPT_FUNCLET_EPILOG
1565 #endif // FEATURE_EH_FUNCLETS
1566         )
1567     {
1568 #ifdef _TARGET_AMD64_
1569         emitOutputPreEpilogNOP();
1570 #endif // _TARGET_AMD64_
1571
1572         emitAdd = true;
1573     }
1574
1575     if (emitCurIGnonEmpty())
1576     {
1577         emitNxtIG(emitAdd);
1578     }
1579
1580     /* Update GC tracking for the beginning of the placeholder IG */
1581
1582     if (!emitAdd)
1583     {
1584         VarSetOps::Assign(emitComp, emitThisGCrefVars, GCvars);
1585         VarSetOps::Assign(emitComp, emitInitGCrefVars, GCvars);
1586         emitThisGCrefRegs = emitInitGCrefRegs = gcrefRegs;
1587         emitThisByrefRegs = emitInitByrefRegs = byrefRegs;
1588     }
1589
1590     /* Convert the group to a placeholder group */
1591
1592     insGroup* igPh = emitCurIG;
1593
1594     igPh->igFlags |= IGF_PLACEHOLDER;
1595
1596     /* Note that we might be re-using a previously created but empty IG. In this
1597      * case, we need to make sure any re-used fields, such as igFuncIdx, are correct.
1598      */
1599
1600     igPh->igFuncIdx = emitComp->compCurrFuncIdx;
1601
1602     /* Create a separate block of memory to store placeholder information.
1603      * We could use unions to put some of this into the insGroup itself, but we don't
1604      * want to grow the insGroup, and it's difficult to make sure the
1605      * insGroup fields are getting set and used elsewhere.
1606      */
1607
1608     igPh->igPhData = new (emitComp, CMK_InstDesc) insPlaceholderGroupData;
1609
1610     igPh->igPhData->igPhNext = nullptr;
1611     igPh->igPhData->igPhType = igType;
1612     igPh->igPhData->igPhBB   = igBB;
1613
1614     VarSetOps::AssignNoCopy(emitComp, igPh->igPhData->igPhPrevGCrefVars, VarSetOps::UninitVal());
1615     VarSetOps::Assign(emitComp, igPh->igPhData->igPhPrevGCrefVars, emitPrevGCrefVars);
1616     igPh->igPhData->igPhPrevGCrefRegs = emitPrevGCrefRegs;
1617     igPh->igPhData->igPhPrevByrefRegs = emitPrevByrefRegs;
1618
1619     VarSetOps::AssignNoCopy(emitComp, igPh->igPhData->igPhInitGCrefVars, VarSetOps::UninitVal());
1620     VarSetOps::Assign(emitComp, igPh->igPhData->igPhInitGCrefVars, emitInitGCrefVars);
1621     igPh->igPhData->igPhInitGCrefRegs = emitInitGCrefRegs;
1622     igPh->igPhData->igPhInitByrefRegs = emitInitByrefRegs;
1623
1624 #if EMITTER_STATS
1625     emitTotalPhIGcnt += 1;
1626 #endif
1627
1628     // Mark function prologs and epilogs properly in the igFlags bits. These bits
1629     // will get used and propagated when the placeholder is converted to a non-placeholder
1630     // during prolog/epilog generation.
1631
1632     if (igType == IGPT_EPILOG)
1633     {
1634         igPh->igFlags |= IGF_EPILOG;
1635     }
1636 #if FEATURE_EH_FUNCLETS
1637     else if (igType == IGPT_FUNCLET_PROLOG)
1638     {
1639         igPh->igFlags |= IGF_FUNCLET_PROLOG;
1640     }
1641     else if (igType == IGPT_FUNCLET_EPILOG)
1642     {
1643         igPh->igFlags |= IGF_FUNCLET_EPILOG;
1644     }
1645 #endif // FEATURE_EH_FUNCLETS
1646
1647     /* Link it into the placeholder list */
1648
1649     if (emitPlaceholderList)
1650     {
1651         emitPlaceholderLast->igPhData->igPhNext = igPh;
1652     }
1653     else
1654     {
1655         emitPlaceholderList = igPh;
1656     }
1657
1658     emitPlaceholderLast = igPh;
1659
1660     // Give an estimated size of this placeholder IG and
1661     // increment emitCurCodeOffset since we are not calling emitNewIG()
1662     //
1663     emitCurIGsize += MAX_PLACEHOLDER_IG_SIZE;
1664     emitCurCodeOffset += emitCurIGsize;
1665
1666 #if FEATURE_EH_FUNCLETS
1667     // Add the appropriate IP mapping debugging record for this placeholder
1668     // group. genExitCode() adds the mapping for main function epilogs.
1669     if (emitComp->opts.compDbgInfo)
1670     {
1671         if (igType == IGPT_FUNCLET_PROLOG)
1672         {
1673             codeGen->genIPmappingAdd((IL_OFFSETX)ICorDebugInfo::PROLOG, true);
1674         }
1675         else if (igType == IGPT_FUNCLET_EPILOG)
1676         {
1677             codeGen->genIPmappingAdd((IL_OFFSETX)ICorDebugInfo::EPILOG, true);
1678         }
1679     }
1680 #endif // FEATURE_EH_FUNCLETS
1681
1682     /* Start a new IG if more code follows */
1683
1684     if (last)
1685     {
1686         emitCurIG = nullptr;
1687     }
1688     else
1689     {
1690         if (igType == IGPT_EPILOG
1691 #if FEATURE_EH_FUNCLETS
1692             || igType == IGPT_FUNCLET_EPILOG
1693 #endif // FEATURE_EH_FUNCLETS
1694             )
1695         {
1696             // If this was an epilog, then assume this is the end of any currently in progress
1697             // no-GC region. If a block after the epilog needs to be no-GC, it needs to call
1698             // emitter::emitDisableGC() directly. This behavior is depended upon by the fast
1699             // tailcall implementation, which disables GC at the beginning of argument setup,
1700             // but assumes that after the epilog it will be re-enabled.
1701             emitNoGCIG = false;
1702         }
1703
1704         emitNewIG();
1705
1706         // We don't know what the GC ref state will be at the end of the placeholder
1707         // group. So, force the next IG to store all the GC ref state variables;
1708         // don't omit them because emitPrev* is the same as emitInit*, because emitPrev*
1709         // will be inaccurate. (Note that, currently, GCrefRegs and ByrefRegs are always
1710         // saved anyway.)
1711         //
1712         // There is no need to re-initialize the emitPrev* variables, as they won't be used
1713         // with emitForceStoreGCState==true, and will be re-initialized just before
1714         // emitForceStoreGCState is set to false;
1715
1716         emitForceStoreGCState = true;
1717
1718         /* The group after the placeholder group doesn't get the "propagate" flags */
1719
1720         emitCurIG->igFlags &= ~IGF_PROPAGATE_MASK;
1721     }
1722
1723 #ifdef DEBUG
1724     if (emitComp->verbose)
1725     {
1726         printf("*************** After placeholder IG creation\n");
1727         emitDispIGlist(false);
1728     }
1729 #endif
1730 }
1731
1732 /*****************************************************************************
1733  *
1734  *  Generate all prologs and epilogs
1735  */
1736
1737 void emitter::emitGeneratePrologEpilog()
1738 {
1739 #ifdef DEBUG
1740     unsigned prologCnt = 0;
1741     unsigned epilogCnt = 0;
1742 #if FEATURE_EH_FUNCLETS
1743     unsigned funcletPrologCnt = 0;
1744     unsigned funcletEpilogCnt = 0;
1745 #endif // FEATURE_EH_FUNCLETS
1746 #endif // DEBUG
1747
1748     insGroup* igPh;
1749     insGroup* igPhNext;
1750
1751     // Generating the prolog/epilog is going to destroy the placeholder group,
1752     // so save the "next" pointer before that happens.
1753
1754     for (igPh = emitPlaceholderList; igPh != nullptr; igPh = igPhNext)
1755     {
1756         assert(igPh->igFlags & IGF_PLACEHOLDER);
1757
1758         igPhNext = igPh->igPhData->igPhNext;
1759
1760         BasicBlock* igPhBB = igPh->igPhData->igPhBB;
1761
1762         switch (igPh->igPhData->igPhType)
1763         {
1764             case IGPT_PROLOG: // currently unused
1765                 INDEBUG(++prologCnt);
1766                 break;
1767
1768             case IGPT_EPILOG:
1769                 INDEBUG(++epilogCnt);
1770                 emitBegFnEpilog(igPh);
1771                 codeGen->genFnEpilog(igPhBB);
1772                 emitEndFnEpilog();
1773                 break;
1774
1775 #if FEATURE_EH_FUNCLETS
1776
1777             case IGPT_FUNCLET_PROLOG:
1778                 INDEBUG(++funcletPrologCnt);
1779                 emitBegFuncletProlog(igPh);
1780                 codeGen->genFuncletProlog(igPhBB);
1781                 emitEndFuncletProlog();
1782                 break;
1783
1784             case IGPT_FUNCLET_EPILOG:
1785                 INDEBUG(++funcletEpilogCnt);
1786                 emitBegFuncletEpilog(igPh);
1787                 codeGen->genFuncletEpilog();
1788                 emitEndFuncletEpilog();
1789                 break;
1790
1791 #endif // FEATURE_EH_FUNCLETS
1792
1793             default:
1794                 unreached();
1795         }
1796     }
1797
1798 #ifdef DEBUG
1799     if (emitComp->verbose)
1800     {
1801         printf("%d prologs, %d epilogs", prologCnt, epilogCnt);
1802 #if FEATURE_EH_FUNCLETS
1803         printf(", %d funclet prologs, %d funclet epilogs", funcletPrologCnt, funcletEpilogCnt);
1804 #endif // FEATURE_EH_FUNCLETS
1805         printf("\n");
1806
1807 // prolog/epilog code doesn't use this yet
1808 // noway_assert(prologCnt == 1);
1809 // noway_assert(epilogCnt == emitEpilogCnt); // Is this correct?
1810 #if FEATURE_EH_FUNCLETS
1811         assert(funcletPrologCnt == emitComp->ehFuncletCount());
1812 #endif // FEATURE_EH_FUNCLETS
1813     }
1814 #endif // DEBUG
1815 }
1816
1817 /*****************************************************************************
1818  *
1819  *  Begin all prolog and epilog generation
1820  */
1821
1822 void emitter::emitStartPrologEpilogGeneration()
1823 {
1824     /* Save the current IG if it's non-empty */
1825
1826     if (emitCurIGnonEmpty())
1827     {
1828         emitSavIG();
1829     }
1830     else
1831     {
1832         assert(emitCurIG == nullptr);
1833     }
1834 }
1835
1836 /*****************************************************************************
1837  *
1838  *  Finish all prolog and epilog generation
1839  */
1840
1841 void emitter::emitFinishPrologEpilogGeneration()
1842 {
1843     /* Update the offsets of all the blocks */
1844
1845     emitRecomputeIGoffsets();
1846
1847     /* We should not generate any more code after this */
1848
1849     emitCurIG = nullptr;
1850 }
1851
1852 /*****************************************************************************
1853  *
1854  *  Common code for prolog / epilog beginning. Convert the placeholder group to actual code IG,
1855  *  and set it as the current group.
1856  */
1857
1858 void emitter::emitBegPrologEpilog(insGroup* igPh)
1859 {
1860     assert(igPh->igFlags & IGF_PLACEHOLDER);
1861
1862     /* Save the current IG if it's non-empty */
1863
1864     if (emitCurIGnonEmpty())
1865     {
1866         emitSavIG();
1867     }
1868
1869     /* Convert the placeholder group to a normal group.
1870      * We need to be very careful to re-initialize the IG properly.
1871      * It turns out, this means we only need to clear the placeholder bit
1872      * and clear the igPhData field, and emitGenIG() will do the rest,
1873      * since in the placeholder IG we didn't touch anything that is set by emitAllocIG().
1874      */
1875
1876     igPh->igFlags &= ~IGF_PLACEHOLDER;
1877     emitNoGCIG     = true;
1878     emitForceNewIG = false;
1879
1880     /* Set up the GC info that we stored in the placeholder */
1881
1882     VarSetOps::Assign(emitComp, emitPrevGCrefVars, igPh->igPhData->igPhPrevGCrefVars);
1883     emitPrevGCrefRegs = igPh->igPhData->igPhPrevGCrefRegs;
1884     emitPrevByrefRegs = igPh->igPhData->igPhPrevByrefRegs;
1885
1886     VarSetOps::Assign(emitComp, emitThisGCrefVars, igPh->igPhData->igPhInitGCrefVars);
1887     VarSetOps::Assign(emitComp, emitInitGCrefVars, igPh->igPhData->igPhInitGCrefVars);
1888     emitThisGCrefRegs = emitInitGCrefRegs = igPh->igPhData->igPhInitGCrefRegs;
1889     emitThisByrefRegs = emitInitByrefRegs = igPh->igPhData->igPhInitByrefRegs;
1890
1891     igPh->igPhData = nullptr;
1892
1893     /* Create a non-placeholder group pointer that we'll now use */
1894
1895     insGroup* ig = igPh;
1896
1897     /* Set the current function using the function index we stored */
1898
1899     emitComp->funSetCurrentFunc(ig->igFuncIdx);
1900
1901     /* Set the new IG as the place to generate code */
1902
1903     emitGenIG(ig);
1904
1905 #if EMIT_TRACK_STACK_DEPTH
1906
1907     /* Don't measure stack depth inside the prolog / epilog, it's misleading */
1908
1909     emitCntStackDepth = 0;
1910
1911     assert(emitCurStackLvl == 0);
1912
1913 #endif
1914 }
1915
1916 /*****************************************************************************
1917  *
1918  *  Common code for end of prolog / epilog
1919  */
1920
1921 void emitter::emitEndPrologEpilog()
1922 {
1923     emitNoGCIG = false;
1924
1925     /* Save the IG if non-empty */
1926
1927     if (emitCurIGnonEmpty())
1928     {
1929         emitSavIG();
1930     }
1931
1932     assert(emitCurIGsize <= MAX_PLACEHOLDER_IG_SIZE);
1933
1934 #if EMIT_TRACK_STACK_DEPTH
1935     /* Reset the stack depth values */
1936
1937     emitCurStackLvl   = 0;
1938     emitCntStackDepth = sizeof(int);
1939 #endif
1940 }
1941
1942 /*****************************************************************************
1943  *
1944  *  Begin generating a main function epilog.
1945  */
1946
1947 void emitter::emitBegFnEpilog(insGroup* igPh)
1948 {
1949     emitEpilogCnt++;
1950
1951     emitBegPrologEpilog(igPh);
1952
1953 #ifdef JIT32_GCENCODER
1954
1955     EpilogList* el = new (emitComp, CMK_GC) EpilogList();
1956
1957     if (emitEpilogLast != nullptr)
1958     {
1959         emitEpilogLast->elNext = el;
1960     }
1961     else
1962     {
1963         emitEpilogList = el;
1964     }
1965
1966     emitEpilogLast = el;
1967
1968 #endif // JIT32_GCENCODER
1969 }
1970
1971 /*****************************************************************************
1972  *
1973  *  Finish generating a funclet epilog.
1974  */
1975
1976 void emitter::emitEndFnEpilog()
1977 {
1978     emitEndPrologEpilog();
1979
1980 #ifdef JIT32_GCENCODER
1981     assert(emitEpilogLast != nullptr);
1982
1983     UNATIVE_OFFSET epilogBegCodeOffset          = emitEpilogLast->elLoc.CodeOffset(this);
1984     UNATIVE_OFFSET epilogExitSeqStartCodeOffset = emitExitSeqBegLoc.CodeOffset(this);
1985     UNATIVE_OFFSET newSize                      = epilogExitSeqStartCodeOffset - epilogBegCodeOffset;
1986
1987     /* Compute total epilog size */
1988     assert(emitEpilogSize == 0 || emitEpilogSize == newSize); // All epilogs must be identical
1989     emitEpilogSize = newSize;
1990
1991     UNATIVE_OFFSET epilogEndCodeOffset = emitCodeOffset(emitCurIG, emitCurOffset());
1992     assert(epilogExitSeqStartCodeOffset != epilogEndCodeOffset);
1993
1994     newSize = epilogEndCodeOffset - epilogExitSeqStartCodeOffset;
1995     if (newSize < emitExitSeqSize)
1996     {
1997         // We expect either the epilog to be the same every time, or that
1998         // one will be a ret or a ret <n> and others will be a jmp addr or jmp [addr];
1999         // we make the epilogs the minimum of these.  Note that this ONLY works
2000         // because the only instruction is the last one and thus a slight
2001         // underestimation of the epilog size is harmless (since the EIP
2002         // can not be between instructions).
2003         assert(emitEpilogCnt == 1 ||
2004                (emitExitSeqSize - newSize) <= 5 // delta between size of various forms of jmp (size is either 6 or 5)
2005                                                 // and various forms of ret (size is either 1 or 3). The combination can
2006                                                 // be anything been 1 and 5.
2007                );
2008         emitExitSeqSize = newSize;
2009     }
2010 #endif // JIT32_GCENCODER
2011 }
2012
2013 #if FEATURE_EH_FUNCLETS
2014
2015 /*****************************************************************************
2016  *
2017  *  Begin generating a funclet prolog.
2018  */
2019
2020 void emitter::emitBegFuncletProlog(insGroup* igPh)
2021 {
2022     emitBegPrologEpilog(igPh);
2023 }
2024
2025 /*****************************************************************************
2026  *
2027  *  Finish generating a funclet prolog.
2028  */
2029
2030 void emitter::emitEndFuncletProlog()
2031 {
2032     emitEndPrologEpilog();
2033 }
2034
2035 /*****************************************************************************
2036  *
2037  *  Begin generating a funclet epilog.
2038  */
2039
2040 void emitter::emitBegFuncletEpilog(insGroup* igPh)
2041 {
2042     emitBegPrologEpilog(igPh);
2043 }
2044
2045 /*****************************************************************************
2046  *
2047  *  Finish generating a funclet epilog.
2048  */
2049
2050 void emitter::emitEndFuncletEpilog()
2051 {
2052     emitEndPrologEpilog();
2053 }
2054
2055 #endif // FEATURE_EH_FUNCLETS
2056
2057 #ifdef JIT32_GCENCODER
2058
2059 //
2060 // emitter::emitStartEpilog:
2061 //   Mark the current position so that we can later compute the total epilog size.
2062 //
2063 void emitter::emitStartEpilog()
2064 {
2065     assert(emitEpilogLast != nullptr);
2066     emitEpilogLast->elLoc.CaptureLocation(this);
2067 }
2068
2069 /*****************************************************************************
2070  *
2071  *  Return non-zero if the current method only has one epilog, which is
2072  *  at the very end of the method body.
2073  */
2074
2075 bool emitter::emitHasEpilogEnd()
2076 {
2077     if (emitEpilogCnt == 1 && (emitIGlast->igFlags & IGF_EPILOG)) // This wouldn't work for funclets
2078         return true;
2079     else
2080         return false;
2081 }
2082
2083 #endif // JIT32_GCENCODER
2084
2085 #ifdef _TARGET_XARCH_
2086
2087 /*****************************************************************************
2088  *
2089  *  Mark the beginning of the epilog exit sequence by remembering our position.
2090  */
2091
2092 void emitter::emitStartExitSeq()
2093 {
2094     assert(emitComp->compGeneratingEpilog);
2095
2096     emitExitSeqBegLoc.CaptureLocation(this);
2097 }
2098
2099 #endif // _TARGET_XARCH_
2100
2101 /*****************************************************************************
2102  *
2103  *  The code generator tells us the range of GC ref locals through this
2104  *  method. Needless to say, locals and temps should be allocated so that
2105  *  the size of the range is as small as possible.
2106  *
2107  * offsLo - The FP offset from which the GC pointer range starts.
2108  * offsHi - The FP offset at which the GC pointer region ends (exclusive).
2109  */
2110
2111 void emitter::emitSetFrameRangeGCRs(int offsLo, int offsHi)
2112 {
2113     assert(emitComp->compGeneratingProlog);
2114     assert(offsHi > offsLo);
2115
2116 #ifdef DEBUG
2117
2118     //  A total of    47254 methods compiled.
2119     //
2120     //  GC ref frame variable counts:
2121     //
2122     //      <=         0 ===>  43175 count ( 91% of total)
2123     //       1 ..      1 ===>   2367 count ( 96% of total)
2124     //       2 ..      2 ===>    887 count ( 98% of total)
2125     //       3 ..      5 ===>    579 count ( 99% of total)
2126     //       6 ..     10 ===>    141 count ( 99% of total)
2127     //      11 ..     20 ===>     40 count ( 99% of total)
2128     //      21 ..     50 ===>     42 count ( 99% of total)
2129     //      51 ..    128 ===>     15 count ( 99% of total)
2130     //     129 ..    256 ===>      4 count ( 99% of total)
2131     //     257 ..    512 ===>      4 count (100% of total)
2132     //     513 ..   1024 ===>      0 count (100% of total)
2133
2134     if (emitComp->verbose)
2135     {
2136         unsigned count = (offsHi - offsLo) / sizeof(void*);
2137         printf("%u tracked GC refs are at stack offsets ", count);
2138
2139         if (offsLo >= 0)
2140         {
2141             printf(" %04X ...  %04X\n", offsLo, offsHi);
2142             assert(offsHi >= 0);
2143         }
2144         else
2145 #if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
2146             if (!emitComp->compIsProfilerHookNeeded())
2147 #endif
2148         {
2149 #ifdef _TARGET_AMD64_
2150             // doesn't have to be all negative on amd
2151             printf("-%04X ... %04X\n", -offsLo, offsHi);
2152 #else
2153             printf("-%04X ... -%04X\n", -offsLo, -offsHi);
2154             assert(offsHi <= 0);
2155 #endif
2156         }
2157 #if defined(_TARGET_ARM_) && defined(PROFILING_SUPPORTED)
2158         else
2159         {
2160             // Under profiler due to prespilling of arguments, offHi need not be < 0
2161             if (offsHi < 0)
2162                 printf("-%04X ... -%04X\n", -offsLo, -offsHi);
2163             else
2164                 printf("-%04X ... %04X\n", -offsLo, offsHi);
2165         }
2166 #endif
2167     }
2168
2169 #endif // DEBUG
2170
2171     assert(((offsHi - offsLo) % sizeof(void*)) == 0);
2172     assert((offsLo % sizeof(void*)) == 0);
2173     assert((offsHi % sizeof(void*)) == 0);
2174
2175     emitGCrFrameOffsMin = offsLo;
2176     emitGCrFrameOffsMax = offsHi;
2177     emitGCrFrameOffsCnt = (offsHi - offsLo) / sizeof(void*);
2178 }
2179
2180 /*****************************************************************************
2181  *
2182  *  The code generator tells us the range of local variables through this
2183  *  method.
2184  */
2185
2186 void emitter::emitSetFrameRangeLcls(int offsLo, int offsHi)
2187 {
2188 }
2189
2190 /*****************************************************************************
2191  *
2192  *  The code generator tells us the range of used arguments through this
2193  *  method.
2194  */
2195
2196 void emitter::emitSetFrameRangeArgs(int offsLo, int offsHi)
2197 {
2198 }
2199
2200 /*****************************************************************************
2201  *
2202  *  A conversion table used to map an operand size value (in bytes) into its
2203  *  small encoding (0 through 3), and vice versa.
2204  */
2205
2206 const emitter::opSize emitter::emitSizeEncode[] = {
2207     emitter::OPSZ1, emitter::OPSZ2,  OPSIZE_INVALID, emitter::OPSZ4,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2208     emitter::OPSZ8, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2209     OPSIZE_INVALID, emitter::OPSZ16, OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2210     OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, OPSIZE_INVALID, OPSIZE_INVALID,
2211     OPSIZE_INVALID, OPSIZE_INVALID,  OPSIZE_INVALID, emitter::OPSZ32,
2212 };
2213
2214 const emitAttr emitter::emitSizeDecode[emitter::OPSZ_COUNT] = {EA_1BYTE, EA_2BYTE,  EA_4BYTE,
2215                                                                EA_8BYTE, EA_16BYTE, EA_32BYTE};
2216
2217 /*****************************************************************************
2218  *
2219  *  Allocate an instruction descriptor for an instruction that uses both
2220  *  a displacement and a constant.
2221  */
2222
2223 emitter::instrDesc* emitter::emitNewInstrCnsDsp(emitAttr size, ssize_t cns, int dsp)
2224 {
2225     if (dsp == 0)
2226     {
2227         if (instrDesc::fitsInSmallCns(cns))
2228         {
2229             instrDesc* id = emitAllocInstr(size);
2230
2231             id->idSmallCns(cns);
2232
2233 #if EMITTER_STATS
2234             emitSmallCnsCnt++;
2235             emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2236             emitSmallDspCnt++;
2237 #endif
2238
2239             return id;
2240         }
2241         else
2242         {
2243             instrDescCns* id = emitAllocInstrCns(size);
2244
2245             id->idSetIsLargeCns();
2246             id->idcCnsVal = cns;
2247
2248 #if EMITTER_STATS
2249             emitLargeCnsCnt++;
2250             emitSmallDspCnt++;
2251 #endif
2252
2253             return id;
2254         }
2255     }
2256     else
2257     {
2258         if (instrDesc::fitsInSmallCns(cns))
2259         {
2260             instrDescDsp* id = emitAllocInstrDsp(size);
2261
2262             id->idSetIsLargeDsp();
2263             id->iddDspVal = dsp;
2264
2265             id->idSmallCns(cns);
2266
2267 #if EMITTER_STATS
2268             emitLargeDspCnt++;
2269             emitSmallCnsCnt++;
2270             emitSmallCns[cns - ID_MIN_SMALL_CNS]++;
2271 #endif
2272
2273             return id;
2274         }
2275         else
2276         {
2277             instrDescCnsDsp* id = emitAllocInstrCnsDsp(size);
2278
2279             id->idSetIsLargeCns();
2280             id->iddcCnsVal = cns;
2281
2282             id->idSetIsLargeDsp();
2283             id->iddcDspVal = dsp;
2284
2285 #if EMITTER_STATS
2286             emitLargeDspCnt++;
2287             emitLargeCnsCnt++;
2288 #endif
2289
2290             return id;
2291         }
2292     }
2293 }
2294
2295 /*****************************************************************************
2296  *
2297  *  Returns true if garbage-collection won't happen within the helper call.
2298  *  Don't need to record live pointers for such call sites.
2299  */
2300
2301 bool emitter::emitNoGChelper(unsigned IHX)
2302 {
2303     // TODO-Throughput: Make this faster (maybe via a simple table of bools?)
2304
2305     switch (IHX)
2306     {
2307         case CORINFO_HELP_UNDEF:
2308             return false;
2309
2310         case CORINFO_HELP_PROF_FCN_LEAVE:
2311         case CORINFO_HELP_PROF_FCN_ENTER:
2312 #if defined(_TARGET_AMD64_) || (defined(_TARGET_X86_) && !defined(LEGACY_BACKEND))
2313         case CORINFO_HELP_PROF_FCN_TAILCALL:
2314 #endif
2315         case CORINFO_HELP_LLSH:
2316         case CORINFO_HELP_LRSH:
2317         case CORINFO_HELP_LRSZ:
2318
2319 //  case CORINFO_HELP_LMUL:
2320 //  case CORINFO_HELP_LDIV:
2321 //  case CORINFO_HELP_LMOD:
2322 //  case CORINFO_HELP_ULDIV:
2323 //  case CORINFO_HELP_ULMOD:
2324
2325 #ifdef _TARGET_X86_
2326         case CORINFO_HELP_ASSIGN_REF_EAX:
2327         case CORINFO_HELP_ASSIGN_REF_ECX:
2328         case CORINFO_HELP_ASSIGN_REF_EBX:
2329         case CORINFO_HELP_ASSIGN_REF_EBP:
2330         case CORINFO_HELP_ASSIGN_REF_ESI:
2331         case CORINFO_HELP_ASSIGN_REF_EDI:
2332
2333         case CORINFO_HELP_CHECKED_ASSIGN_REF_EAX:
2334         case CORINFO_HELP_CHECKED_ASSIGN_REF_ECX:
2335         case CORINFO_HELP_CHECKED_ASSIGN_REF_EBX:
2336         case CORINFO_HELP_CHECKED_ASSIGN_REF_EBP:
2337         case CORINFO_HELP_CHECKED_ASSIGN_REF_ESI:
2338         case CORINFO_HELP_CHECKED_ASSIGN_REF_EDI:
2339 #endif
2340
2341         case CORINFO_HELP_ASSIGN_REF:
2342
2343         case CORINFO_HELP_CHECKED_ASSIGN_REF:
2344
2345         case CORINFO_HELP_GETSHARED_GCSTATIC_BASE_NOCTOR:
2346
2347         case CORINFO_HELP_GETSHARED_NONGCSTATIC_BASE_NOCTOR:
2348
2349         case CORINFO_HELP_ASSIGN_BYREF:
2350
2351         case CORINFO_HELP_INIT_PINVOKE_FRAME:
2352
2353             return true;
2354     }
2355
2356     return false;
2357 }
2358
2359 /*****************************************************************************
2360  *
2361  *  Mark the current spot as having a label.
2362  */
2363
2364 void* emitter::emitAddLabel(VARSET_VALARG_TP GCvars, regMaskTP gcrefRegs, regMaskTP byrefRegs, BOOL isFinallyTarget)
2365 {
2366     /* Create a new IG if the current one is non-empty */
2367
2368     if (emitCurIGnonEmpty())
2369     {
2370         emitNxtIG();
2371     }
2372
2373     VarSetOps::Assign(emitComp, emitThisGCrefVars, GCvars);
2374     VarSetOps::Assign(emitComp, emitInitGCrefVars, GCvars);
2375     emitThisGCrefRegs = emitInitGCrefRegs = gcrefRegs;
2376     emitThisByrefRegs = emitInitByrefRegs = byrefRegs;
2377
2378 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
2379     if (isFinallyTarget)
2380     {
2381         emitCurIG->igFlags |= IGF_FINALLY_TARGET;
2382     }
2383 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
2384
2385 #ifdef DEBUG
2386     if (EMIT_GC_VERBOSE)
2387     {
2388         printf("Label: IG%02u, GCvars=%s ", emitCurIG->igNum, VarSetOps::ToString(emitComp, GCvars));
2389         dumpConvertedVarSet(emitComp, GCvars);
2390         printf(", gcrefRegs=");
2391         printRegMaskInt(gcrefRegs);
2392         emitDispRegSet(gcrefRegs);
2393         printf(", byrefRegs=");
2394         printRegMaskInt(byrefRegs);
2395         emitDispRegSet(byrefRegs);
2396         printf("\n");
2397     }
2398 #endif
2399     return emitCurIG;
2400 }
2401
2402 #ifdef _TARGET_ARMARCH_
2403
2404 // Does the argument location point to an IG at the end of a function or funclet?
2405 // We can ignore the codePos part of the location, since it doesn't affect the
2406 // determination. If 'emitLocNextFragment' is non-NULL, it indicates the first
2407 // IG of the next fragment, so it represents a function end.
2408 bool emitter::emitIsFuncEnd(emitLocation* emitLoc, emitLocation* emitLocNextFragment /* = NULL */)
2409 {
2410     assert(emitLoc);
2411
2412     insGroup* ig = emitLoc->GetIG();
2413     assert(ig);
2414
2415     // Are we at the end of the IG list?
2416     if ((emitLocNextFragment != NULL) && (ig->igNext == emitLocNextFragment->GetIG()))
2417         return true;
2418
2419     // Safety check
2420     if (ig->igNext == NULL)
2421         return true;
2422
2423     // Is the next IG the start of a funclet prolog?
2424     if (ig->igNext->igFlags & IGF_FUNCLET_PROLOG)
2425         return true;
2426
2427 #if FEATURE_EH_FUNCLETS
2428
2429     // Is the next IG a placeholder group for a funclet prolog?
2430     if ((ig->igNext->igFlags & IGF_PLACEHOLDER) && (ig->igNext->igPhData->igPhType == IGPT_FUNCLET_PROLOG))
2431     {
2432         return true;
2433     }
2434
2435 #endif // FEATURE_EH_FUNCLETS
2436
2437     return false;
2438 }
2439
2440 /*****************************************************************************
2441  *
2442  * Split the region from 'startLoc' to 'endLoc' into fragments by calling
2443  * a callback function to indicate the beginning of a fragment. The initial code,
2444  * starting at 'startLoc', doesn't get a callback, but the first code fragment,
2445  * about 'maxSplitSize' bytes out does, as does the beginning of each fragment
2446  * after that. There is no callback for the end (only the beginning of the last
2447  * fragment gets a callback). A fragment must contain at least one instruction
2448  * group. It should be smaller than 'maxSplitSize', although it may be larger to
2449  * satisfy the "at least one instruction group" rule. Do not split prologs or
2450  * epilogs. (Currently, prologs exist in a single instruction group at the main
2451  * function beginning, so they aren't split. Funclets, however, might span IGs,
2452  * so we can't split in between them.)
2453  *
2454  * Note that the locations must be the start of instruction groups; the part of
2455  * the location indicating offset within a group must be zero.
2456  *
2457  * If 'startLoc' is NULL, it means the start of the code.
2458  * If 'endLoc'   is NULL, it means the end   of the code.
2459  */
2460
2461 void emitter::emitSplit(emitLocation*         startLoc,
2462                         emitLocation*         endLoc,
2463                         UNATIVE_OFFSET        maxSplitSize,
2464                         void*                 context,
2465                         emitSplitCallbackType callbackFunc)
2466 {
2467     insGroup*      igStart = (startLoc == NULL) ? emitIGlist : startLoc->GetIG();
2468     insGroup*      igEnd   = (endLoc == NULL) ? NULL : endLoc->GetIG();
2469     insGroup*      igPrev;
2470     insGroup*      ig;
2471     insGroup*      igLastReported;
2472     insGroup*      igLastCandidate;
2473     UNATIVE_OFFSET curSize;
2474     UNATIVE_OFFSET candidateSize;
2475
2476     for (igPrev = NULL, ig = igLastReported = igStart, igLastCandidate = NULL, candidateSize = 0, curSize = 0;
2477          ig != igEnd && ig != NULL; igPrev = ig, ig = ig->igNext)
2478     {
2479         // Keep looking until we've gone past the maximum split size
2480         if (curSize >= maxSplitSize)
2481         {
2482             bool reportCandidate = true;
2483
2484             // Is there a candidate?
2485             if (igLastCandidate == NULL)
2486             {
2487 #ifdef DEBUG
2488                 if (EMITVERBOSE)
2489                     printf("emitSplit: can't split at IG%02u; we don't have a candidate to report\n", ig->igNum);
2490 #endif
2491                 reportCandidate = false;
2492             }
2493
2494             // Don't report the same thing twice (this also happens for the first block, since igLastReported is
2495             // initialized to igStart).
2496             if (igLastCandidate == igLastReported)
2497             {
2498 #ifdef DEBUG
2499                 if (EMITVERBOSE)
2500                     printf("emitSplit: can't split at IG%02u; we already reported it\n", igLastCandidate->igNum);
2501 #endif
2502                 reportCandidate = false;
2503             }
2504
2505             // Report it!
2506             if (reportCandidate)
2507             {
2508 #ifdef DEBUG
2509                 if (EMITVERBOSE && (candidateSize >= maxSplitSize))
2510                     printf("emitSplit: split at IG%02u is size %d, larger than requested maximum size of %d\n",
2511                            igLastCandidate->igNum, candidateSize, maxSplitSize);
2512 #endif
2513
2514                 // hand memory ownership to the callback function
2515                 emitLocation* pEmitLoc = new (emitComp, CMK_Unknown) emitLocation(igLastCandidate);
2516                 callbackFunc(context, pEmitLoc);
2517                 igLastReported  = igLastCandidate;
2518                 igLastCandidate = NULL;
2519                 curSize -= candidateSize;
2520             }
2521         }
2522
2523         // Update the current candidate to be this block, if it isn't in the middle of a
2524         // prolog or epilog, which we can't split. All we know is that certain
2525         // IGs are marked as prolog or epilog. We don't actually know if two adjacent
2526         // IGs are part of the *same* prolog or epilog, so we have to assume they are.
2527
2528         if (igPrev && (((igPrev->igFlags & IGF_FUNCLET_PROLOG) && (ig->igFlags & IGF_FUNCLET_PROLOG)) ||
2529                        ((igPrev->igFlags & IGF_EPILOG) && (ig->igFlags & IGF_EPILOG))))
2530         {
2531             // We can't update the candidate
2532         }
2533         else
2534         {
2535             igLastCandidate = ig;
2536             candidateSize   = curSize;
2537         }
2538
2539         curSize += ig->igSize;
2540
2541     } // end for loop
2542 }
2543
2544 /*****************************************************************************
2545  *
2546  * Given an instruction group, find the array of instructions (instrDesc) and
2547  * number of instructions in the array. If the IG is the current IG, we assume
2548  * that igData does NOT hold the instructions; they are unsaved and pointed
2549  * to by emitCurIGfreeBase.
2550  *
2551  * This function can't be called for placeholder groups, which have no instrDescs.
2552  */
2553
2554 void emitter::emitGetInstrDescs(insGroup* ig, instrDesc** id, int* insCnt)
2555 {
2556     assert(!(ig->igFlags & IGF_PLACEHOLDER));
2557     if (ig == emitCurIG)
2558     {
2559         *id     = (instrDesc*)emitCurIGfreeBase;
2560         *insCnt = emitCurIGinsCnt;
2561     }
2562     else
2563     {
2564         *id     = (instrDesc*)ig->igData;
2565         *insCnt = ig->igInsCnt;
2566     }
2567
2568     assert(*id);
2569 }
2570
2571 /*****************************************************************************
2572  *
2573  * Given a location (an 'emitLocation'), find the instruction group (IG) and
2574  * instruction descriptor (instrDesc) corresponding to that location. Returns
2575  * 'true' if there is an instruction, 'false' if there is no instruction
2576  * (i.e., we're at the end of the instruction list). Also, optionally return
2577  * the number of instructions that follow that instruction in the IG (in *pinsRemaining,
2578  * if pinsRemaining is non-NULL), which can be used for iterating over the
2579  * remaining instrDescs in the IG.
2580  *
2581  * We assume that emitCurIG points to the end of the instructions we care about.
2582  * For the prologs or epilogs, it points to the last IG of the prolog or epilog
2583  * that is being generated. For body code gen, it points to the place we are currently
2584  * adding code, namely, the end of currently generated code.
2585  */
2586
2587 bool emitter::emitGetLocationInfo(emitLocation* emitLoc,
2588                                   insGroup**    pig,
2589                                   instrDesc**   pid,
2590                                   int*          pinsRemaining /* = NULL */)
2591 {
2592     assert(emitLoc != nullptr);
2593     assert(emitLoc->Valid());
2594     assert(emitLoc->GetIG() != nullptr);
2595     assert(pig != nullptr);
2596     assert(pid != nullptr);
2597
2598     insGroup*  ig = emitLoc->GetIG();
2599     instrDesc* id;
2600     int        insNum = emitLoc->GetInsNum();
2601     int        insCnt;
2602
2603     emitGetInstrDescs(ig, &id, &insCnt);
2604     assert(insNum <= insCnt);
2605
2606     // There is a special-case: if the insNum points to the end, then we "wrap" and
2607     // consider that the instruction it is pointing at is actually the first instruction
2608     // of the next non-empty IG (which has its own valid emitLocation). This handles the
2609     // case where you capture a location, then the next instruction creates a new IG.
2610
2611     if (insNum == insCnt)
2612     {
2613         if (ig == emitCurIG)
2614         {
2615             // No instructions beyond the current location.
2616             return false;
2617         }
2618
2619         for (ig = ig->igNext; ig; ig = ig->igNext)
2620         {
2621             emitGetInstrDescs(ig, &id, &insCnt);
2622
2623             if (insCnt > 0)
2624             {
2625                 insNum = 0; // Pretend the index is 0 -- the first instruction
2626                 break;
2627             }
2628
2629             if (ig == emitCurIG)
2630             {
2631                 // There aren't any instructions in the current IG, and this is
2632                 // the current location, so we're at the end.
2633                 return false;
2634             }
2635         }
2636
2637         if (ig == NULL)
2638         {
2639             // 'ig' can't be NULL, or we went past the current IG represented by 'emitCurIG'.
2640             // Perhaps 'loc' was corrupt coming in?
2641             noway_assert(!"corrupt emitter location");
2642             return false;
2643         }
2644     }
2645
2646     // Now find the instrDesc within this group that corresponds to the location
2647
2648     assert(insNum < insCnt);
2649
2650     int i;
2651     for (i = 0; i != insNum; ++i)
2652     {
2653         castto(id, BYTE*) += emitSizeOfInsDsc(id);
2654     }
2655
2656     // Return the info we found
2657
2658     *pig = ig;
2659     *pid = id;
2660
2661     if (pinsRemaining)
2662     {
2663         *pinsRemaining = insCnt - insNum - 1;
2664     }
2665
2666     return true;
2667 }
2668
2669 /*****************************************************************************
2670  *
2671  * Compute the next instrDesc, either in this IG, or in a subsequent IG. 'id'
2672  * will point to this instrDesc. 'ig' and 'insRemaining' will also be updated.
2673  * Returns true if there is an instruction, or false if we've iterated over all
2674  * the instructions up to the current instruction (based on 'emitCurIG').
2675  */
2676
2677 bool emitter::emitNextID(insGroup*& ig, instrDesc*& id, int& insRemaining)
2678 {
2679     if (insRemaining > 0)
2680     {
2681         castto(id, BYTE*) += emitSizeOfInsDsc(id);
2682         --insRemaining;
2683         return true;
2684     }
2685
2686     // We're out of instrDesc in 'ig'. Is this the current IG? If so, we're done.
2687
2688     if (ig == emitCurIG)
2689     {
2690         return false;
2691     }
2692
2693     for (ig = ig->igNext; ig; ig = ig->igNext)
2694     {
2695         int insCnt;
2696         emitGetInstrDescs(ig, &id, &insCnt);
2697
2698         if (insCnt > 0)
2699         {
2700             insRemaining = insCnt - 1;
2701             return true;
2702         }
2703
2704         if (ig == emitCurIG)
2705         {
2706             return false;
2707         }
2708     }
2709
2710     return false;
2711 }
2712
2713 /*****************************************************************************
2714  *
2715  * Walk instrDesc's from the location given by 'locFrom', up to the current location.
2716  * For each instruction, call the callback function 'processFunc'. 'context' is simply
2717  * passed through to the callback function.
2718  */
2719
2720 void emitter::emitWalkIDs(emitLocation* locFrom, emitProcessInstrFunc_t processFunc, void* context)
2721 {
2722     insGroup*  ig;
2723     instrDesc* id;
2724     int        insRemaining;
2725
2726     if (!emitGetLocationInfo(locFrom, &ig, &id, &insRemaining))
2727         return; // no instructions at the 'from' location
2728
2729     do
2730     {
2731         // process <<id>>
2732         (*processFunc)(id, context);
2733
2734     } while (emitNextID(ig, id, insRemaining));
2735 }
2736
2737 /*****************************************************************************
2738  *
2739  * A callback function for emitWalkIDs() that calls Compiler::unwindNop().
2740  */
2741
2742 void emitter::emitGenerateUnwindNop(instrDesc* id, void* context)
2743 {
2744     Compiler* comp = (Compiler*)context;
2745 #if defined(_TARGET_ARM_)
2746     comp->unwindNop(id->idCodeSize());
2747 #elif defined(_TARGET_ARM64_)
2748     comp->unwindNop();
2749 #endif // defined(_TARGET_ARM64_)
2750 }
2751
2752 /*****************************************************************************
2753  *
2754  * emitUnwindNopPadding: call unwindNop() for every instruction from a given
2755  * location 'emitLoc' up to the current location.
2756  */
2757
2758 void emitter::emitUnwindNopPadding(emitLocation* locFrom, Compiler* comp)
2759 {
2760     emitWalkIDs(locFrom, emitGenerateUnwindNop, comp);
2761 }
2762
2763 #endif // _TARGET_ARMARCH_
2764
2765 #if defined(_TARGET_ARM_)
2766
2767 /*****************************************************************************
2768  *
2769  * Return the instruction size in bytes for the instruction at the specified location.
2770  * This is used to assert that the unwind code being generated on ARM has the
2771  * same size as the instruction for which it is being generated (since on ARM
2772  * the unwind codes have a one-to-one relationship with instructions, and the
2773  * unwind codes have an implicit instruction size that must match the instruction size.)
2774  * An instruction must exist at the specified location.
2775  */
2776
2777 unsigned emitter::emitGetInstructionSize(emitLocation* emitLoc)
2778 {
2779     insGroup*  ig;
2780     instrDesc* id;
2781
2782     bool anyInstrs = emitGetLocationInfo(emitLoc, &ig, &id);
2783     assert(anyInstrs); // There better be an instruction at this location (otherwise, we're at the end of the
2784                        // instruction list)
2785     return id->idCodeSize();
2786 }
2787
2788 #endif // defined(_TARGET_ARM_)
2789
2790 /*****************************************************************************/
2791 #ifdef DEBUG
2792 /*****************************************************************************
2793  *
2794  *  Returns the name for the register to use to access frame based variables
2795  */
2796
2797 const char* emitter::emitGetFrameReg()
2798 {
2799     if (emitHasFramePtr)
2800     {
2801         return STR_FPBASE;
2802     }
2803     else
2804     {
2805         return STR_SPBASE;
2806     }
2807 }
2808
2809 /*****************************************************************************
2810  *
2811  *  Display a register set in a readable form.
2812  */
2813
2814 void emitter::emitDispRegSet(regMaskTP regs)
2815 {
2816     regNumber reg;
2817     bool      sp = false;
2818
2819     printf(" {");
2820
2821     for (reg = REG_FIRST; reg < ACTUAL_REG_COUNT; reg = REG_NEXT(reg))
2822     {
2823         if ((regs & genRegMask(reg)) == 0)
2824         {
2825             continue;
2826         }
2827
2828         if (sp)
2829         {
2830             printf(" ");
2831         }
2832         else
2833         {
2834             sp = true;
2835         }
2836
2837         printf("%s", emitRegName(reg));
2838     }
2839
2840     printf("}");
2841 }
2842
2843 /*****************************************************************************
2844  *
2845  *  Display the current GC ref variable set in a readable form.
2846  */
2847
2848 void emitter::emitDispVarSet()
2849 {
2850     unsigned vn;
2851     int      of;
2852     bool     sp = false;
2853
2854     for (vn = 0, of = emitGCrFrameOffsMin; vn < emitGCrFrameOffsCnt; vn += 1, of += sizeof(void*))
2855     {
2856         if (emitGCrFrameLiveTab[vn])
2857         {
2858             if (sp)
2859             {
2860                 printf(" ");
2861             }
2862             else
2863             {
2864                 sp = true;
2865             }
2866
2867             printf("[%s", emitGetFrameReg());
2868
2869             if (of < 0)
2870             {
2871                 printf("-%02XH", -of);
2872             }
2873             else if (of > 0)
2874             {
2875                 printf("+%02XH", +of);
2876             }
2877
2878             printf("]");
2879         }
2880     }
2881
2882     if (!sp)
2883     {
2884         printf("none");
2885     }
2886 }
2887
2888 /*****************************************************************************/
2889 #endif // DEBUG
2890
2891 #if MULTIREG_HAS_SECOND_GC_RET
2892 //------------------------------------------------------------------------
2893 // emitSetSecondRetRegGCType: Sets the GC type of the second return register for instrDescCGCA struct.
2894 //
2895 // Arguments:
2896 //    id            - The large call instr descriptor to set the second GC return register type on.
2897 //    secondRetSize - The EA_SIZE for second return register type.
2898 //
2899 // Return Value:
2900 //    None
2901 //
2902
2903 void emitter::emitSetSecondRetRegGCType(instrDescCGCA* id, emitAttr secondRetSize)
2904 {
2905     if (EA_IS_GCREF(secondRetSize))
2906     {
2907         id->idSecondGCref(GCT_GCREF);
2908     }
2909     else if (EA_IS_BYREF(secondRetSize))
2910     {
2911         id->idSecondGCref(GCT_BYREF);
2912     }
2913     else
2914     {
2915         id->idSecondGCref(GCT_NONE);
2916     }
2917 }
2918 #endif // MULTIREG_HAS_SECOND_GC_RET
2919
2920 /*****************************************************************************
2921  *
2922  *  Allocate an instruction descriptor for an indirect call.
2923  *
2924  *  We use two different descriptors to save space - the common case records
2925  *  no GC variables and has both a very small argument count and an address
2926  *  mode displacement; the other case records the current GC var set,
2927  *  the call scope, and an arbitrarily large argument count and the
2928  *  address mode displacement.
2929  */
2930
2931 emitter::instrDesc* emitter::emitNewInstrCallInd(int              argCnt,
2932                                                  ssize_t          disp,
2933                                                  VARSET_VALARG_TP GCvars,
2934                                                  regMaskTP        gcrefRegs,
2935                                                  regMaskTP        byrefRegs,
2936                                                  emitAttr         retSizeIn
2937                                                      MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(emitAttr secondRetSize))
2938 {
2939     emitAttr retSize = (retSizeIn != EA_UNKNOWN) ? retSizeIn : EA_PTRSIZE;
2940
2941     bool gcRefRegsInScratch = ((gcrefRegs & RBM_CALLEE_TRASH) != 0);
2942
2943     // Allocate a larger descriptor if any GC values need to be saved
2944     // or if we have an absurd number of arguments or a large address
2945     // mode displacement, or we have some byref registers
2946     //
2947     // On Amd64 System V OSs a larger descriptor is also needed if the
2948     // call returns a two-register-returned struct and the second
2949     // register (RDX) is a GCRef or ByRef pointer.
2950
2951     if (!VarSetOps::IsEmpty(emitComp, GCvars) || // any frame GCvars live
2952         (gcRefRegsInScratch) ||                  // any register gc refs live in scratch regs
2953         (byrefRegs != 0) ||                      // any register byrefs live
2954         (disp < AM_DISP_MIN) ||                  // displacement too negative
2955         (disp > AM_DISP_MAX) ||                  // displacement too positive
2956         (argCnt > ID_MAX_SMALL_CNS) ||           // too many args
2957         (argCnt < 0)                             // caller pops arguments
2958                                                  // There is a second ref/byref return register.
2959         MULTIREG_HAS_SECOND_GC_RET_ONLY(|| EA_IS_GCREF_OR_BYREF(secondRetSize)))
2960     {
2961         instrDescCGCA* id;
2962
2963         id = emitAllocInstrCGCA(retSize);
2964
2965         id->idSetIsLargeCall();
2966
2967         VarSetOps::Assign(emitComp, id->idcGCvars, GCvars);
2968         id->idcGcrefRegs = gcrefRegs;
2969         id->idcByrefRegs = byrefRegs;
2970         id->idcArgCnt    = argCnt;
2971         id->idcDisp      = disp;
2972
2973 #if MULTIREG_HAS_SECOND_GC_RET
2974         emitSetSecondRetRegGCType(id, secondRetSize);
2975 #endif // MULTIREG_HAS_SECOND_GC_RET
2976
2977         return id;
2978     }
2979     else
2980     {
2981         instrDesc* id;
2982
2983         id = emitNewInstrCns(retSize, argCnt);
2984
2985         /* Make sure we didn't waste space unexpectedly */
2986         assert(!id->idIsLargeCns());
2987
2988         /* Store the displacement and make sure the value fit */
2989         id->idAddr()->iiaAddrMode.amDisp = disp;
2990         assert(id->idAddr()->iiaAddrMode.amDisp == disp);
2991
2992         /* Save the the live GC registers in the unused register fields */
2993         emitEncodeCallGCregs(gcrefRegs, id);
2994
2995         return id;
2996     }
2997 }
2998
2999 /*****************************************************************************
3000  *
3001  *  Allocate an instruction descriptor for a direct call.
3002  *
3003  *  We use two different descriptors to save space - the common case records
3004  *  with no GC variables or byrefs and has a very small argument count, and no
3005  *  explicit scope;
3006  *  the other case records the current GC var set, the call scope,
3007  *  and an arbitrarily large argument count.
3008  */
3009
3010 emitter::instrDesc* emitter::emitNewInstrCallDir(int              argCnt,
3011                                                  VARSET_VALARG_TP GCvars,
3012                                                  regMaskTP        gcrefRegs,
3013                                                  regMaskTP        byrefRegs,
3014                                                  emitAttr         retSizeIn
3015                                                      MULTIREG_HAS_SECOND_GC_RET_ONLY_ARG(emitAttr secondRetSize))
3016 {
3017     emitAttr retSize = (retSizeIn != EA_UNKNOWN) ? retSizeIn : EA_PTRSIZE;
3018
3019     // Allocate a larger descriptor if new GC values need to be saved
3020     // or if we have an absurd number of arguments or if we need to
3021     // save the scope.
3022     //
3023     // On Amd64 System V OSs a larger descriptor is also needed if the
3024     // call returns a two-register-returned struct and the second
3025     // register (RDX) is a GCRef or ByRef pointer.
3026
3027     bool gcRefRegsInScratch = ((gcrefRegs & RBM_CALLEE_TRASH) != 0);
3028
3029     if (!VarSetOps::IsEmpty(emitComp, GCvars) || // any frame GCvars live
3030         gcRefRegsInScratch ||                    // any register gc refs live in scratch regs
3031         (byrefRegs != 0) ||                      // any register byrefs live
3032         (argCnt > ID_MAX_SMALL_CNS) ||           // too many args
3033         (argCnt < 0)                             // caller pops arguments
3034                                                  // There is a second ref/byref return register.
3035         MULTIREG_HAS_SECOND_GC_RET_ONLY(|| EA_IS_GCREF_OR_BYREF(secondRetSize)))
3036     {
3037         instrDescCGCA* id = emitAllocInstrCGCA(retSize);
3038
3039         // printf("Direct call with GC vars / big arg cnt / explicit scope\n");
3040
3041         id->idSetIsLargeCall();
3042
3043         VarSetOps::Assign(emitComp, id->idcGCvars, GCvars);
3044         id->idcGcrefRegs = gcrefRegs;
3045         id->idcByrefRegs = byrefRegs;
3046         id->idcDisp      = 0;
3047         id->idcArgCnt    = argCnt;
3048
3049 #if MULTIREG_HAS_SECOND_GC_RET
3050         emitSetSecondRetRegGCType(id, secondRetSize);
3051 #endif // MULTIREG_HAS_SECOND_GC_RET
3052
3053         return id;
3054     }
3055     else
3056     {
3057         instrDesc* id = emitNewInstrCns(retSize, argCnt);
3058
3059         // printf("Direct call w/o  GC vars / big arg cnt / explicit scope\n");
3060
3061         /* Make sure we didn't waste space unexpectedly */
3062         assert(!id->idIsLargeCns());
3063
3064         /* Save the the live GC registers in the unused register fields */
3065         emitEncodeCallGCregs(gcrefRegs, id);
3066
3067         return id;
3068     }
3069 }
3070
3071 /*****************************************************************************/
3072 #ifdef DEBUG
3073 /*****************************************************************************
3074  *
3075  *  Return a string with the name of the given class field (blank string (not
3076  *  NULL) is returned when the name isn't available).
3077  */
3078
3079 const char* emitter::emitFldName(CORINFO_FIELD_HANDLE fieldVal)
3080 {
3081     if (emitComp->opts.varNames)
3082     {
3083         const char* memberName;
3084         const char* className;
3085
3086         const int   TEMP_BUFFER_LEN = 1024;
3087         static char buff[TEMP_BUFFER_LEN];
3088
3089         memberName = emitComp->eeGetFieldName(fieldVal, &className);
3090
3091         sprintf_s(buff, TEMP_BUFFER_LEN, "'<%s>.%s'", className, memberName);
3092         return buff;
3093     }
3094     else
3095     {
3096         return "";
3097     }
3098 }
3099
3100 /*****************************************************************************
3101  *
3102  *  Return a string with the name of the given function (blank string (not
3103  *  NULL) is returned when the name isn't available).
3104  */
3105
3106 const char* emitter::emitFncName(CORINFO_METHOD_HANDLE methHnd)
3107 {
3108     return emitComp->eeGetMethodFullName(methHnd);
3109 }
3110
3111 #endif // DEBUG
3112
3113 /*****************************************************************************
3114  *
3115  *  Be very careful, some instruction descriptors are allocated as "tiny" and
3116  *  don't have some of the tail fields of instrDesc (in particular, "idInfo").
3117  */
3118
3119 const BYTE emitter::emitFmtToOps[] = {
3120 #define IF_DEF(en, op1, op2) ID_OP_##op2,
3121 #include "emitfmts.h"
3122 };
3123
3124 #ifdef DEBUG
3125 const unsigned emitter::emitFmtCount = sizeof(emitFmtToOps) / sizeof(emitFmtToOps[0]);
3126 #endif
3127
3128 /*****************************************************************************
3129  *
3130  *  Display the current instruction group list.
3131  */
3132
3133 #ifdef DEBUG
3134
3135 void emitter::emitDispIGflags(unsigned flags)
3136 {
3137     if (flags & IGF_GC_VARS)
3138     {
3139         printf(", gcvars");
3140     }
3141     if (flags & IGF_BYREF_REGS)
3142     {
3143         printf(", byref");
3144     }
3145 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3146     if (flags & IGF_FINALLY_TARGET)
3147     {
3148         printf(", ftarget");
3149     }
3150 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
3151     if (flags & IGF_FUNCLET_PROLOG)
3152     {
3153         printf(", funclet prolog");
3154     }
3155     if (flags & IGF_FUNCLET_EPILOG)
3156     {
3157         printf(", funclet epilog");
3158     }
3159     if (flags & IGF_EPILOG)
3160     {
3161         printf(", epilog");
3162     }
3163     if (flags & IGF_NOGCINTERRUPT)
3164     {
3165         printf(", nogc");
3166     }
3167     if (flags & IGF_UPD_ISZ)
3168     {
3169         printf(", isz");
3170     }
3171     if (flags & IGF_EMIT_ADD)
3172     {
3173         printf(", emitadd");
3174     }
3175 }
3176
3177 void emitter::emitDispIG(insGroup* ig, insGroup* igPrev, bool verbose)
3178 {
3179     const int TEMP_BUFFER_LEN = 40;
3180     char      buff[TEMP_BUFFER_LEN];
3181
3182     sprintf_s(buff, TEMP_BUFFER_LEN, "G_M%03u_IG%02u:        ", Compiler::s_compMethodsCount, ig->igNum);
3183     printf("%s; ", buff);
3184     if ((igPrev == nullptr) || (igPrev->igFuncIdx != ig->igFuncIdx))
3185     {
3186         printf("func=%02u, ", ig->igFuncIdx);
3187     }
3188
3189     if (ig->igFlags & IGF_PLACEHOLDER)
3190     {
3191         insGroup* igPh = ig;
3192
3193         const char* pszType;
3194         switch (igPh->igPhData->igPhType)
3195         {
3196             case IGPT_PROLOG:
3197                 pszType = "prolog";
3198                 break;
3199             case IGPT_EPILOG:
3200                 pszType = "epilog";
3201                 break;
3202 #if FEATURE_EH_FUNCLETS
3203             case IGPT_FUNCLET_PROLOG:
3204                 pszType = "funclet prolog";
3205                 break;
3206             case IGPT_FUNCLET_EPILOG:
3207                 pszType = "funclet epilog";
3208                 break;
3209 #endif // FEATURE_EH_FUNCLETS
3210             default:
3211                 pszType = "UNKNOWN";
3212                 break;
3213         }
3214         printf("%s placeholder, next placeholder=", pszType);
3215         if (igPh->igPhData->igPhNext)
3216         {
3217             printf("IG%02u ", igPh->igPhData->igPhNext->igNum);
3218         }
3219         else
3220         {
3221             printf("<END>");
3222         }
3223
3224         if (igPh->igPhData->igPhBB != nullptr)
3225         {
3226             printf(", %s", igPh->igPhData->igPhBB->dspToString());
3227         }
3228
3229         emitDispIGflags(igPh->igFlags);
3230
3231         if (ig == emitCurIG)
3232         {
3233             printf(" <-- Current IG");
3234         }
3235         if (igPh == emitPlaceholderList)
3236         {
3237             printf(" <-- First placeholder");
3238         }
3239         if (igPh == emitPlaceholderLast)
3240         {
3241             printf(" <-- Last placeholder");
3242         }
3243         printf("\n");
3244
3245         printf("%*s;   PrevGCVars=%s ", strlen(buff), "",
3246                VarSetOps::ToString(emitComp, igPh->igPhData->igPhPrevGCrefVars));
3247         dumpConvertedVarSet(emitComp, igPh->igPhData->igPhPrevGCrefVars);
3248         printf(", PrevGCrefRegs=");
3249         printRegMaskInt(igPh->igPhData->igPhPrevGCrefRegs);
3250         emitDispRegSet(igPh->igPhData->igPhPrevGCrefRegs);
3251         printf(", PrevByrefRegs=");
3252         printRegMaskInt(igPh->igPhData->igPhPrevByrefRegs);
3253         emitDispRegSet(igPh->igPhData->igPhPrevByrefRegs);
3254         printf("\n");
3255
3256         printf("%*s;   InitGCVars=%s ", strlen(buff), "",
3257                VarSetOps::ToString(emitComp, igPh->igPhData->igPhInitGCrefVars));
3258         dumpConvertedVarSet(emitComp, igPh->igPhData->igPhInitGCrefVars);
3259         printf(", InitGCrefRegs=");
3260         printRegMaskInt(igPh->igPhData->igPhInitGCrefRegs);
3261         emitDispRegSet(igPh->igPhData->igPhInitGCrefRegs);
3262         printf(", InitByrefRegs=");
3263         printRegMaskInt(igPh->igPhData->igPhInitByrefRegs);
3264         emitDispRegSet(igPh->igPhData->igPhInitByrefRegs);
3265         printf("\n");
3266
3267         assert(!(ig->igFlags & IGF_GC_VARS));
3268         assert(!(ig->igFlags & IGF_BYREF_REGS));
3269     }
3270     else
3271     {
3272         printf("offs=%06XH, size=%04XH", ig->igOffs, ig->igSize);
3273
3274         if (ig->igFlags & IGF_GC_VARS)
3275         {
3276             printf(", gcVars=%s ", VarSetOps::ToString(emitComp, ig->igGCvars()));
3277             dumpConvertedVarSet(emitComp, ig->igGCvars());
3278         }
3279
3280         if (!(ig->igFlags & IGF_EMIT_ADD))
3281         {
3282             printf(", gcrefRegs=");
3283             printRegMaskInt(ig->igGCregs);
3284             emitDispRegSet(ig->igGCregs);
3285         }
3286
3287         if (ig->igFlags & IGF_BYREF_REGS)
3288         {
3289             printf(", byrefRegs=");
3290             printRegMaskInt(ig->igByrefRegs());
3291             emitDispRegSet(ig->igByrefRegs());
3292         }
3293
3294         emitDispIGflags(ig->igFlags);
3295
3296         if (ig == emitCurIG)
3297         {
3298             printf(" <-- Current IG");
3299         }
3300         if (ig == emitPrologIG)
3301         {
3302             printf(" <-- Prolog IG");
3303         }
3304         printf("\n");
3305
3306         if (verbose)
3307         {
3308             BYTE*          ins = ig->igData;
3309             UNATIVE_OFFSET ofs = ig->igOffs;
3310             unsigned       cnt = ig->igInsCnt;
3311
3312             if (cnt)
3313             {
3314                 printf("\n");
3315
3316                 do
3317                 {
3318                     instrDesc* id = (instrDesc*)ins;
3319
3320                     emitDispIns(id, false, true, false, ofs, nullptr, 0, ig);
3321
3322                     ins += emitSizeOfInsDsc(id);
3323                     ofs += emitInstCodeSz(id);
3324                 } while (--cnt);
3325
3326                 printf("\n");
3327             }
3328         }
3329     }
3330 }
3331
3332 void emitter::emitDispIGlist(bool verbose)
3333 {
3334     insGroup* ig;
3335     insGroup* igPrev;
3336
3337     for (igPrev = nullptr, ig = emitIGlist; ig; igPrev = ig, ig = ig->igNext)
3338     {
3339         emitDispIG(ig, igPrev, verbose);
3340     }
3341 }
3342
3343 void emitter::emitDispGCinfo()
3344 {
3345     printf("Emitter GC tracking info:");
3346     printf("\n  emitPrevGCrefVars ");
3347     dumpConvertedVarSet(emitComp, emitPrevGCrefVars);
3348     printf("\n  emitPrevGCrefRegs(0x%p)=", dspPtr(&emitPrevGCrefRegs));
3349     printRegMaskInt(emitPrevGCrefRegs);
3350     emitDispRegSet(emitPrevGCrefRegs);
3351     printf("\n  emitPrevByrefRegs(0x%p)=", dspPtr(&emitPrevByrefRegs));
3352     printRegMaskInt(emitPrevByrefRegs);
3353     emitDispRegSet(emitPrevByrefRegs);
3354     printf("\n  emitInitGCrefVars ");
3355     dumpConvertedVarSet(emitComp, emitInitGCrefVars);
3356     printf("\n  emitInitGCrefRegs(0x%p)=", dspPtr(&emitInitGCrefRegs));
3357     printRegMaskInt(emitInitGCrefRegs);
3358     emitDispRegSet(emitInitGCrefRegs);
3359     printf("\n  emitInitByrefRegs(0x%p)=", dspPtr(&emitInitByrefRegs));
3360     printRegMaskInt(emitInitByrefRegs);
3361     emitDispRegSet(emitInitByrefRegs);
3362     printf("\n  emitThisGCrefVars ");
3363     dumpConvertedVarSet(emitComp, emitThisGCrefVars);
3364     printf("\n  emitThisGCrefRegs(0x%p)=", dspPtr(&emitThisGCrefRegs));
3365     printRegMaskInt(emitThisGCrefRegs);
3366     emitDispRegSet(emitThisGCrefRegs);
3367     printf("\n  emitThisByrefRegs(0x%p)=", dspPtr(&emitThisByrefRegs));
3368     printRegMaskInt(emitThisByrefRegs);
3369     emitDispRegSet(emitThisByrefRegs);
3370     printf("\n\n");
3371 }
3372
3373 #endif // DEBUG
3374
3375 /*****************************************************************************
3376  *
3377  *  Issue the given instruction. Basically, this is just a thin wrapper around
3378  *  emitOutputInstr() that does a few debug checks.
3379  */
3380
3381 size_t emitter::emitIssue1Instr(insGroup* ig, instrDesc* id, BYTE** dp)
3382 {
3383     size_t is;
3384
3385     /* Record the beginning offset of the instruction */
3386
3387     BYTE* curInsAdr = *dp;
3388
3389     /* Issue the next instruction */
3390
3391     // printf("[S=%02u] " , emitCurStackLvl);
3392
3393     is = emitOutputInstr(ig, id, dp);
3394
3395 // printf("[S=%02u]\n", emitCurStackLvl);
3396
3397 #if EMIT_TRACK_STACK_DEPTH
3398
3399     /*
3400         If we're generating a full pointer map and the stack
3401         is empty, there better not be any "pending" argument
3402         push entries.
3403      */
3404
3405     assert(emitFullGCinfo == false || emitCurStackLvl != 0 || u2.emitGcArgTrackCnt == 0);
3406
3407 #endif
3408
3409     /* Did the size of the instruction match our expectations? */
3410
3411     UNATIVE_OFFSET csz = (UNATIVE_OFFSET)(*dp - curInsAdr);
3412
3413     if (csz != id->idCodeSize())
3414     {
3415         /* It is fatal to under-estimate the instruction size */
3416         noway_assert(emitInstCodeSz(id) >= csz);
3417
3418 #if DEBUG_EMIT
3419         if (EMITVERBOSE)
3420         {
3421             printf("Instruction predicted size = %u, actual = %u\n", emitInstCodeSz(id), csz);
3422         }
3423 #endif // DEBUG_EMIT
3424
3425         /* The instruction size estimate wasn't accurate; remember this */
3426
3427         ig->igFlags |= IGF_UPD_ISZ;
3428 #if defined(_TARGET_XARCH_)
3429         id->idCodeSize(csz);
3430 #elif defined(_TARGET_ARM_)
3431 // This is done as part of emitSetShortJump();
3432 // insSize isz = emitInsSize(id->idInsFmt());
3433 // id->idInsSize(isz);
3434 #else
3435         /* It is fatal to over-estimate the instruction size */
3436         IMPL_LIMITATION("Over-estimated instruction size");
3437 #endif
3438     }
3439
3440 #ifdef DEBUG
3441     /* Make sure the instruction descriptor size also matches our expectations */
3442     if (is != emitSizeOfInsDsc(id))
3443     {
3444         printf("%s at %u: Expected size = %u , actual size = %u\n", emitIfName(id->idInsFmt()),
3445                id->idDebugOnlyInfo()->idNum, is, emitSizeOfInsDsc(id));
3446         assert(is == emitSizeOfInsDsc(id));
3447     }
3448 #endif
3449
3450     return is;
3451 }
3452
3453 /*****************************************************************************
3454  *
3455  *  Update the offsets of all the instruction groups (note: please don't be
3456  *  lazy and call this routine frequently, it walks the list of instruction
3457  *  groups and thus it isn't cheap).
3458  */
3459
3460 void emitter::emitRecomputeIGoffsets()
3461 {
3462     UNATIVE_OFFSET offs;
3463     insGroup*      ig;
3464
3465     for (ig = emitIGlist, offs = 0; ig; ig = ig->igNext)
3466     {
3467         ig->igOffs = offs;
3468         assert(IsCodeAligned(ig->igOffs));
3469         offs += ig->igSize;
3470     }
3471
3472     /* Set the total code size */
3473
3474     emitTotalCodeSize = offs;
3475
3476 #ifdef DEBUG
3477     emitCheckIGoffsets();
3478 #endif
3479 }
3480
3481 /*****************************************************************************
3482  *  Bind targets of relative jumps to choose the smallest possible encoding.
3483  *  X86 and AMD64 have a small and large encoding.
3484  *  ARM has a small, medium, and large encoding. The large encoding is a pseudo-op
3485  *      to handle greater range than the conditional branch instructions can handle.
3486  *  ARM64 has a small and large encoding for both conditional branch and loading label addresses.
3487  *      The large encodings are pseudo-ops that represent a multiple instruction sequence, similar to ARM. (Currently
3488  *      NYI).
3489  */
3490
3491 void emitter::emitJumpDistBind()
3492 {
3493 #ifdef DEBUG
3494     if (emitComp->verbose)
3495     {
3496         printf("*************** In emitJumpDistBind()\n");
3497     }
3498     if (EMIT_INSTLIST_VERBOSE)
3499     {
3500         printf("\nInstruction list before jump distance binding:\n\n");
3501         emitDispIGlist(true);
3502     }
3503 #endif
3504
3505     instrDescJmp* jmp;
3506
3507     UNATIVE_OFFSET minShortExtra; // The smallest offset greater than that required for a jump to be converted
3508                                   // to a small jump. If it is small enough, we will iterate in hopes of
3509                                   // converting those jumps we missed converting the first (or second...) time.
3510
3511 #if defined(_TARGET_ARM_)
3512     UNATIVE_OFFSET minMediumExtra; // Same as 'minShortExtra', but for medium-sized jumps.
3513 #endif                             // _TARGET_ARM_
3514
3515     UNATIVE_OFFSET adjIG;
3516     UNATIVE_OFFSET adjLJ;
3517     insGroup*      lstIG;
3518 #ifdef DEBUG
3519     insGroup* prologIG = emitPrologIG;
3520 #endif // DEBUG
3521
3522     int jmp_iteration = 1;
3523
3524 /*****************************************************************************/
3525 /* If we iterate to look for more jumps to shorten, we start again here.     */
3526 /*****************************************************************************/
3527
3528 AGAIN:
3529
3530 #ifdef DEBUG
3531     emitCheckIGoffsets();
3532 #endif
3533
3534 /*
3535     In the following loop we convert all jump targets from "BasicBlock *"
3536     to "insGroup *" values. We also estimate which jumps will be short.
3537  */
3538
3539 #ifdef DEBUG
3540     insGroup*     lastIG = nullptr;
3541     instrDescJmp* lastLJ = nullptr;
3542 #endif
3543
3544     lstIG         = nullptr;
3545     adjLJ         = 0;
3546     adjIG         = 0;
3547     minShortExtra = (UNATIVE_OFFSET)-1;
3548
3549 #if defined(_TARGET_ARM_)
3550     minMediumExtra = (UNATIVE_OFFSET)-1;
3551 #endif // _TARGET_ARM_
3552
3553     for (jmp = emitJumpList; jmp; jmp = jmp->idjNext)
3554     {
3555         insGroup* jmpIG;
3556         insGroup* tgtIG;
3557
3558         UNATIVE_OFFSET jsz; // size of the jump instruction in bytes
3559
3560         UNATIVE_OFFSET ssz = 0; // small  jump size
3561         NATIVE_OFFSET  nsd = 0; // small  jump max. neg distance
3562         NATIVE_OFFSET  psd = 0; // small  jump max. pos distance
3563
3564 #if defined(_TARGET_ARM_)
3565         UNATIVE_OFFSET msz = 0; // medium jump size
3566         NATIVE_OFFSET  nmd = 0; // medium jump max. neg distance
3567         NATIVE_OFFSET  pmd = 0; // medium jump max. pos distance
3568         NATIVE_OFFSET  mextra;  // How far beyond the medium jump range is this jump offset?
3569 #endif                          // _TARGET_ARM_
3570
3571         NATIVE_OFFSET  extra;           // How far beyond the short jump range is this jump offset?
3572         UNATIVE_OFFSET srcInstrOffs;    // offset of the source instruction of the jump
3573         UNATIVE_OFFSET srcEncodingOffs; // offset of the source used by the instruction set to calculate the relative
3574                                         // offset of the jump
3575         UNATIVE_OFFSET dstOffs;
3576         NATIVE_OFFSET  jmpDist; // the relative jump distance, as it will be encoded
3577         UNATIVE_OFFSET oldSize;
3578         UNATIVE_OFFSET sizeDif;
3579
3580 #ifdef _TARGET_XARCH_
3581         assert(jmp->idInsFmt() == IF_LABEL || jmp->idInsFmt() == IF_RWR_LABEL || jmp->idInsFmt() == IF_SWR_LABEL);
3582
3583         /* Figure out the smallest size we can end up with */
3584
3585         if (jmp->idInsFmt() == IF_LABEL)
3586         {
3587             if (emitIsCondJump(jmp))
3588             {
3589                 ssz = JCC_SIZE_SMALL;
3590                 nsd = JCC_DIST_SMALL_MAX_NEG;
3591                 psd = JCC_DIST_SMALL_MAX_POS;
3592             }
3593             else
3594             {
3595                 ssz = JMP_SIZE_SMALL;
3596                 nsd = JMP_DIST_SMALL_MAX_NEG;
3597                 psd = JMP_DIST_SMALL_MAX_POS;
3598             }
3599         }
3600 #endif // _TARGET_XARCH_
3601
3602 #ifdef _TARGET_ARM_
3603         assert((jmp->idInsFmt() == IF_T2_J1) || (jmp->idInsFmt() == IF_T2_J2) || (jmp->idInsFmt() == IF_T1_I) ||
3604                (jmp->idInsFmt() == IF_T1_K) || (jmp->idInsFmt() == IF_T1_M) || (jmp->idInsFmt() == IF_T2_M1) ||
3605                (jmp->idInsFmt() == IF_T2_N1) || (jmp->idInsFmt() == IF_T1_J3) || (jmp->idInsFmt() == IF_LARGEJMP));
3606
3607         /* Figure out the smallest size we can end up with */
3608
3609         if (emitIsCondJump(jmp))
3610         {
3611             ssz = JCC_SIZE_SMALL;
3612             nsd = JCC_DIST_SMALL_MAX_NEG;
3613             psd = JCC_DIST_SMALL_MAX_POS;
3614
3615             msz = JCC_SIZE_MEDIUM;
3616             nmd = JCC_DIST_MEDIUM_MAX_NEG;
3617             pmd = JCC_DIST_MEDIUM_MAX_POS;
3618         }
3619         else if (emitIsCmpJump(jmp))
3620         {
3621             ssz = JMP_SIZE_SMALL;
3622             nsd = 0;
3623             psd = 126;
3624         }
3625         else if (emitIsUncondJump(jmp))
3626         {
3627             ssz = JMP_SIZE_SMALL;
3628             nsd = JMP_DIST_SMALL_MAX_NEG;
3629             psd = JMP_DIST_SMALL_MAX_POS;
3630         }
3631         else if (emitIsLoadLabel(jmp))
3632         {
3633             ssz = LBL_SIZE_SMALL;
3634             nsd = LBL_DIST_SMALL_MAX_NEG;
3635             psd = LBL_DIST_SMALL_MAX_POS;
3636         }
3637         else
3638         {
3639             assert(!"Unknown jump instruction");
3640         }
3641 #endif // _TARGET_ARM_
3642
3643 #ifdef _TARGET_ARM64_
3644         /* Figure out the smallest size we can end up with */
3645
3646         if (emitIsCondJump(jmp))
3647         {
3648             ssz         = JCC_SIZE_SMALL;
3649             bool isTest = (jmp->idIns() == INS_tbz) || (jmp->idIns() == INS_tbnz);
3650
3651             nsd = (isTest) ? TB_DIST_SMALL_MAX_NEG : JCC_DIST_SMALL_MAX_NEG;
3652             psd = (isTest) ? TB_DIST_SMALL_MAX_POS : JCC_DIST_SMALL_MAX_POS;
3653         }
3654         else if (emitIsUncondJump(jmp))
3655         {
3656             // Nothing to do; we don't shrink these.
3657             assert(jmp->idjShort);
3658             ssz = JMP_SIZE_SMALL;
3659         }
3660         else if (emitIsLoadLabel(jmp))
3661         {
3662             ssz = LBL_SIZE_SMALL;
3663             nsd = LBL_DIST_SMALL_MAX_NEG;
3664             psd = LBL_DIST_SMALL_MAX_POS;
3665         }
3666         else if (emitIsLoadConstant(jmp))
3667         {
3668             ssz = LDC_SIZE_SMALL;
3669             nsd = LDC_DIST_SMALL_MAX_NEG;
3670             psd = LDC_DIST_SMALL_MAX_POS;
3671         }
3672         else
3673         {
3674             assert(!"Unknown jump instruction");
3675         }
3676 #endif // _TARGET_ARM64_
3677
3678 /* Make sure the jumps are properly ordered */
3679
3680 #ifdef DEBUG
3681         assert(lastLJ == nullptr || lastIG != jmp->idjIG || lastLJ->idjOffs < jmp->idjOffs);
3682         lastLJ = (lastIG == jmp->idjIG) ? jmp : nullptr;
3683
3684         assert(lastIG == nullptr || lastIG->igNum <= jmp->idjIG->igNum || jmp->idjIG == prologIG ||
3685                emitNxtIGnum > unsigned(0xFFFF)); // igNum might overflow
3686         lastIG = jmp->idjIG;
3687 #endif // DEBUG
3688
3689         /* Get hold of the current jump size */
3690
3691         jsz = emitSizeOfJump(jmp);
3692
3693         /* Get the group the jump is in */
3694
3695         jmpIG = jmp->idjIG;
3696
3697         /* Are we in a group different from the previous jump? */
3698
3699         if (lstIG != jmpIG)
3700         {
3701             /* Were there any jumps before this one? */
3702
3703             if (lstIG)
3704             {
3705                 /* Adjust the offsets of the intervening blocks */
3706
3707                 do
3708                 {
3709                     lstIG = lstIG->igNext;
3710                     assert(lstIG);
3711                     // printf("Adjusted offset of block %02u from %04X to %04X\n", lstIG->igNum, lstIG->igOffs,
3712                     // lstIG->igOffs - adjIG);
3713                     lstIG->igOffs -= adjIG;
3714                     assert(IsCodeAligned(lstIG->igOffs));
3715                 } while (lstIG != jmpIG);
3716             }
3717
3718             /* We've got the first jump in a new group */
3719
3720             adjLJ = 0;
3721             lstIG = jmpIG;
3722         }
3723
3724         /* Apply any local size adjustment to the jump's relative offset */
3725
3726         jmp->idjOffs -= adjLJ;
3727
3728         // If this is a jump via register, the instruction size does not change, so we are done.
3729         CLANG_FORMAT_COMMENT_ANCHOR;
3730
3731 #if defined(_TARGET_ARM64_)
3732         // JIT code and data will be allocated together for arm64 so the relative offset to JIT data is known.
3733         // In case such offset can be encodeable for `ldr` (+-1MB), shorten it.
3734         if (jmp->idAddr()->iiaIsJitDataOffset())
3735         {
3736             // Reference to JIT data
3737             assert(jmp->idIsBound());
3738             UNATIVE_OFFSET srcOffs = jmpIG->igOffs + jmp->idjOffs;
3739
3740             int doff = jmp->idAddr()->iiaGetJitDataOffset();
3741             assert(doff >= 0);
3742             ssize_t imm = emitGetInsSC(jmp);
3743             assert((imm >= 0) && (imm < 0x1000)); // 0x1000 is arbitrary, currently 'imm' is always 0
3744
3745             unsigned dataOffs = (unsigned)(doff + imm);
3746             assert(dataOffs < emitDataSize());
3747
3748             // Conservately assume JIT data starts after the entire code size.
3749             // TODO-ARM64: we might consider only hot code size which will be computed later in emitComputeCodeSizes().
3750             assert(emitTotalCodeSize > 0);
3751             UNATIVE_OFFSET maxDstOffs = emitTotalCodeSize + dataOffs;
3752
3753             // Check if the distance is within the encoding length.
3754             jmpDist = maxDstOffs - srcOffs;
3755             extra   = jmpDist - psd;
3756             if (extra <= 0)
3757             {
3758                 goto SHORT_JMP;
3759             }
3760
3761             // Keep the large form.
3762             continue;
3763         }
3764 #endif
3765
3766         /* Have we bound this jump's target already? */
3767
3768         if (jmp->idIsBound())
3769         {
3770             /* Does the jump already have the smallest size? */
3771
3772             if (jmp->idjShort)
3773             {
3774                 assert(emitSizeOfJump(jmp) == ssz);
3775
3776                 // We should not be jumping/branching across funclets/functions
3777                 emitCheckFuncletBranch(jmp, jmpIG);
3778
3779                 continue;
3780             }
3781
3782             tgtIG = jmp->idAddr()->iiaIGlabel;
3783         }
3784         else
3785         {
3786             /* First time we've seen this label, convert its target */
3787             CLANG_FORMAT_COMMENT_ANCHOR;
3788
3789 #ifdef DEBUG
3790             if (EMITVERBOSE)
3791             {
3792                 printf("Binding: ");
3793                 emitDispIns(jmp, false, false, false);
3794                 printf("Binding L_M%03u_BB%02u ", Compiler::s_compMethodsCount, jmp->idAddr()->iiaBBlabel->bbNum);
3795             }
3796 #endif // DEBUG
3797
3798             tgtIG = (insGroup*)emitCodeGetCookie(jmp->idAddr()->iiaBBlabel);
3799
3800 #ifdef DEBUG
3801             if (EMITVERBOSE)
3802             {
3803                 if (tgtIG)
3804                 {
3805                     printf("to G_M%03u_IG%02u\n", Compiler::s_compMethodsCount, tgtIG->igNum);
3806                 }
3807                 else
3808                 {
3809                     printf("-- ERROR, no emitter cookie for BB%02u; it is probably missing BBF_JMP_TARGET or "
3810                            "BBF_HAS_LABEL.\n",
3811                            jmp->idAddr()->iiaBBlabel->bbNum);
3812                 }
3813             }
3814             assert(tgtIG);
3815 #endif // DEBUG
3816
3817             /* Record the bound target */
3818
3819             jmp->idAddr()->iiaIGlabel = tgtIG;
3820             jmp->idSetIsBound();
3821         }
3822
3823         // We should not be jumping/branching across funclets/functions
3824         emitCheckFuncletBranch(jmp, jmpIG);
3825
3826 #ifdef _TARGET_XARCH_
3827         /* Done if this is not a variable-sized jump */
3828
3829         if ((jmp->idIns() == INS_push) || (jmp->idIns() == INS_mov) || (jmp->idIns() == INS_call) ||
3830             (jmp->idIns() == INS_push_hide))
3831         {
3832             continue;
3833         }
3834 #endif
3835 #ifdef _TARGET_ARM_
3836         if ((jmp->idIns() == INS_push) || (jmp->idIns() == INS_mov) || (jmp->idIns() == INS_movt) ||
3837             (jmp->idIns() == INS_movw))
3838         {
3839             continue;
3840         }
3841 #endif
3842 #ifdef _TARGET_ARM64_
3843         // There is only one size of unconditional branch; we don't support functions larger than 2^28 bytes (our branch
3844         // range).
3845         if (emitIsUncondJump(jmp))
3846         {
3847             continue;
3848         }
3849 #endif
3850
3851         /*
3852             In the following distance calculations, if we're not actually
3853             scheduling the code (i.e. reordering instructions), we can
3854             use the actual offset of the jump (rather than the beg/end of
3855             the instruction group) since the jump will not be moved around
3856             and thus its offset is accurate.
3857
3858             First we need to figure out whether this jump is a forward or
3859             backward one; to do this we simply look at the ordinals of the
3860             group that contains the jump and the target.
3861          */
3862
3863         srcInstrOffs = jmpIG->igOffs + jmp->idjOffs;
3864
3865         /* Note that the destination is always the beginning of an IG, so no need for an offset inside it */
3866         dstOffs = tgtIG->igOffs;
3867
3868 #if defined(_TARGET_ARM_)
3869         srcEncodingOffs =
3870             srcInstrOffs + 4; // For relative branches, ARM PC is always considered to be the instruction address + 4
3871 #elif defined(_TARGET_ARM64_)
3872         srcEncodingOffs =
3873             srcInstrOffs; // For relative branches, ARM64 PC is always considered to be the instruction address
3874 #else
3875         srcEncodingOffs = srcInstrOffs + ssz; // Encoding offset of relative offset for small branch
3876 #endif
3877
3878         if (jmpIG->igNum < tgtIG->igNum)
3879         {
3880             /* Forward jump */
3881
3882             /* Adjust the target offset by the current delta. This is a worst-case estimate, as jumps between
3883                here and the target could be shortened, causing the actual distance to shrink.
3884              */
3885
3886             dstOffs -= adjIG;
3887
3888             /* Compute the distance estimate */
3889
3890             jmpDist = dstOffs - srcEncodingOffs;
3891
3892             /* How much beyond the max. short distance does the jump go? */
3893
3894             extra = jmpDist - psd;
3895
3896 #if DEBUG_EMIT
3897             assert(jmp->idDebugOnlyInfo() != nullptr);
3898             if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
3899             {
3900                 if (INTERESTING_JUMP_NUM == 0)
3901                 {
3902                     printf("[1] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
3903                 }
3904                 printf("[1] Jump  block is at %08X\n", jmpIG->igOffs);
3905                 printf("[1] Jump reloffset is %04X\n", jmp->idjOffs);
3906                 printf("[1] Jump source is at %08X\n", srcEncodingOffs);
3907                 printf("[1] Label block is at %08X\n", dstOffs);
3908                 printf("[1] Jump  dist. is    %04X\n", jmpDist);
3909                 if (extra > 0)
3910                 {
3911                     printf("[1] Dist excess [S] = %d  \n", extra);
3912                 }
3913             }
3914             if (EMITVERBOSE)
3915             {
3916                 printf("Estimate of fwd jump [%08X/%03u]: %04X -> %04X = %04X\n", dspPtr(jmp),
3917                        jmp->idDebugOnlyInfo()->idNum, srcInstrOffs, dstOffs, jmpDist);
3918             }
3919 #endif // DEBUG_EMIT
3920
3921             if (extra <= 0)
3922             {
3923                 /* This jump will be a short one */
3924                 goto SHORT_JMP;
3925             }
3926         }
3927         else
3928         {
3929             /* Backward jump */
3930
3931             /* Compute the distance estimate */
3932
3933             jmpDist = srcEncodingOffs - dstOffs;
3934
3935             /* How much beyond the max. short distance does the jump go? */
3936
3937             extra = jmpDist + nsd;
3938
3939 #if DEBUG_EMIT
3940             assert(jmp->idDebugOnlyInfo() != nullptr);
3941             if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
3942             {
3943                 if (INTERESTING_JUMP_NUM == 0)
3944                 {
3945                     printf("[2] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
3946                 }
3947                 printf("[2] Jump  block is at %08X\n", jmpIG->igOffs);
3948                 printf("[2] Jump reloffset is %04X\n", jmp->idjOffs);
3949                 printf("[2] Jump source is at %08X\n", srcEncodingOffs);
3950                 printf("[2] Label block is at %08X\n", dstOffs);
3951                 printf("[2] Jump  dist. is    %04X\n", jmpDist);
3952                 if (extra > 0)
3953                 {
3954                     printf("[2] Dist excess [S] = %d  \n", extra);
3955                 }
3956             }
3957             if (EMITVERBOSE)
3958             {
3959                 printf("Estimate of bwd jump [%08X/%03u]: %04X -> %04X = %04X\n", dspPtr(jmp),
3960                        jmp->idDebugOnlyInfo()->idNum, srcInstrOffs, dstOffs, jmpDist);
3961             }
3962 #endif // DEBUG_EMIT
3963
3964             if (extra <= 0)
3965             {
3966                 /* This jump will be a short one */
3967                 goto SHORT_JMP;
3968             }
3969         }
3970
3971         /* We arrive here if the jump couldn't be made short, at least for now */
3972
3973         /* We had better not have eagerly marked the jump as short
3974          * in emitIns_J(). If we did, then it has to be able to stay short
3975          * as emitIns_J() uses the worst case scenario, and blocks can
3976          * only move closer together after that.
3977          */
3978         assert(jmp->idjShort == 0);
3979
3980         /* Keep track of the closest distance we got */
3981
3982         if (minShortExtra > (unsigned)extra)
3983         {
3984             minShortExtra = (unsigned)extra;
3985         }
3986
3987 #if defined(_TARGET_ARM_)
3988
3989         // If we're here, we couldn't convert to a small jump.
3990         // Handle conversion to medium-sized conditional jumps.
3991         // 'srcInstrOffs', 'srcEncodingOffs', 'dstOffs', 'jmpDist' have already been computed
3992         // and don't need to be recomputed.
3993
3994         if (emitIsCondJump(jmp))
3995         {
3996             if (jmpIG->igNum < tgtIG->igNum)
3997             {
3998                 /* Forward jump */
3999
4000                 /* How much beyond the max. medium distance does the jump go? */
4001
4002                 mextra = jmpDist - pmd;
4003
4004 #if DEBUG_EMIT
4005                 assert(jmp->idDebugOnlyInfo() != NULL);
4006                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4007                 {
4008                     if (mextra > 0)
4009                     {
4010                         if (INTERESTING_JUMP_NUM == 0)
4011                             printf("[6] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4012                         printf("[6] Dist excess [S] = %d  \n", mextra);
4013                     }
4014                 }
4015 #endif // DEBUG_EMIT
4016
4017                 if (mextra <= 0)
4018                 {
4019                     /* This jump will be a medium one */
4020                     goto MEDIUM_JMP;
4021                 }
4022             }
4023             else
4024             {
4025                 /* Backward jump */
4026
4027                 /* How much beyond the max. medium distance does the jump go? */
4028
4029                 mextra = jmpDist + nmd;
4030
4031 #if DEBUG_EMIT
4032                 assert(jmp->idDebugOnlyInfo() != NULL);
4033                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4034                 {
4035                     if (mextra > 0)
4036                     {
4037                         if (INTERESTING_JUMP_NUM == 0)
4038                             printf("[7] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4039                         printf("[7] Dist excess [S] = %d  \n", mextra);
4040                     }
4041                 }
4042 #endif // DEBUG_EMIT
4043
4044                 if (mextra <= 0)
4045                 {
4046                     /* This jump will be a medium one */
4047                     goto MEDIUM_JMP;
4048                 }
4049             }
4050
4051             /* We arrive here if the jump couldn't be made medium, at least for now */
4052
4053             /* Keep track of the closest distance we got */
4054
4055             if (minMediumExtra > (unsigned)mextra)
4056                 minMediumExtra = (unsigned)mextra;
4057         }
4058
4059 #endif // _TARGET_ARM_
4060
4061         /*****************************************************************************
4062          * We arrive here if the jump must stay long, at least for now.
4063          * Go try the next one.
4064          */
4065
4066         continue;
4067
4068     /*****************************************************************************/
4069     /* Handle conversion to short jump                                           */
4070     /*****************************************************************************/
4071
4072     SHORT_JMP:
4073
4074         /* Try to make this jump a short one */
4075
4076         emitSetShortJump(jmp);
4077
4078         if (!jmp->idjShort)
4079         {
4080             continue; // This jump must be kept long
4081         }
4082
4083         /* This jump is becoming either short or medium */
4084
4085         oldSize = jsz;
4086         jsz     = ssz;
4087         assert(oldSize >= jsz);
4088         sizeDif = oldSize - jsz;
4089
4090 #if defined(_TARGET_XARCH_)
4091         jmp->idCodeSize(jsz);
4092 #elif defined(_TARGET_ARM_)
4093 #if 0
4094         // This is done as part of emitSetShortJump():
4095         insSize isz = emitInsSize(jmp->idInsFmt());
4096         jmp->idInsSize(isz);
4097 #endif
4098 #elif defined(_TARGET_ARM64_)
4099         // The size of IF_LARGEJMP/IF_LARGEADR/IF_LARGELDC are 8 or 12.
4100         // All other code size is 4.
4101         assert((sizeDif == 4) || (sizeDif == 8));
4102 #else
4103 #error Unsupported or unset target architecture
4104 #endif
4105
4106         goto NEXT_JMP;
4107
4108 #if defined(_TARGET_ARM_)
4109
4110     /*****************************************************************************/
4111     /* Handle conversion to medium jump                                          */
4112     /*****************************************************************************/
4113
4114     MEDIUM_JMP:
4115
4116         /* Try to make this jump a medium one */
4117
4118         emitSetMediumJump(jmp);
4119
4120         if (jmp->idCodeSize() > msz)
4121         {
4122             continue; // This jump wasn't shortened
4123         }
4124         assert(jmp->idCodeSize() == msz);
4125
4126         /* This jump is becoming medium */
4127
4128         oldSize = jsz;
4129         jsz     = msz;
4130         assert(oldSize >= jsz);
4131         sizeDif = oldSize - jsz;
4132
4133         goto NEXT_JMP;
4134
4135 #endif // _TARGET_ARM_
4136
4137     /*****************************************************************************/
4138
4139     NEXT_JMP:
4140
4141         /* Make sure the size of the jump is marked correctly */
4142
4143         assert((0 == (jsz | jmpDist)) || (jsz == emitSizeOfJump(jmp)));
4144
4145 #ifdef DEBUG
4146         if (EMITVERBOSE)
4147         {
4148             printf("Shrinking jump [%08X/%03u]\n", dspPtr(jmp), jmp->idDebugOnlyInfo()->idNum);
4149         }
4150 #endif
4151         noway_assert((unsigned short)sizeDif == sizeDif);
4152
4153         adjIG += sizeDif;
4154         adjLJ += sizeDif;
4155         jmpIG->igSize -= (unsigned short)sizeDif;
4156         emitTotalCodeSize -= sizeDif;
4157
4158         /* The jump size estimate wasn't accurate; flag its group */
4159
4160         jmpIG->igFlags |= IGF_UPD_ISZ;
4161
4162     } // end for each jump
4163
4164     /* Did we shorten any jumps? */
4165
4166     if (adjIG)
4167     {
4168         /* Adjust offsets of any remaining blocks */
4169
4170         assert(lstIG);
4171
4172         for (;;)
4173         {
4174             lstIG = lstIG->igNext;
4175             if (!lstIG)
4176             {
4177                 break;
4178             }
4179             // printf("Adjusted offset of block %02u from %04X to %04X\n", lstIG->igNum, lstIG->igOffs,
4180             // lstIG->igOffs - adjIG);
4181             lstIG->igOffs -= adjIG;
4182             assert(IsCodeAligned(lstIG->igOffs));
4183         }
4184
4185 #ifdef DEBUG
4186         emitCheckIGoffsets();
4187 #endif
4188
4189         /* Is there a chance of other jumps becoming short? */
4190         CLANG_FORMAT_COMMENT_ANCHOR;
4191 #ifdef DEBUG
4192 #if defined(_TARGET_ARM_)
4193         if (EMITVERBOSE)
4194             printf("Total shrinkage = %3u, min extra short jump size = %3u, min extra medium jump size = %u\n", adjIG,
4195                    minShortExtra, minMediumExtra);
4196 #else
4197         if (EMITVERBOSE)
4198         {
4199             printf("Total shrinkage = %3u, min extra jump size = %3u\n", adjIG, minShortExtra);
4200         }
4201 #endif
4202 #endif
4203
4204         if ((minShortExtra <= adjIG)
4205 #if defined(_TARGET_ARM_)
4206             || (minMediumExtra <= adjIG)
4207 #endif // _TARGET_ARM_
4208                 )
4209         {
4210             jmp_iteration++;
4211
4212 #ifdef DEBUG
4213             if (EMITVERBOSE)
4214             {
4215                 printf("Iterating branch shortening. Iteration = %d\n", jmp_iteration);
4216             }
4217 #endif
4218
4219             goto AGAIN;
4220         }
4221     }
4222 }
4223
4224 void emitter::emitCheckFuncletBranch(instrDesc* jmp, insGroup* jmpIG)
4225 {
4226 #ifdef DEBUG
4227     // We should not be jumping/branching across funclets/functions
4228     // Except possibly a 'call' to a finally funclet for a local unwind
4229     // or a 'return' from a catch handler (that can go just about anywhere)
4230     // This routine attempts to validate that any branches across funclets
4231     // meets one of those criteria...
4232     assert(jmp->idIsBound());
4233
4234 #ifdef _TARGET_XARCH_
4235     // An lea of a code address (for constant data stored with the code)
4236     // is treated like a jump for emission purposes but is not really a jump so
4237     // we don't have to check anything here.
4238     if (jmp->idIns() == INS_lea)
4239     {
4240         return;
4241     }
4242 #endif
4243
4244 #ifdef _TARGET_ARMARCH_
4245     if (jmp->idAddr()->iiaHasInstrCount())
4246     {
4247         // Too hard to figure out funclets from just an instruction count
4248         // You're on your own!
4249         return;
4250     }
4251 #endif // _TARGET_ARMARCH_
4252
4253 #ifdef _TARGET_ARM64_
4254     // No interest if it's not jmp.
4255     if (emitIsLoadLabel(jmp) || emitIsLoadConstant(jmp))
4256     {
4257         return;
4258     }
4259 #endif // _TARGET_ARM64_
4260
4261     insGroup* tgtIG = jmp->idAddr()->iiaIGlabel;
4262     assert(tgtIG);
4263     if (tgtIG->igFuncIdx != jmpIG->igFuncIdx)
4264     {
4265         if (jmp->idDebugOnlyInfo()->idFinallyCall)
4266         {
4267             // We don't record enough information to determine this accurately, so instead
4268             // we assume that any branch to the very start of a finally is OK.
4269
4270             // No branches back to the root method
4271             assert(tgtIG->igFuncIdx > 0);
4272             FuncInfoDsc* tgtFunc = emitComp->funGetFunc(tgtIG->igFuncIdx);
4273             assert(tgtFunc->funKind == FUNC_HANDLER);
4274             EHblkDsc* tgtEH = emitComp->ehGetDsc(tgtFunc->funEHIndex);
4275
4276             // Only branches to finallys (not faults, catches, filters, etc.)
4277             assert(tgtEH->HasFinallyHandler());
4278
4279             // Only to the first block of the finally (which is properly marked)
4280             BasicBlock* tgtBlk = tgtEH->ebdHndBeg;
4281             assert(tgtBlk->bbFlags & BBF_FUNCLET_BEG);
4282
4283             // And now we made it back to where we started
4284             assert(tgtIG == emitCodeGetCookie(tgtBlk));
4285             assert(tgtIG->igFuncIdx == emitComp->funGetFuncIdx(tgtBlk));
4286         }
4287         else if (jmp->idDebugOnlyInfo()->idCatchRet)
4288         {
4289             // Again there isn't enough information to prove this correct
4290             // so just allow a 'branch' to any other 'parent' funclet
4291
4292             FuncInfoDsc* jmpFunc = emitComp->funGetFunc(jmpIG->igFuncIdx);
4293             assert(jmpFunc->funKind == FUNC_HANDLER);
4294             EHblkDsc* jmpEH = emitComp->ehGetDsc(jmpFunc->funEHIndex);
4295
4296             // Only branches out of catches
4297             assert(jmpEH->HasCatchHandler());
4298
4299             FuncInfoDsc* tgtFunc = emitComp->funGetFunc(tgtIG->igFuncIdx);
4300             assert(tgtFunc);
4301             if (tgtFunc->funKind == FUNC_HANDLER)
4302             {
4303                 // An outward chain to the containing funclet/EH handler
4304                 // Note that it might be anywhere within nested try bodies
4305                 assert(jmpEH->ebdEnclosingHndIndex == tgtFunc->funEHIndex);
4306             }
4307             else
4308             {
4309                 // This funclet is 'top level' and so it is branching back to the
4310                 // root function, and should have no containing EH handlers
4311                 // but it could be nested within try bodies...
4312                 assert(tgtFunc->funKind == FUNC_ROOT);
4313                 assert(jmpEH->ebdEnclosingHndIndex == EHblkDsc::NO_ENCLOSING_INDEX);
4314             }
4315         }
4316         else
4317         {
4318             printf("Hit an illegal branch between funclets!");
4319             assert(tgtIG->igFuncIdx == jmpIG->igFuncIdx);
4320         }
4321     }
4322 #endif // DEBUG
4323 }
4324
4325 /*****************************************************************************
4326  *
4327  *  Compute the code sizes that we're going to use to allocate the code buffers.
4328  *
4329  *  This sets:
4330  *
4331  *      emitTotalHotCodeSize
4332  *      emitTotalColdCodeSize
4333  *      Compiler::info.compTotalHotCodeSize
4334  *      Compiler::info.compTotalColdCodeSize
4335  */
4336
4337 void emitter::emitComputeCodeSizes()
4338 {
4339     assert((emitComp->fgFirstColdBlock == nullptr) == (emitFirstColdIG == nullptr));
4340
4341     if (emitFirstColdIG)
4342     {
4343         emitTotalHotCodeSize  = emitFirstColdIG->igOffs;
4344         emitTotalColdCodeSize = emitTotalCodeSize - emitTotalHotCodeSize;
4345     }
4346     else
4347     {
4348         emitTotalHotCodeSize  = emitTotalCodeSize;
4349         emitTotalColdCodeSize = 0;
4350     }
4351
4352     emitComp->info.compTotalHotCodeSize  = emitTotalHotCodeSize;
4353     emitComp->info.compTotalColdCodeSize = emitTotalColdCodeSize;
4354
4355 #ifdef DEBUG
4356     if (emitComp->verbose)
4357     {
4358         printf("\nHot  code size = 0x%X bytes\n", emitTotalHotCodeSize);
4359         printf("Cold code size = 0x%X bytes\n", emitTotalColdCodeSize);
4360     }
4361 #endif
4362 }
4363
4364 /*****************************************************************************
4365  *
4366  *  Called at the end of code generation, this method creates the code, data
4367  *  and GC info blocks for the method.  Returns the size of the method (which must fit in an unsigned).
4368  */
4369
4370 unsigned emitter::emitEndCodeGen(Compiler* comp,
4371                                  bool      contTrkPtrLcls,
4372                                  bool      fullyInt,
4373                                  bool      fullPtrMap,
4374                                  bool      returnsGCr,
4375                                  unsigned  xcptnsCount,
4376                                  unsigned* prologSize,
4377                                  unsigned* epilogSize,
4378                                  void**    codeAddr,
4379                                  void**    coldCodeAddr,
4380                                  void**    consAddr)
4381 {
4382 #ifdef DEBUG
4383     if (emitComp->verbose)
4384     {
4385         printf("*************** In emitEndCodeGen()\n");
4386     }
4387 #endif
4388
4389     insGroup* ig;
4390
4391     BYTE* consBlock;
4392     BYTE* codeBlock;
4393     BYTE* coldCodeBlock;
4394     BYTE* cp;
4395
4396     assert(emitCurIG == nullptr);
4397
4398     emitCodeBlock = nullptr;
4399     emitConsBlock = nullptr;
4400
4401     /* Tell everyone whether we have fully interruptible code or not */
4402
4403     emitFullyInt   = fullyInt;
4404     emitFullGCinfo = fullPtrMap;
4405
4406 #ifndef UNIX_X86_ABI
4407     emitFullArgInfo = !emitHasFramePtr;
4408 #else
4409     emitFullArgInfo = fullPtrMap;
4410 #endif
4411
4412 #if EMITTER_STATS
4413     GCrefsTable.record(emitGCrFrameOffsCnt);
4414     emitSizeTable.record(static_cast<unsigned>(emitSizeMethod));
4415     stkDepthTable.record(emitMaxStackDepth);
4416 #endif // EMITTER_STATS
4417
4418     // Default values, correct even if EMIT_TRACK_STACK_DEPTH is 0.
4419     emitSimpleStkUsed         = true;
4420     u1.emitSimpleStkMask      = 0;
4421     u1.emitSimpleByrefStkMask = 0;
4422
4423 #if EMIT_TRACK_STACK_DEPTH
4424     /* Convert max. stack depth from # of bytes to # of entries */
4425
4426     unsigned maxStackDepthIn4ByteElements = emitMaxStackDepth / sizeof(int);
4427     JITDUMP("Converting emitMaxStackDepth from bytes (%d) to elements (%d)\n", emitMaxStackDepth,
4428             maxStackDepthIn4ByteElements);
4429     emitMaxStackDepth = maxStackDepthIn4ByteElements;
4430
4431     /* Should we use the simple stack */
4432
4433     if (emitMaxStackDepth > MAX_SIMPLE_STK_DEPTH || emitFullGCinfo)
4434     {
4435         /* We won't use the "simple" argument table */
4436
4437         emitSimpleStkUsed = false;
4438
4439         /* Allocate the argument tracking table */
4440
4441         if (emitMaxStackDepth <= sizeof(u2.emitArgTrackLcl))
4442         {
4443             u2.emitArgTrackTab = (BYTE*)u2.emitArgTrackLcl;
4444         }
4445         else
4446         {
4447             u2.emitArgTrackTab = (BYTE*)emitGetMem(roundUp(emitMaxStackDepth));
4448         }
4449
4450         u2.emitArgTrackTop   = u2.emitArgTrackTab;
4451         u2.emitGcArgTrackCnt = 0;
4452     }
4453 #endif
4454
4455     if (emitEpilogCnt == 0)
4456     {
4457         /* No epilogs, make sure the epilog size is set to 0 */
4458
4459         emitEpilogSize = 0;
4460
4461 #ifdef _TARGET_XARCH_
4462         emitExitSeqSize = 0;
4463 #endif // _TARGET_XARCH_
4464     }
4465
4466     /* Return the size of the epilog to the caller */
4467
4468     *epilogSize = emitEpilogSize;
4469
4470 #ifdef _TARGET_XARCH_
4471     *epilogSize += emitExitSeqSize;
4472 #endif // _TARGET_XARCH_
4473
4474 #ifdef DEBUG
4475     if (EMIT_INSTLIST_VERBOSE)
4476     {
4477         printf("\nInstruction list before instruction issue:\n\n");
4478         emitDispIGlist(true);
4479     }
4480
4481     emitCheckIGoffsets();
4482 #endif
4483
4484     /* Allocate the code block (and optionally the data blocks) */
4485
4486     // If we're doing procedure splitting and we found cold blocks, then
4487     // allocate hot and cold buffers.  Otherwise only allocate a hot
4488     // buffer.
4489
4490     coldCodeBlock = nullptr;
4491
4492     CorJitAllocMemFlag allocMemFlag = CORJIT_ALLOCMEM_DEFAULT_CODE_ALIGN;
4493
4494 #ifdef _TARGET_X86_
4495     //
4496     // These are the heuristics we use to decide whether or not to force the
4497     // code to be 16-byte aligned.
4498     //
4499     // 1. For ngen code with IBC data, use 16-byte alignment if the method
4500     //    has been called more than BB_VERY_HOT_WEIGHT times.
4501     // 2. For JITed code and ngen code without IBC data, use 16-byte alignment
4502     //    when the code is 16 bytes or smaller. We align small getters/setters
4503     //    because of they are penalized heavily on certain hardware when not 16-byte
4504     //    aligned (VSWhidbey #373938). To minimize size impact of this optimization,
4505     //    we do not align large methods because of the penalty is amortized for them.
4506     //
4507     if (emitComp->fgHaveProfileData())
4508     {
4509         if (emitComp->fgCalledCount > (BB_VERY_HOT_WEIGHT * emitComp->fgProfileRunsCount()))
4510         {
4511             allocMemFlag = CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN;
4512         }
4513     }
4514     else
4515     {
4516         if (emitTotalHotCodeSize <= 16)
4517         {
4518             allocMemFlag = CORJIT_ALLOCMEM_FLG_16BYTE_ALIGN;
4519         }
4520     }
4521 #endif
4522
4523 #ifdef _TARGET_ARM64_
4524     // For arm64, we want to allocate JIT data always adjacent to code similar to what native compiler does.
4525     // This way allows us to use a single `ldr` to access such data like float constant/jmp table.
4526     if (emitTotalColdCodeSize > 0)
4527     {
4528         // JIT data might be far away from the cold code.
4529         NYI_ARM64("Need to handle fix-up to data from cold code.");
4530     }
4531
4532     UNATIVE_OFFSET roDataAlignmentDelta = 0;
4533     if (emitConsDsc.dsdOffs)
4534     {
4535         UNATIVE_OFFSET roDataAlignment = sizeof(void*); // 8 Byte align by default.
4536         roDataAlignmentDelta = (UNATIVE_OFFSET)ALIGN_UP(emitTotalHotCodeSize, roDataAlignment) - emitTotalHotCodeSize;
4537         assert((roDataAlignmentDelta == 0) || (roDataAlignmentDelta == 4));
4538     }
4539     emitCmpHandle->allocMem(emitTotalHotCodeSize + roDataAlignmentDelta + emitConsDsc.dsdOffs, emitTotalColdCodeSize, 0,
4540                             xcptnsCount, allocMemFlag, (void**)&codeBlock, (void**)&coldCodeBlock, (void**)&consBlock);
4541
4542     consBlock = codeBlock + emitTotalHotCodeSize + roDataAlignmentDelta;
4543
4544 #else
4545     emitCmpHandle->allocMem(emitTotalHotCodeSize, emitTotalColdCodeSize, emitConsDsc.dsdOffs, xcptnsCount, allocMemFlag,
4546                             (void**)&codeBlock, (void**)&coldCodeBlock, (void**)&consBlock);
4547 #endif
4548
4549     // if (emitConsDsc.dsdOffs)
4550     //     printf("Cons=%08X\n", consBlock);
4551
4552     /* Give the block addresses to the caller and other functions here */
4553
4554     *codeAddr = emitCodeBlock = codeBlock;
4555     *coldCodeAddr = emitColdCodeBlock = coldCodeBlock;
4556     *consAddr = emitConsBlock = consBlock;
4557
4558     /* Nothing has been pushed on the stack */
4559     CLANG_FORMAT_COMMENT_ANCHOR;
4560
4561 #if EMIT_TRACK_STACK_DEPTH
4562     emitCurStackLvl = 0;
4563 #endif
4564
4565     /* Assume no live GC ref variables on entry */
4566
4567     VarSetOps::OldStyleClearD(emitComp, emitThisGCrefVars); // This is initialized to Empty at the start of codegen.
4568     emitThisGCrefRegs = emitThisByrefRegs = RBM_NONE;
4569     emitThisGCrefVset                     = true;
4570
4571 #ifdef DEBUG
4572
4573     emitIssuing = true;
4574
4575     // We don't use these after this point
4576
4577     VarSetOps::AssignNoCopy(emitComp, emitPrevGCrefVars, VarSetOps::UninitVal());
4578     emitPrevGCrefRegs = emitPrevByrefRegs = 0xBAADFEED;
4579
4580     VarSetOps::AssignNoCopy(emitComp, emitInitGCrefVars, VarSetOps::UninitVal());
4581     emitInitGCrefRegs = emitInitByrefRegs = 0xBAADFEED;
4582
4583 #endif
4584
4585     /* Initialize the GC ref variable lifetime tracking logic */
4586
4587     codeGen->gcInfo.gcVarPtrSetInit();
4588
4589     emitSyncThisObjOffs = -1;     /* -1  means no offset set */
4590     emitSyncThisObjReg  = REG_NA; /* REG_NA  means not set */
4591
4592 #ifdef JIT32_GCENCODER
4593     if (emitComp->lvaKeepAliveAndReportThis())
4594     {
4595         assert(emitComp->lvaIsOriginalThisArg(0));
4596         LclVarDsc* thisDsc = &emitComp->lvaTable[0];
4597
4598         /* If "this" (which is passed in as a register argument in REG_ARG_0)
4599            is enregistered, we normally spot the "mov REG_ARG_0 -> thisReg"
4600            in the prolog and note the location of "this" at that point.
4601            However, if 'this' is enregistered into REG_ARG_0 itself, no code
4602            will be generated in the prolog, so we explicitly need to note
4603            the location of "this" here.
4604            NOTE that we can do this even if "this" is not enregistered in
4605            REG_ARG_0, and it will result in more accurate "this" info over the
4606            prolog. However, as methods are not interruptible over the prolog,
4607            we try to save space by avoiding that.
4608          */
4609
4610         if (thisDsc->lvRegister)
4611         {
4612             emitSyncThisObjReg = thisDsc->lvRegNum;
4613
4614             if (emitSyncThisObjReg == (int)REG_ARG_0 &&
4615                 (codeGen->intRegState.rsCalleeRegArgMaskLiveIn & genRegMask(REG_ARG_0)))
4616             {
4617                 if (emitFullGCinfo)
4618                 {
4619                     emitGCregLiveSet(GCT_GCREF, genRegMask(REG_ARG_0),
4620                                      emitCodeBlock, // from offset 0
4621                                      true);
4622                 }
4623                 else
4624                 {
4625                     /* If emitFullGCinfo==false, the we don't use any
4626                        regPtrDsc's and so explictly note the location
4627                        of "this" in GCEncode.cpp
4628                      */
4629                 }
4630             }
4631         }
4632     }
4633 #endif // JIT32_GCENCODER
4634
4635     emitContTrkPtrLcls = contTrkPtrLcls;
4636
4637     /* Are there any GC ref variables on the stack? */
4638
4639     if (emitGCrFrameOffsCnt)
4640     {
4641         size_t     siz;
4642         unsigned   cnt;
4643         unsigned   num;
4644         LclVarDsc* dsc;
4645         int*       tab;
4646
4647         /* Allocate and clear emitGCrFrameLiveTab[]. This is the table
4648            mapping "stkOffs -> varPtrDsc". It holds a pointer to
4649            the liveness descriptor that was created when the
4650            variable became alive. When the variable becomes dead, the
4651            descriptor will be appended to the liveness descriptor list, and
4652            the entry in emitGCrFrameLiveTab[] will be made NULL.
4653
4654            Note that if all GC refs are assigned consecutively,
4655            emitGCrFrameLiveTab[] can be only as big as the number of GC refs
4656            present, instead of lvaTrackedCount.
4657          */
4658
4659         siz                 = emitGCrFrameOffsCnt * sizeof(*emitGCrFrameLiveTab);
4660         emitGCrFrameLiveTab = (varPtrDsc**)emitGetMem(roundUp(siz));
4661         memset(emitGCrFrameLiveTab, 0, siz);
4662
4663         /* Allocate and fill in emitGCrFrameOffsTab[]. This is the table
4664            mapping "varIndex -> stkOffs".
4665            Non-ptrs or reg vars have entries of -1.
4666            Entries of Tracked stack byrefs have the lower bit set to 1.
4667         */
4668
4669         emitTrkVarCnt = cnt = emitComp->lvaTrackedCount;
4670         assert(cnt);
4671         emitGCrFrameOffsTab = tab = (int*)emitGetMem(cnt * sizeof(int));
4672
4673         memset(emitGCrFrameOffsTab, -1, cnt * sizeof(int));
4674
4675         /* Now fill in all the actual used entries */
4676
4677         for (num = 0, dsc = emitComp->lvaTable, cnt = emitComp->lvaCount; num < cnt; num++, dsc++)
4678         {
4679             if (!dsc->lvOnFrame || (dsc->lvIsParam && !dsc->lvIsRegArg))
4680             {
4681                 continue;
4682             }
4683
4684 #if FEATURE_FIXED_OUT_ARGS
4685             if (num == emitComp->lvaOutgoingArgSpaceVar)
4686             {
4687                 continue;
4688             }
4689 #endif // FEATURE_FIXED_OUT_ARGS
4690
4691             int offs = dsc->lvStkOffs;
4692
4693             /* Is it within the interesting range of offsets */
4694
4695             if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
4696             {
4697                 /* Are tracked stack ptr locals laid out contiguously?
4698                    If not, skip non-ptrs. The emitter is optimized to work
4699                    with contiguous ptrs, but for EditNContinue, the variables
4700                    are laid out in the order they occur in the local-sig.
4701                  */
4702
4703                 if (!emitContTrkPtrLcls)
4704                 {
4705                     if (!emitComp->lvaIsGCTracked(dsc))
4706                     {
4707                         continue;
4708                     }
4709                 }
4710
4711                 unsigned indx = dsc->lvVarIndex;
4712
4713                 assert(!dsc->lvRegister);
4714                 assert(dsc->lvTracked);
4715                 assert(dsc->lvRefCnt != 0);
4716
4717                 assert(dsc->TypeGet() == TYP_REF || dsc->TypeGet() == TYP_BYREF);
4718
4719                 assert(indx < emitComp->lvaTrackedCount);
4720
4721 // printf("Variable #%2u/%2u is at stack offset %d\n", num, indx, offs);
4722
4723 #ifdef JIT32_GCENCODER
4724 #ifndef WIN64EXCEPTIONS
4725                 /* Remember the frame offset of the "this" argument for synchronized methods */
4726                 if (emitComp->lvaIsOriginalThisArg(num) && emitComp->lvaKeepAliveAndReportThis())
4727                 {
4728                     emitSyncThisObjOffs = offs;
4729                     offs |= this_OFFSET_FLAG;
4730                 }
4731 #endif
4732 #endif // JIT32_GCENCODER
4733
4734                 if (dsc->TypeGet() == TYP_BYREF)
4735                 {
4736                     offs |= byref_OFFSET_FLAG;
4737                 }
4738                 tab[indx] = offs;
4739             }
4740         }
4741     }
4742     else
4743     {
4744 #ifdef DEBUG
4745         emitTrkVarCnt       = 0;
4746         emitGCrFrameOffsTab = nullptr;
4747 #endif
4748     }
4749
4750 #ifdef DEBUG
4751     if (emitComp->verbose)
4752     {
4753         printf("\n***************************************************************************\n");
4754         printf("Instructions as they come out of the scheduler\n\n");
4755     }
4756 #endif
4757
4758     /* Issue all instruction groups in order */
4759     cp = codeBlock;
4760
4761 #define DEFAULT_CODE_BUFFER_INIT 0xcc
4762
4763     for (ig = emitIGlist; ig; ig = ig->igNext)
4764     {
4765         assert(!(ig->igFlags & IGF_PLACEHOLDER)); // There better not be any placeholder groups left
4766
4767         /* Is this the first cold block? */
4768         if (ig == emitFirstColdIG)
4769         {
4770             unsigned actualHotCodeSize = emitCurCodeOffs(cp);
4771
4772             /* Fill in eventual unused space */
4773             while (emitCurCodeOffs(cp) < emitTotalHotCodeSize)
4774             {
4775                 *cp++ = DEFAULT_CODE_BUFFER_INIT;
4776             }
4777
4778             assert(coldCodeBlock);
4779             cp = coldCodeBlock;
4780 #ifdef DEBUG
4781             if (emitComp->opts.disAsm || emitComp->opts.dspEmit || emitComp->verbose)
4782             {
4783                 printf("\n************** Beginning of cold code **************\n");
4784             }
4785 #endif
4786         }
4787
4788         /* Are we overflowing? */
4789         if (ig->igNext && ig->igNum + 1 != ig->igNext->igNum)
4790         {
4791             NO_WAY("Too many instruction groups");
4792         }
4793
4794         // If this instruction group is returned to from a funclet implementing a finally,
4795         // on architectures where it is necessary generate GC info for the current instruction as
4796         // if it were the instruction following a call.
4797         emitGenGCInfoIfFuncletRetTarget(ig, cp);
4798
4799         instrDesc* id = (instrDesc*)ig->igData;
4800
4801 #ifdef DEBUG
4802
4803         /* Print the IG label, but only if it is a branch label */
4804
4805         if (emitComp->opts.disAsm || emitComp->opts.dspEmit || emitComp->verbose)
4806         {
4807             if (emitComp->verbose)
4808             {
4809                 printf("\n");
4810                 emitDispIG(ig); // Display the flags, IG data, etc.
4811             }
4812             else
4813             {
4814                 printf("\nG_M%03u_IG%02u:\n", Compiler::s_compMethodsCount, ig->igNum);
4815             }
4816         }
4817
4818 #endif // DEBUG
4819
4820         BYTE* bp = cp;
4821
4822         /* Record the actual offset of the block, noting the difference */
4823
4824         emitOffsAdj = ig->igOffs - emitCurCodeOffs(cp);
4825         assert(emitOffsAdj >= 0);
4826
4827 #if DEBUG_EMIT
4828         if ((emitOffsAdj != 0) && emitComp->verbose)
4829         {
4830             printf("Block predicted offs = %08X, actual = %08X -> size adj = %d\n", ig->igOffs, emitCurCodeOffs(cp),
4831                    emitOffsAdj);
4832         }
4833 #endif // DEBUG_EMIT
4834
4835         ig->igOffs = emitCurCodeOffs(cp);
4836         assert(IsCodeAligned(ig->igOffs));
4837
4838 #if EMIT_TRACK_STACK_DEPTH
4839
4840         /* Set the proper stack level if appropriate */
4841
4842         if (ig->igStkLvl != emitCurStackLvl)
4843         {
4844             /* We are pushing stuff implicitly at this label */
4845
4846             assert((unsigned)ig->igStkLvl > (unsigned)emitCurStackLvl);
4847             emitStackPushN(cp, (ig->igStkLvl - (unsigned)emitCurStackLvl) / sizeof(int));
4848         }
4849
4850 #endif
4851
4852         /* Update current GC information for non-overflow IG (not added implicitly by the emitter) */
4853
4854         if (!(ig->igFlags & IGF_EMIT_ADD))
4855         {
4856             /* Is there a new set of live GC ref variables? */
4857
4858             if (ig->igFlags & IGF_GC_VARS)
4859             {
4860                 emitUpdateLiveGCvars(ig->igGCvars(), cp);
4861             }
4862             else if (!emitThisGCrefVset)
4863             {
4864                 emitUpdateLiveGCvars(emitThisGCrefVars, cp);
4865             }
4866
4867             /* Update the set of live GC ref registers */
4868
4869             {
4870                 regMaskTP GCregs = ig->igGCregs;
4871
4872                 if (GCregs != emitThisGCrefRegs)
4873                 {
4874                     emitUpdateLiveGCregs(GCT_GCREF, GCregs, cp);
4875                 }
4876             }
4877
4878             /* Is there a new set of live byref registers? */
4879
4880             if (ig->igFlags & IGF_BYREF_REGS)
4881             {
4882                 unsigned byrefRegs = ig->igByrefRegs();
4883
4884                 if (byrefRegs != emitThisByrefRegs)
4885                 {
4886                     emitUpdateLiveGCregs(GCT_BYREF, byrefRegs, cp);
4887                 }
4888             }
4889         }
4890         else
4891         {
4892             // These are not set for "overflow" groups
4893             assert(!(ig->igFlags & IGF_GC_VARS));
4894             assert(!(ig->igFlags & IGF_BYREF_REGS));
4895         }
4896
4897         /* Issue each instruction in order */
4898
4899         emitCurIG = ig;
4900
4901         for (unsigned cnt = ig->igInsCnt; cnt; cnt--)
4902         {
4903             castto(id, BYTE*) += emitIssue1Instr(ig, id, &cp);
4904         }
4905
4906         emitCurIG = nullptr;
4907
4908         assert(ig->igSize >= cp - bp);
4909         ig->igSize = (unsigned short)(cp - bp);
4910     }
4911
4912 #if EMIT_TRACK_STACK_DEPTH
4913     assert(emitCurStackLvl == 0);
4914 #endif
4915
4916     /* Output any initialized data we may have */
4917
4918     if (emitConsDsc.dsdOffs)
4919     {
4920         emitOutputDataSec(&emitConsDsc, consBlock);
4921     }
4922
4923     /* Make sure all GC ref variables are marked as dead */
4924
4925     if (emitGCrFrameOffsCnt)
4926     {
4927         unsigned    vn;
4928         int         of;
4929         varPtrDsc** dp;
4930
4931         for (vn = 0, of = emitGCrFrameOffsMin, dp = emitGCrFrameLiveTab; vn < emitGCrFrameOffsCnt;
4932              vn++, of += sizeof(void*), dp++)
4933         {
4934             if (*dp)
4935             {
4936                 emitGCvarDeadSet(of, cp, vn);
4937             }
4938         }
4939     }
4940
4941     /* No GC registers are live any more */
4942
4943     if (emitThisByrefRegs)
4944     {
4945         emitUpdateLiveGCregs(GCT_BYREF, RBM_NONE, cp);
4946     }
4947     if (emitThisGCrefRegs)
4948     {
4949         emitUpdateLiveGCregs(GCT_GCREF, RBM_NONE, cp);
4950     }
4951
4952     /* Patch any forward jumps */
4953
4954     if (emitFwdJumps)
4955     {
4956         instrDescJmp* jmp;
4957
4958         for (jmp = emitJumpList; jmp; jmp = jmp->idjNext)
4959         {
4960             insGroup* tgt;
4961 #ifdef _TARGET_XARCH_
4962             assert(jmp->idInsFmt() == IF_LABEL || jmp->idInsFmt() == IF_RWR_LABEL || jmp->idInsFmt() == IF_SWR_LABEL);
4963 #endif
4964             tgt = jmp->idAddr()->iiaIGlabel;
4965
4966             if (jmp->idjTemp.idjAddr == nullptr)
4967             {
4968                 continue;
4969             }
4970
4971             if (jmp->idjOffs != tgt->igOffs)
4972             {
4973                 BYTE* adr = jmp->idjTemp.idjAddr;
4974                 int   adj = jmp->idjOffs - tgt->igOffs;
4975 #ifdef _TARGET_ARM_
4976                 // On Arm, the offset is encoded in unit of 2 bytes.
4977                 adj >>= 1;
4978 #endif
4979
4980 #if DEBUG_EMIT
4981                 if (jmp->idDebugOnlyInfo()->idNum == (unsigned)INTERESTING_JUMP_NUM || INTERESTING_JUMP_NUM == 0)
4982                 {
4983 #ifdef _TARGET_ARM_
4984                     printf("[5] This output is broken for ARM, since it doesn't properly decode the jump offsets of "
4985                            "the instruction at adr\n");
4986 #endif
4987
4988                     if (INTERESTING_JUMP_NUM == 0)
4989                     {
4990                         printf("[5] Jump %u:\n", jmp->idDebugOnlyInfo()->idNum);
4991                     }
4992
4993                     if (jmp->idjShort)
4994                     {
4995                         printf("[5] Jump        is at %08X\n", (adr + 1 - emitCodeBlock));
4996                         printf("[5] Jump distance is  %02X - %02X = %02X\n", *(BYTE*)adr, adj, *(BYTE*)adr - adj);
4997                     }
4998                     else
4999                     {
5000                         printf("[5] Jump        is at %08X\n", (adr + 4 - emitCodeBlock));
5001                         printf("[5] Jump distance is  %08X - %02X = %08X\n", *(int*)adr, adj, *(int*)adr - adj);
5002                     }
5003                 }
5004 #endif // DEBUG_EMIT
5005
5006                 if (jmp->idjShort)
5007                 {
5008                     // Patch Forward Short Jump
5009                     CLANG_FORMAT_COMMENT_ANCHOR;
5010 #if defined(_TARGET_XARCH_)
5011                     *(BYTE*)adr -= (BYTE)adj;
5012 #elif defined(_TARGET_ARM_)
5013                     // The following works because the jump offset is in the low order bits of the instruction.
5014                     // Presumably we could also just call "emitOutputLJ(NULL, adr, jmp)", like for long jumps?
5015                     *(short int*)adr -= (short)adj;
5016 #elif defined(_TARGET_ARM64_)
5017                     assert(!jmp->idAddr()->iiaHasInstrCount());
5018                     emitOutputLJ(NULL, adr, jmp);
5019 #else
5020 #error Unsupported or unset target architecture
5021 #endif
5022                 }
5023                 else
5024                 {
5025                     // Patch Forward non-Short Jump
5026                     CLANG_FORMAT_COMMENT_ANCHOR;
5027 #if defined(_TARGET_XARCH_)
5028                     *(int*)adr -= adj;
5029 #elif defined(_TARGET_ARMARCH_)
5030                     assert(!jmp->idAddr()->iiaHasInstrCount());
5031                     emitOutputLJ(NULL, adr, jmp);
5032 #else
5033 #error Unsupported or unset target architecture
5034 #endif
5035                 }
5036             }
5037         }
5038     }
5039
5040 #ifdef DEBUG
5041     if (emitComp->opts.disAsm)
5042     {
5043         printf("\n");
5044     }
5045
5046     if (emitComp->verbose)
5047     {
5048         printf("Allocated method code size = %4u , actual size = %4u\n", emitTotalCodeSize, cp - codeBlock);
5049     }
5050 #endif
5051
5052     unsigned actualCodeSize = emitCurCodeOffs(cp);
5053
5054     /* Fill in eventual unused space */
5055     while (emitCurCodeOffs(cp) < emitTotalCodeSize)
5056     {
5057         *cp++ = DEFAULT_CODE_BUFFER_INIT;
5058     }
5059
5060 #if EMITTER_STATS
5061     totAllocdSize += emitTotalCodeSize;
5062     totActualSize += actualCodeSize;
5063 #endif
5064
5065 #ifdef DEBUG
5066
5067     // Make sure these didn't change during the "issuing" phase
5068
5069     assert(VarSetOps::MayBeUninit(emitPrevGCrefVars));
5070     assert(emitPrevGCrefRegs == 0xBAADFEED);
5071     assert(emitPrevByrefRegs == 0xBAADFEED);
5072
5073     assert(VarSetOps::MayBeUninit(emitInitGCrefVars));
5074     assert(emitInitGCrefRegs == 0xBAADFEED);
5075     assert(emitInitByrefRegs == 0xBAADFEED);
5076
5077 #endif
5078
5079     // Assign the real prolog size
5080     *prologSize = emitCodeOffset(emitPrologIG, emitPrologEndPos);
5081
5082     /* Return the amount of code we've generated */
5083
5084     return actualCodeSize;
5085 }
5086
5087 // See specification comment at the declaration.
5088 void emitter::emitGenGCInfoIfFuncletRetTarget(insGroup* ig, BYTE* cp)
5089 {
5090 #if FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
5091     // We only emit this GC information on targets where finally's are implemented via funclets,
5092     // and the finally is invoked, during non-exceptional execution, via a branch with a predefined
5093     // link register, rather than a "true call" for which we would already generate GC info.  Currently,
5094     // this means precisely ARM.
5095     if (ig->igFlags & IGF_FINALLY_TARGET)
5096     {
5097         // We don't actually have a call instruction in this case, so we don't have
5098         // a real size for that instruction.  We'll use 1.
5099         emitStackPop(cp, /*isCall*/ true, /*callInstrSize*/ 1, /*args*/ 0);
5100
5101         /* Do we need to record a call location for GC purposes? */
5102         if (!emitFullGCinfo)
5103         {
5104             emitRecordGCcall(cp, /*callInstrSize*/ 1);
5105         }
5106     }
5107 #endif // FEATURE_EH_FUNCLETS && defined(_TARGET_ARM_)
5108 }
5109
5110 /*****************************************************************************
5111  *
5112  *  We have an instruction in an insGroup and we need to know the
5113  *  instruction number for this instruction
5114  */
5115
5116 unsigned emitter::emitFindInsNum(insGroup* ig, instrDesc* idMatch)
5117 {
5118     instrDesc* id = (instrDesc*)ig->igData;
5119
5120     // Check if we are the first instruction in the group
5121     if (id == idMatch)
5122     {
5123         return 0;
5124     }
5125
5126     /* Walk the list of instructions until we find a match */
5127     unsigned insNum       = 0;
5128     unsigned insRemaining = ig->igInsCnt;
5129
5130     while (insRemaining > 0)
5131     {
5132         castto(id, BYTE*) += emitSizeOfInsDsc(id);
5133         insNum++;
5134         insRemaining--;
5135
5136         if (id == idMatch)
5137         {
5138             return insNum;
5139         }
5140     }
5141     assert(!"emitFindInsNum failed");
5142     return -1;
5143 }
5144
5145 /*****************************************************************************
5146  *
5147  *  We've been asked for the code offset of an instruction but alas one or
5148  *  more instruction sizes in the block have been mis-predicted, so we have
5149  *  to find the true offset by looking for the instruction within the group.
5150  */
5151
5152 UNATIVE_OFFSET emitter::emitFindOffset(insGroup* ig, unsigned insNum)
5153 {
5154     instrDesc*     id = (instrDesc*)ig->igData;
5155     UNATIVE_OFFSET of = 0;
5156
5157 #ifdef DEBUG
5158     /* Make sure we were passed reasonable arguments */
5159     assert(ig && ig->igSelf == ig);
5160     assert(ig->igInsCnt >= insNum);
5161 #endif
5162
5163     /* Walk the instruction list until all are counted */
5164
5165     while (insNum > 0)
5166     {
5167         of += emitInstCodeSz(id);
5168
5169         castto(id, BYTE*) += emitSizeOfInsDsc(id);
5170
5171         insNum--;
5172     }
5173
5174     return of;
5175 }
5176
5177 /*****************************************************************************
5178  *
5179  *  Start generating a constant data section for the current
5180  *  function. Returns the offset of the section in the appropriate data
5181  *  block.
5182  */
5183
5184 UNATIVE_OFFSET emitter::emitDataGenBeg(UNATIVE_OFFSET size, bool dblAlign, bool codeLtab)
5185 {
5186     unsigned     secOffs;
5187     dataSection* secDesc;
5188
5189     assert(emitDataSecCur == nullptr);
5190
5191     /* The size better not be some kind of an odd thing */
5192
5193     assert(size && size % sizeof(int) == 0);
5194
5195     /* Get hold of the current offset */
5196
5197     secOffs = emitConsDsc.dsdOffs;
5198
5199     /* Are we require to align this request on an eight byte boundry? */
5200     if (dblAlign && (secOffs % sizeof(double) != 0))
5201     {
5202         /* Need to skip 4 bytes to honor dblAlign */
5203         /* Must allocate a dummy 4 byte integer */
5204         int zero = 0;
5205         emitDataGenBeg(4, false, false);
5206         emitDataGenData(0, &zero, 4);
5207         emitDataGenEnd();
5208
5209         /* Get the new secOffs */
5210         secOffs = emitConsDsc.dsdOffs;
5211         /* Now it should be a multiple of 8 */
5212         assert(secOffs % sizeof(double) == 0);
5213     }
5214
5215     /* Advance the current offset */
5216
5217     emitConsDsc.dsdOffs += size;
5218
5219     /* Allocate a data section descriptor and add it to the list */
5220
5221     secDesc = emitDataSecCur = (dataSection*)emitGetMem(roundUp(sizeof(*secDesc) + size));
5222
5223     secDesc->dsSize = size;
5224
5225     secDesc->dsType = dataSection::data;
5226
5227     secDesc->dsNext = nullptr;
5228
5229     if (emitConsDsc.dsdLast)
5230     {
5231         emitConsDsc.dsdLast->dsNext = secDesc;
5232     }
5233     else
5234     {
5235         emitConsDsc.dsdList = secDesc;
5236     }
5237     emitConsDsc.dsdLast = secDesc;
5238
5239     return secOffs;
5240 }
5241
5242 //  Start generating a constant data section for the current function
5243 //  populated with BasicBlock references.
5244 //  You can choose the references to be either absolute pointers, or
5245 //  4-byte relative addresses.
5246 //  Currently the relative references are relative to the start of the
5247 //  first block (this is somewhat arbitrary)
5248
5249 UNATIVE_OFFSET emitter::emitBBTableDataGenBeg(unsigned numEntries, bool relativeAddr)
5250 {
5251     unsigned     secOffs;
5252     dataSection* secDesc;
5253
5254     assert(emitDataSecCur == nullptr);
5255
5256     UNATIVE_OFFSET emittedSize;
5257
5258     if (relativeAddr)
5259     {
5260         emittedSize = numEntries * 4;
5261     }
5262     else
5263     {
5264         emittedSize = numEntries * TARGET_POINTER_SIZE;
5265     }
5266
5267     /* Get hold of the current offset */
5268
5269     secOffs = emitConsDsc.dsdOffs;
5270
5271     /* Advance the current offset */
5272
5273     emitConsDsc.dsdOffs += emittedSize;
5274
5275     /* Allocate a data section descriptor and add it to the list */
5276
5277     secDesc = emitDataSecCur = (dataSection*)emitGetMem(roundUp(sizeof(*secDesc) + numEntries * sizeof(BasicBlock*)));
5278
5279     secDesc->dsSize = emittedSize;
5280
5281     secDesc->dsType = relativeAddr ? dataSection::blockRelative32 : dataSection::blockAbsoluteAddr;
5282
5283     secDesc->dsNext = nullptr;
5284
5285     if (emitConsDsc.dsdLast)
5286     {
5287         emitConsDsc.dsdLast->dsNext = secDesc;
5288     }
5289     else
5290     {
5291         emitConsDsc.dsdList = secDesc;
5292     }
5293
5294     emitConsDsc.dsdLast = secDesc;
5295
5296     return secOffs;
5297 }
5298
5299 /*****************************************************************************
5300  *
5301  *  Emit the given block of bits into the current data section.
5302  */
5303
5304 void emitter::emitDataGenData(unsigned offs, const void* data, size_t size)
5305 {
5306     assert(emitDataSecCur && (emitDataSecCur->dsSize >= offs + size));
5307
5308     assert(emitDataSecCur->dsType == dataSection::data);
5309
5310     memcpy(emitDataSecCur->dsCont + offs, data, size);
5311 }
5312
5313 /*****************************************************************************
5314  *
5315  *  Emit the address of the given basic block into the current data section.
5316  */
5317
5318 void emitter::emitDataGenData(unsigned index, BasicBlock* label)
5319 {
5320     assert(emitDataSecCur != nullptr);
5321     assert(emitDataSecCur->dsType == dataSection::blockAbsoluteAddr ||
5322            emitDataSecCur->dsType == dataSection::blockRelative32);
5323
5324     unsigned emittedElemSize = emitDataSecCur->dsType == dataSection::blockAbsoluteAddr ? TARGET_POINTER_SIZE : 4;
5325
5326     assert(emitDataSecCur->dsSize >= emittedElemSize * (index + 1));
5327
5328     ((BasicBlock**)(emitDataSecCur->dsCont))[index] = label;
5329 }
5330
5331 /*****************************************************************************
5332  *
5333  *  We're done generating a data section.
5334  */
5335
5336 void emitter::emitDataGenEnd()
5337 {
5338
5339 #ifdef DEBUG
5340     assert(emitDataSecCur);
5341     emitDataSecCur = nullptr;
5342 #endif
5343 }
5344
5345 /********************************************************************************
5346  * Generates a data section constant
5347  *
5348  * Parameters:
5349  *     cnsAddr  - memory location containing constant value
5350  *     cnsSize  - size of constant in bytes
5351  *     dblAlign - whether to double align the data section constant
5352  *
5353  * Returns constant number as offset into data section.
5354  */
5355 UNATIVE_OFFSET emitter::emitDataConst(const void* cnsAddr, unsigned cnsSize, bool dblAlign)
5356 {
5357     // When generating SMALL_CODE, we don't bother with dblAlign
5358     if (dblAlign && (emitComp->compCodeOpt() == Compiler::SMALL_CODE))
5359     {
5360         dblAlign = false;
5361     }
5362
5363     UNATIVE_OFFSET cnum = emitDataGenBeg(cnsSize, dblAlign, false);
5364     emitDataGenData(0, cnsAddr, cnsSize);
5365     emitDataGenEnd();
5366
5367     return cnum;
5368 }
5369
5370 /*****************************************************************************
5371  *
5372  *  Output the given data section at the specified address.
5373  */
5374
5375 void emitter::emitOutputDataSec(dataSecDsc* sec, BYTE* dst)
5376 {
5377 #ifdef DEBUG
5378     if (EMITVERBOSE)
5379     {
5380         printf("\nEmitting data sections: %u total bytes\n", sec->dsdOffs);
5381     }
5382
5383     unsigned secNum = 0;
5384 #endif
5385
5386     assert(dst);
5387     assert(sec->dsdOffs);
5388     assert(sec->dsdList);
5389
5390     /* Walk and emit the contents of all the data blocks */
5391
5392     dataSection* dsc;
5393
5394     for (dsc = sec->dsdList; dsc; dsc = dsc->dsNext)
5395     {
5396         size_t dscSize = dsc->dsSize;
5397
5398         // absolute label table
5399         if (dsc->dsType == dataSection::blockAbsoluteAddr)
5400         {
5401             JITDUMP("  section %u, size %u, block absolute addr\n", secNum++, dscSize);
5402
5403             assert(dscSize && dscSize % sizeof(BasicBlock*) == 0);
5404             size_t numElems = dscSize / TARGET_POINTER_SIZE;
5405             BYTE** bDst     = (BYTE**)dst;
5406             for (unsigned i = 0; i < numElems; i++)
5407             {
5408                 BasicBlock* block = ((BasicBlock**)dsc->dsCont)[i];
5409
5410                 // Convert the BasicBlock* value to an IG address
5411                 insGroup* lab = (insGroup*)emitCodeGetCookie(block);
5412
5413                 // Append the appropriate address to the destination
5414                 BYTE* target = emitOffsetToPtr(lab->igOffs);
5415
5416 #ifdef _TARGET_ARM_
5417                 target = (BYTE*)((size_t)target | 1); // Or in thumb bit
5418 #endif
5419                 bDst[i] = target;
5420                 if (emitComp->opts.compReloc)
5421                 {
5422                     emitRecordRelocation(&(bDst[i]), target, IMAGE_REL_BASED_HIGHLOW);
5423                 }
5424
5425                 JITDUMP("  BB%02u: 0x%p\n", block->bbNum, bDst[i]);
5426             }
5427         }
5428         // relative label table
5429         else if (dsc->dsType == dataSection::blockRelative32)
5430         {
5431             JITDUMP("  section %u, size %u, block relative addr\n", secNum++, dscSize);
5432
5433             unsigned  elemSize = 4;
5434             size_t    numElems = dscSize / 4;
5435             unsigned* uDst     = (unsigned*)dst;
5436             insGroup* labFirst = (insGroup*)emitCodeGetCookie(emitComp->fgFirstBB);
5437
5438             for (unsigned i = 0; i < numElems; i++)
5439             {
5440                 BasicBlock* block = ((BasicBlock**)dsc->dsCont)[i];
5441
5442                 // Convert the BasicBlock* value to an IG address
5443                 insGroup* lab = (insGroup*)emitCodeGetCookie(block);
5444
5445                 assert(FitsIn<uint32_t>(lab->igOffs - labFirst->igOffs));
5446                 uDst[i] = lab->igOffs - labFirst->igOffs;
5447
5448                 JITDUMP("  BB%02u: 0x%x\n", block->bbNum, uDst[i]);
5449             }
5450         }
5451         else
5452         {
5453             JITDUMP("  section %u, size %u, raw data\n", secNum++, dscSize);
5454
5455             // Simple binary data: copy the bytes to the target
5456             assert(dsc->dsType == dataSection::data);
5457
5458             memcpy(dst, dsc->dsCont, dscSize);
5459
5460 #ifdef DEBUG
5461             if (EMITVERBOSE)
5462             {
5463                 printf("  ");
5464                 for (size_t i = 0; i < dscSize; i++)
5465                 {
5466                     printf("%02x ", dsc->dsCont[i]);
5467                     if ((((i + 1) % 16) == 0) && (i + 1 != dscSize))
5468                     {
5469                         printf("\n  ");
5470                     }
5471                 }
5472                 printf("\n");
5473             }
5474 #endif // DEBUG
5475         }
5476         dst += dscSize;
5477     }
5478 }
5479
5480 /*****************************************************************************/
5481 /*****************************************************************************
5482  *
5483  *  Record the fact that the given variable now contains a live GC ref.
5484  */
5485
5486 void emitter::emitGCvarLiveSet(int offs, GCtype gcType, BYTE* addr, ssize_t disp)
5487 {
5488     assert(emitIssuing);
5489
5490     varPtrDsc* desc;
5491
5492     assert((abs(offs) % sizeof(ssize_t)) == 0);
5493     assert(needsGC(gcType));
5494
5495     /* Compute the index into the GC frame table if the caller didn't do it */
5496
5497     if (disp == -1)
5498     {
5499         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
5500     }
5501
5502     assert((size_t)disp < emitGCrFrameOffsCnt);
5503
5504     /* Allocate a lifetime record */
5505
5506     desc = new (emitComp, CMK_GC) varPtrDsc;
5507
5508     desc->vpdBegOfs = emitCurCodeOffs(addr);
5509 #ifdef DEBUG
5510     desc->vpdEndOfs = 0xFACEDEAD;
5511 #endif
5512
5513     desc->vpdVarNum = offs;
5514
5515     desc->vpdNext = nullptr;
5516
5517 #if !defined(JIT32_GCENCODER) || !defined(WIN64EXCEPTIONS)
5518     /* the lower 2 bits encode props about the stk ptr */
5519
5520     if (offs == emitSyncThisObjOffs)
5521     {
5522         desc->vpdVarNum |= this_OFFSET_FLAG;
5523     }
5524 #endif
5525
5526     if (gcType == GCT_BYREF)
5527     {
5528         desc->vpdVarNum |= byref_OFFSET_FLAG;
5529     }
5530
5531     /* Append the new entry to the end of the list */
5532     if (codeGen->gcInfo.gcVarPtrLast == nullptr)
5533     {
5534         assert(codeGen->gcInfo.gcVarPtrList == nullptr);
5535         codeGen->gcInfo.gcVarPtrList = codeGen->gcInfo.gcVarPtrLast = desc;
5536     }
5537     else
5538     {
5539         assert(codeGen->gcInfo.gcVarPtrList != nullptr);
5540         codeGen->gcInfo.gcVarPtrLast->vpdNext = desc;
5541         codeGen->gcInfo.gcVarPtrLast          = desc;
5542     }
5543
5544     /* Record the variable descriptor in the table */
5545
5546     assert(emitGCrFrameLiveTab[disp] == nullptr);
5547     emitGCrFrameLiveTab[disp] = desc;
5548
5549 #ifdef DEBUG
5550     if (EMITVERBOSE)
5551     {
5552         printf("[%08X] %s var born at [%s", dspPtr(desc), GCtypeStr(gcType), emitGetFrameReg());
5553
5554         if (offs < 0)
5555         {
5556             printf("-%02XH", -offs);
5557         }
5558         else if (offs > 0)
5559         {
5560             printf("+%02XH", +offs);
5561         }
5562
5563         printf("]\n");
5564     }
5565 #endif
5566
5567     /* The "global" live GC variable mask is no longer up-to-date */
5568
5569     emitThisGCrefVset = false;
5570 }
5571
5572 /*****************************************************************************
5573  *
5574  *  Record the fact that the given variable no longer contains a live GC ref.
5575  */
5576
5577 void emitter::emitGCvarDeadSet(int offs, BYTE* addr, ssize_t disp)
5578 {
5579     assert(emitIssuing);
5580
5581     varPtrDsc* desc;
5582
5583     assert(abs(offs) % sizeof(int) == 0);
5584
5585     /* Compute the index into the GC frame table if the caller didn't do it */
5586
5587     if (disp == -1)
5588     {
5589         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
5590     }
5591
5592     assert((unsigned)disp < emitGCrFrameOffsCnt);
5593
5594     /* Get hold of the lifetime descriptor and clear the entry */
5595
5596     desc                      = emitGCrFrameLiveTab[disp];
5597     emitGCrFrameLiveTab[disp] = nullptr;
5598
5599     assert(desc);
5600     assert((desc->vpdVarNum & ~OFFSET_MASK) == (unsigned)offs);
5601
5602     /* Record the death code offset */
5603
5604     assert(desc->vpdEndOfs == 0xFACEDEAD);
5605     desc->vpdEndOfs = emitCurCodeOffs(addr);
5606
5607 #ifdef DEBUG
5608     if (EMITVERBOSE)
5609     {
5610         GCtype gcType = (desc->vpdVarNum & byref_OFFSET_FLAG) ? GCT_BYREF : GCT_GCREF;
5611 #if !defined(JIT32_GCENCODER) || !defined(WIN64EXCEPTIONS)
5612         bool isThis = (desc->vpdVarNum & this_OFFSET_FLAG) != 0;
5613
5614         printf("[%08X] %s%s var died at [%s", dspPtr(desc), GCtypeStr(gcType), isThis ? "this-ptr" : "",
5615                emitGetFrameReg());
5616 #else
5617         bool isPinned = (desc->vpdVarNum & pinned_OFFSET_FLAG) != 0;
5618
5619         printf("[%08X] %s%s var died at [%s", dspPtr(desc), GCtypeStr(gcType), isPinned ? "pinned" : "",
5620                emitGetFrameReg());
5621 #endif
5622
5623         if (offs < 0)
5624         {
5625             printf("-%02XH", -offs);
5626         }
5627         else if (offs > 0)
5628         {
5629             printf("+%02XH", +offs);
5630         }
5631
5632         printf("]\n");
5633     }
5634 #endif
5635
5636     /* The "global" live GC variable mask is no longer up-to-date */
5637
5638     emitThisGCrefVset = false;
5639 }
5640
5641 /*****************************************************************************
5642  *
5643  *  Record a new set of live GC ref variables.
5644  */
5645
5646 void emitter::emitUpdateLiveGCvars(VARSET_VALARG_TP vars, BYTE* addr)
5647 {
5648     assert(emitIssuing);
5649
5650     // Don't track GC changes in epilogs
5651     if (emitIGisInEpilog(emitCurIG))
5652     {
5653         return;
5654     }
5655
5656     /* Is the current set accurate and unchanged? */
5657
5658     if (emitThisGCrefVset && VarSetOps::Equal(emitComp, emitThisGCrefVars, vars))
5659     {
5660         return;
5661     }
5662
5663 #ifdef DEBUG
5664     if (EMIT_GC_VERBOSE)
5665     {
5666         printf("New GC ref live vars=%s ", VarSetOps::ToString(emitComp, vars));
5667         dumpConvertedVarSet(emitComp, vars);
5668         printf("\n");
5669     }
5670 #endif
5671
5672     VarSetOps::Assign(emitComp, emitThisGCrefVars, vars);
5673
5674     /* Are there any GC ref variables on the stack? */
5675
5676     if (emitGCrFrameOffsCnt)
5677     {
5678         int*     tab;
5679         unsigned cnt = emitTrkVarCnt;
5680         unsigned num;
5681
5682         /* Test all the tracked variable bits in the mask */
5683
5684         for (num = 0, tab = emitGCrFrameOffsTab; num < cnt; num++, tab++)
5685         {
5686             int val = *tab;
5687
5688             if (val != -1)
5689             {
5690                 // byref_OFFSET_FLAG and this_OFFSET_FLAG are set
5691                 //  in the table-offsets for byrefs and this-ptr
5692
5693                 int offs = val & ~OFFSET_MASK;
5694
5695                 // printf("var #%2u at %3d is now %s\n", num, offs, (vars & 1) ? "live" : "dead");
5696
5697                 if (VarSetOps::IsMember(emitComp, vars, num))
5698                 {
5699                     GCtype gcType = (val & byref_OFFSET_FLAG) ? GCT_BYREF : GCT_GCREF;
5700                     emitGCvarLiveUpd(offs, INT_MAX, gcType, addr);
5701                 }
5702                 else
5703                 {
5704                     emitGCvarDeadUpd(offs, addr);
5705                 }
5706             }
5707         }
5708     }
5709
5710     emitThisGCrefVset = true;
5711 }
5712
5713 /*****************************************************************************
5714  *
5715  *  Record a call location for GC purposes (we know that this is a method that
5716  *  will not be fully interruptible).
5717  */
5718
5719 void emitter::emitRecordGCcall(BYTE* codePos, unsigned char callInstrSize)
5720 {
5721     assert(emitIssuing);
5722     assert(!emitFullGCinfo);
5723
5724     unsigned offs = emitCurCodeOffs(codePos);
5725     unsigned regs = (emitThisGCrefRegs | emitThisByrefRegs) & ~RBM_INTRET;
5726     callDsc* call;
5727
5728 #ifdef JIT32_GCENCODER
5729     // The JIT32 GCInfo encoder allows us to (as the comment previously here said):
5730     // "Bail if this is a totally boring call", but the GCInfoEncoder/Decoder interface
5731     // requires a definition for every call site, so we skip these "early outs" when we're
5732     // using the general encoder.
5733     if (regs == 0)
5734     {
5735 #if EMIT_TRACK_STACK_DEPTH
5736         if (emitCurStackLvl == 0)
5737             return;
5738 #endif
5739         /* Nope, only interesting calls get recorded */
5740
5741         if (emitSimpleStkUsed)
5742         {
5743             if (!u1.emitSimpleStkMask)
5744                 return;
5745         }
5746         else
5747         {
5748             if (u2.emitGcArgTrackCnt == 0)
5749                 return;
5750         }
5751     }
5752 #endif // JIT32_GCENCODER
5753
5754 #ifdef DEBUG
5755
5756     if (EMIT_GC_VERBOSE)
5757     {
5758         printf("; Call at %04X [stk=%u], GCvars=", offs - callInstrSize, emitCurStackLvl);
5759         emitDispVarSet();
5760         printf(", gcrefRegs=");
5761         printRegMaskInt(emitThisGCrefRegs);
5762         emitDispRegSet(emitThisGCrefRegs);
5763         // printRegMaskInt(emitThisGCrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5764         // emitDispRegSet (emitThisGCrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5765         printf(", byrefRegs=");
5766         printRegMaskInt(emitThisByrefRegs);
5767         emitDispRegSet(emitThisByrefRegs);
5768         // printRegMaskInt(emitThisByrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5769         // emitDispRegSet (emitThisByrefRegs & ~RBM_INTRET & RBM_CALLEE_SAVED);    // only display callee-saved
5770         printf("\n");
5771     }
5772
5773 #endif
5774
5775     /* Allocate a 'call site' descriptor and start filling it in */
5776
5777     call = new (emitComp, CMK_GC) callDsc;
5778
5779     call->cdBlock = nullptr;
5780     call->cdOffs  = offs;
5781 #ifndef JIT32_GCENCODER
5782     call->cdCallInstrSize = callInstrSize;
5783 #endif
5784     call->cdNext = nullptr;
5785
5786     call->cdGCrefRegs = (regMaskSmall)emitThisGCrefRegs;
5787     call->cdByrefRegs = (regMaskSmall)emitThisByrefRegs;
5788
5789 #if EMIT_TRACK_STACK_DEPTH
5790 #ifndef FEATURE_UNIX_AMD64_STRUCT_PASSING
5791     noway_assert(FitsIn<USHORT>(emitCurStackLvl / ((unsigned)sizeof(unsigned))));
5792 #endif // FEATURE_UNIX_AMD64_STRUCT_PASSING
5793 #endif
5794
5795     // Append the call descriptor to the list */
5796     if (codeGen->gcInfo.gcCallDescLast == nullptr)
5797     {
5798         assert(codeGen->gcInfo.gcCallDescList == nullptr);
5799         codeGen->gcInfo.gcCallDescList = codeGen->gcInfo.gcCallDescLast = call;
5800     }
5801     else
5802     {
5803         assert(codeGen->gcInfo.gcCallDescList != nullptr);
5804         codeGen->gcInfo.gcCallDescLast->cdNext = call;
5805         codeGen->gcInfo.gcCallDescLast         = call;
5806     }
5807
5808     /* Record the current "pending" argument list */
5809
5810     if (emitSimpleStkUsed)
5811     {
5812         /* The biggest call is less than MAX_SIMPLE_STK_DEPTH. So use
5813            small format */
5814
5815         call->u1.cdArgMask      = u1.emitSimpleStkMask;
5816         call->u1.cdByrefArgMask = u1.emitSimpleByrefStkMask;
5817         call->cdArgCnt          = 0;
5818     }
5819     else
5820     {
5821         /* The current call has too many arguments, so we need to report the
5822            offsets of each individual GC arg. */
5823
5824         call->cdArgCnt = u2.emitGcArgTrackCnt;
5825         if (call->cdArgCnt == 0)
5826         {
5827             call->u1.cdArgMask = call->u1.cdByrefArgMask = 0;
5828             return;
5829         }
5830
5831         call->cdArgTable = new (emitComp, CMK_GC) unsigned[u2.emitGcArgTrackCnt];
5832
5833         unsigned gcArgs = 0;
5834         unsigned stkLvl = emitCurStackLvl / sizeof(int);
5835
5836         for (unsigned i = 0; i < stkLvl; i++)
5837         {
5838             GCtype gcType = (GCtype)u2.emitArgTrackTab[stkLvl - i - 1];
5839
5840             if (needsGC(gcType))
5841             {
5842                 call->cdArgTable[gcArgs] = i * sizeof(void*);
5843
5844                 if (gcType == GCT_BYREF)
5845                 {
5846                     call->cdArgTable[gcArgs] |= byref_OFFSET_FLAG;
5847                 }
5848
5849                 gcArgs++;
5850             }
5851         }
5852
5853         assert(gcArgs == u2.emitGcArgTrackCnt);
5854     }
5855 }
5856
5857 /*****************************************************************************
5858  *
5859  *  Record a new set of live GC ref registers.
5860  */
5861
5862 void emitter::emitUpdateLiveGCregs(GCtype gcType, regMaskTP regs, BYTE* addr)
5863 {
5864     assert(emitIssuing);
5865
5866     // Don't track GC changes in epilogs
5867     if (emitIGisInEpilog(emitCurIG))
5868     {
5869         return;
5870     }
5871
5872     regMaskTP life;
5873     regMaskTP dead;
5874     regMaskTP chg;
5875
5876 #ifdef DEBUG
5877     if (EMIT_GC_VERBOSE)
5878     {
5879         printf("New %sReg live regs=", GCtypeStr(gcType));
5880         printRegMaskInt(regs);
5881         emitDispRegSet(regs);
5882         printf("\n");
5883     }
5884 #endif
5885
5886     assert(needsGC(gcType));
5887
5888     regMaskTP& emitThisXXrefRegs = (gcType == GCT_GCREF) ? emitThisGCrefRegs : emitThisByrefRegs;
5889     regMaskTP& emitThisYYrefRegs = (gcType == GCT_GCREF) ? emitThisByrefRegs : emitThisGCrefRegs;
5890     assert(emitThisXXrefRegs != regs);
5891
5892     if (emitFullGCinfo)
5893     {
5894         /* Figure out which GC registers are becoming live/dead at this point */
5895
5896         dead = (emitThisXXrefRegs & ~regs);
5897         life = (~emitThisXXrefRegs & regs);
5898
5899         /* Can't simultaneously become live and dead at the same time */
5900
5901         assert((dead | life) != 0);
5902         assert((dead & life) == 0);
5903
5904         /* Compute the 'changing state' mask */
5905
5906         chg = (dead | life);
5907
5908         do
5909         {
5910             regMaskTP bit = genFindLowestBit(chg);
5911             regNumber reg = genRegNumFromMask(bit);
5912
5913             if (life & bit)
5914             {
5915                 emitGCregLiveUpd(gcType, reg, addr);
5916             }
5917             else
5918             {
5919                 emitGCregDeadUpd(reg, addr);
5920             }
5921
5922             chg -= bit;
5923         } while (chg);
5924
5925         assert(emitThisXXrefRegs == regs);
5926     }
5927     else
5928     {
5929         emitThisYYrefRegs &= ~regs; // Kill the regs from the other GC type (if live)
5930         emitThisXXrefRegs = regs;   // Mark them as live in the requested GC type
5931     }
5932
5933     // The 2 GC reg masks can't be overlapping
5934
5935     assert((emitThisGCrefRegs & emitThisByrefRegs) == 0);
5936 }
5937
5938 /*****************************************************************************
5939  *
5940  *  Record the fact that the given register now contains a live GC ref.
5941  */
5942
5943 void emitter::emitGCregLiveSet(GCtype gcType, regMaskTP regMask, BYTE* addr, bool isThis)
5944 {
5945     assert(emitIssuing);
5946     assert(needsGC(gcType));
5947
5948     regPtrDsc* regPtrNext;
5949
5950     assert(!isThis || emitComp->lvaKeepAliveAndReportThis());
5951     // assert(emitFullyInt || isThis);
5952     assert(emitFullGCinfo);
5953
5954     assert(((emitThisGCrefRegs | emitThisByrefRegs) & regMask) == 0);
5955
5956     /* Allocate a new regptr entry and fill it in */
5957
5958     regPtrNext            = codeGen->gcInfo.gcRegPtrAllocDsc();
5959     regPtrNext->rpdGCtype = gcType;
5960
5961     regPtrNext->rpdOffs            = emitCurCodeOffs(addr);
5962     regPtrNext->rpdArg             = FALSE;
5963     regPtrNext->rpdCall            = FALSE;
5964     regPtrNext->rpdIsThis          = isThis;
5965     regPtrNext->rpdCompiler.rpdAdd = (regMaskSmall)regMask;
5966     regPtrNext->rpdCompiler.rpdDel = 0;
5967 }
5968
5969 /*****************************************************************************
5970  *
5971  *  Record the fact that the given register no longer contains a live GC ref.
5972  */
5973
5974 void emitter::emitGCregDeadSet(GCtype gcType, regMaskTP regMask, BYTE* addr)
5975 {
5976     assert(emitIssuing);
5977     assert(needsGC(gcType));
5978
5979     regPtrDsc* regPtrNext;
5980
5981     // assert(emitFullyInt);
5982     assert(emitFullGCinfo);
5983
5984     assert(((emitThisGCrefRegs | emitThisByrefRegs) & regMask) != 0);
5985
5986     /* Allocate a new regptr entry and fill it in */
5987
5988     regPtrNext            = codeGen->gcInfo.gcRegPtrAllocDsc();
5989     regPtrNext->rpdGCtype = gcType;
5990
5991     regPtrNext->rpdOffs            = emitCurCodeOffs(addr);
5992     regPtrNext->rpdCall            = FALSE;
5993     regPtrNext->rpdIsThis          = FALSE;
5994     regPtrNext->rpdArg             = FALSE;
5995     regPtrNext->rpdCompiler.rpdAdd = 0;
5996     regPtrNext->rpdCompiler.rpdDel = (regMaskSmall)regMask;
5997 }
5998
5999 /*****************************************************************************
6000  *
6001  *  Emit an 8-bit integer as code.
6002  */
6003
6004 unsigned char emitter::emitOutputByte(BYTE* dst, ssize_t val)
6005 {
6006     *castto(dst, unsigned char*) = (unsigned char)val;
6007
6008 #ifdef DEBUG
6009     if (emitComp->opts.dspEmit)
6010     {
6011         printf("; emit_byte 0%02XH\n", val & 0xFF);
6012     }
6013 #ifdef _TARGET_AMD64_
6014     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6015     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6016 #endif // _TARGET_AMD64_
6017 #endif
6018
6019     return sizeof(unsigned char);
6020 }
6021
6022 /*****************************************************************************
6023  *
6024  *  Emit a 16-bit integer as code.
6025  */
6026
6027 unsigned char emitter::emitOutputWord(BYTE* dst, ssize_t val)
6028 {
6029     MISALIGNED_WR_I2(dst, (short)val);
6030
6031 #ifdef DEBUG
6032     if (emitComp->opts.dspEmit)
6033     {
6034         printf("; emit_word 0%02XH,0%02XH\n", (val & 0xFF), (val >> 8) & 0xFF);
6035     }
6036 #ifdef _TARGET_AMD64_
6037     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6038     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6039 #endif // _TARGET_AMD64_
6040 #endif
6041
6042     return sizeof(short);
6043 }
6044
6045 /*****************************************************************************
6046  *
6047  *  Emit a 32-bit integer as code.
6048  */
6049
6050 unsigned char emitter::emitOutputLong(BYTE* dst, ssize_t val)
6051 {
6052     MISALIGNED_WR_I4(dst, (int)val);
6053
6054 #ifdef DEBUG
6055     if (emitComp->opts.dspEmit)
6056     {
6057         printf("; emit_long 0%08XH\n", (int)val);
6058     }
6059 #ifdef _TARGET_AMD64_
6060     // if we're emitting code bytes, ensure that we've already emitted the rex prefix!
6061     assert(((val & 0xFF00000000LL) == 0) || ((val & 0xFFFFFFFF00000000LL) == 0xFFFFFFFF00000000LL));
6062 #endif // _TARGET_AMD64_
6063 #endif
6064
6065     return sizeof(int);
6066 }
6067
6068 /*****************************************************************************
6069  *
6070  *  Emit a pointer-sized integer as code.
6071  */
6072
6073 unsigned char emitter::emitOutputSizeT(BYTE* dst, ssize_t val)
6074 {
6075     MISALIGNED_WR_ST(dst, val);
6076
6077 #ifdef DEBUG
6078     if (emitComp->opts.dspEmit)
6079     {
6080 #ifdef _TARGET_AMD64_
6081         printf("; emit_size_t 0%016llXH\n", val);
6082 #else  // _TARGET_AMD64_
6083         printf("; emit_size_t 0%08XH\n", val);
6084 #endif // _TARGET_AMD64_
6085     }
6086 #endif // DEBUG
6087
6088     return sizeof(size_t);
6089 }
6090
6091 //------------------------------------------------------------------------
6092 // Wrappers to emitOutputByte, emitOutputWord, emitOutputLong, emitOutputSizeT
6093 // that take unsigned __int64 or size_t type instead of ssize_t. Used on RyuJIT/x86.
6094 //
6095 // Arguments:
6096 //    dst - passed through
6097 //    val - passed through
6098 //
6099 // Return Value:
6100 //    Same as wrapped function.
6101 //
6102
6103 #if !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
6104 unsigned char emitter::emitOutputByte(BYTE* dst, size_t val)
6105 {
6106     return emitOutputByte(dst, (ssize_t)val);
6107 }
6108
6109 unsigned char emitter::emitOutputWord(BYTE* dst, size_t val)
6110 {
6111     return emitOutputWord(dst, (ssize_t)val);
6112 }
6113
6114 unsigned char emitter::emitOutputLong(BYTE* dst, size_t val)
6115 {
6116     return emitOutputLong(dst, (ssize_t)val);
6117 }
6118
6119 unsigned char emitter::emitOutputSizeT(BYTE* dst, size_t val)
6120 {
6121     return emitOutputSizeT(dst, (ssize_t)val);
6122 }
6123
6124 unsigned char emitter::emitOutputByte(BYTE* dst, unsigned __int64 val)
6125 {
6126     return emitOutputByte(dst, (ssize_t)val);
6127 }
6128
6129 unsigned char emitter::emitOutputWord(BYTE* dst, unsigned __int64 val)
6130 {
6131     return emitOutputWord(dst, (ssize_t)val);
6132 }
6133
6134 unsigned char emitter::emitOutputLong(BYTE* dst, unsigned __int64 val)
6135 {
6136     return emitOutputLong(dst, (ssize_t)val);
6137 }
6138
6139 unsigned char emitter::emitOutputSizeT(BYTE* dst, unsigned __int64 val)
6140 {
6141     return emitOutputSizeT(dst, (ssize_t)val);
6142 }
6143 #endif // !defined(LEGACY_BACKEND) && defined(_TARGET_X86_)
6144
6145 /*****************************************************************************
6146  *
6147  *  Given a block cookie and a code position, return the actual code offset;
6148  *  this can only be called at the end of code generation.
6149  */
6150
6151 UNATIVE_OFFSET emitter::emitCodeOffset(void* blockPtr, unsigned codePos)
6152 {
6153     insGroup* ig;
6154
6155     UNATIVE_OFFSET of;
6156     unsigned       no = emitGetInsNumFromCodePos(codePos);
6157
6158     /* Make sure we weren't passed some kind of a garbage thing */
6159
6160     ig = (insGroup*)blockPtr;
6161 #ifdef DEBUG
6162     assert(ig && ig->igSelf == ig);
6163 #endif
6164
6165     /* The first and last offsets are always easy */
6166
6167     if (no == 0)
6168     {
6169         of = 0;
6170     }
6171     else if (no == ig->igInsCnt)
6172     {
6173         of = ig->igSize;
6174     }
6175     else if (ig->igFlags & IGF_UPD_ISZ)
6176     {
6177         /*
6178             Some instruction sizes have changed, so we'll have to figure
6179             out the instruction offset "the hard way".
6180          */
6181
6182         of = emitFindOffset(ig, no);
6183     }
6184     else
6185     {
6186         /* All instructions correctly predicted, the offset stays the same */
6187
6188         of = emitGetInsOfsFromCodePos(codePos);
6189
6190         // printf("[IG=%02u;ID=%03u;OF=%04X] <= %08X\n", ig->igNum, emitGetInsNumFromCodePos(codePos), of, codePos);
6191
6192         /* Make sure the offset estimate is accurate */
6193
6194         assert(of == emitFindOffset(ig, emitGetInsNumFromCodePos(codePos)));
6195     }
6196
6197     return ig->igOffs + of;
6198 }
6199
6200 /*****************************************************************************
6201  *
6202  *  Record the fact that the given register now contains a live GC ref.
6203  */
6204
6205 void emitter::emitGCregLiveUpd(GCtype gcType, regNumber reg, BYTE* addr)
6206 {
6207     assert(emitIssuing);
6208
6209     // Don't track GC changes in epilogs
6210     if (emitIGisInEpilog(emitCurIG))
6211     {
6212         return;
6213     }
6214
6215     assert(needsGC(gcType));
6216
6217     regMaskTP regMask = genRegMask(reg);
6218
6219     regMaskTP& emitThisXXrefRegs = (gcType == GCT_GCREF) ? emitThisGCrefRegs : emitThisByrefRegs;
6220     regMaskTP& emitThisYYrefRegs = (gcType == GCT_GCREF) ? emitThisByrefRegs : emitThisGCrefRegs;
6221
6222     if ((emitThisXXrefRegs & regMask) == 0)
6223     {
6224         // If the register was holding the other GC type, that type should
6225         // go dead now
6226
6227         if (emitThisYYrefRegs & regMask)
6228         {
6229             emitGCregDeadUpd(reg, addr);
6230         }
6231
6232         // For synchronized methods, "this" is always alive and in the same register.
6233         // However, if we generate any code after the epilog block (where "this"
6234         // goes dead), "this" will come alive again. We need to notice that.
6235         // Note that we only expect isThis to be true at an insGroup boundary.
6236
6237         bool isThis = (reg == emitSyncThisObjReg) ? true : false;
6238
6239         if (emitFullGCinfo)
6240         {
6241             emitGCregLiveSet(gcType, regMask, addr, isThis);
6242         }
6243
6244         emitThisXXrefRegs |= regMask;
6245
6246 #ifdef DEBUG
6247         if (EMIT_GC_VERBOSE)
6248         {
6249             printf("%sReg +[%s]\n", GCtypeStr(gcType), emitRegName(reg));
6250         }
6251 #endif
6252     }
6253
6254     // The 2 GC reg masks can't be overlapping
6255
6256     assert((emitThisGCrefRegs & emitThisByrefRegs) == 0);
6257 }
6258
6259 /*****************************************************************************
6260  *
6261  *  Record the fact that the given set of registers no longer contain live GC refs.
6262  */
6263
6264 void emitter::emitGCregDeadUpdMask(regMaskTP regs, BYTE* addr)
6265 {
6266     assert(emitIssuing);
6267
6268     // Don't track GC changes in epilogs
6269     if (emitIGisInEpilog(emitCurIG))
6270     {
6271         return;
6272     }
6273
6274     // First, handle the gcref regs going dead
6275
6276     regMaskTP gcrefRegs = emitThisGCrefRegs & regs;
6277
6278     // "this" can never go dead in synchronized methods, except in the epilog
6279     // after the call to CORINFO_HELP_MON_EXIT.
6280     assert(emitSyncThisObjReg == REG_NA || (genRegMask(emitSyncThisObjReg) & regs) == 0);
6281
6282     if (gcrefRegs)
6283     {
6284         assert((emitThisByrefRegs & gcrefRegs) == 0);
6285
6286         if (emitFullGCinfo)
6287         {
6288             emitGCregDeadSet(GCT_GCREF, gcrefRegs, addr);
6289         }
6290
6291         emitThisGCrefRegs &= ~gcrefRegs;
6292
6293 #ifdef DEBUG
6294         if (EMIT_GC_VERBOSE)
6295         {
6296             printf("gcrReg ");
6297             printRegMaskInt(gcrefRegs);
6298             printf(" -");
6299             emitDispRegSet(gcrefRegs);
6300             printf("\n");
6301         }
6302 #endif
6303     }
6304
6305     // Second, handle the byref regs going dead
6306
6307     regMaskTP byrefRegs = emitThisByrefRegs & regs;
6308
6309     if (byrefRegs)
6310     {
6311         assert((emitThisGCrefRegs & byrefRegs) == 0);
6312
6313         if (emitFullGCinfo)
6314         {
6315             emitGCregDeadSet(GCT_BYREF, byrefRegs, addr);
6316         }
6317
6318         emitThisByrefRegs &= ~byrefRegs;
6319
6320 #ifdef DEBUG
6321         if (EMIT_GC_VERBOSE)
6322         {
6323             printf("byrReg ");
6324             printRegMaskInt(byrefRegs);
6325             printf(" -");
6326             emitDispRegSet(byrefRegs);
6327             printf("\n");
6328         }
6329 #endif
6330     }
6331 }
6332
6333 /*****************************************************************************
6334  *
6335  *  Record the fact that the given register no longer contains a live GC ref.
6336  */
6337
6338 void emitter::emitGCregDeadUpd(regNumber reg, BYTE* addr)
6339 {
6340     assert(emitIssuing);
6341
6342     // Don't track GC changes in epilogs
6343     if (emitIGisInEpilog(emitCurIG))
6344     {
6345         return;
6346     }
6347
6348     regMaskTP regMask = genRegMask(reg);
6349
6350     if ((emitThisGCrefRegs & regMask) != 0)
6351     {
6352         assert((emitThisByrefRegs & regMask) == 0);
6353
6354         if (emitFullGCinfo)
6355         {
6356             emitGCregDeadSet(GCT_GCREF, regMask, addr);
6357         }
6358
6359         emitThisGCrefRegs &= ~regMask;
6360
6361 #ifdef DEBUG
6362         if (EMIT_GC_VERBOSE)
6363         {
6364             printf("%s -[%s]\n", "gcrReg", emitRegName(reg));
6365         }
6366 #endif
6367     }
6368     else if ((emitThisByrefRegs & regMask) != 0)
6369     {
6370         if (emitFullGCinfo)
6371         {
6372             emitGCregDeadSet(GCT_BYREF, regMask, addr);
6373         }
6374
6375         emitThisByrefRegs &= ~regMask;
6376
6377 #ifdef DEBUG
6378         if (EMIT_GC_VERBOSE)
6379         {
6380             printf("%s -[%s]\n", "byrReg", emitRegName(reg));
6381         }
6382 #endif
6383     }
6384 }
6385
6386 /*****************************************************************************
6387  *
6388  *  Record the fact that the given variable now contains a live GC ref.
6389  *  varNum may be INT_MAX or negative (indicating a spill temp) only if
6390  *    offs is guaranteed to be the offset of a tracked GC ref. Else we
6391  *    need a valid value to check if the variable is tracked or not.
6392  */
6393
6394 void emitter::emitGCvarLiveUpd(int offs, int varNum, GCtype gcType, BYTE* addr)
6395 {
6396     assert(abs(offs) % sizeof(int) == 0);
6397     assert(needsGC(gcType));
6398
6399 #if FEATURE_FIXED_OUT_ARGS
6400     if ((unsigned)varNum == emitComp->lvaOutgoingArgSpaceVar)
6401     {
6402         if (emitFullGCinfo)
6403         {
6404             /* Append an "arg push" entry to track a GC written to the
6405                outgoing argument space.
6406                Allocate a new ptr arg entry and fill it in */
6407
6408             regPtrDsc* regPtrNext = gcInfo->gcRegPtrAllocDsc();
6409             regPtrNext->rpdGCtype = gcType;
6410             regPtrNext->rpdOffs   = emitCurCodeOffs(addr);
6411             regPtrNext->rpdArg    = TRUE;
6412             regPtrNext->rpdCall   = FALSE;
6413             noway_assert(FitsIn<unsigned short>(offs));
6414             regPtrNext->rpdPtrArg  = (unsigned short)offs;
6415             regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_PUSH;
6416             regPtrNext->rpdIsThis  = FALSE;
6417
6418 #ifdef DEBUG
6419             if (EMIT_GC_VERBOSE)
6420             {
6421                 printf("[%04X] %s arg write\n", offs, GCtypeStr(gcType));
6422             }
6423 #endif
6424         }
6425     }
6426     else
6427 #endif // FEATURE_FIXED_OUT_ARGS
6428     {
6429         /* Is the frame offset within the "interesting" range? */
6430
6431         if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
6432         {
6433             /* Normally all variables in this range must be tracked stack
6434                pointers. However, for EnC, we relax this condition. So we
6435                must check if this is not such a variable.
6436                Note that varNum might be negative, indicating a spill temp.
6437             */
6438
6439             if (varNum != INT_MAX)
6440             {
6441                 bool isTracked = false;
6442                 if (varNum >= 0)
6443                 {
6444                     // This is NOT a spill temp
6445                     LclVarDsc* varDsc = &emitComp->lvaTable[varNum];
6446                     isTracked         = emitComp->lvaIsGCTracked(varDsc);
6447                 }
6448                 else
6449                 {
6450                     // Is it an untracked spill temp?
6451                     isTracked = TRACK_GC_TEMP_LIFETIMES;
6452                 }
6453                 if (!isTracked)
6454                 {
6455 #if DOUBLE_ALIGN
6456                     assert(!emitContTrkPtrLcls ||
6457                            // EBP based variables in the double-aligned frames are indeed input arguments.
6458                            // and we don't require them to fall into the "interesting" range.
6459                            ((emitComp->rpFrameType == FT_DOUBLE_ALIGN_FRAME) && (varNum >= 0) &&
6460                             (emitComp->lvaTable[varNum].lvFramePointerBased == 1)));
6461 #else
6462                     assert(!emitContTrkPtrLcls);
6463 #endif
6464                     return;
6465                 }
6466             }
6467
6468             size_t disp;
6469
6470             /* Compute the index into the GC frame table */
6471
6472             disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
6473             assert(disp < emitGCrFrameOffsCnt);
6474
6475             /* If the variable is currently dead, mark it as live */
6476
6477             if (emitGCrFrameLiveTab[disp] == nullptr)
6478             {
6479                 emitGCvarLiveSet(offs, gcType, addr, disp);
6480             }
6481         }
6482     }
6483 }
6484
6485 /*****************************************************************************
6486  *
6487  *  Record the fact that the given variable no longer contains a live GC ref.
6488  */
6489
6490 void emitter::emitGCvarDeadUpd(int offs, BYTE* addr)
6491 {
6492     assert(emitIssuing);
6493     assert(abs(offs) % sizeof(int) == 0);
6494
6495     /* Is the frame offset within the "interesting" range? */
6496
6497     if (offs >= emitGCrFrameOffsMin && offs < emitGCrFrameOffsMax)
6498     {
6499         size_t disp;
6500
6501         /* Compute the index into the GC frame table */
6502
6503         disp = (offs - emitGCrFrameOffsMin) / sizeof(void*);
6504         assert(disp < emitGCrFrameOffsCnt);
6505
6506         /* If the variable is currently live, mark it as dead */
6507
6508         if (emitGCrFrameLiveTab[disp] != nullptr)
6509         {
6510             emitGCvarDeadSet(offs, addr, disp);
6511         }
6512     }
6513 }
6514
6515 /*****************************************************************************
6516  *
6517  *  Allocate a new IG and link it in to the global list after the current IG
6518  */
6519
6520 insGroup* emitter::emitAllocAndLinkIG()
6521 {
6522     insGroup* ig = emitAllocIG();
6523
6524     assert(emitCurIG);
6525
6526     emitInsertIGAfter(emitCurIG, ig);
6527
6528     /* Propagate some IG flags from the current group to the new group */
6529
6530     ig->igFlags |= (emitCurIG->igFlags & IGF_PROPAGATE_MASK);
6531
6532     /* Set the new IG as the current IG */
6533
6534     emitCurIG = ig;
6535
6536     return ig;
6537 }
6538
6539 /*****************************************************************************
6540  *
6541  *  Allocate an instruction group descriptor and assign it the next index.
6542  */
6543
6544 insGroup* emitter::emitAllocIG()
6545 {
6546     insGroup* ig;
6547
6548     /* Allocate a group descriptor */
6549
6550     size_t sz = sizeof(insGroup);
6551     ig        = (insGroup*)emitGetMem(sz);
6552
6553 #ifdef DEBUG
6554     ig->igSelf = ig;
6555 #endif
6556
6557 #if EMITTER_STATS
6558     emitTotalIGcnt += 1;
6559     emitTotalIGsize += sz;
6560     emitSizeMethod += sz;
6561 #endif
6562
6563     /* Do basic initialization */
6564
6565     emitInitIG(ig);
6566
6567     return ig;
6568 }
6569
6570 /*****************************************************************************
6571  *
6572  *  Initialize an instruction group
6573  */
6574
6575 void emitter::emitInitIG(insGroup* ig)
6576 {
6577     /* Assign the next available index to the instruction group */
6578
6579     ig->igNum = emitNxtIGnum;
6580
6581     emitNxtIGnum++;
6582
6583     /* Record the (estimated) code offset of the group */
6584
6585     ig->igOffs = emitCurCodeOffset;
6586     assert(IsCodeAligned(ig->igOffs));
6587
6588     /* Set the current function index */
6589
6590     ig->igFuncIdx = emitComp->compCurrFuncIdx;
6591
6592     ig->igFlags = 0;
6593
6594     /* Zero out some fields to avoid printing garbage in JitDumps. These
6595        really only need to be set in DEBUG, but do it in all cases to make
6596        sure we act the same in non-DEBUG builds.
6597     */
6598
6599     ig->igSize   = 0;
6600     ig->igGCregs = RBM_NONE;
6601     ig->igInsCnt = 0;
6602 }
6603
6604 /*****************************************************************************
6605  *
6606  *  Insert instruction group 'ig' after 'igInsertAfterIG'
6607  */
6608
6609 void emitter::emitInsertIGAfter(insGroup* insertAfterIG, insGroup* ig)
6610 {
6611     assert(emitIGlist);
6612     assert(emitIGlast);
6613
6614     ig->igNext            = insertAfterIG->igNext;
6615     insertAfterIG->igNext = ig;
6616
6617     if (emitIGlast == insertAfterIG)
6618     {
6619         // If we are inserting at the end, then update the 'last' pointer
6620         emitIGlast = ig;
6621     }
6622 }
6623
6624 /*****************************************************************************
6625  *
6626  *  Save the current IG and start a new one.
6627  */
6628
6629 void emitter::emitNxtIG(bool emitAdd)
6630 {
6631     /* Right now we don't allow multi-IG prologs */
6632
6633     assert(emitCurIG != emitPrologIG);
6634
6635     /* First save the current group */
6636
6637     emitSavIG(emitAdd);
6638
6639     /* Update the GC live sets for the group's start
6640      * Do it only if not an emitter added block */
6641
6642     if (!emitAdd)
6643     {
6644         VarSetOps::Assign(emitComp, emitInitGCrefVars, emitThisGCrefVars);
6645         emitInitGCrefRegs = emitThisGCrefRegs;
6646         emitInitByrefRegs = emitThisByrefRegs;
6647     }
6648
6649     /* Start generating the new group */
6650
6651     emitNewIG();
6652
6653     /* If this is an emitter added block, flag it */
6654
6655     if (emitAdd)
6656     {
6657         emitCurIG->igFlags |= IGF_EMIT_ADD;
6658     }
6659
6660     // We've created a new IG; no need to force another one.
6661     emitForceNewIG = false;
6662 }
6663
6664 /*****************************************************************************
6665  *
6666  *  emitGetInsSC: Get the instruction's constant value.
6667  */
6668
6669 ssize_t emitter::emitGetInsSC(instrDesc* id)
6670 {
6671 #ifdef _TARGET_ARM_ // should it be _TARGET_ARMARCH_? Why do we need this? Note that on ARM64 we store scaled immediates
6672                     // for some formats
6673     if (id->idIsLclVar())
6674     {
6675         int varNum = id->idAddr()->iiaLclVar.lvaVarNum();
6676
6677         regNumber baseReg;
6678         int       offs = id->idAddr()->iiaLclVar.lvaOffset();
6679 #if defined(_TARGET_ARM_)
6680         int adr = emitComp->lvaFrameAddress(varNum, id->idIsLclFPBase(), &baseReg, offs);
6681         int dsp = adr + offs;
6682         if ((id->idIns() == INS_sub) || (id->idIns() == INS_subw))
6683             dsp = -dsp;
6684 #elif defined(_TARGET_ARM64_)
6685         // TODO-ARM64-Cleanup: this is currently unreachable. Do we need it?
6686         bool FPbased;
6687         int  adr = emitComp->lvaFrameAddress(varNum, &FPbased);
6688         int  dsp = adr + offs;
6689         if (id->idIns() == INS_sub)
6690             dsp = -dsp;
6691 #endif
6692         return dsp;
6693     }
6694     else
6695 #endif // _TARGET_ARM_
6696         if (id->idIsLargeCns())
6697     {
6698         return ((instrDescCns*)id)->idcCnsVal;
6699     }
6700     else
6701     {
6702         return id->idSmallCns();
6703     }
6704 }
6705
6706 /*****************************************************************************/
6707 #if EMIT_TRACK_STACK_DEPTH
6708 /*****************************************************************************
6709  *
6710  *  Record a push of a single dword on the stack.
6711  */
6712
6713 void emitter::emitStackPush(BYTE* addr, GCtype gcType)
6714 {
6715 #ifdef DEBUG
6716     assert(IsValidGCtype(gcType));
6717 #endif
6718
6719     if (emitSimpleStkUsed)
6720     {
6721         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6722         assert(emitCurStackLvl / sizeof(int) < MAX_SIMPLE_STK_DEPTH);
6723
6724         u1.emitSimpleStkMask <<= 1;
6725         u1.emitSimpleStkMask |= (unsigned)needsGC(gcType);
6726
6727         u1.emitSimpleByrefStkMask <<= 1;
6728         u1.emitSimpleByrefStkMask |= (gcType == GCT_BYREF);
6729
6730         assert((u1.emitSimpleStkMask & u1.emitSimpleByrefStkMask) == u1.emitSimpleByrefStkMask);
6731     }
6732     else
6733     {
6734         emitStackPushLargeStk(addr, gcType);
6735     }
6736
6737     emitCurStackLvl += sizeof(int);
6738 }
6739
6740 /*****************************************************************************
6741  *
6742  *  Record a push of a bunch of non-GC dwords on the stack.
6743  */
6744
6745 void emitter::emitStackPushN(BYTE* addr, unsigned count)
6746 {
6747     assert(count);
6748
6749     if (emitSimpleStkUsed)
6750     {
6751         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6752
6753         u1.emitSimpleStkMask <<= count;
6754         u1.emitSimpleByrefStkMask <<= count;
6755     }
6756     else
6757     {
6758         emitStackPushLargeStk(addr, GCT_NONE, count);
6759     }
6760
6761     emitCurStackLvl += count * sizeof(int);
6762 }
6763
6764 /*****************************************************************************
6765  *
6766  *  Record a pop of the given number of dwords from the stack.
6767  */
6768
6769 void emitter::emitStackPop(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count)
6770 {
6771     assert(emitCurStackLvl / sizeof(int) >= count);
6772     assert(!isCall || callInstrSize > 0);
6773
6774     if (count)
6775     {
6776         if (emitSimpleStkUsed)
6777         {
6778             assert(!emitFullGCinfo); // Simple stk not used for emitFullGCinfo
6779
6780             unsigned cnt = count;
6781
6782             do
6783             {
6784                 u1.emitSimpleStkMask >>= 1;
6785                 u1.emitSimpleByrefStkMask >>= 1;
6786             } while (--cnt);
6787         }
6788         else
6789         {
6790             emitStackPopLargeStk(addr, isCall, callInstrSize, count);
6791         }
6792
6793         emitCurStackLvl -= count * sizeof(int);
6794     }
6795     else
6796     {
6797         assert(isCall);
6798
6799         // For the general encoder we do the call below always when it's a call, to ensure that the call is
6800         // recorded (when we're doing the ptr reg map for a non-fully-interruptible method).
6801         if (emitFullGCinfo
6802 #ifndef JIT32_GCENCODER
6803             || (emitComp->genFullPtrRegMap && (!emitComp->genInterruptible) && isCall)
6804 #endif // JIT32_GCENCODER
6805                 )
6806         {
6807             emitStackPopLargeStk(addr, isCall, callInstrSize, 0);
6808         }
6809     }
6810 }
6811
6812 /*****************************************************************************
6813  *
6814  *  Record a push of a single word on the stack for a full pointer map.
6815  */
6816
6817 void emitter::emitStackPushLargeStk(BYTE* addr, GCtype gcType, unsigned count)
6818 {
6819     S_UINT32 level(emitCurStackLvl / sizeof(int));
6820
6821     assert(IsValidGCtype(gcType));
6822     assert(count);
6823     assert(!emitSimpleStkUsed);
6824
6825     do
6826     {
6827         /* Push an entry for this argument on the tracking stack */
6828
6829         // printf("Pushed [%d] at lvl %2u [max=%u]\n", isGCref, emitArgTrackTop - emitArgTrackTab, emitMaxStackDepth);
6830
6831         assert(level.IsOverflow() || u2.emitArgTrackTop == u2.emitArgTrackTab + level.Value());
6832         *u2.emitArgTrackTop++ = (BYTE)gcType;
6833         assert(u2.emitArgTrackTop <= u2.emitArgTrackTab + emitMaxStackDepth);
6834
6835         if (emitFullArgInfo || needsGC(gcType))
6836         {
6837             if (emitFullGCinfo)
6838             {
6839                 /* Append an "arg push" entry if this is a GC ref or
6840                    FPO method. Allocate a new ptr arg entry and fill it in */
6841
6842                 regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
6843                 regPtrNext->rpdGCtype = gcType;
6844
6845                 regPtrNext->rpdOffs = emitCurCodeOffs(addr);
6846                 regPtrNext->rpdArg  = TRUE;
6847                 regPtrNext->rpdCall = FALSE;
6848                 if (level.IsOverflow() || !FitsIn<unsigned short>(level.Value()))
6849                 {
6850                     IMPL_LIMITATION("Too many/too big arguments to encode GC information");
6851                 }
6852                 regPtrNext->rpdPtrArg  = (unsigned short)level.Value();
6853                 regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_PUSH;
6854                 regPtrNext->rpdIsThis  = FALSE;
6855
6856 #ifdef DEBUG
6857                 if (EMIT_GC_VERBOSE)
6858                 {
6859                     printf("[%08X] %s arg push %u\n", dspPtr(regPtrNext), GCtypeStr(gcType), level.Value());
6860                 }
6861 #endif
6862             }
6863
6864             /* This is an "interesting" argument push */
6865
6866             u2.emitGcArgTrackCnt++;
6867         }
6868         level += 1;
6869         assert(!level.IsOverflow());
6870     } while (--count);
6871 }
6872
6873 /*****************************************************************************
6874  *
6875  *  Record a pop of the given number of words from the stack for a full ptr
6876  *  map.
6877  */
6878
6879 void emitter::emitStackPopLargeStk(BYTE* addr, bool isCall, unsigned char callInstrSize, unsigned count)
6880 {
6881     assert(emitIssuing);
6882
6883     unsigned argStkCnt;
6884     S_UINT16 argRecCnt(0); // arg count for ESP, ptr-arg count for EBP
6885     unsigned gcrefRegs, byrefRegs;
6886
6887 #ifdef JIT32_GCENCODER
6888     // For the general encoder, we always need to record calls, so we make this call
6889     // even when emitSimpleStkUsed is true.
6890     assert(!emitSimpleStkUsed);
6891 #endif
6892
6893     /* Count how many pointer records correspond to this "pop" */
6894
6895     for (argStkCnt = count; argStkCnt; argStkCnt--)
6896     {
6897         assert(u2.emitArgTrackTop > u2.emitArgTrackTab);
6898
6899         GCtype gcType = (GCtype)(*--u2.emitArgTrackTop);
6900
6901         assert(IsValidGCtype(gcType));
6902
6903         // printf("Popped [%d] at lvl %u\n", GCtypeStr(gcType), emitArgTrackTop - emitArgTrackTab);
6904
6905         // This is an "interesting" argument
6906
6907         if (emitFullArgInfo || needsGC(gcType))
6908         {
6909             argRecCnt += 1;
6910         }
6911     }
6912
6913     assert(u2.emitArgTrackTop >= u2.emitArgTrackTab);
6914     assert(u2.emitArgTrackTop == u2.emitArgTrackTab + emitCurStackLvl / sizeof(int) - count);
6915     noway_assert(!argRecCnt.IsOverflow());
6916
6917     /* We're about to pop the corresponding arg records */
6918
6919     u2.emitGcArgTrackCnt -= argRecCnt.Value();
6920
6921 #ifdef JIT32_GCENCODER
6922     // For the general encoder, we always have to record calls, so we don't take this early return.
6923     if (!emitFullGCinfo)
6924         return;
6925 #endif
6926
6927     // Do we have any interesting (i.e., callee-saved) registers live here?
6928
6929     gcrefRegs = byrefRegs = 0;
6930
6931     // We make a bitmask whose bits correspond to callee-saved register indices (in the sequence
6932     // of callee-saved registers only).
6933     for (unsigned calleeSavedRegIdx = 0; calleeSavedRegIdx < CNT_CALLEE_SAVED; calleeSavedRegIdx++)
6934     {
6935         regMaskTP calleeSavedRbm = raRbmCalleeSaveOrder[calleeSavedRegIdx];
6936         if (emitThisGCrefRegs & calleeSavedRbm)
6937         {
6938             gcrefRegs |= (1 << calleeSavedRegIdx);
6939         }
6940         if (emitThisByrefRegs & calleeSavedRbm)
6941         {
6942             byrefRegs |= (1 << calleeSavedRegIdx);
6943         }
6944     }
6945
6946 #ifdef JIT32_GCENCODER
6947     // For the general encoder, we always have to record calls, so we don't take this early return.    /* Are there any
6948     // args to pop at this call site?
6949
6950     if (argRecCnt.Value() == 0)
6951     {
6952         /*
6953             Or do we have a partially interruptible EBP-less frame, and any
6954             of EDI,ESI,EBX,EBP are live, or is there an outer/pending call?
6955          */
6956         CLANG_FORMAT_COMMENT_ANCHOR;
6957
6958 #if !FPO_INTERRUPTIBLE
6959         if (emitFullyInt || (gcrefRegs == 0 && byrefRegs == 0 && u2.emitGcArgTrackCnt == 0))
6960 #endif
6961             return;
6962     }
6963 #endif // JIT32_GCENCODER
6964
6965     /* Only calls may pop more than one value */
6966     // More detail:
6967     // _cdecl calls accomplish this popping via a post-call-instruction SP adjustment.
6968     // The "rpdCall" field below should be interpreted as "the instruction accomplishes
6969     // call-related popping, even if it's not itself a call".  Therefore, we don't just
6970     // use the "isCall" input argument, which means that the instruction actually is a call --
6971     // we use the OR of "isCall" or the "pops more than one value."
6972
6973     bool isCallRelatedPop = (argRecCnt.Value() > 1);
6974
6975     /* Allocate a new ptr arg entry and fill it in */
6976
6977     regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
6978     regPtrNext->rpdGCtype = GCT_GCREF; // Pops need a non-0 value (??)
6979
6980     regPtrNext->rpdOffs = emitCurCodeOffs(addr);
6981     regPtrNext->rpdCall = (isCall || isCallRelatedPop);
6982 #ifndef JIT32_GCENCODER
6983     if (regPtrNext->rpdCall)
6984     {
6985         assert(isCall || callInstrSize == 0);
6986         regPtrNext->rpdCallInstrSize = callInstrSize;
6987     }
6988 #endif
6989     regPtrNext->rpdCallGCrefRegs = gcrefRegs;
6990     regPtrNext->rpdCallByrefRegs = byrefRegs;
6991     regPtrNext->rpdArg           = TRUE;
6992     regPtrNext->rpdArgType       = (unsigned short)GCInfo::rpdARG_POP;
6993     regPtrNext->rpdPtrArg        = argRecCnt.Value();
6994
6995 #ifdef DEBUG
6996     if (EMIT_GC_VERBOSE)
6997     {
6998         printf("[%08X] ptr arg pop  %u\n", dspPtr(regPtrNext), count);
6999     }
7000 #endif
7001 }
7002
7003 /*****************************************************************************
7004  *  For caller-pop arguments, we report the arguments as pending arguments.
7005  *  However, any GC arguments are now dead, so we need to report them
7006  *  as non-GC.
7007  */
7008
7009 void emitter::emitStackKillArgs(BYTE* addr, unsigned count, unsigned char callInstrSize)
7010 {
7011     assert(count > 0);
7012
7013     if (emitSimpleStkUsed)
7014     {
7015         assert(!emitFullGCinfo); // Simple stk not used for emitFullGCInfo
7016
7017         /* We don't need to report this to the GC info, but we do need
7018            to kill mark the ptrs on the stack as non-GC */
7019
7020         assert(emitCurStackLvl / sizeof(int) >= count);
7021
7022         for (unsigned lvl = 0; lvl < count; lvl++)
7023         {
7024             u1.emitSimpleStkMask &= ~(1 << lvl);
7025             u1.emitSimpleByrefStkMask &= ~(1 << lvl);
7026         }
7027     }
7028     else
7029     {
7030         BYTE*    argTrackTop = u2.emitArgTrackTop;
7031         S_UINT16 gcCnt(0);
7032
7033         for (unsigned i = 0; i < count; i++)
7034         {
7035             assert(argTrackTop > u2.emitArgTrackTab);
7036
7037             --argTrackTop;
7038
7039             GCtype gcType = (GCtype)(*argTrackTop);
7040             assert(IsValidGCtype(gcType));
7041
7042             if (needsGC(gcType))
7043             {
7044                 // printf("Killed %s at lvl %u\n", GCtypeStr(gcType), argTrackTop - emitArgTrackTab);
7045
7046                 *argTrackTop = GCT_NONE;
7047                 gcCnt += 1;
7048             }
7049         }
7050
7051         noway_assert(!gcCnt.IsOverflow());
7052
7053         /* We're about to kill the corresponding (pointer) arg records */
7054
7055         if (!emitFullArgInfo)
7056         {
7057             u2.emitGcArgTrackCnt -= gcCnt.Value();
7058         }
7059
7060         if (!emitFullGCinfo)
7061         {
7062             return;
7063         }
7064
7065         /* Right after the call, the arguments are still sitting on the
7066            stack, but they are effectively dead. For fully-interruptible
7067            methods, we need to report that */
7068
7069         if (emitFullGCinfo && gcCnt.Value())
7070         {
7071             /* Allocate a new ptr arg entry and fill it in */
7072
7073             regPtrDsc* regPtrNext = codeGen->gcInfo.gcRegPtrAllocDsc();
7074             regPtrNext->rpdGCtype = GCT_GCREF; // Kills need a non-0 value (??)
7075
7076             regPtrNext->rpdOffs = emitCurCodeOffs(addr);
7077
7078             regPtrNext->rpdArg     = TRUE;
7079             regPtrNext->rpdArgType = (unsigned short)GCInfo::rpdARG_KILL;
7080             regPtrNext->rpdPtrArg  = gcCnt.Value();
7081
7082 #ifdef DEBUG
7083             if (EMIT_GC_VERBOSE)
7084             {
7085                 printf("[%08X] ptr arg kill %u\n", dspPtr(regPtrNext), count);
7086             }
7087 #endif
7088         }
7089
7090         /* Now that ptr args have been marked as non-ptrs, we need to record
7091            the call itself as one that has no arguments. */
7092
7093         emitStackPopLargeStk(addr, true, callInstrSize, 0);
7094     }
7095 }
7096
7097 /*****************************************************************************
7098  *  A helper for recording a relocation with the EE.
7099  */
7100 void emitter::emitRecordRelocation(void* location,            /* IN */
7101                                    void* target,              /* IN */
7102                                    WORD  fRelocType,          /* IN */
7103                                    WORD  slotNum /* = 0 */,   /* IN */
7104                                    INT32 addlDelta /* = 0 */) /* IN */
7105 {
7106     // If we're an unmatched altjit, don't tell the VM anything. We still record the relocation for
7107     // late disassembly; maybe we'll need it?
7108     if (emitComp->info.compMatchedVM)
7109     {
7110         emitCmpHandle->recordRelocation(location, target, fRelocType, slotNum, addlDelta);
7111     }
7112 #if defined(LATE_DISASM)
7113     codeGen->getDisAssembler().disRecordRelocation((size_t)location, (size_t)target);
7114 #endif // defined(LATE_DISASM)
7115 }
7116
7117 #ifdef _TARGET_ARM_
7118 /*****************************************************************************
7119  *  A helper for handling a Thumb-Mov32 of position-independent (PC-relative) value
7120  *
7121  *  This routine either records relocation for the location with the EE,
7122  *  or creates a virtual relocation entry to perform offset fixup during
7123  *  compilation without recording it with EE - depending on which of
7124  *  absolute/relocative relocations mode are used for code section.
7125  */
7126 void emitter::emitHandlePCRelativeMov32(void* location, /* IN */
7127                                         void* target)   /* IN */
7128 {
7129     if (emitComp->opts.jitFlags->IsSet(JitFlags::JIT_FLAG_RELATIVE_CODE_RELOCS))
7130     {
7131         emitRecordRelocation(location, target, IMAGE_REL_BASED_REL_THUMB_MOV32_PCREL);
7132     }
7133     else
7134     {
7135         emitRecordRelocation(location, target, IMAGE_REL_BASED_THUMB_MOV32);
7136     }
7137 }
7138 #endif // _TARGET_ARM_
7139
7140 /*****************************************************************************
7141  *  A helper for recording a call site with the EE.
7142  */
7143 void emitter::emitRecordCallSite(ULONG                 instrOffset,  /* IN */
7144                                  CORINFO_SIG_INFO*     callSig,      /* IN */
7145                                  CORINFO_METHOD_HANDLE methodHandle) /* IN */
7146 {
7147 #if defined(DEBUG)
7148     // Since CORINFO_SIG_INFO is a heavyweight structure, in most cases we can
7149     // lazily obtain it here using the given method handle (we only save the sig
7150     // info when we explicitly need it, i.e. for CALLI calls, vararg calls, and
7151     // tail calls).
7152     if (callSig == nullptr)
7153     {
7154         assert(methodHandle != nullptr);
7155
7156         if (Compiler::eeGetHelperNum(methodHandle) == CORINFO_HELP_UNDEF)
7157         {
7158             if (emitScratchSigInfo == nullptr)
7159             {
7160                 emitScratchSigInfo = new (emitComp, CMK_CorSig) CORINFO_SIG_INFO;
7161             }
7162
7163             emitComp->eeGetMethodSig(methodHandle, emitScratchSigInfo);
7164             callSig = emitScratchSigInfo;
7165         }
7166     }
7167
7168     emitCmpHandle->recordCallSite(instrOffset, callSig, methodHandle);
7169 #endif // defined(DEBUG)
7170 }
7171
7172 /*****************************************************************************/
7173 #endif // EMIT_TRACK_STACK_DEPTH
7174 /*****************************************************************************/
7175 /*****************************************************************************/
7176
7177 #ifdef DEBUG
7178
7179 /*****************************************************************************
7180  *  Given a code offset, return a string representing a label for that offset.
7181  *  If the code offset is just after the end of the code of the function, the
7182  *  label will be "END". If the code offset doesn't correspond to any known
7183  *  offset, the label will be "UNKNOWN". The strings are returned from static
7184  *  buffers. This function rotates amongst four such static buffers (there are
7185  *  cases where this function is called four times to provide data for a single
7186  *  printf()).
7187  */
7188
7189 const char* emitter::emitOffsetToLabel(unsigned offs)
7190 {
7191     const size_t    TEMP_BUFFER_LEN = 40;
7192     static unsigned curBuf          = 0;
7193     static char     buf[4][TEMP_BUFFER_LEN];
7194     char*           retbuf;
7195
7196     insGroup*      ig;
7197     UNATIVE_OFFSET of;
7198     UNATIVE_OFFSET nextof = 0;
7199
7200     for (ig = emitIGlist; ig != nullptr; ig = ig->igNext)
7201     {
7202         assert(nextof == ig->igOffs);
7203
7204         if (ig->igOffs == offs)
7205         {
7206             // Found it!
7207             sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "G_M%03u_IG%02u", Compiler::s_compMethodsCount, ig->igNum);
7208             retbuf = buf[curBuf];
7209             curBuf = (curBuf + 1) % 4;
7210             return retbuf;
7211         }
7212         else if (ig->igOffs > offs)
7213         {
7214             // We went past the requested offset but didn't find it.
7215             sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "UNKNOWN");
7216             retbuf = buf[curBuf];
7217             curBuf = (curBuf + 1) % 4;
7218             return retbuf;
7219         }
7220
7221         nextof = ig->igOffs + ig->igSize;
7222     }
7223
7224     if (nextof == offs)
7225     {
7226         // It's a pseudo-label to the end.
7227         sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "END");
7228         retbuf = buf[curBuf];
7229         curBuf = (curBuf + 1) % 4;
7230         return retbuf;
7231     }
7232     else
7233     {
7234         sprintf_s(buf[curBuf], TEMP_BUFFER_LEN, "UNKNOWN");
7235         retbuf = buf[curBuf];
7236         curBuf = (curBuf + 1) % 4;
7237         return retbuf;
7238     }
7239 }
7240
7241 #endif // DEBUG