Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion src/driver.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ The default [`relocation_lowering`](@ref) strategy resolves Julia-value relocati

The IR in the result (the `:llvm` module, or `meta.ir` and `meta.entry`) lives in the
LLVM context of the enclosing [`JuliaContext`](@ref) block, and is freed with it. Use it,
and dispose of it, within that block.
and dispose of it, within that block. The do-block form, `compile(f, target, job)`, takes
care of both.
"""
function compile(target::Symbol, @nospecialize(job::CompilerJob))
run_compile_hook(job)
Expand All @@ -92,6 +93,34 @@ function compile(target::Symbol, @nospecialize(job::CompilerJob))
end
end

"""
compile(f, target::Symbol, job::CompilerJob)

Compile `job` as `compile(target, job)` does, in an LLVM context of its own, and return
`f(result, meta)`. `result` is the module for `:llvm`, and the code otherwise.

`f` runs with the context of the IR active, so it can work with the module and its values
directly. The IR and its context are freed when `f` returns: return only values that don't
refer to them, e.g., strings, or the code.

```julia
compile(:obj, job) do obj, meta
(; obj, entry=meta.entry.name)
end
```
"""
function compile(f, target::Symbol, @nospecialize(job::CompilerJob))
return JuliaContext() do _
result, meta = compile(target, job)
ir = target === :llvm ? result : meta.ir
try
f(result, meta)
finally
dispose(ir)
end
end
end

function report_failure(f, @nospecialize(job::CompilerJob))
hook = compile_failure_hook[]
hook === nothing && return f()
Expand Down
22 changes: 22 additions & 0 deletions test/native.jl
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,28 @@ import InteractiveUtils
end
end

@testset "compile do-block" begin
mod = @eval module $(gensym())
f(x::Int) = x + 1
end
job, _ = Native.create_job(mod.f, (Int,))

# the block runs in the context of the IR
name = GPUCompiler.compile(:llvm, job) do ir, meta
@test context() == context(ir)
@test meta.entry in ir.functions
meta.entry.name
end
asm, entry = GPUCompiler.compile(:asm, job) do asm, meta
@test meta.entry in meta.ir.functions
asm, meta.entry.name
end
@test occursin(r"^(julia|j)_f_\d+$", name)
@test occursin(r"^(julia|j)_f_\d+$", entry) && occursin(entry, asm)

@test_throws "boom" GPUCompiler.compile((_, _) -> error("boom"), :llvm, job)
end

@testset "compile hook" begin
mod = @eval module $(gensym())
f(x::Int) = nothing
Expand Down
Loading