Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend metadata APIs to all values. #414

Merged
merged 1 commit into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 0 additions & 54 deletions src/core/instructions.jl
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
export Instruction, unsafe_delete!,
metadata,
opcode,
predicate_int, predicate_real

Expand Down Expand Up @@ -57,59 +56,6 @@ Base.show(io::IO, ::MIME"text/plain", inst::Instruction) = print(io, lstrip(stri
Base.show(io::IO, inst::Instruction) = print(io, typeof(inst), "(", lstrip(string(inst)), ")")


## metadata iteration
# TODO: doesn't actually iterate, since we can't list the available keys

@enum(MD, MD_dbg = 0,
MD_tbaa = 1,
MD_prof = 2,
MD_fpmath = 3,
MD_range = 4,
MD_tbaa_struct = 5,
MD_invariant_load = 6,
MD_alias_scope = 7,
MD_noalias = 8,
MD_nontemporal = 9,
MD_mem_parallel_loop_access = 10,
MD_nonnull = 11,
MD_dereferenceable = 12,
MD_dereferenceable_or_null = 13,
MD_make_implicit = 14,
MD_unpredictable = 15,
MD_invariant_group = 16,
MD_align = 17,
MD_loop = 18,
MD_type = 19,
MD_section_prefix = 20,
MD_absolute_symbol = 21,
MD_associated = 22)

export InstructionMetadataDict

struct InstructionMetadataDict <: AbstractDict{MD,MetadataAsValue}
inst::Instruction
end

metadata(inst::Instruction) = InstructionMetadataDict(inst)

Base.isempty(md::InstructionMetadataDict) = !Bool(API.LLVMHasMetadata(md.inst))

Base.haskey(md::InstructionMetadataDict, kind::MD) =
API.LLVMGetMetadata(md.inst, kind) != C_NULL

function Base.getindex(md::InstructionMetadataDict, kind::MD)
objref = API.LLVMGetMetadata(md.inst, kind)
objref == C_NULL && throw(KeyError(kind))
return Metadata(MetadataAsValue(objref))
end

Base.setindex!(md::InstructionMetadataDict, node::Metadata, kind::MD) =
API.LLVMSetMetadata(md.inst, kind, Value(node))

Base.delete!(md::InstructionMetadataDict, kind::MD) =
API.LLVMSetMetadata(md.inst, kind, C_NULL)


## instruction types

const opcodes = [:Ret, :Br, :Switch, :IndirectBr, :Invoke, :Unreachable, :CallBr, :FNeg,
Expand Down
158 changes: 158 additions & 0 deletions src/core/metadata.jl
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
## core type

export Metadata

# subtypes are expected to have a 'ref::API.LLVMMetadataRef' field
Expand Down Expand Up @@ -139,3 +141,159 @@ struct MDNull <: Metadata end
Base.convert(::Type{Metadata}, ::Nothing) = MDNull()
Base.unsafe_convert(::Type{API.LLVMMetadataRef}, md::MDNull) =
convert(API.LLVMMetadataRef, C_NULL)


## value metadata

export metadata

@enum(MDKind, MD_dbg = 0,
MD_tbaa = 1,
MD_prof = 2,
MD_fpmath = 3,
MD_range = 4,
MD_tbaa_struct = 5,
MD_invariant_load = 6,
MD_alias_scope = 7,
MD_noalias = 8,
MD_nontemporal = 9,
MD_mem_parallel_loop_access = 10,
MD_nonnull = 11,
MD_dereferenceable = 12,
MD_dereferenceable_or_null = 13,
MD_make_implicit = 14,
MD_unpredictable = 15,
MD_invariant_group = 16,
MD_align = 17,
MD_loop = 18,
MD_type = 19,
MD_section_prefix = 20,
MD_absolute_symbol = 21,
MD_associated = 22)
MDKind(name::String) = API.LLVMGetMDKindIDInContext(context(), name, length(name))
MDKind(kind::MDKind) = kind

# TODO: doesn't actually iterate, since we can't list the available keys
struct ValueMetadataDict <: AbstractDict{MDKind,MetadataAsValue}
inst::Value
end

metadata(inst::Value) = ValueMetadataDict(inst)

Base.isempty(md::ValueMetadataDict) = !Bool(API.LLVMHasMetadata(md.inst))

Base.haskey(md::ValueMetadataDict, key) =
API.LLVMGetMetadata(md.inst, MDKind(key)) != C_NULL

function Base.getindex(md::ValueMetadataDict, key)
kind = MDKind(key)
objref = API.LLVMGetMetadata(md.inst, kind)
objref == C_NULL && throw(KeyError(kind))
return Metadata(MetadataAsValue(objref))
end

Base.setindex!(md::ValueMetadataDict, node::Metadata, key) =
API.LLVMSetMetadata(md.inst, MDKind(key), Value(node))

Base.delete!(md::ValueMetadataDict, key) =
API.LLVMSetMetadata(md.inst, MDKind(key), C_NULL)


## named metadata

export NamedMDNode, operands

# a named metadata note, tying together a name and a MDNode

struct NamedMDNode
mod::LLVM.Module # not exposed by the API
ref::API.LLVMNamedMDNodeRef
end

Base.unsafe_convert(::Type{API.LLVMNamedMDNodeRef}, node::NamedMDNode) = node.ref

function name(node::NamedMDNode)
len = Ref{Csize_t}()
data = API.LLVMGetNamedMetadataName(node, len)
unsafe_string(convert(Ptr{Int8}, data), len[])
end

function Base.show(io::IO, mime::MIME"text/plain", node::NamedMDNode)
print(io, "!$(name(node)) = !{")
for (i, op) in enumerate(operands(node))
i > 1 && print(io, ", ")
show(io, mime, op)
end
print(io, "}")
return io
end

function operands(node::NamedMDNode)
nops = API.LLVMGetNamedMetadataNumOperands2(node)
ops = Vector{API.LLVMMetadataRef}(undef, nops)
if nops > 0
API.LLVMGetNamedMetadataOperands2(node, ops)
end
return [Metadata(op) for op in ops]
end

Base.push!(node::NamedMDNode, val::MDNode) =
API.LLVMAddNamedMetadataOperand2(node, val)


## module named metadata

export metadata

struct ModuleMetadataIterator <: AbstractDict{String,NamedMDNode}
mod::Module
end

"""
metadata(mod)

Fetch the module-level named metadata. This can be inspected using a Dict-like interface.
Mutation is different: There is no `setindex!` method, as named metadata is append-only.
Instead, fetch the named metadata node using `getindex`, and `push!` to it.
"""
metadata(mod::Module) = ModuleMetadataIterator(mod)

function Base.show(io::IO, mime::MIME"text/plain", iter::ModuleMetadataIterator)
print(io, "ModuleMetadataIterator for module $(name(iter.mod))")
if !isempty(iter)
print(io, ":")
for (key,val) in iter
print(io, "\n ")
show(io, mime, val)
end
end
return io
end

function Base.iterate(iter::ModuleMetadataIterator, state=API.LLVMGetFirstNamedMetadata(iter.mod))
if state == C_NULL
nothing
else
node = NamedMDNode(iter.mod, state)
(name(node) => node, API.LLVMGetNextNamedMetadata(state))
end
end

Base.last(iter::ModuleMetadataIterator) =
NamedMDNode(iter.mod, API.LLVMGetLastNamedMetadata(iter.mod))

Base.isempty(iter::ModuleMetadataIterator) =
API.LLVMGetLastNamedMetadata(iter.mod) == C_NULL

Base.IteratorSize(::ModuleMetadataIterator) = Base.SizeUnknown()

function Base.haskey(iter::ModuleMetadataIterator, name::String)
return API.LLVMGetNamedMetadata(iter.mod, name, length(name)) != C_NULL
end

function Base.getindex(iter::ModuleMetadataIterator, name::String)
ref = API.LLVMGetOrInsertNamedMetadata(iter.mod, name, length(name))
@assert ref != C_NULL
node = NamedMDNode(iter.mod, ref)
return node
end
97 changes: 0 additions & 97 deletions src/core/module.jl
Original file line number Diff line number Diff line change
Expand Up @@ -87,103 +87,6 @@ set_compiler_used!(mod::Module, values::GlobalVariable...) =
API.LLVMAppendToCompilerUsed(mod, collect(values), length(values))


## named metadata iteration

export metadata, NamedMDNode, operands

# a named metadata note, tying together a name and a MDNode

struct NamedMDNode
mod::LLVM.Module # not exposed by the API
ref::API.LLVMNamedMDNodeRef
end

Base.unsafe_convert(::Type{API.LLVMNamedMDNodeRef}, node::NamedMDNode) = node.ref

function name(node::NamedMDNode)
len = Ref{Csize_t}()
data = API.LLVMGetNamedMetadataName(node, len)
unsafe_string(convert(Ptr{Int8}, data), len[])
end

function Base.show(io::IO, mime::MIME"text/plain", node::NamedMDNode)
print(io, "!$(name(node)) = !{")
for (i, op) in enumerate(operands(node))
i > 1 && print(io, ", ")
show(io, mime, op)
end
print(io, "}")
return io
end

function operands(node::NamedMDNode)
nops = API.LLVMGetNamedMetadataNumOperands2(node)
ops = Vector{API.LLVMMetadataRef}(undef, nops)
if nops > 0
API.LLVMGetNamedMetadataOperands2(node, ops)
end
return [Metadata(op) for op in ops]
end

Base.push!(node::NamedMDNode, val::MDNode) =
API.LLVMAddNamedMetadataOperand2(node, val)

# module metadata iteration

struct ModuleMetadataIterator <: AbstractDict{String,NamedMDNode}
mod::Module
end

"""
metadata(mod)

Fetch the module-level named metadata. This can be inspected using a Dict-like interface.
Mutation is different: There is no `setindex!` method, as named metadata is append-only.
Instead, fetch the named metadata node using `getindex`, and `push!` to it.
"""
metadata(mod::Module) = ModuleMetadataIterator(mod)

function Base.show(io::IO, mime::MIME"text/plain", iter::ModuleMetadataIterator)
print(io, "ModuleMetadataIterator for module $(name(iter.mod))")
if !isempty(iter)
print(io, ":")
for (key,val) in iter
print(io, "\n ")
show(io, mime, val)
end
end
return io
end

function Base.iterate(iter::ModuleMetadataIterator, state=API.LLVMGetFirstNamedMetadata(iter.mod))
if state == C_NULL
nothing
else
node = NamedMDNode(iter.mod, state)
(name(node) => node, API.LLVMGetNextNamedMetadata(state))
end
end

Base.last(iter::ModuleMetadataIterator) =
NamedMDNode(iter.mod, API.LLVMGetLastNamedMetadata(iter.mod))

Base.isempty(iter::ModuleMetadataIterator) =
API.LLVMGetLastNamedMetadata(iter.mod) == C_NULL

Base.IteratorSize(::ModuleMetadataIterator) = Base.SizeUnknown()

function Base.haskey(iter::ModuleMetadataIterator, name::String)
return API.LLVMGetNamedMetadata(iter.mod, name, length(name)) != C_NULL
end

function Base.getindex(iter::ModuleMetadataIterator, name::String)
ref = API.LLVMGetOrInsertNamedMetadata(iter.mod, name, length(name))
@assert ref != C_NULL
node = NamedMDNode(iter.mod, ref)
return node
end


## global variable iteration

export globals
Expand Down
28 changes: 17 additions & 11 deletions test/core_tests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -771,6 +771,12 @@ end
@test alignment(fn) == 0
alignment!(fn, 4)
@test alignment(fn) == 4

@test isempty(metadata(fn))
str = MDString("bar")
md = MDNode([str])
metadata(fn)["foo"] = md
@test !isempty(metadata(fn))
end

# global variables
Expand Down Expand Up @@ -968,8 +974,8 @@ mod = parse(LLVM.Module, raw"""
bb = first(collect(blocks(fun)))
inst = first(collect(instructions(bb)))

@test haskey(metadata(inst), LLVM.MD_dbg)
loc = metadata(inst)[LLVM.MD_dbg]
@test haskey(metadata(inst), "dbg")
loc = metadata(inst)["dbg"]

@test loc isa DILocation
@test LLVM.line(loc) == 94
Expand Down Expand Up @@ -1467,25 +1473,25 @@ end
# metadata
mdval = MDNode([MDString("whatever")])
let md = metadata(brinst)
@test keytype(md) == LLVM.MD
@test keytype(md) == LLVM.MDKind
@test valtype(md) == LLVM.MetadataAsValue

@test isempty(md)
@test !haskey(md, LLVM.MD_dbg)
@test !haskey(md, "dbg")

md[LLVM.MD_dbg] = mdval
@test md[LLVM.MD_dbg] == mdval
md["dbg"] = mdval
@test md["dbg"] == mdval

@test !isempty(md)
@test haskey(md, LLVM.MD_dbg)
@test haskey(md, "dbg")

@test !haskey(md, LLVM.MD_tbaa)
@test_throws KeyError md[LLVM.MD_tbaa]
@test !haskey(md, "tbaa")
@test_throws KeyError md["tbaa"]

delete!(md, LLVM.MD_dbg)
delete!(md, "dbg")

@test isempty(md)
@test !haskey(md, LLVM.MD_dbg)
@test !haskey(md, "dbg")
end

@test retinst in instructions(bb3)
Expand Down
Loading