From: whitequark Date: Fri, 4 Oct 2019 07:56:06 +0000 (+0000) Subject: back.rtlil: avoid unsoundness for division by zero. X-Git-Url: https://git.libre-soc.org/?a=commitdiff_plain;h=b2f5e5026d8c862dbd7bbbb3e5eb1b440c37172e;p=nmigen.git back.rtlil: avoid unsoundness for division by zero. Fixes #238. --- 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):