blob: a3227c67743f47d343b89b2c7de3aa73967a7d06 [file] [log] [blame]
Fangrui Song0a301a12018-03-02 17:37:04 +00001#!/usr/bin/env python3
2'''A utility to update LLVM IR CHECK lines in C/C++ FileCheck test files.
3
4Example 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
9Usage:
10
11% utils/update_cc_test_checks.py --llvm-bin=release/bin test/a.cc
Alex Richardson0df4a8f2019-11-15 12:50:10 +000012% utils/update_cc_test_checks.py --clang=release/bin/clang /tmp/c/a.cc
Fangrui Song0a301a12018-03-02 17:37:04 +000013'''
14
15import argparse
16import collections
17import distutils.spawn
Alex Richardson0df4a8f2019-11-15 12:50:10 +000018import json
Fangrui Song0a301a12018-03-02 17:37:04 +000019import os
20import shlex
21import string
22import subprocess
23import sys
24import re
25import tempfile
26
27from UpdateTestChecks import asm, common
28
29ADVERT = '// NOTE: Assertions have been autogenerated by '
30
31CHECK_RE = re.compile(r'^\s*//\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
Alex Richardson4a372092019-10-30 09:17:29 +000032RUN_LINE_RE = re.compile(r'^//\s*RUN:\s*(.*)$')
Fangrui Song0a301a12018-03-02 17:37:04 +000033
34SUBST = {
35 '%clang': [],
36 '%clang_cc1': ['-cc1'],
37 '%clangxx': ['--driver-mode=g++'],
38}
39
40def get_line2spell_and_mangled(args, clang_args):
Alex Richardson0df4a8f2019-11-15 12:50:10 +000041 def debug_mangled(*print_args, **kwargs):
42 if args.verbose:
43 print(*print_args, file=sys.stderr, **kwargs)
Fangrui Song0a301a12018-03-02 17:37:04 +000044 ret = {}
Alex Richardson0df4a8f2019-11-15 12:50:10 +000045 # 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 Greeneeb669852019-10-08 16:25:42 +000063
Alex Richardson0df4a8f2019-11-15 12:50:10 +000064 # 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 Greeneeb669852019-10-08 16:25:42 +000068 continue
Alex Richardson0df4a8f2019-11-15 12:50:10 +000069 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 Song0a301a12018-03-02 17:37:04 +000081 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 Richardson0df4a8f2019-11-15 12:50:10 +000084 if not ret:
85 common.warn('Did not find any functions using', ' '.join(json_dump_args))
Fangrui Song0a301a12018-03-02 17:37:04 +000086 return ret
87
88
89def config():
90 parser = argparse.ArgumentParser(
91 description=__doc__,
92 formatter_class=argparse.RawTextHelpFormatter)
Fangrui Song0a301a12018-03-02 17:37:04 +000093 parser.add_argument('--llvm-bin', help='llvm $prefix/bin path')
94 parser.add_argument('--clang',
95 help='"clang" executable, defaults to $llvm_bin/clang')
96 parser.add_argument('--clang-args',
97 help='Space-separated extra args to clang, e.g. --clang-args=-v')
Simon Tatham109c7732019-10-10 08:25:34 +000098 parser.add_argument('--opt',
99 help='"opt" executable, defaults to $llvm_bin/opt')
Fangrui Song0a301a12018-03-02 17:37:04 +0000100 parser.add_argument(
101 '--functions', nargs='+', help='A list of function name regexes. '
102 'If specified, update CHECK lines for functions matching at least one regex')
103 parser.add_argument(
104 '--x86_extra_scrub', action='store_true',
105 help='Use more regex for x86 matching to reduce diffs between various subtargets')
Alex Richardson50807c82019-11-20 13:20:15 +0000106 parser.add_argument('--function-signature', action='store_true',
107 help='Keep function signature information around for the check line')
Fangrui Song0a301a12018-03-02 17:37:04 +0000108 parser.add_argument('tests', nargs='+')
Alex Richardson61873942019-11-20 13:19:48 +0000109 args = common.parse_commandline_args(parser)
Fangrui Song0a301a12018-03-02 17:37:04 +0000110 args.clang_args = shlex.split(args.clang_args or '')
111
112 if args.clang is None:
113 if args.llvm_bin is None:
114 args.clang = 'clang'
115 else:
116 args.clang = os.path.join(args.llvm_bin, 'clang')
117 if not distutils.spawn.find_executable(args.clang):
118 print('Please specify --llvm-bin or --clang', file=sys.stderr)
119 sys.exit(1)
Simon Tatham109c7732019-10-10 08:25:34 +0000120
Alex Richardsond9cc7d12019-10-31 21:18:32 +0000121 # Determine the builtin includes directory so that we can update tests that
122 # depend on the builtin headers. See get_clang_builtin_include_dir() and
123 # use_clang() in llvm/utils/lit/lit/llvm/config.py.
124 try:
125 builtin_include_dir = subprocess.check_output(
126 [args.clang, '-print-file-name=include']).decode().strip()
127 SUBST['%clang_cc1'] = ['-cc1', '-internal-isystem', builtin_include_dir,
128 '-nostdsysteminc']
129 except subprocess.CalledProcessError:
130 common.warn('Could not determine clang builtins directory, some tests '
131 'might not update correctly.')
132
Simon Tatham109c7732019-10-10 08:25:34 +0000133 if args.opt is None:
134 if args.llvm_bin is None:
135 args.opt = 'opt'
136 else:
137 args.opt = os.path.join(args.llvm_bin, 'opt')
138 if not distutils.spawn.find_executable(args.opt):
139 # Many uses of this tool will not need an opt binary, because it's only
140 # needed for updating a test that runs clang | opt | FileCheck. So we
141 # defer this error message until we find that opt is actually needed.
142 args.opt = None
143
Fangrui Song0a301a12018-03-02 17:37:04 +0000144 return args
145
146
Simon Tatham109c7732019-10-10 08:25:34 +0000147def get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict):
Fangrui Song0a301a12018-03-02 17:37:04 +0000148 # TODO Clean up duplication of asm/common build_function_body_dictionary
149 # Invoke external tool and extract function bodies.
150 raw_tool_output = common.invoke_tool(args.clang, clang_args, filename)
Simon Tatham109c7732019-10-10 08:25:34 +0000151 for extra_command in extra_commands:
152 extra_args = shlex.split(extra_command)
153 with tempfile.NamedTemporaryFile() as f:
154 f.write(raw_tool_output.encode())
155 f.flush()
156 if extra_args[0] == 'opt':
157 if args.opt is None:
158 print(filename, 'needs to run opt. '
159 'Please specify --llvm-bin or --opt', file=sys.stderr)
160 sys.exit(1)
161 extra_args[0] = args.opt
162 raw_tool_output = common.invoke_tool(extra_args[0],
163 extra_args[1:], f.name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000164 if '-emit-llvm' in clang_args:
165 common.build_function_body_dictionary(
166 common.OPT_FUNCTION_RE, common.scrub_body, [],
Alex Richardson50807c82019-11-20 13:20:15 +0000167 raw_tool_output, prefixes, func_dict, args.verbose, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000168 else:
169 print('The clang command line should include -emit-llvm as asm tests '
170 'are discouraged in Clang testsuite.', file=sys.stderr)
171 sys.exit(1)
172
173
174def main():
175 args = config()
David Bolvansky7169ea32019-08-07 14:44:50 +0000176 script_name = os.path.basename(__file__)
177 autogenerated_note = (ADVERT + 'utils/' + script_name)
Fangrui Song0a301a12018-03-02 17:37:04 +0000178
179 for filename in args.tests:
180 with open(filename) as f:
181 input_lines = [l.rstrip() for l in f]
Johannes Doerferte67f6472019-11-01 11:17:27 -0500182
David Bolvansky7169ea32019-08-07 14:44:50 +0000183 first_line = input_lines[0] if input_lines else ""
184 if 'autogenerated' in first_line and script_name not in first_line:
185 common.warn("Skipping test which wasn't autogenerated by " + script_name, filename)
186 continue
187
188 if args.update_only:
189 if not first_line or 'autogenerated' not in first_line:
190 common.warn("Skipping test which isn't autogenerated: " + filename)
191 continue
Fangrui Song0a301a12018-03-02 17:37:04 +0000192
193 # Extract RUN lines.
194 raw_lines = [m.group(1)
195 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
196 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
197 for l in raw_lines[1:]:
198 if run_lines[-1].endswith("\\"):
199 run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
200 else:
201 run_lines.append(l)
202
203 if args.verbose:
204 print('Found {} RUN lines:'.format(len(run_lines)), file=sys.stderr)
205 for l in run_lines:
206 print(' RUN: ' + l, file=sys.stderr)
207
208 # Build a list of clang command lines and check prefixes from RUN lines.
209 run_list = []
210 line2spell_and_mangled_list = collections.defaultdict(list)
211 for l in run_lines:
Simon Tatham109c7732019-10-10 08:25:34 +0000212 commands = [cmd.strip() for cmd in l.split('|')]
Fangrui Song0a301a12018-03-02 17:37:04 +0000213
214 triple_in_cmd = None
215 m = common.TRIPLE_ARG_RE.search(commands[0])
216 if m:
217 triple_in_cmd = m.groups()[0]
218
219 # Apply %clang substitution rule, replace %s by `filename`, and append args.clang_args
220 clang_args = shlex.split(commands[0])
221 if clang_args[0] not in SUBST:
222 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
223 continue
224 clang_args[0:1] = SUBST[clang_args[0]]
225 clang_args = [filename if i == '%s' else i for i in clang_args] + args.clang_args
226
Simon Tatham109c7732019-10-10 08:25:34 +0000227 # Permit piping the output through opt
228 if not (len(commands) == 2 or
229 (len(commands) == 3 and commands[1].startswith('opt'))):
230 print('WARNING: Skipping non-clang RUN line: ' + l, file=sys.stderr)
231
Fangrui Song0a301a12018-03-02 17:37:04 +0000232 # Extract -check-prefix in FileCheck args
233 filecheck_cmd = commands[-1]
David Bolvansky45be5e42019-07-29 17:41:00 +0000234 common.verify_filecheck_prefixes(filecheck_cmd)
Fangrui Song0a301a12018-03-02 17:37:04 +0000235 if not filecheck_cmd.startswith('FileCheck '):
236 print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
237 continue
238 check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
239 for item in m.group(1).split(',')]
240 if not check_prefixes:
241 check_prefixes = ['CHECK']
Simon Tatham109c7732019-10-10 08:25:34 +0000242 run_list.append((check_prefixes, clang_args, commands[1:-1], triple_in_cmd))
Fangrui Song0a301a12018-03-02 17:37:04 +0000243
244 # Strip CHECK lines which are in `prefix_set`, update test file.
245 prefix_set = set([prefix for p in run_list for prefix in p[0]])
246 input_lines = []
247 with open(filename, 'r+') as f:
248 for line in f:
249 m = CHECK_RE.match(line)
250 if not (m and m.group(1) in prefix_set) and line != '//\n':
251 input_lines.append(line)
252 f.seek(0)
253 f.writelines(input_lines)
254 f.truncate()
255
256 # Execute clang, generate LLVM IR, and extract functions.
257 func_dict = {}
258 for p in run_list:
259 prefixes = p[0]
260 for prefix in prefixes:
261 func_dict.update({prefix: dict()})
Simon Tatham109c7732019-10-10 08:25:34 +0000262 for prefixes, clang_args, extra_commands, triple_in_cmd in run_list:
Fangrui Song0a301a12018-03-02 17:37:04 +0000263 if args.verbose:
264 print('Extracted clang cmd: clang {}'.format(clang_args), file=sys.stderr)
265 print('Extracted FileCheck prefixes: {}'.format(prefixes), file=sys.stderr)
266
Simon Tatham109c7732019-10-10 08:25:34 +0000267 get_function_body(args, filename, clang_args, extra_commands, prefixes, triple_in_cmd, func_dict)
Fangrui Song0a301a12018-03-02 17:37:04 +0000268
Alex Richardson0df4a8f2019-11-15 12:50:10 +0000269 # Invoke clang -Xclang -ast-dump=json to get mapping from start lines to
270 # mangled names. Forward all clang args for now.
Fangrui Song0a301a12018-03-02 17:37:04 +0000271 for k, v in get_line2spell_and_mangled(args, clang_args).items():
272 line2spell_and_mangled_list[k].append(v)
273
274 output_lines = [autogenerated_note]
275 for idx, line in enumerate(input_lines):
276 # Discard any previous script advertising.
277 if line.startswith(ADVERT):
278 continue
279 if idx in line2spell_and_mangled_list:
280 added = set()
281 for spell, mangled in line2spell_and_mangled_list[idx]:
282 # One line may contain multiple function declarations.
283 # Skip if the mangled name has been added before.
284 # The line number may come from an included file,
285 # we simply require the spelling name to appear on the line
286 # to exclude functions from other files.
287 if mangled in added or spell not in line:
288 continue
289 if args.functions is None or any(re.search(regex, spell) for regex in args.functions):
290 if added:
291 output_lines.append('//')
292 added.add(mangled)
Alex Richardson50807c82019-11-20 13:20:15 +0000293 common.add_ir_checks(output_lines, '//', run_list, func_dict, mangled,
294 False, args.function_signature)
Fangrui Song0a301a12018-03-02 17:37:04 +0000295 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
305if __name__ == '__main__':
306 sys.exit(main())