Instruction Set Architecture: The Bridge Between Hardware and Software

Explore RISC vs CISC, x86 vs ARM, opcodes, operands, and instruction formats that define how CPUs understand your code.

published: reading time: 36 min read author: Geek Workbench updated: November 18, 2026
Quick Summary

Explore RISC vs CISC, x86 vs ARM, opcodes, operands, and instruction formats that define how CPUs understand your code.

Introduction

The Instruction Set Architecture (ISA) is the contract between hardware and software. It defines what instructions a processor can run, what registers are available, how memory works, and what data types the instructions handle. Without an ISA, compilers would have no standard target to generate code for, and operating systems would have to deal with hardware differences directly.

When you write a C program or any high-level code, it eventually becomes machine instructions following a specific ISA. Whether your system runs on Intel’s x86, ARM, or RISC-V, the ISA determines how your software communicates with the silicon underneath.

When to Use / When Not to Use

When to Use ISA Knowledge:

  • Writing performance-critical code that benefits from instruction selection
  • Debugging at the assembly level when profiling reveals hotspots
  • Choosing between processor architectures for a new deployment
  • Understanding why certain operations are faster on specific hardware
  • Contributing to compilers, operating systems, or embedded firmware

When Not to Use:

  • Writing business logic in high-level languages where portability matters more than micro-optimization
  • When working purely with managed runtimes that abstract all hardware details (Java JVM, .NET CLR)
  • Quick prototyping where development speed outweighs execution efficiency

Architecture Diagram

flowchart TB
    subgraph "Software Layer"
        A["High-Level Code<br/>C, C++, Rust"] --> B["Compiler"]
        B --> C["Assembly / Object Code"]
        C --> D["Machine Code<br/>Binary Instructions"]
    end

    subgraph "ISA Layer"
        E["Instruction Set Architecture"] --> F["Opcodes"]
        E --> G["Register Set"]
        E --> H["Data Types"]
        E --> I["Addressing Modes"]
        E --> J["Instruction Format"]
    end

    subgraph "Hardware Layer"
        K["CPU Core"] --> L["Control Unit"]
        K --> M["ALU"]
        K --> N["Register File"]
    end

    D --> E
    E --> K

Core Concepts

Opcodes and Operands

Every machine instruction consists of an opcode (operation code) and zero or more operands. The opcode specifies what operation to perform, while operands indicate the data sources and destination.

flowchart LR
    subgraph "Instruction Layout"
        A["Opcode<br/>[7 bits]"] --> B["Operand 1<br/>[5 bits]"] --> C["Operand 2<br/>[5 bits]"] --> D["Destination<br/>[5 bits]"]
    end

Consider the x86 instruction ADD EAX, EBX:

  • ADD is the opcode
  • EAX is the destination operand
  • EBX is the source operand

In 32-bit x86 encoding, this register form can be written as the two bytes 01 D8 in hexadecimal: 01 is the opcode and D8 is the ModRM byte. The exact bytes depend on the operand form and execution mode.

Opcode encoding schemes determine how an instruction’s operation is identified. In the 32-bit base RISC-V format, bits [6:0] hold the opcode; other RISC-V formats use different layouts. AArch64 uses fixed 32-bit instruction formats, while ARM32 has multiple formats. x86 has variable-length encodings: prefixes such as REX or 0x66 may precede an opcode, and 0x0F introduces an extended opcode map. The ISA defines these bytes; how a processor parses them is an implementation detail.

Operand encoding is equally complex. Register operands encode as small integers (3–5 bits) directly in the instruction; x86 uses 3-bit fields in the ModRM byte, with REX prefixes extending some register numbers in 64-bit mode. Immediate values are stored in the instruction for constants, with their size depending on the instruction form. In ModRM addressing, the mod field selects register or memory addressing and the displacement size; r/m identifies a register or addressing form. The ModRM byte is an operand-specifier byte, not a second opcode byte.

The ModRM byte has three fields. The mod field (bits 7–6) and r/m field (bits 2–0) specify whether the operand is a register or memory address; the reg field (bits 5–3) names a register or extends the opcode. For ADD EAX, [EBX+8] in 32-bit mode, the encoding is 03 43 08: 03 is the opcode, 43 is the ModRM byte, and 08 is the displacement. In 43, mod=01 selects an 8-bit displacement, reg=000 selects EAX, and r/m=011 selects EBX as the base. A ModRM byte is part of the instruction encoding; it is not itself an opcode byte. In x86-64 mode, a REX prefix can extend register fields to reach R8–R15. The decoder must parse the instruction’s prefixes and operand bytes to determine its length.

RISC opcode design takes a different path. In the 32-bit base RISC-V instruction format, the opcode is in bits [6:0], and register fields have consistent positions (rd in [11:7], rs1 in [19:15], and rs2 in [24:20]). The optional compressed extension adds 16-bit encodings, so implementations must also identify instruction length. ARM32 has instruction formats with condition-code and opcode fields; AArch64 uses fixed 32-bit instructions. These load/store ISAs generally move data into registers before arithmetic instead of using a memory operand for the arithmetic operation.

RISC vs CISC

