-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
lsra.cpp
14037 lines (12839 loc) · 555 KB
/
lsra.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Linear Scan Register Allocation
a.k.a. LSRA
Preconditions
- All register requirements are expressed in the code stream, either as destination
registers of tree nodes, or as internal registers. These requirements are
expressed in the RefPositions built for each node by BuildNode(), which includes:
- The register uses and definitions.
- The register restrictions (candidates) of the target register, both from itself,
as producer of the value (dstCandidates), and from its consuming node (srcCandidates).
Note that when we talk about srcCandidates we are referring to the destination register
(not any of its sources).
- The number (internalCount) of registers required, and their register restrictions (internalCandidates).
These are neither inputs nor outputs of the node, but used in the sequence of code generated for the tree.
"Internal registers" are registers used during the code sequence generated for the node.
The register lifetimes must obey the following lifetime model:
- First, any internal registers are defined.
- Next, any source registers are used (and are then freed if they are last use and are not identified as
"delayRegFree").
- Next, the internal registers are used (and are then freed).
- Next, any registers in the kill set for the instruction are killed.
- Next, the destination register(s) are defined (multiple destination registers are only supported on ARM)
- Finally, any "delayRegFree" source registers are freed.
There are several things to note about this order:
- The internal registers will never overlap any use, but they may overlap a destination register.
- Internal registers are never live beyond the node.
- The "delayRegFree" annotation is used for instructions that are only available in a Read-Modify-Write form.
That is, the destination register is one of the sources. In this case, we must not use the same register for
the non-RMW operand as for the destination.
Overview (doLinearScan):
- Walk all blocks, building intervals and RefPositions (buildIntervals)
- Allocate registers (allocateRegisters)
- Annotate nodes with register assignments (resolveRegisters)
- Add move nodes as needed to resolve conflicting register
assignments across non-adjacent edges. (resolveEdges, called from resolveRegisters)
Postconditions:
Tree nodes (GenTree):
- GenTree::GetRegNum() (and gtRegPair for ARM) is annotated with the register
assignment for a node. If the node does not require a register, it is
annotated as such (GetRegNum() = REG_NA). For a variable definition or interior
tree node (an "implicit" definition), this is the register to put the result.
For an expression use, this is the place to find the value that has previously
been computed.
- In most cases, this register must satisfy the constraints specified for the RefPosition.
- In some cases, this is difficult:
- If a lclVar node currently lives in some register, it may not be desirable to move it
(i.e. its current location may be desirable for future uses, e.g. if it's a callee save register,
but needs to be in a specific arg register for a call).
- In other cases there may be conflicts on the restrictions placed by the defining node and the node which
consumes it
- If such a node is constrained to a single fixed register (e.g. an arg register, or a return from a call),
then LSRA is free to annotate the node with a different register. The code generator must issue the appropriate
move.
- However, if such a node is constrained to a set of registers, and its current location does not satisfy that
requirement, LSRA must insert a GT_COPY node between the node and its parent. The GetRegNum() on the GT_COPY
node must satisfy the register requirement of the parent.
- GenTree::gtRsvdRegs has a set of registers used for internal temps.
- A tree node is marked GTF_SPILL if the tree node must be spilled by the code generator after it has been
evaluated.
- LSRA currently does not set GTF_SPILLED on such nodes, because it caused problems in the old code generator.
In the new backend perhaps this should change (see also the note below under CodeGen).
- A tree node is marked GTF_SPILLED if it is a lclVar that must be reloaded prior to use.
- The register (GetRegNum()) on the node indicates the register to which it must be reloaded.
- For lclVar nodes, since the uses and defs are distinct tree nodes, it is always possible to annotate the node
with the register to which the variable must be reloaded.
- For other nodes, since they represent both the def and use, if the value must be reloaded to a different
register, LSRA must insert a GT_RELOAD node in order to specify the register to which it should be reloaded.
Local variable table (LclVarDsc):
- LclVarDsc::lvRegister is set to true if a local variable has the
same register assignment for its entire lifetime.
- LclVarDsc::lvRegNum / GetOtherReg(): these are initialized to their
first value at the end of LSRA (it looks like GetOtherReg() isn't?
This is probably a bug (ARM)). Codegen will set them to their current value
as it processes the trees, since a variable can (now) be assigned different
registers over its lifetimes.
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "lsra.h"
#ifdef DEBUG
const char* LinearScan::resolveTypeName[] = {"Split", "Join", "Critical", "SharedCritical"};
#endif // DEBUG
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Small Helper functions XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
//--------------------------------------------------------------
// lsraAssignRegToTree: Assign the given reg to tree node.
//
// Arguments:
// tree - GenTree node
// reg - register to be assigned
// regIdx - register idx, if tree is a multi-reg call node.
// regIdx will be zero for single-reg result producing tree nodes.
//
// Return Value:
// None
//
void lsraAssignRegToTree(GenTree* tree, regNumber reg, unsigned regIdx)
{
if (regIdx == 0)
{
tree->SetRegNum(reg);
}
#if !defined(TARGET_64BIT)
else if (tree->OperIsMultiRegOp())
{
assert(regIdx == 1);
GenTreeMultiRegOp* mul = tree->AsMultiRegOp();
mul->gtOtherReg = reg;
}
#endif // TARGET_64BIT
#if FEATURE_MULTIREG_RET
else if (tree->OperGet() == GT_COPY)
{
assert(regIdx == 1);
GenTreeCopyOrReload* copy = tree->AsCopyOrReload();
copy->gtOtherRegs[0] = (regNumberSmall)reg;
}
#endif // FEATURE_MULTIREG_RET
#if FEATURE_ARG_SPLIT
else if (tree->OperIsPutArgSplit())
{
GenTreePutArgSplit* putArg = tree->AsPutArgSplit();
putArg->SetRegNumByIdx(reg, regIdx);
}
#endif // FEATURE_ARG_SPLIT
#ifdef FEATURE_HW_INTRINSICS
else if (tree->OperIs(GT_HWINTRINSIC))
{
tree->AsHWIntrinsic()->SetRegNumByIdx(reg, regIdx);
}
#endif // FEATURE_HW_INTRINSICS
else if (tree->OperIs(GT_LCL_VAR, GT_STORE_LCL_VAR))
{
tree->AsLclVar()->SetRegNumByIdx(reg, regIdx);
}
else
{
assert(tree->IsMultiRegCall());
GenTreeCall* call = tree->AsCall();
call->SetRegNumByIdx(reg, regIdx);
}
}
//-------------------------------------------------------------
// getWeight: Returns the weight of the RefPosition.
//
// Arguments:
// refPos - ref position
//
// Returns:
// Weight of ref position.
weight_t LinearScan::getWeight(RefPosition* refPos)
{
// RefTypeKill does not have a valid treeNode field, so we do not expect
// to see getWeight called for it
assert(refPos->refType != RefTypeKill);
weight_t weight;
GenTree* treeNode = refPos->treeNode;
if (treeNode != nullptr)
{
if (isCandidateLocalRef(treeNode))
{
// Tracked locals: use weighted ref cnt as the weight of the
// ref position.
const LclVarDsc* varDsc = compiler->lvaGetDesc(treeNode->AsLclVarCommon());
weight = varDsc->lvRefCntWtd();
if (refPos->getInterval()->isSpilled)
{
// Decrease the weight if the interval has already been spilled.
if (varDsc->lvLiveInOutOfHndlr || refPos->getInterval()->firstRefPosition->singleDefSpill)
{
// An EH-var/single-def is always spilled at defs, and we'll decrease the weight by half,
// since only the reload is needed.
weight = weight / 2;
}
else
{
weight -= BB_UNITY_WEIGHT;
}
}
}
else
{
// Non-candidate local ref or non-lcl tree node.
// These are considered to have two references in the basic block:
// a def and a use and hence weighted ref count would be 2 times
// the basic block weight in which they appear.
// However, it is generally more harmful to spill tree temps, so we
// double that.
const unsigned TREE_TEMP_REF_COUNT = 2;
const unsigned TREE_TEMP_BOOST_FACTOR = 2;
weight = TREE_TEMP_REF_COUNT * TREE_TEMP_BOOST_FACTOR * blockInfo[refPos->bbNum].weight;
}
}
else
{
// Non-tree node ref positions. These will have a single
// reference in the basic block and hence their weighted
// refcount is equal to the block weight in which they
// appear.
weight = blockInfo[refPos->bbNum].weight;
}
return weight;
}
// allRegs represents a set of registers that can
// be used to allocate the specified type in any point
// in time (more of a 'bank' of registers).
SingleTypeRegSet LinearScan::allRegs(RegisterType rt)
{
assert((rt != TYP_UNDEF) && (rt != TYP_STRUCT));
return *availableRegs[rt];
}
SingleTypeRegSet LinearScan::allByteRegs()
{
#ifdef TARGET_X86
return availableIntRegs & RBM_BYTE_REGS.GetIntRegSet();
#else
return availableIntRegs;
#endif
}
SingleTypeRegSet LinearScan::allSIMDRegs()
{
return availableFloatRegs;
}
//------------------------------------------------------------------------
// lowSIMDRegs(): Return the set of SIMD registers associated with VEX
// encoding only, i.e., remove the high EVEX SIMD registers from the available
// set.
//
// Return Value:
// Register mask of the SSE/VEX-only SIMD registers
//
SingleTypeRegSet LinearScan::lowSIMDRegs()
{
#if defined(TARGET_AMD64)
return (availableFloatRegs & RBM_LOWFLOAT.GetFloatRegSet());
#else
return availableFloatRegs;
#endif
}
void LinearScan::updateNextFixedRef(RegRecord* regRecord, RefPosition* nextRefPosition, RefPosition* nextKill)
{
LsraLocation nextLocation = nextRefPosition == nullptr ? MaxLocation : nextRefPosition->nodeLocation;
RefPosition* kill = nextKill;
while ((kill != nullptr) && (kill->nodeLocation < nextLocation))
{
if (kill->killedRegisters.IsRegNumInMask(regRecord->regNum))
{
nextLocation = kill->nodeLocation;
break;
}
kill = kill->nextRefPosition;
}
if (nextLocation == MaxLocation)
{
fixedRegs.RemoveRegNumFromMask(regRecord->regNum);
}
else
{
fixedRegs.AddRegNumInMask(regRecord->regNum);
}
nextFixedRef[regRecord->regNum] = nextLocation;
}
SingleTypeRegSet LinearScan::getMatchingConstants(SingleTypeRegSet mask,
Interval* currentInterval,
RefPosition* refPosition)
{
assert(currentInterval->isConstant && RefTypeIsDef(refPosition->refType));
SingleTypeRegSet candidates = mask & m_RegistersWithConstants.GetRegSetForType(currentInterval->registerType);
SingleTypeRegSet result = RBM_NONE;
while (candidates != RBM_NONE)
{
regNumber regNum = genFirstRegNumFromMask(candidates, currentInterval->registerType);
SingleTypeRegSet candidateBit = genSingleTypeRegMask(regNum);
candidates ^= candidateBit;
RegRecord* physRegRecord = getRegisterRecord(regNum);
if (isMatchingConstant(physRegRecord, refPosition))
{
result |= candidateBit;
}
}
return result;
}
void LinearScan::clearAllNextIntervalRef()
{
memset(nextIntervalRef, MaxLocation, AVAILABLE_REG_COUNT * sizeof(LsraLocation));
}
void LinearScan::clearNextIntervalRef(regNumber reg, var_types regType)
{
nextIntervalRef[reg] = MaxLocation;
#ifdef TARGET_ARM
if (regType == TYP_DOUBLE)
{
assert(genIsValidDoubleReg(reg));
regNumber otherReg = REG_NEXT(reg);
nextIntervalRef[otherReg] = MaxLocation;
}
#endif
}
void LinearScan::clearAllSpillCost()
{
memset(spillCost, 0, AVAILABLE_REG_COUNT * sizeof(weight_t));
}
void LinearScan::clearSpillCost(regNumber reg, var_types regType)
{
spillCost[reg] = 0;
#ifdef TARGET_ARM
if (regType == TYP_DOUBLE)
{
assert(genIsValidDoubleReg(reg));
regNumber otherReg = REG_NEXT(reg);
spillCost[otherReg] = 0;
}
#endif
}
void LinearScan::updateNextIntervalRef(regNumber reg, Interval* interval)
{
LsraLocation nextRefLocation = interval->getNextRefLocation();
nextIntervalRef[reg] = nextRefLocation;
#ifdef TARGET_ARM
if (interval->registerType == TYP_DOUBLE)
{
regNumber otherReg = REG_NEXT(reg);
nextIntervalRef[otherReg] = nextRefLocation;
}
#endif
}
void LinearScan::updateSpillCost(regNumber reg, Interval* interval)
{
// An interval can have no recentRefPosition if this is the initial assignment
// of a parameter to its home register.
weight_t cost = (interval->recentRefPosition != nullptr) ? getWeight(interval->recentRefPosition) : 0;
spillCost[reg] = cost;
#ifdef TARGET_ARM
if (interval->registerType == TYP_DOUBLE)
{
regNumber otherReg = REG_NEXT(reg);
spillCost[otherReg] = cost;
}
#endif
}
//------------------------------------------------------------------------
// updateRegsFreeBusyState: Update various register masks and global state to track
// registers that are free and busy.
//
// Arguments:
// refPosition - RefPosition for which we need to update the state.
// regsBusy - Mask of registers that are busy.
// regsToFree - Mask of registers that are set to be free.
// delayRegsToFree - Mask of registers that are set to be delayed free.
// interval - Interval of Refposition.
// assignedReg - Assigned register for this refposition.
//
void LinearScan::updateRegsFreeBusyState(RefPosition& refPosition,
var_types registerType,
SingleTypeRegSet regsBusy,
regMaskTP* regsToFree,
regMaskTP* delayRegsToFree DEBUG_ARG(Interval* interval)
DEBUG_ARG(regNumber assignedReg))
{
regsInUseThisLocation.AddRegsetForType(regsBusy, registerType);
if (refPosition.lastUse)
{
if (refPosition.delayRegFree)
{
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE_DELAYED, interval, assignedReg));
delayRegsToFree->AddRegsetForType(regsBusy, registerType);
regsInUseNextLocation.AddRegsetForType(regsBusy, registerType);
}
else
{
INDEBUG(dumpLsraAllocationEvent(LSRA_EVENT_LAST_USE, interval, assignedReg));
regsToFree->AddRegsetForType(regsBusy, registerType);
}
}
else if (refPosition.delayRegFree)
{
regsInUseNextLocation.AddRegsetForType(regsBusy, registerType);
}
}
//------------------------------------------------------------------------
// internalFloatRegCandidates: Return the set of registers that are appropriate
// for use as internal float registers.
//
// Return Value:
// The set of registers (as a regMaskTP).
//
// Notes:
// compFloatingPointUsed is only required to be set if it is possible that we
// will use floating point callee-save registers.
// It is unlikely, if an internal register is the only use of floating point,
// that it will select a callee-save register. But to be safe, we restrict
// the set of candidates if compFloatingPointUsed is not already set.
//
SingleTypeRegSet LinearScan::internalFloatRegCandidates()
{
needNonIntegerRegisters = true;
if (compiler->compFloatingPointUsed)
{
return availableFloatRegs;
}
else
{
return RBM_FLT_CALLEE_TRASH.GetFloatRegSet();
}
}
bool LinearScan::isFree(RegRecord* regRecord)
{
return ((regRecord->assignedInterval == nullptr || !regRecord->assignedInterval->isActive) &&
!isRegBusy(regRecord->regNum, regRecord->registerType));
}
RegRecord* LinearScan::getRegisterRecord(regNumber regNum)
{
assert((unsigned)regNum < ArrLen(physRegs));
return &physRegs[regNum];
}
#ifdef DEBUG
//----------------------------------------------------------------------------
// getConstrainedRegMask: Returns new regMask which is the intersection of
// regMaskActual and regMaskConstraint if the new regMask has at least
// minRegCount registers, otherwise returns regMaskActual.
//
// Arguments:
// refPosition - RefPosition which we want to constrain.
// regType - Type of register for which we want constrained mask
// regMaskActual - regMask that needs to be constrained
// regMaskConstraint - regMask constraint that needs to be
// applied to regMaskActual
// minRegCount - Minimum number of regs that should be
// be present in new regMask.
//
// Return Value:
// New regMask that has minRegCount registers after intersection.
// Otherwise returns regMaskActual.
//
SingleTypeRegSet LinearScan::getConstrainedRegMask(RefPosition* refPosition,
RegisterType regType,
SingleTypeRegSet regMaskActual,
SingleTypeRegSet regMaskConstraint,
unsigned minRegCount)
{
SingleTypeRegSet newMask = regMaskActual & regMaskConstraint;
if (PopCount(newMask) < minRegCount)
{
// Constrained mask does not have minimum required registers needed.
return regMaskActual;
}
if ((refPosition != nullptr) && !refPosition->RegOptional())
{
SingleTypeRegSet busyRegs = (regsBusyUntilKill | regsInUseThisLocation).GetRegSetForType(regType);
if ((newMask & ~busyRegs) == RBM_NONE)
{
// Constrained mask does not have at least one free register to allocate.
// Skip for RegOptional, because its ok to not have registers for them.
return regMaskActual;
}
}
return newMask;
}
//------------------------------------------------------------------------
// When LSRA_LIMIT_SMALL_SET is specified, it is desirable to select a "mixed" set of caller- and callee-save
// registers, so as to get different coverage than limiting to callee or caller.
// At least for x86 and AMD64, and potentially other architecture that will support SIMD,
// we need a minimum of 5 fp regs in order to support the InitN intrinsic for Vector4.
// Hence the "SmallFPSet" has 5 elements.
#if defined(TARGET_AMD64)
#ifdef UNIX_AMD64_ABI
// On System V the RDI and RSI are not callee saved. Use R12 ans R13 as callee saved registers.
static const regMaskTP LsraLimitSmallIntSet = (RBM_EAX | RBM_ECX | RBM_EBX | RBM_ETW_FRAMED_EBP | RBM_R12 | RBM_R13);
#else // !UNIX_AMD64_ABI
// On Windows Amd64 use the RDI and RSI as callee saved registers.
static const regMaskTP LsraLimitSmallIntSet = (RBM_EAX | RBM_ECX | RBM_EBX | RBM_ETW_FRAMED_EBP | RBM_ESI | RBM_EDI);
#endif // !UNIX_AMD64_ABI
static const regMaskTP LsraLimitSmallFPSet = (RBM_XMM0 | RBM_XMM1 | RBM_XMM2 | RBM_XMM6 | RBM_XMM7);
static const regMaskTP LsraLimitUpperSimdSet =
(RBM_XMM16 | RBM_XMM17 | RBM_XMM18 | RBM_XMM19 | RBM_XMM20 | RBM_XMM21 | RBM_XMM22 | RBM_XMM23 | RBM_XMM24 |
RBM_XMM25 | RBM_XMM26 | RBM_XMM27 | RBM_XMM28 | RBM_XMM29 | RBM_XMM30 | RBM_XMM31);
#elif defined(TARGET_ARM)
// On ARM, we may need two registers to set up the target register for a virtual call, so we need
// to have at least the maximum number of arg registers, plus 2.
static const regMaskTP LsraLimitSmallIntSet = (RBM_R0 | RBM_R1 | RBM_R2 | RBM_R3 | RBM_R4 | RBM_R5);
static const regMaskTP LsraLimitSmallFPSet = (RBM_F0 | RBM_F1 | RBM_F2 | RBM_F16 | RBM_F17);
#elif defined(TARGET_ARM64)
static const regMaskTP LsraLimitSmallIntSet = (RBM_R0 | RBM_R1 | RBM_R2 | RBM_R19 | RBM_R20);
static const regMaskTP LsraLimitSmallFPSet = (RBM_V0 | RBM_V1 | RBM_V2 | RBM_V8 | RBM_V9);
#elif defined(TARGET_X86)
static const regMaskTP LsraLimitSmallIntSet = (RBM_EAX | RBM_ECX | RBM_EDI);
static const regMaskTP LsraLimitSmallFPSet = (RBM_XMM0 | RBM_XMM1 | RBM_XMM2 | RBM_XMM6 | RBM_XMM7);
#elif defined(TARGET_LOONGARCH64)
static const regMaskTP LsraLimitSmallIntSet = (RBM_T1 | RBM_T3 | RBM_A0 | RBM_A1 | RBM_T0);
static const regMaskTP LsraLimitSmallFPSet = (RBM_F0 | RBM_F1 | RBM_F2 | RBM_F8 | RBM_F9);
#elif defined(TARGET_RISCV64)
static const regMaskTP LsraLimitSmallIntSet = (RBM_T1 | RBM_T3 | RBM_A0 | RBM_A1 | RBM_T0);
static const regMaskTP LsraLimitSmallFPSet = (RBM_F0 | RBM_F1 | RBM_F2 | RBM_F8 | RBM_F9);
#else
#error Unsupported or unset target architecture
#endif // target
//------------------------------------------------------------------------
// stressLimitRegs: Given a set of registers, expressed as a register mask, reduce
// them based on the current stress options.
//
// Arguments:
// mask - The current mask of register candidates for a node
//
// Return Value:
// A possibly-modified mask, based on the value of DOTNET_JitStressRegs.
//
// Notes:
// This is the method used to implement the stress options that limit
// the set of registers considered for allocation.
//
SingleTypeRegSet LinearScan::stressLimitRegs(RefPosition* refPosition, RegisterType regType, SingleTypeRegSet mask)
{
#ifdef TARGET_ARM64
if ((refPosition != nullptr) && refPosition->isLiveAtConsecutiveRegistersLoc(consecutiveRegistersLocation))
{
// If we are assigning for the refPositions that has consecutive registers requirements, skip the
// limit stress for them, because there are high chances that many registers are busy for consecutive
// requirements and we do not have enough remaining to assign other refpositions (like operands).
// Likewise, skip for the definition node that comes after that, for which, all the registers are in
// the "delayRegFree" state.
return mask;
}
#endif
if (getStressLimitRegs() != LSRA_LIMIT_NONE)
{
// The refPosition could be null, for example when called
// by getTempRegForResolution().
int minRegCount = (refPosition != nullptr) ? refPosition->minRegCandidateCount : 1;
switch (getStressLimitRegs())
{
case LSRA_LIMIT_CALLEE:
if (!compiler->opts.compDbgEnC)
{
mask = getConstrainedRegMask(refPosition, regType, mask, RBM_CALLEE_SAVED.GetRegSetForType(regType),
minRegCount);
}
break;
case LSRA_LIMIT_CALLER:
{
mask = getConstrainedRegMask(refPosition, regType, mask, RBM_CALLEE_TRASH.GetRegSetForType(regType),
minRegCount);
}
break;
case LSRA_LIMIT_SMALL_SET:
if ((mask & LsraLimitSmallIntSet) != RBM_NONE)
{
mask = getConstrainedRegMask(refPosition, regType, mask,
LsraLimitSmallIntSet.GetRegSetForType(regType), minRegCount);
}
else if ((mask & LsraLimitSmallFPSet) != RBM_NONE)
{
mask = getConstrainedRegMask(refPosition, regType, mask,
LsraLimitSmallFPSet.GetRegSetForType(regType), minRegCount);
}
break;
#if defined(TARGET_AMD64)
case LSRA_LIMIT_UPPER_SIMD_SET:
if ((mask & LsraLimitUpperSimdSet) != RBM_NONE)
{
mask = getConstrainedRegMask(refPosition, regType, mask,
LsraLimitUpperSimdSet.GetRegSetForType(regType), minRegCount);
}
break;
#endif
default:
{
unreached();
}
}
if (refPosition != nullptr && refPosition->isFixedRegRef)
{
mask |= refPosition->registerAssignment;
}
}
return mask;
}
#endif // DEBUG
//------------------------------------------------------------------------
// conflictingFixedRegReference: Determine whether the 'reg' has a
// fixed register use that conflicts with 'refPosition'
//
// Arguments:
// regNum - The register of interest
// refPosition - The RefPosition of interest
//
// Return Value:
// Returns true iff the given RefPosition is NOT a fixed use of this register,
// AND either:
// - there is a RefPosition on this RegRecord at the nodeLocation of the given RefPosition, or
// - the given RefPosition has a delayRegFree, and there is a RefPosition on this RegRecord at
// the nodeLocation just past the given RefPosition.
//
// Assumptions:
// 'refPosition is non-null.
//
bool LinearScan::conflictingFixedRegReference(regNumber regNum, RefPosition* refPosition)
{
// Is this a fixed reference of this register? If so, there is no conflict.
if (refPosition->isFixedRefOfRegMask(genSingleTypeRegMask(regNum)))
{
return false;
}
// Otherwise, check for conflicts.
// There is a conflict if:
// 1. There is a recent RefPosition on this RegRecord that is at this location, OR
// 2. There is an upcoming RefPosition at this location, or at the next location
// if refPosition is a delayed use (i.e. must be kept live through the next/def location).
LsraLocation refLocation = refPosition->nodeLocation;
RegRecord* regRecord = getRegisterRecord(regNum);
if (isRegInUse(regNum, refPosition->getInterval()->registerType) &&
(regRecord->assignedInterval != refPosition->getInterval()))
{
return true;
}
LsraLocation nextPhysRefLocation = nextFixedRef[regNum];
if (nextPhysRefLocation == refLocation || (refPosition->delayRegFree && nextPhysRefLocation == (refLocation + 1)))
{
return true;
}
return false;
}
/*****************************************************************************
* Inline functions for Interval
*****************************************************************************/
RefPosition* Referenceable::getNextRefPosition()
{
if (recentRefPosition == nullptr)
{
return firstRefPosition;
}
else
{
return recentRefPosition->nextRefPosition;
}
}
LsraLocation Referenceable::getNextRefLocation()
{
RefPosition* nextRefPosition = getNextRefPosition();
if (nextRefPosition == nullptr)
{
return MaxLocation;
}
else
{
return nextRefPosition->nodeLocation;
}
}
#ifdef DEBUG
void LinearScan::dumpVarToRegMap(VarToRegMap map)
{
bool anyPrinted = false;
for (unsigned varIndex = 0; varIndex < compiler->lvaTrackedCount; varIndex++)
{
if (map[varIndex] != REG_STK)
{
printf("V%02u=%s ", compiler->lvaTrackedIndexToLclNum(varIndex), getRegName(map[varIndex]));
anyPrinted = true;
}
}
if (!anyPrinted)
{
printf("none");
}
printf("\n");
}
void LinearScan::dumpInVarToRegMap(BasicBlock* block)
{
printf("Var=Reg beg of " FMT_BB ": ", block->bbNum);
VarToRegMap map = getInVarToRegMap(block->bbNum);
dumpVarToRegMap(map);
}
void LinearScan::dumpOutVarToRegMap(BasicBlock* block)
{
printf("Var=Reg end of " FMT_BB ": ", block->bbNum);
VarToRegMap map = getOutVarToRegMap(block->bbNum);
dumpVarToRegMap(map);
}
#endif // DEBUG
LinearScanInterface* getLinearScanAllocator(Compiler* comp)
{
return new (comp, CMK_LSRA) LinearScan(comp);
}
//------------------------------------------------------------------------
// LSRA constructor
//
// Arguments:
// theCompiler
//
// Notes:
// The constructor takes care of initializing the data structures that are used
// during Lowering, including (in DEBUG) getting the stress environment variables,
// as they may affect the block ordering.
//
LinearScan::LinearScan(Compiler* theCompiler)
: compiler(theCompiler)
, intervals(theCompiler->getAllocator(CMK_LSRA_Interval))
, allocationPassComplete(false)
, refPositions(theCompiler->getAllocator(CMK_LSRA_RefPosition))
, killHead(nullptr)
, killTail(&killHead)
, listNodePool(theCompiler)
{
availableRegCount = ACTUAL_REG_COUNT;
needNonIntegerRegisters = false;
#if defined(TARGET_AMD64)
rbmAllFloat = compiler->rbmAllFloat;
rbmFltCalleeTrash = compiler->rbmFltCalleeTrash;
#endif // TARGET_AMD64
#if defined(TARGET_XARCH)
rbmAllMask = compiler->rbmAllMask;
rbmMskCalleeTrash = compiler->rbmMskCalleeTrash;
memcpy(varTypeCalleeTrashRegs, compiler->varTypeCalleeTrashRegs, sizeof(regMaskTP) * TYP_COUNT);
if (!compiler->canUseEvexEncoding())
{
availableRegCount -= (CNT_HIGHFLOAT + CNT_MASK_REGS);
}
#endif // TARGET_XARCH
firstColdLoc = MaxLocation;
#ifdef DEBUG
maxNodeLocation = 0;
consecutiveRegistersLocation = 0;
activeRefPosition = nullptr;
currBuildNode = nullptr;
lsraStressMask = JitConfig.JitStressRegs();
if (lsraStressMask != 0)
{
// See if stress regs is enabled for this method
//
static ConfigMethodRange JitStressRegsRange;
JitStressRegsRange.EnsureInit(JitConfig.JitStressRegsRange());
const unsigned methHash = compiler->info.compMethodHash();
const bool inRange = JitStressRegsRange.Contains(methHash);
if (!inRange)
{
JITDUMP("*** JitStressRegs = 0x%x -- disabled by JitStressRegsRange\n", lsraStressMask);
lsraStressMask = 0;
}
else
{
JITDUMP("*** JitStressRegs = 0x%x\n", lsraStressMask);
}
}
#endif // DEBUG
// Assume that we will enregister local variables if it's not disabled. We'll reset it if we
// have no tracked locals when we start allocating. Note that new tracked lclVars may be added
// after the first liveness analysis - either by optimizations or by Lowering, and the tracked
// set won't be recomputed until after Lowering (and this constructor is called prior to Lowering),
// so we don't want to check that yet.
enregisterLocalVars = compiler->compEnregLocals();
regSelector = new (theCompiler, CMK_LSRA) RegisterSelection(this);
#ifdef TARGET_ARM64
// Note: one known reason why we exclude LR is because NativeAOT has dependency on not
// using LR as a GPR. See: https://github.com/dotnet/runtime/issues/101932
// Once that is addressed, we may consider allowing LR in availableIntRegs.
availableIntRegs =
(RBM_ALLINT & ~(RBM_PR | RBM_FP | RBM_LR) & ~compiler->codeGen->regSet.rsMaskResvd).GetIntRegSet();
#elif defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
availableIntRegs = (RBM_ALLINT & ~(RBM_FP | RBM_RA) & ~compiler->codeGen->regSet.rsMaskResvd).GetIntRegSet();
#else
availableIntRegs = (RBM_ALLINT & ~compiler->codeGen->regSet.rsMaskResvd).GetIntRegSet();
#endif
#if ETW_EBP_FRAMED
availableIntRegs &= ~RBM_FPBASE.GetIntRegSet();
#endif // ETW_EBP_FRAMED
#ifdef TARGET_AMD64
availableFloatRegs = RBM_ALLFLOAT.GetFloatRegSet();
availableDoubleRegs = RBM_ALLDOUBLE.GetFloatRegSet();
#else
availableFloatRegs = RBM_ALLFLOAT.GetFloatRegSet();
availableDoubleRegs = RBM_ALLDOUBLE.GetFloatRegSet();
#endif
#if defined(TARGET_XARCH) || defined(TARGET_ARM64)
availableMaskRegs = RBM_ALLMASK.GetPredicateRegSet();
#endif
#if defined(TARGET_AMD64) || defined(TARGET_ARM64)
if (compiler->opts.compDbgEnC)
{
// When the EnC option is set we have an exact set of registers that we always save
// that are also available in future versions.
availableIntRegs &= (~RBM_INT_CALLEE_SAVED | RBM_ENC_CALLEE_SAVED).GetIntRegSet();
#if defined(UNIX_AMD64_ABI)
availableFloatRegs &= ~RBM_FLT_CALLEE_SAVED;
availableDoubleRegs &= ~RBM_FLT_CALLEE_SAVED;
#else
availableFloatRegs &= ~RBM_FLT_CALLEE_SAVED.GetFloatRegSet();
availableDoubleRegs &= ~RBM_FLT_CALLEE_SAVED.GetFloatRegSet();
#endif // UNIX_AMD64_ABI
#if defined(TARGET_XARCH)
availableMaskRegs &= ~RBM_MSK_CALLEE_SAVED;
#endif // TARGET_XARCH
}
#endif // TARGET_AMD64 || TARGET_ARM64
#if defined(TARGET_AMD64)
if (compiler->canUseEvexEncoding())
{
availableFloatRegs |= RBM_HIGHFLOAT.GetFloatRegSet();
availableDoubleRegs |= RBM_HIGHFLOAT.GetFloatRegSet();
}
#endif
// Initialize the availableRegs to use for each TYP_*
#define DEF_TP(tn, nm, jitType, sz, sze, asze, st, al, regTyp, regFld, csr, ctr, tf) \
availableRegs[static_cast<int>(TYP_##tn)] = ®Fld;
#include "typelist.h"
#undef DEF_TP
compiler->rpFrameType = FT_NOT_SET;
compiler->rpMustCreateEBPCalled = false;
compiler->codeGen->intRegState.rsIsFloat = false;
compiler->codeGen->floatRegState.rsIsFloat = true;
// Block sequencing (the order in which we schedule).
// Note that we don't initialize the bbVisitedSet until we do the first traversal
// This is so that any blocks that are added during the first traversal
// are accounted for (and we don't have BasicBlockEpoch issues).
blockSequencingDone = false;
blockSequence = nullptr;
blockSequenceWorkList = nullptr;
curBBSeqNum = 0;
bbSeqCount = 0;
// Information about each block, including predecessor blocks used for variable locations at block entry.
blockInfo = nullptr;
pendingDelayFree = false;
tgtPrefUse = nullptr;
}
//------------------------------------------------------------------------
// getNextCandidateFromWorkList: Get the next candidate for block sequencing
//
// Arguments:
// None.
//
// Return Value:
// The next block to be placed in the sequence.
//
// Notes:
// This method currently always returns the next block in the list, and relies on having
// blocks added to the list only when they are "ready", and on the
// addToBlockSequenceWorkList() method to insert them in the proper order.
// However, a block may be in the list and already selected, if it was subsequently
// encountered as both a flow and layout successor of the most recently selected
// block.
//
BasicBlock* LinearScan::getNextCandidateFromWorkList()
{
BasicBlockList* nextWorkList = nullptr;
for (BasicBlockList* workList = blockSequenceWorkList; workList != nullptr; workList = nextWorkList)
{
nextWorkList = workList->next;
BasicBlock* candBlock = workList->block;
removeFromBlockSequenceWorkList(workList, nullptr);
if (!isBlockVisited(candBlock))
{
return candBlock;
}
}
return nullptr;
}
//------------------------------------------------------------------------
// setBlockSequence: Determine the block order for register allocation.
//
// Arguments:
// None
//
// Return Value:
// None
//
// Notes:
// On return, the blockSequence array contains the blocks, in the order in which they
// will be allocated.
// This method clears the bbVisitedSet on LinearScan, and when it returns the set
// contains all the bbNums for the block.
//
void LinearScan::setBlockSequence()
{
assert(!blockSequencingDone); // The method should be called only once.
compiler->EnsureBasicBlockEpoch();
#ifdef DEBUG
blockEpoch = compiler->GetCurBasicBlockEpoch();
#endif // DEBUG
// Initialize the "visited" blocks set.
bbVisitedSet = BlockSetOps::MakeEmpty(compiler);
BlockSet readySet(BlockSetOps::MakeEmpty(compiler));
BlockSet predSet(BlockSetOps::MakeEmpty(compiler));
assert(blockSequence == nullptr && bbSeqCount == 0);
blockSequence = new (compiler, CMK_LSRA) BasicBlock*[compiler->fgBBcount];
bbNumMaxBeforeResolution = compiler->fgBBNumMax;
blockInfo = new (compiler, CMK_LSRA) LsraBlockInfo[bbNumMaxBeforeResolution + 1];
assert(blockSequenceWorkList == nullptr);
verifiedAllBBs = false;
hasCriticalEdges = false;