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