COMPUTER ORGANIZATION AND DESIGN
5
Edition
th
The Hardware/Software Interface
Chapter 4
The Processor
§4.1 Introduction
Introduction
CPU performance factors
Instruction count
Determined by ISA and compiler
CPI and Cycle time
Determined by CPU hardware
We will examine two MIPS implementations
A simplified version
A more realistic pipelined version
Simple subset, shows most aspects
Memory reference: lw, sw
Arithmetic/logical: add, sub, and, or, slt
Control transfer: beq, j
Chapter 4 — The Processor — 2
MIPS Architecture
Chapter 4 — The Processor — 3
Instruction Execution
For every instruction, the first two steps are identical:
1. Send the program counter (PC) to the memory that contains
the code and fetch the instruction from that memory.
2. Read one or two registers, using fi elds of the instruction to
select the registers to read.
For the load word instruction, we need to read only one
register, but most other instructions require reading two
registers.
Aft er these two steps, the actions required to complete the
instruction depend on the instruction class.
Fortunately, for each of the three instruction classes
(memory-reference, arithmetic-logical, and branches), the
actions are largely the same, independent of the exact
instruction.
Chapter 4 — The Processor — 4
Instruction Execution
For example, all instruction classes, except jump, use the
arithmetic-logical unit (ALU) aft er reading the registers.
The memory-reference instructions use the ALU for an
address calculation, the arithmetic-logical instructions for
the operation execution, and branches for comparison.
After using the ALU, the actions required to complete
various instruction classes differ.
A memory-reference instruction will need to access the
memory either to read data for a load or write data for a
store.
An arithmetic-logical or load instruction must write the
data from the ALU or memory back into a register.
Chapter 4 — The Processor — 5
Instruction Execution
Lastly, for a branch instruction, we may need to change
the next instruction address based on the comparison;
otherwise, the PC should be incremented by 4 to get the
address of the next instruction.
Chapter 4 — The Processor — 6
Instruction Execution
PC instruction memory, fetch instruction
Register numbers register file, read registers
Depending on instruction class
Use ALU to calculate
Arithmetic result
Memory address for load/store
Branch target address
Access data memory for load/store
PC target address or PC + 4
Chapter 4 — The Processor — 7
CPU Overview: An abstract view of the implementation
of the MIPS subset showing themajor functional units
and the major connections between them.
Chapter 4 — The Processor — 8
Use Multiplexers- Data has two sources
Can’t just join
wires together
Use multiplexers
Chapter 4 — The Processor — 9
CPU Overview
All instructions start by using the program counter to
supply the instruction address to the instruction memory.
After the instruction is fetched, the register operands
used by an instruction are specified by fields of that
instruction.
Once the register operands have been fetched, they can
be operated on to compute a memory address (for a load
or store), to compute an arithmetic result (for an integer
arithmetic-logical instruction), or a compare (for a
branch).
If the instruction is an arithmetic-logical instruction, the
result from the ALU must be written to a register
Chapter 4 — The Processor — 10
If the operation is a load or store, the ALU result is used
as an address to either store a value from the registers
or load a value from memory into the registers.
The result from the ALU or memory is written back into
the register file.
Branches require the use of the ALU output to determine
the next instruction address, which comes either from the
ALU (where the PC and branch off set are summed) or
from an adder that increments the current PC by 4.
The thick lines interconnecting the functional units
represent buses, which consist of multiple signals.
Chapter 4 — The Processor — 11
CPU Overview
The arrows are used to guide the reader in knowing how
information flows.
Since signal lines may cross, we explicitly show when
crossing lines are connected by the presence of a dot
where the lines cross.
Chapter 4 — The Processor — 12
Control
Several of the units must be controlled depending on the
type of instruction.
For example, the data memory must read on a load and
written on a store.
The register file must be written only on a load or an
arithmetic-logical instruction.
And, of course, the ALU must perform one of several
operations.
Like the multiplexors, control lines that are set on the
basis of various fields in the instruction direct these
operations.
Chapter 4 — The Processor — 13
Control
Chapter 4 — The Processor — 14
Control
Fig shows the datapath of Figure 4.1 with the three
required multiplexors added, as well as control lines for
the major functional units.
A control unit, which has the instruction as an input, is
used to determine how to set the control lines for the
functional units and two of the multiplexors.
The third multiplexor, which determines whether PC + 4
or the branch destination address is written into the PC,
is set based on the Zero output of the ALU, which is used
to perform the comparison of a beq instruction.
Chapter 4 — The Processor — 15
The top multiplexor (“Mux”) controls what value replaces
the PC (PC + 4 or the branch destination address); the
multiplexor is controlled by the gate that “ANDs” together
the Zero output of the ALU and a control signal that
indicates that the instruction is a branch.
The middle multiplexor, whose output returns to the
register file, is used to steer the output of the ALU (in the
case of an arithmetic-logical instruction) or the output of
the data memory (in the case of a load) for writing into the
register file.
Finally, the bottommost multiplexor is used to determine
whether the second ALU input is from the registers (for an
arithmetic-logical instruction or a branch) or from the off set
fi eld of the instruction (for a load or store).
Chapter 4 — The Processor — 16
The added control lines are straight forward and
determine the operation performed at the ALU, whether
the data memory should read or write, and whether the
registers should perform a write operation.
Chapter 4 — The Processor — 17
§4.2 Logic Design Conventions
Logic Design Basics
Information encoded in binary
Low voltage = 0, High voltage = 1
One wire per bit
Multi-bit data encoded on multi-wire buses
Combinational element
Operate on data
Output is a function of input
State (sequential) elements
Store information
Chapter 4 — The Processor — 18
Logic Design Basics
we must decide how the hardware logic implementing the
computer will operate and how the computer is clocked.
The data path elements in the MIPS implementation
consist of two different types of logic elements: elements
that operate on data values and elements that contain
state.
The elements that operate on data values are all
combinational, which means that their outputs depend
only on the current inputs.
Given a set of inputs, it always produces the same output
because it has no internal storage. Eg ALU
Chapter 4 — The Processor — 19
Logic Design Basics
Other elements in the design are not combinational, but
instead contain state. An element contains state if it has
some internal storage.
We call these elements state elements because, if we
pulled the power plug on the computer, we could
restart it accurately by loading the state elements with
the values they contained before we pulled the plug.
Furthermore, if we saved and restored the state
elements, it would be as if the computer had never lost
power.
the instruction and data memories, as well as the
registers, are all examples of state elements.
Chapter 4 — The Processor — 20
Combinational Elements
AND-gate Adder A
Y
+
Y=A&B Y=A+B B
A
Y
B
Arithmetic/Logic Unit
Multiplexer Y = F(A, B)
Y = S ? I1 : I0
A
I0 M
u Y ALU Y
I1 x
B
S F
Chapter 4 — The Processor — 21
Sequential Elements
Register: stores data in a circuit
Uses a clock signal to determine when to
update the stored value
Edge-triggered: update when Clk changes
from 0 to 1
Clk
D Q
D
Clk
Q
Chapter 4 — The Processor — 22
Sequential Elements
Register with write control
Only updates on clock edge when write
control input is 1
Used when stored value is required later
Clk
D Q Write
Write D
Clk
Q
Chapter 4 — The Processor — 23
Clocking Methodology
Combinational logic transforms data during
clock cycles
Between clock edges
Input from state elements, output to state
element
Longest delay determines clock period
Chapter 4 — The Processor — 24
Clocking Methodology
A clocking methodology defines when signals can be read and when
they can be written.
It is important to specify the timing of reads and writes, because if a
signal is written at the same time it is read, the value of the read
could correspond to the old value, the newly written value, or even
some mix of the two!
Chapter 4 — The Processor — 25
§4.3 Building a Datapath
Building a Datapath
Datapath
Elements that process data and addresses
in the CPU
Registers, ALUs, mux’s, memories, …
We will build a MIPS datapath
incrementally
Refining the overview design
Chapter 4 — The Processor — 26
Instruction Fetch
Increment by
4 for next
32-bit instruction
register
Chapter 4 — The Processor — 27
Chapter 4 — The Processor — 28
R-Format Instructions
Read two register operands
Perform arithmetic/logical operation
Write register result
Chapter 4 — The Processor — 29
R-Format Instructions
Now let’s consider the R-format instructions
They all read two registers, perform an ALU operation on
the contents of theregisters, and write the result to a
register.
Recall that a typical instance of such an instruction is
add $t1,$t2,$t3, which reads $t2 and $t3 and writes $t1.
The processor’s 32 general-purpose registers are stored
in a structure called a register file.
A register file is a collection of registers in which any
register can be read or written by specifying the number
of the register in the file.
Chapter 4 — The Processor — 30
R-Format Instructions
R-format instructions have three register operands, so
we will need to read two data words from the register file
and write one data word into the register file foreach
instruction.
For each data word to be read from the registers, we
need an input to the register file that specifies the
register number to be read and an output from the
register file that will carry the value that has been read
from the registers.
To write a data word, we will need two inputs: one to
specify the register number to be written and one to
supply the data to be written into the register.
Chapter 4 — The Processor — 31
R-Format Instructions
The register file always outputs the contents of whatever
register numbers are on the Read register inputs.
Writes, however, are controlled by the write control signal,
which must be asserted for a write to occur at the clock
edge.
The register number inputs are 5 bits wide to specify one
Of 32 registers.
The register file always outputs the contents of the
registers corresponding to the Read register inputs on the
outputs; no other control inputs are needed.
In contrast, a register write must be explicitly indicated by
asserting the write control signal. Remember that writes
are edge-triggered, so that all the write inputs must be
valid at the clock edge.
Chapter 4 — The Processor — 32
R-Format Instructions
Since writes to the register file are edge-triggered, our
design can legally read and write the same register within
a clock cycle: the read will get the value written in an
earlier clock cycle, while the value written will be
available to a read in a subsequent clock cycle.
The inputs carrying the register number to the register
file are all 5 bits wide, whereas the lines carrying data
values are 32 bits wide.
Chapter 4 — The Processor — 33
Chapter 4 — The Processor — 34
Chapter 4 — The Processor — 35
Load/Store Instructions
Read register operands
Calculate address using 16-bit offset
Use ALU, but sign-extend offset
Load: Read memory and update register
Store: Write register value to memory
Chapter 4 — The Processor — 36
Chapter 4 — The Processor — 37
Chapter 4 — The Processor — 38
Chapter 4 — The Processor — 39
I-Format Instructions
Next, consider the MIPS load word and store word instructions,
which have the general form
lw $t1,offset_value($t2) or sw $t1,offset_value ($t2).
These instructions compute a memory address by adding the base
register, which is $t2, to the 16-bit signed off set field contained in
the instruction.
If the instruction is a store, the value to be stored must also be read
from the register file where it resides in $t1.
If the instruction is a load, the value read from memory must be
written into the register file in the specified register, which is $t1.
In addition, we will need a unit to sign-extend the 16-bit off set
field in the instruction to a 32-bit signed value, and a data memory
unit to read from or write to.
The data memory must be written on store instructions; hence, data
memory has read and write control signals, an address input, and
an input for the data to be written into memory.
Chapter 4 — The Processor — 40
Branch Instructions
Read register operands
Compare operands
Use ALU, subtract and check Zero output
Calculate target address
Sign-extend displacement
Shift left 2 places (word displacement)
Add to PC + 4
Already calculated by instruction fetch
Chapter 4 — The Processor — 41
Branch Instructions
Just
re-routes
wires
Sign-bit wire
replicated
Chapter 4 — The Processor — 42
The datapath for a branch uses the ALU to evaluate the branch
condition and a separate adder to compute the branch target as the
sum of the incremented PC and the sign-extended, lower 16 bits of
the instruction (the branch displacement), shifted left 2.
Chapter 4 — The Processor — 43
Branch Instruction
The instruction set architecture specifies that the
base for the branch address calculation is the
address of the instruction following the branch.
Since we compute PC + 4 (the address of the next
instruction) in the instruction fetch datapath, it is
easy to use this value as the base for computing
the branch target address.
The architecture also states that the off set field is
shifted left 2 bits so that it is a word off set; this
shift increases the effective range of the off set
field by a factor of 4.
Chapter 4 — The Processor — 44
Chapter 4 — The Processor — 45
Chapter 4 — The Processor — 46
Branch Instructions
The beq instruction has three operands, two registers
that are compared for equality, and a 16-bit off set used
to compute the branch target address relative to the
branch instruction address. Its form is beq $t1,$t2,offset.
To implement this instruction, we must compute the
branch target address by adding the sign-extended off
set field of the instruction to the PC.
As well as computing the branch target address, we
must also determine whether the next instruction is the
instruction that follows sequentially or the instruction at
the branch target address. When the condition is true
(i.e., the operands are equal), the branch target address
becomes the new PC, and we say that the branch
Is taken.
Chapter 4 — The Processor — 47
If the operands are not equal, the incremented PC should
replace the current PC (just as for any other normal
instruction); in this case, we say that the branch is not
taken.
Thus, the branch datapath must do two operations:
compute the branch target address and compare the
register contents.
To compute the branch target address, the branch
datapath includes a sign extension unit, and an adder.
To perform the compare, we need to use the register file
shown in to supply the two register operands
Since that ALU provides an output signal that indicates
whether the result was 0, we can send the two register
operands to the ALU with the control set to do a subtract.
Chapter 4 — The Processor — 48
If the Zero signal out of the ALU unit is asserted,
we know that the two values are equal.
Although the Zero output always signals if the result is 0,
we will be using it only to implement the equal test of
branches.
The jump instruction operates by replacing the lower 28
bits of the PC with the lower 26 bits of the instruction
shifted left by 2 bits. Simply concatenating 00 to the
jump off set accomplishes this shift.
Chapter 4 — The Processor — 49
Chapter 4 — The Processor — 50
Chapter 4 — The Processor — 51
Implementing Jumps
Jump 2 address
31:26 25:0
Jump uses word address
Update PC with concatenation of
Top 4 bits of old PC
26-bit jump address
00
Need an extra control signal decoded from
opcode
Chapter 4 — The Processor — 52
Datapath With Jumps Added
Chapter 4 — The Processor — 53
Creating a Single Datapath
The simplest datapath will attempt to execute all
instructions in one clock cycle.
This means that no datapath resource can be used more
than once per instruction, so any element needed more
than once must be duplicated.
We therefore need a memory for instructions separate
from one for data. Although some of the functional units
will need to be duplicated, many of the elements can be
shared by different instruction flows.
To share a datapath element between two different
instruction classes, we may need to allow multiple
connections to the input of an element, using a multiplexor
and control signal to select among the multiple inputs.
Chapter 4 — The Processor — 54
Composing the Elements
First-cut data path does an instruction in
one clock cycle
Each datapath element can only do one
function at a time
Hence, we need separate instruction and data
memories
Use multiplexers where alternate data
sources are used for different instructions
Chapter 4 — The Processor — 55
R-Type/Load/Store Datapath
Chapter 4 — The Processor — 56
The branch instruction uses the main ALU for comparison of the
Full Datapath register operands, so we must keep the adder from Fig for
computing the branch target address. An additional multiplexor
is required to select either the sequentially following instruction
address (PC + 4) or the branch target address to be written into
the PC.
Chapter 4 — The Processor — 57
§4.4 A Simple Implementation Scheme
ALU Control
ALU used for
Load/Store: F = add
Branch: F = subtract
R-type: F depends on funct field
ALU control Function
0000 AND
0001 OR
0010 add
0110 subtract
0111 set-on-less-than
1100 NOR
Chapter 4 — The Processor — 58
For load word and store word instructions, we use the
ALU to compute the memory address by addition.
For the R-type instructions, the ALU needs to perform
one of the five actions (AND, OR, subtract, add, or set on
less than), depending on the value of the 6-bit funct (or
function) field in the low-order bits of the instruction
For branch equal, the ALU must perform a subtraction.
Chapter 4 — The Processor — 59
We can generate the 4-bit ALU control input using a small control
unit that has as inputs the function field of the instruction and a 2-bit
control field, which we call ALUOp.
ALUOp indicates whether the operation to be performed should be
add (00) for loads and stores, subtract (01) for beq, or determined by
the operation encoded in the funct field (10).
The output of the ALU control unit is a 4-bit signal that directly
controls the ALU by generating one of the 4-bit combinations.
This style of using multiple levels of decoding—that is, the main
control unit generates the ALUOp bits, which then are used as input
to the ALU control that generates the actual signals to control the
ALU unit—is a common implementation technique.
Chapter 4 — The Processor — 60
Using multiple levels of control can reduce the
size of the main control unit. Using several
smaller control units may also potentially
increase the speed of the control unit.
Such optimizations are important, since the
speed of the control unit is often critical to clock
cycle time.
Chapter 4 — The Processor — 61
ALU Control
Assume 2-bit ALUOp derived from opcode
Combinational logic derives ALU control
opcode ALUOp Operation funct ALU function ALU control
lw 00 load word XXXXXX add 0010
sw 00 store word XXXXXX add 0010
beq 01 branch equal XXXXXX subtract 0110
R-type 10 add 100000 add 0010
subtract 100010 subtract 0110
AND 100100 AND 0000
OR 100101 OR 0001
set-on-less-than 101010 set-on-less-than 0111
Chapter 4 — The Processor — 62
The Main Control Unit
Control signals derived from instruction
R-type 0 rs rt rd shamt funct
31:26 25:21 20:16 15:11 10:6 5:0
Load/
35 or 43 rs rt address
Store
31:26 25:21 20:16 15:0
Branch 4 rs rt address
31:26 25:21 20:16 15:0
opcode always read, write for sign-extend
read except R-type and add
for load and load
Chapter 4 — The Processor — 63
Chapter 4 — The Processor — 64
Chapter 4 — The Processor — 65
Chapter 4 — The Processor — 66
Chapter 4 — The Processor — 67
35 43 04
All Zeros
Chapter 4 — The Processor — 68
Chapter 4 — The Processor — 69
Datapath With Control
Chapter 4 — The Processor — 70
R-Type Instruction
Chapter 4 — The Processor — 71
Example : add $t1,$t2,$t3
Chapter 4 — The Processor — 72
Load Instruction
Chapter 4 — The Processor — 73
Chapter 4 — The Processor — 74
Branch-on-Equal Instruction
Chapter 4 — The Processor — 75
Finally, we can show the operation of the branch-on-equal
instruction, such as
beq $t1, $t2, offset
It operates much like an R-format instruction, but the ALU output
is used to determine whether the PC is written with PC + 4 or the
branch target address.
1.An instruction is fetched from the instruction memory, and the
PC is incremented.
2. Two registers, $t1 and $t2, are read from the register file.
3. The ALU performs a subtract on the data values read from the
register file. The value of PC + 4 is added to the sign-extended,
lower 16 bits of the instruction(offset) shifted left by two; the
result is the branch target address.
4. The Zero result from the ALU is used to decide which adder
result to store into the PC.
Chapter 4 — The Processor — 76
Data path of Jump instruction(Figure 4.17.)
Chapter 4 — The Processor — 77
Like a branch, the low-order 2 bits of a jump address are
always 00twolower 26 bits of this 32-bit address come from the 26-bit
Th e next
immediate field in the instruction.
The upper 4 bits of the address that should replace the PC come from
the PC of the jump instruction plus 4.
Thus, we can implement a jump by storing into the PC the
concatenation of
Chapter 4 — The Processor — 78
Figure 4.24 below shows the addition of the control for jump
added to Figure 4.17.
Chapter 4 — The Processor — 79
1. An additional multiplexor is used to select the
source for the new PC value, which is either the
incremented PC (PC + 4), the branch target PC,
or the jump target PC.
2. One additional control signal is needed for
the additional multiplexor.
3. This control signal, called Jump, is asserted
only when the instruction is a jump— that is,
when the opcode is 2.
Chapter 4 — The Processor — 80
Chapter 4 — The Processor — 81
Chapter 4 — The Processor — 82
Solution
Chapter 4 — The Processor — 83
Chapter 4 — The Processor — 84
1430 x (95/100) = 1130 = improvement. (1358.5 -1130) /1358.5
Improvement =1-0.168=0.83 (slowdown as value less than 1)
Chapter 4 — The Processor — 85
Chapter 4 — The Processor — 86
Fig 4.6
Chapter 4 — The Processor — 87
Chapter 4 — The Processor — 88
Chapter 4 — The Processor — 89
Chapter 4 — The Processor — 90
Chapter 4 — The Processor — 91
Fig for prob 4.7
Chapter 4 — The Processor — 92
Load/ 35 or 43 rs rt address
Store
Chapter 4 — The Processor — 94
Module 1, 2 and 3 End Sem Preparations(35 to
40 Marks)
Module 1: Numerical and theory
Module 2: C to MIPS and MIPS to C
Module 3: Instruction set, Instruction
execution, Data path and control path,
Neumerical
Chapter 4 — The Processor — 95
Performance Issues
Longest delay determines clock period
Critical path: load instruction
Instruction memory register file ALU
data memory register file
Not feasible to vary period for different
instructions
Violates design principle
Making the common case fast
We will improve performance by pipelining
Chapter 4 — The Processor — 96
An Overview of Pipelining
Pipelining improves throughput of our laundry system.
Chapter 4 — The Processor — 97
§4.5 An Overview of Pipelining
Pipelining Analogy
Pipelined laundry: overlapping execution
Parallelism improves performance
Four loads:
Speedup
= 8/3.5 = 2.3
Non-stop:
Speedup
= 2n/0.5n + 1.5 ≈ 4
= number of stages
Chapter 4 — The Processor — 98
MIPS Pipeline
Five stages, one step per stage
1. IF: Instruction fetch from memory
2. ID: Instruction decode & register read
3. EX: Execute operation or calculate address
4. MEM: Access memory operand
5. WB: Write result back to register
Chapter 4 — The Processor — 99
Pipeline Performance
Assume time for stages is
100ps for register read or write
200ps for other stages
Compare pipelined datapath with single-cycle
datapath
Instr Instr fetch Register ALU op Memory Register Total time
read access write
lw 200ps 100 ps 200ps 200ps 100 ps 800ps
sw 200ps 100 ps 200ps 200ps 700ps
R-format 200ps 100 ps 200ps 100 ps 600ps
beq 200ps 100 ps 200ps 500ps
Chapter 4 — The Processor — 100
Pipeline Performance
Single-cycle (Tc= 800ps)
Pipelined (Tc= 200ps)
Chapter 4 — The Processor — 101
Pipeline Speedup
If all stages are balanced
i.e., all take the same time
Time between instructionspipelined
= Time between instructionsnonpipelined
Number of stages
If not balanced, speedup is less
Speedup due to increased throughput
Latency (time for each instruction) does not
decrease
Chapter 4 — The Processor — 102
total execution time for the three instructions: it’s
1400 ps versus 2400 ps.
What would happen if we increased the number
of instructions?
We could extend the previous figures to
1,000,003 instructions. We would add 1,000,000
instructions In the pipelined example; each
instruction adds 200 ps to the total execution
time.
The total execution time would be 1,000,000 ×
200 ps + 1400 ps, or 200,001,400 ps.
Chapter 4 — The Processor — 103
In the nonpipelined example, we would add
1,000,000 instructions, each taking 800 ps, so
total execution time would be 1,000,000 × 800
ps + 2400 ps, or 800,002,400 ps.
Under these conditions, the ratio of total
execution times for real programs on
nonpipelined to pipelined processors is close to
the ratio of times between instructions:
Chapter 4 — The Processor — 104
Pipelining improves performance by increasing
instruction throughput, as opposed to decreasing
the execution time of an individual instruction,
but instruction throughput is the important metric
because real programs execute billions of
instructions.
Chapter 4 — The Processor — 105
Pipelining and ISA Design
MIPS ISA designed for pipelining
All instructions are 32-bits
Easier to fetch and decode in one cycle
c.f. x86: 1- to 17-byte instructions
Few and regular instruction formats
Can decode and read registers in one step
Load/store addressing
Can calculate address in 3rd stage, access memory
in 4th stage
Alignment of memory operands
Memory access takes only one cycle
Chapter 4 — The Processor — 106
Hazards
Situations that prevent starting the next
instruction in the next cycle
Structure hazards
A required resource is busy(washer dryer
combination instead of separate washer and
dryer)
Data hazard
Need to wait for previous instruction to complete
its data read/write
Control hazard
Deciding on control action depends on previous
instruction
Chapter 4 — The Processor — 107
Structure Hazards
It means that the hardware cannot support the
combination of instructions that we want to execute in the
same clock cycle.
A structural hazard in the laundry room would occur if we
used a washer dryer combination instead of a separate
washer and dryer, or if our roommate was busy doing
something else and wouldn’t put clothes away.
Suppose, however, that we had a single memory instead
of two memories.
Chapter 4 — The Processor — 108
If the pipeline in Figure 4.27 had a fourth instruction, we
would see that in the same clock cycle the first instruction
is accessing data from memory while the fourth
instruction is fetching an instruction from that same
memory.
Without two memories, our pipeline could have a
structural hazard.
Chapter 4 — The Processor — 109
Structure Hazards
Conflict for use of a resource
In MIPS pipeline with a single memory
Load/store requires data access
Instruction fetch would have to stall for that
cycle
Would cause a pipeline “bubble”
Hence, pipelined datapaths require
separate instruction/data memories
Or separate instruction/data caches
Chapter 4 — The Processor — 110
Data Hazards
An instruction depends on completion of
data access by a previous instruction
add $s0, $t0, $t1
sub $t2, $s0, $t3
Chapter 4 — The Processor — 111
Without intervention, a data hazard could severely stall
the pipeline.
The add instruction doesn’t write its result until the fifth
stage, meaning that we would have to waste three clock
cycles in the pipeline.
Although we could try to rely on compilers to remove all
such hazards, the results would not be satisfactory.
The primary solution is based on the observation that we
don’t need to wait for the instruction to complete before
trying to resolve the data hazard.
For the code sequence above, as soon as the ALU
creates the sum for the add, we can supply it as an input
for the subtract.
Chapter 4 — The Processor — 112
In this graphical representation of events, forwarding
paths are valid only if the destination stage is later in time
than the source stage.
For example, there cannot be a valid forwarding path
from the output of the memory access stage in the first
instruction to the input of the execution stage of the
following, since that would mean going backward in time.
Chapter 4 — The Processor — 113
The second instruction (sub) depends on the
result of the first instruction (add).
This leads to a data hazard because the sub
instruction needs the value of $s0, which is
produced by the add instruction.
For the add instruction:
It writes back the result to $s0 in the WB stage.
For the sub instruction:
It reads $s0 from the register file in the ID stage.
Chapter 4 — The Processor — 114
Why Forwarding Cannot Solve This Hazard?
MIPS uses forwarding (data forwarding or bypassing) to
reduce data hazards by passing data directly from later
stages to earlier stages, bypassing the register file.
However, forwarding is not always sufficient.
If the required value is available in the EX or MEM stage of
the first instruction, it can be forwarded.
However, the value of $s0 is only written to the register file
during the WB stage of the add instruction.
The sub instruction needs $s0 in its ID stage, which
happens before the WB stage of add.
Since data cannot be forwarded backward in time, there
is no valid forwarding path from the WB stage of add to the
ID stage of sub.
Chapter 4 — The Processor — 115
Forwarding (aka Bypassing)
Use result when it is computed
Don’t wait for it to be stored in a register
Requires extra connections in the datapath
Chapter 4 — The Processor — 116
even with forwarding, we would have to stall one stage
for a load-use data hazard, as Figure 4.30 shows.
A specific form of data hazard in which the data being
loaded by a load instruction has not yet become available
when it is needed by another instruction.
Chapter 4 — The Processor — 117
Load-Use Data Hazard
Can’t always avoid stalls by forwarding
If value not computed when needed
Can’t forward backward in time!
Figure 4.30
Chapter 4 — The Processor — 118
Find the hazards in the preceding code segment and reorder the
instructions
to avoid any pipeline stalls.
Chapter 4 — The Processor — 119
Both add instructions have a hazard because of their
respective dependence on the immediately preceding lw
instruction.
Notice that bypassing eliminates several other potential
hazards, including the dependence of the first add on the
first lw and any hazards for store instructions.
Moving up the third lw instruction to become the third
instruction eliminates both hazards:
Chapter 4 — The Processor — 120
Code Scheduling to Avoid Stalls
Reorder code to avoid use of load result in
the next instruction
C code for A = B + E; C = B + F;
lw $t1, 0($t0) lw $t1, 0($t0)
lw $t2, 4($t0) lw $t2, 4($t0)
stall add $t3, $t1, $t2 lw $t4, 8($t0)
sw $t3, 12($t0) add $t3, $t1, $t2
lw $t4, 8($t0) sw $t3, 12($t0)
stall add $t5, $t1, $t4 add $t5, $t1, $t4
sw $t5, 16($t0) sw $t5, 16($t0)
13 cycles 11 cycles
Chapter 4 — The Processor — 121
Control Hazards
Branch determines flow of control
Fetching next instruction depends on branch
outcome
Pipeline can’t always fetch correct instruction
Still working on ID stage of branch
In MIPS pipeline
Need to compare registers and compute
target early in the pipeline
Add hardware to do it in ID stage
Chapter 4 — The Processor — 122
Stall on Branch
Wait until branch outcome determined
before fetching next instruction
Chapter 4 — The Processor — 123
Branch Prediction
Longer pipelines can’t readily determine
branch outcome early
Stall penalty becomes unacceptable
Predict outcome of branch
Only stall if prediction is wrong
In MIPS pipeline
Can predict branches not taken
Fetch instruction after branch, with no delay
Chapter 4 — The Processor — 124
MIPS with Predict Not Taken
Prediction
correct
Prediction
incorrect
Chapter 4 — The Processor — 125
More-Realistic Branch Prediction
Static branch prediction
Based on typical branch behavior
Example: loop and if-statement branches
Predict backward branches taken
Predict forward branches not taken
Dynamic branch prediction
Hardware measures actual branch behavior
e.g., record recent history of each branch
Assume future behavior will continue the trend
When wrong, stall while re-fetching, and update history
Chapter 4 — The Processor — 126
Chapter 4 — The Processor — 127
Chapter 4 — The Processor — 128
In this exercise, we examine how data dependences affect execution in the
basic 5-stage pipeline of MIPS processor. Problems in this exercise refer to the
following sequence of instructions:
or r1,r2,r3
or r2,r1,r4
or r1,r1,r2.
Also, assume the following cycle times for each of the options related to
forwarding: Without Forwarding : 250ps, With Full Forwarding : 300 ps, With
ALU-ALU Forwarding Only: 290 ps.
Q1. Indicate dependences and their type.
Q2. Assume there is no forwarding in this pipelined processor. Indicate hazards
and add nop instructions to eliminate them.
Q3. Assume there is full forwarding. Indicate hazards and add NOP instructions
to eliminate them.
Q4. What is the total execution time of this instruction sequence without
forwarding and with full forwarding? What is the speedup achieved by adding
full forwarding to a pipeline that had no forwarding?
Chapter 4 — The Processor — 129
Q5. Add nop instructions to this code to eliminate hazards if there is
ALU-ALU forwarding only (no forwarding from the MEM to the EX
stage) Q6. What is the total execution time of this instruction
sequence with only ALU-ALU forwarding? What is the speedup over
a no-forwarding pipeline?
SOLUTION:
Given Instruction Sequence:
or r1, r2, r3
or r2, r1, r4
or r1, r1, r2
Chapter 4 — The Processor — 130
Q1: Indicate dependences and their type.
RAW (Read After Write) Dependences:
or r2, r1, r4 depends on or r1, r2, r3 because it needs r1 after it is written.
•
•
or r1, r1, r2 depends on or r2, r1, r4 because it needs r2 after it is written.
or r1, r1, r2 also depends on or r1, r2, r3 because it reads r1.
•
WAR (Write After Read) and WAW (Write After Write) Dependences:
No WAR hazard since all read operations occur before dependent
writes
or r1, r1, r2 and or r1, r2, r3 both write to r1, causing a
WAW hazard if instructions are reordered.
Chapter 4 — The Processor — 131
Q2: No Forwarding - Insert NOPs to Resolve Hazards
Without forwarding, results are available only after WB (write-
back), meaning the dependent instruction must wait.
Total Execution Time: 13 cycles
Chapter 4 — The Processor — 132
Q3: Full Forwarding - Insert NOPs to Resolve Hazards
Chapter 4 — The Processor — 133
How Full Forwarding Works
Full forwarding allows data to be bypassed
(forwarded) directly from an intermediate
pipeline stage rather than waiting for WB.
• Instead of waiting for WB (5th stage), forwarding
enables the ALU in the EX stage to use values
from the MEM stage (4th stage) or even from a
prior EX stage.
• The key hardware components that support this
are forwarding paths that detect RAW hazards
and send the correct values to the EX stage
before WB completes.
Chapter 4 — The Processor — 134
Q4: Execution Time & Speedup Calculation
Without Forwarding:
• Each instruction takes 5 cycles, with extra 4 NOPs per
dependence.
• Execution Time = 13 cycles × 250 ps = 3250 ps
With Full Forwarding:
• Execution Time = 9 cycles × 300 ps = 2700 ps
Speedup Calculation:
Chapter 4 — The Processor — 135
Q5: ALU-ALU Forwarding Only (No MEM to EX Forwarding)
• ALU-ALU forwarding allows EX stage to use results from
previous EX stage.
• However, if MEM stage is needed for forwarding, extra
NOPs are required.
Chapter 4 — The Processor — 136
Execution Time & Speedup for ALU-ALU
Forwarding
ALU-ALU forwarding pipeline time = 10 cycles × 290 ps = 2900 ps
Speedup Over No Forwarding:
Chapter 4 — The Processor — 137
Pipeline Summary
The BIG Picture
Pipelining improves performance by
increasing instruction throughput
Executes multiple instructions in parallel
Each instruction has the same latency
Subject to hazards
Structure, data, control
Instruction set design affects complexity of
pipeline implementation
Chapter 4 — The Processor — 138
§4.6 Pipelined Datapath and Control
MIPS Pipelined Datapath
MEM
Right-to-left WB
flow leads to
hazards
Chapter 4 — The Processor — 139
Pipeline registers
Need registers between stages
To hold information produced in previous cycle
Chapter 4 — The Processor — 140
Pipeline Operation
Cycle-by-cycle flow of instructions through
the pipelined datapath
“Single-clock-cycle” pipeline diagram
Shows pipeline usage in a single cycle
Highlight resources used
c.f. “multi-clock-cycle” diagram
Graph of operation over time
We’ll look at “single-clock-cycle” diagrams
for load & store
Chapter 4 — The Processor — 141
IF for Load, Store, …
Chapter 4 — The Processor — 142
ID for Load, Store, …
Chapter 4 — The Processor — 143
EX for Load
Chapter 4 — The Processor — 144
MEM for Load
Chapter 4 — The Processor — 145
WB for Load
Wrong
register
number
Chapter 4 — The Processor — 146
Corrected Datapath for Load
Chapter 4 — The Processor — 147
EX for Store
Chapter 4 — The Processor — 148
MEM for Store
Chapter 4 — The Processor — 149
WB for Store
Chapter 4 — The Processor — 150
Multi-Cycle Pipeline Diagram
Form showing resource usage
Chapter 4 — The Processor — 151
Multi-Cycle Pipeline Diagram
Traditional form
Chapter 4 — The Processor — 152
Single-Cycle Pipeline Diagram
State of pipeline in a given cycle
Chapter 4 — The Processor — 153
Pipelined Control (Simplified)
Chapter 4 — The Processor — 154
Pipelined Control
Control signals derived from instruction
As in single-cycle implementation
Chapter 4 — The Processor — 155
Pipelined Control
Chapter 4 — The Processor — 156
§4.7 Data Hazards: Forwarding vs. Stalling
Data Hazards in ALU Instructions
Consider this sequence:
sub $2, $1,$3
and $12,$2,$5
or $13,$6,$2
add $14,$2,$2
sw $15,100($2)
We can resolve hazards with forwarding
How do we detect when to forward?
Chapter 4 — The Processor — 157
Dependencies & Forwarding
Chapter 4 — The Processor — 158
Detecting the Need to Forward
Pass register numbers along pipeline
e.g., ID/EX.RegisterRs = register number for Rs
sitting in ID/EX pipeline register
ALU operand register numbers in EX stage
are given by
ID/EX.RegisterRs, ID/EX.RegisterRt
Data hazards when
Fwd from
1a. EX/MEM.RegisterRd = ID/EX.RegisterRs EX/MEM
pipeline reg
1b. EX/MEM.RegisterRd = ID/EX.RegisterRt
2a. MEM/WB.RegisterRd = ID/EX.RegisterRs Fwd from
MEM/WB
2b. MEM/WB.RegisterRd = ID/EX.RegisterRt pipeline reg
Chapter 4 — The Processor — 159
Detecting the Need to Forward
But only if forwarding instruction will write
to a register!
EX/MEM.RegWrite, MEM/WB.RegWrite
And only if Rd for that instruction is not
$zero
EX/MEM.RegisterRd ≠ 0,
MEM/WB.RegisterRd ≠ 0
Chapter 4 — The Processor — 160
Forwarding Paths
Chapter 4 — The Processor — 161
Forwarding Conditions
EX hazard
if (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0)
and (EX/MEM.RegisterRd = ID/EX.RegisterRs))
ForwardA = 10
if (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0)
and (EX/MEM.RegisterRd = ID/EX.RegisterRt))
ForwardB = 10
MEM hazard
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0)
and (MEM/WB.RegisterRd = ID/EX.RegisterRs))
ForwardA = 01
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0)
and (MEM/WB.RegisterRd = ID/EX.RegisterRt))
ForwardB = 01
Chapter 4 — The Processor — 162
Double Data Hazard
Consider the sequence:
add $1,$1,$2
add $1,$1,$3
add $1,$1,$4
Both hazards occur
Want to use the most recent
Revise MEM hazard condition
Only fwd if EX hazard condition isn’t true
Chapter 4 — The Processor — 163
Revised Forwarding Condition
MEM hazard
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0)
and not (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0)
and (EX/MEM.RegisterRd = ID/EX.RegisterRs))
and (MEM/WB.RegisterRd = ID/EX.RegisterRs))
ForwardA = 01
if (MEM/WB.RegWrite and (MEM/WB.RegisterRd ≠ 0)
and not (EX/MEM.RegWrite and (EX/MEM.RegisterRd ≠ 0)
and (EX/MEM.RegisterRd = ID/EX.RegisterRt))
and (MEM/WB.RegisterRd = ID/EX.RegisterRt))
ForwardB = 01
Chapter 4 — The Processor — 164
Datapath with Forwarding
Chapter 4 — The Processor — 165
Load-Use Data Hazard
Need to stall
for one cycle
Chapter 4 — The Processor — 166
Load-Use Hazard Detection
Check when using instruction is decoded
in ID stage
ALU operand register numbers in ID stage
are given by
IF/ID.RegisterRs, IF/ID.RegisterRt
Load-use hazard when
ID/EX.MemRead and
((ID/EX.RegisterRt = IF/ID.RegisterRs) or
(ID/EX.RegisterRt = IF/ID.RegisterRt))
If detected, stall and insert bubble
Chapter 4 — The Processor — 167
How to Stall the Pipeline
Force control values in ID/EX register
to 0
EX, MEM and WB do nop (no-operation)
Prevent update of PC and IF/ID register
Using instruction is decoded again
Following instruction is fetched again
1-cycle stall allows MEM to read data for lw
Can subsequently forward to EX stage
Chapter 4 — The Processor — 168
Stall/Bubble in the Pipeline
Stall inserted
here
Chapter 4 — The Processor — 169
Stall/Bubble in the Pipeline
Or, more
accurately…
Chapter 4 — The Processor — 170
Datapath with Hazard Detection
Chapter 4 — The Processor — 171
Stalls and Performance
The BIG Picture
Stalls reduce performance
But are required to get correct results
Compiler can arrange code to avoid
hazards and stalls
Requires knowledge of the pipeline structure
Chapter 4 — The Processor — 172
§4.8 Control Hazards
Branch Hazards
If branch outcome determined in MEM
Flush these
instructions
(Set control
values to 0)
PC
Chapter 4 — The Processor — 173
Reducing Branch Delay
Move hardware to determine outcome to ID
stage
Target address adder
Register comparator
Example: branch taken
36: sub $10, $4, $8
40: beq $1, $3, 7
44: and $12, $2, $5
48: or $13, $2, $6
52: add $14, $4, $2
56: slt $15, $6, $7
...
72: lw $4, 50($7)
Chapter 4 — The Processor — 174
Example: Branch Taken
Chapter 4 — The Processor — 175
Example: Branch Taken
Chapter 4 — The Processor — 176
Data Hazards for Branches
If a comparison register is a destination of
2nd or 3rd preceding ALU instruction
add $1, $2, $3 IF ID EX MEM WB
add $4, $5, $6 IF ID EX MEM WB
… IF ID EX MEM WB
beq $1, $4, target IF ID EX MEM WB
Can resolve using forwarding
Chapter 4 — The Processor — 177
Data Hazards for Branches
If a comparison register is a destination of
preceding ALU instruction or 2nd preceding
load instruction
Need 1 stall cycle
lw $1, addr IF ID EX MEM WB
add $4, $5, $6 IF ID EX MEM WB
beq stalled IF ID
beq $1, $4, target ID EX MEM WB
Chapter 4 — The Processor — 178
Data Hazards for Branches
If a comparison register is a destination of
immediately preceding load instruction
Need 2 stall cycles
lw $1, addr IF ID EX MEM WB
beq stalled IF ID
beq stalled ID
beq $1, $0, target ID EX MEM WB
Chapter 4 — The Processor — 179
Dynamic Branch Prediction
In deeper and superscalar pipelines, branch
penalty is more significant
Use dynamic prediction
Branch prediction buffer (aka branch history table)
Indexed by recent branch instruction addresses
Stores outcome (taken/not taken)
To execute a branch
Check table, expect the same outcome
Start fetching from fall-through or target
If wrong, flush pipeline and flip prediction
Chapter 4 — The Processor — 180
1-Bit Predictor: Shortcoming
Inner loop branches mispredicted twice!
outer: …
…
inner: …
…
beq …, …, inner
…
beq …, …, outer
Mispredict as taken on last iteration of
inner loop
Then mispredict as not taken on first
iteration of inner loop next time around
Chapter 4 — The Processor — 181
2-Bit Predictor
Only change prediction on two successive
mispredictions
Chapter 4 — The Processor — 182
Calculating the Branch Target
Even with predictor, still need to calculate
the target address
1-cycle penalty for a taken branch
Branch target buffer
Cache of target addresses
Indexed by PC when instruction fetched
If hit and instruction is branch predicted taken, can
fetch target immediately
Chapter 4 — The Processor — 183
§4.9 Exceptions
Exceptions and Interrupts
“Unexpected” events requiring change
in flow of control
Different ISAs use the terms differently
Exception
Arises within the CPU
e.g., undefined opcode, overflow, syscall, …
Interrupt
From an external I/O controller
Dealing with them without sacrificing
performance is hard
Chapter 4 — The Processor — 184
Handling Exceptions
In MIPS, exceptions managed by a System
Control Coprocessor (CP0)
Save PC of offending (or interrupted) instruction
In MIPS: Exception Program Counter (EPC)
Save indication of the problem
In MIPS: Cause register
We’ll assume 1-bit
0 for undefined opcode, 1 for overflow
Jump to handler at 8000 00180
Chapter 4 — The Processor — 185
An Alternate Mechanism
Vectored Interrupts
Handler address determined by the cause
Example:
Undefined opcode: C000 0000
Overflow: C000 0020
…: C000 0040
Instructions either
Deal with the interrupt, or
Jump to real handler
Chapter 4 — The Processor — 186
Handler Actions
Read cause, and transfer to relevant
handler
Determine action required
If restartable
Take corrective action
use EPC to return to program
Otherwise
Terminate program
Report error using EPC, cause, …
Chapter 4 — The Processor — 187
Exceptions in a Pipeline
Another form of control hazard
Consider overflow on add in EX stage
add $1, $2, $1
Prevent $1 from being clobbered
Complete previous instructions
Flush add and subsequent instructions
Set Cause and EPC register values
Transfer control to handler
Similar to mispredicted branch
Use much of the same hardware
Chapter 4 — The Processor — 188
Pipeline with Exceptions
Chapter 4 — The Processor — 189
Exception Properties
Restartable exceptions
Pipeline can flush the instruction
Handler executes, then returns to the
instruction
Refetched and executed from scratch
PC saved in EPC register
Identifies causing instruction
Actually PC + 4 is saved
Handler must adjust
Chapter 4 — The Processor — 190
Exception Example
Exception on add in
40 sub $11, $2, $4
44 and $12, $2, $5
48 or $13, $2, $6
4C add $1, $2, $1
50 slt $15, $6, $7
54 lw $16, 50($7)
…
Handler
80000180 sw $25, 1000($0)
80000184 sw $26, 1004($0)
…
Chapter 4 — The Processor — 191
Exception Example
Chapter 4 — The Processor — 192
Exception Example
Chapter 4 — The Processor — 193
Multiple Exceptions
Pipelining overlaps multiple instructions
Could have multiple exceptions at once
Simple approach: deal with exception from
earliest instruction
Flush subsequent instructions
“Precise” exceptions
In complex pipelines
Multiple instructions issued per cycle
Out-of-order completion
Maintaining precise exceptions is difficult!
Chapter 4 — The Processor — 194
Imprecise Exceptions
Just stop pipeline and save state
Including exception cause(s)
Let the handler work out
Which instruction(s) had exceptions
Which to complete or flush
May require “manual” completion
Simplifies hardware, but more complex handler
software
Not feasible for complex multiple-issue
out-of-order pipelines
Chapter 4 — The Processor — 195
§4.10 Parallelism via Instructions
Instruction-Level Parallelism (ILP)
Pipelining: executing multiple instructions in
parallel
To increase ILP
Deeper pipeline
Less work per stage shorter clock cycle
Multiple issue
Replicate pipeline stages multiple pipelines
Start multiple instructions per clock cycle
CPI < 1, so use Instructions Per Cycle (IPC)
E.g., 4GHz 4-way multiple-issue
16 BIPS, peak CPI = 0.25, peak IPC = 4
But dependencies reduce this in practice
Chapter 4 — The Processor — 196
Multiple Issue
Static multiple issue
Compiler groups instructions to be issued together
Packages them into “issue slots”
Compiler detects and avoids hazards
Dynamic multiple issue
CPU examines instruction stream and chooses
instructions to issue each cycle
Compiler can help by reordering instructions
CPU resolves hazards using advanced techniques at
runtime
Chapter 4 — The Processor — 197
Speculation
“Guess” what to do with an instruction
Start operation as soon as possible
Check whether guess was right
If so, complete the operation
If not, roll-back and do the right thing
Common to static and dynamic multiple issue
Examples
Speculate on branch outcome
Roll back if path taken is different
Speculate on load
Roll back if location is updated
Chapter 4 — The Processor — 198
Compiler/Hardware Speculation
Compiler can reorder instructions
e.g., move load before branch
Can include “fix-up” instructions to recover
from incorrect guess
Hardware can look ahead for instructions
to execute
Buffer results until it determines they are
actually needed
Flush buffers on incorrect speculation
Chapter 4 — The Processor — 199
Speculation and Exceptions
What if exception occurs on a
speculatively executed instruction?
e.g., speculative load before null-pointer
check
Static speculation
Can add ISA support for deferring exceptions
Dynamic speculation
Can buffer exceptions until instruction
completion (which may not occur)
Chapter 4 — The Processor — 200
Static Multiple Issue
Compiler groups instructions into “issue
packets”
Group of instructions that can be issued on a
single cycle
Determined by pipeline resources required
Think of an issue packet as a very long
instruction
Specifies multiple concurrent operations
Very Long Instruction Word (VLIW)
Chapter 4 — The Processor — 201
Scheduling Static Multiple Issue
Compiler must remove some/all hazards
Reorder instructions into issue packets
No dependencies with a packet
Possibly some dependencies between
packets
Varies between ISAs; compiler must know!
Pad with nop if necessary
Chapter 4 — The Processor — 202
MIPS with Static Dual Issue
Two-issue packets
One ALU/branch instruction
One load/store instruction
64-bit aligned
ALU/branch, then load/store
Pad an unused instruction with nop
Address Instruction type Pipeline Stages
n ALU/branch IF ID EX MEM WB
n+4 Load/store IF ID EX MEM WB
n+8 ALU/branch IF ID EX MEM WB
n + 12 Load/store IF ID EX MEM WB
n + 16 ALU/branch IF ID EX MEM WB
n + 20 Load/store IF ID EX MEM WB
Chapter 4 — The Processor — 203
MIPS with Static Dual Issue
Chapter 4 — The Processor — 204
Hazards in the Dual-Issue MIPS
More instructions executing in parallel
EX data hazard
Forwarding avoided stalls with single-issue
Now can’t use ALU result in load/store in same packet
add $t0, $s0, $s1
load $s2, 0($t0)
Split into two packets, effectively a stall
Load-use hazard
Still one cycle use latency, but now two instructions
More aggressive scheduling required
Chapter 4 — The Processor — 205
Scheduling Example
Schedule this for dual-issue MIPS
Loop: lw $t0, 0($s1) # $t0=array element
addu $t0, $t0, $s2 # add scalar in $s2
sw $t0, 0($s1) # store result
addi $s1, $s1,–4 # decrement pointer
bne $s1, $zero, Loop # branch $s1!=0
ALU/branch Load/store cycle
Loop: nop lw $t0, 0($s1) 1
addi $s1, $s1,–4 nop 2
addu $t0, $t0, $s2 nop 3
bne $s1, $zero, Loop sw $t0, 4($s1) 4
IPC = 5/4 = 1.25 (c.f. peak IPC = 2)
Chapter 4 — The Processor — 206
Loop Unrolling
Replicate loop body to expose more
parallelism
Reduces loop-control overhead
Use different registers per replication
Called “register renaming”
Avoid loop-carried “anti-dependencies”
Store followed by a load of the same register
Aka “name dependence”
Reuse of a register name
Chapter 4 — The Processor — 207
Loop Unrolling Example
ALU/branch Load/store cycle
Loop: addi $s1, $s1,–16 lw $t0, 0($s1) 1
nop lw $t1, 12($s1) 2
addu $t0, $t0, $s2 lw $t2, 8($s1) 3
addu $t1, $t1, $s2 lw $t3, 4($s1) 4
addu $t2, $t2, $s2 sw $t0, 16($s1) 5
addu $t3, $t4, $s2 sw $t1, 12($s1) 6
nop sw $t2, 8($s1) 7
bne $s1, $zero, Loop sw $t3, 4($s1) 8
IPC = 14/8 = 1.75
Closer to 2, but at cost of registers and code size
Chapter 4 — The Processor — 208
Dynamic Multiple Issue
“Superscalar” processors
CPU decides whether to issue 0, 1, 2, …
each cycle
Avoiding structural and data hazards
Avoids the need for compiler scheduling
Though it may still help
Code semantics ensured by the CPU
Chapter 4 — The Processor — 209
Dynamic Pipeline Scheduling
Allow the CPU to execute instructions out
of order to avoid stalls
But commit result to registers in order
Example
lw $t0, 20($s2)
addu $t1, $t0, $t2
sub $s4, $s4, $t3
slti $t5, $s4, 20
Can start sub while addu is waiting for lw
Chapter 4 — The Processor — 210
Dynamically Scheduled CPU
Preserves
dependencies
Hold pending
operands
Results also sent
to any waiting
reservation
stations
Reorders buffer for
register writes
Can supply
operands for
issued instructions
Chapter 4 — The Processor — 211
Register Renaming
Reservation stations and reorder buffer
effectively provide register renaming
On instruction issue to reservation station
If operand is available in register file or
reorder buffer
Copied to reservation station
No longer required in the register; can be
overwritten
If operand is not yet available
It will be provided to the reservation station by a
function unit
Register update may not be required
Chapter 4 — The Processor — 212
Speculation
Predict branch and continue issuing
Don’t commit until branch outcome
determined
Load speculation
Avoid load and cache miss delay
Predict the effective address
Predict loaded value
Load before completing outstanding stores
Bypass stored values to load unit
Don’t commit load until speculation cleared
Chapter 4 — The Processor — 213
Why Do Dynamic Scheduling?
Why not just let the compiler schedule
code?
Not all stalls are predicable
e.g., cache misses
Can’t always schedule around branches
Branch outcome is dynamically determined
Different implementations of an ISA have
different latencies and hazards
Chapter 4 — The Processor — 214
Does Multiple Issue Work?
The BIG Picture
Yes, but not as much as we’d like
Programs have real dependencies that limit ILP
Some dependencies are hard to eliminate
e.g., pointer aliasing
Some parallelism is hard to expose
Limited window size during instruction issue
Memory delays and limited bandwidth
Hard to keep pipelines full
Speculation can help if done well
Chapter 4 — The Processor — 215
Power Efficiency
Complexity of dynamic scheduling and
speculations requires power
Multiple simpler cores may be better
Microprocessor Year Clock Rate Pipeline Issue Out-of-order/ Cores Power
Stages width Speculation
i486 1989 25MHz 5 1 No 1 5W
Pentium 1993 66MHz 5 2 No 1 10W
Pentium Pro 1997 200MHz 10 3 Yes 1 29W
P4 Willamette 2001 2000MHz 22 3 Yes 1 75W
P4 Prescott 2004 3600MHz 31 3 Yes 1 103W
Core 2006 2930MHz 14 4 Yes 2 75W
UltraSparc III 2003 1950MHz 14 4 No 1 90W
UltraSparc T1 2005 1200MHz 6 1 No 8 70W
Chapter 4 — The Processor — 216
§4.11 Real Stuff: The ARM Cortex-A8 and Intel Core i7 Pipelines
Cortex A8 and Intel i7
Processor ARM A8 Intel Core i7 920
Market Personal Mobile Device Server, cloud
Thermal design power 2 Watts 130 Watts
Clock rate 1 GHz 2.66 GHz
Cores/Chip 1 4
Floating point? No Yes
Multiple issue? Dynamic Dynamic
Peak instructions/clock cycle 2 4
Pipeline stages 14 14
Pipeline schedule Static in-order Dynamic out-of-order
with speculation
Branch prediction 2-level 2-level
1st level caches/core 32 KiB I, 32 KiB D 32 KiB I, 32 KiB D
2nd level caches/core 128-1024 KiB 256 KiB
3rd level caches (shared) - 2- 8 MB
Chapter 4 — The Processor — 217
ARM Cortex-A8 Pipeline
Chapter 4 — The Processor — 218
ARM Cortex-A8 Performance
Chapter 4 — The Processor — 219
Core i7 Pipeline
Chapter 4 — The Processor — 220
Core i7 Performance
Chapter 4 — The Processor — 221
§4.12 Instruction-Level Parallelism and Matrix Multiply
Matrix Multiply
Unrolled C code
1 #include <x86intrin.h>
2 #define UNROLL (4)
3
4 void dgemm (int n, double* A, double* B, double* C)
5 {
6 for ( int i = 0; i < n; i+=UNROLL*4 )
7 for ( int j = 0; j < n; j++ ) {
8 __m256d c[4];
9 for ( int x = 0; x < UNROLL; x++ )
10 c[x] = _mm256_load_pd(C+i+x*4+j*n);
11
12 for( int k = 0; k < n; k++ )
13 {
14 __m256d b = _mm256_broadcast_sd(B+k+j*n);
15 for (int x = 0; x < UNROLL; x++)
16 c[x] = _mm256_add_pd(c[x],
17 _mm256_mul_pd(_mm256_load_pd(A+n*k+x*4+i), b));
18 }
19
20 for ( int x = 0; x < UNROLL; x++ )
21 _mm256_store_pd(C+i+x*4+j*n, c[x]);
22 }
23 }
Chapter 4 — The Processor — 222
§4.12 Instruction-Level Parallelism and Matrix Multiply
Matrix Multiply
Assembly code:
1 vmovapd (%r11),%ymm4 # Load 4 elements of C into %ymm4
2 mov %rbx,%rax # register %rax = %rbx
3 xor %ecx,%ecx # register %ecx = 0
4 vmovapd 0x20(%r11),%ymm3 # Load 4 elements of C into %ymm3
5 vmovapd 0x40(%r11),%ymm2 # Load 4 elements of C into %ymm2
6 vmovapd 0x60(%r11),%ymm1 # Load 4 elements of C into %ymm1
7 vbroadcastsd (%rcx,%r9,1),%ymm0 # Make 4 copies of B element
8 add $0x8,%rcx # register %rcx = %rcx + 8
9 vmulpd (%rax),%ymm0,%ymm5 # Parallel mul %ymm1,4 A elements
10 vaddpd %ymm5,%ymm4,%ymm4 # Parallel add %ymm5, %ymm4
11 vmulpd 0x20(%rax),%ymm0,%ymm5 # Parallel mul %ymm1,4 A elements
12 vaddpd %ymm5,%ymm3,%ymm3 # Parallel add %ymm5, %ymm3
13 vmulpd 0x40(%rax),%ymm0,%ymm5 # Parallel mul %ymm1,4 A elements
14 vmulpd 0x60(%rax),%ymm0,%ymm0 # Parallel mul %ymm1,4 A elements
15 add %r8,%rax # register %rax = %rax + %r8
16 cmp %r10,%rcx # compare %r8 to %rax
17 vaddpd %ymm5,%ymm2,%ymm2 # Parallel add %ymm5, %ymm2
18 vaddpd %ymm0,%ymm1,%ymm1 # Parallel add %ymm0, %ymm1
19 jne 68 <dgemm+0x68> # jump if not %r8 != %rax
20 add $0x1,%esi # register % esi = % esi + 1
21 vmovapd %ymm4,(%r11) # Store %ymm4 into 4 C elements
22 vmovapd %ymm3,0x20(%r11) # Store %ymm3 into 4 C elements
23 vmovapd %ymm2,0x40(%r11) # Store %ymm2 into 4 C elements
24 vmovapd %ymm1,0x60(%r11) # Store %ymm1 into 4 C elements
Chapter 4 — The Processor — 223
Performance Impact
Chapter 4 — The Processor — 224
§4.14 Fallacies and Pitfalls
Fallacies
Pipelining is easy (!)
The basic idea is easy
The devil is in the details
e.g., detecting data hazards
Pipelining is independent of technology
So why haven’t we always done pipelining?
More transistors make more advanced techniques
feasible
Pipeline-related ISA design needs to take account of
technology trends
e.g., predicated instructions
Chapter 4 — The Processor — 225
Pitfalls
Poor ISA design can make pipelining
harder
e.g., complex instruction sets (VAX, IA-32)
Significant overhead to make pipelining work
IA-32 micro-op approach
e.g., complex addressing modes
Register update side effects, memory indirection
e.g., delayed branches
Advanced pipelines have long delay slots
Chapter 4 — The Processor — 226
§4.14 Concluding Remarks
Concluding Remarks
ISA influences design of datapath and control
Datapath and control influence design of ISA
Pipelining improves instruction throughput
using parallelism
More instructions completed per second
Latency for each instruction not reduced
Hazards: structural, data, control
Multiple issue and dynamic scheduling (ILP)
Dependencies limit achievable parallelism
Complexity leads to the power wall
Chapter 4 — The Processor — 227