diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -6384,6 +6384,9 @@ } Entry = CV; + if (CodeGenOpts.KeepPersistentStorageVariables) + addUsedOrCompilerUsedGlobal(GV); + return ConstantAddress(CV, Type, Align); } diff --git a/clang/lib/CodeGen/ItaniumCXXABI.cpp b/clang/lib/CodeGen/ItaniumCXXABI.cpp --- a/clang/lib/CodeGen/ItaniumCXXABI.cpp +++ b/clang/lib/CodeGen/ItaniumCXXABI.cpp @@ -2381,6 +2381,11 @@ } CGM.setStaticLocalDeclGuardAddress(&D, guard); + + if (CGM.getCodeGenOpts().KeepPersistentStorageVariables && + (D.getStorageDuration() == SD_Static || + D.getStorageDuration() == SD_Thread)) + CGM.addUsedOrCompilerUsedGlobal(guard); } Address guardAddr = Address(guard, guard->getValueType(), guardAlignment); diff --git a/clang/lib/CodeGen/MicrosoftCXXABI.cpp b/clang/lib/CodeGen/MicrosoftCXXABI.cpp --- a/clang/lib/CodeGen/MicrosoftCXXABI.cpp +++ b/clang/lib/CodeGen/MicrosoftCXXABI.cpp @@ -2674,6 +2674,11 @@ CGM.setTLSMode(GuardVar, D); if (GI && !HasPerVariableGuard) GI->Guard = GuardVar; + + if (CGM.getCodeGenOpts().KeepPersistentStorageVariables && + (D.getStorageDuration() == SD_Static || + D.getStorageDuration() == SD_Thread)) + CGM.addUsedOrCompilerUsedGlobal(GuardVar); } ConstantAddress GuardAddr(GuardVar, GuardTy, GuardAlign); diff --git a/clang/test/CodeGen/keep-persistent-storage-variables.cpp b/clang/test/CodeGen/keep-persistent-storage-variables.cpp --- a/clang/test/CodeGen/keep-persistent-storage-variables.cpp +++ b/clang/test/CodeGen/keep-persistent-storage-variables.cpp @@ -15,7 +15,11 @@ // CHECK: @_ZN2ST2s6E = global i32 7, align 4 // CHECK: @_Z2v7 = internal global %union.anon zeroinitializer, align 4 // CHECK: @_ZDC2v8E = global %struct.ST8 zeroinitializer, align 4 -// CHECK: @llvm{{(\.compiler)?}}.used = appending global [14 x ptr] [ptr @_ZL2g1, ptr @_ZL2g2, ptr @tl1, ptr @tl2, ptr @_ZL3tl3, ptr @_ZL3tl4, ptr @g5, ptr @g6, ptr @_ZZ5test3vE2s3, ptr @_ZN12_GLOBAL__N_12s4E, ptr @_ZZ5test5vE3tl5, ptr @_ZN2ST2s6E, ptr @_Z2v7, ptr @_ZDC2v8E], section "llvm.metadata" +// CHECK: @_ZGRL2g9_ = internal global i32 55, align 4 +// CHECK: @_ZL2g9 = internal constant ptr @_ZGRL2g9_, align 8 +// CHECK: @_ZZ6test10vE3s10 = internal global i32 0, align 4 +// CHECK: @_ZGVZ6test10vE3s10 = internal global i64 0, align 8 +// CHECK: @llvm{{(\.compiler)?}}.used = appending global [18 x ptr] [ptr @_ZL2g1, ptr @_ZL2g2, ptr @tl1, ptr @tl2, ptr @_ZL3tl3, ptr @_ZL3tl4, ptr @g5, ptr @g6, ptr @_ZZ5test3vE2s3, ptr @_ZN12_GLOBAL__N_12s4E, ptr @_ZZ5test5vE3tl5, ptr @_ZN2ST2s6E, ptr @_Z2v7, ptr @_ZDC2v8E, ptr @_ZGRL2g9_, ptr @_ZL2g9, ptr @_ZGVZ6test10vE3s10, ptr @_ZZ6test10vE3s10], section "llvm.metadata" static int g1; static int g2 = 1; @@ -51,3 +55,11 @@ struct ST8 { int v8; }; auto [v8] = ST8{0}; + +static const int &g9 = 55; + +int f10(); +int test10() { + static int s10 = f10(); + return s10; +}