On this page

call and ret aren’t “entering a function”—they’re a control transfer that pushes and pops a return address on the stack.

In lesson 09, we moved the stack pointer by hand. Functions do the same thing by protocol: call pushes the address of the next instruction onto the stack, the prologue builds a frame, and ret pops that address back off. In this lesson, I dissect a recursive call, the rbp frame, the registers a function is required to preserve, and tail recursion that never grows the stack.

Mental Model: A Frame Instead of Names

What it looks like in C99 What happens in hardware
The stack holds local variable names The frame holds numbers and addresses; names exist only in debug info
A recursive call always grows the stack A tail call can be replaced by a jump, leaving $rsp unchanged
call f is the same as jmp f call also pushes the return address, and ret pops it back
Returning from a function is compiler magic ret pops an address off the stack and jumps to it
rbp is just cosmetic The rbp chain defines frame boundaries for debuggers and unwinders

call, ret, and the Return Address

The sum_range.asm testbed computes 1 + 2 + ... + n recursively:

sum_range.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; sum_range.asm — recursive sum 1..n with a full rbp frame.
; The frame_probe label lets GDB inspect the saved frame pointer,
; return address, and argument — with no variable names in sight.

default rel

%define SYS_EXIT 60
%define SUM_ARG 5

section .text
    global _start

; ------------------------------------------------------------------------------
; int64_t asm_sum_range(int64_t n)
; Input:     rdi = n
; Output:    rax = 1 + 2 + ... + n, or 0 if n <= 0
; Clobbers:  rdi, rax, flags (caller-saved)
; Preserves: rbp (callee-saved; push rbp in prologue, leave in epilogue)
; ------------------------------------------------------------------------------
asm_sum_range:
    push rbp
    mov rbp, rsp
    sub rsp, 16
    mov qword [rbp - 8], rdi

frame_probe:
    test rdi, rdi
    jle .zero

    dec rdi
    call asm_sum_range
    add rax, qword [rbp - 8]
    jmp .done

.zero:
    xor eax, eax

.done:
    leave

    ret

_start:
    mov rdi, SUM_ARG
    call asm_sum_range
    mov edi, eax

    ; syscall: exit(asm_sum_range(SUM_ARG))
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

The call from _start takes five bytes: opcode e8 and a 32-bit relative displacement to the target.

  401023:	bf 05 00 00 00       	mov    edi,0x5
  401028:	e8 d3 ff ff ff       	call   401000 <asm_sum_range>
  40102d:	89 c7                	mov    edi,eax
  • bf 05 00 00 00 — mov edi, 5: the SUM_ARG argument.
  • e8 d3 ff ff ff — call with rel32; displacement d3 ff ff ff decodes as -45 (-0x2d).
  • 89 c7 — the next instruction, mov edi, eax; its address is the return address.

The displacement is measured from the end of call, not its start:

0x40102d−0x2d=0x401000 \mathtt{0x40102d} - \mathtt{0x2d} = \mathtt{0x401000}

The five-byte call instruction pushes the return address onto the stack. Recursion uses the exact same mechanism: every call pushes its own return address.

The Stack Frame

A function’s Prologue subtracts space for locals from $rsp, while rbp anchors the base of the frame. That stack frame is built with four instructions:

  • push rbp saves the caller’s frame pointer;
  • mov rbp, rsp sets the new frame pointer;
  • sub rsp, 16 reserves local slots;
  • leave in the epilogue restores rsp and rbp to the caller’s values.

In GDB at frame_probe, two adjacent invocations are visible side by side:

Breakpoint 1, frame_probe () at sum_range.asm:29
29	    test rdi, rdi
rbp=0x7fffffffd800 rsp=0x7fffffffd7f0
0x7fffffffd7f8:	0x0000000000000005	0x0000000000000000
0x7fffffffd808:	0x000000000040102d

