Export Carbon global variables and static vars to C++ (#7298)

Add `ExportVarToCpp`. This checks the `clang_decls` mapping and returns
an existing decl if found. Otherwise, it creates a new `VarDecl` and
adds it to the `clang_decls` mapping.

When lowering, in `FileContext::BuildGlobalVariableDecl`, the
`clang_decls` mapping is used to lookup an existing
`llvm::GlobalVariable` for the instruction. If found, use that rather
than creating a new one to avoid an unwanted second definition in the
llvm IR.
This commit is contained in:
Nicholas Bishop
2026-06-03 20:47:54 +00:00
committed by GitHub
parent 76dd872ab4
commit f2d0c4d0ae
12 changed files with 354 additions and 11 deletions
+15
View File
@@ -672,6 +672,21 @@ auto FileContext::BuildDISubprogram(const SemIR::Function& function,
auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
-> llvm::Constant* {
// When a Carbon variable is exported and used from C++, code
// generation for the C++ code may have already created an
// llvm::GlobalVariable. If so, return that global rather than
// creating a new one.
auto clang_decl_id = sem_ir().clang_decls().Lookup(var_storage.pattern_id);
if (clang_decl_id.has_value()) {
auto* decl = sem_ir().clang_decls().Get(clang_decl_id).key.decl;
auto* constant = cpp_code_generator_->GetAddrOfGlobal(
CreateGlobalDecl(cast<clang::NamedDecl>(decl)),
/*isForDefinition=*/false);
if (constant) {
return constant;
}
}
auto var_name_id =
SemIR::GetFirstBindingNameFromPatternId(sem_ir(), var_storage.pattern_id);
if (auto cpp_global_var_id =