Master the fundamental concepts of code generation through this focused micro-challenge.
You have read the whole brief, and the concepts above stay free on every task. Writing and running the code needs a plan.
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
Every task includes starter code, theory, and hidden tests so you can implement and verify locally in the browser.
How it worksThe stack frame holds return address, saved frame pointer, callee-saved registers, spill slots, and local variables. Clang computes frame layout in TargetFrameLowering; debug info references stack offsets for each variable.
Growing downward from high addresses: incoming arguments, return address, saved rbp, callee-saved regs, spill slots, local arrays, scalar locals. Each slot gets a negative offset from rbp or rsp.
cLoading…
Production compilers embed this step inside a longer pipeline. GCC flows through cpp, cc1, assembly, and ld; Clang uses the driver, Sema, LLVM IR passes, and a target backend. LLVM bitcode, JVM bytecode, and WASM are other familiar IRs at the same layer. The exercise isolates one pass so you can test it alone before chaining it to the next stage.
You will design and implement stack frame layout for functions. This exercise requires assigning stack offsets to locals and spill slots and generating addressing modes that reference them.
Lay out a function's local variables in its stack frame: give each one an rbp-relative offset that respects its alignment, then compare the natural declaration-order layout with a sorted layout that minimises padding: the reordering compilers perform for locals.
One function per line:
cLoading…
| Type | Size | Alignment |
|---|---|---|
char | 1 | 1 |
short | 2 | 2 |
int | 4 | 4 |
long, double, ptr | 8 | 8 |
TYPE var[N] is an array: size N × element size, alignment of the element.
Variables are placed downward from rbp. Keep end = bytes used so far (starting at 0). For each variable in strategy order: end = round_up(end + size, align); the variable lives at [rbp-end]. The frame is round_up(end, 16) bytes.
Padding before a variable is the gap between the previous end + its size and its own end; total padding also includes the round-up to 16.
For each function:
cLoading…
where data is the sum of all sizes, padding = frame - data. Print a blank line between functions.
Input:
cLoading…
Output:
cLoading…
round_up(x, a) helper and one allocation routine used by both strategies.Hidden tests cover arrays of every element type, functions whose two layouts are identical, a single local, and many small locals mixed with pointers.