-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenCast.cpp
1117 lines (978 loc) · 42 KB
/
GenCast.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
//===--- GenCast.cpp - Swift IR Generation for dynamic casts --------------===//
//
// 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 dynamic casts.
//
//===----------------------------------------------------------------------===//
#include "GenCast.h"
#include "Explosion.h"
#include "GenEnum.h"
#include "GenExistential.h"
#include "GenHeap.h"
#include "GenProto.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "MetadataRequest.h"
#include "TypeInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Module.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/DynamicCasts.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/ABI/MetadataValues.h"
using namespace swift;
using namespace irgen;
/// Compute the flags to pass to swift_dynamicCast.
static DynamicCastFlags getDynamicCastFlags(CastConsumptionKind consumptionKind,
CheckedCastMode mode) {
DynamicCastFlags flags = DynamicCastFlags::Default;
if (mode == CheckedCastMode::Unconditional)
flags |= DynamicCastFlags::Unconditional;
if (shouldDestroyOnFailure(consumptionKind))
flags |= DynamicCastFlags::DestroyOnFailure;
if (shouldTakeOnSuccess(consumptionKind))
flags |= DynamicCastFlags::TakeOnSuccess;
return flags;
}
/// Emit a checked cast, starting with a value in memory.
llvm::Value *irgen::emitCheckedCast(IRGenFunction &IGF,
Address src,
CanType srcType,
Address dest,
CanType targetType,
CastConsumptionKind consumptionKind,
CheckedCastMode mode) {
// TODO: attempt to specialize this based on the known types.
DynamicCastFlags flags = getDynamicCastFlags(consumptionKind, mode);
// Cast both addresses to opaque pointer type.
dest = IGF.Builder.CreateElementBitCast(dest, IGF.IGM.OpaqueTy);
src = IGF.Builder.CreateElementBitCast(src, IGF.IGM.OpaqueTy);
// Load type metadata for the source's static type and the target type.
llvm::Value *srcMetadata = IGF.emitTypeMetadataRef(srcType);
llvm::Value *targetMetadata = IGF.emitTypeMetadataRef(targetType);
llvm::Value *args[] = {
dest.getAddress(), src.getAddress(),
srcMetadata, targetMetadata,
IGF.IGM.getSize(Size(unsigned(flags)))
};
auto call =
IGF.Builder.CreateCall(IGF.IGM.getDynamicCastFunctionPointer(), args);
call->setDoesNotThrow();
return call;
}
FailableCastResult irgen::emitClassIdenticalCast(IRGenFunction &IGF,
llvm::Value *from,
SILType fromType,
SILType toType) {
// Check metatype objects directly. Don't try to find their meta-metatype.
auto isMetatype = false;
if (auto metaType = toType.getAs<MetatypeType>()) {
isMetatype = true;
assert(metaType->getRepresentation() != MetatypeRepresentation::ObjC &&
"not implemented");
toType = IGF.IGM.getLoweredType(metaType.getInstanceType());
}
// Emit a reference to the heap metadata for the target type.
// If we're allowed to do a conservative check, try to just use the
// global class symbol. If the class has been re-allocated, this
// might not be the heap metadata actually in use, and hence the
// test might fail; but it's a much faster check.
// TODO: use ObjC class references
llvm::Value *targetMetadata;
if ((targetMetadata =
tryEmitConstantHeapMetadataRef(IGF.IGM, toType.getASTType(),
/*allowUninitialized*/ false))) {
// ok
} else {
targetMetadata
= emitClassHeapMetadataRef(IGF, toType.getASTType(),
MetadataValueType::ObjCClass,
MetadataState::Complete,
/*allowUninitialized*/ false);
}
// Handle checking a metatype object's type by directly comparing the address
// of the metatype value to the subclass's static metatype instance.
//
// %1 = value_metatype $Super.Type, %0 : $A
// checked_cast_br [exact] Super.Type in %1 : $Super.Type to $Sub.Type
// =>
// icmp eq %1, @metadata.Sub
llvm::Value *objectMetadata = isMetatype ? from :
emitHeapMetadataRefForHeapObject(IGF, from, fromType);
objectMetadata = IGF.Builder.CreateBitCast(objectMetadata,
targetMetadata->getType());
llvm::Value *cond = IGF.Builder.CreateICmpEQ(objectMetadata, targetMetadata);
return {cond, from};
}
/// Returns an ArrayRef with the set of arguments to pass to a dynamic cast call.
///
/// `argsBuf` should be passed in as a reference to an array with three nullptr
/// values at the end. These will be dropped from the return ArrayRef for a
/// conditional cast, or filled in with source location arguments for an
/// unconditional cast.
template<unsigned n>
static ArrayRef<llvm::Value*>
getDynamicCastArguments(IRGenFunction &IGF,
llvm::Value *(&argsBuf)[n], CheckedCastMode mode
/*TODO , SILLocation location*/)
{
switch (mode) {
case CheckedCastMode::Unconditional:
// TODO: Pass along location info if available for unconditional casts, so
// that the runtime error for a failed cast can report the source of the
// error from user code.
argsBuf[n-3] = llvm::ConstantPointerNull::get(IGF.IGM.Int8PtrTy);
argsBuf[n-2] = llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0);
argsBuf[n-1] = llvm::ConstantInt::get(IGF.IGM.Int32Ty, 0);
return argsBuf;
case CheckedCastMode::Conditional:
return llvm::ArrayRef(argsBuf, n - 3);
break;
}
llvm_unreachable("covered switch");
}
/// Emit a checked unconditional downcast of a class value.
llvm::Value *irgen::emitClassDowncast(IRGenFunction &IGF, llvm::Value *from,
CanType toType, CheckedCastMode mode) {
// Emit the value we're casting from.
if (from->getType() != IGF.IGM.Int8PtrTy)
from = IGF.Builder.CreateBitOrPointerCast(from, IGF.IGM.Int8PtrTy);
// Emit a reference to the metadata and figure out what cast
// function to use.
llvm::Value *metadataRef;
FunctionPointer castFn;
// If true, the target class is not known at compile time because it is a
// class-bounded archetype or the dynamic Self type.
bool nonSpecificClass = false;
// Get the best known type information about the destination type.
ClassDecl *destClass = nullptr;
if (auto archetypeTy = dyn_cast<ArchetypeType>(toType)) {
nonSpecificClass = true;
if (auto superclassTy = archetypeTy->getSuperclass())
destClass = superclassTy->getClassOrBoundGenericClass();
} else if (auto selfTy = dyn_cast<DynamicSelfType>(toType)) {
nonSpecificClass = true;
destClass = selfTy->getSelfType()->getClassOrBoundGenericClass();
} else {
destClass = toType.getClassOrBoundGenericClass();
assert(destClass != nullptr);
}
// If the destination type is known to have a Swift-compatible
// implementation, use the most specific entrypoint.
if (destClass && destClass->hasKnownSwiftImplementation()) {
metadataRef = IGF.emitTypeMetadataRef(toType);
switch (mode) {
case CheckedCastMode::Unconditional:
castFn = IGF.IGM.getDynamicCastClassUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn = IGF.IGM.getDynamicCastClassFunctionPointer();
break;
}
// If the destination type is a CF type or a non-specific
// class-bounded archetype, use the most general cast entrypoint.
} else if (nonSpecificClass ||
destClass->getForeignClassKind()==ClassDecl::ForeignKind::CFType) {
metadataRef = IGF.emitTypeMetadataRef(toType);
switch (mode) {
case CheckedCastMode::Unconditional:
castFn = IGF.IGM.getDynamicCastUnknownClassUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn = IGF.IGM.getDynamicCastUnknownClassFunctionPointer();
break;
}
// Otherwise, use the ObjC-specific entrypoint.
} else {
metadataRef = emitObjCHeapMetadataRef(IGF, destClass);
switch (mode) {
case CheckedCastMode::Unconditional:
castFn = IGF.IGM.getDynamicCastObjCClassUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn = IGF.IGM.getDynamicCastObjCClassFunctionPointer();
break;
}
}
if (metadataRef->getType() != IGF.IGM.Int8PtrTy)
metadataRef = IGF.Builder.CreateBitCast(metadataRef, IGF.IGM.Int8PtrTy);
// Call the (unconditional) dynamic cast.
llvm::Value *argsBuf[] = {
from,
metadataRef,
nullptr,
nullptr,
nullptr,
};
auto call = IGF.Builder.CreateCall(
castFn, getDynamicCastArguments(IGF, argsBuf, mode));
call->setDoesNotThrow();
llvm::Type *subTy = IGF.getTypeInfoForUnlowered(toType).getStorageType();
return IGF.Builder.CreateBitCast(call, subTy);
}
/// Emit a checked cast of a metatype.
void irgen::emitMetatypeDowncast(IRGenFunction &IGF,
llvm::Value *metatype,
CanMetatypeType toMetatype,
CheckedCastMode mode,
Explosion &ex) {
// Pick a runtime entry point and target metadata based on what kind of
// representation we're casting.
FunctionPointer castFn;
llvm::Value *toMetadata;
switch (toMetatype->getRepresentation()) {
case MetatypeRepresentation::Thick: {
// Get the Swift metadata for the type we're checking.
toMetadata = IGF.emitTypeMetadataRef(toMetatype.getInstanceType());
switch (mode) {
case CheckedCastMode::Unconditional:
castFn = IGF.IGM.getDynamicCastMetatypeUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn = IGF.IGM.getDynamicCastMetatypeFunctionPointer();
break;
}
break;
}
case MetatypeRepresentation::ObjC: {
assert(IGF.IGM.ObjCInterop && "should have objc runtime");
// Get the ObjC metadata for the type we're checking.
toMetadata = emitClassHeapMetadataRef(IGF, toMetatype.getInstanceType(),
MetadataValueType::ObjCClass,
MetadataState::Complete);
switch (mode) {
case CheckedCastMode::Unconditional:
castFn =
IGF.IGM.getDynamicCastObjCClassMetatypeUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn = IGF.IGM.getDynamicCastObjCClassMetatypeFunctionPointer();
break;
}
break;
}
case MetatypeRepresentation::Thin:
llvm_unreachable("not implemented");
}
llvm::Value *argsBuf[] = {
metatype,
toMetadata,
nullptr,
nullptr,
nullptr,
};
auto call = IGF.Builder.CreateCall(
castFn, getDynamicCastArguments(IGF, argsBuf, mode));
call->setDoesNotThrow();
ex.add(call);
}
/// Emit a Protocol* value referencing an ObjC protocol.
llvm::Value *irgen::emitReferenceToObjCProtocol(IRGenFunction &IGF,
ProtocolDecl *proto) {
assert(proto->isObjC() && "not an objc protocol");
// Get the address of the global variable the protocol reference gets
// indirected through.
auto protocolRefAddr =
IGF.IGM.getAddrOfObjCProtocolRef(proto, NotForDefinition);
return IGF.Builder.CreateLoad(protocolRefAddr);
}
/// Emit a helper function to look up \c numProtocols witness tables given
/// a value and a type metadata reference.
///
/// If \p checkClassConstraint is true, we must emit an explicit check that the
/// instance is a class.
///
/// If \p checkSuperclassConstraint is true, we are given an additional parameter
/// with a superclass type in it, and must emit a check that the instance is a
/// subclass of the given class.
///
/// The function's input type is (value, metadataValue, superclass?, protocol...)
/// The function's output type is (value, witnessTable...)
///
/// The value is NULL if the cast failed.
static FunctionPointer
emitExistentialScalarCastFn(IRGenModule &IGM, unsigned numProtocols,
CheckedCastMode mode, bool checkClassConstraint,
bool checkSuperclassConstraint) {
assert(!checkSuperclassConstraint || checkClassConstraint);
// Build the function name.
llvm::SmallString<32> name;
{
llvm::raw_svector_ostream os(name);
os << "dynamic_cast_existential_";
os << numProtocols;
if (checkSuperclassConstraint)
os << "_superclass";
else if (checkClassConstraint)
os << "_class";
switch (mode) {
case CheckedCastMode::Unconditional:
os << "_unconditional";
break;
case CheckedCastMode::Conditional:
os << "_conditional";
break;
}
}
// Build the function type.
llvm::SmallVector<llvm::Type *, 4> argTys;
llvm::SmallVector<llvm::Type *, 4> returnTys;
argTys.push_back(IGM.Int8PtrTy);
argTys.push_back(IGM.TypeMetadataPtrTy);
returnTys.push_back(IGM.Int8PtrTy);
if (checkSuperclassConstraint)
argTys.push_back(IGM.TypeMetadataPtrTy);
for (unsigned i = 0; i < numProtocols; ++i) {
argTys.push_back(IGM.ProtocolDescriptorPtrTy);
returnTys.push_back(IGM.WitnessTablePtrTy);
}
llvm::Type *returnTy = llvm::StructType::get(IGM.getLLVMContext(), returnTys);
auto fn = IGM.getOrCreateHelperFunction(
name, returnTy, argTys, [&](IRGenFunction &IGF) {
Explosion args = IGF.collectParameters();
auto value = args.claimNext();
auto ref = args.claimNext();
auto failBB = IGF.createBasicBlock("fail");
auto conformsToProtocol = IGM.getConformsToProtocolFunctionPointer();
Explosion rets;
rets.add(value);
// Check the class constraint if necessary.
if (checkSuperclassConstraint) {
auto superclassMetadata = args.claimNext();
auto castFn = IGF.IGM.getDynamicCastMetatypeFunctionPointer();
auto castResult =
IGF.Builder.CreateCall(castFn, {ref, superclassMetadata});
// FIXME: Eventually, we may want to throw.
castResult->setDoesNotThrow();
auto isClass = IGF.Builder.CreateICmpNE(
castResult,
llvm::ConstantPointerNull::get(IGF.IGM.TypeMetadataPtrTy));
auto contBB = IGF.createBasicBlock("cont");
IGF.Builder.CreateCondBr(isClass, contBB, failBB);
IGF.Builder.emitBlock(contBB);
} else if (checkClassConstraint) {
auto isClass =
IGF.Builder.CreateCall(IGM.getIsClassTypeFunctionPointer(), ref);
auto contBB = IGF.createBasicBlock("cont");
IGF.Builder.CreateCondBr(isClass, contBB, failBB);
IGF.Builder.emitBlock(contBB);
}
// Look up each protocol conformance we want.
for (unsigned i = 0; i < numProtocols; ++i) {
auto proto = args.claimNext();
auto witness =
IGF.Builder.CreateCall(conformsToProtocol, {ref, proto});
auto isNull = IGF.Builder.CreateICmpEQ(
witness, llvm::ConstantPointerNull::get(IGM.WitnessTablePtrTy));
auto contBB = IGF.createBasicBlock("cont");
IGF.Builder.CreateCondBr(isNull, failBB, contBB);
IGF.Builder.emitBlock(contBB);
rets.add(witness);
}
// If we succeeded, return the witnesses.
IGF.emitScalarReturn(returnTy, rets);
// If we failed, return nil or trap.
IGF.Builder.emitBlock(failBB);
switch (mode) {
case CheckedCastMode::Conditional: {
auto null = llvm::ConstantStruct::getNullValue(returnTy);
IGF.Builder.CreateRet(null);
break;
}
case CheckedCastMode::Unconditional: {
IGF.emitTrap("type cast failed", /*EmitUnreachable=*/true);
break;
}
}
});
auto fnType = llvm::FunctionType::get(returnTy, argTys, false);
auto sig = Signature(fnType, {}, IGM.DefaultCC);
return FunctionPointer::forDirect(FunctionPointer::Kind::Function, fn,
nullptr, sig);
}
llvm::Value *irgen::emitMetatypeToAnyObjectDowncast(IRGenFunction &IGF,
llvm::Value *metatypeValue,
CanAnyMetatypeType type,
CheckedCastMode mode) {
// If ObjC interop is enabled, casting a metatype to AnyObject succeeds
// if the metatype is for a class.
if (!IGF.IGM.ObjCInterop)
return nullptr;
switch (type->getRepresentation()) {
case MetatypeRepresentation::ObjC:
// Metatypes that can be represented as ObjC trivially cast to AnyObject.
return IGF.Builder.CreateBitCast(metatypeValue, IGF.IGM.ObjCPtrTy);
case MetatypeRepresentation::Thin:
// Metatypes that can be thin would never be classes.
// TODO: Final class metatypes could in principle be thin.
assert(!type.getInstanceType()->mayHaveSuperclass()
&& "classes should not have thin metatypes (yet)");
return nullptr;
case MetatypeRepresentation::Thick: {
auto instanceTy = type.getInstanceType();
// Is the type obviously a class?
if (instanceTy->mayHaveSuperclass()) {
// Get the ObjC metadata for the class.
auto heapMetadata = emitClassHeapMetadataRefForMetatype(IGF,metatypeValue,
instanceTy);
return IGF.Builder.CreateBitCast(heapMetadata, IGF.IGM.ObjCPtrTy);
}
// If it's not a class, we can't handle it here
if (!isa<ArchetypeType>(instanceTy) && !isa<ExistentialMetatypeType>(type)) {
return nullptr;
}
// Ask the runtime whether this is class metadata.
FunctionPointer castFn;
switch (mode) {
case CheckedCastMode::Conditional:
castFn =
IGF.IGM.getDynamicCastMetatypeToObjectConditionalFunctionPointer();
break;
case CheckedCastMode::Unconditional:
castFn =
IGF.IGM.getDynamicCastMetatypeToObjectUnconditionalFunctionPointer();
break;
}
llvm::Value *argsBuf[] = {
metatypeValue,
nullptr,
nullptr,
nullptr,
};
auto call = IGF.Builder.CreateCall(
castFn, getDynamicCastArguments(IGF, argsBuf, mode));
return call;
}
}
llvm_unreachable("invalid metatype representation");
}
/// Emit a checked cast to a protocol or protocol composition.
void irgen::emitScalarExistentialDowncast(
IRGenFunction &IGF, llvm::Value *value, SILType srcType, SILType destType,
CheckedCastMode mode, std::optional<MetatypeRepresentation> metatypeKind,
Explosion &ex) {
auto srcInstanceType = srcType.getASTType();
auto destInstanceType = destType.getASTType();
while (auto metatypeType = dyn_cast<ExistentialMetatypeType>(
destInstanceType)) {
destInstanceType = metatypeType.getInstanceType();
srcInstanceType = cast<AnyMetatypeType>(srcInstanceType).getInstanceType();
}
auto layout = destInstanceType.getExistentialLayout();
// Look up witness tables for the protocols that need them and get
// references to the ObjC Protocol* values for the objc protocols.
SmallVector<llvm::Value*, 4> objcProtos;
SmallVector<llvm::Value*, 4> witnessTableProtos;
bool hasClassConstraint = layout.requiresClass();
bool hasClassConstraintByProtocol = false;
bool hasSuperclassConstraint = bool(layout.explicitSuperclass);
for (auto protoDecl : layout.getProtocols()) {
// If the protocol introduces a class constraint, track whether we need
// to check for it independent of protocol witnesses.
if (protoDecl->requiresClass()) {
assert(hasClassConstraint);
hasClassConstraintByProtocol = true;
}
if (Lowering::TypeConverter::protocolRequiresWitnessTable(protoDecl)) {
auto descriptor = IGF.IGM.getAddrOfProtocolDescriptor(protoDecl);
witnessTableProtos.push_back(descriptor);
}
if (protoDecl->isObjC())
objcProtos.push_back(emitReferenceToObjCProtocol(IGF, protoDecl));
}
llvm::Type *resultType;
if (metatypeKind) {
switch (*metatypeKind) {
case MetatypeRepresentation::Thin:
llvm_unreachable("can't cast to thin metatype");
case MetatypeRepresentation::Thick:
resultType = IGF.IGM.TypeMetadataPtrTy;
break;
case MetatypeRepresentation::ObjC:
resultType = IGF.IGM.ObjCClassPtrTy;
break;
}
} else {
auto schema = IGF.getTypeInfo(destType).getSchema();
resultType = schema[0].getScalarType();
}
// The source of a scalar cast is statically known to be a class or a
// metatype, so we only have to check the class constraint in two cases:
//
// 1) The destination type has a superclass constraint that is
// more derived than what the source type is known to be.
//
// 2) We are casting between metatypes, in which case the source might
// be a non-class metatype.
bool checkClassConstraint = false;
if ((bool)metatypeKind &&
hasClassConstraint &&
!hasClassConstraintByProtocol &&
!srcInstanceType->mayHaveSuperclass())
checkClassConstraint = true;
// If the source has an equal or more derived superclass constraint than
// the destination, we can elide the superclass check.
//
// Note that destInstanceType is always an existential type, so calling
// getSuperclass() returns the superclass constraint of the existential,
// not the superclass of some concrete class.
bool checkSuperclassConstraint = false;
if (hasSuperclassConstraint) {
Type srcSuperclassType = srcInstanceType;
if (srcSuperclassType->isExistentialType()) {
srcSuperclassType = srcSuperclassType->getSuperclass();
// Look for an AnyObject superclass (getSuperclass() returns nil).
if (!srcSuperclassType && srcInstanceType->isClassExistentialType())
checkSuperclassConstraint = true;
}
if (srcSuperclassType) {
checkSuperclassConstraint =
!destInstanceType->getSuperclass()->isExactSuperclassOf(
srcSuperclassType);
}
}
if (checkSuperclassConstraint)
checkClassConstraint = true;
llvm::Value *resultValue = value;
// If we don't have anything we really need to check, then trivially succeed.
if (objcProtos.empty() && witnessTableProtos.empty() &&
!checkClassConstraint) {
resultValue = IGF.Builder.CreateBitCast(value, resultType);
ex.add(resultValue);
return;
}
// Check the ObjC protocol conformances if there were any.
llvm::Value *objcCast = nullptr;
if (!objcProtos.empty()) {
// Get the ObjC instance or class object to check for these conformances.
llvm::Value *objcObject;
if (metatypeKind) {
switch (*metatypeKind) {
case MetatypeRepresentation::Thin:
llvm_unreachable("can't cast to thin metatype");
case MetatypeRepresentation::Thick: {
// The metadata might be for a non-class type, which wouldn't have
// an ObjC class object.
objcObject = nullptr;
break;
}
case MetatypeRepresentation::ObjC:
// Metatype is already an ObjC object.
objcObject = value;
break;
}
} else {
// Class instance is already an ObjC object.
objcObject = value;
}
if (objcObject)
objcObject = IGF.Builder.CreateBitCast(objcObject,
IGF.IGM.UnknownRefCountedPtrTy);
// Pick the cast function based on the cast mode and on whether we're
// casting a Swift metatype or ObjC object.
FunctionPointer castFn;
switch (mode) {
case CheckedCastMode::Unconditional:
castFn =
objcObject
? IGF.IGM.getDynamicCastObjCProtocolUnconditionalFunctionPointer()
: IGF.IGM
.getDynamicCastTypeToObjCProtocolUnconditionalFunctionPointer();
break;
case CheckedCastMode::Conditional:
castFn =
objcObject
? IGF.IGM.getDynamicCastObjCProtocolConditionalFunctionPointer()
: IGF.IGM
.getDynamicCastTypeToObjCProtocolConditionalFunctionPointer();
break;
}
llvm::Value *objcCastObject = objcObject ? objcObject : value;
Address protoRefsBuf = IGF.createAlloca(
llvm::ArrayType::get(IGF.IGM.Int8PtrTy,
objcProtos.size()),
IGF.IGM.getPointerAlignment(),
"objc_protocols");
protoRefsBuf =
IGF.Builder.CreateElementBitCast(protoRefsBuf, IGF.IGM.Int8PtrTy);
for (unsigned index : indices(objcProtos)) {
Address protoRefSlot = IGF.Builder.CreateConstArrayGEP(
protoRefsBuf, index,
IGF.IGM.getPointerSize());
IGF.Builder.CreateStore(objcProtos[index], protoRefSlot);
++index;
}
llvm::Value *argsBuf[] = {
objcCastObject,
IGF.IGM.getSize(Size(objcProtos.size())),
protoRefsBuf.getAddress(),
nullptr,
nullptr,
nullptr,
};
auto call = IGF.Builder.CreateCall(
castFn, getDynamicCastArguments(IGF, argsBuf, mode));
objcCast = call;
resultValue = IGF.Builder.CreateBitCast(objcCast, resultType);
}
// If we don't need to look up any witness tables, we're done.
if (witnessTableProtos.empty() && !checkClassConstraint) {
ex.add(resultValue);
return;
}
// If we're doing a conditional cast, and the ObjC protocol checks failed,
// then the cast is done.
std::optional<ConditionalDominanceScope> condition;
llvm::BasicBlock *origBB = nullptr, *successBB = nullptr, *contBB = nullptr;
if (!objcProtos.empty()) {
switch (mode) {
case CheckedCastMode::Unconditional:
break;
case CheckedCastMode::Conditional: {
origBB = IGF.Builder.GetInsertBlock();
successBB = IGF.createBasicBlock("success");
contBB = IGF.createBasicBlock("cont");
auto isNull = IGF.Builder.CreateICmpEQ(objcCast,
llvm::ConstantPointerNull::get(
cast<llvm::PointerType>(objcCast->getType())));
IGF.Builder.CreateCondBr(isNull, contBB, successBB);
IGF.Builder.emitBlock(successBB);
condition.emplace(IGF);
}
}
}
// Get the Swift type metadata for the type.
llvm::Value *metadataValue;
if (metatypeKind) {
switch (*metatypeKind) {
case MetatypeRepresentation::Thin:
llvm_unreachable("can't cast to thin metatype");
case MetatypeRepresentation::Thick:
// The value is already a native metatype.
metadataValue = value;
break;
case MetatypeRepresentation::ObjC:
// Get the type metadata from the ObjC class, which may be a wrapper.
metadataValue = emitObjCMetadataRefForMetadata(IGF, value);
}
} else {
// Get the type metadata for the instance.
metadataValue = emitDynamicTypeOfHeapObject(IGF, value,
MetatypeRepresentation::Thick,
srcType);
}
// Look up witness tables for the protocols that need them.
auto fn = emitExistentialScalarCastFn(IGF.IGM,
witnessTableProtos.size(),
mode,
checkClassConstraint,
checkSuperclassConstraint);
llvm::SmallVector<llvm::Value *, 4> args;
if (resultValue->getType() != IGF.IGM.Int8PtrTy)
resultValue = IGF.Builder.CreateBitCast(resultValue, IGF.IGM.Int8PtrTy);
args.push_back(resultValue);
args.push_back(metadataValue);
if (checkSuperclassConstraint)
args.push_back(IGF.emitTypeMetadataRef(CanType(layout.explicitSuperclass)));
for (auto proto : witnessTableProtos)
args.push_back(proto);
auto valueAndWitnessTables = IGF.Builder.CreateCall(fn, args);
resultValue = IGF.Builder.CreateExtractValue(valueAndWitnessTables, 0);
if (resultValue->getType() != resultType)
resultValue = IGF.Builder.CreateBitCast(resultValue, resultType);
ex.add(resultValue);
for (unsigned i = 0, e = witnessTableProtos.size(); i < e; ++i) {
auto wt = IGF.Builder.CreateExtractValue(valueAndWitnessTables, i + 1);
ex.add(wt);
}
// If we had conditional ObjC checks, join the failure paths.
if (contBB) {
condition.reset();
IGF.Builder.CreateBr(contBB);
IGF.Builder.emitBlock(contBB);
// Return null on the failure path.
Explosion successEx = std::move(ex);
ex.reset();
while (!successEx.empty()) {
auto successVal = successEx.claimNext();
auto failureVal = llvm::Constant::getNullValue(successVal->getType());
auto phi = IGF.Builder.CreatePHI(successVal->getType(), 2);
phi->addIncoming(successVal, successBB);
phi->addIncoming(failureVal, origBB);
ex.add(phi);
}
}
}
/// Emit a checked cast of a scalar value.
///
/// This is not just an implementation of emitCheckedCast for scalar types;
/// it imposes strict restrictions on the source and target types that ensure
/// that the actual value isn't changed in any way, thus preserving its
/// reference identity.
///
/// These restrictions are set by \c canSILUseScalarCheckedCastInstructions.
/// Essentially, both the source and target types must be one of:
/// - a (possibly generic) concrete class type,
/// - a class-bounded archetype,
/// - a class-bounded existential,
/// - a concrete metatype, or
/// - an existential metatype.
///
/// Furthermore, if the target type is a metatype, the source type must be
/// a metatype. This restriction isn't obviously necessary; it's just that
/// the runtime support for checking that an object instance is a metatype
/// isn't exposed.
void irgen::emitScalarCheckedCast(IRGenFunction &IGF,
Explosion &value,
SILType sourceLoweredType,
CanType sourceFormalType,
SILType targetLoweredType,
CanType targetFormalType,
CheckedCastMode mode,
Explosion &out) {
assert(sourceLoweredType.isObject());
assert(targetLoweredType.isObject());
llvm::BasicBlock *nilCheckBB = nullptr;
llvm::BasicBlock *nilMergeBB = nullptr;
// Merge the nil check and return the merged result: either nil or the value.
auto returnNilCheckedResult = [&](IRBuilder &Builder,
Explosion &nonNilResult) {
if (nilCheckBB) {
auto notNilBB = Builder.GetInsertBlock();
Builder.CreateBr(nilMergeBB);
Builder.emitBlock(nilMergeBB);
// Insert result phi.
Explosion result;
while (!nonNilResult.empty()) {
auto val = nonNilResult.claimNext();
auto valTy = cast<llvm::PointerType>(val->getType());
auto nil = llvm::ConstantPointerNull::get(valTy);
auto phi = Builder.CreatePHI(valTy, 2);
phi->addIncoming(nil, nilCheckBB);
phi->addIncoming(val, notNilBB);
result.add(phi);
}
out = std::move(result);
} else {
out = std::move(nonNilResult);
}
};
bool sourceWrappedInOptional = false;
std::optional<ConditionalDominanceScope> domScope;
if (auto sourceOptObjectType = sourceLoweredType.getOptionalObjectType()) {
// Translate the value from an enum representation to a possibly-null
// representation. Note that we assume that this projection is safe
// for the particular case of an optional class-reference or metatype
// value.
Explosion optValue;
auto someDecl = IGF.IGM.Context.getOptionalSomeDecl();
emitProjectLoadableEnum(IGF, sourceLoweredType, value, someDecl, optValue);
assert(value.empty());
value = std::move(optValue);
sourceLoweredType = sourceOptObjectType;
sourceFormalType = sourceFormalType.getOptionalObjectType();
sourceWrappedInOptional = true;
// We need a null-check because the runtime function can't handle null in
// some of the cases.
if (targetLoweredType.isExistentialType()) {
auto &Builder = IGF.Builder;
auto val = value.getAll()[0];
auto isNotNil = Builder.CreateICmpNE(
val, llvm::ConstantPointerNull::get(
cast<llvm::PointerType>(val->getType())));
auto *isNotNilContBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
nilMergeBB = llvm::BasicBlock::Create(IGF.IGM.getLLVMContext());
nilCheckBB = Builder.GetInsertBlock();
Builder.CreateCondBr(isNotNil, isNotNilContBB, nilMergeBB);
Builder.emitBlock(isNotNilContBB);
domScope.emplace(IGF);
}
}
// If the source value is a metatype, either do a metatype-to-metatype
// cast or cast it to an object instance and continue.
if (auto sourceMetatype = sourceLoweredType.getAs<AnyMetatypeType>()) {
llvm::Value *metatypeVal = nullptr;
if (sourceMetatype->getRepresentation() != MetatypeRepresentation::Thin)
metatypeVal = value.claimNext();
// If the metatype is existential, there may be witness tables in the
// value, which we don't need.
// TODO: In existential-to-existential casts, we should carry over common
// witness tables from the source to the destination.
(void)value.claimAll();
SmallVector<ProtocolDecl*, 1> protocols;
// Casts to existential metatypes.
if (auto existential = targetLoweredType.getAs<ExistentialMetatypeType>()) {
emitScalarExistentialDowncast(IGF, metatypeVal, sourceLoweredType,
targetLoweredType, mode,
existential->getRepresentation(),
out);
return;
// Casts to concrete metatypes.
} else if (auto destMetaType = targetLoweredType.getAs<MetatypeType>()) {
emitMetatypeDowncast(IGF, metatypeVal, destMetaType, mode, out);
return;
}
// Otherwise, this is a metatype-to-object cast.
assert(targetLoweredType.isAnyClassReferenceType());
// Can we convert the metatype value to AnyObject using Obj-C machinery?
llvm::Value *object =
emitMetatypeToAnyObjectDowncast(IGF, metatypeVal, sourceMetatype, mode);
if (object == nullptr) {
// Obj-C cast routine failed, use swift_dynamicCast instead
if (sourceMetatype->getRepresentation() == MetatypeRepresentation::Thin
|| metatypeVal == nullptr) {
// Earlier stages *should* never generate a checked cast with a thin metatype argument.
// TODO: Move this assertion up to apply to all checked cast operations.
// In assert builds, enforce this by failing here:
assert(false && "Invalid SIL: General checked_cast_br cannot have thin argument");
// In non-assert builds, stay compatible with previous behavior by emitting a null load.
object = llvm::ConstantPointerNull::get(IGF.IGM.ObjCPtrTy);
} else {
Address src = IGF.createAlloca(metatypeVal->getType(),
IGF.IGM.getPointerAlignment(),
"castSrc");
IGF.Builder.CreateStore(metatypeVal, src);
llvm::PointerType *destPtrType = IGF.IGM.getStoragePointerType(targetLoweredType);
Address dest = IGF.createAlloca(destPtrType,
IGF.IGM.getPointerAlignment(),
"castDest");
IGF.Builder.CreateStore(llvm::ConstantPointerNull::get(destPtrType), dest);
llvm::Value *success = emitCheckedCast(IGF,
src, sourceFormalType,
dest, targetFormalType,
CastConsumptionKind::TakeAlways,
mode);
llvm::Value *successResult = IGF.Builder.CreateLoad(dest);
llvm::Value *failureResult = llvm::ConstantPointerNull::get(destPtrType);
llvm::Value *result = IGF.Builder.CreateSelect(success, successResult, failureResult);
object = std::move(result);
}
}
sourceFormalType = IGF.IGM.Context.getAnyObjectType();
sourceLoweredType = SILType::getPrimitiveObjectType(sourceFormalType);
// Continue, pretending that the source value was an (optional) value.
Explosion newValue;
newValue.add(object);
value = std::move(newValue);
}
assert(!targetLoweredType.is<AnyMetatypeType>() &&
"scalar cast of class reference to metatype is unimplemented");
// If the source type is existential, project out the class pointer.
//