RISC (Reduced Instruction Set Computer) designs tend to use regular instruction formats and load/store operations, where arithmetic works on registers. The ISA does not promise that each instruction completes in one clock cycle. A64 and RISC-V are examples of RISC ISAs.

CISC (Complex Instruction Set Computer) philosophy packs complex operations into single instructions. x86 is the dominant CISC architecture, with instructions ranging from simple NOP to the complex ENTER for function prologues.

The instruction forms differ. AArch64 arithmetic operates on registers, so incrementing a 32-bit value through a pointer in X0 can use LDR, ADD, and STR. In x86-64, ADD DWORD PTR [RDX], EAX can read a memory operand, add the register, and write the result with one instruction. This is an instruction-count comparison for these forms; it does not predict their latency or throughput on a particular processor.

Some x86 processors translate instructions into internal micro-operations (μops), but the number and execution behavior are implementation details, not ISA guarantees. Pipeline width, cache sizes, branch prediction, latency, and throughput also vary by processor. Compare a specific processor’s documentation or measurements before drawing performance conclusions from instruction count or encoding alone.

ISA property x86-64 AArch64 RISC-V
Instruction length Variable, 1–15 bytes Fixed, 4 bytes 32-bit base; optional 16-bit C
Arithmetic with memory data Some forms accept a memory operand Load, operate, store Load, operate, store
General-purpose registers 16 31 32 (including x0)
Decode and execution behavior Processor-specific Processor-specific Processor-specific

In practice, the choice comes down to ecosystem and constraints. x86 dominates desktop and server markets where decades of software investment create lock-in. ARM leads in mobile and embedded where power efficiency matters most. RISC-V is appealing when you want an open, customizable architecture without licensing fees — custom silicon, research processors, specialized workloads.

Historical context shapes these architectures. MIPS (1980s) and SPARC (1987) helped establish RISC principles such as regular instruction formats and separating loads and stores from ALU operations. Those design choices did not guarantee single-cycle execution; implementations differed. Meanwhile, x86 (1978) grew from 8-bit to 16-bit to 32-bit to 64-bit, accumulating instructions and addressing modes at each step. ARM came from Acorn computers in 1985 with a clean RISC design, later adopted by Apple for Newton PDAs and then iPhones. RISC-V arrived in 2010 from UC Berkeley as an open ISA, gaining traction in research and embedded markets.

Instruction size depends on the actual operands and encoding mode. For example, GNU as in Intel syntax with a 32-bit target encodes INC DWORD PTR [0x1000] as FF 05 00 10 00 00 (6 bytes). In 64-bit mode the same absolute address form encodes as FF 04 25 00 10 00 00 (7 bytes). These assembler-verified forms follow Intel’s INC encoding entry; they are examples for the stated modes, not a general x86 byte count. See the Intel Software Developer’s Manual.

For AArch64, if X0 already points to the 32-bit value, this non-atomic sequence uses three 4-byte A64 instructions (12 bytes total):

// AArch64 GNU/LLVM assembly syntax; X0 points to a 32-bit value
ldr w1, [x0]
add w1, w1, #1
str w1, [x0]

The byte totals describe these particular instruction forms; code density varies with the operation, addressing mode, compiler, and target. A shorter encoding does not by itself mean a faster operation. The Arm A-profile A64 ISA reference defines the instruction forms used here.

ISA guarantees and microarchitecture behavior are different things. An ISA specifies instruction encodings, architectural registers, and the visible effect of each instruction. It does not specify a processor’s pipeline depth, internal μop count, cache capacity, or general instruction latency. Those depend on the implementation. Intel and Arm manuals define the architectural instruction behavior; processor-specific optimization manuals and measurements describe implementation performance.

Power use and performance per watt depend on the processor implementation, process technology, and workload; they are not guaranteed by the ISA label. A small base ISA can suit constrained designs, while extensions and implementation choices determine what a particular chip supports and how it performs.

Register Architecture

Registers are the fastest memory locations, built directly into the CPU. The register set defines what values can be held and manipulated:

Register Type Purpose Example in x86 Example in ARM
General Purpose Temporary data storage RAX, RBX, RCX, RDX R0-R12
Stack Pointer Points to current stack frame RSP SP
Base Pointer Frame reference RBP FP
Program Counter Next instruction address RIP PC
Status Flags Condition codes EFLAGS CPSR

Special-purpose registers carry specific roles beyond general data storage. The program counter (PC/RIP/PC) holds the address of the currently executing instruction — not the next instruction, because the pipeline increments it during fetch. On x86, PC is not directly readable as a general register; on ARM, PC is readable as a register (typically used only in debug contexts). The stack pointer (SP/ESP/RSP) points to the current top of the stack and adjusts automatically on PUSH/POP/CALL/RET. The base pointer (BP/EBP/RBP) forms a stable frame reference within a function, at a fixed offset from SP throughout the function’s execution. Status flags track condition codes — x86’s EFLAGS packs nine flags (ZF, SF, OF, CF, PF, AF, IF, DF, OF) into one register; ARM’s CPSR and PSTATE hold similar condition state plus process state bits.

