| 1 |
structure SparcCSizes = |
| 2 |
struct |
| 3 |
|
| 4 |
structure Ty = CType |
| 5 |
|
| 6 |
fun roundup (i, a) = a * ((i + a - 1) div a) |
| 7 |
|
| 8 |
(* calculate size and alignment for a C type *) |
| 9 |
fun sizeOfTy (Ty.C_void | Ty.C_float | Ty.C_PTR | |
| 10 |
Ty.C_signed (Ty.I_int | Ty.I_long) | |
| 11 |
Ty.C_unsigned (Ty.I_int | Ty.I_long)) = {sz=4, align=4} |
| 12 |
| sizeOfTy (Ty.C_double | |
| 13 |
Ty.C_signed Ty.I_long_long | |
| 14 |
Ty.C_unsigned Ty.I_long_long) = {sz=8, align=8} |
| 15 |
| sizeOfTy (Ty.C_long_double) = {sz=16, align=8} |
| 16 |
| sizeOfTy (Ty.C_signed Ty.I_char | Ty.C_unsigned Ty.I_char) = {sz=1, align=1} |
| 17 |
| sizeOfTy (Ty.C_signed Ty.I_short | Ty.C_unsigned Ty.I_short) = {sz=2, align=2} |
| 18 |
| sizeOfTy (Ty.C_ARRAY (t, n)) = let val {sz=s, align=a} = sizeOfTy t in {sz=n * s, align=a} end |
| 19 |
| sizeOfTy (Ty.C_STRUCT l) = |
| 20 |
let (* i: next free memory address (relative to struct start); |
| 21 |
* a: current total alignment, |
| 22 |
* l: list of struct member types *) |
| 23 |
fun pack (i, a, []) = |
| 24 |
(* when we are done with all elements, the total size |
| 25 |
* of the struct must be padded out to its own alignment *) |
| 26 |
{sz=roundup (i, a), align=a} |
| 27 |
| pack (i, a, t :: tl) = let |
| 28 |
val {sz=ts, align=ta} = sizeOfTy t (* size and alignment for member *) |
| 29 |
in |
| 30 |
(* member must be aligned according to its own |
| 31 |
* alignment requirement; the next free position |
| 32 |
* is then at "aligned member-address plus member-size"; |
| 33 |
* new total alignment is max of current alignment |
| 34 |
* and member alignment (assuming all alignments are |
| 35 |
* powers of 2) *) |
| 36 |
pack (roundup (i, ta) + ts, Int.max (a, ta), tl) |
| 37 |
end |
| 38 |
in |
| 39 |
pack (0, 1, l) |
| 40 |
end |
| 41 |
| sizeOfTy (Ty.C_UNION l) = |
| 42 |
let (* m: current max size |
| 43 |
* a: current total alignment *) |
| 44 |
fun overlay (m, a, []) = {sz=roundup (m, a), align=a} |
| 45 |
| overlay (m, a, t :: tl) = |
| 46 |
let val {sz=ts, align=ta} = sizeOfTy t |
| 47 |
in |
| 48 |
overlay (Int.max (m, ts), Int.max (a, ta), tl) |
| 49 |
end |
| 50 |
in |
| 51 |
overlay (0, 1, l) |
| 52 |
end |
| 53 |
|
| 54 |
end |