-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
lower.cpp
7344 lines (6459 loc) · 267 KB
/
lower.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.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Lower XX
XX XX
XX Preconditions: XX
XX XX
XX Postconditions (for the nodes currently handled): XX
XX - All operands requiring a register are explicit in the graph XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "lower.h"
#if !defined(TARGET_64BIT)
#include "decomposelongs.h"
#endif // !defined(TARGET_64BIT)
//------------------------------------------------------------------------
// MakeSrcContained: Make "childNode" a contained node
//
// Arguments:
// parentNode - is a non-leaf node that can contain its 'childNode'
// childNode - is an op that will now be contained by its parent.
//
// Notes:
// If 'childNode' it has any existing sources, they will now be sources for the parent.
//
void Lowering::MakeSrcContained(GenTree* parentNode, GenTree* childNode) const
{
assert(!parentNode->OperIsLeaf());
assert(childNode->canBeContained());
childNode->SetContained();
assert(childNode->isContained());
#ifdef DEBUG
if (IsContainableMemoryOp(childNode))
{
// Verify caller of this method checked safety.
//
const bool isSafeToContainMem = IsSafeToContainMem(parentNode, childNode);
if (!isSafeToContainMem)
{
JITDUMP("** Unsafe mem containment of [%06u] in [%06u}, comp->dspTreeID(childNode), "
"comp->dspTreeID(parentNode)\n");
assert(isSafeToContainMem);
}
}
#endif
}
//------------------------------------------------------------------------
// CheckImmedAndMakeContained: Checks if the 'childNode' is a containable immediate
// and, if so, makes it contained.
//
// Arguments:
// parentNode - is any non-leaf node
// childNode - is an child op of 'parentNode'
//
// Return value:
// true if we are able to make childNode a contained immediate
//
bool Lowering::CheckImmedAndMakeContained(GenTree* parentNode, GenTree* childNode)
{
assert(!parentNode->OperIsLeaf());
// If childNode is a containable immediate
if (IsContainableImmed(parentNode, childNode))
{
// then make it contained within the parentNode
MakeSrcContained(parentNode, childNode);
return true;
}
return false;
}
//------------------------------------------------------------------------
// IsSafeToContainMem: Checks for conflicts between childNode and parentNode,
// and returns 'true' iff memory operand childNode can be contained in parentNode.
//
// Arguments:
// parentNode - any non-leaf node
// childNode - some node that is an input to `parentNode`
//
// Return value:
// true if it is safe to make childNode a contained memory operand.
//
bool Lowering::IsSafeToContainMem(GenTree* parentNode, GenTree* childNode) const
{
// Quick early-out for unary cases
//
if (childNode->gtNext == parentNode)
{
return true;
}
m_scratchSideEffects.Clear();
m_scratchSideEffects.AddNode(comp, childNode);
for (GenTree* node = childNode->gtNext; node != parentNode; node = node->gtNext)
{
const bool strict = true;
if (m_scratchSideEffects.InterferesWith(comp, node, strict))
{
return false;
}
}
return true;
}
//------------------------------------------------------------------------
// IsSafeToContainMem: Checks for conflicts between childNode and grandParentNode
// and returns 'true' iff memory operand childNode can be contained in ancestorNode
//
// Arguments:
// grandParentNode - any non-leaf node
// parentNode - parent of `childNode` and an input to `grandParentNode`
// childNode - some node that is an input to `parentNode`
//
// Return value:
// true if it is safe to make childNode a contained memory operand.
//
bool Lowering::IsSafeToContainMem(GenTree* grandparentNode, GenTree* parentNode, GenTree* childNode) const
{
m_scratchSideEffects.Clear();
m_scratchSideEffects.AddNode(comp, childNode);
for (GenTree* node = childNode->gtNext; node != grandparentNode; node = node->gtNext)
{
if (node == parentNode)
{
continue;
}
const bool strict = true;
if (m_scratchSideEffects.InterferesWith(comp, node, strict))
{
return false;
}
}
return true;
}
//------------------------------------------------------------------------
// LowerNode: this is the main entry point for Lowering.
//
// Arguments:
// node - the node we are lowering.
//
// Returns:
// next node in the transformed node sequence that needs to be lowered.
//
GenTree* Lowering::LowerNode(GenTree* node)
{
assert(node != nullptr);
switch (node->gtOper)
{
case GT_NULLCHECK:
case GT_IND:
LowerIndir(node->AsIndir());
break;
case GT_STOREIND:
LowerStoreIndirCommon(node->AsStoreInd());
break;
case GT_ADD:
{
GenTree* next = LowerAdd(node->AsOp());
if (next != nullptr)
{
return next;
}
}
break;
#if !defined(TARGET_64BIT)
case GT_ADD_LO:
case GT_ADD_HI:
case GT_SUB_LO:
case GT_SUB_HI:
#endif
case GT_SUB:
case GT_AND:
case GT_OR:
case GT_XOR:
return LowerBinaryArithmetic(node->AsOp());
case GT_MUL:
case GT_MULHI:
#if defined(TARGET_X86) || defined(TARGET_ARM64)
case GT_MUL_LONG:
#endif
return LowerMul(node->AsOp());
case GT_UDIV:
case GT_UMOD:
if (!LowerUnsignedDivOrMod(node->AsOp()))
{
ContainCheckDivOrMod(node->AsOp());
}
break;
case GT_DIV:
case GT_MOD:
return LowerSignedDivOrMod(node);
case GT_SWITCH:
return LowerSwitch(node);
case GT_CALL:
LowerCall(node);
break;
case GT_LT:
case GT_LE:
case GT_GT:
case GT_GE:
case GT_EQ:
case GT_NE:
case GT_TEST_EQ:
case GT_TEST_NE:
case GT_CMP:
return LowerCompare(node);
case GT_JTRUE:
return LowerJTrue(node->AsOp());
case GT_JMP:
LowerJmpMethod(node);
break;
case GT_RETURN:
LowerRet(node->AsUnOp());
break;
case GT_RETURNTRAP:
ContainCheckReturnTrap(node->AsOp());
break;
case GT_CAST:
LowerCast(node);
break;
#if defined(TARGET_XARCH) || defined(TARGET_ARM64)
case GT_BOUNDS_CHECK:
ContainCheckBoundsChk(node->AsBoundsChk());
break;
#endif // TARGET_XARCH
case GT_ARR_ELEM:
return LowerArrElem(node);
case GT_ARR_OFFSET:
ContainCheckArrOffset(node->AsArrOffs());
break;
case GT_ROL:
case GT_ROR:
LowerRotate(node);
break;
#ifndef TARGET_64BIT
case GT_LSH_HI:
case GT_RSH_LO:
ContainCheckShiftRotate(node->AsOp());
break;
#endif // !TARGET_64BIT
case GT_LSH:
case GT_RSH:
case GT_RSZ:
#if defined(TARGET_XARCH) || defined(TARGET_ARM64)
LowerShift(node->AsOp());
#else
ContainCheckShiftRotate(node->AsOp());
#endif
break;
case GT_STORE_BLK:
case GT_STORE_OBJ:
if (node->AsBlk()->Data()->IsCall())
{
LowerStoreSingleRegCallStruct(node->AsBlk());
break;
}
FALLTHROUGH;
case GT_STORE_DYN_BLK:
LowerBlockStoreCommon(node->AsBlk());
break;
case GT_LCLHEAP:
ContainCheckLclHeap(node->AsOp());
break;
#ifdef TARGET_XARCH
case GT_INTRINSIC:
ContainCheckIntrinsic(node->AsOp());
break;
#endif // TARGET_XARCH
#ifdef FEATURE_SIMD
case GT_SIMD:
LowerSIMD(node->AsSIMD());
break;
#endif // FEATURE_SIMD
#ifdef FEATURE_HW_INTRINSICS
case GT_HWINTRINSIC:
LowerHWIntrinsic(node->AsHWIntrinsic());
break;
#endif // FEATURE_HW_INTRINSICS
case GT_LCL_FLD:
{
// We should only encounter this for lclVars that are lvDoNotEnregister.
verifyLclFldDoNotEnregister(node->AsLclVarCommon()->GetLclNum());
break;
}
case GT_LCL_VAR:
{
GenTreeLclVar* lclNode = node->AsLclVar();
WidenSIMD12IfNecessary(lclNode);
LclVarDsc* varDsc = comp->lvaGetDesc(lclNode);
// The consumer of this node must check compatibility of the fields.
// This merely checks whether it is possible for this to be a multireg node.
if (lclNode->IsMultiRegLclVar())
{
if (!varDsc->lvPromoted ||
(comp->lvaGetPromotionType(varDsc) != Compiler::PROMOTION_TYPE_INDEPENDENT) ||
(varDsc->lvFieldCnt > MAX_MULTIREG_COUNT))
{
lclNode->ClearMultiReg();
if (lclNode->TypeIs(TYP_STRUCT))
{
comp->lvaSetVarDoNotEnregister(lclNode->GetLclNum() DEBUGARG(DoNotEnregisterReason::BlockOp));
}
}
}
break;
}
case GT_STORE_LCL_VAR:
WidenSIMD12IfNecessary(node->AsLclVarCommon());
FALLTHROUGH;
case GT_STORE_LCL_FLD:
LowerStoreLocCommon(node->AsLclVarCommon());
break;
#if defined(TARGET_ARM64)
case GT_CMPXCHG:
CheckImmedAndMakeContained(node, node->AsCmpXchg()->gtOpComparand);
break;
case GT_XORR:
case GT_XAND:
case GT_XADD:
CheckImmedAndMakeContained(node, node->AsOp()->gtOp2);
break;
#elif defined(TARGET_XARCH)
case GT_XORR:
case GT_XAND:
case GT_XADD:
if (node->IsUnusedValue())
{
node->ClearUnusedValue();
// Make sure the types are identical, since the node type is changed to VOID
// CodeGen relies on op2's type to determine the instruction size.
// Note that the node type cannot be a small int but the data operand can.
assert(genActualType(node->gtGetOp2()->TypeGet()) == node->TypeGet());
node->SetOper(GT_LOCKADD);
node->gtType = TYP_VOID;
CheckImmedAndMakeContained(node, node->gtGetOp2());
}
break;
#endif
#ifndef TARGET_ARMARCH
// TODO-ARMARCH-CQ: We should contain this as long as the offset fits.
case GT_OBJ:
if (node->AsObj()->Addr()->OperIsLocalAddr())
{
node->AsObj()->Addr()->SetContained();
}
break;
#endif // !TARGET_ARMARCH
case GT_KEEPALIVE:
node->gtGetOp1()->SetRegOptional();
break;
case GT_LCL_FLD_ADDR:
case GT_LCL_VAR_ADDR:
{
const GenTreeLclVarCommon* lclAddr = node->AsLclVarCommon();
const LclVarDsc* varDsc = comp->lvaGetDesc(lclAddr);
if (!varDsc->lvDoNotEnregister)
{
// TODO-Cleanup: this is definitely not the best place for this detection,
// but for now it is the easiest. Move it to morph.
comp->lvaSetVarDoNotEnregister(lclAddr->GetLclNum() DEBUGARG(DoNotEnregisterReason::LclAddrNode));
}
}
break;
default:
break;
}
return node->gtNext;
}
/** -- Switch Lowering --
* The main idea of switch lowering is to keep transparency of the register requirements of this node
* downstream in LSRA. Given that the switch instruction is inherently a control statement which in the JIT
* is represented as a simple tree node, at the time we actually generate code for it we end up
* generating instructions that actually modify the flow of execution that imposes complicated
* register requirement and lifetimes.
*
* So, for the purpose of LSRA, we want to have a more detailed specification of what a switch node actually
* means and more importantly, which and when do we need a register for each instruction we want to issue
* to correctly allocate them downstream.
*
* For this purpose, this procedure performs switch lowering in two different ways:
*
* a) Represent the switch statement as a zero-index jump table construct. This means that for every destination
* of the switch, we will store this destination in an array of addresses and the code generator will issue
* a data section where this array will live and will emit code that based on the switch index, will indirect and
* jump to the destination specified in the jump table.
*
* For this transformation we introduce a new GT node called GT_SWITCH_TABLE that is a specialization of the switch
* node for jump table based switches.
* The overall structure of a GT_SWITCH_TABLE is:
*
* GT_SWITCH_TABLE
* |_________ localVar (a temporary local that holds the switch index)
* |_________ jumpTable (this is a special node that holds the address of the jump table array)
*
* Now, the way we morph a GT_SWITCH node into this lowered switch table node form is the following:
*
* Input: GT_SWITCH (inside a basic block whose Branch Type is BBJ_SWITCH)
* |_____ expr (an arbitrarily complex GT_NODE that represents the switch index)
*
* This gets transformed into the following statements inside a BBJ_COND basic block (the target would be
* the default case of the switch in case the conditional is evaluated to true).
*
* ----- original block, transformed
* GT_STORE_LCL_VAR tempLocal (a new temporary local variable used to store the switch index)
* |_____ expr (the index expression)
*
* GT_JTRUE
* |_____ GT_COND
* |_____ GT_GE
* |___ Int_Constant (This constant is the index of the default case
* that happens to be the highest index in the jump table).
* |___ tempLocal (The local variable were we stored the index expression).
*
* ----- new basic block
* GT_SWITCH_TABLE
* |_____ tempLocal
* |_____ jumpTable (a new jump table node that now LSRA can allocate registers for explicitly
* and LinearCodeGen will be responsible to generate downstream).
*
* This way there are no implicit temporaries.
*
* b) For small-sized switches, we will actually morph them into a series of conditionals of the form
* if (case falls into the default){ goto jumpTable[size]; // last entry in the jump table is the default case }
* (For the default case conditional, we'll be constructing the exact same code as the jump table case one).
* else if (case == firstCase){ goto jumpTable[1]; }
* else if (case == secondCase) { goto jumptable[2]; } and so on.
*
* This transformation is of course made in JIT-IR, not downstream to CodeGen level, so this way we no longer
* require internal temporaries to maintain the index we're evaluating plus we're using existing code from
* LinearCodeGen to implement this instead of implement all the control flow constructs using InstrDscs and
* InstrGroups downstream.
*/
GenTree* Lowering::LowerSwitch(GenTree* node)
{
unsigned jumpCnt;
unsigned targetCnt;
BasicBlock** jumpTab;
assert(node->gtOper == GT_SWITCH);
// The first step is to build the default case conditional construct that is
// shared between both kinds of expansion of the switch node.
// To avoid confusion, we'll alias m_block to originalSwitchBB
// that represents the node we're morphing.
BasicBlock* originalSwitchBB = m_block;
LIR::Range& switchBBRange = LIR::AsRange(originalSwitchBB);
// jumpCnt is the number of elements in the jump table array.
// jumpTab is the actual pointer to the jump table array.
// targetCnt is the number of unique targets in the jump table array.
jumpCnt = originalSwitchBB->bbJumpSwt->bbsCount;
jumpTab = originalSwitchBB->bbJumpSwt->bbsDstTab;
targetCnt = originalSwitchBB->NumSucc(comp);
// GT_SWITCH must be a top-level node with no use.
#ifdef DEBUG
{
LIR::Use use;
assert(!switchBBRange.TryGetUse(node, &use));
}
#endif
JITDUMP("Lowering switch " FMT_BB ", %d cases\n", originalSwitchBB->bbNum, jumpCnt);
// Handle a degenerate case: if the switch has only a default case, just convert it
// to an unconditional branch. This should only happen in minopts or with debuggable
// code.
if (targetCnt == 1)
{
JITDUMP("Lowering switch " FMT_BB ": single target; converting to BBJ_ALWAYS\n", originalSwitchBB->bbNum);
noway_assert(comp->opts.OptimizationDisabled());
if (originalSwitchBB->bbNext == jumpTab[0])
{
originalSwitchBB->bbJumpKind = BBJ_NONE;
originalSwitchBB->bbJumpDest = nullptr;
}
else
{
originalSwitchBB->bbJumpKind = BBJ_ALWAYS;
originalSwitchBB->bbJumpDest = jumpTab[0];
}
// Remove extra predecessor links if there was more than one case.
for (unsigned i = 1; i < jumpCnt; ++i)
{
(void)comp->fgRemoveRefPred(jumpTab[i], originalSwitchBB);
}
// We have to get rid of the GT_SWITCH node but a child might have side effects so just assign
// the result of the child subtree to a temp.
GenTree* rhs = node->AsOp()->gtOp1;
unsigned lclNum = comp->lvaGrabTemp(true DEBUGARG("Lowering is creating a new local variable"));
comp->lvaTable[lclNum].lvType = rhs->TypeGet();
GenTreeLclVar* store = comp->gtNewStoreLclVar(lclNum, rhs);
switchBBRange.InsertAfter(node, store);
switchBBRange.Remove(node);
return store;
}
noway_assert(jumpCnt >= 2);
// Spill the argument to the switch node into a local so that it can be used later.
LIR::Use use(switchBBRange, &(node->AsOp()->gtOp1), node);
ReplaceWithLclVar(use);
// GT_SWITCH(indexExpression) is now two statements:
// 1. a statement containing 'asg' (for temp = indexExpression)
// 2. and a statement with GT_SWITCH(temp)
assert(node->gtOper == GT_SWITCH);
GenTree* temp = node->AsOp()->gtOp1;
assert(temp->gtOper == GT_LCL_VAR);
unsigned tempLclNum = temp->AsLclVarCommon()->GetLclNum();
var_types tempLclType = temp->TypeGet();
BasicBlock* defaultBB = jumpTab[jumpCnt - 1];
BasicBlock* followingBB = originalSwitchBB->bbNext;
/* Is the number of cases right for a test and jump switch? */
const bool fFirstCaseFollows = (followingBB == jumpTab[0]);
const bool fDefaultFollows = (followingBB == defaultBB);
unsigned minSwitchTabJumpCnt = 2; // table is better than just 2 cmp/jcc
// This means really just a single cmp/jcc (aka a simple if/else)
if (fFirstCaseFollows || fDefaultFollows)
{
minSwitchTabJumpCnt++;
}
#if defined(TARGET_ARM)
// On ARM for small switch tables we will
// generate a sequence of compare and branch instructions
// because the code to load the base of the switch
// table is huge and hideous due to the relocation... :(
minSwitchTabJumpCnt += 2;
#endif // TARGET_ARM
// Once we have the temporary variable, we construct the conditional branch for
// the default case. As stated above, this conditional is being shared between
// both GT_SWITCH lowering code paths.
// This condition is of the form: if (temp > jumpTableLength - 2){ goto jumpTable[jumpTableLength - 1]; }
GenTree* gtDefaultCaseCond = comp->gtNewOperNode(GT_GT, TYP_INT, comp->gtNewLclvNode(tempLclNum, tempLclType),
comp->gtNewIconNode(jumpCnt - 2, genActualType(tempLclType)));
// Make sure we perform an unsigned comparison, just in case the switch index in 'temp'
// is now less than zero 0 (that would also hit the default case).
gtDefaultCaseCond->gtFlags |= GTF_UNSIGNED;
GenTree* gtDefaultCaseJump = comp->gtNewOperNode(GT_JTRUE, TYP_VOID, gtDefaultCaseCond);
gtDefaultCaseJump->gtFlags = node->gtFlags;
LIR::Range condRange = LIR::SeqTree(comp, gtDefaultCaseJump);
switchBBRange.InsertAtEnd(std::move(condRange));
BasicBlock* afterDefaultCondBlock = comp->fgSplitBlockAfterNode(originalSwitchBB, condRange.LastNode());
// afterDefaultCondBlock is now the switch, and all the switch targets have it as a predecessor.
// originalSwitchBB is now a BBJ_NONE, and there is a predecessor edge in afterDefaultCondBlock
// representing the fall-through flow from originalSwitchBB.
assert(originalSwitchBB->bbJumpKind == BBJ_NONE);
assert(originalSwitchBB->bbNext == afterDefaultCondBlock);
assert(afterDefaultCondBlock->bbJumpKind == BBJ_SWITCH);
assert(afterDefaultCondBlock->bbJumpSwt->bbsHasDefault);
assert(afterDefaultCondBlock->isEmpty()); // Nothing here yet.
// The GT_SWITCH code is still in originalSwitchBB (it will be removed later).
// Turn originalSwitchBB into a BBJ_COND.
originalSwitchBB->bbJumpKind = BBJ_COND;
originalSwitchBB->bbJumpDest = jumpTab[jumpCnt - 1];
// Fix the pred for the default case: the default block target still has originalSwitchBB
// as a predecessor, but the fgSplitBlockAfterStatement() moved all predecessors to point
// to afterDefaultCondBlock.
flowList* oldEdge = comp->fgRemoveRefPred(jumpTab[jumpCnt - 1], afterDefaultCondBlock);
comp->fgAddRefPred(jumpTab[jumpCnt - 1], originalSwitchBB, oldEdge);
bool useJumpSequence = jumpCnt < minSwitchTabJumpCnt;
if (TargetOS::IsUnix && TargetArchitecture::IsArm32)
{
// Force using an inlined jumping instead switch table generation.
// Switch jump table is generated with incorrect values in CoreRT case,
// so any large switch will crash after loading to PC any such value.
// I think this is due to the fact that we use absolute addressing
// instead of relative. But in CoreRT is used as a rule relative
// addressing when we generate an executable.
// See also https://github.com/dotnet/runtime/issues/8683
// Also https://github.com/dotnet/coreclr/pull/13197
useJumpSequence = useJumpSequence || comp->IsTargetAbi(CORINFO_CORERT_ABI);
}
// If we originally had 2 unique successors, check to see whether there is a unique
// non-default case, in which case we can eliminate the switch altogether.
// Note that the single unique successor case is handled above.
BasicBlock* uniqueSucc = nullptr;
if (targetCnt == 2)
{
uniqueSucc = jumpTab[0];
noway_assert(jumpCnt >= 2);
for (unsigned i = 1; i < jumpCnt - 1; i++)
{
if (jumpTab[i] != uniqueSucc)
{
uniqueSucc = nullptr;
break;
}
}
}
if (uniqueSucc != nullptr)
{
// If the unique successor immediately follows this block, we have nothing to do -
// it will simply fall-through after we remove the switch, below.
// Otherwise, make this a BBJ_ALWAYS.
// Now, fixup the predecessor links to uniqueSucc. In the original jumpTab:
// jumpTab[i-1] was the default target, which we handled above,
// jumpTab[0] is the first target, and we'll leave that predecessor link.
// Remove any additional predecessor links to uniqueSucc.
for (unsigned i = 1; i < jumpCnt - 1; ++i)
{
assert(jumpTab[i] == uniqueSucc);
(void)comp->fgRemoveRefPred(uniqueSucc, afterDefaultCondBlock);
}
if (afterDefaultCondBlock->bbNext == uniqueSucc)
{
afterDefaultCondBlock->bbJumpKind = BBJ_NONE;
afterDefaultCondBlock->bbJumpDest = nullptr;
}
else
{
afterDefaultCondBlock->bbJumpKind = BBJ_ALWAYS;
afterDefaultCondBlock->bbJumpDest = uniqueSucc;
}
}
// If the number of possible destinations is small enough, we proceed to expand the switch
// into a series of conditional branches, otherwise we follow the jump table based switch
// transformation.
else if (useJumpSequence || comp->compStressCompile(Compiler::STRESS_SWITCH_CMP_BR_EXPANSION, 50))
{
// Lower the switch into a series of compare and branch IR trees.
//
// In this case we will morph the node in the following way:
// 1. Generate a JTRUE statement to evaluate the default case. (This happens above.)
// 2. Start splitting the switch basic block into subsequent basic blocks, each of which will contain
// a statement that is responsible for performing a comparison of the table index and conditional
// branch if equal.
JITDUMP("Lowering switch " FMT_BB ": using compare/branch expansion\n", originalSwitchBB->bbNum);
// We'll use 'afterDefaultCondBlock' for the first conditional. After that, we'll add new
// blocks. If we end up not needing it at all (say, if all the non-default cases just fall through),
// we'll delete it.
bool fUsedAfterDefaultCondBlock = false;
BasicBlock* currentBlock = afterDefaultCondBlock;
LIR::Range* currentBBRange = &LIR::AsRange(currentBlock);
// Walk to entries 0 to jumpCnt - 1. If a case target follows, ignore it and let it fall through.
// If no case target follows, the last one doesn't need to be a compare/branch: it can be an
// unconditional branch.
bool fAnyTargetFollows = false;
for (unsigned i = 0; i < jumpCnt - 1; ++i)
{
assert(currentBlock != nullptr);
// Remove the switch from the predecessor list of this case target's block.
// We'll add the proper new predecessor edge later.
flowList* oldEdge = comp->fgRemoveRefPred(jumpTab[i], afterDefaultCondBlock);
if (jumpTab[i] == followingBB)
{
// This case label follows the switch; let it fall through.
fAnyTargetFollows = true;
continue;
}
// We need a block to put in the new compare and/or branch.
// If we haven't used the afterDefaultCondBlock yet, then use that.
if (fUsedAfterDefaultCondBlock)
{
BasicBlock* newBlock = comp->fgNewBBafter(BBJ_NONE, currentBlock, true);
comp->fgAddRefPred(newBlock, currentBlock); // The fall-through predecessor.
currentBlock = newBlock;
currentBBRange = &LIR::AsRange(currentBlock);
}
else
{
assert(currentBlock == afterDefaultCondBlock);
fUsedAfterDefaultCondBlock = true;
}
// We're going to have a branch, either a conditional or unconditional,
// to the target. Set the target.
currentBlock->bbJumpDest = jumpTab[i];
// Wire up the predecessor list for the "branch" case.
comp->fgAddRefPred(jumpTab[i], currentBlock, oldEdge);
if (!fAnyTargetFollows && (i == jumpCnt - 2))
{
// We're processing the last one, and there is no fall through from any case
// to the following block, so we can use an unconditional branch to the final
// case: there is no need to compare against the case index, since it's
// guaranteed to be taken (since the default case was handled first, above).
currentBlock->bbJumpKind = BBJ_ALWAYS;
}
else
{
// Otherwise, it's a conditional branch. Set the branch kind, then add the
// condition statement.
currentBlock->bbJumpKind = BBJ_COND;
// Now, build the conditional statement for the current case that is
// being evaluated:
// GT_JTRUE
// |__ GT_COND
// |____GT_EQ
// |____ (switchIndex) (The temp variable)
// |____ (ICon) (The actual case constant)
GenTree* gtCaseCond = comp->gtNewOperNode(GT_EQ, TYP_INT, comp->gtNewLclvNode(tempLclNum, tempLclType),
comp->gtNewIconNode(i, tempLclType));
GenTree* gtCaseBranch = comp->gtNewOperNode(GT_JTRUE, TYP_VOID, gtCaseCond);
LIR::Range caseRange = LIR::SeqTree(comp, gtCaseBranch);
currentBBRange->InsertAtEnd(std::move(caseRange));
}
}
if (fAnyTargetFollows)
{
// There is a fall-through to the following block. In the loop
// above, we deleted all the predecessor edges from the switch.
// In this case, we need to add one back.
comp->fgAddRefPred(currentBlock->bbNext, currentBlock);
}
if (!fUsedAfterDefaultCondBlock)
{
// All the cases were fall-through! We don't need this block.
// Convert it from BBJ_SWITCH to BBJ_NONE and unset the BBF_DONT_REMOVE flag
// so fgRemoveBlock() doesn't complain.
JITDUMP("Lowering switch " FMT_BB ": all switch cases were fall-through\n", originalSwitchBB->bbNum);
assert(currentBlock == afterDefaultCondBlock);
assert(currentBlock->bbJumpKind == BBJ_SWITCH);
currentBlock->bbJumpKind = BBJ_NONE;
currentBlock->bbFlags &= ~BBF_DONT_REMOVE;
comp->fgRemoveBlock(currentBlock, /* unreachable */ false); // It's an empty block.
}
}
else
{
// At this point the default case has already been handled and we need to generate a jump
// table based switch or a bit test based switch at the end of afterDefaultCondBlock. Both
// switch variants need the switch value so create the necessary LclVar node here.
GenTree* switchValue = comp->gtNewLclvNode(tempLclNum, tempLclType);
LIR::Range& switchBlockRange = LIR::AsRange(afterDefaultCondBlock);
switchBlockRange.InsertAtEnd(switchValue);
// Try generating a bit test based switch first,
// if that's not possible a jump table based switch will be generated.
if (!TryLowerSwitchToBitTest(jumpTab, jumpCnt, targetCnt, afterDefaultCondBlock, switchValue))
{
JITDUMP("Lowering switch " FMT_BB ": using jump table expansion\n", originalSwitchBB->bbNum);
#ifdef TARGET_64BIT
if (tempLclType != TYP_I_IMPL)
{
// SWITCH_TABLE expects the switch value (the index into the jump table) to be TYP_I_IMPL.
// Note that the switch value is unsigned so the cast should be unsigned as well.
switchValue = comp->gtNewCastNode(TYP_I_IMPL, switchValue, true, TYP_U_IMPL);
switchBlockRange.InsertAtEnd(switchValue);
}
#endif
GenTree* switchTable = comp->gtNewJmpTableNode();
GenTree* switchJump = comp->gtNewOperNode(GT_SWITCH_TABLE, TYP_VOID, switchValue, switchTable);
switchBlockRange.InsertAfter(switchValue, switchTable, switchJump);
// this block no longer branches to the default block
afterDefaultCondBlock->bbJumpSwt->removeDefault();
}
comp->fgInvalidateSwitchDescMapEntry(afterDefaultCondBlock);
}
GenTree* next = node->gtNext;
// Get rid of the GT_SWITCH(temp).
switchBBRange.Remove(node->AsOp()->gtOp1);
switchBBRange.Remove(node);
return next;
}
//------------------------------------------------------------------------
// TryLowerSwitchToBitTest: Attempts to transform a jump table switch into a bit test.
//
// Arguments:
// jumpTable - The jump table
// jumpCount - The number of blocks in the jump table
// targetCount - The number of distinct blocks in the jump table
// bbSwitch - The switch block
// switchValue - A LclVar node that provides the switch value
//
// Return value:
// true if the switch has been lowered to a bit test
//
// Notes:
// If the jump table contains less than 32 (64 on 64 bit targets) entries and there
// are at most 2 distinct jump targets then the jump table can be converted to a word
// of bits where a 0 bit corresponds to one jump target and a 1 bit corresponds to the
// other jump target. Instead of the indirect jump a BT-JCC sequence is used to jump
// to the appropriate target:
// mov eax, 245 ; jump table converted to a "bit table"
// bt eax, ebx ; ebx is supposed to contain the switch value
// jc target1
// target0:
// ...
// target1:
// Such code is both shorter and faster (in part due to the removal of a memory load)
// than the traditional jump table base code. And of course, it also avoids the need
// to emit the jump table itself that can reach up to 256 bytes (for 64 entries).
//
bool Lowering::TryLowerSwitchToBitTest(
BasicBlock* jumpTable[], unsigned jumpCount, unsigned targetCount, BasicBlock* bbSwitch, GenTree* switchValue)
{
#ifndef TARGET_XARCH
// Other architectures may use this if they substitute GT_BT with equivalent code.
return false;
#else
assert(jumpCount >= 2);
assert(targetCount >= 2);
assert(bbSwitch->bbJumpKind == BBJ_SWITCH);
assert(switchValue->OperIs(GT_LCL_VAR));
//
// Quick check to see if it's worth going through the jump table. The bit test switch supports
// up to 2 targets but targetCount also includes the default block so we need to allow 3 targets.
// We'll ensure that there are only 2 targets when building the bit table.
//
if (targetCount > 3)
{
return false;
}
//
// The number of bits in the bit table is the same as the number of jump table entries. But the
// jump table also includes the default target (at the end) so we need to ignore it. The default
// has already been handled by a JTRUE(GT(switchValue, jumpCount - 2)) that LowerSwitch generates.
//
const unsigned bitCount = jumpCount - 1;
if (bitCount > (genTypeSize(TYP_I_IMPL) * 8))
{
return false;
}
//
// Build a bit table where a bit set to 0 corresponds to bbCase0 and a bit set to 1 corresponds to
// bbCase1. Simply use the first block in the jump table as bbCase1, later we can invert the bit
// table and/or swap the blocks if it's beneficial.
//
BasicBlock* bbCase0 = nullptr;
BasicBlock* bbCase1 = jumpTable[0];
size_t bitTable = 1;
for (unsigned bitIndex = 1; bitIndex < bitCount; bitIndex++)
{
if (jumpTable[bitIndex] == bbCase1)
{
bitTable |= (size_t(1) << bitIndex);
}
else if (bbCase0 == nullptr)
{
bbCase0 = jumpTable[bitIndex];
}
else if (jumpTable[bitIndex] != bbCase0)
{
// If it's neither bbCase0 nor bbCase1 then it means we have 3 targets. There can't be more
// than 3 because of the check at the start of the function.
assert(targetCount == 3);
return false;
}
}
//
// One of the case blocks has to follow the switch block. This requirement could be avoided
// by adding a BBJ_ALWAYS block after the switch block but doing that sometimes negatively
// impacts register allocation.
//
if ((bbSwitch->bbNext != bbCase0) && (bbSwitch->bbNext != bbCase1))
{
return false;
}
#ifdef TARGET_64BIT
//
// See if we can avoid a 8 byte immediate on 64 bit targets. If all upper 32 bits are 1
// then inverting the bit table will make them 0 so that the table now fits in 32 bits.
// Note that this does not change the number of bits in the bit table, it just takes
// advantage of the fact that loading a 32 bit immediate into a 64 bit register zero
// extends the immediate value to 64 bit.
//
if (~bitTable <= UINT32_MAX)
{
bitTable = ~bitTable;
std::swap(bbCase0, bbCase1);
}
#endif
//
// Rewire the blocks as needed and figure out the condition to use for JCC.
//
GenCondition bbSwitchCondition;
bbSwitch->bbJumpKind = BBJ_COND;
comp->fgRemoveAllRefPreds(bbCase1, bbSwitch);
comp->fgRemoveAllRefPreds(bbCase0, bbSwitch);
if (bbSwitch->bbNext == bbCase0)
{
// GenCondition::C generates JC so we jump to bbCase1 when the bit is set
bbSwitchCondition = GenCondition::C;
bbSwitch->bbJumpDest = bbCase1;
comp->fgAddRefPred(bbCase0, bbSwitch);
comp->fgAddRefPred(bbCase1, bbSwitch);
}
else
{