-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathEETypeNode.cs
More file actions
1422 lines (1198 loc) · 69.4 KB
/
Copy pathEETypeNode.cs
File metadata and controls
1422 lines (1198 loc) · 69.4 KB
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 Internal.IL;
using Internal.IL.Stubs;
using Internal.Runtime;
using Internal.Text;
using Internal.TypeSystem;
using Debug = System.Diagnostics.Debug;
using GenericVariance = Internal.Runtime.GenericVariance;
namespace ILCompiler.DependencyAnalysis
{
/// <summary>
/// Given a type, EETypeNode writes an MethodTable data structure in the format expected by the runtime.
///
/// Format of an MethodTable:
///
/// Field Size | Contents
/// ----------------+-----------------------------------
/// UInt32 | Flags field
/// | Flags for: IsValueType, IsCrossModule, HasPointers, HasOptionalFields, IsInterface, IsGeneric, etc ...
/// | EETypeKind (Normal, Array, Pointer type)
/// |
/// | 5 bits near the top are used for enum EETypeElementType to record whether it's back by an Int32, Int16 etc
/// |
/// | The highest/sign bit indicates whether the lower Uint16 contains a number, which represents:
/// | - element type size for arrays,
/// | - char size for strings (normally 2, since .NET uses UTF16 character encoding),
/// | - for generic type definitions it is the number of generic parameters,
/// |
/// | If the sign bit is not set, then the lower Uint16 is used for additional ExtendedFlags
/// |
/// Uint32 | Base size.
/// |
/// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types.
/// |
/// UInt16 | Number of VTable slots (X)
/// |
/// UInt16 | Number of interfaces implemented by type (Y)
/// |
/// UInt32 | Hash code
/// |
/// X * [Ptr Size] | VTable entries (optional)
/// |
/// Y * [Ptr Size] | Pointers to interface map data structures (optional)
/// |
/// [Relative ptr] | Pointer to containing TypeManager indirection cell
/// |
/// [Relative ptr] | Pointer to writable data
/// |
/// [Relative ptr] | Pointer to finalizer method (optional)
/// |
/// [Relative ptr] | Pointer to optional fields (optional)
/// |
/// [Relative ptr] | Pointer to the generic type definition MethodTable (optional)
/// |
/// [Relative ptr] | Pointer to the generic argument and variance info (optional)
/// </summary>
public partial class EETypeNode : DehydratableObjectNode, IEETypeNode, ISymbolDefinitionNode, ISymbolNodeWithLinkage
{
protected readonly TypeDesc _type;
internal readonly EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder();
internal readonly EETypeOptionalFieldsNode _optionalFieldsNode;
private readonly WritableDataNode _writableDataNode;
protected bool? _mightHaveInterfaceDispatchMap;
private bool _hasConditionalDependenciesFromMetadataManager;
protected readonly VirtualMethodAnalysisFlags _virtualMethodAnalysisFlags;
[Flags]
protected enum VirtualMethodAnalysisFlags
{
None = 0,
NeedsGvmEntries = 0x0001,
InterestingForDynamicDependencies = 0x0002,
AllFlags = NeedsGvmEntries
| InterestingForDynamicDependencies,
}
public EETypeNode(NodeFactory factory, TypeDesc type)
{
if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any))
Debug.Assert(this is CanonicalDefinitionEETypeNode);
else if (type.IsCanonicalSubtype(CanonicalFormKind.Any))
Debug.Assert((this is CanonicalEETypeNode) || (this is NecessaryCanonicalEETypeNode));
Debug.Assert(!type.IsRuntimeDeterminedSubtype);
_type = type;
_optionalFieldsNode = new EETypeOptionalFieldsNode(this);
_writableDataNode = factory.Target.SupportsRelativePointers ? new WritableDataNode(this) : null;
_hasConditionalDependenciesFromMetadataManager = factory.MetadataManager.HasConditionalDependenciesDueToEETypePresence(type);
if (EmitVirtualSlotsAndInterfaces)
_virtualMethodAnalysisFlags = AnalyzeVirtualMethods(type);
factory.TypeSystemContext.EnsureLoadableType(type);
}
private static VirtualMethodAnalysisFlags AnalyzeVirtualMethods(TypeDesc type)
{
var result = VirtualMethodAnalysisFlags.None;
// Interface EETypes not relevant to virtual method analysis at this time.
if (type.IsInterface)
return result;
DefType defType = type.GetClosestDefType();
foreach (MethodDesc method in defType.GetAllVirtualMethods())
{
// First, check if this type has any GVM that overrides a GVM on a parent type. If that's the case, this makes
// the current type interesting for GVM analysis (i.e. instantiate its overriding GVMs for existing GVMDependenciesNodes
// of the instantiated GVM on the parent types).
if (method.HasInstantiation)
{
result |= VirtualMethodAnalysisFlags.NeedsGvmEntries;
MethodDesc slotDecl = MetadataVirtualMethodAlgorithm.FindSlotDefiningMethodForVirtualMethod(method);
if (slotDecl != method)
result |= VirtualMethodAnalysisFlags.InterestingForDynamicDependencies;
}
// Early out if we set all the flags we could have set
if ((result & VirtualMethodAnalysisFlags.AllFlags) == VirtualMethodAnalysisFlags.AllFlags)
return result;
}
//
// Check if the type implements any interface, where the method implementations could be on
// base types.
// Example:
// interface IFace {
// void IFaceGVMethod<U>();
// }
// class BaseClass {
// public virtual void IFaceGVMethod<U>() { ... }
// }
// public class DerivedClass : BaseClass, IFace { }
//
foreach (DefType interfaceImpl in defType.RuntimeInterfaces)
{
foreach (MethodDesc method in interfaceImpl.GetAllVirtualMethods())
{
if (!method.HasInstantiation)
continue;
// We found a GVM on one of the implemented interfaces. Find if the type implements this method.
// (Note, do this comparison against the generic definition of the method, not the specific method instantiation
MethodDesc slotDecl = method.Signature.IsStatic ?
defType.ResolveInterfaceMethodToStaticVirtualMethodOnType(method)
: defType.ResolveInterfaceMethodTarget(method);
if (slotDecl != null)
{
// If the type doesn't introduce this interface method implementation (i.e. the same implementation
// already exists in the base type), do not consider this type interesting for GVM analysis just yet.
//
// We need to limit the number of types that are interesting for GVM analysis at all costs since
// these all will be looked at for every unique generic virtual method call in the program.
// Having a long list of interesting types affects the compilation throughput heavily.
if (slotDecl.OwningType == defType ||
defType.BaseType.ResolveInterfaceMethodTarget(method) != slotDecl)
{
result |= VirtualMethodAnalysisFlags.InterestingForDynamicDependencies
| VirtualMethodAnalysisFlags.NeedsGvmEntries;
}
}
else
{
// The method could be implemented by a default interface method
var resolution = defType.ResolveInterfaceMethodToDefaultImplementationOnType(method, out _);
if (resolution == DefaultInterfaceMethodResolution.DefaultImplementation)
{
result |= VirtualMethodAnalysisFlags.InterestingForDynamicDependencies
| VirtualMethodAnalysisFlags.NeedsGvmEntries;
}
}
// Early out if we set all the flags we could have set
if ((result & VirtualMethodAnalysisFlags.AllFlags) == VirtualMethodAnalysisFlags.AllFlags)
return result;
}
}
return result;
}
protected bool MightHaveInterfaceDispatchMap(NodeFactory factory)
{
if (!_mightHaveInterfaceDispatchMap.HasValue)
{
_mightHaveInterfaceDispatchMap = EmitVirtualSlotsAndInterfaces && InterfaceDispatchMapNode.MightHaveInterfaceDispatchMap(_type, factory);
}
return _mightHaveInterfaceDispatchMap.Value;
}
protected override string GetName(NodeFactory factory) => this.GetMangledName(factory.NameMangler);
public override bool ShouldSkipEmittingObjectNode(NodeFactory factory)
{
// If there is a constructed version of this node in the graph, emit that instead
if (ConstructedEETypeNode.CreationAllowed(_type))
return factory.ConstructedTypeSymbol(_type).Marked;
return false;
}
public virtual ISymbolNode NodeForLinkage(NodeFactory factory)
{
return factory.NecessaryTypeSymbol(_type);
}
public TypeDesc Type => _type;
protected override ObjectNodeSection GetDehydratedSection(NodeFactory factory)
{
if (factory.Target.IsWindows)
return ObjectNodeSection.ReadOnlyDataSection;
else
return ObjectNodeSection.DataSection;
}
public int MinimumObjectSize => GetMinimumObjectSize(_type.Context);
public static int GetMinimumObjectSize(TypeSystemContext typeSystemContext)
=> typeSystemContext.Target.PointerSize * 3;
protected virtual bool EmitVirtualSlotsAndInterfaces => false;
public override bool InterestingForDynamicDependencyAnalysis
=> (_virtualMethodAnalysisFlags & VirtualMethodAnalysisFlags.InterestingForDynamicDependencies) != 0;
internal bool HasOptionalFields
{
get { return _optionalFieldsBuilder.IsAtLeastOneFieldUsed(); }
}
internal byte[] GetOptionalFieldsData()
{
return _optionalFieldsBuilder.GetBytes();
}
public override bool StaticDependenciesAreComputed => true;
public static string GetMangledName(TypeDesc type, NameMangler nameMangler)
{
return nameMangler.NodeMangler.MethodTable(type);
}
public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb)
{
sb.Append(nameMangler.NodeMangler.MethodTable(_type));
}
int ISymbolNode.Offset => 0;
int ISymbolDefinitionNode.Offset => GCDescSize;
public override bool IsShareable => IsTypeNodeShareable(_type);
private bool CanonFormTypeMayExist
{
get
{
if (!_type.HasInstantiation)
return false;
if (!_type.Context.SupportsCanon)
return false;
// If type is already in canon form, a canonically equivalent type cannot exist
if (_type.IsCanonicalSubtype(CanonicalFormKind.Any))
return false;
// If we reach here, a universal canon variant can exist (if universal canon is supported)
if (_type.Context.SupportsUniversalCanon)
return true;
// Attempt to convert to canon. If the type changes, then the CanonForm exists
return (_type.ConvertToCanonForm(CanonicalFormKind.Specific) != _type);
}
}
public sealed override bool HasConditionalStaticDependencies
{
get
{
// If the type is can be converted to some interesting canon type, and this is the non-constructed variant of an MethodTable
// we may need to trigger the fully constructed type to exist to make the behavior of the type consistent
// in reflection and generic template expansion scenarios
if (CanonFormTypeMayExist)
{
return true;
}
if (!EmitVirtualSlotsAndInterfaces)
return false;
// Since the vtable is dependency driven, generate conditional static dependencies for
// all possible vtable entries.
//
// The conditional dependencies conditionally add the implementation of the virtual method
// if the virtual method is used.
//
// We walk the inheritance chain because abstract bases would only add a "tentative"
// method body of the implementation that can be trimmed away if no other type uses it.
DefType currentType = _type.GetClosestDefType();
while (currentType != null)
{
if (currentType == _type || (currentType is MetadataType mdType && mdType.IsAbstract))
{
foreach (var method in currentType.GetAllVirtualMethods())
{
// Abstract methods don't have a body associated with it so there's no conditional
// dependency to add.
// Generic virtual methods are tracked by an orthogonal mechanism.
if (!method.IsAbstract && !method.HasInstantiation)
return true;
}
}
currentType = currentType.BaseType;
}
// If the type implements at least one interface, calls against that interface could result in this type's
// implementation being used.
if (_type.RuntimeInterfaces.Length > 0)
return true;
return _hasConditionalDependenciesFromMetadataManager;
}
}
public sealed override IEnumerable<CombinedDependencyListEntry> GetConditionalStaticDependencies(NodeFactory factory)
{
List<CombinedDependencyListEntry> result = new List<CombinedDependencyListEntry>();
IEETypeNode maximallyConstructableType = factory.MaximallyConstructableType(_type);
if (maximallyConstructableType != this)
{
// MethodTable upgrading from necessary to constructed if some template instantiation exists that matches up
// This ensures we don't end up having two EETypes in the system (one is this necessary type, and another one
// that was dynamically created at runtime).
if (CanonFormTypeMayExist)
{
result.Add(new CombinedDependencyListEntry(maximallyConstructableType, factory.MaximallyConstructableType(_type.ConvertToCanonForm(CanonicalFormKind.Specific)), "Trigger full type generation if canonical form exists"));
if (_type.Context.SupportsUniversalCanon)
result.Add(new CombinedDependencyListEntry(maximallyConstructableType, factory.MaximallyConstructableType(_type.ConvertToCanonForm(CanonicalFormKind.Universal)), "Trigger full type generation if universal canonical form exists"));
}
return result;
}
TypeDesc canonOwningType = _type.ConvertToCanonForm(CanonicalFormKind.Specific);
if (_type.IsDefType && _type != canonOwningType)
{
result.Add(new CombinedDependencyListEntry(
factory.GenericStaticBaseInfo((MetadataType)_type),
factory.NativeLayout.TemplateTypeLayout(canonOwningType),
"Information about static bases for type with template"));
}
if (!EmitVirtualSlotsAndInterfaces)
return result;
DefType defType = _type.GetClosestDefType();
// If we're producing a full vtable, none of the dependencies are conditional.
if (!factory.VTable(defType).HasFixedSlots)
{
bool isNonInterfaceAbstractType = !defType.IsInterface && ((MetadataType)defType).IsAbstract;
foreach (MethodDesc decl in defType.EnumAllVirtualSlots())
{
// Generic virtual methods are tracked by an orthogonal mechanism.
if (decl.HasInstantiation)
continue;
MethodDesc impl = defType.FindVirtualFunctionTargetMethodOnObjectType(decl);
bool implOwnerIsAbstract = ((MetadataType)impl.OwningType).IsAbstract;
// We add a conditional dependency in two situations:
// 1. The implementation is on this type. This is pretty obvious.
// 2. The implementation comes from an abstract base type. We do this
// because abstract types only request a TentativeMethodEntrypoint of the implementation.
// The actual method body of this entrypoint might still be trimmed away.
// We don't need to do this for implementations from non-abstract bases since
// non-abstract types will create a hard conditional reference to their virtual
// method implementations.
//
// We also skip abstract methods since they don't have a body to refer to.
if ((impl.OwningType == defType || implOwnerIsAbstract) && !impl.IsAbstract)
{
MethodDesc canonImpl = impl.GetCanonMethodTarget(CanonicalFormKind.Specific);
// If this is an abstract type, only request a tentative entrypoint (whose body
// might just be stubbed out). This lets us avoid generating method bodies for
// virtual method on abstract types that are overriden in all their children.
//
// We don't do this if the method can be placed in the sealed vtable since
// those can never be overriden by children anyway.
bool canUseTentativeMethod = isNonInterfaceAbstractType
&& !decl.CanMethodBeInSealedVTable()
&& factory.CompilationModuleGroup.AllowVirtualMethodOnAbstractTypeOptimization(canonImpl);
IMethodNode implNode = canUseTentativeMethod ?
factory.TentativeMethodEntrypoint(canonImpl, impl.OwningType.IsValueType) :
factory.MethodEntrypoint(canonImpl, impl.OwningType.IsValueType);
result.Add(new CombinedDependencyListEntry(implNode, factory.VirtualMethodUse(decl), "Virtual method"));
}
if (impl.OwningType == defType)
{
factory.MetadataManager.NoteOverridingMethod(decl, impl);
}
factory.MetadataManager.GetDependenciesForOverridingMethod(ref result, factory, decl, impl);
}
Debug.Assert(
_type == defType ||
((System.Collections.IStructuralEquatable)defType.RuntimeInterfaces).Equals(_type.RuntimeInterfaces,
EqualityComparer<DefType>.Default));
// Interfaces don't have vtables and we don't need to track their instance method slot use.
// The only exception are those interfaces that provide IDynamicInterfaceCastable implementations;
// those have slots and we dispatch on them.
bool needsDependenciesForInstanceInterfaceMethodImpls = !defType.IsInterface
|| ((MetadataType)defType).IsDynamicInterfaceCastableImplementation();
// Add conditional dependencies for interface methods the type implements. For example, if the type T implements
// interface IFoo which has a method M1, add a dependency on T.M1 dependent on IFoo.M1 being called, since it's
// possible for any IFoo object to actually be an instance of T.
DefType[] defTypeRuntimeInterfaces = defType.RuntimeInterfaces;
for (int interfaceIndex = 0; interfaceIndex < defTypeRuntimeInterfaces.Length; interfaceIndex++)
{
DefType interfaceType = defTypeRuntimeInterfaces[interfaceIndex];
Debug.Assert(interfaceType.IsInterface);
bool isVariantInterfaceImpl = VariantInterfaceMethodUseNode.IsVariantInterfaceImplementation(factory, _type, interfaceType);
foreach (MethodDesc interfaceMethod in interfaceType.GetAllVirtualMethods())
{
// Generic virtual methods are tracked by an orthogonal mechanism.
if (interfaceMethod.HasInstantiation)
continue;
bool isStaticInterfaceMethod = interfaceMethod.Signature.IsStatic;
if (!isStaticInterfaceMethod && !needsDependenciesForInstanceInterfaceMethodImpls)
continue;
MethodDesc implMethod = isStaticInterfaceMethod ?
defType.ResolveInterfaceMethodToStaticVirtualMethodOnType(interfaceMethod) :
defType.ResolveInterfaceMethodToVirtualMethodOnType(interfaceMethod);
if (implMethod != null)
{
if (isStaticInterfaceMethod)
{
Debug.Assert(!implMethod.IsVirtual);
MethodDesc defaultIntfMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
// If the interface method is used virtually, the implementation body is used
result.Add(new CombinedDependencyListEntry(factory.MethodEntrypoint(defaultIntfMethod), factory.VirtualMethodUse(interfaceMethod), "Interface method"));
}
else
{
// If the interface method is used virtually, the slot is used virtually
result.Add(new CombinedDependencyListEntry(factory.VirtualMethodUse(implMethod), factory.VirtualMethodUse(interfaceMethod), "Interface method"));
}
// If any of the implemented interfaces have variance, calls against compatible interface methods
// could result in interface methods of this type being used (e.g. IEnumerable<object>.GetEnumerator()
// can dispatch to an implementation of IEnumerable<string>.GetEnumerator()).
if (isVariantInterfaceImpl)
{
MethodDesc typicalInterfaceMethod = interfaceMethod.GetTypicalMethodDefinition();
object implMethodUseNode = isStaticInterfaceMethod ?
factory.CanonicalEntrypoint(implMethod) : factory.VirtualMethodUse(implMethod);
result.Add(new CombinedDependencyListEntry(implMethodUseNode, factory.VariantInterfaceMethodUse(typicalInterfaceMethod), "Interface method"));
result.Add(new CombinedDependencyListEntry(factory.VirtualMethodUse(interfaceMethod), factory.VariantInterfaceMethodUse(typicalInterfaceMethod), "Interface method"));
}
factory.MetadataManager.NoteOverridingMethod(interfaceMethod, implMethod);
factory.MetadataManager.GetDependenciesForOverridingMethod(ref result, factory, interfaceMethod, implMethod);
}
else
{
// Is the implementation provided by a default interface method?
// If so, add a dependency on the entrypoint directly since nobody else is going to do that
// (interface types have an empty vtable, modulo their generic dictionary).
TypeDesc interfaceOnDefinition = defType.GetTypeDefinition().RuntimeInterfaces[interfaceIndex];
MethodDesc interfaceMethodDefinition = interfaceMethod;
if (!interfaceType.IsTypeDefinition)
interfaceMethodDefinition = factory.TypeSystemContext.GetMethodForInstantiatedType(interfaceMethod.GetTypicalMethodDefinition(), (InstantiatedType)interfaceOnDefinition);
var resolution = defType.GetTypeDefinition().ResolveInterfaceMethodToDefaultImplementationOnType(interfaceMethodDefinition, out implMethod);
if (resolution == DefaultInterfaceMethodResolution.DefaultImplementation)
{
DefType providingInterfaceDefinitionType = (DefType)implMethod.OwningType;
implMethod = implMethod.InstantiateSignature(defType.Instantiation, Instantiation.Empty);
MethodDesc defaultIntfMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific);
if (!isStaticInterfaceMethod && defaultIntfMethod.IsCanonicalMethod(CanonicalFormKind.Any))
{
// Canonical instance default methods need to go through a thunk that adds the right generic context
defaultIntfMethod = factory.TypeSystemContext.GetDefaultInterfaceMethodImplementationThunk(defaultIntfMethod, _type.ConvertToCanonForm(CanonicalFormKind.Specific), providingInterfaceDefinitionType);
}
result.Add(new CombinedDependencyListEntry(factory.MethodEntrypoint(defaultIntfMethod), factory.VirtualMethodUse(interfaceMethod), "Interface method"));
factory.MetadataManager.NoteOverridingMethod(interfaceMethod, implMethod);
factory.MetadataManager.GetDependenciesForOverridingMethod(ref result, factory, interfaceMethod, implMethod);
}
}
}
}
}
factory.MetadataManager.GetConditionalDependenciesDueToEETypePresence(ref result, factory, _type);
return result;
}
public static bool IsTypeNodeShareable(TypeDesc type)
{
return type.IsParameterizedType || type.IsFunctionPointer || type is InstantiatedType;
}
internal static bool MethodHasNonGenericILMethodBody(MethodDesc method)
{
// Generic methods have their own generic dictionaries
if (method.HasInstantiation)
return false;
// Abstract methods don't have a body
if (method.IsAbstract)
return false;
// PInvoke methods are not permitted on generic types,
// but let's not crash the compilation because of that.
if (method.IsPInvoke)
return false;
// NativeAOT can generate method bodies for these no matter what (worst case
// they'll be throwing). We don't want to take the "return false" code path because
// delegate methods fall into the runtime implemented category on NativeAOT, but we
// just treat them like regular method bodies.
return true;
}
protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory)
{
DependencyList dependencies = new DependencyList();
// Include the optional fields by default. We don't know if optional fields will be needed until
// all of the interface usage has been stabilized. If we end up not needing it, the MethodTable node will not
// generate any relocs to it, and the optional fields node will instruct the object writer to skip
// emitting it.
dependencies.Add(new DependencyListEntry(_optionalFieldsNode, "Optional fields"));
if (EmitVirtualSlotsAndInterfaces)
{
if (!_type.IsArrayTypeWithoutGenericInterfaces())
{
// Sealed vtables have relative pointers, so to minimize size, we build sealed vtables for the canonical types
dependencies.Add(new DependencyListEntry(factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific)), "Sealed Vtable"));
}
// Also add the un-normalized vtable slices of implemented interfaces.
// This is important to do in the scanning phase so that the compilation phase can find
// vtable information for things like IEnumerator<List<__Canon>>.
foreach (TypeDesc intface in _type.RuntimeInterfaces)
dependencies.Add(factory.VTable(intface), "Interface vtable slice");
// Generated type contains generic virtual methods that will get added to the GVM tables
if ((_virtualMethodAnalysisFlags & VirtualMethodAnalysisFlags.NeedsGvmEntries) != 0)
{
dependencies.Add(new DependencyListEntry(factory.TypeGVMEntries(_type.GetTypeDefinition()), "Type with generic virtual methods"));
AddDependenciesForUniversalGVMSupport(factory, _type, ref dependencies);
TypeDesc canonicalType = _type.ConvertToCanonForm(CanonicalFormKind.Specific);
if (canonicalType != _type)
dependencies.Add(factory.ConstructedTypeSymbol(canonicalType), "Type with generic virtual methods");
}
}
if (factory.CompilationModuleGroup.PresenceOfEETypeImpliesAllMethodsOnType(_type))
{
if (_type.IsArray || _type.IsDefType)
{
// If the compilation group wants this type to be fully promoted, ensure that all non-generic methods of the
// type are generated.
// This may be done for several reasons:
// - The MethodTable may be going to be COMDAT folded with other EETypes generated in a different object file
// This means their generic dictionaries need to have identical contents. The only way to achieve that is
// by generating the entries for all methods that contribute to the dictionary, and sorting the dictionaries.
// - The generic type may be imported into another module, in which case the generic dictionary imported
// must represent all of the methods, as the set of used methods cannot be known at compile time
// - As a matter of policy, the type and its methods may be exported for use in another module. The policy
// may wish to specify that if a type is to be placed into a shared module, all of the methods associated with
// it should be also be exported.
foreach (var method in _type.GetClosestDefType().ConvertToCanonForm(CanonicalFormKind.Specific).GetAllMethods())
{
if (!MethodHasNonGenericILMethodBody(method))
continue;
dependencies.Add(factory.MethodEntrypoint(method.GetCanonMethodTarget(CanonicalFormKind.Specific)),
"Ensure all methods on type due to CompilationModuleGroup policy");
}
}
}
// Ask the metadata manager
// if we have any dependencies due to presence of the EEType.
factory.MetadataManager.GetDependenciesDueToEETypePresence(ref dependencies, factory, _type);
if (_type is MetadataType mdType)
ModuleUseBasedDependencyAlgorithm.AddDependenciesDueToModuleUse(ref dependencies, factory, mdType.Module);
if (_type.IsFunctionPointer)
FunctionPointerMapNode.GetHashtableDependencies(ref dependencies, factory, (FunctionPointerType)_type);
return dependencies;
}
protected override ObjectData GetDehydratableData(NodeFactory factory, bool relocsOnly)
{
ObjectDataBuilder objData = new ObjectDataBuilder(factory, relocsOnly);
objData.RequireInitialPointerAlignment();
objData.AddSymbol(this);
ComputeOptionalEETypeFields(factory, relocsOnly);
OutputGCDesc(ref objData);
OutputFlags(factory, ref objData, relocsOnly);
objData.EmitInt(BaseSize);
OutputRelatedType(factory, ref objData);
// Number of vtable slots will be only known later. Reseve the bytes for it.
var vtableSlotCountReservation = objData.ReserveShort();
// Number of interfaces will only be known later. Reserve the bytes for it.
var interfaceCountReservation = objData.ReserveShort();
objData.EmitInt(_type.GetHashCode());
if (EmitVirtualSlotsAndInterfaces)
{
// Emit VTable
Debug.Assert(objData.CountBytes - ((ISymbolDefinitionNode)this).Offset == GetVTableOffset(objData.TargetPointerSize));
SlotCounter virtualSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData);
OutputVirtualSlots(factory, ref objData, _type, _type, _type, relocsOnly);
// Update slot count
int numberOfVtableSlots = virtualSlotCounter.CountSlots(ref /* readonly */ objData);
objData.EmitShort(vtableSlotCountReservation, checked((short)numberOfVtableSlots));
// Emit interface map
SlotCounter interfaceSlotCounter = SlotCounter.BeginCounting(ref /* readonly */ objData);
OutputInterfaceMap(factory, ref objData);
// Update slot count
int numberOfInterfaceSlots = interfaceSlotCounter.CountSlots(ref /* readonly */ objData);
objData.EmitShort(interfaceCountReservation, checked((short)numberOfInterfaceSlots));
}
else
{
// If we're not emitting any slots, the number of slots is zero.
objData.EmitShort(vtableSlotCountReservation, 0);
objData.EmitShort(interfaceCountReservation, 0);
}
OutputTypeManagerIndirection(factory, ref objData);
OutputWritableData(factory, ref objData);
OutputDispatchMap(factory, ref objData);
OutputFinalizerMethod(factory, ref objData);
OutputOptionalFields(factory, ref objData);
OutputSealedVTable(factory, relocsOnly, ref objData);
OutputGenericInstantiationDetails(factory, ref objData);
OutputFunctionPointerParameters(factory, ref objData);
return objData.ToObjectData();
}
/// <summary>
/// Returns the offset within an MethodTable of the beginning of VTable entries
/// </summary>
/// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param>
public static int GetVTableOffset(int pointerSize)
{
return 16 + pointerSize;
}
protected virtual int GCDescSize => 0;
protected virtual void OutputGCDesc(ref ObjectDataBuilder builder)
{
// Non-constructed EETypeNodes get no GC Desc
Debug.Assert(GCDescSize == 0);
}
private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData, bool relocsOnly)
{
uint flags = EETypeBuilderHelpers.ComputeFlags(_type);
if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType)
{
// Generic array enumerators use special variance rules recognized by the runtime
flags |= (uint)EETypeFlags.GenericVarianceFlag;
}
if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type))
{
// Runtime casting logic relies on all interface types implemented on arrays
// to have the variant flag set (even if all the arguments are non-variant).
// This supports e.g. casting uint[] to ICollection<int>
flags |= (uint)EETypeFlags.GenericVarianceFlag;
}
if (EmitVirtualSlotsAndInterfaces && !_type.IsArrayTypeWithoutGenericInterfaces())
{
SealedVTableNode sealedVTable = factory.SealedVTable(_type.ConvertToCanonForm(CanonicalFormKind.Specific));
if (sealedVTable.BuildSealedVTableSlots(factory, relocsOnly) && sealedVTable.NumSealedVTableEntries > 0)
flags |= (uint)EETypeFlags.HasSealedVTableEntriesFlag;
}
if (MightHaveInterfaceDispatchMap(factory))
{
flags |= (uint)EETypeFlags.HasDispatchMap;
}
if (HasOptionalFields)
{
flags |= (uint)EETypeFlags.OptionalFieldsFlag;
}
if (_type.IsArray || _type.IsString)
{
flags |= (uint)EETypeFlags.HasComponentSizeFlag;
}
//
// output ComponentSize or FlagsEx
//
if (_type.IsArray)
{
TypeDesc elementType = ((ArrayType)_type).ElementType;
if (elementType == elementType.Context.UniversalCanonType)
{
// elementSize == 0
}
else
{
int elementSize = elementType.GetElementSize().AsInt;
// We validated that this will fit the short when the node was constructed. No need for nice messages.
flags |= (uint)checked((ushort)elementSize);
}
}
else if (_type.IsString)
{
flags |= StringComponentSize.Value;
}
else
{
ushort flagsEx = EETypeBuilderHelpers.ComputeFlagsEx(_type);
flags |= flagsEx;
}
objData.EmitUInt(flags);
}
protected virtual int BaseSize
{
get
{
int pointerSize = _type.Context.Target.PointerSize;
int objectSize;
if (_type.IsInterface)
{
// Interfaces don't live on the GC heap. Don't bother computing a number.
// Zero compresses better than any useless number we would come up with.
return 0;
}
else if (_type.IsDefType)
{
LayoutInt instanceByteCount = ((DefType)_type).InstanceByteCount;
if (instanceByteCount.IsIndeterminate)
{
// Some value must be put in, but the specific value doesn't matter as it
// isn't used for specific instantiations, and the universal canon MethodTable
// is never associated with an allocated object.
objectSize = pointerSize;
}
else
{
objectSize = pointerSize +
((DefType)_type).InstanceByteCount.AsInt; // +pointerSize for SyncBlock
}
if (_type.IsValueType)
objectSize += pointerSize; // + EETypePtr field inherited from System.Object
}
else if (_type.IsArray)
{
objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length
if (_type.IsMdArray)
objectSize +=
2 * sizeof(int) * ((ArrayType)_type).Rank;
}
else if (_type.IsPointer)
{
// These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime.
return ParameterizedTypeShapeConstants.Pointer;
}
else if (_type.IsByRef)
{
// These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime.
return ParameterizedTypeShapeConstants.ByRef;
}
else if (_type.IsFunctionPointer)
{
// These never get boxed and don't have a base size. We store the 'unmanaged' flag and number of parameters.
MethodSignature sig = ((FunctionPointerType)_type).Signature;
return (sig.Flags & MethodSignatureFlags.UnmanagedCallingConventionMask) switch
{
0 => sig.Length,
_ => sig.Length | unchecked((int)FunctionPointerFlags.IsUnmanaged),
};
}
else
throw new NotImplementedException();
objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize);
objectSize = Math.Max(MinimumObjectSize, objectSize);
if (_type.IsString)
{
// If this is a string, throw away objectSize we computed so far. Strings are special.
// SyncBlock + EETypePtr + length + firstChar
objectSize = 2 * pointerSize +
sizeof(int) +
StringComponentSize.Value;
}
return objectSize;
}
}
protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory)
{
return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null;
}
protected virtual ISymbolNode GetNonNullableValueTypeArrayElementTypeNode(NodeFactory factory)
{
return factory.NecessaryTypeSymbol(((ArrayType)_type).ElementType);
}
private ISymbolNode GetRelatedTypeNode(NodeFactory factory)
{
ISymbolNode relatedTypeNode = null;
if (_type.IsParameterizedType)
{
var parameterType = ((ParameterizedType)_type).ParameterType;
if (_type.IsArray && parameterType.IsValueType && !parameterType.IsNullable)
{
// This might be a constructed type symbol. There are APIs on Array that allow allocating element
// types through runtime magic ("((Array)new NeverAllocated[1]).GetValue(0)" or IEnumerable) and we don't have
// visibility into that. Conservatively assume element types of constructed arrays are also constructed.
relatedTypeNode = GetNonNullableValueTypeArrayElementTypeNode(factory);
}
else
{
relatedTypeNode = factory.NecessaryTypeSymbol(parameterType);
}
}
else if (_type.IsFunctionPointer)
{
relatedTypeNode = factory.NecessaryTypeSymbol(((FunctionPointerType)_type).Signature.ReturnType);
}
else
{
TypeDesc baseType = _type.BaseType;
if (baseType != null)
{
relatedTypeNode = GetBaseTypeNode(factory);
}
}
return relatedTypeNode;
}
protected virtual void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData)
{
ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory);
if (relatedTypeNode != null)
{
objData.EmitPointerReloc(relatedTypeNode);
}
else
{
objData.EmitZeroPointer();
}
}
private void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType, TypeDesc templateType, bool relocsOnly)
{
Debug.Assert(EmitVirtualSlotsAndInterfaces);
declType = declType.GetClosestDefType();
templateType = templateType.ConvertToCanonForm(CanonicalFormKind.Specific);
var baseType = declType.BaseType;
if (baseType != null)
{
Debug.Assert(templateType.BaseType != null);
OutputVirtualSlots(factory, ref objData, implType, baseType, templateType.BaseType, relocsOnly);
}
//
// In the universal canonical types case, we could have base types in the hierarchy that are partial universal canonical types.
// The presence of these types could cause incorrect vtable layouts, so we need to fully canonicalize them and walk the
// hierarchy of the template type of the original input type to detect these cases.
//
// Exmaple: we begin with Derived<__UniversalCanon> and walk the template hierarchy:
//
// class Derived<T> : Middle<T, MyStruct> { } // -> Template is Derived<__UniversalCanon> and needs a dictionary slot
// // -> Basetype tempalte is Middle<__UniversalCanon, MyStruct>. It's a partial
// Universal canonical type, so we need to fully canonicalize it.
//
// class Middle<T, U> : Base<U> { } // -> Template is Middle<__UniversalCanon, __UniversalCanon> and needs a dictionary slot
// // -> Basetype template is Base<__UniversalCanon>
//
// class Base<T> { } // -> Template is Base<__UniversalCanon> and needs a dictionary slot.
//
// If we had not fully canonicalized the Middle class template, we would have ended up with Base<MyStruct>, which does not need
// a dictionary slot, meaning we would have created a vtable layout that the runtime does not expect.
//
// The generic dictionary pointer occupies the first slot of each type vtable slice
if (declType.HasGenericDictionarySlot() || templateType.HasGenericDictionarySlot())
{
// All generic interface types have a dictionary slot, but only some of them have an actual dictionary.
bool isInterfaceWithAnEmptySlot = declType.IsInterface &&
declType.ConvertToCanonForm(CanonicalFormKind.Specific) == declType;
// Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty
// Note: If the current EETypeNode represents a universal canonical type, any dictionary slot must be empty
if (declType.IsCanonicalSubtype(CanonicalFormKind.Any)
|| implType.IsCanonicalSubtype(CanonicalFormKind.Universal)
|| factory.LazyGenericsPolicy.UsesLazyGenerics(declType)
|| isInterfaceWithAnEmptySlot)
{
objData.EmitZeroPointer();
}
else
{
TypeGenericDictionaryNode dictionaryNode = factory.TypeGenericDictionary(declType);
DictionaryLayoutNode layoutNode = dictionaryNode.GetDictionaryLayout(factory);
// Don't bother emitting a reloc to an empty dictionary. We'll only know whether the dictionary is
// empty at final object emission time, so don't ask if we're not emitting yet.
if (!relocsOnly && layoutNode.IsEmpty)
objData.EmitZeroPointer();
else
objData.EmitPointerReloc(dictionaryNode);
}
}
VTableSliceNode declVTable = factory.VTable(declType);
// It's only okay to touch the actual list of slots if we're in the final emission phase
// or the vtable is not built lazily.
if (relocsOnly && !declVTable.HasFixedSlots)
return;
// Interface types don't place anything else in their physical vtable.
// Interfaces have logical slots for their methods but since they're all abstract, they would be zero.
// We place default implementations of interface methods into the vtable of the interface-implementing
// type, pretending there was an extra virtual slot.
if (_type.IsInterface)