Search Knowledge

© 2026 LIBREUNI PROJECT

Computer Architecture/Instruction sets and execution
Page 4 of 20

Instruction-Set Architecture

The contract between software and a processor implementation.

Lesson briefInstruction sets and execution · 9 h · 3 outcomes

Required knowledge

  • Programming in a systems language
  • Binary arithmetic and basic digital logic

Learning outcomes

  • Specify programmer-visible state and precise instruction semantics, including memory access, control flow, privilege, and exceptions.
  • Decode encodings and trace an ABI-conforming sequence through registers, stack, memory order, and traps.
  • Separate ISA guarantees from implementation choices and construct a refinement test for an ISA extension.

Assessment target

Given an unfamiliar instruction encoding and memory-ordering rule, derive its architectural transition, trace a short program, and identify an implementation that violates the contract.

Scope boundary

  • Dynamic binary translation and JIT compilation (Rosetta, QEMU TCG) between mismatched ISAs are omitted in favor of native execution.
  • Hardware hypervisor extensions (nested stage-2 page tables, VM control blocks) are treated in advanced systems.
  • Multistep microcode ROM sequencers are omitted to focus on hardwired RISC control logic.

An instruction-set architecture (ISA) is the stable contract presented by a processor to software. It specifies the programmer-visible state, instruction semantics, encodings, addressing rules, memory-access behavior, privilege boundaries, and exceptional events.

A microarchitecture may execute instructions in one cycle, in a deep pipeline, out of order, or through translation into internal operations; as long as it preserves the ISA’s specified observations, it remains a valid implementation. This abstraction is what lets one binary run across generations of hardware and lets compilers target a machine without knowing its transistor-level organization.

The contract is narrower than “what the hardware happens to do.” Timing, cache size, branch-predictor state, and speculative execution are usually not architectural state, although they affect performance and can create side channels.

Conversely, the exact behavior of an unaligned access, an overflow flag, a memory ordering operation, or an illegal instruction is architectural if software can observe it. A rigorous ISA specification therefore separates functional semantics from implementation accidents and states what is guaranteed, permitted, or undefined.

Programmer-visible state

The architectural state commonly includes a program counter (PC), a register file, memory, status/control registers, and privileged state. A register file has a finite set of named registers with a defined width. Some ISAs reserve a register whose reads always produce zero; others expose a stack pointer, link register, condition-code register, or vector register bank. The PC identifies the next instruction according to the ISA’s fetch convention. It may advance by a fixed instruction width, by an instruction-length decoder, or by a branch/jump target.

An instruction is a state transition. If architectural state before execution is σ\sigma instruction bytes decode to operation opop and the memory system supplies the required values, then execution defines σ′=⟦op⟧(σ)\sigma'=\llbracket op\rrbracket(\sigma) The notation hides important partiality: an access may be misaligned, a privilege check may fail, a page may be absent, or a divide may have an invalid operand. In those cases, the ISA specifies an exception transition rather than an ordinary result.

Worked example: load/store semantics. A RISC-style load word lw r1, 12(r2) computes an effective address EA=R[r2]+12EA=R[r2]+12 checks alignment and access permission, reads four bytes according to the memory endianness, sign- or zero-extends the word as specified, writes it to r1, and advances the PC. A store computes the same kind of address but writes register data to memory and does not update a general-purpose destination. The assembler syntax is short; the architectural transition includes address arithmetic, width, alignment, permission, and exception behavior.

Locate the abstraction

0 / 4 answered

Evaluate which elements belong strictly to the Instruction-Set Architecture (ISA) interface contract rather than a specific microarchitectural implementation:

Classify each option as correct or incorrect, or leave uncertain options unanswered (“I don't know”) and verify at any time.

1
Programmer-visible register files, instruction encodings, memory semantics, and trap exception behaviors.
2
The physical number of pipelined hardware stages configured to execute integer and branch operations.
3
The specific set-associative replacement policy implemented inside the level-1 physical data cache.
4
Formal addressing mode specifications, instruction byte widths, and architectural memory alignment contracts.

RISC and CISC as design families

A load/store ISA restricts memory access to explicit load and store operations; arithmetic instructions operate on registers. This regularity simplifies decode, register allocation, pipeline staging, and formal reasoning. It may increase instruction count for operations that could be expressed as memory-to-memory work. A more instruction-rich ISA can encode complex addressing modes or multi-step operations, reducing code size at the cost of decoding and implementation complexity.

The labels RISC and CISC describe tendencies, not a complete classification. Modern “complex” ISAs may translate instructions into simple internal operations, while a RISC ISA can contain vector, atomic, compressed, or privileged instructions with substantial semantics. The useful question is what software-visible contract is exposed and what implementation freedom it preserves.

Instruction length presents a trade-off. Fixed-width encodings simplify fetch alignment and parallel decode but may waste bits for small operations. Variable-length encodings improve code density but make instruction boundaries and branch targets harder to locate. Compressed encodings add a second width while preserving a common register or operation subset. Code density affects instruction-cache pressure, so encoding is a performance design choice as well as a compiler-interface choice.

Architectural state defines the instruction

Two implementations execute an ADD instruction differently internally. Both read the same operands, update the destination register, advance the PC, and raise identical exceptions.

Evaluate what establishes these two different processor designs as valid implementations of the same ISA operation:

Encoding and decoding

An instruction encoding partitions bits into fields: opcode, register identifiers, immediate values, function modifiers, and sometimes mode or rounding controls. Field widths constrain the number of registers and immediate range. If a register file has 2r2^r entries, a register identifier needs rr bits. An immediate may be sign-extended from a compact field; its range and alignment may be more important than its raw width.

Worked example: PC-relative branch. Suppose a branch encodes a signed kk-bit displacement in instruction units of four bytes. The signed displacement range is [−2k−1,2k−1−1][-2^{k-1},2^{k-1}-1] units, and the byte target is PC+4dPC+4d if the architecture defines the PC as the current instruction address. A compiler cannot assume that every label is reachable; the assembler or linker must synthesize a longer branch sequence when the displacement does not fit. Misunderstanding whether the base is current PC or next PC creates an off-by-one-instruction error that passes short tests and fails at range boundaries.

Immediate encoding also interacts with sign extension. An instruction that adds a signed 12-bit immediate must interpret 0xFFF as -1, not 4095. A separate unsigned-immediate instruction or zero-extension rule is needed when the latter is intended. The opcode’s semantic definition, not the bit pattern alone, determines the result.

Pause & Predict: The 12-Bit Immediate Sign-Extension Trap. Suppose you execute addi a0, zero, 0x800 on a 32-bit RISC-V processor where addi accepts a 12-bit immediate field imm[11:0]. What 32-bit hexadecimal value is stored in a0? Is it 0x00000800 +2048+2048 or 0xFFFFF800 −2048-2048 Commit your reasoning before opening the analysis below.

Show hintExpand

Check bit 11 of 0x800 (0b1000_0000_0000). If the most significant bit of the 12-bit immediate is 1, what does arithmetic sign extension do to bits 31..12?

Reveal analysisExpand

Analysis: The value stored is 0xFFFFF800 −2048-2048 In standard RISC-V I-type instructions, the 12-bit immediate is strictly sign-extended to 32 bits. The hex value 0x800 has bit 11 equal to 1 (0b1000_0000_0000). The sign bit imm[11] is copied into all upper 20 bits: imm[31:12] = 0b1111_1111_1111_1111_1111 (0xFFFFF). Thus, the machine sign-extends 0x800 to 0xFFFFF800. To load an unsigned +2048+2048 or construct larger 32-bit values, one must use lui (Load Upper Immediate) combined with addi, carefully adjusting for the negative sign bit.

For a hypothetical 32-bit, fixed-width register-add ISA with modular arithmetic and no flags, the decoded fields select a precise state transition. This is a semantic map, not a claim about execution stages; the source operands are read from the pre-state even when a destination aliases a source.

Code
rectangle "Instruction fields: opcode, rs1, rs2, rd" as I
rectangle "Pre-state: registers R, PC, memory M" as S
rectangle "Decode ADD; select R[rs1], R[rs2]" as D
rectangle "v = (R[rs1] + R[rs2]) mod 2^32" as A
rectangle "Post-state: R[rd] = v; PC = PC + 4" as N
I --> D : decode fields
S --> D : read pre-state
D --> A : operand values
A --> N : result
S --> N : preserve other registers and memory
Instruction fields: opcode, rs1,rs2, rdPre-state: registers R, PC,memory MDecode ADD; select R[rs1],R[rs2]v = (R[rs1] + R[rs2]) mod 2^32Post-state: R[rd] = v; PC = PC +4decode fieldsread pre-stateoperand valuesresultpreserve other registersand memory

Transfer check. Set rs1=5, rs2=6, rd=5, with initial R[5]=0xffffffff and R[6]=2. Determine the post-state and explain why destination/source aliasing does not change the operands.

Addressing modes and memory consistency

An addressing mode defines how an instruction derives an effective address: base plus offset, base plus index times scale, PC-relative, absolute, or indirect through a register. Addressing modes are conveniences expressed in the ISA; a microarchitecture may compute them in one adder or several internal steps. The mode must specify overflow behavior, alignment, privilege checks, and whether an address is computed before or after an update.

Worked example: effective address and instruction count. A RISC-V load lw x5, 12(x6) computes EA=R[x6]+12EA = R[x6] + 12 If x6 = 0x1000, then EA = 0x100c; alignment and permission are checked on that address before the four bytes are read. An indexed access to element i of an 8-byte array is not a single RISC-V addressing mode: with the index in a1 and the base in a0, a compiler emits slli t0, a1, 3, add t0, a0, t0, then ld x5, 0(t0). An x86-64 mov rax, [rbx + rcx*8] encodes the same base-plus-index arithmetic in one instruction. The trade is visible: the complex mode reduces instruction count but adds address-generation work and encoding constraints; the load/store ISA keeps the arithmetic explicit.

Memory is not an array of independent locations on a modern multiprocessor. The ISA specifies an ordering model for loads and stores. A sequentially consistent model places operations from all cores into one order consistent with each core’s program order. Weaker models permit certain reorderings and require explicit fences or atomic operations when synchronization depends on visibility order. A compiler and processor must jointly preserve the language-level memory model; a lock implemented with ordinary unordered loads and stores is not automatically a lock.

Falsifiable trace: store buffering. Two cores execute the following program, with x and y initially zero:

Core 0:                 Core 1:
store 1 -> x            store 1 -> y
r0 <- load y            r1 <- load x

Under sequential consistency, at least one load must observe 1: the alternative requires a cycle in the single total order, because each core’s store precedes its own load. Under x86-TSO and RISC-V’s weak ordering, the outcome r0 = 0 and r1 = 0 is permitted: each store may remain buffered while its core loads the other location. Observing (0,0) therefore falsifies a claim that the implementation is sequentially consistent, but it does not falsify x86-TSO or RVWMO. Adding mfence between the store and load on x86, fence rw, rw on RISC-V, or sequentially consistent atomics forbids the outcome. Release/acquire ordering forbids the message-passing variant—store data, release-store a flag, acquire-load the flag, load data—but it does not order a store followed by a load on the same core, so it does not by itself forbid this store-buffering outcome. A lock built from plain loads and stores without these constraints has no such guarantee.

An atomic read-modify-write instruction can guarantee that no competing core observes an intermediate state. Compare-and-swap typically reads a location, compares it with an expected value, and writes a replacement only if equal, returning success or failure. Its semantics must specify memory order, spurious failure if permitted, alignment, and exception behavior. Atomicity is about indivisibility at the specified granularity; it does not by itself prevent starvation, ABA problems, or incorrect higher-level invariants.

Procedure calls and ABI boundaries

The ISA supplies call, jump, and return primitives, but a usable software ecosystem also needs an application binary interface (ABI). The ABI assigns arguments and return values to registers or stack locations, classifies caller- and callee-saved registers, defines stack alignment, lays out aggregate values, and specifies symbol naming and object formats. A compiler-generated function and hand-written assembly interoperate only if both obey these conventions.

A call often saves a return address in a link register or stack, transfers control to a target, establishes a frame if needed, and returns through the saved address. Leaf functions may avoid a frame; recursive or reentrant functions cannot assume a single global copy of locals. The ABI’s preservation rule is an invariant across the call boundary: after the callee returns, every callee-saved register has the value the caller expects, while caller-saved registers may have changed.

Worked example: summing an array. Suppose arguments are a pointer p and length n, and the result is returned in r0. A correct loop needs a pointer, remaining count, and accumulator. Each iteration loads a word, adds it to the accumulator, advances the pointer by the element size, decrements the count, and branches while nonzero. The proof invariant is: after kk iterations, the accumulator is the sum of the first kk elements and p points to element kk The machine sequence is correct only if the load width, pointer increment, signedness of the loop comparison, and return convention all match the source-level contract.

Exceptions, traps, and privilege

An exception transfers control from ordinary instruction execution to a handler with architectural state saved according to the ISA. Synchronous exceptions arise from the current instruction—illegal opcode, page fault, arithmetic fault, or system call. Interrupts are asynchronous events such as a timer or device completion, though the architectural boundary may use a common entry mechanism.

Precise exceptions mean the machine state appears as if all older instructions completed and no younger instruction took effect. In an in-order implementation this is natural; an out-of-order implementation needs a reorder or retirement mechanism to preserve the illusion. The exception record must identify a restart PC or faulting instruction, cause code, privilege transition, and saved status. A handler that cannot determine whether to retry or skip an instruction cannot safely recover.

Worked trace: a load page fault and restart. User code executes lw a0, 0(s0) with PC = 0x4000_1000 and s0 = 0x0000_0000_dead_b000. The page-table walk finds no valid mapping. The hart records a synchronous exception with scause = 13 (load page fault), stval = 0xdead_b000, and sepc = 0x4000_1000; it copies the previous privilege (U) into sstatus.SPP, saves the interrupt-enable state in sstatus.SPIE, disables supervisor interrupts, and enters the handler at stvec. The destination a0 is not written: a precise exception leaves the register file as if the faulting instruction had not executed.

The handler allocates a page, installs a valid PTE, executes sfence.vma to discard stale translations on the handling hart, and executes sret. sret restores privilege from SPP, restores SIE from SPIE, and sets PC = sepc, so the load re-executes at 0x4000_1000 and now succeeds. Other harts that may have cached the old translation require a TLB shootdown. If the handler instead advanced sepc by four bytes, it would skip the load and silently leave a0 undefined; if the hardware partially wrote a0 before the fault was resolved, it would violate precise-exception semantics.

Privilege modes constrain access to memory, control registers, and devices. A system call deliberately enters a more privileged mode through a defined instruction; a page-protection violation enters it because an access violated a rule. The boundary is a security contract: user code should not be able to forge the saved privilege state, redirect the handler to an untrusted address, or retain access to privileged mappings after return.

Instruction semantics and compiler reasoning

Compilers transform programs by proving that the transformed program has equivalent permitted observations. If an ISA defines signed overflow as trapping, the compiler cannot replace a checked addition with modular addition. If overflow is undefined at the language level, the compiler may use that assumption to eliminate impossible branches—but only within the source language’s rules. If an ISA operation wraps but the language operation is checked, the compiler must insert a range check or use a widening instruction.

Worked example: reassociation is not a semantic identity. IEEE 754 addition is not associative, so these two source expressions have different values:

double left  = (0.1 + 0.2) + 0.3;   /* 0.6000000000000001 */
double right = 0.1 + (0.2 + 0.3);   /* 0.6 */

A compiler may reassociate only when the language or an explicit fast-math mode permits it; otherwise the transformation changes the permitted observations. The same distinction separates the language from the ISA. C signed overflow is undefined behavior, so a compiler may fold x + 1 > x to true; with -fwrapv it must preserve wraparound. The ISA’s add instruction may wrap modulo the register width, but the compiler’s obligation comes from the source language. If the language operation is checked, the compiler must insert a range check or use a wider instruction rather than relying on the hardware’s wraparound.

Alias and alignment assumptions also affect legal transformations. A load can be hoisted above another operation only if the ISA and memory model permit the reordering and no aliasing or exception behavior changes. A vectorized load may require alignment or use a defined unaligned instruction. “The hardware usually handles it” is not an architectural proof.

Verification of an ISA implementation

An ISA simulator is an executable reference model, but a simulator bug can repeat the same misunderstanding as the hardware. Differential testing compares an implementation against a trusted model across random and directed programs. Directed tests target sign extension, branch boundaries, register-zero behavior, misalignment, privilege transitions, page faults, atomic races, and precise exception restart.

Worked example: directed tests and a random property. Differential testing is only as strong as the observations it compares. On RV64, the reference transition for addi x5, x0, imm is R[x5]=sext⁡64(imm12)R[x5] = \operatorname{sext}_{64}(imm_{12}) with x0 hardwired to zero and PC advancing by four. A test set that omits the sign bit passes a zero-extending bug.

StimulusReference observationBug it exposes
addi x5, x0, 0x000x5 = 0wrong constant path
addi x5, x0, 0x7ffx5 = 2047truncation or off-by-one
addi x5, x0, -2048 (immediate bits 0x800)x5 = 0xffff_ffff_ffff_f800zero-extension instead of sign-extension
addi x5, x0, -1 (immediate bits 0xfff)x5 = -1failure to sign-extend
addi x0, x0, 1x0 remains 0register-zero not hardwired
addi x5, x0, imm for random 12-bit immx5 = sext(imm)any mismatch in the decode path

Random testing can exercise many additional encodings but does not guarantee all 4,096 cases are covered. Exhaustive enumeration of the 12-bit immediate field does; the directed cases explain why a mismatch matters. A simulator that agrees with the hardware on the same wrong interpretation is not a reference: differential testing needs an independently written model, or formal refinement against the ISA’s transition relation, before agreement is evidence.

Formal instruction proofs typically establish a refinement relation between microarchitectural state and architectural state. Internal pipeline registers, speculative values, and cache metadata are allowed to differ; at retirement, the visible state must match the reference transition. This relation explains why an implementation can execute instructions out of order while still satisfying a sequential ISA.

Counterexample & Failure Mode: The Unaligned Split-Access Trap & Atomicity Breakdown

Does an ISA’s memory access contract guarantee atomicity and fault isolation for arbitrary pointers? Consider executing a 32-bit load lw x5, 0(x1) where x1 = 0x0FFF_FFFE.

  1. Boundary Breakdown:

    • The 4-byte word occupies addresses [0x0FFF_FFFE, 0x0FFF_FFFF, 0x1000_0000, 0x1000_0001].
    • These bytes straddle two distinct 4 KB virtual memory pages: Page 0 (0x0FFF_F000) and Page 1 (0x1000_0000).
  2. Split Fault Failure Mode: Suppose Page 0 is resident in RAM with read permissions, but Page 1 is unmapped or paged out to disk.

    • A naive microarchitecture that reads bytes 0 and 1 before translating Page 1 will encounter a Page Fault on the second half of the instruction!
    • If the core partially wrote the destination register x5 with the first two bytes, the architectural state is corrupted prior to exception entry, violating precise exception semantics.
  3. Multicore Atomicity Collapse: Even if both pages are resident, an unaligned access straddling a 64-byte cache line boundary cannot be fulfilled by a single L1 cache tag match. It requires two distinct bus/interconnect transactions.

    • If another core executes a concurrent store to either cache line, it can interleave between the two halves.
    • The load reads bytes 0-1 from before the store, and bytes 2-3 from after the store, observing a “torn read” word that never existed in memory.
    • ISA Contract Guarantee: This is why strict RISC ISAs specify that misaligned accesses either raise an Address-Misaligned Trap or are explicitly non-atomic across cache boundaries.
Section Exercises

Deep Practice

Solve these problems to test and consolidate your understanding. Complete worked solutions and diagnostic hints are available for each problem.

Exercise 2.1.1: Signed Load Architectural State Transition Specification

Constructionapplication

Specify the complete formal architectural state transition for a signed load instruction (e.g. lw rd, offset(rs1)), covering effective address arithmetic, privilege and alignment validation, byte endianness, sign extension into destination register rd, and precise exception handling.

HintExpand

Trace effective address generation, alignment verification, memory read, and sign extension into destination.

Worked solutionExpand

Compute effective address EA=R[rs1]+sign_extend(offset)EA = R[rs1] + \text{sign\_extend}(offset) Verify user privilege level and that EA(mod4)=0EA \pmod 4 = 0 (for 32-bit aligned accesses). If misaligned or access-violating, suppress destination update and trigger an Address-Misaligned or Load-Access-Fault trap saving faulting PCPC in exception state. If valid, read 4 bytes starting at EAEA according to machine endianness, sign-extend the 32-bit word to register width, write to R[rd]R[rd] (if rd≠x0rd \ne x0 and advance PC←PC+4PC \gets PC + 4

Exercise 2.1.2: Fixed-Width 32-Bit Instruction Encoding Layout

Constructionapplication

Design a 32-bit fixed-width encoding scheme supporting: (1) 16 three-register R-type operations; (2) 8 two-register I-type operations with a 12-bit signed immediate; and (3) 8 two-register B-type word-aligned conditional branches with a 12-bit signed displacement. Allocate explicit bitfields for opcode, registers, and immediates.

HintExpand

Allocate explicit bitfields for opcode, destination register, source registers, and immediate constants.

Worked solutionExpand

Use a 7-bit primary opcode field inst[6:0] to distinguish instruction classes. For R-type: rd[11:7] (5 bits), funct3[14:12] (3 bits), rs1[19:15] (5 bits), rs2[24:20] (5 bits), funct7[31:25] (7 bits). For I-type: rd[11:7], funct3[14:12], rs1[19:15], imm[31:20] (12 bits signed [−2048,2047][-2048, 2047] For B-type: funct3[14:12], rs1[19:15], rs2[24:20], with displacement bits split across inst[31], inst[7], inst[30:25], and inst[11:8] to encode a ±4 KB\pm 4\text{ KB} word-aligned branch offset.

Exercise 2.1.3: Assembly Loop Invariant Inductive Proof

Proofsynthesis

Prove the partial correctness of an assembly array-sum loop using mathematical induction over loop iterations kk demonstrating that the accumulator satisfies acc=∑i=0k−1A[i]\text{acc} = \sum_{i=0}^{k-1} A[i] at the loop header for arrays up to length NN

HintExpand

Induct on array index kk, showing that the accumulator equals ∑i=0k−1A[i]\sum_{i=0}^{k-1} A[i] at the loop header, and discuss modular integer overflow.

Worked solutionExpand

Base case k=0k=0 Before entering the loop, the accumulator is cleared to 0 and the base pointer references A[0]A[0] the empty sum is 0, satisfying the invariant. Inductive step: Assume acck=∑i=0k−1A[i]\text{acc}_k = \sum_{i=0}^{k-1} A[i] at the start of iteration kk The loop body executes lw t0, 0(ptr), add acc, acc, t0, and addi ptr, ptr, 4. At the end of the iteration, acck+1=acck+A[k]=∑i=0kA[i]\text{acc}_{k+1} = \text{acc}_k + A[k] = \sum_{i=0}^k A[i] When the branch condition k=Nk = N terminates the loop, the accumulator contains ∑i=0N−1A[i]\sum_{i=0}^{N-1} A[i] under two’s-complement modular arithmetic (mod232)\pmod{2^{32}}

Exercise 2.1.4: Memory Consistency and Litmus Test Synchronization

Verificationapplication

In a multiprocessor system, thread 1 executes data = 42; flag = 1; while thread 2 executes while (flag == 0); r1 = data;. Verify why a weak memory model allows thread 2 to observe r1=0r_1 = 0 and insert the necessary ISA memory barrier instructions to guarantee sequentially consistent message passing.

HintExpand

Write a classic 2-thread message passing pattern (data write, flag set vs flag check, data read) and insert memory fences or acquire/release operations.

Worked solutionExpand

Under weak memory architectures (e.g. RISC-V or ARM), the hardware memory controller or out-of-order execution engine may reorder independent stores W(data)W(data) and W(flag)W(flag) or independent loads R(flag)R(flag) and R(data)R(data) If W(flag)W(flag) reaches cache before W(data)W(data) thread 2 sees flag=1flag = 1 but reads stale data=0data = 0 Inserting a release store (s-fence or fence w,w) on thread 1 and an acquire load (l-fence or fence r,r) on thread 2 forces visibility order.

Exercise 2.1.5: Precise Exception Constraints on Speculative Store Commits

Descriptionrecall

Explain why an out-of-order processor cannot write speculative store results directly to the L1 data cache before an older floating-point divide instruction has completed without faulting.

HintExpand

Explain how committing a younger store to cache or memory before an older instruction's fault status is determined violates precise state.

Worked solutionExpand

Precise architectural exceptions require that when an exception occurs at instruction IkI_k all instructions prior to IkI_k have completely retired their state, and no instruction at or subsequent to IkI_k has modified architectural registers or memory. If a younger store modifies cache before an older divide raises a divide-by-zero trap, persistent memory reflects side effects of instructions that should have been cancelled, destroying restartability and violating the ISA contract.

Exercise 2.1.6: Procedure Calling Convention and ABI Stack Frame Design

Constructionapplication

Specify an ABI calling convention for an 8-register processor architecture that must support recursive function calls and 16-byte stack alignment. Partition registers and draw the resulting stack frame layout.

HintExpand

Partition registers into argument, temporary (caller-saved), and preserved (callee-saved) sets, and allocate stack slots for spilled return addresses and frames.

Worked solutionExpand

Register allocation:

  • r0: Constant zero.
  • r1: Return address ra (caller-saved by leaf, callee-saved across calls).
  • r2: Stack pointer sp.
  • r3, r4: Arguments and return values a0, a1 (caller-saved).
  • r5: Temporary t0 (caller-saved).
  • r6, r7: Saved registers s0, s1 (callee-saved). Stack frame: Prologue decrements sp by 16 bytes, storing ra at 8(sp) and s0 at 0(sp). Epilogue restores both and increments sp by 16 before ret.

Exercise 2.1.7: Differential Testing of 12-Bit Immediate Sign Extension

Generalisationtransfer

Design a property-based differential test suite to verify that a hardware decoder and software emulator decode 12-bit signed immediates identically. Specify the boundary vectors and mathematical invariant property.

HintExpand

Construct test vectors covering positive maximum (+2047+2047), negative minimum (−2048-2048), zero, −1-1, and property-based mathematical equivalence.

Worked solutionExpand

Test vectors:

  • Boundary values: 00 +1+1 −1-1 (0xFFF), +2047+2047 (0x7FF, maximum positive), −2048-2048 (0x800, minimum negative).
  • Bit-pattern isolates: single bit set at each position 0…110 \dots 11 Property invariant: For all b∈[0,4095]b \in [0, 4095] if b<2048b < 2048 decoded value must equal bb if b≥2048b \ge 2048 decoded value must equal b−4096b - 4096 Assert that hardware RTL simulation and software instruction emulator yield identical extended 64-bit integers across all 4096 inputs.

References & Further Reading

  • Patterson, D. A., & Hennessy, J. L. (2020). Computer Organization and Design: The Hardware/Software Interface (RISC-V Edition) (2nd ed.), Chapter 2 (“Instructions: Language of the Computer”). Morgan Kaufmann.
  • Waterman, A., & Asanović, K. (Eds.). (2019). The RISC-V Instruction Set Manual, Volume I: User-Level ISA (Document Version 20191213). RISC-V International.
  • Waterman, A., & Asanović, K. (Eds.). The RISC-V Instruction Set Manual, Volume II: Privileged Architecture. RISC-V International. https://github.com/riscv/riscv-isa-manual
  • Weaver, D. L., & Germond, T. (1994). The SPARC Architecture Manual (Version 9). Prentice Hall.