Breakpoint 1, frame_probe () at sum_range.asm:29
29	    test rdi, rdi
rbp=0x7fffffffd7e0 rsp=0x7fffffffd7d0
0x7fffffffd7d8:	0x0000000000000004	0x00007fffffffd800
0x7fffffffd7e8:	0x0000000000401019
  • At rbp - 8 sits the argument: 5 at depth 1 and 4 at depth 2.
  • At rbp sits the caller’s saved rbp: 0 at depth 1, because _start never built a frame.
  • At rbp + 8 sits the return address: 0x40102d back in _start, and 0x401019 inside asm_sum_range.

Adjacent frames are spaced exactly 32 bytes apart:

0x7fffffffd800−0x7fffffffd7e0=0x20 \mathtt{0x7fffffffd800} - \mathtt{0x7fffffffd7e0} = \mathtt{0x20}

Those 32 bytes break down into three parts:

  • saved rbp — 8 bytes;
  • return address — 8 bytes;
  • local slot — 16 bytes.

Why reserve 16 bytes instead of 8 for a single 8-byte slot [rbp - 8]? To preserve 16-byte alignment on rsp before the recursive call (we’ll examine this ABI rule in detail in lesson 18).

Recursion via call (asm_sum_range)       Tail jmp (asm_sum_down)
┌─────────────────────────┐ 0x...d808     ┌─────────────────────────┐
│ ret addr -> _start      │               │ ret addr -> _start      │ ◄─ $rsp
├─────────────────────────┤ 0x...d800     └─────────────────────────┘   never grows
│ saved rbp (= 0)         │ ◄──┐          all 5 iterations reuse
├─────────────────────────┤    │          the exact same return slot
│ slot n=5 + alignment    │    │
├─────────────────────────┤    │
│ ret addr -> asm_sum_rng │    │
├─────────────────────────┤ 0x...d7e0
│ saved rbp ──────────────┼────┘
├─────────────────────────┤
│ slot n=4 + alignment    │ ◄── $rsp
└─────────────────────────┘

There are no variable names on the stack: at the exact same checkpoint, info locals replies No locals. and info args replies No symbol table info available.

Registers: Who Preserves What

The calling convention splits general-purpose registers into two groups: caller-saved registers and callee-saved registers.

Group Registers Who is responsible for saving
caller-saved rax, rcx, rdx, rsi, rdi, r8–r11 the caller, if needed after call
callee-saved rbx, rbp, r12–r15 the callee, on every exit path
stack pointer rsp both sides: by ret, it must point to the return address

That’s why asm_sum_range opens with push rbp and closes with leave: without them, the caller would lose its frame pointer. Vector registers xmm0–xmm15 are all caller-saved under the System V AMD64 ABI; the full ABI is covered in lesson 18.

leave is shorthand for two instructions:

  • mov rsp, rbp discards local slots and points rsp back at the saved rbp;
  • pop rbp pops the saved value and restores the caller’s frame.

leave leaves other callee-saved registers untouched: if a function saved rbx or r12, it must restore them with explicit pop instructions before ret. In sum_range.asm, leave is followed directly by ret, returning both the stack and control together.

Tail Calls

When a call is the final action of a function, there’s no need to push a new return address: jumping straight back to the start of the function is tail-call optimization.

This is only valid when no work remains after the call: no adding to the return value, no restoring registers, and no frame teardown.

The sum_down.asm testbed implements this with jmp. A single call pushes the return address back to _start, and every subsequent iteration executes jmp to the same label, keeping $rsp constant across iterations.

sum_down.asm
; SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0

; sum_down.asm — tail recursion via jmp: rsp stays constant across iterations.
; The tail_iteration label is inspected by GDB on each pass.

default rel

%define SYS_EXIT 60
%define SUM_ARG 5

section .text
    global _start

; ------------------------------------------------------------------------------
; int64_t asm_sum_down(int64_t n, int64_t acc)
; Input:     rdi = n, rsi = running accumulator
; Output:    rax = acc + 1 + 2 + ... + n, or acc if n <= 0
; Clobbers:  rdi, rsi, rax, flags (caller-saved)
; ------------------------------------------------------------------------------
asm_sum_down:
tail_iteration:
    test rdi, rdi
    jle .done
    add rsi, rdi
    dec rdi
    jmp asm_sum_down

