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