Register-file ports, forwarding paths, and execution width are microarchitecture choices. A simple datapath might read two registers and write one result per cycle; larger out-of-order designs use different organizations to feed their execution units. Forwarding can send a result directly to a dependent operation before it is written back to the architectural register file. The number of ports, timing, and bypass paths vary by processor and are not specified by the ISA.

Architectural register counts are part of each ISA. x86-64 exposes 16 general-purpose registers, AArch64 exposes 31, and base RISC-V defines 32 register names with x0 hardwired to zero. Implementations may add physical registers for register renaming; their number, area, and access time are microarchitecture choices.

Calling conventions define how functions exchange data. A calling convention specifies which registers hold parameters (and in what order), which register holds the return value, which registers the callee must preserve across the call, and how the stack frame is laid out. On x86-64 System V ABI, RDI, RSI, RDX, RCX, R8, R9 hold the first six integer parameters in order; RAX holds the return value; RBX, RBP, R12, R13, R14, R15 are callee-saved (the callee must preserve their values). On Microsoft x64 ABI, RCX, RDX, R8, R9 hold the first four parameters, with a mandatory 32-byte shadow space on the stack. Mixing conventions — calling a library compiled with a different convention — causes subtle parameter mismatches and register corruption. These conventions are not part of the ISA itself but are part of the platform ABI.

Addressing Modes

How operands specify their location defines the addressing mode:

  1. Immediate: MOV EAX, 42 — constant value
  2. Register Direct: MOV EAX, EBX — register contains value
  3. Memory Direct: MOV EAX, [0x0040] — absolute address
  4. Register Indirect: MOV EAX, [EBX] — register contains address
  5. Base + Offset: MOV EAX, [EBX + 8] — indexed access
  6. Scaled Index: MOV EAX, [EBX + ESI*4] — array access

Addressing modes trade off encoding flexibility against the instructions needed for common operations. x86 defines memory operands with base, index, scale, and displacement fields; AArch64’s load/store instructions define base-plus-offset forms. These are ISA differences. Their effect on decoder size, area, and speed depends on the processor implementation.

Base+offset versus scaled index serve different access patterns. Base+offset ([EBX+8]) adds a constant offset to a base register, as in a struct field access. Scaled index ([EBX+ESI*4]) multiplies an index by a scale of 1, 2, 4, or 8 before adding it to the base, as in an array access. This x86 address form can avoid a separate shift instruction, though it does not guarantee a faster result on every processor.

PC-relative addressing enables position-independent code (PIC). With PC-relative addressing, the address is computed relative to the current program counter value rather than as an absolute address. A jump instruction B label in ARM encodes as PC + offset — if the code is loaded at a different base address, the same offset still reaches the correct target. This is essential for shared libraries in operating systems, where the same library code is loaded at different virtual addresses in different processes. Without PC-relative addressing, every instruction that references a global variable or code label would need relocation fixups when the library loads. x86 uses PC-relative addressing for jumps (RIP-relative: JMP [RIP+0x10]) but historically used absolute addresses for data, requiring the operating system to perform data relocations. x86-64 improved this with RIP-relative addressing for data as well.

x86 and AArch64 define different memory-address forms. x86 can encode a base register, scaled index, and displacement in one effective address. AArch64 load/store instructions support base-plus-offset forms, including selected register offsets. A programmer may need different instruction sequences for the same data access, but decode cost and speed depend on the particular processor.

Instruction Formats

Instruction encoding varies dramatically between architectures:

x86 Variable Length:

  • Instructions range from 1 to 15 bytes
  • Prefixes can add additional bytes (segment override, operand size, repeat)
  • Complex decoding logic required

ARM Fixed Length:

  • All instructions are 32 bits (ARM mode) or 16 bits (Thumb mode)
  • Consistent decoding pipeline
  • Conditional execution encoded in instruction bits

RISC-V Variable Length (RV64GC):

  • Base instruction is 32 bits
  • Compressed extensions provide 16-bit forms
  • Clean, orthogonal encoding

Fixed-width formats make instruction boundaries straightforward to locate: in AArch64, the next sequential instruction is four bytes later. A variable-length format such as x86 requires identifying each instruction’s length before locating the next one. The amount of hardware, number of pipeline stages, and throughput used to decode an ISA are processor implementation choices, not properties guaranteed by its encoding format.

Prefix bytes in x86 serve multiple purposes and illustrate the encoding complexity. The REX prefix (0x40-0x4F) appears in x86-64 mode to extend the register field from 3 bits to 4 bits, enabling access to registers R8-R15. Operand size prefix (0x66) switches between 16-bit and 32-bit operand sizes — necessary because x86-64 defaults to 32-bit operand size for most instructions. Address size prefix (0x67) switches address calculation to 32-bit mode, enabling 32-bit addressing in long mode. Segment override prefixes (0x2E, 0x36, 0x3E, 0x26, 0x64, 0x65) select which segment register to use for memory addressing. The REPZ prefix (0xF3) modifies string operations to repeat until a counter register reaches zero. Each prefix byte costs an extra byte in the instruction encoding and requires the decoder to perform additional processing.

