From 20104f317e697ee5cea1af9aca6c534d05ca9515 Mon Sep 17 00:00:00 2001 From: Kirill Radkin Date: Tue, 10 Oct 2023 12:25:49 +0300 Subject: [PATCH] Fix macro generation 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) --- registers.py | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/registers.py b/registers.py index 95d8ac7c..85a79122 100755 --- a/registers.py +++ b/registers.py @@ -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):