-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenExistential.cpp
2905 lines (2550 loc) · 122 KB
/
GenExistential.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
//===--- GenExistential.cpp - Swift IR Generation for Existential Types ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for existential types in Swift.
//
//===----------------------------------------------------------------------===//
#include "GenExistential.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/IRGen/Linking.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/raw_ostream.h"
#include "BitPatternBuilder.h"
#include "EnumPayload.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenClass.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenOpaque.h"
#include "GenPoly.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IndirectTypeInfo.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "MetadataRequest.h"
#include "NonFixedTypeInfo.h"
#include "Outlining.h"
#include "ProtocolInfo.h"
#include "TypeInfo.h"
using namespace swift;
using namespace irgen;
namespace {
/// The layout of an existential buffer. This is intended to be a
/// small, easily-computed type that can be passed around by value.
class OpaqueExistentialLayout {
private:
unsigned NumTables;
// If you add anything to the layout computation, you might need
// to update certain uses; check the external uses of getNumTables().
public:
explicit OpaqueExistentialLayout(unsigned numTables)
: NumTables(numTables) {}
unsigned getNumTables() const { return NumTables; }
Size getSize(IRGenModule &IGM) const {
return getFixedBufferSize(IGM)
+ IGM.getPointerSize() * (getNumTables() + 1);
}
Alignment getAlignment(IRGenModule &IGM) const {
return getFixedBufferAlignment(IGM);
}
// friend bool operator==(ExistentialLayout a, ExistentialLayout b) {
// return a.NumTables == b.NumTables;
// }
/// Given the address of an existential object, drill down to the
/// buffer.
Address projectExistentialBuffer(IRGenFunction &IGF, Address addr) const {
return IGF.Builder.CreateStructGEP(addr, 0, Size(0));
}
/// Given the address of an existential object, drill down to the
/// witness-table field.
Address projectWitnessTable(IRGenFunction &IGF, Address addr,
unsigned which) const {
assert(which < getNumTables());
return IGF.Builder.CreateStructGEP(addr, which + 2,
getFixedBufferSize(IGF.IGM)
+ IGF.IGM.getPointerSize() * (which + 1));
}
/// Given the address of an existential object, load its witness table.
llvm::Value *loadWitnessTable(IRGenFunction &IGF, Address addr,
unsigned which) const {
return IGF.Builder.CreateLoad(projectWitnessTable(IGF, addr, which));
}
/// Given the address of an existential object, drill down to the
/// metadata field.
Address projectMetadataRef(IRGenFunction &IGF, Address addr) {
return IGF.Builder.CreateStructGEP(addr, 1, getFixedBufferSize(IGF.IGM));
}
/// Give the offset of the metadata field of an existential object.
Size getMetadataRefOffset(IRGenModule &IGM) {
return getFixedBufferSize(IGM);
}
/// Given the address of an existential object, load its metadata
/// object.
llvm::Value *loadMetadataRef(IRGenFunction &IGF, Address addr) {
return IGF.Builder.CreateLoad(projectMetadataRef(IGF, addr));
}
};
/// A helper class for implementing existential type infos that
/// store an existential value of some sort.
template <class Derived, class Base>
class ExistentialTypeInfoBase : public Base,
private llvm::TrailingObjects<Derived, const ProtocolDecl *> {
friend class llvm::TrailingObjects<Derived, const ProtocolDecl *>;
/// The number of non-trivial protocols for this existential.
unsigned NumStoredProtocols;
protected:
const Derived &asDerived() const {
return *static_cast<const Derived*>(this);
}
Derived &asDerived() {
return *static_cast<Derived*>(this);
}
template <class... As>
ExistentialTypeInfoBase(ArrayRef<const ProtocolDecl *> protocols,
As &&...args)
: Base(std::forward<As>(args)...),
NumStoredProtocols(protocols.size()) {
std::uninitialized_copy(protocols.begin(), protocols.end(),
this->template getTrailingObjects<const ProtocolDecl *>());
}
public:
template <class... As>
static const Derived *
create(ArrayRef<const ProtocolDecl *> protocols, As &&...args)
{
void *buffer = operator new(
llvm::TrailingObjects<Derived, const ProtocolDecl *>::
template totalSizeToAlloc<const ProtocolDecl *>(
protocols.size()));
return new (buffer) Derived(protocols, std::forward<As>(args)...);
}
/// Returns the number of protocol witness tables directly carried
/// by values of this type.
unsigned getNumStoredProtocols() const { return NumStoredProtocols; }
/// Returns the protocols that values of this type are known to
/// implement. This can be empty, meaning that values of this
/// type are not know to implement any protocols, although we do
/// still know how to manipulate them.
ArrayRef<const ProtocolDecl *> getStoredProtocols() const {
return {this->template getTrailingObjects<const ProtocolDecl *>(),
NumStoredProtocols};
}
/// Given the address of an existential object, find the witness
/// table of a directly-stored witness table.
llvm::Value *loadWitnessTable(IRGenFunction &IGF, Address obj,
unsigned which) const {
return IGF.Builder.CreateLoad(
asDerived().projectWitnessTable(IGF, obj, which));
}
void emitCopyOfTables(IRGenFunction &IGF, Address dest, Address src) const {
if (NumStoredProtocols == 0) return;
Explosion temp;
asDerived().emitLoadOfTables(IGF, src, temp);
asDerived().emitStoreOfTables(IGF, temp, dest);
}
void emitLoadOfTables(IRGenFunction &IGF, Address existential,
Explosion &out) const {
for (unsigned i = 0; i != NumStoredProtocols; ++i) {
auto tableAddr = asDerived().projectWitnessTable(IGF, existential, i);
out.add(IGF.Builder.CreateLoad(tableAddr));
}
}
void emitStoreOfTables(IRGenFunction &IGF, Explosion &in,
Address existential) const {
for (unsigned i = 0; i != NumStoredProtocols; ++i) {
auto tableAddr = asDerived().projectWitnessTable(IGF, existential, i);
IGF.Builder.CreateStore(in.claimNext(), tableAddr);
}
}
};
/// A type implementation for address-only reference storage of
/// class existential types.
template <class Impl, class Base>
class AddressOnlyClassExistentialTypeInfoBase :
public ExistentialTypeInfoBase<Impl, IndirectTypeInfo<Impl, Base>> {
using super = ExistentialTypeInfoBase<Impl, IndirectTypeInfo<Impl, Base>>;
using super::asDerived;
using super::emitCopyOfTables;
protected:
using super::getNumStoredProtocols;
const ReferenceCounting Refcounting;
template <class... As>
AddressOnlyClassExistentialTypeInfoBase(
ArrayRef<const ProtocolDecl *> protocols,
ReferenceCounting refcounting,
As &&...args)
: super(protocols, std::forward<As>(args)...),
Refcounting(refcounting) {
}
public:
Address projectWitnessTable(IRGenFunction &IGF, Address container,
unsigned index) const {
assert(index < getNumStoredProtocols());
return IGF.Builder.CreateStructGEP(container, index + 1,
(index + 1) * IGF.IGM.getPointerSize());
}
Address projectValue(IRGenFunction &IGF, Address existential) const {
return IGF.Builder.CreateStructGEP(existential, 0, Size(0),
existential.getAddress()->getName() +
asDerived().getStructNameSuffix());
}
void assignWithCopy(IRGenFunction &IGF, Address dest, Address src, SILType T,
bool isOutlined) const override {
if (isOutlined || T.hasLocalArchetype()) {
Address destValue = projectValue(IGF, dest);
Address srcValue = projectValue(IGF, src);
asDerived().emitValueAssignWithCopy(IGF, destValue, srcValue);
emitCopyOfTables(IGF, dest, src);
} else {
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsNotInitialization, IsNotTake);
}
}
void initializeWithCopy(IRGenFunction &IGF, Address dest, Address src,
SILType T, bool isOutlined) const override {
if (isOutlined || T.hasLocalArchetype()) {
Address destValue = projectValue(IGF, dest);
Address srcValue = projectValue(IGF, src);
asDerived().emitValueInitializeWithCopy(IGF, destValue, srcValue);
emitCopyOfTables(IGF, dest, src);
} else {
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsInitialization, IsNotTake);
}
}
void assignWithTake(IRGenFunction &IGF, Address dest, Address src, SILType T,
bool isOutlined) const override {
if (isOutlined || T.hasLocalArchetype()) {
Address destValue = projectValue(IGF, dest);
Address srcValue = projectValue(IGF, src);
asDerived().emitValueAssignWithTake(IGF, destValue, srcValue);
emitCopyOfTables(IGF, dest, src);
} else {
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsNotInitialization, IsTake);
}
}
void initializeWithTake(IRGenFunction &IGF, Address dest, Address src,
SILType T, bool isOutlined,
bool zeroizeIfSensitive) const override {
if (isOutlined || T.hasLocalArchetype()) {
Address destValue = projectValue(IGF, dest);
Address srcValue = projectValue(IGF, src);
asDerived().emitValueInitializeWithTake(IGF, destValue, srcValue);
emitCopyOfTables(IGF, dest, src);
} else {
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsInitialization, IsTake);
}
}
void destroy(IRGenFunction &IGF, Address existential, SILType T,
bool isOutlined) const override {
if (isOutlined || T.hasLocalArchetype()) {
Address valueAddr = projectValue(IGF, existential);
asDerived().emitValueDestroy(IGF, valueAddr);
} else {
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNeeded);
collector.emitCallToOutlinedDestroy(existential, T, *this);
}
}
};
/// A helper class for working with existential types that can be
/// exploded into scalars.
///
/// The subclass must provide:
/// void emitValueRetain(IRGenFunction &IGF, llvm::Value *value) const;
/// void emitValueRelease(IRGenFunction &IGF, llvm::Value *value) const;
/// void emitValueFixLifetime(IRGenFunction &IGF,
/// llvm::Value *value) const;
/// const LoadableTypeInfo &
/// getValueTypeInfoForExtraInhabitants(IRGenModule &IGM) const;
/// The value type info is only used to manage extra inhabitants, so it's
/// okay for it to implement different semantics.
template <class Derived, class Base>
class ScalarExistentialTypeInfoBase :
public ExistentialTypeInfoBase<Derived, ScalarTypeInfo<Derived, Base>> {
using super =
ExistentialTypeInfoBase<Derived, ScalarTypeInfo<Derived, Base>>;
protected:
template <class... T>
ScalarExistentialTypeInfoBase(T &&...args)
: super(std::forward<T>(args)...) {}
using super::asDerived;
public:
/// The storage type of a class existential is a struct containing
/// a refcounted pointer to the class instance value followed by
/// witness table pointers for each conformed-to protocol. Unlike opaque
/// existentials, a class existential does not need to store type
/// metadata as an additional element, since it can be derived from the
/// class instance.
llvm::StructType *getStorageType() const {
return cast<llvm::StructType>(TypeInfo::getStorageType());
}
using super::getNumStoredProtocols;
unsigned getExplosionSize() const final {
return 1 + getNumStoredProtocols();
}
void getSchema(ExplosionSchema &schema) const override {
schema.add(ExplosionSchema::Element::forScalar(asDerived().getValueType()));
llvm::StructType *ty = getStorageType();
for (unsigned i = 1, e = getExplosionSize(); i != e; ++i)
schema.add(ExplosionSchema::Element::forScalar(ty->getElementType(i)));
}
void addToAggLowering(IRGenModule &IGM, SwiftAggLowering &lowering,
Size offset) const override {
auto ptrSize = IGM.getPointerSize();
LoadableTypeInfo::addScalarToAggLowering(IGM, lowering,
asDerived().getValueType(),
offset, ptrSize);
llvm::StructType *ty = getStorageType();
for (unsigned i = 1, e = getExplosionSize(); i != e; ++i)
LoadableTypeInfo::addScalarToAggLowering(IGM, lowering,
ty->getElementType(i),
offset + i * ptrSize, ptrSize);
}
/// Given the address of a class existential container, returns
/// the address of a witness table pointer.
Address projectWitnessTable(IRGenFunction &IGF, Address address,
unsigned n) const {
assert(n < getNumStoredProtocols() && "witness table index out of bounds");
return IGF.Builder.CreateStructGEP(address, n+1,
IGF.IGM.getPointerSize() * (n+1));
}
/// Return the type of the instance value.
llvm::Type *getValueType() const {
return getStorageType()->getElementType(0);
}
/// Given the address of a class existential container, returns
/// the address of its instance pointer.
Address projectValue(IRGenFunction &IGF, Address address) const {
return IGF.Builder.CreateStructGEP(address, 0, Size(0));
}
llvm::Value *loadValue(IRGenFunction &IGF, Address addr) const {
return IGF.Builder.CreateLoad(asDerived().projectValue(IGF, addr));
}
/// Given a class existential container, returns a witness table
/// pointer out of the container, and the type metadata pointer for the
/// value.
llvm::Value *
extractWitnessTable(IRGenFunction &IGF, Explosion &container,
unsigned which) const {
assert(which < getNumStoredProtocols() && "witness table index out of bounds");
ArrayRef<llvm::Value *> values = container.claim(getExplosionSize());
return values[which+1];
}
/// Deconstruct an existential object into witness tables and instance
/// pointer.
std::pair<ArrayRef<llvm::Value*>, llvm::Value*>
getWitnessTablesAndValue(Explosion &container) const {
llvm::Value *instance = container.claimNext();
ArrayRef<llvm::Value*> witnesses = container.claim(getNumStoredProtocols());
return {witnesses, instance};
}
/// Given an existential object, returns the payload value.
llvm::Value *getValue(IRGenFunction &IGF, Explosion &container) const {
llvm::Value *instance = container.claimNext();
(void)container.claim(getNumStoredProtocols());
return instance;
}
void loadAsCopy(IRGenFunction &IGF, Address address,
Explosion &out) const override {
// Load the instance pointer, which is unknown-refcounted.
llvm::Value *instance = asDerived().loadValue(IGF, address);
asDerived().emitValueRetain(IGF, instance, IGF.getDefaultAtomicity());
out.add(instance);
// Load the witness table pointers.
asDerived().emitLoadOfTables(IGF, address, out);
}
void loadAsTake(IRGenFunction &IGF, Address address,
Explosion &e) const override {
// Load the instance pointer.
e.add(asDerived().loadValue(IGF, address));
// Load the witness table pointers.
asDerived().emitLoadOfTables(IGF, address, e);
}
void assign(IRGenFunction &IGF, Explosion &e, Address address,
bool isOutlined, SILType T) const override {
// Assign the value.
Address instanceAddr = asDerived().projectValue(IGF, address);
llvm::Value *old = IGF.Builder.CreateLoad(instanceAddr);
IGF.Builder.CreateStore(e.claimNext(), instanceAddr);
asDerived().emitValueRelease(IGF, old, IGF.getDefaultAtomicity());
// Store the witness table pointers.
asDerived().emitStoreOfTables(IGF, e, address);
}
void initialize(IRGenFunction &IGF, Explosion &e, Address address,
bool isOutlined) const override {
// Store the instance pointer.
IGF.Builder.CreateStore(e.claimNext(),
asDerived().projectValue(IGF, address));
// Store the witness table pointers.
asDerived().emitStoreOfTables(IGF, e, address);
}
void copy(IRGenFunction &IGF, Explosion &src, Explosion &dest,
Atomicity atomicity)
const override {
// Copy the instance pointer.
llvm::Value *value = src.claimNext();
dest.add(value);
asDerived().emitValueRetain(IGF, value, atomicity);
// Transfer the witness table pointers.
src.transferInto(dest, getNumStoredProtocols());
}
void consume(IRGenFunction &IGF, Explosion &src, Atomicity atomicity,
SILType T)
const override {
// Copy the instance pointer.
llvm::Value *value = src.claimNext();
asDerived().emitValueRelease(IGF, value, atomicity);
// Throw out the witness table pointers.
(void)src.claim(getNumStoredProtocols());
}
void fixLifetime(IRGenFunction &IGF, Explosion &src) const override {
// Copy the instance pointer.
llvm::Value *value = src.claimNext();
asDerived().emitValueFixLifetime(IGF, value);
// Throw out the witness table pointers.
(void)src.claim(getNumStoredProtocols());
}
void destroy(IRGenFunction &IGF, Address addr, SILType T,
bool isOutlined) const override {
// Small type (scalar) do not create outlined function
llvm::Value *value = asDerived().loadValue(IGF, addr);
asDerived().emitValueRelease(IGF, value, IGF.getDefaultAtomicity());
}
void packIntoEnumPayload(IRGenModule &IGM,
IRBuilder &builder,
EnumPayload &payload,
Explosion &src,
unsigned offset) const override {
payload.insertValue(IGM, builder, src.claimNext(), offset);
auto wordSize = IGM.getPointerSize().getValueInBits();
for (unsigned i = 0; i < getNumStoredProtocols(); ++i) {
offset += wordSize;
payload.insertValue(IGM, builder, src.claimNext(), offset);
}
}
void unpackFromEnumPayload(IRGenFunction &IGF,
const EnumPayload &payload,
Explosion &dest,
unsigned offset) const override {
ExplosionSchema schema;
getSchema(schema);
dest.add(payload.extractValue(IGF, schema[0].getScalarType(), offset));
auto wordSize = IGF.IGM.getPointerSize().getValueInBits();
for (unsigned i = 0; i < getNumStoredProtocols(); ++i) {
offset += wordSize;
dest.add(payload.extractValue(IGF, IGF.IGM.WitnessTablePtrTy, offset));
}
}
// Extra inhabitants of the various scalar existential containers.
// We use the heap object extra inhabitants over the class pointer value.
// We could get even more extra inhabitants from the witness table
// pointer(s), but it's unlikely we would ever need to.
bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
assert(asDerived().getValueTypeInfoForExtraInhabitants(IGM)
.mayHaveExtraInhabitants(IGM));
return true;
}
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return asDerived().getValueTypeInfoForExtraInhabitants(IGM)
.getFixedExtraInhabitantCount(IGM);
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const override {
// Note that we pass down the original bit-width.
return asDerived().getValueTypeInfoForExtraInhabitants(IGM)
.getFixedExtraInhabitantValue(IGM, bits, index);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src,
SILType T, bool isOutlined)
const override {
// NB: We assume that the witness table slots are zero if an extra
// inhabitant is stored in the container.
src = projectValue(IGF, src);
return asDerived().getValueTypeInfoForExtraInhabitants(IGF.IGM)
.getExtraInhabitantIndex(IGF, src, SILType(), isOutlined);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T, bool isOutlined)
const override {
Address valueDest = projectValue(IGF, dest);
asDerived().getValueTypeInfoForExtraInhabitants(IGF.IGM)
.storeExtraInhabitant(IGF, index, valueDest, SILType(), isOutlined);
}
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override {
// Ask the value type for its mask.
APInt bits = asDerived().getValueTypeInfoForExtraInhabitants(IGM)
.getFixedExtraInhabitantMask(IGM);
// Zext out to the size of the existential.
auto totalSize = asDerived().getFixedSize().getValueInBits();
auto mask = BitPatternBuilder(IGM.Triple.isLittleEndian());
mask.append(bits);
mask.padWithClearBitsTo(totalSize);
return mask.build().value();
}
};
/// A type implementation for existential types.
#define REF_STORAGE_HELPER(Name, Super) \
private: \
bool shouldStoreExtraInhabitantsInRef(IRGenModule &IGM) const { \
if (IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, Refcounting) > 1) \
return true; \
return getNumStoredProtocols() == 0; \
} \
public: \
bool mayHaveExtraInhabitants(IRGenModule &IGM) const override { \
return getFixedExtraInhabitantCount(IGM) > 0; \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
if (shouldStoreExtraInhabitantsInRef(IGM)) { \
return IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, Refcounting) - IsOptional; \
} else { \
return Super::getFixedExtraInhabitantCount(IGM); \
} \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
if (shouldStoreExtraInhabitantsInRef(IGM)) { \
return IGM.getReferenceStorageExtraInhabitantValue(bits, \
index + IsOptional, \
ReferenceOwnership::Name, \
Refcounting); \
} else { \
return Super::getFixedExtraInhabitantValue(IGM, bits, index); \
} \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
Address valueSrc = projectValue(IGF, src); \
if (shouldStoreExtraInhabitantsInRef(IGF.IGM)) { \
return IGF.getReferenceStorageExtraInhabitantIndex(valueSrc, \
ReferenceOwnership::Name, Refcounting); \
} else { \
return Super::getExtraInhabitantIndex(IGF, src, T, isOutlined); \
} \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
Address valueDest = projectValue(IGF, dest); \
if (shouldStoreExtraInhabitantsInRef(IGF.IGM)) { \
return IGF.storeReferenceStorageExtraInhabitant(index, valueDest, \
ReferenceOwnership::Name, Refcounting); \
} else { \
return Super::storeExtraInhabitant(IGF, index, dest, T, isOutlined); \
} \
} \
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { \
if (shouldStoreExtraInhabitantsInRef(IGM)) { \
APInt bits = IGM.getReferenceStorageExtraInhabitantMask( \
ReferenceOwnership::Name, \
Refcounting); \
/* Zext out to the size of the existential. */ \
auto mask = BitPatternBuilder(IGM.Triple.isLittleEndian()); \
mask.append(bits); \
mask.padWithClearBitsTo(getFixedSize().getValueInBits()); \
return mask.build().value(); \
} else { \
return Super::getFixedExtraInhabitantMask(IGM); \
} \
}
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \
class AddressOnly##Name##ClassExistentialTypeInfo final : \
public AddressOnlyClassExistentialTypeInfoBase< \
AddressOnly##Name##ClassExistentialTypeInfo, \
FixedTypeInfo> { \
bool IsOptional; \
public: \
AddressOnly##Name##ClassExistentialTypeInfo( \
ArrayRef<const ProtocolDecl *> protocols, \
llvm::Type *ty, \
SpareBitVector &&spareBits, \
Size size, Alignment align, \
ReferenceCounting refcounting, \
bool isOptional) \
: AddressOnlyClassExistentialTypeInfoBase(protocols, refcounting, \
ty, size, std::move(spareBits), \
align, IsNotTriviallyDestroyable, \
IsNotBitwiseTakable, \
IsCopyable, \
IsFixedSize, \
IsABIAccessible), \
IsOptional(isOptional) {} \
TypeLayoutEntry \
*buildTypeLayoutEntry(IRGenModule &IGM, \
SILType T, \
bool useStructLayouts) const override { \
if (!useStructLayouts) { \
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T); \
} else if (Refcounting == ReferenceCounting::Native) { \
return IGM.typeLayoutCache.getOrCreateScalarEntry( \
*this, T, ScalarKind::Native##Name##Reference); \
} else { \
return IGM.typeLayoutCache.getOrCreateScalarEntry( \
*this, T, ScalarKind::Unknown##Name##Reference); \
} \
} \
void emitValueAssignWithCopy(IRGenFunction &IGF, \
Address dest, Address src) const { \
IGF.emit##Name##CopyAssign(dest, src, Refcounting); \
} \
void emitValueInitializeWithCopy(IRGenFunction &IGF, \
Address dest, Address src) const { \
IGF.emit##Name##CopyInit(dest, src, Refcounting); \
} \
void emitValueAssignWithTake(IRGenFunction &IGF, \
Address dest, Address src) const { \
IGF.emit##Name##TakeAssign(dest, src, Refcounting); \
} \
void emitValueInitializeWithTake(IRGenFunction &IGF, \
Address dest, Address src) const { \
IGF.emit##Name##TakeInit(dest, src, Refcounting); \
} \
void emitValueDestroy(IRGenFunction &IGF, Address addr) const { \
IGF.emit##Name##Destroy(addr, Refcounting); \
} \
StringRef getStructNameSuffix() const { return "." #name "ref"; } \
REF_STORAGE_HELPER(Name, FixedTypeInfo) \
};
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
class Loadable##Name##ClassExistentialTypeInfo final \
: public ScalarExistentialTypeInfoBase< \
Loadable##Name##ClassExistentialTypeInfo, \
LoadableTypeInfo> { \
ReferenceCounting Refcounting; \
llvm::Type *ValueType; \
bool IsOptional; \
public: \
Loadable##Name##ClassExistentialTypeInfo( \
ArrayRef<const ProtocolDecl *> storedProtocols, \
llvm::Type *valueTy, llvm::Type *ty, \
const SpareBitVector &spareBits, \
Size size, Alignment align, \
ReferenceCounting refcounting, \
bool isOptional) \
: ScalarExistentialTypeInfoBase(storedProtocols, ty, size, \
spareBits, align, \
IsNotTriviallyDestroyable, \
IsCopyable, \
IsFixedSize, IsABIAccessible), \
Refcounting(refcounting), ValueType(valueTy), IsOptional(isOptional) { \
assert(refcounting == ReferenceCounting::Native || \
refcounting == ReferenceCounting::Unknown); \
} \
TypeLayoutEntry \
*buildTypeLayoutEntry(IRGenModule &IGM, \
SILType T, \
bool useStructLayouts) const override { \
if (!useStructLayouts) { \
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T); \
} \
ScalarKind kind; \
switch (Refcounting) { \
case ReferenceCounting::Native: kind = ScalarKind::NativeStrongReference; break; \
case ReferenceCounting::ObjC: kind = ScalarKind::ObjCReference; break; \
case ReferenceCounting::Block: kind = ScalarKind::BlockReference; break; \
case ReferenceCounting::Unknown: kind = ScalarKind::UnknownReference; break; \
case ReferenceCounting::Bridge: kind = ScalarKind::BridgeReference; break; \
case ReferenceCounting::Error: kind = ScalarKind::ErrorReference; break; \
case ReferenceCounting::None: kind = ScalarKind::TriviallyDestroyable; break; \
case ReferenceCounting::Custom: kind = ScalarKind::CustomReference; break; \
} \
return IGM.typeLayoutCache.getOrCreateScalarEntry(*this, T, kind); \
} \
llvm::Type *getValueType() const { \
return ValueType; \
} \
Address projectValue(IRGenFunction &IGF, Address addr) const { \
Address valueAddr = ScalarExistentialTypeInfoBase::projectValue(IGF, addr); \
return IGF.Builder.CreateElementBitCast(valueAddr, ValueType); \
} \
void emitValueRetain(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Name##Retain(value, Refcounting, atomicity); \
} \
void emitValueRelease(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Name##Release(value, Refcounting, atomicity); \
} \
void emitValueFixLifetime(IRGenFunction &IGF, llvm::Value *value) const { \
IGF.emitFixLifetime(value); \
} \
const LoadableTypeInfo & \
getValueTypeInfoForExtraInhabitants(IRGenModule &IGM) const { \
llvm_unreachable("should have overridden all actual uses of this"); \
} \
REF_STORAGE_HELPER(Name, LoadableTypeInfo) \
};
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \
NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, name, "...") \
ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, "...")
/// A type implementation for static reference storage class existential types
/// that do not generate dynamic (i.e. runtime) logic.
#define UNCHECKED_REF_STORAGE(Name, ...) \
class Name##ClassExistentialTypeInfo final \
: public ScalarExistentialTypeInfoBase<Name##ClassExistentialTypeInfo, \
LoadableTypeInfo> { \
bool IsOptional; \
public: \
Name##ClassExistentialTypeInfo( \
ArrayRef<const ProtocolDecl *> storedProtocols, \
llvm::Type *ty, \
const SpareBitVector &spareBits, \
Size size, Alignment align, \
bool isOptional) \
: ScalarExistentialTypeInfoBase(storedProtocols, ty, size, \
spareBits, align, IsTriviallyDestroyable,\
IsCopyable, IsFixedSize, IsABIAccessible), \
IsOptional(isOptional) {} \
TypeLayoutEntry \
*buildTypeLayoutEntry(IRGenModule &IGM, \
SILType T, \
bool useStructLayouts) const override { \
if (!useStructLayouts) { \
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T); \
} \
return IGM.typeLayoutCache.getOrCreateScalarEntry(*this, T, ScalarKind::TriviallyDestroyable); \
} \
const LoadableTypeInfo & \
getValueTypeInfoForExtraInhabitants(IRGenModule &IGM) const { \
if (!IGM.ObjCInterop) \
return IGM.getNativeObjectTypeInfo(); \
else \
return IGM.getUnknownObjectTypeInfo(); \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
return getValueTypeInfoForExtraInhabitants(IGM) \
.getFixedExtraInhabitantCount(IGM) - IsOptional; \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
/* Note that we pass down the original bit-width. */ \
return getValueTypeInfoForExtraInhabitants(IGM) \
.getFixedExtraInhabitantValue(IGM, bits, \
index + IsOptional); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, \
Address src, SILType T, \
bool isOutlined) const override { \
return PointerInfo::forHeapObject(IGF.IGM) \
.withNullable(IsNullable_t(IsOptional)) \
.getExtraInhabitantIndex(IGF, src); \
} \
/* FIXME -- Use REF_STORAGE_HELPER and make */ \
/* getValueTypeInfoForExtraInhabitants call llvm_unreachable() */ \
void emitValueRetain(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const {} \
void emitValueRelease(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const {} \
void emitValueFixLifetime(IRGenFunction &IGF, llvm::Value *value) const {} \
};
#include "swift/AST/ReferenceStorage.def"
#undef REF_STORAGE_HELPER
} // end anonymous namespace
static llvm::Function *getAssignBoxedOpaqueExistentialBufferFunction(
IRGenModule &IGM, OpaqueExistentialLayout existLayout);
static llvm::Function *getDestroyBoxedOpaqueExistentialBufferFunction(
IRGenModule &IGM, OpaqueExistentialLayout existLayout);
static llvm::Function *
getProjectBoxedOpaqueExistentialFunction(IRGenFunction &IGF,
OpenedExistentialAccess accessKind,
OpaqueExistentialLayout existLayout);
namespace {
/// A TypeInfo implementation for existential types, i.e., types like:
/// Printable
/// Printable & Serializable
/// Any
/// with the semantic translation:
/// \exists t : Printable . t
/// t here is an ArchetypeType.
///
/// This is used for both ProtocolTypes and ProtocolCompositionTypes.
class OpaqueExistentialTypeInfo final :
public ExistentialTypeInfoBase<OpaqueExistentialTypeInfo,
IndirectTypeInfo<OpaqueExistentialTypeInfo, FixedTypeInfo>> {
using super =
ExistentialTypeInfoBase<OpaqueExistentialTypeInfo,
IndirectTypeInfo<OpaqueExistentialTypeInfo, FixedTypeInfo>>;
friend super;
OpaqueExistentialTypeInfo(ArrayRef<const ProtocolDecl *> protocols,
llvm::Type *ty, Size size,
IsCopyable_t copyable,
SpareBitVector &&spareBits,
Alignment align)
: super(protocols, ty, size,
std::move(spareBits), align,
IsNotTriviallyDestroyable,
// Copyable existentials are bitwise-takable and borrowable.
// Noncopyable existentials are bitwise-takable only.
copyable ? IsBitwiseTakableAndBorrowable : IsBitwiseTakableOnly,
copyable,
IsFixedSize, IsABIAccessible) {}
public:
OpaqueExistentialLayout getLayout() const {
return OpaqueExistentialLayout(getNumStoredProtocols());
}
TypeLayoutEntry
*buildTypeLayoutEntry(IRGenModule &IGM,
SILType T,
bool useStructLayouts) const override {
if (!useStructLayouts) {
return IGM.typeLayoutCache.getOrCreateTypeInfoBasedEntry(*this, T);
}
return IGM.typeLayoutCache.getOrCreateScalarEntry(
*this, T, ScalarKind::ExistentialReference);
}
Address projectWitnessTable(IRGenFunction &IGF, Address obj,
unsigned index) const {
return getLayout().projectWitnessTable(IGF, obj, index);
}
void assignWithCopy(IRGenFunction &IGF, Address dest, Address src, SILType T,
bool isOutlined) const override {
// Use copy-on-write existentials?
auto fn = getAssignBoxedOpaqueExistentialBufferFunction(
IGF.IGM, getLayout());
auto *type = IGF.IGM.getExistentialPtrTy(getLayout().getNumTables());
auto *destAddr = IGF.Builder.CreateBitCast(dest.getAddress(), type);
auto *srcAddr = IGF.Builder.CreateBitCast(src.getAddress(), type);
auto call = IGF.Builder.CreateCallWithoutDbgLoc(fn->getFunctionType(), fn,
{destAddr, srcAddr});
call->setCallingConv(IGF.IGM.DefaultCC);
call->setDoesNotThrow();
return;
}
llvm::Value *copyType(IRGenFunction &IGF, Address dest, Address src) const {
auto layout = getLayout();
llvm::Value *metadata = layout.loadMetadataRef(IGF, src);
IGF.Builder.CreateStore(metadata, layout.projectMetadataRef(IGF, dest));
// Load the witness tables and copy them into the new object.
emitCopyOfTables(IGF, dest, src);
return metadata;
}
void initializeWithCopy(IRGenFunction &IGF, Address dest, Address src,
SILType T, bool isOutlined) const override {
if (isOutlined || T.hasLocalArchetype()) {
llvm::Value *metadata = copyType(IGF, dest, src);
auto layout = getLayout();
// Project down to the buffers and ask the witnesses to do a
// copy-initialize.
Address srcBuffer = layout.projectExistentialBuffer(IGF, src);
Address destBuffer = layout.projectExistentialBuffer(IGF, dest);
emitInitializeBufferWithCopyOfBufferCall(IGF, metadata, destBuffer,
srcBuffer);
} else {
// Create an outlined function to avoid explosion
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsInitialization, IsNotTake);
}
}
void initializeWithTake(IRGenFunction &IGF, Address dest, Address src,
SILType T, bool isOutlined,
bool zeroizeIfSensitive) const override {
if (isOutlined || T.hasLocalArchetype()) {
// memcpy the existential container. This is safe because: either the
// value is stored inline and is therefore by convention bitwise takable
// or the value is stored in a reference counted heap buffer, in which
// case a memcpy of the reference is also correct.
IGF.emitMemCpy(dest, src, getLayout().getSize(IGF.IGM));
} else {
// Create an outlined function to avoid explosion
OutliningMetadataCollector collector(T, IGF, LayoutIsNeeded,
DeinitIsNotNeeded);
collector.emitCallToOutlinedCopy(dest, src, T, *this,
IsInitialization, IsTake);