move corrections to separate class
[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, verilog
7
8 from fpbase import FPNumIn, FPNumOut, FPOp, Overflow, FPBase
9
10
11 class FPState(FPBase):
12 def __init__(self, state_from):
13 self.state_from = state_from
14
15 def set_inputs(self, inputs):
16 self.inputs = inputs
17 for k,v in inputs.items():
18 setattr(self, k, v)
19
20 def set_outputs(self, outputs):
21 self.outputs = outputs
22 for k,v in outputs.items():
23 setattr(self, k, v)
24
25
26 class FPGetOpA(FPState):
27
28 def action(self, m):
29 self.get_op(m, self.in_a, self.a, "get_b")
30
31
32 class FPGetOpB(FPState):
33
34 def action(self, m):
35 self.get_op(m, self.in_b, self.b, "special_cases")
36
37
38 class FPAddSpecialCases(FPState):
39
40 def action(self, m):
41 """ special cases: NaNs, infs, zeros, denormalised
42 NOTE: some of these are unique to add. see "Special Operations"
43 https://steve.hollasch.net/cgindex/coding/ieeefloat.html
44 """
45 s_nomatch = Signal()
46 m.d.comb += s_nomatch.eq(self.a.s != self.b.s)
47
48 m_match = Signal()
49 m.d.comb += m_match.eq(self.a.m == self.b.m)
50
51 # if a is NaN or b is NaN return NaN
52 with m.If(self.a.is_nan | self.b.is_nan):
53 m.next = "put_z"
54 m.d.sync += self.z.nan(1)
55
56 # XXX WEIRDNESS for FP16 non-canonical NaN handling
57 # under review
58
59 ## if a is zero and b is NaN return -b
60 #with m.If(a.is_zero & (a.s==0) & b.is_nan):
61 # m.next = "put_z"
62 # m.d.sync += z.create(b.s, b.e, Cat(b.m[3:-2], ~b.m[0]))
63
64 ## if b is zero and a is NaN return -a
65 #with m.Elif(b.is_zero & (b.s==0) & a.is_nan):
66 # m.next = "put_z"
67 # m.d.sync += z.create(a.s, a.e, Cat(a.m[3:-2], ~a.m[0]))
68
69 ## if a is -zero and b is NaN return -b
70 #with m.Elif(a.is_zero & (a.s==1) & b.is_nan):
71 # m.next = "put_z"
72 # m.d.sync += z.create(a.s & b.s, b.e, Cat(b.m[3:-2], 1))
73
74 ## if b is -zero and a is NaN return -a
75 #with m.Elif(b.is_zero & (b.s==1) & a.is_nan):
76 # m.next = "put_z"
77 # m.d.sync += z.create(a.s & b.s, a.e, Cat(a.m[3:-2], 1))
78
79 # if a is inf return inf (or NaN)
80 with m.Elif(self.a.is_inf):
81 m.next = "put_z"
82 m.d.sync += self.z.inf(self.a.s)
83 # if a is inf and signs don't match return NaN
84 with m.If(self.b.exp_128 & s_nomatch):
85 m.d.sync += self.z.nan(1)
86
87 # if b is inf return inf
88 with m.Elif(self.b.is_inf):
89 m.next = "put_z"
90 m.d.sync += self.z.inf(self.b.s)
91
92 # if a is zero and b zero return signed-a/b
93 with m.Elif(self.a.is_zero & self.b.is_zero):
94 m.next = "put_z"
95 m.d.sync += self.z.create(self.a.s & self.b.s, self.b.e,
96 self.b.m[3:-1])
97
98 # if a is zero return b
99 with m.Elif(self.a.is_zero):
100 m.next = "put_z"
101 m.d.sync += self.z.create(self.b.s, self.b.e, self.b.m[3:-1])
102
103 # if b is zero return a
104 with m.Elif(self.b.is_zero):
105 m.next = "put_z"
106 m.d.sync += self.z.create(self.a.s, self.a.e, self.a.m[3:-1])
107
108 # if a equal to -b return zero (+ve zero)
109 with m.Elif(s_nomatch & m_match & (self.a.e == self.b.e)):
110 m.next = "put_z"
111 m.d.sync += self.z.zero(0)
112
113 # Denormalised Number checks
114 with m.Else():
115 m.next = "denormalise"
116
117
118 class FPAddDeNorm(FPState):
119
120 def action(self, m):
121 # Denormalised Number checks
122 m.next = "align"
123 self.denormalise(m, self.a)
124 self.denormalise(m, self.b)
125
126
127 class FPAddAlignMulti(FPState):
128
129 def action(self, m):
130 # NOTE: this does *not* do single-cycle multi-shifting,
131 # it *STAYS* in the align state until exponents match
132
133 # exponent of a greater than b: shift b down
134 with m.If(self.a.e > self.b.e):
135 m.d.sync += self.b.shift_down()
136 # exponent of b greater than a: shift a down
137 with m.Elif(self.a.e < self.b.e):
138 m.d.sync += self.a.shift_down()
139 # exponents equal: move to next stage.
140 with m.Else():
141 m.next = "add_0"
142
143
144 class FPAddAlignSingle(FPState):
145
146 def action(self, m):
147 # This one however (single-cycle) will do the shift
148 # in one go.
149
150 # XXX TODO: the shifter used here is quite expensive
151 # having only one would be better
152
153 ediff = Signal((len(self.a.e), True), reset_less=True)
154 ediffr = Signal((len(self.a.e), True), reset_less=True)
155 m.d.comb += ediff.eq(self.a.e - self.b.e)
156 m.d.comb += ediffr.eq(self.b.e - self.a.e)
157 with m.If(ediff > 0):
158 m.d.sync += self.b.shift_down_multi(ediff)
159 # exponent of b greater than a: shift a down
160 with m.Elif(ediff < 0):
161 m.d.sync += self.a.shift_down_multi(ediffr)
162
163 m.next = "add_0"
164
165
166 class FPAddStage0(FPState):
167
168 def action(self, m):
169 """ First stage of add. covers same-sign (add) and subtract
170 special-casing when mantissas are greater or equal, to
171 give greatest accuracy.
172 """
173 m.next = "add_1"
174 m.d.sync += self.z.e.eq(self.a.e)
175 # same-sign (both negative or both positive) add mantissas
176 with m.If(self.a.s == self.b.s):
177 m.d.sync += [
178 self.tot.eq(Cat(self.a.m, 0) + Cat(self.b.m, 0)),
179 self.z.s.eq(self.a.s)
180 ]
181 # a mantissa greater than b, use a
182 with m.Elif(self.a.m >= self.b.m):
183 m.d.sync += [
184 self.tot.eq(Cat(self.a.m, 0) - Cat(self.b.m, 0)),
185 self.z.s.eq(self.a.s)
186 ]
187 # b mantissa greater than a, use b
188 with m.Else():
189 m.d.sync += [
190 self.tot.eq(Cat(self.b.m, 0) - Cat(self.a.m, 0)),
191 self.z.s.eq(self.b.s)
192 ]
193
194
195 """ Second stage of add: preparation for normalisation.
196 detects when tot sum is too big (tot[27] is kinda a carry bit)
197 """
198
199 class FPAddStage1(FPState):
200
201 def action(self, m):
202 m.next = "normalise_1"
203 # tot[27] gets set when the sum overflows. shift result down
204 with m.If(self.tot[-1]):
205 m.d.sync += [
206 self.z.m.eq(self.tot[4:]),
207 self.of.m0.eq(self.tot[4]),
208 self.of.guard.eq(self.tot[3]),
209 self.of.round_bit.eq(self.tot[2]),
210 self.of.sticky.eq(self.tot[1] | self.tot[0]),
211 self.z.e.eq(self.z.e + 1)
212 ]
213 # tot[27] zero case
214 with m.Else():
215 m.d.sync += [
216 self.z.m.eq(self.tot[3:]),
217 self.of.m0.eq(self.tot[3]),
218 self.of.guard.eq(self.tot[2]),
219 self.of.round_bit.eq(self.tot[1]),
220 self.of.sticky.eq(self.tot[0])
221 ]
222
223
224 class FPNorm1(FPState):
225
226 def action(self, m):
227 self.normalise_1(m, self.z, self.of, "normalise_2")
228
229
230 class FPNorm2(FPState):
231
232 def action(self, m):
233 self.normalise_2(m, self.z, self.of, "round")
234
235
236 class FPRound(FPState):
237
238 def action(self, m):
239 self.roundz(m, self.z, self.of, "corrections")
240
241 class FPCorrections(FPState):
242
243 def action(self, m):
244 self.corrections(m, self.z, "pack")
245
246
247 class FPADD(FPBase):
248
249 def __init__(self, width, single_cycle=False):
250 FPBase.__init__(self)
251 self.width = width
252 self.single_cycle = single_cycle
253
254 self.in_a = FPOp(width)
255 self.in_b = FPOp(width)
256 self.out_z = FPOp(width)
257
258 def get_fragment(self, platform=None):
259 """ creates the HDL code-fragment for FPAdd
260 """
261 m = Module()
262
263 # Latches
264 a = FPNumIn(self.in_a, self.width)
265 b = FPNumIn(self.in_b, self.width)
266 z = FPNumOut(self.width, False)
267
268 m.submodules.fpnum_a = a
269 m.submodules.fpnum_b = b
270 m.submodules.fpnum_z = z
271
272 w = z.m_width + 4
273 tot = Signal(w, reset_less=True) # sticky/round/guard, {mantissa} result, 1 overflow
274
275 of = Overflow()
276 m.submodules.overflow = of
277
278 geta = FPGetOpA("get_a")
279 geta.set_inputs({"in_a": self.in_a})
280 geta.set_outputs({"a": a})
281 m.d.comb += a.v.eq(self.in_a.v) # links in_a to a
282
283 getb = FPGetOpB("get_b")
284 getb.set_inputs({"in_b": self.in_b})
285 getb.set_outputs({"b": b})
286 m.d.comb += b.v.eq(self.in_b.v) # links in_b to b
287
288 sc = FPAddSpecialCases("special_cases")
289 sc.set_inputs({"a": a, "b": b})
290 sc.set_outputs({"z": z})
291
292 dn = FPAddDeNorm("denormalise")
293 dn.set_inputs({"a": a, "b": b})
294 dn.set_outputs({"a": a, "b": b}) # XXX outputs same as inputs
295
296 if self.single_cycle:
297 alm = FPAddAlignSingle("align")
298 else:
299 alm = FPAddAlignMulti("align")
300 alm.set_inputs({"a": a, "b": b})
301 alm.set_outputs({"a": a, "b": b}) # XXX outputs same as inputs
302
303 add0 = FPAddStage0("add_0")
304 add0.set_inputs({"a": a, "b": b})
305 add0.set_outputs({"z": z, "tot": tot})
306
307 add1 = FPAddStage1("add_1")
308 add1.set_inputs({"tot": tot, "z": z}) # Z input passes through
309 add1.set_outputs({"z": z, "of": of}) # XXX Z as output
310
311 n1 = FPNorm1("normalise_1")
312 n1.set_inputs({"z": z, "of": of}) # XXX Z as output
313 n1.set_outputs({"z": z}) # XXX Z as output
314
315 n2 = FPNorm2("normalise_2")
316 n2.set_inputs({"z": z, "of": of}) # XXX Z as output
317 n2.set_outputs({"z": z}) # XXX Z as output
318
319 rn = FPRound("round")
320 rn.set_inputs({"z": z, "of": of}) # XXX Z as output
321 rn.set_outputs({"z": z}) # XXX Z as output
322
323 cor = FPCorrections("corrections")
324 cor.set_inputs({"z": z}) # XXX Z as output
325 cor.set_outputs({"z": z}) # XXX Z as output
326
327 with m.FSM() as fsm:
328
329 # ******
330 # gets operand a
331
332 with m.State("get_a"):
333 geta.action(m)
334
335 # ******
336 # gets operand b
337
338 with m.State("get_b"):
339 #self.get_op(m, self.in_b, b, "special_cases")
340 getb.action(m)
341
342 # ******
343 # special cases: NaNs, infs, zeros, denormalised
344 # NOTE: some of these are unique to add. see "Special Operations"
345 # https://steve.hollasch.net/cgindex/coding/ieeefloat.html
346
347 with m.State("special_cases"):
348 sc.action(m)
349
350 # ******
351 # denormalise.
352
353 with m.State("denormalise"):
354 dn.action(m)
355
356 # ******
357 # align.
358
359 with m.State("align"):
360 alm.action(m)
361
362 # ******
363 # First stage of add. covers same-sign (add) and subtract
364 # special-casing when mantissas are greater or equal, to
365 # give greatest accuracy.
366
367 with m.State("add_0"):
368 add0.action(m)
369
370 # ******
371 # Second stage of add: preparation for normalisation.
372 # detects when tot sum is too big (tot[27] is kinda a carry bit)
373
374 with m.State("add_1"):
375 add1.action(m)
376
377 # ******
378 # First stage of normalisation.
379
380 with m.State("normalise_1"):
381 n1.action(m)
382
383 # ******
384 # Second stage of normalisation.
385
386 with m.State("normalise_2"):
387 n2.action(m)
388
389 # ******
390 # rounding stage
391
392 with m.State("round"):
393 rn.action(m)
394
395 # ******
396 # correction stage
397
398 with m.State("corrections"):
399 cor.action(m)
400
401 # ******
402 # pack stage
403
404 with m.State("pack"):
405 self.pack(m, z, "put_z")
406
407 # ******
408 # put_z stage
409
410 with m.State("put_z"):
411 self.put_z(m, z, self.out_z, "get_a")
412
413 return m
414
415
416 if __name__ == "__main__":
417 alu = FPADD(width=32)
418 main(alu, ports=alu.in_a.ports() + alu.in_b.ports() + alu.out_z.ports())
419
420
421 # works... but don't use, just do "python fname.py convert -t v"
422 #print (verilog.convert(alu, ports=[
423 # ports=alu.in_a.ports() + \
424 # alu.in_b.ports() + \
425 # alu.out_z.ports())