Module I: Performance, Pipelining & Exception Handling

Simple Answers & Key Points · 39 Questions

1. Define: Benchmark programs.

Benchmark programs are standardized applications, workloads, or suites of programs specifically designed to evaluate, measure, and compare the performance of different computer systems or components (like CPUs, GPUs, or memory).

Key Characteristics (Key Detail):

  • Objective Measurement: They provide an objective baseline. Because the exact same source code is compiled and run on different architectures, the resulting execution times directly reflect the hardware/compiler performance differences.
  • Real-World Representation: Modern benchmarks (like SPEC CPU suites) consist of real-world applications (e.g., GCC compiler, video compression, AI physics simulations) rather than synthetic, artificial loops (like Dhrystone or Whetstone). This ensures the metric reflects actual user experience.
  • Workload Variety: A good benchmark suite includes both integer-heavy (SPECint) and floating-point-heavy (SPECfp) programs to test different Execution Units of the processor.
  • Normalization: Results are often normalized against a reference machine to produce a dimensionless ratio, making it easier to say "Processor A is 1.5x faster than the reference."

2. How do we measure performance?

Measuring performance in computer architecture relies heavily on the perspective of the user versus the perspective of the system administrator. It is fundamentally measured using two main metrics: Execution Time and Throughput.

1. Execution Time (Response Time or Latency):

  • This is the total time required for the computer to complete a specific task, including disk accesses, memory accesses, I/O activities, and operating system overhead.
  • From a user's perspective, this is the most critical metric. Lower execution time equals higher performance.
  • Performance = 1 / Execution Time. If Computer X is 'n' times faster than Computer Y, then: Execution Time(Y) / Execution Time(X) = n.

2. CPU Execution Time:

  • A more precise metric for processor designers. It isolates the time the CPU spends actually computing a specific program, ignoring I/O and time spent running other programs.
  • CPU Time = Instruction Count × Cycles Per Instruction (CPI) × Clock Cycle Time

3. Throughput (Bandwidth):

  • This is a measure of the total amount of work completed in a given unit of time (e.g., transactions per second, jobs per hour).
  • Datacenters and server administrators prioritize throughput over individual response time.

3. Computers A and B implement the same ISA. A: 250ps clock, CPI=2.0. B: 500ps clock, CPI=1.2. Which is faster and by how much?

To determine which computer is faster, we must calculate the CPU Execution Time for both machines. Since they implement the exact same Instruction Set Architecture (ISA), the Instruction Count (IC) required to run the same program will be identical for both machines.

Step 1: State the Formula

Execution Time = Instruction Count (IC) × CPI × Clock Cycle Time

Step 2: Calculate Execution Time for Computer A

  • Clock Cycle Time (A) = 250 ps
  • CPI (A) = 2.0
  • Time (A) = IC × 2.0 × 250 ps = 500 × IC ps

Step 3: Calculate Execution Time for Computer B

  • Clock Cycle Time (B) = 500 ps
  • CPI (B) = 1.2
  • Time (B) = IC × 1.2 × 500 ps = 600 × IC ps

Step 4: Compare and Calculate Speedup

  • Computer A takes 500 units of time, while Computer B takes 600 units. Because 500 < 600, Computer A is faster.
  • To find out by how much, we use the relative performance ratio:
    Speedup = Execution Time (B) / Execution Time (A)
    Speedup = (600 × IC) / (500 × IC) = 1.2

Conclusion: Computer A is 1.2 times faster (or 20% faster) than Computer B.

4. Explain Latency and Throughput.

Latency and Throughput are the two fundamental metrics used to define system performance, and they often trade off against one another.

Latency (Response Time):

  • Definition: The total time elapsed between the initiation of a single task and its completion.
  • Analogy: The time it takes for a single car to travel from city A to city B on a highway.
  • Importance: Crucial for interactive applications (e.g., gaming, desktop applications) where the user waits for a response.
  • Measurement: Usually measured in seconds, milliseconds (ms), or nanoseconds (ns).

Throughput (Bandwidth):

  • Definition: The total number of tasks completed within a specific unit of time.
  • Analogy: The total number of cars that arrive at city B per hour. You can increase throughput by adding more lanes to the highway, even if the speed limit (latency) remains exactly the same.
  • Importance: Crucial for servers, batch processing, and database systems.
  • Measurement: Measured in tasks per second, gigabytes per second (GB/s), etc.

Relationship in Pipelining: Pipelining a processor increases Throughput (more instructions complete per clock cycle) but usually slightly degrades individual instruction Latency due to the overhead of pipeline registers and clock skew.

5. State the factors which affect the performance of Computer Systems.

The performance of a computer system is not dictated by hardware alone; it is a complex interplay of hardware, architecture, and software. The classic CPU performance equation highlights three primary factors, but there are others:

CPU Time = Instruction Count × CPI × Clock Cycle Time
  • 1. Algorithm & Program (Affects Instruction Count): A more efficient algorithm (e.g., O(N log N) instead of O(N²)) drastically reduces the total number of instructions the CPU must execute.
  • 2. Compiler Optimizations (Affects Instruction Count & CPI): A high-quality compiler can translate high-level code into fewer machine instructions. It can also schedule instructions to avoid pipeline hazards, thereby lowering the average CPI.
  • 3. Instruction Set Architecture - ISA (Affects Instruction Count & Clock Cycle Time): CISC architectures (like x86) have fewer but more complex instructions. RISC architectures (like ARM) have more, but simpler, instructions that allow for faster clock speeds.
  • 4. Processor Organization / Pipelining (Affects CPI): Techniques like deep pipelining, superscalar execution, out-of-order execution, and branch prediction aim to bring the ideal CPI down to 1.0 or even lower (IPC > 1).
  • 5. Hardware Technology (Affects Clock Cycle Time): The physical manufacturing process (e.g., 3nm vs 7nm silicon nodes) directly dictates how fast the transistors can switch, determining the maximum clock frequency (GHz).
  • 6. Memory Hierarchy (Affects CPI): Even the fastest processor will stall if it has to wait for slow RAM. Large, fast L1/L2/L3 caches reduce the "Memory Stall Cycles" penalty, significantly lowering the effective CPI.

