194aa3
Partial backport of:
194aa3
194aa3
commit 7e1d42400c1b8f03316fe14176133c8853cd3bbe
194aa3
Author: Joseph Myers <joseph@codesourcery.com>
194aa3
Date:   Fri Nov 30 15:20:41 2018 +0000
194aa3
194aa3
    Replace gen-as-const.awk by gen-as-const.py.
194aa3
    
194aa3
    This patch replaces gen-as-const.awk, and some fragments of the
194aa3
    Makefile code that used it, by a Python script.  The point is not such
194aa3
    much that awk is problematic for this particular script, as that I'd
194aa3
    like to build up a general Python infrastructure for extracting
194aa3
    information from C headers, for use in writing tests of such headers.
194aa3
    Thus, although this patch does not set up such infrastructure, the
194aa3
    compute_c_consts function in gen-as-const.py might be moved to a
194aa3
    separate Python module in a subsequent patch as a starting point for
194aa3
    such infrastructure.
194aa3
    
194aa3
    The general idea of the code is the same as in the awk version, but no
194aa3
    attempt is made to make the output files textually identical.  When
194aa3
    generating a header, a dict of constant names and values is generated
194aa3
    internally then defines are printed in sorted order (rather than the
194aa3
    order in the .sym file, which would have been used before).  When
194aa3
    generating a test that the values computed match those from a normal
194aa3
    header inclusion, the test code is made into a compilation test using
194aa3
    _Static_assert, where previously the comparisons were done only when
194aa3
    the test was executed.  One fragment of test generation (converting
194aa3
    the previously generated header to use asconst_* prefixes on its macro
194aa3
    names) is still in awk code in the makefiles; only the .sym processing
194aa3
    and subsequent execution of the compiler to extract constants have
194aa3
    moved to the Python script.
194aa3
    
194aa3
    Tested for x86_64, and with build-many-glibcs.py.
194aa3
    
194aa3
            * scripts/gen-as-const.py: New file.
194aa3
            * scripts/gen-as-const.awk: Remove.
194aa3
            * Makerules ($(common-objpfx)%.h $(common-objpfx)%.h.d): Use
194aa3
            gen-as-const.py.
194aa3
            ($(objpfx)test-as-const-%.c): Likewise.
