This may be a silly question but I am struggling to figure out how to store nontrivial values(basically anything not an integer) on the stack? I feel like I understand it conceptually but I am really lost on how to actually achieve this? For example how could I store a simple array of integers on the stack?
You'd have to make an explicit stack slot that is the size of your compound structure and then store/load to it piece-wise for each scalar that ultimately make up that compound structure
https://docs.rs/cranelift-codegen/latest/cranelift_codegen/ir/stackslot/struct.StackSlotData.html
Is there anywhere I could see an example of something like this? Specifically storing it in multiple pieces
I'm sure cg_clif
has an example somewhere
cc @bjorn3
If you have a struct you did calculate a layout for this struct which contains the size of the struct and the offsets of all fields. Then you create a stack slot big enough to fit the struct and when you want to access a field you offset a pointer to the stack slot by the offset of the field.
For an array the size would be the size of the element type times the amount of elements. And calculating the offset would be multiplying the size of the element by the index of the element you want to access.
Thanks for the information. It seems that I must determine the offset at compile time for the stack functions in InstBuilder, how would I deal with this if I want my array to be indexable by a runtime value?
You use the stack_addr
instruction, then iadd
and imul
for computing the pointer to the element you want to access and finally use plain load
and store
for accessing the target.
stack_load
/stack_store
get desugared to stack_addr
+load
/store
anyway.
Thanks! This has been very helpful
Till Schneidereit has marked this topic as resolved.
Last updated: Dec 23 2024 at 12:05 UTC