forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenMeta.cpp
5086 lines (4331 loc) · 194 KB
/
GenMeta.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- GenMeta.cpp - IR generation for metadata constructs --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for metadata constructs like
// metatypes and modules. These is presently always trivial, but in
// the future we will likely have some sort of physical
// representation for at least some metatypes.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Substitution.h"
#include "swift/AST/Types.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/ABI/MetadataValues.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Module.h"
#include "llvm/ADT/SmallString.h"
#include "Address.h"
#include "Callee.h"
#include "ClassMetadataLayout.h"
#include "FixedTypeInfo.h"
#include "GenClass.h"
#include "GenPoly.h"
#include "GenArchetype.h"
#include "GenStruct.h"
#include "HeapTypeInfo.h"
#include "IRGenModule.h"
#include "IRGenDebugInfo.h"
#include "Linking.h"
#include "ScalarTypeInfo.h"
#include "StructMetadataLayout.h"
#include "StructLayout.h"
#include "EnumMetadataLayout.h"
#include "GenMeta.h"
using namespace swift;
using namespace irgen;
static llvm::Value *emitLoadOfObjCHeapMetadataRef(IRGenFunction &IGF,
llvm::Value *object);
/// Produce a constant to place in a metatype's isa field
/// corresponding to the given metadata kind.
static llvm::ConstantInt *getMetadataKind(IRGenModule &IGM,
MetadataKind kind) {
return llvm::ConstantInt::get(IGM.MetadataKindTy, uint8_t(kind));
}
static Size::int_type getOffsetInWords(IRGenModule &IGM, Size offset) {
assert(offset.isMultipleOf(IGM.getPointerSize()));
return offset / IGM.getPointerSize();
}
static Address createPointerSizedGEP(IRGenFunction &IGF,
Address base,
Size offset) {
return IGF.Builder.CreateConstArrayGEP(base,
getOffsetInWords(IGF.IGM, offset),
offset);
}
static llvm::Constant *getMangledTypeName(IRGenModule &IGM, CanType type) {
auto name = LinkEntity::forTypeMangling(type);
llvm::SmallString<32> mangling;
name.mangle(mangling);
return IGM.getAddrOfGlobalString(mangling);
}
llvm::Value *irgen::emitObjCMetadataRefForMetadata(IRGenFunction &IGF,
llvm::Value *classPtr) {
classPtr = IGF.Builder.CreateBitCast(classPtr, IGF.IGM.ObjCClassPtrTy);
// Fetch the metadata for that class.
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetObjCClassMetadataFn(),
classPtr);
call->setDoesNotThrow();
call->setDoesNotAccessMemory();
call->setCallingConv(IGF.IGM.RuntimeCC);
return call;
}
/// Emit a reference to the Swift metadata for an Objective-C class.
static llvm::Value *emitObjCMetadataRef(IRGenFunction &IGF,
ClassDecl *theClass) {
// Derive a pointer to the Objective-C class.
auto classPtr = emitObjCHeapMetadataRef(IGF, theClass);
return emitObjCMetadataRefForMetadata(IGF, classPtr);
}
namespace {
/// A structure for collecting generic arguments for emitting a
/// nominal metadata reference. The structure produced here is
/// consumed by swift_getGenericMetadata() and must correspond to
/// the fill operations that the compiler emits for the bound decl.
struct GenericArguments {
/// The values to use to initialize the arguments structure.
SmallVector<llvm::Value *, 8> Values;
SmallVector<llvm::Type *, 8> Types;
void collect(IRGenFunction &IGF, BoundGenericType *type) {
// Add all the argument archetypes.
// TODO: only the *primary* archetypes
// TODO: not archetypes from outer contexts
// TODO: but we are partially determined by the outer context!
for (auto &sub : type->getSubstitutions(/*FIXME:*/nullptr, nullptr)) {
CanType subbed = sub.getReplacement()->getCanonicalType();
Values.push_back(IGF.emitTypeMetadataRef(subbed));
}
// All of those values are metadata pointers.
Types.append(Values.size(), IGF.IGM.TypeMetadataPtrTy);
// Add protocol witness tables for all those archetypes.
for (auto &sub : type->getSubstitutions(/*FIXME:*/nullptr, nullptr))
emitWitnessTableRefs(IGF, sub, Values);
// All of those values are witness table pointers.
Types.append(Values.size() - Types.size(), IGF.IGM.WitnessTablePtrTy);
}
};
}
/// Given an array of polymorphic arguments as might be set up by
/// GenericArguments, bind the polymorphic parameters.
static void emitPolymorphicParametersFromArray(IRGenFunction &IGF,
const GenericParamList &generics,
Address array) {
unsigned nextIndex = 0;
auto claimNext = [&](llvm::PointerType *desiredType) {
Address addr = array;
if (unsigned index = nextIndex++) {
addr = IGF.Builder.CreateConstArrayGEP(array, index,
index * IGF.IGM.getPointerSize());
}
llvm::Value *value = IGF.Builder.CreateLoad(addr);
return IGF.Builder.CreateBitCast(value, desiredType);
};
// Bind all the argument archetypes.
for (auto archetype : generics.getAllArchetypes()) {
llvm::Value *metadata = claimNext(IGF.IGM.TypeMetadataPtrTy);
metadata->setName(archetype->getFullName());
IGF.setUnscopedLocalTypeData(CanType(archetype),
LocalTypeData::forMetatype(),
metadata);
}
// Bind all the argument witness tables.
for (auto archetype : generics.getAllArchetypes()) {
unsigned nextProtocolIndex = 0;
for (auto protocol : archetype->getConformsTo()) {
LocalTypeData key
= LocalTypeData::forArchetypeProtocolWitness(nextProtocolIndex);
nextProtocolIndex++;
if (!Lowering::TypeConverter::protocolRequiresWitnessTable(protocol))
continue;
llvm::Value *wtable = claimNext(IGF.IGM.WitnessTablePtrTy);
IGF.setUnscopedLocalTypeData(CanType(archetype), key, wtable);
}
}
}
/// If true, we lazily initialize metadata at runtime because the layout
/// is only partially known. Otherwise, we can emit a direct reference a
/// constant metadata symbol.
static bool hasMetadataPattern(IRGenModule &IGM, NominalTypeDecl *theDecl) {
// Protocols must be special-cased in a few places.
assert(!isa<ProtocolDecl>(theDecl));
// Classes imported from Objective-C never have a metadata pattern.
if (theDecl->hasClangNode())
return false;
// A generic class, struct, or enum is always initialized at runtime.
if (theDecl->isGenericContext())
return true;
// If we have fields of resilient type, the metadata still has to be
// initialized at runtime.
if (!IGM.getTypeInfoForUnlowered(theDecl->getDeclaredType()).isFixedSize())
return true;
return false;
}
/// Attempts to return a constant heap metadata reference for a
/// nominal type.
llvm::Constant *irgen::tryEmitConstantHeapMetadataRef(IRGenModule &IGM,
CanType type) {
auto theDecl = type->getAnyNominal();
assert(theDecl && "emitting constant metadata ref for non-nominal type?");
if (hasMetadataPattern(IGM, theDecl))
return nullptr;
if (auto theClass = type->getClassOrBoundGenericClass())
if (!hasKnownSwiftMetadata(IGM, theClass))
return IGM.getAddrOfObjCClass(theClass, NotForDefinition);
return IGM.getAddrOfTypeMetadata(type, false);
}
/// Emit a reference to an ObjC class. In general, the only things
/// you're allowed to do with the address of an ObjC class symbol are
/// (1) send ObjC messages to it (in which case the message will be
/// forwarded to the real class, if one exists) or (2) put it in
/// various data sections where the ObjC runtime will properly arrange
/// things. Therefore, we must typically force the initialization of
/// a class when emitting a reference to it.
llvm::Value *irgen::emitObjCHeapMetadataRef(IRGenFunction &IGF,
ClassDecl *theClass,
bool allowUninitialized) {
auto classObject = IGF.IGM.getAddrOfObjCClass(theClass, NotForDefinition);
if (allowUninitialized) return classObject;
// TODO: memoize this the same way that we memoize Swift type metadata?
return IGF.Builder.CreateCall(IGF.IGM.getGetInitializedObjCClassFn(),
classObject);
}
/// Emit a reference to the type metadata for a foreign type.
static llvm::Value *emitForeignTypeMetadataRef(IRGenFunction &IGF,
CanType type) {
llvm::Value *candidate = IGF.IGM.getAddrOfForeignTypeMetadataCandidate(type);
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetForeignTypeMetadataFn(),
candidate);
call->addAttribute(llvm::AttributeSet::FunctionIndex,
llvm::Attribute::NoUnwind);
call->addAttribute(llvm::AttributeSet::FunctionIndex,
llvm::Attribute::ReadNone);
return call;
}
/// Returns a metadata reference for a nominal type.
static llvm::Value *emitNominalMetadataRef(IRGenFunction &IGF,
NominalTypeDecl *theDecl,
CanType theType) {
assert(!isa<ProtocolDecl>(theDecl));
// Non-native Swift classes need to be handled differently.
if (auto theClass = dyn_cast<ClassDecl>(theDecl)) {
// We emit a completely different pattern for foreign classes.
if (theClass->isForeign()) {
return emitForeignTypeMetadataRef(IGF, theType);
}
// Classes that might not have Swift metadata use a different
// symbol name.
if (!hasKnownSwiftMetadata(IGF.IGM, theClass)) {
assert(!theDecl->getGenericParamsOfContext() &&
"ObjC class cannot be generic");
return emitObjCMetadataRef(IGF, theClass);
}
} else if (theDecl->hasClangNode()) {
// Imported Clang types require foreign metadata uniquing too.
return emitForeignTypeMetadataRef(IGF, theType);
}
bool isPattern = hasMetadataPattern(IGF.IGM, theDecl);
// If this is generic, check to see if we've maybe got a local
// reference already.
if (isPattern) {
if (auto cache = IGF.tryGetLocalTypeData(theType,
LocalTypeData::forMetatype()))
return cache;
}
// Grab a reference to the metadata or metadata template.
CanType declaredType = theDecl->getDeclaredType()->getCanonicalType();
llvm::Value *metadata = IGF.IGM.getAddrOfTypeMetadata(declaredType,isPattern);
// If we don't have a metadata pattern, that's all we need.
if (!isPattern) {
assert(metadata->getType() == IGF.IGM.TypeMetadataPtrTy);
// If this is a class, we need to force ObjC initialization,
// but only if we're doing Objective-C interop.
if (IGF.IGM.ObjCInterop && isa<ClassDecl>(theDecl)) {
metadata = IGF.Builder.CreateBitCast(metadata, IGF.IGM.ObjCClassPtrTy);
metadata = IGF.Builder.CreateCall(IGF.IGM.getGetInitializedObjCClassFn(),
metadata);
metadata = IGF.Builder.CreateBitCast(metadata, IGF.IGM.TypeMetadataPtrTy);
}
return metadata;
}
// Okay, we need to call swift_getGenericMetadata.
assert(metadata->getType() == IGF.IGM.TypeMetadataPatternPtrTy);
// If we have a pattern but no generic substitutions, we're just
// doing resilient type layout.
if (isPattern && !theDecl->isGenericContext()) {
llvm::Constant *getter = IGF.IGM.getGetResilientMetadataFn();
auto result = IGF.Builder.CreateCall(getter, {metadata});
result->setDoesNotThrow();
result->addAttribute(llvm::AttributeSet::FunctionIndex,
llvm::Attribute::ReadNone);
IGF.setScopedLocalTypeData(theType, LocalTypeData::forMetatype(), result);
return result;
}
// Grab the substitutions.
auto boundGeneric = cast<BoundGenericType>(theType);
assert(boundGeneric->getDecl() == theDecl);
GenericArguments genericArgs;
genericArgs.collect(IGF, boundGeneric);
// If we have less than four arguments, use a fast entry point.
assert(genericArgs.Values.size() > 0 && "no generic args?!");
if (genericArgs.Values.size() <= 4) {
llvm::Constant *fastGetter;
switch (genericArgs.Values.size()) {
case 1: fastGetter = IGF.IGM.getGetGenericMetadata1Fn(); break;
case 2: fastGetter = IGF.IGM.getGetGenericMetadata2Fn(); break;
case 3: fastGetter = IGF.IGM.getGetGenericMetadata3Fn(); break;
case 4: fastGetter = IGF.IGM.getGetGenericMetadata4Fn(); break;
default: llvm_unreachable("bad number of generic arguments");
}
SmallVector<llvm::Value *, 5> args;
args.push_back(metadata);
for (auto value : genericArgs.Values)
args.push_back(IGF.Builder.CreateBitCast(value, IGF.IGM.Int8PtrTy));
auto result = IGF.Builder.CreateCall(fastGetter, args);
result->setDoesNotThrow();
result->addAttribute(llvm::AttributeSet::FunctionIndex,
llvm::Attribute::ReadNone);
IGF.setScopedLocalTypeData(theType, LocalTypeData::forMetatype(), result);
return result;
}
// Slam that information directly into the generic arguments buffer.
auto argsBufferTy =
llvm::StructType::get(IGF.IGM.LLVMContext, genericArgs.Types);
Address argsBuffer = IGF.createAlloca(argsBufferTy,
IGF.IGM.getPointerAlignment(),
"generic.arguments");
for (unsigned i = 0, e = genericArgs.Values.size(); i != e; ++i) {
Address elt = IGF.Builder.CreateStructGEP(argsBuffer, i,
IGF.IGM.getPointerSize() * i);
IGF.Builder.CreateStore(genericArgs.Values[i], elt);
}
// Cast to void*.
llvm::Value *arguments =
IGF.Builder.CreateBitCast(argsBuffer.getAddress(), IGF.IGM.Int8PtrTy);
// Make the call.
auto result = IGF.Builder.CreateCall(IGF.IGM.getGetGenericMetadataFn(),
{metadata, arguments});
result->setDoesNotThrow();
result->addAttribute(llvm::AttributeSet::FunctionIndex,
llvm::Attribute::ReadOnly);
IGF.setScopedLocalTypeData(theType, LocalTypeData::forMetatype(), result);
return result;
}
bool irgen::hasKnownSwiftMetadata(IRGenModule &IGM, CanType type) {
if (ClassDecl *theClass = type.getClassOrBoundGenericClass()) {
return hasKnownSwiftMetadata(IGM, theClass);
}
if (auto archetype = dyn_cast<ArchetypeType>(type)) {
if (auto superclass = archetype->getSuperclass()) {
return hasKnownSwiftMetadata(IGM, superclass->getCanonicalType());
}
}
// Class existentials, etc.
return false;
}
/// Is the given class known to have Swift-compatible metadata?
bool irgen::hasKnownSwiftMetadata(IRGenModule &IGM, ClassDecl *theClass) {
// For now, the fact that a declaration was not implemented in Swift
// is enough to conclusively force us into a slower path.
// Eventually we might have an attribute here or something based on
// the deployment target.
return hasKnownSwiftImplementation(IGM, theClass);
}
/// Is the given class known to have an implementation in Swift?
bool irgen::hasKnownSwiftImplementation(IRGenModule &IGM, ClassDecl *theClass) {
return !theClass->hasClangNode();
}
/// Is the given method known to be callable by vtable lookup?
bool irgen::hasKnownVTableEntry(IRGenModule &IGM,
AbstractFunctionDecl *theMethod) {
auto theClass = dyn_cast<ClassDecl>(theMethod->getDeclContext());
// Extension methods don't get vtable entries.
if (!theClass) {
return false;
}
return hasKnownSwiftImplementation(IGM, theClass);
}
/// If we have a non-generic struct or enum whose size does not
/// depend on any opaque resilient types, we can access metadata
/// directly. Otherwise, call an accessor.
///
/// FIXME: Really, we want to use accessors for any nominal type
/// defined in a different module, too.
static bool isTypeMetadataAccessTrivial(IRGenModule &IGM, CanType type) {
if (isa<StructType>(type) || isa<EnumType>(type))
if (IGM.getTypeInfoForLowered(type).isFixedSize())
return true;
return false;
}
/// Return the standard access strategy for getting a non-dependent
/// type metadata object.
MetadataAccessStrategy
irgen::getTypeMetadataAccessStrategy(IRGenModule &IGM, CanType type,
bool preferDirectAccess) {
assert(!type->hasArchetype());
// Non-generic structs, enums, and classes are special cases.
//
// Note that while protocol types don't have a metadata pattern,
// we still require an accessor since we actually want to get
// the metadata for the existential type.
auto nominal = dyn_cast<NominalType>(type);
if (nominal && !isa<ProtocolType>(nominal)) {
assert(!nominal->getDecl()->isGenericContext());
if (preferDirectAccess &&
isTypeMetadataAccessTrivial(IGM, type))
return MetadataAccessStrategy::Direct;
// Everything else requires accessors.
switch (getDeclLinkage(nominal->getDecl())) {
case FormalLinkage::PublicUnique:
return MetadataAccessStrategy::PublicUniqueAccessor;
case FormalLinkage::HiddenUnique:
return MetadataAccessStrategy::HiddenUniqueAccessor;
case FormalLinkage::Private:
return MetadataAccessStrategy::PrivateAccessor;
case FormalLinkage::PublicNonUnique:
case FormalLinkage::HiddenNonUnique:
return MetadataAccessStrategy::NonUniqueAccessor;
}
llvm_unreachable("bad formal linkage");
}
// Builtin types are assumed to be implemented with metadata in the runtime.
if (isa<BuiltinType>(type))
return MetadataAccessStrategy::Direct;
// DynamicSelfType is actually local.
if (type->hasDynamicSelfType())
return MetadataAccessStrategy::Direct;
// The zero-element tuple has special metadata in the runtime.
if (auto tuple = dyn_cast<TupleType>(type))
if (tuple->getNumElements() == 0)
return MetadataAccessStrategy::Direct;
// SIL box types are opaque to the runtime; NativeObject stands in for them.
if (isa<SILBoxType>(type))
return MetadataAccessStrategy::Direct;
// Everything else requires a shared accessor function.
return MetadataAccessStrategy::NonUniqueAccessor;
}
/// Emit a string encoding the labels in the given tuple type.
static llvm::Constant *getTupleLabelsString(IRGenModule &IGM,
CanTupleType type) {
bool hasLabels = false;
llvm::SmallString<128> buffer;
for (auto &elt : type->getElements()) {
if (elt.hasName()) {
hasLabels = true;
buffer.append(elt.getName().str());
}
// Each label is space-terminated.
buffer += ' ';
}
// If there are no labels, use a null pointer.
if (!hasLabels) {
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
}
// Otherwise, create a new string literal.
// This method implicitly adds a null terminator.
return IGM.getAddrOfGlobalString(buffer);
}
namespace {
/// A visitor class for emitting a reference to a metatype object.
/// This implements a "raw" access, useful for implementing cache
/// functions or for implementing dependent accesses.
///
/// If the access requires runtime initialization, that initialization
/// must be dependency-ordered-before any load that carries a dependency
/// from the resulting metadata pointer.
class EmitTypeMetadataRef
: public CanTypeVisitor<EmitTypeMetadataRef, llvm::Value *> {
private:
IRGenFunction &IGF;
public:
EmitTypeMetadataRef(IRGenFunction &IGF) : IGF(IGF) {}
#define TREAT_AS_OPAQUE(KIND) \
llvm::Value *visit##KIND##Type(KIND##Type *type) { \
return visitOpaqueType(CanType(type)); \
}
TREAT_AS_OPAQUE(BuiltinInteger)
TREAT_AS_OPAQUE(BuiltinFloat)
TREAT_AS_OPAQUE(BuiltinVector)
TREAT_AS_OPAQUE(BuiltinRawPointer)
#undef TREAT_AS_OPAQUE
llvm::Value *emitDirectMetadataRef(CanType type) {
return IGF.IGM.getAddrOfTypeMetadata(type,
/*pattern*/ false);
}
/// The given type should use opaque type info. We assume that
/// the runtime always provides an entry for such a type; right
/// now, that mapping is as one of the power-of-two integer types.
llvm::Value *visitOpaqueType(CanType type) {
auto &opaqueTI = cast<FixedTypeInfo>(IGF.IGM.getTypeInfoForLowered(type));
unsigned numBits = opaqueTI.getFixedSize().getValueInBits();
if (!llvm::isPowerOf2_32(numBits))
numBits = llvm::NextPowerOf2(numBits);
auto intTy = BuiltinIntegerType::get(numBits, IGF.IGM.Context);
return emitDirectMetadataRef(CanType(intTy));
}
llvm::Value *visitBuiltinNativeObjectType(CanBuiltinNativeObjectType type) {
return emitDirectMetadataRef(type);
}
llvm::Value *visitBuiltinBridgeObjectType(CanBuiltinBridgeObjectType type) {
return emitDirectMetadataRef(type);
}
llvm::Value *visitBuiltinUnknownObjectType(CanBuiltinUnknownObjectType type) {
return emitDirectMetadataRef(type);
}
llvm::Value *visitBuiltinUnsafeValueBufferType(
CanBuiltinUnsafeValueBufferType type) {
return emitDirectMetadataRef(type);
}
llvm::Value *visitNominalType(CanNominalType type) {
assert(!type->isExistentialType());
return emitNominalMetadataRef(IGF, type->getDecl(), type);
}
llvm::Value *visitBoundGenericType(CanBoundGenericType type) {
assert(!type->isExistentialType());
return emitNominalMetadataRef(IGF, type->getDecl(), type);
}
llvm::Value *visitTupleType(CanTupleType type) {
if (auto cached = tryGetLocal(type))
return cached;
// I think the sanest thing to do here is drop labels, but maybe
// that's not correct. If so, that's really unfortunate in a
// lot of ways.
// Er, varargs bit? Should that go in?
switch (type->getNumElements()) {
case 0: {// Special case the empty tuple, just use the global descriptor.
llvm::Constant *fullMetadata = IGF.IGM.getEmptyTupleMetadata();
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGF.IGM.Int32Ty, 1)
};
return llvm::ConstantExpr::getInBoundsGetElementPtr(
/*Ty=*/nullptr, fullMetadata, indices);
}
case 1:
// For metadata purposes, we consider a singleton tuple to be
// isomorphic to its element type.
return IGF.emitTypeMetadataRef(type.getElementType(0));
case 2: {
// Find the metadata pointer for this element.
auto elt0Metadata = IGF.emitTypeMetadataRef(type.getElementType(0));
auto elt1Metadata = IGF.emitTypeMetadataRef(type.getElementType(1));
llvm::Value *args[] = {
elt0Metadata, elt1Metadata,
getTupleLabelsString(IGF.IGM, type),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadata2Fn(),
args);
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(CanType(type), call);
}
case 3: {
// Find the metadata pointer for this element.
auto elt0Metadata = IGF.emitTypeMetadataRef(type.getElementType(0));
auto elt1Metadata = IGF.emitTypeMetadataRef(type.getElementType(1));
auto elt2Metadata = IGF.emitTypeMetadataRef(type.getElementType(2));
llvm::Value *args[] = {
elt0Metadata, elt1Metadata, elt2Metadata,
getTupleLabelsString(IGF.IGM, type),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadata3Fn(),
args);
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(CanType(type), call);
}
default:
// TODO: use a caching entrypoint (with all information
// out-of-line) for non-dependent tuples.
llvm::Value *pointerToFirst = nullptr; // appease -Wuninitialized
auto elements = type.getElementTypes();
auto arrayTy = llvm::ArrayType::get(IGF.IGM.TypeMetadataPtrTy,
elements.size());
Address buffer = IGF.createAlloca(arrayTy,IGF.IGM.getPointerAlignment(),
"tuple-elements");
for (unsigned i = 0, e = elements.size(); i != e; ++i) {
// Find the metadata pointer for this element.
llvm::Value *eltMetadata = IGF.emitTypeMetadataRef(elements[i]);
// GEP to the appropriate element and store.
Address eltPtr = IGF.Builder.CreateStructGEP(buffer, i,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(eltMetadata, eltPtr);
// Remember the GEP to the first element.
if (i == 0) pointerToFirst = eltPtr.getAddress();
}
llvm::Value *args[] = {
llvm::ConstantInt::get(IGF.IGM.SizeTy, elements.size()),
pointerToFirst,
getTupleLabelsString(IGF.IGM, type),
llvm::ConstantPointerNull::get(IGF.IGM.WitnessTablePtrTy) // proposed
};
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetTupleMetadataFn(),
args);
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(type, call);
}
}
llvm::Value *visitPolymorphicFunctionType(CanPolymorphicFunctionType type) {
IGF.unimplemented(SourceLoc(),
"metadata ref for polymorphic function type");
return llvm::UndefValue::get(IGF.IGM.TypeMetadataPtrTy);
}
llvm::Value *visitGenericFunctionType(CanGenericFunctionType type) {
IGF.unimplemented(SourceLoc(),
"metadata ref for generic function type");
return llvm::UndefValue::get(IGF.IGM.TypeMetadataPtrTy);
}
llvm::Value *extractAndMarkResultType(CanFunctionType type) {
// If the function type throws, set the lower bit of the return type
// address, so that we can carry this information over to the function
// type metadata.
auto metadata = IGF.emitTypeMetadataRef(type->getResult()->
getCanonicalType());
return metadata;
}
llvm::Value *extractAndMarkInOut(CanType type) {
// If the type is inout, get the metadata for its inner object type
// instead, and then set the lowest bit to help the runtime unique
// the metadata type for this function.
if (auto inoutType = dyn_cast<InOutType>(type)) {
auto metadata = IGF.emitTypeMetadataRef(inoutType.getObjectType());
auto metadataInt = IGF.Builder.CreatePtrToInt(metadata, IGF.IGM.SizeTy);
auto inoutFlag = llvm::ConstantInt::get(IGF.IGM.SizeTy, 1);
auto marked = IGF.Builder.CreateOr(metadataInt, inoutFlag);
return IGF.Builder.CreateIntToPtr(marked, IGF.IGM.Int8PtrTy);
}
auto metadata = IGF.emitTypeMetadataRef(type);
return IGF.Builder.CreateBitCast(metadata, IGF.IGM.Int8PtrTy);
}
llvm::Value *visitFunctionType(CanFunctionType type) {
if (auto metatype = tryGetLocal(type))
return metatype;
auto resultMetadata = extractAndMarkResultType(type);
CanTupleType inputTuple = dyn_cast<TupleType>(type.getInput());
size_t numArguments = 1;
if (inputTuple && !inputTuple->isMaterializable())
numArguments = inputTuple->getNumElements();
// Map the convention to a runtime metadata value.
FunctionMetadataConvention metadataConvention;
switch (type->getRepresentation()) {
case FunctionTypeRepresentation::Swift:
metadataConvention = FunctionMetadataConvention::Swift;
break;
case FunctionTypeRepresentation::Thin:
metadataConvention = FunctionMetadataConvention::Thin;
break;
case FunctionTypeRepresentation::Block:
metadataConvention = FunctionMetadataConvention::Block;
break;
case FunctionTypeRepresentation::CFunctionPointer:
metadataConvention = FunctionMetadataConvention::CFunctionPointer;
break;
}
auto flagsVal = FunctionTypeFlags()
.withNumArguments(numArguments)
.withConvention(metadataConvention)
.withThrows(type->throws());
auto flags = llvm::ConstantInt::get(IGF.IGM.SizeTy,
flagsVal.getIntValue());
switch (numArguments) {
case 1: {
auto arg0 = (inputTuple && !inputTuple->isMaterializable()) ?
extractAndMarkInOut(inputTuple.getElementType(0))
: extractAndMarkInOut(type.getInput());
auto call = IGF.Builder.CreateCall(
IGF.IGM.getGetFunctionMetadata1Fn(),
{flags, arg0, resultMetadata});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(CanType(type), call);
}
case 2: {
auto arg0 = extractAndMarkInOut(inputTuple.getElementType(0));
auto arg1 = extractAndMarkInOut(inputTuple.getElementType(1));
auto call = IGF.Builder.CreateCall(
IGF.IGM.getGetFunctionMetadata2Fn(),
{flags, arg0, arg1, resultMetadata});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(CanType(type), call);
}
case 3: {
auto arg0 = extractAndMarkInOut(inputTuple.getElementType(0));
auto arg1 = extractAndMarkInOut(inputTuple.getElementType(1));
auto arg2 = extractAndMarkInOut(inputTuple.getElementType(2));
auto call = IGF.Builder.CreateCall(
IGF.IGM.getGetFunctionMetadata3Fn(),
{flags, arg0, arg1, arg2,
resultMetadata});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(CanType(type), call);
}
default:
auto arguments = inputTuple.getElementTypes();
auto arrayTy = llvm::ArrayType::get(IGF.IGM.Int8PtrTy,
arguments.size() + 2);
Address buffer = IGF.createAlloca(arrayTy,
IGF.IGM.getPointerAlignment(),
"function-arguments");
Address pointerToFirstArg = IGF.Builder.CreateStructGEP(buffer, 0,
Size(0));
Address flagsPtr = IGF.Builder.CreateBitCast(pointerToFirstArg,
IGF.IGM.SizeTy->getPointerTo());
IGF.Builder.CreateStore(flags, flagsPtr);
for (size_t i = 0; i < arguments.size(); ++i) {
auto argMetadata = extractAndMarkInOut(
inputTuple.getElementType(i));
Address argPtr = IGF.Builder.CreateStructGEP(buffer, i + 1,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(argMetadata, argPtr);
}
Address resultPtr = IGF.Builder.CreateStructGEP(buffer,
arguments.size() + 1,
IGF.IGM.getPointerSize());
resultPtr = IGF.Builder.CreateBitCast(resultPtr,
IGF.IGM.TypeMetadataPtrTy->getPointerTo());
IGF.Builder.CreateStore(resultMetadata, resultPtr);
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetFunctionMetadataFn(),
pointerToFirstArg.getAddress());
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(type, call);
}
}
llvm::Value *visitAnyMetatypeType(CanAnyMetatypeType type) {
// FIXME: We shouldn't accept a lowered metatype here, but we need to
// represent Optional<@objc_metatype T.Type> as an AST type for ABI
// reasons.
// assert(!type->hasRepresentation()
// && "should not be asking for a representation-specific metatype "
// "metadata");
if (auto metatype = tryGetLocal(type))
return metatype;
auto instMetadata = IGF.emitTypeMetadataRef(type.getInstanceType());
auto fn = isa<MetatypeType>(type)
? IGF.IGM.getGetMetatypeMetadataFn()
: IGF.IGM.getGetExistentialMetatypeMetadataFn();
auto call = IGF.Builder.CreateCall(fn, instMetadata);
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(type, call);
}
llvm::Value *visitModuleType(CanModuleType type) {
IGF.unimplemented(SourceLoc(), "metadata ref for module type");
return llvm::UndefValue::get(IGF.IGM.TypeMetadataPtrTy);
}
llvm::Value *visitDynamicSelfType(CanDynamicSelfType type) {
return IGF.getLocalSelfMetadata();
}
llvm::Value *emitExistentialTypeMetadata(CanType type) {
SmallVector<ProtocolDecl*, 2> protocols;
type.getAnyExistentialTypeProtocols(protocols);
// Collect references to the protocol descriptors.
auto descriptorArrayTy
= llvm::ArrayType::get(IGF.IGM.ProtocolDescriptorPtrTy,
protocols.size());
Address descriptorArray = IGF.createAlloca(descriptorArrayTy,
IGF.IGM.getPointerAlignment(),
"protocols");
descriptorArray = IGF.Builder.CreateBitCast(descriptorArray,
IGF.IGM.ProtocolDescriptorPtrTy->getPointerTo());
unsigned index = 0;
for (auto *p : protocols) {
llvm::Value *ref = emitProtocolDescriptorRef(IGF, p);
Address slot = IGF.Builder.CreateConstArrayGEP(descriptorArray,
index, IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(ref, slot);
++index;
}
auto call = IGF.Builder.CreateCall(IGF.IGM.getGetExistentialMetadataFn(),
{IGF.IGM.getSize(Size(protocols.size())),
descriptorArray.getAddress()});
call->setDoesNotThrow();
call->setCallingConv(IGF.IGM.RuntimeCC);
return setLocal(type, call);
}
llvm::Value *visitProtocolType(CanProtocolType type) {
return emitExistentialTypeMetadata(type);
}
llvm::Value *visitProtocolCompositionType(CanProtocolCompositionType type) {
return emitExistentialTypeMetadata(type);
}
llvm::Value *visitReferenceStorageType(CanReferenceStorageType type) {
llvm_unreachable("reference storage type should have been converted by "
"SILGen");
}
llvm::Value *visitSILFunctionType(CanSILFunctionType type) {
llvm_unreachable("should not be asking for metadata of a lowered SIL "
"function type--SILGen should have used the AST type");
}
llvm::Value *visitArchetypeType(CanArchetypeType type) {
return IGF.getLocalTypeData(type, LocalTypeData::forMetatype());
}
llvm::Value *visitGenericTypeParamType(CanGenericTypeParamType type) {
llvm_unreachable("dependent type should have been substituted by Sema or SILGen");
}
llvm::Value *visitDependentMemberType(CanDependentMemberType type) {
llvm_unreachable("dependent type should have been substituted by Sema or SILGen");
}
llvm::Value *visitLValueType(CanLValueType type) {
llvm_unreachable("lvalue type should have been lowered by SILGen");
}
llvm::Value *visitInOutType(CanInOutType type) {
llvm_unreachable("inout type should have been lowered by SILGen");
}
llvm::Value *visitSILBlockStorageType(CanSILBlockStorageType type) {
llvm_unreachable("cannot ask for metadata of block storage");
}
llvm::Value *visitSILBoxType(CanSILBoxType type) {
// The Builtin.NativeObject metadata can stand in for boxes.
return emitDirectMetadataRef(type->getASTContext().TheNativeObjectType);
}
/// Try to find the metatype in local data.
llvm::Value *tryGetLocal(CanType type) {
return IGF.tryGetLocalTypeData(type, LocalTypeData::forMetatype());
}
/// Set the metatype in local data.
llvm::Value *setLocal(CanType type, llvm::Instruction *metatype) {
IGF.setScopedLocalTypeData(type, LocalTypeData::forMetatype(),
metatype);
return metatype;
}
};
}
/// Emit a type metadata reference without using an accessor function.
static llvm::Value *emitDirectTypeMetadataRef(IRGenFunction &IGF,
CanType type) {
return EmitTypeMetadataRef(IGF).visit(type);
}
static Address emitAddressOfSuperclassRefInClassMetadata(IRGenFunction &IGF,
llvm::Value *metadata) {
// The superclass field in a class type is the first field past the isa.
unsigned index = 1;
Address addr(metadata, IGF.IGM.getPointerAlignment());
addr = IGF.Builder.CreateBitCast(addr,
IGF.IGM.TypeMetadataPtrTy->getPointerTo());
return IGF.Builder.CreateConstArrayGEP(addr, index, IGF.IGM.getPointerSize());
}
static void emitInitializeSuperclassOfMetaclass(IRGenFunction &IGF,
llvm::Value *metaclass,
llvm::Value *superMetadata) {
assert(IGF.IGM.ObjCInterop && "metaclasses only matter for ObjC interop");
// The superclass of the metaclass is the metaclass of the superclass.
// Read the superclass's metaclass.
llvm::Value *superMetaClass =
emitLoadOfObjCHeapMetadataRef(IGF, superMetadata);
superMetaClass = IGF.Builder.CreateBitCast(superMetaClass,
IGF.IGM.TypeMetadataPtrTy);
// Write to the new metaclass's superclass field.
Address metaSuperField
= emitAddressOfSuperclassRefInClassMetadata(IGF, metaclass);
IGF.Builder.CreateStore(superMetaClass, metaSuperField);
}