Thumb mode in ARM provides 16-bit compressed instructions that improve code density for memory-constrained environments. ARM’s 32-bit instruction set wastes bits — register fields and opcode fields have unused encodings. Thumb mode remaps 16-bit encodings to a subset of 32-bit ARM instructions, dropping fields that are always constant for the compressed instructions. A Thumb-encoded function uses 16-bit instructions for common operations (most ALU instructions, branches, loads/stores of small immediates) and can intermix 32-bit Thumb-2 instructions for operations that need the full range. The cost is decode complexity: the processor must decode both 16-bit and 32-bit instructions, determining instruction width on the fly. ARM’s Thumb-2 extensions allow any instruction to be either 16 or 32 bits, requiring the decoder to examine the first half-word to determine whether a second half-word is needed. ARM’s Thumb mode is conceptually similar to x86’s variable-length encoding in that instruction width is not known until decode begins, though the compression ratio is less extreme.

RISC-V compressed extension (RVC) balances code density against decode simplicity. RVC adds 16-bit encodings for a subset of RISC-V instructions, using a compressed format called C Instructions. The C extension reuses the top two bits of every 16-bit instruction to indicate compressed format (00, 01, 10 for different instruction types), leaving 14 bits for the actual instruction encoding. This is less dense than Thumb (which uses variable 16/32-bit encoding) but simpler because the decoder can determine the compressed format from the top bits alone. RVC targets common operations: stack pointer adjustments, load/store with small immediates, conditional branches with short offsets. Complex operations (64-bit arithmetic, floating-point, atomic operations) are not compressed and require the full 32-bit encoding. The result is typical code size reduction of 25-30% compared to pure 32-bit RISC-V, bringing RISC-V’s density closer to ARM Thumb while maintaining the decode simplicity of a RISC-style format.

Production Failure Scenarios

Scenario 1: Spectre and Meltdown Vulnerabilities

Failure: Branch prediction and speculative execution allowed unauthorized memory reads across privilege boundaries. Processors from multiple vendors were affected.

Impact: A malicious process could read memory belonging to other processes or the kernel.

Mitigation:

  • Microcode updates from Intel/AMD/ARM
  • Kernel page table isolation (KPTI) to separate user and kernel page tables
  • Retpoline patches to prevent speculative indirect jumps
  • -mindirect-branch=thunk compiler options for Spectre v2 protection

Scenario 2: Translation Lookaside Buffer (TLB) Shootdowns

Failure: On multiprocessor systems, when one CPU modifies its page tables, all other CPUs must invalidate their TLB entries. Under high core count systems, TLB shootdown storms caused performance degradation.

Impact: Lock contention during context switches, unexpected latency spikes.

Mitigation:

  • Adaptive TLB shootdown algorithms that batch invalidations
  • Hardware-assisted address space identifiers (ASIDs) to avoid full shootdowns
  • Per-core page tables where sharing is minimal

Scenario 3: Memory Order Violations

Failure: Weak memory ordering in ARM processors caused race conditions when code assumed strong ordering (x86 model).

Impact: Subtle data corruption in concurrent code that worked on x86 but failed on ARM servers.

Mitigation:

  • Explicit memory barriers (MFENCE, DMB, ISB instructions)
  • Compiler barriers to prevent reordering
  • Lock-free data structures must use proper atomic operations

Trade-off Table

Dimension x86 (CISC) ARM (RISC) RISC-V (RISC)
Instruction format Variable-length encoding Fixed 32-bit A64 encoding Base 32-bit; optional 16-bit C
Register count 16 general-purpose registers 31 general-purpose registers 32 register names (x0 is zero)
Memory arithmetic Some arithmetic forms accept memory operands Load/store plus register arithmetic Load/store plus register arithmetic
Decode and execution Processor-specific Processor-specific Processor-specific
Market Position Desktop/Server dominant Mobile dominant Open-source emerging
Software Ecosystem Mature, extensive Growing (Apple Silicon) Early, rapidly expanding
Customization None (vendor-controlled) Limited (ARM licensees) Full (open standard)

Implementation Snippet

x86 Assembly: Function Call Convention

// C function we want to inspect
int sum(int a, int b) {
    return a + b;
}
; x86-64 System V ABI, Intel/NASM-style syntax
; Parameters: RDI, RSI, RDX, RCX, R8, R9 (then stack)
; Return value: RAX

sum:
    ; Function prolog
    push    rbp
    mov     rbp, rsp

    ; In the System V AMD64 ABI, the int arguments arrive in EDI and ESI
    mov     eax, edi        ; move a into return register
    add     eax, esi        ; add b to it
    ; Result already in EAX for return

    ; Function epilog
    pop     rbp
    ret

ARM64 Assembly: Same Function

// AArch64, GNU/LLVM syntax; int arguments and return value use W0/W1
// (AAPCS64 assigns the corresponding X0/X1 argument registers.)

sum:
    // Add the low 32-bit int values and return in W0
    add     w0, w0, w1
    ret

Observability Checklist

