Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
04f986b
llvmcall: Ptr values as integers of their size, as native code passes…
vchuravy Oct 19, 2026
4d18a1e
llvmcall convention: extern functions, overloads of intrinsics by bas…
vchuravy Oct 19, 2026
7680e02
Atomic fields: loads with an order, modifications as a cmpxchg loop
vchuravy Oct 19, 2026
147d48c
throw through jl_throw also where inference knows the call throws
vchuravy Oct 19, 2026
059d8bc
Fast-math flags on the _fast intrinsics, as native code
vchuravy Oct 19, 2026
3409f16
The runtime's objects through its globals, as native code
vchuravy Oct 19, 2026
00a65cd
Unions keep the box of a constant member, or the box it came from
vchuravy Oct 19, 2026
91c2066
llvmcall of unknown names as native code; type checks of pointerset v…
vchuravy Oct 19, 2026
f633ae3
ccall: runtime symbols by their ijl_ alias; others lazily bound as na…
vchuravy Oct 19, 2026
a922cba
Globals: other bindings from the runtime, typed assignments through t…
vchuravy Oct 19, 2026
cccbdf5
Calls of specialized varargs methods: compiled, with the varargs packed
vchuravy Oct 19, 2026
6164275
Debug information: the statement in the column, names of the specsig …
vchuravy Oct 19, 2026
fc3de49
Debug information: the statement in the column only from Julia 1.14 o…
vchuravy Oct 19, 2026
196afc7
specsig: varargs methods, with their arguments one by one
vchuravy Oct 19, 2026
af9c54f
emit_into!: the jlcall entry calls the specsig entry, as native code's
vchuravy Oct 19, 2026
888e912
getfield with an index known only at run time
vchuravy Oct 19, 2026
3a97301
Inline aggregates by reference, as native code's specsig convention
vchuravy Oct 19, 2026
a4ff09f
emit_into!: jlcall entries with the attributes of native code's
vchuravy Oct 19, 2026
3a96361
Functions of @noinline methods are noinline, as native code's
vchuravy Oct 19, 2026
55f4574
Error paths through the runtime, as native code's
vchuravy Oct 19, 2026
e0ca352
Core.svec and Core._svec_len, as native code
vchuravy Oct 19, 2026
e1f194a
Debug information: the NoDebug emission kind, with locations
vchuravy Oct 20, 2026
399b4eb
Base.llvmcall passes structs of fields of one type as arrays
vchuravy Oct 20, 2026
6c0cce7
Objects' globals named as native code's, small-tag types from jl_smal…
vchuravy Oct 20, 2026
e04207a
specsig: union results, as native code
vchuravy Oct 20, 2026
46e3675
specsig: a union result keeps its box
vchuravy Oct 20, 2026
d58890b
specsig: union results with their roots, as native code from Julia 1.…
vchuravy Oct 20, 2026
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
10 changes: 8 additions & 2 deletions src/boxing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ end

derived(fc::FnCtx, v::LLVM.Value) = LLVM.addrspacecast!(fc.builder, v, T_derived())

# a tracked pointer passed to a function that roots it (`mark_callee_rooted`)
callee_rooted(fc::FnCtx, v::LLVM.Value) =
LLVM.addrspacecast!(fc.builder, v, LLVM.PointerType(AddrSpace.CalleeRooted))

"""
JuliaCodegen.emit_allocation(fc, T) -> LLVM.Value

Expand Down Expand Up @@ -101,10 +105,12 @@ function convert_repr(fc::FnCtx, v::CGVal, @nospecialize T)
v.typ === T && return v
# the value is known to be of type T, so representations agree
value_type(fc, v.typ) == value_type(fc, T) &&
return CGVal(T, Inline, v.V, v.constant, v.vboxed)
return CGVal(T, Inline, v.V, v.constant, v.vboxed, v.mem)
unsupported("converting the inline ", v.typ, " to ", T)
elseif v.kind === Boxed
return inline(T, emit_unbox(fc, v.V, T); constant=v.constant)
# (an immutable object: its contents never change)
mem = byref(fc.cgm, T) ? derived(fc, v.V) : nothing
return inline(T, emit_unbox(fc, v.V, T); constant=v.constant, mem)
end
unsupported("converting the ghost ", v.typ, " to the inline ", T)
end
Expand Down
303 changes: 283 additions & 20 deletions src/builtins.jl

Large diffs are not rendered by default.

48 changes: 40 additions & 8 deletions src/calls.jl
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,26 @@ function emit_guard!(fc::FnCtx, cond::LLVM.Value, f::Function, args::CGVal...)
return nothing
end

"""
JuliaCodegen.emit_raise_unless!(fc, cond, exc)

