News:

MASM32 SDK Description, downloads and other helpful links
MASM32.com New Forum Link
masmforum WebSite

generating array code

Started by victorvmpm, October 05, 2010, 05:13:43 PM

Previous topic - Next topic

victorvmpm

Hi, I'm studying in the university and I was wondering how a compiler creates the code for an array on a stack?

I was thinking of int a[5]

it would be:
mov eax, 5
mul 4
add esp, eax

but if it was from a function:

int a[z.getlength()];

without knowing z, what could would it generate?

How would it manage code for incoming local variables?


Any ideas?

P.S. Everything is local and can't go on the .data section


Thanks in Advance
Victor Pereira







redskull

Generally speaking, it can't.  In C, for example, array indices must be constant.  Language that allow it probably default to using the heap instead of the stack.

-r
Strange women, lying in ponds, distributing swords, is no basis for a system of government

clive

Well typically you move ESP to EBP on entry to fix the stack frame, and access parameters and local with respect to that. Compilers that do everything relative to the stack pointer keep track of where it is, but that only works well for fixed allocations.

Your first case would be written as SUB ESP,20 (the stack grows down, and the compiler can pre-compute constants removing unnecessary run-time math), or ADD ESP,-20

For the variable case


  PUSH EBP ; Epilogue
  MOV EBP,ESP
  ADD ESP,-32 ; locals
  PUSH ESI


  MOV EAX, [EBP + 8]; length parameter or call a routine returning array size in EAX
  SHL EAX,2 ; *4
  SUB ESP,EAX ; Allocate from stack
  MOV ESI,ESP ; Fix array at ESI


  POP ESI ; Prologue
  MOV ESP,EBP
  POP EBP
  RET
It could be a random act of randomness. Those happen a lot as well.

victorvmpm

Thanks for the posts!

I was thinking it last night, and I thought of a solution, however it would be too hard to implement.

I was thinking of having the array as 2 of 4 byte elements one of them the data and the other the reference to the next element. Unfortunately, that would mean that the table would be on runtime and managed on the heap. Even though is just an idea I haven't thought of how to implement it.