-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
morph.cpp
15602 lines (13553 loc) · 555 KB
/
morph.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 Morph XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#include "allocacheck.h" // for alloca
//-------------------------------------------------------------
// fgMorphInit: prepare for running the morph phases
//
// Returns:
// suitable phase status
//
PhaseStatus Compiler::fgMorphInit()
{
bool madeChanges = false;
// We could allow ESP frames. Just need to reserve space for
// pushing EBP if the method becomes an EBP-frame after an edit.
// Note that requiring a EBP Frame disallows double alignment. Thus if we change this
// we either have to disallow double alignment for E&C some other way or handle it in EETwain.
if (opts.compDbgEnC)
{
codeGen->setFramePointerRequired(true);
// We don't care about localloc right now. If we do support it,
// EECodeManager::FixContextForEnC() needs to handle it smartly
// in case the localloc was actually executed.
//
// compLocallocUsed = true;
}
fgAvailableOutgoingArgTemps = hashBv::Create(this);
// Insert call to class constructor as the first basic block if
// we were asked to do so.
if (info.compCompHnd->initClass(nullptr /* field */, nullptr /* method */,
impTokenLookupContextHandle /* context */) &
CORINFO_INITCLASS_USE_HELPER)
{
fgNewStmtAtBeg(fgFirstBB, fgInitThisClass());
madeChanges = true;
}
#ifdef DEBUG
if (opts.compGcChecks)
{
for (unsigned i = 0; i < info.compArgsCount; i++)
{
if (lvaGetDesc(i)->TypeGet() == TYP_REF)
{
// confirm that the argument is a GC pointer (for debugging (GC stress))
GenTree* op = gtNewLclvNode(i, TYP_REF);
op = gtNewHelperCallNode(CORINFO_HELP_CHECK_OBJ, TYP_VOID, op);
fgNewStmtAtBeg(fgFirstBB, op);
madeChanges = true;
if (verbose)
{
printf("\ncompGcChecks tree:\n");
gtDispTree(op);
}
}
}
}
#endif // DEBUG
#if defined(DEBUG) && defined(TARGET_XARCH)
if (opts.compStackCheckOnRet)
{
lvaReturnSpCheck = lvaGrabTempWithImplicitUse(false DEBUGARG("ReturnSpCheck"));
lvaSetVarDoNotEnregister(lvaReturnSpCheck, DoNotEnregisterReason::ReturnSpCheck);
lvaGetDesc(lvaReturnSpCheck)->lvType = TYP_I_IMPL;
madeChanges = true;
}
#endif // defined(DEBUG) && defined(TARGET_XARCH)
#if defined(DEBUG) && defined(TARGET_X86)
if (opts.compStackCheckOnCall)
{
lvaCallSpCheck = lvaGrabTempWithImplicitUse(false DEBUGARG("CallSpCheck"));
lvaSetVarDoNotEnregister(lvaCallSpCheck, DoNotEnregisterReason::CallSpCheck);
lvaGetDesc(lvaCallSpCheck)->lvType = TYP_I_IMPL;
madeChanges = true;
}
#endif // defined(DEBUG) && defined(TARGET_X86)
return madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING;
}
// Convert the given node into a call to the specified helper passing
// the given argument list.
//
// Tries to fold constants and also adds an edge for overflow exception
// returns the morphed tree
GenTree* Compiler::fgMorphCastIntoHelper(GenTree* tree, int helper, GenTree* oper)
{
GenTree* result;
/* If the operand is a constant, we'll try to fold it */
if (oper->OperIsConst())
{
GenTree* oldTree = tree;
tree = gtFoldExprConst(tree); // This may not fold the constant (NaN ...)
if (tree != oldTree)
{
return fgMorphTree(tree);
}
else if (tree->OperIsConst())
{
return fgMorphConst(tree);
}
// assert that oper is unchanged and that it is still a GT_CAST node
noway_assert(tree->AsCast()->CastOp() == oper);
noway_assert(tree->gtOper == GT_CAST);
}
result = fgMorphIntoHelperCall(tree, helper, true /* morphArgs */, oper);
assert(result == tree);
return result;
}
class SharedTempsScope
{
Compiler* m_comp;
ArrayStack<unsigned> m_usedSharedTemps;
ArrayStack<unsigned>* m_prevUsedSharedTemps;
public:
SharedTempsScope(Compiler* comp)
: m_comp(comp)
, m_usedSharedTemps(comp->getAllocator(CMK_CallArgs))
, m_prevUsedSharedTemps(comp->fgUsedSharedTemps)
{
comp->fgUsedSharedTemps = &m_usedSharedTemps;
}
~SharedTempsScope()
{
m_comp->fgUsedSharedTemps = m_prevUsedSharedTemps;
for (int i = 0; i < m_usedSharedTemps.Height(); i++)
{
m_comp->fgAvailableOutgoingArgTemps->setBit((indexType)m_usedSharedTemps.Top(i));
}
}
};
//------------------------------------------------------------------------
// fgMorphIntoHelperCall:
// Morph a node into a helper call, specifying up to two args and whether to
// call fgMorphArgs after.
//
// Parameters:
// tree - The node that is changed. This must be a large node.
// helper - The helper.
// morphArgs - Whether to call fgMorphArgs after adding the args.
// arg1, arg2 - Optional arguments to add to the call.
//
// Return value:
// The call (which is the same as `tree`).
//
GenTree* Compiler::fgMorphIntoHelperCall(GenTree* tree, int helper, bool morphArgs, GenTree* arg1, GenTree* arg2)
{
// The helper call ought to be semantically equivalent to the original node, so preserve its VN.
tree->ChangeOper(GT_CALL, GenTree::PRESERVE_VN);
GenTreeCall* call = tree->AsCall();
// Args are cleared by ChangeOper above
call->gtCallType = CT_HELPER;
call->gtReturnType = tree->TypeGet();
call->gtCallMethHnd = eeFindHelper(helper);
call->gtRetClsHnd = nullptr;
call->gtCallMoreFlags = GTF_CALL_M_EMPTY;
INDEBUG(call->gtCallDebugFlags = GTF_CALL_MD_EMPTY);
call->gtControlExpr = nullptr;
call->ClearInlineInfo();
#ifdef UNIX_X86_ABI
call->gtFlags |= GTF_CALL_POP_ARGS;
#endif // UNIX_X86_ABI
#if DEBUG
// Helper calls are never candidates.
call->gtInlineObservation = InlineObservation::CALLSITE_IS_CALL_TO_HELPER;
call->callSig = nullptr;
#endif // DEBUG
#ifdef FEATURE_READYTORUN
call->gtEntryPoint.addr = nullptr;
call->gtEntryPoint.accessType = IAT_VALUE;
#endif
#if FEATURE_MULTIREG_RET
call->ResetReturnType();
call->ClearOtherRegs();
call->ClearOtherRegFlags();
#ifndef TARGET_64BIT
if (varTypeIsLong(tree))
{
call->InitializeLongReturnType();
}
#endif // !TARGET_64BIT
#endif // FEATURE_MULTIREG_RET
if (call->OperMayThrow(this))
{
call->gtFlags |= GTF_EXCEPT;
}
else
{
call->gtFlags &= ~GTF_EXCEPT;
}
call->gtFlags |= GTF_CALL;
if (arg2 != nullptr)
{
call->gtArgs.PushFront(this, NewCallArg::Primitive(arg2));
call->gtFlags |= arg2->gtFlags & GTF_ALL_EFFECT;
}
if (arg1 != nullptr)
{
call->gtArgs.PushFront(this, NewCallArg::Primitive(arg1));
call->gtFlags |= arg1->gtFlags & GTF_ALL_EFFECT;
}
// Perform the morphing
if (morphArgs)
{
SharedTempsScope scope(this);
tree = fgMorphArgs(call);
}
return tree;
}
//------------------------------------------------------------------------
// fgMorphExpandCast: Performs the pre-order (required) morphing for a cast.
//
// Performs a rich variety of pre-order transformations (and some optimizations).
//
// Notably:
// 1. Splits long -> small type casts into long -> int -> small type
// for 32 bit targets. Does the same for float/double -> small type
// casts for all targets.
// 2. Morphs casts not supported by the target directly into helpers.
// These mostly have to do with casts from and to floating point
// types, especially checked ones. Refer to the implementation for
// what specific casts need to be handled - it is a complex matrix.
// 3. "Casts away" the GC-ness of a tree (for CAST(nint <- byref)) via
// storing the GC tree to an inline non-GC temporary.
// 3. "Pushes down" truncating long -> int casts for some operations:
// CAST(int <- MUL(long, long)) => MUL(CAST(int <- long), CAST(int <- long)).
// The purpose of this is to allow "optNarrowTree" in the post-order
// traversal to fold the tree into a TYP_INT one, which helps 32 bit
// targets (and AMD64 too since 32 bit instructions are more compact).
// TODO-Arm64-CQ: Re-evaluate the value of this optimization for ARM64.
//
// Arguments:
// tree - the cast tree to morph
//
// Return Value:
// The fully morphed tree, or "nullptr" if it needs further morphing,
// in which case the cast may be transformed into an unchecked one
// and its operand changed (the cast "expanded" into two).
//
GenTree* Compiler::fgMorphExpandCast(GenTreeCast* tree)
{
GenTree* oper = tree->CastOp();
var_types srcType = genActualType(oper);
var_types dstType = tree->CastToType();
unsigned dstSize = genTypeSize(dstType);
#if defined(TARGET_AMD64)
// If AVX512 is present, we have intrinsic available to convert
// ulong directly to float. Hence, we need to combine the 2 nodes
// GT_CAST(GT_CAST(TYP_ULONG, TYP_DOUBLE), TYP_FLOAT) into a single
// node i.e. GT_CAST(TYP_ULONG, TYP_FLOAT). At this point, we already
// have the 2 GT_CAST nodes in the tree and we are combining them below.
if (oper->OperIs(GT_CAST))
{
GenTreeCast* innerCast = oper->AsCast();
if (innerCast->IsUnsigned())
{
GenTree* innerOper = innerCast->CastOp();
var_types innerSrcType = genActualType(innerOper);
var_types innerDstType = innerCast->CastToType();
unsigned innerDstSize = genTypeSize(innerDstType);
innerSrcType = varTypeToUnsigned(innerSrcType);
// Check if we are going from ulong->double->float
if ((innerSrcType == TYP_ULONG) && (innerDstType == TYP_DOUBLE) && (dstType == TYP_FLOAT))
{
if (canUseEvexEncoding())
{
// One optimized (combined) cast here
tree = gtNewCastNode(TYP_FLOAT, innerOper, true, TYP_FLOAT);
return fgMorphTree(tree);
}
}
}
}
#endif // TARGET_AMD64
// See if the cast has to be done in two steps. R -> I
if (varTypeIsFloating(srcType) && varTypeIsIntegral(dstType))
{
if (srcType == TYP_FLOAT
#if defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
// Arm64: src = float, dst is overflow conversion.
// This goes through helper and hence src needs to be converted to double.
&& tree->gtOverflow()
#elif defined(TARGET_AMD64)
// Amd64: src = float, dst = uint64 or overflow conversion.
// src needs to be converted to double except for the following cases
// dstType = int/uint/ulong for AVX512F
// dstType = int for SSE41
// For pre-SSE41, the all src is converted to TYP_DOUBLE
// and goes through helpers.
&& (tree->gtOverflow() || (dstType == TYP_LONG) ||
!(canUseEvexEncoding() || (dstType == TYP_INT && compOpportunisticallyDependsOn(InstructionSet_SSE41))))
#elif defined(TARGET_ARM)
// Arm: src = float, dst = int64/uint64 or overflow conversion.
&& (tree->gtOverflow() || varTypeIsLong(dstType))
#else
// x86: src = float, dst = uint32/int64/uint64 or overflow conversion.
&& (tree->gtOverflow() || varTypeIsIntegral(dstType))
#endif
)
{
oper = gtNewCastNode(TYP_DOUBLE, oper, false, TYP_DOUBLE);
}
// Do we need to do it in two steps R -> I -> smallType?
if (dstSize < genTypeSize(TYP_INT))
{
oper = gtNewCastNodeL(TYP_INT, oper, /* fromUnsigned */ false, TYP_INT);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->AsCast()->CastOp() = oper;
// We must not mistreat the original cast, which was from a floating point type,
// as from an unsigned type, since we now have a TYP_INT node for the source and
// CAST_OVF(BYTE <- INT) != CAST_OVF(BYTE <- UINT).
assert(!tree->IsUnsigned());
}
else
{
if (!tree->gtOverflow())
{
// ARM64 and LoongArch64 optimize all non-overflow checking conversions
#if defined(TARGET_ARM64) || defined(TARGET_LOONGARCH64) || defined(TARGET_RISCV64)
return nullptr;
#else
#if defined(TARGET_AMD64)
// Following nodes are handled when lowering the nodes
// float -> ulong/uint/int for AVX512F
// double -> ulong/uint/long/int for AVX512F
// float -> int for SSE41
// double -> int/uint/long for SSE41
// For all other conversions, we use helper functions.
if (canUseEvexEncoding() ||
((dstType != TYP_ULONG) && compOpportunisticallyDependsOn(InstructionSet_SSE41)))
{
if (tree->CastOp() != oper)
{
tree->CastOp() = oper;
}
return nullptr;
}
#endif // TARGET_AMD64
switch (dstType)
{
case TYP_INT:
#ifdef TARGET_XARCH
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2INT, oper);
#endif // TARGET_XARCH
return nullptr;
case TYP_UINT:
#if defined(TARGET_ARM)
return nullptr;
#endif
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT, oper);
case TYP_LONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG, oper);
case TYP_ULONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG, oper);
default:
unreached();
}
#endif // TARGET_ARM64 || TARGET_LOONGARCH64 || TARGET_RISCV64
}
else
{
switch (dstType)
{
case TYP_INT:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2INT_OVF, oper);
case TYP_UINT:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2UINT_OVF, oper);
case TYP_LONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2LNG_OVF, oper);
case TYP_ULONG:
return fgMorphCastIntoHelper(tree, CORINFO_HELP_DBL2ULNG_OVF, oper);
default:
unreached();
}
}
}
}
#ifndef TARGET_64BIT
// The code generation phase (for x86 & ARM32) does not handle casts
// directly from [u]long to anything other than [u]int. Insert an
// intermediate cast to native int.
else if (varTypeIsLong(srcType) && varTypeIsSmall(dstType))
{
oper = gtNewCastNode(TYP_I_IMPL, oper, tree->IsUnsigned(), TYP_I_IMPL);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->ClearUnsigned();
tree->AsCast()->CastOp() = oper;
}
#endif //! TARGET_64BIT
#ifdef TARGET_ARMARCH
// AArch, unlike x86/amd64, has instructions that can cast directly from
// all integers (except for longs on AArch32 of course) to floats.
// Because there is no IL instruction conv.r4.un, uint/ulong -> float
// casts are always imported as CAST(float <- CAST(double <- uint/ulong)).
// We can eliminate the redundant intermediate cast as an optimization.
else if ((dstType == TYP_FLOAT) && (srcType == TYP_DOUBLE) && oper->OperIs(GT_CAST)
#ifdef TARGET_ARM
&& !varTypeIsLong(oper->AsCast()->CastOp())
#endif
)
{
oper->gtType = TYP_FLOAT;
oper->CastToType() = TYP_FLOAT;
return fgMorphTree(oper);
}
#endif // TARGET_ARMARCH
#ifdef TARGET_ARM
// converts long/ulong --> float/double casts into helper calls.
else if (varTypeIsFloating(dstType) && varTypeIsLong(srcType))
{
if (dstType == TYP_FLOAT)
{
// there is only a double helper, so we
// - change the dsttype to double
// - insert a cast from double to float
// - recurse into the resulting tree
tree->CastToType() = TYP_DOUBLE;
tree->gtType = TYP_DOUBLE;
tree = gtNewCastNode(TYP_FLOAT, tree, false, TYP_FLOAT);
return fgMorphTree(tree);
}
if (tree->gtFlags & GTF_UNSIGNED)
return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper);
return fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
}
#endif // TARGET_ARM
#ifdef TARGET_AMD64
// Do we have to do two step U4/8 -> R4/8 ?
// Codegen supports the following conversion as one-step operation
// a) Long -> R4/R8
// b) U8 -> R8
//
// The following conversions are performed as two-step operations using above.
// U4 -> R4/8 = U4-> Long -> R4/8
// U8 -> R4 = U8 -> R8 -> R4
else if (tree->IsUnsigned() && varTypeIsFloating(dstType))
{
srcType = varTypeToUnsigned(srcType);
if (srcType == TYP_ULONG && !canUseEvexEncoding())
{
if (dstType == TYP_FLOAT)
{
// Codegen can handle U8 -> R8 conversion.
// U8 -> R4 = U8 -> R8 -> R4
// - change the dsttype to double
// - insert a cast from double to float
// - recurse into the resulting tree
tree->CastToType() = TYP_DOUBLE;
tree->gtType = TYP_DOUBLE;
tree = gtNewCastNode(TYP_FLOAT, tree, false, TYP_FLOAT);
return fgMorphTree(tree);
}
}
else if (srcType == TYP_UINT)
{
oper = gtNewCastNode(TYP_LONG, oper, true, TYP_LONG);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->ClearUnsigned();
tree->CastOp() = oper;
}
}
#endif // TARGET_AMD64
#ifdef TARGET_X86
// Do we have to do two step U4/8 -> R4/8 ?
else if (tree->IsUnsigned() && varTypeIsFloating(dstType))
{
srcType = varTypeToUnsigned(srcType);
if (srcType == TYP_ULONG)
{
return fgMorphCastIntoHelper(tree, CORINFO_HELP_ULNG2DBL, oper);
}
else if (srcType == TYP_UINT)
{
oper = gtNewCastNode(TYP_LONG, oper, true, TYP_LONG);
oper->gtFlags |= (tree->gtFlags & (GTF_OVERFLOW | GTF_EXCEPT));
tree->gtFlags &= ~GTF_UNSIGNED;
return fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
}
}
else if (((tree->gtFlags & GTF_UNSIGNED) == 0) && (srcType == TYP_LONG) && varTypeIsFloating(dstType))
{
oper = fgMorphCastIntoHelper(tree, CORINFO_HELP_LNG2DBL, oper);
// Since we don't have a Jit Helper that converts to a TYP_FLOAT
// we just use the one that converts to a TYP_DOUBLE
// and then add a cast to TYP_FLOAT
//
if ((dstType == TYP_FLOAT) && (oper->OperGet() == GT_CALL))
{
// Fix the return type to be TYP_DOUBLE
//
oper->gtType = TYP_DOUBLE;
// Add a Cast to TYP_FLOAT
//
tree = gtNewCastNode(TYP_FLOAT, oper, false, TYP_FLOAT);
INDEBUG(tree->gtDebugFlags |= GTF_DEBUG_NODE_MORPHED);
return tree;
}
else
{
return oper;
}
}
#endif // TARGET_X86
else if (varTypeIsGC(srcType) != varTypeIsGC(dstType))
{
// We are casting away GC information. we would like to just
// change the type to int, however this gives the emitter fits because
// it believes the variable is a GC variable at the beginning of the
// instruction group, but is not turned non-gc by the code generator
// we fix this by copying the GC pointer to a non-gc pointer temp.
noway_assert(!varTypeIsGC(dstType) && "How can we have a cast to a GCRef here?");
// We generate a store to an int and then do the cast from an int. With this we avoid
// the gc problem and we allow casts to bytes, longs, etc...
unsigned lclNum = lvaGrabTemp(true DEBUGARG("Cast away GC"));
oper->gtType = TYP_I_IMPL;
GenTree* store = gtNewTempStore(lclNum, oper);
oper->gtType = srcType;
// do the real cast
GenTree* cast = gtNewCastNode(tree->TypeGet(), gtNewLclvNode(lclNum, TYP_I_IMPL), false, dstType);
// Generate the comma tree
oper = gtNewOperNode(GT_COMMA, tree->TypeGet(), store, cast);
return fgMorphTree(oper);
}
// Look for narrowing casts ([u]long -> [u]int) and try to push them
// down into the operand before morphing it.
//
// It doesn't matter if this is cast is from ulong or long (i.e. if
// GTF_UNSIGNED is set) because the transformation is only applied to
// overflow-insensitive narrowing casts, which always silently truncate.
//
// Note that casts from [u]long to small integer types are handled above.
if ((srcType == TYP_LONG) && ((dstType == TYP_INT) || (dstType == TYP_UINT)))
{
// As a special case, look for overflow-sensitive casts of an AND
// expression, and see if the second operand is a small constant. Since
// the result of an AND is bound by its smaller operand, it may be
// possible to prove that the cast won't overflow, which will in turn
// allow the cast's operand to be transformed.
if (tree->gtOverflow() && (oper->OperGet() == GT_AND))
{
GenTree* andOp2 = oper->AsOp()->gtOp2;
// Look for a constant less than 2^{32} for a cast to uint, or less
// than 2^{31} for a cast to int.
int maxWidth = (dstType == TYP_UINT) ? 32 : 31;
if ((andOp2->OperGet() == GT_CNS_NATIVELONG) && ((andOp2->AsIntConCommon()->LngValue() >> maxWidth) == 0))
{
tree->ClearOverflow();
tree->SetAllEffectsFlags(oper);
}
}
// Only apply this transformation during global morph,
// when neither the cast node nor the oper node may throw an exception
// based on the upper 32 bits.
//
if (fgGlobalMorph && !tree->gtOverflow() && !oper->gtOverflowEx())
{
// For these operations the lower 32 bits of the result only depends
// upon the lower 32 bits of the operands.
//
bool canPushCast = oper->OperIs(GT_ADD, GT_SUB, GT_MUL, GT_AND, GT_OR, GT_XOR, GT_NOT, GT_NEG);
// For long LSH cast to int, there is a discontinuity in behavior
// when the shift amount is 32 or larger.
//
// CAST(INT, LSH(1LL, 31)) == LSH(1, 31)
// LSH(CAST(INT, 1LL), CAST(INT, 31)) == LSH(1, 31)
//
// CAST(INT, LSH(1LL, 32)) == 0
// LSH(CAST(INT, 1LL), CAST(INT, 32)) == LSH(1, 32) == LSH(1, 0) == 1
//
// So some extra validation is needed.
//
if (oper->OperIs(GT_LSH))
{
GenTree* shiftAmount = oper->AsOp()->gtOp2;
// Expose constant value for shift, if possible, to maximize the number
// of cases we can handle.
shiftAmount = gtFoldExpr(shiftAmount);
oper->AsOp()->gtOp2 = shiftAmount;
#if DEBUG
// We may remorph the shift amount tree again later, so clear any morphed flag.
shiftAmount->gtDebugFlags &= ~GTF_DEBUG_NODE_MORPHED;
#endif // DEBUG
if (shiftAmount->IsIntegralConst())
{
const ssize_t shiftAmountValue = shiftAmount->AsIntCon()->IconValue();
if ((shiftAmountValue >= 64) || (shiftAmountValue < 0))
{
// Shift amount is large enough or negative so result is undefined.
// Don't try to optimize.
assert(!canPushCast);
}
else if (shiftAmountValue >= 32)
{
// We know that we have a narrowing cast ([u]long -> [u]int)
// and that we are casting to a 32-bit value, which will result in zero.
//
// Check to see if we have any side-effects that we must keep
//
if ((tree->gtFlags & GTF_ALL_EFFECT) == 0)
{
// Result of the shift is zero.
DEBUG_DESTROY_NODE(tree);
GenTree* zero = gtNewZeroConNode(TYP_INT);
return fgMorphTree(zero);
}
else // We do have a side-effect
{
// We could create a GT_COMMA node here to keep the side-effect and return a zero
// Instead we just don't try to optimize this case.
canPushCast = false;
}
}
else
{
// Shift amount is positive and small enough that we can push the cast through.
canPushCast = true;
}
}
else
{
// Shift amount is unknown. We can't optimize this case.
assert(!canPushCast);
}
}
if (canPushCast)
{
GenTree* op1 = oper->gtGetOp1();
GenTree* op2 = oper->gtGetOp2IfPresent();
canPushCast = !varTypeIsGC(op1) && ((op2 == nullptr) || !varTypeIsGC(op2));
}
if (canPushCast)
{
DEBUG_DESTROY_NODE(tree);
// Insert narrowing casts for op1 and op2.
oper->AsOp()->gtOp1 = gtNewCastNode(TYP_INT, oper->AsOp()->gtOp1, false, dstType);
if (oper->AsOp()->gtOp2 != nullptr)
{
oper->AsOp()->gtOp2 = gtNewCastNode(TYP_INT, oper->AsOp()->gtOp2, false, dstType);
}
// Clear the GT_MUL_64RSLT if it is set.
if (oper->gtOper == GT_MUL && (oper->gtFlags & GTF_MUL_64RSLT))
{
oper->gtFlags &= ~GTF_MUL_64RSLT;
}
// The operation now produces a 32-bit result.
oper->gtType = TYP_INT;
// Remorph the new tree as the casts that we added may be folded away.
return fgMorphTree(oper);
}
}
}
return nullptr;
}
#ifdef DEBUG
//------------------------------------------------------------------------
// getWellKnownArgName: Get a string representation of a WellKnownArg.
//
const char* getWellKnownArgName(WellKnownArg arg)
{
switch (arg)
{
case WellKnownArg::None:
return "None";
case WellKnownArg::ThisPointer:
return "ThisPointer";
case WellKnownArg::VarArgsCookie:
return "VarArgsCookie";
case WellKnownArg::InstParam:
return "InstParam";
case WellKnownArg::RetBuffer:
return "RetBuffer";
case WellKnownArg::PInvokeFrame:
return "PInvokeFrame";
case WellKnownArg::WrapperDelegateCell:
return "WrapperDelegateCell";
case WellKnownArg::ShiftLow:
return "ShiftLow";
case WellKnownArg::ShiftHigh:
return "ShiftHigh";
case WellKnownArg::VirtualStubCell:
return "VirtualStubCell";
case WellKnownArg::PInvokeCookie:
return "PInvokeCookie";
case WellKnownArg::PInvokeTarget:
return "PInvokeTarget";
case WellKnownArg::R2RIndirectionCell:
return "R2RIndirectionCell";
case WellKnownArg::ValidateIndirectCallTarget:
return "ValidateIndirectCallTarget";
case WellKnownArg::DispatchIndirectCallTarget:
return "DispatchIndirectCallTarget";
case WellKnownArg::SwiftError:
return "SwiftError";
case WellKnownArg::SwiftSelf:
return "SwiftSelf";
case WellKnownArg::X86TailCallSpecialArg:
return "X86TailCallSpecialArg";
}
return "N/A";
}
//------------------------------------------------------------------------
// Dump: Dump information about a CallArg to jitstdout.
//
void CallArg::Dump(Compiler* comp)
{
printf("CallArg[[%06u].%s", comp->dspTreeID(GetNode()), GenTree::OpName(GetNode()->OperGet()));
printf(" %s", varTypeName(m_signatureType));
printf(" (%s)", AbiInfo.PassedByRef ? "By ref" : "By value");
if (AbiInfo.GetRegNum() != REG_STK)
{
printf(", %u reg%s:", AbiInfo.NumRegs, AbiInfo.NumRegs == 1 ? "" : "s");
for (unsigned i = 0; i < AbiInfo.NumRegs; i++)
{
printf(" %s", getRegName(AbiInfo.GetRegNum(i)));
}
}
if (AbiInfo.GetStackByteSize() > 0)
{
printf(", byteSize=%u, byteOffset=%u", AbiInfo.ByteSize, AbiInfo.ByteOffset);
}
if (GetLateNode() != nullptr)
{
printf(", isLate");
}
if (AbiInfo.IsSplit())
{
printf(", isSplit");
}
if (m_needPlace)
{
printf(", needPlace");
}
if (m_processed)
{
printf(", processed");
}
if (AbiInfo.IsHfaRegArg())
{
printf(", isHfa(%s)", varTypeName(AbiInfo.GetHfaType()));
}
if (m_wellKnownArg != WellKnownArg::None)
{
printf(", wellKnown[%s]", getWellKnownArgName(m_wellKnownArg));
}
printf("]\n");
}
#endif
//------------------------------------------------------------------------
// ArgsComplete: Make final decisions on which arguments to evaluate into temporaries.
//
void CallArgs::ArgsComplete(Compiler* comp, GenTreeCall* call)
{
unsigned argCount = CountArgs();
// Previous argument with GTF_EXCEPT
GenTree* prevExceptionTree = nullptr;
// Exceptions previous tree with GTF_EXCEPT may throw (computed lazily, may
// be empty)
ExceptionSetFlags prevExceptionFlags = ExceptionSetFlags::None;
for (CallArg& arg : Args())
{
GenTree* argx = arg.GetEarlyNode();
assert(argx != nullptr);
bool canEvalToTemp = true;
if (arg.AbiInfo.GetRegNum() == REG_STK)
{
assert(m_hasStackArgs);
#if !FEATURE_FIXED_OUT_ARGS
// Non-register arguments are evaluated and pushed in order; they
// should never go in the late arg list.
canEvalToTemp = false;
#endif
}
#if FEATURE_ARG_SPLIT
else if (arg.AbiInfo.IsSplit())
{
assert(m_hasStackArgs);
}
#endif // FEATURE_ARG_SPLIT
// If the argument tree contains a store (GTF_ASG) then the argument and
// and every earlier argument (except constants) must be evaluated into temps
// since there may be other arguments that follow and they may use the value being defined.
//
// EXAMPLE: ArgTab is "a, a=5, a"
// -> when we see the second arg "a=5"
// we know the first two arguments "a, a=5" have to be evaluated into temps
//
if ((argx->gtFlags & GTF_ASG) != 0)
{
// fgMakeOutgoingStructArgCopy can have introduced a temp already,
// in which case it will have created a setup node in the early
// node.
if (!argx->IsValue())
{
assert(arg.m_needTmp);
}
else if (canEvalToTemp && (argCount > 1))
{
SetNeedsTemp(&arg);
}
// For all previous arguments that may interfere with the store we
// require that they be evaluated into temps.
for (CallArg& prevArg : Args())
{
if (&prevArg == &arg)
{
break;
}
#if !FEATURE_FIXED_OUT_ARGS
if (prevArg.AbiInfo.GetRegNum() == REG_STK)
{
// All stack args are already evaluated and placed in order
// in this case.
continue;
}
#endif
if ((prevArg.GetEarlyNode() == nullptr) || prevArg.m_needTmp)
{
continue;
}
if (((prevArg.GetEarlyNode()->gtFlags & GTF_ALL_EFFECT) != 0) ||
comp->gtMayHaveStoreInterference(argx, prevArg.GetEarlyNode()))
{
SetNeedsTemp(&prevArg);
}
}
}
bool treatLikeCall = ((argx->gtFlags & GTF_CALL) != 0);
ExceptionSetFlags exceptionFlags = ExceptionSetFlags::None;
#if FEATURE_FIXED_OUT_ARGS
// Like calls, if this argument has a tree that will do an inline throw,
// a call to a jit helper, then we need to treat it like a call (but only
// if there are/were any stack args).
// This means unnesting, sorting, etc. Technically this is overly
// conservative, but I want to avoid as much special-case debug-only code
// as possible, so leveraging the GTF_CALL flag is the easiest.
//
if (!treatLikeCall && (argx->gtFlags & GTF_EXCEPT) && (argCount > 1) && comp->opts.compDbgCode)
{
exceptionFlags = comp->gtCollectExceptions(argx);
if ((exceptionFlags & (ExceptionSetFlags::IndexOutOfRangeException |
ExceptionSetFlags::OverflowException)) != ExceptionSetFlags::None)
{
for (CallArg& otherArg : Args())
{
if (&otherArg == &arg)
{
continue;
}
if (otherArg.AbiInfo.GetRegNum() == REG_STK)
{
treatLikeCall = true;
break;
}
}
}
}
#endif // FEATURE_FIXED_OUT_ARGS
// If it contains a call (GTF_CALL) then itself and everything before the call
// with a GLOB_EFFECT must eval to temp (this is because everything with SIDE_EFFECT
// has to be kept in the right order since we will move the call to the first position)
// For calls we don't have to be quite as conservative as we are with stores
// since the call won't be modifying any non-address taken LclVars.
if (treatLikeCall)
{
if (canEvalToTemp)
{
if (argCount > 1) // If this is not the only argument
{
SetNeedsTemp(&arg);
}
else if (varTypeIsFloating(argx->TypeGet()) && (argx->OperGet() == GT_CALL))
{
// Spill all arguments that are floating point calls
SetNeedsTemp(&arg);
}
}
// All previous arguments may need to be evaluated into temps
for (CallArg& prevArg : Args())
{
if (&prevArg == &arg)
{
break;
}
#if !FEATURE_FIXED_OUT_ARGS
if (prevArg.AbiInfo.GetRegNum() == REG_STK)
{
// All stack args are already evaluated and placed in order
// in this case.
continue;
}
#endif
// For all previous arguments, if they have any GTF_ALL_EFFECT