6. Explain CPU Clock Time and CPU execution time.

These two terms are fundamental to understanding processor speeds and represent the base units of the CPU performance equation.

CPU Clock Time (Clock Cycle Time or Period):

  • Definition: The time duration of one complete clock cycle. It is the basic heartbeat of the processor's synchronous logic. All internal operations are synchronized to this clock.
  • Relation to Frequency: It is the inverse of the Clock Rate (Frequency).
    Clock Cycle Time = 1 / Clock Rate.
  • Example: If a processor operates at 4 GHz (4 billion cycles per second), its Clock Cycle Time is 1 / (4 × 10^9) = 0.25 nanoseconds (250 ps).

CPU Execution Time:

  • Definition: The total actual, physical time the CPU spends computing a specific task. It completely ignores time the CPU spends waiting for I/O operations or executing other background operating system tasks.
  • Formula:
    CPU Execution Time = Total CPU Clock Cycles for Program × Clock Cycle Time
    Because Total Cycles = Instruction Count × Average CPI, this expands to:
    CPU Execution Time = Instruction Count × CPI / Clock Rate
  • Significance: This is the ultimate metric for processor designers. To lower CPU Execution Time, designers must decrease the Instruction Count, decrease the CPI, or increase the Clock Rate (without negatively impacting the other two).

7. What is Amdahl's law?

Amdahl's Law is a fundamental principle in computer architecture used to find the maximum expected improvement (speedup) to an overall system when only a fraction of the system is improved.

The Core Concept:

The law states that the overall performance gain is strictly limited by the portion of the execution time that cannot be improved. You suffer from diminishing returns if you optimize only one part of the code while ignoring the rest.

The Formula:

Speedup(overall) = 1 / [ (1 - F) + (F / S) ]
  • F (Fraction Enhanced): The fraction of the original execution time that can be affected by the enhancement (0 ≤ F ≤ 1).
  • S (Speedup Enhanced): The speedup factor achieved on that specific fraction (S > 1).
  • (1 - F): The fraction of time that remains completely unaffected (the sequential bottleneck).

Example Application:

Suppose a program spends 80% of its time doing floating-point (FP) math, and 20% doing integer logic. You invent a new FP unit that is 4 times faster.

  • F = 0.80 (80%)
  • S = 4 (4x speedup)
  • Speedup = 1 / [ (1 - 0.8) + (0.8 / 4) ] = 1 / [ 0.2 + 0.2 ] = 1 / 0.4 = 2.5x overall speedup.

Even though the FP unit is 4x faster, the overall system is only 2.5x faster because of the 20% unoptimized integer code. If S approached infinity, the max speedup is bounded by 1/(1-F) = 1/0.2 = 5x.

8. Explain temporal and spatial locality.

The Principle of Locality states that programs do not access all memory addresses uniformly; instead, they tend to access a relatively small portion of the address space at any given instant. This principle is the entire foundation upon which Cache Memory is built.

1. Temporal Locality (Locality in Time):

  • Definition: If a memory location is referenced once, there is a very high probability that the exact same location will be referenced again in the near future.
  • Programming Reason: This is caused by loops and function calls. Variables used as loop counters (e.g., int i) or accumulators (e.g., sum += x) are accessed repeatedly over a short time span.
  • Cache Exploitation: Caches exploit this by keeping recently accessed data blocks inside the fast SRAM cache, assuming they will be needed again shortly.

2. Spatial Locality (Locality in Space):

  • Definition: If a memory location is referenced, there is a very high probability that memory locations with sequential or physically adjacent addresses will be referenced in the near future.
  • Programming Reason: This is caused by array traversals and sequential instruction execution. When a program processes an array A[i], it will soon access A[i+1]. Furthermore, programs execute instructions sequentially unless a branch occurs.
  • Cache Exploitation: Caches exploit this by not just bringing in the single requested byte from memory, but fetching an entire Cache Block (e.g., 64 bytes) at once. When the CPU asks for the next adjacent byte, it is already loaded in the cache.

9. Explain the different types of hazards.

In a pipelined processor, a Hazard is a condition that prevents the next instruction from entering its designated pipeline stage in the current clock cycle, necessitating a stall (pipeline bubble). There are three main classes of hazards:

1. Structural Hazards (Resource Conflicts):

  • Cause: The hardware does not have enough resources to support all the instructions currently executing in the pipeline in the same clock cycle.
  • Example: If a processor has only one physical memory port, an instruction in the Instruction Fetch (IF) stage cannot read memory at the exact same time an older instruction in the Memory Access (MEM) stage is trying to read/write data.

2. Data Hazards (Data Dependencies):

  • Cause: An instruction depends on the result of a previous instruction, but that result has not yet been computed and written back to the register file.
  • Example (RAW - Read After Write):
    ADD R1, R2, R3 (Writes to R1 in WB stage)
    SUB R4, R1, R5 (Reads R1 in ID stage)
    The SUB instruction attempts to read R1 before the ADD instruction has written the new value to it, causing a True Data Hazard.

3. Control Hazards (Branch Hazards):

  • Cause: The pipeline makes decisions on what instructions to fetch next based on the assumption that a conditional branch will not be taken. If the branch is taken, the pipeline fetched the wrong instructions.
  • Example: A BEQ (Branch if Equal) instruction determines its target address and condition outcome in the EX or ID stage. By that time, 1 or 2 incorrect sequential instructions have already been fetched into the IF and ID stages and must be flushed.

10. How can data hazards be avoided or mitigated?

Data hazards (specifically Read-After-Write, or True Dependencies) occur when an instruction needs a value that is still flowing through the pipeline. They can be mitigated using three primary techniques:

1. Forwarding (or Bypassing):

  • Hardware Solution: This is the most effective method. Extra hardware multiplexers and datapaths are added to route the output of the ALU (from the EX/MEM pipeline register) directly back to the input of the ALU for the next instruction.
  • Result: The dependent instruction receives the data immediately, bypassing the slow write-back-to-register process, completely eliminating the stall for standard arithmetic dependencies.

