-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDeserializeSIL.cpp
4677 lines (4267 loc) · 185 KB
/
DeserializeSIL.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
//===--- DeserializeSIL.cpp - Read SIL ------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "deserialize"
#include "DeserializeSIL.h"
#include "BCReadingExtras.h"
#include "DeserializationErrors.h"
#include "ModuleFile.h"
#include "SILFormat.h"
#include "SILSerializationFunctionBuilder.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILMoveOnlyDeinit.h"
#include "swift/SIL/SILProperty.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/OwnershipUtils.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/DJB.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/OnDiskHashTable.h"
#include <type_traits>
using namespace swift;
using namespace swift::serialization;
using namespace swift::serialization::sil_block;
using namespace llvm::support;
const char SILEntityError::ID = '\0';
void SILEntityError::anchor() {}
const char SILFunctionTypeMismatch::ID = '\0';
void SILFunctionTypeMismatch::anchor() {}
STATISTIC(NumDeserializedFunc, "Number of deserialized SIL functions");
static std::optional<StringLiteralInst::Encoding>
fromStableStringEncoding(unsigned value) {
switch (value) {
case SIL_BYTES: return StringLiteralInst::Encoding::Bytes;
case SIL_UTF8: return StringLiteralInst::Encoding::UTF8;
case SIL_OBJC_SELECTOR: return StringLiteralInst::Encoding::ObjCSelector;
case SIL_UTF8_OSLOG: return StringLiteralInst::Encoding::UTF8_OSLOG;
default:
return std::nullopt;
}
}
static std::optional<SILLinkage> fromStableSILLinkage(unsigned value) {
switch (value) {
case SIL_LINKAGE_PUBLIC: return SILLinkage::Public;
case SIL_LINKAGE_PUBLIC_NON_ABI: return SILLinkage::PublicNonABI;
case SIL_LINKAGE_PACKAGE: return SILLinkage::Package;
case SIL_LINKAGE_PACKAGE_NON_ABI: return SILLinkage::PackageNonABI;
case SIL_LINKAGE_HIDDEN: return SILLinkage::Hidden;
case SIL_LINKAGE_SHARED: return SILLinkage::Shared;
case SIL_LINKAGE_PRIVATE: return SILLinkage::Private;
case SIL_LINKAGE_PUBLIC_EXTERNAL: return SILLinkage::PublicExternal;
case SIL_LINKAGE_HIDDEN_EXTERNAL: return SILLinkage::HiddenExternal;
}
llvm_unreachable("Invalid SIL linkage");
}
static std::optional<SILVTable::Entry::Kind>
fromStableVTableEntryKind(unsigned value) {
switch (value) {
case SIL_VTABLE_ENTRY_NORMAL: return SILVTable::Entry::Kind::Normal;
case SIL_VTABLE_ENTRY_INHERITED: return SILVTable::Entry::Kind::Inherited;
case SIL_VTABLE_ENTRY_OVERRIDE: return SILVTable::Entry::Kind::Override;
default:
return std::nullopt;
}
}
static std::optional<swift::DifferentiabilityKind>
fromStableDifferentiabilityKind(uint8_t diffKind) {
switch (diffKind) {
#define CASE(THE_DK) \
case (uint8_t)serialization::DifferentiabilityKind::THE_DK: \
return swift::DifferentiabilityKind::THE_DK;
CASE(NonDifferentiable)
CASE(Forward)
CASE(Reverse)
CASE(Normal)
CASE(Linear)
#undef CASE
default:
return std::nullopt;
}
}
/// Used to deserialize entries in the on-disk func hash table.
class SILDeserializer::FuncTableInfo {
ModuleFile &MF;
public:
using internal_key_type = StringRef;
using external_key_type = StringRef;
using data_type = DeclID;
using hash_value_type = uint32_t;
using offset_type = unsigned;
explicit FuncTableInfo(ModuleFile &MF) : MF(MF) {}
internal_key_type GetInternalKey(external_key_type ID) { return ID; }
external_key_type GetExternalKey(internal_key_type ID) { return ID; }
hash_value_type ComputeHash(internal_key_type key) {
return llvm::djbHash(key, SWIFTMODULE_HASH_SEED);
}
static bool EqualKey(internal_key_type lhs, internal_key_type rhs) {
return lhs == rhs;
}
static std::pair<unsigned, unsigned> ReadKeyDataLength(const uint8_t *&data) {
return { sizeof(uint32_t), sizeof(uint32_t) };
}
internal_key_type ReadKey(const uint8_t *data, unsigned length) {
assert(length == sizeof(uint32_t) && "Expect a single IdentifierID.");
IdentifierID keyID = endian::readNext<uint32_t, little, unaligned>(data);
return MF.getIdentifierText(keyID);
}
static data_type ReadData(internal_key_type key, const uint8_t *data,
unsigned length) {
assert(length == sizeof(uint32_t) && "Expect a single DeclID.");
data_type result = endian::readNext<uint32_t, little, unaligned>(data);
return result;
}
};
SILDeserializer::SILDeserializer(
ModuleFile *MF, SILModule &M,
DeserializationNotificationHandlerSet *callback)
: MF(MF), SILMod(M), Callback(callback) {
SILCursor = MF->getSILCursor();
SILIndexCursor = MF->getSILIndexCursor();
// Early return if either sil block or sil index block does not exist.
if (SILCursor.AtEndOfStream() || SILIndexCursor.AtEndOfStream())
return;
// Load any abbrev records at the start of the block.
MF->fatalIfUnexpected(SILCursor.advance());
llvm::BitstreamCursor cursor = SILIndexCursor;
// We expect SIL_FUNC_NAMES first, then SIL_VTABLE_NAMES, then
// SIL_GLOBALVAR_NAMES, then SIL_WITNESS_TABLE_NAMES, and finally
// SIL_DEFAULT_WITNESS_TABLE_NAMES. But each one can be
// omitted if no entries exist in the module file.
unsigned kind = 0;
while (kind != sil_index_block::SIL_PROPERTY_OFFSETS) {
llvm::BitstreamEntry next = MF->fatalIfUnexpected(cursor.advance());
if (next.Kind == llvm::BitstreamEntry::EndBlock)
return;
SmallVector<uint64_t, 4> scratch;
StringRef blobData;
unsigned prevKind = kind;
kind =
MF->fatalIfUnexpected(cursor.readRecord(next.ID, scratch, &blobData));
assert((next.Kind == llvm::BitstreamEntry::Record && kind > prevKind &&
(kind == sil_index_block::SIL_FUNC_NAMES ||
kind == sil_index_block::SIL_VTABLE_NAMES ||
kind == sil_index_block::SIL_MOVEONLYDEINIT_NAMES ||
kind == sil_index_block::SIL_GLOBALVAR_NAMES ||
kind == sil_index_block::SIL_WITNESS_TABLE_NAMES ||
kind == sil_index_block::SIL_DEFAULT_WITNESS_TABLE_NAMES ||
kind == sil_index_block::SIL_PROPERTY_OFFSETS ||
kind == sil_index_block::SIL_DIFFERENTIABILITY_WITNESS_NAMES)) &&
"Expect SIL_FUNC_NAMES, SIL_VTABLE_NAMES, SIL_GLOBALVAR_NAMES, \
SIL_WITNESS_TABLE_NAMES, SIL_DEFAULT_WITNESS_TABLE_NAMES, \
SIL_PROPERTY_OFFSETS, SIL_MOVEONLYDEINIT_NAMES, or SIL_DIFFERENTIABILITY_WITNESS_NAMES.");
(void)prevKind;
if (kind == sil_index_block::SIL_FUNC_NAMES)
FuncTable = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_VTABLE_NAMES)
VTableList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_MOVEONLYDEINIT_NAMES)
MoveOnlyDeinitList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_GLOBALVAR_NAMES)
GlobalVarList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_WITNESS_TABLE_NAMES)
WitnessTableList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_DEFAULT_WITNESS_TABLE_NAMES)
DefaultWitnessTableList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_DIFFERENTIABILITY_WITNESS_NAMES)
DifferentiabilityWitnessList = readFuncTable(scratch, blobData);
else if (kind == sil_index_block::SIL_PROPERTY_OFFSETS) {
// No matching 'names' block for property descriptors needed yet.
MF->allocateBuffer(Properties, scratch);
return;
}
// Read SIL_FUNC|VTABLE|GLOBALVAR_OFFSETS record.
next = MF->fatalIfUnexpected(cursor.advance());
scratch.clear();
unsigned offKind =
MF->fatalIfUnexpected(cursor.readRecord(next.ID, scratch, &blobData));
(void)offKind;
if (kind == sil_index_block::SIL_FUNC_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_FUNC_OFFSETS) &&
"Expect a SIL_FUNC_OFFSETS record.");
MF->allocateBuffer(Funcs, scratch);
} else if (kind == sil_index_block::SIL_VTABLE_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_VTABLE_OFFSETS) &&
"Expect a SIL_VTABLE_OFFSETS record.");
MF->allocateBuffer(VTables, scratch);
} else if (kind == sil_index_block::SIL_MOVEONLYDEINIT_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_MOVEONLYDEINIT_OFFSETS) &&
"Expect a SIL_MOVEONLYDEINIT_OFFSETS record.");
MF->allocateBuffer(MoveOnlyDeinits, scratch);
} else if (kind == sil_index_block::SIL_GLOBALVAR_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_GLOBALVAR_OFFSETS) &&
"Expect a SIL_GLOBALVAR_OFFSETS record.");
MF->allocateBuffer(GlobalVars, scratch);
} else if (kind == sil_index_block::SIL_WITNESS_TABLE_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_WITNESS_TABLE_OFFSETS) &&
"Expect a SIL_WITNESS_TABLE_OFFSETS record.");
MF->allocateBuffer(WitnessTables, scratch);
} else if (kind == sil_index_block::SIL_DEFAULT_WITNESS_TABLE_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind == sil_index_block::SIL_DEFAULT_WITNESS_TABLE_OFFSETS) &&
"Expect a SIL_DEFAULT_WITNESS_TABLE_OFFSETS record.");
MF->allocateBuffer(DefaultWitnessTables, scratch);
} else if (kind == sil_index_block::SIL_DIFFERENTIABILITY_WITNESS_NAMES) {
assert((next.Kind == llvm::BitstreamEntry::Record &&
offKind ==
sil_index_block::SIL_DIFFERENTIABILITY_WITNESS_OFFSETS) &&
"Expect a SIL_DIFFERENTIABILITY_WITNESS_OFFSETS record.");
MF->allocateBuffer(DifferentiabilityWitnesses, scratch);
}
}
}
std::unique_ptr<SILDeserializer::SerializedFuncTable>
SILDeserializer::readFuncTable(ArrayRef<uint64_t> fields, StringRef blobData) {
uint32_t tableOffset;
sil_index_block::ListLayout::readRecord(fields, tableOffset);
auto base = reinterpret_cast<const uint8_t *>(blobData.data());
using OwnedTable = std::unique_ptr<SerializedFuncTable>;
return OwnedTable(SerializedFuncTable::Create(base + tableOffset,
base + sizeof(uint32_t), base,
FuncTableInfo(*MF)));
}
/// A high-level overview of how forward references work in serializer and
/// deserializer:
/// In the serializer, we pre-assign a value ID in order, to each basic block
/// argument and each SILInstruction that has a value.
/// In the deserializer, we create a PlaceholderValue for a forward-referenced
/// value (a value that is used but not yet defined). LocalValues are updated in
/// setLocalValue where the ID passed in assumes the same ordering as in
/// serializer: in-order for each basic block argument and each SILInstruction
/// that has a value.
/// When a forward-referenced value is defined, it replaces the PlaceholderValue
/// in LocalValues.
void SILDeserializer::setLocalValue(ValueBase *Value, ValueID Id) {
ValueBase *&Entry = LocalValues[Id];
if (auto *placeholder = dyn_cast_or_null<PlaceholderValue>(Entry)) {
placeholder->replaceAllUsesWith(Value);
::delete placeholder;
} else {
assert(!Entry && "We should not redefine the same value.");
}
// Store it in our map.
Entry = Value;
}
SILValue SILDeserializer::getLocalValue(SILFunction *inContext, ValueID Id,
SILType Type) {
// The first two IDs are special undefined values.
if (Id == 0) {
assert(inContext &&
"Should never have a SILUndef in a global variable initializer?!");
return SILUndef::get(*inContext, Type);
}
assert(Id != 1 && "This used to be for SILUndef with OwnershipKind::Owned... "
"but we don't support that anymore. Make sure no one "
"changes that without updating this code if needed");
// Check to see if this is already defined.
ValueBase *&Entry = LocalValues[Id];
if (!Entry) {
// Otherwise, this is a forward reference. Create a dummy node to represent
// it until we see a real definition.
Entry = ::new PlaceholderValue(inContext, Type);
}
// If this value was already defined, check it to make sure types match.
assert(Entry->getType() == Type && "Value Type mismatch?");
return Entry;
}
/// Return the SILBasicBlock of a given ID.
SILBasicBlock *SILDeserializer::getBBForDefinition(SILFunction *Fn,
SILBasicBlock *Prev,
unsigned ID) {
SILBasicBlock *&BB = BlocksByID[ID];
// If the block has never been named yet, just create it.
if (BB == nullptr) {
if (Prev) {
BB = Fn->createBasicBlockAfter(Prev);
} else {
BB = Fn->createBasicBlock();
}
return BB;
}
// If it already exists, it was either a forward reference or a redefinition.
// The latter should never happen.
bool wasForwardReferenced = UndefinedBlocks.erase(BB);
assert(wasForwardReferenced);
(void)wasForwardReferenced;
if (Prev)
Fn->moveBlockAfter(BB, Prev);
return BB;
}
/// Return the SILBasicBlock of a given ID.
SILBasicBlock *SILDeserializer::getBBForReference(SILFunction *Fn,
unsigned ID) {
SILBasicBlock *&BB = BlocksByID[ID];
if (BB != nullptr)
return BB;
// Otherwise, create it and remember that this is a forward reference
BB = Fn->createBasicBlock();
UndefinedBlocks[BB] = ID;
return BB;
}
/// Helper function to convert from Type to SILType.
SILType SILDeserializer::getSILType(Type Ty, SILValueCategory Category,
SILFunction *inContext) {
auto TyLoc = TypeLoc::withoutLoc(Ty);
if (!inContext) {
return SILType::getPrimitiveType(TyLoc.getType()->getCanonicalType(),
Category);
}
return inContext->getLoweredType(TyLoc.getType()->getCanonicalType())
.getCategoryType(Category);
}
/// Helper function to find a SILDifferentiabilityWitness, given its mangled
/// key.
SILDifferentiabilityWitness *
SILDeserializer::getSILDifferentiabilityWitnessForReference(
StringRef mangledKey) {
// Check to see if we have a witness under this key already.
auto *witness = SILMod.lookUpDifferentiabilityWitness(mangledKey);
if (witness)
return witness;
// Otherwise, look for a witness under this key in the module.
if (!DifferentiabilityWitnessList)
return nullptr;
auto iter = DifferentiabilityWitnessList->find(mangledKey);
if (iter == DifferentiabilityWitnessList->end())
return nullptr;
return readDifferentiabilityWitness(*iter);
}
/// Helper function to find a SILFunction, given its name and type.
SILFunction *SILDeserializer::getFuncForReference(StringRef name,
SILType type,
TypeExpansionContext context) {
// Check to see if we have a function by this name already.
SILFunction *fn = SILMod.lookUpFunction(name);
if (!fn) {
// Otherwise, look for a function with this name in the module.
auto iter = FuncTable->find(name);
if (iter != FuncTable->end()) {
auto maybeFn = readSILFunctionChecked(*iter, nullptr, name,
/*declarationOnly*/ true);
if (maybeFn) {
fn = maybeFn.get();
} else {
// Ignore the failure; we'll synthesize a bogus function instead.
llvm::consumeError(maybeFn.takeError());
}
}
}
// At this point, if fn is set, we know that we have a good function to use.
if (fn) {
SILType fnType = fn->getLoweredTypeInContext(context);
if (fnType != type &&
// It can happen that opaque return types cause a mismatch when merging
// modules, without causing any further assertion failures.
// TODO: fix the underlying problem
fnType.hasOpaqueArchetype() == type.hasOpaqueArchetype()) {
StringRef fnName = fn->getName();
if (auto *dc = fn->getDeclContext()) {
if (auto *decl = dyn_cast_or_null<AbstractFunctionDecl>(dc->getAsDecl()))
fnName = decl->getNameStr();
}
fn->getModule().getASTContext().Diags.diagnose(
fn->getLocation().getSourceLoc(),
diag::deserialize_function_type_mismatch,
fnName, fnType.getASTType(), type.getASTType());
exit(1);
}
return fn;
}
// Otherwise, create a function declaration with the right type and a bogus
// source location. This ensures that we can at least parse the rest of the
// SIL.
SourceLoc sourceLoc;
SILSerializationFunctionBuilder builder(SILMod);
fn = builder.createDeclaration(name, type,
RegularLocation(sourceLoc));
// The function is not really de-serialized, but it's important to call
// `didDeserialize` on every new function. Otherwise some Analysis might miss
// `notifyAddedOrModifiedFunction` notifications.
if (Callback)
Callback->didDeserialize(MF->getAssociatedModule(), fn);
return fn;
}
/// Helper function to find a SILFunction, given its name and type.
SILFunction *SILDeserializer::getFuncForReference(StringRef name) {
// Check to see if we have a function by this name already.
SILFunction *fn = SILMod.lookUpFunction(name);
if (fn)
return fn;
// Otherwise, look for a function with this name in the module.
auto iter = FuncTable->find(name);
if (iter == FuncTable->end())
return nullptr;
auto maybeFn = readSILFunctionChecked(*iter, nullptr, name,
/*declarationOnly*/ true);
if (!maybeFn) {
// Ignore the failure and just pretend the function doesn't exist
llvm::consumeError(maybeFn.takeError());
return nullptr;
}
return maybeFn.get();
}
/// Helper function to find a SILGlobalVariable given its name. It first checks
/// in the module. If we cannot find it in the module, we attempt to
/// deserialize it.
SILGlobalVariable *SILDeserializer::getGlobalForReference(StringRef name) {
// Check to see if we have a global by this name already.
if (SILGlobalVariable *g = SILMod.lookUpGlobalVariable(name))
return g;
// Otherwise, look for a global with this name in the module.
return readGlobalVar(name);
}
/// Deserialize a SILFunction if it is not already deserialized. The input
/// SILFunction can either be an empty declaration or null. If it is an empty
/// declaration, we fill in the contents. If the input SILFunction is
/// null, we create a SILFunction.
SILFunction *SILDeserializer::readSILFunction(DeclID FID,
SILFunction *existingFn,
StringRef name,
bool declarationOnly,
bool errorIfEmptyBody) {
llvm::Expected<SILFunction *> deserialized =
readSILFunctionChecked(FID, existingFn, name, declarationOnly,
errorIfEmptyBody);
if (!deserialized) {
MF->fatal(deserialized.takeError());
}
return deserialized.get();
}
llvm::Expected<SILFunction *>
SILDeserializer::readSILFunctionChecked(DeclID FID, SILFunction *existingFn,
StringRef name, bool declarationOnly,
bool errorIfEmptyBody) {
// We can't deserialize function bodies after IRGen lowering passes have
// happened since other definitions in the module will no longer be in
// canonical SIL form.
switch (SILMod.getStage()) {
case SILStage::Raw:
case SILStage::Canonical:
break;
case SILStage::Lowered:
llvm_unreachable("cannot deserialize into a module that has entered "
"Lowered stage");
}
if (FID == 0)
return nullptr;
assert(FID <= Funcs.size() && "invalid SILFunction ID");
PrettyStackTraceStringAction trace("deserializing SIL function", name);
auto &cacheEntry = Funcs[FID-1];
if (cacheEntry.isFullyDeserialized() ||
(cacheEntry.isDeserialized() && declarationOnly))
return cacheEntry.get();
BCOffsetRAII restoreOffset(SILCursor);
if (llvm::Error Err = SILCursor.JumpToBit(cacheEntry.getOffset()))
return std::move(Err);
llvm::Expected<llvm::BitstreamEntry> maybeEntry =
SILCursor.advance(AF_DontPopBlockAtEnd);
if (!maybeEntry)
return maybeEntry.takeError();
llvm::BitstreamEntry entry = maybeEntry.get();
if (entry.Kind == llvm::BitstreamEntry::Error)
return MF->diagnoseFatal("Cursor advance error in readSILFunction");
SmallVector<uint64_t, 64> scratch;
StringRef blobData;
llvm::Expected<unsigned> maybeKind =
SILCursor.readRecord(entry.ID, scratch, &blobData);
if (!maybeKind)
return MF->diagnoseFatal(maybeKind.takeError());
unsigned kind = maybeKind.get();
assert(kind == SIL_FUNCTION && "expect a sil function");
(void)kind;
DeclID clangNodeOwnerID;
ModuleID parentModuleID;
TypeID funcTyID;
IdentifierID replacedFunctionID;
IdentifierID usedAdHocWitnessFunctionID;
GenericSignatureID genericSigID;
unsigned rawLinkage, isTransparent, isSerialized, isThunk,
isWithoutActuallyEscapingThunk, specialPurpose, inlineStrategy,
optimizationMode, perfConstr, subclassScope, hasCReferences, effect,
numAttrs, hasQualifiedOwnership, isWeakImported,
LIST_VER_TUPLE_PIECES(available), isDynamic, isExactSelfClass,
isDistributed, isRuntimeAccessible, forceEnableLexicalLifetimes;
ArrayRef<uint64_t> SemanticsIDs;
SILFunctionLayout::readRecord(
scratch, rawLinkage, isTransparent, isSerialized, isThunk,
isWithoutActuallyEscapingThunk, specialPurpose, inlineStrategy,
optimizationMode, perfConstr, subclassScope, hasCReferences, effect,
numAttrs, hasQualifiedOwnership, isWeakImported,
LIST_VER_TUPLE_PIECES(available), isDynamic, isExactSelfClass,
isDistributed, isRuntimeAccessible, forceEnableLexicalLifetimes, funcTyID,
replacedFunctionID, usedAdHocWitnessFunctionID, genericSigID,
clangNodeOwnerID, parentModuleID, SemanticsIDs);
if (funcTyID == 0)
return MF->diagnoseFatal("SILFunction typeID is 0");
auto astType = MF->getTypeChecked(funcTyID);
if (!astType) {
if (!existingFn || errorIfEmptyBody) {
return llvm::make_error<SILEntityError>(
name, takeErrorInfo(astType.takeError()));
}
consumeError(astType.takeError());
return existingFn;
}
auto ty = getSILType(astType.get(), SILValueCategory::Object, nullptr);
if (!ty.is<SILFunctionType>())
return MF->diagnoseFatal("not a function type for SILFunction");
SILFunction *replacedFunction = nullptr;
Identifier replacedObjectiveCFunc;
if (replacedFunctionID &&
ty.getAs<SILFunctionType>()->getExtInfo().getRepresentation() !=
SILFunctionTypeRepresentation::ObjCMethod) {
replacedFunction =
getFuncForReference(MF->getIdentifier(replacedFunctionID).str());
} else if (replacedFunctionID) {
replacedObjectiveCFunc = MF->getIdentifier(replacedFunctionID);
}
SILFunction *usedAdHocWitnessFunction = nullptr;
if (usedAdHocWitnessFunctionID) {
auto usedAdHocWitnessFunctionStr =
MF->getIdentifier(usedAdHocWitnessFunctionID).str();
usedAdHocWitnessFunction = getFuncForReference(usedAdHocWitnessFunctionStr);
}
auto linkageOpt = fromStableSILLinkage(rawLinkage);
if (!linkageOpt) {
LLVM_DEBUG(llvm::dbgs() << "invalid linkage code " << rawLinkage
<< " for SILFunction\n");
return MF->diagnoseFatal("invalid linkage code");
}
SILLinkage linkage = linkageOpt.value();
ValueDecl *clangNodeOwner = nullptr;
if (clangNodeOwnerID != 0) {
clangNodeOwner = dyn_cast_or_null<ValueDecl>(MF->getDecl(clangNodeOwnerID));
if (!clangNodeOwner)
return MF->diagnoseFatal("invalid clang node owner for SILFunction");
}
// If we weren't handed a function, check for an existing
// declaration in the output module.
if (!existingFn) existingFn = SILMod.lookUpFunction(name);
auto fn = existingFn;
// TODO: use the correct SILLocation from module.
SILLocation loc = RegularLocation::getAutoGeneratedLocation();
// If we've already serialized the module, don't mark the function
// as serialized, since we no longer need to enforce resilience
// boundaries.
if (SILMod.isSerialized())
isSerialized = IsNotSerialized;
SILSerializationFunctionBuilder builder(SILMod);
// If we have an existing function, verify that the types match up.
if (fn) {
if (fn->getLoweredType() != ty) {
auto error = llvm::make_error<SILFunctionTypeMismatch>(
name,
fn->getLoweredType().getDebugDescription(),
ty.getDebugDescription());
return MF->diagnoseFatal(std::move(error));
}
fn->setSerialized(IsSerialized_t(isSerialized));
// If the serialized function comes from the same module, we're merging
// modules, and can update the linkage directly. This is needed to
// correctly update the linkage for forward declarations to entities defined
// in another file of the same module – we want to ensure the linkage
// reflects the fact that the entity isn't really external and shouldn't be
// dropped from the resulting merged module.
if (getFile()->getParentModule() == SILMod.getSwiftModule())
fn->setLinkage(linkage);
// Don't override the transparency or linkage of a function with
// an existing declaration, except if we deserialized a
// PublicNonABI function, which has HiddenExternal when
// referenced as a declaration, and Shared when it has
// a deserialized body.
if (isAvailableExternally(fn->getLinkage())) {
switch (linkage) {
case SILLinkage::PublicNonABI:
case SILLinkage::PackageNonABI:
case SILLinkage::Shared:
fn->setLinkage(SILLinkage::Shared);
break;
case SILLinkage::Public:
case SILLinkage::Package:
case SILLinkage::Hidden:
case SILLinkage::Private:
case SILLinkage::PublicExternal:
case SILLinkage::PackageExternal:
case SILLinkage::HiddenExternal:
if (hasPublicVisibility(linkage)) {
// Cross-module-optimization can change the linkage to public. In this
// case we need to update the linkage of the function (which is
// originally just derived from the AST).
fn->setLinkage(SILLinkage::PublicExternal);
}
break;
}
}
if (fn->isDynamicallyReplaceable() != isDynamic)
return MF->diagnoseFatal("SILFunction dynamic replaceable mismatch");
} else {
// Otherwise, create a new function.
fn = builder.createDeclaration(name, ty, loc);
fn->setLinkage(linkage);
fn->setTransparent(IsTransparent_t(isTransparent == 1));
fn->setSerialized(IsSerialized_t(isSerialized));
fn->setThunk(IsThunk_t(isThunk));
fn->setWithoutActuallyEscapingThunk(bool(isWithoutActuallyEscapingThunk));
fn->setInlineStrategy(Inline_t(inlineStrategy));
fn->setSpecialPurpose(SILFunction::Purpose(specialPurpose));
fn->setEffectsKind(EffectsKind(effect));
fn->setOptimizationMode(OptimizationMode(optimizationMode));
fn->setPerfConstraints((PerformanceConstraints)perfConstr);
fn->setIsAlwaysWeakImported(isWeakImported);
fn->setClassSubclassScope(SubclassScope(subclassScope));
fn->setHasCReferences(bool(hasCReferences));
llvm::VersionTuple available;
DECODE_VER_TUPLE(available);
fn->setAvailabilityForLinkage(
available.empty()
? AvailabilityContext::alwaysAvailable()
: AvailabilityContext(VersionRange::allGTE(available)));
fn->setIsDynamic(IsDynamicallyReplaceable_t(isDynamic));
fn->setIsExactSelfClass(IsExactSelfClass_t(isExactSelfClass));
fn->setIsDistributed(IsDistributed_t(isDistributed));
fn->setIsRuntimeAccessible(IsRuntimeAccessible_t(isRuntimeAccessible));
fn->setForceEnableLexicalLifetimes(
ForceEnableLexicalLifetimes_t(forceEnableLexicalLifetimes));
if (replacedFunction)
fn->setDynamicallyReplacedFunction(replacedFunction);
if (!replacedObjectiveCFunc.empty())
fn->setObjCReplacement(replacedObjectiveCFunc);
if (usedAdHocWitnessFunction)
fn->setReferencedAdHocRequirementWitnessFunction(usedAdHocWitnessFunction);
if (clangNodeOwner)
fn->setClangNodeOwner(clangNodeOwner);
for (auto ID : SemanticsIDs) {
fn->addSemanticsAttr(MF->getIdentifierText(ID));
}
if (Callback) Callback->didDeserialize(MF->getAssociatedModule(), fn);
}
// First before we do /anything/ validate that our function is truly empty.
assert(fn->empty() && "SILFunction to be deserialized starts being empty.");
// Given that our original function was empty, just match the deserialized
// function. Ownership doesn't really have a meaning without a body.
builder.setHasOwnership(fn, hasQualifiedOwnership);
// Mark this function as deserialized. This avoids rerunning diagnostic
// passes. Certain passes in the mandatory pipeline may not work as expected
// after arbitrary optimization and lowering.
if (!MF->isSIB())
fn->setWasDeserializedCanonical();
fn->setBare(IsBare);
if (!fn->getDebugScope()) {
const SILDebugScope *DS = new (SILMod) SILDebugScope(loc, fn);
fn->setDebugScope(DS);
}
// If we don't already have a DeclContext to use to find a parent module,
// attempt to deserialize a parent module reference directly.
if (!fn->getDeclContext() && parentModuleID)
fn->setParentModule(MF->getModule(parentModuleID));
// Read and instantiate the specialize attributes.
bool shouldAddSpecAttrs = fn->getSpecializeAttrs().empty();
bool shouldAddEffectAttrs = !fn->hasArgumentEffects();
for (unsigned attrIdx = 0; attrIdx < numAttrs; ++attrIdx) {
llvm::Expected<llvm::BitstreamEntry> maybeNext =
SILCursor.advance(AF_DontPopBlockAtEnd);
if (!maybeNext)
return maybeNext.takeError();
llvm::BitstreamEntry next = maybeNext.get();
assert(next.Kind == llvm::BitstreamEntry::Record);
scratch.clear();
llvm::Expected<unsigned> maybeKind = SILCursor.readRecord(next.ID, scratch);
if (!maybeKind)
return maybeKind.takeError();
unsigned kind = maybeKind.get();
if (kind == SIL_ARG_EFFECTS_ATTR) {
IdentifierID effectID;
unsigned isDerived;
unsigned isGlobalSideEffects;
unsigned argumentIndex;
SILArgEffectsAttrLayout::readRecord(scratch, effectID, argumentIndex,
isGlobalSideEffects, isDerived);
if (shouldAddEffectAttrs) {
StringRef effectStr = MF->getIdentifierText(effectID);
std::pair<const char *, int> error;
if (isGlobalSideEffects) {
error = fn->parseGlobalEffectsFromSIL(effectStr);
} else {
error = fn->parseArgumentEffectsFromSIL(effectStr, (int)argumentIndex);
}
(void)error;
assert(!error.first && "effects deserialization error");
}
continue;
}
assert(kind == SIL_SPECIALIZE_ATTR && "Missing specialization attribute");
unsigned exported;
unsigned specializationKindVal;
GenericSignatureID specializedSigID;
IdentifierID targetFunctionID;
IdentifierID spiGroupID;
ModuleID spiModuleID;
ArrayRef<uint64_t> typeErasedParamsIDs;
unsigned LIST_VER_TUPLE_PIECES(available);
SILSpecializeAttrLayout::readRecord(
scratch, exported, specializationKindVal, specializedSigID,
targetFunctionID, spiGroupID, spiModuleID,
LIST_VER_TUPLE_PIECES(available), typeErasedParamsIDs);
SILFunction *target = nullptr;
if (targetFunctionID) {
target = getFuncForReference(MF->getIdentifier(targetFunctionID).str());
}
Identifier spiGroup;
const ModuleDecl *spiModule = nullptr;
if (spiGroupID) {
spiGroup = MF->getIdentifier(spiGroupID);
spiModule = MF->getModule(spiModuleID);
}
SILSpecializeAttr::SpecializationKind specializationKind =
specializationKindVal ? SILSpecializeAttr::SpecializationKind::Partial
: SILSpecializeAttr::SpecializationKind::Full;
llvm::VersionTuple available;
DECODE_VER_TUPLE(available);
auto availability = available.empty()
? AvailabilityContext::alwaysAvailable()
: AvailabilityContext(VersionRange::allGTE(available));
llvm::SmallVector<Type, 4> typeErasedParams;
for (auto id : typeErasedParamsIDs) {
typeErasedParams.push_back(MF->getType(id));
}
auto specializedSig = MF->getGenericSignature(specializedSigID);
// Only add the specialize attributes once.
if (shouldAddSpecAttrs) {
// Read the substitution list and construct a SILSpecializeAttr.
fn->addSpecializeAttr(SILSpecializeAttr::create(
SILMod, specializedSig, typeErasedParams,
exported != 0, specializationKind, target,
spiGroup, spiModule, availability));
}
}
GenericEnvironment *genericEnv = nullptr;
if (!declarationOnly)
genericEnv = MF->getGenericSignature(genericSigID).getGenericEnvironment();
// If the next entry is the end of the block, then this function has
// no contents.
maybeEntry = SILCursor.advance(AF_DontPopBlockAtEnd);
if (!maybeEntry)
return maybeEntry.takeError();
entry = maybeEntry.get();
bool isEmptyFunction = (entry.Kind == llvm::BitstreamEntry::EndBlock);
assert((!isEmptyFunction || !genericEnv) &&
"generic environment without body?!");
// Remember this in our cache in case it's a recursive function.
// Increase the reference count to keep it alive.
bool isFullyDeserialized = (isEmptyFunction || !declarationOnly);
if (cacheEntry.isDeserialized()) {
assert(fn == cacheEntry.get() && "changing SIL function during deserialization!");
} else {
fn->incrementRefCount();
}
cacheEntry.set(fn, isFullyDeserialized);
// Stop here if we have nothing else to do.
if (isEmptyFunction || declarationOnly) {
return fn;
}
++NumDeserializedFunc;
assert(!(fn->getGenericEnvironment() && !fn->empty())
&& "function already has context generic params?!");
if (genericEnv)
fn->setGenericEnvironment(genericEnv);
scratch.clear();
maybeKind = SILCursor.readRecord(entry.ID, scratch);
if (!maybeKind)
return maybeKind.takeError();
kind = maybeKind.get();
SILBasicBlock *CurrentBB = nullptr;
// Clear up at the beginning of each SILFunction.
BasicBlockID = 0;
BlocksByID.clear();
UndefinedBlocks.clear();
// The first two IDs are reserved for SILUndef.
LastValueID = 1;
LocalValues.clear();
SILBuilder Builder(*fn);
// Another SIL_FUNCTION record means the end of this SILFunction.
// SIL_VTABLE or SIL_GLOBALVAR or SIL_WITNESS_TABLE record also means the end
// of this SILFunction.
while (kind != SIL_FUNCTION && kind != SIL_VTABLE && kind != SIL_GLOBALVAR &&
kind != SIL_MOVEONLY_DEINIT && kind != SIL_WITNESS_TABLE &&
kind != SIL_DIFFERENTIABILITY_WITNESS) {
if (kind == SIL_BASIC_BLOCK)
// Handle a SILBasicBlock record.
CurrentBB = readSILBasicBlock(fn, CurrentBB, scratch);
else {
// If CurrentBB is empty, just return fn. The code in readSILInstruction
// assumes that such a situation means that fn is a declaration. Thus it
// is using return false to mean two different things, error a failure
// occurred and this is a declaration. Work around that for now.
if (!CurrentBB)
return fn;
Builder.setInsertionPoint(CurrentBB);
// Handle a SILInstruction record.
if (readSILInstruction(fn, Builder, kind, scratch))
return MF->diagnoseFatal("readSILInstruction returns error");
}
// Fetch the next record.
scratch.clear();
llvm::Expected<llvm::BitstreamEntry> maybeEntry =
SILCursor.advance(AF_DontPopBlockAtEnd);
if (!maybeEntry)
return maybeEntry.takeError();
llvm::BitstreamEntry entry = maybeEntry.get();
// EndBlock means the end of this SILFunction.
if (entry.Kind == llvm::BitstreamEntry::EndBlock)
break;
maybeKind = SILCursor.readRecord(entry.ID, scratch);
if (!maybeKind)
return maybeKind.takeError();
kind = maybeKind.get();
}
// If fn is empty, we failed to deserialize its body. Return nullptr to signal
// error.
if (fn->empty() && errorIfEmptyBody)
return nullptr;
// Check that there are no unresolved forward definitions of local
// archetypes.
if (SILMod.hasUnresolvedLocalArchetypeDefinitions())
llvm_unreachable(
"All forward definitions of local archetypes should be resolved");
if (Callback)
Callback->didDeserializeFunctionBody(MF->getAssociatedModule(), fn);
if (!MF->isSIB() && !SILMod.isSerialized()) {
assert((fn->isSerialized() || fn->empty()) &&
"deserialized function must have the IsSerialized flag set");
}
return fn;
}
// We put these static asserts here to formalize our assumption that both
// SILValueCategory and ValueOwnershipKind have uint8_t as their underlying
// pointer values.
static_assert(
std::is_same<std::underlying_type<SILValueCategory>::type, uint8_t>::value,
"Expected an underlying uint8_t type");
// We put these static asserts here to formalize our assumption that both
// SILValueCategory and ValueOwnershipKind have uint8_t as their underlying
// pointer values.
static_assert(std::is_same<std::underlying_type<OwnershipKind::innerty>::type,
uint8_t>::value,
"Expected an underlying uint8_t type");
SILBasicBlock *SILDeserializer::readSILBasicBlock(SILFunction *Fn,
SILBasicBlock *Prev,
SmallVectorImpl<uint64_t> &scratch) {
ArrayRef<uint64_t> Args;
SILBasicBlockLayout::readRecord(scratch, Args);
// Args should be a list of triples of the following form:
//
// 1. A TypeID.
// 2. A flag of metadata. This currently includes the SILValueCategory and
// ValueOwnershipKind. We enforce size constraints of these types above.
// 3. A ValueID.
SILBasicBlock *CurrentBB = getBBForDefinition(Fn, Prev, BasicBlockID++);
bool IsEntry = CurrentBB->isEntry();
for (unsigned I = 0, E = Args.size(); I < E; I += 3) {