forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeLowering.cpp
2880 lines (2472 loc) · 108 KB
/
TypeLowering.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
//===--- TypeLowering.cpp - Type information for SILGen -------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/CanTypeVisitor.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/Types.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "clang/AST/Type.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace Lowering;
namespace {
/// A CRTP type visitor for deciding whether the metatype for a type
/// is a singleton type, i.e. whether there can only ever be one
/// such value.
struct HasSingletonMetatype : CanTypeVisitor<HasSingletonMetatype, bool> {
/// Class metatypes have non-trivial representation due to the
/// possibility of subclassing.
bool visitClassType(CanClassType type) {
return false;
}
bool visitBoundGenericClassType(CanBoundGenericClassType type) {
return false;
}
bool visitDynamicSelfType(CanDynamicSelfType type) {
return false;
}
/// Dependent types have non-trivial representation in case they
/// instantiate to a class metatype.
bool visitGenericTypeParamType(CanGenericTypeParamType type) {
return false;
}
bool visitDependentMemberType(CanDependentMemberType type) {
return false;
}
/// Archetype metatypes have non-trivial representation in case
/// they instantiate to a class metatype.
bool visitArchetypeType(CanArchetypeType type) {
return false;
}
/// All levels of class metatypes support subtyping.
bool visitMetatypeType(CanMetatypeType type) {
return visit(type.getInstanceType());
}
/// Everything else is trivial. Note that ordinary metatypes of
/// existential types are still singleton.
bool visitType(CanType type) {
return true;
}
};
} // end anonymous namespace
/// Does the metatype for the given type have a known-singleton
/// representation?
static bool hasSingletonMetatype(CanType instanceType) {
return HasSingletonMetatype().visit(instanceType);
}
CaptureKind TypeConverter::getDeclCaptureKind(CapturedValue capture,
TypeExpansionContext expansion) {
auto decl = capture.getDecl();
auto *var = cast<VarDecl>(decl);
assert(var->hasStorage() &&
"should not have attempted to directly capture this variable");
// If this is a non-address-only stored 'let' constant, we can capture it
// by value. If it is address-only, then we can't load it, so capture it
// by its address (like a var) instead.
if (!var->supportsMutation() &&
(Context.LangOpts.EnableSILOpaqueValues ||
!getTypeLowering(
var->getType(),
TypeExpansionContext::noOpaqueTypeArchetypesSubstitution(
expansion.getResilienceExpansion()))
.isAddressOnly()))
return CaptureKind::Constant;
// In-out parameters are captured by address.
if (auto *param = dyn_cast<ParamDecl>(var)) {
if (param->isInOut())
return CaptureKind::StorageAddress;
}
// Reference storage types can appear in a capture list, which means
// we might allocate boxes to store the captures. However, those boxes
// have the same lifetime as the closure itself, so we must capture
// the box itself and not the payload, even if the closure is noescape,
// otherwise they will be destroyed when the closure is formed.
if (var->getType()->is<ReferenceStorageType>()) {
return CaptureKind::Box;
}
// If we're capturing into a non-escaping closure, we can generally just
// capture the address of the value as no-escape.
return (capture.isNoEscape()
? CaptureKind::StorageAddress
: CaptureKind::Box);
}
using RecursiveProperties = TypeLowering::RecursiveProperties;
static RecursiveProperties
classifyType(CanType type, TypeConverter &TC, CanGenericSignature sig,
TypeExpansionContext expansion);
namespace {
/// A CRTP helper class for doing things that depends on type
/// classification.
template <class Impl, class RetTy>
class TypeClassifierBase : public CanTypeVisitor<Impl, RetTy> {
Impl &asImpl() { return *static_cast<Impl*>(this); }
protected:
TypeConverter &TC;
CanGenericSignature Sig;
TypeExpansionContext Expansion;
TypeClassifierBase(TypeConverter &TC, CanGenericSignature Sig,
TypeExpansionContext Expansion)
: TC(TC), Sig(Sig), Expansion(Expansion) {}
public:
// The subclass should implement:
// // Trivial, fixed-layout, and non-address-only.
// RetTy handleTrivial(CanType);
// RetTy handleTrivial(CanType. RecursiveProperties properties);
// // A reference type.
// RetTy handleReference(CanType);
// // Non-trivial and address-only.
// RetTy handleAddressOnly(CanType, RecursiveProperties properties);
// and, if it doesn't override handleTupleType,
// // An aggregate type that's non-trivial.
// RetTy handleNonTrivialAggregate(CanType, RecursiveProperties properties);
//
// Alternatively, it can just implement:
// RetTy handle(CanType, RecursiveProperties properties);
/// Handle a trivial, fixed-size, loadable type.
RetTy handleTrivial(CanType type, RecursiveProperties properties) {
return asImpl().handle(type, properties);
}
RetTy handleAddressOnly(CanType type, RecursiveProperties properties) {
return asImpl().handle(type, properties);
}
RetTy handleNonTrivialAggregate(CanType type,
RecursiveProperties properties) {
return asImpl().handle(type, properties);
}
RetTy handleTrivial(CanType type) {
return asImpl().handleTrivial(type, RecursiveProperties::forTrivial());
}
RetTy handleReference(CanType type) {
return asImpl().handle(type, RecursiveProperties::forReference());
}
#define IMPL(TYPE, LOWERING) \
RetTy visit##TYPE##Type(Can##TYPE##Type type) { \
return asImpl().handle##LOWERING(type); \
}
IMPL(BuiltinInteger, Trivial)
IMPL(BuiltinIntegerLiteral, Trivial)
IMPL(BuiltinFloat, Trivial)
IMPL(BuiltinRawPointer, Trivial)
IMPL(BuiltinNativeObject, Reference)
IMPL(BuiltinBridgeObject, Reference)
IMPL(BuiltinVector, Trivial)
IMPL(SILToken, Trivial)
IMPL(Class, Reference)
IMPL(BoundGenericClass, Reference)
IMPL(AnyMetatype, Trivial)
IMPL(Module, Trivial)
#undef IMPL
RetTy visitBuiltinUnsafeValueBufferType(
CanBuiltinUnsafeValueBufferType type) {
return asImpl().handleAddressOnly(type, {IsNotTrivial, IsFixedABI,
IsAddressOnly, IsNotResilient});
}
RetTy visitAnyFunctionType(CanAnyFunctionType type) {
switch (type->getRepresentation()) {
case AnyFunctionType::Representation::Swift:
case AnyFunctionType::Representation::Block:
return asImpl().handleReference(type);
case AnyFunctionType::Representation::CFunctionPointer:
case AnyFunctionType::Representation::Thin:
return asImpl().handleTrivial(type);
}
llvm_unreachable("bad function representation");
}
RetTy visitSILFunctionType(CanSILFunctionType type) {
// Only escaping closures are references.
bool isSwiftEscaping = type->getExtInfo().isNoEscape() &&
type->getExtInfo().getRepresentation() ==
SILFunctionType::Representation::Thick;
if (type->getExtInfo().hasContext() && !isSwiftEscaping)
return asImpl().handleReference(type);
// No escaping closures are trivial types.
return asImpl().handleTrivial(type);
}
RetTy visitLValueType(CanLValueType type) {
llvm_unreachable("shouldn't get an l-value type here");
}
RetTy visitInOutType(CanInOutType type) {
llvm_unreachable("shouldn't get an inout type here");
}
RetTy visitErrorType(CanErrorType type) {
return asImpl().handleTrivial(type);
}
// Dependent types should be contextualized before visiting.
CanGenericSignature getGenericSignature() {
if (Sig)
return Sig;
return TC.getCurGenericContext();
}
RetTy visitAbstractTypeParamType(CanType type) {
if (auto genericSig = getGenericSignature()) {
if (genericSig->requiresClass(type)) {
return asImpl().handleReference(type);
} else if (genericSig->isConcreteType(type)) {
return asImpl().visit(genericSig->getConcreteType(type)
->getCanonicalType());
} else {
return asImpl().handleAddressOnly(type,
RecursiveProperties::forOpaque());
}
}
llvm_unreachable("should have substituted dependent type into context");
}
RetTy visitGenericTypeParamType(CanGenericTypeParamType type) {
return visitAbstractTypeParamType(type);
}
RetTy visitDependentMemberType(CanDependentMemberType type) {
return visitAbstractTypeParamType(type);
}
Type getConcreteReferenceStorageReferent(Type type) {
if (type->isTypeParameter()) {
auto signature = getGenericSignature();
assert(signature && "dependent type without generic signature?!");
if (auto concreteType = signature->getConcreteType(type))
return concreteType->getCanonicalType();
assert(signature->requiresClass(type));
// If we have a superclass bound, recurse on that. This should
// always terminate: even if we allow
// <T, U: T, V: U, ...>
// at some point the type-checker should prove acyclic-ness.
auto bound = signature->getSuperclassBound(type);
if (bound) {
return getConcreteReferenceStorageReferent(bound->getCanonicalType());
}
return TC.Context.getAnyObjectType();
}
return type;
}
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
RetTy visit##Name##StorageType(Can##Name##StorageType type) { \
return asImpl().handleAddressOnly(type, {IsNotTrivial, \
IsFixedABI, \
IsAddressOnly, \
IsNotResilient}); \
}
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
RetTy visit##Name##StorageType(Can##Name##StorageType type) { \
return asImpl().handleReference(type); \
}
#define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
RetTy visitLoadable##Name##StorageType(Can##Name##StorageType type) { \
return asImpl().handleReference(type); \
} \
RetTy visitAddressOnly##Name##StorageType(Can##Name##StorageType type) { \
return asImpl().handleAddressOnly(type, {IsNotTrivial, \
IsFixedABI, \
IsAddressOnly, \
IsNotResilient}); \
} \
RetTy visit##Name##StorageType(Can##Name##StorageType type) { \
auto referentType = type->getReferentType(); \
auto concreteType = getConcreteReferenceStorageReferent(referentType); \
if (Name##StorageType::get(concreteType, TC.Context) \
->isLoadable(Expansion.getResilienceExpansion())) { \
return asImpl().visitLoadable##Name##StorageType(type); \
} else { \
return asImpl().visitAddressOnly##Name##StorageType(type); \
} \
}
#define UNCHECKED_REF_STORAGE(Name, ...) \
RetTy visit##Name##StorageType(Can##Name##StorageType type) { \
return asImpl().handleTrivial(type); \
}
#include "swift/AST/ReferenceStorage.def"
RetTy visitOpaqueTypeArchetypeType(CanOpaqueTypeArchetypeType ty) {
auto replacedTy = substOpaqueTypesWithUnderlyingTypes(ty, Expansion);
if (replacedTy == ty)
return visitArchetypeType(ty);
return this->visit(replacedTy);
}
RetTy visitArchetypeType(CanArchetypeType type) {
if (type->requiresClass()) {
return asImpl().handleReference(type);
}
auto LayoutInfo = type->getLayoutConstraint();
if (LayoutInfo) {
if (LayoutInfo->isFixedSizeTrivial()) {
return asImpl().handleTrivial(type);
}
if (LayoutInfo->isAddressOnlyTrivial()) {
auto properties = RecursiveProperties::forTrivial();
properties.setAddressOnly();
return asImpl().handleAddressOnly(type, properties);
}
if (LayoutInfo->isRefCounted())
return asImpl().handleReference(type);
}
return asImpl().handleAddressOnly(type, RecursiveProperties::forOpaque());
}
RetTy visitExistentialType(CanType type) {
switch (SILType::getPrimitiveObjectType(type)
.getPreferredExistentialRepresentation()) {
case ExistentialRepresentation::None:
llvm_unreachable("not an existential type?!");
// Opaque existentials are address-only.
case ExistentialRepresentation::Opaque:
return asImpl().handleAddressOnly(type, {IsNotTrivial,
IsFixedABI,
IsAddressOnly,
IsNotResilient});
// Class-constrained and boxed existentials are refcounted.
case ExistentialRepresentation::Class:
case ExistentialRepresentation::Boxed:
return asImpl().handleReference(type);
// Existential metatypes are trivial.
case ExistentialRepresentation::Metatype:
return asImpl().handleTrivial(type);
}
llvm_unreachable("Unhandled ExistentialRepresentation in switch.");
}
RetTy visitProtocolType(CanProtocolType type) {
return visitExistentialType(type);
}
RetTy visitProtocolCompositionType(CanProtocolCompositionType type) {
return visitExistentialType(type);
}
// Enums depend on their enumerators.
RetTy visitEnumType(CanEnumType type) {
return asImpl().visitAnyEnumType(type, type->getDecl());
}
RetTy visitBoundGenericEnumType(CanBoundGenericEnumType type) {
return asImpl().visitAnyEnumType(type, type->getDecl());
}
// Structs depend on their physical fields.
RetTy visitStructType(CanStructType type) {
return asImpl().visitAnyStructType(type, type->getDecl());
}
RetTy visitBoundGenericStructType(CanBoundGenericStructType type) {
return asImpl().visitAnyStructType(type, type->getDecl());
}
// Tuples depend on their elements.
RetTy visitTupleType(CanTupleType type) {
RecursiveProperties props;
for (auto eltType : type.getElementTypes()) {
props.addSubobject(classifyType(eltType, TC, Sig, Expansion));
}
return asImpl().handleAggregateByProperties(type, props);
}
RetTy visitDynamicSelfType(CanDynamicSelfType type) {
return this->visit(type.getSelfType());
}
RetTy visitSILBlockStorageType(CanSILBlockStorageType type) {
// Should not be loaded.
return asImpl().handleAddressOnly(type, {IsNotTrivial,
IsFixedABI,
IsAddressOnly,
IsNotResilient});
}
RetTy visitSILBoxType(CanSILBoxType type) {
// Should not be loaded.
return asImpl().handleReference(type);
}
RetTy handleAggregateByProperties(CanType type, RecursiveProperties props) {
if (props.isAddressOnly()) {
return asImpl().handleAddressOnly(type, props);
}
assert(props.isFixedABI() && "unsupported combination for now");
if (props.isTrivial()) {
return asImpl().handleTrivial(type, props);
}
return asImpl().handleNonTrivialAggregate(type, props);
}
};
class TypeClassifier :
public TypeClassifierBase<TypeClassifier, RecursiveProperties> {
public:
TypeClassifier(TypeConverter &TC, CanGenericSignature Sig,
TypeExpansionContext Expansion)
: TypeClassifierBase(TC, Sig, Expansion) {}
RecursiveProperties handle(CanType type, RecursiveProperties properties) {
return properties;
}
RecursiveProperties visitAnyEnumType(CanType type, EnumDecl *D) {
// We have to look through optionals here without grabbing the
// type lowering because the way that optionals are reabstracted
// can trip recursion checks if we try to build a lowered type.
if (D->isOptionalDecl()) {
return visit(type.getOptionalObjectType());
}
// Consult the type lowering.
type = getSubstitutedTypeForTypeLowering(type);
auto &lowering = TC.getTypeLowering(type, Expansion);
return handleClassificationFromLowering(type, lowering);
}
RecursiveProperties visitAnyStructType(CanType type, StructDecl *D) {
// Consult the type lowering.
type = getSubstitutedTypeForTypeLowering(type);
auto &lowering = TC.getTypeLowering(type, Expansion);
return handleClassificationFromLowering(type, lowering);
}
private:
CanType getSubstitutedTypeForTypeLowering(CanType type) {
// If we're using a generic signature different from
// TC.getCurGenericContext(), we have to map the
// type into context before asking for a type lowering
// because the rest of type lowering doesn't have a generic
// signature plumbed through.
if (Sig && type->hasTypeParameter()) {
type = Sig->getCanonicalSignature()
->getGenericEnvironment()
->mapTypeIntoContext(type)
->getCanonicalType();
}
return type;
}
RecursiveProperties handleClassificationFromLowering(CanType type,
const TypeLowering &lowering) {
return handle(type, lowering.getRecursiveProperties());
}
};
} // end anonymous namespace
static RecursiveProperties classifyType(CanType type, TypeConverter &tc,
CanGenericSignature sig,
TypeExpansionContext expansion) {
return TypeClassifier(tc, sig, expansion).visit(type);
}
/// True if the type, or the referenced type of an address
/// type, is address-only. For example, it could be a resilient struct or
/// something of unknown size.
bool SILType::isAddressOnly(CanType type, TypeConverter &tc,
CanGenericSignature sig,
TypeExpansionContext expansion) {
return classifyType(type, tc, sig, expansion).isAddressOnly();
}
namespace {
/// A class for types that can be loaded and stored in SIL.
/// This always include loadable types, but can include address-only types if
/// opaque values are passed by value.
class LoadableTypeLowering : public TypeLowering {
protected:
LoadableTypeLowering(SILType type, RecursiveProperties properties,
IsReferenceCounted_t isRefCounted,
TypeExpansionContext forExpansion)
: TypeLowering(type, properties, isRefCounted, forExpansion) {}
public:
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
SILValue value = emitLoad(B, loc, addr, LoadOwnershipQualifier::Take);
emitDestroyValue(B, loc, value);
}
void emitDestroyRValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
emitDestroyValue(B, loc, value);
}
void emitCopyInto(SILBuilder &B, SILLocation loc,
SILValue src, SILValue dest, IsTake_t isTake,
IsInitialization_t isInit) const override {
SILValue value = emitLoadOfCopy(B, loc, src, isTake);
emitStoreOfCopy(B, loc, value, dest, isInit);
}
};
/// A class for trivial, fixed-layout, loadable types.
class TrivialTypeLowering final : public LoadableTypeLowering {
public:
TrivialTypeLowering(SILType type, RecursiveProperties properties,
TypeExpansionContext forExpansion)
: LoadableTypeLowering(type, properties, IsNotReferenceCounted,
forExpansion) {
assert(properties.isFixedABI());
assert(properties.isTrivial());
assert(!properties.isAddressOnly());
}
SILValue emitLoadOfCopy(SILBuilder &B, SILLocation loc, SILValue addr,
IsTake_t isTake) const override {
return emitLoad(B, loc, addr, LoadOwnershipQualifier::Trivial);
}
void emitStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue value, SILValue addr,
IsInitialization_t isInit) const override {
emitStore(B, loc, value, addr, StoreOwnershipQualifier::Trivial);
}
void emitStore(SILBuilder &B, SILLocation loc, SILValue value,
SILValue addr, StoreOwnershipQualifier qual) const override {
if (B.getFunction().hasOwnership()) {
B.createStore(loc, value, addr, StoreOwnershipQualifier::Trivial);
return;
}
B.createStore(loc, value, addr, StoreOwnershipQualifier::Unqualified);
}
SILValue emitLoad(SILBuilder &B, SILLocation loc, SILValue addr,
LoadOwnershipQualifier qual) const override {
if (B.getFunction().hasOwnership())
return B.createLoad(loc, addr, LoadOwnershipQualifier::Trivial);
return B.createLoad(loc, addr, LoadOwnershipQualifier::Unqualified);
}
void emitDestroyAddress(SILBuilder &B, SILLocation loc,
SILValue addr) const override {
// Trivial
}
void
emitLoweredDestroyValue(SILBuilder &B, SILLocation loc, SILValue value,
TypeExpansionKind loweringStyle) const override {
// Trivial
}
SILValue emitLoweredCopyValue(SILBuilder &B, SILLocation loc,
SILValue value,
TypeExpansionKind style) const override {
// Trivial
return value;
}
SILValue emitCopyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
// Trivial
return value;
}
void emitDestroyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
// Trivial
}
};
class NonTrivialLoadableTypeLowering : public LoadableTypeLowering {
public:
NonTrivialLoadableTypeLowering(SILType type,
RecursiveProperties properties,
IsReferenceCounted_t isRefCounted,
TypeExpansionContext forExpansion)
: LoadableTypeLowering(type, properties, isRefCounted, forExpansion) {
assert(!properties.isTrivial());
}
SILValue emitLoadOfCopy(SILBuilder &B, SILLocation loc,
SILValue addr, IsTake_t isTake) const override {
auto qual =
isTake ? LoadOwnershipQualifier::Take : LoadOwnershipQualifier::Copy;
return emitLoad(B, loc, addr, qual);
}
void emitStoreOfCopy(SILBuilder &B, SILLocation loc,
SILValue newValue, SILValue addr,
IsInitialization_t isInit) const override {
auto qual = isInit ? StoreOwnershipQualifier::Init
: StoreOwnershipQualifier::Assign;
emitStore(B, loc, newValue, addr, qual);
}
void emitStore(SILBuilder &B, SILLocation loc, SILValue value,
SILValue addr, StoreOwnershipQualifier qual) const override {
if (B.getFunction().hasOwnership()) {
B.createStore(loc, value, addr, qual);
return;
}
if (qual != StoreOwnershipQualifier::Assign) {
B.createStore(loc, value, addr, StoreOwnershipQualifier::Unqualified);
return;
}
// If the ownership qualifier is [assign], then we need to eliminate the
// old value.
//
// 1. Load old value.
// 2. Store new value.
// 3. Release old value.
SILValue old =
B.createLoad(loc, addr, LoadOwnershipQualifier::Unqualified);
B.createStore(loc, value, addr, StoreOwnershipQualifier::Unqualified);
B.emitDestroyValueOperation(loc, old);
}
SILValue emitLoad(SILBuilder &B, SILLocation loc, SILValue addr,
LoadOwnershipQualifier qual) const override {
if (B.getFunction().hasOwnership())
return B.createLoad(loc, addr, qual);
SILValue loadValue =
B.createLoad(loc, addr, LoadOwnershipQualifier::Unqualified);
// If we do not have a copy, just return the value...
if (qual != LoadOwnershipQualifier::Copy)
return loadValue;
// Otherwise, emit the copy value operation.
return B.emitCopyValueOperation(loc, loadValue);
}
};
/// A CRTP helper class for loadable but non-trivial aggregate types.
template <class Impl, class IndexType>
class LoadableAggTypeLowering : public NonTrivialLoadableTypeLowering {
public:
/// A child of this aggregate type.
class Child {
/// The index of this child, used to project it out.
IndexType Index;
/// The aggregate's type lowering.
const TypeLowering *Lowering;
public:
Child(IndexType index, const TypeLowering &lowering)
: Index(index), Lowering(&lowering) {}
const TypeLowering &getLowering() const { return *Lowering; }
IndexType getIndex() const { return Index; }
bool isTrivial() const { return Lowering->isTrivial(); }
};
private:
const Impl &asImpl() const { return static_cast<const Impl&>(*this); }
Impl &asImpl() { return static_cast<Impl&>(*this); }
// A reference to the lazily-allocated children vector.
mutable ArrayRef<Child> Children = {};
protected:
virtual void lowerChildren(TypeConverter &TC, SmallVectorImpl<Child> &children)
const = 0;
public:
LoadableAggTypeLowering(CanType type, RecursiveProperties properties,
TypeExpansionContext forExpansion)
: NonTrivialLoadableTypeLowering(SILType::getPrimitiveObjectType(type),
properties, IsNotReferenceCounted,
forExpansion) {
}
virtual SILValue rebuildAggregate(SILBuilder &B, SILLocation loc,
ArrayRef<SILValue> values) const = 0;
ArrayRef<Child> getChildren(TypeConverter &TC) const {
if (Children.data() == nullptr) {
SmallVector<Child, 4> children;
lowerChildren(TC, children);
auto isDependent = IsDependent_t(getLoweredType().hasTypeParameter());
auto buf = operator new(sizeof(Child) * children.size(), TC,
isDependent);
memcpy(buf, children.data(), sizeof(Child) * children.size());
Children = {reinterpret_cast<Child*>(buf), children.size()};
}
return Children;
}
template <class T>
void forEachNonTrivialChild(SILBuilder &B, SILLocation loc,
SILValue aggValue,
const T &operation) const {
for (auto &child : getChildren(B.getModule().Types)) {
auto &childLowering = child.getLowering();
// Skip trivial children.
if (childLowering.isTrivial())
continue;
auto childIndex = child.getIndex();
auto childValue = asImpl().emitRValueProject(B, loc, aggValue,
childIndex, childLowering);
operation(B, loc, childIndex, childValue, childLowering);
}
}
using SimpleOperationTy = void (TypeLowering::*)(SILBuilder &B,
SILLocation loc,
SILValue value) const;
void forEachNonTrivialChild(SILBuilder &B, SILLocation loc,
SILValue aggValue,
SimpleOperationTy operation) const {
forEachNonTrivialChild(B, loc, aggValue,
[operation](SILBuilder &B, SILLocation loc, IndexType index,
SILValue childValue, const TypeLowering &childLowering) {
(childLowering.*operation)(B, loc, childValue);
});
}
SILValue emitCopyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (B.getFunction().hasOwnership())
return B.createCopyValue(loc, value);
B.createRetainValue(loc, value, B.getDefaultAtomicity());
return value;
}
SILValue emitLoweredCopyValue(SILBuilder &B, SILLocation loc,
SILValue aggValue,
TypeExpansionKind style) const override {
if (style == TypeExpansionKind::None) {
return emitCopyValue(B, loc, aggValue);
}
llvm::SmallVector<SILValue, 8> loweredChildValues;
for (auto &child : getChildren(B.getModule().Types)) {
auto &childLowering = child.getLowering();
SILValue childValue = asImpl().emitRValueProject(B, loc, aggValue,
child.getIndex(),
childLowering);
if (!childLowering.isTrivial()) {
SILValue loweredChildValue = childLowering.emitLoweredCopyChildValue(
B, loc, childValue, style);
loweredChildValues.push_back(loweredChildValue);
} else {
loweredChildValues.push_back(childValue);
}
}
return rebuildAggregate(B, loc, loweredChildValues);
}
void emitDestroyValue(SILBuilder &B, SILLocation loc,
SILValue aggValue) const override {
if (B.getFunction().hasOwnership()) {
B.createDestroyValue(loc, aggValue);
return;
}
B.emitReleaseValueAndFold(loc, aggValue);
}
void
emitLoweredDestroyValue(SILBuilder &B, SILLocation loc, SILValue aggValue,
TypeExpansionKind loweringStyle) const override {
SimpleOperationTy Fn;
switch(loweringStyle) {
case TypeExpansionKind::None:
return emitDestroyValue(B, loc, aggValue);
case TypeExpansionKind::DirectChildren:
Fn = &TypeLowering::emitDestroyValue;
break;
case TypeExpansionKind::MostDerivedDescendents:
Fn = &TypeLowering::emitLoweredDestroyValueMostDerivedDescendents;
break;
}
forEachNonTrivialChild(B, loc, aggValue, Fn);
}
};
/// A lowering for loadable but non-trivial tuple types.
class LoadableTupleTypeLowering final
: public LoadableAggTypeLowering<LoadableTupleTypeLowering, unsigned> {
public:
LoadableTupleTypeLowering(CanType type, RecursiveProperties properties,
TypeExpansionContext forExpansion)
: LoadableAggTypeLowering(type, properties, forExpansion) {}
SILValue emitRValueProject(SILBuilder &B, SILLocation loc,
SILValue tupleValue, unsigned index,
const TypeLowering &eltLowering) const {
return B.createTupleExtract(loc, tupleValue, index,
eltLowering.getLoweredType());
}
SILValue rebuildAggregate(SILBuilder &B, SILLocation loc,
ArrayRef<SILValue> values) const override {
return B.createTuple(loc, getLoweredType(), values);
}
private:
void lowerChildren(TypeConverter &TC, SmallVectorImpl<Child> &children)
const override {
// The children are just the elements of the lowered tuple.
auto silTy = getLoweredType();
auto tupleTy = silTy.castTo<TupleType>();
children.reserve(tupleTy->getNumElements());
unsigned index = 0;
for (auto elt : tupleTy.getElementTypes()) {
auto silElt = SILType::getPrimitiveType(elt, silTy.getCategory());
auto &eltTL = TC.getTypeLowering(silElt, getExpansionContext());
children.push_back(Child{index, eltTL});
++index;
}
}
};
/// A lowering for loadable but non-trivial struct types.
class LoadableStructTypeLowering final
: public LoadableAggTypeLowering<LoadableStructTypeLowering, VarDecl*> {
public:
LoadableStructTypeLowering(CanType type, RecursiveProperties properties,
TypeExpansionContext forExpansion)
: LoadableAggTypeLowering(type, properties, forExpansion) {}
SILValue emitRValueProject(SILBuilder &B, SILLocation loc,
SILValue structValue, VarDecl *field,
const TypeLowering &fieldLowering) const {
return B.createStructExtract(loc, structValue, field,
fieldLowering.getLoweredType());
}
SILValue rebuildAggregate(SILBuilder &B, SILLocation loc,
ArrayRef<SILValue> values) const override {
return B.createStruct(loc, getLoweredType(), values);
}
private:
void lowerChildren(TypeConverter &TC, SmallVectorImpl<Child> &children)
const override {
auto silTy = getLoweredType();
auto structDecl = silTy.getStructOrBoundGenericStruct();
assert(structDecl);
for (auto prop : structDecl->getStoredProperties()) {
SILType propTy = silTy.getFieldType(prop, TC, getExpansionContext());
auto &propTL = TC.getTypeLowering(propTy, getExpansionContext());
children.push_back(Child{prop, propTL});
}
}
};
/// A lowering for loadable but non-trivial enum types.
class LoadableEnumTypeLowering final : public NonTrivialLoadableTypeLowering {
public:
LoadableEnumTypeLowering(CanType type, RecursiveProperties properties,
TypeExpansionContext forExpansion)
: NonTrivialLoadableTypeLowering(SILType::getPrimitiveObjectType(type),
properties,
IsNotReferenceCounted,
forExpansion) {}
SILValue emitCopyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (B.getFunction().hasOwnership())
return B.createCopyValue(loc, value);
B.createRetainValue(loc, value, B.getDefaultAtomicity());
return value;
}
SILValue emitLoweredCopyValue(SILBuilder &B, SILLocation loc,
SILValue value,
TypeExpansionKind style) const override {
if (B.getFunction().hasOwnership())
return B.createCopyValue(loc, value);
B.createRetainValue(loc, value, B.getDefaultAtomicity());
return value;
}
void emitDestroyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (B.getFunction().hasOwnership()) {
B.createDestroyValue(loc, value);
return;
}
B.emitReleaseValueAndFold(loc, value);
}
void emitLoweredDestroyValue(SILBuilder &B, SILLocation loc, SILValue value,
TypeExpansionKind style) const override {
// Enums, we never want to expand.
return emitDestroyValue(B, loc, value);
}
};
class LeafLoadableTypeLowering : public NonTrivialLoadableTypeLowering {
public:
LeafLoadableTypeLowering(SILType type, RecursiveProperties properties,
IsReferenceCounted_t isRefCounted,
TypeExpansionContext forExpansion)
: NonTrivialLoadableTypeLowering(type, properties, isRefCounted,
forExpansion) {}
SILValue emitLoweredCopyValue(SILBuilder &B, SILLocation loc,
SILValue value,
TypeExpansionKind style) const override {
return emitCopyValue(B, loc, value);
}
void emitLoweredDestroyValue(SILBuilder &B, SILLocation loc, SILValue value,
TypeExpansionKind style) const override {
emitDestroyValue(B, loc, value);
}
};
/// A class for reference types, which are all non-trivial but still
/// loadable.
class ReferenceTypeLowering : public LeafLoadableTypeLowering {
public:
ReferenceTypeLowering(SILType type, TypeExpansionContext forExpansion)
: LeafLoadableTypeLowering(type, RecursiveProperties::forReference(),
IsReferenceCounted, forExpansion) {}
SILValue emitCopyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (isa<FunctionRefInst>(value) || isa<DynamicFunctionRefInst>(value) ||
isa<PreviousDynamicFunctionRefInst>(value))
return value;
if (B.getFunction().hasOwnership())
return B.createCopyValue(loc, value);
B.createStrongRetain(loc, value, B.getDefaultAtomicity());
return value;
}
void emitDestroyValue(SILBuilder &B, SILLocation loc,
SILValue value) const override {
if (B.getFunction().hasOwnership()) {
B.createDestroyValue(loc, value);