diff --git a/src/boxing.jl b/src/boxing.jl index c34218d..efdfa1f 100644 --- a/src/boxing.jl +++ b/src/boxing.jl @@ -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 @@ -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 diff --git a/src/builtins.jl b/src/builtins.jl index 8f7aa5d..902e8de 100644 --- a/src/builtins.jl +++ b/src/builtins.jl @@ -319,16 +319,23 @@ end function nonconst_global(fc::FnCtx, ref::GlobalRef) d = direct_binding(fc, ref) + b = fc.builder if d === nothing - return emit_dynamic_call(fc, const_value(fc, Core.getglobal), - CGVal[const_value(fc, ref.mod), const_value(fc, ref.name)], Any) + # another binding (imported, not yet resolved, undefined): its value from the + # runtime (`jl_get_binding_value_seqcst`), as native code reads it + bnd = convert(Core.Binding, ref) + t = literal_pointer(fc, bnd) + raw = t isa LLVM.AddrSpaceCastInst ? LLVM.operands(t)[1] : LLVM.addrspacecast!(b, t, T_ptr()) + gb = declare_runtime(fc.cgm.mod, dialect(fc), :jl_get_binding_value_seqcst) + v = LLVM.call!(b, LLVM.function_type(gb), gb, LLVM.Value[raw]) + T = Any + else + bnd, T = d + v = LLVM.load!(b, T_tracked(), binding_value_address(fc, bnd)) + LLVM.ordering!(v, LLVM.API.LLVMAtomicOrderingUnordered) + LLVM.alignment!(v, config(fc).target.pointer_size) + tbaa!(fc, v, :binding) end - bnd, T = d - b = fc.builder - v = LLVM.load!(b, T_tracked(), binding_value_address(fc, bnd)) - LLVM.ordering!(v, LLVM.API.LLVMAtomicOrderingUnordered) - LLVM.alignment!(v, config(fc).target.pointer_size) - tbaa!(fc, v, :binding) # undefined: an UndefVarError, from the runtime as native code's f = current_function(fc) err = LLVM.BasicBlock(f, "err") @@ -343,11 +350,11 @@ function nonconst_global(fc::FnCtx, ref::GlobalRef) return boxed(T isa Type ? T : Any, v) end -# `global ref = v` of a global of type `Any` through its binding, as native code does; -# `false` for other bindings +# `global ref = v` of a global through its binding, as native code does, when `v` is of the +# global's type (no conversion); `false` for other bindings function emit_binding_assignment!(fc::FnCtx, ref::GlobalRef, v::CGVal) d = direct_binding(fc, ref) - (d === nothing || d[2] !== Any) && return false + (d === nothing || !(d[2] isa Type && v.typ <: d[2])) && return false bnd, _ = d b = fc.builder p = emit_box(fc, v) @@ -374,10 +381,8 @@ function field_index(@nospecialize(T), f::CGVal) return nothing end -@noinline throw_undefref() = throw(UndefRefError()) - -# a null check of a reference that is undefined when null: UndefRefError -undef_check!(fc::FnCtx, p::LLVM.Value) = emit_guard!(fc, nonnull(fc, p), throw_undefref) +# a null check of a reference that is undefined when null: the runtime's UndefRefError +undef_check!(fc::FnCtx, p::LLVM.Value) = emit_raise_unless!(fc, nonnull(fc, p), UndefRefError()) # `getfield(x, f, [order], [boundscheck])` function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) @@ -386,13 +391,31 @@ function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) T = x.typ (T isa DataType && isconcretetype(T)) || return nothing i = field_index(T, args[2]) - i === nothing && return nothing - # an explicit order: only the plain access of a non-atomic field here + if i === nothing + (args[2].typ === Int && args[2].kind === Inline && !isconstant(args[2])) || return nothing + bc = const_value(fc, true) + for a in args[3:end] + if a.typ === Bool + bc = a + elseif !(isconstant(a) && constant_value(a) === :not_atomic) + return nothing + end + end + return emit_getfield_unknownidx(fc, x, T, args[2], bc, rt) + end + # an explicit order: the plain access of a non-atomic field, or the atomic load of an + # atomic one (mismatches are the runtime's ConcurrencyViolationError) + order = :not_atomic for a in args[3:end] a.typ === Bool && continue - (isconstant(a) && constant_value(a) === :not_atomic) || return nothing + (isconstant(a) && constant_value(a) isa Symbol) || return nothing + order = constant_value(a) + end + if ismutabletype(T) && Base.isfieldatomic(T, i) + order === :not_atomic && return nothing + return emit_atomic_getfield(fc, x, T, i, order, rt) end - ismutabletype(T) && Base.isfieldatomic(T, i) && return nothing + order === :not_atomic || return nothing FT = fieldtype(T, i) b = fc.builder if x.kind === Ghost @@ -432,6 +455,95 @@ function emit_getfield(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return nothing end +# `getfield(x, i)` of the field whose index `i` (an `Int`) is only known at run time, +# with the bounds check of the boundscheck argument `bc` (native code's +# `emit_getfield_unknownidx`): of the fields of an inline tuple of a single type, or of an +# object whose fields are all references or all of a single type +function emit_getfield_unknownidx(fc::FnCtx, x::CGVal, @nospecialize(T), idx::CGVal, bc::CGVal, + @nospecialize(rt)) + n = fieldcount(T) + n == 0 && return nothing + b = fc.builder + types = fieldtypes(T) + FT = types[1] + same = all(t -> t === FT, types) + if n == 1 + lowered = fc -> emit_getfield(fc, CGVal[x, const_value(fc, 1)], rt) + elseif x.kind === Ghost || (same && repr_kind(FT) === Ghost) + same || return nothing + lowered = fc -> convert_repr(fc, ghost(FT, something(ghost_value(FT))), rt) + elseif x.kind === Inline + lay = layout(fc, T) + (lay.llvm isa LLVM.ArrayType || lay.llvm isa LLVM.VectorType) || return nothing + # (references, of any types, or values of a single type) + refs = all(i -> field_storage(T, i) === FieldPointer, 1:n) + (refs || same) || return nothing + lowered = fc -> begin + v = inline_element(fc, x, lay, refs, n, idx; align=Base.datatype_alignment(FT)) + convert_repr(fc, refs ? boxed(Union{types...}, v) : inline(FT, v), rt) + end + elseif x.kind === Boxed + ismutabletype(T) && T.name.atomicfields != C_NULL && return nothing + storage = [field_storage(T, i) for i in 1:n] + if all(==(FieldPointer), storage) + lowered = fc -> begin + p = LLVM.inbounds_gep!(b, T_tracked(), derived(fc, x.V), [LLVM.sub!(b, idx.V, iptr(fc, 1))]) + v = tbaa!(fc, LLVM.load!(b, T_tracked(), p; align=config(fc).target.pointer_size), field_tbaa(fc, T)) + any(i -> maybe_undef_field(T, i), 1:n) && undef_check!(fc, v) + convert_repr(fc, boxed(Union{types...}, v), rt) + end + elseif same && all(==(FieldInline), storage) && + !(has_references(FT) && any(i -> maybe_undef_field(T, i), 1:n)) + stride = fieldoffset(T, 2) - fieldoffset(T, 1) + lowered = fc -> begin + off = LLVM.mul!(b, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, stride)) + p = LLVM.inbounds_gep!(b, LLVM.Int8Type(), derived(fc, x.V), [off]) + v = LLVM.load!(b, value_type(fc, FT), p; align=field_alignment(fc, T, FT)) + convert_repr(fc, inline(FT, tbaa!(fc, v, field_tbaa(fc, T))), rt) + end + else + return nothing + end + else + return nothing + end + bounds_check!(fc, LLVM.sub!(b, idx.V, iptr(fc, 1)), iptr(fc, n), bc, x, idx; unboxed=true) + return lowered(fc) +end + +# the element `idx` (1-based, in bounds) of the inline tuple `x` with the layout `lay` (an +# LLVM array or vector of `n` elements, references if `refs`, aligned to `align`): +# extracted from a vector, selected among references or a few values not in memory, or +# loaded from memory (the memory it was loaded from; for a constant, a private global, as +# native code's `value_to_pointer`; or a stack slot) +function inline_element(fc::FnCtx, x::CGVal, lay::Layout, refs::Bool, n::Int, idx::CGVal; + align::Integer) + b = fc.builder + i0 = LLVM.sub!(b, idx.V, iptr(fc, 1)) + if lay.llvm isa LLVM.VectorType + return LLVM.extract_element!(b, x.V, LLVM.trunc!(b, i0, LLVM.Int32Type())) + elseif refs || has_references(x.typ) || + (n <= 3 && x.mem === nothing && !(isconstant(x) && x.V isa LLVM.Constant)) + v = LLVM.extract_value!(b, x.V, 0) + for i in 1:n-1 + c = LLVM.icmp!(b, LLVM.API.LLVMIntEQ, i0, iptr(fc, i)) + v = LLVM.select!(b, c, LLVM.extract_value!(b, x.V, i), v) + end + return v + end + if x.mem !== nothing + mem, tb = x.mem, :const + elseif isconstant(x) && x.V isa LLVM.Constant + mem, tb = constant_memory!(fc.cgm, x.V, Base.datatype_alignment(x.typ)), :const + else + mem, tb = entry_alloca!(fc, lay.llvm; align=Base.datatype_alignment(x.typ)), :stack + tbaa!(fc, LLVM.store!(b, x.V, mem), :stack) + end + et = LLVM.element_type(lay.llvm) + p = LLVM.inbounds_gep!(b, et, mem, [i0]) + return tbaa!(fc, LLVM.load!(b, et, p; align), tb) +end + # `setfield!(x, f, v, [order])` of a non-atomic field function emit_setfield!(fc::FnCtx, args::Vector{CGVal}) length(args) in (3, 4) || return nothing @@ -516,7 +628,7 @@ function emit_throw(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) length(args) == 1 || return nothing b = fc.builder f = runtime_function(fc, :jl_throw) - p = LLVM.addrspacecast!(b, emit_box(fc, args[1]), LLVM.PointerType(AddrSpace.CalleeRooted)) + p = callee_rooted(fc, emit_box(fc, args[1])) LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[p]) return emit_unreachable!(fc) end @@ -551,6 +663,123 @@ function emit_getglobal(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return convert_repr(fc, nonconst_global(fc, ref), rt) end +# the atomic load with `order` of the atomic field `i` of the object `x` of type `T`: of a +# bits type of 1 to 8 bytes, or a reference +function emit_atomic_getfield(fc::FnCtx, x::CGVal, @nospecialize(T), i::Int, order::Symbol, + @nospecialize(rt)) + x.kind === Boxed || return nothing + ord = atomic_ordering(order; load=true) + ord === nothing && return nothing + FT = fieldtype(T, i) + s = field_storage(T, i) + b = fc.builder + if s === FieldPointer + ty, W = T_tracked(), config(fc).target.pointer_size + elseif s === FieldInline && isbitstype(FT) && sizeof(FT) in (1, 2, 4, 8) && repr_kind(FT) === Inline + ty, W = LLVM.IntType(8 * sizeof(FT)), sizeof(FT) + else + return nothing + end + v = LLVM.load!(b, ty, field_address(fc, x.V, T, i)) + LLVM.ordering!(v, ord) + LLVM.alignment!(v, W) + tbaa!(fc, v, field_tbaa(fc, T)) + if s === FieldPointer + maybe_undef_field(T, i) && undef_check!(fc, v) + return convert_repr(fc, boxed(FT, v), rt) + end + return convert_repr(fc, inline(FT, llvmcall_value(fc, v, value_type(fc, FT))), rt) +end + +@noinline throw_modify_type(@nospecialize(T), @nospecialize(x)) = + throw(TypeError(:modifyfield!, "", T, x)) + +""" + JuliaCodegen.emit_invoke_modify(fc, ex, typ) -> CGVal + +`Expr(:invoke_modify, ci, modifyfield!, obj, field, op, x, order)`: `modifyfield!` with +the operation `op` known to be the CodeInstance `ci`. For an atomic field of a bits type of +1 to 8 bytes, or of a reference, a loop of the atomic compare-and-exchange of the field +with `op(old, x)`, as native code does; otherwise, the call of `modifyfield!`. +""" +function emit_invoke_modify(fc::FnCtx, ex::Expr, @nospecialize(typ)) + args = CGVal[operand(fc, a) for a in ex.args[2:end]] + any(a -> a.kind === Bottom, args) && return bottom() + # (the operation's result type, of its CodeInstance) + opt = ex.args[1] isa Core.CodeInstance ? ex.args[1].rettype : Any + r = length(args) == 6 ? emit_modify_loop(fc, invoke_target(ex.args[1]), opt, args, typ) : nothing + r === nothing || return r + return emit_dynamic_call(fc, args[1], args[2:end], typ) +end + +function emit_modify_loop(fc::FnCtx, mi::Core.MethodInstance, @nospecialize(opt), + args::Vector{CGVal}, @nospecialize(typ)) + _, obj, fld, op, x, ord = args + T = obj.typ + (obj.kind === Boxed && T isa DataType && ismutabletype(T) && isconcretetype(T)) || return nothing + i = field_index(T, fld) + (i !== nothing && isconstant(ord) && constant_value(ord) isa Symbol) || return nothing + Base.isfieldatomic(T, i) || return nothing + order = constant_value(ord) + success = atomic_ordering(order; load=true) + (success === nothing || order in (:not_atomic, :unordered)) && return nothing + FT = fieldtype(T, i) + # (a result that can't be stored: the runtime's TypeError) + typeintersect(opt, FT) === Union{} && return nothing + s = field_storage(T, i) + b = fc.builder + isref = s === FieldPointer + if isref + ity = T_tracked() + elseif s === FieldInline && isbitstype(FT) && sizeof(FT) in (1, 2, 4, 8) && repr_kind(FT) === Inline + ity = LLVM.IntType(8 * sizeof(FT)) + else + return nothing + end + W = isref ? config(fc).target.pointer_size : sizeof(FT) + addr = field_address(fc, obj.V, T, i) + value_of(v) = isref ? boxed(FT, v) : inline(FT, llvmcall_value(fc, v, value_type(fc, FT))) + bits_of(v::CGVal) = isref ? emit_box(fc, v) : llvmcall_value(fc, convert_repr(fc, v, FT).V, ity) + init = LLVM.load!(b, ity, addr) + LLVM.ordering!(init, LLVM.API.LLVMAtomicOrderingMonotonic) + LLVM.alignment!(init, W) + tbaa!(fc, init, field_tbaa(fc, T)) + f = current_function(fc) + from = current_block(b) + loop = LLVM.BasicBlock(f, "xchg") + done = LLVM.BasicBlock(f, "done_xchg") + LLVM.br!(b, loop) + LLVM.position!(b, LLVM.at_end(loop)) + old = LLVM.phi!(b, ity) + # (a reference field may be undefined: UndefRefError) + isref && undef_check!(fc, old) + oldv = value_of(old) + # the new value: `op(old, x)`, of the field's type + newv = emit_invoke_call(fc, mi, CGVal[op, oldv, x], opt) + newv.kind === Bottom && return newv + if !(newv.typ <: FT) + ok = emit_isa(fc, newv, FT) + ok === nothing && return nothing + emit_guard!(fc, ok, throw_modify_type, const_value(fc, FT), newv) + end + newbits = bits_of(newv) + r = LLVM.atomic_cmpxchg!(b, addr, old, newbits, success, LLVM.API.LLVMAtomicOrderingMonotonic; + align=W) + tbaa!(fc, r, field_tbaa(fc, T)) + loaded = LLVM.extract_value!(b, r, 0) + ok = LLVM.extract_value!(b, r, 1) + tail = current_block(b) + append!(LLVM.incoming(old), [(init, from), (loaded, tail)]) + LLVM.br!(b, ok, done, loop) + LLVM.position!(b, LLVM.at_end(done)) + isref && write_barrier!(b, fc.cgm.mod, dialect(fc), obj.V, LLVM.addrspacecast!(b, addr, T_derived()), newbits) + newfinal = isref ? boxed(FT, newbits) : value_of(newbits) + P = Pair{FT,FT} + pair = repr_kind(P) === Inline ? emit_new_inline(fc, P, CGVal[oldv, newfinal]) : nothing + pair === nothing && return nothing + return convert_repr(fc, pair, typ) +end + # `setglobal!(m, s, x, [order])` of a global of type `Any` with the default (release) order, # through its binding function emit_setglobal!(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) @@ -583,6 +812,38 @@ function emit_isdefined(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) return nothing end +# `Core.svec(xs...)`: allocated inline, as native code (from Julia 1.12 on), with the +# elements boxed first +function emit_svec(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) + isempty(args) && return const_value(fc, Core.svec()) + b = fc.builder + W = config(fc).target.pointer_size + elems = LLVM.Value[emit_box(fc, a) for a in args] + sv = call_op!(fc, "julia.gc_alloc_obj", fc.current_task, + LLVM.ConstantInt(LLVM.Int64Type(), W * (length(args) + 1)), + type_tag(fc, Core.SimpleVector)) + data = derived(fc, sv) + LLVM.store!(b, iptr(fc, length(args)), data; align=W) + for (i, e) in enumerate(elems) + addr = LLVM.inbounds_gep!(b, LLVM.Int8Type(), data, [iptr(fc, W * i)]) + st = LLVM.store!(b, e, addr; align=W) + LLVM.ordering!(st, LLVM.API.LLVMAtomicOrderingRelease) + write_barrier!(b, fc.cgm.mod, dialect(fc), sv, addr, e) + end + return boxed(Core.SimpleVector, sv) +end + +# `Core._svec_len(sv)`: the length, the first word +function emit_svec_len(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) + length(args) == 1 || return nothing + sv = args[1] + isconstant(sv) && constant_value(sv) isa Core.SimpleVector && + return const_value(fc, length(constant_value(sv))) + sv.typ === Core.SimpleVector || return nothing + W = config(fc).target.pointer_size + return inline(Int, LLVM.load!(fc.builder, iptr_type(fc), derived(fc, emit_box(fc, sv)); align=W)) +end + const BUILTINS = IdDict{Any,Function}( Core.:(===) => (fc, args, rt) -> length(args) == 2 ? emit_egal(fc, args[1], args[2]) : nothing, Core.ifelse => emit_ifelse, @@ -597,6 +858,8 @@ const BUILTINS = IdDict{Any,Function}( Core.sizeof => emit_sizeof, Core.getglobal => emit_getglobal, Core.setglobal! => emit_setglobal!, + Core.svec => emit_svec, + Core._svec_len => emit_svec_len, ) """ diff --git a/src/calls.jl b/src/calls.jl index 8a4963e..6e7b5b7 100644 --- a/src/calls.jl +++ b/src/calls.jl @@ -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 @@ -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 @@ -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) diff --git a/src/ccall.jl b/src/ccall.jl index ca1d2b0..196a4a9 100644 --- a/src/ccall.jl +++ b/src/ccall.jl @@ -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 @@ -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 @@ -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) @@ -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) @@ -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 @@ -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) @@ -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) @@ -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 diff --git a/src/config.jl b/src/config.jl index dc481e9..dfe77fb 100644 --- a/src/config.jl +++ b/src/config.jl @@ -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). @@ -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 diff --git a/src/constants.jl b/src/constants.jl index 3515093..1c865a1 100644 --- a/src/constants.jl +++ b/src/constants.jl @@ -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}} @@ -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) diff --git a/src/context.jl b/src/context.jl index 8421a0b..5185704 100644 --- a/src/context.jl +++ b/src/context.jl @@ -5,8 +5,9 @@ An LLVM function emitted for a `MethodInstance`, in JuliaCodegen's internal calling convention: ghost arguments are dropped, the others are passed in their representation -(inline values by value, boxed ones as tracked pointers, unboxed unions as their union -type), and the result is returned in the representation of the inferred return type +(inline values by value, but aggregates without references by reference to memory that +doesn't change, `ptr addrspace(11)`, as native code's specsig convention; boxed ones as +tracked pointers, unboxed unions as their union type), and the result is returned in the representation of the inferred return type (`void` for ghosts and `Union{}`). """ struct FuncInfo @@ -61,6 +62,8 @@ mutable struct CGModule throwing_stubs::Bool "The debug information (a `DebugInfo`), created on first use." debuginfo::Any + "The linkage names of the subprograms of functions, if not the functions' names." + debug_linkage::IdDict{LLVM.Function,String} counter::Int end @@ -71,7 +74,7 @@ function CGModule(mod::LLVM.Module, config::CodegenConfig; world::UInt=Base.get_ return CGModule(mod, config, world, Layouts(config), TBAA(config.dialect), IdDict{Core.MethodInstance,FuncInfo}(), Tuple{FuncInfo,Any}[], IdDict{Any,LLVM.GlobalVariable}(), Pair{Core.MethodInstance,Any}[], Entry[], ir_source, - throwing_stubs, nothing, 0) + throwing_stubs, nothing, IdDict{LLVM.Function,String}(), 0) end "A name that is unique in the module, from `prefix` and the function `f` (if any)." diff --git a/src/debuginfo.jl b/src/debuginfo.jl index 1b1d66b..88b33cf 100644 --- a/src/debuginfo.jl +++ b/src/debuginfo.jl @@ -1,11 +1,11 @@ -# Debug information: the line tables of native code (`debug_info_kind` above `NoDebug`): +# Debug information: the line tables of native code (`debug_info_level` above 0): # a compile unit for the module, a subprogram for every function, and for every # statement the location of its line, with the functions inlined into it as inlined frames # (from the IR's line information). Tools (and GPUCompiler's error messages) read # backtraces from them. There is no information about variables or types. # the emission kinds of `debug_info` (`DICompileUnit::DebugEmissionKind`) -const DEBUG_EMISSION_KINDS = (none=0, full=1, line_tables=2, directives=3) +const DEBUG_EMISSION_KINDS = (no_debug=0, full=1, line_tables=2, directives=3) """ JuliaCodegen.DebugInfo @@ -82,7 +82,8 @@ frame_name(@nospecialize(m)) = JuliaCodegen.debug_function!(fc, f; name, file, line) Give the function `f` that `fc` emits a subprogram (`name` at `file:line`, by default -those of the method being compiled), and the builder its location, for the instructions +those of the method being compiled; with the linkage name `cgm.debug_linkage[f]`, if any, +else the function's), and the builder its location, for the instructions emitted before the first statement and in functions without IR (entries, stubs). """ function debug_function!(fc::FnCtx, f::LLVM.Function; name=nothing, file=nothing, line=nothing) @@ -92,7 +93,7 @@ function debug_function!(fc::FnCtx, f::LLVM.Function; name=nothing, file=nothing name = something(name, frame_name(m)) file = something(file, m isa Method ? m.file : :none) line = something(line, m isa Method ? m.line : 0) - sp = subprogram!(di, name, file, line, LLVM.name(f)) + sp = subprogram!(di, name, file, line, get(fc.cgm.debug_linkage, f, LLVM.name(f))) f.subprogram = sp fc.subprogram = sp LLVM.debug_location!(fc.builder, LLVM.DILocation(max(Int(line), 0), 0, sp)) @@ -107,6 +108,7 @@ function statement_location!(fc::FnCtx, idx::Int) frames = Base.IRShow.buildLineInfoNode(fc.ir.debuginfo, fc.info.mi, idx) isempty(frames) && return # (keep the previous location) loc = nothing + n = length(frames) for (k, fr) in enumerate(frames) scope = if k == 1 fc.subprogram @@ -116,7 +118,10 @@ function statement_location!(fc::FnCtx, idx::Int) subprogram!(di, name, fr.file, 0) end end - loc = LLVM.DILocation(max(Int(fr.line), 0), 0, scope, loc) + # (from Julia 1.14 on, the column of the innermost location is the statement, as + # native code encodes it: tools map errors in the LLVM IR back to the Julia IR by it) + col = k == n && config(fc).dialect.minor >= v"1.14" ? idx : 0 + loc = LLVM.DILocation(max(Int(fr.line), 0), col, scope, loc) end LLVM.debug_location!(fc.builder, loc) end diff --git a/src/emit_into.jl b/src/emit_into.jl index d74d768..663707a 100644 --- a/src/emit_into.jl +++ b/src/emit_into.jl @@ -78,7 +78,10 @@ end function emit_sources!(cgm::CGModule, codeinfos, sources) infos = Pair{Core.CodeInstance,FuncInfo}[] for (ci, _) in codeinfos - push!(infos, ci => get_function!(cgm, CC.get_ci_mi(ci))) + info = get_function!(cgm, CC.get_ci_mi(ci)) + push!(infos, ci => info) + # (debug information names a function by its specsig entry, as tools look it up) + cgm.debug_linkage[info.llvmf] = "j_" * chopprefix(LLVM.name(info.llvmf), "julia_") end process_worklist!(cgm) compiled = IdDict{Core.CodeInstance,CompiledFunctions}() @@ -87,15 +90,16 @@ function emit_sources!(cgm::CGModule, codeinfos, sources) # call), its entries `j_f_N` in the specsig convention (the prefix of native code's # specsig wrappers) and `jfptr_f_N` in the jlcall one base = chopprefix(LLVM.name(info.llvmf), "julia_") - func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base) - push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) specfunc = try - LLVM.name(emit_specsig_wrapper!(cgm, info, "j_" * base)) + emit_specsig_wrapper!(cgm, info, "j_" * base) catch err err isa Unsupported || rethrow() nothing end - compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc) + # (which calls the specsig entry, as native code's) + func = emit_jlcall_wrapper!(cgm, info, "jfptr_" * base; specfunc) + push!(cgm.entries, Entry(info.mi, LLVM.name(func), :jlcall)) + compiled[ci] = CompiledFunctions(LLVM.name(func), specfunc === nothing ? nothing : LLVM.name(specfunc)) end return compiled, codegen_output(cgm) end diff --git a/src/exceptions.jl b/src/exceptions.jl index 0f71117..d449cda 100644 --- a/src/exceptions.jl +++ b/src/exceptions.jl @@ -200,8 +200,6 @@ end ## statements that throw, and assignments of globals -@noinline throw_undefvar(@nospecialize(s)) = ccall(:jl_undefined_var_error, Union{}, (Any, Any), s, :local) - function emit_exception_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ)) head = ex.head if head === :leave @@ -220,10 +218,21 @@ function emit_exception_head!(fc::FnCtx, idx::Int, ex::Expr, @nospecialize(typ)) ok = LLVM.trunc!(fc.builder, c.V, LLVM.Int1Type()) var = ex.args[1] if var === :getfield_undefref || var === Symbol("##getfield##") - emit_guard!(fc, ok, throw_undefref) + emit_raise_unless!(fc, ok, UndefRefError()) else - # (a Symbol, or a GlobalRef in a module context; passed to UndefVarError as is) - emit_guard!(fc, ok, throw_undefvar, const_value(fc, var)) + # the runtime's UndefVarError of the local variable (`undef_var_error_ifnot`; a + # Symbol, or a GlobalRef in a module context, passed to UndefVarError as is) + b = fc.builder + fail = LLVM.BasicBlock(current_function(fc), "err") + pass = LLVM.BasicBlock(current_function(fc), "ok") + LLVM.br!(b, ok, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + f = runtime_function(fc, :jl_undefined_var_error) + LLVM.call!(b, LLVM.function_type(f), f, + LLVM.Value[callee_rooted(fc, literal_pointer(fc, var)), + callee_rooted(fc, literal_pointer(fc, :local))]) + LLVM.unreachable!(b) + LLVM.position!(b, LLVM.at_end(pass)) end return ghost(Nothing, nothing) elseif head === :(=) diff --git a/src/function.jl b/src/function.jl index 0c44a42..18ea618 100644 --- a/src/function.jl +++ b/src/function.jl @@ -31,26 +31,150 @@ Declare the function of `mi` in JuliaCodegen's internal convention (see function declare_function!(cgm::CGModule, mi::Core.MethodInstance, argtypes::Vector{Any}, @nospecialize(rettype)) params = LLVM.LLVMType[] + attrs = Vector{LLVM.Attribute}[] for T in argtypes t = value_type(cgm.layouts, T) - t === nothing || push!(params, t) + t === nothing && continue + if byref(cgm, T) + push!(params, T_derived()) + push!(attrs, LLVM.Attribute[attr("readonly"), ref_attributes(T)...]) + else + push!(params, t) + push!(attrs, LLVM.Attribute[]) + end end ret = something(value_type(cgm.layouts, rettype), LLVM.VoidType()) f = mi.def isa Method ? mi.specTypes.parameters[1] : nothing fobj = f isa DataType && isdefined(f, :instance) ? f.instance : nothing llvmf = LLVM.Function(cgm.mod, unique_name(cgm, "julia", fobj), LLVM.FunctionType(ret, params)) + for (i, as) in enumerate(attrs), a in as + push!(LLVM.parameter_attributes(llvmf)[i], a) + end LLVM.linkage!(llvmf, LLVM.API.LLVMInternalLinkage) init_function!(llvmf, cgm.config.target) rettype === Union{} && push!(llvmf.function_attributes, LLVM.EnumAttribute("noreturn")) + # (as native code's, for methods declared `@noinline`) + is_noinline(mi) && push!(llvmf.function_attributes, LLVM.EnumAttribute("noinline")) info = FuncInfo(mi, llvmf, argtypes, rettype) cgm.funcs[mi] = info return info end +# whether the method of `mi` is declared `@noinline` (its source's inlining flag) +function is_noinline(mi::Core.MethodInstance) + m = mi.def + (m isa Method && m.source !== nothing) || return false + return ccall(:jl_ir_flag_inlining, UInt8, (Any,), m.source) == 2 +end + +""" + JuliaCodegen.byref(cgm, T) -> Bool + +Whether functions take arguments of the inline type `T` by reference (see +[`FuncInfo`](@ref JuliaCodegen.FuncInfo)): aggregates without references. +""" +byref(cgm::CGModule, @nospecialize(T)) = + repr_kind(T) === Inline && !has_references(T) && is_aggregate(layout(cgm.layouts, T).llvm) + +# the operand that passes the inline value `v` of type `T` by reference: the memory it +# was loaded from, a constant global for a constant, or a stack slot +function byref_operand(fc::FnCtx, v::CGVal, @nospecialize(T)) + v.mem === nothing || return derived(fc, v.mem) + lay = layout(fc, T) + mem = if isconstant(v) && v.V isa LLVM.Constant + constant_memory!(fc.cgm, v.V, Base.datatype_alignment(T)) + else + slot = entry_alloca!(fc, lay.llvm; align=Base.datatype_alignment(T)) + st = LLVM.store!(fc.builder, v.V, slot) + LLVM.alignment!(st, Base.datatype_alignment(T)) + tbaa!(fc, st, :stack) + slot + end + return derived(fc, mem) +end + +# a private constant global with the value `c` (native code's `get_pointer_to_constant`) +function constant_memory!(cgm::CGModule, c::LLVM.Constant, align::Integer) + gv = LLVM.GlobalVariable(cgm.mod, LLVM.value_type(c), unique_name(cgm, "_j_const")) + LLVM.initializer!(gv, c) + LLVM.constant!(gv, true) + LLVM.linkage!(gv, LLVM.API.LLVMPrivateLinkage) + LLVM.unnamed_addr!(gv, LLVM.API.LLVMGlobalUnnamedAddr) + LLVM.alignment!(gv, align) + return gv +end + +# the operands of a call of the function `info` with the values `args` +function call_operands(fc::FnCtx, info::FuncInfo, args::Vector{CGVal}) + ops = LLVM.Value[] + for (a, T) in zip(args, info.argtypes) + v = convert_repr(fc, a, T) + v.kind === Ghost && continue + push!(ops, byref(fc.cgm, T) ? byref_operand(fc, v, T) : v.V) + end + return ops +end + +# a reference argument of type `T`: its value, loaded, and the memory +function byref_argument(fc::FnCtx, @nospecialize(T), p::LLVM.Value) + ld = LLVM.load!(fc.builder, layout(fc, T).llvm, p) + LLVM.alignment!(ld, Base.datatype_alignment(T)) + return inline(T, tbaa!(fc, ld, :const); mem=p) +end + "The Julia argument types of the function of `mi`, from its signature." signature_argtypes(mi::Core.MethodInstance) = Any[Base.unwrap_unionall(mi.specTypes).parameters...] +""" + JuliaCodegen.function_argtypes(mi) -> Vector{Any} + +The argument types of the function of `mi`, as its IR has them: those of its signature, +with the varargs of a varargs method packed into a tuple. +""" +function function_argtypes(mi::Core.MethodInstance) + sig = signature_argtypes(mi) + m = mi.def + (m isa Method && m.isva) || return sig + n = Int(m.nargs) + return Any[sig[1:n-1]..., Tuple{sig[n:end]...}] +end + +""" + JuliaCodegen.pack_varargs(fc, mi, args) -> Vector{CGVal} + +The arguments `args` of a call of the varargs method instance `mi`, one per element of its +signature, with the varargs packed into the tuple its function takes. +""" +function pack_varargs(fc::FnCtx, mi::Core.MethodInstance, args::Vector{CGVal}) + n = Int(mi.def.nargs) + rest = args[n:end] + TT = Tuple{(a.typ for a in rest)...} + PT = function_argtypes(mi)[n] + tup = if repr_kind(TT) === Ghost + ghost(TT, something(ghost_value(TT))) + elseif repr_kind(TT) === Inline + emit_new_inline(fc, TT, CGVal[convert_repr(fc, a, a.typ) for a in rest]) + else + nothing + end + tup === nothing && (tup = emit_dynamic_call(fc, const_value(fc, Core.tuple), rest, TT)) + return CGVal[args[1:n-1]..., convert_repr(fc, tup, PT)] +end + +# whether `args` are of the types of the signature `sig` (whose last element may be a +# `Vararg`) +function args_match(sig::Vector{Any}, args::Vector{CGVal}) + if !isempty(sig) && last(sig) isa Core.TypeofVararg + fixed = sig[1:end-1] + T = Base.unwrapva(last(sig)) + length(args) >= length(fixed) || return false + return all(i -> args[i].typ <: fixed[i], eachindex(fixed)) && + all(a -> a.typ <: T, args[length(fixed)+1:end]) + end + return length(args) == length(sig) && all(i -> args[i].typ <: sig[i], eachindex(args)) +end + # the pgcstack and the current task, and the safepoint on entry function emit_prologue!(fc::FnCtx; safepoint::Bool=true) b = fc.builder @@ -71,7 +195,8 @@ function bind_arguments!(fc::FnCtx) if repr_kind(T) === Ghost push!(fc.args, ghost(T, something(ghost_value(T)))) else - push!(fc.args, CGVal(T, repr_kind(T), params[p], nothing, nothing)) + push!(fc.args, byref(fc.cgm, T) ? byref_argument(fc, T, params[p]) : + CGVal(T, repr_kind(T), params[p], nothing, nothing)) p += 1 end end @@ -279,16 +404,23 @@ end ## the jlcall entry """ - JuliaCodegen.emit_jlcall_wrapper!(cgm, info, name) -> LLVM.Function + JuliaCodegen.emit_jlcall_wrapper!(cgm, info, name; specfunc=nothing) -> LLVM.Function The entry of the function `info` in the jlcall convention, `jl_value_t *name(jl_value_t *F, jl_value_t **args, uint32_t nargs)`: it unboxes the arguments, calls the function, -and boxes the result. +and boxes the result. With `specfunc`, the function's entry in the specsig convention +(see [`emit_specsig_wrapper!`](@ref JuliaCodegen.emit_specsig_wrapper!)), it calls that, +as native code's jlcall entries call their specsig functions. """ -function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString) +function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString; + specfunc::Union{Nothing,LLVM.Function}=nothing) ft = LLVM.FunctionType(T_tracked(), [T_tracked(), T_ptr(), LLVM.Int32Type()]) f = LLVM.Function(cgm.mod, String(name), ft) init_function!(f, cgm.config.target) + # (as native code's) + push!(f.return_attributes, attr("nonnull")) + foreach(a -> push!(f.parameter_attributes[2], a), + (attr("noalias"), nocapture(), attr("noundef"), attr("readonly"))) @dispose b=LLVM.IRBuilder() begin top = LLVM.BasicBlock(f, "top") LLVM.position!(b, LLVM.at_end(top)) @@ -296,18 +428,46 @@ function emit_jlcall_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStrin debug_function!(fc, f) emit_prologue!(fc; safepoint=false) F, argv, _ = LLVM.parameters(f) - ops = LLVM.Value[] - for (i, T) in enumerate(info.argtypes) - repr_kind(T) === Ghost && continue + # the arguments, one per element of the signature (the varargs of a varargs method + # packed for its function) + sig = signature_argtypes(info.mi) + m = info.mi.def + nfixed = length(sig) + packed = nothing + if !isempty(sig) && last(sig) isa Core.TypeofVararg + # as many varargs as the call has: packed by the runtime (`jl_f_tuple`, the builtin) + nfixed = Int(m.nargs) - 1 + ft = LLVM.FunctionType(T_tracked(), [T_tracked(), T_ptr(), LLVM.Int32Type()]) + tf = declare_symbol(cgm, "jl_f_tuple", ft) + k = nfixed - 1 # (the function isn't in the array) + rest = LLVM.gep!(b, T_tracked(), argv, [LLVM.ConstantInt(LLVM.Int64Type(), k)]) + n = LLVM.sub!(b, LLVM.parameters(f)[3], LLVM.ConstantInt(LLVM.Int32Type(), k)) + packed = boxed(info.argtypes[end], LLVM.call!(b, ft, tf, LLVM.Value[LLVM.null(T_tracked()), rest, n])) + end + args = CGVal[] + for (i, T) in enumerate(sig[1:nfixed]) p = if i == 1 F else slot = LLVM.gep!(b, T_tracked(), argv, [LLVM.ConstantInt(LLVM.Int64Type(), i - 2)]) tbaa!(fc, LLVM.load!(b, T_tracked(), slot; align=config(fc).target.pointer_size), :const) end - push!(ops, convert_repr(fc, boxed(Any, p), T).V) + push!(args, convert_repr(fc, boxed(Any, p), T)) + end + if specfunc !== nothing + # (which takes the arguments of a varargs method one by one) + sig = specsig_abi(cgm, sig, info.rettype) + r = emit_specsig_call!(fc, sig, specfunc, args) + # (after a call that doesn't return, in a block that is never reached) + repr_kind(info.rettype) === Bottom ? LLVM.unreachable!(b) : LLVM.ret!(b, emit_box(fc, r)) + return f + end + if packed !== nothing + push!(args, packed) + elseif m isa Method && m.isva + args = pack_varargs(fc, info.mi, args) end - r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) # (the entry is the function, as native code's: inlined by any pipeline) push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) rt = info.rettype @@ -329,7 +489,7 @@ end The function of `mi` in the module, declared on first use and queued for emission: its body from its IR, or a stub that calls its native code (for methods that always throw, -which are error paths, and varargs methods, for now). +which are error paths). """ function get_function!(cgm::CGModule, mi::Core.MethodInstance) info = get(cgm.funcs, mi, nothing) @@ -339,23 +499,19 @@ function get_function!(cgm::CGModule, mi::Core.MethodInstance) ir = nothing rt = Any reason = nothing - if m.isva - reason = "a varargs method" - else - try - ir, rt = cgm.ir_source(mi, cgm.world) - catch err - err isa Unsupported || rethrow() - # (calling native code instead follows the configuration's policy) - handle_failure(cgm.config, mi, err, catch_backtrace()) - reason = err - end - if ir !== nothing && rt === Union{} && cgm.throwing_stubs - reason = "a method that always throws" - ir = nothing - end + try + ir, rt = cgm.ir_source(mi, cgm.world) + catch err + err isa Unsupported || rethrow() + # (calling native code instead follows the configuration's policy) + handle_failure(cgm.config, mi, err, catch_backtrace()) + reason = err + end + if ir !== nothing && rt === Union{} && cgm.throwing_stubs + reason = "a method that always throws" + ir = nothing end - info = declare_function!(cgm, mi, signature_argtypes(mi), ir === nothing ? Any : rt) + info = declare_function!(cgm, mi, function_argtypes(mi), ir === nothing ? Any : rt) push!(cgm.worklist, (info, ir === nothing ? reason : ir)) return info end @@ -412,7 +568,31 @@ function emit_stub!(cgm::CGModule, info::FuncInfo) debug_function!(fc, info.llvmf) emit_prologue!(fc; safepoint=false) bind_arguments!(fc) - r = emit_dynamic_call(fc, fc.args[1], fc.args[2:end], info.rettype; invoke=info.mi) + args = fc.args + m = info.mi.def + r = nothing + if m isa Method && m.isva + # the native code of the method takes the varargs one by one + tup = args[end] + PT = tup.typ + elems = PT isa DataType && !Base.isvatuple(PT) ? CGVal[] : nothing + for i in 1:(elems === nothing ? 0 : fieldcount(PT)) + e = emit_builtin(fc, Core.getfield, CGVal[tup, const_value(fc, i)], fieldtype(PT, i)) + e === nothing && (elems = nothing; break) + push!(elems, e) + end + if elems !== nothing + args = CGVal[args[1:end-1]..., elems...] + else + # as many as the tuple has: splat it (`f(fixed..., tup...)`) + fixed = emit_dynamic_call(fc, const_value(fc, Core.tuple), args[2:end-1], + Tuple{(a.typ for a in args[2:end-1])...}) + r = emit_dynamic_call(fc, const_value(fc, Core._apply_iterate), + CGVal[const_value(fc, iterate), args[1], fixed, tup], info.rettype) + end + end + r === nothing && + (r = emit_dynamic_call(fc, args[1], args[2:end], info.rettype; invoke=info.mi)) emit_return!(fc, r) end end @@ -423,12 +603,7 @@ end Call the function `info` with the values `args` (converted to its argument types). """ function emit_call_info(fc::FnCtx, info::FuncInfo, args::Vector{CGVal}) - ops = LLVM.Value[] - for (a, T) in zip(args, info.argtypes) - v = convert_repr(fc, a, T) - v.kind === Ghost || push!(ops, v.V) - end - r = LLVM.call!(fc.builder, LLVM.function_type(info.llvmf), info.llvmf, ops) + r = LLVM.call!(fc.builder, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) rt = info.rettype k = repr_kind(rt) k === Bottom && return emit_unreachable!(fc) diff --git a/src/intrinsics.jl b/src/intrinsics.jl index 888e535..116c328 100644 --- a/src/intrinsics.jl +++ b/src/intrinsics.jl @@ -63,6 +63,46 @@ const CHECKED_ARITH = Dict{Symbol,String}( const CHECKED_DIVREM = (:checked_sdiv_int, :checked_udiv_int, :checked_srem_int, :checked_urem_int) +""" + JuliaCodegen.emit_typecheck!(fc, x, T, context) -> Union{CGVal,Nothing} + +The value `x` as a value of type `T`, checked at run time as native code's +`emit_typecheck`: a `TypeError` from the runtime (`jl_type_error(context, T, x)`) when it +isn't one. `nothing` if the check needs a subtype test. +""" +function emit_typecheck!(fc::FnCtx, x::CGVal, @nospecialize(T), context::String) + x.typ <: T && return convert_repr(fc, x, T) + b = fc.builder + function type_error() + err = declare_runtime(fc.cgm.mod, dialect(fc), :jl_type_error) + LLVM.call!(b, LLVM.function_type(err), err, + LLVM.Value[cstring!(fc.cgm, context), literal_pointer(fc, T), callee_rooted(fc, emit_box(fc, x))]) + LLVM.unreachable!(b) + end + if typeintersect(x.typ, T) === Union{} + type_error() + LLVM.position!(b, LLVM.at_end(LLVM.BasicBlock(current_function(fc), "after_type_error"))) + return bottom() + end + ok = emit_isa(fc, x, T) + ok === nothing && return nothing + f = current_function(fc) + fail = LLVM.BasicBlock(f, "type_error") + pass = LLVM.BasicBlock(f, "pass") + LLVM.br!(b, ok, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + type_error() + LLVM.position!(b, LLVM.at_end(pass)) + return convert_repr(fc, x.kind === Boxed ? boxed(T, x.V) : x, T) +end + +# the instruction of the intrinsic `name`, with all fast-math flags for the `_fast` ones, as +# native code +function fast!(name::Symbol, v::LLVM.Value) + endswith(String(name), "_fast") && v isa LLVM.Instruction && (v.fast_math.fast = true) + return v +end + isfloat_type(t::LLVM.LLVMType) = t isa Union{LLVM.HalfType,LLVM.BFloatType,LLVM.FloatType,LLVM.DoubleType} float_bits(t::LLVM.LLVMType) = t isa LLVM.DoubleType ? 64 : t isa LLVM.FloatType ? 32 : 16 @@ -130,6 +170,16 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal # `cglobal(target, T)` up to Julia 1.13 (a `:foreignglobal` expression later) name === :cglobal && return nothing (haskey(CASTS, name) || name === :bitcast) && return emit_cast(fc, name, args) + if name === :pointerset && length(args) == 4 && args[1].kind === Inline && args[1].typ <: Ptr + # the value as the element type, with a TypeError for others (as native code) + T = eltype(args[1].typ) + if repr_kind(T) === Inline && args[2].typ !== T + v = emit_typecheck!(fc, args[2], T, "pointerset") + v === nothing && return nothing + v.kind === Bottom && return v + args = CGVal[args[1], v, args[3], args[4]] + end + end any(a -> a.kind !== Inline, args) && return nothing # arithmetic and comparisons of operands of different types are a run-time error if (haskey(INT_BINOPS, name) || haskey(FLOAT_BINOPS, name) || haskey(ICMP, name) || @@ -142,17 +192,17 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal if haskey(INT_BINOPS, name) return iresult(fc, INT_BINOPS[name](b, xs[1], xs[2]), rt) elseif haskey(FLOAT_BINOPS, name) - return iresult(fc, FLOAT_BINOPS[name](b, xs[1], xs[2]), rt) + return iresult(fc, fast!(name, FLOAT_BINOPS[name](b, xs[1], xs[2])), rt) elseif haskey(ICMP, name) return iresult(fc, LLVM.icmp!(b, ICMP[name], xs[1], xs[2]), Bool) elseif haskey(FCMP, name) - return iresult(fc, LLVM.fcmp!(b, FCMP[name], xs[1], xs[2]), Bool) + return iresult(fc, fast!(name, LLVM.fcmp!(b, FCMP[name], xs[1], xs[2])), Bool) elseif name === :neg_int return iresult(fc, LLVM.neg!(b, xs[1]), rt) elseif name === :not_int return iresult(fc, LLVM.not!(b, xs[1]), rt) elseif name === :neg_float || name === :neg_float_fast - return iresult(fc, LLVM.fneg!(b, xs[1]), rt) + return iresult(fc, fast!(name, LLVM.fneg!(b, xs[1])), rt) elseif name === :fpiseq return emit_fpiseq(fc, args, xs) elseif name in (:shl_int, :lshr_int, :ashr_int) @@ -162,7 +212,7 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal neg = LLVM.icmp!(b, LLVM.API.LLVMIntSLT, y, LLVM.ConstantInt(LLVM.value_type(y), 0)) return iresult(fc, LLVM.select!(b, neg, LLVM.neg!(b, x), x), rt) elseif haskey(FLOAT_UNARY, name) - return iresult(fc, call_llvm_intrinsic!(fc, FLOAT_UNARY[name], [LLVM.value_type(xs[1])], xs), rt) + return iresult(fc, fast!(name, call_llvm_intrinsic!(fc, FLOAT_UNARY[name], [LLVM.value_type(xs[1])], xs)), rt) elseif name === :copysign_float return iresult(fc, call_llvm_intrinsic!(fc, "llvm.copysign", [LLVM.value_type(xs[1])], xs), rt) elseif name === :fma_float @@ -171,9 +221,9 @@ function emit_intrinsic(fc::FnCtx, f::Core.IntrinsicFunction, args::Vector{CGVal return iresult(fc, call_llvm_intrinsic!(fc, "llvm.fma", [LLVM.value_type(xs[1])], xs), rt) elseif name === :muladd_float return iresult(fc, call_llvm_intrinsic!(fc, "llvm.fmuladd", [LLVM.value_type(xs[1])], xs), rt) - elseif name === :min_float || name === :max_float - nm = name === :min_float ? "llvm.minimum" : "llvm.maximum" - return iresult(fc, call_llvm_intrinsic!(fc, nm, [LLVM.value_type(xs[1])], xs), rt) + elseif name in (:min_float, :max_float, :min_float_fast, :max_float_fast) + nm = name in (:min_float, :min_float_fast) ? "llvm.minimum" : "llvm.maximum" + return iresult(fc, fast!(name, call_llvm_intrinsic!(fc, nm, [LLVM.value_type(xs[1])], xs)), rt) elseif haskey(INT_UNARY, name) return emit_int_unary(fc, name, xs, rt) elseif haskey(CHECKED_ARITH, name) @@ -303,7 +353,7 @@ function emit_checked_divrem(fc::FnCtx, name::Symbol, xs::Vector{LLVM.Value}, @n ismin = LLVM.icmp!(b, LLVM.API.LLVMIntEQ, x, tmin) ok = LLVM.and!(b, ok, LLVM.not!(b, LLVM.and!(b, isneg1, ismin))) end - emit_guard!(fc, ok, throw_divide_error) + emit_raise_unless!(fc, ok, DivideError()) r = if name === :checked_sdiv_int LLVM.sdiv!(b, x, y) elseif name === :checked_udiv_int @@ -400,13 +450,19 @@ end # %1, ...) or a `(module, entry)` pair. The IR is parsed into the module being emitted, # marked `alwaysinline`, and called. -function llvmcall_type(fc::FnCtx, @nospecialize T) +# the LLVM type of values of type `T` in an llvmcall: of `ccall(..., llvmcall, ...)`, or +# with `base`, of `Base.llvmcall` +function llvmcall_type(fc::FnCtx, @nospecialize(T); base::Bool=false) (T === Nothing || T === Cvoid) && return LLVM.VoidType() + # (the IR of `Base.llvmcall` gets `Ptr` values as integers of their size, as native + # code passes them) + base && T isa DataType && T <: Ptr && return iptr_type(fc) repr_kind(T) === Inline || unsupported("llvmcall with the type ", T) ty = value_type(fc, T) - # (llvmcall passes structs other than tuples as LLVM structs) - if ty isa LLVM.ArrayType && !(T <: Tuple) - return LLVM.StructType(fill(ty.element_type, Int(length(ty)))) + # (`ccall` passes structs other than tuples as LLVM structs, `julia_struct_to_llvm` + # for llvmcall) + if !base && ty isa LLVM.ArrayType && !(T <: Tuple) + return LLVM.StructType(fill(ty.element_type, LLVM.array_length(ty))) end return ty end @@ -424,8 +480,8 @@ function emit_llvmcall(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) vals = args[4:end] ATs = AT isa DataType ? collect(Any, AT.parameters) : Any[] length(ATs) == length(vals) || return nothing - lrt = llvmcall_type(fc, RT) - lats = LLVM.LLVMType[llvmcall_type(fc, T) for T in ATs] + lrt = llvmcall_type(fc, RT; base=true) + lats = LLVM.LLVMType[llvmcall_type(fc, T; base=true) for T in ATs] cgm = fc.cgm if ir isa String name = unique_name(cgm, "jl_llvmcall") @@ -451,12 +507,21 @@ function emit_llvmcall(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) for (v, T, t) in zip(vals, ATs, lats) cv = convert_repr(fc, v, T) cv.kind === Inline || unsupported("an llvmcall argument of type ", T) - push!(ops, LLVM.value_type(cv.V) == t ? cv.V : reinterpret_value(fc, cv.V, t)) + push!(ops, llvmcall_value(fc, cv.V, t)) end r = LLVM.call!(fc.builder, LLVM.function_type(f), f, ops) lrt isa LLVM.VoidType && return ghost(Nothing, nothing) - rty = value_type(fc, RT) - return inline(RT, LLVM.value_type(r) == rty ? r : reinterpret_value(fc, r, rty)) + return inline(RT, llvmcall_value(fc, r, value_type(fc, RT))) +end + +# a value as the LLVM type `ty` of llvmcall: pointers and integers converted, other types +# reinterpreted +function llvmcall_value(fc::FnCtx, v::LLVM.Value, ty::LLVM.LLVMType) + from = LLVM.value_type(v) + from == ty && return v + from isa LLVM.PointerType && ty isa LLVM.IntegerType && return LLVM.ptrtoint!(fc.builder, v, ty) + from isa LLVM.IntegerType && ty isa LLVM.PointerType && return LLVM.inttoptr!(fc.builder, v, ty) + return reinterpret_value(fc, v, ty) end """ diff --git a/src/ir.jl b/src/ir.jl index 4f94ff1..14f63f2 100644 --- a/src/ir.jl +++ b/src/ir.jl @@ -32,7 +32,7 @@ jlcall entry wrapper named `name`. The entry function itself must be supported: function emit_entry!(cgm::CGModule, @nospecialize(tt::Type); name::AbstractString=unique_name(cgm, "jfptr")) mi = method_instance(tt, cgm.world) ir, rt = cgm.ir_source(mi, cgm.world) - info = declare_function!(cgm, mi, signature_argtypes(mi), rt) + info = declare_function!(cgm, mi, function_argtypes(mi), rt) push!(cgm.worklist, (info, ir)) process_worklist!(cgm; strict=mi) f = emit_jlcall_wrapper!(cgm, info, name) diff --git a/src/jit.jl b/src/jit.jl index 0a52e9f..b0519d1 100644 --- a/src/jit.jl +++ b/src/jit.jl @@ -35,24 +35,31 @@ The CodeInstances that `interp` infers for `mi` and, transitively, for what its function collect_codeinfos(interp::CC.AbstractInterpreter, mi::Core.MethodInstance) out = Pair{Core.CodeInstance,Core.CodeInfo}[] seen = IdSet{Core.MethodInstance}() - work = [mi] + # (a method instance, or the CodeInstance an `:invoke` refers to) + work = Any[mi] while !isempty(work) - m = popfirst!(work) + target = popfirst!(work) + m = target isa Core.CodeInstance ? CC.get_ci_mi(target) : target m in seen && continue push!(seen, m) - # (varargs methods are called through the runtime, for now) - m.def isa Method && m !== mi && m.def.isva && continue - ci = CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + ci = target isa Core.CodeInstance && target.inferred isa Core.CodeInfo ? target : + CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + # (inference may give the CodeInstance of another, normalized, method instance) + cm = CC.get_ci_mi(ci) + if cm !== m + cm in seen && continue + push!(seen, cm) + end src = ci.inferred if !(src isa Core.CodeInfo) # (inference keeps no source of functions with a constant result) - src = CC.typeinf_code(interp, m, true) - src isa Core.CodeInfo || unsupported("the code of ", m, ", which inference gives no source of") + src = CC.typeinf_code(interp, cm, true) + src isa Core.CodeInfo || unsupported("the code of ", cm, ", which inference gives no source of") end push!(out, ci => src) for stmt in src.code Meta.isexpr(stmt, :invoke) || continue - push!(work, invoke_target(stmt.args[1])) + push!(work, stmt.args[1]) end end return out diff --git a/src/memory.jl b/src/memory.jl index cf9fdb0..1899bf3 100644 --- a/src/memory.jl +++ b/src/memory.jl @@ -37,7 +37,6 @@ memory_elsize(@nospecialize R) = Int(unsafe_load(Ptr{Base.DataTypeLayout}( GenericMemory{R.parameters[1], R.parameters[2], R.parameters[3]}.layout)).size) -@noinline throw_boundserror(a, i) = throw(BoundsError(a, i)) memory_length(fc::FnCtx, mem::LLVM.Value) = tbaa!(fc, LLVM.load!(fc.builder, iptr_type(fc), derived(fc, mem); align=config(fc).target.pointer_size), @@ -67,13 +66,41 @@ function memory_owner(fc::FnCtx, mem::LLVM.Value) end # a bounds check of the 0-based index `i0` against the length `len`, unless the -# boundscheck argument `bc` is false -function bounds_check!(fc::FnCtx, i0::LLVM.Value, len::LLVM.Value, bc::CGVal, x::CGVal, idx::CGVal) +# boundscheck argument `bc` is false: out of bounds, the runtime throws the BoundsError of +# `x` and the index `idx` (`emit_bounds_check`), of `x` boxed (`jl_bounds_error_int`), or +# with `unboxed`, of an inline `x` without references by its data +# (`jl_bounds_error_unboxed_int`) +function bounds_check!(fc::FnCtx, i0::LLVM.Value, len::LLVM.Value, bc::CGVal, x::CGVal, idx::CGVal; + unboxed::Bool=false) (isconstant(bc) && constant_value(bc) === false) && return b = fc.builder inb = LLVM.icmp!(b, LLVM.API.LLVMIntULT, i0, len) isconstant(bc) || (inb = LLVM.or!(b, inb, LLVM.not!(b, LLVM.trunc!(b, bc.V, LLVM.Int1Type())))) - emit_guard!(fc, inb, throw_boundserror, x, idx) + fail = LLVM.BasicBlock(current_function(fc), "oob") + pass = LLVM.BasicBlock(current_function(fc), "idxend") + LLVM.br!(b, inb, pass, fail) + LLVM.position!(b, LLVM.at_end(fail)) + # (a value with references boxed, so that they are rooted while the runtime allocates) + if unboxed && x.kind !== Boxed && !has_references(x.typ) + data = if x.kind === Ghost + LLVM.null(T_derived()) + elseif x.mem !== nothing + derived(fc, x.mem) + else + # (on the error path) + slot = LLVM.alloca!(b, LLVM.value_type(x.V)) + LLVM.store!(b, x.V, slot) + derived(fc, slot) + end + f = runtime_function(fc, :jl_bounds_error_unboxed_int) + LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[data, literal_pointer_raw(fc, x.typ), idx.V]) + else + f = runtime_function(fc, :jl_bounds_error_int) + LLVM.call!(b, LLVM.function_type(f), f, LLVM.Value[callee_rooted(fc, emit_box(fc, x)), idx.V]) + end + LLVM.unreachable!(b) + LLVM.position!(b, LLVM.at_end(pass)) + return end function emit_memoryrefnew(fc::FnCtx, args::Vector{CGVal}, @nospecialize(rt)) diff --git a/src/runtime.jl b/src/runtime.jl index 5a20571..4252023 100644 --- a/src/runtime.jl +++ b/src/runtime.jl @@ -3,12 +3,13 @@ # an image, binds them. """ - JuliaCodegen.declare_runtime(mod, dialect, name) -> LLVM.Function + JuliaCodegen.declare_runtime(mod, dialect, name; T_size) -> LLVM.Function The declaration of the runtime function `name` (e.g. `:jl_apply_generic`) in `mod`, as the -dialect's code generator declares it. +dialect's code generator declares it, with `T_size` the target's `size_t`. """ -function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbol) +function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbol; + T_size::LLVM.IntegerType=LLVM.Int64Type()) sym = runtime_symbol(name) haskey(mod.functions, sym) && return mod.functions[sym] T_rooted = LLVM.PointerType(AddrSpace.CalleeRooted) @@ -49,6 +50,17 @@ function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbo push!(f.function_attributes, LLVM.EnumAttribute("willreturn")) elseif name === :jl_current_exception f = LLVM.Function(mod, sym, LLVM.FunctionType(T_tracked(), [T_ptr()])) + elseif name === :jl_get_binding_value_seqcst + # `jl_value_t *(jl_binding_t *b)`, null when undefined + f = LLVM.Function(mod, sym, LLVM.FunctionType(T_tracked(), [T_ptr()])) + elseif name === :jl_type_error + # `void (const char *fname, jl_value_t *expected, jl_value_t *got)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_ptr(), T_tracked(), T_rooted])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_error + # `void (const char *str)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_ptr()])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) elseif name === :jl_undefined_var_error # `void (jl_sym_t *var, jl_value_t *scope)` f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted, T_rooted])) @@ -56,6 +68,14 @@ function declare_runtime(mod::LLVM.Module, dialect::JuliaIR.Dialect, name::Symbo elseif name === :jl_throw f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted])) push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_bounds_error_int + # `void (jl_value_t *v, size_t i)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_rooted, T_size])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) + elseif name === :jl_bounds_error_unboxed_int + # `void (void *data, jl_value_t *vt, size_t i)` + f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.VoidType(), [T_derived(), T_ptr(), T_size])) + push!(f.function_attributes, LLVM.EnumAttribute("noreturn")) elseif name === :jl_subtype f = LLVM.Function(mod, sym, LLVM.FunctionType(LLVM.Int32Type(), [T_tracked(), T_tracked()])) elseif name === :jl_egal__unboxed @@ -89,9 +109,10 @@ end # the exported name of a runtime function: `ijl_` for the `jl_` functions libjulia # exports under both names (not the internal ones, like `jl_egal__unboxed`) -const INTERNAL_RUNTIME = (:jl_egal__unboxed, :jl_alloc_genericmemory) +const INTERNAL_RUNTIME = (:jl_egal__unboxed, :jl_alloc_genericmemory, :jl_get_binding_value_seqcst) runtime_symbol(name::Symbol) = startswith(String(name), "jl_") && !(name in INTERNAL_RUNTIME) ? "i" * String(name) : String(name) "The address of the runtime function `name` as an LLVM value." -runtime_function(fc::FnCtx, name::Symbol) = declare_runtime(fc.cgm.mod, dialect(fc), name) +runtime_function(fc::FnCtx, name::Symbol) = + declare_runtime(fc.cgm.mod, dialect(fc), name; T_size=iptr_type(fc)) diff --git a/src/specsig.jl b/src/specsig.jl index 9e4c72f..c47a291 100644 --- a/src/specsig.jl +++ b/src/specsig.jl @@ -9,9 +9,12 @@ # and other inline values by a `ptr addrspace(11)` reference. Inline results larger than # a pointer (but floating point and vector values) are returned through `sret`. # +# Union results are returned as `{box or null, type index}`, with the data of a member +# returned unboxed in a buffer argument (and from Julia 1.14 on, its references in a +# separate roots argument). +# # Not handled yet: inline values with references to objects, which native code passes and -# returns with their roots in separate arguments, and union results, which it returns as -# a union struct with the payload in a separate argument. +# returns with their roots in separate arguments. "How an argument is passed in the specsig convention." @enum SpecArg SpecValue SpecBoxed SpecByRef @@ -21,15 +24,18 @@ A function signature in Julia's native specialized calling convention: how each argument is passed (`nothing` for ghosts, which aren't), how the result is returned (`:void`, -`:value`, `:boxed` or `:sret`), whether the pgcstack is passed (`gcstack`, then in the -Swift calling convention), the LLVM function type and the return and parameter -attributes. +`:value`, `:boxed`, `:sret`, or for unions, `:union`, the box or the type index and the +data in a buffer, or `:ghosts`, the type index of a union of singletons), the number of +references of a union member returned in the roots argument (`return_roots`, 0 without +one), whether the pgcstack is passed (`gcstack`, then in the Swift calling convention), +the LLVM function type and the return and parameter attributes. """ struct SpecSig argtypes::Vector{Any} rettype::Any args::Vector{Union{Nothing,SpecArg}} ret::Symbol + return_roots::Int gcstack::Bool ft::LLVM.FunctionType retattrs::Vector{LLVM.Attribute} @@ -44,6 +50,35 @@ ref_attributes(@nospecialize T) = LLVM.Attribute[nocapture(), attr("noundef"), attr("nonnull"), attr("align", Base.datatype_alignment(T)), attr("dereferenceable", sizeof(T))] +# Whether union results return members with references unboxed, their references in a +# roots argument (from Julia 1.14 on, JuliaLang/julia#55045, with the attribute that tells +# GC lowering about them) +union_returns_roots(cgm::CGModule) = cgm.config.dialect.gc_return_roots === :attribute + +# The members of the union `U` that native code's union results return unboxed, in the +# order of their type indices (from 1; `for_each_uniontype_small`): the inline ones, or +# before Julia 1.14, those without references +union_return_members(cgm::CGModule, @nospecialize U) = + union_returns_roots(cgm) ? union_members(U) : + Any[M for M in Base.uniontypes(U) if union_member_ok(M; bits=true)] + +# the size and alignment of the buffer of a union result of type `U`, the number of roots +# of its members, and whether all its members are returned unboxed (native +# `union_alloca_type`, and `get_specsig_function`'s buffer for members that are only +# references) +function union_return_layout(cgm::CGModule, @nospecialize U) + ms = union_return_members(cgm, U) + data = filter(M -> !is_singleton_type(M) && !allpointers(M), ms) + nbytes = maximum(sizeof, data; init=0) + align = min(maximum(Base.datatype_alignment, data; init=0), 16) + nroots = maximum((npointers(M) for M in ms if !is_singleton_type(M)); init=0) + if nbytes == 0 && nroots > 0 + nbytes = nroots * cgm.config.target.pointer_size + align = cgm.config.target.pointer_size + end + return nbytes, align, nroots, length(ms) == length(Base.uniontypes(U)) && length(ms) < 128 +end + # as native `deserves_sret` deserves_sret(cgm::CGModule, @nospecialize(T), ty::LLVM.LLVMType) = sizeof(T) > cgm.config.target.pointer_size && @@ -69,6 +104,7 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype paramattrs = Vector{LLVM.Attribute}[] retattrs = LLVM.Attribute[] rk = repr_kind(rettype) + return_roots = 0 # (a ghost that isn't a singleton object, a `Type{T}` with a unique representation, is # returned boxed) if rk === Bottom || (rk === Ghost && is_singleton_type(rettype)) @@ -77,7 +113,31 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype ret, rty = :boxed, T_tracked() push!(retattrs, attr("nonnull")) elseif rk === UnionVal - unsupported("the specsig convention for a result of the union ", rettype) + nbytes, align, nroots, allunbox = union_return_layout(cgm, rettype) + if nbytes > 0 + # `{box or null, type index}`, the data of an unboxed member in the buffer + # `union_bytes_return` + ret, rty = :union, LLVM.StructType([T_tracked(), LLVM.Int8Type()]) + push!(params, T_ptr()) + push!(paramattrs, LLVM.Attribute[attr("noalias"), nocapture(), attr("noundef"), + attr("nonnull"), attr("align", align), + attr("dereferenceable", nbytes)]) + if nroots > 0 + # the references of an unboxed member, in the order of their offsets + return_roots = nroots + ps = cgm.config.target.pointer_size + push!(params, T_ptr()) + push!(paramattrs, LLVM.Attribute[attr("noalias"), nocapture(), attr("noundef"), + LLVM.StringAttribute("julia.return_roots", string(nroots)), + attr("nonnull"), attr("align", ps), + attr("dereferenceable", nroots * ps)]) + end + elseif allunbox + ret, rty = :ghosts, LLVM.Int8Type() + else + ret, rty = :boxed, T_tracked() + push!(retattrs, attr("nonnull")) + end else has_references(rettype) && unsupported("the specsig convention for a result of ", rettype, ", which has references") @@ -123,7 +183,7 @@ function specsig_abi(cgm::CGModule, argtypes::Vector{Any}, @nospecialize(rettype push!(paramattrs, ext === nothing ? LLVM.Attribute[] : LLVM.Attribute[attr(ext)]) end end - return SpecSig(argtypes, rettype, args, ret, gcstack_arg, LLVM.FunctionType(rty, params), + return SpecSig(argtypes, rettype, args, ret, return_roots, gcstack_arg, LLVM.FunctionType(rty, params), retattrs, paramattrs) end @@ -140,13 +200,19 @@ end The entry of the function `info` in the specsig convention (see [`specsig_abi`](@ref JuliaCodegen.specsig_abi)), named `name`, which natively compiled -code can call directly. Throws `Unsupported` for signatures it doesn't handle, and for -varargs methods, which native code calls in the jlcall convention. +code can call directly. A varargs method takes its arguments one by one, as native code +passes them. Throws `Unsupported` for signatures it doesn't handle, and for signatures +ending in `Vararg`, which native code calls in the jlcall convention. """ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractString) m = info.mi.def - m isa Method && m.isva && unsupported("the specsig convention for the varargs method ", m) - sig = specsig_abi(cgm, info.argtypes, info.rettype) + isva = m isa Method && m.isva + # (a varargs method takes its arguments one by one, as native code passes them, in a + # signature without `Vararg`; others are called in the jlcall convention) + argtypes = isva ? signature_argtypes(info.mi) : info.argtypes + isva && any(T -> T isa Core.TypeofVararg, argtypes) && + unsupported("the specsig convention for the varargs signature of ", info.mi) + sig = specsig_abi(cgm, argtypes, info.rettype) f = LLVM.Function(cgm.mod, String(name), sig.ft) sig.gcstack && LLVM.callconv!(f, LLVM.API.LLVMSwiftCallConv) init_function!(f, cgm.config.target) @@ -157,26 +223,28 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri fc = FnCtx(cgm, info, nothing, b, top) debug_function!(fc, f) ps = LLVM.parameters(f) - p = sig.ret === :sret ? 2 : 1 + p = 1 + (sig.ret in (:sret, :union)) + (sig.return_roots > 0) if sig.gcstack fc.pgcstack = ps[p] p += 1 end - ops = LLVM.Value[] - for (T, k) in zip(info.argtypes, sig.args) - k === nothing && continue + args = CGVal[] + for (T, k) in zip(argtypes, sig.args) + if k === nothing + push!(args, ghost(T, something(ghost_value(T)))) + continue + end v = ps[p] p += 1 cv = if k === SpecByRef - ld = LLVM.load!(b, layout(fc, T).llvm, v) - LLVM.alignment!(ld, Base.datatype_alignment(T)) - inline(T, tbaa!(fc, ld, :const)) + byref_argument(fc, T, v) else CGVal(T, k === SpecBoxed ? Boxed : Inline, v, nothing, nothing) end - push!(ops, convert_repr(fc, cv, T).V) + push!(args, cv) end - r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, ops) + isva && (args = pack_varargs(fc, info.mi, args)) + r = LLVM.call!(b, LLVM.function_type(info.llvmf), info.llvmf, call_operands(fc, info, args)) # (the entry is the function, as native code's: inlined by any pipeline) push!(LLVM.function_attributes(r), LLVM.EnumAttribute("alwaysinline")) if sig.ret === :sret @@ -188,6 +256,16 @@ function emit_specsig_wrapper!(cgm::CGModule, info::FuncInfo, name::AbstractStri repr_kind(info.rettype) === Bottom ? LLVM.unreachable!(b) : LLVM.ret!(b) elseif repr_kind(info.rettype) === Ghost LLVM.ret!(b, emit_box(fc, ghost(info.rettype, something(ghost_value(info.rettype))))) + elseif repr_kind(info.rettype) === UnionVal + # (which may box the result) + if sig.gcstack + fc.current_task = current_task!(b, config(fc).runtime, fc.pgcstack) + else + emit_prologue!(fc; safepoint=false) + end + LLVM.ret!(b, union_return(fc, sig, unboxed_union(info.rettype, r), + sig.ret === :union ? ps[1] : nothing, + sig.return_roots > 0 ? ps[2] : nothing)) else LLVM.ret!(b, r) end @@ -206,10 +284,18 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V b = fc.builder ops = LLVM.Value[] rt = sig.rettype - slot = nothing + slot = roots = nothing if sig.ret === :sret slot = entry_alloca!(fc, layout(fc, rt).llvm; align=Base.datatype_alignment(rt)) push!(ops, slot) + elseif sig.ret === :union + nbytes, align, _ = union_return_layout(fc.cgm, rt) + slot = entry_alloca!(fc, LLVM.ArrayType(LLVM.Int8Type(), nbytes); align) + push!(ops, slot) + if sig.return_roots > 0 + roots = roots_alloca!(fc, sig.return_roots) + push!(ops, roots) + end end sig.gcstack && push!(ops, fc.pgcstack) for (a, T, k) in zip(args, sig.argtypes, sig.args) @@ -219,9 +305,7 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V elseif k === SpecValue push!(ops, convert_repr(fc, a, T).V) else - arg = entry_alloca!(fc, layout(fc, T).llvm; align=Base.datatype_alignment(T)) - tbaa!(fc, LLVM.store!(b, convert_repr(fc, a, T).V, arg), :stack) - push!(ops, LLVM.addrspacecast!(b, arg, T_derived())) + push!(ops, byref_operand(fc, convert_repr(fc, a, T), T)) end end r = LLVM.call!(b, sig.ft, callee, ops) @@ -231,6 +315,101 @@ function emit_specsig_call!(fc::FnCtx, sig::SpecSig, callee::LLVM.Value, args::V k === Bottom && return emit_unreachable!(fc) k === Ghost && return ghost(rt, something(ghost_value(rt))) sig.ret === :boxed && return boxed(rt, r) + sig.ret in (:union, :ghosts) && return union_result(fc, sig, r, slot, roots) sig.ret === :sret && return inline(rt, tbaa!(fc, LLVM.load!(b, layout(fc, rt).llvm, slot), :stack)) return inline(rt, r) end + +# a stack slot for `n` references returned by a call, null-initialized (a GC frame slot +# for GC lowering, native `emit_static_roots`) +function roots_alloca!(fc::FnCtx, n::Int) + b = fc.builder + ps = config(fc).target.pointer_size + LLVM.position!(b, top_insertion_point(fc)) do + a = LLVM.array_alloca!(b, T_tracked(), LLVM.ConstantInt(LLVM.Int32Type(), n)) + LLVM.alignment!(a, ps) + tbaa!(fc, LLVM.memset!(b, a, i8(0), LLVM.ConstantInt(iptr_type(fc), n * ps), ps), :gcframe) + a + end +end + +# the union value `v` returned in the convention of `sig`, with the buffer `buf` of the +# data of `:union` and the roots argument `roots`: its box if it has one, else for a +# member returned unboxed, its type index (and data and references), else its box; a box +# with `UNION_BOX_MARKER` and the type index of its member, if returned unboxed (0 if not) +function union_return(fc::FnCtx, sig::SpecSig, v::CGVal, buf, roots) + b = fc.builder + U = v.typ + sig.ret === :boxed && return emit_box(fc, v) + ms = union_return_members(fc.cgm, U) + # (the type indices of `v` and of the result agree when every member is returned + # unboxed) + sig.ret === :ghosts && return union_tindex_value(fc, v) + rty = LLVM.return_type(sig.ft) + pack(data, t) = LLVM.insert_value!(b, LLVM.insert_value!(b, LLVM.UndefValue(rty), data, 0), t, 1) + unboxed() = union_switch(fc, v, rty; boxed=() -> pack(union_box_value(fc, v), i8(UNION_BOX_MARKER))) do M + k = findfirst(m -> m === M, ms) + k === nothing && return pack(emit_box(fc, union_member(fc, v, M)), i8(UNION_BOX_MARKER)) + if is_singleton_type(M) + elseif npointers(M) > 0 + # (a split value: its bytes but the references, then the references) + rs = LLVM.Value[] + split_store!(fc, union_member(fc, v, M).V, M, allpointers(M) ? nothing : buf, rs) + ps = config(fc).target.pointer_size + for (i, r) in enumerate(rs) + st = LLVM.store!(b, r, LLVM.gep!(b, LLVM.Int8Type(), roots, [iptr(fc, (i - 1) * ps)])) + LLVM.alignment!(st, ps) + tbaa!(fc, st, :gcframe) + end + else + st = LLVM.store!(b, union_member(fc, v, M).V, buf) + LLVM.alignment!(st, Base.datatype_alignment(M)) + end + pack(LLVM.null(T_tracked()), i8(k)) + end + union_has_box(U) || return unboxed() + return emit_if(fc, union_isboxed(fc, v), rty; name="union_return", otherwise=unboxed) do + t = union_tindex_value(fc, v) + k = i8(0) + for (i, M) in enumerate(union_members(U)) + j = findfirst(m -> m === M, ms) + j === nothing && continue + k = LLVM.select!(b, LLVM.icmp!(b, LLVM.API.LLVMIntEQ, t, i8(i)), i8(j), k) + end + pack(union_box_value(fc, v), LLVM.or!(b, k, i8(UNION_BOX_MARKER))) + end +end + +# the union value of the result `r` of a call in the convention of `sig`, with the buffer +# `buf` of the data of `:union` and the roots `roots` (the inverse of `union_return`) +function union_result(fc::FnCtx, sig::SpecSig, r::LLVM.Value, buf, roots) + b = fc.builder + U = sig.rettype + ms = union_return_members(fc.cgm, U) + unboxed(t) = tindex_switch(fc, t, ms, union_type(U); name="union_result") do _, M + v = if is_singleton_type(M) + ghost(M, something(ghost_value(M))) + elseif npointers(M) > 0 + ps = config(fc).target.pointer_size + rs = LLVM.Value[] + for i in 1:npointers(M) + ld = LLVM.load!(b, T_tracked(), LLVM.gep!(b, LLVM.Int8Type(), roots, [iptr(fc, (i - 1) * ps)])) + LLVM.alignment!(ld, ps) + push!(rs, tbaa!(fc, ld, :gcframe)) + end + inline(M, split_load(fc, M, allpointers(M) ? nothing : buf, rs)) + else + ld = LLVM.load!(b, value_type(fc, M), buf) + LLVM.alignment!(ld, Base.datatype_alignment(M)) + inline(M, ld) + end + to_union(fc, v, U).V + end + sig.ret === :ghosts && return unboxed_union(U, unboxed(r)) + data = LLVM.extract_value!(b, r, 0) + t = LLVM.extract_value!(b, r, 1) + isboxed = LLVM.icmp!(b, LLVM.API.LLVMIntNE, LLVM.and!(b, t, i8(UNION_BOX_MARKER)), i8(0)) + v = emit_if(() -> unbox_union(fc, data, U).V, fc, isboxed, union_type(U); + name="union_result", otherwise=() -> unboxed(t)) + return unboxed_union(U, v) +end diff --git a/src/unions.jl b/src/unions.jl index 5ee5cf6..274739c 100644 --- a/src/unions.jl +++ b/src/unions.jl @@ -302,7 +302,21 @@ function to_union(fc::FnCtx, v::CGVal, @nospecialize U) v = convert_repr(fc, v, M) end payload, roots = member_parts(fc, U, v) - return make_union(fc, U, payload, i8(union_tindex(U, M)), roots) + t = i8(union_tindex(U, M)) + if union_has_box(U) && v.kind === Inline && M !== Bool + # the box of the value, if it has one: of a constant (native code keeps isbits + # constants in unions boxed, JuliaLang/julia#55045), or the box it came from + if isconstant(v) + return make_union(fc, U, payload, i8(union_tindex(U, M) | UNION_BOX_MARKER), roots; + box=literal_pointer(fc, constant_value(v))) + elseif v.vboxed !== nothing + # (which may be null: then it has none) + t = LLVM.select!(fc.builder, nonnull(fc, v.vboxed), + i8(union_tindex(U, M) | UNION_BOX_MARKER), t) + return make_union(fc, U, payload, t, roots; box=v.vboxed) + end + end + return make_union(fc, U, payload, t, roots) end """ diff --git a/src/values.jl b/src/values.jl index b9e3e7e..d5e45e5 100644 --- a/src/values.jl +++ b/src/values.jl @@ -8,7 +8,9 @@ A value in generated code: its Julia type `typ` (widened), its representation `k (see [`Repr`](@ref JuliaCodegen.Repr)), the LLVM value `V` (`nothing` for ghosts and `Bottom`), the value itself when it is known at compile time (`constant`), and for inline values that may also exist as a box (null at run time if not), that box (`vboxed`, -native `Vboxed`), which boxing the value again reuses. +native `Vboxed`), which boxing the value again reuses, and for inline values loaded from +memory that never changes (a reference argument, a box), a pointer to it (`mem`), which +calls pass by reference and dynamic indices index. Use the constructors [`ghost`](@ref JuliaCodegen.ghost), [`inline`](@ref JuliaCodegen.inline), [`boxed`](@ref JuliaCodegen.boxed), [`unboxed_union`](@ref @@ -20,8 +22,12 @@ struct CGVal V::Union{Nothing,LLVM.Value} constant::Union{Nothing,Some{Any}} vboxed::Union{Nothing,LLVM.Value} + mem::Union{Nothing,LLVM.Value} end +CGVal(@nospecialize(typ), kind::Repr, V, constant, vboxed) = + CGVal(typ, kind, V, constant, vboxed, nothing) + "The ghost value `v` of type `T`." ghost(@nospecialize(T), @nospecialize(v)) = CGVal(T, Ghost, nothing, Some{Any}(v), nothing) @@ -29,14 +35,14 @@ ghost(@nospecialize(T), @nospecialize(v)) = CGVal(T, Ghost, nothing, Some{Any}(v bottom() = CGVal(Union{}, Bottom, nothing, nothing, nothing) """ - inline(T, V; constant, vboxed) + inline(T, V; constant, vboxed, mem) An inline value of type `T`, the LLVM value `V` of its layout. """ function inline(@nospecialize(T), V::LLVM.Value; constant::Union{Nothing,Some}=nothing, - vboxed::Union{Nothing,LLVM.Value}=nothing) + vboxed::Union{Nothing,LLVM.Value}=nothing, mem::Union{Nothing,LLVM.Value}=nothing) return CGVal(T, Inline, V, constant === nothing ? nothing : Some{Any}(something(constant)), - vboxed) + vboxed, mem) end """ diff --git a/test/builtins.jl b/test/builtins.jl index 4ba6a01..0d19477 100644 --- a/test/builtins.jl +++ b/test/builtins.jl @@ -40,6 +40,18 @@ b_getglobal() = Core.getglobal(Base, :pi) b_namedtuple(nt) = (nt.a, nt.b) b_const_field(c::BConst) = (c.c, c.v) b_tuple_index(t) = (t[1], t[2]) +b_dynamic_index(t, i) = t[i] +b_dynamic_inbounds(t, i) = @inbounds t[i] +b_dynamic_const(i) = @inbounds (1.0f0, 2.0f0, 3.0f0, 4.0f0)[i] +b_dynamic_field(m, i) = getfield(m, i) +b_div(x, y) = div(x, y) +b_svec(x, y) = Core.svec(x, y, 1) +b_svec_len(s) = length(s) +b_memoryref(m, i) = Core.memoryrefnew(Core.memoryrefnew(m), i, true) +function b_undefvar(c) + c && (x = 1) + return x +end const B_EGAL_PAIRS = Any[ (1, 1), (1, 2), (1, 1.0), (NaN, NaN), (0.0, -0.0), (1.0f0, 1.0f0), (true, true), (true, false), @@ -50,6 +62,28 @@ const B_EGAL_PAIRS = Any[ (missing, missing), (BNested(BPoint(0, 1), BRef(2, "x")), BNested(BPoint(0, 1), BRef(2, "x"))), ] +b_objects(x) = Any[x > 0, nothing, ()] +b_throw(x) = throw(ArgumentError(x)) +b_throw_singleton() = throw(DivideError()) + +mutable struct B_Atomic + @atomic n::Int + @atomic f::Float64 + @atomic s::Int8 + @atomic r::Any +end +b_new() = B_Atomic(1, 1.5, Int8(3), "x") +b_inc(c) = ((@atomic c.n += 2), (@atomic c.n)) +b_max(c) = ((@atomic c.f max 4.0), (@atomic c.f)) +b_small(c) = ((@atomic c.s *= Int8(2)), (@atomic c.s)) +b_ref(c) = ((@atomic c.r = (@atomic c.r) * "y"), (@atomic c.r)) +b_refmod(c) = ((@atomic c.r *= "z"), (@atomic c.r)) +b_bad(c) = (@atomic c.n += 0.5) # (the result isn't an Int: TypeError) +mutable struct B_Plain; n::Int; end +b_plain(c) = Core.modifyfield!(c, :n, +, 1) # (not atomic: an error from the runtime) +b_orders(c) = (getfield(c, :n, :monotonic), getfield(c, :f, :acquire), getfield(c, :r, :sequentially_consistent), + getfield(c, :s, :not_atomic)) # (the last: ConcurrencyViolationError) + @testset "builtins" begin @testset "===" begin @@ -88,6 +122,23 @@ end @cgtest b_namedtuple((a=1, b="b")) @cgtest b_const_field(BConst(1, 2)) @cgtest b_tuple_index((1, "a", 2.0)) + # fields whose index is only known at run time + for t in Any[(1, 2), (1.0f0, 2.0f0, 3.0f0, 4.0f0, 5.0f0), ("a", "b", "c", "d"), ("a", :b, 3), + (BPoint(1, 2), BPoint(3, 4), BPoint(5, 6), BPoint(7, 8)), + ntuple(i -> VecElement(Float32(i)), 4), (nothing, nothing), (7,)], + i in (1, 2, 0, length(t) + 1) # (out of bounds: BoundsError) + @cgtest b_dynamic_index(t, i) + 1 <= i <= length(t) && @cgtest b_dynamic_inbounds(t, i) + end + @cgtest b_dynamic_const(3) + @cgtest b_dynamic_field(BPoint(1, 2), 2) + @cgtest b_dynamic_field(BMutable(1, "a", BRef(2, "b")), 2) + @cgtest b_dynamic_field(BPartial(3), 2) # UndefRefError + @cgtest b_dynamic_field(BPartial(3), 3) # BoundsError + @cgtest b_memoryref(Memory{Int}(1:3), 4) # BoundsError + @cgtest b_div(1, 0) # DivideError + @cgtest b_undefvar(true) + @cgtest b_undefvar(false) # UndefVarError # the write barrier: young objects stored into an old one survive collections old = BMutable(0, nothing, BRef(0, "")) GC.gc(); GC.gc() @@ -112,6 +163,9 @@ end @cgtest b_sizeof("abcd") @cgtest b_sizeof(1.0) @cgtest b_getglobal() + @cgtest b_svec("a", 2.0) + @cgtest b_svec_len(Core.svec(1, "b", :c)) + @cgtest b_svec_len(Core.svec()) end @testset "code" begin @@ -119,12 +173,31 @@ end for (f, types) in ((b_fields, (BPoint,)), (b_new_point, (Float64, Float64)), (b_new_mutable, (Int, Any, BRef)), (b_mutable_set!, (BMutable, Int, Any, BRef)), (b_egal, (BPoint, BPoint)), (b_egal, (Symbol, Symbol)), - (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,))) + (b_isa_int, (Int,)), (b_tuple, (Int, String)), (b_sizeof, (String,)), + (b_svec, (String, Float64)), (b_svec_len, (Core.SimpleVector,))) @test @filecheck begin @check_not "julia.call" print(test_ir(f, types)) end end + # (unless --check-bounds=yes checks bounds in `@inbounds` too, throwing through a call) + if Base.JLOptions().check_bounds != 1 + for types in ((NTuple{2,Int}, Int), (NTuple{4,Float32}, Int), (NTuple{4,String}, Int)) + @test @filecheck begin + @check_not "julia.call" + print(test_ir(b_dynamic_inbounds, types)) + end + end + end + # an inline argument indexed at run time is read where it is, from the memory it is + # passed in + @test @filecheck begin + @check_label "define internal float @julia_b_dynamic_inbounds" + @check "ptr addrspace(11)" + @check_not "alloca" + @check "getelementptr inbounds float, ptr addrspace(11)" + print(test_ir(b_dynamic_inbounds, (NTuple{8,Float32}, Int))) + end # a write barrier for each reference stored into an object ir = test_ir(b_mutable_set!, (BMutable, Int, Any, BRef)) if JuliaCodegen.CodegenConfig().dialect.barrier_flavour === :write_barrier @@ -138,6 +211,27 @@ end print(ir) end end + # a constant tuple indexed at run time is loaded from a constant global, as native + # code's (which GPU back ends place in constant memory) + @test @filecheck begin + @check "@_j_const{{.*}} = private unnamed_addr constant [4 x float]" + @check "load float, ptr" + print(test_ir(b_dynamic_const, (Int,))) + end + # error paths throw through the runtime, as native code's (which GPU back ends lower), + # rather than construct their exceptions + for (f, types, callee) in ((b_dynamic_index, (NTuple{4,Float32}, Int), "@ijl_bounds_error_unboxed_int("), + (b_dynamic_index, (Tuple{String,Symbol}, Int), "@ijl_bounds_error_int("), + (b_memoryref, (Memory{Int}, Int), "@ijl_bounds_error_int("), + (b_partial_get, (BPartial,), "@ijl_throw("), + (b_div, (Int, Int), "@ijl_throw("), + (b_undefvar, (Bool,), "@ijl_undefined_var_error(")) + @test @filecheck begin + @check_not "julia.call" + @check "call void $callee" + print(test_ir(f, types)) + end + end # the box of an object is compared by the runtime only if it isn't identical @test @filecheck begin @check "icmp ne ptr addrspace(10)" @@ -146,4 +240,47 @@ end end end +@testset "the runtime's objects" begin + # `true`, `false`, `nothing`, `()` and `Core.svec()` through the runtime's globals, as + # native code refers to them + ir = test_ir(b_objects, (Int,)) + for name in ("jl_true", "jl_false", "jl_nothing", "jl_emptytuple") + @test occursin("@$name = external constant ptr", ir) + end + @cgtest b_objects(1) + @cgtest b_objects(-1) +end + +@testset "throw" begin + @cgtest b_throw("message") + @cgtest b_throw_singleton() + # through the runtime's `jl_throw`, as native code (which GPU compilers lower) + for (f, types) in ((b_throw, (String,)), (b_throw_singleton, ())) + @test @filecheck begin + @check_label "define internal void @julia_" + @check "call void @ijl_throw(ptr addrspace(12)" + @check_not "@ijl_apply_generic" + test_ir(f, types) + end + end +end + +@testset "atomic field modifications" begin + @cgtest b_inc(b_new()) + @cgtest b_max(b_new()) + @cgtest b_small(b_new()) + @cgtest b_ref(b_new()) + @cgtest b_refmod(b_new()) + @cgtest b_bad(b_new()) + @cgtest b_plain(B_Plain(1)) + @cgtest b_orders(b_new()) + # a loop of compare-and-exchange calling the operation, as native code + @test @filecheck begin + @check "load atomic i64" + @check "cmpxchg ptr addrspace(11) %{{[0-9]+}}, i64 %{{[0-9]+}}, i64 %{{[0-9]+}} seq_cst monotonic" + @check_not "@ijl_apply_generic" + test_ir(b_inc, (B_Atomic,)) + end +end + end diff --git a/test/calls.jl b/test/calls.jl index 30ec60c..9c5e9bb 100644 --- a/test/calls.jl +++ b/test/calls.jl @@ -15,6 +15,10 @@ c_less_specific(x::Int) = invoke(c_generic, Tuple{Number}, x) c_call_throws(x) = x > 0 ? x : c_throws(x) @noinline c_vararg(xs...) = length(xs) c_call_vararg(x) = c_vararg(x, x, x) +@noinline c_vararg2(x, xs...) = x + sum(xs) +c_call_vararg2(x) = c_vararg2(x, x, 2x) + c_vararg2(x, 1) +@noinline c_vararg_any(xs...) = map(string, xs) +c_call_vararg_any(x) = c_vararg_any(x, "s", 1.5) c_closure(x) = (y -> x + y)(3) # (a calling convention JuliaCodegen doesn't support, which native code only compiles for # x86: LLVM aborts on other targets) @@ -54,12 +58,28 @@ c_run_fallback(f, args...) = cgrun(f, args...; config=C_FALLBACK) @cgtest c_sum_found(collect(1:30)) end +@testset "varargs" begin + # the varargs in the tuple the function takes, as its IR has them + @cgtest c_call_vararg(1) + @cgtest c_call_vararg2(3) + @cgtest c_call_vararg_any(7) + @test !any(((mi, why),) -> mi.def.name in (:c_vararg, :c_vararg2), test_fallbacks(c_call_vararg2, (Int,))) + # a specialized varargs method: called directly, with the varargs in a tuple; one whose + # signature has a `Vararg` (as inference keeps two or more varargs here): through the + # runtime, with the arguments one by one + ir = test_ir(c_call_vararg2, (Int,)) + @test occursin(r"call i64 @julia_c_vararg2_\d+\(i64 %\d+, ptr addrspace\(11\)", ir) + @test occursin("@ijl_invoke", ir) + # a varargs entry + @cgtest c_vararg2(1, 2, 3) + @cgtest c_vararg(1, "two") +end + @testset "stubs" begin # always throws: an error path, called through the runtime @cgtest c_call_throws(1) @cgtest c_call_throws(-1) @test any(((mi, why),) -> mi.def.name === :c_throws, test_fallbacks(c_call_throws, (Int,))) - # varargs methods, for now @cgtest c_call_vararg(1) # a callee with an unsupported construct calls its native code, or throws when the # configuration says so @@ -77,7 +97,7 @@ end @check "define internal i64 @julia_c_fib_[[N:[0-9]+]](" @check "call i64 @julia_c_fib_[[N]](" @check_not "julia.call" - @check "define ptr addrspace(10) @jctest_entry" + @check "define nonnull ptr addrspace(10) @jctest_entry" print(test_ir(c_fib, (Int,))) end # a union-returning callee is called directly, with the union by value @@ -85,6 +105,12 @@ end @check "call { [8 x i8], i8, ptr addrspace(10) } @julia_c_maybe_" print(test_ir(c_use_maybe, (Int,))) end + # a function of a method declared `@noinline` isn't inlined, as native code's + @test @filecheck begin + @check "define internal i64 @julia_c_add_{{[0-9]+}}(i64 %0, i64 %1) [[ATTRS:#[0-9]+]]" + @check "attributes [[ATTRS]] = { noinline" + print(test_ir(c_calls, (Int,))) + end end end diff --git a/test/ccall.jl b/test/ccall.jl index d421c6d..cb9adde 100644 --- a/test/ccall.jl +++ b/test/ccall.jl @@ -59,6 +59,8 @@ cc_fma(a, b, c) = ccall("llvm.fma.v4f32", llvmcall, CC_V4, (CC_V4, CC_V4, CC_V4) cc_donothing(x) = (ccall("llvm.donothing", llvmcall, Cvoid, ()); x) cc_unknown() = (ccall("llvm.jctest.nonexistent", llvmcall, Cvoid, ()); nothing) cc_not_intrinsic(x) = ccall("jctest_function", llvmcall, Int, (Int,), x) +cc_extern(s) = GC.@preserve s Int(ccall("extern strlen", llvmcall, Csize_t, (Ptr{UInt8},), pointer(s))) +cc_powi(x, n) = ccall("llvm.powi", llvmcall, Float64, (Float64, Int32), x, n) @testset "ccall" begin @@ -127,12 +129,17 @@ end @check "call double @llvm.sqrt.f64(double" test_ir(cc_sqrt, (Float64,)) end - # an intrinsic LLVM doesn't know is declared, and left to back ends and validation - @test @filecheck begin - @check "declare void @llvm.jctest.nonexistent()" - test_module_ir(cc_unknown, (); triple=JuliaCodegen.host_target().triple) - end - @test_throws JuliaCodegen.Unsupported test_ir(cc_not_intrinsic, (Int,)) + # an intrinsic LLVM doesn't know, or not an intrinsic: an error at run time, as native + # code ("llvmcall only supports intrinsic calls") + @cgtest cc_unknown() + @cgtest cc_not_intrinsic(1) + @test occursin("call void @ijl_error(", test_ir(cc_unknown, ())) + # an external function, by name + @cgtest cc_extern("four") + @test occursin("declare i64 @strlen(ptr)", test_ir(cc_extern, (String,))) + # the base name of an overloaded intrinsic: the overload of the signature + @cgtest cc_powi(1.5, Int32(3)) + @test occursin("call double @llvm.powi.f64.i32(double", test_ir(cc_powi, (Float64, Int32))) end end diff --git a/test/cfunction.jl b/test/cfunction.jl index 345d79c..c9dcdb9 100644 --- a/test/cfunction.jl +++ b/test/cfunction.jl @@ -83,11 +83,12 @@ end @check "ret double" ir end - # the jlcall convention for results it doesn't call in the specsig convention + # a union result in the specsig convention, as native code's: the type index, and the + # box or the data in a buffer @test @filecheck begin @check_label "define internal ptr addrspace(10) @jlcapi_cf_maybe" @check "@jl_get_abi_converter" - @check "call ptr addrspace(10) (ptr, ptr addrspace(10), ...) @julia.call(ptr %" + @check "call swiftcc { ptr addrspace(10), i8 } %" test_ir(cf_call_maybe, (Int,)) end end diff --git a/test/debuginfo.jl b/test/debuginfo.jl index 98efc7b..57877a8 100644 --- a/test/debuginfo.jl +++ b/test/debuginfo.jl @@ -34,6 +34,9 @@ end # the lines of the functions inlined into a statement: inlined frames @test occursin(r"!DILocation\(line: \d+, scope: ![0-9]+, inlinedAt: ![0-9]+\)", ir) @test occursin("!DISubprogram(name: \"sin\"", ir) || occursin("!DISubprogram(name: \"+\"", ir) + # the innermost location's column is the statement, as native code from Julia 1.14 on + @test occursin(r"!DILocation\(line: \d+, column: [1-9]\d*, scope: ", ir) == + (D_CONFIG.dialect.minor >= v"1.14") # every function has a subprogram, entries included @test count("distinct !DISubprogram(name: \"d_outer\"", ir) == 2 # without, none @@ -51,6 +54,14 @@ end debug_info=kind) @test occursin("emissionKind: $name", d_ir(d_inner, (Int,); config)) end + # without debug information, but with the locations + config = JuliaCodegen.CodegenConfig(; on_unsupported=:error, on_internal_error=:error, + debug_info=:no_debug) + @test @filecheck begin + @check "!dbg" + @check "emissionKind: NoDebug" + d_ir(d_inner, (Int,); config) + end @test_throws "invalid debug_info" JuliaCodegen.CodegenConfig(; debug_info=:lines) end diff --git a/test/emit_into.jl b/test/emit_into.jl index fd4655c..20327ba 100644 --- a/test/emit_into.jl +++ b/test/emit_into.jl @@ -38,17 +38,18 @@ function ei_codeinfos(mi; world=Base.get_world_counter(), exclude=()) interp = EIInterp(world) out = Pair{Core.CodeInstance,Core.CodeInfo}[] seen = IdSet{Core.MethodInstance}() - work = [mi] + work = Any[mi] # (method instances, and the CodeInstances `:invoke`s refer to) while !isempty(work) - m = pop!(work) + t = pop!(work) + m = t isa Core.CodeInstance ? CC.get_ci_mi(t) : t (m in seen || m.def.name in exclude) && continue push!(seen, m) - ci = CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) + ci = t isa Core.CodeInstance && t.inferred isa Core.CodeInfo ? t : + CC.typeinf_ext_toplevel(interp, m, CC.SOURCE_MODE_ABI) push!(out, ci => ci.inferred::Core.CodeInfo) for st in ci.inferred.code Meta.isexpr(st, :invoke) || continue - t = st.args[1] - push!(work, t isa Core.CodeInstance ? CC.get_ci_mi(t) : t) + push!(work, st.args[1]) end end return out diff --git a/test/exceptions.jl b/test/exceptions.jl index d9eac14..35b4b5d 100644 --- a/test/exceptions.jl +++ b/test/exceptions.jl @@ -89,8 +89,14 @@ end @check "call void @ijl_undefined_var_error" test_ir(e_assign, (Int,)) end - # a typed global is assigned through the runtime, which converts the value - @test occursin("@ijl_apply_generic", test_ir(e_typed_assign, (Int,))) + # a typed global with a value of its type through the binding too; one that needs + # converting through the runtime + @test !occursin("@ijl_apply_generic", test_ir(e_typed_assign, (Int,))) + @cgtest e_typed_assign(Int8(3)) + @cgtest e_typed_assign(2.0) + @cgtest e_typed_assign(2.5) # (InexactError) + # undefined names, from the runtime + @test occursin("@jl_get_binding_value_seqcst(", test_ir(e_read_undefined, ())) end @testset "code" begin diff --git a/test/intrinsics.jl b/test/intrinsics.jl index 0437fc3..468912f 100644 --- a/test/intrinsics.jl +++ b/test/intrinsics.jl @@ -21,7 +21,25 @@ i_fence() = (Core.Intrinsics.atomic_fence(:sequentially_consistent); nothing) i_fence2() = (Core.Intrinsics.atomic_fence(:sequentially_consistent, :system); nothing) # an intrinsic with the wrong number of arguments, which inference knows throws i_bad_intrinsic(x) = Core.Intrinsics.add_int(x) +i_store_any(v::Vector{Int}, x) = GC.@preserve v (unsafe_store!(pointer(v), x); v[1]) +i_fast(x, y) = (Base.FastMath.mul_fast(x, y), Base.FastMath.div_fast(x, y), + Base.FastMath.min_fast(x, y), Base.FastMath.max_fast(x, y), Base.FastMath.sqrt_fast(x), + Base.FastMath.lt_fast(x, y), Base.FastMath.neg_fast(x)) i_llvmcall(x::Int32) = Base.llvmcall("%r = add i32 %0, 1\nret i32 %r", Int32, Tuple{Int32}, x) +# (pointers are integers of their size in the IR, as native code passes them) +i_llvmcall_load(p::Ptr{Int32}) = Base.llvmcall(""" + %p = inttoptr i64 %0 to i32* + %v = load i32, i32* %p, align 4 + ret i32 %v""", Int32, Tuple{Ptr{Int32}}, p) +i_llvmcall_ptr(p::Ptr{Int32}) = Base.llvmcall("%q = add i64 %0, 4\nret i64 %q", Ptr{Int32}, Tuple{Ptr{Int32}}, p) +# (a struct of fields of one type, which Base.llvmcall passes as an LLVM array) +struct IPair; a::Int64; b::Int64; end +i_llvmcall_struct(p::IPair) = Base.llvmcall(""" + %a = extractvalue [2 x i64] %0, 0 + %b = extractvalue [2 x i64] %0, 1 + %s = add i64 %a, %b + ret i64 %s""", Int64, Tuple{IPair}, p) +i_llvmcall_ptrs(v::Vector{Int32}) = GC.@preserve v (i_llvmcall_load(pointer(v)), i_llvmcall_ptr(pointer(v)) - pointer(v)) i_poly(x) = 3x^2 - 2x + 1 i_loop(n) = (s = 0; for i in 1:n; s += i; end; s) i_dynamic(f, x) = f(x) @@ -95,6 +113,24 @@ end @cgtest i_fence2() @cgtest i_bad_intrinsic(1) @cgtest i_llvmcall(Int32(41)) + @cgtest i_fast(2.0f0, 8.0f0) + # a value of another type than the element: checked (TypeError), as native code + @cgtest i_store_any([1], Any[5][1]) + @cgtest i_store_any([1], Any[5.5][1]) # (InexactError, from `convert`) + @cgtest i_store_any([1], Any["x"][1]) # (MethodError, from `convert`) + @test occursin("@ijl_type_error(", test_ir(unsafe_store!, (Ptr{Int}, Any, Int))) + # the fast-math flags of native code + @test @filecheck begin + @check "fmul fast float" + @check "fdiv fast float" + @check "call fast float @llvm.minimum.f32" + @check "call fast float @llvm.maximum.f32" + @check "call fast float @llvm.sqrt.f32" + @check "fcmp fast olt float" + test_ir(i_fast, (Float32, Float32)) + end + @cgtest i_llvmcall_ptrs(Int32[7, 8]) + @cgtest i_llvmcall_struct(IPair(3, 4)) end @testset "code" begin diff --git a/test/jitdriver.jl b/test/jitdriver.jl index d55ccae..2e23f7b 100644 --- a/test/jitdriver.jl +++ b/test/jitdriver.jl @@ -52,7 +52,7 @@ end @test any(((mi, why),) -> mi.def.name === :jd_stdcall, jf.fallbacks) @test_throws JuliaCodegen.Unsupported jd_run(jd_call_stdcall, "four") end - # varargs callees are called through the runtime + # varargs callees @test jd_run(jd_call_vararg, 3) == 6 end diff --git a/test/memory.jl b/test/memory.jl index dd3d33a..a097000 100644 --- a/test/memory.jl +++ b/test/memory.jl @@ -97,8 +97,8 @@ end v = collect(1:100) cgrun(m_sum_found, v), cgrun(m_length, v) # (the least of a few measurements: a GC or another task may allocate meanwhile) - work = minimum(_ -> @allocated(cgrun(m_sum_found, v)), 1:3) - baseline = minimum(_ -> @allocated(cgrun(m_length, v)), 1:3) + work = minimum(_ -> @allocated(cgrun(m_sum_found, v)), 1:10) + baseline = minimum(_ -> @allocated(cgrun(m_length, v)), 1:10) @test work - baseline <= 64 # element accesses are tied to their memory @test @filecheck begin diff --git a/test/specsig.jl b/test/specsig.jl index e3d3c7c..fc090e6 100644 --- a/test/specsig.jl +++ b/test/specsig.jl @@ -22,6 +22,15 @@ ss_box(x::Int) = Ref(x) ss_throw(x) = throw(ArgumentError("ss_throw $x")) ss_vec(v::SS_V4) = map(x -> VecElement(x.value * 2f0), v) @noinline ss_vararg(xs...) = length(xs) +ss_vararg2(a, xs...) = a + sum(xs) +# unions: data and singletons unboxed, other members boxed (before Julia 1.14, also +# those with references) +ss_pick(c::Bool) = c ? 1 : "s" +ss_pick_refs(c::Bool) = c ? 1.5 : (1, "a") +ss_pick_mid(c::Bool) = c ? Int8(1) : (Int8(2), "a", Int16(3)) # (a reference between data) +ss_pick_ptrs(c::Bool) = c ? nothing : ("a", :b) # (only references) +ss_pick_boxed(c::Bool) = c ? nothing : "s" +ss_pick_const(c::Bool) = c ? 2.5 : nothing # (the constant keeps its box) # The first function definition's header in native code for `f(::types...)`, without # names: the convention, the result and the parameters with their attributes. @@ -119,6 +128,12 @@ const SS_CASES = [ (ss_mix, (Int8, Bool, UInt16, Float32, SS_Pair, Nothing, String)), (ss_fst, (Int, SS_Empty)), (ss_dup, (Int,)), (ss_widen, (Int64,)), (ss_maybe, (Union{Nothing,Int},)), (ss_box, (Int,)), (ss_throw, (Int,)), (ss_vec, (SS_V4,)), + # (varargs methods, with their arguments one by one) + (ss_vararg2, (Int, Float64, Int8)), + # (union results) + (ss_id, (Union{Nothing,Int},)), (ss_id, (Union{Nothing,Missing},)), (ss_pick, (Bool,)), + (ss_pick_boxed, (Bool,)), (ss_pick_const, (Bool,)), (ss_pick_refs, (Bool,)), + (ss_pick_mid, (Bool,)), (ss_pick_ptrs, (Bool,)), ] @testset "specsig" begin @@ -140,14 +155,29 @@ const SS_CASES = [ ir end end + # from Julia 1.14 on, the references of a union member are returned in a roots + # argument, which GC lowering knows by its attribute + if test_config().dialect.gc_return_roots === :attribute + @test @filecheck begin + @check "define swiftcc { ptr addrspace(10), i8 } @ss_entry(ptr {{.*}}dereferenceable(16) %0, ptr {{.*}}dereferenceable(16) \"julia.return_roots\"=\"2\" %1," + @check "store ptr addrspace(10) {{%.*}}, ptr {{%.*}}" + @check "store ptr addrspace(10) {{%.*}}, ptr {{%.*}}" + specsig_ir(ss_pick_ptrs, (Bool,)) + end + end end @testset "unsupported" begin - # inline values with references are passed with their roots, unions returned with - # their payload separately + # inline values with references are passed with their roots @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (SS_Ref,)) - @test_throws JuliaCodegen.Unsupported specsig_header(ss_id, (Union{Nothing,Int},)) - @test_throws JuliaCodegen.Unsupported specsig_header(ss_vararg, (Int, Int)) + # (a signature that ends in `Vararg`: the jlcall convention) + @dispose ctx=LLVM.Context() mod=LLVM.Module("x") begin + cgm = JuliaCodegen.CGModule(mod, test_config()) + m = only(methods(ss_vararg)) + mi = Base.Compiler.specialize_method(m, Tuple{typeof(ss_vararg), Vararg{Int}}, Core.svec()) + info = JuliaCodegen.get_function!(cgm, mi) + @test_throws JuliaCodegen.Unsupported JuliaCodegen.emit_specsig_wrapper!(cgm, info, "x") + end end @testset "calls through the convention" begin @@ -170,7 +200,17 @@ end @cgtest run=run ss_box(10) @cgtest run=run ss_throw(11) @cgtest run=run ss_vec(map(VecElement, (1f0, 2f0, 3f0, 4f0))) + for c in (true, false) + @cgtest run=run ss_pick(c) + @cgtest run=run ss_pick_refs(c) + @cgtest run=run ss_pick_mid(c) + @cgtest run=run ss_pick_ptrs(c) + @cgtest run=run ss_pick_boxed(c) + @cgtest run=run ss_pick_const(c) + end end + @cgtest run=run_through_specsig ss_id(Union{Nothing,Int}[3][1]) + @cgtest run=run_through_specsig ss_id(Union{Nothing,Missing}[missing][1]) # (native code for these returns a constant, without code in the convention) @cgtest run=run_through_specsig ss_id(SS_Empty()) @cgtest run=run_through_specsig ss_id(nothing) diff --git a/test/unions.jl b/test/unions.jl index 35bc920..8ea3abf 100644 --- a/test/unions.jl +++ b/test/unions.jl @@ -37,6 +37,9 @@ function u_sum_found(v::Vector{Int}) return s end +@noinline u_produce(c::Bool, a::Int32) = c ? a : 2.5 +u_box_const(c::Bool) = Any[u_produce(c, Int32(7))][1] + @testset "unions" begin @testset "members" begin @@ -98,7 +101,7 @@ end @test @filecheck begin @check_label "define internal" @check_not "julia.gc_alloc_obj" - @check_label "define ptr addrspace(10) @jctest_entry" + @check_label "define nonnull ptr addrspace(10) @jctest_entry" print(test_ir(u_maybe, (Bool, Int))) end @test @filecheck begin @@ -107,4 +110,18 @@ end end end +@testset "constants keep their box" begin + # an isbits constant in a union keeps the object of the constant as its box + # (JuliaLang/julia#55045), as native code: boxing it allocates nothing + @cgtest u_box_const(true) + @cgtest u_box_const(false) + p() = ccall(:jl_value_ptr, Ptr{Cvoid}, (Any,), cgrun(u_box_const, false)) + @test p() == p() + @test @filecheck begin + @check_label "define internal { [8 x i8], i8, ptr addrspace(10) } @julia_u_produce" + @check "insertvalue { [8 x i8], i8, ptr addrspace(10) } %{{[0-9]+}}, i8 -12{{[0-9]}}, 1" + test_ir(u_produce, (Bool, Int32)) + end +end + end diff --git a/test/walker.jl b/test/walker.jl index 043c1c5..5521dcc 100644 --- a/test/walker.jl +++ b/test/walker.jl @@ -56,7 +56,7 @@ end # objects are referenced through globals, not by address ir = test_ir(w_constant_string, ()) @test @filecheck begin - @check "@jl_global_{{[0-9]+}} = external global ptr" + @check "@\"jl_global#{{[0-9]+}}\" = external global ptr" @check_not "inttoptr (i64 {{[0-9]+}} to ptr)" print(ir) end