.done:
    mov rax, rsi

    ret

_start:
    mov rdi, SUM_ARG
    xor esi, esi
    call asm_sum_down
    mov edi, eax

    ; syscall: exit(asm_sum_down(SUM_ARG, 0))
    mov eax, SYS_EXIT
    syscall

section .note.GNU-stack noalloc noexec nowrite progbits

GDB hits tail_iteration repeatedly, yet $rsp never moves. Here are the first and third stops:

(gdb) break tail_iteration
Breakpoint 1 at 0x401000: file sum_down.asm, line 22.
(gdb) run
Starting program: .../build/sum_down

Breakpoint 1, tail_iteration () at sum_down.asm:22
22	    test rdi, rdi
(gdb) set $first = $rsp
(gdb) print/x $rsp
$1 = 0x7fffffffd818
(gdb) continue
Continuing.

Breakpoint 1, tail_iteration () at sum_down.asm:22
22	    test rdi, rdi
(gdb) continue
Continuing.

Breakpoint 1, tail_iteration () at sum_down.asm:22
22	    test rdi, rdi
(gdb) print/x $rsp
$2 = 0x7fffffffd818
(gdb) print/d $rsp == $first
$3 = 1
(gdb) x/2gx $rsp
0x7fffffffd818:	0x000000000040101d	0x0000000000000001

print/d $rsp == $first returns 1: five recursive passes share a single frame. At $rsp still sits the lone return address 0x40101d back to _start, followed by argc.

Compilers fold recursion into a loop automatically—even when an associative accumulation remains after the recursive call (strictly speaking, n + sum_down(n - 1) in tco_demo.c is linear recursion rather than a syntactic tail call, yet the optimizer still turns it into an accumulator loop):

tco_demo.c
/* SPDX-License-Identifier: PolyForm-Noncommercial-1.0.0 */

/* tco_demo.c — recursion: -O0 keeps call, -O2 folds it into a loop. */

#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>

static uint64_t sum_down(uint64_t n)
{
    if (n == 0) {
        return 0;
    }

    return n + sum_down(n - 1);
}

int main(void)
{
    volatile uint64_t n = 1000000;
    uint64_t total = sum_down(n);

    printf("sum_down(%" PRIu64 ") = %" PRIu64 "\n", n, total);

    return 0;
}

In main, n is marked volatile uint64_t so -O2 cannot constant-fold 1000000 into a compile-time literal: the value stays in memory, forcing the loop to actually run.

Without optimization, GCC emits a real call and a 32-byte frame:

"sum_down":
	push	rbp
	mov	rbp, rsp
	sub	rsp, 16
	mov	QWORD PTR -8[rbp], rdi
	cmp	QWORD PTR -8[rbp], 0
	jne	.L2
...
	call	"sum_down"

At -O2, the function disappears: its body is inlined into main and lowered into a loop, with neither call nor jmp to sum_down left in the listing:

	sub	rsp, 24
...
	test	rax, rax
	je	.L3
.L2:
	add	rdx, rax
	sub	rax, 1
	jne	.L2
.L3:

The quotes around "sum_down" are how GAS quotes symbol names in Intel syntax. At -O2, the running sum lives in rdx, the counter in rax, and the stack never grows.

Verification in the Terminal

Both testbeds return the sum as their exit status:

$ ./build/sum_range; echo $?
15
$ ./build/sum_down; echo $?
15

Running tco_demo with one million steps highlights the difference between stack recursion and a loop:

$ (ulimit -c 0; ./build/tco_demo_O0); echo $?
139
$ ./build/tco_demo_O2
sum_down(1000000) = 500000500000

Exit status 139 is 128 + 11, termination by SIGSEGV on stack exhaustion: a million 32-byte frames won’t fit inside 8 MiB. The -O2 build covers the exact same range in a single frame.

