This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
/
codegenxarch.cpp
8774 lines (7648 loc) · 309 KB
/
codegenxarch.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.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Amd64/x86 Code Generator XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#ifndef LEGACY_BACKEND // This file is ONLY used for the RyuJIT backend that uses the linear scan register allocator.
#ifdef _TARGET_XARCH_
#include "emit.h"
#include "codegen.h"
#include "lower.h"
#include "gcinfo.h"
#include "gcinfoencoder.h"
/*****************************************************************************
*
* Generate code that will set the given register to the integer constant.
*/
void CodeGen::genSetRegToIcon(regNumber reg, ssize_t val, var_types type, insFlags flags)
{
// Reg cannot be a FP reg
assert(!genIsValidFloatReg(reg));
// The only TYP_REF constant that can come this path is a managed 'null' since it is not
// relocatable. Other ref type constants (e.g. string objects) go through a different
// code path.
noway_assert(type != TYP_REF || val == 0);
if (val == 0)
{
instGen_Set_Reg_To_Zero(emitActualTypeSize(type), reg, flags);
}
else
{
// TODO-XArch-CQ: needs all the optimized cases
getEmitter()->emitIns_R_I(INS_mov, emitActualTypeSize(type), reg, val);
}
}
/*****************************************************************************
*
* Generate code to check that the GS cookie wasn't thrashed by a buffer
* overrun. If pushReg is true, preserve all registers around code sequence.
* Otherwise ECX could be modified.
*
* Implementation Note: pushReg = true, in case of tail calls.
*/
void CodeGen::genEmitGSCookieCheck(bool pushReg)
{
noway_assert(compiler->gsGlobalSecurityCookieAddr || compiler->gsGlobalSecurityCookieVal);
// Make sure that EAX is reported as live GC-ref so that any GC that kicks in while
// executing GS cookie check will not collect the object pointed to by EAX.
//
// For Amd64 System V, a two-register-returned struct could be returned in RAX and RDX
// In such case make sure that the correct GC-ness of RDX is reported as well, so
// a GC object pointed by RDX will not be collected.
if (!pushReg)
{
// Handle multi-reg return type values
if (compiler->compMethodReturnsMultiRegRetType())
{
ReturnTypeDesc retTypeDesc;
if (varTypeIsLong(compiler->info.compRetNativeType))
{
retTypeDesc.InitializeLongReturnType(compiler);
}
else // we must have a struct return type
{
retTypeDesc.InitializeStructReturnType(compiler, compiler->info.compMethodInfo->args.retTypeClass);
}
unsigned regCount = retTypeDesc.GetReturnRegCount();
// Only x86 and x64 Unix ABI allows multi-reg return and
// number of result regs should be equal to MAX_RET_REG_COUNT.
assert(regCount == MAX_RET_REG_COUNT);
for (unsigned i = 0; i < regCount; ++i)
{
gcInfo.gcMarkRegPtrVal(retTypeDesc.GetABIReturnReg(i), retTypeDesc.GetReturnRegType(i));
}
}
else if (compiler->compMethodReturnsRetBufAddr())
{
// This is for returning in an implicit RetBuf.
// If the address of the buffer is returned in REG_INTRET, mark the content of INTRET as ByRef.
// In case the return is in an implicit RetBuf, the native return type should be a struct
assert(varTypeIsStruct(compiler->info.compRetNativeType));
gcInfo.gcMarkRegPtrVal(REG_INTRET, TYP_BYREF);
}
// ... all other cases.
else
{
#ifdef _TARGET_AMD64_
// For x64, structs that are not returned in registers are always
// returned in implicit RetBuf. If we reached here, we should not have
// a RetBuf and the return type should not be a struct.
assert(compiler->info.compRetBuffArg == BAD_VAR_NUM);
assert(!varTypeIsStruct(compiler->info.compRetNativeType));
#endif // _TARGET_AMD64_
// For x86 Windows we can't make such assertions since we generate code for returning of
// the RetBuf in REG_INTRET only when the ProfilerHook is enabled. Otherwise
// compRetNativeType could be TYP_STRUCT.
gcInfo.gcMarkRegPtrVal(REG_INTRET, compiler->info.compRetNativeType);
}
}
regNumber regGSCheck;
regMaskTP regMaskGSCheck = RBM_NONE;
if (!pushReg)
{
// Non-tail call: we can use any callee trash register that is not
// a return register or contain 'this' pointer (keep alive this), since
// we are generating GS cookie check after a GT_RETURN block.
// Note: On Amd64 System V RDX is an arg register - REG_ARG_2 - as well
// as return register for two-register-returned structs.
if (compiler->lvaKeepAliveAndReportThis() && compiler->lvaTable[compiler->info.compThisArg].lvRegister &&
(compiler->lvaTable[compiler->info.compThisArg].lvRegNum == REG_ARG_0))
{
regGSCheck = REG_ARG_1;
}
else
{
regGSCheck = REG_ARG_0;
}
}
else
{
#ifdef _TARGET_X86_
// It doesn't matter which register we pick, since we're going to save and restore it
// around the check.
// TODO-CQ: Can we optimize the choice of register to avoid doing the push/pop sometimes?
regGSCheck = REG_EAX;
regMaskGSCheck = RBM_EAX;
#else // !_TARGET_X86_
// Tail calls from methods that need GS check: We need to preserve registers while
// emitting GS cookie check for a tail prefixed call or a jmp. To emit GS cookie
// check, we might need a register. This won't be an issue for jmp calls for the
// reason mentioned below (see comment starting with "Jmp Calls:").
//
// The following are the possible solutions in case of tail prefixed calls:
// 1) Use R11 - ignore tail prefix on calls that need to pass a param in R11 when
// present in methods that require GS cookie check. Rest of the tail calls that
// do not require R11 will be honored.
// 2) Internal register - GT_CALL node reserves an internal register and emits GS
// cookie check as part of tail call codegen. GenExitCode() needs to special case
// fast tail calls implemented as epilog+jmp or such tail calls should always get
// dispatched via helper.
// 3) Materialize GS cookie check as a sperate node hanging off GT_CALL node in
// right execution order during rationalization.
//
// There are two calls that use R11: VSD and calli pinvokes with cookie param. Tail
// prefix on pinvokes is ignored. That is, options 2 and 3 will allow tail prefixed
// VSD calls from methods that need GS check.
//
// Tail prefixed calls: Right now for Jit64 compat, method requiring GS cookie check
// ignores tail prefix. In future, if we intend to support tail calls from such a method,
// consider one of the options mentioned above. For now adding an assert that we don't
// expect to see a tail call in a method that requires GS check.
noway_assert(!compiler->compTailCallUsed);
// Jmp calls: specify method handle using which JIT queries VM for its entry point
// address and hence it can neither be a VSD call nor PInvoke calli with cookie
// parameter. Therefore, in case of jmp calls it is safe to use R11.
regGSCheck = REG_R11;
#endif // !_TARGET_X86_
}
regMaskTP byrefPushedRegs = RBM_NONE;
regMaskTP norefPushedRegs = RBM_NONE;
regMaskTP pushedRegs = RBM_NONE;
if (compiler->gsGlobalSecurityCookieAddr == nullptr)
{
#if defined(_TARGET_AMD64_)
// If GS cookie value fits within 32-bits we can use 'cmp mem64, imm32'.
// Otherwise, load the value into a reg and use 'cmp mem64, reg64'.
if ((int)compiler->gsGlobalSecurityCookieVal != (ssize_t)compiler->gsGlobalSecurityCookieVal)
{
genSetRegToIcon(regGSCheck, compiler->gsGlobalSecurityCookieVal, TYP_I_IMPL);
getEmitter()->emitIns_S_R(INS_cmp, EA_PTRSIZE, regGSCheck, compiler->lvaGSSecurityCookie, 0);
}
else
#endif // defined(_TARGET_AMD64_)
{
assert((int)compiler->gsGlobalSecurityCookieVal == (ssize_t)compiler->gsGlobalSecurityCookieVal);
getEmitter()->emitIns_S_I(INS_cmp, EA_PTRSIZE, compiler->lvaGSSecurityCookie, 0,
(int)compiler->gsGlobalSecurityCookieVal);
}
}
else
{
// Ngen case - GS cookie value needs to be accessed through an indirection.
pushedRegs = genPushRegs(regMaskGSCheck, &byrefPushedRegs, &norefPushedRegs);
instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, regGSCheck, (ssize_t)compiler->gsGlobalSecurityCookieAddr);
getEmitter()->emitIns_R_AR(ins_Load(TYP_I_IMPL), EA_PTRSIZE, regGSCheck, regGSCheck, 0);
getEmitter()->emitIns_S_R(INS_cmp, EA_PTRSIZE, regGSCheck, compiler->lvaGSSecurityCookie, 0);
}
BasicBlock* gsCheckBlk = genCreateTempLabel();
emitJumpKind jmpEqual = genJumpKindForOper(GT_EQ, CK_SIGNED);
inst_JMP(jmpEqual, gsCheckBlk);
genEmitHelperCall(CORINFO_HELP_FAIL_FAST, 0, EA_UNKNOWN);
genDefineTempLabel(gsCheckBlk);
genPopRegs(pushedRegs, byrefPushedRegs, norefPushedRegs);
}
BasicBlock* CodeGen::genCallFinally(BasicBlock* block)
{
#if FEATURE_EH_FUNCLETS
// Generate a call to the finally, like this:
// mov rcx,qword ptr [rbp + 20H] // Load rcx with PSPSym
// call finally-funclet
// jmp finally-return // Only for non-retless finally calls
// The jmp can be a NOP if we're going to the next block.
// If we're generating code for the main function (not a funclet), and there is no localloc,
// then RSP at this point is the same value as that stored in the PSPSym. So just copy RSP
// instead of loading the PSPSym in this case, or if PSPSym is not used (CoreRT ABI).
if ((compiler->lvaPSPSym == BAD_VAR_NUM) ||
(!compiler->compLocallocUsed && (compiler->funCurrentFunc()->funKind == FUNC_ROOT)))
{
#ifndef UNIX_X86_ABI
inst_RV_RV(INS_mov, REG_ARG_0, REG_SPBASE, TYP_I_IMPL);
#endif // !UNIX_X86_ABI
}
else
{
getEmitter()->emitIns_R_S(ins_Load(TYP_I_IMPL), EA_PTRSIZE, REG_ARG_0, compiler->lvaPSPSym, 0);
}
getEmitter()->emitIns_J(INS_call, block->bbJumpDest);
if (block->bbFlags & BBF_RETLESS_CALL)
{
// We have a retless call, and the last instruction generated was a call.
// If the next block is in a different EH region (or is the end of the code
// block), then we need to generate a breakpoint here (since it will never
// get executed) to get proper unwind behavior.
if ((block->bbNext == nullptr) || !BasicBlock::sameEHRegion(block, block->bbNext))
{
instGen(INS_BREAKPOINT); // This should never get executed
}
}
else
{
// TODO-Linux-x86: Do we need to handle the GC information for this NOP or JMP specially, as is done for other
// architectures?
#ifndef JIT32_GCENCODER
// Because of the way the flowgraph is connected, the liveness info for this one instruction
// after the call is not (can not be) correct in cases where a variable has a last use in the
// handler. So turn off GC reporting for this single instruction.
getEmitter()->emitDisableGC();
#endif // JIT32_GCENCODER
// Now go to where the finally funclet needs to return to.
if (block->bbNext->bbJumpDest == block->bbNext->bbNext)
{
// Fall-through.
// TODO-XArch-CQ: Can we get rid of this instruction, and just have the call return directly
// to the next instruction? This would depend on stack walking from within the finally
// handler working without this instruction being in this special EH region.
instGen(INS_nop);
}
else
{
inst_JMP(EJ_jmp, block->bbNext->bbJumpDest);
}
#ifndef JIT32_GCENCODER
getEmitter()->emitEnableGC();
#endif // JIT32_GCENCODER
}
#else // !FEATURE_EH_FUNCLETS
// If we are about to invoke a finally locally from a try block, we have to set the ShadowSP slot
// corresponding to the finally's nesting level. When invoked in response to an exception, the
// EE does this.
//
// We have a BBJ_CALLFINALLY followed by a BBJ_ALWAYS.
//
// We will emit :
// mov [ebp - (n + 1)], 0
// mov [ebp - n ], 0xFC
// push &step
// jmp finallyBlock
// ...
// step:
// mov [ebp - n ], 0
// jmp leaveTarget
// ...
// leaveTarget:
noway_assert(isFramePointerUsed());
// Get the nesting level which contains the finally
unsigned finallyNesting = 0;
compiler->fgGetNestingLevel(block, &finallyNesting);
// The last slot is reserved for ICodeManager::FixContext(ppEndRegion)
unsigned filterEndOffsetSlotOffs;
filterEndOffsetSlotOffs = (unsigned)(compiler->lvaLclSize(compiler->lvaShadowSPslotsVar) - TARGET_POINTER_SIZE);
unsigned curNestingSlotOffs;
curNestingSlotOffs = (unsigned)(filterEndOffsetSlotOffs - ((finallyNesting + 1) * TARGET_POINTER_SIZE));
// Zero out the slot for the next nesting level
instGen_Store_Imm_Into_Lcl(TYP_I_IMPL, EA_PTRSIZE, 0, compiler->lvaShadowSPslotsVar,
curNestingSlotOffs - TARGET_POINTER_SIZE);
instGen_Store_Imm_Into_Lcl(TYP_I_IMPL, EA_PTRSIZE, LCL_FINALLY_MARK, compiler->lvaShadowSPslotsVar,
curNestingSlotOffs);
// Now push the address where the finally funclet should return to directly.
if (!(block->bbFlags & BBF_RETLESS_CALL))
{
assert(block->isBBCallAlwaysPair());
getEmitter()->emitIns_J(INS_push_hide, block->bbNext->bbJumpDest);
}
else
{
// EE expects a DWORD, so we give him 0
inst_IV(INS_push_hide, 0);
}
// Jump to the finally BB
inst_JMP(EJ_jmp, block->bbJumpDest);
#endif // !FEATURE_EH_FUNCLETS
// The BBJ_ALWAYS is used because the BBJ_CALLFINALLY can't point to the
// jump target using bbJumpDest - that is already used to point
// to the finally block. So just skip past the BBJ_ALWAYS unless the
// block is RETLESS.
if (!(block->bbFlags & BBF_RETLESS_CALL))
{
assert(block->isBBCallAlwaysPair());
block = block->bbNext;
}
return block;
}
#if FEATURE_EH_FUNCLETS
void CodeGen::genEHCatchRet(BasicBlock* block)
{
// Set RAX to the address the VM should return to after the catch.
// Generate a RIP-relative
// lea reg, [rip + disp32] ; the RIP is implicit
// which will be position-indepenent.
getEmitter()->emitIns_R_L(INS_lea, EA_PTR_DSP_RELOC, block->bbJumpDest, REG_INTRET);
}
#else // !FEATURE_EH_FUNCLETS
void CodeGen::genEHFinallyOrFilterRet(BasicBlock* block)
{
// The last statement of the block must be a GT_RETFILT, which has already been generated.
assert(block->lastNode() != nullptr);
assert(block->lastNode()->OperGet() == GT_RETFILT);
if (block->bbJumpKind == BBJ_EHFINALLYRET)
{
assert(block->lastNode()->gtOp.gtOp1 == nullptr); // op1 == nullptr means endfinally
// Return using a pop-jmp sequence. As the "try" block calls
// the finally with a jmp, this leaves the x86 call-ret stack
// balanced in the normal flow of path.
noway_assert(isFramePointerRequired());
inst_RV(INS_pop_hide, REG_EAX, TYP_I_IMPL);
inst_RV(INS_i_jmp, REG_EAX, TYP_I_IMPL);
}
else
{
assert(block->bbJumpKind == BBJ_EHFILTERRET);
// The return value has already been computed.
instGen_Return(0);
}
}
#endif // !FEATURE_EH_FUNCLETS
// Move an immediate value into an integer register
void CodeGen::instGen_Set_Reg_To_Imm(emitAttr size, regNumber reg, ssize_t imm, insFlags flags)
{
// reg cannot be a FP register
assert(!genIsValidFloatReg(reg));
if (!compiler->opts.compReloc)
{
size = EA_SIZE(size); // Strip any Reloc flags from size if we aren't doing relocs
}
if ((imm == 0) && !EA_IS_RELOC(size))
{
instGen_Set_Reg_To_Zero(size, reg, flags);
}
else
{
if (genDataIndirAddrCanBeEncodedAsPCRelOffset(imm))
{
getEmitter()->emitIns_R_AI(INS_lea, EA_PTR_DSP_RELOC, reg, imm);
}
else
{
getEmitter()->emitIns_R_I(INS_mov, size, reg, imm);
}
}
regTracker.rsTrackRegIntCns(reg, imm);
}
/***********************************************************************************
*
* Generate code to set a register 'targetReg' of type 'targetType' to the constant
* specified by the constant (GT_CNS_INT or GT_CNS_DBL) in 'tree'. This does not call
* genProduceReg() on the target register.
*/
void CodeGen::genSetRegToConst(regNumber targetReg, var_types targetType, GenTree* tree)
{
switch (tree->gtOper)
{
case GT_CNS_INT:
{
// relocatable values tend to come down as a CNS_INT of native int type
// so the line between these two opcodes is kind of blurry
GenTreeIntConCommon* con = tree->AsIntConCommon();
ssize_t cnsVal = con->IconValue();
if (con->ImmedValNeedsReloc(compiler))
{
instGen_Set_Reg_To_Imm(EA_HANDLE_CNS_RELOC, targetReg, cnsVal);
regTracker.rsTrackRegTrash(targetReg);
}
else
{
genSetRegToIcon(targetReg, cnsVal, targetType);
}
}
break;
case GT_CNS_DBL:
{
emitter* emit = getEmitter();
emitAttr size = emitTypeSize(targetType);
double constValue = tree->gtDblCon.gtDconVal;
// Make sure we use "xorps reg, reg" only for +ve zero constant (0.0) and not for -ve zero (-0.0)
if (*(__int64*)&constValue == 0)
{
// A faster/smaller way to generate 0
emit->emitIns_R_R(INS_xorps, size, targetReg, targetReg);
}
else
{
CORINFO_FIELD_HANDLE hnd = emit->emitFltOrDblConst(constValue, size);
emit->emitIns_R_C(ins_Load(targetType), size, targetReg, hnd, 0);
}
}
break;
default:
unreached();
}
}
//------------------------------------------------------------------------
// genCodeForNegNot: Produce code for a GT_NEG/GT_NOT node.
//
// Arguments:
// tree - the node
//
void CodeGen::genCodeForNegNot(GenTree* tree)
{
assert(tree->OperIs(GT_NEG, GT_NOT));
regNumber targetReg = tree->gtRegNum;
var_types targetType = tree->TypeGet();
if (varTypeIsFloating(targetType))
{
assert(tree->gtOper == GT_NEG);
genSSE2BitwiseOp(tree);
}
else
{
GenTree* operand = tree->gtGetOp1();
assert(operand->isUsedFromReg());
regNumber operandReg = genConsumeReg(operand);
if (operandReg != targetReg)
{
inst_RV_RV(INS_mov, targetReg, operandReg, targetType);
}
instruction ins = genGetInsForOper(tree->OperGet(), targetType);
inst_RV(ins, targetReg, targetType);
}
genProduceReg(tree);
}
// Generate code to get the high N bits of a N*N=2N bit multiplication result
void CodeGen::genCodeForMulHi(GenTreeOp* treeNode)
{
assert(!treeNode->gtOverflowEx());
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
emitAttr size = emitTypeSize(treeNode);
GenTree* op1 = treeNode->gtOp.gtOp1;
GenTree* op2 = treeNode->gtOp.gtOp2;
// to get the high bits of the multiply, we are constrained to using the
// 1-op form: RDX:RAX = RAX * rm
// The 3-op form (Rx=Ry*Rz) does not support it.
genConsumeOperands(treeNode->AsOp());
GenTree* regOp = op1;
GenTree* rmOp = op2;
// Set rmOp to the memory operand (if any)
if (op1->isUsedFromMemory() || (op2->isUsedFromReg() && (op2->gtRegNum == REG_RAX)))
{
regOp = op2;
rmOp = op1;
}
assert(regOp->isUsedFromReg());
// Setup targetReg when neither of the source operands was a matching register
if (regOp->gtRegNum != REG_RAX)
{
inst_RV_RV(ins_Copy(targetType), REG_RAX, regOp->gtRegNum, targetType);
}
instruction ins;
if ((treeNode->gtFlags & GTF_UNSIGNED) == 0)
{
ins = INS_imulEAX;
}
else
{
ins = INS_mulEAX;
}
emit->emitInsBinary(ins, size, treeNode, rmOp);
// Move the result to the desired register, if necessary
if (treeNode->OperGet() == GT_MULHI && targetReg != REG_RDX)
{
inst_RV_RV(INS_mov, targetReg, REG_RDX, targetType);
}
genProduceReg(treeNode);
}
#ifdef _TARGET_X86_
//------------------------------------------------------------------------
// genCodeForLongUMod: Generate code for a tree of the form
// `(umod (gt_long x y) (const int))`
//
// Arguments:
// node - the node for which to generate code
//
void CodeGen::genCodeForLongUMod(GenTreeOp* node)
{
assert(node != nullptr);
assert(node->OperGet() == GT_UMOD);
assert(node->TypeGet() == TYP_INT);
GenTreeOp* const dividend = node->gtOp1->AsOp();
assert(dividend->OperGet() == GT_LONG);
assert(varTypeIsLong(dividend));
genConsumeOperands(node);
GenTree* const dividendLo = dividend->gtOp1;
GenTree* const dividendHi = dividend->gtOp2;
assert(dividendLo->isUsedFromReg());
assert(dividendHi->isUsedFromReg());
GenTree* const divisor = node->gtOp2;
assert(divisor->gtSkipReloadOrCopy()->OperGet() == GT_CNS_INT);
assert(divisor->gtSkipReloadOrCopy()->isUsedFromReg());
assert(divisor->gtSkipReloadOrCopy()->AsIntCon()->gtIconVal >= 2);
assert(divisor->gtSkipReloadOrCopy()->AsIntCon()->gtIconVal <= 0x3fffffff);
// dividendLo must be in RAX; dividendHi must be in RDX
genCopyRegIfNeeded(dividendLo, REG_EAX);
genCopyRegIfNeeded(dividendHi, REG_EDX);
// At this point, EAX:EDX contains the 64bit dividend and op2->gtRegNum
// contains the 32bit divisor. We want to generate the following code:
//
// cmp edx, divisor->gtRegNum
// jb noOverflow
//
// mov temp, eax
// mov eax, edx
// xor edx, edx
// div divisor->gtRegNum
// mov eax, temp
//
// noOverflow:
// div divisor->gtRegNum
//
// This works because (a * 2^32 + b) % c = ((a % c) * 2^32 + b) % c.
BasicBlock* const noOverflow = genCreateTempLabel();
// cmp edx, divisor->gtRegNum
// jb noOverflow
inst_RV_RV(INS_cmp, REG_EDX, divisor->gtRegNum);
inst_JMP(EJ_jb, noOverflow);
// mov temp, eax
// mov eax, edx
// xor edx, edx
// div divisor->gtRegNum
// mov eax, temp
const regNumber tempReg = node->GetSingleTempReg();
inst_RV_RV(INS_mov, tempReg, REG_EAX, TYP_INT);
inst_RV_RV(INS_mov, REG_EAX, REG_EDX, TYP_INT);
instGen_Set_Reg_To_Zero(EA_PTRSIZE, REG_EDX);
inst_RV(INS_div, divisor->gtRegNum, TYP_INT);
inst_RV_RV(INS_mov, REG_EAX, tempReg, TYP_INT);
// noOverflow:
// div divisor->gtRegNum
genDefineTempLabel(noOverflow);
inst_RV(INS_div, divisor->gtRegNum, TYP_INT);
const regNumber targetReg = node->gtRegNum;
if (targetReg != REG_EDX)
{
inst_RV_RV(INS_mov, targetReg, REG_RDX, TYP_INT);
}
genProduceReg(node);
}
#endif // _TARGET_X86_
//------------------------------------------------------------------------
// genCodeForDivMod: Generate code for a DIV or MOD operation.
//
// Arguments:
// treeNode - the node to generate the code for
//
void CodeGen::genCodeForDivMod(GenTreeOp* treeNode)
{
assert(treeNode->OperIs(GT_DIV, GT_UDIV, GT_MOD, GT_UMOD));
// We shouldn't be seeing GT_MOD on float/double args as it should get morphed into a
// helper call by front-end. Similarly we shouldn't be seeing GT_UDIV and GT_UMOD
// on float/double args.
assert(treeNode->OperIs(GT_DIV) || !varTypeIsFloating(treeNode));
GenTree* dividend = treeNode->gtOp1;
#ifdef _TARGET_X86_
if (varTypeIsLong(dividend->TypeGet()))
{
genCodeForLongUMod(treeNode);
return;
}
#endif // _TARGET_X86_
GenTree* divisor = treeNode->gtOp2;
genTreeOps oper = treeNode->OperGet();
emitAttr size = emitTypeSize(treeNode);
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
// dividend is in a register.
assert(dividend->isUsedFromReg());
genConsumeOperands(treeNode->AsOp());
if (varTypeIsFloating(targetType))
{
// Floating point div/rem operation
assert(oper == GT_DIV || oper == GT_MOD);
if (dividend->gtRegNum == targetReg)
{
emit->emitInsBinary(genGetInsForOper(treeNode->gtOper, targetType), size, treeNode, divisor);
}
else if (divisor->isUsedFromReg() && divisor->gtRegNum == targetReg)
{
// It is not possible to generate 2-operand divss or divsd where reg2 = reg1 / reg2
// because divss/divsd reg1, reg2 will over-write reg1. Therefore, in case of AMD64
// LSRA has to make sure that such a register assignment is not generated for floating
// point div/rem operations.
noway_assert(
!"GT_DIV/GT_MOD (float): case of reg2 = reg1 / reg2, LSRA should never generate such a reg assignment");
}
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, dividend->gtRegNum, targetType);
emit->emitInsBinary(genGetInsForOper(treeNode->gtOper, targetType), size, treeNode, divisor);
}
}
else
{
// dividend must be in RAX
genCopyRegIfNeeded(dividend, REG_RAX);
// zero or sign extend rax to rdx
if (oper == GT_UMOD || oper == GT_UDIV)
{
instGen_Set_Reg_To_Zero(EA_PTRSIZE, REG_EDX);
}
else
{
emit->emitIns(INS_cdq, size);
// the cdq instruction writes RDX, So clear the gcInfo for RDX
gcInfo.gcMarkRegSetNpt(RBM_RDX);
}
// Perform the 'targetType' (64-bit or 32-bit) divide instruction
instruction ins;
if (oper == GT_UMOD || oper == GT_UDIV)
{
ins = INS_div;
}
else
{
ins = INS_idiv;
}
emit->emitInsBinary(ins, size, treeNode, divisor);
// DIV/IDIV instructions always store the quotient in RAX and the remainder in RDX.
// Move the result to the desired register, if necessary
if (oper == GT_DIV || oper == GT_UDIV)
{
if (targetReg != REG_RAX)
{
inst_RV_RV(INS_mov, targetReg, REG_RAX, targetType);
}
}
else
{
assert((oper == GT_MOD) || (oper == GT_UMOD));
if (targetReg != REG_RDX)
{
inst_RV_RV(INS_mov, targetReg, REG_RDX, targetType);
}
}
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genCodeForBinary: Generate code for many binary arithmetic operators
// This method is expected to have called genConsumeOperands() before calling it.
//
// Arguments:
// treeNode - The binary operation for which we are generating code.
//
// Return Value:
// None.
//
// Notes:
// Mul and div variants have special constraints on x64 so are not handled here.
// See teh assert below for the operators that are handled.
void CodeGen::genCodeForBinary(GenTree* treeNode)
{
const genTreeOps oper = treeNode->OperGet();
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
#if defined(_TARGET_64BIT_)
assert(oper == GT_OR || oper == GT_XOR || oper == GT_AND || oper == GT_ADD || oper == GT_SUB);
#else // !defined(_TARGET_64BIT_)
assert(oper == GT_OR || oper == GT_XOR || oper == GT_AND || oper == GT_ADD_LO || oper == GT_ADD_HI ||
oper == GT_SUB_LO || oper == GT_SUB_HI || oper == GT_ADD || oper == GT_SUB);
#endif // !defined(_TARGET_64BIT_)
GenTree* op1 = treeNode->gtGetOp1();
GenTree* op2 = treeNode->gtGetOp2();
// Commutative operations can mark op1 as contained or reg-optional to generate "op reg, memop/immed"
if (!op1->isUsedFromReg())
{
assert(treeNode->OperIsCommutative());
assert(op1->isMemoryOp() || op1->IsLocal() || op1->IsCnsNonZeroFltOrDbl() || op1->IsIntCnsFitsInI32() ||
op1->IsRegOptional());
op1 = treeNode->gtGetOp2();
op2 = treeNode->gtGetOp1();
}
instruction ins = genGetInsForOper(treeNode->OperGet(), targetType);
// The arithmetic node must be sitting in a register (since it's not contained)
noway_assert(targetReg != REG_NA);
regNumber op1reg = op1->isUsedFromReg() ? op1->gtRegNum : REG_NA;
regNumber op2reg = op2->isUsedFromReg() ? op2->gtRegNum : REG_NA;
GenTree* dst;
GenTree* src;
// This is the case of reg1 = reg1 op reg2
// We're ready to emit the instruction without any moves
if (op1reg == targetReg)
{
dst = op1;
src = op2;
}
// We have reg1 = reg2 op reg1
// In order for this operation to be correct
// we need that op is a commutative operation so
// we can convert it into reg1 = reg1 op reg2 and emit
// the same code as above
else if (op2reg == targetReg)
{
noway_assert(GenTree::OperIsCommutative(oper));
dst = op2;
src = op1;
}
// now we know there are 3 different operands so attempt to use LEA
else if (oper == GT_ADD && !varTypeIsFloating(treeNode) && !treeNode->gtOverflowEx() // LEA does not set flags
&& (op2->isContainedIntOrIImmed() || op2->isUsedFromReg()) && !treeNode->gtSetFlags())
{
if (op2->isContainedIntOrIImmed())
{
emit->emitIns_R_AR(INS_lea, emitTypeSize(treeNode), targetReg, op1reg,
(int)op2->AsIntConCommon()->IconValue());
}
else
{
assert(op2reg != REG_NA);
emit->emitIns_R_ARX(INS_lea, emitTypeSize(treeNode), targetReg, op1reg, op2reg, 1, 0);
}
genProduceReg(treeNode);
return;
}
// dest, op1 and op2 registers are different:
// reg3 = reg1 op reg2
// We can implement this by issuing a mov:
// reg3 = reg1
// reg3 = reg3 op reg2
else
{
inst_RV_RV(ins_Copy(targetType), targetReg, op1reg, targetType);
regTracker.rsTrackRegCopy(targetReg, op1reg);
gcInfo.gcMarkRegPtrVal(targetReg, targetType);
dst = treeNode;
src = op2;
}
// try to use an inc or dec
if (oper == GT_ADD && !varTypeIsFloating(treeNode) && src->isContainedIntOrIImmed() && !treeNode->gtOverflowEx())
{
if (src->IsIntegralConst(1))
{
emit->emitIns_R(INS_inc, emitTypeSize(treeNode), targetReg);
genProduceReg(treeNode);
return;
}
else if (src->IsIntegralConst(-1))
{
emit->emitIns_R(INS_dec, emitTypeSize(treeNode), targetReg);
genProduceReg(treeNode);
return;
}
}
regNumber r = emit->emitInsBinary(ins, emitTypeSize(treeNode), dst, src);
noway_assert(r == targetReg);
if (treeNode->gtOverflowEx())
{
#if !defined(_TARGET_64BIT_)
assert(oper == GT_ADD || oper == GT_SUB || oper == GT_ADD_HI || oper == GT_SUB_HI);
#else
assert(oper == GT_ADD || oper == GT_SUB);
#endif
genCheckOverflow(treeNode);
}
genProduceReg(treeNode);
}
//------------------------------------------------------------------------
// genCodeForMul: Generate code for a MUL operation.
//
// Arguments:
// treeNode - the node to generate the code for
//
void CodeGen::genCodeForMul(GenTreeOp* treeNode)
{
assert(treeNode->OperIs(GT_MUL));
regNumber targetReg = treeNode->gtRegNum;
var_types targetType = treeNode->TypeGet();
emitter* emit = getEmitter();
instruction ins;
emitAttr size = emitTypeSize(treeNode);
bool isUnsignedMultiply = ((treeNode->gtFlags & GTF_UNSIGNED) != 0);
bool requiresOverflowCheck = treeNode->gtOverflowEx();
GenTree* op1 = treeNode->gtGetOp1();
GenTree* op2 = treeNode->gtGetOp2();
// there are 3 forms of x64 multiply:
// 1-op form with 128 result: RDX:RAX = RAX * rm
// 2-op form: reg *= rm
// 3-op form: reg = rm * imm
genConsumeOperands(treeNode->AsOp());
// This matches the 'mul' lowering in Lowering::SetMulOpCounts()
//
// immOp :: Only one operand can be an immediate
// rmOp :: Only one operand can be a memory op.
// regOp :: A register op (especially the operand that matches 'targetReg')
// (can be nullptr when we have both a memory op and an immediate op)
GenTree* immOp = nullptr;
GenTree* rmOp = op1;
GenTree* regOp;
if (op2->isContainedIntOrIImmed())
{
immOp = op2;
}
else if (op1->isContainedIntOrIImmed())
{
immOp = op1;
rmOp = op2;
}
if (immOp != nullptr)
{
// This must be a non-floating point operation.
assert(!varTypeIsFloating(treeNode));
// CQ: When possible use LEA for mul by imm 3, 5 or 9
ssize_t imm = immOp->AsIntConCommon()->IconValue();
if (!requiresOverflowCheck && rmOp->isUsedFromReg() && ((imm == 3) || (imm == 5) || (imm == 9)))
{
// We will use the LEA instruction to perform this multiply
// Note that an LEA with base=x, index=x and scale=(imm-1) computes x*imm when imm=3,5 or 9.
unsigned int scale = (unsigned int)(imm - 1);
getEmitter()->emitIns_R_ARX(INS_lea, size, targetReg, rmOp->gtRegNum, rmOp->gtRegNum, scale, 0);
}
else if (!requiresOverflowCheck && rmOp->isUsedFromReg() && (imm == genFindLowestBit(imm)) && (imm != 0))
{
// Use shift for constant multiply when legal
uint64_t zextImm = static_cast<uint64_t>(static_cast<size_t>(imm));
unsigned int shiftAmount = genLog2(zextImm);
if (targetReg != rmOp->gtRegNum)
{
// Copy reg src to dest register
inst_RV_RV(ins_Copy(targetType), targetReg, rmOp->gtRegNum, targetType);
}
inst_RV_SH(INS_shl, size, targetReg, shiftAmount);
}
else
{
// use the 3-op form with immediate
ins = getEmitter()->inst3opImulForReg(targetReg);
emit->emitInsBinary(ins, size, rmOp, immOp);
}
}
else // we have no contained immediate operand
{
regOp = op1;
rmOp = op2;
regNumber mulTargetReg = targetReg;
if (isUnsignedMultiply && requiresOverflowCheck)