-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
lowerxarch.cpp
11826 lines (10115 loc) · 449 KB
/
lowerxarch.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 Lowering for AMD64, x86 XX
XX XX
XX This encapsulates all the logic for lowering trees for the AMD64 XX
XX architecture. For a more detailed view of what is lowering, please XX
XX take a look at Lower.cpp XX
XX XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifdef TARGET_XARCH // This file is only used for xarch
#include "jit.h"
#include "sideeffects.h"
#include "lower.h"
// xarch supports both ROL and ROR instructions so no lowering is required.
void Lowering::LowerRotate(GenTree* tree)
{
ContainCheckShiftRotate(tree->AsOp());
}
//------------------------------------------------------------------------
// LowerStoreLoc: Lower a store of a lclVar
//
// Arguments:
// storeLoc - the local store (GT_STORE_LCL_FLD or GT_STORE_LCL_VAR)
//
// Notes:
// This involves:
// - Handling of contained immediates.
// - Widening some small stores.
//
// Returns:
// Next tree to lower.
//
GenTree* Lowering::LowerStoreLoc(GenTreeLclVarCommon* storeLoc)
{
// Most small locals (the exception is dependently promoted fields) have 4 byte wide stack slots, so
// we can widen the store, if profitable. The widening is only (largely) profitable for 2 byte stores.
// We could widen bytes too but that would only be better when the constant is zero and reused, which
// we presume is not common enough.
//
if (storeLoc->OperIs(GT_STORE_LCL_VAR) && (genTypeSize(storeLoc) == 2) && storeLoc->Data()->IsCnsIntOrI())
{
if (!comp->lvaGetDesc(storeLoc)->lvIsStructField)
{
storeLoc->gtType = TYP_INT;
}
}
if (storeLoc->OperIs(GT_STORE_LCL_FLD))
{
// We should only encounter this for lclVars that are lvDoNotEnregister.
verifyLclFldDoNotEnregister(storeLoc->GetLclNum());
}
ContainCheckStoreLoc(storeLoc);
return storeLoc->gtNext;
}
//------------------------------------------------------------------------
// LowerStoreIndir: Determine addressing mode for an indirection, and whether operands are contained.
//
// Arguments:
// node - The indirect store node (GT_STORE_IND) of interest
//
// Return Value:
// Next node to lower.
//
GenTree* Lowering::LowerStoreIndir(GenTreeStoreInd* node)
{
// Mark all GT_STOREIND nodes to indicate that it is not known
// whether it represents a RMW memory op.
node->SetRMWStatusDefault();
if (!varTypeIsFloating(node))
{
// Perform recognition of trees with the following structure:
// StoreInd(addr, BinOp(expr, GT_IND(addr)))
// to be able to fold this into an instruction of the form
// BINOP [addr], register
// where register is the actual place where 'expr' is computed.
//
// SSE2 doesn't support RMW form of instructions.
if (LowerRMWMemOp(node))
{
return node->gtNext;
}
}
// Optimization: do not unnecessarily zero-extend the result of setcc.
if (varTypeIsByte(node) && (node->Data()->OperIsCompare() || node->Data()->OperIs(GT_SETCC)))
{
node->Data()->ChangeType(TYP_BYTE);
}
ContainCheckStoreIndir(node);
#if defined(FEATURE_HW_INTRINSICS)
if (comp->IsBaselineVector512IsaSupportedOpportunistically() ||
comp->compOpportunisticallyDependsOn(InstructionSet_AVX2))
{
if (!node->Data()->IsCnsVec())
{
return node->gtNext;
}
if (!node->Data()->AsVecCon()->TypeIs(TYP_SIMD32, TYP_SIMD64))
{
return node->gtNext;
}
if (node->Data()->IsVectorAllBitsSet() || node->Data()->IsVectorZero())
{
// To avoid some unexpected regression, this optimization only applies to non-all 1/0 constant vectors.
return node->gtNext;
}
TryCompressConstVecData(node);
}
#endif
return node->gtNext;
}
//----------------------------------------------------------------------------------------------
// Lowering::TryLowerMulWithConstant:
// Lowers a tree MUL(X, CNS) to LSH(X, CNS_SHIFT)
// or
// Lowers a tree MUL(X, CNS) to SUB(LSH(X, CNS_SHIFT), X)
// or
// Lowers a tree MUL(X, CNS) to ADD(LSH(X, CNS_SHIFT), X)
//
// Arguments:
// node - GT_MUL node of integral type
//
// Return Value:
// Returns the replacement node if one is created else nullptr indicating no replacement
//
// Notes:
// Performs containment checks on the replacement node if one is created
GenTree* Lowering::TryLowerMulWithConstant(GenTreeOp* node)
{
assert(node->OperIs(GT_MUL));
// Do not do these optimizations when min-opts enabled.
if (comp->opts.MinOpts())
return nullptr;
if (!varTypeIsIntegral(node))
return nullptr;
if (node->gtOverflow())
return nullptr;
GenTree* op1 = node->gtGetOp1();
GenTree* op2 = node->gtGetOp2();
if (op1->isContained() || op2->isContained())
return nullptr;
if (!op2->IsCnsIntOrI())
return nullptr;
GenTreeIntConCommon* cns = op2->AsIntConCommon();
ssize_t cnsVal = cns->IconValue();
// Use GT_LEA if cnsVal is 3, 5, or 9.
// These are handled in codegen.
if (cnsVal == 3 || cnsVal == 5 || cnsVal == 9)
return nullptr;
// Use GT_LSH if cnsVal is a power of two.
if (isPow2(cnsVal))
{
// Use shift for constant multiply when legal
unsigned int shiftAmount = genLog2(static_cast<uint64_t>(static_cast<size_t>(cnsVal)));
cns->SetIconValue(shiftAmount);
node->ChangeOper(GT_LSH);
ContainCheckShiftRotate(node);
return node;
}
// We do not do this optimization in X86 as it is not recommended.
#if TARGET_X86
return nullptr;
#endif // TARGET_X86
ssize_t cnsValPlusOne = cnsVal + 1;
ssize_t cnsValMinusOne = cnsVal - 1;
bool useSub = isPow2(cnsValPlusOne);
if (!useSub && !isPow2(cnsValMinusOne))
return nullptr;
LIR::Use op1Use(BlockRange(), &node->gtOp1, node);
op1 = ReplaceWithLclVar(op1Use);
if (useSub)
{
cnsVal = cnsValPlusOne;
node->ChangeOper(GT_SUB);
}
else
{
cnsVal = cnsValMinusOne;
node->ChangeOper(GT_ADD);
}
unsigned int shiftAmount = genLog2(static_cast<uint64_t>(static_cast<size_t>(cnsVal)));
cns->SetIconValue(shiftAmount);
node->gtOp1 = comp->gtNewOperNode(GT_LSH, node->gtType, op1, cns);
node->gtOp2 = comp->gtClone(op1);
BlockRange().Remove(op1);
BlockRange().Remove(cns);
BlockRange().InsertBefore(node, node->gtGetOp2());
BlockRange().InsertBefore(node, cns);
BlockRange().InsertBefore(node, op1);
BlockRange().InsertBefore(node, node->gtGetOp1());
ContainCheckBinary(node);
ContainCheckShiftRotate(node->gtGetOp1()->AsOp());
return node;
}
//------------------------------------------------------------------------
// LowerMul: Lower a GT_MUL/GT_MULHI/GT_MUL_LONG node.
//
// Currently only performs containment checks.
//
// Arguments:
// mul - The node to lower
//
// Return Value:
// The next node to lower.
//
GenTree* Lowering::LowerMul(GenTreeOp* mul)
{
assert(mul->OperIsMul());
if (mul->OperIs(GT_MUL))
{
GenTree* replacementNode = TryLowerMulWithConstant(mul);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
ContainCheckMul(mul);
return mul->gtNext;
}
//------------------------------------------------------------------------
// LowerBinaryArithmetic: lowers the given binary arithmetic node.
//
// Recognizes opportunities for using target-independent "combined" nodes
// Performs containment checks.
//
// Arguments:
// node - the arithmetic node to lower
//
// Returns:
// The next node to lower.
//
GenTree* Lowering::LowerBinaryArithmetic(GenTreeOp* binOp)
{
#ifdef FEATURE_HW_INTRINSICS
if (comp->opts.OptimizationEnabled() && varTypeIsIntegral(binOp))
{
if (binOp->OperIs(GT_AND))
{
GenTree* replacementNode = TryLowerAndOpToAndNot(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
replacementNode = TryLowerAndOpToResetLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
replacementNode = TryLowerAndOpToExtractLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
else if (binOp->OperIs(GT_XOR))
{
GenTree* replacementNode = TryLowerXorOpToGetMaskUpToLowestSetBit(binOp);
if (replacementNode != nullptr)
{
return replacementNode->gtNext;
}
}
}
#endif
ContainCheckBinary(binOp);
return binOp->gtNext;
}
//------------------------------------------------------------------------
// LowerBlockStore: Lower a block store node
//
// Arguments:
// blkNode - The block store node to lower
//
void Lowering::LowerBlockStore(GenTreeBlk* blkNode)
{
TryCreateAddrMode(blkNode->Addr(), false, blkNode);
GenTree* dstAddr = blkNode->Addr();
GenTree* src = blkNode->Data();
unsigned size = blkNode->Size();
if (blkNode->OperIsInitBlkOp())
{
#ifdef DEBUG
// Use BlkOpKindLoop for more cases under stress mode
if (comp->compStressCompile(Compiler::STRESS_STORE_BLOCK_UNROLLING, 50) && blkNode->OperIs(GT_STORE_BLK) &&
((blkNode->GetLayout()->GetSize() % TARGET_POINTER_SIZE) == 0) && src->IsIntegralConst(0))
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindLoop;
return;
}
#endif
if (src->OperIs(GT_INIT_VAL))
{
src->SetContained();
src = src->AsUnOp()->gtGetOp1();
}
if (size <= comp->getUnrollThreshold(Compiler::UnrollKind::Memset))
{
if (!src->OperIs(GT_CNS_INT))
{
// TODO-CQ: We could unroll even when the initialization value is not a constant
// by inserting a MUL init, 0x01010101 instruction. We need to determine if the
// extra latency that MUL introduces isn't worse that rep stosb. Likely not.
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
}
else
{
// The fill value of an initblk is interpreted to hold a
// value of (unsigned int8) however a constant of any size
// may practically reside on the evaluation stack. So extract
// the lower byte out of the initVal constant and replicate
// it to a larger constant whose size is sufficient to support
// the largest width store of the desired inline expansion.
ssize_t fill = src->AsIntCon()->IconValue() & 0xFF;
const bool canUseSimd = !blkNode->IsOnHeapAndContainsReferences() && comp->IsBaselineSimdIsaSupported();
if (size > comp->getUnrollThreshold(Compiler::UnrollKind::Memset, canUseSimd))
{
// It turns out we can't use SIMD so the default threshold is too big
goto TOO_BIG_TO_UNROLL;
}
if (canUseSimd && (size >= XMM_REGSIZE_BYTES))
{
// We're going to use SIMD (and only SIMD - we don't want to occupy a GPR register
// with a fill value just to handle the remainder when we can do that with
// an overlapped SIMD load).
src->SetContained();
}
else if (fill == 0)
{
// Leave as is - zero shouldn't be contained when we don't use SIMD.
}
#ifdef TARGET_AMD64
else if (size >= REGSIZE_BYTES)
{
fill *= 0x0101010101010101LL;
src->gtType = TYP_LONG;
}
#endif
else
{
fill *= 0x01010101;
}
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll;
src->AsIntCon()->SetIconValue(fill);
ContainBlockStoreAddress(blkNode, size, dstAddr, nullptr);
}
}
else
{
TOO_BIG_TO_UNROLL:
if (blkNode->IsZeroingGcPointersOnHeap())
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindLoop;
}
else
{
#ifdef TARGET_AMD64
LowerBlockStoreAsHelperCall(blkNode);
return;
#else
// TODO-X86-CQ: Investigate whether a helper call would be beneficial on x86
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
#endif
}
}
}
else
{
assert(src->OperIs(GT_IND, GT_LCL_VAR, GT_LCL_FLD));
src->SetContained();
if (src->OperIs(GT_LCL_VAR))
{
// TODO-1stClassStructs: for now we can't work with STORE_BLOCK source in register.
const unsigned srcLclNum = src->AsLclVar()->GetLclNum();
comp->lvaSetVarDoNotEnregister(srcLclNum DEBUGARG(DoNotEnregisterReason::StoreBlkSrc));
}
ClassLayout* layout = blkNode->GetLayout();
bool doCpObj = layout->HasGCPtr();
unsigned copyBlockUnrollLimit = comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy, false);
#ifndef JIT32_GCENCODER
if (doCpObj && (size <= copyBlockUnrollLimit))
{
// No write barriers are needed on the stack.
// If the layout is byref-like, then we know it must live on the stack.
if (dstAddr->OperIs(GT_LCL_ADDR) || layout->IsStackOnly(comp))
{
// If the size is small enough to unroll then we need to mark the block as non-interruptible
// to actually allow unrolling. The generated code does not report GC references loaded in the
// temporary register(s) used for copying. This is not supported for the JIT32_GCENCODER.
doCpObj = false;
blkNode->gtBlkOpGcUnsafe = true;
}
}
#endif
if (doCpObj)
{
// Try to use bulk copy helper
if (TryLowerBlockStoreAsGcBulkCopyCall(blkNode))
{
return;
}
assert((dstAddr->TypeGet() == TYP_BYREF) || (dstAddr->TypeGet() == TYP_I_IMPL));
// If we have a long enough sequence of slots that do not require write barriers then
// we can use REP MOVSD/Q instead of a sequence of MOVSD/Q instructions. According to the
// Intel Manual, the sweet spot for small structs is between 4 to 12 slots of size where
// the entire operation takes 20 cycles and encodes in 5 bytes (loading RCX and REP MOVSD/Q).
unsigned nonGCSlots = 0;
if (dstAddr->OperIs(GT_LCL_ADDR) || layout->IsStackOnly(comp))
{
// If the destination is on the stack then no write barriers are needed.
nonGCSlots = layout->GetSlotCount();
}
else
{
// Otherwise a write barrier is needed for every GC pointer in the layout
// so we need to check if there's a long enough sequence of non-GC slots.
unsigned slots = layout->GetSlotCount();
for (unsigned i = 0; i < slots; i++)
{
if (layout->IsGCPtr(i))
{
nonGCSlots = 0;
}
else
{
nonGCSlots++;
if (nonGCSlots >= CPOBJ_NONGC_SLOTS_LIMIT)
{
break;
}
}
}
}
if (nonGCSlots >= CPOBJ_NONGC_SLOTS_LIMIT)
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindCpObjRepInstr;
}
else
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindCpObjUnroll;
}
}
else if (blkNode->OperIs(GT_STORE_BLK) &&
(size <= comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy, !layout->HasGCPtr())))
{
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindUnroll;
if (src->OperIs(GT_IND))
{
ContainBlockStoreAddress(blkNode, size, src->AsIndir()->Addr(), src->AsIndir());
}
ContainBlockStoreAddress(blkNode, size, dstAddr, nullptr);
}
else
{
assert(blkNode->OperIs(GT_STORE_BLK));
#ifdef TARGET_AMD64
LowerBlockStoreAsHelperCall(blkNode);
return;
#else
// TODO-X86-CQ: Investigate whether a helper call would be beneficial on x86
blkNode->gtBlkOpKind = GenTreeBlk::BlkOpKindRepInstr;
#endif
}
}
assert(blkNode->gtBlkOpKind != GenTreeBlk::BlkOpKindInvalid);
}
//------------------------------------------------------------------------
// ContainBlockStoreAddress: Attempt to contain an address used by an unrolled block store.
//
// Arguments:
// blkNode - the block store node
// size - the block size
// addr - the address node to try to contain
// addrParent - the parent of addr, in case this is checking containment of the source address.
//
void Lowering::ContainBlockStoreAddress(GenTreeBlk* blkNode, unsigned size, GenTree* addr, GenTree* addrParent)
{
assert(blkNode->OperIs(GT_STORE_BLK) && (blkNode->gtBlkOpKind == GenTreeBlk::BlkOpKindUnroll));
assert(size < INT32_MAX);
if (addr->OperIs(GT_LCL_ADDR) && IsContainableLclAddr(addr->AsLclFld(), size))
{
addr->SetContained();
return;
}
if (!addr->OperIsAddrMode() && !TryCreateAddrMode(addr, true, blkNode))
{
return;
}
GenTreeAddrMode* addrMode = addr->AsAddrMode();
// On x64 the address mode displacement is signed so it must not exceed INT32_MAX. This check is
// an approximation since the last displacement we generate in an unrolled block operation can be
// up to 16 bytes lower than offset + size. But offsets large enough to hit this case are likely
// to be extremely rare for this to ever be a CQ issue.
// On x86 this shouldn't be needed but then again, offsets large enough to hit this are rare.
if (addrMode->Offset() > (INT32_MAX - static_cast<int>(size)))
{
return;
}
// Note that the parentNode is always the block node, even if we're dealing with the source address.
// The source address is not directly used by the block node but by an IND node and that IND node is
// always contained.
if (!IsInvariantInRange(addrMode, blkNode, addrParent))
{
return;
}
addrMode->SetContained();
}
//------------------------------------------------------------------------
// LowerPutArgStkOrSplit: Lower a GT_PUTARG_STK/GT_PUTARG_SPLIT.
//
// Arguments:
// putArgNode - The node of interest
//
void Lowering::LowerPutArgStkOrSplit(GenTreePutArgStk* putArgNode)
{
assert(putArgNode->OperIs(GT_PUTARG_STK)); // No split args on XArch.
LowerPutArgStk(putArgNode);
}
//------------------------------------------------------------------------
// LowerPutArgStk: Lower a GT_PUTARG_STK.
//
// Arguments:
// putArgStk - The node of interest
//
void Lowering::LowerPutArgStk(GenTreePutArgStk* putArgStk)
{
GenTree* src = putArgStk->Data();
bool srcIsLocal = src->OperIsLocalRead();
if (src->OperIs(GT_FIELD_LIST))
{
#ifdef TARGET_X86
GenTreeFieldList* fieldList = src->AsFieldList();
// The code generator will push these fields in reverse order by offset. Reorder the list here s.t. the order
// of uses is visible to LSRA.
assert(fieldList->Uses().IsSorted());
fieldList->Uses().Reverse();
// Containment checks.
for (GenTreeFieldList::Use& use : fieldList->Uses())
{
GenTree* const fieldNode = use.GetNode();
const var_types fieldType = use.GetType();
assert(!fieldNode->TypeIs(TYP_LONG));
// For x86 we must mark all integral fields as contained or reg-optional, and handle them
// accordingly in code generation, since we may have up to 8 fields, which cannot all be in
// registers to be consumed atomically by the call.
if (varTypeIsIntegralOrI(fieldNode))
{
if (IsContainableImmed(putArgStk, fieldNode))
{
MakeSrcContained(putArgStk, fieldNode);
}
else if (IsContainableMemoryOp(fieldNode) && IsSafeToContainMem(putArgStk, fieldNode))
{
MakeSrcContained(putArgStk, fieldNode);
}
else
{
// For the case where we cannot directly push the value, if we run out of registers,
// it would be better to defer computation until we are pushing the arguments rather
// than spilling, but this situation is not all that common, as most cases of FIELD_LIST
// are promoted structs, which do not not have a large number of fields, and of those
// most are lclVars or copy-propagated constants.
fieldNode->SetRegOptional();
}
}
}
// Set the copy kind.
// TODO-X86-CQ: Even if we are using push, if there are contiguous floating point fields, we should
// adjust the stack once for those fields. The latter is really best done in code generation, but
// this tuning should probably be undertaken as a whole.
// Also, if there are floating point fields, it may be better to use the "Unroll" mode
// of copying the struct as a whole, if the fields are not register candidates.
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
#endif // TARGET_X86
return;
}
#ifdef FEATURE_PUT_STRUCT_ARG_STK
if (src->TypeIs(TYP_STRUCT))
{
assert(src->OperIs(GT_BLK) || src->OperIsLocalRead());
ClassLayout* layout = src->GetLayout(comp);
var_types regType = layout->GetRegisterType();
if (regType == TYP_UNDEF)
{
// In case of a CpBlk we could use a helper call. In case of putarg_stk we
// can't do that since the helper call could kill some already set up outgoing args.
// TODO-Amd64-Unix: converge the code for putarg_stk with cpyblk/cpyobj.
// The cpyXXXX code is rather complex and this could cause it to be more complex, but
// it might be the right thing to do.
// If possible, widen the load, this results in more compact code.
unsigned loadSize = srcIsLocal ? roundUp(layout->GetSize(), TARGET_POINTER_SIZE) : layout->GetSize();
putArgStk->SetArgLoadSize(loadSize);
// TODO-X86-CQ: The helper call either is not supported on x86 or required more work
// (I don't know which).
if (!layout->HasGCPtr())
{
#ifdef TARGET_X86
// Codegen for "Kind::Push" will always load bytes in TARGET_POINTER_SIZE
// chunks. As such, we'll only use this path for correctly-sized sources.
if ((loadSize < XMM_REGSIZE_BYTES) && ((loadSize % TARGET_POINTER_SIZE) == 0))
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
}
else
#endif // TARGET_X86
if (loadSize <= comp->getUnrollThreshold(Compiler::UnrollKind::Memcpy))
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Unroll;
}
else
{
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::RepInstr;
}
}
else // There are GC pointers.
{
#ifdef TARGET_X86
// On x86, we must use `push` to store GC references to the stack in order for the emitter to
// properly update the function's GC info. These `putargstk` nodes will generate a sequence of
// `push` instructions.
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::Push;
#else // !TARGET_X86
putArgStk->gtPutArgStkKind = GenTreePutArgStk::Kind::PartialRepInstr;
#endif // !TARGET_X86
}
if (src->OperIs(GT_LCL_VAR))
{
comp->lvaSetVarDoNotEnregister(src->AsLclVar()->GetLclNum()
DEBUGARG(DoNotEnregisterReason::IsStructArg));
}
// Always mark the OBJ/LCL_VAR/LCL_FLD as contained trees.
MakeSrcContained(putArgStk, src);
}
else
{
// The ABI allows upper bits of small struct args to remain undefined,
// so if possible, widen the load to avoid the sign/zero-extension.
if (varTypeIsSmall(regType) && srcIsLocal)
{
assert(genTypeSize(TYP_INT) <= putArgStk->GetStackByteSize());
regType = TYP_INT;
}
src->ChangeType(regType);
if (src->OperIs(GT_BLK))
{
src->SetOper(GT_IND);
LowerIndir(src->AsIndir());
}
}
}
if (src->TypeIs(TYP_STRUCT))
{
return;
}
#endif // FEATURE_PUT_STRUCT_ARG_STK
assert(!src->TypeIs(TYP_STRUCT));
// If the child of GT_PUTARG_STK is a constant, we don't need a register to
// move it to memory (stack location).
//
// On AMD64, we don't want to make 0 contained, because we can generate smaller code
// by zeroing a register and then storing it. E.g.:
// xor rdx, rdx
// mov gword ptr [rsp+28H], rdx
// is 2 bytes smaller than:
// mov gword ptr [rsp+28H], 0
//
// On x86, we push stack arguments; we don't use 'mov'. So:
// push 0
// is 1 byte smaller than:
// xor rdx, rdx
// push rdx
if (IsContainableImmed(putArgStk, src)
#if defined(TARGET_AMD64)
&& !src->IsIntegralConst(0)
#endif // TARGET_AMD64
)
{
MakeSrcContained(putArgStk, src);
}
#ifdef TARGET_X86
else if (genTypeSize(src) == TARGET_POINTER_SIZE)
{
// We can use "src" directly from memory with "push [mem]".
TryMakeSrcContainedOrRegOptional(putArgStk, src);
}
#endif // TARGET_X86
}
/* Lower GT_CAST(srcType, DstType) nodes.
*
* Casts from small int type to float/double are transformed as follows:
* GT_CAST(byte, float/double) = GT_CAST(GT_CAST(byte, int32), float/double)
* GT_CAST(sbyte, float/double) = GT_CAST(GT_CAST(sbyte, int32), float/double)
* GT_CAST(int16, float/double) = GT_CAST(GT_CAST(int16, int32), float/double)
* GT_CAST(uint16, float/double) = GT_CAST(GT_CAST(uint16, int32), float/double)
*
* SSE2 conversion instructions operate on signed integers. casts from Uint32/Uint64
* are morphed as follows by front-end and hence should not be seen here.
* GT_CAST(uint32, float/double) = GT_CAST(GT_CAST(uint32, long), float/double)
* GT_CAST(uint64, float) = GT_CAST(GT_CAST(uint64, double), float)
*
*
* Similarly casts from float/double to a smaller int type are transformed as follows:
* GT_CAST(float/double, byte) = GT_CAST(GT_CAST(float/double, int32), byte)
* GT_CAST(float/double, sbyte) = GT_CAST(GT_CAST(float/double, int32), sbyte)
* GT_CAST(float/double, int16) = GT_CAST(GT_CAST(double/double, int32), int16)
* GT_CAST(float/double, uint16) = GT_CAST(GT_CAST(double/double, int32), uint16)
*
* SSE2 has instructions to convert a float/double vlaue into a signed 32/64-bit
* integer. The above transformations help us to leverage those instructions.
*
* Note that for the following conversions we still depend on helper calls and
* don't expect to see them here.
* i) GT_CAST(float/double, uint64)
* ii) GT_CAST(float/double, int type with overflow detection)
*
* TODO-XArch-CQ: (Low-pri): Jit64 generates in-line code of 8 instructions for (i) above.
* There are hardly any occurrences of this conversion operation in platform
* assemblies or in CQ perf benchmarks (1 occurrence in corelib, microsoft.jscript,
* 1 occurrence in Roslyn and no occurrences in system, system.core, system.numerics
* system.windows.forms, scimark, fractals, bio mums). If we ever find evidence that
* doing this optimization is a win, should consider generating in-lined code.
*/
GenTree* Lowering::LowerCast(GenTree* tree)
{
assert(tree->OperGet() == GT_CAST);
GenTree* castOp = tree->AsCast()->CastOp();
var_types castToType = tree->CastToType();
var_types dstType = castToType;
var_types srcType = castOp->TypeGet();
var_types tmpType = TYP_UNDEF;
// force the srcType to unsigned if GT_UNSIGNED flag is set
if (tree->gtFlags & GTF_UNSIGNED)
{
srcType = varTypeToUnsigned(srcType);
}
// We should never see the following casts as they are expected to be lowered
// appropriately or converted into helper calls by front-end.
// srcType = float/double castToType = * and overflow detecting cast
// Reason: must be converted to a helper call
// srcType = float/double, castToType = ulong
// Reason: must be converted to a helper call
// srcType = uint castToType = float/double
// Reason: uint -> float/double = uint -> long -> float/double
// srcType = ulong castToType = float
// Reason: ulong -> float = ulong -> double -> float
if (varTypeIsFloating(srcType))
{
noway_assert(!tree->gtOverflow());
assert(castToType != TYP_ULONG || comp->canUseEvexEncoding());
}
else if (srcType == TYP_UINT)
{
noway_assert(!varTypeIsFloating(castToType));
}
else if (srcType == TYP_ULONG)
{
assert(castToType != TYP_FLOAT || comp->canUseEvexEncoding());
}
#if defined(TARGET_AMD64)
// Handle saturation logic for X64
if (varTypeIsFloating(srcType) && varTypeIsIntegral(dstType) && !varTypeIsSmall(dstType))
{
// We should have filtered out float -> long conversion and
// converted it to float -> double -> long conversion.
assert((dstType != TYP_LONG) || (srcType != TYP_FLOAT));
// we should have handled overflow cases in morph itself
assert(!tree->gtOverflow());
CorInfoType fieldType = (srcType == TYP_DOUBLE) ? CORINFO_TYPE_DOUBLE : CORINFO_TYPE_FLOAT;
GenTree* castOutput = nullptr;
LIR::Use castOpUse(BlockRange(), &(tree->AsCast()->CastOp()), tree);
ReplaceWithLclVar(castOpUse);
castOp = tree->AsCast()->CastOp();
bool isV512Supported = false;
/*The code below is to introduce saturating conversions on X86/X64.
The C# equivalence of the code is given below -->
// Replace QNaN and SNaN with Zero
op1 = Avx512F.Fixup(op1, op1, Vector128.Create<long>(0x88), 0);
// Convert from double to long, replacing any values that were greater than or equal to MaxValue
with MaxValue
// Values that were less than or equal to MinValue will already be MinValue
return Vector128.ConditionalSelect(
Vector128.LessThan(op1, Vector128.Create<double>(long.MaxValue)).AsInt64(),
Avx512DQ.VL.ConvertToVector128Int64(op1),
Vector128.Create<long>(long.MaxValue)
);
*/
if (comp->compIsEvexOpportunisticallySupported(isV512Supported))
{
// Clone the cast operand for usage.
GenTree* op1Clone1 = comp->gtClone(castOp);
BlockRange().InsertAfter(castOp, op1Clone1);
// Generate the control table for VFIXUPIMMSD
// The behavior we want is to saturate negative values to 0.
GenTreeVecCon* tbl = comp->gtNewVconNode(TYP_SIMD16);
tbl->gtSimdVal.i32[0] = (varTypeIsUnsigned(dstType)) ? 0x08080088 : 0x00000088;
BlockRange().InsertAfter(op1Clone1, tbl);
// get a zero int node for control table
GenTree* ctrlByte = comp->gtNewIconNode(0);
BlockRange().InsertAfter(tbl, ctrlByte);
NamedIntrinsic fixupHwIntrinsicID = !isV512Supported ? NI_AVX10v1_FixupScalar : NI_AVX512F_FixupScalar;
if (varTypeIsUnsigned(dstType))
{
// run vfixupimmsd base on table and no flags reporting
GenTree* oper1 = comp->gtNewSimdHWIntrinsicNode(TYP_SIMD16, castOp, op1Clone1, tbl, ctrlByte,
fixupHwIntrinsicID, fieldType, 16);
BlockRange().InsertAfter(ctrlByte, oper1);
LowerNode(oper1);
// Convert to scalar
// Here, we try to insert a Vector128 to Scalar node so that the input
// can be provided to the scalar cast
GenTree* oper2 = comp->gtNewSimdHWIntrinsicNode(srcType, oper1, NI_Vector128_ToScalar, fieldType, 16);
BlockRange().InsertAfter(oper1, oper2);
LowerNode(oper2);
castOutput = comp->gtNewCastNode(genActualType(dstType), oper2, false, dstType);
BlockRange().InsertAfter(oper2, castOutput);
}
else
{
CorInfoType destFieldType = (dstType == TYP_INT) ? CORINFO_TYPE_INT : CORINFO_TYPE_LONG;
ssize_t actualMaxVal = (dstType == TYP_INT) ? INT32_MAX : INT64_MAX;
// run vfixupimmsd base on table and no flags reporting
GenTree* fixupVal = comp->gtNewSimdHWIntrinsicNode(TYP_SIMD16, castOp, op1Clone1, tbl, ctrlByte,
fixupHwIntrinsicID, fieldType, 16);
BlockRange().InsertAfter(ctrlByte, fixupVal);
LowerNode(fixupVal);
// get the max value vector
GenTree* maxValScalar = (srcType == TYP_DOUBLE)
? comp->gtNewDconNodeD(static_cast<double>(actualMaxVal))
: comp->gtNewDconNodeF(static_cast<float>(actualMaxVal));
GenTree* maxVal = comp->gtNewSimdCreateBroadcastNode(TYP_SIMD16, maxValScalar, fieldType, 16);
BlockRange().InsertAfter(fixupVal, maxVal);
GenTree* maxValDstTypeScalar = (dstType == TYP_INT) ? comp->gtNewIconNode(actualMaxVal, dstType)
: comp->gtNewLconNode(actualMaxVal);
GenTree* maxValDstType =
comp->gtNewSimdCreateBroadcastNode(TYP_SIMD16, maxValDstTypeScalar, destFieldType, 16);
BlockRange().InsertAfter(maxVal, maxValDstType);
// usage 1 --> compare with max value of integer
GenTree* compMask = comp->gtNewSimdCmpOpNode(GT_GE, TYP_SIMD16, fixupVal, maxVal, fieldType, 16);
BlockRange().InsertAfter(maxValDstType, compMask);
// convert fixupVal to local variable and clone it for further use
LIR::Use fixupValUse(BlockRange(), &(compMask->AsHWIntrinsic()->Op(1)), compMask);
ReplaceWithLclVar(fixupValUse);
fixupVal = compMask->AsHWIntrinsic()->Op(1);
GenTree* fixupValClone = comp->gtClone(fixupVal);
LowerNode(compMask);
BlockRange().InsertAfter(fixupVal, fixupValClone);
GenTree* FixupValCloneScalar =
comp->gtNewSimdHWIntrinsicNode(srcType, fixupValClone, NI_Vector128_ToScalar, fieldType, 16);
BlockRange().InsertAfter(compMask, FixupValCloneScalar);
LowerNode(FixupValCloneScalar);
// cast it
GenTreeCast* newCast = comp->gtNewCastNode(dstType, FixupValCloneScalar, false, dstType);
BlockRange().InsertAfter(FixupValCloneScalar, newCast);
GenTree* newTree = comp->gtNewSimdCreateBroadcastNode(TYP_SIMD16, newCast, destFieldType, 16);
BlockRange().InsertAfter(newCast, newTree);
LowerNode(newTree);
// usage 2 --> use thecompared mask with input value and max value to blend
GenTree* control = comp->gtNewIconNode(0xCA); // (B & A) | (C & ~A)
BlockRange().InsertAfter(newTree, control);
GenTree* cndSelect = comp->gtNewSimdTernaryLogicNode(TYP_SIMD16, compMask, maxValDstType, newTree,
control, destFieldType, 16);
BlockRange().InsertAfter(control, cndSelect);
LowerNode(cndSelect);
castOutput =
comp->gtNewSimdHWIntrinsicNode(dstType, cndSelect, NI_Vector128_ToScalar, destFieldType, 16);
BlockRange().InsertAfter(cndSelect, castOutput);
LowerNode(castOutput);
}
}