Common Pitfalls

  1. “Assuming $rsp restores itself after a recursive call.”
    Fact: without leave or a matching pop, the function returns, but $rsp stays shifted and the next ret jumps to garbage.
    Cause: call and push decrement $rsp; only ret, pop, leave, or an explicit add rsp, N restores it.
    Fix: keep prologue and epilogue symmetric across every exit path and verify $rsp in GDB right before each ret.

  2. “Expecting to find local variable names on the stack.”
    Fact: at frame_probe, info locals says No locals. and info args says No symbol table info available.
    Cause: variable names live in DWARF debug metadata, not on the hardware stack; raw assembly files carry no variable symbols at all.
    Fix: inspect frame slots by offsets from rbp and match them against comments in your listing.

  3. “Tail recursion will blow the stack anyway.”
    Fact: tco_demo_O0 crashes with 139, while tco_demo_O2 prints 500000500000.
    Cause: tco_demo.c uses ordinary linear recursion (return n + sum_down(n - 1)), yet -O2 still turns it into a loop using accumulator rdx; at -O0, each step emits a call and allocates a new frame until the stack runs out.
    Fix: rewrite tail calls as jmp manually in assembly, or enable optimization and verify in the disassembly that no call remains.

Lab

Goal. Build frame_walk.asm to compute 1 + 2 + ... + n in two ways—recursive call and tail-call jmp—and demonstrate the difference in stack depth.

Contract and requirements.

  • Both functions take n and return the sum; for n <= 0, return 0.
  • The recursive version must build a full rbp frame and use call.
  • The tail-recursive version must leave $rsp unchanged across iterations.
  • Define n as a constant in the source file; exit with the low byte of the sum.
  • Place debug labels in both functions so GDB can break on entry to each pass.

Verification criteria.

  1. ./build/frame_walk; echo $? exits with the expected sum for your chosen n.
  2. In GDB at the recursive label, $rsp decreases by one frame size at each deeper call.
  3. In GDB at the tail-call label, $rsp is identical on the first and last iteration.
  4. objdump -d -M intel build/frame_walk shows call in the recursive function and none in the tail-call function.
  5. gcc -O0 -S and gcc -O2 -S on an equivalent C99 function produce a call at -O0 and a loop at -O2.
Hints, expected output, and walkthrough

For n = 6, the sum is 21, so the exit code is 21. If the recursive version returns something else, check the order of add and dec: accumulate the current value before decrementing the counter.

On this testbed, a recursive frame takes 32 bytes: 8 for saved rbp, 8 for the return address, and 16 for the local slot. Between n = 6 and n = 1, that’s 5 * 32 = 160 bytes; measuring down to the base case n = 0 where recursion stops gives 6 * 32 = 192 bytes.

In the tail-call version, $rsp must match down to the exact byte: any drift means a call or an unmatched push slipped in.

At -O2, GCC may inline the function into main and eliminate its symbol completely. Look for a loop across the whole disassembly rather than under the function name: a jne loop without call confirms the transformation.

Testbed sources, Makefile, and automated tests for this lesson: lessons/10-functions.

Summary

  1. call pushes the next instruction’s address onto the stack; ret pops it and transfers control there.
  2. A push rbp / mov rbp, rsp / sub rsp, N prologue builds a stack frame, and leave tears it down.
  3. rbp holds the saved frame pointer, rbp + 8 holds the return address, and negative offsets below rbp hold local slots.
  4. Callee-saved registers rbx, rbp, r12–r15 must be restored along every return path.
  5. A tail call via jmp leaves $rsp untouched and turns recursion into a loop.
  6. gcc -O2 performs this transformation automatically, whereas -O0 keeps growing the stack until SIGSEGV.
Bridge to the Next Lesson
call and ret hand control back, and the frame disappears. In lesson 11, I move from single stack slots to contiguous data: arrays, arrays of structs, and the addressing formula shared by both mov and lea.