194aa3
194aa3
In the downstream version, scripts/gen-as-const.awk is not removed and
194aa3
still used in Makerules.
194aa3
194aa3
diff --git a/scripts/gen-as-const.py b/scripts/gen-as-const.py
194aa3
new file mode 100644
194aa3
index 0000000000000000..b7a5744bb192dd67
194aa3
--- /dev/null
194aa3
+++ b/scripts/gen-as-const.py
194aa3
@@ -0,0 +1,159 @@
194aa3
+#!/usr/bin/python3
194aa3
+# Produce headers of assembly constants from C expressions.
194aa3
+# Copyright (C) 2018 Free Software Foundation, Inc.
194aa3
+# This file is part of the GNU C Library.
194aa3
+#
194aa3
+# The GNU C Library is free software; you can redistribute it and/or
194aa3
+# modify it under the terms of the GNU Lesser General Public
194aa3
+# License as published by the Free Software Foundation; either
194aa3
+# version 2.1 of the License, or (at your option) any later version.
194aa3
+#
194aa3
+# The GNU C Library is distributed in the hope that it will be useful,
194aa3
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
194aa3
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
194aa3
+# Lesser General Public License for more details.
194aa3
+#
194aa3
+# You should have received a copy of the GNU Lesser General Public
194aa3
+# License along with the GNU C Library; if not, see
194aa3
+# <http://www.gnu.org/licenses/>.
194aa3
+
194aa3
+# The input to this script looks like:
194aa3
+#       #cpp-directive ...
194aa3
+#       NAME1
194aa3
+#       NAME2 expression ...
194aa3
+# A line giving just a name implies an expression consisting of just that name.
194aa3
+
194aa3
+import argparse
194aa3
+import os.path
194aa3
+import re
194aa3
+import subprocess
194aa3
+import tempfile
194aa3
+
194aa3
+
194aa3
+def compute_c_consts(sym_data, cc):
194aa3
+    """Compute the values of some C constants.
194aa3
+
194aa3
+    The first argument is a list whose elements are either strings
194aa3
+    (preprocessor directives) or pairs of strings (a name and a C
194aa3
+    expression for the corresponding value).  Preprocessor directives
194aa3
+    in the middle of the list may be used to select which constants
194aa3
+    end up being evaluated using which expressions.
194aa3
+
194aa3
+    """
194aa3
+    out_lines = []
194aa3
+    started = False
194aa3
+    for arg in sym_data:
194aa3
+        if isinstance(arg, str):
194aa3
+            out_lines.append(arg)
194aa3
+            continue
194aa3
+        name = arg[0]
194aa3
+        value = arg[1]
194aa3
+        if not started:
194aa3
+            out_lines.append('void\ndummy (void)\n{')
194aa3
+            started = True
194aa3
+        out_lines.append('asm ("@@@name@@@%s@@@value@@@%%0@@@end@@@" '
194aa3
+                         ': : \"i\" ((long int) (%s)));'
194aa3
+                         % (name, value))
194aa3
+    if started:
194aa3
+        out_lines.append('}')
194aa3
+    out_lines.append('')
194aa3
+    out_text = '\n'.join(out_lines)
194aa3
+    with tempfile.TemporaryDirectory() as temp_dir:
194aa3
+        c_file_name = os.path.join(temp_dir, 'test.c')
194aa3
+        s_file_name = os.path.join(temp_dir, 'test.s')
194aa3
+        with open(c_file_name, 'w') as c_file:
194aa3
+            c_file.write(out_text)
194aa3
+        # Compilation has to be from stdin to avoid the temporary file
194aa3
+        # name being written into the generated dependencies.
194aa3
+        cmd = ('%s -S -o %s -x c - < %s' % (cc, s_file_name, c_file_name))
194aa3
+        subprocess.check_call(cmd, shell=True)
194aa3
+        consts = {}
194aa3
+        with open(s_file_name, 'r') as s_file:
194aa3
+            for line in s_file:
194aa3
+                match = re.search('@@@name@@@([^@]*)'
194aa3
+                                  '@@@value@@@[^0-9Xxa-fA-F-]*'
194aa3
+                                  '([0-9Xxa-fA-F-]+).*@@@end@@@', line)
194aa3
+                if match:
194aa3
+                    if (match.group(1) in consts
194aa3
+                        and match.group(2) != consts[match.group(1)]):
194aa3
+                        raise ValueError('duplicate constant %s'
194aa3
+                                         % match.group(1))
194aa3
+                    consts[match.group(1)] = match.group(2)
194aa3
+        return consts
194aa3
+
194aa3
+
194aa3
+def gen_test(sym_data):
194aa3
+    """Generate a test for the values of some C constants.
194aa3
+
194aa3
+    The first argument is as for compute_c_consts.
194aa3
+
194aa3
+    """
194aa3
+    out_lines = []
194aa3
+    started = False
194aa3
+    for arg in sym_data:
194aa3
+        if isinstance(arg, str):
194aa3
+            out_lines.append(arg)
194aa3
+            continue
194aa3
+        name = arg[0]
194aa3
+        value = arg[1]
194aa3
+        if not started:
194aa3
+            out_lines.append('#include <stdint.h>\n'
194aa3
+                             '#include <stdio.h>\n'
194aa3
+                             '#include <bits/wordsize.h>\n'
194aa3
+                             '#if __WORDSIZE == 64\n'
194aa3
+                             'typedef uint64_t c_t;\n'
194aa3
+                             '# define U(n) UINT64_C (n)\n'
194aa3
+                             '#else\n'
194aa3
+                             'typedef uint32_t c_t;\n'
194aa3
+                             '# define U(n) UINT32_C (n)\n'
194aa3
+                             '#endif\n'
194aa3
+                             'static int\n'
194aa3
+                             'do_test (void)\n'
194aa3
+                             '{\n'
194aa3
+                             # Compilation test only, using static assertions.
194aa3
+                             '  return 0;\n'
194aa3
+                             '}\n'
194aa3
+                             '#include <support/test-driver.c>')
194aa3
+            started = True
194aa3
+        out_lines.append('_Static_assert (U (asconst_%s) == (c_t) (%s), '
194aa3
+                         '"value of %s");'
194aa3
+                         % (name, value, name))
194aa3
+    return '\n'.join(out_lines)
194aa3
+
194aa3
+
194aa3
+def main():
194aa3
+    """The main entry point."""
194aa3
+    parser = argparse.ArgumentParser(
194aa3
+        description='Produce headers of assembly constants.')
194aa3
+    parser.add_argument('--cc', metavar='CC',
194aa3
+                        help='C compiler (including options) to use')
194aa3
+    parser.add_argument('--test', action='store_true',
194aa3
+                        help='Generate test case instead of header')
194aa3
+    parser.add_argument('sym_file',
194aa3
+                        help='.sym file to process')
194aa3
+    args = parser.parse_args()
194aa3
+    sym_data = []
194aa3
+    with open(args.sym_file, 'r') as sym_file:
194aa3
+        for line in sym_file:
194aa3
+            line = line.strip()
194aa3
+            if line == '':
194aa3
+                continue
194aa3
+            # Pass preprocessor directives through.
194aa3
+            if line.startswith('#'):
194aa3
+                sym_data.append(line)
194aa3
+                continue
194aa3
+            words = line.split(maxsplit=1)
194aa3
+            # Separator.
194aa3
+            if words[0] == '--':
194aa3
+                continue
194aa3
+            name = words[0]
194aa3
+            value = words[1] if len(words) > 1 else words[0]
194aa3
+            sym_data.append((name, value))
194aa3
+    if args.test:
194aa3
+        print(gen_test(sym_data))
194aa3
+    else:
194aa3
+        consts = compute_c_consts(sym_data, args.cc)
194aa3
+        print('\n'.join('#define %s %s' % c for c in sorted(consts.items())))
194aa3
+
194aa3
+if __name__ == '__main__':
194aa3
+    main()