diff --git a/src/irgen/irgen.cpp b/src/irgen/irgen.cpp index 5a412809..7109f697 100644 --- a/src/irgen/irgen.cpp +++ b/src/irgen/irgen.cpp @@ -112,8 +112,7 @@ llvm::Value* IRGenerator::findValue(llvm::StringRef name, const Decl* decl) { switch (decl->getKind()) { case DeclKind::VarDecl: - codegenVarDecl(*llvm::cast(decl)); - return globalScope().getLocalValues().find(llvm::cast(decl)->getName())->second; + return codegenVarDecl(*llvm::cast(decl)); case DeclKind::FieldDecl: return codegenMemberAccess(findValue("this", nullptr), @@ -656,8 +655,11 @@ llvm::StructType* IRGenerator::codegenTypeDecl(const TypeDecl& decl) { return structType; } -void IRGenerator::codegenVarDecl(const VarDecl& decl) { - if (globalScope().getLocalValues().find(decl.getName()) != globalScope().getLocalValues().end()) return; +llvm::Value* IRGenerator::codegenVarDecl(const VarDecl& decl) { + if (auto* value = module.getGlobalVariable(decl.getName(), true)) return value; + + auto it = globalScope().getLocalValues().find(decl.getName()); + if (it != globalScope().getLocalValues().end()) return it->second; llvm::Value* value = decl.getInitializer() ? codegenExpr(*decl.getInitializer()) : nullptr; @@ -669,6 +671,7 @@ void IRGenerator::codegenVarDecl(const VarDecl& decl) { } globalScope().addLocalValue(decl.getName(), value); + return value; } void IRGenerator::codegenDecl(const Decl& decl) { diff --git a/src/irgen/irgen.h b/src/irgen/irgen.h index 382b6208..a0a26afb 100644 --- a/src/irgen/irgen.h +++ b/src/irgen/irgen.h @@ -129,7 +129,7 @@ class IRGenerator { void codegenFunctionDecl(const FunctionDecl& decl); void codegenInitDecl(const InitDecl& decl); llvm::StructType* codegenTypeDecl(const TypeDecl& decl); - void codegenVarDecl(const VarDecl& decl); + llvm::Value* codegenVarDecl(const VarDecl& decl); llvm::Value* getFunctionForCall(const CallExpr& call); llvm::Function* getFunctionProto(const FunctionDecl& decl, Type receiverType = nullptr,