From b2f5e5026d8c862dbd7bbbb3e5eb1b440c37172e Mon Sep 17 00:00:00 2001 From: whitequark Date: Fri, 4 Oct 2019 07:56:06 +0000 Subject: [PATCH] back.rtlil: avoid unsoundness for division by zero. Fixes #238. --- nmigen/back/rtlil.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/nmigen/back/rtlil.py b/nmigen/back/rtlil.py index eb26bf8..e962366 100644 --- a/nmigen/back/rtlil.py +++ b/nmigen/back/rtlil.py @@ -505,6 +505,18 @@ class _RHSValueCompiler(_ValueCompiler): "B_WIDTH": rhs_bits, "Y_WIDTH": res_bits, }, src=src(value.src_loc)) + if value.op in ("//", "%"): + # RTLIL leaves division by zero undefined, but we require it to return zero. + divmod_res = res + res = self.s.rtlil.wire(width=res_bits, src=src(value.src_loc)) + self.s.rtlil.cell("$mux", ports={ + "\\A": divmod_res, + "\\B": self(ast.Const(0, (res_bits, res_sign))), + "\\S": self(lhs == 0), + "\\Y": res, + }, params={ + "WIDTH": res_bits + }, src=src(value.src_loc)) return res def on_Operator_mux(self, value): -- 2.30.2