Skip to content

Commit

Permalink
Fix macro generation
Browse files Browse the repository at this point in the history
1) We don't need ULL modifier because of https://en.cppreference.com/w/c/language/integer_constant (look at `The type of the integer constant` section)
2) We need to add U modifier to all values to fix some issues with `set_field` and `get_field` macros (for example, when `mask` = 1 << 31, it leads to UB becuase of signed overflow)
  • Loading branch information
kr-sc committed Oct 10, 2023
1 parent 393715e commit 20104f3
Showing 1 changed file with 5 additions and 14 deletions.
19 changes: 5 additions & 14 deletions registers.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,26 +386,17 @@ def prototype(self):
def body(self):
return self.expression

def sympy_to_c(expression, sym_to_c = lambda s: "(" + str(s) + ")"):
def sympy_to_c(expression, sym_to_c = lambda s: f"({s})", unsigned=True):
"""Implement our own string function, so we can replace 2** with 1<<."""
stc = lambda x : sympy_to_c(x, sym_to_c)
if isinstance(expression, str):
return expression
if isinstance(expression, sympy.Number):
if (expression >= 2**32):
return "0x%xULL" % expression
elif (expression >= 2**31):
return "0x%xU" % expression
elif (expression >= 10):
return "0x%x" % expression
elif (expression > -10):
return "%d" % expression
elif (expression > -2**31):
return "-0x%x" % -expression
elif (expression > -2**32):
return "-0x%xU" % -expression
sufffix = "U" if unsigned else ""
if (expression < 10 and expression > -10):
return "%d%s" % (expression, sufffix)
else:
return "-0x%xULL" % -expression
return "%#0x%s" % (expression, sufffix)
elif isinstance(expression, sympy.Symbol):
return sym_to_c(expression)
elif isinstance(expression, sympy.Add):
Expand Down

0 comments on commit 20104f3

Please sign in to comment.