forked from dotnet/runtimelab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CorInfoImpl.cs
3487 lines (2897 loc) · 138 KB
/
CorInfoImpl.cs
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.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
#if SUPPORT_JIT
using Internal.Runtime.CompilerServices;
#endif
using Internal.IL;
using Internal.TypeSystem;
using Internal.TypeSystem.Ecma;
using Internal.TypeSystem.Interop;
using Internal.CorConstants;
using ILCompiler;
using ILCompiler.DependencyAnalysis;
using Internal.IL.Stubs;
#if READYTORUN
using System.Reflection.Metadata.Ecma335;
using ILCompiler.DependencyAnalysis.ReadyToRun;
#endif
namespace Internal.JitInterface
{
public unsafe sealed partial class CorInfoImpl
{
//
// Global initialization and state
//
private enum ImageFileMachine
{
I386 = 0x014c,
IA64 = 0x0200,
AMD64 = 0x8664,
ARM = 0x01c4,
ARM64 = 0xaa64,
}
private enum CFI_OPCODE
{
CFI_ADJUST_CFA_OFFSET, // Offset is adjusted relative to the current one.
CFI_DEF_CFA_REGISTER, // New register is used to compute CFA
CFI_REL_OFFSET, // Register is saved at offset from the current CFA
CFI_DEF_CFA // Take address from register and add offset to it.
};
internal const string JitLibrary = "clrjitilc";
#if SUPPORT_JIT
private const string JitSupportLibrary = "*";
#else
internal const string JitSupportLibrary = "jitinterface";
#endif
private IntPtr _jit;
private IntPtr _unmanagedCallbacks; // array of pointers to JIT-EE interface callbacks
private ExceptionDispatchInfo _lastException;
[DllImport(JitLibrary, CallingConvention = CallingConvention.StdCall)] // stdcall in CoreCLR!
private extern static IntPtr jitStartup(IntPtr host);
[DllImport(JitLibrary, CallingConvention = CallingConvention.StdCall)]
private extern static IntPtr getJit();
[DllImport(JitSupportLibrary)]
private extern static IntPtr GetJitHost(IntPtr configProvider);
//
// Per-method initialization and state
//
private static CorInfoImpl GetThis(IntPtr thisHandle)
{
CorInfoImpl _this = Unsafe.Read<CorInfoImpl>((void*)thisHandle);
Debug.Assert(_this is CorInfoImpl);
return _this;
}
[DllImport(JitSupportLibrary)]
internal extern static CorJitResult JitCompileMethod(out IntPtr exception,
IntPtr jit, IntPtr thisHandle, IntPtr callbacks,
ref CORINFO_METHOD_INFO info, uint flags, out IntPtr nativeEntry, out uint codeSize);
[DllImport(JitSupportLibrary)]
private extern static uint GetMaxIntrinsicSIMDVectorLength(IntPtr jit, CORJIT_FLAGS* flags);
[DllImport(JitSupportLibrary)]
private extern static IntPtr AllocException([MarshalAs(UnmanagedType.LPWStr)]string message, int messageLength);
private IntPtr AllocException(Exception ex)
{
_lastException = ExceptionDispatchInfo.Capture(ex);
string exString = ex.ToString();
IntPtr nativeException = AllocException(exString, exString.Length);
if (_nativeExceptions == null)
{
_nativeExceptions = new List<IntPtr>();
}
_nativeExceptions.Add(nativeException);
return nativeException;
}
[DllImport(JitSupportLibrary)]
private extern static void FreeException(IntPtr obj);
[DllImport(JitSupportLibrary)]
private extern static char* GetExceptionMessage(IntPtr obj);
public static void Startup()
{
jitStartup(GetJitHost(JitConfigProvider.Instance.UnmanagedInstance));
}
public CorInfoImpl()
{
_jit = getJit();
if (_jit == IntPtr.Zero)
{
throw new IOException("Failed to initialize JIT");
}
_unmanagedCallbacks = GetUnmanagedCallbacks();
}
public TextWriter Log
{
get
{
return _compilation.Logger.Writer;
}
}
private CORINFO_MODULE_STRUCT_* _methodScope; // Needed to resolve CORINFO_EH_CLAUSE tokens
private void CompileMethodInternal(IMethodNode methodCodeNodeNeedingCode, MethodIL methodIL)
{
// methodIL must not be null
if (methodIL == null)
{
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramSpecific, MethodBeingCompiled);
}
CORINFO_METHOD_INFO methodInfo;
Get_CORINFO_METHOD_INFO(MethodBeingCompiled, methodIL, &methodInfo);
_methodScope = methodInfo.scope;
#if !READYTORUN
SetDebugInformation(methodCodeNodeNeedingCode, methodIL);
#endif
CorInfoImpl _this = this;
IntPtr exception;
IntPtr nativeEntry;
uint codeSize;
var result = JitCompileMethod(out exception,
_jit, (IntPtr)Unsafe.AsPointer(ref _this), _unmanagedCallbacks,
ref methodInfo, (uint)CorJitFlag.CORJIT_FLAG_CALL_GETJITFLAGS, out nativeEntry, out codeSize);
if (exception != IntPtr.Zero)
{
if (_lastException != null)
{
// If we captured a managed exception, rethrow that.
// TODO: might not actually be the real reason. It could be e.g. a JIT failure/bad IL that followed
// an inlining attempt with a type system problem in it...
#if SUPPORT_JIT
_lastException.Throw();
#else
if (_lastException.SourceException is TypeSystemException)
{
// Type system exceptions can be turned into code that throws the exception at runtime.
_lastException.Throw();
}
#if READYTORUN
else if (_lastException.SourceException is RequiresRuntimeJitException)
{
// Runtime JIT requirement is not a cause for failure, we just mustn't JIT a particular method
_lastException.Throw();
}
#endif
else
{
// This is just a bug somewhere.
throw new CodeGenerationFailedException(_methodCodeNode.Method, _lastException.SourceException);
}
#endif
}
// This is a failure we don't know much about.
char* szMessage = GetExceptionMessage(exception);
string message = szMessage != null ? new string(szMessage) : "JIT Exception";
throw new Exception(message);
}
if (result == CorJitResult.CORJIT_BADCODE)
{
ThrowHelper.ThrowInvalidProgramException();
}
if (result == CorJitResult.CORJIT_IMPLLIMITATION)
{
#if READYTORUN
throw new RequiresRuntimeJitException("JIT implementation limitation");
#else
ThrowHelper.ThrowInvalidProgramException();
#endif
}
if (result != CorJitResult.CORJIT_OK)
{
#if SUPPORT_JIT
// FailFast?
throw new Exception("JIT failed");
#else
throw new CodeGenerationFailedException(_methodCodeNode.Method);
#endif
}
PublishCode();
PublishROData();
}
private void PublishCode()
{
var relocs = _codeRelocs.ToArray();
Array.Sort(relocs, (x, y) => (x.Offset - y.Offset));
int alignment = JitConfigProvider.Instance.HasFlag(CorJitFlag.CORJIT_FLAG_SIZE_OPT) ?
_compilation.NodeFactory.Target.MinimumFunctionAlignment :
_compilation.NodeFactory.Target.OptimumFunctionAlignment;
alignment = Math.Max(alignment, _codeAlignment);
var objectData = new ObjectNode.ObjectData(_code,
relocs,
alignment,
new ISymbolDefinitionNode[] { _methodCodeNode });
ObjectNode.ObjectData ehInfo = _ehClauses != null ? EncodeEHInfo() : null;
DebugEHClauseInfo[] debugEHClauseInfos = null;
if (_ehClauses != null)
{
debugEHClauseInfos = new DebugEHClauseInfo[_ehClauses.Length];
for (int i = 0; i < _ehClauses.Length; i++)
{
var clause = _ehClauses[i];
debugEHClauseInfos[i] = new DebugEHClauseInfo(clause.TryOffset, clause.TryLength,
clause.HandlerOffset, clause.HandlerLength);
}
}
_methodCodeNode.SetCode(objectData
#if !SUPPORT_JIT && !READYTORUN
, isFoldable: (_compilation._compilationOptions & RyuJitCompilationOptions.MethodBodyFolding) != 0
#endif
);
_methodCodeNode.InitializeFrameInfos(_frameInfos);
_methodCodeNode.InitializeDebugEHClauseInfos(debugEHClauseInfos);
_methodCodeNode.InitializeGCInfo(_gcInfo);
_methodCodeNode.InitializeEHInfo(ehInfo);
_methodCodeNode.InitializeDebugLocInfos(_debugLocInfos);
_methodCodeNode.InitializeDebugVarInfos(_debugVarInfos);
#if READYTORUN
_methodCodeNode.InitializeInliningInfo(_inlinedMethods.ToArray());
// Detect cases where the instruction set support used is a superset of the baseline instruction set specification
var baselineSupport = _compilation.InstructionSetSupport;
bool needPerMethodInstructionSetFixup = false;
foreach (var instructionSet in _actualInstructionSetSupported)
{
if (!baselineSupport.IsInstructionSetSupported(instructionSet) &&
!baselineSupport.NonSpecifiableFlags.HasInstructionSet(instructionSet))
{
needPerMethodInstructionSetFixup = true;
}
}
foreach (var instructionSet in _actualInstructionSetUnsupported)
{
if (!baselineSupport.IsInstructionSetExplicitlyUnsupported(instructionSet))
{
needPerMethodInstructionSetFixup = true;
}
}
if (needPerMethodInstructionSetFixup)
{
TargetArchitecture architecture = _compilation.TypeSystemContext.Target.Architecture;
_actualInstructionSetSupported.ExpandInstructionSetByImplication(architecture);
_actualInstructionSetUnsupported.ExpandInstructionSetByReverseImplication(architecture);
_actualInstructionSetUnsupported.Set64BitInstructionSetVariants(architecture);
InstructionSetSupport actualSupport = new InstructionSetSupport(_actualInstructionSetSupported, _actualInstructionSetUnsupported, architecture);
var node = _compilation.SymbolNodeFactory.PerMethodInstructionSetSupportFixup(actualSupport);
_methodCodeNode.Fixups.Add(node);
}
#else
MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope);
CodeBasedDependencyAlgorithm.AddDependenciesDueToMethodCodePresence(ref _additionalDependencies, _compilation.NodeFactory, MethodBeingCompiled, methodIL);
_methodCodeNode.InitializeNonRelocationDependencies(_additionalDependencies);
#endif
PublishProfileData();
}
private void PublishROData()
{
if (_roDataBlob == null)
{
return;
}
var relocs = _roDataRelocs.ToArray();
Array.Sort(relocs, (x, y) => (x.Offset - y.Offset));
var objectData = new ObjectNode.ObjectData(_roData,
relocs,
_roDataAlignment,
new ISymbolDefinitionNode[] { _roDataBlob });
_roDataBlob.InitializeData(objectData);
}
partial void PublishProfileData();
private MethodDesc MethodBeingCompiled
{
get
{
return _methodCodeNode.Method;
}
}
private int PointerSize
{
get
{
return _compilation.TypeSystemContext.Target.PointerSize;
}
}
private Dictionary<Object, GCHandle> _pins = new Dictionary<object, GCHandle>();
private IntPtr GetPin(Object obj)
{
GCHandle handle;
if (!_pins.TryGetValue(obj, out handle))
{
handle = GCHandle.Alloc(obj, GCHandleType.Pinned);
_pins.Add(obj, handle);
}
return handle.AddrOfPinnedObject();
}
private List<IntPtr> _nativeExceptions;
private void CompileMethodCleanup()
{
foreach (var pin in _pins)
pin.Value.Free();
_pins.Clear();
if (_nativeExceptions != null)
{
foreach (IntPtr ex in _nativeExceptions)
FreeException(ex);
_nativeExceptions = null;
}
_methodCodeNode = null;
_code = null;
_coldCode = null;
_roData = null;
_roDataBlob = null;
_codeRelocs = new ArrayBuilder<Relocation>();
_roDataRelocs = new ArrayBuilder<Relocation>();
_numFrameInfos = 0;
_usedFrameInfos = 0;
_frameInfos = null;
_gcInfo = null;
_ehClauses = null;
#if !READYTORUN
_sequencePoints = null;
_variableToTypeDesc = null;
_parameterIndexToNameMap = null;
_localSlotToInfoMap = null;
_additionalDependencies = null;
#endif
_debugLocInfos = null;
_debugVarInfos = null;
_lastException = null;
#if READYTORUN
_profileDataNode = null;
_inlinedMethods = new ArrayBuilder<MethodDesc>();
_actualInstructionSetSupported = default(InstructionSetFlags);
_actualInstructionSetUnsupported = default(InstructionSetFlags);
#endif
}
private Dictionary<Object, IntPtr> _objectToHandle = new Dictionary<Object, IntPtr>();
private List<Object> _handleToObject = new List<Object>();
private const int handleMultipler = 8;
private const int handleBase = 0x420000;
#if DEBUG
private static readonly IntPtr s_handleHighBitSet = (sizeof(IntPtr) == 4) ? new IntPtr(0x40000000) : new IntPtr(0x4000000000000000);
#endif
private IntPtr ObjectToHandle(Object obj)
{
// SuperPMI relies on the handle returned from this function being stable for the lifetime of the crossgen2 process
// If handle deletion is implemented, please update SuperPMI
IntPtr handle;
if (!_objectToHandle.TryGetValue(obj, out handle))
{
handle = (IntPtr)(handleMultipler * _handleToObject.Count + handleBase);
#if DEBUG
handle = new IntPtr((long)s_handleHighBitSet | (long)handle);
#endif
_handleToObject.Add(obj);
_objectToHandle.Add(obj, handle);
}
return handle;
}
private Object HandleToObject(IntPtr handle)
{
#if DEBUG
handle = new IntPtr(~(long)s_handleHighBitSet & (long) handle);
#endif
int index = ((int)handle - handleBase) / handleMultipler;
return _handleToObject[index];
}
private MethodDesc HandleToObject(CORINFO_METHOD_STRUCT_* method) { return (MethodDesc)HandleToObject((IntPtr)method); }
private CORINFO_METHOD_STRUCT_* ObjectToHandle(MethodDesc method) { return (CORINFO_METHOD_STRUCT_*)ObjectToHandle((Object)method); }
private TypeDesc HandleToObject(CORINFO_CLASS_STRUCT_* type) { return (TypeDesc)HandleToObject((IntPtr)type); }
private CORINFO_CLASS_STRUCT_* ObjectToHandle(TypeDesc type) { return (CORINFO_CLASS_STRUCT_*)ObjectToHandle((Object)type); }
private FieldDesc HandleToObject(CORINFO_FIELD_STRUCT_* field) { return (FieldDesc)HandleToObject((IntPtr)field); }
private CORINFO_FIELD_STRUCT_* ObjectToHandle(FieldDesc field) { return (CORINFO_FIELD_STRUCT_*)ObjectToHandle((Object)field); }
private bool Get_CORINFO_METHOD_INFO(MethodDesc method, MethodIL methodIL, CORINFO_METHOD_INFO* methodInfo)
{
if (methodIL == null)
{
*methodInfo = default(CORINFO_METHOD_INFO);
return false;
}
methodInfo->ftn = ObjectToHandle(method);
methodInfo->scope = (CORINFO_MODULE_STRUCT_*)ObjectToHandle(methodIL);
var ilCode = methodIL.GetILBytes();
methodInfo->ILCode = (byte*)GetPin(ilCode);
methodInfo->ILCodeSize = (uint)ilCode.Length;
methodInfo->maxStack = (uint)methodIL.MaxStack;
methodInfo->EHcount = (uint)methodIL.GetExceptionRegions().Length;
methodInfo->options = methodIL.IsInitLocals ? CorInfoOptions.CORINFO_OPT_INIT_LOCALS : (CorInfoOptions)0;
if (method.AcquiresInstMethodTableFromThis())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_THIS;
}
else if (method.RequiresInstMethodDescArg())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODDESC;
}
else if (method.RequiresInstMethodTableArg())
{
methodInfo->options |= CorInfoOptions.CORINFO_GENERICS_CTXT_FROM_METHODTABLE;
}
methodInfo->regionKind = CorInfoRegionKind.CORINFO_REGION_NONE;
Get_CORINFO_SIG_INFO(method, sig: &methodInfo->args);
Get_CORINFO_SIG_INFO(methodIL.GetLocals(), &methodInfo->locals);
return true;
}
private void Get_CORINFO_SIG_INFO(MethodDesc method, CORINFO_SIG_INFO* sig, bool suppressHiddenArgument = false)
{
Get_CORINFO_SIG_INFO(method.Signature, sig);
// Does the method have a hidden parameter?
bool hasHiddenParameter = !suppressHiddenArgument && method.RequiresInstArg();
if (method.IsIntrinsic)
{
// Some intrinsics will beg to differ about the hasHiddenParameter decision
#if !READYTORUN
if (_compilation.TypeSystemContext.IsSpecialUnboxingThunkTargetMethod(method))
hasHiddenParameter = false;
#endif
if (method.IsArrayAddressMethod())
hasHiddenParameter = true;
// We only populate sigInst for intrinsic methods because most of the time,
// JIT doesn't care what the instantiation is and this is expensive.
Instantiation owningTypeInst = method.OwningType.Instantiation;
sig->sigInst.classInstCount = (uint)owningTypeInst.Length;
if (owningTypeInst.Length > 0)
{
var classInst = new IntPtr[owningTypeInst.Length];
for (int i = 0; i < owningTypeInst.Length; i++)
classInst[i] = (IntPtr)ObjectToHandle(owningTypeInst[i]);
sig->sigInst.classInst = (CORINFO_CLASS_STRUCT_**)GetPin(classInst);
}
}
if (hasHiddenParameter)
{
sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_PARAMTYPE;
}
}
private CorInfoCallConvExtension GetUnmanagedCallingConventionFromAttribute(CustomAttributeValue<TypeDesc> unmanagedCallersOnlyAttribute)
{
CorInfoCallConvExtension callConv = (CorInfoCallConvExtension)PlatformDefaultUnmanagedCallingConvention();
ImmutableArray<CustomAttributeTypedArgument<TypeDesc>> callConvArray = default;
foreach (var arg in unmanagedCallersOnlyAttribute.NamedArguments)
{
if (arg.Name == "CallConvs")
{
callConvArray = (ImmutableArray<CustomAttributeTypedArgument<TypeDesc>>)arg.Value;
}
}
// No calling convention was specified in the attribute, so return the default.
if (callConvArray.IsDefault)
{
return callConv;
}
bool found = false;
foreach (CustomAttributeTypedArgument<TypeDesc> type in callConvArray)
{
if (!(type.Value is DefType defType))
continue;
if (defType.Namespace != "System.Runtime.CompilerServices")
continue;
CorInfoCallConvExtension? callConvLocal = GetCallingConventionForCallConvType(defType);
if (callConvLocal.HasValue)
{
// Error if there are multiple recognized calling conventions
if (found)
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramMultipleCallConv, MethodBeingCompiled);
callConv = callConvLocal.Value;
found = true;
}
}
return callConv;
}
private bool TryGetUnmanagedCallingConventionFromModOpt(MethodSignature signature, out CorInfoCallConvExtension callConv, out bool suppressGCTransition)
{
suppressGCTransition = false;
callConv = CorInfoCallConvExtension.Managed;
if (!signature.HasEmbeddedSignatureData || signature.GetEmbeddedSignatureData() == null)
return false;
bool found = false;
foreach (EmbeddedSignatureData data in signature.GetEmbeddedSignatureData())
{
if (data.kind != EmbeddedSignatureDataKind.OptionalCustomModifier)
continue;
// We only care about the modifiers for the return type. These will be at the start of
// the signature, so will be first in the array of embedded signature data.
if (data.index != MethodSignature.IndexOfCustomModifiersOnReturnType)
break;
if (!(data.type is DefType defType))
continue;
if (defType.Namespace != "System.Runtime.CompilerServices")
continue;
if (defType.Name == "CallConvSuppressGCTransition")
{
suppressGCTransition = true;
continue;
}
CorInfoCallConvExtension? callConvLocal = GetCallingConventionForCallConvType(defType);
if (callConvLocal.HasValue)
{
// Error if there are multiple recognized calling conventions
if (found)
ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramMultipleCallConv, MethodBeingCompiled);
callConv = callConvLocal.Value;
found = true;
}
}
return found;
}
private static CorInfoCallConvExtension? GetCallingConventionForCallConvType(DefType defType) =>
// Look for a recognized calling convention in metadata.
defType.Name switch
{
"CallConvCdecl" => CorInfoCallConvExtension.C,
"CallConvStdcall" => CorInfoCallConvExtension.Stdcall,
"CallConvFastcall" => CorInfoCallConvExtension.Fastcall,
"CallConvThiscall" => CorInfoCallConvExtension.Thiscall,
_ => null
};
private void Get_CORINFO_SIG_INFO(MethodSignature signature, CORINFO_SIG_INFO* sig)
{
sig->callConv = (CorInfoCallConv)(signature.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask);
// Varargs are not supported in .NET Core
if (sig->callConv == CorInfoCallConv.CORINFO_CALLCONV_VARARG)
ThrowHelper.ThrowBadImageFormatException();
if (!signature.IsStatic) sig->callConv |= CorInfoCallConv.CORINFO_CALLCONV_HASTHIS;
TypeDesc returnType = signature.ReturnType;
CorInfoType corInfoRetType = asCorInfoType(signature.ReturnType, &sig->retTypeClass);
sig->_retType = (byte)corInfoRetType;
sig->retTypeSigClass = ObjectToHandle(signature.ReturnType);
sig->flags = 0; // used by IL stubs code
sig->numArgs = (ushort)signature.Length;
sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index
sig->sigInst.classInst = null; // Not used by the JIT
sig->sigInst.classInstCount = 0; // Not used by the JIT
sig->sigInst.methInst = null; // Not used by the JIT
sig->sigInst.methInstCount = (uint)signature.GenericParameterCount;
sig->pSig = (byte*)ObjectToHandle(signature);
sig->cbSig = 0; // Not used by the JIT
sig->scope = null;
sig->token = 0; // Not used by the JIT
}
private void Get_CORINFO_SIG_INFO(LocalVariableDefinition[] locals, CORINFO_SIG_INFO* sig)
{
sig->callConv = CorInfoCallConv.CORINFO_CALLCONV_DEFAULT;
sig->_retType = (byte)CorInfoType.CORINFO_TYPE_VOID;
sig->retTypeClass = null;
sig->retTypeSigClass = null;
sig->flags = CorInfoSigInfoFlags.CORINFO_SIGFLAG_IS_LOCAL_SIG;
sig->numArgs = (ushort)locals.Length;
sig->sigInst.classInst = null;
sig->sigInst.classInstCount = 0;
sig->sigInst.methInst = null;
sig->sigInst.methInstCount = 0;
sig->args = (CORINFO_ARG_LIST_STRUCT_*)0; // CORINFO_ARG_LIST_STRUCT_ is argument index
sig->pSig = (byte*)ObjectToHandle(locals);
sig->cbSig = 0; // Not used by the JIT
sig->scope = null; // Not used by the JIT
sig->token = 0; // Not used by the JIT
}
private CorInfoType asCorInfoType(TypeDesc type)
{
return asCorInfoType(type, out _);
}
private CorInfoType asCorInfoType(TypeDesc type, out TypeDesc typeIfNotPrimitive)
{
if (type.IsEnum)
{
type = type.UnderlyingType;
}
if (type.IsPrimitive)
{
typeIfNotPrimitive = null;
Debug.Assert((CorInfoType)TypeFlags.Void == CorInfoType.CORINFO_TYPE_VOID);
Debug.Assert((CorInfoType)TypeFlags.Double == CorInfoType.CORINFO_TYPE_DOUBLE);
return (CorInfoType)type.Category;
}
if (type.IsPointer || type.IsFunctionPointer)
{
typeIfNotPrimitive = null;
return CorInfoType.CORINFO_TYPE_PTR;
}
typeIfNotPrimitive = type;
if (type.IsByRef)
{
return CorInfoType.CORINFO_TYPE_BYREF;
}
if (type.IsValueType)
{
if (_compilation.TypeSystemContext.Target.Architecture == TargetArchitecture.X86)
{
LayoutInt elementSize = type.GetElementSize();
#if READYTORUN
if (elementSize.IsIndeterminate)
{
throw new RequiresRuntimeJitException(type);
}
#endif
}
return CorInfoType.CORINFO_TYPE_VALUECLASS;
}
return CorInfoType.CORINFO_TYPE_CLASS;
}
private CorInfoType asCorInfoType(TypeDesc type, CORINFO_CLASS_STRUCT_** structType)
{
var corInfoType = asCorInfoType(type, out TypeDesc typeIfNotPrimitive);
*structType = (typeIfNotPrimitive != null) ? ObjectToHandle(typeIfNotPrimitive) : null;
return corInfoType;
}
private CORINFO_CONTEXT_STRUCT* contextFromMethod(MethodDesc method)
{
return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(method)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_METHOD);
}
private CORINFO_CONTEXT_STRUCT* contextFromType(TypeDesc type)
{
return (CORINFO_CONTEXT_STRUCT*)(((ulong)ObjectToHandle(type)) | (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS);
}
private static CORINFO_CONTEXT_STRUCT* contextFromMethodBeingCompiled()
{
return (CORINFO_CONTEXT_STRUCT*)1;
}
private MethodDesc methodFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
{
if (contextStruct == contextFromMethodBeingCompiled())
{
return MethodBeingCompiled;
}
if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
{
return null;
}
else
{
return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
}
}
private TypeDesc typeFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
{
if (contextStruct == contextFromMethodBeingCompiled())
{
return MethodBeingCompiled.OwningType;
}
if (((ulong)contextStruct & (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK) == (ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_CLASS)
{
return HandleToObject((CORINFO_CLASS_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
}
else
{
return HandleToObject((CORINFO_METHOD_STRUCT_*)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK)).OwningType;
}
}
private TypeSystemEntity entityFromContext(CORINFO_CONTEXT_STRUCT* contextStruct)
{
if (contextStruct == contextFromMethodBeingCompiled())
{
return MethodBeingCompiled.HasInstantiation ? (TypeSystemEntity)MethodBeingCompiled: (TypeSystemEntity)MethodBeingCompiled.OwningType;
}
return (TypeSystemEntity)HandleToObject((IntPtr)((ulong)contextStruct & ~(ulong)CorInfoContextFlags.CORINFO_CONTEXTFLAGS_MASK));
}
private uint getMethodAttribsInternal(MethodDesc method)
{
CorInfoFlag result = 0;
// CORINFO_FLG_PROTECTED - verification only
if (method.Signature.IsStatic)
result |= CorInfoFlag.CORINFO_FLG_STATIC;
if (method.IsSynchronized)
result |= CorInfoFlag.CORINFO_FLG_SYNCH;
if (method.IsIntrinsic)
result |= CorInfoFlag.CORINFO_FLG_INTRINSIC | CorInfoFlag.CORINFO_FLG_JIT_INTRINSIC;
if (method.IsVirtual)
result |= CorInfoFlag.CORINFO_FLG_VIRTUAL;
if (method.IsAbstract)
result |= CorInfoFlag.CORINFO_FLG_ABSTRACT;
if (method.IsConstructor || method.IsStaticConstructor)
result |= CorInfoFlag.CORINFO_FLG_CONSTRUCTOR;
//
// See if we need to embed a .cctor call at the head of the
// method body.
//
// method or class might have the final bit
if (_compilation.IsEffectivelySealed(method))
result |= CorInfoFlag.CORINFO_FLG_FINAL;
if (method.IsSharedByGenericInstantiations)
result |= CorInfoFlag.CORINFO_FLG_SHAREDINST;
if (method.IsPInvoke)
result |= CorInfoFlag.CORINFO_FLG_PINVOKE;
#if READYTORUN
if (method.RequireSecObject)
{
result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE_CALLER;
}
#endif
if (method.IsAggressiveOptimization)
{
result |= CorInfoFlag.CORINFO_FLG_AGGRESSIVE_OPT;
}
// TODO: Cache inlining hits
// Check for an inlining directive.
if (method.IsNoInlining)
{
/* Function marked as not inlineable */
result |= CorInfoFlag.CORINFO_FLG_DONT_INLINE;
}
else if (method.IsAggressiveInlining)
{
result |= CorInfoFlag.CORINFO_FLG_FORCEINLINE;
}
if (method.OwningType.IsDelegate && method.Name == "Invoke")
{
// This is now used to emit efficient invoke code for any delegate invoke,
// including multicast.
result |= CorInfoFlag.CORINFO_FLG_DELEGATE_INVOKE;
// RyuJIT special cases this method; it would assert if it's not final
// and we might not have set the bit in the code above.
result |= CorInfoFlag.CORINFO_FLG_FINAL;
}
#if READYTORUN
// Check for SIMD intrinsics
if (method.Context.Target.MaximumSimdVectorLength == SimdVectorLength.None)
{
DefType owningDefType = method.OwningType as DefType;
if (owningDefType != null && VectorOfTFieldLayoutAlgorithm.IsVectorOfTType(owningDefType))
{
throw new RequiresRuntimeJitException("This function is using SIMD intrinsics, their size is machine specific");
}
}
#endif
// Check for hardware intrinsics
if (HardwareIntrinsicHelpers.IsHardwareIntrinsic(method))
{
result |= CorInfoFlag.CORINFO_FLG_JIT_INTRINSIC;
}
return (uint)result;
}
private void setMethodAttribs(CORINFO_METHOD_STRUCT_* ftn, CorInfoMethodRuntimeFlags attribs)
{
// TODO: Inlining
}
private void getMethodSig(CORINFO_METHOD_STRUCT_* ftn, CORINFO_SIG_INFO* sig, CORINFO_CLASS_STRUCT_* memberParent)
{
MethodDesc method = HandleToObject(ftn);
// There might be a more concrete parent type specified - this can happen when inlining.
if (memberParent != null)
{
TypeDesc type = HandleToObject(memberParent);
// Typically, the owning type of the method is a canonical type and the member parent
// supplied by RyuJIT is a concrete instantiation.
if (type != method.OwningType)
{
Debug.Assert(type.HasSameTypeDefinition(method.OwningType));
Instantiation methodInst = method.Instantiation;
method = _compilation.TypeSystemContext.GetMethodForInstantiatedType(method.GetTypicalMethodDefinition(), (InstantiatedType)type);
if (methodInst.Length > 0)
{
method = method.MakeInstantiatedMethod(methodInst);
}
}
}
Get_CORINFO_SIG_INFO(method, sig: sig);
}
private bool getMethodInfo(CORINFO_METHOD_STRUCT_* ftn, CORINFO_METHOD_INFO* info)
{
MethodDesc method = HandleToObject(ftn);
MethodIL methodIL = _compilation.GetMethodIL(method);
return Get_CORINFO_METHOD_INFO(method, methodIL, info);
}
private CorInfoInline canInline(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, ref uint pRestrictions)
{
MethodDesc callerMethod = HandleToObject(callerHnd);
MethodDesc calleeMethod = HandleToObject(calleeHnd);
if (_compilation.CanInline(callerMethod, calleeMethod))
{
// No restrictions on inlining
return CorInfoInline.INLINE_PASS;
}
else
{
// Call may not be inlined
return CorInfoInline.INLINE_NEVER;
}
}
private void reportTailCallDecision(CORINFO_METHOD_STRUCT_* callerHnd, CORINFO_METHOD_STRUCT_* calleeHnd, bool fIsTailPrefix, CorInfoTailCall tailCallResult, byte* reason)
{
}
private void getEHinfo(CORINFO_METHOD_STRUCT_* ftn, uint EHnumber, ref CORINFO_EH_CLAUSE clause)
{
var methodIL = _compilation.GetMethodIL(HandleToObject(ftn));
var ehRegion = methodIL.GetExceptionRegions()[EHnumber];
clause.Flags = (CORINFO_EH_CLAUSE_FLAGS)ehRegion.Kind;
clause.TryOffset = (uint)ehRegion.TryOffset;
clause.TryLength = (uint)ehRegion.TryLength;
clause.HandlerOffset = (uint)ehRegion.HandlerOffset;
clause.HandlerLength = (uint)ehRegion.HandlerLength;
clause.ClassTokenOrOffset = (uint)((ehRegion.Kind == ILExceptionRegionKind.Filter) ? ehRegion.FilterOffset : ehRegion.ClassToken);
}
private CORINFO_CLASS_STRUCT_* getMethodClass(CORINFO_METHOD_STRUCT_* method)
{
var m = HandleToObject(method);
return ObjectToHandle(m.OwningType);
}
private CORINFO_MODULE_STRUCT_* getMethodModule(CORINFO_METHOD_STRUCT_* method)
{
MethodDesc m = HandleToObject(method);
if (m is UnboxingMethodDesc unboxingMethodDesc)
{
m = unboxingMethodDesc.Target;
}
MethodIL methodIL = _compilation.GetMethodIL(m);
if (methodIL == null)
{
return null;
}
return (CORINFO_MODULE_STRUCT_*)ObjectToHandle(methodIL);
}
private bool resolveVirtualMethod(CORINFO_DEVIRTUALIZATION_INFO* info)
{
// Initialize OUT fields