2. Pipeline Interlocking (Hardware Stalls):

  • Hardware Solution: Not all hazards can be forwarded. For example, a Load-Use Data Hazard occurs when a LOAD instruction fetches data in the MEM stage, but the very next instruction needs it in the EX stage. Forwarding goes backward in time, which is impossible.
  • Result: Hardware detection logic forces a 1-cycle stall (a "bubble" or NOP) in the pipeline to delay the dependent instruction until the data can be forwarded from the MEM/WB register.

3. Compiler Instruction Scheduling (Software Solution):

  • Software Solution: The compiler analyzes the code at compile-time and attempts to reorder instructions. It finds independent instructions and places them between the data-producing instruction and the data-consuming instruction.
  • Result: This naturally separates the dependent instructions by enough clock cycles that the hardware stall (interlock) is no longer necessary.

11. What is a hazard?

Definition: In computer architecture, particularly in instruction pipelining, a hazard is a situation or condition that prevents the next instruction in the instruction stream from executing during its designated clock cycle.

Detailed Implications:

  • Pipeline Disruption: Pipelining relies on a steady, continuous flow of instructions. A hazard disrupts this flow.
  • Stalls and Bubbles: When a hazard cannot be resolved dynamically via forwarding, the processor must issue a stall. A stall effectively injects a No-Operation (NOP), often called a "bubble", into the pipeline stages.
  • Performance Degradation: Every stall cycle increases the effective CPI (Cycles Per Instruction) of the program above the ideal CPI of 1.0. Therefore, hazards directly reduce the instruction throughput and overall speedup achieved by pipelining.
  • Classification: As noted previously, hazards are strictly classified into Structural (hardware limits), Data (operand dependencies), and Control (branching) hazards.

12. What are the different ways of handling hazards?

Processor designers and compiler writers use a combination of hardware and software techniques to handle hazards and minimize their performance impact:

Handling Structural Hazards:

  • Resource Duplication: Add more hardware. For example, use a Harvard Architecture (separate instruction cache and data cache) so IF and MEM stages don't collide on a single memory port.
  • Stalling: If resources cannot be duplicated, the hardware forces the younger instruction to wait.

Handling Data Hazards:

  • Forwarding/Bypassing: Adding internal data paths to pass ALU results backward in the pipeline to dependent instructions.
  • Interlocking (Stalling): Hardware detects unavoidable hazards (like Load-Use) and inserts a bubble.
  • Code Scheduling: The compiler reorders instructions to physically separate dependencies.

Handling Control Hazards:

  • Assume Branch Not Taken: The simplest hardware simply keeps fetching sequentially. If the branch is taken, it flushes the pipeline.
  • Branch Prediction: Hardware guesses whether the branch will be taken (using Branch History Tables). If correct, zero penalty.
  • Delayed Branch: The compiler moves a safe, independent instruction into the "branch delay slot" (the cycle immediately following the branch). The hardware executes this slot regardless of the branch outcome, preventing a wasted cycle.

13. What is the impact of data hazards and structural hazards on pipeline performance?

Both data and structural hazards negatively impact pipeline performance by introducing stall cycles, which directly degrades the instruction throughput.

Mathematical Impact:

  • The theoretical maximum speedup of a pipeline is equal to the number of pipeline stages (k). This assumes an ideal CPI of 1.0.
  • However, the actual Speedup formula is:
    Speedup = Pipeline Depth / (1 + Pipeline Stall Cycles per Instruction)
  • Effective CPI: Hazards increase the Effective CPI. Effective CPI = Ideal CPI (1) + Stall Cycles/Instruction.

Specific Impacts:

  • Structural Hazards: Because they represent a fundamental lack of hardware, they guarantee a stall every time the conflict occurs. For example, if memory isn't separated into Instruction and Data caches, every single Load/Store instruction will stall the Instruction Fetch stage, drastically lowering performance.
  • Data Hazards: If unmitigated by forwarding, every RAW dependency would cause a 2 or 3 cycle stall, virtually eliminating the benefit of pipelining. Even with forwarding, Load-Use hazards force a mandatory 1-cycle stall, which degrades performance by 10-15% in integer workloads.

14. What is branch prediction, and how does it help reduce control hazards?

Branch prediction is a sophisticated optimization technique where the processor's hardware attempts to guess the outcome of a conditional branch (e.g., an if statement or a for loop condition) before the condition is actually evaluated in the execution stage.

How it works:

  • When a branch instruction is fetched, the predictor looks at historical data. If the branch is at the end of a loop, it has likely been taken 99 times in a row. The predictor will guess "Taken".
  • The processor immediately begins fetching and executing instructions from the predicted target address speculatively.

How it reduces control hazards:

  • If the prediction is correct: The pipeline remains full. There are zero stall cycles, and the control hazard penalty is entirely eliminated.
  • If the prediction is incorrect (Misprediction): The processor must undo the speculative work. It flushes the incorrectly fetched instructions from the pipeline and resumes fetching from the correct address. This incurs a misprediction penalty (e.g., 2-3 cycles in simple processors, up to 15+ in deep pipelines).

Because modern dynamic branch predictors (like two-bit predictors or tournament predictors) achieve >95% accuracy, they effectively eliminate the vast majority of control hazard stalls.

15. Explain the pipeline process. What are pipeline stages typically involved in instruction execution?

Pipelining is an implementation technique where multiple instructions are overlapped in execution. It is analogous to an automobile assembly line: a car doesn't wait for the previous car to be completely finished before it starts; instead, different stations work on different cars simultaneously.

To achieve this, the execution of a single instruction is divided into distinct, isolated steps called stages. Each stage is separated by hardware registers (pipeline registers) to hold data between clock cycles.