When debugging ISA-level issues or optimizing performance:

  • CPU Cycle Counters: Use perf stat, rdtsc on x86, or PMCCNTR on ARM to count cycles
  • Instruction retired counter: Verify actual instruction count matches expectations
  • Branch misprediction rate: Check performance counters for mispredicted branches
  • Cache miss rates: L1/L2/L3 hit ratios via hardware counters
  • TLB miss rates: DTLB and ITLB miss counters
  • Pipeline stalls: Monitor for RAW hazards, branch delays
  • Memory ordering violations: Enable DOMON (ARM) or monitor x86 lock contention
  • Microcode version: Ensure latest microcode for security and bug fixes

Tools:

  • perf (Linux): perf stat -e cycles,instructions,branches,branch-misses ./program
  • vtune (Intel): GUI and CLI for profiling
  • arm-trace (ARM): Streamline profiling on ARM targets

Common Pitfalls / Anti-Patterns

Security & Compliance

  1. Code Injection Attacks: Stack-based buffer overflows can overwrite return addresses. Modern mitigations:

    • Stack canaries (-fstack-protector)
    • NX (No-Execute) bit on memory pages
    • ASLR (Address Space Layout Randomization)
  2. Return-Oriented Programming (ROP): Attackers chain existing code fragments. Defenses:

    • CFG (Control Flow Guard) on Windows
    • Intel CET (Control-flow Enforcement Technology)
    • ARM BTI (Branch Target Identification)
  3. Side-Channel Attacks: Timing variations leak information:

    • Spectre variants (speculative execution)
    • Meltdown (out-of-order execution)
    • Rowhammer (DRAM electrical coupling)
    • Mitigation: Kernel isolation, microcode patches, hardware assistance
  4. Compliance Requirements: Regulated environments require specific processor features:

    • FIPS 140-3: Cryptographic modules must use validated instruction sets
    • Common Criteria: Evaluation requires documented ISA subsets
    • DO-178C: Aviation software requires deterministic instruction timing analysis

Programming Pitfalls

  1. Assuming Memory Ordering: x86 has strong memory ordering by default; ARM does not. Never assume operations appear in program order across threads.

  2. Ignoring Alignment: Unaligned access on ARM can cause alignment faults or performance penalties. x86 handles it but slowly.

  3. Using Wrong Operand Size: Mixing 32-bit and 64-bit registers on x86-64 (e.g., mov eax, ebx vs mov rax, rbx) creates different semantics.

  4. Assuming Instruction Timing: Former “rules” like “division is slow” have changed dramatically across CPU generations. Always measure.

  5. Neglecting Stack Alignment: x86-64 ABI requires 16-byte stack alignment at function call. Violation causes crashes on calls to external libraries.

  6. Overusing CMOV: Conditional move prevents branch misprediction but can create hidden stalls when the condition is unpredictable.

Quick Recap Checklist

  • The ISA defines the contract between hardware and software through opcodes, registers, and addressing modes
  • RISC and CISC describe ISA design approaches; internal decoding into micro-operations is an implementation choice
  • x86-64 uses variable-length encoding and 16 general-purpose registers; AArch64 uses 32-bit instructions and 31 general-purpose registers
  • Memory ordering differences between architectures cause real-world bugs in portable concurrent code
  • Speculative execution is a processor implementation behavior involved in vulnerabilities such as Spectre
  • Always use profiling tools that access hardware counters to verify assumptions about instruction performance
  • Stack alignment, register width semantics, and calling conventions differ significantly between architectures

Interview Questions

1. What is the difference between RISC and CISC architectures, and why has the distinction blurred over time?

RISC and CISC describe ISA design approaches. RISC designs often use regular instruction formats and load/store operations; CISC designs may provide more complex instruction forms. Neither approach promises that an instruction completes in one cycle.

Some x86 processors translate instructions into internal micro-operations (μops). That is a microarchitecture choice, not part of the x86 ISA, and it does not establish a general performance ranking between x86 and AArch64.

2. Explain the fetch-decode-execute cycle and how it relates to the instruction set architecture.

The fetch-decode-execute cycle is the fundamental operation of any CPU. First, the fetch phase retrieves the next instruction from memory using the address in the program counter (PC) register, then increments the PC. Second, the decode phase interprets the instruction bits to determine what operation to perform and which operands to use. Third, the execute phase performs the actual computation—accessing registers, performing ALU operations, or memory reads/writes.

The ISA defines instruction encodings, architectural registers, and the visible effects of instructions. It does not prescribe a processor's fetch width, pipeline stages, execution units, or cycle count. Those are implementation choices.

3. What are addressing modes, and why do different architectures support different sets?

Addressing modes specify how instructions locate their operands. Common modes include immediate (constant values embedded in the instruction), register direct (value in a register), and various memory addressing forms like direct (absolute address), indirect (register contains address), and indexed (base plus offset).

Different ISAs define different addressing forms. AArch64 arithmetic uses registers, while its load and store instructions support base registers with immediate or register offsets. x86 also allows memory operands in many arithmetic instructions. The ISA specifies these forms; the complexity and speed of decoding them depend on the processor implementation.

4. How does memory ordering differ between x86 and ARM, and what problems can this cause?

x86 uses strong memory ordering, meaning stores are not reordered with other stores and loads are not reordered with other loads or stores. This makes porting concurrent code from x86 to ARM dangerous—code that appears correct due to implicit ordering can fail on ARM's weak ordering.

