-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDeserialization.cpp
8832 lines (7472 loc) · 308 KB
/
Deserialization.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
//===--- Deserialization.cpp - Loading a serialized AST -------------------===//
//
// 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 "BCReadingExtras.h"
#include "DeserializationErrors.h"
#include "ModuleFile.h"
#include "ModuleFormat.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AttrKind.h"
#include "swift/AST/AutoDiff.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignAsyncConvention.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/MacroDefinition.h"
#include "swift/AST/NameLookupRequests.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/TypeCheckRequests.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/ClangImporter/SwiftAbstractBasicReader.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Attr.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/AttributeCommonInfo.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "Serialization"
STATISTIC(NumDeclsLoaded, "# of decls deserialized");
STATISTIC(NumMemberListsLoaded,
"# of nominals/extensions whose members were loaded");
STATISTIC(NumNormalProtocolConformancesLoaded,
"# of normal protocol conformances deserialized");
STATISTIC(NumNormalProtocolConformancesCompleted,
"# of normal protocol conformances completed");
STATISTIC(NumNestedTypeShortcuts,
"# of nested types resolved without full lookup");
using namespace swift;
using namespace swift::serialization;
using llvm::Expected;
namespace {
struct DeclAndOffset {
const Decl *D;
uint64_t offset;
};
static raw_ostream &operator<<(raw_ostream &os, DeclAndOffset &&pair) {
return os << Decl::getKindName(pair.D->getKind())
<< "Decl @ " << pair.offset;
}
class PrettyDeclDeserialization : public llvm::PrettyStackTraceEntry {
const ModuleFile *MF;
const ModuleFile::Serialized<Decl*> &DeclOrOffset;
uint64_t offset;
decls_block::RecordKind Kind;
public:
PrettyDeclDeserialization(ModuleFile *module,
const ModuleFile::Serialized<Decl*> &declOrOffset,
decls_block::RecordKind kind)
: MF(module), DeclOrOffset(declOrOffset), offset(declOrOffset),
Kind(kind) {
}
static const char *getRecordKindString(decls_block::RecordKind Kind) {
switch (Kind) {
#define RECORD(Id) case decls_block::Id: return #Id;
#include "DeclTypeRecordNodes.def"
}
llvm_unreachable("Unhandled RecordKind in switch.");
}
void print(raw_ostream &os) const override {
if (!DeclOrOffset.isComplete()) {
os << "While deserializing decl @ " << offset << " ("
<< getRecordKindString(Kind) << ")";
} else {
os << "While deserializing ";
if (auto VD = dyn_cast<ValueDecl>(DeclOrOffset.get())) {
os << "'" << VD->getBaseName() << "' (" << DeclAndOffset{VD, offset}
<< ")";
} else if (auto ED = dyn_cast<ExtensionDecl>(DeclOrOffset.get())) {
os << "extension of '" << ED->getExtendedType() << "' ("
<< DeclAndOffset{ED, offset} << ")";
} else {
os << DeclAndOffset{DeclOrOffset.get(), offset};
}
}
os << " in '" << MF->getName() << "'\n";
}
};
class PrettySupplementalDeclNameTrace : public llvm::PrettyStackTraceEntry {
DeclName name;
public:
PrettySupplementalDeclNameTrace(DeclName name)
: name(name) { }
void print(raw_ostream &os) const override {
os << " ...decl is named '" << name << "'\n";
}
};
class PrettyXRefTrace :
public llvm::PrettyStackTraceEntry,
public XRefTracePath {
public:
explicit PrettyXRefTrace(ModuleDecl &M) : XRefTracePath(M) {}
void print(raw_ostream &os) const override {
XRefTracePath::print(os, "\t");
}
};
} // end anonymous namespace
const char DeclDeserializationError::ID = '\0';
void DeclDeserializationError::anchor() {}
const char XRefError::ID = '\0';
void XRefError::anchor() {}
const char XRefNonLoadedModuleError::ID = '\0';
void XRefNonLoadedModuleError::anchor() {}
const char OverrideError::ID = '\0';
void OverrideError::anchor() {}
const char TypeError::ID = '\0';
void TypeError::anchor() {}
const char ExtensionError::ID = '\0';
void ExtensionError::anchor() {}
const char DeclAttributesDidNotMatch::ID = '\0';
void DeclAttributesDidNotMatch::anchor() {}
const char InvalidRecordKindError::ID = '\0';
void InvalidRecordKindError::anchor() {}
const char UnsafeDeserializationError::ID = '\0';
void UnsafeDeserializationError::anchor() {}
const char ModularizationError::ID = '\0';
void ModularizationError::anchor() {}
const char InvalidEnumValueError::ID = '\0';
void InvalidEnumValueError::anchor() {}
/// Skips a single record in the bitstream.
///
/// Destroys the stream position if the next entry is not a record.
static void skipRecord(llvm::BitstreamCursor &cursor, unsigned recordKind) {
auto next = llvm::cantFail<llvm::BitstreamEntry>(
cursor.advance(AF_DontPopBlockAtEnd));
assert(next.Kind == llvm::BitstreamEntry::Record);
unsigned kind = llvm::cantFail<unsigned>(cursor.skipRecord(next.ID));
assert(kind == recordKind);
(void)kind;
}
char FatalDeserializationError::ID;
void ModuleFile::fatal(llvm::Error error) const {
Core->fatal(diagnoseFatal(std::move(error)));
}
SourceLoc ModuleFile::getSourceLoc() const {
auto &SourceMgr = getContext().Diags.SourceMgr;
auto filename = getModuleFilename();
auto bufferID = SourceMgr.getIDForBufferIdentifier(filename);
if (!bufferID)
bufferID = SourceMgr.addMemBufferCopy("<binary format>", filename);
return SourceMgr.getLocForBufferStart(*bufferID);
}
SourceLoc ModularizationError::getSourceLoc() const {
auto &SourceMgr = referenceModule->getContext().Diags.SourceMgr;
auto filename = referenceModule->getModuleFilename();
// Synthesize some context. We don't have an actual decl here
// so try to print a simple representation of the reference.
std::string S;
llvm::raw_string_ostream OS(S);
OS << expectedModule->getName() << "." << name;
// If we enable these remarks by default we may want to reuse these buffers.
auto bufferID = SourceMgr.addMemBufferCopy(S, filename);
return SourceMgr.getLocForBufferStart(bufferID);
}
void
ModularizationError::diagnose(const ModuleFile *MF,
DiagnosticBehavior limit) const {
auto &ctx = MF->getContext();
auto loc = getSourceLoc();
auto diagnoseError = [&](Kind errorKind) {
switch (errorKind) {
case Kind::DeclMoved:
return ctx.Diags.diagnose(loc,
diag::modularization_issue_decl_moved,
declIsType, name, expectedModule,
foundModule);
case Kind::DeclKindChanged:
return
ctx.Diags.diagnose(loc,
diag::modularization_issue_decl_type_changed,
declIsType, name, expectedModule,
referenceModule->getName(), foundModule,
foundModule != expectedModule);
case Kind::DeclNotFound:
return ctx.Diags.diagnose(loc,
diag::modularization_issue_decl_not_found,
declIsType, name, expectedModule);
}
llvm_unreachable("Unhandled ModularizationError::Kind in switch.");
};
auto inFlight = diagnoseError(errorKind);
inFlight.limitBehavior(limit);
inFlight.flush();
// We could pass along the `path` information through notes.
// However, for a top-level decl a path would just duplicate the
// expected module name and the decl name from the diagnostic.
// Show context with relevant file paths.
ctx.Diags.diagnose(loc,
diag::modularization_issue_note_expected,
declIsType, expectedModule,
expectedModule->getModuleSourceFilename());
const clang::Module *expectedUnderlying =
expectedModule->findUnderlyingClangModule();
if (!expectedModule->isNonSwiftModule() &&
expectedUnderlying) {
auto CML = ctx.getClangModuleLoader();
auto &CSM = CML->getClangASTContext().getSourceManager();
StringRef filename = CSM.getFilename(expectedUnderlying->DefinitionLoc);
ctx.Diags.diagnose(loc,
diag::modularization_issue_note_expected_underlying,
expectedUnderlying->Name,
filename);
}
if (foundModule)
ctx.Diags.diagnose(loc,
diag::modularization_issue_note_found,
declIsType, foundModule,
foundModule->getModuleSourceFilename());
if (mismatchingTypes.has_value()) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_type_mismatch,
mismatchingTypes->first, mismatchingTypes->second);
}
// A Swift language version mismatch could lead to a different set of rules
// from APINotes files being applied when building the module vs when reading
// from it.
version::Version
moduleLangVersion = referenceModule->getCompatibilityVersion(),
clientLangVersion = MF->getContext().LangOpts.EffectiveLanguageVersion;
ModuleDecl *referenceModuleDecl = referenceModule->getAssociatedModule();
if (clientLangVersion != moduleLangVersion) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_swift_version,
referenceModuleDecl, moduleLangVersion,
clientLangVersion);
}
// If the error is in a resilient swiftmodule adjacent to a swiftinterface,
// deleting the module to rebuild from the swiftinterface may fix the issue.
// Limit this suggestion to distributed Swift modules to not hint at
// deleting local caches and such.
bool referenceModuleIsDistributed = referenceModuleDecl &&
referenceModuleDecl->isNonUserModule();
if (referenceModule->getResilienceStrategy() ==
ResilienceStrategy::Resilient &&
referenceModuleIsDistributed) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_stale_module,
referenceModuleDecl,
referenceModule->getModuleFilename());
}
// If the missing decl was expected to be in a clang module,
// it may be hidden by some clang defined passed via `-Xcc` affecting how
// headers are seen.
if (expectedUnderlying) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_audit_headers,
expectedModule->isNonSwiftModule(), expectedModule);
}
// If the reference goes from a distributed module to a local module,
// the compiler may have picked up an undesired module. We usually expect
// distributed modules to only reference other distributed modules.
// Local modules can reference both local modules and distributed modules.
if (referenceModuleIsDistributed) {
if (!expectedModule->isNonUserModule()) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_layering_expected_local,
referenceModuleDecl, expectedModule);
} else if (foundModule && !foundModule->isNonUserModule()) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_layering_found_local,
referenceModuleDecl, foundModule);
}
}
// If a type moved between MyModule and MyModule_Private, it can be caused
// by the use of `-Xcc -D` to change the API of the modules, leading to
// decls moving between both modules.
if (errorKind == Kind::DeclMoved ||
errorKind == Kind::DeclKindChanged) {
StringRef foundModuleName = foundModule->getName().str();
StringRef expectedModuleName = expectedModule->getName().str();
if (foundModuleName != expectedModuleName &&
(foundModuleName.starts_with(expectedModuleName) ||
expectedModuleName.starts_with(foundModuleName)) &&
(expectedUnderlying ||
expectedModule->findUnderlyingClangModule())) {
ctx.Diags.diagnose(loc,
diag::modularization_issue_related_modules,
declIsType, name);
}
}
ctx.Diags.flushConsumers();
}
void TypeError::diagnose(const ModuleFile *MF) const {
MF->getContext().Diags.diagnose(MF->getSourceLoc(),
diag::modularization_issue_side_effect_type_error,
name);
}
void ExtensionError::diagnose(const ModuleFile *MF) const {
MF->getContext().Diags.diagnose(MF->getSourceLoc(),
diag::modularization_issue_side_effect_extension_error);
}
llvm::Error
ModuleFile::diagnoseModularizationError(llvm::Error error,
DiagnosticBehavior limit) const {
auto handleModularizationError =
[&](const ModularizationError &modularError) -> llvm::Error {
modularError.diagnose(this, limit);
return llvm::Error::success();
};
llvm::Error outError = llvm::handleErrors(std::move(error),
handleModularizationError,
[&](TypeError &typeError) -> llvm::Error {
if (typeError.diagnoseUnderlyingReason(handleModularizationError)) {
typeError.diagnose(this);
return llvm::Error::success();
}
return llvm::make_error<TypeError>(std::move(typeError));
},
[&](ExtensionError &extError) -> llvm::Error {
if (extError.diagnoseUnderlyingReason(handleModularizationError)) {
extError.diagnose(this);
return llvm::Error::success();
}
return llvm::make_error<ExtensionError>(std::move(extError));
});
return outError;
}
llvm::Error ModuleFile::diagnoseFatal(llvm::Error error) const {
auto &ctx = getContext();
if (FileContext) {
if (ctx.LangOpts.EnableDeserializationRecovery) {
error = diagnoseModularizationError(std::move(error));
// If no error is left, it was reported as a diagnostic. There's no
// need to crash.
if (!error)
return llvm::Error::success();
}
// General deserialization failure message.
ctx.Diags.diagnose(getSourceLoc(), diag::serialization_fatal, Core->Name);
}
// Unless in the debugger, crash. ModuleFileSharedCore::fatal() calls abort().
// This allows aggregation of crash logs for compiler development, but in a
// long-running process like LLDB this is undesirable. Only abort() if not in
// the debugger.
if (!ctx.LangOpts.DebuggerSupport)
Core->fatal(std::move(error));
// Otherwise, augment the error with contextual information at this point
// of failure and pass it back to be reported later.
std::string msg;
{
llvm::raw_string_ostream os(msg);
Core->outputDiagnosticInfo(os);
os << '\n';
llvm::sys::PrintStackTrace(os, 128);
}
msg += ": " + toString(std::move(error));
return llvm::make_error<FatalDeserializationError>(msg);
}
void ModuleFile::outputDiagnosticInfo(llvm::raw_ostream &os) const {
Core->outputDiagnosticInfo(os);
}
static std::optional<swift::AccessorKind> getActualAccessorKind(uint8_t raw) {
switch (serialization::AccessorKind(raw)) {
#define ACCESSOR(ID) \
case serialization::AccessorKind::ID: return swift::AccessorKind::ID;
#include "swift/AST/AccessorKinds.def"
}
return std::nullopt;
}
/// Translate from the serialization DefaultArgumentKind enumerators, which are
/// guaranteed to be stable, to the AST ones.
static std::optional<swift::DefaultArgumentKind>
getActualDefaultArgKind(uint8_t raw) {
switch (static_cast<serialization::DefaultArgumentKind>(raw)) {
#define CASE(X) \
case serialization::DefaultArgumentKind::X: \
return swift::DefaultArgumentKind::X;
CASE(None)
CASE(Normal)
CASE(Inherited)
CASE(Column)
CASE(FileID)
CASE(FileIDSpelledAsFile)
CASE(FilePath)
CASE(FilePathSpelledAsFile)
CASE(Line)
CASE(Function)
CASE(DSOHandle)
CASE(NilLiteral)
CASE(EmptyArray)
CASE(EmptyDictionary)
CASE(StoredProperty)
CASE(ExpressionMacro)
#undef CASE
}
return std::nullopt;
}
static std::optional<swift::ActorIsolation::Kind>
getActualActorIsolationKind(uint8_t raw) {
switch (static_cast<serialization::ActorIsolation>(raw)) {
#define CASE(X) \
case serialization::ActorIsolation::X: \
return swift::ActorIsolation::Kind::X;
CASE(Unspecified)
CASE(ActorInstance)
CASE(Nonisolated)
CASE(NonisolatedUnsafe)
CASE(GlobalActor)
CASE(Erased)
#undef CASE
case serialization::ActorIsolation::GlobalActorUnsafe:
return swift::ActorIsolation::GlobalActor;
}
return std::nullopt;
}
static std::optional<StableSerializationPath::ExternalPath::ComponentKind>
getActualClangDeclPathComponentKind(uint64_t raw) {
switch (static_cast<serialization::ClangDeclPathComponentKind>(raw)) {
#define CASE(ID) \
case serialization::ClangDeclPathComponentKind::ID: \
return StableSerializationPath::ExternalPath::ID;
CASE(Record)
CASE(Enum)
CASE(Namespace)
CASE(Typedef)
CASE(TypedefAnonDecl)
CASE(ObjCInterface)
CASE(ObjCProtocol)
#undef CASE
}
return std::nullopt;
}
ParameterList *ModuleFile::readParameterList() {
using namespace decls_block;
SmallVector<uint64_t, 8> scratch;
llvm::BitstreamEntry entry =
fatalIfUnexpected(DeclTypeCursor.advance(AF_DontPopBlockAtEnd));
unsigned recordID =
fatalIfUnexpected(DeclTypeCursor.readRecord(entry.ID, scratch));
if (recordID != PARAMETERLIST)
fatal(llvm::make_error<InvalidRecordKindError>(recordID));
ArrayRef<uint64_t> rawMemberIDs;
decls_block::ParameterListLayout::readRecord(scratch, rawMemberIDs);
SmallVector<ParamDecl *, 8> params;
for (DeclID paramID : rawMemberIDs)
params.push_back(cast<ParamDecl>(getDecl(paramID)));
return ParameterList::create(getContext(), params);
}
static std::optional<swift::VarDecl::Introducer>
getActualVarDeclIntroducer(serialization::VarDeclIntroducer raw) {
switch (raw) {
#define CASE(ID) \
case serialization::VarDeclIntroducer::ID: \
return swift::VarDecl::Introducer::ID;
CASE(Let)
CASE(Var)
CASE(InOut)
CASE(Borrowing)
}
#undef CASE
return std::nullopt;
}
Expected<Pattern *> ModuleFile::readPattern(DeclContext *owningDC) {
// Currently, the only case in which this function can fail (return an error)
// is when reading a pattern for a single variable declaration.
using namespace decls_block;
auto readPatternUnchecked = [this](DeclContext *owningDC) -> Pattern * {
Expected<Pattern *> deserialized = readPattern(owningDC);
if (!deserialized) {
fatal(deserialized.takeError());
}
assert(deserialized.get());
return deserialized.get();
};
SmallVector<uint64_t, 8> scratch;
BCOffsetRAII restoreOffset(DeclTypeCursor);
llvm::BitstreamEntry next =
fatalIfUnexpected(DeclTypeCursor.advance(AF_DontPopBlockAtEnd));
if (next.Kind != llvm::BitstreamEntry::Record)
return diagnoseFatal();
/// Local function to record the type of this pattern.
auto recordPatternType = [&](Pattern *pattern, Type type) {
if (type->hasTypeParameter())
pattern->setDelayedInterfaceType(type, owningDC);
else
pattern->setType(type);
};
unsigned kind =
fatalIfUnexpected(DeclTypeCursor.readRecord(next.ID, scratch));
switch (kind) {
case decls_block::PAREN_PATTERN: {
Pattern *subPattern = readPatternUnchecked(owningDC);
auto result = ParenPattern::createImplicit(getContext(), subPattern);
if (Type interfaceType = subPattern->getDelayedInterfaceType())
result->setDelayedInterfaceType(ParenType::get(getContext(),
interfaceType), owningDC);
else
result->setType(ParenType::get(getContext(), subPattern->getType()));
restoreOffset.reset();
return result;
}
case decls_block::TUPLE_PATTERN: {
TypeID tupleTypeID;
unsigned count;
TuplePatternLayout::readRecord(scratch, tupleTypeID, count);
SmallVector<TuplePatternElt, 8> elements;
for ( ; count > 0; --count) {
scratch.clear();
next = fatalIfUnexpected(DeclTypeCursor.advance());
assert(next.Kind == llvm::BitstreamEntry::Record);
kind = fatalIfUnexpected(DeclTypeCursor.readRecord(next.ID, scratch));
if (kind != decls_block::TUPLE_PATTERN_ELT)
fatal(llvm::make_error<InvalidRecordKindError>(kind));
// FIXME: Add something for this record or remove it.
IdentifierID labelID;
TuplePatternEltLayout::readRecord(scratch, labelID);
Identifier label = getIdentifier(labelID);
Pattern *subPattern = readPatternUnchecked(owningDC);
elements.push_back(TuplePatternElt(label, SourceLoc(), subPattern));
}
auto result = TuplePattern::createImplicit(getContext(), elements);
recordPatternType(result, getType(tupleTypeID));
restoreOffset.reset();
return result;
}
case decls_block::NAMED_PATTERN: {
DeclID varID;
TypeID typeID;
NamedPatternLayout::readRecord(scratch, varID, typeID);
auto deserialized = getDeclChecked(varID);
if (!deserialized) {
// Pass through the error. It's too bad that it affects the whole pattern,
// but that's what we get.
return deserialized.takeError();
}
auto var = cast<VarDecl>(deserialized.get());
auto result = NamedPattern::createImplicit(getContext(), var);
auto typeOrErr = getTypeChecked(typeID);
if (!typeOrErr)
return typeOrErr.takeError();
recordPatternType(result, typeOrErr.get());
restoreOffset.reset();
return result;
}
case decls_block::ANY_PATTERN: {
TypeID typeID;
bool isAsyncLet;
AnyPatternLayout::readRecord(scratch, typeID, isAsyncLet);
auto result = AnyPattern::createImplicit(getContext());
if (isAsyncLet) {
result->setIsAsyncLet();
}
recordPatternType(result, getType(typeID));
restoreOffset.reset();
return result;
}
case decls_block::TYPED_PATTERN: {
TypeID typeID;
TypedPatternLayout::readRecord(scratch, typeID);
Expected<Pattern *> subPattern = readPattern(owningDC);
if (!subPattern) {
// Pass through any errors.
return subPattern;
}
auto type = getType(typeID);
auto result = TypedPattern::createImplicit(getContext(),
subPattern.get(), type);
recordPatternType(result, type);
restoreOffset.reset();
return result;
}
case decls_block::VAR_PATTERN: {
unsigned rawIntroducer;
BindingPatternLayout::readRecord(scratch, rawIntroducer);
Pattern *subPattern = readPatternUnchecked(owningDC);
auto introducer = getActualVarDeclIntroducer(
(serialization::VarDeclIntroducer) rawIntroducer);
if (!introducer)
return diagnoseFatal();
auto result = BindingPattern::createImplicit(
getContext(), *introducer, subPattern);
if (Type interfaceType = subPattern->getDelayedInterfaceType())
result->setDelayedInterfaceType(interfaceType, owningDC);
else
result->setType(subPattern->getType());
restoreOffset.reset();
return result;
}
default:
return llvm::make_error<InvalidRecordKindError>(kind);
}
}
SILLayout *ModuleFile::readSILLayout(llvm::BitstreamCursor &Cursor) {
using namespace decls_block;
SmallVector<uint64_t, 16> scratch;
llvm::BitstreamEntry next =
fatalIfUnexpected(Cursor.advance(AF_DontPopBlockAtEnd));
assert(next.Kind == llvm::BitstreamEntry::Record);
unsigned kind = fatalIfUnexpected(Cursor.readRecord(next.ID, scratch));
switch (kind) {
case decls_block::SIL_LAYOUT: {
GenericSignatureID rawGenericSig;
bool capturesGenerics;
unsigned numFields;
ArrayRef<uint64_t> types;
decls_block::SILLayoutLayout::readRecord(scratch, rawGenericSig,
capturesGenerics,
numFields, types);
SmallVector<SILField, 4> fields;
for (auto fieldInfo : types.slice(0, numFields)) {
bool isMutable = fieldInfo & 0x80000000U;
auto typeId = fieldInfo & 0x7FFFFFFFU;
fields.push_back(
SILField(getType(typeId)->getCanonicalType(),
isMutable));
}
CanGenericSignature canSig;
if (auto sig = getGenericSignature(rawGenericSig))
canSig = sig.getCanonicalSignature();
return SILLayout::get(getContext(), canSig, fields, capturesGenerics);
}
default:
fatal(llvm::make_error<InvalidRecordKindError>(kind));
}
}
namespace swift {
class ProtocolConformanceDeserializer {
ModuleFile &MF;
ASTContext &ctx;
using TypeID = serialization::TypeID;
using ProtocolConformanceID = serialization::ProtocolConformanceID;
public:
ProtocolConformanceDeserializer(ModuleFile &mf)
: MF(mf), ctx(mf.getContext()) {}
Expected<ProtocolConformance *>
read(ModuleFile::Serialized<ProtocolConformance *> &entry);
Expected<ProtocolConformance *>
readSelfProtocolConformance(ArrayRef<uint64_t> data);
Expected<ProtocolConformance *>
readSpecializedProtocolConformance(ArrayRef<uint64_t> data);
Expected<ProtocolConformance *>
readInheritedProtocolConformance(ArrayRef<uint64_t> data);
Expected<ProtocolConformance *>
readBuiltinProtocolConformance(ArrayRef<uint64_t> data);
Expected<ProtocolConformance *>
readNormalProtocolConformance(ArrayRef<uint64_t> data,
ModuleFile::Serialized<ProtocolConformance *> &entry);
Expected<ProtocolConformance *>
readNormalProtocolConformanceXRef(ArrayRef<uint64_t> data);
Expected<PackConformance *>
read(ModuleFile::Serialized<PackConformance *> &entry);
};
} // end namespace swift
Expected<ProtocolConformance*>
ProtocolConformanceDeserializer::read(
ModuleFile::Serialized<ProtocolConformance *> &conformanceEntry) {
SmallVector<uint64_t, 16> scratch;
if (auto s = ctx.Stats)
++s->getFrontendCounters().NumConformancesDeserialized;
llvm::BitstreamEntry entry =
MF.fatalIfUnexpected(MF.DeclTypeCursor.advance());
if (entry.Kind != llvm::BitstreamEntry::Record) {
// We don't know how to serialize types represented by sub-blocks.
return MF.diagnoseFatal();
}
StringRef blobData;
unsigned kind = MF.fatalIfUnexpected(
MF.DeclTypeCursor.readRecord(entry.ID, scratch, &blobData));
assert(blobData.empty());
switch (kind) {
case decls_block::SELF_PROTOCOL_CONFORMANCE:
return readSelfProtocolConformance(scratch);
case decls_block::SPECIALIZED_PROTOCOL_CONFORMANCE:
return readSpecializedProtocolConformance(scratch);
case decls_block::INHERITED_PROTOCOL_CONFORMANCE:
return readInheritedProtocolConformance(scratch);
case decls_block::BUILTIN_PROTOCOL_CONFORMANCE:
return readBuiltinProtocolConformance(scratch);
case decls_block::NORMAL_PROTOCOL_CONFORMANCE:
return readNormalProtocolConformance(scratch, conformanceEntry);
case decls_block::PROTOCOL_CONFORMANCE_XREF:
return readNormalProtocolConformanceXRef(scratch);
// Not a protocol conformance.
default:
return MF.diagnoseFatal(llvm::make_error<InvalidRecordKindError>(kind));
}
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readSelfProtocolConformance(
ArrayRef<uint64_t> scratch) {
using namespace decls_block;
DeclID protoID;
SelfProtocolConformanceLayout::readRecord(scratch, protoID);
auto decl = MF.getDeclChecked(protoID);
if (!decl)
return decl.takeError();
auto proto = cast<ProtocolDecl>(decl.get());
auto conformance = ctx.getSelfConformance(proto);
return conformance;
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readSpecializedProtocolConformance(
ArrayRef<uint64_t> scratch) {
using namespace decls_block;
ProtocolConformanceID conformanceID;
TypeID conformingTypeID;
SubstitutionMapID substitutionMapID;
SpecializedProtocolConformanceLayout::readRecord(scratch,
conformanceID,
conformingTypeID,
substitutionMapID);
Type conformingType = MF.getType(conformingTypeID);
PrettyStackTraceType trace(MF.getAssociatedModule()->getASTContext(),
"reading specialized conformance for",
conformingType);
auto subMapOrError = MF.getSubstitutionMapChecked(substitutionMapID);
if (!subMapOrError)
return subMapOrError.takeError();
auto subMap = subMapOrError.get();
auto genericConformance = MF.getConformance(conformanceID);
PrettyStackTraceDecl traceTo("... to", genericConformance.getRequirement());
++NumNormalProtocolConformancesLoaded;
auto *rootConformance = cast<NormalProtocolConformance>(
genericConformance.getConcrete());
auto conformance =
ctx.getSpecializedConformance(conformingType, rootConformance, subMap);
return conformance;
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readInheritedProtocolConformance(
ArrayRef<uint64_t> scratch) {
using namespace decls_block;
ProtocolConformanceID conformanceID;
TypeID conformingTypeID;
InheritedProtocolConformanceLayout::readRecord(scratch, conformanceID,
conformingTypeID);
auto conformingTypeOrError =
MF.getTypeChecked(conformingTypeID);
if (!conformingTypeOrError)
return conformingTypeOrError.takeError();
Type conformingType = conformingTypeOrError.get();
PrettyStackTraceType trace(ctx, "reading inherited conformance for",
conformingType);
ProtocolConformanceRef inheritedConformance =
MF.getConformance(conformanceID);
PrettyStackTraceDecl traceTo("... to",
inheritedConformance.getRequirement());
assert(inheritedConformance.isConcrete() &&
"Abstract inherited conformance?");
auto conformance =
ctx.getInheritedConformance(conformingType,
inheritedConformance.getConcrete());
return conformance;
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readBuiltinProtocolConformance(
ArrayRef<uint64_t> scratch) {
using namespace decls_block;
TypeID conformingTypeID;
DeclID protoID;
unsigned builtinConformanceKind;
BuiltinProtocolConformanceLayout::readRecord(scratch, conformingTypeID,
protoID, builtinConformanceKind);
auto conformingType = MF.getTypeChecked(conformingTypeID);
if (!conformingType)
return conformingType.takeError();
auto decl = MF.getDeclChecked(protoID);
if (!decl)
return decl.takeError();
auto proto = cast<ProtocolDecl>(decl.get());
auto conformance = ctx.getBuiltinConformance(
conformingType.get(), proto,
static_cast<BuiltinConformanceKind>(builtinConformanceKind));
return conformance;
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readNormalProtocolConformanceXRef(
ArrayRef<uint64_t> scratch) {
using namespace decls_block;
DeclID protoID;
DeclID nominalID;
ModuleID moduleID;
ProtocolConformanceXrefLayout::readRecord(scratch, protoID, nominalID,
moduleID);
auto maybeNominal = MF.getDeclChecked(nominalID);
if (!maybeNominal)
return maybeNominal.takeError();
auto nominal = cast<NominalTypeDecl>(maybeNominal.get());
PrettyStackTraceDecl trace("cross-referencing conformance for", nominal);
auto proto = cast<ProtocolDecl>(MF.getDecl(protoID));
PrettyStackTraceDecl traceTo("... to", proto);
auto module = MF.getModule(moduleID);
// FIXME: If the module hasn't been loaded, we probably don't want to fall
// back to the current module like this.
if (!module)
module = MF.getAssociatedModule();
SmallVector<ProtocolConformance *, 2> conformances;
nominal->lookupConformance(proto, conformances);
PrettyStackTraceModuleFile traceMsg(
"If you're seeing a crash here, check that your SDK and dependencies "
"are at least as new as the versions used to build", MF);
// This would normally be an assertion but it's more useful to print the
// PrettyStackTrace here even in no-asserts builds.
if (conformances.empty())
abort();
return conformances.front();
}
Expected<ProtocolConformance *>
ProtocolConformanceDeserializer::readNormalProtocolConformance(
ArrayRef<uint64_t> scratch,
ModuleFile::Serialized<ProtocolConformance *> &conformanceEntry) {
using namespace decls_block;
DeclID protoID;
DeclContextID contextID;
unsigned valueCount, typeCount, conformanceCount, isUnchecked,
isPreconcurrency;
ArrayRef<uint64_t> rawIDs;
NormalProtocolConformanceLayout::readRecord(scratch, protoID,
contextID, typeCount,
valueCount, conformanceCount,
isUnchecked,
isPreconcurrency,
rawIDs);
auto doOrError = MF.getDeclContextChecked(contextID);
if (!doOrError)
return doOrError.takeError();
DeclContext *dc = doOrError.get();
assert(!isa<ClangModuleUnit>(dc->getModuleScopeContext())
&& "should not have serialized a conformance from a clang module");
Type conformingType = dc->getSelfInterfaceType();
PrettyStackTraceType trace(ctx, "reading conformance for", conformingType);
auto protoOrError = MF.getDeclChecked(protoID);
if (!protoOrError)
return protoOrError.takeError();
auto proto = cast<ProtocolDecl>(protoOrError.get());
PrettyStackTraceDecl traceTo("... to", proto);
auto conformance = ctx.getNormalConformance(