The Classic 5-Stage RISC Pipeline:

  1. Instruction Fetch (IF): The CPU sends the Program Counter (PC) to the Instruction Memory/Cache and fetches the instruction. The PC is incremented (PC + 4).
  2. Instruction Decode / Register Read (ID): The control unit decodes the fetched instruction to determine what operation to perform. Simultaneously, the required source operands are read from the Register File.
  3. Execution / Effective Address (EX): The ALU performs the arithmetic or logical operation. For load/store instructions, the ALU calculates the effective memory address (Base Register + Offset).
  4. Memory Access (MEM): If the instruction is a Load, data is read from the Data Cache. If it is a Store, data is written to the Data Cache. For arithmetic instructions, this stage does nothing.
  5. Write-Back (WB): The final result (either from the ALU or from Memory) is written back into the destination register in the Register File.

16. Explain the stages of an instruction pipeline.

(Note: This is a direct continuation and expansion of Question 15). In a classic 5-stage MIPS/RISC architecture, the stages operate precisely on the rising edge of the clock cycle:

  • 1. IF (Instruction Fetch): Uses the PC to index the Instruction Cache. Retrieves the 32-bit instruction word. Places it into the IF/ID pipeline register. Updates PC to PC+4.
  • 2. ID (Instruction Decode): The hardware looks at the opcode bits (e.g., top 6 bits) to generate control signals. It reads registers rs and rt from the register file. It sign-extends the 16-bit immediate value to 32 bits. All this data is placed into the ID/EX pipeline register.
  • 3. EX (Execution): The Arithmetic Logic Unit (ALU) does the heavy lifting. It either calculates arithmetic (ADD, SUB), logic (AND, OR), or calculates a memory address for Load/Stores. It also determines if a branch condition is met. Output goes to EX/MEM register.
  • 4. MEM (Memory Access): Active only for Data Transfer instructions. Reads from Data Cache (for loads) or writes to Data Cache (for stores). Other instructions pass their ALU result passively through this stage into the MEM/WB register.
  • 5. WB (Write Back): The data—either the ALU result or the memory read result—is routed to the Register File and written to the destination register (rd or rt).

By dividing execution into these 5 stages, a pipeline can process 5 different instructions simultaneously, one in each stage.

17. What are the challenges in implementing instruction pipelines?

Implementing a robust, high-performance pipeline involves significant hardware complexity. Key challenges include:

  • 1. Balancing Stage Delays: The clock cycle time of the entire processor is dictated by the slowest pipeline stage. If the EX stage takes 200ps but the MEM stage takes 500ps, the clock cycle must be set to 500ps, wasting 300ps in the EX stage. Designing logic to balance latency perfectly across stages is immensely difficult.
  • 2. Hazard Resolution Logic: Implementing Forwarding requires massive data multiplexers connecting almost every stage back to the ALU. Detecting hazards requires complex combinatorial logic that compares destination registers of older instructions with source registers of incoming instructions.
  • 3. Precise Exceptions/Interrupts: When an exception (like page fault) occurs in the MEM stage for Instruction A, Instructions B, C, and D are already partially executed in earlier stages. The hardware must perfectly halt Instruction A, flush B, C, and D, handle the exception, and then flawlessly restart from Instruction A. This "Precise State" management is notoriously complex.
  • 4. Power Dissipation and Clock Skew: Pipelining requires inserting hundreds of pipeline registers, all connected to the global clock tree. Driving this massive clock tree consumes significant power and causes "clock skew" (the clock signal arriving at different registers at slightly different times).

18. Why is instruction pipelining less effective for certain instruction sets?

Instruction pipelining is highly effective for RISC (Reduced Instruction Set Computer) architectures (like ARM or MIPS), but historically much less effective for CISC (Complex Instruction Set Computer) architectures (like older x86).

Reasons CISC impedes pipelining:

  • Variable Instruction Lengths: CISC instructions can vary from 1 byte to 15 bytes. A pipeline's IF (Fetch) stage doesn't know where the next instruction begins until it fully decodes the current one, breaking the smooth flow of the fetch stage.
  • Variable Execution Times: In RISC, almost all instructions take exactly 1 cycle in the EX stage. In CISC, an instruction like "String Move" might take 100 cycles to execute in the EX stage, completely stalling the pipeline behind it and destroying throughput.
  • Complex Addressing Modes: CISC allows memory operands directly in ALU instructions (e.g., ADD R1, [Memory_Address]). This forces the instruction to undergo Address Calculation, Memory Fetch, AND Execution all within the same pipeline instruction flow, making it impossible to map neatly onto a standard 5-stage pipeline without massive stalls.

Note: Modern x86 processors solve this by having a complex hardware decoder at the front-end that translates ugly CISC instructions into clean, RISC-like "micro-operations" (uOps) which are then pipelined efficiently.

19. How does pipelining improve CPU performance?

Pipelining improves performance fundamentally by increasing Instruction Throughput—the number of instructions completing per unit of time—rather than decreasing the latency of any individual instruction.

The Mechanism of Improvement:

  • In a non-pipelined, single-cycle processor, the clock cycle must be long enough to accommodate the entire instruction fetch, decode, execute, memory, and write-back sequence sequentially (e.g., 1000ps). Only one instruction finishes every 1000ps.
  • In a pipelined processor, the hardware is chopped into 5 stages separated by registers. The clock cycle only needs to be as long as the longest individual stage (e.g., 200ps).
  • Because there are 5 stages, up to 5 instructions can be processed simultaneously (in parallel temporal overlap).
  • After the initial pipeline fills up (which takes 5 cycles), one instruction completes and exits the pipeline every single clock cycle (every 200ps).

The Mathematical Result:

Ideally, an N-stage pipeline can yield a speedup of almost exactly N over a non-pipelined equivalent, multiplying overall CPU performance by N, simply by overlapping work that uses different hardware components.

20. How does arithmetic pipelining differ from instruction pipelining?

Both utilize the concept of pipelining (breaking a task into sequential stages separated by registers), but they apply to entirely different levels of the processor hierarchy.

