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