forked from dotnet/coreclr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
codegenarm.cpp
2198 lines (1846 loc) · 73.5 KB
/
codegenarm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX ARM Code Generator XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator
#ifdef _TARGET_ARM_
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "emit.h"
#ifndef JIT32_GCENCODER
#include "gcinfoencoder.h"
#endif
// Get the register assigned to the given node
regNumber CodeGenInterface::genGetAssignedReg(GenTreePtr tree)
{
return tree->gtRegNum;
}
//------------------------------------------------------------------------
// genSpillVar: Spill a local variable
//
// Arguments:
// tree - the lclVar node for the variable being spilled
//
// Return Value:
// None.
//
// Assumptions:
// The lclVar must be a register candidate (lvRegCandidate)
void CodeGen::genSpillVar(GenTreePtr tree)
{
regMaskTP regMask;
unsigned varNum = tree->gtLclVarCommon.gtLclNum;
LclVarDsc * varDsc = &(compiler->lvaTable[varNum]);
// We don't actually need to spill if it is already living in memory
bool needsSpill = ((tree->gtFlags & GTF_VAR_DEF) == 0 && varDsc->lvIsInReg());
if (needsSpill)
{
bool restoreRegVar = false;
if (tree->gtOper == GT_REG_VAR)
{
tree->SetOper(GT_LCL_VAR);
restoreRegVar = true;
}
// mask off the flag to generate the right spill code, then bring it back
tree->gtFlags &= ~GTF_REG_VAL;
instruction storeIns = ins_Store(tree->TypeGet());
if (varTypeIsMultiReg(tree))
{
assert(varDsc->lvRegNum == genRegPairLo(tree->gtRegPair));
assert(varDsc->lvOtherReg == genRegPairHi(tree->gtRegPair));
regNumber regLo = genRegPairLo(tree->gtRegPair);
regNumber regHi = genRegPairHi(tree->gtRegPair);
inst_TT_RV(storeIns, tree, regLo);
inst_TT_RV(storeIns, tree, regHi, 4);
}
else
{
assert(varDsc->lvRegNum == tree->gtRegNum);
inst_TT_RV(storeIns, tree, tree->gtRegNum);
}
tree->gtFlags |= GTF_REG_VAL;
if (restoreRegVar)
{
tree->SetOper(GT_REG_VAR);
}
genUpdateRegLife(varDsc, /*isBorn*/ false, /*isDying*/ true DEBUGARG(tree));
gcInfo.gcMarkRegSetNpt(varDsc->lvRegMask());
if (VarSetOps::IsMember(compiler, gcInfo.gcTrkStkPtrLcls, varDsc->lvVarIndex))
{
#ifdef DEBUG
if (!VarSetOps::IsMember(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex))
{
JITDUMP("\t\t\t\t\t\t\tVar V%02u becoming live\n", varNum);
}
else
{
JITDUMP("\t\t\t\t\t\t\tVar V%02u continuing live\n", varNum);
}
#endif
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varDsc->lvVarIndex);
}
}
tree->gtFlags &= ~GTF_SPILL;
varDsc->lvRegNum = REG_STK;
if (varTypeIsMultiReg(tree))
{
varDsc->lvOtherReg = REG_STK;
}
}
// inline
void CodeGenInterface::genUpdateVarReg(LclVarDsc * varDsc, GenTreePtr tree)
{
assert(tree->OperIsScalarLocal() || (tree->gtOper == GT_COPY));
varDsc->lvRegNum = tree->gtRegNum;
}
/*****************************************************************************
*
* Generate code that will set the given register to the integer constant.
*/
void CodeGen::genSetRegToIcon(regNumber reg,
ssize_t val,
var_types type,
insFlags flags)
{
// Reg cannot be a FP reg
assert(!genIsValidFloatReg(reg));
// The only TYP_REF constant that can come this path is a managed 'null' since it is not
// relocatable. Other ref type constants (e.g. string objects) go through a different
// code path.
noway_assert(type != TYP_REF || val == 0);
if (val == 0)
{
instGen_Set_Reg_To_Zero(emitActualTypeSize(type), reg, flags);
}
else
{
// TODO-CQ: needs all the optimized cases
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(type), reg, val);
}
}
/*****************************************************************************
*
* Generate code to check that the GS cookie wasn't thrashed by a buffer
* overrun. If pushReg is true, preserve all registers around code sequence.
* Otherwise, ECX maybe modified.
*/
void CodeGen::genEmitGSCookieCheck(bool pushReg)
{
NYI("ARM genEmitGSCookieCheck is not yet implemented for protojit");
}
/*****************************************************************************
*
* Generate code for all the basic blocks in the function.
*/
void CodeGen::genCodeForBBlist()
{
unsigned varNum;
LclVarDsc * varDsc;
unsigned savedStkLvl;
#ifdef DEBUG
genInterruptibleUsed = true;
unsigned stmtNum = 0;
unsigned totalCostEx = 0;
unsigned totalCostSz = 0;
// You have to be careful if you create basic blocks from now on
compiler->fgSafeBasicBlockCreation = false;
// This stress mode is not comptible with fully interruptible GC
if (genInterruptible && compiler->opts.compStackCheckOnCall)
{
compiler->opts.compStackCheckOnCall = false;
}
// This stress mode is not comptible with fully interruptible GC
if (genInterruptible && compiler->opts.compStackCheckOnRet)
{
compiler->opts.compStackCheckOnRet = false;
}
#endif
// Prepare the blocks for exception handling codegen: mark the blocks that needs labels.
genPrepForEHCodegen();
assert(!compiler->fgFirstBBScratch || compiler->fgFirstBB == compiler->fgFirstBBScratch); // compiler->fgFirstBBScratch has to be first.
/* Initialize the spill tracking logic */
regSet.rsSpillBeg();
/* Initialize the line# tracking logic */
#ifdef DEBUGGING_SUPPORT
if (compiler->opts.compScopeInfo)
{
siInit();
}
#endif
if (compiler->opts.compDbgEnC)
{
noway_assert(isFramePointerUsed());
regSet.rsSetRegsModified(RBM_INT_CALLEE_SAVED & ~RBM_FPBASE);
}
#if INLINE_NDIRECT
/* If we have any pinvoke calls, we might potentially trash everything */
if (compiler->info.compCallUnmanaged)
{
noway_assert(isFramePointerUsed()); // Setup of Pinvoke frame currently requires an EBP style frame
regSet.rsSetRegsModified(RBM_INT_CALLEE_SAVED & ~RBM_FPBASE);
}
#endif // INLINE_NDIRECT
genPendingCallLabel = nullptr;
/* Initialize the pointer tracking code */
gcInfo.gcRegPtrSetInit();
gcInfo.gcVarPtrSetInit();
/* If any arguments live in registers, mark those regs as such */
for (varNum = 0, varDsc = compiler->lvaTable;
varNum < compiler->lvaCount;
varNum++ , varDsc++)
{
/* Is this variable a parameter assigned to a register? */
if (!varDsc->lvIsParam || !varDsc->lvRegister)
continue;
/* Is the argument live on entry to the method? */
if (!VarSetOps::IsMember(compiler, compiler->fgFirstBB->bbLiveIn, varDsc->lvVarIndex))
continue;
/* Is this a floating-point argument? */
if (varDsc->IsFloatRegType())
continue;
noway_assert(!varTypeIsFloating(varDsc->TypeGet()));
/* Mark the register as holding the variable */
regTracker.rsTrackRegLclVar(varDsc->lvRegNum, varNum);
}
unsigned finallyNesting = 0;
// Make sure a set is allocated for compiler->compCurLife (in the long case), so we can set it to empty without
// allocation at the start of each basic block.
VarSetOps::AssignNoCopy(compiler, compiler->compCurLife, VarSetOps::MakeEmpty(compiler));
/*-------------------------------------------------------------------------
*
* Walk the basic blocks and generate code for each one
*
*/
BasicBlock * block;
BasicBlock * lblk; /* previous block */
for (lblk = NULL, block = compiler->fgFirstBB;
block != NULL;
lblk = block, block = block->bbNext)
{
#ifdef DEBUG
if (compiler->verbose)
{
printf("\n=============== Generating ");
block->dspBlockHeader(compiler, true, true);
compiler->fgDispBBLiveness(block);
}
#endif // DEBUG
/* Figure out which registers hold variables on entry to this block */
regSet.rsMaskVars = RBM_NONE;
gcInfo.gcRegGCrefSetCur = RBM_NONE;
gcInfo.gcRegByrefSetCur = RBM_NONE;
compiler->m_pLinearScan->recordVarLocationsAtStartOfBB(block);
genUpdateLife(block->bbLiveIn);
// Even if liveness didn't change, we need to update the registers containing GC references.
// genUpdateLife will update the registers live due to liveness changes. But what about registers that didn't change?
// We cleared them out above. Maybe we should just not clear them out, but update the ones that change here.
// That would require handling the changes in recordVarLocationsAtStartOfBB().
regMaskTP newLiveRegSet = RBM_NONE;
regMaskTP newRegGCrefSet = RBM_NONE;
regMaskTP newRegByrefSet = RBM_NONE;
VARSET_ITER_INIT(compiler, iter, block->bbLiveIn, varIndex);
while (iter.NextElem(compiler, &varIndex))
{
unsigned varNum = compiler->lvaTrackedToVarNum[varIndex];
LclVarDsc* varDsc = &(compiler->lvaTable[varNum]);
if (varDsc->lvIsInReg())
{
newLiveRegSet |= varDsc->lvRegMask();
if (varDsc->lvType == TYP_REF)
{
newRegGCrefSet |= varDsc->lvRegMask();
}
else if (varDsc->lvType == TYP_BYREF)
{
newRegByrefSet |= varDsc->lvRegMask();
}
}
else if (varDsc->lvType == TYP_REF || varDsc->lvType == TYP_BYREF)
{
VarSetOps::AddElemD(compiler, gcInfo.gcVarPtrSetCur, varIndex);
}
}
#ifdef DEBUG
if (compiler->verbose)
{
printf("\t\t\t\t\t\t\tLive regs: ");
if (regSet.rsMaskVars == newLiveRegSet)
{
printf("(unchanged) ");
}
else
{
printRegMaskInt(regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(regSet.rsMaskVars);
printf(" => ");
}
printRegMaskInt(newLiveRegSet);
compiler->getEmitter()->emitDispRegSet(newLiveRegSet);
printf("\n");
}
#endif // DEBUG
regSet.rsMaskVars = newLiveRegSet;
gcInfo.gcMarkRegSetGCref(newRegGCrefSet DEBUG_ARG(true));
gcInfo.gcMarkRegSetByref(newRegByrefSet DEBUG_ARG(true));
/* Blocks with handlerGetsXcptnObj()==true use GT_CATCH_ARG to
represent the exception object (TYP_REF).
We mark REG_EXCEPTION_OBJECT as holding a GC object on entry
to the block, it will be the first thing evaluated
(thanks to GTF_ORDER_SIDEEFF).
*/
if (handlerGetsXcptnObj(block->bbCatchTyp))
{
#if JIT_FEATURE_SSA_SKIP_DEFS
GenTreePtr firstStmt = block->FirstNonPhiDef();
#else
GenTreePtr firstStmt = block->bbTreeList;
#endif
if (firstStmt != NULL)
{
GenTreePtr firstTree = firstStmt->gtStmt.gtStmtExpr;
if (compiler->gtHasCatchArg(firstTree))
{
gcInfo.gcMarkRegSetGCref(RBM_EXCEPTION_OBJECT);
}
}
}
/* Start a new code output block */
#if FEATURE_EH_FUNCLETS
#if defined(_TARGET_ARM_)
// If this block is the target of a finally return, we need to add a preceding NOP, in the same EH region,
// so the unwinder doesn't get confused by our "movw lr, xxx; movt lr, xxx; b Lyyy" calling convention that
// calls the funclet during non-exceptional control flow.
if (block->bbFlags & BBF_FINALLY_TARGET)
{
assert(block->bbFlags & BBF_JMP_TARGET);
// Create a label that we'll use for computing the start of an EH region, if this block is
// at the beginning of such a region. If we used the existing bbEmitCookie as is for
// determining the EH regions, then this NOP would end up outside of the region, if this
// block starts an EH region. If we pointed the existing bbEmitCookie here, then the NOP
// would be executed, which we would prefer not to do.
#ifdef DEBUG
if (compiler->verbose)
{
printf("\nEmitting finally target NOP predecessor for BB%02u\n", block->bbNum);
}
#endif
block->bbUnwindNopEmitCookie = getEmitter()->emitAddLabel(gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur);
instGen(INS_nop);
}
#endif // defined(_TARGET_ARM_)
genUpdateCurrentFunclet(block);
#endif // FEATURE_EH_FUNCLETS
#ifdef _TARGET_XARCH_
if (genAlignLoops && block->bbFlags & BBF_LOOP_HEAD)
{
getEmitter()->emitLoopAlign();
}
#endif
#ifdef DEBUG
if (compiler->opts.dspCode)
printf("\n L_M%03u_BB%02u:\n", Compiler::s_compMethodsCount, block->bbNum);
#endif
block->bbEmitCookie = NULL;
if (block->bbFlags & (BBF_JMP_TARGET|BBF_HAS_LABEL))
{
/* Mark a label and update the current set of live GC refs */
block->bbEmitCookie = getEmitter()->emitAddLabel(
gcInfo.gcVarPtrSetCur,
gcInfo.gcRegGCrefSetCur,
gcInfo.gcRegByrefSetCur,
/*isFinally*/block->bbFlags & BBF_FINALLY_TARGET);
}
if (block == compiler->fgFirstColdBlock)
{
#ifdef DEBUG
if (compiler->verbose)
{
printf("\nThis is the start of the cold region of the method\n");
}
#endif
// We should never have a block that falls through into the Cold section
noway_assert(!lblk->bbFallsThrough());
// We require the block that starts the Cold section to have a label
noway_assert(block->bbEmitCookie);
getEmitter()->emitSetFirstColdIGCookie(block->bbEmitCookie);
}
/* Both stacks are always empty on entry to a basic block */
genStackLevel = 0;
#if !FEATURE_FIXED_OUT_ARGS
/* Check for inserted throw blocks and adjust genStackLevel */
if (!isFramePointerUsed() && compiler->fgIsThrowHlpBlk(block))
{
noway_assert(block->bbFlags & BBF_JMP_TARGET);
genStackLevel = compiler->fgThrowHlpBlkStkLevel(block) * sizeof(int);
if (genStackLevel)
{
NYI("Need emitMarkStackLvl()");
}
}
#endif // !FEATURE_FIXED_OUT_ARGS
savedStkLvl = genStackLevel;
/* Tell everyone which basic block we're working on */
compiler->compCurBB = block;
#ifdef DEBUGGING_SUPPORT
siBeginBlock(block);
// BBF_INTERNAL blocks don't correspond to any single IL instruction.
if (compiler->opts.compDbgInfo && (block->bbFlags & BBF_INTERNAL) && block != compiler->fgFirstBB)
genIPmappingAdd((IL_OFFSETX) ICorDebugInfo::NO_MAPPING, true);
bool firstMapping = true;
#endif // DEBUGGING_SUPPORT
/*---------------------------------------------------------------------
*
* Generate code for each statement-tree in the block
*
*/
#if FEATURE_EH_FUNCLETS
if (block->bbFlags & BBF_FUNCLET_BEG)
{
genReserveFuncletProlog(block);
}
#endif // FEATURE_EH_FUNCLETS
#if JIT_FEATURE_SSA_SKIP_DEFS
for (GenTreePtr stmt = block->FirstNonPhiDef(); stmt; stmt = stmt->gtNext)
#else
for (GenTreePtr stmt = block->bbTreeList; stmt; stmt = stmt->gtNext)
#endif
{
noway_assert(stmt->gtOper == GT_STMT);
if (stmt->AsStmt()->gtStmtIsEmbedded())
continue;
/* Get hold of the statement tree */
GenTreePtr tree = stmt->gtStmt.gtStmtExpr;
#if defined(DEBUGGING_SUPPORT)
/* Do we have a new IL-offset ? */
if (stmt->gtStmt.gtStmtILoffsx != BAD_IL_OFFSET)
{
/* Create and append a new IP-mapping entry */
genIPmappingAdd(stmt->gtStmt.gtStmt.gtStmtILoffsx, firstMapping);
firstMapping = false;
}
#endif // DEBUGGING_SUPPORT
#ifdef DEBUG
noway_assert(stmt->gtStmt.gtStmtLastILoffs <= compiler->info.compILCodeSize ||
stmt->gtStmt.gtStmtLastILoffs == BAD_IL_OFFSET);
if (compiler->opts.dspCode && compiler->opts.dspInstrs &&
stmt->gtStmt.gtStmtLastILoffs != BAD_IL_OFFSET)
{
while (genCurDispOffset <= stmt->gtStmt.gtStmtLastILoffs)
{
genCurDispOffset +=
dumpSingleInstr(compiler->info.compCode, genCurDispOffset, "> ");
}
}
stmtNum++;
if (compiler->verbose)
{
printf("\nGenerating BB%02u, stmt %u\t\t", block->bbNum, stmtNum);
printf("Holding variables: ");
dspRegMask(regSet.rsMaskVars); printf("\n\n");
compiler->gtDispTree(compiler->opts.compDbgInfo ? stmt : tree);
printf("\n");
}
totalCostEx += (stmt->gtCostEx * block->getBBWeight(compiler));
totalCostSz += stmt->gtCostSz;
#endif // DEBUG
// Traverse the tree in linear order, generating code for each node in the
// tree as we encounter it
// If we have embedded statements, we need to keep track of the next top-level
// node in order, because if it produces a register, we need to consume it
GenTreeStmt* curPossiblyEmbeddedStmt = stmt->gtStmt.gtStmtNextIfEmbedded();
if (curPossiblyEmbeddedStmt == nullptr)
curPossiblyEmbeddedStmt = stmt->AsStmt();
compiler->compCurLifeTree = NULL;
compiler->compCurStmt = stmt;
for (GenTreePtr treeNode = stmt->gtStmt.gtStmtList;
treeNode != NULL;
treeNode = treeNode->gtNext)
{
genCodeForTreeNode(treeNode);
if (treeNode == curPossiblyEmbeddedStmt->gtStmtExpr)
{
// It is possible that the last top-level node may generate a result
// that is not used (but may still require a register, e.g. an indir
// that is evaluated only for the side-effect of a null check).
// In that case, we must "consume" the register now.
if (treeNode->gtHasReg())
{
genConsumeReg(treeNode);
}
if (curPossiblyEmbeddedStmt != stmt)
{
curPossiblyEmbeddedStmt = curPossiblyEmbeddedStmt->gtStmt.gtStmtNextIfEmbedded();
if (curPossiblyEmbeddedStmt == nullptr)
curPossiblyEmbeddedStmt = stmt->AsStmt();
}
}
}
regSet.rsSpillChk();
#ifdef DEBUG
/* Make sure we didn't bungle pointer register tracking */
regMaskTP ptrRegs = (gcInfo.gcRegGCrefSetCur|gcInfo.gcRegByrefSetCur);
regMaskTP nonVarPtrRegs = ptrRegs & ~regSet.rsMaskVars;
// If return is a GC-type, clear it. Note that if a common
// epilog is generated (genReturnBB) it has a void return
// even though we might return a ref. We can't use the compRetType
// as the determiner because something we are tracking as a byref
// might be used as a return value of a int function (which is legal)
if (tree->gtOper == GT_RETURN &&
(varTypeIsGC(compiler->info.compRetType) ||
(tree->gtOp.gtOp1 != 0 && varTypeIsGC(tree->gtOp.gtOp1->TypeGet()))))
{
nonVarPtrRegs &= ~RBM_INTRET;
}
// When profiling, the first statement in a catch block will be the
// harmless "inc" instruction (does not interfere with the exception
// object).
if ((compiler->opts.eeFlags & CORJIT_FLG_BBINSTR) &&
(stmt == block->bbTreeList) &&
handlerGetsXcptnObj(block->bbCatchTyp))
{
nonVarPtrRegs &= ~RBM_EXCEPTION_OBJECT;
}
if (nonVarPtrRegs)
{
printf("Regset after tree=");
Compiler::printTreeID(tree);
printf(" BB%02u gcr=", block->bbNum);
printRegMaskInt(gcInfo.gcRegGCrefSetCur & ~regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(gcInfo.gcRegGCrefSetCur & ~regSet.rsMaskVars);
printf(", byr=");
printRegMaskInt(gcInfo.gcRegByrefSetCur & ~regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(gcInfo.gcRegByrefSetCur & ~regSet.rsMaskVars);
printf(", regVars=");
printRegMaskInt(regSet.rsMaskVars);
compiler->getEmitter()->emitDispRegSet(regSet.rsMaskVars);
printf("\n");
}
noway_assert(nonVarPtrRegs == 0);
for (GenTree * node = stmt->gtStmt.gtStmtList; node; node=node->gtNext)
{
assert(!(node->gtFlags & GTF_SPILL));
}
#endif // DEBUG
noway_assert(stmt->gtOper == GT_STMT);
#ifdef DEBUGGING_SUPPORT
genEnsureCodeEmitted(stmt->gtStmt.gtStmtILoffsx);
#endif
} //-------- END-FOR each statement-tree of the current block ---------
#ifdef DEBUGGING_SUPPORT
if (compiler->opts.compScopeInfo && (compiler->info.compVarScopesCount > 0))
{
siEndBlock(block);
/* Is this the last block, and are there any open scopes left ? */
bool isLastBlockProcessed = (block->bbNext == NULL);
if (block->isBBCallAlwaysPair())
{
isLastBlockProcessed = (block->bbNext->bbNext == NULL);
}
if (isLastBlockProcessed && siOpenScopeList.scNext)
{
/* This assert no longer holds, because we may insert a throw
block to demarcate the end of a try or finally region when they
are at the end of the method. It would be nice if we could fix
our code so that this throw block will no longer be necessary. */
//noway_assert(block->bbCodeOffsEnd != compiler->info.compILCodeSize);
siCloseAllOpenScopes();
}
}
#endif // DEBUGGING_SUPPORT
genStackLevel -= savedStkLvl;
#ifdef DEBUG
// compCurLife should be equal to the liveOut set, except that we don't keep
// it up to date for vars that are not register candidates
// (it would be nice to have a xor set function)
VARSET_TP VARSET_INIT_NOCOPY(extraLiveVars, VarSetOps::Diff(compiler, block->bbLiveOut, compiler->compCurLife));
VarSetOps::UnionD(compiler, extraLiveVars, VarSetOps::Diff(compiler, compiler->compCurLife, block->bbLiveOut));
VARSET_ITER_INIT(compiler, extraLiveVarIter, extraLiveVars, extraLiveVarIndex);
while (extraLiveVarIter.NextElem(compiler, &extraLiveVarIndex))
{
unsigned varNum = compiler->lvaTrackedToVarNum[extraLiveVarIndex];
LclVarDsc * varDsc = compiler->lvaTable + varNum;
assert(!varDsc->lvIsRegCandidate());
}
#endif
/* Both stacks should always be empty on exit from a basic block */
noway_assert(genStackLevel == 0);
#ifdef _TARGET_AMD64_
// On AMD64, we need to generate a NOP after a call that is the last instruction of the block, in several
// situations, to support proper exception handling semantics. This is mostly to ensure that when the stack
// walker computes an instruction pointer for a frame, that instruction pointer is in the correct EH region.
// The document "X64 and ARM ABIs.docx" has more details. The situations:
// 1. If the call instruction is in a different EH region as the instruction that follows it.
// 2. If the call immediately precedes an OS epilog. (Note that what the JIT or VM consider an epilog might
// be slightly different from what the OS considers an epilog, and it is the OS-reported epilog that matters here.)
// We handle case #1 here, and case #2 in the emitter.
if (getEmitter()->emitIsLastInsCall())
{
// Ok, the last instruction generated is a call instruction. Do any of the other conditions hold?
// Note: we may be generating a few too many NOPs for the case of call preceding an epilog. Technically,
// if the next block is a BBJ_RETURN, an epilog will be generated, but there may be some instructions
// generated before the OS epilog starts, such as a GS cookie check.
if ((block->bbNext == nullptr) ||
!BasicBlock::sameEHRegion(block, block->bbNext))
{
// We only need the NOP if we're not going to generate any more code as part of the block end.
switch (block->bbJumpKind)
{
case BBJ_ALWAYS:
case BBJ_THROW:
case BBJ_CALLFINALLY:
case BBJ_EHCATCHRET:
// We're going to generate more code below anyway, so no need for the NOP.
case BBJ_RETURN:
case BBJ_EHFINALLYRET:
case BBJ_EHFILTERRET:
// These are the "epilog follows" case, handled in the emitter.
break;
case BBJ_NONE:
if (block->bbNext == nullptr)
{
// Call immediately before the end of the code; we should never get here .
instGen(INS_BREAKPOINT); // This should never get executed
}
else
{
// We need the NOP
instGen(INS_nop);
}
break;
case BBJ_COND:
case BBJ_SWITCH:
// These can't have a call as the last instruction!
default:
noway_assert(!"Unexpected bbJumpKind");
break;
}
}
}
#endif _TARGET_AMD64_
/* Do we need to generate a jump or return? */
switch (block->bbJumpKind)
{
case BBJ_ALWAYS:
inst_JMP(EJ_jmp, block->bbJumpDest);
break;
case BBJ_RETURN:
genExitCode(block);
break;
case BBJ_THROW:
// If we have a throw at the end of a function or funclet, we need to emit another instruction
// afterwards to help the OS unwinder determine the correct context during unwind.
// We insert an unexecuted breakpoint instruction in several situations
// following a throw instruction:
// 1. If the throw is the last instruction of the function or funclet. This helps
// the OS unwinder determine the correct context during an unwind from the
// thrown exception.
// 2. If this is this is the last block of the hot section.
// 3. If the subsequent block is a special throw block.
// 4. On AMD64, if the next block is in a different EH region.
if ((block->bbNext == NULL)
#if FEATURE_EH_FUNCLETS
|| (block->bbNext->bbFlags & BBF_FUNCLET_BEG)
#endif // FEATURE_EH_FUNCLETS
#ifdef _TARGET_AMD64_
|| !BasicBlock::sameEHRegion(block, block->bbNext)
#endif // _TARGET_AMD64_
|| (!isFramePointerUsed() && compiler->fgIsThrowHlpBlk(block->bbNext))
|| block->bbNext == compiler->fgFirstColdBlock
)
{
instGen(INS_BREAKPOINT); // This should never get executed
}
break;
case BBJ_CALLFINALLY:
// Now set REG_LR to the address of where the finally funclet should
// return to directly.
BasicBlock * bbFinallyRet; bbFinallyRet = NULL;
// We don't have retless calls, since we use the BBJ_ALWAYS to point at a NOP pad where
// we would have otherwise created retless calls.
assert(block->isBBCallAlwaysPair());
assert(block->bbNext != NULL);
assert(block->bbNext->bbJumpKind == BBJ_ALWAYS);
assert(block->bbNext->bbJumpDest != NULL);
assert(block->bbNext->bbJumpDest->bbFlags & BBF_FINALLY_TARGET);
bbFinallyRet = block->bbNext->bbJumpDest;
bbFinallyRet->bbFlags |= BBF_JMP_TARGET;
#if 0
// TODO-ARM-CQ:
// We don't know the address of finally funclet yet. But adr requires the offset
// to finally funclet from current IP is within 4095 bytes. So this code is disabled
// for now.
getEmitter()->emitIns_J_R (INS_adr,
EA_4BYTE,
bbFinallyRet,
REG_LR);
#else // !0
// Load the address where the finally funclet should return into LR.
// The funclet prolog/epilog will do "push {lr}" / "pop {pc}" to do
// the return.
getEmitter()->emitIns_R_L (INS_movw,
EA_4BYTE_DSP_RELOC,
bbFinallyRet,
REG_LR);
getEmitter()->emitIns_R_L (INS_movt,
EA_4BYTE_DSP_RELOC,
bbFinallyRet,
REG_LR);
#endif // !0
// Jump to the finally BB
inst_JMP(EJ_jmp, block->bbJumpDest);
// The BBJ_ALWAYS is used because the BBJ_CALLFINALLY can't point to the
// jump target using bbJumpDest - that is already used to point
// to the finally block. So just skip past the BBJ_ALWAYS unless the
// block is RETLESS.
if ( !(block->bbFlags & BBF_RETLESS_CALL) )
{
assert(block->isBBCallAlwaysPair());
lblk = block;
block = block->bbNext;
}
break;
#ifdef _TARGET_ARM_
case BBJ_EHCATCHRET:
// set r0 to the address the VM should return to after the catch
getEmitter()->emitIns_R_L (INS_movw,
EA_4BYTE_DSP_RELOC,
block->bbJumpDest,
REG_R0);
getEmitter()->emitIns_R_L (INS_movt,
EA_4BYTE_DSP_RELOC,
block->bbJumpDest,
REG_R0);
__fallthrough;
case BBJ_EHFINALLYRET:
case BBJ_EHFILTERRET:
genReserveFuncletEpilog(block);
break;
#elif defined(_TARGET_AMD64_)
case BBJ_EHCATCHRET:
// Set EAX to the address the VM should return to after the catch.
// Generate a RIP-relative
// lea reg, [rip + disp32] ; the RIP is implicit
// which will be position-indepenent.
// TODO-ARM-Bug?: For ngen, we need to generate a reloc for the displacement (maybe EA_PTR_DSP_RELOC).
getEmitter()->emitIns_R_L(INS_lea, EA_PTRSIZE, block->bbJumpDest, REG_INTRET);
__fallthrough;
case BBJ_EHFINALLYRET:
case BBJ_EHFILTERRET:
genReserveFuncletEpilog(block);
break;
#endif // _TARGET_AMD64_
case BBJ_NONE:
case BBJ_COND:
case BBJ_SWITCH:
break;
default:
noway_assert(!"Unexpected bbJumpKind");
break;
}
#ifdef DEBUG
compiler->compCurBB = 0;
#endif
} //------------------ END-FOR each block of the method -------------------
/* Nothing is live at this point */
genUpdateLife(VarSetOps::MakeEmpty(compiler));
/* Finalize the spill tracking logic */
regSet.rsSpillEnd();
/* Finalize the temp tracking logic */
compiler->tmpEnd();
#ifdef DEBUG
if (compiler->verbose)
{
printf("\n# ");
printf("totalCostEx = %6d, totalCostSz = %5d ",
totalCostEx, totalCostSz);
printf("%s\n", compiler->info.compFullName);
}
#endif
}
// return the child that has the same reg as the dst (if any)
// other child returned (out param) in 'other'
GenTree *
sameRegAsDst(GenTree *tree, GenTree *&other /*out*/)
{
if (tree->gtRegNum == REG_NA)
{
other = nullptr;
return NULL;
}
GenTreePtr op1 = tree->gtOp.gtOp1->gtEffectiveVal();
GenTreePtr op2 = tree->gtOp.gtOp2->gtEffectiveVal();
if (op1->gtRegNum == tree->gtRegNum)
{
other = op2;
return op1;
}
if (op2->gtRegNum == tree->gtRegNum)
{
other = op1;
return op2;
}
else
{
other = nullptr;
return NULL;
}
}
// move an immediate value into an integer register
void CodeGen::instGen_Set_Reg_To_Imm(emitAttr size,
regNumber reg,
ssize_t imm,
insFlags flags)
{
// reg cannot be a FP register
assert(!genIsValidFloatReg(reg));
if (!compiler->opts.compReloc)
{
size = EA_SIZE(size); // Strip any Reloc flags from size if we aren't doing relocs
}