llir / llvm

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

How to generate ir for embedded struct? #232

Open wiltchamberian opened 11 months ago

wiltchamberian commented 11 months ago

I didn't find about anything to process embedded struct, such as type A struct{ value int } type B struct{ a A }

what should I fill in " b := types.NewStruct(/what to fill here?/) "

dannypsnl commented 11 months ago

From my understanding, embedded struct is a field that got an implicit name, so you insert reference to A and give a generated name.

wiltchamberian commented 11 months ago

yes, I understand, but how to write the code there, it is a type of types.Var, so what if I have a types.Struct?

dannypsnl commented 11 months ago

I believe you can use the "variable" in Go as instance of "type"

wiltchamberian commented 11 months ago

in fact, not that easy. the variable in Go has type types.Struct but the input needs to be a types.Var, types.Var includes types.object and types.object include golang "Type", but not a types.Struct, so I have no idea about how to input the parameters. Or if you can write down the code.

dannypsnl commented 11 months ago
    m := ir.NewModule()

    foo := m.NewTypeDef("foo", types.NewStruct(types.I32))
    _ = m.NewTypeDef("bar", types.NewStruct(foo))

    main := m.NewFunc("main", types.I32)

    {
        entry := main.NewBlock("")
        entry.NewRet(constant.NewInt(types.I32, 0))
    }

    fmt.Println(m)

output

%foo = type { i32 }
%bar = type { %foo }

define i32 @main() {
0:
    ret i32 0
}
dannypsnl commented 11 months ago

You can also use types.NewPointer(foo) to get:

%foo = type { i32 }
%bar = type { %foo* }

define i32 @main() {
0:
    ret i32 0
}