Instruction Pipelining:

  • Scope: Operates at the macroscopic level of the whole CPU.
  • Function: It overlaps the execution of entirely different, separate instructions in the program (e.g., Fetching Instruction 3 while Decoding Instruction 2 and Executing Instruction 1).
  • Stages: IF, ID, EX, MEM, WB.

Arithmetic Pipelining:

  • Scope: Operates at the microscopic level, deep within the ALU or FPU (Floating Point Unit).
  • Function: It overlaps the sub-operations of a single, highly complex mathematical operation across multiple data sets.
  • Example (Floating Point Addition): Adding floating point numbers is slow. It is broken into stages:
    1. Compare Exponents.
    2. Shift Mantissa to align decimal points.
    3. Add Mantissas.
    4. Normalize the result.
    An arithmetic pipeline allows the CPU to start a new Floating Point addition every clock cycle, even if one addition takes 4 cycles to finish.

21. What is data forwarding? How does it resolve RAW hazards?

Data Forwarding (also known as bypassing or short-circuiting) is a critical hardware optimization used to resolve Read-After-Write (RAW) data hazards without stalling the pipeline.

The RAW Hazard Problem:

If Instruction A writes to R1, and Instruction B reads from R1, Instruction B normally has to wait until Instruction A completes its Write-Back (WB) stage. This would cause a 2- or 3-cycle stall.

How Forwarding Works (Details):

  • Internal Data Paths: Hardware designers add physical wires (buses) and multiplexers that connect the output of the ALU (the EX stage) and the output of the Data Memory (the MEM stage) directly back to the inputs of the ALU.
  • Forwarding Unit Logic: A specialized forwarding control unit continuously monitors the pipeline. It compares the Destination Register of the instruction currently in the EX/MEM and MEM/WB registers with the Source Registers of the instruction currently entering the EX stage.
  • The Resolution: If a match is found (a hazard is detected), the multiplexer selects the forwarded data from the pipeline register rather than the stale data read from the Register File.
  • Result: The dependent instruction receives the newly computed data exactly when it needs it, bypassing the register file entirely, and eliminating the stall cycle.

22. What is branch prediction? How does it reduce control hazards?

Branch prediction is a microprocessor technique that attempts to guess the outcome of a conditional branch (e.g., whether an 'if' statement is true or a loop will iterate again) before it is officially evaluated. This mitigates Control Hazards.

Static vs. Dynamic Prediction:

  • Static Prediction: The compiler predicts the branch. For example, it might predict that backward branches (loops) are always taken, and forward branches (if-statements) are never taken.
  • Dynamic Prediction: The hardware uses a Branch History Table (BHT) or Branch Target Buffer (BTB) to track the past behavior of branches at runtime. A common implementation is a 2-bit saturating counter, which requires a branch to deviate twice before changing its prediction, making it highly accurate for loops.

Reducing Control Hazards:

  • When a branch is fetched, the predictor supplies a guess. If the guess is "Taken", the CPU immediately fetches from the target address. If "Not Taken", it fetches sequentially.
  • Zero Penalty on Success: If the guess is correct (which modern predictors do >95% of the time), the pipeline never stalls. The control hazard is effectively erased.
  • Misprediction Penalty: If the guess is wrong, the CPU must flush the incorrectly fetched instructions and restart fetching from the correct address, incurring a penalty of several clock cycles.

23. Why do structural hazards occur in a pipeline with a single memory for instruction and data?

A structural hazard occurs when the hardware cannot support all the operations that the pipeline needs to execute simultaneously in a single clock cycle.

The Single Memory Problem (Von Neumann Architecture):

  • In a classic 5-stage pipeline, the Instruction Fetch (IF) stage requires access to memory every single clock cycle to fetch the next instruction.
  • The Memory Access (MEM) stage requires access to memory whenever a Load or Store instruction is executed.
  • If the processor utilizes a unified, single physical memory block (or a single memory bus port) for both instructions and data, it cannot perform two memory operations simultaneously.

The Hazard Scenario:

If Instruction A (a Load) is in the MEM stage, it occupies the memory port to read data. In that exact same clock cycle, Instruction D (four cycles behind) is in the IF stage, trying to fetch its instruction word. They collide. The hardware must stall the IF stage (injecting a bubble) to let the MEM stage finish.

The Solution: Modern processors use a Harvard Architecture at the L1 cache level, providing a physically separate Instruction Cache (I-Cache) and Data Cache (D-Cache). This provides two independent memory ports, entirely eliminating this structural hazard.

24. How does pipeline flushing work?

Pipeline flushing (also called pipeline squashing or clearing) is the mechanism used by the processor to discard instructions that were speculatively fetched into the pipeline but should not be executed.

When does flushing occur?

  • Branch Misprediction: The processor guessed a branch would be taken and fetched instructions from the target. The EX stage later determines the branch was actually not taken.
  • Exceptions/Interrupts: An instruction causes a fault (like divide by zero). Instructions currently in the pipeline behind the faulting instruction must not be allowed to change machine state.

Mechanism (How it works):

  1. Identify Invalid Instructions: The hardware identifies the pipeline stages containing the incorrectly fetched instructions (typically IF, ID, and sometimes EX).
  2. Zeroing Control Signals: The control lines in the pipeline registers for those specific stages are set to zero. This effectively transforms the invalid instructions into NOPs (No-Operations).
  3. Preventing State Change: Because the control signals are zero, the NOPs will flow harmlessly through the MEM and WB stages without writing to memory or the register file.
  4. Update PC: The Program Counter is updated with the correct restart address (either the correct branch path or the Exception Handler address), and fetching resumes.

25. Calculate speedup for 5 stages, 2ns each, for 100 instructions.

This is a classic performance calculation requiring comparison of execution times between a non-pipelined and pipelined processor.

Parameters:

  • Number of stages (k) = 5
  • Stage delay (clock cycle) = 2 ns
  • Number of instructions (n) = 100

1. Non-Pipelined Execution Time:

  • In a non-pipelined processor, an instruction must finish completely before the next begins.
  • Time per instruction = 5 stages × 2 ns = 10 ns.
  • Total Time = 100 instructions × 10 ns = 1000 ns.

