Skip to content

Commit

Permalink
Temporarily externalize Julia globals
Browse files Browse the repository at this point in the history
  • Loading branch information
jpsamaroo committed Jun 9, 2021
1 parent 9fbe9cc commit 4b3cf11
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/driver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,12 @@ const __llvm_initialized = Ref(false)
internalize!(pm, exports)

# eliminate all unused internal functions
add!(pm, ModulePass("ExternalizeJuliaGlobals",
externalize_julia_globals!))
global_optimizer!(pm)
global_dce!(pm)
add!(pm, ModulePass("InternalizeJuliaGlobals",
internalize_julia_globals!))
strip_dead_prototypes!(pm)

# merge constants (such as exception messages) from the runtime
Expand Down Expand Up @@ -309,6 +313,39 @@ const __llvm_initialized = Ref(false)
return ir, (; entry, compiled)
end

# Protect null globals from being killed and inlined
function externalize_julia_globals!(mod::LLVM.Module)
changed = false
for gbl in LLVM.globals(mod)
if LLVM.linkage(gbl) == LLVM.API.LLVMInternalLinkage &&
typeof(LLVM.initializer(gbl)) <: LLVM.PointerNull &&
(startswith(LLVM.name(gbl), "jl_global") ||
startswith(LLVM.name(gbl), "jl_sym"))
LLVM.linkage!(gbl, LLVM.API.LLVMExternalLinkage)
LLVM.initializer!(gbl, nothing)
LLVM.extinit!(gbl, true)
changed = true
end
end
changed
end
# And reset the back later
function internalize_julia_globals!(mod::LLVM.Module)
changed = false
for gbl in LLVM.globals(mod)
if LLVM.linkage(gbl) == LLVM.API.LLVMExternalLinkage &&
LLVM.initializer(gbl) === nothing &&
(startswith(LLVM.name(gbl), "jl_global") ||
startswith(LLVM.name(gbl), "jl_sym"))
LLVM.extinit!(gbl, false)
LLVM.initializer!(gbl, null(eltype(llvmtype(gbl))))
LLVM.linkage!(gbl, LLVM.API.LLVMInternalLinkage)
changed = true
end
end
changed
end

@locked function emit_asm(@nospecialize(job::CompilerJob), ir::LLVM.Module;
strip::Bool=false, validate::Bool=true, format::LLVM.API.LLVMCodeGenFileType)
finish_module!(job, ir)
Expand Down
4 changes: 4 additions & 0 deletions src/mcgen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,15 @@ function prepare_execution!(@nospecialize(job::CompilerJob), mod::LLVM.Module)
global current_job
current_job = job

add!(pm, ModulePass("ExternalizeJuliaGlobals",
externalize_julia_globals!))
global_optimizer!(pm)

add!(pm, ModulePass("ResolveCPUReferences", resolve_cpu_references!))

global_dce!(pm)
add!(pm, ModulePass("InternalizeJuliaGlobals",
internalize_julia_globals!))
strip_dead_prototypes!(pm)

run!(pm, mod)
Expand Down

0 comments on commit 4b3cf11

Please sign in to comment.