If `cond` (an `i1`) is false, throw the exception object `exc` through the runtime
(`jl_throw`), as native code's `raise_exception_unless`.
"""
function emit_raise_unless!(fc::FnCtx, cond::LLVM.Value, @nospecialize(exc))
b = fc.builder
fail = LLVM.BasicBlock(current_function(fc), "fail")
pass = LLVM.BasicBlock(current_function(fc), "pass")
LLVM.br!(b, cond, pass, fail)
LLVM.position!(b, LLVM.at_end(fail))
f = runtime_function(fc, :jl_throw)
LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[callee_rooted(fc, literal_pointer(fc, exc))])
LLVM.unreachable!(b)
LLVM.position!(b, LLVM.at_end(pass))
return nothing
end

# error paths, which construct the exceptions in Julia
@noinline throw_divide_error() = throw(DivideError())
@noinline throw_error_message(msg::String) = throw(ErrorException(msg))

## walker hooks
Expand All @@ -67,8 +85,15 @@ function emit_call!(fc::FnCtx, f::CGVal, ex::Expr, @nospecialize(typ))
end
args = CGVal[operand(fc, a) for a in ex.args[2:end]]
# a call that inference found to throw (e.g. of an intrinsic with the wrong number of
# arguments) goes to the runtime, which throws the error
typ === Union{} && return emit_dynamic_call(fc, f, args, typ)
# arguments) goes to the runtime, which throws the error; but `throw` itself, which
# throws through `jl_throw` as native code (which GPU compilers lower)
if typ === Union{}
if isconstant(f) && constant_value(f) === Core.throw
r = emit_builtin(fc, Core.throw, args, typ)
r === nothing || return r
end
return emit_dynamic_call(fc, f, args, typ)
end
if isconstant(f) && constant_value(f) isa Core.IntrinsicFunction
r = emit_intrinsic(fc, constant_value(f), args, typ)
r === nothing || return r
Expand All @@ -83,17 +108,24 @@ end
invoke_target(@nospecialize(x)) =
x isa Core.CodeInstance ? CC.get_ci_mi(x) : x::Core.MethodInstance

function emit_invoke!(fc::FnCtx, ex::Expr, @nospecialize(typ))
mi = invoke_target(ex.args[1])
args = CGVal[operand(fc, a) for a in ex.args[2:end]]
emit_invoke!(fc::FnCtx, ex::Expr, @nospecialize(typ)) =
emit_invoke_call(fc, invoke_target(ex.args[1]), CGVal[operand(fc, a) for a in ex.args[2:end]], typ)

# the call `args` (the function first) of the method instance `mi`, a value of type `typ`
function emit_invoke_call(fc::FnCtx, mi::Core.MethodInstance, args::Vector{CGVal}, @nospecialize(typ))
# a call whose arguments may not match the signature (an invoke of a less specific
# method with more specific arguments is fine; others are left to the runtime)
sig = signature_argtypes(mi)
if !(mi.def isa Method) || mi.def.isva || any(T -> T isa Core.TypeofVararg, sig) ||
length(args) != length(sig) || !all(i -> args[i].typ <: sig[i], eachindex(args))
# (a varargs method instance whose signature has a `Vararg`, e.g. of an error path, is
# called through the runtime, with the arguments one by one; specialized ones are
# compiled)
if !(mi.def isa Method) || !args_match(sig, args) ||
(!isempty(sig) && last(sig) isa Core.TypeofVararg)
return emit_dynamic_call(fc, args[1], args[2:end], typ; invoke=mi)
end
info = get_function!(fc.cgm, mi)
# (the varargs of a varargs method in the tuple its function takes)
mi.def.isva && (args = pack_varargs(fc, mi, args))
r = emit_call_info(fc, info, args)
r.kind === Bottom && return r
return convert_repr(fc, r, typ)
Expand Down
97 changes: 69 additions & 28 deletions src/ccall.jl
Original file line number Diff line number Diff line change
Expand Up @@ -262,10 +262,24 @@ function runtime_symbol_name(sym::Symbol)
isempty(hs) && return nothing
iname = Symbol("i", sym)
own_dlsym(hs[1], iname) != C_NULL && return String(iname)
any(h -> own_dlsym(h, sym) != C_NULL, hs) && return String(sym)
return nothing
end

# the runtime's libraries as `jl_dlfind` names them (pointers that are not strings,
# `JL_EXE_LIBNAME` etc.), with the globals of their handles
const RUNTIME_LIBRARIES = Dict(1 => "jl_exe_handle", 2 => "jl_libjulia_handle",
3 => "jl_libjulia_internal_handle")

# the library that defines `sym` as native code finds it (`jl_dlfind`): `nothing` (any
# library), a library name (on Windows, which has no global symbol namespace, the C
# runtime, kernel32, ...), or one of the runtime's libraries (an `Int`, see above)
function find_library(sym::Symbol)
found = ccall(:jl_dlfind, Ptr{UInt8}, (Cstring,), String(sym))
found == C_NULL && return nothing
haskey(RUNTIME_LIBRARIES, Int(UInt(found))) && return Int(UInt(found))
return unsafe_string(found)
end

# an external declaration: a function of type `ft`, or without `ft`, a global
function declare_symbol(cgm::CGModule, name::String, ft=nothing)
mod = cgm.mod
Expand All @@ -276,8 +290,8 @@ function declare_symbol(cgm::CGModule, name::String, ft=nothing)
end

# a module-owned `ptr` global, initially null
function symbol_cache!(cgm::CGModule, prefix::String)
gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, prefix))
function symbol_cache!(cgm::CGModule, prefix::String, suffix::String="")
gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, prefix) * suffix)
LLVM.initializer!(gv, LLVM.null(T_ptr()))
LLVM.linkage!(gv, LLVM.API.LLVMInternalLinkage)
return gv
Expand Down Expand Up @@ -307,16 +321,14 @@ function emit_symbol_address(fc::FnCtx, sym::Symbol, @nospecialize(lib); ft=noth
if lib === nothing && libexpr === nothing
rname = runtime_symbol_name(sym)
rname === nothing || return declare_symbol(cgm, rname, ft)
# the library that defines it, as native code finds it (`jl_dlfind`): on Windows,
# which has no global symbol namespace, the C runtime, kernel32, ...
found = ccall(:jl_dlfind, Cstring, (Cstring,), String(sym))
found == C_NULL || (lib = unsafe_string(found))
lib = find_library(sym)
end
b = fc.builder
P = T_ptr()
W = config(fc).target.pointer_size
dynamic = libexpr !== nothing || !(lib === nothing || lib isa Union{String,Symbol})
cache = symbol_cache!(cgm, "ccall_" * String(sym))
dynamic = libexpr !== nothing || !(lib === nothing || lib isa Union{String,Symbol,Int})
# (named as native code's lazily bound functions, `jlplt_name_N_got`)
cache = symbol_cache!(cgm, "jlplt_" * String(sym), "_got")
cached = LLVM.load!(b, P, cache; align=W, ordering=LLVM.API.LLVMAtomicOrderingUnordered)
from = current_block(b)
f = current_function(fc)
Expand All @@ -330,8 +342,15 @@ function emit_symbol_address(fc::FnCtx, sym::Symbol, @nospecialize(lib); ft=noth
LLVM.call!(b, LLVM.function_type(lf), lf, LLVM.Value[libv, literal_pointer(fc, sym)])
else
lf = declare_runtime(cgm.mod, dialect(fc), :jl_load_and_lookup)
libname, hnd = lib === nothing ? (LLVM.null(P), declare_symbol(cgm, "jl_RTLD_DEFAULT_handle")) :
(cstring!(cgm, String(lib)), symbol_cache!(cgm, "ccalllib"))
libname, hnd = if lib === nothing
LLVM.null(P), declare_symbol(cgm, "jl_RTLD_DEFAULT_handle")
elseif lib isa Int
# one of the runtime's libraries, by `jl_dlfind`'s name and its handle's global
LLVM.const_inttoptr(LLVM.ConstantInt(iptr_type(fc), lib), P),
declare_symbol(cgm, RUNTIME_LIBRARIES[lib])
else
cstring!(cgm, String(lib)), symbol_cache!(cgm, "ccalllib")
end
LLVM.call!(b, LLVM.function_type(lf), lf, LLVM.Value[libname, cstring!(cgm, String(sym)), hnd])
end
LLVM.store!(b, found, cache; align=W, ordering=LLVM.API.LLVMAtomicOrderingRelease)
Expand Down Expand Up @@ -564,10 +583,12 @@ end
"""
JuliaCodegen.emit_llvmcall_cc(fc, ex, typ) -> CGVal

