Skip to content

Commit d4de1a0

Browse files
committed
Deserializer: fix a crash with global variables and cross-module-optimization
In case of cross-module-optimizations it can happen that a private global variable is changed to public, but it's declaration is not available in the module file.
1 parent 7ede371 commit d4de1a0

File tree

3 files changed

+26
-1
lines changed

3 files changed

+26
-1
lines changed

lib/Serialization/DeserializeSIL.cpp

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3642,11 +3642,23 @@ SILGlobalVariable *SILDeserializer::readGlobalVar(StringRef Name) {
36423642
return nullptr;
36433643
}
36443644

3645+
VarDecl *globalDecl = nullptr;
3646+
if (dID) {
3647+
llvm::Expected<Decl *> d = MF->getDeclChecked(dID);
3648+
if (d) {
3649+
globalDecl = cast<VarDecl>(d.get());
3650+
} else {
3651+
// This can happen with cross-module-optimizations, if the linkage of a
3652+
// private global variable is changed to public.
3653+
consumeError(d.takeError());
3654+
}
3655+
}
3656+
36453657
auto Ty = MF->getType(TyID);
36463658
SILGlobalVariable *v = SILGlobalVariable::create(
36473659
SILMod, linkage.value(), SerializedKind_t(serializedKind),
36483660
Name.str(), getSILType(Ty, SILValueCategory::Object, nullptr),
3649-
std::nullopt, dID ? cast<VarDecl>(MF->getDecl(dID)) : nullptr);
3661+
std::nullopt, globalDecl);
36503662
v->setLet(IsLet);
36513663
globalVarOrOffset.set(v, true /*isFullyDeserialized*/);
36523664
v->setDeclaration(IsDeclaration);

test/SILOptimizer/Inputs/cross-module/cross-module.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,12 @@ public func callCImplementationOnly<T>(_ t: T) -> Int {
287287

288288
public let globalLet = 529387
289289

290+
private var privateVar = Int.random(in: 0..<100)
291+
292+
public func getRandom() -> Int {
293+
return privateVar
294+
}
295+
290296
public struct StructWithClosure {
291297
public static let c = { (x: Int) -> Int in return x }
292298
}

test/SILOptimizer/cross-module-optimization.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,12 @@ func testImplementationOnly() {
165165
// CHECK-SIL2: } // end sil function '$s4Main22testImplementationOnlyyyF'
166166
}
167167

168+
@inline(never)
169+
func testPrivateVar() {
170+
// CHECK-OUTPUT: {{[0-9]+}}
171+
print(getRandom())
172+
}
173+
168174
testNestedTypes()
169175
testClass()
170176
testError()
@@ -175,4 +181,5 @@ testKeypath()
175181
testMisc()
176182
testGlobal()
177183
testImplementationOnly()
184+
testPrivateVar()
178185

0 commit comments

Comments
 (0)