2. Pipelined Execution Time:

  • In a pipeline, it takes k cycles to fill the pipeline and finish the first instruction. After that, one instruction finishes every cycle.
  • Total Cycles = k + (n - 1) = 5 + (100 - 1) = 104 cycles.
  • Total Time = 104 cycles × 2 ns/cycle = 208 ns.

3. Speedup Calculation:

Speedup = Time(Non-pipelined) / Time(Pipelined)
Speedup = 1000 ns / 208 ns = 4.807

Conclusion: The pipelined processor achieves a speedup of ~4.8x over the non-pipelined equivalent. (Notice how this approaches the theoretical maximum speedup of k = 5).

26. 5% branch freq, 2-cycle penalty. Calculate pipeline efficiency.

To calculate pipeline efficiency, we must determine the Ideal CPI and the Actual Effective CPI considering the branch penalties.

Parameters:

  • Ideal CPI of a pipeline = 1.0 (assuming no stalls)
  • Branch frequency = 5% (0.05)
  • Penalty per branch = 2 cycles

1. Calculate Stall Cycles per Instruction:

  • Not every instruction is a branch, and only branches incur the penalty. Therefore, we average the penalty over all instructions.
  • Stalls/Instruction = Branch Frequency × Branch Penalty
  • Stalls/Instruction = 0.05 × 2 = 0.1 cycles

2. Calculate Actual Effective CPI:

  • Effective CPI = Ideal CPI + Stalls/Instruction
  • Effective CPI = 1.0 + 0.1 = 1.1

3. Calculate Pipeline Efficiency:

Efficiency = Ideal CPI / Effective CPI
Efficiency = 1.0 / 1.1 = 0.9090...

Conclusion: The pipeline efficiency is 90.9%. This means the processor achieves 90.9% of its theoretical maximum throughput.

27. Illustrate pipeline execution of sequence with data dependencies.

Note: You can draw a pipeline timing diagram to show how hazards are resolved. Let's assume the following common sequence demonstrating a RAW hazard:

1. ADD R1, R2, R3   (Writes to R1)
2. SUB R4, R1, R5   (Reads R1)
                

Scenario A: Without Forwarding (Hardware Interlock)

The ADD writes R1 in cycle 5 (WB). The SUB needs R1 in cycle 3 (ID). The hardware must stall SUB for 2 cycles.

Cycle:  1   2   3   4   5   6   7   8
ADD     IF  ID  EX  MEM WB
SUB         IF  ID  [stall] [stall] EX  MEM WB
                

The pipeline wastes 2 cycles (bubbles) waiting for the register file to update.

Scenario B: With Forwarding (Bypassing)

The ADD computes the result of R1 at the end of cycle 3 (EX stage). The SUB needs R1 at the beginning of its EX stage (cycle 4). Forwarding hardware routes the ALU output directly back to the ALU input.

Cycle:  1   2   3   4   5   6
ADD     IF  ID  EX  MEM WB
SUB         IF  ID  EX  MEM WB
                

The SUB executes smoothly without stalling. The data is forwarded from the EX/MEM pipeline register to the ALU input multiplexer in Cycle 4.

28. Calculate CPI for pipeline with hazards causing 20% instructions stalled for 2 cycles.

This calculation requires understanding how stalls artificially inflate the Cycles Per Instruction (CPI).

Parameters:

  • Base CPI (Ideal): 1.0. In a perfect pipeline, one instruction completes every clock cycle.
  • Hazard Frequency: 20% of all instructions encounter a hazard that causes a stall. (Probability = 0.20)
  • Stall Penalty: When a hazard occurs, it causes a stall of 2 clock cycles.

Calculation Steps:

The average penalty spread across all instructions is calculated by multiplying the frequency of the hazard by the penalty of the hazard.

Average Stall Cycles per Instruction = Hazard Frequency × Stall Penalty
Stall/Instr = 0.20 × 2 cycles = 0.4 cycles

Now, add this penalty to the base ideal CPI.

Effective CPI = Ideal CPI + Average Stall Cycles
Effective CPI = 1.0 + 0.4 = 1.4

Conclusion: The effective CPI of the processor under these conditions is 1.4. It takes 1.4 clock cycles, on average, to retire an instruction.

29. Differentiate between exceptions and interrupts.

While often used interchangeably in a casual context, computer architecture makes a strict distinction between the two based on their origin, synchronicity, and handling behaviour.

FeatureExceptionsInterrupts
OriginGenerated internally by the CPU as a direct result of executing the current instruction.Generated externally by hardware/peripheral devices (I/O) outside the CPU.
SynchronicitySynchronous: They occur at the exact same instruction boundary every time the program runs with the same data.Asynchronous: Can occur at any random/unpredictable instruction boundary, independent of the code.
HandlingMust be handled immediately before proceeding, as the faulting instruction cannot complete execution.The CPU typically finishes the current instruction in the pipeline, saves state, and then services it.
Program Counter (EPC)EPC points to the faulting instruction itself (so it can be re-executed after correcting the exception).EPC points to the next instruction to execute when the program resumes.
ExamplesDivide-by-zero, page fault, arithmetic overflow, invalid opcode, memory protection violation.Keyboard keystroke, mouse movement, network packet arrival, hardware timer expiration.

30. Importance of Status Register.

The Status Register (also known as the Condition Code Register or Flags Register) is a crucial hardware register containing a set of boolean flags. It is vital for control flow and system state management.

Primary Functions:

  1. Reflecting ALU Outcomes: After an Arithmetic Logic Unit (ALU) operation, the hardware automatically sets flags in the status register to reflect the result.
    • Z (Zero): Set to 1 if the ALU result is 0.
    • N (Negative): Set to 1 if the ALU result is negative.
    • C (Carry): Set to 1 if an addition caused a carry-out of the MSB.
    • V (Overflow): Set to 1 if signed arithmetic overflow occurred.
  2. Enabling Conditional Branching: Control instructions (like Branch if Equal or Branch if Less Than) do not perform math themselves. They simply look at the flags set by a previous comparison instruction to decide whether to take the branch. Without the status register, loops and if-statements cannot function.
  3. System State and Privilege: It often contains bits that define the current operating state, such as whether the CPU is in User Mode or Kernel Mode, and whether external interrupts are currently enabled or masked.

