/
ImportType.cpp
3449 lines (2982 loc) · 132 KB
/
ImportType.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
//===--- ImportType.cpp - Import Clang Types ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 support for importing Clang types as Swift types.
//
//===----------------------------------------------------------------------===//
#include "CFTypeInfo.h"
#include "ClangDiagnosticConsumer.h"
#include "ImporterImpl.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DefaultArgumentKind.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsClangImporter.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/Types.h"
#include "swift/ClangImporter/ClangImporterRequests.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Parse/Token.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjCCommon.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/TypeVisitor.h"
#include "clang/Basic/Builtins.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace importer;
/// Given that a type is the result of a special typedef import, was
/// it originally a CF pointer?
static bool isImportedCFPointer(clang::QualType clangType, Type type) {
return (clangType->isPointerType() &&
(type->is<ClassType>() || type->isClassExistentialType()));
}
bool ClangImporter::Implementation::isOverAligned(const clang::TypeDecl *decl) {
auto type = getClangASTContext().getTypeDeclType(decl);
return isOverAligned(type);
}
bool ClangImporter::Implementation::isOverAligned(clang::QualType type) {
// Do not check type layout for a clang type in symbolic mode as the
// type could be a dependent type.
if (importSymbolicCXXDecls)
return false;
auto align = getClangASTContext().getTypeAlignInChars(type);
return align > clang::CharUnits::fromQuantity(MaximumAlignment);
}
namespace {
/// Various types that we want to do something interesting to after
/// importing them.
struct ImportHint {
enum ImportHintKind {
/// There is nothing special about the source type.
None,
/// The source type is 'void'.
Void,
/// The source type is 'BOOL' or 'Boolean' -- a type mapped to Swift's
/// 'Bool'.
Boolean,
/// The source type is 'NSUInteger'.
NSUInteger,
/// The source type is 'va_list'.
VAList,
/// The source type is an Objective-C class type bridged to a Swift
/// type.
ObjCBridged,
/// The source type is an Objective-C object pointer type.
ObjCPointer,
/// The source type is a CF object pointer type.
CFPointer,
/// The source type is a block pointer type.
Block,
/// The source type is a function pointer type.
CFunctionPointer,
/// The source type is any other pointer type.
OtherPointer,
};
ImportHintKind Kind;
/// The type to which the imported type is bridged.
Type BridgedType;
/// Allow conversion from an import hint to an import hint kind,
/// which is useful for switches and comparisons.
operator ImportHintKind() const { return Kind; }
ImportHint(ImportHintKind kind) : Kind(kind) {
assert(kind != ObjCBridged &&
"Bridged entry point requires a bridged type");
}
ImportHint(ImportHintKind kind, Type bridgedType)
: Kind(kind), BridgedType(bridgedType) {
assert(kind == ImportHint::ObjCBridged && "Wrong kind for bridged type");
}
};
bool canImportAsOptional(ImportHint hint) {
// See also ClangImporter.cpp's canImportAsOptional.
switch (hint) {
case ImportHint::None:
case ImportHint::Boolean:
case ImportHint::NSUInteger:
case ImportHint::Void:
return false;
case ImportHint::Block:
case ImportHint::CFPointer:
case ImportHint::ObjCBridged:
case ImportHint::ObjCPointer:
case ImportHint::CFunctionPointer:
case ImportHint::OtherPointer:
case ImportHint::VAList:
return true;
}
llvm_unreachable("Invalid ImportHint.");
}
struct ImportResult {
Type AbstractType;
ImportHint Hint;
/*implicit*/ ImportResult(Type type = Type(),
ImportHint hint = ImportHint::None)
: AbstractType(type), Hint(hint) {}
/*implicit*/ ImportResult(TypeBase *type,
ImportHint hint = ImportHint::None)
: AbstractType(type), Hint(hint) {}
explicit operator bool() const { return (bool) AbstractType; }
};
static ImportResult importFunctionPointerLikeType(const clang::Type &type,
const Type &pointeeType) {
auto funcTy = pointeeType->castTo<FunctionType>();
return {FunctionType::get(
funcTy->getParams(), funcTy->getResult(),
funcTy->getExtInfo()
.intoBuilder()
.withRepresentation(
AnyFunctionType::Representation::CFunctionPointer)
.withClangFunctionType(&type)
.build()),
type.isReferenceType() ? ImportHint::None
: ImportHint::CFunctionPointer};
}
static ImportResult importOverAlignedFunctionPointerLikeType(
const clang::Type &type, ClangImporter::Implementation &Impl) {
auto opaquePointer = Impl.SwiftContext.getOpaquePointerDecl();
if (!opaquePointer) {
return Type();
}
return {opaquePointer->getDeclaredInterfaceType(),
type.isReferenceType() ? ImportHint::None
: ImportHint::OtherPointer};
}
class SwiftTypeConverter :
public clang::TypeVisitor<SwiftTypeConverter, ImportResult>
{
ClangImporter::Implementation &Impl;
llvm::function_ref<void(Diagnostic &&)> addImportDiagnostic;
bool AllowNSUIntegerAsInt;
Bridgeability Bridging;
const clang::FunctionType *CompletionHandlerType;
llvm::Optional<unsigned> CompletionHandlerErrorParamIndex;
public:
SwiftTypeConverter(
ClangImporter::Implementation &impl,
llvm::function_ref<void(Diagnostic &&)> addDiag,
bool allowNSUIntegerAsInt, Bridgeability bridging,
const clang::FunctionType *completionHandlerType,
llvm::Optional<unsigned> completionHandlerErrorParamIndex)
: Impl(impl), addImportDiagnostic(addDiag),
AllowNSUIntegerAsInt(allowNSUIntegerAsInt), Bridging(bridging),
CompletionHandlerType(completionHandlerType),
CompletionHandlerErrorParamIndex(completionHandlerErrorParamIndex) {}
using TypeVisitor::Visit;
ImportResult Visit(clang::QualType type) {
PrettyStackTraceClangType trace(Impl.getClangASTContext(),
"importing a clang type",
type.getTypePtr());
auto IR = Visit(type.getTypePtr());
return IR;
}
ImportResult VisitType(const Type*) = delete;
// TODO(https://github.com/apple/swift/issues/56206): Add support for dependent types.
#define DEPENDENT_TYPE(Class, Base) \
ImportResult Visit##Class##Type(const clang::Class##Type *) { return Impl.SwiftContext.getAnyExistentialType(); }
#define TYPE(Class, Base)
#include "clang/AST/TypeNodes.inc"
// Given a loaded type like CInt, look through the type alias sugar that the
// stdlib uses to show the underlying type. We want to import the signature
// of the exit(3) libc function as "func exit(Int32)", not as
// "func exit(CInt)".
static Type unwrapCType(Type T) {
// Handle missing or invalid stdlib declarations
if (!T || T->hasError())
return Type();
if (auto *NAT = dyn_cast<TypeAliasType>(T.getPointer()))
return NAT->getSinglyDesugaredType();
return T;
}
ImportResult VisitBuiltinType(const clang::BuiltinType *type) {
switch (type->getKind()) {
case clang::BuiltinType::Void:
return { Type(), ImportHint::Void };
#define MAP_BUILTIN_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) \
case clang::BuiltinType::CLANG_BUILTIN_KIND: \
return unwrapCType(Impl.getNamedSwiftType(Impl.getStdlibModule(), \
#SWIFT_TYPE_NAME));
#define MAP_BUILTIN_CCHAR_TYPE(CLANG_BUILTIN_KIND, SWIFT_TYPE_NAME) \
case clang::BuiltinType::CLANG_BUILTIN_KIND: \
return Impl.getNamedSwiftType(Impl.getStdlibModule(), #SWIFT_TYPE_NAME);
#include "swift/ClangImporter/BuiltinMappedTypes.def"
// Types that cannot be mapped into Swift, and probably won't ever be.
case clang::BuiltinType::Dependent:
case clang::BuiltinType::ARCUnbridgedCast:
case clang::BuiltinType::BoundMember:
case clang::BuiltinType::BuiltinFn:
case clang::BuiltinType::IncompleteMatrixIdx:
case clang::BuiltinType::Overload:
case clang::BuiltinType::PseudoObject:
case clang::BuiltinType::UnknownAny:
return Type();
// FIXME: Types that can be mapped, but aren't yet.
case clang::BuiltinType::ShortAccum:
case clang::BuiltinType::Accum:
case clang::BuiltinType::LongAccum:
case clang::BuiltinType::UShortAccum:
case clang::BuiltinType::UAccum:
case clang::BuiltinType::ULongAccum:
case clang::BuiltinType::ShortFract:
case clang::BuiltinType::Fract:
case clang::BuiltinType::LongFract:
case clang::BuiltinType::UShortFract:
case clang::BuiltinType::UFract:
case clang::BuiltinType::ULongFract:
case clang::BuiltinType::SatShortAccum:
case clang::BuiltinType::SatAccum:
case clang::BuiltinType::SatLongAccum:
case clang::BuiltinType::SatUShortAccum:
case clang::BuiltinType::SatUAccum:
case clang::BuiltinType::SatULongAccum:
case clang::BuiltinType::SatShortFract:
case clang::BuiltinType::SatFract:
case clang::BuiltinType::SatLongFract:
case clang::BuiltinType::SatUShortFract:
case clang::BuiltinType::SatUFract:
case clang::BuiltinType::SatULongFract:
case clang::BuiltinType::BFloat16:
case clang::BuiltinType::Float128:
case clang::BuiltinType::NullPtr:
case clang::BuiltinType::Char8:
case clang::BuiltinType::Ibm128:
return Type();
// Objective-C types that aren't mapped directly; rather, pointers to
// these types will be mapped.
case clang::BuiltinType::ObjCClass:
case clang::BuiltinType::ObjCId:
case clang::BuiltinType::ObjCSel:
return Type();
// OpenCL types that don't have Swift equivalents.
case clang::BuiltinType::OCLImage1dRO:
case clang::BuiltinType::OCLImage1dRW:
case clang::BuiltinType::OCLImage1dWO:
case clang::BuiltinType::OCLImage1dArrayRO:
case clang::BuiltinType::OCLImage1dArrayRW:
case clang::BuiltinType::OCLImage1dArrayWO:
case clang::BuiltinType::OCLImage1dBufferRO:
case clang::BuiltinType::OCLImage1dBufferRW:
case clang::BuiltinType::OCLImage1dBufferWO:
case clang::BuiltinType::OCLImage2dRO:
case clang::BuiltinType::OCLImage2dRW:
case clang::BuiltinType::OCLImage2dWO:
case clang::BuiltinType::OCLImage2dArrayRO:
case clang::BuiltinType::OCLImage2dArrayRW:
case clang::BuiltinType::OCLImage2dArrayWO:
case clang::BuiltinType::OCLImage2dDepthRO:
case clang::BuiltinType::OCLImage2dDepthRW:
case clang::BuiltinType::OCLImage2dDepthWO:
case clang::BuiltinType::OCLImage2dArrayDepthRO:
case clang::BuiltinType::OCLImage2dArrayDepthRW:
case clang::BuiltinType::OCLImage2dArrayDepthWO:
case clang::BuiltinType::OCLImage2dMSAARO:
case clang::BuiltinType::OCLImage2dMSAARW:
case clang::BuiltinType::OCLImage2dMSAAWO:
case clang::BuiltinType::OCLImage2dArrayMSAARO:
case clang::BuiltinType::OCLImage2dArrayMSAARW:
case clang::BuiltinType::OCLImage2dArrayMSAAWO:
case clang::BuiltinType::OCLImage2dMSAADepthRO:
case clang::BuiltinType::OCLImage2dMSAADepthRW:
case clang::BuiltinType::OCLImage2dMSAADepthWO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRO:
case clang::BuiltinType::OCLImage2dArrayMSAADepthRW:
case clang::BuiltinType::OCLImage2dArrayMSAADepthWO:
case clang::BuiltinType::OCLImage3dRO:
case clang::BuiltinType::OCLImage3dRW:
case clang::BuiltinType::OCLImage3dWO:
case clang::BuiltinType::OCLSampler:
case clang::BuiltinType::OCLEvent:
case clang::BuiltinType::OCLClkEvent:
case clang::BuiltinType::OCLQueue:
case clang::BuiltinType::OCLReserveID:
case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
return Type();
// OpenMP types that don't have Swift equivalents.
case clang::BuiltinType::OMPArraySection:
case clang::BuiltinType::OMPArrayShaping:
case clang::BuiltinType::OMPIterator:
return Type();
// ARM SVE builtin types that don't have Swift equivalents.
#define SVE_TYPE(Name, Id, ...) case clang::BuiltinType::Id:
#include "clang/Basic/AArch64SVEACLETypes.def"
return Type();
// PPC SVE builtin types that don't have Swift equivalents.
#define PPC_VECTOR_TYPE(Name, Id, Size) case clang::BuiltinType::Id:
#include "clang/Basic/PPCTypes.def"
return Type();
// RISC-V V builtin types that don't have Swift equivalents.
#define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id:
#include "clang/Basic/RISCVVTypes.def"
return Type();
}
llvm_unreachable("Invalid BuiltinType.");
}
ImportResult VisitBitIntType(const clang::BitIntType *type) {
Impl.addImportDiagnostic(type, Diagnostic(diag::unsupported_builtin_type,
type->getTypeClassName()),
clang::SourceLocation());
// BitInt is not supported in Swift.
return Type();
}
ImportResult VisitPipeType(const clang::PipeType *type) {
Impl.addImportDiagnostic(type, Diagnostic(diag::unsupported_builtin_type,
type->getTypeClassName()),
clang::SourceLocation());
// OpenCL types are not supported in Swift.
return Type();
}
ImportResult VisitMatrixType(const clang::MatrixType *ty) {
Impl.addImportDiagnostic(ty, Diagnostic(diag::unsupported_builtin_type,
ty->getTypeClassName()),
clang::SourceLocation());
// Matrix types are not supported in Swift.
return Type();
}
ImportResult VisitComplexType(const clang::ComplexType *type) {
Impl.addImportDiagnostic(type, Diagnostic(diag::unsupported_builtin_type,
type->getTypeClassName()),
clang::SourceLocation());
// FIXME: Implement once Complex is in the library.
return Type();
}
ImportResult VisitAtomicType(const clang::AtomicType *type) {
Impl.addImportDiagnostic(type, Diagnostic(diag::unsupported_builtin_type,
type->getTypeClassName()),
clang::SourceLocation());
// FIXME: handle pointers and fields of atomic type
return Type();
}
ImportResult VisitMemberPointerType(const clang::MemberPointerType *type) {
return Type();
}
ImportResult VisitPointerType(const clang::PointerType *type) {
auto pointeeQualType = type->getPointeeType();
auto quals = pointeeQualType.getQualifiers();
// Special case for NSZone*, which has its own Swift wrapper.
if (const clang::RecordType *pointee =
pointeeQualType->getAsStructureType()) {
if (pointee && !pointee->getDecl()->isCompleteDefinition() &&
pointee->getDecl()->getName() == "_NSZone") {
Identifier Id_ObjectiveC = Impl.SwiftContext.Id_ObjectiveC;
ModuleDecl *objCModule = Impl.SwiftContext.getLoadedModule(Id_ObjectiveC);
Type wrapperTy = Impl.getNamedSwiftType(
objCModule,
swift::getSwiftName(
KnownFoundationEntity::NSZone));
if (wrapperTy)
return {wrapperTy, ImportHint::OtherPointer};
}
}
// Import 'void*' as 'UnsafeMutableRawPointer' and 'const void*' as
// 'UnsafeRawPointer'. This is Swift's version of an untyped pointer. Note
// that 'Unsafe[Mutable]Pointer<T>' implicitly converts to
// 'Unsafe[Mutable]RawPointer' for interoperability.
if (pointeeQualType->isVoidType()) {
auto pointerTypeDecl =
(quals.hasConst()
? Impl.SwiftContext.getUnsafeRawPointerDecl()
: Impl.SwiftContext.getUnsafeMutableRawPointerDecl());
if (!pointerTypeDecl)
return Type();
return {pointerTypeDecl->getDeclaredInterfaceType(),
ImportHint::OtherPointer};
}
if (pointeeQualType->isDependentType())
return Type();
// All other C pointers to concrete types map to
// UnsafeMutablePointer<T> or OpaquePointer.
// With pointer conversions enabled, map to the normal pointer types
// without special hints.
Type pointeeType = Impl.importTypeIgnoreIUO(
pointeeQualType, ImportTypeKind::Value, addImportDiagnostic,
AllowNSUIntegerAsInt, Bridgeability::None, ImportTypeAttrs());
// If this is imported as a reference type, ignore the pointer.
if (pointeeType && pointeeType->isForeignReferenceType())
return {pointeeType, ImportHint::OtherPointer};
// If the pointed-to type is unrepresentable in Swift, or its C
// alignment is greater than the maximum Swift alignment, import as
// OpaquePointer.
if (!pointeeType || Impl.isOverAligned(pointeeQualType)) {
return importOverAlignedFunctionPointerLikeType(*type, Impl);
}
if (pointeeQualType->isFunctionType()) {
return importFunctionPointerLikeType(*type, pointeeType);
}
PointerTypeKind pointerKind;
if (quals.hasConst()) {
pointerKind = PTK_UnsafePointer;
} else {
switch (quals.getObjCLifetime()) {
case clang::Qualifiers::OCL_Autoreleasing:
case clang::Qualifiers::OCL_ExplicitNone:
// Mutable pointers with __autoreleasing or __unsafe_unretained
// ownership map to AutoreleasingUnsafeMutablePointer<T>.
pointerKind = PTK_AutoreleasingUnsafeMutablePointer;
// FIXME: We have tests using a non-Apple stdlib that nevertheless
// exercise ObjC interop. Fail softly for those tests.
if (!Impl.SwiftContext.getAutoreleasingUnsafeMutablePointerDecl())
return Type();
break;
case clang::Qualifiers::OCL_Weak:
// FIXME: We should refuse to import this.
LLVM_FALLTHROUGH;
case clang::Qualifiers::OCL_None:
case clang::Qualifiers::OCL_Strong:
// All other mutable pointers map to UnsafeMutablePointer.
pointerKind = PTK_UnsafeMutablePointer;
}
}
if (auto wrapped = pointeeType->wrapInPointer(pointerKind)) {
return {wrapped, ImportHint::OtherPointer};
} else {
return Type();
}
}
ImportResult VisitBlockPointerType(const clang::BlockPointerType *type) {
// Block pointer types are mapped to function types.
Type pointeeType = Visit(type->getPointeeType()).AbstractType;
if (!pointeeType)
return Type();
FunctionType *fTy = pointeeType->castTo<FunctionType>();
auto extInfo =
fTy->getExtInfo()
.intoBuilder()
.withRepresentation(FunctionType::Representation::Block)
.withClangFunctionType(type)
.build();
auto funcTy =
FunctionType::get(fTy->getParams(), fTy->getResult(), extInfo);
return { funcTy, ImportHint::Block };
}
ImportResult VisitReferenceType(const clang::ReferenceType *type) {
auto pointeeQualType = type->getPointeeType();
auto quals = pointeeQualType.getQualifiers();
Type pointeeType =
Impl.importTypeIgnoreIUO(pointeeQualType, ImportTypeKind::Value,
addImportDiagnostic,
AllowNSUIntegerAsInt, Bridgeability::None,
ImportTypeAttrs());
if (!pointeeType)
return Type();
if (pointeeType->isForeignReferenceType())
return {pointeeType, ImportHint::None};
if (pointeeQualType->isFunctionType()) {
return importFunctionPointerLikeType(*type, pointeeType);
}
// Currently, we can't generate thunks for references to dependent types
// because there's no way to cast without a copy (without writing the SIL
// manually).
if (pointeeQualType->isDependentType())
return Type();
if (Impl.isOverAligned(pointeeQualType)) {
return importOverAlignedFunctionPointerLikeType(*type, Impl);
}
PointerTypeKind pointerKind;
if (quals.hasConst()) {
pointerKind = PTK_UnsafePointer;
} else {
pointerKind = PTK_UnsafeMutablePointer;
}
return {pointeeType->wrapInPointer(pointerKind),
ImportHint::None};
}
ImportResult VisitMemberPointer(const clang::MemberPointerType *type) {
// FIXME: Member function pointers can be mapped to curried functions,
// but only when we can express the notion of a function that does
// not capture anything from its enclosing context.
return Type();
}
ImportResult VisitArrayType(const clang::ArrayType *type) {
// FIXME: Array types will need to be mapped differently depending on
// context.
return Type();
}
ImportResult VisitConstantArrayType(const clang::ConstantArrayType *type) {
// FIXME: Map to a real fixed-size Swift array type when we have those.
// Importing as a tuple at least fills the right amount of space, and
// we can cheese static-offset "indexing" using .$n operations.
Type elementType = Impl.importTypeIgnoreIUO(
type->getElementType(), ImportTypeKind::Value, addImportDiagnostic,
AllowNSUIntegerAsInt, Bridgeability::None, ImportTypeAttrs());
if (!elementType)
return Type();
auto size = type->getSize().getZExtValue();
// An array of size N is imported as an N-element tuple which
// takes very long to compile. We chose 4096 as the upper limit because
// we don't want to break arrays of size PATH_MAX.
if (size > 4096)
return Type();
if (size == 1)
return ParenType::get(elementType->getASTContext(), elementType);
SmallVector<TupleTypeElt, 8> elts{static_cast<size_t>(size), elementType};
return TupleType::get(elts, elementType->getASTContext());
}
ImportResult VisitVectorType(const clang::VectorType *type) {
// Get the imported element type and count.
Type element = Impl.importTypeIgnoreIUO(
type->getElementType(), ImportTypeKind::Abstract, addImportDiagnostic,
false /* No NSUIntegerAsInt */, Bridgeability::None, ImportTypeAttrs(),
OptionalTypeKind::OTK_None);
if (!element) { return Type(); }
unsigned count = type->getNumElements();
// Import vector-of-one as the element type.
if (count == 1) { return element; }
// Imported element type needs to conform to SIMDScalar.
auto nominal = element->getAnyNominal();
auto simdscalar = Impl.SwiftContext.getProtocol(KnownProtocolKind::SIMDScalar);
SmallVector<ProtocolConformance *, 2> conformances;
if (simdscalar && nominal->lookupConformance(simdscalar, conformances)) {
// Element type conforms to SIMDScalar. Get the SIMDn generic type
// if it exists.
SmallString<8> name("SIMD");
name.append(std::to_string(count));
if (auto vector = Impl.getNamedSwiftType(Impl.getStdlibModule(), name)) {
if (auto unbound = vector->getAs<UnboundGenericType>()) {
// All checks passed: the imported element type is SIMDScalar,
// and a generic SIMDn type exists with n == count. Construct the
// bound generic type and return that.
return BoundGenericType::get(
cast<NominalTypeDecl>(unbound->getDecl()), Type(), { element }
);
}
}
}
return Type();
}
ImportResult VisitFunctionProtoType(const clang::FunctionProtoType *type) {
// C-style variadic functions cannot be called from Swift.
if (type->isVariadic())
return Type();
// Import the result type.
auto resultTy = Impl.importTypeIgnoreIUO(
type->getReturnType(), ImportTypeKind::Result, addImportDiagnostic,
AllowNSUIntegerAsInt, Bridging, ImportTypeAttrs(), OTK_Optional);
if (!resultTy)
return Type();
SmallVector<FunctionType::Param, 4> params;
for (auto param = type->param_type_begin(),
paramEnd = type->param_type_end();
param != paramEnd; ++param) {
// Determine whether we have a result parameter of a completion
// handler that can also express a thrown error.
ImportTypeKind paramImportKind = ImportTypeKind::Parameter;
unsigned paramIdx = param - type->param_type_begin();
if (CompletionHandlerType &&
Impl.getClangASTContext().hasSameType(
CompletionHandlerType, type) &&
paramIdx != CompletionHandlerErrorParamIndex) {
paramImportKind = ImportTypeKind::CompletionHandlerResultParameter;
}
auto paramQualType = *param;
if (paramQualType->isReferenceType() &&
paramQualType->getPointeeType().isConstQualified())
paramQualType = paramQualType->getPointeeType();
auto swiftParamTy = Impl.importTypeIgnoreIUO(
paramQualType, paramImportKind, addImportDiagnostic,
AllowNSUIntegerAsInt, Bridging, ImportTypeAttrs(), OTK_Optional);
if (!swiftParamTy)
return Type();
// FIXME(https://github.com/apple/swift/issues/45134): If we were walking TypeLocs, we could actually get parameter names.
// The probably doesn't matter outside of a FuncDecl, which we'll have
// to special-case, but it's an interesting bit of data loss.
params.push_back(FunctionType::Param(swiftParamTy));
}
// Form the function type.
return FunctionType::get(params, resultTy, FunctionType::ExtInfo());
}
ImportResult
VisitFunctionNoProtoType(const clang::FunctionNoProtoType *type) {
// Import functions without prototypes as functions with no parameters.
auto resultTy = Impl.importTypeIgnoreIUO(
type->getReturnType(), ImportTypeKind::Result, addImportDiagnostic,
AllowNSUIntegerAsInt, Bridging, ImportTypeAttrs(), OTK_Optional);
if (!resultTy)
return Type();
// FIXME: Verify ExtInfo state is correct, not working by accident.
FunctionType::ExtInfo info;
return FunctionType::get({}, resultTy, info);
}
ImportResult VisitParenType(const clang::ParenType *type) {
auto inner = Visit(type->getInnerType());
if (!inner)
return Type();
return { ParenType::get(Impl.SwiftContext, inner.AbstractType),
inner.Hint };
}
/// Imports the type defined by \p objcTypeParamDecl.
///
/// If the type parameter is not imported for some reason, returns \c None.
/// This is different from a failure; it means the caller should try
/// importing the underlying type instead.
llvm::Optional<ImportResult>
importObjCTypeParamDecl(const clang::ObjCTypeParamDecl *objcTypeParamDecl) {
// Pull the corresponding generic type parameter from the imported class.
const auto *typeParamContext = objcTypeParamDecl->getDeclContext();
GenericSignature genericSig;
if (auto *category =
dyn_cast<clang::ObjCCategoryDecl>(typeParamContext)) {
auto ext = cast_or_null<ExtensionDecl>(
Impl.importDecl(category, Impl.CurrentVersion));
if (!ext)
return ImportResult();
genericSig = ext->getGenericSignature();
} else if (auto *interface =
dyn_cast<clang::ObjCInterfaceDecl>(typeParamContext)) {
auto cls = castIgnoringCompatibilityAlias<ClassDecl>(
Impl.importDecl(interface, Impl.CurrentVersion));
if (!cls)
return ImportResult();
genericSig = cls->getGenericSignature();
}
unsigned index = objcTypeParamDecl->getIndex();
// Pull the generic param decl out of the imported class.
if (!genericSig) {
// The ObjC type param didn't get imported, possibly because it was
// suppressed. Treat it as a typedef.
return llvm::None;
}
if (index > genericSig.getGenericParams().size()) {
return ImportResult();
}
return ImportResult(genericSig.getGenericParams()[index],
ImportHint::ObjCPointer);
}
ImportResult VisitObjCTypeParamType(const clang::ObjCTypeParamType *type) {
// FIXME: This drops any added protocols on the floor, which is the whole
// point of ObjCTypeParamType. Fixing this might be source-breaking,
// though. rdar://problem/29763975
if (auto result = importObjCTypeParamDecl(type->getDecl()))
return result.value();
// Fall back to importing the desugared type, which uses the parameter's
// bound. This isn't perfect but it's better than dropping the type.
return Visit(type->getLocallyUnqualifiedSingleStepDesugaredType());
}
ImportResult VisitTypedefType(const clang::TypedefType *type) {
// If the underlying declaration is an Objective-C type parameter,
// pull the corresponding generic type parameter from the imported class.
if (auto *objcTypeParamDecl =
dyn_cast<clang::ObjCTypeParamDecl>(type->getDecl())) {
if (auto result = importObjCTypeParamDecl(objcTypeParamDecl))
return result.value();
return Visit(type->getLocallyUnqualifiedSingleStepDesugaredType());
}
// Import the underlying declaration.
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(type->getDecl(), Impl.CurrentVersion));
// If that fails, fall back on importing the underlying type.
if (!decl) return Visit(type->desugar());
Type mappedType = decl->getDeclaredInterfaceType();
if (getSwiftNewtypeAttr(type->getDecl(), Impl.CurrentVersion)) {
auto underlying = Visit(type->getDecl()->getUnderlyingType());
switch (underlying.Hint) {
case ImportHint::None:
case ImportHint::Void:
case ImportHint::Block:
case ImportHint::CFPointer:
case ImportHint::ObjCPointer:
case ImportHint::CFunctionPointer:
case ImportHint::OtherPointer:
case ImportHint::VAList:
return {mappedType, underlying.Hint};
case ImportHint::Boolean:
case ImportHint::NSUInteger:
// Toss out the special rules for these types; we still want to
// import as a wrapper.
return {mappedType, ImportHint::None};
case ImportHint::ObjCBridged:
// If the underlying type was bridged, the wrapper type is
// only useful in bridged cases. Exit early.
return { underlying.AbstractType,
ImportHint(ImportHint::ObjCBridged, mappedType) };
}
}
// For certain special typedefs, we don't want to use the imported type.
if (auto specialKind = Impl.getSpecialTypedefKind(type->getDecl())) {
switch (specialKind.value()) {
case MappedTypeNameKind::DoNothing:
case MappedTypeNameKind::DefineAndUse:
break;
case MappedTypeNameKind::DefineOnly:
if (auto typealias = dyn_cast<TypeAliasDecl>(decl))
mappedType = typealias->getDeclaredInterfaceType()
->getDesugaredType();
break;
}
static const llvm::StringLiteral vaListNames[] = {
"va_list", "__gnuc_va_list", "__va_list"
};
ImportHint hint = ImportHint::None;
if (type->getDecl()->getName() == "BOOL") {
hint = ImportHint::Boolean;
} else if (type->getDecl()->getName() == "Boolean") {
// FIXME: Darwin only?
hint = ImportHint::Boolean;
} else if (type->getDecl()->getName() == "NSUInteger") {
hint = ImportHint::NSUInteger;
} else if (llvm::is_contained(vaListNames,
type->getDecl()->getName())) {
hint = ImportHint::VAList;
} else if (isImportedCFPointer(type->desugar(), mappedType)) {
hint = ImportHint::CFPointer;
} else if (mappedType->isAnyExistentialType()) { // id, Class
hint = ImportHint::ObjCPointer;
} else if (type->isPointerType() || type->isBlockPointerType()) {
hint = ImportHint::OtherPointer;
}
// Any other interesting mapped types should be hinted here.
return { mappedType, hint };
}
// Otherwise, recurse on the underlying type. We need to recompute
// the hint, and if the typedef uses different bridgeability than the
// context then we may also need to bypass the typedef.
auto underlyingResult = Visit(type->desugar());
// If we used different bridgeability than this typedef normally
// would because we're in a non-bridgeable context, and therefore
// the underlying type is different from the mapping of the typedef,
// use the underlying type.
if (Bridging != getTypedefBridgeability(type->getDecl()) &&
!underlyingResult.AbstractType->isEqual(mappedType)) {
return underlyingResult;
}
#ifndef NDEBUG
switch (underlyingResult.Hint) {
case ImportHint::Block:
case ImportHint::ObjCBridged:
// Bridging is fine for Objective-C and blocks.
break;
case ImportHint::NSUInteger:
// NSUInteger might be imported as Int rather than UInt depending
// on where the import lives.
if (underlyingResult.AbstractType->isInt())
break;
LLVM_FALLTHROUGH;
default:
if (!underlyingResult.AbstractType->isEqual(mappedType)) {
underlyingResult.AbstractType->dump(llvm::errs());
mappedType->dump(llvm::errs());
}
assert(underlyingResult.AbstractType->isEqual(mappedType) &&
"typedef without special typedef kind was mapped "
"differently from its underlying type?");
}
#endif
// If the imported typealias is unavailable, return the underlying type.
if (decl->getAttrs().isUnavailable(Impl.SwiftContext))
return underlyingResult;
return { mappedType, underlyingResult.Hint };
}
// TODO: add custom visitors for these types.
#define MAYBE_SUGAR_TYPE(KIND) \
ImportResult Visit##KIND##Type(const clang::KIND##Type *type) { \
if (type->isSugared()) \
return Visit(type->desugar()); \
return Type(); \
}
MAYBE_SUGAR_TYPE(TypeOfExpr)
MAYBE_SUGAR_TYPE(TypeOf)
MAYBE_SUGAR_TYPE(Decltype)
MAYBE_SUGAR_TYPE(UnaryTransform)
MAYBE_SUGAR_TYPE(TemplateSpecialization)
MAYBE_SUGAR_TYPE(Auto)
MAYBE_SUGAR_TYPE(DeducedTemplateSpecialization)
// These types are ALWAYS sugared.
#define SUGAR_TYPE(KIND) \
ImportResult Visit##KIND##Type(const clang::KIND##Type *type) { \
return Visit(type->desugar()); \
}
SUGAR_TYPE(MacroQualified)
SUGAR_TYPE(Attributed)
SUGAR_TYPE(Adjusted)
SUGAR_TYPE(SubstTemplateTypeParm)
SUGAR_TYPE(Elaborated)
SUGAR_TYPE(Using)
SUGAR_TYPE(BTFTagAttributed)
ImportResult VisitDecayedType(const clang::DecayedType *type) {
clang::ASTContext &clangCtx = Impl.getClangASTContext();
if (clangCtx.hasSameType(type->getOriginalType(),
clangCtx.getBuiltinVaListType())) {
return {Impl.getNamedSwiftType(Impl.getStdlibModule(),
"CVaListPointer"),
ImportHint::VAList};
}
return Visit(type->desugar());
}
ImportResult VisitRecordType(const clang::RecordType *type) {
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(type->getDecl(), Impl.CurrentVersion));
if (!decl)
return nullptr;
return decl->getDeclaredInterfaceType();
}
ImportResult VisitEnumType(const clang::EnumType *type) {
auto clangDecl = type->getDecl()->getDefinition();
if (!clangDecl) {
// FIXME: If the enum has a fixed underlying type, can we use that
// instead? Or import it opaquely somehow?
return nullptr;
}
switch (Impl.getEnumKind(clangDecl)) {
case EnumKind::Constants: {
// Map anonymous enums with no fixed underlying type to Int /if/
// they fit in an Int32. If not, this mapping isn't guaranteed to be
// consistent for all platforms we care about.
if (!clangDecl->isFixed() && clangDecl->isFreeStanding() &&
clangDecl->getNumPositiveBits() < 32 &&
clangDecl->getNumNegativeBits() <= 32)
return Impl.getNamedSwiftType(Impl.getStdlibModule(), "Int");
// Import the underlying integer type.
return Visit(clangDecl->getIntegerType());
}
case EnumKind::NonFrozenEnum:
case EnumKind::FrozenEnum:
case EnumKind::Unknown:
case EnumKind::Options: {
auto decl = dyn_cast_or_null<TypeDecl>(
Impl.importDecl(clangDecl, Impl.CurrentVersion));
if (!decl)
return nullptr;
return decl->getDeclaredInterfaceType();
}
}
llvm_unreachable("Invalid EnumKind.");