Simvik

Where do the arguments go?

Apply the Arm calling convention's rules to place each argument in a register or on the stack. A medium embedded C problem (Calling conventions and the…

medium · Calling conventions and the stack · aapcs · calling-convention · arm · alignment

Under the Arm procedure call standard (AAPCS, without floating-point registers), a function's arguments are placed one at a time, left to right. args describes them, one letter each: w a 32-bit value (int, pointer), b a char or short (widened to 32 bits, so placed like w), d a 64-bit value (long long, or a double without an FPU).

Start with the next core register NCRN = 0 and the next stack offset NSAA = 0.

  • A 32-bit argument: if NCRN < 4 it goes in register NCRN and NCRN goes up by 1. Otherwise it goes on the stack at NSAA, and NSAA goes up by 4.
  • A 64-bit argument needs an even register pair: round NCRN up to even first. If NCRN ≤ 2 it goes in NCRN and NCRN+1, and NCRN goes up by 2. Otherwise NCRN becomes 4 (no later argument uses a register), NSAA is rounded up to a multiple of 8, and the argument takes 8 bytes of stack there.

A register skipped for alignment is never filled later. Write aapcs_place(args, out) to fill one place_t per letter.

Starter code

void aapcs_place(const char *args, place_t *out) {
  int ncrn = 0, nsaa = 0;
  for (int i = 0; args[i]; i++) {
    int words = args[i] == 'd' ? 2 : 1;
    if (ncrn + words <= 4) {
      out[i].reg = ncrn;
      out[i].stack = 0;
      ncrn += words;
    } else {
      out[i].reg = -1;
      out[i].stack = nsaa;
      nsaa += 4 * words;
    }
  }
}

Example tests

Words, an aligned pair, and a fifth argument

show("www");
show("wd");
show("wwwww");

Expected output:

www: r0 r1 r2
wd: r0 r2:r3
wwwww: r0 r1 r2 r3 sp+0

Learn it first