llir / llvm

Library for interacting with LLVM IR in pure Go.
https://llir.github.io/document/
BSD Zero Clause License
1.19k stars 78 forks source link

howto: converting from *ir.Param to *constant.Struct #149

Closed nektro closed 4 years ago

nektro commented 4 years ago
pr := // *ir.Param
t := types.NewStruct(types.I8Ptr, types.I32)
s := constant.NewStruct(t, pr)

however, this produces an error: cannot use pr (type *ir.Param) as type constant.Constant in argument to constant.NewStruct: *ir.Param does not implement constant.Constant (missing IsConstant method)

is this a bug, or is there another intended way to cast a Param to a custom type?

nektro commented 4 years ago

additionally, pr.Type() == t == true

dannypsnl commented 4 years ago

Hi, ir.Param is not a constant, this is expected. The reason is the value of a parameter cannot be detected before runtime. What you need is alloca an instance for the structure type, ref: https://llir.github.io/document/user-guide/types/#structure

nektro commented 4 years ago

I don't need to instantiate the type and I'm okay with it being a value.Value but what I'm trying to do is access the fields of the struct.

nektro commented 4 years ago

using block.NewGetElementPtr worked, thanks for the docs pointer!

nektro commented 4 years ago

hmmm, I can't seem to get past this though

llvm-as-10: out.ll:11:30: error: explicit pointee type doesn't match operand's pointee type
        %3 = getelementptr inbounds [15 x i8], { [15 x i8], i32 }* %1, i32 0
                                    ^
dannypsnl commented 4 years ago

Because the operand's type mismatched, it should be getelementptr inbounds { [15 x i8], i32 }, { [15 x i8], i32 }*.

nektro commented 4 years ago

func NewGetElementPtr(elemType types.Type, src value.Value, indices ...value.Value) *InstGetElementPtr

ahhh, didn't realized that elemType is the type of src. thought for a while it was the output type.

dannypsnl commented 4 years ago

@mewmew any suggestion about this signature? elemType seems quite wrong.

nektro commented 4 years ago

https://github.com/llir/llvm/blob/v0.3.2/ir/block_memory.go#L74-L80

mewmew commented 4 years ago

@mewmew any suggestion about this signature? elemType seems quite wrong.

The intention is to mirror that of the official LLVM IR semantics for the getelementptr instruction. So the first argument to NewGetElementPtr is the same as the first argument to the getelementptr instruction.

Perhaps the name elemType is confusion? Any thoughts about what name would be better suited?

dannypsnl commented 4 years ago

Well, getelementptr always take a pointer or vector, can seem as Ptr<T> or Vec<T>, say T is elemType make sense IMO.