cleanup
[ieee754fpu.git] / src / add / nmigen_add_experiment.py
1 # IEEE Floating Point Adder (Single Precision)
2 # Copyright (C) Jonathan P Dawson 2013
3 # 2013-12-12
4
5 from nmigen import Module, Signal, Cat
6 from nmigen.cli import main
7
8
9 class FPNum:
10 """ Floating-point Number Class, variable-width TODO (currently 32-bit)
11
12 Contains signals for an incoming copy of the value, decoded into
13 sign / exponent / mantissa.
14 Also contains encoding functions, creation and recognition of
15 zero, NaN and inf (all signed)
16
17 Four extra bits are included in the mantissa: the top bit
18 (m[-1]) is effectively a carry-overflow. The other three are
19 guard (m[2]), round (m[1]), and sticky (m[0])
20 """
21 def __init__(self, width, m_width=None):
22 self.width = width
23 if m_width is None:
24 m_width = width - 5 # mantissa extra bits (top,guard,round)
25 self.v = Signal(width) # Latched copy of value
26 self.m = Signal(m_width) # Mantissa
27 self.e = Signal((10, True)) # Exponent: 10 bits, signed
28 self.s = Signal() # Sign bit
29
30 def decode(self):
31 """ decodes a latched value into sign / exponent / mantissa
32
33 bias is subtracted here, from the exponent.
34 """
35 v = self.v
36 return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
37 self.e.eq(Cat(v[23:31]) - 127), # exponent (take off bias)
38 self.s.eq(Cat(v[31])), # sign
39 ]
40
41 def create(self, s, e, m):
42 """ creates a value from sign / exponent / mantissa
43
44 bias is added here, to the exponent
45 """
46 return [
47 self.v[31].eq(s), # sign
48 self.v[23:31].eq(e + 127), # exp (add on bias)
49 self.v[0:23].eq(m) # mantissa
50 ]
51
52 def shift_down(self):
53 """ shifts a mantissa down by one. exponent is increased to compensate
54
55 accuracy is lost as a result in the mantissa however there are 3
56 guard bits (the latter of which is the "sticky" bit)
57 """
58 return self.create(self.s,
59 self.e + 1,
60 Cat(self.m[0] | self.m[1], self.m[1:-5], 0))
61
62 def nan(self, s):
63 return self.create(s, 0x80, 1<<22)
64
65 def inf(self, s):
66 return self.create(s, 0x80, 0)
67
68 def zero(self, s):
69 return self.create(s, -127, 0)
70
71 def is_nan(self):
72 return (self.e == 128) & (self.m != 0)
73
74 def is_inf(self):
75 return (self.e == 128) & (self.m == 0)
76
77 def is_zero(self):
78 return (self.e == -127) & (self.m == 0)
79
80
81 class FPADD:
82 def __init__(self, width):
83 self.width = width
84
85 self.in_a = Signal(width)
86 self.in_a_stb = Signal()
87 self.in_a_ack = Signal()
88
89 self.in_b = Signal(width)
90 self.in_b_stb = Signal()
91 self.in_b_ack = Signal()
92
93 self.out_z = Signal(width)
94 self.out_z_stb = Signal()
95 self.out_z_ack = Signal()
96
97 def get_fragment(self, platform):
98 m = Module()
99
100 # Latches
101 a = FPNum(self.width)
102 b = FPNum(self.width)
103 z = FPNum(self.width, 24)
104
105 tot = Signal(28) # sticky/round/guard bits, 23 result, 1 overflow
106
107 guard = Signal() # tot[2]
108 round_bit = Signal() # tot[1]
109 sticky = Signal() # tot[0]
110
111 with m.FSM() as fsm:
112
113 # ******
114 # gets operand a
115
116 with m.State("get_a"):
117 with m.If((self.in_a_ack) & (self.in_a_stb)):
118 m.next = "get_b"
119 m.d.sync += [
120 a.v.eq(self.in_a),
121 self.in_a_ack.eq(0)
122 ]
123 with m.Else():
124 m.d.sync += self.in_a_ack.eq(1)
125
126 # ******
127 # gets operand b
128
129 with m.State("get_b"):
130 with m.If((self.in_b_ack) & (self.in_b_stb)):
131 m.next = "get_a"
132 m.d.sync += [
133 b.v.eq(self.in_b),
134 self.in_b_ack.eq(0)
135 ]
136 with m.Else():
137 m.d.sync += self.in_b_ack.eq(1)
138
139 # ******
140 # unpacks operands into sign, mantissa and exponent
141
142 with m.State("unpack"):
143 m.next = "special_cases"
144 m.d.sync += a.decode()
145 m.d.sync += b.decode()
146
147 # ******
148 # special cases: NaNs, infs, zeros, denormalised
149
150 with m.State("special_cases"):
151
152 # if a is NaN or b is NaN return NaN
153 with m.If(a.is_nan() | b.is_nan()):
154 m.next = "put_z"
155 m.d.sync += z.nan(1)
156
157 # if a is inf return inf (or NaN)
158 with m.Elif(a.is_inf()):
159 m.next = "put_z"
160 m.d.sync += z.inf(a.s)
161 # if a is inf and signs don't match return NaN
162 with m.If((b.e == 128) & (a.s != b.s)):
163 m.d.sync += z.nan(b.s)
164
165 # if b is inf return inf
166 with m.Elif(b.is_inf()):
167 m.next = "put_z"
168 m.d.sync += z.inf(b.s)
169
170 # if a is zero and b zero return signed-a/b
171 with m.Elif(a.is_zero() & b.is_zero()):
172 m.next = "put_z"
173 m.d.sync += z.create(a.s & b.s, b.e[0:8], b.m[3:26])
174
175 # if a is zero return b
176 with m.Elif(a.is_zero()):
177 m.next = "put_z"
178 m.d.sync += z.create(b.s, b.e[0:8], b.m[3:26])
179
180 # if b is zero return a
181 with m.Elif(b.is_zero()):
182 m.next = "put_z"
183 m.d.sync += z.create(a.s, a.e[0:8], a.m[3:26])
184
185 # Denormalised Number checks
186 with m.Else():
187 m.next = "align"
188 # denormalise a check
189 with m.If(a.e == -127):
190 m.d.sync += a.e.eq(-126) # limit a exponent
191 with m.Else():
192 m.d.sync += a.m[26].eq(1) # set highest mantissa bit
193 # denormalise b check
194 with m.If(b.e == -127):
195 m.d.sync += b.e.eq(-126) # limit b exponent
196 with m.Else():
197 m.d.sync += b.m[26].eq(1) # set highest mantissa bit
198
199 # ******
200 # align. NOTE: this does *not* do single-cycle multi-shifting,
201 # it *STAYS* in the align state until the exponents match
202
203 with m.State("align"):
204 # exponent of a greater than b: increment b exp, shift b mant
205 with m.If(a.e > b.e):
206 m.d.sync += b.shift_down()
207 # exponent of b greater than a: increment a exp, shift a mant
208 with m.Elif(a.e < b.e):
209 m.d.sync += a.shift_down()
210 # exponents equal: move to next stage.
211 with m.Else():
212 m.next = "add_0"
213
214 # ******
215 # First stage of add. covers same-sign (add) and subtract
216 # special-casing when mantissas are greater or equal, to
217 # give greatest accuracy.
218
219 with m.State("add_0"):
220 m.next = "add_1"
221 m.d.sync += z.e.eq(a.e)
222 # same-sign (both negative or both positive) add mantissas
223 with m.If(a.s == b.s):
224 m.d.sync += [
225 tot.eq(a.m + b.m),
226 z.s.eq(a.s)
227 ]
228 # a mantissa greater than b, use a
229 with m.Elif(a.m >= b.m):
230 m.d.sync += [
231 tot.eq(a.m - b.m),
232 z.s.eq(a.s)
233 ]
234 # b mantissa greater than a, use b
235 with m.Else():
236 m.d.sync += [
237 tot.eq(b.m - a.m),
238 z.s.eq(b.s)
239 ]
240
241 # ******
242 # Second stage of add: preparation for normalisation.
243 # detects when tot sum is too big (tot[27] is kinda a carry bit)
244
245 with m.State("add_1"):
246 m.next = "normalise_1"
247 # tot[27] gets set when the sum overflows. shift result down
248 with m.If(tot[27]):
249 m.d.sync += [
250 z.m.eq(tot[4:28]),
251 guard.eq(tot[3]),
252 round_bit.eq(tot[2]),
253 sticky.eq(tot[1] | tot[0]),
254 z.e.eq(z.e + 1)
255 ]
256 # tot[27] zero case
257 with m.Else():
258 m.d.sync += [
259 z.m.eq(tot[3:27]),
260 guard.eq(tot[2]),
261 round_bit.eq(tot[1]),
262 sticky.eq(tot[0])
263 ]
264
265 # ******
266 # First stage of normalisation.
267 # NOTE: just like "align", this one keeps going round every clock
268 # until the result's exponent is within acceptable "range"
269 # NOTE: the weirdness of reassigning guard and round is due to
270 # the extra mantissa bits coming from tot[0..2]
271
272 with m.State("normalise_1"):
273 with m.If((z.m[23] == 0) & (z.e > -126)):
274 m.d.sync +=[
275 z.e.eq(z.e - 1), # DECREASE exponent
276 z.m.eq(z.m << 1), # shift mantissa UP
277 z.m[0].eq(guard), # steal guard bit (was tot[2])
278 guard.eq(round_bit), # steal round_bit (was tot[1])
279 ]
280 with m.Else():
281 m.next = "normalize_2"
282
283 # ******
284 # Second stage of normalisation.
285 # NOTE: just like "align", this one keeps going round every clock
286 # until the result's exponent is within acceptable "range"
287 # NOTE: the weirdness of reassigning guard and round is due to
288 # the extra mantissa bits coming from tot[0..2]
289
290 with m.State("normalise_2"):
291 with m.If(z.e < -126):
292 m.d.sync +=[
293 z.e.eq(z.e + 1), # INCREASE exponent
294 z.m.eq(z.m >> 1), # shift mantissa DOWN
295 guard.eq(z.m[0]),
296 round_bit.eq(guard),
297 sticky.eq(sticky | round_bit)
298 ]
299 with m.Else():
300 m.next = "round"
301
302 # ******
303 # rounding stage
304
305 with m.State("round"):
306 m.next = "pack"
307 with m.If(guard & (round_bit | sticky | z.m[0])):
308 m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
309 with m.If(z.m == 0xffffff): # all 1s
310 m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
311
312 # ******
313 # pack stage
314
315 with m.State("pack"):
316 m.next = "put_z"
317 m.d.sync += [
318 z.v[0:22].eq(z.m[0:22]),
319 z.v[22:31].eq(z.e[0:7]),
320 z.v[31].eq(z.s)
321 ]
322 with m.If((z.e == -126) & (z.m[23] == 0)):
323 m.d.sync += z.v[23:31].eq(0)
324 with m.If((z.e == -126) & (z.m[0:23] == 0)):
325 m.d.sync += z.v[23:31].eq(0)
326 with m.If(z.e > 127):
327 m.d.sync += [
328 z.v[0:22].eq(0),
329 z.v[23:31].eq(255),
330 z.v[31].eq(z.s),
331 ]
332
333 # ******
334 # put_z stage
335
336 """
337 put_z:
338 begin
339 s_out_z_stb <= 1;
340 s_out_z <= z;
341 if (s_out_z_stb && out_z_ack) begin
342 s_out_z_stb <= 0;
343 state <= get_a;
344 end
345 end
346 """
347
348 return m
349
350 """
351 always @(posedge clk)
352 begin
353
354 case(state)
355
356 get_a:
357 begin
358 s_in_a_ack <= 1;
359 if (s_in_a_ack && in_a_stb) begin
360 a <= in_a;
361 s_in_a_ack <= 0;
362 state <= get_b;
363 end
364 end
365
366 get_b:
367 begin
368 s_in_b_ack <= 1;
369 if (s_in_b_ack && in_b_stb) begin
370 b <= in_b;
371 s_in_b_ack <= 0;
372 state <= unpack;
373 end
374 end
375
376 unpack:
377 begin
378 a_m <= {a[22 : 0], 3'd0};
379 b_m <= {b[22 : 0], 3'd0};
380 a_e <= a[30 : 23] - 127;
381 b_e <= b[30 : 23] - 127;
382 a_s <= a[31];
383 b_s <= b[31];
384 state <= special_cases;
385 end
386
387 special_cases:
388 begin
389 //if a is NaN or b is NaN return NaN
390 if ((a_e == 128 && a_m != 0) || (b_e == 128 && b_m != 0)) begin
391 z[31] <= 1;
392 z[30:23] <= 255;
393 z[22] <= 1;
394 z[21:0] <= 0;
395 state <= put_z;
396 //if a is inf return inf
397 end else if (a_e == 128) begin
398 z[31] <= a_s;
399 z[30:23] <= 255;
400 z[22:0] <= 0;
401 //if a is inf and signs don't match return nan
402 if ((b_e == 128) && (a_s != b_s)) begin
403 z[31] <= b_s;
404 z[30:23] <= 255;
405 z[22] <= 1;
406 z[21:0] <= 0;
407 end
408 state <= put_z;
409 //if b is inf return inf
410 end else if (b_e == 128) begin
411 z[31] <= b_s;
412 z[30:23] <= 255;
413 z[22:0] <= 0;
414 state <= put_z;
415 //if a is zero return b
416 end else if ((($signed(a_e) == -127) && (a_m == 0)) && (($signed(b_e) == -127) && (b_m == 0))) begin
417 z[31] <= a_s & b_s;
418 z[30:23] <= b_e[7:0] + 127;
419 z[22:0] <= b_m[26:3];
420 state <= put_z;
421 //if a is zero return b
422 end else if (($signed(a_e) == -127) && (a_m == 0)) begin
423 z[31] <= b_s;
424 z[30:23] <= b_e[7:0] + 127;
425 z[22:0] <= b_m[26:3];
426 state <= put_z;
427 //if b is zero return a
428 end else if (($signed(b_e) == -127) && (b_m == 0)) begin
429 z[31] <= a_s;
430 z[30:23] <= a_e[7:0] + 127;
431 z[22:0] <= a_m[26:3];
432 state <= put_z;
433 end else begin
434 //Denormalised Number
435 if ($signed(a_e) == -127) begin
436 a_e <= -126;
437 end else begin
438 a_m[26] <= 1;
439 end
440 //Denormalised Number
441 if ($signed(b_e) == -127) begin
442 b_e <= -126;
443 end else begin
444 b_m[26] <= 1;
445 end
446 state <= align;
447 end
448 end
449
450 align:
451 begin
452 if ($signed(a_e) > $signed(b_e)) begin
453 b_e <= b_e + 1;
454 b_m <= b_m >> 1;
455 b_m[0] <= b_m[0] | b_m[1];
456 end else if ($signed(a_e) < $signed(b_e)) begin
457 a_e <= a_e + 1;
458 a_m <= a_m >> 1;
459 a_m[0] <= a_m[0] | a_m[1];
460 end else begin
461 state <= add_0;
462 end
463 end
464
465 add_0:
466 begin
467 z_e <= a_e;
468 if (a_s == b_s) begin
469 tot <= a_m + b_m;
470 z_s <= a_s;
471 end else begin
472 if (a_m >= b_m) begin
473 tot <= a_m - b_m;
474 z_s <= a_s;
475 end else begin
476 tot <= b_m - a_m;
477 z_s <= b_s;
478 end
479 end
480 state <= add_1;
481 end
482
483 add_1:
484 begin
485 if (tot[27]) begin
486 z_m <= tot[27:4];
487 guard <= tot[3];
488 round_bit <= tot[2];
489 sticky <= tot[1] | tot[0];
490 z_e <= z_e + 1;
491 end else begin
492 z_m <= tot[26:3];
493 guard <= tot[2];
494 round_bit <= tot[1];
495 sticky <= tot[0];
496 end
497 state <= normalise_1;
498 end
499
500 normalise_1:
501 begin
502 if (z_m[23] == 0 && $signed(z_e) > -126) begin
503 z_e <= z_e - 1;
504 z_m <= z_m << 1;
505 z_m[0] <= guard;
506 guard <= round_bit;
507 round_bit <= 0;
508 end else begin
509 state <= normalise_2;
510 end
511 end
512
513 normalise_2:
514 begin
515 if ($signed(z_e) < -126) begin
516 z_e <= z_e + 1;
517 z_m <= z_m >> 1;
518 guard <= z_m[0];
519 round_bit <= guard;
520 sticky <= sticky | round_bit;
521 end else begin
522 state <= round;
523 end
524 end
525
526 round:
527 begin
528 if (guard && (round_bit | sticky | z_m[0])) begin
529 z_m <= z_m + 1;
530 if (z_m == 24'hffffff) begin
531 z_e <=z_e + 1;
532 end
533 end
534 state <= pack;
535 end
536
537 pack:
538 begin
539 z[22 : 0] <= z_m[22:0];
540 z[30 : 23] <= z_e[7:0] + 127;
541 z[31] <= z_s;
542 if ($signed(z_e) == -126 && z_m[23] == 0) begin
543 z[30 : 23] <= 0;
544 end
545 if ($signed(z_e) == -126 && z_m[23:0] == 24'h0) begin
546 z[31] <= 1'b0; // FIX SIGN BUG: -a + a = +0.
547 end
548 //if overflow occurs, return inf
549 if ($signed(z_e) > 127) begin
550 z[22 : 0] <= 0;
551 z[30 : 23] <= 255;
552 z[31] <= z_s;
553 end
554 state <= put_z;
555 end
556
557 put_z:
558 begin
559 s_out_z_stb <= 1;
560 s_out_z <= z;
561 if (s_out_z_stb && out_z_ack) begin
562 s_out_z_stb <= 0;
563 state <= get_a;
564 end
565 end
566
567 endcase
568
569 if (rst == 1) begin
570 state <= get_a;
571 s_in_a_ack <= 0;
572 s_in_b_ack <= 0;
573 s_out_z_stb <= 0;
574 end
575
576 end
577 assign in_a_ack = s_in_a_ack;
578 assign in_b_ack = s_in_b_ack;
579 assign out_z_stb = s_out_z_stb;
580 assign out_z = s_out_z;
581
582 endmodule
583 """
584
585 if __name__ == "__main__":
586 alu = FPADD(width=32)
587 main(alu, ports=[
588 alu.in_a, alu.in_a_stb, alu.in_a_ack,
589 alu.in_b, alu.in_b_stb, alu.in_b_ack,
590 alu.out_z, alu.out_z_stb, alu.out_z_ack,
591 ])
592
593
594 """
595 print(verilog.convert(alu, ports=[in_a, in_a_stb, in_a_ack, #doesnt work for some reason
596 in_b, in_b_stb, in_b_ack,
597 out_z, out_z_stb, out_z_ack]))
598 """