ARM uses weak ordering where loads and stores can be reordered by the hardware for performance. This means a load can be reordered with a preceding store, potentially reading stale data. Developers writing lock-free code or concurrent data structures must use explicit memory barriers (DMB, DSB on ARM; MFENCE on x86) to enforce ordering when required.

5. What is the purpose of the stack pointer and base pointer registers in function calls?

The stack pointer (SP) always points to the current top of the stack, where the next push will store data. It automatically adjusts as values are pushed and popped during function calls, returns, and local variable allocation.

The base pointer (BP), also called frame pointer, provides a stable reference point within a function's stack frame. While SP moves during execution, BP remains fixed throughout the function, making it easy to locate function parameters and locals at known offsets from BP. This is essential for debuggers to perform stack unwinding and for exception handling. Modern compilers can omit frame pointers with -fomit-frame-pointer optimization when frame pointers aren't needed for debugging.

6. How does instruction pipelining work and what are the major hazards?

Instruction pipelining overlaps execution of multiple instructions by dividing execution into stages (fetch, decode, execute, memory, write-back). While one instruction is in stage 2, the next can be in stage 1.

Major hazards include:

  • Structural hazards: Hardware cannot support all combinations of instructions in pipeline simultaneously (e.g., single memory port)
  • Data hazards: Instruction depends on result of previous instruction still in pipeline (RAW, WAR, WAW)
  • Control hazards: A branch changes which instruction should be fetched next. A misprediction penalty depends on the processor and workload.

Solutions include forwarding paths, branch prediction, and out-of-order execution to hide dependencies.

7. What is the difference between RISC and CISC, and why have they converged?

RISC and CISC describe ISA design approaches. RISC designs often use regular instruction formats and load/store operations; CISC designs may provide more complex instruction forms. Neither approach promises a particular cycle count.

Some x86 processors translate instructions into internal micro-operations (μops); that translation is not specified by the x86 ISA. Both RISC and CISC processors can use complex pipelines and execution units. Compare particular processor implementations rather than inferring performance from the ISA category.

8. Explain the concept of calling conventions and why they matter.

A calling convention defines how functions exchange data: parameter passing (registers vs stack), return value location, caller/callee-saved register handling, and stack frame layout.

Common conventions include:

  • System V AMD64 ABI: Parameters in RDI, RSI, RDX, RCX, R8, R9, then stack; return in RAX
  • Microsoft x64 ABI: Parameters in RCX, RDX, R8, R9; shadow space on stack
  • ARM64 AAPCS: Parameters in X0-X7; return in X0

Mismatches between caller and callee conventions cause subtle bugs—wrong values returned, registers clobbered, crashes on external library calls. Compiler and language support handle this, but mixing assembly with high-level code requires explicit knowledge.

9. How does the instruction fetch stage work on a modern out-of-order CPU, and what role does the L1 instruction cache play?

Many processors fetch instructions through an instruction cache and buffers, often using branch prediction. The exact design and rates are microarchitecture-specific. For example, one implementation may:

  1. Fetch address calculation: PC points to the next instruction. For sequential flow, PC = PC + instruction_length. For branches, the target comes from the branch predictor.
  2. L1 instruction-cache lookup: A hit or miss changes how long instruction bytes take to reach the decoder. Hit rates and miss costs depend on the processor and workload.
  3. Instruction queue: Fetched bytes or decoded instructions may wait in buffers for decoding and execution. Buffer sizes and fetch width vary by design.
  4. Branch prediction: The fetch unit uses the branch predictor to speculatively fetch down the predicted path, keeping the pipeline fed.

An instruction-cache miss can stall instruction delivery, though an out-of-order processor may continue useful work already in flight. The impact depends on cache hierarchy, prefetching, and the code path.

10. What is the difference between a microcode implementation and a hardwired control unit?

A microcode control unit stores control words in a control store and can use them to sequence datapath operations. Some processors use microcode for some instructions, but which instructions use it is implementation-specific. The ISA describes the result the instruction must produce, not the internal control mechanism.

A hardwired control unit uses combinational logic to generate control signals from instruction bits. Control implementation affects design and performance, but it is not determined by whether the ISA is RISC or CISC.

A processor may combine these approaches. Consult documentation for the specific implementation before making claims about how a particular instruction is internally handled.

11. What is instruction-level parallelism (ILP) and what are the main techniques to exploit it?

Instruction-Level Parallelism (ILP) is the opportunity to execute independent instructions at the same time. Whether a processor can exploit it, and how many operations it handles per cycle, depends on its implementation.

Techniques to exploit ILP:

  • Pipelining: Overlap execution of multiple instructions by dividing execution into stages. A five-stage pipeline is a common teaching model; real implementations vary.
  • Superscalar: Multiple execution units allow dispatching multiple instructions per cycle to different units.
  • Out-of-order execution: Execute instructions in dataflow order rather than program order, filling gaps from cache misses.
  • Speculative execution: Execute instructions before their outcome is known (branch prediction), discarding results if speculation fails.
  • VLIW (Very Long Instruction Word): Compiler bundles independent instructions into a single long instruction word—the compiler does the scheduling.

