0

I'm trying convert this raw LLVM code:

%UnwEx = type { i64, i8*, i64, i64 }
@UnwEx.size = constant i64 ptrtoint (%UnwEx* getelementptr (%UnwEx* null, i32 1) to i64)

To the llvmlite:

unw_ex = context.get_identified_type("UnwEx")
unw_ex.elements = [int_, i8_ptr, int_, int_]
i32 = ir.IntType(32)
gep = builder.gep(ir.PointerType(unw_ex), [i32(1)], name="gep")
... # some extra code to cast gep to integer

The idea is get the size of the structured type UnwEx in runtime. However the last line with get command raise this:

Traceback (most recent call last):
  File "C:/Users/DavidRagazzi/Desktop/mamba/mamba/core/runtime.py", line 495, in <module>
    generate(None, 64, 8)
  File "C:/Users/DavidRagazzi/Desktop/mamba/mamba/core/runtime.py", line 280, in generate
    gep = builder.gep(unw_ex_ptr, [i32(1)], name="gep")
  File "C:\Program Files\Python37\lib\site-packages\llvmlite\ir\builder.py", line 925, in gep
    inbounds=inbounds, name=name)
  File "C:\Program Files\Python37\lib\site-packages\llvmlite\ir\instructions.py", line 494, in __init__
    typ = ptr.type
AttributeError: 'PointerType' object has no attribute 'type'

What's wrong with this? Is there a better way to get the size of type?

David Ragazzi
  • 300
  • 2
  • 6

1 Answers1

1

The first argument to gep should be a value that is pointer to an instance UnwEx. What you're passing is a type, not a value. The way you get that pointer is by allocating memory using alloca or malloc (in which case you'd have to bitcast the returned pointer to UnwEx*).

Another way of getting UnwEx's size is by using its get_abi_size member. Something like

target = llvmlite.binding.Target.from_default_triple()
target_machine = target.create_target_machine()
unw_ex_size = unw_ex.get_abi_size(target_machine.target_data)

gives you the size of in bytes an instance of UnwEx would occupy on your host platform.

droptop
  • 1,372
  • 13
  • 24
  • Yep, get_abi_size was the trick to solve my problem a time ago. Anyway your answer is useful to people facing the same problem. Thanks! – David Ragazzi Dec 28 '21 at 22:05