31. Explain: Vectored and Polled Interrupt.

These are the two primary mechanisms a processor uses to figure out which device caused an interrupt and how to handle it.

FeaturePolled Interrupts (Software-Driven)Vectored Interrupts (Hardware-Driven)
MechanismAll devices share a single interrupt request line. The CPU jumps to one central, general-purpose Interrupt Service Routine (ISR).Each device sends a unique identifier code called the Interrupt Vector over the data bus during interrupt acknowledgment.
IdentificationThe ISR executes a software loop, checking (polling) the status register of each attached device sequentially.The CPU uses the vector code as an index into the Interrupt Vector Table in memory to find the specific ISR address directly.
Speed & EfficiencySlow. Software polling loop wastes CPU clock cycles querying idle devices.Extremely fast. Direct hardware mapping jumps to the target ISR instantly without scanning.
Hardware CostVery simple and cheap. No extra hardware logic needed.Complex. Requires a dedicated Interrupt Controller to handle vector generation and priorities.
ScalabilityPoor. Polling delay increases linearly as more devices are added.Excellent. Scalable to many devices with low overhead.

32. Explain how Exception takes place.

The process of an exception taking place and being handled is a highly coordinated dance between the hardware pipeline and the operating system software.

The Step-by-Step Mechanism:

  1. Detection: The hardware detects an anomaly (e.g., the ALU detects a divide-by-zero in the EX stage, or the MMU detects a page fault in the MEM stage).
  2. Pipeline Flush: The hardware immediately turns the faulting instruction, and all younger instructions behind it in the pipeline, into NOPs (flushing them). It must ensure these instructions do not write to memory or registers.
  3. State Preservation: The hardware saves the address of the faulting instruction into a special register, usually called the Exception Program Counter (EPC). This is crucial so the OS knows where the error occurred and can potentially restart the program later.
  4. Record Cause: The hardware writes an error code identifying the type of exception into a Cause Register.
  5. Privilege Escalation: The CPU switches from User Mode to Kernel Mode, granting full access to hardware resources.
  6. Jump to Handler: The Program Counter (PC) is forcibly set to the predefined memory address of the Operating System's Exception Handler routine. The OS then reads the Cause register, handles the error (e.g., terminates the program or loads a page), and optionally uses the EPC to return control to the user program.

33. Discuss how exceptions affect the performance of a pipeline. Suggest mechanisms to minimize this loss.

Exceptions are catastrophic to pipeline throughput. They violate the core assumption of pipelining: a steady, uninterrupted flow of instructions.

Impact on Performance:

  • Pipeline Flushing Penalty: When an exception occurs in a deep pipeline (e.g., stage 5), all instructions in stages 1 through 4 must be thrown away. This wastes multiple clock cycles of work.
  • State Save/Restore Overhead: Jumping to the OS handler requires saving dozens of CPU registers to memory and restoring them later, costing hundreds of clock cycles.
  • Cache Pollution: The OS handler brings its own code and data into the CPU caches, potentially evicting the user program's data, causing further cache misses when the user program resumes.

Mechanisms to Minimize Loss:

  1. Precise Exception Handling: Ensure that only instructions occurring before the faulting instruction complete, and none after. This allows for quick, clean restarts without complex software recovery logic.
  2. Delayed Exceptions (Poison Bits): If a speculative instruction causes an exception (like a divide-by-zero on a guessed branch path), do not handle it immediately. Instead, tag the result register with a "poison bit" (NaN). Only throw the exception later if the program actually attempts to commit/use that poisoned register.
  3. Shadow Registers: Hardware duplicates the register file. When an exception occurs, the hardware simply switches to the shadow registers for the OS handler, eliminating the need to save all registers to slow RAM.

34. How is exception priority managed when multiple exceptions occur simultaneously in different pipeline stages?

In a pipelined processor, multiple instructions are executing simultaneously in different stages. It is entirely possible for an instruction in the MEM stage to cause a page fault in the exact same clock cycle that an instruction in the IF stage causes a memory protection violation.

The Rule of Precise Exceptions (Program Order):

To maintain architectural correctness, exceptions must be handled in the exact logical order the instructions appeared in the original program, regardless of when the hardware detected them.

How Hardware Manages Priority:

  • Older Instructions Win: The instruction further down the pipeline (closer to completion, e.g., in the MEM stage) is the "older" instruction in program order. It always has higher priority.
  • The Mechanism:
    1. When an exception is detected in early stages (like IF or ID), the processor does not handle it immediately.
    2. Instead, the hardware attaches an "Exception Status Flag" to that specific instruction as it flows down the pipeline registers.
    3. When an instruction reaches the final stage (Write-Back or Commit stage), the hardware checks the status flags.
    4. If the flag is set, the exception is triggered. Because instructions reach the final stage strictly in program order, the oldest instruction's exception will be triggered first, naturally causing the pipeline to flush the younger instruction (along with its pending exception).

35. Explain the role of the program counter (PC) and register file in exception handling in a pipelined system.

Both are critical for preserving the state of the machine so the Operating System can diagnose the issue and potentially resume the interrupted program.

Role of the Program Counter (PC):

  • In a pipeline, there isn't just one PC. The IF stage is fetching instruction PC+16, while the EX stage is faulting on instruction PC.
  • When the fault occurs, the hardware must capture the exact address of the faulting instruction and save it to the Exception Program Counter (EPC) register.
  • This allows the OS to pinpoint exactly which line of code failed. If the OS fixes the issue (e.g., loads the missing page from disk for a page fault), it executes a "Return from Exception" instruction, which restores the PC from the EPC, flawlessly restarting the faulting instruction.

