-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSerialization.cpp
7175 lines (6202 loc) · 272 KB
/
Serialization.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
//===--- Serialization.cpp - Read and write Swift modules -----------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "Serialization.h"
#include "ModuleFormat.h"
#include "SILFormat.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/AutoDiff.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Expr.h"
#include "swift/AST/FileSystem.h"
#include "swift/AST/ForeignAsyncConvention.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IndexSubset.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/LinkLibrary.h"
#include "swift/AST/MacroDefinition.h"
#include "swift/AST/Module.h"
#include "swift/AST/PackConformance.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILLayout.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/SynthesizedFileUnit.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/FileSystem.h"
#include "swift/Basic/LLVMExtras.h"
#include "swift/Basic/PathRemapper.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/ClangImporter/SwiftAbstractBasicWriter.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Serialization/Serialization.h"
#include "swift/Serialization/SerializationOptions.h"
#include "swift/Strings.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Bitcode/BitcodeConvenience.h"
#include "llvm/Bitstream/BitstreamWriter.h"
#include "llvm/Config/config.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/OnDiskHashTable.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include <vector>
#define DEBUG_TYPE "Serialization"
using namespace swift;
using namespace swift::serialization;
using namespace llvm::support;
using swift::version::Version;
using llvm::BCBlockRAII;
ASTContext &SerializerBase::getASTContext() const { return M->getASTContext(); }
/// Used for static_assert.
static constexpr bool declIDFitsIn32Bits() {
using Int32Info = std::numeric_limits<uint32_t>;
using PtrIntInfo = std::numeric_limits<uintptr_t>;
using DeclIDTraits = llvm::PointerLikeTypeTraits<DeclID>;
return PtrIntInfo::digits - DeclIDTraits::NumLowBitsAvailable <= Int32Info::digits;
}
/// Used for static_assert.
static constexpr bool bitOffsetFitsIn32Bits() {
// FIXME: Considering BitOffset is a _bit_ offset, and we're storing it in 31
// bits of a PointerEmbeddedInt, the maximum offset inside a modulefile we can
// handle happens at 2**28 _bytes_, which is only 268MB. Considering
// Swift.swiftmodule is itself 25MB, it seems entirely possible users will
// exceed this limit.
using Int32Info = std::numeric_limits<uint32_t>;
using PtrIntInfo = std::numeric_limits<uintptr_t>;
using BitOffsetTraits = llvm::PointerLikeTypeTraits<BitOffset>;
return PtrIntInfo::digits - BitOffsetTraits::NumLowBitsAvailable <= Int32Info::digits;
}
namespace {
/// Used to serialize the on-disk decl hash table.
class DeclTableInfo {
public:
using key_type = DeclBaseName;
using key_type_ref = key_type;
using data_type = Serializer::DeclTableData;
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
switch (key.getKind()) {
case DeclBaseName::Kind::Normal:
assert(!key.empty());
return llvm::djbHash(key.getIdentifier().str(),
SWIFTMODULE_HASH_SEED);
case DeclBaseName::Kind::Subscript:
return static_cast<uint8_t>(DeclNameKind::Subscript);
case DeclBaseName::Kind::Constructor:
return static_cast<uint8_t>(DeclNameKind::Constructor);
case DeclBaseName::Kind::Destructor:
return static_cast<uint8_t>(DeclNameKind::Destructor);
}
llvm_unreachable("unhandled kind");
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
uint32_t keyLength = sizeof(uint8_t); // For the flag of the name's kind
if (key.getKind() == DeclBaseName::Kind::Normal) {
keyLength += key.getIdentifier().str().size(); // The name's length
}
assert(keyLength == static_cast<uint16_t>(keyLength));
uint32_t dataLength = (sizeof(uint32_t) + 1) * data.size();
assert(dataLength == static_cast<uint16_t>(dataLength));
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint16_t>(keyLength);
writer.write<uint16_t>(dataLength);
return { keyLength, dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
endian::Writer writer(out, llvm::endianness::little);
switch (key.getKind()) {
case DeclBaseName::Kind::Normal:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Normal));
writer.OS << key.getIdentifier().str();
break;
case DeclBaseName::Kind::Subscript:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Subscript));
break;
case DeclBaseName::Kind::Constructor:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Constructor));
break;
case DeclBaseName::Kind::Destructor:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Destructor));
break;
}
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
endian::Writer writer(out, llvm::endianness::little);
for (auto entry : data) {
writer.write<uint8_t>(entry.first);
writer.write<uint32_t>(entry.second);
}
}
};
class ExtensionTableInfo {
serialization::Serializer &Serializer;
llvm::SmallDenseMap<const NominalTypeDecl *,std::string,4> MangledNameCache;
public:
explicit ExtensionTableInfo(serialization::Serializer &serializer)
: Serializer(serializer) {}
using key_type = Identifier;
using key_type_ref = key_type;
using data_type = Serializer::ExtensionTableData;
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
assert(!key.empty());
return llvm::djbHash(key.str(), SWIFTMODULE_HASH_SEED);
}
int32_t getNameDataForBase(const NominalTypeDecl *nominal,
StringRef *dataToWrite = nullptr) {
if (nominal->getDeclContext()->isModuleScopeContext())
return -Serializer.addContainingModuleRef(nominal->getDeclContext(),
/*ignoreExport=*/false);
auto &mangledName = MangledNameCache[nominal];
if (mangledName.empty())
mangledName = Mangle::ASTMangler(nominal->getASTContext()).mangleNominalType(nominal);
assert(llvm::isUInt<31>(mangledName.size()));
if (dataToWrite)
*dataToWrite = mangledName;
return mangledName.size();
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
uint32_t keyLength = key.str().size();
assert(keyLength == static_cast<uint16_t>(keyLength));
uint32_t dataLength = (sizeof(uint32_t) * 2) * data.size();
for (auto dataPair : data) {
int32_t nameData = getNameDataForBase(dataPair.first);
if (nameData > 0)
dataLength += nameData;
}
assert(dataLength == static_cast<uint16_t>(dataLength));
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint16_t>(keyLength);
writer.write<uint16_t>(dataLength);
return { keyLength, dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
out << key.str();
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
endian::Writer writer(out, llvm::endianness::little);
for (auto entry : data) {
StringRef dataToWrite;
writer.write<uint32_t>(entry.second);
writer.write<int32_t>(getNameDataForBase(entry.first, &dataToWrite));
out << dataToWrite;
}
}
};
class LocalDeclTableInfo {
public:
using key_type = std::string;
using key_type_ref = StringRef;
using data_type = DeclID;
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
assert(!key.empty());
return llvm::djbHash(key, SWIFTMODULE_HASH_SEED);
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
uint32_t keyLength = key.size();
assert(keyLength == static_cast<uint16_t>(keyLength));
uint32_t dataLength = sizeof(uint32_t);
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint16_t>(keyLength);
// No need to write the data length; it's constant.
return { keyLength, dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
out << key;
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint32_t>(data);
}
};
using LocalTypeHashTableGenerator =
llvm::OnDiskChainedHashTableGenerator<LocalDeclTableInfo>;
class NestedTypeDeclsTableInfo {
public:
using key_type = Identifier;
using key_type_ref = const key_type &;
using data_type = Serializer::NestedTypeDeclsData; // (parent, child) pairs
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
assert(!key.empty());
return llvm::djbHash(key.str(), SWIFTMODULE_HASH_SEED);
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
uint32_t keyLength = key.str().size();
assert(keyLength == static_cast<uint16_t>(keyLength));
uint32_t dataLength = (sizeof(uint32_t) * 2) * data.size();
assert(dataLength == static_cast<uint16_t>(dataLength));
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint16_t>(keyLength);
writer.write<uint16_t>(dataLength);
return { keyLength, dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
// FIXME: Avoid writing string data for identifiers here.
out << key.str();
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
endian::Writer writer(out, llvm::endianness::little);
for (auto entry : data) {
writer.write<uint32_t>(entry.first);
writer.write<uint32_t>(entry.second);
}
}
};
class DeclMemberNamesTableInfo {
public:
using key_type = DeclBaseName;
using key_type_ref = const key_type &;
using data_type = BitOffset; // Offsets to sub-tables
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
switch (key.getKind()) {
case DeclBaseName::Kind::Normal:
assert(!key.empty());
return llvm::djbHash(key.getIdentifier().str(), SWIFTMODULE_HASH_SEED);
case DeclBaseName::Kind::Subscript:
return static_cast<uint8_t>(DeclNameKind::Subscript);
case DeclBaseName::Kind::Constructor:
return static_cast<uint8_t>(DeclNameKind::Constructor);
case DeclBaseName::Kind::Destructor:
return static_cast<uint8_t>(DeclNameKind::Destructor);
}
llvm_unreachable("unhandled kind");
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
uint32_t keyLength = sizeof(uint8_t); // For the flag of the name's kind
if (key.getKind() == DeclBaseName::Kind::Normal) {
keyLength += key.getIdentifier().str().size(); // The name's length
}
assert(keyLength == static_cast<uint16_t>(keyLength));
uint32_t dataLength = sizeof(uint32_t);
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint16_t>(keyLength);
// No need to write dataLength, it's constant.
return { keyLength, dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
endian::Writer writer(out, llvm::endianness::little);
switch (key.getKind()) {
case DeclBaseName::Kind::Normal:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Normal));
writer.OS << key.getIdentifier().str();
break;
case DeclBaseName::Kind::Subscript:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Subscript));
break;
case DeclBaseName::Kind::Constructor:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Constructor));
break;
case DeclBaseName::Kind::Destructor:
writer.write<uint8_t>(static_cast<uint8_t>(DeclNameKind::Destructor));
break;
}
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(bitOffsetFitsIn32Bits(), "BitOffset too large");
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint32_t>(static_cast<uint32_t>(data));
}
};
class DeclMembersTableInfo {
public:
using key_type = DeclID;
using key_type_ref = const key_type &;
using data_type = Serializer::DeclMembersData; // Vector of DeclIDs
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
return key;
}
std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &out,
key_type_ref key,
data_type_ref data) {
// This will trap if a single ValueDecl has more than 16383 members
// with the same DeclBaseName. Seems highly unlikely.
assert((data.size() < (1 << 14)) && "Too many members");
uint32_t dataLength = sizeof(uint32_t) * data.size(); // value DeclIDs
endian::Writer writer(out, llvm::endianness::little);
// No need to write the key length; it's constant.
writer.write<uint16_t>(dataLength);
return { sizeof(uint32_t), dataLength };
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
assert(len == sizeof(uint32_t));
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint32_t>(key);
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
endian::Writer writer(out, llvm::endianness::little);
for (auto entry : data) {
writer.write<uint32_t>(entry);
}
}
};
// Side table information for serializing the table keyed under
// \c DeclFingerprintsLayout.
class DeclFingerprintsTableInfo {
public:
using key_type = DeclID;
using key_type_ref = const key_type &;
using data_type = Fingerprint;
using data_type_ref = const data_type &;
using hash_value_type = uint32_t;
using offset_type = unsigned;
hash_value_type ComputeHash(key_type_ref key) {
return key;
}
std::pair<unsigned, unsigned>
EmitKeyDataLength(raw_ostream &out, key_type_ref key, data_type_ref data) {
endian::Writer writer(out, llvm::endianness::little);
// No need to write the key or value length; they're both constant.
const unsigned valueLen = Fingerprint::DIGEST_LENGTH;
return {sizeof(uint32_t), valueLen};
}
void EmitKey(raw_ostream &out, key_type_ref key, unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
assert(len == sizeof(uint32_t));
endian::Writer writer(out, llvm::endianness::little);
writer.write<uint32_t>(key);
}
void EmitData(raw_ostream &out, key_type_ref key, data_type_ref data,
unsigned len) {
static_assert(declIDFitsIn32Bits(), "DeclID too large");
assert(len == Fingerprint::DIGEST_LENGTH);
endian::Writer writer(out, llvm::endianness::little);
out << data;
}
};
} // end anonymous namespace
static ModuleDecl *getModule(ModuleOrSourceFile DC) {
if (auto M = DC.dyn_cast<ModuleDecl *>())
return M;
return DC.get<SourceFile *>()->getParentModule();
}
static bool shouldSerializeAsLocalContext(const DeclContext *DC) {
return DC->isLocalContext() && !isa<AbstractFunctionDecl>(DC) &&
!isa<SubscriptDecl>(DC) && !isa<EnumElementDecl>(DC) &&
!isa<MacroDecl>(DC);
}
namespace {
struct Accessors {
uint8_t OpaqueReadOwnership;
uint8_t ReadImpl, WriteImpl, ReadWriteImpl;
SmallVector<AccessorDecl *, 8> Decls;
};
} // end anonymous namespace
static uint8_t getRawOpaqueReadOwnership(swift::OpaqueReadOwnership ownership) {
switch (ownership) {
#define CASE(KIND) \
case swift::OpaqueReadOwnership::KIND: \
return uint8_t(serialization::OpaqueReadOwnership::KIND);
CASE(Owned)
CASE(Borrowed)
CASE(OwnedOrBorrowed)
#undef CASE
}
llvm_unreachable("bad kind");
}
static uint8_t getRawReadImplKind(swift::ReadImplKind kind) {
switch (kind) {
#define CASE(KIND) \
case swift::ReadImplKind::KIND: \
return uint8_t(serialization::ReadImplKind::KIND);
CASE(Stored)
CASE(Get)
CASE(Inherited)
CASE(Address)
CASE(Read)
CASE(Read2)
#undef CASE
}
llvm_unreachable("bad kind");
}
static unsigned getRawWriteImplKind(swift::WriteImplKind kind) {
switch (kind) {
#define CASE(KIND) \
case swift::WriteImplKind::KIND: \
return uint8_t(serialization::WriteImplKind::KIND);
CASE(Immutable)
CASE(Stored)
CASE(Set)
CASE(StoredWithObservers)
CASE(InheritedWithObservers)
CASE(MutableAddress)
CASE(Modify)
CASE(Modify2)
#undef CASE
}
llvm_unreachable("bad kind");
}
static unsigned getRawReadWriteImplKind(swift::ReadWriteImplKind kind) {
switch (kind) {
#define CASE(KIND) \
case swift::ReadWriteImplKind::KIND: \
return uint8_t(serialization::ReadWriteImplKind::KIND);
CASE(Immutable)
CASE(Stored)
CASE(MutableAddress)
CASE(MaterializeToTemporary)
CASE(Modify)
CASE(Modify2)
CASE(StoredWithDidSet)
CASE(InheritedWithDidSet)
#undef CASE
}
llvm_unreachable("bad kind");
}
static Accessors getAccessors(const AbstractStorageDecl *storage) {
Accessors accessors;
accessors.OpaqueReadOwnership =
getRawOpaqueReadOwnership(storage->getOpaqueReadOwnership());
auto impl = storage->getImplInfo();
accessors.ReadImpl = getRawReadImplKind(impl.getReadImpl());
accessors.WriteImpl = getRawWriteImplKind(impl.getWriteImpl());
accessors.ReadWriteImpl = getRawReadWriteImplKind(impl.getReadWriteImpl());
auto decls = storage->getAllAccessors();
accessors.Decls.append(decls.begin(), decls.end());
return accessors;
}
LocalDeclContextID Serializer::addLocalDeclContextRef(const DeclContext *DC) {
assert(DC->isLocalContext() && "Expected a local DeclContext");
return LocalDeclContextsToSerialize.addRef(DC);
}
GenericSignatureID
Serializer::addGenericSignatureRef(GenericSignature sig) {
if (!sig)
return 0;
return GenericSignaturesToSerialize.addRef(sig);
}
GenericEnvironmentID
Serializer::addGenericEnvironmentRef(GenericEnvironment *env) {
if (!env)
return 0;
return GenericEnvironmentsToSerialize.addRef(env);
}
SubstitutionMapID
Serializer::addSubstitutionMapRef(SubstitutionMap substitutions) {
return SubstitutionMapsToSerialize.addRef(substitutions);
}
DeclContextID Serializer::addDeclContextRef(const DeclContext *DC) {
assert(DC && "cannot reference a null DeclContext");
switch (DC->getContextKind()) {
case DeclContextKind::Package:
case DeclContextKind::Module:
case DeclContextKind::FileUnit: // Skip up to the module
return DeclContextID();
default:
break;
}
// If this decl context is a plain old serializable decl, queue it up for
// normal serialization.
if (shouldSerializeAsLocalContext(DC))
return DeclContextID::forLocalDeclContext(addLocalDeclContextRef(DC));
return DeclContextID::forDecl(addDeclRef(DC->getAsDecl()));
}
DeclID Serializer::addDeclRef(const Decl *D, bool allowTypeAliasXRef) {
assert((!D || !isDeclXRef(D) || isa<ValueDecl>(D) || isa<OperatorDecl>(D) ||
isa<PrecedenceGroupDecl>(D)) &&
"cannot cross-reference this decl");
assert((!D || allowTypeAliasXRef || !isa<TypeAliasDecl>(D) ||
D->getModuleContext() == M) &&
"cannot cross-reference typealiases directly (use the TypeAliasType)");
return DeclsToSerialize.addRef(D);
}
serialization::TypeID Serializer::addTypeRef(Type ty) {
Type typeToSerialize = ty;
if (ty) {
if (auto nominalDecl = ty->getAnyNominal()) {
if (auto structDecl = dyn_cast<StructDecl>(nominalDecl)) {
if (auto templateInstantiationType =
structDecl->getTemplateInstantiationType()) {
typeToSerialize = templateInstantiationType;
}
}
}
}
#ifndef NDEBUG
PrettyStackTraceType trace(M->getASTContext(), "serializing", typeToSerialize);
assert((allowCompilerErrors() || !typeToSerialize ||
!typeToSerialize->hasError()) &&
"serializing type with an error");
#endif
return TypesToSerialize.addRef(typeToSerialize);
}
serialization::ClangTypeID Serializer::addClangTypeRef(const clang::Type *ty) {
if (!ty) return 0;
// Try to serialize the non-canonical type, but fall back to the
// canonical type if necessary.
auto loader = getASTContext().getClangModuleLoader();
bool isSerializable;
if (loader->isSerializable(ty, false)) {
isSerializable = true;
} else if (!ty->isCanonicalUnqualified()) {
ty = ty->getCanonicalTypeInternal().getTypePtr();
isSerializable = loader->isSerializable(ty, false);
} else {
isSerializable = false;
}
if (!isSerializable) {
PrettyStackTraceClangType trace(loader->getClangASTContext(),
"staging a serialized reference to", ty);
llvm::report_fatal_error("Clang function type is not serializable");
}
return ClangTypesToSerialize.addRef(ty);
}
IdentifierID Serializer::addDeclBaseNameRef(DeclBaseName ident) {
switch (ident.getKind()) {
case DeclBaseName::Kind::Normal: {
if (ident.empty())
return 0;
IdentifierID &id = IdentifierIDs[ident.getIdentifier()];
if (id != 0)
return id;
id = ++LastUniquedStringID;
StringsToWrite.push_back(ident.getIdentifier().str());
return id;
}
case DeclBaseName::Kind::Subscript:
return SUBSCRIPT_ID;
case DeclBaseName::Kind::Constructor:
return CONSTRUCTOR_ID;
case DeclBaseName::Kind::Destructor:
return DESTRUCTOR_ID;
}
llvm_unreachable("unhandled kind");
}
std::pair<StringRef, IdentifierID> Serializer::addUniquedString(StringRef str) {
if (str.empty())
return {str, 0};
decltype(UniquedStringIDs)::iterator iter;
bool isNew;
std::tie(iter, isNew) =
UniquedStringIDs.insert({str, LastUniquedStringID + 1});
if (!isNew)
return {iter->getKey(), iter->getValue()};
++LastUniquedStringID;
// Note that we use the string data stored in the StringMap.
StringsToWrite.push_back(iter->getKey());
return {iter->getKey(), LastUniquedStringID};
}
IdentifierID Serializer::addFilename(StringRef filename) {
assert(!filename.empty() && "Attempting to add an empty filename");
return addUniquedString(filename).second;
}
IdentifierID Serializer::addContainingModuleRef(const DeclContext *DC,
bool ignoreExport) {
assert(!isa<ModuleDecl>(DC) &&
"References should be to things within modules");
const FileUnit *file = cast<FileUnit>(DC->getModuleScopeContext());
const ModuleDecl *M = file->getParentModule();
if (M == this->M)
return CURRENT_MODULE_ID;
if (M == this->M->getASTContext().TheBuiltinModule)
return BUILTIN_MODULE_ID;
if (M->isClangHeaderImportModule())
return OBJC_HEADER_MODULE_ID;
auto exportedModuleName = file->getExportedModuleName();
assert(!exportedModuleName.empty());
auto moduleID = M->getASTContext().getIdentifier(exportedModuleName);
if (ignoreExport) {
auto realModuleName = M->getRealName().str();
assert(!realModuleName.empty());
if (realModuleName != exportedModuleName) {
// Still register the exported name as it can be referenced
// from the lookup tables.
addDeclBaseNameRef(moduleID);
moduleID = M->getASTContext().getIdentifier(realModuleName);
}
}
return addDeclBaseNameRef(moduleID);
}
IdentifierID Serializer::addModuleRef(const ModuleDecl *module) {
if (module == this->M)
return CURRENT_MODULE_ID;
if (module == this->M->getASTContext().TheBuiltinModule)
return BUILTIN_MODULE_ID;
// Use module 'real name', which can be different from 'name'
// in case module aliasing was used (-module-alias flag)
auto moduleName =
module->getASTContext().getIdentifier(module->getRealName().str());
return addDeclBaseNameRef(moduleName);
}
SILLayoutID Serializer::addSILLayoutRef(const SILLayout *layout) {
return SILLayoutsToSerialize.addRef(layout);
}
/// Record the name of a block.
void SerializerBase::emitBlockID(unsigned ID, StringRef name,
SmallVectorImpl<unsigned char> &nameBuffer) {
SmallVector<unsigned, 1> idBuffer;
idBuffer.push_back(ID);
Out.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, idBuffer);
// Emit the block name if present.
if (name.empty())
return;
nameBuffer.resize(name.size());
memcpy(nameBuffer.data(), name.data(), name.size());
Out.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, nameBuffer);
}
void SerializerBase::emitRecordID(unsigned ID, StringRef name,
SmallVectorImpl<unsigned char> &nameBuffer,
SmallVectorImpl<unsigned> *wideNameBuffer) {
// Use the byte-based buffer if the ID is in range.
if (ID < 256) {
nameBuffer.resize(name.size()+1);
nameBuffer[0] = ID;
memcpy(nameBuffer.data()+1, name.data(), name.size());
Out.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, nameBuffer);
// Otherwise, we have to use the wide name buffer.
} else {
assert(wideNameBuffer && "too many IDs to use narrow name buffer");
auto &buffer = *wideNameBuffer;
buffer.resize(name.size()+1);
buffer[0] = ID;
for (unsigned i = 0, e = name.size(); i != e; ++i)
buffer[i+1] = name[i];
Out.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, buffer);
}
}
void Serializer::writeBlockInfoBlock() {
BCBlockRAII restoreBlock(Out, llvm::bitc::BLOCKINFO_BLOCK_ID, 2);
SmallVector<unsigned char, 64> nameBuffer;
SmallVector<unsigned, 32> wideNameBuffer;
#define BLOCK(X) emitBlockID(X ## _ID, #X, nameBuffer)
#define BLOCK_RECORD(K, X) emitRecordID(K::X, #X, nameBuffer, &wideNameBuffer)
BLOCK(MODULE_BLOCK);
BLOCK(CONTROL_BLOCK);
BLOCK_RECORD(control_block, METADATA);
BLOCK_RECORD(control_block, MODULE_NAME);
BLOCK_RECORD(control_block, TARGET);
BLOCK_RECORD(control_block, SDK_NAME);
BLOCK_RECORD(control_block, REVISION);
BLOCK_RECORD(control_block, IS_OSSA);
BLOCK_RECORD(control_block, ALLOWABLE_CLIENT_NAME);
BLOCK_RECORD(control_block, CHANNEL);
BLOCK_RECORD(control_block, SDK_VERSION);
BLOCK(OPTIONS_BLOCK);
BLOCK_RECORD(options_block, SDK_PATH);
BLOCK_RECORD(options_block, XCC);
BLOCK_RECORD(options_block, IS_SIB);
BLOCK_RECORD(options_block, IS_STATIC_LIBRARY);
BLOCK_RECORD(options_block, HAS_HERMETIC_SEAL_AT_LINK);
BLOCK_RECORD(options_block, IS_EMBEDDED_SWIFT_MODULE);
BLOCK_RECORD(options_block, IS_TESTABLE);
BLOCK_RECORD(options_block, RESILIENCE_STRATEGY);
BLOCK_RECORD(options_block, ARE_PRIVATE_IMPORTS_ENABLED);
BLOCK_RECORD(options_block, IS_IMPLICIT_DYNAMIC_ENABLED);
BLOCK_RECORD(options_block, IS_BUILT_FROM_INTERFACE);
BLOCK_RECORD(options_block, IS_ALLOW_MODULE_WITH_COMPILER_ERRORS_ENABLED);
BLOCK_RECORD(options_block, MODULE_ABI_NAME);
BLOCK_RECORD(options_block, IS_CONCURRENCY_CHECKED);
BLOCK_RECORD(options_block, MODULE_PACKAGE_NAME);
BLOCK_RECORD(options_block, MODULE_EXPORT_AS_NAME);
BLOCK_RECORD(options_block, PLUGIN_SEARCH_OPTION);
BLOCK_RECORD(options_block, HAS_CXX_INTEROPERABILITY_ENABLED);
BLOCK_RECORD(options_block, ALLOW_NON_RESILIENT_ACCESS);
BLOCK_RECORD(options_block, SERIALIZE_PACKAGE_ENABLED);
BLOCK_RECORD(options_block, STRICT_MEMORY_SAFETY);
BLOCK_RECORD(options_block, CXX_STDLIB_KIND);
BLOCK_RECORD(options_block, PUBLIC_MODULE_NAME);
BLOCK_RECORD(options_block, SWIFT_INTERFACE_COMPILER_VERSION);
BLOCK(INPUT_BLOCK);
BLOCK_RECORD(input_block, IMPORTED_MODULE);
BLOCK_RECORD(input_block, LINK_LIBRARY);
BLOCK_RECORD(input_block, IMPORTED_HEADER);
BLOCK_RECORD(input_block, IMPORTED_HEADER_CONTENTS);
BLOCK_RECORD(input_block, MODULE_FLAGS);
BLOCK_RECORD(input_block, SEARCH_PATH);
BLOCK_RECORD(input_block, FILE_DEPENDENCY);
BLOCK_RECORD(input_block, DEPENDENCY_DIRECTORY);
BLOCK_RECORD(input_block, MODULE_INTERFACE_PATH);
BLOCK_RECORD(input_block, IMPORTED_MODULE_SPIS);
BLOCK_RECORD(input_block, EXTERNAL_MACRO);
BLOCK(DECLS_AND_TYPES_BLOCK);
#define RECORD(X) BLOCK_RECORD(decls_block, X);
#include "DeclTypeRecordNodes.def"
BLOCK(IDENTIFIER_DATA_BLOCK);
BLOCK_RECORD(identifier_block, IDENTIFIER_DATA);
BLOCK(INDEX_BLOCK);
BLOCK_RECORD(index_block, TYPE_OFFSETS);
BLOCK_RECORD(index_block, DECL_OFFSETS);
BLOCK_RECORD(index_block, IDENTIFIER_OFFSETS);
BLOCK_RECORD(index_block, TOP_LEVEL_DECLS);
BLOCK_RECORD(index_block, OPERATORS);
BLOCK_RECORD(index_block, EXTENSIONS);
BLOCK_RECORD(index_block, CLASS_MEMBERS_FOR_DYNAMIC_LOOKUP);
BLOCK_RECORD(index_block, OPERATOR_METHODS);
BLOCK_RECORD(index_block, OBJC_METHODS);
BLOCK_RECORD(index_block, DERIVATIVE_FUNCTION_CONFIGURATIONS);
BLOCK_RECORD(index_block, ENTRY_POINT);
BLOCK_RECORD(index_block, LOCAL_DECL_CONTEXT_OFFSETS);
BLOCK_RECORD(index_block, GENERIC_SIGNATURE_OFFSETS);
BLOCK_RECORD(index_block, GENERIC_ENVIRONMENT_OFFSETS);
BLOCK_RECORD(index_block, SUBSTITUTION_MAP_OFFSETS);
BLOCK_RECORD(index_block, CLANG_TYPE_OFFSETS);
BLOCK_RECORD(index_block, LOCAL_TYPE_DECLS);
BLOCK_RECORD(index_block, OPAQUE_RETURN_TYPE_DECLS);
BLOCK_RECORD(index_block, PROTOCOL_CONFORMANCE_OFFSETS);
BLOCK_RECORD(index_block, PACK_CONFORMANCE_OFFSETS);
BLOCK_RECORD(index_block, SIL_LAYOUT_OFFSETS);
BLOCK_RECORD(index_block, PRECEDENCE_GROUPS);
BLOCK_RECORD(index_block, NESTED_TYPE_DECLS);
BLOCK_RECORD(index_block, DECL_MEMBER_NAMES);
BLOCK_RECORD(index_block, DECL_FINGERPRINTS);
BLOCK_RECORD(index_block, ORDERED_TOP_LEVEL_DECLS);
BLOCK_RECORD(index_block, EXPORTED_PRESPECIALIZATION_DECLS);
BLOCK(DECL_MEMBER_TABLES_BLOCK);
BLOCK_RECORD(decl_member_tables_block, DECL_MEMBERS);
BLOCK(SIL_BLOCK);
BLOCK_RECORD(sil_block, SIL_FUNCTION);
BLOCK_RECORD(sil_block, SIL_BASIC_BLOCK);
BLOCK_RECORD(sil_block, SIL_ONE_VALUE_ONE_OPERAND);
BLOCK_RECORD(sil_block, SIL_ONE_TYPE);
BLOCK_RECORD(sil_block, SIL_ONE_OPERAND);
BLOCK_RECORD(sil_block, SIL_ONE_TYPE_ONE_OPERAND);
BLOCK_RECORD(sil_block, SIL_ONE_TYPE_VALUES);
BLOCK_RECORD(sil_block, SIL_ONE_TYPE_OWNERSHIP_VALUES);
BLOCK_RECORD(sil_block, SIL_TWO_OPERANDS);
BLOCK_RECORD(sil_block, SIL_TAIL_ADDR);
BLOCK_RECORD(sil_block, SIL_INST_APPLY);
BLOCK_RECORD(sil_block, SIL_INST_NO_OPERAND);
BLOCK_RECORD(sil_block, SIL_VTABLE);
BLOCK_RECORD(sil_block, SIL_VTABLE_ENTRY);
BLOCK_RECORD(sil_block, SIL_GLOBALVAR);
BLOCK_RECORD(sil_block, SIL_INIT_EXISTENTIAL);
BLOCK_RECORD(sil_block, SIL_WITNESS_TABLE);
BLOCK_RECORD(sil_block, SIL_WITNESS_METHOD_ENTRY);
BLOCK_RECORD(sil_block, SIL_WITNESS_BASE_ENTRY);
BLOCK_RECORD(sil_block, SIL_WITNESS_ASSOC_PROTOCOL);
BLOCK_RECORD(sil_block, SIL_WITNESS_ASSOC_ENTRY);
BLOCK_RECORD(sil_block, SIL_WITNESS_CONDITIONAL_CONFORMANCE);
BLOCK_RECORD(sil_block, SIL_DEFAULT_WITNESS_TABLE);
BLOCK_RECORD(sil_block, SIL_DEFAULT_WITNESS_TABLE_NO_ENTRY);
BLOCK_RECORD(sil_block, SIL_INST_WITNESS_METHOD);
BLOCK_RECORD(sil_block, SIL_SPECIALIZE_ATTR);
BLOCK_RECORD(sil_block, SIL_ARG_EFFECTS_ATTR);
BLOCK_RECORD(sil_block, SIL_ONE_OPERAND_EXTRA_ATTR);
BLOCK_RECORD(sil_block, SIL_ONE_TYPE_ONE_OPERAND_EXTRA_ATTR);
BLOCK_RECORD(sil_block, SIL_TWO_OPERANDS_EXTRA_ATTR);
BLOCK_RECORD(sil_block, SIL_INST_DIFFERENTIABLE_FUNCTION);
BLOCK_RECORD(sil_block, SIL_INST_LINEAR_FUNCTION);
BLOCK_RECORD(sil_block, SIL_INST_DIFFERENTIABLE_FUNCTION_EXTRACT);
BLOCK_RECORD(sil_block, SIL_INST_LINEAR_FUNCTION_EXTRACT);
BLOCK_RECORD(sil_block, SIL_INST_INCREMENT_PROFILER_COUNTER);
BLOCK_RECORD(sil_block, SIL_MOVEONLY_DEINIT);
BLOCK_RECORD(sil_block, SIL_INST_HAS_SYMBOL);
BLOCK_RECORD(sil_block, SIL_OPEN_PACK_ELEMENT);
BLOCK_RECORD(sil_block, SIL_PACK_ELEMENT_GET);
BLOCK_RECORD(sil_block, SIL_PACK_ELEMENT_SET);
BLOCK_RECORD(sil_block, SIL_TYPE_VALUE);
BLOCK_RECORD(sil_block, SIL_DEBUG_SCOPE);
BLOCK_RECORD(sil_block, SIL_DEBUG_SCOPE_REF);
BLOCK_RECORD(sil_block, SIL_SOURCE_LOC);
BLOCK_RECORD(sil_block, SIL_SOURCE_LOC_REF);
BLOCK_RECORD(sil_block, SIL_DEBUG_VALUE);
BLOCK_RECORD(sil_block, SIL_DEBUG_VALUE_DELIMITER);
BLOCK(SIL_INDEX_BLOCK);
BLOCK_RECORD(sil_index_block, SIL_FUNC_NAMES);
BLOCK_RECORD(sil_index_block, SIL_FUNC_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_VTABLE_NAMES);
BLOCK_RECORD(sil_index_block, SIL_VTABLE_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_MOVEONLYDEINIT_NAMES);
BLOCK_RECORD(sil_index_block, SIL_MOVEONLYDEINIT_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_GLOBALVAR_NAMES);
BLOCK_RECORD(sil_index_block, SIL_GLOBALVAR_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_WITNESS_TABLE_NAMES);
BLOCK_RECORD(sil_index_block, SIL_WITNESS_TABLE_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_DEFAULT_WITNESS_TABLE_NAMES);
BLOCK_RECORD(sil_index_block, SIL_DEFAULT_WITNESS_TABLE_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_PROPERTY_OFFSETS);
BLOCK_RECORD(sil_index_block, SIL_DIFFERENTIABILITY_WITNESS_NAMES);
BLOCK_RECORD(sil_index_block, SIL_DIFFERENTIABILITY_WITNESS_OFFSETS);
BLOCK(INCREMENTAL_INFORMATION_BLOCK);
BLOCK_RECORD(fine_grained_dependencies::record_block, METADATA);
BLOCK_RECORD(fine_grained_dependencies::record_block, SOURCE_FILE_DEP_GRAPH_NODE);
BLOCK_RECORD(fine_grained_dependencies::record_block, FINGERPRINT_NODE);
BLOCK_RECORD(fine_grained_dependencies::record_block, DEPENDS_ON_DEFINITION_NODE);
BLOCK_RECORD(fine_grained_dependencies::record_block, IDENTIFIER_NODE);
#undef BLOCK
#undef BLOCK_RECORD
}
void Serializer::writeHeader() {