The limits of ILP are reached when dependencies (data hazards) or branches prevent further parallelism—Amdahl's law governs the achievable speedup.

12. Explain the different privilege modes in modern CPUs (kernel/user, PL0-PL3, EL0-EL3).

Modern CPUs support multiple privilege levels or security rings to isolate the operating system from user applications:

x86-64 ( rings):

  • Ring 0 (kernel): Full hardware access, can execute all instructions, access all memory
  • Ring 3 (user): Restricted instruction set, cannot access hardware directly, limited memory access via page tables
  • Rings 1-2 rarely used (historical: DOS, Windows 3.1)

ARM64 (Exception Levels):

  • EL0: User mode, least privilege
  • EL1: Operating system kernel
  • EL2: Hypervisor (for virtualization)
  • EL3: Secure monitor (TrustZone)

Transitions between levels occur via specific instructions (SYSRET, ERET) or exceptions (interrupts, traps, page faults). Each level has different instruction availability and memory access rules enforced by the MMU.

13. What is the relationship between condition codes, flags registers, and branch instructions?

The flags register (EFLAGS in x86, CPSR in ARM) stores condition codes that reflect the result of the most recent arithmetic or logical operation. Branch instructions read these flags to make decisions.

In x86:

  • ZF (Zero Flag): Set when result is zero
  • SF (Sign Flag): Set when result is negative (MSB=1)
  • OF (Overflow Flag): Set on signed overflow
  • CF (Carry Flag): Set on unsigned overflow

Branch instructions test these: JE (jump if equal = ZF=1), JL (jump if less = SF≠OF), JA (jump if above = CF=0 and ZF=0).

In AArch64, the flags are in the NZCV register (Negative, Zero, Carry, Overflow). Conditional instructions like csel use these flags without branching. Whether that is faster than a branch depends on the processor and surrounding code.

AArch64's cbz (compare and branch if zero) encodes a zero check and branch in one instruction. Whether it is faster than cmp plus b.eq depends on the processor and surrounding code.

14. How does instruction encoding differ between fixed-length and variable-length ISAs?

Fixed-length encoding (for example, AArch64 and the 32-bit base RISC-V instructions): Each instruction in that format is 32 bits, so its next sequential address is four bytes later. RISC-V's compressed extension also defines 16-bit instructions.

Fixed-width formats make instruction boundaries straightforward to determine. They can use more bytes for some simple operations, depending on the ISA and available compressed forms.

Variable-length encoding (used by x86, x87, VAX): Instructions range from 1 to 15 bytes. The opcode might be in byte 1 or may require parsing a ModRM byte first.

Variable-length formats can encode some operations compactly, but the decoder must determine each instruction's length before finding the next boundary. x86-64 uses this format; some processor implementations also cache decoded micro-operations.

15. What are the different addressing modes and when would you use each?

Addressing modes specify how operands locate their data:

  • Immediate: Value embedded in instruction. Use for constants known at compile time.
  • Register direct: Value in a register. Most efficient—use for frequently accessed variables.
  • Memory direct: Absolute address in instruction. Rarely used—hardcodes addresses that may not exist.
  • Register indirect: Register contains address. Good for pointers: mov eax, [ebx].
  • Base + offset: mov eax, [ebx+8]. Good for struct field access: ebx points to struct, 8 is field offset.
  • Indexed: mov eax, [ebx+esi]. Good for array access: ebx=base, esi=index.
  • Scaled indexed: mov eax, [ebx+esi*4]. For arrays of 4-byte elements: index already multiplied.
  • PC-relative: Address relative to PC. Used for jumps and calls: b label in ARM is PC+offset.

ARM primarily supports immediate and register direct plus base+offset. x86 supports all these and more (including segment-relative in legacy modes). The complexity of addressing modes in x86 allows single-instruction memory operations that ARM would need multiple instructions for.

16. What is the purpose of a stack and how is it implemented at the hardware level?

The stack is a LIFO (Last-In-First-Out) memory region used for function calls, local variables, and control flow. It's implemented via a dedicated register (SP/ESP/RSP on x86, SP on ARM) that points to the current top.

On x86-64:

  • PUSH reg: SP -= 8, then store reg at [SP]
  • POP reg: Load from [SP] into reg, then SP += 8
  • CALL addr: Push return address (IP of instruction after CALL), then jump to addr
  • RET: Pop return address into IP

The stack grows downward (toward lower addresses). Each function call pushes the return address and allocates space for locals. The frame pointer (BP/EBP/RBP) provides a stable reference point within each frame.

On ARM64, the stack pointer must maintain 16-byte alignment at call boundaries (AAPCS64 requirement). The STP (store pair) and LDP (load pair) instructions efficiently push/pop registers.

Stack overflow occurs when SP goes beyond the allocated stack region—detected by the OS causing a segmentation fault or stack overflow exception.

17. Explain the difference between big-endian, little-endian, and bi-endian architectures.

Big-endian: The most significant byte is stored at the lowest memory address. Like writing a number with the most significant digit first. Network protocols use big-endian (network byte order).

