Stream: cranelift

Topic: ✔ How to store non trivial values on the stack


view this post on Zulip Cregg (May 30 2024 at 18:15):

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?

view this post on Zulip fitzgen (he/him) (May 30 2024 at 18:38):

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

view this post on Zulip fitzgen (he/him) (May 30 2024 at 18:39):

https://docs.rs/cranelift-codegen/latest/cranelift_codegen/ir/stackslot/enum.StackSlotKind.html#variant.ExplicitSlot

https://docs.rs/cranelift-codegen/latest/cranelift_codegen/ir/stackslot/struct.StackSlotData.html

view this post on Zulip Cregg (May 30 2024 at 19:24):

Is there anywhere I could see an example of something like this? Specifically storing it in multiple pieces

view this post on Zulip fitzgen (he/him) (May 30 2024 at 19:31):

I'm sure cg_clif has an example somewhere

cc @bjorn3

view this post on Zulip bjorn3 (May 30 2024 at 19:43):

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.

view this post on Zulip bjorn3 (May 30 2024 at 19:44):

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.

view this post on Zulip Cregg (May 30 2024 at 19:48):

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?

view this post on Zulip bjorn3 (May 30 2024 at 20:02):

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.

view this post on Zulip bjorn3 (May 30 2024 at 20:03):

stack_load/stack_store get desugared to stack_addr+load/store anyway.

view this post on Zulip Cregg (May 30 2024 at 20:56):

Thanks! This has been very helpful

view this post on Zulip Notification Bot (Sep 08 2024 at 13:45):

Till Schneidereit has marked this topic as resolved.


Last updated: Nov 22 2024 at 16:03 UTC