Computer Organization and Architecture with MIPS
Introduction to Computer Organization and Hardware Fundamentals
Under-the-Hood Architectural Knowledge:
- Understanding the internal mechanics of a computer system is analogous to a driver understanding automobile mechanics (the four-cycle engine, distributor, and electrical system); although one can drive without it, the knowledge allows rapid diagnosis of failures and empowers software professionals to produce significantly more efficient code.
- George Neville-Neil addressed the necessity of hardware awareness among software professionals in the Kode Vicious column of the March/April 2021 issue of ACM Queue.
- The MIPS (Microprocessor without Interlocked Pipeline Stages) architecture serves as a primary model because it is simple enough to understand and program while possessing sufficient sophistication for real-world devices such as embedded systems, routers, and video game consoles.
Digital Nature of Computer Devices:
- Modern digital hardware stores and manipulates solely binary values: zeros () and ones ().
- All forms of data—including whole numbers, floating point numbers, textual keyboard characters, digital sound, and raster images—are composed of sequences of binary digits (bits).
- This principle applies universally to desktop computers, laptops, tablets, smartphones, digital cameras, audio players, gaming consoles, and embedded controllers found in automobiles, medical appliances, and home equipment.
The Central Processing Unit (CPU):
- Computations and programmatic decisions governing instruction execution sequences occur within the CPU.
- The primary hardware blocks of a CPU comprise registers, an arithmetic logic unit (ALU), a control unit, and internal interconnections (buses and discrete wires).
- Registers: Dedicated, ultra-fast internal memory storage elements. While accessing random access memory (RAM) can be over slower than accessing CPU hardware, registers provide single-cycle data availability.
- In the MIPS architecture, general registers are wide (one full word) and number in total (designated through ). Register () is hardwired to all zeros () and cannot be modified.
- Program Counter (): A specialized, non-programmable CPU register storing the memory address of the next instruction to be fetched and executed.
- Datapath: The internal collective assembly of components through which data flows and is manipulated: the general register file, memory interfaces, ALU, , control unit, and the routing buses.
Main Memory (Random Access Memory - RAM):
- Main memory serves as proximate storage for active program code and working variables (such as numerical arrays).
- Each byte in the memory space possesses a unique sequential numerical address; memory is thus byte-addressable.
- A MIPS full word consists of (). Consecutive word addresses in MIPS memory differ by (for example, address is immediately followed by word address ).
- Memory is volatile: it requires uninterrupted electrical power to retain binary states. Sudden interruption of electricity empties all stored states, causing immediate data loss.
Peripheral Storage and Input/Output Devices:
- Non-volatile Storage: Devices capable of retaining data without continuous electrical supply.
- Magnetic Disks: Fixed (internal hard drives) or removable rotating platters holding the operating system, applications, and persistent data files.
- Optical Disks: Removable media read and written via lasers (CD, CD-ROM, DVD); data written to optical discs is typically permanent.
- Flash Memory: Solid-state semiconductor storage with no moving mechanical components (USB flash drives, thumb drives, internal non-removable solid-state drives in mobile devices).
- Input and Output Classification (Memory Perspective):
- Input: Data transfer directed into main memory from an external device (keyboards, mice, joysticks).
- Output: Data transfer directed outward from main memory to an external device (printers, audio speakers).
- Bidirectional / Memory-Mapped: Monitors display content continuously from a designated memory block (memory-mapped video); network interfaces (Ethernet, Wi-Fi) and USB ports exchange data in both directions.
Software Abstraction Hierarchy:
- Machine Language: The fundamental binary-encoded instruction sequence (s and s) directly decoded by the CPU. Instructions specify basic operation codes and register or memory operand addresses.
- Assembly Language: A human-readable low-level symbolic representation where operations appear as textual mnemonics (e.g.,
add,sub) and memory locations use symbolic alphanumeric labels. - Assembler: Specialized systems software (such as the Missouri State University MARS simulator) that translates symbolic assembly language source programs into executable binary machine code.
- High-Level Programming Languages: Languages (Java, C++, Visual Basic, Python) allowing compound operational expressions (e.g., ) within a single statement, requiring compilation via a compiler into machine language.
- Operating System (OS): Core software managing computational resources. Key duties include processor time multiplexing across concurrent tasks, managing access to peripheral devices, supervising the permanent filesystem, and expanding physical memory through virtual memory mechanisms. Modern examples include Microsoft Windows, Apple macOS, Linux, Android, and Apple iOS.
Number Systems, Positional Bases, and Representation Schemes
Positional Number Representation:
- Positional number systems, attributed historically to ninth-century Hindu and Arab mathematicians, represent quantities as polynomials of a chosen base :
- In base (decimal), digits range from to . In base (binary), numerals are restricted to and . In base (octal), numerals range from to . In base (hexadecimal), numerals include through augmented by , , , , , and .
Binary Arithmetic Operations:
- Addition rules:
- ( with carry-out of to the next higher positional column)
- ( with carry-out of )
- Subtraction rules:
- after borrowing from the immediately adjacent high-order column (a borrowed becomes a value of in the current column).
Octal and Hexadecimal Bit Grouping:
- Base groups binary strings into clusters of (). When translating binary strings whose total length is not a multiple of , extra bits remain on the high-order (leftmost) end.
- Base groups binary strings into clusters of (). Any leftover bits reside on the leftmost (most significant) boundary.
- Hexadecimal numbers are formally annotated with a base subscript ( or ) or an assembly prefix (
0x321). - In the MIPS architecture, breaking down instructions formatted across fields of lengths bits requires tracking partial-hex boundaries: each or field requires two hexadecimal characters when isolated, but regroups into eight uniform 4-bit nibbles when viewed as a composite word.
Twos Complement Representation of Signed Integers:
- Used across contemporary processor architectures to unify integer addition and subtraction hardware regardless of operand signs.
- The most significant bit (MSB) acts as the sign bit: a leading indicates non-negative values; a leading indicates negative values.
- For an register word, the representable signed range is:
- In a space, the range is () to (); zero is ; negative one () is represented by all ones ().
- An automotive mechanical odometer illustrates twos complement: rolling a brand-new odometer reading of backward by one mile rolls the digits over to , representing .
- Negation (Complement) Algorithms:
- Subtraction from Zero: Compute , assuming an implied high-order borrow.
- Inversion plus One: Form the ones complement by flipping every bit (, ) and add to the result ().
- Right-to-Left Bit Inspection: Scan bits from right to left (least significant to most significant); replicate all zeros until the first is encountered; copy that first unchanged; complement all remaining bits to the left.
Powers of Two and Standard Prefixes:
- Memorized baseline powers:
- Multiplicative binary scales (capitalized to distinguish from decimal prefixes):
- The magnitude of up to is calculated mentally: the tens digit determines the prefix () and the units digit determines the numerical multiplier (). For example, .
- Fundamental exponent laws apply directly:
MIPS Assembly Language Programming
General CPU Register Allocations and Conventions:
- General registers store values and are accessed by number (
$0to$31) or by predefined symbolic functional names: ($0): Hardwired constant .($1): Assembler temporary, reserved exclusively for synthetic pseudo-operation translation.($2 - $3): Subprogram expression evaluation and return values.($4 - $7): Subprogram input arguments/parameters.($8 - $15): Temporary registers; not preserved across subprogram calls.($16 - $23): Saved temporary registers; must be preserved and restored by called functions.($24 - $25): Additional temporary registers.($26 - $27): Reserved for operating system kernel trap handling.($28): Global pointer for static data addressing.($29): Stack pointer referencing the runtime call stack boundary.($30): Frame pointer referencing local subroutine activation frames.($31): Function return address loaded during execution of jump and link.
- General registers store values and are accessed by number (
Assembly Language Syntax:
- Statements follow the canonical syntax:
assembly [label:] mnemonic operand, operand, operand [# comment] - Labels provide symbolic branch and data anchors. Mnemonics identify target machine operations. Operands represent registers, immediate numerical constants, or symbolic memory targets. Comments begin with
#and continue to the end of the line.
- Statements follow the canonical syntax:
Core R-Format Arithmetic Instructions:
add $rd, $rs, rd] = Reg[rt]. Trailing overflows trigger hardware exceptions in twos complement.sub $rd, $rs, rd] = Reg[rt]via twos complement addition of the negated operand:Reg[rt] + 1).slt $rd, $rs, rd] = 1ifReg[rt]under signed comparison; otherwise setsReg[$rd] = 0.
Bitwise Logical Instructions:
and $rd, $rs, rd] = Reg[rs] & Reg[rt]).or $rd, $rs, rd] = Reg[rt]).xor $rd, $rs, rd] = Reg[rt]).nor $rd, $rs, rd] = ~(Reg[rt])).not $rd, $rs: Bitwise complement pseudo-op implemented asnor $rd, $rs, $zerobased on the identity~x = ~(x | 0).- Bit Masking Techniques:
- Clearing bits: Bitwise AND with a mask having zeros at target bit locations (
x & 0 = 0,x & 1 = x). - Setting bits: Bitwise OR with a mask having ones at target bit locations (
x | 1 = 1,x | 0 = x). - Inverting bits: Bitwise XOR with a mask having ones at target bit locations (
x ^ 1 = ~x,x ^ 0 = x). - Symmetric Cryptography Identity:
k ^ m ^ k = menables reversible encryption and decryption via a secret key maskk.
Shift Operations:
sll $rd, $rt, shamt: Shift Left Logical. Moves bits left byshamtpositions, shifting in zeros at the least significant bits. Shifting left by positions performs integer multiplication by .srl $rd, $rt, shamt: Shift Right Logical. Moves bits right byshamtpositions, inserting zeros at the most significant bit. Treats registers as unsigned.sra $rd, $rt, shamt: Shift Right Arithmetic. Moves bits right byshamtpositions, copying the original MSB (sign bit) into vacated high-order bit positions, preserving signed integrity for division by (valid integer division provided no active ones are discarded).
Immediate Format Instructions and Pseudo-Operations:
addi $rt, $rs, constant: Adds a signed immediate value (range to ) to registerrt. Sign-extends the immediate operand to .- Subtraction with a constant is executed using negative constants in
addi(e.g.,addi $a0, $a0, -3). andi $rt, $rs, constant: Zero-extends the 16-bit constant and performs bitwise AND.ori $rt, $rs, constant: Zero-extends the 16-bit constant and performs bitwise OR.xori $rt, $rs, constant: Zero-extends the 16-bit constant and performs bitwise XOR.lui $rt, constant: Load Upper Immediate. Loads a 16-bit constant into bit positions of$rt, clearing bits to zero.li $rd, constant: Load Immediate pseudo-operation. Translated toaddi $rd, $zero, constantfor 16-bit values. For values (e.g.,0x00010003), the assembler expands it into two operations:assembly lui $at, 0x0001 ori $at, $at, 0x0003 move $rd, $rs: Pseudo-operation to duplicate register content, translated toadd $rd, $rs, $zero(oraddu).
Memory Reference and Assembler Directives:
.text: Directs the assembler to place following code within the instruction memory area..data: Directs the assembler to allocate following elements into contiguous data segment memory (starting at address0x10010000in MARS).- Allocation types:
.word( signed integer),.byte( integer),.float( single-precision float),.double( double-precision float),.ascii(character string),.asciiz(null-terminated character string),.space n(allocates an uninitialized buffer of ). lw $rt, label/lw $rt, imm($rs): Load Word. Retrieves a memory value into registerrs] + imm.sw $rt, label/sw $rt, imm($rs): Store Word. Writes value fromrs] + imm.la $rd, label: Load Address pseudo-op. Loads the calculated effective memory address oflabelintoat.
Transfer of Control Architecture:
- Conditional Branching:
beq $rs, $rt, label: Branch tolabelifReg[rt].bne $rs, $rt, label: Branch tolabelifReg[rt].- Pseudo-branches (
blt,ble,bgt,bge) expand to combinations ofsltusing register$atfollowed bybeqorbne:blt $rs, $rt, destexpands toslt $at, $rs, $rtthenbne $at, $zero, dest.ble $rs, $rt, destexpands toslt $at, $rt, $rsthenbeq $at, $zero, dest.bgt $rs, $rt, destexpands toslt $at, $rt, $rsthenbne $at, $zero, dest.bge $rs, $rt, destexpands toslt $at, $rs, $rtthenbeq $at, $zero, dest.
- Unconditional Jumps:
j label: Absolute jump tolabel.jal label: Jump and Link. Writes the address of the immediately sequential instruction (PC + 4) into return register($31) and jumps tolabel.jr rs]; typicallyjr $rato return from subroutines.- Control Flow Patterns:
- One-way Selection (
if): Evaluates condition; conditionally branches around the conditional block to a forward label if false. - Two-way Selection (
if-else): Evaluates condition; conditionally branches to theelseblock if false; theifblock concludes with an unconditional jump (j) to bypass theelseblock. - Pretest Loops (
while): Condition evaluated at the loop head via conditional branch jumping beyond the loop body if false; ends with unconditional jump (j) back to the header. - Posttest Loops (
do-while): Loop body executes at least once; ends with a conditional branch evaluating loop continuation criteria and jumping back to the head if true.
Subroutines, Register Conventions, and the Runtime Stack:
- Calling convention rules specify responsibility for register preservation:
- Subroutine input arguments pass via
. - Output values return via
. - Local preserved registers
must be saved by the called function prior to modification and restored before return. - Temporary registers
must be preserved by the calling function if needed across the call. - Subroutines making nested or recursive calls must save the return address
onto the runtime stack. - The Call Stack:
- A LIFO data structure growing downwards toward lower memory addresses.
- The stack pointer
holds the address of the current top of the stack. - Push operation: Decrements
by per register, then stores values:assembly addi $sp, $sp, -4 sw sp)
Pop operation: Loads values from current stack positions, then increments
:assembly lw sp) addi $sp, $sp, 4 - Modular Scope and Name Conflicts: To eliminate label collision when combining distinct subprogram files, internal labels are explicitly scoped by appending function-specific suffixes (e.g.,
lp_strlen,done_strcmp).
- Modular Scope and Name Conflicts: To eliminate label collision when combining distinct subprogram files, internal labels are explicitly scoped by appending function-specific suffixes (e.g.,
Character and String Processing:
- Strings reside in memory as contiguous arrays of one-byte ASCII characters, terminated by an ending null byte (
0x00). lbu rs): Load Byte Unsigned. Loads an byte from memory into bits of$rt, filling bits with zeros.sb rs): Store Byte. Writes bits of register$rtinto the designated byte memory address.- When stepping through characters of a string, memory pointers increment by , unlike word arrays which increment by .
- Strings reside in memory as contiguous arrays of one-byte ASCII characters, terminated by an ending null byte (
Multiplication and Division Systems:
- Multiplying two integers can produce a product up to long.
- The MIPS CPU incorporates dedicated hardware registers:
HI(storing the upper ) andLO(storing the lower ). mult $rs, $rt: Signed multiplication; product deposited into{HI, LO}.multu $rs, $rt: Unsigned multiplication.mfhi rd.mflo rd.div $rs, $rt: Signed division. Computes integer quotientReg[rt]intoLO, and integer remainderReg[rt]intoHI.divu $rs, $rt: Unsigned division.- Software algorithms for platforms lacking hardware multipliers/dividers include repeated addition/subtraction, or optimized binary shift-and-add / shift-and-subtract methods processing one bit per step across 32 iterations.
Floating Point Computing (Coprocessor 1):
- MIPS manages floating point values via a distinct subsystem: Coprocessor 1.
- Features independent floating point registers named
f31. For double-precision () calculations, registers pair into even-odd groupings (e.g.,f1,f3). - Single-precision operations carry a
.ssuffix; double-precision operations carry a.dsuffix. - Arithmetic instructions:
add.s,sub.s,mul.s,div.s(format:add.s $fd, $fs, $ft). - Transfer operations:
mov.s $fd, $fs,lwc1 rs),swc1 rs). - Comparisons set an internal 1-bit floating-point condition code flag (
cc): c.eq.s $fs, $ft: Setscc = 1if$fs == $ft, else0.c.lt.s $fs, $ft: Setscc = 1if$fs < $ft, else0.c.le.s $fs, $ft: Setscc = 1if$fs <= $ft, else0.- Conditional branching inspects the condition code:
bc1t label: Branches if condition code is true (1).bc1f label: Branches if condition code is false (0).- Type conversions:
cvt.s.w $fd, $fs(converts integer word to float);cvt.w.s $fd, $fs(truncates float to integer word via floor). Rounding to the nearest integer is implemented by adding0.5prior to applyingcvt.w.s.
System Calls via MARS (
syscall):- Invoked by writing a service code into register
and executingsyscall: : Print Integer (argument passed in).: Print Float (argument passed in).: Print String (pointer address passed in).: Read Integer (input integer returned in).: Read Float (input float returned in).: Read String (buffer address passed in, maximum character length in).: Exit / Terminate program execution normally.
- Invoked by writing a service code into register
MIPS Machine Language Formats and Encoding
Primary Instruction Word Formats:
- Every MIPS instruction occupies exactly one full word divided into standardized functional fields.
- Register (R) Format:
- Bit range ():
opcode(always0x00for standard R-format arithmetic/logical operations). - Bit range ():
rs(source register identifier, ). - Bit range ():
rt(second source operand register, ). - Bit range ():
rd(destination register receiving result, ). - Bit range ():
shamt(shift amount, values ). - Bit range ():
funct(function code distinguishing specific operations underopcode = 0). - Ordering caveat: Assembly statements specify operands in the sequence
$rd, $rs, $rt, whereas binary machine words encode them in the sequencers, rt, rd. - Immediate (I) Format:
- Bit range ():
opcode. - Bit range ():
rs(base address register or first source register). - Bit range ():
rt(destination register for loads/immediate operations, or source register for stores). - Bit range ():
immediate(numerical constant, address displacement, or relative branch displacement). - Ordering caveat: Assembly statements specify
$rt, $rs, imm, whereas binary machine words placersbeforert. - Jump (J) Format:
- Bit range ():
opcode(0x02forj,0x03forjal). - Bit range ():
address(target absolute word address).
Encoding Operations and Opcode/Function Specifications:
- R-Format Functions (
opcode = 0x00): add:funct = 0x20sub:funct = 0x22and:funct = 0x24or:funct = 0x25xor:funct = 0x26nor:funct = 0x27slt:funct = 0x2asll:funct = 0x00(rsunused/don't care)srl:funct = 0x02(rsunused/don't care)sra:funct = 0x03(rsunused/don't care)mult:funct = 0x18(rdandshamtunused)div:funct = 0x1a(rdandshamtunused)mfhi:funct = 0x10(rs,rt,shamtunused)mflo:funct = 0x12(rs,rt,shamtunused)jr:funct = 0x08(rt,rd,shamtunused)- I-Format Opcodes:
addi:opcode = 0x08andi:opcode = 0x0cori:opcode = 0x0dxori:opcode = 0x0elui:opcode = 0x0f(rsunused)lw:opcode = 0x23sw:opcode = 0x2blbu:opcode = 0x24sb:opcode = 0x28beq:opcode = 0x04bne:opcode = 0x05lwc1:opcode = 0x31swc1:opcode = 0x39
- R-Format Functions (
Branch and Jump Address Calculations:
- Conditional Branch Offsets:
- Branches use relative word offsets from the instruction following the branch statement (
PC + 4). - Because all instructions occupy (word-aligned), the lowest two bits of an instruction byte address are always
00and are dropped. - Formula:
- Forward branches yield positive offsets; backward branches yield negative offsets (represented in 16-bit twos complement).
- Jump Target Addresses:
- J-format instructions hold a 26-bit absolute word field.
- Formula:
- When executed, the CPU concatenates the high-order 4 bits of the current
PCwith the 26-bit field shifted left by 2 positions (00appended at the bottom):
Floating Point Instruction Formats:
- Floating Point Register (FR) Format:
- Bit range :
opcode = 0x11(17 decimal, denoting Coprocessor 1). - Bit range :
fmt(data type:0x10specifies single-precision float.s). - Bit range :
ft(source operand register). - Bit range :
fs(second source operand register). - Bit range :
fd(destination register). - Bit range :
funct(0x00foradd.s,0x01forsub.s,0x02formul.s,0x03fordiv.s,0x32forc.eq.s,0x3cforc.lt.s,0x3eforc.le.s). - Register order in machine language reverses the assembly syntax: assembly uses
$fd, $fs, $ft, while machine code groupsft, fs, fd. - Floating Point Immediate (FI) Format:
- Used for conditional branches (
bc1t,bc1f). - Bit range :
opcode = 0x11. - Bit range :
fmt = 0x08. - Bit range :
ft(0x01forbc1t,0x00forbc1f). - Bit range :
immediate(relative target branch word offset).
Architectural Design and Construction of a MIPS Assembler
Bootstrapping Concept:
- Bootstrapping is the process of writing an initial rudimentary language translator (assembler or compiler) in a low-level format, and progressively leveraging it to translate richer, more complex versions of itself.
Structural Evolution across Development Stages:
- Version 1a: Translates only core R-format instructions with explicit numeric register specifications (
$0to$31). Excludes labels, shift operations, comments, and pseudo-ops. Directs output straight to memory words. - Version 1b: Introduces support for symbolic register identifiers (
t0,$ra) through lookup against a hardcoded string table of 32 names. - Version 2a: Incorporates basic I-format (
addi,andi,ori) and J-format (j,jal) instructions, plus basic branch instructions (beq,bne).parseIntis enhanced to process optional negative sign flags. - Version 2b: Implements a two-pass assembler structure to resolve memory referencing and branch targets:
- Pass 1: Scans raw source code, identifies symbolic labels, records their memory addresses in a Symbol Table, and converts one-to-one pseudo-operations (
move,li) into native machine equivalents within a temporary buffer (basic). - Pass 2: Processes the
basicbuffer, resolves forward and backward label addresses from the Symbol Table, calculates relative offsets, and generates final binary machine words.
- Version 1a: Translates only core R-format instructions with explicit numeric register specifications (
Component Functional Architecture of the Assembler:
skipCommaWhite: Traverses a character string from a starting memory address; steps past spaces (' '), horizontal tabs ('\t'), and commas (','); returns a pointer positioned at the first non-delimiter byte.isNumeric: Checks whether the character at a given memory location falls within the ASCII interval'0'to'9'( to ); returns1if true,0if false.parseInt: Converts a multi-character ASCII decimal numerical string into a signed binary full-word integer via iterative multiplication by :strcmp: Performs lexicographical character comparison between two memory strings terminated by whitespace or commas; returns zero () if identical.mnemonic: Searches the internal instruction dictionary table (ops_mnemonic) for an operational mnemonic matching the source statement; initializes the output instruction with corresponding opcode and function codes; returns format status codes.reg: Evaluates register text. If the leading character after$is numeric, it callsparseInt; otherwise, it matches the name againstregNames_regusingstrcmpand returns the positional index ().operand: Encapsulates register parsing; shifts the parsed register index leftward using a format-dependent variable shift (sllv) by (forrd), (forrt), or (forrs), and bitwise ORs it into the instruction word under construction.lineEnd: Traverses any residual trailing characters in an assembly statement, asserting that only whitespace, newline characters (' '), or null bytes (0x00) exist prior to advancing to the next statement.
Dependency and Linkage Management:
- In assembly source architecture utilizing
.includedirectives, multiple inclusions of common subroutines cause assembler symbol collision errors ("multiply defined symbols"). - System organization requires strict call-graph discipline: each shared routine source file is included via
.includeexactly once within a single compilation tree.
- In assembly source architecture utilizing
Boolean Algebra, Digital Logic, and Circuit Design
Boolean Algebraic Notation and Precedence:
- Operations:
- AND: Represented by a centered dot or direct variable juxtaposition: .
- OR: Represented by the plus sign: .
- NOT: Represented by a prime mark or overbar: or .
- XOR: Represented by the circled plus sign: .
- Operator Precedence (in the absence of grouping parentheses):
- NOT ()
- AND ()
- OR () and XOR ()
- Operations of equal precedence evaluate from left to right.
Core Axiomatic Identities and Duals:
- The principle of duality dictates that every valid boolean identity remains valid when AND and OR operators are interchanged, and identities and are interchanged.
- Identity Laws: ;
- Negation Laws: ;
- Idempotent Laws: ;
- Constant Laws: ;
- Involution Law:
- Commutative Laws: ;
- Associative Laws: ;
- Distributive Laws: ;
- DeMorgan's Laws: ;
- Absorption Laws: ; ; ;
- Consensus Laws: ;
Karnaugh Map (K-Map) Minimization:
- A two-dimensional representation of a truth table where adjacent cells differ by exactly one binary variable (arranged via Gray Code sequences:
00, 01, 11, 10). - Group Sizing and Adjacency:
- Groups must be rectangular and contain a number of cells that is an integral power of two ().
- Adjacent ones can group horizontally, vertically, wrap across opposing outer boundary edges, or merge across the four outer corners of a grid.
- Variables that change state within an identified group drop out of the resulting simplified algebraic product term.
- Don't-Care Outputs ( or ):
- Unspecified or physically impossible input states assigned arbitrary outputs ( or ).
- During minimization, don't-cares are treated as ones if doing so expands an existing group into a larger power of two; otherwise, they are treated as zeros to avoid generating unnecessary terms.
- A two-dimensional representation of a truth table where adjacent cells differ by exactly one binary variable (arranged via Gray Code sequences:
Fundamental Digital Logic Gates:
- AND Gate: Flat input edge, rounded output nose; outputs only when all inputs are .
- OR Gate: Curved input edge, pointed output tip; outputs only when all inputs are .
- Inverter (NOT): Triangle with an inversion bubble; inverts input state.
- Exclusive OR (XOR) Gate: Double-curved input line, pointed tip; outputs when inputs differ.
- NOR Gate: OR gate followed by an inversion bubble ().
- NAND Gate: AND gate followed by an inversion bubble ().
Schematic Rules for Wires and Buses:
- Crossing wires without a connection point cross freely without electrical contact. A solid dot indicates an electrical junction.
- Contradiction Condition: Connecting two gate outputs together directly creates an indeterminate electrical conflict and is strictly prohibited without intervening multiplexing.
- Buses: Parallel conduits conveying multi-bit signals, represented by thickened lines annotated with their bit width in parentheses (e.g.,
(32)). Multi-bit buses may split into sub-buses (e.g.,[0..7]and[8..31]) or merge into wider aggregates.
Combinational Logic Subsystems:
- Sign-Extend Component: Expands an input bus of width to an output bus of width () by routing the input MSB (the sign bit) across all upper output bits ( through ).
- Decoder (): Takes an selection binary code and drives exactly one of its output lines to , setting all others to .
- Encoder (): The inverse of a decoder. Accepts inputs (assuming only one input is asserted) and produces the corresponding binary number.
- A encoder accepts inputs and produces outputs according to:
- Multiplexer (): Routes one of input buses (each wide) to a single output bus based on a control selector.
- A multiplexer with data inputs and select line is defined by:
- Binary Adders:
- Half Adder: Adds two single-bit inputs (), producing a Sum () and Carry ():
- Full Adder: Adds two single-bit operands () plus an incoming carry ():
- A full adder is constructed from two half adders and an OR gate.
- Ripple-Carry Adder (): Cascades full adders such that of stage connects directly to of stage .
- Twos Complement Overflow Detection: Overflow in signed integer addition occurs if and only if the carry-in into the sign bit ( of MSB) differs from the carry-out of the sign bit ( of MSB):
Sequential Logic Circuits:
- Unlike combinational logic (whose outputs depend entirely on current inputs), sequential circuits incorporate internal memory and state feedback.
- Clock Signal: A square wave oscillating continuously between and . Characterized by its period (cycle duration) and frequency (measured in Hertz, where ).
- SR Latch: Constructed from two cross-coupled NOR gates with inputs Set () and Reset (). When , it retains its existing state. forces state . forces state . The condition is disallowed, as it produces a contradictory state where both and evaluate to .
- Clocked SR Flip-Flop: Augments the SR latch with input AND gates driven by a clock signal, restricting state transitions to intervals where the clock is high ().
- D Flip-Flop: Resolves the undefined condition by routing a single Data input () directly to the Set path, and its inverted complement () to the Reset path. State captures the value of upon clock assertion.
- JK Flip-Flop: Incorporates feedback from the outputs back to the input AND gates. When , the state is set to . When , the state is reset to . When , the flip-flop toggles to its complement ().
- Registers: Formed by grouping D flip-flops in parallel. An enabled register gates the common clock line via a
Loadenable line through an AND gate:Clock_In = Clock & Load. - Finite State Machines (FSM): Sequential systems modeling discrete operational states, transitions driven by external inputs, and outputs. Designed by assigning flip-flop states, mapping a transition table, determining logic expressions for flip-flop inputs via K-maps, and realizing feedback wiring.
Arithmetic and Logic Unit (ALU) Construction
ALU Architectural Specifications:
- The MIPS ALU processes two input buses ( and ) and produces one output bus along with a 1-bit zero indicator ().
- Operations are governed by a 4-bit
Operation Selectline: 0000: Bitwise AND ()0001: Bitwise OR ()0010: Addition ()0110: Subtraction ()0111: Set If Less Than (determines signed relation )1100: Bitwise NOR (
Internal Operational Logic per Bit-Stage ():
- Logical AND: Bitwise AND gate: .
- Logical OR: Bitwise OR gate: .
- Logical NOR: Bitwise OR gate followed by an inverter: .
- Twos Complement Addition: Full adder receiving , and carry-in , producing sum bit and carry-out . For stage , .
- Twos Complement Subtraction: Derived from the algebraic equivalence:
- Each bit of is inverted () via an inverter. In stage , the carry-in is hardwired to (), executing the necessary "plus one" increment.
Output Multiplexing and Composite ALU Layout:
- Each bit-stage routes its candidate results () into a multiplexer driven by the 4-bit
Operation Selectsignal. - The parallel array of 32 multiplexers forms the composite output multiplexer yielding the 32-bit Data Out bus.
- Zero () Flag Synthesis: Indicates whether the ALU Data Out bus equals zero. All 32 output bits enter a wide OR gate, whose output is inverted:
- Set If Less Than Synthesis (
Operation Select = 0111): - Under signed twos complement subtraction (), if , the resulting difference is negative, meaning its sign bit () is .
- A multiplexer selects between the standard negated zero-detect signal and the difference sign bit (), switching to when
Operation Selectequals0111.
- Each bit-stage routes its candidate results () into a multiplexer driven by the 4-bit
Design and Implementation of the MIPS Datapath
Storage Components in the Datapath:
- Register File ():
- Houses 32 general-purpose registers.
- Inputs:
A sel(),B sel(),Write Sel(),Data In(), and a control lineR/W(where and , synchronized with the system clock). - Outputs:
A Out() andB Out(). - Data Memory ():
- Volatile RAM storing application runtime data.
- Inputs:
Address In(),Data In(), andR/Wcontrol. - Output:
Data Out(). - Instruction Memory ():
- Read-only storage for program instruction words.
- Input:
Address Infrom the Program Counter (). - Output:
Instruction Outrouted to the Instruction Register (). - Program Counter (): A 32-bit register providing the memory address of the current instruction.
Subsystem Data Routing and Contradiction Resolution:
- Connecting discrete paths for varied instructions introduces hardware bus contradictions (points where multiple distinct sources feed a common input). Each is resolved using a multiplexer:
- ALU Input B Contradiction (
MUX ALU): - R-Format: Second ALU operand comes from register output
B Out. - Memory Reference (
lw/sw): Second operand comes from the sign-extended 16-bit immediate displacement. - Resolution: A MUX (
MUX ALU), controlled by signalALUB, routes eitherB Out(when1) orSignExtend(imm)(when0) to the ALU B input. - Register File Data In Contradiction (
MUX RF): - R-Format: Register write data originates from the ALU Data Out bus.
- Load Word (
lw): Register write data originates from Data MemoryData Out. - Resolution: A MUX (
MUX RF), controlled by signalRF, selects between ALU output (when0) and Memory output (when1). - Register File Write Select Contradiction (
MUX WS): - R-Format: The destination register is specified by
IR[15..11](rd). - I-Format (
lw,addi): The destination register is specified byIR[20..16](rt). - Resolution: A MUX (
MUX WS), controlled by signalWS, selects betweenrd(when0) andrt(when1). - Program Counter Source Contradictions (
MUX BCandMUX J): - Sequential Execution: Next address is (computed by a dedicated adder).
- Conditional Branch (
beq/bne): Next address is (computed by a second dedicated adder). - Resolution:
MUX BCselects between (input0) and the branch target adder (input1). - Unconditional Jump (
j/jal): Target address is formed fromIR[25..0]padded with the upper bits of . - Resolution:
MUX Jselects between the output ofMUX BC(input1) and the jump address bus (input0).
The Control Unit and Signal Synthesis
Control Unit Architecture:
- Decodes the instruction word and issues control signals across the datapath.
- Inputs:
opcode(IR[31..26], 6 bits) andfunct(IR[5..0], 6 bits). - Primary Control Outputs:
RegW: Register File write control (, ).DW: Data Memory write control (, ).ALUB: ControlsMUX ALU(, ).RF: ControlsMUX RF(, ).WS: ControlsMUX WS(, ).J: ControlsMUX J(, ).BEQ: Indicates a branch-if-equal instruction.BNE: Indicates a branch-if-not-equal instruction.ALUOP: 4-bit operational code routed to the ALU.
Control Signal Decoding Matrix:
| Instruction | Opcode | Funct | RegW | DW | ALUB | RF | WS | J | BEQ | BNE | ALUOP |
|---|---|---|---|---|---|---|---|---|---|---|---|
add | 00x | 20x | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0010 |
sub | 00x | 22x | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0110 |
and | 00x | 24x | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0000 |
or | 00x | 25x | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0001 |
nor | 00x | 27x | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 1100 |
slt | 00x | 2ax | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0111 |
lw | 23x | — | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0010 |
sw | 2bx | — | 1 | 0 | 0 | ? | ? | 1 | 0 | 0 | 0010 |
beq | 04x | — | 1 | 1 | 1 | ? | ? | 1 | 1 | 0 | 0110 |
bne | 05x | — | 1 | 1 | 1 | ? | ? | 1 | 0 | 1 | 0110 |
j | 02x | — | 1 | 1 | ? | ? | ? | 0 | ? | ? | ???? |
Note: Question marks (?) represent don't-care conditions, allowing logic simplification during circuit synthesis.
Branch Decision Logic (
MUX BCSelector):- Subtraction is performed within the ALU for both
beqandbne, driving the Zero flag (). - The control selection line triggering a branch transition in
MUX BCis synthesized as:
- Subtraction is performed within the ALU for both
Logic Expressions for Control Output Lines:
- Let represent the opcode bits, and represent the function bits.
DW(Data Memory Write, active low forsw=101011):BEQ(Opcode000100):BNE(Opcode000101):J(Opcode000010):
The Memory Hierarchy, Caching, and Virtual Memory
The Memory Latency Dilemma:
- CPU arithmetic processing completes in fractional nanoseconds, while dynamic RAM accesses require tens to hundreds of nanoseconds (often a speed differential).
- Without low-latency intermediary structures, execution stalls during memory references.
- Primary memory strategies mitigating latency include pipeline instruction prefetching (fetching instruction queues into arrays of internal registers ahead of the ) and hierarchical caching.
Memory Technology Hierarchy:
| Memory Technology | Typical Usage | Access Speed | Relative Cost | Volatile? |
|---|---|---|---|---|
| FPGA / Flip-Flops | CPU Registers | Fastest | Maximum | Yes |
| SRAM (Static RAM) | Cache Memory | Very Fast | High | Yes |
| DRAM (Dynamic RAM) | Main System Memory (RAM) | Moderate | Moderate | Yes |
| Flash Memory (SSD) | Secondary Storage / Virtual Memory | Slow | Low | No |
| Fixed Magnetic Disk | Hard Drives / Virtual Memory | Very Slow | Low | No |
| Optical Disk (DVD) | Archival Storage | Ultra Slow | Very Low | No |
| Magnetic Tape | Offline Backup | Slowest | Lowest | No |
Direct-Mapped Cache Architecture:
- High-speed, small-capacity SRAM cache mapped to main memory in fixed-size blocks (e.g., ).
- Main memory blocks map directly to specific cache blocks via modulo arithmetic:
- A memory byte address divides into three fields:
tag: Upper bits identifying which specific RAM block currently occupies the cache slot.cache block: Middle bits indexing the target cache line.byte offset: Lower bits specifying the addressed byte within the block.- Cache Hit vs. Miss:
- Hit: Tag matching confirms the requested block is present; data access completes with zero memory delay.
- Miss: Tag mismatch requires fetching the entire containing block from main RAM, overwriting the cache entry.
- Write Policies:
- Write-Through: Every memory write updates the cache block and the backing DRAM simultaneously.
- Write-Back (with Dirty Bit): Writes modify only the cache block, setting a 1-bit
dirty bit. The block is written back to main memory only when it is displaced by a cache miss.
Associative Cache Architecture:
- Groups cache blocks into sets; an set associative cache organizes blocks into sets containing blocks each. (A 1-way cache is functionally direct-mapped).
- Address breakdown consists of:
tag,cache set, andbyte offset. - A given RAM block maps to a designated set, but can be placed in any available block within that set, dramatically mitigating conflict misses caused by blocks competing for the identical cache slot.
- Block Replacement Strategies:
- Least Recently Used (LRU): Tracks access history and replaces the block within the set that has gone unreferenced the longest.
- First-In, First-Out (FIFO): Evicts the block that has resided in the set the longest time.
- Random: Selects an eviction candidate at random, preventing systemic failure modes.
- Thrashing: Pathological operational state where contiguous access patterns cause repetitive, unending block evictions, driving miss rates toward .
Virtual Memory Architecture:
- Extends available memory beyond physical RAM limits by using secondary magnetic disks or solid-state storage as backing swap space.
- Physical memory and swap files are partitioned into units called pages (typically or ).
- Page Table: An operating system lookup table indexed by the virtual page number. Translates virtual addresses to physical RAM page frames or flags a page fault if the page resides strictly on secondary storage.
- Page Fault Handling: A page fault triggers an interrupt halting user-thread execution, initiates slow disk retrieval of the missing page into a vacant or evicted RAM page frame, updates the Page Table, and restarts the instruction.
- Similar to caches, page management uses a
dirty bitto avoid writing unaltered pages back to disk upon eviction, and relies on LRU or FIFO page-replacement policies.
Locality Principles and Program Performance
The Principle of Locality:
- Program performance through caching and virtual memory depends heavily on locality of reference.
- Temporal Locality: Memory locations accessed recently have a high probability of being accessed again in the near future (e.g., loop variables, subroutine addresses).
- Spatial Locality: Memory locations positioned close to recently accessed addresses have a high probability of being accessed shortly thereafter (e.g., sequential instruction execution, contiguous array indexing).
Data Locality vs. Instruction Locality:
- Instruction Locality: Preserved by sequential code execution and tight, compact loop structures. Broken by long-distance branch tables, unpredictable dynamic jumps, or scattered subroutines.
- Data Locality: Preserved when algorithms iterate linearly across contiguous data structures.
Algorithmic Implications and Performance Impacts:
- Multi-dimensional arrays are allocated in row-major order (contiguous rows placed end-to-end in linear memory addresses).
- Traversing a large two-dimensional matrix row by row processes memory sequentially, maximizing spatial locality and cache hits.
- Traversing the identical matrix column by column incurs an address leap of an entire row width per element, potentially causing a cache miss on every access and degrading performance by several orders of magnitude.
- Similarly, linear sequential array scans run significantly faster than random access patterns across the same data set.
Alternative Computer Architectures
The Classical Von Neumann Model:
- Formulated by John von Neumann in 1945, defining the stored-program computer:
- A central processing unit containing an Arithmetic Logic Unit and working registers.
- A control unit featuring an Instruction Register and Program Counter.
- A unified or separated primary memory storing data and program instructions.
- External non-volatile secondary storage.
- Input and output mechanisms.
Instruction Set Architecture (ISA) Address Classifications:
- Zero-Address Architecture (Stack Machine):
- Instructions contain no explicit operand addresses. Operands reside on an internal hardware/memory stack.
- Operations pop the top two stack values and push the calculated result back onto the stack.
- Used by systems like the Burroughs B-Machine series (circa 1970).
- Evaluating :
assembly Push a Push b Sub # Pops b, pops a, pushes a - b Push c Add # Pops c, pops a - b, pushes (a - b) + c Pop x
One-Address Architecture (Accumulator Machine):
- Instructions contain a single memory address. A dedicated CPU register, the accumulator (
Acc), serves as the implicit left operand and result destination. - Represented by early minicomputers such as the DEC PDP-8 (circa 1970).
- Evaluating :
assembly Clr # Acc = 0 Add b # Acc = b Add c # Acc = b + c Neg # Acc = -(b + c) Add a # Acc = a - (b + c) Store x
- Instructions contain a single memory address. A dedicated CPU register, the accumulator (
Two-Address Architecture:
- Instructions specify two operands; the first operand serves as both a source and the final destination (
op1 = op1 OP op2). - Common in mainframe architectures (IBM 360/370) and Intel x86 microprocessors.
- Evaluating :
assembly Load r1, a # r1 = a Sub r1, b # r1 = a - b Add r1, c # r1 = (a - b) + c Store r1, x
- Instructions specify two operands; the first operand serves as both a source and the final destination (
Three-Address Architecture:
- Instructions designate two explicit source operands and an independent destination operand (
dest = src1 OP src2). - Standard across modern RISC designs, including MIPS and ARM.
- Evaluating :
assembly Load r1, a Load r2, b Load r3, c Add r3, r2, r3 # r3 = b + c Sub r3, r1, r3 # r3 = a - (b + c) Store r3, x
- Instructions designate two explicit source operands and an independent destination operand (
Memory Addressing Modes:
- Direct Addressing: The instruction word contains the absolute memory address of the operand.
- Indirect Addressing: The instruction word references a memory pointer word, which holds the target operand address.
- Base-Displacement Addressing: Effective address is the arithmetic sum of a general base register plus an immediate offset. Facilitates relocatable code necessary for multiprogrammed operating systems.
- Base-Index-Displacement Addressing: Effective address combines a base register, an index register, and an immediate displacement:
The ARM (Advanced RISC Machine) Architecture:
- Developed in the 1980s by Acorn Computers; a dominant 32-bit/64-bit load-store RISC architecture.
- Features 32 registers (
X0toX31, whereX31/XZRis hardwired to zero). Conventions designateX0..X7for arguments/returns,X19..X27as callee-saved,X28as Stack Pointer (SP),X29as Frame Pointer (FP), andX30as Link Register (LR). - Instruction formats include R, I, D (Data transfer), B (Branch), CB (Conditional Branch), and IW (Wide Immediate).
- Memory access requires explicit load/store operations:
LDUR/STUR(unscaled) andLDR/STR(scaled by word size). - Condition Codes and Flags:
- ALU operations appended with an
S(e.g.,ADDS,SUBS) update four hardware status flags:- (Negative): Set if MSB of result is .
- (Zero): Set if all bits of result are .
- (Overflow): Set if signed integer twos complement overflow occurs.
- (Carry): Set if an unsigned carry-out occurs from the MSB.
- Conditional branches evaluate these flags:
B.EQtestsB.NEtestsB.LTtests
B.GEtestsB.LEtestsB.GTtests- Derivation of
B.GTcondition: When subtracting , overflow can invert the expected sign of the result. Truth table analysis yields the logic equation:
- Derivation of
The Intel x86 / Pentium Architecture:
- Historically grounded in the 8086, 8088, 286, 386, 486, Pentium, and subsequent Core architectures. Highly backward compatible.
- Classified as a Complex Instruction Set Computer (CISC) using a two-address model.
- Non-orthogonal architecture: instructions exhibit asymmetries regarding which registers and addressing modes can pair with specific operations.
- Core Registers ( Extended Names):
EAX: Accumulator for operations and function results (sub-register:AX,AH,AL).EBX: Base register for pointer addressing (BX).ECX: Counter for loops and variable bit-shifts (CX,CL).EDX: Data register; arithmetic overflow/multiplier extension (DX).EBP: Base Pointer (BP).ESI: Source Index for memory streaming (SI).EDI: Destination Index for memory streaming (DI).ESP: Stack Pointer (SP).- Pentium Addressing Modes:
- The effective address incorporates an optional scaling factor ():
- Instructions:
- Data transfer:
mov dest, src(handles register-to-register, memory-to-register, immediate-to-register, and register-to-memory);lea(Load Effective Address). - Arithmetic:
add,sub,inc,dec,cmp(evaluates subtraction, setting flags without saving the difference). - Multiplication/Division:
mul/imulanddiv/idivimplicitly utilize the(EDX, EAX)register pair to hold double-length results. - Shifts and Rotates:
shl/sal(shift left),shr(logical shift right),sar(arithmetic shift right preserving sign),rol(rotate circular left),ror(rotate circular right). EFLAGSregister holds status flags:OF(Overflow),SF(Sign),ZF(Zero),PF(Parity, asserted if low-order byte holds an even number of ones),CF(Carry).
The MARS Environment and Reference Instruction Tables
The MARS Execution Environment:
- A Java-based development platform simulating the MIPS32 architecture.
- Interface Panes:
- Text Segment Pane: Displays raw assembly source statements, translated machine instructions, and intermediate basic code with their hexadecimal addresses.
- Registers Pane: Shows the real-time contents of the 32 general-purpose registers, plus
PC,HI, andLO. - Data Segment Pane: Inspects allocated data memory beginning at address
0x10010000. - Run I/O Pane: Serves as the system console, displaying execution output and capturing keyboard input.
- Operational Controls: Assemble (
F3), Run / Go (F5), Single-Step (F7), Reset (F12), and interactive breakpoint insertion.
MIPS Core Instruction Set Summary:
| Instruction | Mnemonic | Format | Syntax | Machine Code (Hex) | Semantics |
|---|---|---|---|---|---|
| Add | add | R | add $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 20 | Reg[rs] + Reg[$rt] |
| Add Immediate | addi | I | addi $rt, $rs, imm | 08 / rs / rt / imm | Reg[rs] + imm |
| And | and | R | and $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 24 | Reg[rs] & Reg[$rt] |
| And Immediate | andi | I | andi $rt, $rs, imm | 0c / rs / rt / imm | Reg[rs] & imm |
| Branch Equal | beq | I | beq $rs, $rt, addr | 04 / rs / rt / addr | if ($rs == $rt) PC = Target |
| Branch Not Equal | bne | I | bne $rs, $rt, addr | 05 / rs / rt / addr | if ($rs != $rt) PC = Target |
| Jump | j | J | j target | 02 / target | PC = JumpAddress |
| Jump and Link | jal | J | jal target | 03 / target | $ra = PC + 4; PC = Target |
| Jump Register | jr | R | jr $rs | 00 / rs / 00 / 00 / 00 / 08 | PC = Reg[$rs] |
| Load Byte Unsigned | lbu | I | lbu rs) | 24 / rs / rt / d | Reg[$rt] = Mem[rs + d][0..7] |
| Load Upper Imm | lui | I | lui $rt, imm | 0f / 00 / rt / imm | Reg[$rt][16..31] = imm |
| Load Word | lw | I | lw rs) | 23 / rs / rt / d | Reg[$rt] = Mem[rs + d] |
| Nor | nor | R | nor $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 27 | Reg[rs] | Reg[$rt]) |
| Or | or | R | or $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 25 | Reg[rs] | Reg[$rt] |
| Or Immediate | ori | I | ori $rt, $rs, imm | 0d / rs / rt / imm | Reg[rs] | imm |
| Set If Less Than | slt | R | slt $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 2a | Reg[rs] < Reg[$rt]) ? 1 : 0 |
| Shift Left Logical | sll | R | sll $rd, $rt, shamt | 00 / 00 / rt / rd / shamt / 00 | Reg[rt] << shamt |
| Shift Right Logical | srl | R | srl $rd, $rt, shamt | 00 / 00 / rt / rd / shamt / 02 | Reg[rt] >>> shamt |
| Shift Right Arith | sra | R | sra $rd, $rt, shamt | 00 / 00 / rt / rd / shamt / 03 | Reg[rt] >> shamt |
| Store Byte | sb | I | sb rs) | 28 / rs / rt / d | Mem[rs + d][0..7] = Reg[$rt] |
| Store Word | sw | I | sw rs) | 2b / rs / rt / d | Mem[rs + d] = Reg[$rt] |
| Subtract | sub | R | sub $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 22 | Reg[rs] - Reg[$rt] |
| Xor | xor | R | xor $rd, $rs, $rt | 00 / rs / rt / rd / 00 / 26 | Reg[rs] ^ Reg[$rt] |
| Xor Immediate | xori | I | xori $rt, $rs, imm | 0e / rs / rt / imm | Reg[rs] ^ imm |
| Multiply | mult | R | mult $rs, $rt | 00 / rs / rt / 00 / 00 / 18 | {HI, LO} = Reg[rt] |
| Divide | div | R | div $rs, $rt | 00 / rs / rt / 00 / 00 / 1a | LO = $rs / $rt; HI = $rs % $rt |
| Move From Hi | mfhi | R | mfhi $rd | 00 / 00 / 00 / rd / 00 / 10 | Reg[$rd] = HI |
| Move From Lo | mflo | R | mflo $rd | 00 / 00 / 00 / rd / 00 / 12 | Reg[$rd] = LO |
- MIPS Floating Point Instructions (Coprocessor 1):
| Instruction | Mnemonic | Format | Syntax | Machine Code (Hex) | Semantics |
|---|---|---|---|---|---|
| Add Single | add.s | FR | add.s $fd, $fs, $ft | 11 / 10 / ft / fs / fd / 00 | FpReg[fs] + FpReg[$ft] |
| Sub Single | sub.s | FR | sub.s $fd, $fs, $ft | 11 / 10 / ft / fs / fd / 01 | FpReg[fs] - FpReg[$ft] |
| Mul Single | mul.s | FR | mul.s $fd, $fs, $ft | 11 / 10 / ft / fs / fd / 02 | FpReg[fs] * FpReg[$ft] |
| Div Single | div.s | FR | div.s $fd, $fs, $ft | 11 / 10 / ft / fs / fd / 03 | FpReg[fs] / FpReg[$ft] |
| Load Word Coproc 1 | lwc1 | I | lwc1 rs) | 31 / rs / ft / d | FpReg[$ft] = Mem[rs + d] |
| Store Word Coproc 1 | swc1 | I | swc1 rs) | 39 / rs / ft / d | Mem[rs + d] = FpReg[$ft] |
| Branch FP True | bc1t | FI | bc1t addr | 11 / 08 / 01 / addr | if (FP_condition == 1) PC = Target |
| Branch FP False | bc1f | FI | bc1f addr | 11 / 08 / 00 / addr | if (FP_condition == 0) PC = Target |
| Compare Float Equal | c.eq.s | FR | c.eq.s $fs, $ft | 11 / 10 / ft / fs / 00 / 32 | FP_condition = ($fs == $ft) |
| Compare Float Less Equal | c.le.s | FR | c.le.s $fs, $ft | 11 / 10 / ft / fs / 00 / 3e | FP_condition = ($fs <= $ft) |
| Compare Float Less Than | c.lt.s | FR | c.lt.s $fs, $ft | 11 / 10 / ft / fs / 00 / 3c | FP_condition = ($fs < $ft) |
- Common Supported Pseudo-Operations:
| Pseudo-Op | Mnemonic | Representative Syntax | Equivalent Machine Translation |
|---|---|---|---|
| Load Immediate | li | li $rd, imm | addi $rd, $zero, imm (or lui + ori) |
| Load Address | la | la $rd, label | lui $at, upper(addr) followed by ori $rd, $at, lower(addr) |
| Move | move | move $rd, $rs | add $rd, $rs, $zero |
| Bitwise NOT | not | not $rd, $rs | nor $rd, $rs, $zero |
| Negate | neg | neg $rd, $rs | sub $rd, $zero, $rs |
| Branch Unconditional | b | b label | beq $zero, $zero, label |
| Branch Equal Zero | beqz | beqz $rs, label | beq $rs, $zero, label |
| Branch Less Than | blt | blt $rs, $rt, label | slt $at, $rs, $rt followed by bne $at, $zero, label |
| Branch Greater Than | bgt | bgt $rs, $rt, label | slt $at, $rt, $rs followed by bne $at, $zero, label |
| Branch Less/Equal | ble | ble $rs, $rt, label | slt $at, $rt, $rs followed by beq $at, $zero, label |
| Branch Greater/Equal | bge | bge $rs, $rt, label | slt $at, $rs, $rt followed by beq $at, $zero, label |
| Divide Three-Operand | div | div $rd, $rs, $rt | div $rs, $rt followed by mflo $rd |
| Remainder Three-Op | rem | rem $rd, $rs, $rt | div $rs, $rt followed by mfhi $rd |