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