Little-endian: The least significant byte is stored at the lowest memory address. Like writing a number with the least significant digit first. Intel and AMD processors use little-endian.

Bi-endian: Can operate in either mode. ARM processors support both endianness via a mode bit (CPSR.E). They execute in little-endian by default but can switch. Some older architectures (MIPS, PowerPC) had bi-endian support.

Consider the 32-bit value 0x12345678 at address 0x100:

  • Big-endian: 0x100=0x12, 0x101=0x34, 0x102=0x56, 0x103=0x78
  • Little-endian: 0x100=0x78, 0x101=0x56, 0x102=0x34, 0x103=0x12

When transferring data between systems of different endianness, conversion is required. The htonl()/ntohl() functions on big-endian machines are no-ops, on little-endian machines they swap bytes.

18. What is a register file and what are the trade-offs in its design?

The register file is the set of registers visible to the programmer (architectural registers) plus any internal registers used by the implementation.

Design trade-offs:

  • Number of registers: More architectural registers can reduce spilling, but physical register-file size and timing depend on the implementation. AArch64 defines 31 general-purpose registers; x86-64 defines 16.
  • Port count: Read and write port counts are microarchitecture choices. More ports can feed more operations in parallel, with design costs that depend on the implementation.
  • Read vs write latency: Register access latency varies by processor. Physical register renaming and forwarding are implementation techniques.
  • Width: 32-bit, 64-bit, or even 128-bit for SIMD. Larger registers enable vector operations but increase port count and power.

Register allocation pressure affects compiler code generation. If a function uses more registers than available, the compiler must spill to stack, which is slower.

19. How does branch prediction improve pipeline performance and what are the main prediction techniques?

Without branch prediction, a processor may wait for a branch result before fetching from its target. The resulting cost depends on the processor's pipeline and the branch.

Prediction allows the processor to guess the branch direction and continue fetching speculatively. If the guess is wrong, the pipeline is flushed and execution restarts from the correct path.

Main techniques:

  • Static prediction: Always predict taken or not-taken. Simple but limited accuracy (~35-65%).
  • 1-bit counter: Predict based on last outcome. Two states: branch-taken last time, branch-not-taken last time. Better but still limited.
  • 2-bit counter: Requires two mispredictions to change prediction. More stable, better for loops. Four states: strongly taken, weakly taken, weakly not-taken, strongly not-taken.
  • Two-level adaptive: Branch history table (BHT) tracks patterns for each branch address. Can recognize repeating patterns like alternating branches.
  • Global branch history: A single global register (GHR) records the outcome of the last N branches. Correlates different branches.
  • Perceptron branch predictor: Uses neural network-like weights to combine multiple history sources.

Prediction accuracy and misprediction cost depend on the processor and workload. Use hardware performance counters or processor-specific documentation when those measurements matter.

20. What is the role of the control unit in a CPU and how does it differ from the datapath?

The datapath is the "muscle" of the CPU—the circuits that actually perform computation. It includes:

  • Register file (read/write ports)
  • ALU (arithmetic and logic operations)
  • Multiplexers for selecting inputs
  • buses that move data between components

The control unit is the "brain"—it generates the control signals that tell the datapath what to do. For each instruction, the control unit determines:

  • Which registers to read
  • Which ALU operation to perform
  • Where to route the result
  • Whether to update PC

The control unit's input is the instruction opcode (and sometimes status flags). Its output is a set of binary control signals that select MUX inputs, enable writes, and configure the ALU.

Design approaches:

  • Hardwired: Combinational logic generates control signals from opcode. Fast but complex for complex ISAs.
  • Microcoded: Control signals are stored in ROM and sequenced. More flexible for complex instructions but slower.

In super-scalar out-of-order processors, the control unit is more complex and includes the register rename unit, issue queue, and retirement logic.

Further Reading

Conclusion

The Instruction Set Architecture defines how software communicates with hardware. Whether you’re working with x86, ARM, or RISC-V, understanding opcodes, registers, addressing modes, and instruction formats helps you reason about everything from compiler output to security vulnerabilities.

The differences between architectures (CISC vs RISC, memory ordering, calling conventions) matter when porting code or debugging concurrency issues. RISC and CISC describe instruction-set design; a processor’s internal decoding and execution are implementation choices. The ISA remains the contract software depends on.

Continue your low-level journey by exploring assembly language basics to see how ISA instructions translate to actual code, or study building a simple CPU simulator to implement these concepts hands-on.

Category

Related Posts

ASLR & Stack Protection

Explore ASLR, PIE, stack canaries, and NX on Linux with GCC, then inspect a harmless C program to see what each mitigation does and where it falls short.

#operating-systems #aslr-stack-protection #computer-science

Assembly Language Basics: Writing Code the CPU Understands

Learn x86-64 Linux assembly with the System V ABI: track registers, assemble and run a small program, debug it in GDB, then compare AArch64.

#operating-systems #assembly-language-basics #computer-science

Boolean Logic & Gates

Understanding AND, OR, NOT gates and how they combine into arithmetic logic units — the building blocks of every processor.

#operating-systems #boolean-logic-gates #computer-science