use constant P128 instead of 128
[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, Const
6 from nmigen.cli import main, verilog
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 self.mzero = Const(0, (m_width, False))
31 self.P128 = Const(128, (10, True))
32 self.P127 = Const(127, (10, True))
33 self.N127 = Const(-127, (10, True))
34 self.N126 = Const(-126, (10, True))
35
36 def decode(self):
37 """ decodes a latched value into sign / exponent / mantissa
38
39 bias is subtracted here, from the exponent. exponent
40 is extended to 10 bits so that subtract 127 is done on
41 a 10-bit number
42 """
43 v = self.v
44 return [self.m.eq(Cat(0, 0, 0, v[0:23])), # mantissa
45 self.e.eq(v[23:31] - self.P127), # exp (minus bias)
46 self.s.eq(v[31]), # sign
47 ]
48
49 def create(self, s, e, m):
50 """ creates a value from sign / exponent / mantissa
51
52 bias is added here, to the exponent
53 """
54 return [
55 self.v[31].eq(s), # sign
56 self.v[23:31].eq(e + self.P127), # exp (add on bias)
57 self.v[0:23].eq(m) # mantissa
58 ]
59
60 def shift_down(self):
61 """ shifts a mantissa down by one. exponent is increased to compensate
62
63 accuracy is lost as a result in the mantissa however there are 3
64 guard bits (the latter of which is the "sticky" bit)
65 """
66 return [self.e.eq(self.e + 1),
67 self.m.eq(Cat(self.m[0] | self.m[1], self.m[2:], 0))
68 ]
69
70 def nan(self, s):
71 return self.create(s, self.P128, 1<<22)
72
73 def inf(self, s):
74 return self.create(s, self.P128, 0)
75
76 def zero(self, s):
77 return self.create(s, self.N127, 0)
78
79 def is_nan(self):
80 return (self.e == self.P128) & (self.m != 0)
81
82 def is_inf(self):
83 return (self.e == self.P128) & (self.m == 0)
84
85 def is_zero(self):
86 return (self.e == self.N127) & (self.m == self.mzero)
87
88 def is_overflowed(self):
89 return (self.e > self.P127)
90
91 def is_denormalised(self):
92 return (self.e == self.N126) & (self.m[23] == 0)
93
94
95 class FPADD:
96 def __init__(self, width):
97 self.width = width
98
99 self.in_a = Signal(width)
100 self.in_a_stb = Signal()
101 self.in_a_ack = Signal()
102
103 self.in_b = Signal(width)
104 self.in_b_stb = Signal()
105 self.in_b_ack = Signal()
106
107 self.out_z = Signal(width)
108 self.out_z_stb = Signal()
109 self.out_z_ack = Signal()
110
111 def get_fragment(self, platform=None):
112 m = Module()
113
114 # Latches
115 a = FPNum(self.width)
116 b = FPNum(self.width)
117 z = FPNum(self.width, 24)
118
119 tot = Signal(28) # sticky/round/guard bits, 23 result, 1 overflow
120
121 guard = Signal() # tot[2]
122 round_bit = Signal() # tot[1]
123 sticky = Signal() # tot[0]
124
125 with m.FSM() as fsm:
126
127 # ******
128 # gets operand a
129
130 with m.State("get_a"):
131 with m.If((self.in_a_ack) & (self.in_a_stb)):
132 m.next = "get_b"
133 m.d.sync += [
134 a.v.eq(self.in_a),
135 self.in_a_ack.eq(0)
136 ]
137 with m.Else():
138 m.d.sync += self.in_a_ack.eq(1)
139
140 # ******
141 # gets operand b
142
143 with m.State("get_b"):
144 with m.If((self.in_b_ack) & (self.in_b_stb)):
145 m.next = "unpack"
146 m.d.sync += [
147 b.v.eq(self.in_b),
148 self.in_b_ack.eq(0)
149 ]
150 with m.Else():
151 m.d.sync += self.in_b_ack.eq(1)
152
153 # ******
154 # unpacks operands into sign, mantissa and exponent
155
156 with m.State("unpack"):
157 m.next = "special_cases"
158 m.d.sync += a.decode()
159 m.d.sync += b.decode()
160
161 # ******
162 # special cases: NaNs, infs, zeros, denormalised
163
164 with m.State("special_cases"):
165
166 # if a is NaN or b is NaN return NaN
167 with m.If(a.is_nan() | b.is_nan()):
168 m.next = "put_z"
169 m.d.sync += z.nan(1)
170
171 # if a is inf return inf (or NaN)
172 with m.Elif(a.is_inf()):
173 m.next = "put_z"
174 m.d.sync += z.inf(a.s)
175 # if a is inf and signs don't match return NaN
176 with m.If((b.e == b.P128) & (a.s != b.s)):
177 m.d.sync += z.nan(b.s)
178
179 # if b is inf return inf
180 with m.Elif(b.is_inf()):
181 m.next = "put_z"
182 m.d.sync += z.inf(b.s)
183
184 # if a is zero and b zero return signed-a/b
185 with m.Elif(a.is_zero() & b.is_zero()):
186 m.next = "put_z"
187 m.d.sync += z.create(a.s & b.s, b.e[0:8], b.m[3:26])
188
189 # if a is zero return b
190 with m.Elif(a.is_zero()):
191 m.next = "put_z"
192 m.d.sync += z.create(b.s, b.e[0:8], b.m[3:26])
193
194 # if b is zero return a
195 with m.Elif(b.is_zero()):
196 m.next = "put_z"
197 m.d.sync += z.create(a.s, a.e[0:8], a.m[3:26])
198
199 # Denormalised Number checks
200 with m.Else():
201 m.next = "align"
202 # denormalise a check
203 with m.If(a.e == a.N127):
204 m.d.sync += a.e.eq(-126) # limit a exponent
205 with m.Else():
206 m.d.sync += a.m[26].eq(1) # set top mantissa bit
207 # denormalise b check
208 with m.If(b.e == a.N127):
209 m.d.sync += b.e.eq(-126) # limit b exponent
210 with m.Else():
211 m.d.sync += b.m[26].eq(1) # set top mantissa bit
212
213 # ******
214 # align. NOTE: this does *not* do single-cycle multi-shifting,
215 # it *STAYS* in the align state until the exponents match
216
217 with m.State("align"):
218 # exponent of a greater than b: increment b exp, shift b mant
219 with m.If(a.e > b.e):
220 m.d.sync += b.shift_down()
221 # exponent of b greater than a: increment a exp, shift a mant
222 with m.Elif(a.e < b.e):
223 m.d.sync += a.shift_down()
224 # exponents equal: move to next stage.
225 with m.Else():
226 m.next = "add_0"
227
228 # ******
229 # First stage of add. covers same-sign (add) and subtract
230 # special-casing when mantissas are greater or equal, to
231 # give greatest accuracy.
232
233 with m.State("add_0"):
234 m.next = "add_1"
235 m.d.sync += z.e.eq(a.e)
236 # same-sign (both negative or both positive) add mantissas
237 with m.If(a.s == b.s):
238 m.d.sync += [
239 tot.eq(a.m + b.m),
240 z.s.eq(a.s)
241 ]
242 # a mantissa greater than b, use a
243 with m.Elif(a.m >= b.m):
244 m.d.sync += [
245 tot.eq(a.m - b.m),
246 z.s.eq(a.s)
247 ]
248 # b mantissa greater than a, use b
249 with m.Else():
250 m.d.sync += [
251 tot.eq(b.m - a.m),
252 z.s.eq(b.s)
253 ]
254
255 # ******
256 # Second stage of add: preparation for normalisation.
257 # detects when tot sum is too big (tot[27] is kinda a carry bit)
258
259 with m.State("add_1"):
260 m.next = "normalise_1"
261 # tot[27] gets set when the sum overflows. shift result down
262 with m.If(tot[27]):
263 m.d.sync += [
264 z.m.eq(tot[4:28]),
265 guard.eq(tot[3]),
266 round_bit.eq(tot[2]),
267 sticky.eq(tot[1] | tot[0]),
268 z.e.eq(z.e + 1)
269 ]
270 # tot[27] zero case
271 with m.Else():
272 m.d.sync += [
273 z.m.eq(tot[3:27]),
274 guard.eq(tot[2]),
275 round_bit.eq(tot[1]),
276 sticky.eq(tot[0])
277 ]
278
279 # ******
280 # First stage of normalisation.
281 # NOTE: just like "align", this one keeps going round every clock
282 # until the result's exponent is within acceptable "range"
283 # NOTE: the weirdness of reassigning guard and round is due to
284 # the extra mantissa bits coming from tot[0..2]
285
286 with m.State("normalise_1"):
287 with m.If((z.m[23] == 0) & (z.e > z.N126)):
288 m.d.sync +=[
289 z.e.eq(z.e - 1), # DECREASE exponent
290 z.m.eq(z.m << 1), # shift mantissa UP
291 z.m[0].eq(guard), # steal guard bit (was tot[2])
292 guard.eq(round_bit), # steal round_bit (was tot[1])
293 ]
294 with m.Else():
295 m.next = "normalise_2"
296
297 # ******
298 # Second stage of normalisation.
299 # NOTE: just like "align", this one keeps going round every clock
300 # until the result's exponent is within acceptable "range"
301 # NOTE: the weirdness of reassigning guard and round is due to
302 # the extra mantissa bits coming from tot[0..2]
303
304 with m.State("normalise_2"):
305 with m.If(z.e < z.N126):
306 m.d.sync +=[
307 z.e.eq(z.e + 1), # INCREASE exponent
308 z.m.eq(z.m >> 1), # shift mantissa DOWN
309 guard.eq(z.m[0]),
310 round_bit.eq(guard),
311 sticky.eq(sticky | round_bit)
312 ]
313 with m.Else():
314 m.next = "round"
315
316 # ******
317 # rounding stage
318
319 with m.State("round"):
320 m.next = "corrections"
321 with m.If(guard & (round_bit | sticky | z.m[0])):
322 m.d.sync += z.m.eq(z.m + 1) # mantissa rounds up
323 with m.If(z.m == 0xffffff): # all 1s
324 m.d.sync += z.e.eq(z.e + 1) # exponent rounds up
325
326 # ******
327 # correction stage
328
329 with m.State("corrections"):
330 m.next = "pack"
331 # denormalised, correct exponent to zero
332 with m.If(z.is_denormalised()):
333 m.d.sync += z.m.eq(-127)
334 # FIX SIGN BUG: -a + a = +0.
335 with m.If((z.e == z.N126) & (z.m[0:23] == 0)):
336 m.d.sync += z.s.eq(0)
337
338 # ******
339 # pack stage
340
341 with m.State("pack"):
342 m.next = "put_z"
343 # if overflow occurs, return inf
344 with m.If(z.is_overflowed()):
345 m.d.sync += z.inf(0)
346 with m.Else():
347 m.d.sync += z.create(z.s, z.e, z.m)
348
349 # ******
350 # put_z stage
351
352 with m.State("put_z"):
353 m.d.sync += [
354 self.out_z_stb.eq(1),
355 self.out_z.eq(z.v)
356 ]
357 with m.If(self.out_z_stb & self.out_z_ack):
358 m.d.sync += self.out_z_stb.eq(0)
359 m.next = "get_a"
360
361 return m
362
363
364 if __name__ == "__main__":
365 alu = FPADD(width=32)
366 main(alu, ports=[
367 alu.in_a, alu.in_a_stb, alu.in_a_ack,
368 alu.in_b, alu.in_b_stb, alu.in_b_ack,
369 alu.out_z, alu.out_z_stb, alu.out_z_ack,
370 ])
371
372
373 # works... but don't use, just do "python fname.py convert -t v"
374 #print (verilog.convert(alu, ports=[
375 # alu.in_a, alu.in_a_stb, alu.in_a_ack,
376 # alu.in_b, alu.in_b_stb, alu.in_b_ack,
377 # alu.out_z, alu.out_z_stb, alu.out_z_ack,
378 # ]))