19. Processor Architecture, MIPS Assembly, and Performance Optimization
Memory Architecture and the Stored-Program Concept
Memory Agnosticism:
Computer memory is fundamentally agnostic to the semantics of its stored contents.
Memory hardware makes no operational distinction between program instructions and data; all information is stored uniformly as arbitrary sequences of binary digits (bits: and ) organized into bytes.
The von Neumann Model and the Stored-Program Concept:
Under the von Neumann architecture, both executing programs and the data operated upon reside concurrently within the same physical memory space.
This structural paradigm is formally termed the stored-program concept.
Memory Layout and Content Varieties:
Machine Code (Binaries): Encoded as pure binary sequences (s and s). This encompasses system tools and application binaries such as accounting software, text editors, and compilers.
Compilers: Translators such as GCC or g++ exist in memory purely as machine code binaries.
Application Data: Stored alongside code, such as payroll database records utilized by accounting programs or manuscript text manipulated by an editor.
Source Code: High-level source code (such as C programs) is initially stored as ASCII text files. Each character is mapped to an () binary pattern before eventual compilation into machine binary.
Programs Operating on Programs:
Programs can take other programs as their direct data inputs.
A compiler takes a high-level source code file as its input data and outputs a machine-readable binary file.
Linkers and Executable Generation:
Linkers are operating system utilities that integrate multiple distinct binary object files into a single, cohesive executable binary file (e.g., an
.exefile).In standard C programming, routines such as mathematical functions (, ) are not written from scratch; rather, header files like
math.hare declared at the beginning of the source file.The compiler translates the source file (e.g.,
myprogram.c) into a user binary, after which the linker merges that user binary with the pre-compiled binary code of the included standard runtime libraries.
Binary Compatibility and Instruction Set Architecture (ISA) Standardization
Definition of Binary Compatibility:
Binary compatibility is the property of an architecture that permits an executable binary program compiled for an earlier processor implementation to execute without modification or recompilation on subsequent processor models within the same architectural genre.
Examples across Processor Families:
Processors such as the MIPS architecture or Apple Silicon M-series chips (Apple M2, M3, M4, and M5) implement this principle.
A program compiled for an Apple M2 processor will execute directly on an Apple M5 processor, exhibiting backward compatibility.
Economic and Practical Rationales:
Customer Base Retention: Forcing users to repurchase or manually recompile software applications whenever hardware is upgraded risks alienating users.
Proprietary and Closed-Source Software: Commercial vendors (e.g., Microsoft with its Office suite) do not distribute source code to end users. If backward compatibility were broken, end users would be unable to recompile their software and would be forced to purchase vendor upgrades.
Architectural Trade-Offs and Performance Penalties:
Suboptimal Execution: Successive processor generations introduce architectural enhancements, optimized execution pipelines, expanded instruction sets, and superior hardware accelerators (e.g., improved graphics engines).
Because a binary compiled for an older architecture (e.g., Apple M2) lacks instructions that target newer architectural features, running that binary on a newer processor (e.g., Apple M5) results in suboptimal execution that fails to exploit modern hardware features.
Application Divergence: While everyday productivity tasks (like word processing) suffer negligibly from missing new graphics features, performance-sensitive workloads (such as modern gaming) run noticeably slower or experience performance bottlenecks unless recompiled or upgraded.
Standardization via Instruction Set Supersets:
Binary compatibility requires backward-compatible ISA standardization, wherein each successive architecture implements an instruction set that is a mathematical superset of its predecessor:
The newer generation architecture supports every instruction present in the legacy architecture, while incorporating supplementary instructions and capabilities.
Intel employs the same superset standardization strategy across its x86 processor lines.
Bitwise Logical Operations in MIPS
Purpose of Bitwise Instructions:
MIPS provides specific instructions to manipulate individual bits or arbitrary bitfields within a standard register word.
Shift Operations:
Shift Left Logical (
sll):Shifts all bits within a source register to the left by a specified shift amount (
shamt), filling the vacated low-order bit positions on the right with zeros.The shift amount ranges from to bits.
Shifting left by bit positions multiplies the original unsigned numerical value by a factor of .
Shift Right Logical (
srl):Shifts all bits within a source register to the right by a specified shift amount, filling the vacated high-order bit positions on the left with zeros while discarding the lowest bits.
Shifting right by bit positions performs integer division of the value by a factor of .
Bitwise AND (
and):Primary Function: Bit masking (applying an AND mask) to isolate and preserve a targeted subset of bits while clearing all remaining bits to .
Masking Logic: The mask register contains s in bit positions designated for preservation and s in bit positions designated for clearing.
Extraction Example: To extract the four most significant bits of register into register , a mask register is populated with in the four highest-order bit positions and s across the remaining bits. Computing the bitwise AND between and isolates the target bits in .
Image Processing Analogy: Cropping a digital image uses a two-dimensional bitmask where pixels inside the crop boundary are retained and outer pixels are forced to zero.
Bitwise OR (
or):Primary Function: Bit insertion and bit setting, forcing targeted bits within a register to while leaving all remaining bits entirely unaltered.
Masking Logic: The mask register contains s in bit positions that must be set to , and s in bit positions where existing values must be preserved.
Bitwise Inversion and the MIPS NOR Instruction:
Inversion Logic: A logical NOT operation flips every individual bit ( and ), producing a bitwise complement.
Hardware Minimization: MIPS omits a dedicated hardware
notinstruction to reduce instruction set and datapath complexity, providing thenor(NOT OR) instruction instead.Implementing Inversion using
nor:Self-NOR: Performing a NOR on a register with itself computes its complement, based on the Boolean equivalence .
Zero-Register NOR: Performing a NOR between the source register and the constant zero register () also computes its complement, based on the Boolean equivalence .
MIPS Syntax:
nor $t0, $t1, $t1ornor $t0, $t1, $zero.
Applications in Digital Media, Entertainment, and Gaming:
Modern computing cycles are predominantly consumed by multimedia editing, audio engineering, video streaming, and gaming rather than simple numerical calculations.
Digital Image Processing: Inverting black-and-white bitmap pixels via bitwise NOT operations generates photographic negative images (dark pixels become light, and light pixels become dark).
Audio and Video Production: Computerized splicing, track mixing, and graphic layer masking depend directly on underlying bitwise logic and masking instructions.
Conditional Operations and Control Flow Implementation
Control Flow Instructions:
Branch if Equal (
beq):Syntax:
beq rs, rt, L1Operational semantics: Evaluates whether the contents of register equal the contents of register . If , program control branches to the instruction labeled
L1; otherwise, execution proceeds sequentially to the immediate next instruction.
Branch if Not Equal (
bne):Syntax:
bne rs, rt, L1Operational semantics: Evaluates whether the contents of register do not equal the contents of register . If , control branches to the instruction labeled
L1; otherwise, execution proceeds sequentially.
Unconditional Jump (
j):Syntax:
j L1Operational semantics: Immediately transfers control unconditionally to the instruction at
L1, functionally equivalent to agotostatement in high-level C.
Symbolic Labels:
Labels (such as
L1,Else, orExit) act as human-readable alphanumeric placeholders representing physical instruction addresses in memory.The assembler subsequently resolves and translates these symbolic labels into concrete binary memory addresses.
Compiling High-Level If-Else Statements:
High-Level Code Example:
if (i == j) f = g + h; else f = g - h;
Register Allocations:
Variable mapped to register
Variable mapped to register
Variable mapped to register
Variable mapped to register
Variable mapped to register
Formulation 1: Inverted Condition using
bne:Instruction 1:
bne $s3, $s4, Else(if , branch directly to theElselabel).Instruction 2:
add $s0, $s1, $s2(executes the true path: ).Instruction 3:
j Exit(unconditional jump over the false path to preserve mutual exclusivity).Instruction 4:
Else: sub $s0, $s1, $s2(executes the false path: ).Instruction 5:
Exit:(subsequent sequential code).
Formulation 2: Direct Condition using
beq:Instruction 1:
beq $s3, $s4, If_Block(if , branch to theIf_Blocklabel).Instruction 2:
sub $s0, $s1, $s2(executes the false path: ).Instruction 3:
j Exit(skips the true path).Instruction 4:
If_Block: add $s0, $s1, $s2(executes the true path: ).Instruction 5:
Exit:(subsequent sequential code).
Generalized Block Structures and Nesting:
Conditional branches scale to arbitrary statement blocks (
if-blockandelse-block).Branch statements can be nested hierarchically within other branch blocks, directly mapping to nested conditional structures in high-level programming.
Array Indexing and Loop Translation in Assembly
High-Level While Loop Construct:
Target Statement:
while (save[i] == k) i += 1;Program Intent: Traverses consecutive elements of integer array
savestarting at index , incrementing until encountering an element whose value does not equal .
Register Mappings:
Array index variable mapped to register
Comparison variable mapped to register
Base address of array
savemapped to register
Array Addressing Arithmetic in Byte-Addressable Memory:
MIPS architecture uses byte addressing.
Standard integer elements occupy () each.
Element Offsets:
Element
save[0]resides at base memory addressElement
save[1]resides at addressElement
save[2]resides at addressIn general, element
save[i]resides at byte address
Optimization of Index Scaling via Bit Shifting:
Multiplying index by the word size using standard integer multiplication instructions requires multiple processor clock cycles.
Because , shifting index register left by bit positions performs multiplication by in a single clock cycle.
Step-by-Step Loop Assembly Implementation:
Label:
Loop:sll $t1, $s3, 2(computes byte offset: )add $t1, $t1, $s6(computes effective physical memory address:lw t1)(loads the array elementsave[i]from memory address into temporary register using an offset of )bne $t0, $s5, Exit(evaluates condition: ifsave[i] != k, branches out of the loop toExit)addi $s3, $s3, 1(increments index variable: )j Loop(unconditionally jumps back toLoopto process the next iteration)Label:
Exit:(points to the subsequent instruction following loop termination)
Basic Blocks and Cache Preloading Optimization
Strict Definition of a Basic Block:
A basic block is a contiguous sequence of program instructions that satisfies two structural invariants:
It contains no embedded branch instructions anywhere within its body, except potentially at the very last instruction.
It contains no branch targets (entry labels) anywhere within its body, except at the very first instruction.
Execution Invariant:
Whenever program execution enters the initial instruction of a basic block (either sequentially or via a branch), every subsequent instruction within that block is guaranteed to execute sequentially to completion.
Compiler Detection and Cache Preloading:
Optimizing compilers analyze control flow graphs to partition code into basic blocks.
Instruction Cache Preloading: When the initial instruction of an identified basic block is fetched from memory, the memory hierarchy preloads (prefetches) the entire set of instructions comprising that basic block into the high-speed L1 instruction cache.
Latency Reduction: Memory access latency represents a significant fraction of total instruction execution time. Prefetching an entire basic block prevents repeated main memory fetch penalties for subsequent instructions, maximizing system throughput.
Illustrative Analogies:
Nightstand Book Reading Analogy: An individual reading a multi-volume book series with a nightstand that holds three books will place the current book, its direct sequel, and the third volume on the nightstand simultaneously. Once the first book is finished, the sequel is accessed immediately without walking to the primary bookshelf.
Web Page Hyperlink Analogy: A primary web page is an HTML document. Its basic block analog corresponds to all web pages hyperlinked directly from that initial page. Prefetching those linked pages into local cache before the user clicks on them eliminates network latency.
Cache Capacity Constraints:
If a basic block exceeds available cache line capacity, compilers and memory controllers preload as many instructions of the block as the cache can accommodate.
Set on Less Than (SLT) and Hardware Design Trade-Offs
The Set on Less Than (
slt) Instruction:Syntax:
slt rd, rs, rtOperational Semantics: Evaluates whether the signed value in register is strictly less than the signed value in register .
If , destination register is set to .
If , destination register is cleared to .
Synthesizing Relational Branch Operations:
To compile relational conditions such as
if (s1 < s2) goto L;, MIPS pairssltwith an equality branch instruction:Step 1:
slt $t0, $s1, $s2(evaluates comparison; sets if true, if false).Step 2:
bne $t0, $zero, L(branches to labelLif register ).
Hardware Architectural Trade-Offs:
Absence of Complex Branch Instructions: MIPS deliberately omits dedicated instructions such as
blt(branch on less than) orbge(branch on greater than or equal to).Circuit Complexity and Propagation Delays: Testing for equality or inequality (
beq,bne) requires fast, shallow XOR/XNOR logic gates. In contrast, checking relational inequalities ( or ) requires arithmetic subtraction and sign/overflow bit evaluation, which incurs substantially greater gate delay.Clock Period Determination: The global processor clock period is constrained by the critical path of the slowest instruction in the execution pipeline. Introducing complex, slow branch instructions would force hardware designers to lengthen the global clock cycle, penalizing the execution speed of all instructions.
Execution Frequency Realities: Statistical profiling reveals that equality and inequality branches (
beq,bne) are overwhelmingly the most common branch conditions encountered in real-world software.Architectural Decision: MIPS preserves a fast system clock by restricting branch instructions to simple equality checks, synthesizing less frequent relational tests using a two-instruction combination (
sltpaired withbneorbeq).
Questions and Discussion
Bitmask Formulation for High-Order Bit Extraction:
Query: How is an AND mask configured to extract exclusively the four most significant bits of register into register while clearing all other bits?
Response: The mask register must be populated with binary s across the target bit positions (the four most significant bits) and binary s across all remaining bit positions. Performing
and $t0, $t1, $t2isolates the target bits while clearing all others to zero.
Video Production Facilities:
Query: Has anyone visited the movie production facilities, such as the digital studios located at the University of Georgia (UGA)?
Response: Student Trevor confirmed familiarity. Digital studios illustrate how modern computing is centered around digital media, track splicing, audio mixing, and graphical manipulation.
Video Game Creation and Cognitive Skills:
Query: Do students actively build their own video games or primarily play existing games?
Response: A student reported engaging exclusively as a player. Game development is highly recommended because it exercises both halves of the brain simultaneously: the analytical programming side and the creative, artistic design side.
Branch Condition Inversion and Block Association:
Query: Can an if-block or else-block be targeted interchangeably using either
beqorbne, or is a programmer constrained to use an if-block exclusively withbeqand an else-block withbne?Response: A programmer is not restricted. The choice depends entirely on the formulation of the high-level conditional expression. If the original high-level condition is
if (i != j), thenbnebranches directly to the if-block. Either instruction can target either block by adjusting the branch condition.
Nesting Capabilities of Branch Instructions:
Query: Can conditional branch operations such as
beqandbnebe nested inside one another?Response: Yes, branch instructions can be nested hierarchically. Just as high-level languages permit nested
ifstatements, assembly routines can place branch instructions within code blocks governed by preceding branches.
Index Multiplier Bit Shift Discrepancy:
Query: When calculating array byte offsets for word-sized elements (), why is the index shifted left by bit positions rather than by bit positions?
Response: A shift left by bits scales a value by . Because the word size is , and , the required power of two is . Shifting by multiplies the index by . Shifting by bits would erroneously multiply the value by .
Basic Block Size and Cache Capacity Constraints:
Query: Are all basic blocks preloaded into the cache in their entirety, or only a subset?
Response: Preloading depends on the size of the basic block relative to available cache space. If a basic block is exceptionally large, it will not fit entirely in the cache. In such instances, the system preloads as many sequential instructions of the basic block as cache capacity permits.
Web Caching Analog to Basic Blocks:
Query: In web caching technologies, what constitutes the structural equivalent of a basic block for a given HTML web page?
Response: The equivalent consists of all the pages that are directly linked on that primary web page. Preloading those linked pages anticipates user navigation and eliminates network latency, just as prefetching a basic block eliminates memory latency.