Role of the Register File:

  • The register file holds the working variables of the user program. When an exception jumps to the OS handler, the OS must use those exact same registers to execute its own code.
  • Therefore, the first step of an OS exception handler is to save the entire state of the user's Register File into RAM (usually onto a system stack).
  • Before returning control to the user, the OS restores the Register File from RAM. If this isn't done perfectly, the user program will wake up with corrupted variables and crash.

36. Design a method to handle multiple simultaneous exceptions in a 5-stage pipeline.

To design a robust system that handles multiple simultaneous exceptions while maintaining "precise exceptions," you must decouple the detection of an exception from the handling of the exception.

The Hardware Design (Details):

  1. Add Status Vectors: Expand every pipeline register (IF/ID, ID/EX, EX/MEM, MEM/WB) to include an "Exception Status Vector." This vector contains bits for every possible error (e.g., Bit 0 = Page Fault, Bit 1 = Overflow, Bit 2 = Invalid Opcode).
  2. Detection & Tagging: If a stage detects an error (e.g., ID detects an invalid opcode), it does NOT jump to the OS handler. Instead, it sets the corresponding bit in the instruction's Exception Status Vector. The instruction is allowed to continue moving down the pipeline.
  3. Inhibit State Changes: Any instruction with a non-zero Exception Status Vector is blocked by hardware from actually writing to the Register File or Data Memory. It effectively becomes a NOP carrying an error code.
  4. Commit Stage Resolution: The logic to actually trigger the exception is placed at the very end of the pipeline, in the Write-Back (WB) or "Commit" stage.
  5. Execution: Because instructions enter the WB stage sequentially in program order, the hardware checks the Exception Status Vector of the oldest instruction. If it has an error, the CPU halts, copies the PC of that instruction to the EPC, flushes all earlier pipeline stages (discarding any pending exceptions of younger instructions), and jumps to the OS handler.

37. Give an example of an exception occurring in the EX stage and explain how the pipeline handles it.

Example Scenario: Arithmetic Overflow.

Consider the instruction sequence:
1. ADD R1, R2, R3 (Causes overflow in EX stage)
2. SUB R4, R5, R6 (Currently in ID stage)
3. AND R7, R8, R9 (Currently in IF stage)

Step-by-Step Handling Process:

  1. Clock Cycle 3: The ADD instruction is in the EX stage. The ALU adds R2 and R3 and detects that the result is too large to fit in 32 bits. The ALU hardware raises the Overflow signal.
  2. Tagging (Cycle 3 end): The hardware sets the "Overflow Exception" bit in the EX/MEM pipeline register associated with the ADD instruction.
  3. Clock Cycle 4: The ADD moves to MEM. The SUB moves to EX. The AND moves to ID.
  4. Clock Cycle 5 (Commit): The ADD moves to WB. The hardware in the WB stage checks the exception bits. It sees the Overflow bit is set.
  5. Action (Cycle 5):
    • Hardware prevents ADD from writing its corrupted result to R1.
    • Hardware asserts the "Flush" control lines for the IF/ID, ID/EX, and EX/MEM registers. This turns the SUB, AND, and any newer instructions into NOPs, throwing them away.
    • The PC of the ADD instruction is loaded into the EPC register.
    • The Cause register is set to indicate "Arithmetic Overflow".
    • The main PC is overwritten with the address of the OS Overflow Handler routine, and execution resumes from there in Cycle 6.

38. What is the impact of out-of-order execution on exception handling? How can it be addressed?

Out-of-Order (OoO) execution massively complicates exception handling. It breaks the fundamental requirement for Precise Exceptions.

The Problem (Imprecise Exceptions):

In an OoO processor, Instruction 5 might execute and complete before Instruction 2 (because Instruction 2 was waiting for a slow memory fetch). If Instruction 2 eventually causes a Page Fault, the machine state is corrupted: Instruction 5 has already written its results to registers. The OS cannot easily restart the program because the processor is in an inconsistent, non-sequential state.

The Solution: The Reorder Buffer (ROB)

Modern OoO processors solve this using a hardware structure called a Reorder Buffer.

  1. In-Order Issue: Instructions are decoded and placed into the ROB sequentially.
  2. Out-of-Order Execution: Instructions execute whenever their data is ready. They write their results to temporary, hidden physical registers, NOT the architectural registers.
  3. In-Order Commit (Retirement): The ROB looks at the oldest instruction. Only if it has finished executing without any exceptions is it allowed to "commit" (permanently write its result to the real architectural Register File).
  4. Exception Resolution: If Instruction 2 has an exception, it sits in the ROB. When it becomes the oldest instruction and is ready to commit, the hardware triggers the exception. It then simply empties the ROB, instantly throwing away the temporary results of Instruction 5 and any other speculatively executed instructions, restoring the machine to a perfectly precise state.

39. Explain the concept of delayed exception handling.

Delayed Exception Handling (often used in conjunction with Speculative Execution or VLIW architectures) is a technique where an exception is detected but intentionally ignored or deferred until a later point in the program.

Why do it?

Modern processors heavily use Speculative Execution (guessing a branch outcome and executing instructions down that path before knowing if the guess was right). If a speculative instruction causes an exception (e.g., reading an invalid memory address), the processor shouldn't crash the program immediately—because it might turn out that the branch was mispredicted and that instruction was never supposed to execute anyway!

How it works (Poison Bits):

  1. A speculative instruction (e.g., a Load) triggers a page fault.
  2. Instead of jumping to the OS, the hardware intercepts it. It writes a special designated "Error Value" (or sets a hardware Poison Bit) into the destination register of that Load instruction.
  3. The program continues executing speculatively. Any subsequent instruction that tries to read the poisoned register also gets poisoned.
  4. Resolution A (Misprediction): If the processor later realizes the branch was mispredicted, it flushes the pipeline. The poisoned registers are thrown away harmlessly. The program survives.
  5. Resolution B (Correct Prediction): If the branch was correct, the instruction was indeed supposed to execute. The exception is only formally triggered (jumping to the OS) when a non-speculative, "commit-stage" instruction finally attempts to write that poisoned data to memory or a permanent state.