-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathDynamicCast.cpp
2649 lines (2398 loc) · 102 KB
/
DynamicCast.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
//===--- DynamicCast.cpp - Swift Language Dynamic Casting Support ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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
//
//===----------------------------------------------------------------------===//
//
// Implementations of the dynamic cast runtime functions.
//
//===----------------------------------------------------------------------===//
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ErrorObject.h"
#include "Private.h"
#include "SwiftHashableSupport.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Bincompat.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/ExistentialContainer.h"
#include "swift/Runtime/HeapObject.h"
#if SWIFT_OBJC_INTEROP
#include "swift/Runtime/ObjCBridge.h"
#include "SwiftObject.h"
#include "SwiftValue.h"
#endif
using namespace swift;
using namespace hashable_support;
//
// The top-level driver code directly handles the most general cases
// (identity casts, _ObjectiveCBridgeable, _SwiftValue boxing) and
// recursively unwraps source and/or destination as appropriate.
// It calls "tryCastToXyz" functions to perform tailored operations
// for a particular destination type.
//
// For each kind of destination, there is a "tryCastToXyz" that
// accepts a source value and attempts to fit it into a destination
// storage location. This function should assume that:
// * The source and destination types are _not_ identical.
// * The destination is of the expected type.
// * The source is already fully unwrapped. If the source is an
// Existential or Optional that you cannot handle directly, do _not_
// try to unwrap it. Just return failure and you will get called
// again with the unwrapped source.
//
// Each such function accepts the following arguments:
// * Destination location and type
// * Source value address and type
// * References to the types that will be used to report failure.
// The function can update these with specific failing types
// to improve the reported failure.
// * Bool indicating whether the compiler has asked us to "take" the
// value instead of copying.
// * Bool indicating whether it's okay to do type checks lazily on later
// access (this is permitted only for unconditional casts that will
// abort the program on failure anyway).
//
// The return value is one of the following:
// * Failure. In this case, the tryCastFunction should do nothing; your
// caller will either try another strategy or report the failure and
// do any necessary cleanup.
// * Success via "copy". You successfully copied the source value.
// * Success via "take". If "take" was requested and you can do so cheaply,
// perform the take and return SuccessViaTake. If "take" is not cheap, you
// should copy and return SuccessViaCopy. Top-level code will detect this
// and take care of destroying the source for you.
//
enum class DynamicCastResult {
Failure, /// The cast attempt "failed" (did nothing).
SuccessViaCopy, /// Cast succeeded, source is still valid.
SuccessViaTake, /// Cast succeeded, source is invalid
};
static bool isSuccess(DynamicCastResult result) {
return result != DynamicCastResult::Failure;
}
// All of our `tryCastXyz` functions have the following signature.
typedef DynamicCastResult (tryCastFunctionType)(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances
);
// Forward-declare the main top-level `tryCast()` function
static tryCastFunctionType tryCast;
/// Nominal type descriptor for Swift.AnyHashable
extern "C" const StructDescriptor STRUCT_TYPE_DESCR_SYM(s11AnyHashable);
/// Nominal type descriptor for Swift.__SwiftValue
//extern "C" const StructDescriptor STRUCT_TYPE_DESCR_SYM(s12__SwiftValue);
/// Nominal type descriptor for Swift.Array.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(Sa);
/// Nominal type descriptor for Swift.Dictionary.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SD);
/// Nominal type descriptor for Swift.Set.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(Sh);
/// Nominal type descriptor for Swift.String.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SS);
/// This issues a fatal error or warning if the srcValue contains a null object
/// reference. It is used when the srcType is a non-nullable reference type, in
/// which case it is dangerous to continue with a null reference. The null
/// reference is returned if we're operating in backwards-compatibility mode, so
/// callers still have to check for null.
static HeapObject * getNonNullSrcObject(OpaqueValue *srcValue,
const Metadata *srcType,
const Metadata *destType) {
auto object = *reinterpret_cast<HeapObject **>(srcValue);
if (LLVM_LIKELY(object != nullptr)) {
return object;
}
std::string srcTypeName = nameForMetadata(srcType);
std::string destTypeName = nameForMetadata(destType);
const char * const msg = "Found a null pointer in a value of type '%s' (%p)."
" Non-Optional values are not allowed to hold null pointers."
" (Detected while casting to '%s' (%p))%s\n";
if (runtime::bincompat::useLegacyPermissiveObjCNullSemanticsInCasting()) {
// In backwards compatibility mode, this code will warn and return the null
// reference anyway: If you examine the calls to the function, you'll see
// that most callers fail the cast in that case, but a few casts (e.g., with
// Obj-C or CF destination type) sill succeed in that case. This is
// dangerous, but necessary for compatibility.
swift::warning(/* flags = */ 0, msg,
srcTypeName.c_str(), srcType,
destTypeName.c_str(), destType,
": Continuing with null object, but expect problems later.");
} else {
// By default, Swift 5.4 and later issue a fatal error.
swift::fatalError(/* flags = */ 0, msg,
srcTypeName.c_str(), srcType,
destTypeName.c_str(), destType,
"");
}
return object;
}
/******************************************************************************/
/******************************* Bridge Helpers *******************************/
/******************************************************************************/
#define _bridgeAnythingToObjectiveC \
MANGLE_SYM(s27_bridgeAnythingToObjectiveCyyXlxlF)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
HeapObject *_bridgeAnythingToObjectiveC(
OpaqueValue *src, const Metadata *srcType);
#if SWIFT_OBJC_INTEROP
SWIFT_RUNTIME_EXPORT
id swift_dynamicCastMetatypeToObjectConditional(const Metadata *metatype);
#endif
// protocol _ObjectiveCBridgeable {
struct _ObjectiveCBridgeableWitnessTable : WitnessTable {
#define _protocolWitnessSignedPointer(n) \
__ptrauth_swift_protocol_witness_function_pointer(SpecialPointerAuthDiscriminators::n##Discriminator) n
static_assert(WitnessTableFirstRequirementOffset == 1,
"Witness table layout changed");
// associatedtype _ObjectiveCType : class
void *_ObjectiveCType;
// func _bridgeToObjectiveC() -> _ObjectiveCType
SWIFT_CC(swift)
HeapObject *(*_protocolWitnessSignedPointer(bridgeToObjectiveC))(
SWIFT_CONTEXT OpaqueValue *self, const Metadata *Self,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _forceBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?)
SWIFT_CC(swift)
void (*_protocolWitnessSignedPointer(forceBridgeFromObjectiveC))(
HeapObject *sourceValue,
OpaqueValue *result,
SWIFT_CONTEXT const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _conditionallyBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?) -> Bool
SWIFT_CC(swift)
bool (*_protocolWitnessSignedPointer(conditionallyBridgeFromObjectiveC))(
HeapObject *sourceValue,
OpaqueValue *result,
SWIFT_CONTEXT const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
};
// }
extern "C" const ProtocolDescriptor
PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable);
static const _ObjectiveCBridgeableWitnessTable *
findBridgeWitness(const Metadata *T) {
auto w = swift_conformsToProtocolCommon(
T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable));
return reinterpret_cast<const _ObjectiveCBridgeableWitnessTable *>(w);
}
/// Retrieve the bridged Objective-C type for the given type that
/// conforms to \c _ObjectiveCBridgeable.
MetadataResponse
_getBridgedObjectiveCType(
MetadataRequest request,
const Metadata *conformingType,
const _ObjectiveCBridgeableWitnessTable *wtable)
{
// FIXME: Can we directly reference the descriptor somehow?
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto assocTypeRequirement = protocol->getRequirements().begin();
assert(assocTypeRequirement->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
auto mutableWTable = (WitnessTable *)wtable;
return swift_getAssociatedTypeWitness(
request, mutableWTable, conformingType,
protocol->getRequirementBaseDescriptor(),
assocTypeRequirement);
}
/// Dynamic cast from a class type to a value type that conforms to the
/// _ObjectiveCBridgeable, first by dynamic casting the object to the
/// class to which the value type is bridged, and then bridging
/// from that object to the value type via the witness table.
///
/// Caveat: Despite the name, this is also used to bridge pure Swift
/// classes to Swift value types even when Obj-C is not being used.
static DynamicCastResult
_tryCastFromClassToObjCBridgeable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType, void *srcObject,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks,
const _ObjectiveCBridgeableWitnessTable *destBridgeWitness,
const Metadata *targetBridgeClass)
{
// 2. Allocate a T? to receive the bridge result.
// The extra byte is for the tag.
auto targetSize = destType->getValueWitnesses()->getSize() + 1;
auto targetAlignMask = destType->getValueWitnesses()->getAlignmentMask();
// Object that frees a buffer when it goes out of scope.
struct FreeBuffer {
void *Buffer = nullptr;
size_t size, alignMask;
FreeBuffer(size_t size, size_t alignMask) :
size(size), alignMask(alignMask) {}
~FreeBuffer() {
if (Buffer)
swift_slowDealloc(Buffer, size, alignMask);
}
} freeBuffer{targetSize, targetAlignMask};
// The extra byte is for the tag on the T?
const std::size_t inlineValueSize = 3 * sizeof(void*);
alignas(MaximumAlignment) char inlineBuffer[inlineValueSize + 1];
void *optDestBuffer;
if (destType->getValueWitnesses()->getStride() <= inlineValueSize) {
// Use the inline buffer.
optDestBuffer = inlineBuffer;
} else {
// Allocate a buffer.
optDestBuffer = swift_slowAlloc(targetSize, targetAlignMask);
freeBuffer.Buffer = optDestBuffer;
}
// Initialize the buffer as an empty optional.
destType->vw_storeEnumTagSinglePayload((OpaqueValue *)optDestBuffer,
1, 1);
// 3. Bridge into the T? (Effectively a copy operation.)
bool success;
if (mayDeferChecks) {
destBridgeWitness->forceBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
destType, destType, destBridgeWitness);
success = true;
} else {
success = destBridgeWitness->conditionallyBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
destType, destType, destBridgeWitness);
}
// If we succeeded, then take the value from the temp buffer.
if (success) {
destType->vw_initializeWithTake(destLocation, (OpaqueValue *)optDestBuffer);
// Bridge above is effectively a copy, so overall we're a copy.
return DynamicCastResult::SuccessViaCopy;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastFromClassToObjCBridgeable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
// We need the _ObjectiveCBridgeable conformance for the target
auto destBridgeWitness = findBridgeWitness(destType);
if (destBridgeWitness == nullptr) {
return DynamicCastResult::Failure;
}
// 1. Soundness check whether the source object can cast to the
// type expected by the target.
auto targetBridgedClass =
_getBridgedObjectiveCType(MetadataState::Complete, destType,
destBridgeWitness).Value;
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// Note: srcObject can be null here in compatibility mode
if (nullptr == srcObject
|| nullptr == swift_dynamicCastUnknownClass(srcObject, targetBridgedClass)) {
destFailureType = targetBridgedClass;
return DynamicCastResult::Failure;
}
return _tryCastFromClassToObjCBridgeable(
destLocation, destType,
srcValue, srcType, srcObject,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks,
destBridgeWitness, targetBridgedClass);
}
/// Dynamic cast from a value type that conforms to the
/// _ObjectiveCBridgeable protocol to a class type, first by bridging
/// the value to its Objective-C object representation and then by
/// dynamic casting that object to the resulting target type.
///
/// Caveat: Despite the name, this is also used to bridge Swift value types
/// to Swift classes even when Obj-C is not being used.
static DynamicCastResult
tryCastFromObjCBridgeableToClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
auto srcBridgeWitness = findBridgeWitness(srcType);
if (srcBridgeWitness == nullptr) {
return DynamicCastResult::Failure;
}
// Bridge the source value to an object.
auto srcBridgedObject =
srcBridgeWitness->bridgeToObjectiveC(srcValue, srcType, srcBridgeWitness);
// Dynamic cast the object to the resulting class type.
if (auto cast = swift_dynamicCastUnknownClass(srcBridgedObject, destType)) {
*reinterpret_cast<const void **>(destLocation) = cast;
return DynamicCastResult::SuccessViaCopy;
} else {
// We don't need the object anymore.
swift_unknownObjectRelease(srcBridgedObject);
return DynamicCastResult::Failure;
}
}
/******************************************************************************/
/****************************** SwiftValue Boxing *****************************/
/******************************************************************************/
#if !SWIFT_OBJC_INTEROP // __SwiftValue is a native class
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_unboxFromSwiftValueWithType(OpaqueValue *source,
OpaqueValue *result,
const Metadata *destinationType);
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_swiftValueConformsTo(const Metadata *, const Metadata *);
#endif
#if SWIFT_OBJC_INTEROP
// Try unwrapping a source holding an Obj-C SwiftValue container and
// recursively casting the contents.
static DynamicCastResult
tryCastUnwrappingObjCSwiftValueSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
id srcObject;
memcpy(&srcObject, srcValue, sizeof(id));
auto srcSwiftValue = getAsSwiftValue(srcObject);
if (srcSwiftValue == nullptr) {
return DynamicCastResult::Failure;
}
const Metadata *srcInnerType;
const OpaqueValue *srcInnerValue;
std::tie(srcInnerType, srcInnerValue)
= getValueFromSwiftValue(srcSwiftValue);
// Note: We never `take` the contents from a SwiftValue box as
// it might have other references. Instead, let our caller
// destroy the reference if necessary.
return tryCast(
destLocation, destType,
const_cast<OpaqueValue *>(srcInnerValue), srcInnerType,
destFailureType, srcFailureType,
/*takeOnSuccess=*/ false, mayDeferChecks, prohibitIsolatedConformances);
}
#else
static DynamicCastResult
tryCastUnwrappingSwiftValueSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType->getKind() == MetadataKind::Class);
// unboxFromSwiftValueWithType is really just a recursive casting operation...
if (swift_unboxFromSwiftValueWithType(srcValue, destLocation, destType)) {
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
#endif
/******************************************************************************/
/****************************** Class Destination *****************************/
/******************************************************************************/
static DynamicCastResult
tryCastToSwiftClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Class);
auto destClassType = cast<ClassMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => Swift class
case MetadataKind::ObjCClassWrapper: { // Obj-C class => Swift class
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// Note: srcObject can be null in compatibility mode.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
if (auto t = swift_dynamicCastClass(srcObject, destClassType)) {
auto castObject = const_cast<void *>(t);
*(reinterpret_cast<void **>(destLocation)) = castObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
swift_unknownObjectRetain(castObject);
return DynamicCastResult::SuccessViaCopy;
}
} else {
srcFailureType = srcType;
destFailureType = destType;
return DynamicCastResult::Failure;
}
}
case MetadataKind::ForeignClass: // CF class => Swift class
// Top-level code will "unwrap" to an Obj-C class and try again.
return DynamicCastResult::Failure;
default:
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastToObjectiveCClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ObjCClassWrapper);
#if SWIFT_OBJC_INTEROP
auto destObjCType = cast<ObjCClassWrapperMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => Obj-C class
case MetadataKind::ObjCClassWrapper: // Obj-C class => Obj-C class
case MetadataKind::ForeignClass: { // CF class => Obj-C class
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If object is null, then we're in the compatibility mode.
// Earlier cast logic always succeeded `as!` casts of nil
// class references but failed `as?` and `is`
if (srcObject == nullptr) {
if (mayDeferChecks) {
*reinterpret_cast<const void **>(destLocation) = nullptr;
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
auto destObjCClass = destObjCType->Class;
if (auto resultObject
= swift_dynamicCastObjCClass(srcObject, destObjCClass)) {
*reinterpret_cast<const void **>(destLocation) = resultObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
objc_retain((id)const_cast<void *>(resultObject));
return DynamicCastResult::SuccessViaCopy;
}
}
break;
}
default:
break;
}
#endif
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToForeignClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
#if SWIFT_OBJC_INTEROP
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ForeignClass);
auto destClassType = cast<ForeignClassMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => CF class
case MetadataKind::ObjCClassWrapper: // Obj-C class => CF class
case MetadataKind::ForeignClass: { // CF class => CF class
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, then we're in compatibility mode.
// Earlier cast logic always succeeded `as!` casts of nil
// class references. Yes, this is very dangerous, which
// is why we no longer permit it.
if (srcObject == nullptr) {
if (mayDeferChecks) {
*reinterpret_cast<const void **>(destLocation) = nullptr;
return DynamicCastResult::SuccessViaCopy;
} else {
// `as?` and `is` checks always fail on nil sources
return DynamicCastResult::Failure;
}
}
if (auto resultObject
= swift_dynamicCastForeignClass(srcObject, destClassType)) {
*reinterpret_cast<const void **>(destLocation) = resultObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
objc_retain((id)const_cast<void *>(resultObject));
return DynamicCastResult::SuccessViaCopy;
}
}
break;
}
default:
break;
}
#endif
return DynamicCastResult::Failure;
}
static DynamicCastResult tryCastToForeignReferenceType(
OpaqueValue *destLocation, const Metadata *destType, OpaqueValue *srcValue,
const Metadata *srcType, const Metadata *&destFailureType,
const Metadata *&srcFailureType, bool takeOnSuccess, bool mayDeferChecks,
bool prohibitIsolatedConformances) {
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ForeignReferenceType);
return DynamicCastResult::Failure;
}
/******************************************************************************/
/***************************** Enum Destination *******************************/
/******************************************************************************/
static DynamicCastResult
tryCastToEnum(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
// Note: Optional is handled elsewhere
assert(destType->getKind() == MetadataKind::Enum);
// Enum has no special cast support at present.
return DynamicCastResult::Failure;
}
/******************************************************************************/
/**************************** Struct Destination ******************************/
/******************************************************************************/
// internal func _arrayDownCastIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Array<SourceValue>>,
// _ target: UnsafeMutablePointer<Array<TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
// internal func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Array<SourceValue>>,
// _ target: UnsafeMutablePointer<Array<TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
// internal func _setDownCastIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Set<SourceValue>>,
// _ target: UnsafeMutablePointer<Set<TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable);
// internal func _setDownCastConditionalIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Set<SourceValue>>,
// _ target: UnsafeMutablePointer<Set<TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable);
// internal func _dictionaryDownCastIndirect<SourceKey, SourceValue,
// TargetKey, TargetValue>(
// _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
// _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable);
// internal func _dictionaryDownCastConditionalIndirect<SourceKey, SourceValue,
// TargetKey, TargetValue>(
// _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
// _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable);
#if SWIFT_OBJC_INTEROP
// Helper to memoize bridging conformance data for a particular
// Swift struct type. This is used to speed up the most common
// ObjC->Swift bridging conversions by eliminating repeated
// protocol conformance lookups.
// Currently used only for String, which may be the only
// type used often enough to justify the extra static memory.
struct ObjCBridgeMemo {
#if !NDEBUG
// Used in assert build to verify that we always get called with
// the same destType
const Metadata *destType;
#endif
const _ObjectiveCBridgeableWitnessTable *destBridgeWitness;
const Metadata *targetBridgedType;
Class targetBridgedObjCClass;
swift_once_t fetchWitnessOnce;
DynamicCastResult tryBridge(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
struct SetupData {
const Metadata *destType;
struct ObjCBridgeMemo *memo;
} setupData { destType, this };
swift_once(&fetchWitnessOnce,
[](void *data) {
struct SetupData *setupData = (struct SetupData *)data;
struct ObjCBridgeMemo *memo = setupData->memo;
#if !NDEBUG
memo->destType = setupData->destType;
#endif
memo->destBridgeWitness = findBridgeWitness(setupData->destType);
if (memo->destBridgeWitness == nullptr) {
memo->targetBridgedType = nullptr;
memo->targetBridgedObjCClass = nullptr;
} else {
memo->targetBridgedType = _getBridgedObjectiveCType(
MetadataState::Complete, setupData->destType, memo->destBridgeWitness).Value;
assert(memo->targetBridgedType->getKind() == MetadataKind::ObjCClassWrapper);
memo->targetBridgedObjCClass = memo->targetBridgedType->getObjCClassObject();
assert(memo->targetBridgedObjCClass != nullptr);
}
}, (void *)&setupData);
// Check that this always gets called with the same destType.
assert((destType == this->destType) && "ObjC casting memo used inconsistently");
// !! If bridging is not usable, stop here.
if (targetBridgedObjCClass == nullptr) {
return DynamicCastResult::Failure;
}
// Use the dynamic ISA type of the object always (Note that this
// also implicitly gives us the ObjC type for a CF object.)
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, then we're in backwards compatibility mode.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
Class srcObjCType = object_getClass((id)srcObject);
// Fail if the ObjC object is not a subclass of the bridge class.
while (srcObjCType != targetBridgedObjCClass) {
srcObjCType = class_getSuperclass(srcObjCType);
if (srcObjCType == nullptr) {
return DynamicCastResult::Failure;
}
}
// The ObjC object is an acceptable type, so call the bridge function...
return _tryCastFromClassToObjCBridgeable(
destLocation, destType, srcValue, srcType, srcObject,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks,
destBridgeWitness, targetBridgedType);
}
};
#endif
static DynamicCastResult
tryCastToAnyHashable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &STRUCT_TYPE_DESCR_SYM(s11AnyHashable));
const HashableWitnessTable *hashableConformance = nullptr;
switch (srcType->getKind()) {
case MetadataKind::ForeignClass: // CF -> String
case MetadataKind::ObjCClassWrapper: { // Obj-C -> String
#if SWIFT_OBJC_INTEROP
auto cls = srcType;
auto nsString = getNSStringMetadata();
do {
if (cls == nsString) {
hashableConformance = getNSStringHashableConformance();
break;
}
cls = _swift_class_getSuperclass(cls);
} while (cls != nullptr);
break;
#else
// If no Obj-C interop, just fall through to the general case.
break;
#endif
}
case MetadataKind::Optional: {
// FIXME: https://github.com/apple/swift/issues/51550
// Until the interactions between AnyHashable and Optional is fixed, we
// avoid directly injecting Optionals. In particular, this allows casts
// from [String?:String] to [AnyHashable:Any] to work the way people
// expect. Otherwise, the resulting dictionary can only be indexed with an
// explicit Optional<String>, not a plain String.
// After fixing the issue, we can consider dropping this special
// case entirely.
// !!!! This breaks compatibility with compiler-optimized casts
// (which just inject) and violates the Casting Spec. It just preserves
// the behavior of the older casting code until we can clean things up.
auto srcInnerType = cast<EnumMetadata>(srcType)->getGenericArgs()[0];
unsigned sourceEnumCase = srcInnerType->vw_getEnumTagSinglePayload(
srcValue, /*emptyCases=*/1);
auto nonNil = (sourceEnumCase == 0);
if (nonNil) {
return DynamicCastResult::Failure; // Our caller will unwrap the optional and try again
}
// Else Optional is nil -- the general case below will inject it
break;
}
default:
break;
}
// General case: If it conforms to Hashable, we cast it
if (hashableConformance == nullptr) {
hashableConformance = reinterpret_cast<const HashableWitnessTable *>(
swift_conformsToProtocolCommon(srcType, &HashableProtocolDescriptor)
);
}
if (hashableConformance) {
_swift_convertToAnyHashableIndirect(srcValue, destLocation,
srcType, hashableConformance);
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastToArray(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(Sa));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Array
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(Sa)) { // Array -> Array
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_arrayDownCastIndirect(
srcValue, destLocation, sourceArgs[0], destArgs[0]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_arrayDownCastConditionalIndirect(
srcValue, destLocation, sourceArgs[0], destArgs[0]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToDictionary(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(SD));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Dictionary
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(SD)) { // Dictionary -> Dictionary
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_dictionaryDownCastIndirect(
srcValue, destLocation, sourceArgs[0], sourceArgs[1],
destArgs[0], destArgs[1], sourceArgs[2], destArgs[2]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_dictionaryDownCastConditionalIndirect(
srcValue, destLocation, sourceArgs[0], sourceArgs[1],
destArgs[0], destArgs[1], sourceArgs[2], destArgs[2]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToSet(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(Sh));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Set
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(Sh)) { // Set -> Set
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_setDownCastIndirect(srcValue, destLocation,
sourceArgs[0], destArgs[0], sourceArgs[1], destArgs[1]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_setDownCastConditionalIndirect(
srcValue, destLocation,
sourceArgs[0], destArgs[0],
sourceArgs[1], destArgs[1]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToString(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks, bool prohibitIsolatedConformances)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(SS));
switch (srcType->getKind()) {
case MetadataKind::ForeignClass: // CF -> String
case MetadataKind::ObjCClassWrapper: { // Obj-C -> String
#if SWIFT_OBJC_INTEROP
static ObjCBridgeMemo memo;
return memo.tryBridge(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType,