Skip to content
BIASED

Branches, loops and memory access

Conditional branches and `jal`, compiling if/while/for by hand, byte and word loads/stores with sign extension, arrays and address arithmetic on little-endian RISC-V.

Branches and jumps

Computational instructions alone run straight-line code with data in 32 registers. Programs also need to choose, repeat, and touch more data than fits in registers. Without control flow a thousand numbers need two thousand instructions; without memory access every value must live in a register at once.

Notation. x[r]x[r] register rr; M[a]M[a] byte at aa; halfword = 2 bytes, word = 4. sext⁡\operatorname{sext} / zext⁡\operatorname{zext} widen by sign or zeros.

Conditional branches: beq, bne, blt, bge, bltu, bgeu — jump to a label (±4 KiB, B-format offset) if the condition holds, else fall through. bgt/ble and beqz/bnez/bltz/… are pseudos that swap operands or use zero. jal rd, label reaches ±1 MiB and links; j is jal zero, label.

Worked. t0=-1, t1=1: blt jumps; bltu does not (t0 as unsigned is 232−12^{32}-1). That unsigned reading catches both i ≥ n and negative i in one bgeu i, n, out_of_range.

if/else and loops

Key idea. Structured statements become branches on the opposite condition plus jumps.

C Assembly sketch
if (a<b) S1; bge a,b,end · S1 · end:
if … else bge … else · S1 · j end · else: S2 · end:
while loop: bge … end · S · j loop · end:
do … while loop: S · blt … loop
for (i=0;i<n;i++) li i,0 · loop: bge i,n,end · S · addi i,i,1 · j loop

Compilers often rotate loops so the test sits at the bottom (one branch per iteration), with a front test to skip empty loops.

Collatz. From n=27n=27: while n≠1n\neq 1, halve evens and replace odds by 3n+13n+1, counting steps and the max. The assembly is beq/bnez/j weaving then/else and the back-edge — 111 steps, max 9232, 864 instructions with I/O in the note’s run.

Loads and stores

Address = x[rs1]+sext⁡(imm)x[\texttt{rs1}]+\operatorname{sext}(\texttt{imm}), imm ∈ [−2048, 2047]. Only loads and stores touch memory.

Op Effect
lw/sw 4 bytes
lh/lhu/sh 2 bytes, sext or zext on load
lb/lbu/sb 1 byte, sext or zext on load

Worked. Bytes f6 00 80 ff at a word-aligned address: lb → −10; lbu → 246; lh at +2 → −128; lhu → 65408; lw → 0xff8000f6. Multi-byte values are little-endian. Word addresses should be multiples of 4 (RARS traps otherwise); halfwords multiples of 2. Misaligned accesses are legal in the ISA with the Zam extension story deferred — for this course, align.

Arrays and address arithmetic

Scale the index by element size (slli by 2 for int, by 3 for double on RV64), add the base, then load/store. A rotated sum loop loads a[i], accumulates, increments the pointer by 4, and branches on the end address — one compare per element after setup. Directives fill .data from 0x10010000: .byte/.half/.word, .asciz (NUL-terminated), .space, .align k to 2k2^k. Strings: walk with lbu until zero; "hi" occupies three bytes including the terminator.

Pseudos and conveniences

beqz t0, L → beq t0, zero, L. Named constants (.eqv N, 10), macros (.macro / .end_macro) and .include keep longer programs readable without changing what the processor sees — the assembler expands them before encoding. Prefer a macro for a repeated three-instruction idiom over copy-paste that drifts out of sync.

Compilers emit the opposite-condition pattern because fall-through is the cheap path in a pipeline that predicts not-taken or that has already fetched PC+4. Putting the rare else out of line keeps the common path contiguous in the I-cache. For loops over arrays, induction-variable strength reduction turns a[i] address math into pointer bumping: after slli t0, i, 2; add t0, a, t0; lw … once, later iterations may only addi ptr, ptr, 4.

Alignment traps in RARS are deliberate teaching friction. On a Linux RV64GC board, misaligned loads may be emulated in the kernel (slow) or supported in hardware; either way, natural alignment remains the fast path. When laying out a .data struct by hand, insert .align 2 before .word fields after a run of .byte so the next word does not sit at an odd address. Counting string length with lbu / addi / bnez is the assembly shape of strlen; watch that you compare the loaded byte as unsigned (lbu, not lb) so bytes ≥ 128 are not treated as negative and break the zero test incorrectly if you ever switch to signed compares.

Pseudo-ops also hide multi-instruction sequences: li t0, 0x12345 may become lui+addi with sign adjustment, exactly as in the encoding topic. Prefer writing the pseudo in source and reading the expansion in the listing when you need the real instruction count for CPI arguments later.

Next: Procedures, the stack and calling conventions — jal/jalr, who saves which registers, and stack frames for recursion.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.