diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index 78627047b19ad..ead29559ced51 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -3701,13 +3701,16 @@ static void emitUsed(CodeGenModule &CGM, StringRef Name, if (List.empty()) return; - // Convert List to what ConstantArray needs. - SmallVector UsedArray; - UsedArray.resize(List.size()); - for (unsigned i = 0, e = List.size(); i != e; ++i) { - UsedArray[i] = - llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( - cast(&*List[i]), CGM.Int8PtrTy); + // Convert List to what ConstantArray needs. A used global may have been + // deleted after it was added to the list (e.g. when its home module keeps + // accumulating declarations after an erroneous incremental parse), leaving + // a null value handle behind; skip those entries. + SmallVector UsedArray; + UsedArray.reserve(List.size()); + for (const llvm::WeakTrackingVH &VH : List) { + if (llvm::Value *V = VH) + UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( + cast(V), CGM.Int8PtrTy)); } if (UsedArray.empty()) diff --git a/clang/test/Interpreter/used-global-after-error.cpp b/clang/test/Interpreter/used-global-after-error.cpp new file mode 100644 index 0000000000000..fc1043042d5cc --- /dev/null +++ b/clang/test/Interpreter/used-global-after-error.cpp @@ -0,0 +1,15 @@ +// REQUIRES: host-supports-jit +// UNSUPPORTED: system-aix +// RUN: cat %s | clang-repl | FileCheck %s + +// A cast<> of a null WeakTrackingVH used to crash emitUsed when a global on +// the llvm.used list was deleted before the module was released: the +// duplicate definition below is diagnosed by CodeGen, which then replaces the +// used global's unreferenced GV with a differently-typed one; the failed +// parse keeps the module alive, and the next successful parse finalizes it. +extern "C" int printf(const char *, ...); +__attribute__((used)) int a asm("sym") = 1; float b asm("sym") = 2.0f; +auto r1 = printf("ok = %d\n", 42); +// CHECK: ok = 42 + +%quit