Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
| 2 | '''A utility to update LLVM IR CHECK lines in C/C++ FileCheck test files. |
| 3 | |
| 4 | Example RUN lines in .c/.cc test files: |
| 5 | |
| 6 | // RUN: %clang -emit-llvm -S %s -o - -O2 | FileCheck %s |
| 7 | // RUN: %clangxx -emit-llvm -S %s -o - -O2 | FileCheck -check-prefix=CHECK-A %s |
| 8 | |
| 9 | Usage: |
| 10 | |
| 11 | % utils/update_cc_test_checks.py --llvm-bin=release/bin test/a.cc |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 12 | % utils/update_cc_test_checks.py --clang=release/bin/clang /tmp/c/a.cc |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 13 | ''' |
| 14 | |
| 15 | import argparse |
| 16 | import collections |
| 17 | import distutils.spawn |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 18 | import json |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 19 | import os |
| 20 | import shlex |
| 21 | import string |
| 22 | import subprocess |
| 23 | import sys |
| 24 | import re |
| 25 | import tempfile |
| 26 | |
| 27 | from UpdateTestChecks import asm, common |
| 28 | |
| 29 | ADVERT = '// NOTE: Assertions have been autogenerated by ' |
| 30 | |
| 31 | CHECK_RE = re.compile(r'^\s*//\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:') |
Alex Richardson | 4a37209 | 2019-10-30 09:17:29 +0000 | [diff] [blame] | 32 | RUN_LINE_RE = re.compile(r'^//\s*RUN:\s*(.*)$') |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 33 | |
| 34 | SUBST = { |
| 35 | '%clang': [], |
| 36 | '%clang_cc1': ['-cc1'], |
| 37 | '%clangxx': ['--driver-mode=g++'], |
| 38 | } |
| 39 | |
| 40 | def get_line2spell_and_mangled(args, clang_args): |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 41 | def debug_mangled(*print_args, **kwargs): |
| 42 | if args.verbose: |
| 43 | print(*print_args, file=sys.stderr, **kwargs) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 44 | ret = {} |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 45 | # Use clang's JSON AST dump to get the mangled name |
| 46 | json_dump_args = [args.clang, *clang_args, '-fsyntax-only', '-o', '-'] |
| 47 | if '-cc1' not in json_dump_args: |
| 48 | # For tests that invoke %clang instead if %clang_cc1 we have to use |
| 49 | # -Xclang -ast-dump=json instead: |
| 50 | json_dump_args.append('-Xclang') |
| 51 | json_dump_args.append('-ast-dump=json') |
| 52 | debug_mangled('Running', ' '.join(json_dump_args)) |
| 53 | status = subprocess.run(json_dump_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) |
| 54 | if status.returncode != 0: |
| 55 | sys.stderr.write('Failed to run ' + ' '.join(json_dump_args) + '\n') |
| 56 | sys.stderr.write(status.stderr.decode()) |
| 57 | sys.stderr.write(status.stdout.decode()) |
| 58 | sys.exit(2) |
| 59 | ast = json.loads(status.stdout.decode()) |
| 60 | if ast['kind'] != 'TranslationUnitDecl': |
| 61 | common.error('Clang AST dump JSON format changed?') |
| 62 | sys.exit(2) |
David Greene | eb66985 | 2019-10-08 16:25:42 +0000 | [diff] [blame] | 63 | |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 64 | # Get the inner node and iterate over all children of type FunctionDecl. |
| 65 | # TODO: Should we add checks for global variables being emitted? |
| 66 | for node in ast['inner']: |
| 67 | if node['kind'] != 'FunctionDecl': |
David Greene | eb66985 | 2019-10-08 16:25:42 +0000 | [diff] [blame] | 68 | continue |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 69 | if node.get('isImplicit') is True and node.get('storageClass') == 'extern': |
| 70 | debug_mangled('Skipping builtin function:', node['name'], '@', node['loc']) |
| 71 | continue |
| 72 | debug_mangled('Found function:', node['kind'], node['name'], '@', node['loc']) |
| 73 | line = node['loc'].get('line') |
| 74 | # If there is no line it is probably a builtin function -> skip |
| 75 | if line is None: |
| 76 | debug_mangled('Skipping function without line number:', node['name'], '@', node['loc']) |
| 77 | continue |
| 78 | spell = node['name'] |
| 79 | mangled = node.get('mangledName', spell) |
| 80 | ret[int(line)-1] = (spell, mangled) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 81 | if args.verbose: |
| 82 | for line, func_name in sorted(ret.items()): |
| 83 | print('line {}: found function {}'.format(line+1, func_name), file=sys.stderr) |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 84 | if not ret: |
| 85 | common.warn('Did not find any functions using', ' '.join(json_dump_args)) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 86 | return ret |
| 87 | |
| 88 | |
| 89 | def config(): |
| 90 | parser = argparse.ArgumentParser( |
| 91 | description=__doc__, |
| 92 | formatter_class=argparse.RawTextHelpFormatter) |
| 93 | parser.add_argument('-v', '--verbose', action='store_true') |
| 94 | parser.add_argument('--llvm-bin', help='llvm $prefix/bin path') |
| 95 | parser.add_argument('--clang', |
| 96 | help='"clang" executable, defaults to $llvm_bin/clang') |
| 97 | parser.add_argument('--clang-args', |
| 98 | help='Space-separated extra args to clang, e.g. --clang-args=-v') |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 99 | parser.add_argument('--opt', |
| 100 | help='"opt" executable, defaults to $llvm_bin/opt') |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 101 | parser.add_argument( |
| 102 | '--functions', nargs='+', help='A list of function name regexes. ' |
| 103 | 'If specified, update CHECK lines for functions matching at least one regex') |
| 104 | parser.add_argument( |
| 105 | '--x86_extra_scrub', action='store_true', |
| 106 | help='Use more regex for x86 matching to reduce diffs between various subtargets') |
David Bolvansky | 7169ea3 | 2019-08-07 14:44:50 +0000 | [diff] [blame] | 107 | parser.add_argument('-u', '--update-only', action='store_true', |
| 108 | help='Only update test if it was already autogened') |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 109 | parser.add_argument('tests', nargs='+') |
| 110 | args = parser.parse_args() |
| 111 | args.clang_args = shlex.split(args.clang_args or '') |
| 112 | |
| 113 | if args.clang is None: |
| 114 | if args.llvm_bin is None: |
| 115 | args.clang = 'clang' |
| 116 | else: |
| 117 | args.clang = os.path.join(args.llvm_bin, 'clang') |
| 118 | if not distutils.spawn.find_executable(args.clang): |
| 119 | print('Please specify --llvm-bin or --clang', file=sys.stderr) |
| 120 | sys.exit(1) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 121 | |
Alex Richardson | d9cc7d1 | 2019-10-31 21:18:32 +0000 | [diff] [blame] | 122 | # Determine the builtin includes directory so that we can update tests that |
| 123 | # depend on the builtin headers. See get_clang_builtin_include_dir() and |
| 124 | # use_clang() in llvm/utils/lit/lit/llvm/config.py. |
| 125 | try: |
| 126 | builtin_include_dir = subprocess.check_output( |
| 127 | [args.clang, '-print-file-name=include']).decode().strip() |
| 128 | SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir, |
| 129 | '-nostdsysteminc'] |
| 130 | except subprocess.CalledProcessError: |
| 131 | common.warn('Could not determine clang builtins directory, some tests ' |
| 132 | 'might not update correctly.') |
| 133 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 134 | if args.opt is None: |
| 135 | if args.llvm_bin is None: |
| 136 | args.opt = 'opt' |
| 137 | else: |
| 138 | args.opt = os.path.join(args.llvm_bin, 'opt') |
| 139 | if not distutils.spawn.find_executable(args.opt): |
| 140 | # Many uses of this tool will not need an opt binary, because it's only |
| 141 | # needed for updating a test that runs clang | opt | FileCheck. So we |
| 142 | # defer this error message until we find that opt is actually needed. |
| 143 | args.opt = None |
| 144 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 145 | return args |
| 146 | |
| 147 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 148 | def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict): |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 149 | # TODO Clean up duplication of asm/common build_function_body_dictionary |
| 150 | # Invoke external tool and extract function bodies. |
| 151 | raw_tool_output = common.invoke_tool(args.clang, clang_args, filename) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 152 | for extra_command in extra_commands: |
| 153 | extra_args = shlex.split(extra_command) |
| 154 | with tempfile.NamedTemporaryFile() as f: |
| 155 | f.write(raw_tool_output.encode()) |
| 156 | f.flush() |
| 157 | if extra_args[0] == 'opt': |
| 158 | if args.opt is None: |
| 159 | print(filename, 'needs to run opt. ' |
| 160 | 'Please specify --llvm-bin or --opt', file=sys.stderr) |
| 161 | sys.exit(1) |
| 162 | extra_args[0] = args.opt |
| 163 | raw_tool_output = common.invoke_tool(extra_args[0], |
| 164 | extra_args[1:], f.name) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 165 | if '-emit-llvm' in clang_args: |
| 166 | common.build_function_body_dictionary( |
| 167 | common.OPT_FUNCTION_RE, common.scrub_body, [], |
Johannes Doerfert | 4de09e0 | 2019-10-31 13:37:34 -0500 | [diff] [blame] | 168 | raw_tool_output, prefixes, func_dict, args.verbose, False) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 169 | else: |
| 170 | print('The clang command line should include -emit-llvm as asm tests ' |
| 171 | 'are discouraged in Clang testsuite.', file=sys.stderr) |
| 172 | sys.exit(1) |
| 173 | |
| 174 | |
| 175 | def main(): |
| 176 | args = config() |
David Bolvansky | 7169ea3 | 2019-08-07 14:44:50 +0000 | [diff] [blame] | 177 | script_name = os.path.basename(__file__) |
| 178 | autogenerated_note = (ADVERT + 'utils/' + script_name) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 179 | |
| 180 | for filename in args.tests: |
| 181 | with open(filename) as f: |
| 182 | input_lines = [l.rstrip() for l in f] |
Johannes Doerfert | e67f647 | 2019-11-01 11:17:27 -0500 | [diff] [blame] | 183 | |
David Bolvansky | 7169ea3 | 2019-08-07 14:44:50 +0000 | [diff] [blame] | 184 | first_line = input_lines[0] if input_lines else "" |
| 185 | if 'autogenerated' in first_line and script_name not in first_line: |
| 186 | common.warn("Skipping test which wasn't autogenerated by " + script_name, filename) |
| 187 | continue |
| 188 | |
| 189 | if args.update_only: |
| 190 | if not first_line or 'autogenerated' not in first_line: |
| 191 | common.warn("Skipping test which isn't autogenerated: " + filename) |
| 192 | continue |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 193 | |
| 194 | # Extract RUN lines. |
| 195 | raw_lines = [m.group(1) |
| 196 | for m in [RUN_LINE_RE.match(l) for l in input_lines] if m] |
| 197 | run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] |
| 198 | for l in raw_lines[1:]: |
| 199 | if run_lines[-1].endswith("\\"): |
| 200 | run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l |
| 201 | else: |
| 202 | run_lines.append(l) |
| 203 | |
| 204 | if args.verbose: |
| 205 | print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr) |
| 206 | for l in run_lines: |
| 207 | print(' RUN: ' + l, file=sys.stderr) |
| 208 | |
| 209 | # Build a list of clang command lines and check prefixes from RUN lines. |
| 210 | run_list = [] |
| 211 | line2spell_and_mangled_list = collections.defaultdict(list) |
| 212 | for l in run_lines: |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 213 | commands = [cmd.strip() for cmd in l.split('|')] |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 214 | |
| 215 | triple_in_cmd = None |
| 216 | m = common.TRIPLE_ARG_RE.search(commands[0]) |
| 217 | if m: |
| 218 | triple_in_cmd = m.groups()[0] |
| 219 | |
| 220 | # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args |
| 221 | clang_args = shlex.split(commands[0]) |
| 222 | if clang_args[0] not in SUBST: |
| 223 | print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr) |
| 224 | continue |
| 225 | clang_args[0:1] = SUBST[clang_args[0]] |
| 226 | clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args |
| 227 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 228 | # Permit piping the output through opt |
| 229 | if not (len(commands) == 2 or |
| 230 | (len(commands) == 3 and commands[1].startswith('opt'))): |
| 231 | print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr) |
| 232 | |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 233 | # Extract -check-prefix in FileCheck args |
| 234 | filecheck_cmd = commands[-1] |
David Bolvansky | 45be5e4 | 2019-07-29 17:41:00 +0000 | [diff] [blame] | 235 | common.verify_filecheck_prefixes(filecheck_cmd) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 236 | if not filecheck_cmd.startswith('FileCheck '): |
| 237 | print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr) |
| 238 | continue |
| 239 | check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd) |
| 240 | for item in m.group(1).split(',')] |
| 241 | if not check_prefixes: |
| 242 | check_prefixes = ['CHECK'] |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 243 | run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd)) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 244 | |
| 245 | # Strip CHECK lines which are in `prefix_set`, update test file. |
| 246 | prefix_set = set([prefix for p in run_list for prefix in p[0]]) |
| 247 | input_lines = [] |
| 248 | with open(filename, 'r+') as f: |
| 249 | for line in f: |
| 250 | m = CHECK_RE.match(line) |
| 251 | if not (m and m.group(1) in prefix_set) and line != '//\n': |
| 252 | input_lines.append(line) |
| 253 | f.seek(0) |
| 254 | f.writelines(input_lines) |
| 255 | f.truncate() |
| 256 | |
| 257 | # Execute clang, generate LLVM IR, and extract functions. |
| 258 | func_dict = {} |
| 259 | for p in run_list: |
| 260 | prefixes = p[0] |
| 261 | for prefix in prefixes: |
| 262 | func_dict.update({prefix: dict()}) |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 263 | for prefixes, clang_args, extra_commands, triple_in_cmd in run_list: |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 264 | if args.verbose: |
| 265 | print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr) |
| 266 | print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr) |
| 267 | |
Simon Tatham | 109c773 | 2019-10-10 08:25:34 +0000 | [diff] [blame] | 268 | get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 269 | |
Alex Richardson | 0df4a8f | 2019-11-15 12:50:10 +0000 | [diff] [blame^] | 270 | # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to |
| 271 | # mangled names. Forward all clang args for now. |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 272 | for k, v in get_line2spell_and_mangled(args, clang_args).items(): |
| 273 | line2spell_and_mangled_list[k].append(v) |
| 274 | |
| 275 | output_lines = [autogenerated_note] |
| 276 | for idx, line in enumerate(input_lines): |
| 277 | # Discard any previous script advertising. |
| 278 | if line.startswith(ADVERT): |
| 279 | continue |
| 280 | if idx in line2spell_and_mangled_list: |
| 281 | added = set() |
| 282 | for spell, mangled in line2spell_and_mangled_list[idx]: |
| 283 | # One line may contain multiple function declarations. |
| 284 | # Skip if the mangled name has been added before. |
| 285 | # The line number may come from an included file, |
| 286 | # we simply require the spelling name to appear on the line |
| 287 | # to exclude functions from other files. |
| 288 | if mangled in added or spell not in line: |
| 289 | continue |
| 290 | if args.functions is None or any(re.search(regex, spell) for regex in args.functions): |
| 291 | if added: |
| 292 | output_lines.append('//') |
| 293 | added.add(mangled) |
Johannes Doerfert | e67f647 | 2019-11-01 11:17:27 -0500 | [diff] [blame] | 294 | common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled, False, False) |
Fangrui Song | 0a301a1 | 2018-03-02 17:37:04 +0000 | [diff] [blame] | 295 | output_lines.append(line.rstrip('\n')) |
| 296 | |
| 297 | # Update the test file. |
| 298 | with open(filename, 'w') as f: |
| 299 | for line in output_lines: |
| 300 | f.write(line + '\n') |
| 301 | |
| 302 | return 0 |
| 303 | |
| 304 | |
| 305 | if __name__ == '__main__': |
| 306 | sys.exit(main()) |