This repository has been archived by the owner on Apr 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 197
/
SwiftASTContext.cpp
9071 lines (7980 loc) · 318 KB
/
SwiftASTContext.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
//===-- SwiftASTContext.cpp -------------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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
//
//===----------------------------------------------------------------------===//
#include "lldb/Symbol/SwiftASTContext.h"
// C++ Includes
#include <mutex> // std::once
#include <queue>
#include <set>
#include <sstream>
#include "swift/AST/ASTContext.h"
#include "swift/AST/DebuggerClient.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/SearchPathOptions.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "swift/ASTSectionImporter/ASTSectionImporter.h"
#include "swift/Basic/Demangle.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/SourceManager.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangImporterOptions.h"
#include "swift/Driver/Util.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/Utils.h"
#include "swift/SIL/SILModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/TargetRegistry.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetSubtargetInfo.h"
#include "swift/../../lib/IRGen/FixedTypeInfo.h"
#include "swift/../../lib/IRGen/GenEnum.h"
#include "swift/../../lib/IRGen/GenHeap.h"
#include "swift/../../lib/IRGen/IRGenModule.h"
#include "swift/../../lib/IRGen/Linking.h"
#include "swift/../../lib/IRGen/TypeInfo.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Strings.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftUserExpression.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/Error.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Section.h"
#include "lldb/Core/StreamFile.h"
#include "lldb/Core/ThreadSafeDenseMap.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/StringConvert.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Target/Platform.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/CleanUp.h"
#include "lldb/Utility/LLDBAssert.h"
#include "Plugins/Platform/MacOSX/PlatformDarwin.h"
#include "Plugins/SymbolFile/DWARF/DWARFASTParserSwift.h"
#ifdef LLDB_CONFIGURATION_DEBUG
#define VALID_OR_RETURN(value) \
do { \
lldbassert(!HasFatalErrors()); \
if (HasFatalErrors()) { \
return (value); \
} \
} while (0)
#define VALID_OR_RETURN_VOID() \
do { \
lldbassert(!HasFatalErrors()); \
if (HasFatalErrors()) { \
return; \
} \
} while (0)
#else
#define VALID_OR_RETURN(value) \
do { \
if (HasFatalErrors()) { \
return (value); \
} \
} while (0)
#define VALID_OR_RETURN_VOID() \
do { \
if (HasFatalErrors()) { \
return; \
} \
} while (0)
#endif
using namespace lldb;
using namespace lldb_private;
typedef lldb_private::ThreadSafeDenseMap<swift::ASTContext *, SwiftASTContext *>
ThreadSafeSwiftASTMap;
static ThreadSafeSwiftASTMap &GetASTMap() {
// The global destructor list will tear down all of the modules when the LLDB
// shared library is being unloaded and this needs to live beyond all of those
// and not be destructed before they have all gone away. So we will leak this
// list intentionally so we can avoid global destructor problems.
static ThreadSafeSwiftASTMap *g_map_ptr = NULL;
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_map_ptr = new ThreadSafeSwiftASTMap(); // NOTE: Intentional leak
});
return *g_map_ptr;
}
static inline swift::Type GetSwiftType(void *opaque_ptr) {
return swift::Type((swift::TypeBase *)opaque_ptr);
}
static inline swift::CanType GetCanonicalSwiftType(void *opaque_ptr) {
return ((swift::TypeBase *)opaque_ptr)->getCanonicalType();
}
static inline swift::Type GetSwiftType(CompilerType type) {
return swift::Type((swift::TypeBase *)type.GetOpaqueQualType());
}
static inline swift::CanType GetCanonicalSwiftType(CompilerType type) {
return ((swift::TypeBase *)type.GetOpaqueQualType())->getCanonicalType();
}
enum class MemberType : uint32_t { Invalid, BaseClass, Field };
static const char *MemberTypeToCString(MemberType member_type) {
switch (member_type) {
case MemberType::Invalid:
return "invalid";
case MemberType::BaseClass:
return "base class";
case MemberType::Field:
return "field";
}
return "???";
}
struct MemberInfo {
CompilerType clang_type;
lldb_private::ConstString name;
uint64_t byte_size;
uint32_t byte_offset;
MemberType member_type;
bool is_fragile;
MemberInfo(MemberType member_type)
: clang_type(), name(), byte_size(0), byte_offset(0),
member_type(member_type), is_fragile(false) {}
void Dump(uint32_t idx) {
printf("[%i] %12s +%u (%s) %s <%" PRIu64 "> %s\n", idx,
MemberTypeToCString(member_type), byte_offset,
clang_type.GetTypeName().AsCString("<no type name>"),
name.AsCString("<NULL>"), byte_size, is_fragile ? "[fragile]" : "");
}
};
struct CachedMemberInfo {
std::vector<MemberInfo> member_infos;
};
struct EnumElementInfo {
CompilerType clang_type;
lldb_private::ConstString name;
uint64_t byte_size;
uint32_t value; // The value for this enumeration element
uint32_t extra_value; // If not UINT32_MAX, then this value is an extra value
// that appears at offset 0 to tell one or more empty
// enums apart. This value will only be filled in if there
// are one ore more enum elements that have a non-zero byte size
EnumElementInfo()
: clang_type(), name(), byte_size(0), extra_value(UINT32_MAX) {}
void Dump(Stream &strm) const {
strm.Printf("<%2" PRIu64 "> %4u", byte_size, value);
if (extra_value != UINT32_MAX)
strm.Printf("%4u: ", extra_value);
else
strm.Printf(" : ");
strm.Printf("case %s", name.GetCString());
if (clang_type)
strm.Printf("%s", clang_type.GetTypeName().AsCString("<no type name>"));
strm.EOL();
}
};
class SwiftEnumDescriptor;
typedef std::shared_ptr<CachedMemberInfo> CachedMemberInfoSP;
typedef std::shared_ptr<SwiftEnumDescriptor> SwiftEnumDescriptorSP;
typedef llvm::DenseMap<lldb::opaque_compiler_type_t, CachedMemberInfoSP>
MemberInfoCache;
typedef llvm::DenseMap<lldb::opaque_compiler_type_t, SwiftEnumDescriptorSP>
EnumInfoCache;
typedef std::shared_ptr<MemberInfoCache> MemberInfoCacheSP;
typedef std::shared_ptr<EnumInfoCache> EnumInfoCacheSP;
typedef llvm::DenseMap<const swift::ASTContext *, MemberInfoCacheSP>
ASTMemberInfoCacheMap;
typedef llvm::DenseMap<const swift::ASTContext *, EnumInfoCacheSP>
ASTEnumInfoCacheMap;
static MemberInfoCache *GetMemberInfoCache(const swift::ASTContext *a) {
static ASTMemberInfoCacheMap g_cache;
static std::mutex g_mutex;
std::lock_guard<std::mutex> locker(g_mutex);
ASTMemberInfoCacheMap::iterator pos = g_cache.find(a);
if (pos == g_cache.end()) {
g_cache.insert(std::make_pair(
a, std::shared_ptr<MemberInfoCache>(new MemberInfoCache())));
return g_cache.find(a)->second.get();
}
return pos->second.get();
}
static EnumInfoCache *GetEnumInfoCache(const swift::ASTContext *a) {
static ASTEnumInfoCacheMap g_cache;
static std::mutex g_mutex;
std::lock_guard<std::mutex> locker(g_mutex);
ASTEnumInfoCacheMap::iterator pos = g_cache.find(a);
if (pos == g_cache.end()) {
g_cache.insert(
std::make_pair(a, std::shared_ptr<EnumInfoCache>(new EnumInfoCache())));
return g_cache.find(a)->second.get();
}
return pos->second.get();
}
llvm::LLVMContext &SwiftASTContext::GetGlobalLLVMContext() {
// TODO check with Sean. Do we really want this to be static across
// an LLDB managing multiple Swift processes?
static llvm::LLVMContext s_global_context;
return s_global_context;
}
CachedMemberInfo *SwiftASTContext::GetCachedMemberInfo(void *type) {
VALID_OR_RETURN(nullptr);
if (type) {
// printf("CompilerType::GetCachedMemberInfo () for %s...",
// GetTypeName().c_str());
bool is_class = false;
bool is_protocol = false;
MemberInfoCache *member_info_cache = GetMemberInfoCache(GetASTContext());
MemberInfoCache::const_iterator pos = member_info_cache->find(type);
if (pos != member_info_cache->end()) {
// printf("cached: %p\n", pos->second.get());
return pos->second.get();
}
CachedMemberInfoSP member_infos_sp(new CachedMemberInfo());
// printf("creating in %p\n", member_infos_sp.get());
swift::CanType swift_can_type(GetCanonicalSwiftType(type));
std::vector<const swift::irgen::TypeInfo *> field_type_infos;
swift::irgen::LayoutStrategy layout_strategy =
swift::irgen::LayoutStrategy::Optimal;
const swift::TypeKind type_kind = swift_can_type->getKind();
switch (type_kind) {
case swift::TypeKind::Error:
case swift::TypeKind::BuiltinInteger:
case swift::TypeKind::BuiltinFloat:
case swift::TypeKind::BuiltinRawPointer:
case swift::TypeKind::BuiltinBridgeObject:
case swift::TypeKind::BuiltinNativeObject:
case swift::TypeKind::BuiltinUnsafeValueBuffer:
case swift::TypeKind::BuiltinUnknownObject:
case swift::TypeKind::BuiltinVector:
case swift::TypeKind::NameAlias:
case swift::TypeKind::Paren:
case swift::TypeKind::UnownedStorage:
case swift::TypeKind::WeakStorage:
case swift::TypeKind::UnmanagedStorage:
case swift::TypeKind::GenericTypeParam:
case swift::TypeKind::DependentMember:
case swift::TypeKind::Optional:
case swift::TypeKind::ImplicitlyUnwrappedOptional:
case swift::TypeKind::Metatype:
case swift::TypeKind::Module:
case swift::TypeKind::Function:
case swift::TypeKind::GenericFunction:
case swift::TypeKind::ArraySlice:
case swift::TypeKind::LValue:
case swift::TypeKind::UnboundGeneric:
case swift::TypeKind::Enum:
case swift::TypeKind::BoundGenericEnum:
case swift::TypeKind::ExistentialMetatype:
case swift::TypeKind::DynamicSelf:
case swift::TypeKind::SILBox:
case swift::TypeKind::SILFunction:
case swift::TypeKind::SILBlockStorage:
case swift::TypeKind::InOut:
case swift::TypeKind::Unresolved:
assert(false &&
"Caller must only call this function with valid type_kind");
break;
case swift::TypeKind::Tuple: {
layout_strategy = swift::irgen::LayoutStrategy::Universal;
swift::TupleType *tuple_type = swift_can_type->getAs<swift::TupleType>();
for (auto tuple_field : tuple_type->getElements()) {
MemberInfo member_info(MemberType::Field);
member_info.clang_type =
CompilerType(GetASTContext(), tuple_field.getType().getPointer());
member_info.byte_size = member_info.clang_type.GetByteSize(nullptr);
const char *tuple_name = tuple_field.getName().get();
if (tuple_name) {
member_info.name.SetCString(tuple_name);
} else {
StreamString tuple_name_strm;
tuple_name_strm.Printf(
"%u", (uint32_t)member_infos_sp->member_infos.size());
member_info.name.SetCString(tuple_name_strm.GetString().c_str());
}
field_type_infos.push_back(
GetSwiftTypeInfo(member_info.clang_type.GetOpaqueQualType()));
assert(field_type_infos.back() != nullptr);
member_infos_sp->member_infos.push_back(member_info);
}
} break;
case swift::TypeKind::Protocol:
case swift::TypeKind::ProtocolComposition: {
ProtocolInfo protocol_info;
if (!GetProtocolTypeInfo(
CompilerType(GetASTContext(), GetSwiftType(type)), protocol_info))
break;
is_protocol = true;
uint32_t num_children = protocol_info.m_num_storage_words;
if (protocol_info.IsOneWordStorage())
protocol_info.m_num_protocols = 0;
for (uint32_t idx = 0; idx < num_children; idx++) {
MemberInfo member_info(MemberType::Field);
member_info.clang_type = CompilerType(
GetASTContext(), GetASTContext()->TheRawPointerType.getPointer());
member_info.byte_size = member_info.clang_type.GetByteSize(nullptr);
member_info.byte_offset = idx * member_info.byte_size;
member_info.is_fragile = false;
StreamString child_name_stream;
if (protocol_info.IsOneWordStorage())
child_name_stream.Printf("instance_type");
else {
if (idx < protocol_info.m_num_payload_words)
child_name_stream.Printf("payload_data_%u", idx);
else {
int l_idx = idx - protocol_info.m_num_payload_words;
if (l_idx == 0)
child_name_stream.Printf("instance_type");
else
child_name_stream.Printf("protocol_witness_%u", l_idx - 1);
}
}
member_info.name = ConstString(child_name_stream.GetData());
member_infos_sp->member_infos.push_back(member_info);
}
} break;
case swift::TypeKind::Struct:
case swift::TypeKind::Class: {
swift::ClassDecl *class_decl =
swift_can_type->getClassOrBoundGenericClass();
swift::NominalType *nominal_type =
swift_can_type->getAs<swift::NominalType>();
if (nominal_type) {
swift::NominalTypeDecl *nominal_decl = nominal_type->getDecl();
if (nominal_decl) {
if (class_decl) {
is_class = true;
swift::Type superclass_type(class_decl->getSuperclass());
if (superclass_type) {
MemberInfo member_info(MemberType::BaseClass);
member_info.clang_type =
CompilerType(GetASTContext(), superclass_type.getPointer());
member_info.byte_size =
member_info.clang_type.GetByteSize(nullptr);
member_info.is_fragile = false;
member_info.name.SetCString(
member_info.clang_type.GetTypeName().AsCString(
"<no type name>"));
field_type_infos.push_back(
GetSwiftTypeInfo(member_info.clang_type.GetOpaqueQualType()));
assert(field_type_infos.back() != nullptr);
member_infos_sp->member_infos.push_back(member_info);
}
}
for (auto decl : nominal_decl->getMembers()) {
if (swift::isa<swift::VarDecl>(decl)) {
swift::VarDecl *var_decl = llvm::cast<swift::VarDecl>(decl);
if (var_decl->hasStorage() && !var_decl->isStatic()) {
MemberInfo member_info(MemberType::Field);
member_info.clang_type = CompilerType(
GetASTContext(), var_decl->getInterfaceType().getPointer());
member_info.byte_size =
member_info.clang_type.GetByteSize(nullptr);
member_info.is_fragile =
is_class; // Class fields are all fragile...
const char *child_name_cstr = var_decl->getName().get();
if (child_name_cstr)
member_info.name.SetCString(child_name_cstr);
field_type_infos.push_back(
GetSwiftTypeInfo(nominal_type, var_decl));
assert(field_type_infos.back() != nullptr);
member_infos_sp->member_infos.push_back(member_info);
}
}
}
}
}
} break;
case swift::TypeKind::BoundGenericStruct:
case swift::TypeKind::BoundGenericClass: {
swift::ClassDecl *class_decl =
swift_can_type->getClassOrBoundGenericClass();
swift::BoundGenericType *t =
swift_can_type->getAs<swift::BoundGenericType>();
if (t) {
swift::NominalTypeDecl *t_decl = t->getDecl();
if (t_decl) {
if (class_decl) {
is_class = true;
swift::LazyResolver *const lazy_resolver = nullptr;
swift::Type superclass_type(t->getSuperclass(lazy_resolver));
if (superclass_type) {
MemberInfo member_info(MemberType::BaseClass);
member_info.clang_type =
CompilerType(GetASTContext(), superclass_type.getPointer());
member_info.byte_size =
member_info.clang_type.GetByteSize(nullptr);
// Showing somemodule.sometype<A> is confusing to the user because
// it will show the *unboud* archetype name even though the type
// is actually properly bound (or it should!) and since one cannot
// overload a class on the number of generic arguments,
// somemodule.sometype is just as unique.
member_info.name.SetCString(
member_info.clang_type.GetUnboundType()
.GetTypeName()
.AsCString("<no type name>"));
field_type_infos.push_back(
GetSwiftTypeInfo(member_info.clang_type.GetOpaqueQualType()));
assert(field_type_infos.back() != nullptr);
member_infos_sp->member_infos.push_back(member_info);
}
}
for (auto decl : t_decl->getMembers()) {
// Find ivars that aren't properties
if (swift::isa<swift::VarDecl>(decl)) {
swift::VarDecl *var_decl = llvm::cast<swift::VarDecl>(decl);
if (var_decl->hasStorage() && !var_decl->isStatic()) {
MemberInfo member_info(MemberType::Field);
swift::Type member_type = swift_can_type->getTypeOfMember(
t_decl->getModuleContext(), var_decl);
member_info.clang_type =
CompilerType(GetASTContext(), member_type.getPointer());
member_info.byte_size =
member_info.clang_type.GetByteSize(nullptr);
member_info.is_fragile =
is_class; // Class fields are all fragile...
const char *child_name_cstr = var_decl->getName().get();
if (child_name_cstr)
member_info.name.SetCString(child_name_cstr);
field_type_infos.push_back(GetSwiftTypeInfo(
member_info.clang_type.GetOpaqueQualType()));
assert(field_type_infos.back() != nullptr);
member_infos_sp->member_infos.push_back(member_info);
}
}
}
}
}
} break;
case swift::TypeKind::Dictionary: {
swift::DictionaryType *t =
llvm::dyn_cast<swift::DictionaryType>(swift_can_type.getPointer());
if (t)
return GetCachedMemberInfo(t->getSinglyDesugaredType());
} break;
case swift::TypeKind::TypeVariable:
case swift::TypeKind::Archetype:
break;
}
if (!member_infos_sp->member_infos.empty()) {
if (is_class) {
// If we have a class, then all offsets are fragile so we don't need to
// do layout since we will need to lookup the ivar offset symbol, or
// munge the runtime data to find the offsets.
} else if (!is_protocol) {
// Only do struct layout if we don't have a union since the only thing
// we need layout for currently is for the byte offset and the byte
// offset of everything in a union is zero.
// As for protocols, their fields are artificially generated from what a
// protocol_container contains in the Swift runtime itself, and it's
// just pointers, so no need to get fancy.
swift::irgen::StructLayout layout(
GetIRGenModule(), swift_can_type,
swift::irgen::LayoutKind::NonHeapObject, layout_strategy,
field_type_infos);
const size_t num_elements = layout.getElements().size();
assert(num_elements == member_infos_sp->member_infos.size());
for (int ii = 0; ii < num_elements; ++ii) {
auto element = layout.getElements()[ii];
// check or crash
if (element.getKind() == swift::irgen::ElementLayout::Kind::Fixed)
member_infos_sp->member_infos[ii].byte_offset =
element.getByteOffset().getValue();
else
member_infos_sp->member_infos[ii].byte_offset =
0; // TODO: dynamic layout
// member_infos_sp->member_infos[ii].Dump(ii);
}
}
member_info_cache->insert(std::make_pair(type, member_infos_sp));
return member_infos_sp.get();
}
}
return nullptr;
}
class SwiftEnumDescriptor {
public:
enum class Kind {
Empty, // no cases in this enum
CStyle, // no cases have payloads
AllPayload, // all cases have payloads
Mixed // some cases have payloads
};
struct ElementInfo {
lldb_private::ConstString name;
CompilerType payload_type;
bool has_payload : 1;
bool is_indirect : 1;
};
Kind GetKind() const { return m_kind; }
ConstString GetTypeName() { return m_type_name; }
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) = 0;
virtual size_t GetNumElements() {
return GetNumElementsWithPayload() + GetNumCStyleElements();
}
virtual size_t GetNumElementsWithPayload() = 0;
virtual size_t GetNumCStyleElements() = 0;
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) = 0;
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) = 0;
virtual ~SwiftEnumDescriptor() = default;
static SwiftEnumDescriptor *CreateDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl);
protected:
SwiftEnumDescriptor(swift::ASTContext *ast, swift::CanType swift_can_type,
swift::EnumDecl *enum_decl, SwiftEnumDescriptor::Kind k)
: m_kind(k), m_type_name() {
if (swift_can_type.getPointer()) {
if (auto nominal = swift_can_type->getAnyNominal()) {
swift::Identifier name(nominal->getName());
if (name.get())
m_type_name.SetCString(name.get());
}
}
}
private:
Kind m_kind;
ConstString m_type_name;
};
class SwiftEmptyEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftEmptyEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::Empty) {}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
return nullptr;
}
virtual size_t GetNumElementsWithPayload() { return 0; }
virtual size_t GetNumCStyleElements() { return 0; }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
return nullptr;
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
return nullptr;
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::Empty;
}
virtual ~SwiftEmptyEnumDescriptor() = default;
};
namespace std {
template <> struct less<swift::ClusteredBitVector> {
bool operator()(const swift::ClusteredBitVector &lhs,
const swift::ClusteredBitVector &rhs) const {
int iL = lhs.size() - 1;
int iR = rhs.size() - 1;
for (; iL >= 0 && iR >= 0; --iL, --iR) {
bool bL = lhs[iL];
bool bR = rhs[iR];
if (bL and not bR)
return false;
if (bR and not bL)
return true;
}
return false;
}
};
}
static std::string Dump(const swift::ClusteredBitVector &bit_vector) {
std::string buffer;
llvm::raw_string_ostream ostream(buffer);
for (size_t i = 0; i < bit_vector.size(); i++) {
if (bit_vector[i])
ostream << '1';
else
ostream << '0';
if ((i % 4) == 3)
ostream << ' ';
}
ostream.flush();
return buffer;
}
class SwiftCStyleEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftCStyleEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::CStyle),
m_nopayload_elems_bitmask(), m_elements(), m_element_indexes() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("doing C-style enum layout for %s",
GetTypeName().AsCString());
SwiftASTContext *swift_ast_ctx = SwiftASTContext::GetSwiftASTContext(ast);
swift::irgen::IRGenModule &irgen_module = swift_ast_ctx->GetIRGenModule();
const swift::irgen::EnumImplStrategy &enum_impl_strategy =
swift::irgen::getEnumImplStrategy(irgen_module, swift_can_type);
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_no_payload =
enum_impl_strategy.getElementsWithNoPayload();
const bool has_payload = false;
const bool is_indirect = false;
uint64_t case_counter = 0;
m_nopayload_elems_bitmask =
enum_impl_strategy.getBitMaskForNoPayloadElements();
if (log)
log->Printf("m_nopayload_elems_bitmask = %s",
Dump(m_nopayload_elems_bitmask).c_str());
for (auto enum_case : elements_with_no_payload) {
ConstString case_name(enum_case.decl->getName().str().data());
swift::ClusteredBitVector case_value =
enum_impl_strategy.getBitPatternForNoPayloadElement(enum_case.decl);
if (log)
log->Printf("case_name = %s, unmasked value = %s",
case_name.AsCString(), Dump(case_value).c_str());
case_value &= m_nopayload_elems_bitmask;
if (log)
log->Printf("case_name = %s, masked value = %s", case_name.AsCString(),
Dump(case_value).c_str());
std::unique_ptr<ElementInfo> elem_info(
new ElementInfo{case_name, CompilerType(), has_payload, is_indirect});
m_element_indexes.emplace(case_counter, elem_info.get());
case_counter++;
m_elements.emplace(case_value, std::move(elem_info));
}
}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"C-style enum - inspecting data to find enum case for type %s",
GetTypeName().AsCString());
swift::ClusteredBitVector current_payload;
lldb::offset_t offset = 0;
for (size_t idx = 0; idx < data.GetByteSize(); idx++) {
uint64_t byte = data.GetU8(&offset);
current_payload.add(8, byte);
}
if (log) {
log->Printf("m_nopayload_elems_bitmask = %s",
Dump(m_nopayload_elems_bitmask).c_str());
log->Printf("current_payload = %s",
Dump(current_payload).c_str());
}
if (current_payload.size() != m_nopayload_elems_bitmask.size()) {
if (log)
log->Printf("sizes don't match; getting out with an error");
return nullptr;
}
current_payload &= m_nopayload_elems_bitmask;
if (log)
log->Printf("masked current_payload = %s",
Dump(current_payload).c_str());
auto iter = m_elements.find(current_payload), end = m_elements.end();
if (iter == end) {
if (log)
log->Printf("bitmask search failed");
return nullptr;
}
if (log)
log->Printf("bitmask search success - found case %s",
iter->second.get()->name.AsCString());
return iter->second.get();
}
virtual size_t GetNumElementsWithPayload() { return 0; }
virtual size_t GetNumCStyleElements() { return m_elements.size(); }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
return nullptr;
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
if (idx >= m_element_indexes.size())
return nullptr;
return m_element_indexes[idx];
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::CStyle;
}
virtual ~SwiftCStyleEnumDescriptor() = default;
private:
swift::ClusteredBitVector m_nopayload_elems_bitmask;
std::map<swift::ClusteredBitVector, std::unique_ptr<ElementInfo>> m_elements;
std::map<uint64_t, ElementInfo *> m_element_indexes;
};
static CompilerType
GetFunctionArgumentTuple(const CompilerType &compiler_type) {
if (compiler_type.IsValid() &&
llvm::dyn_cast_or_null<SwiftASTContext>(compiler_type.GetTypeSystem())) {
swift::CanType swift_can_type(
GetCanonicalSwiftType(compiler_type.GetOpaqueQualType()));
swift::AnyFunctionType *func =
llvm::dyn_cast_or_null<swift::AnyFunctionType>(
swift_can_type.getPointer());
if (func) {
swift::TypeBase *input = func->getInput().getPointer();
if (!input)
return CompilerType();
// See comment in swift::AnyFunctionType for rationale here:
// A function can take either a tuple or a parentype, but if a parentype
// (i.e. (Foo)), then it will be reduced down to just Foo, so if the input
// is not a tuple, that must mean there is only 1 input.
swift::TupleType *tuple = llvm::dyn_cast_or_null<swift::TupleType>(input);
if (tuple)
return CompilerType(compiler_type.GetTypeSystem(), tuple);
else
return CompilerType(compiler_type.GetTypeSystem(), input);
}
}
return CompilerType();
}
class SwiftAllPayloadEnumDescriptor : public SwiftEnumDescriptor {
public:
SwiftAllPayloadEnumDescriptor(swift::ASTContext *ast,
swift::CanType swift_can_type,
swift::EnumDecl *enum_decl)
: SwiftEnumDescriptor(ast, swift_can_type, enum_decl,
SwiftEnumDescriptor::Kind::AllPayload),
m_tag_bits(), m_elements() {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf("doing ADT-style enum layout for %s",
GetTypeName().AsCString());
SwiftASTContext *swift_ast_ctx = SwiftASTContext::GetSwiftASTContext(ast);
swift::irgen::IRGenModule &irgen_module = swift_ast_ctx->GetIRGenModule();
const swift::irgen::EnumImplStrategy &enum_impl_strategy =
swift::irgen::getEnumImplStrategy(irgen_module, swift_can_type);
llvm::ArrayRef<swift::irgen::EnumImplStrategy::Element>
elements_with_payload = enum_impl_strategy.getElementsWithPayload();
m_tag_bits = enum_impl_strategy.getTagBitsForPayloads();
if (log)
log->Printf("tag_bits = %s", Dump(m_tag_bits).c_str());
auto module_ctx = enum_decl->getModuleContext();
const bool has_payload = true;
for (auto enum_case : elements_with_payload) {
ConstString case_name(enum_case.decl->getName().str().data());
swift::EnumElementDecl *case_decl = enum_case.decl;
assert(case_decl);
CompilerType case_type(
ast, swift_can_type->getTypeOfMember(module_ctx, case_decl)
.getPointer());
case_type = GetFunctionArgumentTuple(case_type.GetFunctionReturnType());
const bool is_indirect = case_decl->isIndirect()
|| case_decl->getParentEnum()->isIndirect();
if (log)
log->Printf("case_name = %s, type = %s, is_indirect = %s",
case_name.AsCString(), case_type.GetTypeName().AsCString(),
is_indirect ? "yes" : "no");
std::unique_ptr<ElementInfo> elem_info(
new ElementInfo{case_name, case_type, has_payload, is_indirect});
m_elements.push_back(std::move(elem_info));
}
}
virtual ElementInfo *
GetElementFromData(const lldb_private::DataExtractor &data) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TYPES));
if (log)
log->Printf(
"ADT-style enum - inspecting data to find enum case for type %s",
GetTypeName().AsCString());
if (m_elements.size() == 0) // no elements, just fail
{
if (log)
log->Printf("enum with no cases. getting out");
return nullptr;
}
if (m_elements.size() == 1) // one element, so it's gotta be it
{
if (log)
log->Printf("enum with one case. getting out easy with %s",
m_elements.front().get()->name.AsCString());
return m_elements.front().get();
}
swift::ClusteredBitVector current_payload;
lldb::offset_t offset = 0;
for (size_t idx = 0; idx < data.GetByteSize(); idx++) {
uint64_t byte = data.GetU8(&offset);
current_payload.add(8, byte);
}
if (log) {
log->Printf("tag_bits = %s", Dump(m_tag_bits).c_str());
log->Printf("current_payload = %s", Dump(current_payload).c_str());
}
if (current_payload.size() != m_tag_bits.size()) {
if (log)
log->Printf("sizes don't match; getting out with an error");
return nullptr;
}
size_t discriminator = 0;
size_t power_of_2 = 1;
auto enumerator = m_tag_bits.enumerateSetBits();
for (llvm::Optional<size_t> next = enumerator.findNext(); next.hasValue();
next = enumerator.findNext()) {
discriminator =
discriminator + (current_payload[next.getValue()] ? power_of_2 : 0);
power_of_2 <<= 1;
}
if (discriminator >= m_elements.size()) // discriminator too large, get out
{
if (log)
log->Printf("discriminator value of %" PRIu64 " too large, getting out",
(uint64_t)discriminator);
return nullptr;
} else {
auto ptr = m_elements[discriminator].get();
if (log) {
if (!ptr)
log->Printf("discriminator value of %" PRIu64
" acceptable, but null case matched - that's bad",
(uint64_t)discriminator);
else
log->Printf("discriminator value of %" PRIu64
" acceptable, case %s matched",
(uint64_t)discriminator, ptr->name.AsCString());
}
return ptr;
}
}
virtual size_t GetNumElementsWithPayload() { return m_elements.size(); }
virtual size_t GetNumCStyleElements() { return 0; }
virtual ElementInfo *GetElementWithPayloadAtIndex(size_t idx) {
if (idx >= m_elements.size())
return nullptr;
return m_elements[idx].get();
}
virtual ElementInfo *GetElementWithNoPayloadAtIndex(size_t idx) {
return nullptr;
}
static bool classof(const SwiftEnumDescriptor *S) {
return S->GetKind() == SwiftEnumDescriptor::Kind::AllPayload;
}
virtual ~SwiftAllPayloadEnumDescriptor() = default;
private:
swift::ClusteredBitVector m_tag_bits;
std::vector<std::unique_ptr<ElementInfo>> m_elements;
};
class SwiftMixedEnumDescriptor : public SwiftEnumDescriptor {