Skip to content

Commit

Permalink
registers.py: Fix subtractions in generated C code
Browse files Browse the repository at this point in the history
The registers.py generator outputs expressions with subtractions
into the C code of debug_defines.{h,c} in this form:

```
((XLEN) + -6ULL)
```

Such code may look awkward to code readers and also triggers GCC's
-Wconversion warnings (when enabled).

Fix the generator to produce the expressions with subtraction
in a natural form:

```
((XLEN) - 6ULL)
```
  • Loading branch information
HonzaMat committed Jan 8, 2025
1 parent a467810 commit 6b8b91d
Showing 1 changed file with 16 additions and 1 deletion.
17 changes: 16 additions & 1 deletion registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,7 +472,22 @@ def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True):
elif isinstance(expression, sympy.Symbol):
return sym_to_c(expression)
elif isinstance(expression, sympy.Add):
return "(" + " + ".join(stc(t) for t in reversed(expression.args)) + ")"
args = list(reversed(expression.args))
result = ""
for i in range(len(args)):
arg = args[i]
is_first = (i == 0)
if is_first:
result += stc(arg)
else:
# Simplify additions of negative constants:
# Use (a - 1) instead of (a + -1)
negative_constant = arg.is_constant() and (arg < 0)
result += " - " if negative_constant else " + "
if negative_constant:
arg = -arg # flip to positive
result += stc(arg)
return "(" + result + ")"
elif isinstance(expression, sympy.Mul):
return "(" + " * ".join(stc(t) for t in expression.args) + ")"
elif isinstance(expression, sympy.Pow):
Expand Down

0 comments on commit 6b8b91d

Please sign in to comment.