Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

back.pysim: Implement modulus operator #333

Merged
merged 2 commits into from Mar 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions nmigen/back/pysim.py
Expand Up @@ -363,6 +363,7 @@ class _ValueCompiler(ValueVisitor, _Compiler):
helpers = {
"sign": lambda value, sign: value | sign if value & sign else value,
"zdiv": lambda lhs, rhs: 0 if rhs == 0 else lhs // rhs,
"zmod": lambda lhs, rhs: 0 if rhs == 0 else lhs % rhs,
}

def on_ClockSignal(self, value):
Expand Down Expand Up @@ -448,6 +449,8 @@ def sign(value):
return f"({sign(lhs)} * {sign(rhs)})"
if value.operator == "//":
return f"zdiv({sign(lhs)}, {sign(rhs)})"
if value.operator == "%":
return f"zmod({sign(lhs)}, {sign(rhs)})"
if value.operator == "&":
return f"({self(lhs)} & {self(rhs)})"
if value.operator == "|":
Expand Down
7 changes: 7 additions & 0 deletions nmigen/test/test_sim.py
Expand Up @@ -110,6 +110,13 @@ def test_floordiv(self):
self.assertStatement(stmt, [C(2, 4), C(2, 4)], C(1, 8))
self.assertStatement(stmt, [C(7, 4), C(2, 4)], C(3, 8))

def test_mod(self):
stmt = lambda y, a, b: y.eq(a % b)
self.assertStatement(stmt, [C(2, 4), C(0, 4)], C(0, 8))
self.assertStatement(stmt, [C(2, 4), C(1, 4)], C(0, 8))
self.assertStatement(stmt, [C(2, 4), C(2, 4)], C(0, 8))
self.assertStatement(stmt, [C(7, 4), C(2, 4)], C(1, 8))

def test_and(self):
stmt = lambda y, a, b: y.eq(a & b)
self.assertStatement(stmt, [C(0b1100, 4), C(0b1010, 4)], C(0b1000, 4))
Expand Down