In the last chapter, chapter 24 we explained the creation and implementation of sequential logic written in the HDL (Hardware Description Language) Verilog.
In this chapter we go deeper down the rabbit hole and see how multiplication and division of integers are realised in hardware:
For multipliers and divisors that are powers of two this is easy, as it just means shifting bits to the left - which is multiplication, or to the right, which is division. More complex cases are handled and discussed later - for now let’s look at shifting.
Shifting and Barrel Shifter
Note | Why >>> and not >>?Verilog has two right shift operators:
For an unsigned value, In C and Java, |
The shift commands (sll, srl, sra)
| command | name | direction | shifted in | input | result |
|---|---|---|---|---|---|
| shift left logical | left | zeros from the right |
|
|
| shift right logical | right | zeros from the left |
|
|
| shift right arithmetic | right | copies of the sign bit from the left |
|
|
Important | Why no shift left arithmetic (sla)? The difference between “logical” and “arithmetic” lies solely in what is shifted into the space that becomes available. When shifting to the right, space becomes available on the left—that is, where the sign bit is located. There are two reasonable options: zeros for unsigned numbers (srl) or copies of the sign bit for signed numbers (sra). When shifting left, space is freed up on the right, at the least significant bit. A 0 is always correct there, regardless of whether the number has a sign or not. Even in two’s complement, “multiply by 2” simply means “shift everything one place to the left, with a 0 on the right”: -3 = 11111101 << 1 = 11111010 = -6 5 = 00000101 << 1 = 00001010 = 10 So an sla would produce exactly the same bits as sll. It would just be a second name for the same operation. If the result does not fit into the range of numbers, the sign flips: 100 = 01100100 << 1 = 11001000 = -56 (instead of 200) This is an overflow, just like with add. Keeping the sign bit fixed would not help either: 200 simply does not fit into 8 bits with a sign. |
The Barrel Shifter
What if we had hardware that shifts bits to the left or to the right by an arbitrary number of positions?
This is exactly what a barrel shifter does; its functionality is explained below, command by command…
A barrel shifter can shift the bits by the amount of shamt, so for 1, 2, 4 or a combination of these amounts.
Shift right logical
srl: shift right logical
every bit moves to the right, zeros come in from the left
1
2
3
4
5
6
7
8
9
10
11
12
// srl: shift right logical, 8 bit. Zeros are shifted in from the left.
module shifter_srl (
input wire [7:0] a,
input wire [2:0] shamt,
output wire [7:0] y
);
wire [7:0] s1, s2;
assign s1 = shamt[0] ? {1'b0, a[7:1]} : a; // shift by 1 or not
assign s2 = shamt[1] ? {2'b00, s1[7:2]} : s1; // shift by 2 or not
assign y = shamt[2] ? {4'b0000, s2[7:4]} : s2; // shift by 4 or not
endmodule
Shift right arithmetic
sra: shift right arithmetic
every bit moves to the right, copies of the sign bit a7 come in from the left
1
2
3
4
5
6
7
8
9
10
11
12
// sra: shift right arithmetic, 8 bit. Copies of the sign bit a[7] are shifted in from the left.
module shifter_sra (
input wire [7:0] a,
input wire [2:0] shamt,
output wire [7:0] y
);
wire [7:0] s1, s2;
assign s1 = shamt[0] ? {a[7], a[7:1]} : a; // shift by 1 or not
assign s2 = shamt[1] ? {{2{a[7]}}, s1[7:2]} : s1; // shift by 2 or not
assign y = shamt[2] ? {{4{a[7]}}, s2[7:4]} : s2; // shift by 4 or not
endmodule
Shift left logical
sll: shift left logical
every bit moves to the left, zeros come in from the right
1
2
3
4
5
6
7
8
9
10
11
12
// sll: shift left logical, 8 bit. Zeros are shifted in from the right.
module shifter_sll (
input wire [7:0] a,
input wire [2:0] shamt,
output wire [7:0] y
);
wire [7:0] s1, s2;
assign s1 = shamt[0] ? {a[6:0], 1'b0} : a; // shift by 1 or not
assign s2 = shamt[1] ? {s1[5:0], 2'b00} : s1; // shift by 2 or not
assign y = shamt[2] ? {s2[3:0], 4'b0000} : s2; // shift by 4 or not
endmodule
All three commands together
Next we want hardware that combines all three different commands.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// All three shifts in one circuit: sll, srl and sra, 8 bit.
// op = 00: sll (shift left logical)
// op = 01: srl (shift right logical)
// op = 11: sra (shift right arithmetic)
// The three stages always shift to the right. A left shift is done by
// reversing the bit order before and after shifting.
module shifter_all (
input wire [7:0] a,
input wire [2:0] shamt,
input wire [1:0] op,
output wire [7:0] y
);
wire left = (op == 2'b00); // sll
wire fill = op[1] & a[7]; // sra: sign bit, sll/srl: 0
// reverse the bit order for sll: a[0] becomes bit 7, a[7] becomes bit 0
wire [7:0] a_rev = {a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]};
wire [7:0] in = left ? a_rev : a;
// the three shift stages, always to the right
wire [7:0] s1, s2, s3;
assign s1 = shamt[0] ? {fill, in[7:1]} : in; // shift by 1 or not
assign s2 = shamt[1] ? {{2{fill}}, s1[7:2]} : s1; // shift by 2 or not
assign s3 = shamt[2] ? {{4{fill}}, s2[7:4]} : s2; // shift by 4 or not
// reverse back after shifting
wire [7:0] s3_rev = {s3[0], s3[1], s3[2], s3[3], s3[4], s3[5], s3[6], s3[7]};
assign y = left ? s3_rev : s3;
endmodule
The Shifter Testbench
The testbench checks all four circuits at once: the three single shifters for sll, srl and sra, and the combined shifter, which is instantiated three times, once for each value of op.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
`timescale 1ns / 1ps
// Tests the three single-purpose shifters and the combined shifter against the Verilog operators.
module shifters_tb;
reg [7:0] a;
reg [2:0] shamt;
wire [7:0] y_sll, y_srl, y_sra;
wire [7:0] all_sll, all_srl, all_sra;
reg [7:0] exp_sll, exp_srl, exp_sra;
integer i, j, errors = 0;
shifter_sll u_sll (.a(a), .shamt(shamt), .y(y_sll));
shifter_srl u_srl (.a(a), .shamt(shamt), .y(y_srl));
shifter_sra u_sra (.a(a), .shamt(shamt), .y(y_sra));
// the combined shifter, once for every operation
shifter_all u_all_sll (.a(a), .shamt(shamt), .op(2'b00), .y(all_sll));
shifter_all u_all_srl (.a(a), .shamt(shamt), .op(2'b01), .y(all_srl));
shifter_all u_all_sra (.a(a), .shamt(shamt), .op(2'b11), .y(all_sra));
initial begin
a = 8'b1001_0110; shamt = 3; #1;
$display("a = %b, shamt = 3: sll = %b srl = %b sra = %b", a, y_sll, y_srl, y_sra);
for (i = 0; i < 256; i = i + 1)
for (j = 0; j < 8; j = j + 1) begin
a = i; shamt = j; #1;
// compute the expected values first: inside a comparison with an unsigned
// signal, $signed(a) >>> shamt would be evaluated unsigned (and shift in zeros)
exp_sll = a << shamt;
exp_srl = a >> shamt;
exp_sra = $signed(a) >>> shamt;
if (y_sll !== exp_sll || y_srl !== exp_srl || y_sra !== exp_sra
|| all_sll !== exp_sll || all_srl !== exp_srl || all_sra !== exp_sra) begin
errors = errors + 1;
$display("ERROR: a=%b shamt=%0d", a, shamt);
end
end
if (errors == 0) $display("PASSED: all 2048 combinations correct for sll, srl, sra and the combined shifter");
else $display("FAILED: %0d errors", errors);
$finish;
end
endmodule
First, it prints one example to read: a = 10010110 shifted by 3, which gives 10110000 for sll, 00010010 for srl and 11110010 for sra.
Then it runs through every possible input: all 256 values of a and all 8 shift amounts, 2048 combinations in total.
For each of them, it compares the outputs with the result of the Verilog operators <<, >> and >>>.
If all outputs match, the testbench reports PASSED. Because every combination is tested, PASSED means
that the circuits are correct for every input, not just for a few examples.
Warning | A trap in the testbench The expected values are first stored in their own registers (exp_sll, exp_srl, exp_sra) and only then compared. This looks unnecessary, but it is not. In a comparison like y_sra !== $signed(a) >>> shamt Verilog evaluates the whole expression as unsigned, because y_sra is unsigned. Then |
Multiplier
Multiplying by a power of two is a single shift. But every number is a sum of powers of two, so every multiplication is a sum of shifts:
\[ x \cdot 10 = x \cdot (8 + 2) = (x \ll 3) + (x \ll 1) \]
This is the basic idea of all multipliers: for every bit of the multiplier that is 1, the multiplicand is shifted to the position of this bit and added.
Long Multiplication
Binary multiplication works exactly like long multiplication in school, only simpler. Every bit of the multiplier b produces one row, a partial product: if the bit is 1, the row is the multiplicand a, if it is 0, the row is all zeros. Each row is shifted one position further to the left. At the end, all rows are added.
In binary, a partial product is nothing but an AND: every bit of a is ANDed with one bit of b. And the result needs twice as many bits as the inputs: 4 bit times 4 bit gives up to 8 bit, because 15 · 15 = 225.
Array Multiplier
The array multiplier builds the long multiplication directly in hardware: one row of AND gates for every bit of b, and one adder for every row after the first. For the adders, we reuse the ripple-carry adder from chapter 23 (ripple_adder.v and full_adder.v), with its parameter N set to the width of the multiplier.
The figure follows our example 13 · 11. In every row, the lowest bit of the sum is already final: it does not change anymore, because all following rows are shifted further to the left. So it leaves the array as one bit of the product (p0 to p3), and only the remaining bits, together with the carry, move on to the next row. After the last row, these remaining bits are the upper half of the product.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// N x N array multiplier (unsigned), purely combinational.
// Like long multiplication on paper: every bit of b selects a partial product
// (a AND b[i]), and one ripple-carry adder per row adds it to the running sum.
module array_multiplier #(
parameter N = 4
) (
input wire [N-1:0] a,
input wire [N-1:0] b,
output wire [2*N-1:0] p
);
// partial products: row i = a AND b[i]
wire [N-1:0] pp [0:N-1];
// running sum after each row (upper N bits, the lowest bit is already final)
wire [N-1:0] acc [0:N-1];
genvar i;
generate
for (i = 0; i < N; i = i + 1) begin : partial
assign pp[i] = a & {N{b[i]}};
end
// row 0: nothing to add yet, bit 0 of the product is final
assign p[0] = pp[0][0];
assign acc[0] = {1'b0, pp[0][N-1:1]};
// rows 1 .. N-1: one adder per row
for (i = 1; i < N; i = i + 1) begin : row
wire [N-1:0] sum;
wire cout;
ripple_adder #(.N(N)) add (
.a(acc[i-1]), .b(pp[i]), .cin(1'b0),
.sum(sum), .cout(cout)
);
assign p[i] = sum[0]; // lowest bit is final
assign acc[i] = {cout, sum[N-1:1]}; // the rest moves on to the next row
end
endgenerate
// after the last row, the remaining bits are the upper half of the product
assign p[2*N-1:N] = acc[N-1];
endmodule
The Verilog code describes this structure with two generate loops: the first creates the partial products pp[i] = a & {N{b[i]}}, the second creates one adder per row. Since the code only says how the rows are connected, the same module works for any N.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
`timescale 1ns / 1ps
// Exhaustive test of the 4 x 4 array multiplier: all 256 combinations.
module array_multiplier_tb;
reg [3:0] a, b;
wire [7:0] p;
integer i, j, errors = 0;
array_multiplier #(.N(4)) dut (.a(a), .b(b), .p(p));
initial begin
a = 13; b = 11; #1;
$display("%0d * %0d = %0d (%b * %b = %b)", a, b, p, a, b, p);
for (i = 0; i < 16; i = i + 1)
for (j = 0; j < 16; j = j + 1) begin
a = i; b = j; #1;
if (p !== a * b) begin
errors = errors + 1;
$display("ERROR: %0d * %0d = %0d, expected %0d", a, b, p, a * b);
end
end
if (errors == 0) $display("PASSED: all 256 products correct");
else $display("FAILED: %0d errors", errors);
$finish;
end
endmodule
The testbench prints our example (13 · 11 = 143) and then compares all 256 combinations of two 4-bit numbers with the Verilog
operator *. If all of them match, it reports PASSED.
The array multiplier delivers the result within one clock cycle, but it has two drawbacks. First, its size grows with the square of N: N rows of N AND gates and N−1 adders. Yosys synthesizes the 4-bit version into 64 cells, the 8-bit version already into 327. A 32-bit version would be huge. Second, the signals have to ripple through all adders one after another. This long path limits the clock frequency.
Sequential Multiplier
The sequential multiplier solves the size problem the other way round: instead of N adders side by side, it uses one single adder N times, one bit of the multiplier per clock cycle.
The trick is the product register. Its upper half holds the running sum, its lower half the multiplier bits that have not been processed yet. In every clock cycle, two things happen:
If the lowest bit prod[0] is 1, the multiplicand is added to the upper half.
Then the whole register is shifted right by one bit.
The shift brings the next multiplier bit to position 0, and at the same time it moves the lowest finished bit of the product into the lower half. After N cycles, all multiplier bits have been used up, and the register holds the complete product. The upper half has one extra bit, because the addition can produce a carry.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Sequential shift-and-add multiplier (unsigned), one bit per clock cycle.
// Needs only one N-bit adder instead of N-1 adders, but takes N clock cycles.
//
// The product register holds the upper half (running sum) and the lower half
// (the remaining multiplier bits) at the same time: in every cycle
// 1. if the lowest bit is 1, the multiplicand is added to the upper half,
// 2. the whole register is shifted right by one bit.
// After N cycles the register contains the complete product.
module seq_multiplier #(
parameter N = 8
) (
input wire clk,
input wire rst,
input wire start, // one clock cycle high: start a multiplication
input wire [N-1:0] a, // multiplicand
input wire [N-1:0] b, // multiplier
output wire [2*N-1:0] p, // product
output reg busy,
output reg done // high when p is valid, until the next start
);
reg [N-1:0] mcand; // multiplicand, stays constant
reg [2*N:0] prod; // one extra bit for the carry of the addition
reg [$clog2(N+1)-1:0] count; // remaining steps
wire [N:0] upper = prod[2*N:N] + (prod[0] ? {1'b0, mcand} : {(N+1){1'b0}});
always @(posedge clk) begin
if (rst) begin
busy <= 0;
done <= 0;
count <= 0;
prod <= 0;
mcand <= 0;
end else if (start && !busy) begin
mcand <= a;
prod <= {{(N+1){1'b0}}, b}; // upper half 0, lower half = multiplier
count <= N;
busy <= 1;
done <= 0;
end else if (busy) begin
prod <= {upper, prod[N-1:0]} >> 1; // add, then shift right
count <= count - 1;
if (count == 1) begin
busy <= 0;
done <= 1;
end
end
end
assign p = prod[2*N-1:0];
endmodule
Here, the sequential logic from chapter 24 comes into play. A pulse on start loads the multiplicand, puts the multiplier into the lower half and sets a counter to N. While busy is 1, the circuit adds and shifts in every clock cycle and counts down. When the counter runs out, done goes to 1 and the product p is valid.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
`timescale 1ns / 1ps
module seq_multiplier_tb;
reg clk = 0;
reg rst = 1;
reg start = 0;
reg [7:0] a = 0, b = 0;
wire [15:0] p;
wire busy, done;
integer i, j, errors = 0, tests = 0;
seq_multiplier #(.N(8)) dut (
.clk(clk), .rst(rst), .start(start), .a(a), .b(b),
.p(p), .busy(busy), .done(done)
);
// for the waveform: the two halves of the product register
wire [7:0] upper = dut.prod[15:8]; // running sum
wire [7:0] lower = dut.prod[7:0]; // remaining multiplier bits (and the finished product bits)
// clock: period 10 ns
always #5 clk = ~clk;
// start one multiplication and wait until it is done
task multiply(input [7:0] x, input [7:0] y);
begin
@(negedge clk); // change inputs away from the rising edge
a = x; b = y; start = 1;
@(negedge clk);
start = 0;
@(posedge done);
@(negedge clk);
tests = tests + 1;
if (p !== x * y) begin
errors = errors + 1;
$display("ERROR: %0d * %0d = %0d, expected %0d", x, y, p, x * y);
end
end
endtask
initial begin
$dumpfile("seq_multiplier.vcd");
$dumpvars(0, seq_multiplier_tb);
#12 rst = 0;
multiply(13, 11);
$display("t=%0d ns 13 * 11 = %0d", $time, p);
#20 $dumpoff; // the exhaustive test would make the file huge
for (i = 0; i < 256; i = i + 1)
for (j = 0; j < 256; j = j + 1)
multiply(i, j);
if (errors == 0) $display("PASSED: %0d products correct", tests);
else $display("FAILED: %0d of %0d", errors, tests);
$finish;
end
endmodule
The testbench uses a task to start a multiplication and to wait for done. It runs our example first and then all 65,536 combinations of two 8-bit numbers, which takes a few seconds. For the waveform, it shows the two halves of the product register as the signals upper and lower.
The waveform shows the multiplication 13 · 11, with b = 00001011. At 25 ns, start loads the register, and the counter starts at 8. From 35 ns on, one step follows every clock edge. In the first two steps, the lowest bit is 1: the multiplicand 13 is added, and the register is shifted. In the third step, the lowest bit is 0, so it is only shifted. You can watch the bits of b moving out of lower to the right, while the finished product bits move in from the left. After 8 steps, at 105 ns, done goes to 1: upper is 00000000, lower is 10001111, and p is 143.
Space versus time
| array multiplier | sequential multiplier | ||
|---|---|---|---|
cells (8 bit) | 327 | 113 (30 of them flipflops) | |
clock cycles per multiplication | 1 | 8 | |
size grows with | N² | N |
This is a basic principle of hardware design: area can be traded for time. The barrel shifter was the "everything at once" kind of circuit, the sequential multiplier is the first "step by step" one. Real CPUs use faster methods, such as Booth encoding, Wallace trees or pipelining, but they are all built on these two ideas.
Note | What about signed numbers? Both multipliers work with unsigned numbers. Interestingly, the lower N bits of the product are the same for signed and unsigned numbers. That is why RISC-V has only one instruction mul for the lower half. Only the upper half differs, so there are three instructions for it: mulh (signed · signed), mulhu (unsigned · unsigned) and mulhsu (signed · unsigned). |
Divider
Division is the inverse of multiplication: instead of shifting and adding, we shift and subtract.
Long Division
Again, we start with the method from school. Take as many digits of the dividend as needed until the divisor fits, write a 1 into the quotient, subtract the divisor and bring down the next digit. If the divisor does not fit, write a 0 and just bring down the next digit.
In binary, this is even simpler than in decimal: the divisor fits either once or not at all. So there is no guessing how many times it fits, every step is just a comparison and a subtraction, and every quotient bit is either 1 or 0. In our example, 1100100 (100) divided by 111 (7) gives 1110 (14), with the remainder 10 (2).
Sequential Divider
The sequential divider does exactly these steps, one quotient bit per clock cycle. It needs three registers: the divisor, which stays constant, the remainder, which starts at 0, and the quotient register, which starts with the dividend. In every clock cycle:
The next bit of the dividend, the MSB of the quotient register, is shifted into the remainder from the right. This is "bringing down the next digit".
The divisor is subtracted from this shifted value. If there is no borrow, the difference is not negative: the divisor fits. Then the difference becomes the new remainder. If it does not fit, the remainder keeps its old value, it is "restored". That is why this method is called restoring division.
The quotient register is shifted left, and the result of the comparison, fits, becomes its new lowest bit.
So the quotient register serves two purposes at the same time: on the left, the dividend bits are shifted out, and on the right, the quotient bits are shifted in. After N cycles, all dividend bits are used up, and the register holds the complete quotient. The remainder register holds the remainder.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// Sequential restoring divider (unsigned), one quotient bit per clock cycle.
// Works like long division on paper: in every cycle, the next bit of the
// dividend is shifted into the remainder, and the divisor is subtracted if it fits.
// - fits (no borrow): remainder = difference, quotient bit = 1
// - does not fit: remainder stays (is "restored"), quotient bit = 0
// After N cycles: quotient = dividend / divisor, remainder = dividend % divisor.
//
// Division by zero needs no special case: the divisor 0 always "fits",
// so the quotient becomes all ones and the remainder equals the dividend.
// This is exactly what RISC-V specifies for divu/remu.
module seq_divider #(
parameter N = 8
) (
input wire clk,
input wire rst,
input wire start, // one clock cycle high: start a division
input wire [N-1:0] dividend,
input wire [N-1:0] divisor,
output reg [N-1:0] quotient,
output reg [N-1:0] remainder,
output reg busy,
output reg done // high when the results are valid, until the next start
);
reg [N-1:0] dsor; // divisor, stays constant
reg [$clog2(N+1)-1:0] count; // remaining steps
// shift the next dividend bit (MSB of the quotient register) into the remainder
wire [N:0] shifted = {remainder, quotient[N-1]};
wire [N:0] diff = shifted - {1'b0, dsor};
wire fits = !diff[N]; // no borrow: divisor fits
always @(posedge clk) begin
if (rst) begin
busy <= 0;
done <= 0;
count <= 0;
quotient <= 0;
remainder <= 0;
dsor <= 0;
end else if (start && !busy) begin
dsor <= divisor;
quotient <= dividend; // the quotient register starts with the dividend
remainder <= 0;
count <= N;
busy <= 1;
done <= 0;
end else if (busy) begin
remainder <= fits ? diff[N-1:0] : shifted[N-1:0];
quotient <= {quotient[N-2:0], fits};
count <= count - 1;
if (count == 1) begin
busy <= 0;
done <= 1;
end
end
end
endmodule
The control is the same as in the sequential multiplier: start loads the registers and sets the counter to N, busy is 1 while the circuit is working, and done signals that quotient and remainder are valid. The subtraction uses N+1 bits, so that the borrow appears in the top bit diff[N]: if it is 0, the divisor fits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
`timescale 1ns / 1ps
module seq_divider_tb;
reg clk = 0;
reg rst = 1;
reg start = 0;
reg [7:0] dividend = 0, divisor = 0;
wire [7:0] quotient, remainder;
wire busy, done;
reg [7:0] exp_q, exp_r;
integer i, j, errors = 0, tests = 0;
seq_divider #(.N(8)) dut (
.clk(clk), .rst(rst), .start(start),
.dividend(dividend), .divisor(divisor),
.quotient(quotient), .remainder(remainder),
.busy(busy), .done(done)
);
// clock: period 10 ns
always #5 clk = ~clk;
// start one division and wait until it is done
task divide(input [7:0] x, input [7:0] y);
begin
@(negedge clk);
dividend = x; divisor = y; start = 1;
@(negedge clk);
start = 0;
@(posedge done);
@(negedge clk);
// division by zero: RISC-V defines quotient = all ones, remainder = dividend
exp_q = (y == 0) ? 8'hFF : x / y;
exp_r = (y == 0) ? x : x % y;
tests = tests + 1;
if (quotient !== exp_q || remainder !== exp_r) begin
errors = errors + 1;
$display("ERROR: %0d / %0d = %0d rest %0d, expected %0d rest %0d",
x, y, quotient, remainder, exp_q, exp_r);
end
end
endtask
initial begin
$dumpfile("seq_divider.vcd");
$dumpvars(0, seq_divider_tb);
#12 rst = 0;
divide(100, 7);
$display("t=%0d ns 100 / 7 = %0d rest %0d", $time, quotient, remainder);
divide(42, 0);
$display("t=%0d ns 42 / 0 = %0d rest %0d", $time, quotient, remainder);
$dumpoff; // the exhaustive test would make the file huge
for (i = 0; i < 256; i = i + 1)
for (j = 0; j < 256; j = j + 1)
divide(i, j);
if (errors == 0) $display("PASSED: %0d divisions correct", tests);
else $display("FAILED: %0d of %0d", errors, tests);
$finish;
end
endmodule
The testbench divides 100 by 7 and 42 by 0 first, and then checks all 65,536 combinations of two 8-bit numbers
against the Verilog operators / and %.
The waveform shows the division 100 : 7. At 25 ns, start loads the quotient register with the dividend 01100100. From 35 ns on, one step follows every clock edge. In the first four steps, the remainder grows to 0, 1, 3 and 6 while the dividend bits move in, but 7 never fits, so the quotient bits are 0. In the fifth step, at 75 ns, the remainder would be 12: the divisor fits, the remainder becomes 12 − 7 = 5, and a 1 moves into the quotient register. After 8 steps, at 105 ns, done goes to 1: the quotient register holds 00001110 (14), the remainder is 2.
Note | Division by zero What happens if the divisor is 0? The circuit needs no special case for this: 0 always "fits", so every quotient bit becomes 1, and nothing is ever subtracted from the remainder. The result is a quotient of all ones (255) and the dividend as the remainder, so 42 : 0 gives 255 remainder 42. This is exactly what RISC-V specifies for the instructions divu and remu: dividing by zero raises no exception, the quotient is all ones and the remainder is the dividend. The program has to check for a zero divisor itself. |
Signed division
Our divider works with unsigned numbers only. For signed numbers, a CPU usually divides the absolute values and corrects the sign afterwards. Two details are worth knowing:
Rounding: RISC-V’s div rounds towards zero, like C does: −7 / 2 = −3, with the remainder −1. The arithmetic shift from the beginning of this chapter rounds down instead: −7 >>> 1 = −4. So for negative numbers, a division by 2 is not the same as an arithmetic shift right.
Overflow: The smallest number divided by −1 does not fit: in 8 bits, −128 / −1 would be +128. RISC-V defines the result as −128, with the remainder 0.
Clock cycles compared
How long do our circuits need? With N = 8 bits, the testbenches show:
| circuit | clock cycles (8 bit) | clock cycles (32 bit) | size grows with |
|---|---|---|---|
barrel shifter | 1 | 1 | N · log2 N |
array multiplier | 1 | 1 | N² |
sequential multiplier | 8 (+1 to load) | 32 (+1) | N |
sequential divider | 8 (+1 to load) | 32 (+1) | N |
The combinational circuits deliver their result within one clock cycle, but the longer the path through the adders, the slower that clock cycle has to be. The sequential circuits need one cycle per bit, plus one cycle in which start loads the registers. In the waveforms, start loads at 25 ns, and done goes to 1 at 105 ns: eight steps of 10 ns each.
Real processors make the same trade-off:
The Arm Cortex-M0+, a small microcontroller core, can be built with either of our two kinds of multiplier: a single-cycle multiplier, or a 32-cycle multiplier that needs less area. The chip designer chooses.
The Cortex-M0+ has no divide instruction at all. The RP2040 therefore adds a divider next to each of its two cores, which needs 8 clock cycles for a 32-bit division.
A desktop processor like Intel’s Skylake multiplies two 64-bit numbers with a latency of 3 clock cycles. A 64-bit division takes between about 35 and 89 cycles, depending on the values.
Note | Multiplication has become fast everywhere, division has not. The reason is visible in our circuits: the partial products of a multiplication are all independent of each other, so they can be calculated at the same time and added in a tree. In a division, every step needs the remainder of the step before: whether the divisor fits can only be decided once the previous subtraction is done. Fast dividers do several bits per cycle, but they cannot do all bits at once. That is why compilers replace a division by a constant with a multiplication whenever they can, and why the shift from the beginning of this chapter is still the fastest way to divide by a power of two. |