`ccall("llvm.name", llvmcall, rt, argtypes, args...)`: a call of the LLVM function `name`
(an intrinsic, also one that LLVM doesn't know, which back ends and validation report),
declared with the LLVM types of `llvmcall` (tuples of `VecElement`s are vectors), as
native code calls it.
`ccall("llvm.name", llvmcall, rt, argtypes, args...)`: a call of the LLVM intrinsic `name`
(the base name of an overloaded one is mangled from the call's signature), or with
`"extern name"` of the external function `name`, declared with the LLVM types of
`llvmcall` (tuples of `VecElement`s are vectors), as native code calls it. Any other name
(also of an intrinsic LLVM doesn't know) is an error at run time ("llvmcall only supports
intrinsic calls"), as in native code.
"""
function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ))
b = fc.builder
Expand All @@ -576,26 +597,36 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ))
target isa Tuple && length(target) == 1 && (target = target[1])
target isa Union{Symbol,String} || unsupported("an llvmcall of a name not known at compile time")
fname = String(target)
# (native code compiles anything but an intrinsic to an error: "llvmcall only supports
# intrinsic calls")
startswith(fname, "llvm.") || unsupported("an llvmcall of the non-intrinsic ", fname)
nargs = length(argtypes)
(nreq == 0 || nreq == nargs) || unsupported("a variadic llvmcall")
# (native code mangles the base name of an overloaded intrinsic, e.g. `llvm.powi`, from
# the signature)
intr = tryparse(LLVM.Intrinsic, fname)
intr !== nothing && LLVM.isoverloaded(intr) && LLVM.name(intr) == fname &&
unsupported("an llvmcall of the unmangled overloaded intrinsic ", fname)
mod = fc.cgm.mod
lrt = llvmcall_type(fc, rt)
lats = LLVM.LLVMType[llvmcall_type(fc, T) for T in argtypes]
ft = LLVM.FunctionType(lrt, lats)
f = if haskey(LLVM.functions(mod), fname)
g = LLVM.functions(mod)[fname]
LLVM.function_type(g) == ft || unsupported("an llvmcall of ", fname, " with another signature")
g
f = if startswith(fname, "extern ")
# `extern name`: an external function of that name, e.g. of a GPU runtime
llvmcall_function(mod, chopprefix(fname, "extern "), ft)
elseif startswith(fname, "llvm.") && tryparse(LLVM.Intrinsic, fname) !== nothing
intr = tryparse(LLVM.Intrinsic, fname)
if LLVM.isoverloaded(intr) && LLVM.name(intr) == fname
# the base name of an overloaded intrinsic (`llvm.powi`): the overload of
# the call's signature (`llvm.powi.f64.i32`), as native code mangles it
try
LLVM.Function(mod, intr, ft)
catch err
err isa ArgumentError || rethrow()
unsupported("an llvmcall of ", fname, " with the signature ", string(ft))
end
else
llvmcall_function(mod, fname, ft)
end
else
LLVM.Function(mod, fname, ft)
# anything but an intrinsic LLVM knows or an `extern` function is an error at run
# time, as native code compiles it (which GPU compilers report)
err = declare_runtime(mod, dialect(fc), :jl_error)
LLVM.call!(b, LLVM.function_type(err), err,
LLVM.Value[cstring!(fc.cgm, "llvmcall only supports intrinsic calls")])
return emit_unreachable!(fc)
end
ops = LLVM.Value[]
for (i, T) in enumerate(argtypes)
Expand All @@ -610,6 +641,14 @@ function emit_llvmcall_cc(fc::FnCtx, ex::Expr, @nospecialize(typ))
return inline(rt, LLVM.value_type(r) == rty ? r : reinterpret_value(fc, r, rty))
end

# the function `name` of `mod` with the type `ft`, declared if there is none
function llvmcall_function(mod::LLVM.Module, name::AbstractString, ft::LLVM.FunctionType)
haskey(LLVM.functions(mod), name) || return LLVM.Function(mod, String(name), ft)
f = LLVM.functions(mod)[name]
LLVM.function_type(f) == ft || unsupported("an llvmcall of ", name, " with another signature")
return f
end

# Runtime functions that native code emits inline (`emit_ccall`'s special functions):
# calling them would make their argument escape (e.g. the `Ref` of `pointer_from_objref`).
function emit_special_ccall(fc::FnCtx, name::Symbol, ex::Expr, @nospecialize(rt), argtypes)
Expand Down Expand Up @@ -682,6 +721,8 @@ function emit_expr_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ))
return emit_foreigncall(fc, ex, typ)
elseif head === :cfunction
return emit_cfunction(fc, ex, typ)
elseif head === :invoke_modify
return emit_invoke_modify(fc, ex, typ)
elseif head === :foreignglobal # (Julia 1.14 and later)
return emit_cglobal(fc, ex.args[1], typ)
elseif head === :gc_preserve_begin
Expand Down
8 changes: 5 additions & 3 deletions src/config.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ The configuration of the code generator, which generates code for the running Ju
- `debug_info`: the debug information to emit, as the `debug_info_kind` of Julia's
`CodegenParams`: `:none`, or line tables (a subprogram per function and the location
of every statement, with inlined frames) in a compile unit of the emission kind
`:line_tables`, `:directives` or `:full`.
`:line_tables`, `:directives` or `:full`, or `:no_debug`, which native code emits for
the kind `NoDebug` (unless Julia runs with `-g0`): for tools reading locations, like
GPUCompiler's error messages, which strip them later.

The facts about the running Julia's runtime are `config.runtime`, see
[`RuntimeFacts`](@ref JuliaCodegen.RuntimeFacts).
Expand All @@ -47,8 +49,8 @@ struct CodegenConfig
value in FAILURE_POLICIES ||
throw(ArgumentError("invalid $name policy :$value; expected one of $(join(FAILURE_POLICIES, ", "))"))
end
debug_info in (:none, :line_tables, :directives, :full) ||
throw(ArgumentError("invalid debug_info :$debug_info; expected none, line_tables, directives or full"))
debug_info in (:none, :no_debug, :line_tables, :directives, :full) ||
throw(ArgumentError("invalid debug_info :$debug_info; expected none, no_debug, line_tables, directives or full"))
new(target, dialect, runtime_facts(), on_unsupported, on_internal_error, gcstack_arg,
safepoint_on_entry, debug_info)
end
Expand Down
68 changes: 65 additions & 3 deletions src/constants.jl
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,70 @@
# addresses of objects.

"""
JuliaCodegen.literal_global(cgm, x) -> LLVM.GlobalVariable
JuliaCodegen.literal_global(cgm, x) -> LLVM.Constant

The global of `cgm` that holds the address of the object `x`.
The global of `cgm` that holds the address of the object `x`, as native code's
(`literal_pointer_val_slot`): for `true`, `false`, `nothing`, `()` and `Core.svec()`, the
runtime's own (`jl_true`, ...); for types with a small tag, their entry in the runtime's
`jl_small_typeof`; for other objects, a global of the module, named as native code's.
"""
function literal_global(cgm::CGModule, @nospecialize x)
name = runtime_object_name(x)
name === nothing || return runtime_object_global(cgm, name)
st = smalltag(cgm.config, x)
if x isa DataType && st != 0
table = runtime_global(cgm.mod, :jl_small_typeof, LLVM.Int8Type())
return LLVM.const_inbounds_gep(LLVM.Int8Type(), table,
LLVM.Constant[LLVM.ConstantInt(LLVM.Int32Type(), st << 4)])
end
get!(cgm.literals, x) do
gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), unique_name(cgm, "jl_global"))
gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), literal_name(cgm, x))
LLVM.linkage!(gv, LLVM.API.LLVMExternalLinkage)
gv.metadata["julia.constgv"] = LLVM.MDNode(LLVM.Metadata[])
gv
end
end

# the name of the global of the object `x`, as native code's (`julia_pgv`): `+Mod.T#` for
# types, `-Mod.f#` for methods and their instances, `jl_sym#s#` for symbols and
# `jl_global#` for other objects, numbered
function literal_name(cgm::CGModule, @nospecialize x)
qualified(mod, name) = join((fullname(mod)..., name), '.')
prefix = if x isa DataType
string("+", qualified(x.name.module, x.name.name), "#")
elseif x isa Method
string("-", qualified(x.module, x.name), "#")
elseif x isa Core.MethodInstance && x.def isa Method
string("-", qualified(x.def.module, x.def.name), "#")
elseif x isa Symbol
string("jl_sym#", x, "#")
else
"jl_global#"
end
cgm.counter += 1
return string(prefix, cgm.counter)
end

# The objects the runtime has globals of, which native code refers to by those
# (`global_jlvalue_to_llvm` in codegen.cpp): GPU compilers relocate them by name.
const RUNTIME_OBJECTS = (true => "jl_true", false => "jl_false", nothing => "jl_nothing",
Core.svec() => "jl_emptysvec", () => "jl_emptytuple")

function runtime_object_name(@nospecialize x)
for (obj, name) in RUNTIME_OBJECTS
x === obj && return name
end
return nothing
end

# the runtime's global `name`, which holds the address of its object
function runtime_object_global(cgm::CGModule, name::String)
haskey(LLVM.globals(cgm.mod), name) && return LLVM.globals(cgm.mod)[name]
gv = LLVM.GlobalVariable(cgm.mod, T_ptr(), name)
LLVM.constant!(gv, true)
return gv
end

"""
JuliaCodegen.literal_objects(cgm) -> Vector{Pair{String,Any}}

Expand Down Expand Up @@ -48,6 +100,16 @@ function literal_pointer(fc::FnCtx, @nospecialize x)
end
end

# an untracked pointer to the object `x` (native code's `literal_pointer_val`), for the
# runtime functions that take one, loaded where it is used
function literal_pointer_raw(fc::FnCtx, @nospecialize x)
p = LLVM.load!(fc.builder, T_ptr(), literal_global(fc.cgm, x); align=config(fc).target.pointer_size)
tbaa!(fc, p, :const)
p.metadata[LLVM.MD_invariant_load] = LLVM.MDNode(LLVM.Metadata[])
p.metadata[LLVM.MD_nonnull] = LLVM.MDNode(LLVM.Metadata[])
return p
end

# where loads of objects go: the start of the entry block, which dominates every use
function top_insertion_point(fc::FnCtx)
insts = LLVM.instructions(fc.top)
Expand Down
Loading
Loading