-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
SubstrateAMD64Backend.java
1681 lines (1486 loc) 路 84.8 KB
/
SubstrateAMD64Backend.java
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
/*
* Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.core.graal.amd64;
import static com.oracle.svm.core.graal.code.SubstrateBackend.SubstrateMarkId.PROLOGUE_DECD_RSP;
import static com.oracle.svm.core.graal.code.SubstrateBackend.SubstrateMarkId.PROLOGUE_END;
import static com.oracle.svm.core.util.VMError.shouldNotReachHere;
import static com.oracle.svm.core.util.VMError.unsupportedFeature;
import static jdk.graal.compiler.lir.LIRInstruction.OperandFlag.REG;
import static jdk.graal.compiler.lir.LIRValueUtil.asConstantValue;
import static jdk.graal.compiler.lir.LIRValueUtil.differentRegisters;
import static jdk.vm.ci.amd64.AMD64.rax;
import static jdk.vm.ci.amd64.AMD64.rbp;
import static jdk.vm.ci.amd64.AMD64.rsp;
import static jdk.vm.ci.amd64.AMD64.CPUFeature.AVX;
import static jdk.vm.ci.code.ValueUtil.asRegister;
import static jdk.vm.ci.code.ValueUtil.isRegister;
import java.util.Arrays;
import java.util.Collection;
import java.util.EnumSet;
import java.util.function.BiConsumer;
import com.oracle.svm.core.graal.code.CGlobalDataInfo;
import org.graalvm.collections.EconomicMap;
import org.graalvm.nativeimage.ImageSingletons;
import com.oracle.svm.core.CPUFeatureAccess;
import com.oracle.svm.core.FrameAccess;
import com.oracle.svm.core.ReservedRegisters;
import com.oracle.svm.core.SubstrateControlFlowIntegrity;
import com.oracle.svm.core.SubstrateOptions;
import com.oracle.svm.core.SubstrateUtil;
import com.oracle.svm.core.amd64.AMD64CPUFeatureAccess;
import com.oracle.svm.core.code.BaseLayerMethodAccessor;
import com.oracle.svm.core.config.ConfigurationValues;
import com.oracle.svm.core.cpufeature.Stubs;
import com.oracle.svm.core.deopt.Deoptimizer;
import com.oracle.svm.core.graal.RuntimeCompilation;
import com.oracle.svm.core.graal.code.AssignedLocation;
import com.oracle.svm.core.graal.code.PatchConsumerFactory;
import com.oracle.svm.core.graal.code.StubCallingConvention;
import com.oracle.svm.core.graal.code.SubstrateBackend;
import com.oracle.svm.core.graal.code.SubstrateCallingConvention;
import com.oracle.svm.core.graal.code.SubstrateCallingConventionKind;
import com.oracle.svm.core.graal.code.SubstrateCallingConventionType;
import com.oracle.svm.core.graal.code.SubstrateCompiledCode;
import com.oracle.svm.core.graal.code.SubstrateDataBuilder;
import com.oracle.svm.core.graal.code.SubstrateDebugInfoBuilder;
import com.oracle.svm.core.graal.code.SubstrateLIRGenerator;
import com.oracle.svm.core.graal.code.SubstrateNodeLIRBuilder;
import com.oracle.svm.core.graal.lir.VerificationMarkerOp;
import com.oracle.svm.core.graal.meta.KnownOffsets;
import com.oracle.svm.core.graal.meta.SharedConstantReflectionProvider;
import com.oracle.svm.core.graal.meta.SubstrateForeignCallLinkage;
import com.oracle.svm.core.graal.meta.SubstrateRegisterConfig;
import com.oracle.svm.core.graal.nodes.CGlobalDataLoadAddressNode;
import com.oracle.svm.core.graal.nodes.ComputedIndirectCallTargetNode;
import com.oracle.svm.core.graal.nodes.ComputedIndirectCallTargetNode.Computation;
import com.oracle.svm.core.graal.nodes.ComputedIndirectCallTargetNode.FieldLoad;
import com.oracle.svm.core.graal.nodes.ComputedIndirectCallTargetNode.FieldLoadIfZero;
import com.oracle.svm.core.heap.ReferenceAccess;
import com.oracle.svm.core.heap.SubstrateReferenceMapBuilder;
import com.oracle.svm.core.meta.CompressedNullConstant;
import com.oracle.svm.core.meta.SharedField;
import com.oracle.svm.core.meta.SharedMethod;
import com.oracle.svm.core.meta.SubstrateMethodPointerConstant;
import com.oracle.svm.core.meta.SubstrateObjectConstant;
import com.oracle.svm.core.nodes.SafepointCheckNode;
import com.oracle.svm.core.thread.VMThreads.StatusSupport;
import com.oracle.svm.core.util.VMError;
import jdk.graal.compiler.asm.BranchTargetOutOfBoundsException;
import jdk.graal.compiler.asm.Label;
import jdk.graal.compiler.asm.amd64.AMD64Address;
import jdk.graal.compiler.asm.amd64.AMD64Assembler;
import jdk.graal.compiler.asm.amd64.AMD64BaseAssembler;
import jdk.graal.compiler.asm.amd64.AMD64MacroAssembler;
import jdk.graal.compiler.code.CompilationResult;
import jdk.graal.compiler.core.amd64.AMD64ArithmeticLIRGenerator;
import jdk.graal.compiler.core.amd64.AMD64LIRGenerator;
import jdk.graal.compiler.core.amd64.AMD64LIRKindTool;
import jdk.graal.compiler.core.amd64.AMD64MoveFactory;
import jdk.graal.compiler.core.amd64.AMD64MoveFactoryBase;
import jdk.graal.compiler.core.amd64.AMD64NodeLIRBuilder;
import jdk.graal.compiler.core.amd64.AMD64NodeMatchRules;
import jdk.graal.compiler.core.common.CompilationIdentifier;
import jdk.graal.compiler.core.common.CompressEncoding;
import jdk.graal.compiler.core.common.GraalOptions;
import jdk.graal.compiler.core.common.LIRKind;
import jdk.graal.compiler.core.common.Stride;
import jdk.graal.compiler.core.common.alloc.RegisterAllocationConfig;
import jdk.graal.compiler.core.common.memory.MemoryExtendKind;
import jdk.graal.compiler.core.common.memory.MemoryOrderMode;
import jdk.graal.compiler.core.common.spi.ForeignCallDescriptor;
import jdk.graal.compiler.core.common.spi.ForeignCallLinkage;
import jdk.graal.compiler.core.common.spi.LIRKindTool;
import jdk.graal.compiler.core.common.type.CompressibleConstant;
import jdk.graal.compiler.core.gen.DebugInfoBuilder;
import jdk.graal.compiler.core.gen.LIRGenerationProvider;
import jdk.graal.compiler.core.gen.NodeLIRBuilder;
import jdk.graal.compiler.debug.DebugContext;
import jdk.graal.compiler.debug.GraalError;
import jdk.graal.compiler.lir.ConstantValue;
import jdk.graal.compiler.lir.LIR;
import jdk.graal.compiler.lir.LIRFrameState;
import jdk.graal.compiler.lir.LIRInstruction;
import jdk.graal.compiler.lir.LIRInstructionClass;
import jdk.graal.compiler.lir.LabelRef;
import jdk.graal.compiler.lir.Opcode;
import jdk.graal.compiler.lir.StandardOp.BlockEndOp;
import jdk.graal.compiler.lir.StandardOp.LoadConstantOp;
import jdk.graal.compiler.lir.Variable;
import jdk.graal.compiler.lir.amd64.AMD64AddressValue;
import jdk.graal.compiler.lir.amd64.AMD64BreakpointOp;
import jdk.graal.compiler.lir.amd64.AMD64Call;
import jdk.graal.compiler.lir.amd64.AMD64ControlFlow.BranchOp;
import jdk.graal.compiler.lir.amd64.AMD64FrameMap;
import jdk.graal.compiler.lir.amd64.AMD64FrameMapBuilder;
import jdk.graal.compiler.lir.amd64.AMD64LIRInstruction;
import jdk.graal.compiler.lir.amd64.AMD64Move;
import jdk.graal.compiler.lir.amd64.AMD64Move.MoveFromConstOp;
import jdk.graal.compiler.lir.amd64.AMD64Move.PointerCompressionOp;
import jdk.graal.compiler.lir.amd64.AMD64PrefetchOp;
import jdk.graal.compiler.lir.amd64.AMD64ReadProcid;
import jdk.graal.compiler.lir.amd64.AMD64ReadTimestampCounterWithProcid;
import jdk.graal.compiler.lir.amd64.AMD64VZeroUpper;
import jdk.graal.compiler.lir.asm.CompilationResultBuilder;
import jdk.graal.compiler.lir.asm.CompilationResultBuilderFactory;
import jdk.graal.compiler.lir.asm.DataBuilder;
import jdk.graal.compiler.lir.asm.EntryPointDecorator;
import jdk.graal.compiler.lir.asm.FrameContext;
import jdk.graal.compiler.lir.framemap.FrameMap;
import jdk.graal.compiler.lir.framemap.FrameMapBuilder;
import jdk.graal.compiler.lir.framemap.FrameMapBuilderTool;
import jdk.graal.compiler.lir.framemap.ReferenceMapBuilder;
import jdk.graal.compiler.lir.gen.LIRGenerationResult;
import jdk.graal.compiler.lir.gen.LIRGeneratorTool;
import jdk.graal.compiler.lir.gen.MoveFactory;
import jdk.graal.compiler.lir.gen.MoveFactory.BackupSlotProvider;
import jdk.graal.compiler.nodes.BreakpointNode;
import jdk.graal.compiler.nodes.CallTargetNode;
import jdk.graal.compiler.nodes.DirectCallTargetNode;
import jdk.graal.compiler.nodes.IndirectCallTargetNode;
import jdk.graal.compiler.nodes.InvokeWithExceptionNode;
import jdk.graal.compiler.nodes.LogicNode;
import jdk.graal.compiler.nodes.LoweredCallTargetNode;
import jdk.graal.compiler.nodes.NodeView;
import jdk.graal.compiler.nodes.ParameterNode;
import jdk.graal.compiler.nodes.SafepointNode;
import jdk.graal.compiler.nodes.StructuredGraph;
import jdk.graal.compiler.nodes.ValueNode;
import jdk.graal.compiler.nodes.spi.CoreProviders;
import jdk.graal.compiler.nodes.spi.NodeLIRBuilderTool;
import jdk.graal.compiler.nodes.spi.NodeValueMap;
import jdk.graal.compiler.options.OptionValues;
import jdk.graal.compiler.phases.BasePhase;
import jdk.graal.compiler.phases.common.AddressLoweringByNodePhase;
import jdk.graal.compiler.phases.util.Providers;
import jdk.graal.compiler.replacements.amd64.AMD64IntrinsicStubs;
import jdk.vm.ci.amd64.AMD64;
import jdk.vm.ci.amd64.AMD64.CPUFeature;
import jdk.vm.ci.amd64.AMD64Kind;
import jdk.vm.ci.code.CallingConvention;
import jdk.vm.ci.code.CodeCacheProvider;
import jdk.vm.ci.code.CodeUtil;
import jdk.vm.ci.code.CompilationRequest;
import jdk.vm.ci.code.CompiledCode;
import jdk.vm.ci.code.Register;
import jdk.vm.ci.code.RegisterAttributes;
import jdk.vm.ci.code.RegisterConfig;
import jdk.vm.ci.code.RegisterValue;
import jdk.vm.ci.code.StackSlot;
import jdk.vm.ci.code.TargetDescription;
import jdk.vm.ci.code.ValueUtil;
import jdk.vm.ci.meta.AllocatableValue;
import jdk.vm.ci.meta.Constant;
import jdk.vm.ci.meta.ConstantReflectionProvider;
import jdk.vm.ci.meta.JavaConstant;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.JavaType;
import jdk.vm.ci.meta.ResolvedJavaMethod;
import jdk.vm.ci.meta.Value;
public class SubstrateAMD64Backend extends SubstrateBackend implements LIRGenerationProvider {
protected static CompressEncoding getCompressEncoding() {
return ImageSingletons.lookup(CompressEncoding.class);
}
public SubstrateAMD64Backend(Providers providers) {
super(providers);
}
/**
* Returns {@code true} if a call from run-time compiled code to AOT compiled code is an AVX-SSE
* transition. For AOT compilations, this always returns {@code false}.
*/
@SuppressWarnings("unlikely-arg-type")
public static boolean runtimeToAOTIsAvxSseTransition(TargetDescription target) {
if (SubstrateUtil.HOSTED) {
// hosted does not need to care about this
return false;
}
if (!AMD64CPUFeatureAccess.canUpdateCPUFeatures()) {
// same CPU features as hosted
return false;
}
var arch = (AMD64) target.arch;
var hostedCPUFeatures = ImageSingletons.lookup(CPUFeatureAccess.class).buildtimeCPUFeatures();
var runtimeCPUFeatures = arch.getFeatures();
return !hostedCPUFeatures.contains(AVX) && runtimeCPUFeatures.contains(AVX);
}
/**
* When software control flow integrity is enabled, the CFITargetRegister is overwritten in
* calls. This must be explicitly stated to ensure the register allocator knows this register
* will be killed by the call.
*/
private static AllocatableValue getCFITargetRegister() {
return SubstrateControlFlowIntegrity.useSoftwareCFI() ? SubstrateControlFlowIntegrity.singleton().getCFITargetRegister().asValue() : Value.ILLEGAL;
}
@Opcode("CALL_DIRECT")
public static class SubstrateAMD64DirectCallOp extends AMD64Call.DirectCallOp {
public static final LIRInstructionClass<SubstrateAMD64DirectCallOp> TYPE = LIRInstructionClass.create(SubstrateAMD64DirectCallOp.class);
private final int newThreadStatus;
@Use({REG, OperandFlag.ILLEGAL}) private Value javaFrameAnchor;
@Temp({REG, OperandFlag.ILLEGAL}) private Value javaFrameAnchorTemp;
private final boolean destroysCallerSavedRegisters;
@Temp({REG, OperandFlag.ILLEGAL}) private Value exceptionTemp;
@Temp({REG, OperandFlag.ILLEGAL}) private AllocatableValue cfiTargetRegister;
public SubstrateAMD64DirectCallOp(ResolvedJavaMethod callTarget, Value result, Value[] parameters, Value[] temps, LIRFrameState state,
Value javaFrameAnchor, Value javaFrameAnchorTemp, int newThreadStatus, boolean destroysCallerSavedRegisters, Value exceptionTemp) {
super(TYPE, callTarget, result, parameters, temps, state);
this.newThreadStatus = newThreadStatus;
this.javaFrameAnchor = javaFrameAnchor;
this.javaFrameAnchorTemp = javaFrameAnchorTemp;
this.destroysCallerSavedRegisters = destroysCallerSavedRegisters;
this.exceptionTemp = exceptionTemp;
this.cfiTargetRegister = getCFITargetRegister();
assert differentRegisters(parameters, temps, javaFrameAnchor, javaFrameAnchorTemp, cfiTargetRegister);
}
@Override
public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) {
maybeTransitionToNative(crb, masm, javaFrameAnchor, javaFrameAnchorTemp, state, newThreadStatus);
AMD64Call.directCall(crb, masm, callTarget, null, false, state);
}
@Override
public boolean destroysCallerSavedRegisters() {
return destroysCallerSavedRegisters;
}
}
@Opcode("CALL_INDIRECT")
public static class SubstrateAMD64IndirectCallOp extends AMD64Call.IndirectCallOp {
public static final LIRInstructionClass<SubstrateAMD64IndirectCallOp> TYPE = LIRInstructionClass.create(SubstrateAMD64IndirectCallOp.class);
private final int newThreadStatus;
@Use({REG, OperandFlag.ILLEGAL}) private Value javaFrameAnchor;
@Temp({REG, OperandFlag.ILLEGAL}) private Value javaFrameAnchorTemp;
private final boolean destroysCallerSavedRegisters;
@Temp({REG, OperandFlag.ILLEGAL}) private Value exceptionTemp;
private final BiConsumer<CompilationResultBuilder, Integer> offsetRecorder;
@Def({REG}) private Value[] multipleResults;
@Temp({REG, OperandFlag.ILLEGAL}) AllocatableValue cfiTargetRegister;
private SubstrateCallingConventionType callingConventionType;
public SubstrateAMD64IndirectCallOp(ResolvedJavaMethod callTarget, Value result, Value[] parameters, Value[] temps, Value targetAddress,
LIRFrameState state, Value javaFrameAnchor, Value javaFrameAnchorTemp, int newThreadStatus, boolean destroysCallerSavedRegisters, Value exceptionTemp,
BiConsumer<CompilationResultBuilder, Integer> offsetRecorder) {
this(callTarget, result, parameters, temps, targetAddress, state, javaFrameAnchor, javaFrameAnchorTemp, newThreadStatus, destroysCallerSavedRegisters, exceptionTemp, offsetRecorder,
new Value[0], null);
}
public SubstrateAMD64IndirectCallOp(ResolvedJavaMethod callTarget, Value result, Value[] parameters, Value[] temps, Value targetAddress,
LIRFrameState state, Value javaFrameAnchor, Value javaFrameAnchorTemp, int newThreadStatus, boolean destroysCallerSavedRegisters, Value exceptionTemp,
BiConsumer<CompilationResultBuilder, Integer> offsetRecorder, Value[] multipleResults, SubstrateCallingConventionType callingConventionType) {
super(TYPE, callTarget, result, parameters, temps, targetAddress, state);
this.newThreadStatus = newThreadStatus;
this.javaFrameAnchor = javaFrameAnchor;
this.javaFrameAnchorTemp = javaFrameAnchorTemp;
this.destroysCallerSavedRegisters = destroysCallerSavedRegisters;
this.exceptionTemp = exceptionTemp;
this.offsetRecorder = offsetRecorder;
this.multipleResults = multipleResults;
this.callingConventionType = callingConventionType;
this.cfiTargetRegister = getCFITargetRegister();
assert differentRegisters(parameters, temps, targetAddress, javaFrameAnchor, javaFrameAnchorTemp, cfiTargetRegister);
}
@Override
public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) {
maybeTransitionToNative(crb, masm, javaFrameAnchor, javaFrameAnchorTemp, state, newThreadStatus);
int offset = AMD64Call.indirectCall(crb, masm, asRegister(targetAddress), callTarget, state, callingConventionType);
if (offsetRecorder != null) {
offsetRecorder.accept(crb, offset);
}
}
@Override
public boolean destroysCallerSavedRegisters() {
return destroysCallerSavedRegisters;
}
}
@Opcode("CALL_COMPUTED_INDIRECT")
public static class SubstrateAMD64ComputedIndirectCallOp extends AMD64Call.MethodCallOp {
public static final LIRInstructionClass<SubstrateAMD64ComputedIndirectCallOp> TYPE = LIRInstructionClass.create(SubstrateAMD64ComputedIndirectCallOp.class);
// addressBase is killed during code generation
@Use({REG}) private Value addressBase;
@Temp({REG}) private Value addressBaseTemp;
@Temp({REG, OperandFlag.ILLEGAL}) private Value exceptionTemp;
@Temp({REG, OperandFlag.ILLEGAL}) private AllocatableValue cfiTargetRegister;
private final Computation[] addressComputation;
private final LIRKindTool lirKindTool;
private final ConstantReflectionProvider constantReflection;
public SubstrateAMD64ComputedIndirectCallOp(ResolvedJavaMethod callTarget, Value result, Value[] parameters, Value[] temps,
Value addressBase, Computation[] addressComputation,
LIRFrameState state, Value exceptionTemp, LIRKindTool lirKindTool, ConstantReflectionProvider constantReflection) {
super(TYPE, callTarget, result, parameters, temps, state);
this.addressBase = this.addressBaseTemp = addressBase;
this.exceptionTemp = exceptionTemp;
this.addressComputation = addressComputation;
this.cfiTargetRegister = getCFITargetRegister();
this.lirKindTool = lirKindTool;
this.constantReflection = constantReflection;
assert differentRegisters(parameters, temps, addressBase, cfiTargetRegister);
}
@Override
public void emitCode(CompilationResultBuilder crb, AMD64MacroAssembler masm) {
VMError.guarantee(SubstrateOptions.SpawnIsolates.getValue(), "Memory access without isolates is not implemented");
int compressionShift = ReferenceAccess.singleton().getCompressionShift();
Register computeRegister = asRegister(addressBase);
AMD64BaseAssembler.OperandSize lastOperandSize = AMD64BaseAssembler.OperandSize.get(addressBase.getPlatformKind());
boolean nextMemoryAccessNeedsDecompress = false;
for (var computation : addressComputation) {
/*
* Both supported computations are field loads. The difference is the memory address
* (which either reads from the current computed value, or from a newly provided
* constant object).
*/
SharedField field;
AMD64Address memoryAddress;
Label done = null;
if (computation instanceof FieldLoad) {
field = (SharedField) ((FieldLoad) computation).getField();
if (nextMemoryAccessNeedsDecompress) {
/*
* Manual implementation of the only compressed reference scheme that is
* currently in use: references are relative to the heap base register, with
* an optional shift that is known to be a valid addressing mode.
*/
memoryAddress = new AMD64Address(ReservedRegisters.singleton().getHeapBaseRegister(),
computeRegister, Stride.fromLog2(compressionShift),
field.getOffset());
} else {
memoryAddress = new AMD64Address(computeRegister, field.getOffset());
}
} else if (computation instanceof FieldLoadIfZero) {
done = new Label();
VMError.guarantee(!nextMemoryAccessNeedsDecompress, "Comparison with compressed null value not implemented");
masm.cmpAndJcc(lastOperandSize, computeRegister, 0, AMD64Assembler.ConditionFlag.NotEqual, done, true);
JavaConstant object = ((FieldLoadIfZero) computation).getObject();
field = (SharedField) ((FieldLoadIfZero) computation).getField();
/*
* Loading a field from a constant object can be expressed with a single mov
* instruction: the object is in the image heap, so the displacement relative to
* the heap base is a constant.
*/
memoryAddress = new AMD64Address(ReservedRegisters.singleton().getHeapBaseRegister(),
Register.None, Stride.S1,
field.getOffset() + addressDisplacement(object, constantReflection),
addressDisplacementAnnotation(object));
} else {
throw VMError.shouldNotReachHere("Computation is not supported yet: " + computation.getClass().getTypeName());
}
switch (field.getStorageKind()) {
case Int:
lastOperandSize = AMD64BaseAssembler.OperandSize.DWORD;
nextMemoryAccessNeedsDecompress = false;
break;
case Long:
lastOperandSize = AMD64BaseAssembler.OperandSize.QWORD;
nextMemoryAccessNeedsDecompress = false;
break;
case Object:
lastOperandSize = AMD64BaseAssembler.OperandSize.get(lirKindTool.getNarrowOopKind().getPlatformKind());
nextMemoryAccessNeedsDecompress = true;
break;
default:
throw VMError.shouldNotReachHere("Kind is not supported yet: " + field.getStorageKind());
}
AMD64Assembler.AMD64RMOp.MOV.emit(masm, lastOperandSize, computeRegister, memoryAddress);
if (done != null) {
masm.bind(done);
}
}
VMError.guarantee(!nextMemoryAccessNeedsDecompress, "Final computed call target address is not a primitive value");
AMD64Call.indirectCall(crb, masm, computeRegister, callTarget, state);
}
}
public static Object addressDisplacementAnnotation(JavaConstant constant) {
if (SubstrateUtil.HOSTED) {
/*
* AOT compilation during image generation happens before the image heap objects are
* layouted. So the offset of the constant is not known yet during compilation time, and
* instead needs to be patched in later. We annotate the machine code with the constant
* that needs to be patched in.
*/
return constant;
} else {
return null;
}
}
public static int addressDisplacement(JavaConstant constant, ConstantReflectionProvider constantReflection) {
if (SubstrateUtil.HOSTED) {
return 0;
} else {
/*
* For JIT compilation at run time, the image heap is known and immutable, so the offset
* of the constant can be emitted immediately. No patching is required later on.
*/
return ((SharedConstantReflectionProvider) constantReflection).getImageHeapOffset(constant);
}
}
static void maybeTransitionToNative(CompilationResultBuilder crb, AMD64MacroAssembler masm, Value javaFrameAnchor, Value temp, LIRFrameState state,
int newThreadStatus) {
if (ValueUtil.isIllegal(javaFrameAnchor)) {
/* Not a call that needs to set up a JavaFrameAnchor. */
assert newThreadStatus == StatusSupport.STATUS_ILLEGAL;
return;
}
assert StatusSupport.isValidStatus(newThreadStatus);
Register anchor = ValueUtil.asRegister(javaFrameAnchor);
Register lastJavaIP = ValueUtil.asRegister(temp);
/*
* Record the last Java instruction pointer. Note that this is actually not the return
* address of the call, but that is fine. Patching the offset of the lea instruction would
* be possible but more complex than just recording the reference map information twice for
* different instructions.
*
* We record the instruction to load the current instruction pointer as a Call infopoint, so
* that the same metadata is emitted in the machine code as for a normal call instruction.
* We are already in the code emission from a single LIR instruction. So the register
* allocator cannot interfere anymore, the reference map for the two calls is produced from
* the same point regarding to register spilling.
*
* The lea loads the offset 0 relative to the end of the lea instruction, which is the same
* as for a call instruction. So the usual AMD64 specific semantics that all the metadata is
* registered for the end of the instruction just works.
*/
int startPos = masm.position();
masm.leaq(lastJavaIP, new AMD64Address(AMD64.rip));
/*
* We always record an indirect call, because the direct/indirect flag of the safepoint is
* not used (the target method of the recorded call is null anyway).
*/
crb.recordIndirectCall(startPos, masm.position(), null, state);
KnownOffsets knownOffsets = KnownOffsets.singleton();
masm.movq(new AMD64Address(anchor, knownOffsets.getJavaFrameAnchorLastIPOffset()), lastJavaIP);
masm.movq(new AMD64Address(anchor, knownOffsets.getJavaFrameAnchorLastSPOffset()), AMD64.rsp);
/* Change the VMThread status from Java to Native. */
masm.movl(new AMD64Address(ReservedRegisters.singleton().getThreadRegister(), knownOffsets.getVMThreadStatusOffset()), newThreadStatus);
}
/**
* Marks a point that is unreachable because a previous instruction never returns.
*/
@Opcode("DEAD_END")
public static class DeadEndOp extends LIRInstruction implements BlockEndOp {
public static final LIRInstructionClass<DeadEndOp> TYPE = LIRInstructionClass.create(DeadEndOp.class);
public DeadEndOp() {
super(TYPE);
}
@Override
public void emitCode(CompilationResultBuilder crb) {
if (SubstrateUtil.assertionsEnabled()) {
((AMD64Assembler) crb.asm).int3();
}
}
}
protected static final class SubstrateLIRGenerationResult extends LIRGenerationResult {
private final SharedMethod method;
public SubstrateLIRGenerationResult(CompilationIdentifier compilationId, LIR lir, FrameMapBuilder frameMapBuilder, CallingConvention callingConvention,
RegisterAllocationConfig registerAllocationConfig, SharedMethod method) {
super(compilationId, lir, frameMapBuilder, registerAllocationConfig, callingConvention);
this.method = method;
if (method.hasCalleeSavedRegisters()) {
AMD64CalleeSavedRegisters calleeSavedRegisters = AMD64CalleeSavedRegisters.singleton();
FrameMap frameMap = ((FrameMapBuilderTool) frameMapBuilder).getFrameMap();
int registerSaveAreaSizeInBytes = calleeSavedRegisters.getSaveAreaSize();
StackSlot calleeSaveArea = frameMap.allocateStackMemory(registerSaveAreaSizeInBytes, frameMap.getTarget().wordSize);
/*
* The offset of the callee save area must be fixed early during image generation.
* It is accessed when compiling methods that have a call with callee-saved calling
* convention. Here we verify that offset computed earlier is the same as the offset
* actually reserved.
*/
calleeSavedRegisters.verifySaveAreaOffsetInFrame(calleeSaveArea.getRawOffset());
}
if (method.canDeoptimize() || method.isDeoptTarget()) {
((FrameMapBuilderTool) frameMapBuilder).getFrameMap().reserveOutgoing(16);
}
}
public SharedMethod getMethod() {
return method;
}
@Override
public boolean emitIndirectTargetBranchMarkers() {
return SubstrateControlFlowIntegrity.useSoftwareCFI();
}
}
/**
* Inserts a {@linkplain AMD64VZeroUpper vzeroupper} instruction before calls that are an
* AVX-SSE transition.
*
* The following cases are distinguished:
*
* First, check whether a run-time compiled method calling an AOT compiled method is an AVX-SSE
* transition, i.e., AVX was not enabled for AOT but is enabled for JIT compilation.
*
* Only emit vzeroupper if the call uses a
* {@linkplain SubstrateAMD64LIRGenerator#getDestroysCallerSavedRegisters caller-saved} calling
* convention. For {@link StubCallingConvention stub calling convention} calls, which are
* {@linkplain SharedMethod#hasCalleeSavedRegisters() callee-saved}, all handling is done on the
* callee side.
*
* No vzeroupper is emitted for {@linkplain #isRuntimeToRuntimeCall runtime-to-runtime calls},
* because both, the caller and the callee, have been compiled using the CPU features.
*/
private void vzeroupperBeforeCall(SubstrateAMD64LIRGenerator gen, Value[] arguments, LIRFrameState callState, SharedMethod targetMethod) {
// TODO maybe avoid vzeroupper if the callee does not use SSE (cf. hsLinkage.mayContainFP())
if (runtimeToAOTIsAvxSseTransition(gen.target()) && gen.getDestroysCallerSavedRegisters(targetMethod) && !isRuntimeToRuntimeCall(callState)) {
/*
* We exclude the argument registers from the zeroing LIR instruction since it violates
* the LIR semantics of @Temp that values must not be live. Note that the emitted
* machine instruction actually zeros _all_ XMM registers which is fine since we know
* that their upper half is not used.
*/
gen.append(new AMD64VZeroUpper(arguments, gen.getRegisterConfig()));
}
}
protected class SubstrateAMD64LIRGenerator extends AMD64LIRGenerator implements SubstrateLIRGenerator {
public SubstrateAMD64LIRGenerator(LIRKindTool lirKindTool, AMD64ArithmeticLIRGenerator arithmeticLIRGen, MoveFactory moveFactory, Providers providers, LIRGenerationResult lirGenRes) {
super(lirKindTool, arithmeticLIRGen, null, moveFactory, providers, lirGenRes);
}
@Override
public void emitReturn(JavaKind kind, Value input) {
AllocatableValue operand = Value.ILLEGAL;
if (input != null) {
operand = resultOperandFor(kind, input.getValueKind());
emitMove(operand, input);
}
append(emitReturnOp(operand));
}
protected AMD64ReturnOp emitReturnOp(AllocatableValue operand) {
return new AMD64ReturnOp(operand);
}
@Override
public SubstrateLIRGenerationResult getResult() {
return (SubstrateLIRGenerationResult) super.getResult();
}
@Override
public SubstrateRegisterConfig getRegisterConfig() {
return (SubstrateRegisterConfig) super.getRegisterConfig();
}
// @Override
// public boolean canEliminateRedundantMoves() {
// if (getResult().getMethod().isDeoptTarget()) {
// /*
// * Redundant move elimination can extend the liferanges of intervals, even over
// * method calls. This would introduce new stack slots which are live for a method
// * call, but not recognized during register allocation.
// */
// return false;
// }
// return true;
// }
protected boolean getDestroysCallerSavedRegisters(ResolvedJavaMethod targetMethod) {
if (getResult().getMethod().isDeoptTarget()) {
/*
* The Deoptimizer cannot restore register values, so in a deoptimization target
* method all registers must always be caller saved. It is of course inefficient to
* caller-save all registers and then invoke a method that callee-saves all
* registers again. But deoptimization entry point methods cannot be optimized
* aggressively anyway.
*/
return true;
}
return targetMethod == null || !((SharedMethod) targetMethod).hasCalleeSavedRegisters();
}
@Override
protected Value emitIndirectForeignCallAddress(ForeignCallLinkage linkage) {
SubstrateForeignCallLinkage callTarget = (SubstrateForeignCallLinkage) linkage;
SharedMethod targetMethod = (SharedMethod) callTarget.getMethod();
if (SubstrateUtil.HOSTED && targetMethod.forceIndirectCall()) {
/*
* Load the absolute address of the target method from the method entry stored in
* the data section.
*/
CGlobalDataInfo methodDataInfo = BaseLayerMethodAccessor.singleton().getMethodData(targetMethod);
AllocatableValue methodPointerAddress = newVariable(getLIRKindTool().getWordKind());
append(new AMD64CGlobalDataLoadAddressOp(methodDataInfo, methodPointerAddress));
AMD64AddressValue methodTableEntryAddress = new AMD64AddressValue(getLIRKindTool().getWordKind(), methodPointerAddress, Value.ILLEGAL, Stride.S1, 0);
return getArithmetic().emitLoad(getLIRKindTool().getWordKind(), methodTableEntryAddress, null, MemoryOrderMode.PLAIN, MemoryExtendKind.DEFAULT);
}
if (!shouldEmitOnlyIndirectCalls()) {
return null;
}
Value codeOffsetInImage = emitConstant(getLIRKindTool().getWordKind(), JavaConstant.forLong(targetMethod.getImageCodeOffset()));
Value codeInfo = emitJavaConstant(SubstrateObjectConstant.forObject(targetMethod.getImageCodeInfo()));
Value codeStartField = new AMD64AddressValue(getLIRKindTool().getWordKind(), asAllocatable(codeInfo), KnownOffsets.singleton().getImageCodeInfoCodeStartOffset());
Value codeStart = getArithmetic().emitLoad(getLIRKindTool().getWordKind(), codeStartField, null, MemoryOrderMode.PLAIN, MemoryExtendKind.DEFAULT);
return getArithmetic().emitAdd(codeStart, codeOffsetInImage, false);
}
@Override
protected void emitForeignCallOp(ForeignCallLinkage linkage, Value targetAddress, Value result, Value[] arguments, Value[] temps, LIRFrameState info) {
SubstrateForeignCallLinkage callTarget = (SubstrateForeignCallLinkage) linkage;
SharedMethod targetMethod = (SharedMethod) callTarget.getMethod();
Value exceptionTemp = getExceptionTemp(info != null && info.exceptionEdge != null);
vzeroupperBeforeCall(this, arguments, info, targetMethod);
if (shouldEmitOnlyIndirectCalls() || targetMethod.forceIndirectCall()) {
AllocatableValue targetRegister = AMD64.rax.asValue(FrameAccess.getWordStamp().getLIRKind(getLIRKindTool()));
emitMove(targetRegister, targetAddress); // targetAddress is a CFunctionPointer
append(new SubstrateAMD64IndirectCallOp(targetMethod, result, arguments, temps, targetRegister, info,
Value.ILLEGAL, Value.ILLEGAL, StatusSupport.STATUS_ILLEGAL, getDestroysCallerSavedRegisters(targetMethod), exceptionTemp, null));
} else {
assert targetAddress == null;
append(new SubstrateAMD64DirectCallOp(targetMethod, result, arguments, temps, info, Value.ILLEGAL,
Value.ILLEGAL, StatusSupport.STATUS_ILLEGAL, getDestroysCallerSavedRegisters(targetMethod), exceptionTemp));
}
}
/**
* For invokes that have an exception handler, the register used for the incoming exception
* is destroyed at the call site even when registers are caller saved. The normal object
* return register is used in {@link NodeLIRBuilder#emitReadExceptionObject} also for the
* exception.
*/
private Value getExceptionTemp(boolean hasExceptionEdge) {
if (hasExceptionEdge) {
return getRegisterConfig().getReturnRegister(JavaKind.Object).asValue();
} else {
return Value.ILLEGAL;
}
}
@Override
public void emitUnwind(Value operand) {
throw shouldNotReachHere("handled by lowering");
}
@Override
public void emitDeoptimize(Value actionAndReason, Value failedSpeculation, LIRFrameState state) {
throw shouldNotReachHere("Substrate VM does not use deoptimization");
}
@Override
public void emitVerificationMarker(Object marker) {
append(new VerificationMarkerOp(marker));
}
@Override
public void emitInstructionSynchronizationBarrier() {
throw shouldNotReachHere("AMD64 does not need instruction synchronization");
}
@Override
public void emitFarReturn(AllocatableValue result, Value sp, Value ip, boolean fromMethodWithCalleeSavedRegisters) {
append(new AMD64FarReturnOp(result, asAllocatable(sp), asAllocatable(ip), fromMethodWithCalleeSavedRegisters));
}
@Override
public void emitDeadEnd() {
append(new DeadEndOp());
}
@Override
public void emitPrefetchAllocate(Value address) {
append(new AMD64PrefetchOp(asAddressValue(address), SubstrateOptions.AllocatePrefetchInstr.getValue()));
}
@Override
public Value emitCompress(Value pointer, CompressEncoding encoding, boolean isNonNull) {
Variable result = newVariable(getLIRKindTool().getNarrowOopKind());
boolean nonNull = useLinearPointerCompression() || isNonNull;
append(new AMD64Move.CompressPointerOp(result, asAllocatable(pointer), ReservedRegisters.singleton().getHeapBaseRegister().asValue(), encoding, nonNull, getLIRKindTool()));
return result;
}
@Override
public Value emitUncompress(Value pointer, CompressEncoding encoding, boolean isNonNull) {
assert pointer.getValueKind(LIRKind.class).getPlatformKind() == getLIRKindTool().getNarrowOopKind().getPlatformKind();
Variable result = newVariable(getLIRKindTool().getObjectKind());
boolean nonNull = useLinearPointerCompression() || isNonNull;
append(new AMD64Move.UncompressPointerOp(result, asAllocatable(pointer), ReservedRegisters.singleton().getHeapBaseRegister().asValue(), encoding, nonNull, getLIRKindTool()));
return result;
}
@Override
public void emitConvertNullToZero(AllocatableValue result, AllocatableValue value) {
if (useLinearPointerCompression()) {
append(new AMD64Move.ConvertNullToZeroOp(result, value));
} else {
emitMove(result, value);
}
}
@Override
public void emitConvertZeroToNull(AllocatableValue result, Value value) {
if (useLinearPointerCompression()) {
append(new AMD64Move.ConvertZeroToNullOp(result, (AllocatableValue) value));
} else {
emitMove(result, value);
}
}
@Override
public void emitProcid(AllocatableValue dst) {
if (supportsCPUFeature(CPUFeature.RDPID)) {
append(new AMD64ReadProcid(dst));
} else {
AMD64ReadTimestampCounterWithProcid procid = new AMD64ReadTimestampCounterWithProcid();
append(procid);
emitMove(dst, procid.getProcidResult());
}
getArithmetic().emitAnd(dst, emitConstant(LIRKind.value(AMD64Kind.DWORD), JavaConstant.forInt(0xfff)));
}
@Override
public int getArrayLengthOffset() {
return ConfigurationValues.getObjectLayout().getArrayLengthOffset();
}
@Override
public Register getHeapBaseRegister() {
return ReservedRegisters.singleton().getHeapBaseRegister();
}
@Override
protected void emitRangeTableSwitch(int lowKey, LabelRef defaultTarget, LabelRef[] targets, AllocatableValue key) {
super.emitRangeTableSwitch(lowKey, defaultTarget, targets, key);
markIndirectBranchTargets(targets);
}
@Override
protected void emitHashTableSwitch(JavaConstant[] keys, LabelRef defaultTarget, LabelRef[] targets, AllocatableValue value, Value hash) {
super.emitHashTableSwitch(keys, defaultTarget, targets, value, hash);
markIndirectBranchTargets(targets);
}
private void markIndirectBranchTargets(LabelRef[] labels) {
for (LabelRef label : labels) {
label.getTargetBlock().setIndirectBranchTarget();
}
}
}
public class SubstrateAMD64NodeLIRBuilder extends AMD64NodeLIRBuilder implements SubstrateNodeLIRBuilder {
public SubstrateAMD64NodeLIRBuilder(StructuredGraph graph, LIRGeneratorTool gen, AMD64NodeMatchRules nodeMatchRules) {
super(graph, gen, nodeMatchRules);
}
@Override
public void visitSafepointNode(SafepointNode node) {
throw shouldNotReachHere("handled by lowering");
}
@Override
public void visitBreakpointNode(BreakpointNode node) {
JavaType[] sig = new JavaType[node.arguments().size()];
for (int i = 0; i < sig.length; i++) {
sig[i] = node.arguments().get(i).stamp(NodeView.DEFAULT).javaType(gen.getMetaAccess());
}
CallingConvention convention = gen.getRegisterConfig().getCallingConvention(SubstrateCallingConventionKind.Java.toType(true), null, sig, gen);
append(new AMD64BreakpointOp(visitInvokeArguments(convention, node.arguments())));
}
@Override
protected DebugInfoBuilder createDebugInfoBuilder(StructuredGraph graph, NodeValueMap nodeValueMap) {
return new SubstrateDebugInfoBuilder(graph, gen.getProviders().getMetaAccessExtensionProvider(), nodeValueMap);
}
@Override
protected void prologSetParameterNodes(StructuredGraph graph, Value[] params) {
SubstrateCallingConvention convention = (SubstrateCallingConvention) gen.getResult().getCallingConvention();
for (ParameterNode param : graph.getNodes(ParameterNode.TYPE)) {
Value inputValue = params[param.index()];
Value paramValue = gen.emitMove(inputValue);
/*
* In the native ABI, some parameters are not extended to the equivalent Java stack
* kinds.
*/
if (inputValue.getPlatformKind().getSizeInBytes() < Integer.BYTES) {
SubstrateCallingConventionType type = (SubstrateCallingConventionType) convention.getType();
assert !type.outgoing && type.nativeABI();
JavaKind kind = convention.getArgumentStorageKinds()[param.index()];
JavaKind stackKind = kind.getStackKind();
if (kind.isUnsigned()) {
paramValue = gen.getArithmetic().emitZeroExtend(paramValue, kind.getBitCount(), stackKind.getBitCount());
} else {
paramValue = gen.getArithmetic().emitSignExtend(paramValue, kind.getBitCount(), stackKind.getBitCount());
}
}
assert paramValue.getValueKind().equals(gen.getLIRKind(param.stamp(NodeView.DEFAULT)));
setResult(param, paramValue);
}
}
@Override
public Value[] visitInvokeArguments(CallingConvention invokeCc, Collection<ValueNode> arguments) {
Value[] values = super.visitInvokeArguments(invokeCc, arguments);
SubstrateCallingConventionType type = (SubstrateCallingConventionType) ((SubstrateCallingConvention) invokeCc).getType();
if (type.usesReturnBuffer()) {
/*
* We save the return buffer so that it can be accessed after the call.
*/
assert values.length > 0;
Value returnBuffer = values[0];
Variable saved = gen.newVariable(returnBuffer.getValueKind());
gen.append(gen.getSpillMoveFactory().createMove(saved, returnBuffer));
values[0] = saved;
}
if (type.nativeABI()) {
VMError.guarantee(values.length == invokeCc.getArgumentCount() - 1, "The last argument should be missing.");
AllocatableValue raxValue = invokeCc.getArgument(values.length);
VMError.guarantee(raxValue instanceof RegisterValue && ((RegisterValue) raxValue).getRegister().equals(rax));
values = Arrays.copyOf(values, values.length + 1);
// Native functions might have varargs, in which case we need to set %al to the
// number of XMM registers used for passing arguments
int xmmCount = 0;
for (int i = 0; i < values.length - 1; ++i) {
Value v = values[i];
if (isRegister(v) && asRegister(v).getRegisterCategory().equals(AMD64.XMM)) {
xmmCount++;
}
}
assert xmmCount <= 8;
gen.emitMoveConstant(raxValue, JavaConstant.forInt(xmmCount));
values[values.length - 1] = raxValue;
}
return values;
}
private boolean getDestroysCallerSavedRegisters(ResolvedJavaMethod targetMethod) {
return ((SubstrateAMD64LIRGenerator) gen).getDestroysCallerSavedRegisters(targetMethod);
}
/**
* For invokes that have an exception handler, the register used for the incoming exception
* is destroyed at the call site even when registers are caller saved. The normal object
* return register is used in {@link NodeLIRBuilder#emitReadExceptionObject} also for the
* exception.
*/
private Value getExceptionTemp(CallTargetNode callTarget) {
return ((SubstrateAMD64LIRGenerator) gen).getExceptionTemp(callTarget.invoke() instanceof InvokeWithExceptionNode);
}
public BiConsumer<CompilationResultBuilder, Integer> getOffsetRecorder(@SuppressWarnings("unused") IndirectCallTargetNode callTargetNode) {
return null;
}
private static AllocatableValue asReturnedValue(AssignedLocation assignedLocation) {
assert assignedLocation.assignsToRegister();
Register.RegisterCategory category = assignedLocation.register().getRegisterCategory();
LIRKind kind;
if (category.equals(AMD64.CPU)) {
kind = LIRKind.value(AMD64Kind.QWORD);
} else if (category.equals(AMD64.XMM)) {
kind = LIRKind.value(AMD64Kind.V128_DOUBLE);
} else {
throw unsupportedFeature("Register category " + category + " should not be used for returns spanning multiple registers.");
}
return assignedLocation.register().asValue(kind);
}
@Override
protected void emitInvoke(LoweredCallTargetNode callTarget, Value[] parameters, LIRFrameState callState, Value result) {
var cc = (SubstrateCallingConventionType) callTarget.callType();
verifyCallTarget(callTarget);
if (callTarget instanceof ComputedIndirectCallTargetNode) {
assert !cc.customABI();
emitComputedIndirectCall((ComputedIndirectCallTargetNode) callTarget, result, parameters, AllocatableValue.NONE, callState);
} else {
super.emitInvoke(callTarget, parameters, callState, result);
}
if (cc.usesReturnBuffer()) {
/*
* The buffer argument was saved in visitInvokeArguments, so that the value was not
* killed by the call.
*/
Value returnBuffer = parameters[0];
long offset = 0;
for (AssignedLocation ret : cc.returnSaving) {
Value saveLocation = gen.getArithmetic().emitAdd(returnBuffer, gen.emitJavaConstant(JavaConstant.forLong(offset)), false);
AllocatableValue returnedValue = asReturnedValue(ret);
gen.getArithmetic().emitStore(returnedValue.getValueKind(), saveLocation, returnedValue, callState, MemoryOrderMode.PLAIN);
offset += returnedValue.getPlatformKind().getSizeInBytes();
}
}
}
@Override
protected void emitDirectCall(DirectCallTargetNode callTarget, Value result, Value[] parameters, Value[] temps, LIRFrameState callState) {
ResolvedJavaMethod targetMethod = callTarget.targetMethod();
vzeroupperBeforeCall((SubstrateAMD64LIRGenerator) getLIRGeneratorTool(), parameters, callState, (SharedMethod) targetMethod);
append(new SubstrateAMD64DirectCallOp(targetMethod, result, parameters, temps, callState,
setupJavaFrameAnchor(callTarget), setupJavaFrameAnchorTemp(callTarget), getNewThreadStatus(callTarget),
getDestroysCallerSavedRegisters(targetMethod), getExceptionTemp(callTarget)));
}
@Override