forked from llvm/llvm-project
- Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathupdate_mir_test_checks.py
executable file
·439 lines (368 loc) · 15.7 KB
/
update_mir_test_checks.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env python3
"""Updates FileCheck checks in MIR tests.
This script is a utility to update MIR based tests with new FileCheck
patterns.
The checks added by this script will cover the entire body of each
function it handles. Virtual registers used are given names via
FileCheck patterns, so if you do want to check a subset of the body it
should be straightforward to trim out the irrelevant parts. None of
the YAML metadata will be checked, other than function names.
If there are multiple llc commands in a test, the full set of checks
will be repeated for each different check pattern. Checks for patterns
that are common between different commands will be left as-is by
default, or removed if the --remove-common-prefixes flag is provided.
"""
from __future__ importprint_function
importargparse
importcollections
importglob
importos
importre
importsubprocess
importsys
fromUpdateTestChecksimportcommon
MIR_FUNC_NAME_RE=re.compile(r' *name: *(?P<func>[A-Za-z0-9_.-]+)')
MIR_BODY_BEGIN_RE=re.compile(r' *body: *\|')
MIR_BASIC_BLOCK_RE=re.compile(r' *bb\.[0-9]+.*:$')
VREG_RE=re.compile(r'(%[0-9]+)(?::[a-z0-9_]+)?(?:\([<>a-z0-9 ]+\))?')
MI_FLAGS_STR= (
r'(frame-setup |frame-destroy |nnan |ninf |nsz |arcp |contract |afn '
r'|reassoc |nuw |nsw |exact |fpexcept )*')
VREG_DEF_RE=re.compile(
r'^ *(?P<vregs>{0}(?:, {0})*) = '
r'{1}(?P<opcode>[A-Zt][A-Za-z0-9_]+)'.format(VREG_RE.pattern, MI_FLAGS_STR))
MIR_PREFIX_DATA_RE=re.compile(r'^ *(;|bb.[0-9].*: *$|[a-z]+:( |$)|$)')
IR_FUNC_NAME_RE=re.compile(
r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[A-Za-z0-9_.]+)\s*\(')
IR_PREFIX_DATA_RE=re.compile(r'^ *(;|$)')
MIR_FUNC_RE=re.compile(
r'^---$'
r'\n'
r'^ *name: *(?P<func>[A-Za-z0-9_.-]+)$'
r'.*?'
r'^ *body: *\|\n'
r'(?P<body>.*?)\n'
r'^\.\.\.$',
flags=(re.M|re.S))
classLLC:
def__init__(self, bin):
self.bin=bin
def__call__(self, args, ir):
ifir.endswith('.mir'):
args='{} -x mir'.format(args)
withopen(ir) asir_file:
stdout=subprocess.check_output('{} {}'.format(self.bin, args),
shell=True, stdin=ir_file)
ifsys.version_info[0] >2:
stdout=stdout.decode()
# Fix line endings to unix CR style.
stdout=stdout.replace('\r\n', '\n')
returnstdout
classRun:
def__init__(self, prefixes, cmd_args, triple):
self.prefixes=prefixes
self.cmd_args=cmd_args
self.triple=triple
def__getitem__(self, index):
return [self.prefixes, self.cmd_args, self.triple][index]
deflog(msg, verbose=True):
ifverbose:
print(msg, file=sys.stderr)
deffind_triple_in_ir(lines, verbose=False):
forlinlines:
m=common.TRIPLE_IR_RE.match(l)
ifm:
returnm.group(1)
returnNone
defbuild_run_list(test, run_lines, verbose=False):
run_list= []
all_prefixes= []
forlinrun_lines:
if'|'notinl:
common.warn('Skipping unparseable RUN line: '+l)
continue
commands= [cmd.strip() forcmdinl.split('|', 1)]
llc_cmd=commands[0]
filecheck_cmd=commands[1] iflen(commands) >1else''
common.verify_filecheck_prefixes(filecheck_cmd)
ifnotllc_cmd.startswith('llc '):
common.warn('Skipping non-llc RUN line: {}'.format(l), test_file=test)
continue
ifnotfilecheck_cmd.startswith('FileCheck '):
common.warn('Skipping non-FileChecked RUN line: {}'.format(l),
test_file=test)
continue
triple=None
m=common.TRIPLE_ARG_RE.search(llc_cmd)
ifm:
triple=m.group(1)
# If we find -march but not -mtriple, use that.
m=common.MARCH_ARG_RE.search(llc_cmd)
ifmandnottriple:
triple='{}--'.format(m.group(1))
cmd_args=llc_cmd[len('llc'):].strip()
cmd_args=cmd_args.replace('< %s', '').replace('%s', '').strip()
check_prefixes= [
item
formincommon.CHECK_PREFIX_RE.finditer(filecheck_cmd)
foriteminm.group(1).split(',')]
ifnotcheck_prefixes:
check_prefixes= ['CHECK']
all_prefixes+=check_prefixes
run_list.append(Run(check_prefixes, cmd_args, triple))
# Remove any common prefixes. We'll just leave those entirely alone.
common_prefixes=set([prefixforprefixinall_prefixes
ifall_prefixes.count(prefix) >1])
forruninrun_list:
run.prefixes= [pforpinrun.prefixesifpnotincommon_prefixes]
returnrun_list, common_prefixes
deffind_functions_with_one_bb(lines, verbose=False):
result= []
cur_func=None
bbs=0
forlineinlines:
m=MIR_FUNC_NAME_RE.match(line)
ifm:
ifbbs==1:
result.append(cur_func)
cur_func=m.group('func')
bbs=0
m=MIR_BASIC_BLOCK_RE.match(line)
ifm:
bbs+=1
ifbbs==1:
result.append(cur_func)
returnresult
defbuild_function_body_dictionary(test, raw_tool_output, triple, prefixes,
func_dict, verbose):
forminMIR_FUNC_RE.finditer(raw_tool_output):
func=m.group('func')
body=m.group('body')
ifverbose:
log('Processing function: {}'.format(func))
forlinbody.splitlines():
log(' {}'.format(l))
forprefixinprefixes:
iffuncinfunc_dict[prefix] andfunc_dict[prefix][func] !=body:
common.warn('Found conflicting asm for prefix: {}'.format(prefix),
test_file=test)
func_dict[prefix][func] =body
defadd_checks_for_function(test, output_lines, run_list, func_dict, func_name,
single_bb, verbose=False):
printed_prefixes=set()
forruninrun_list:
forprefixinrun.prefixes:
ifprefixinprinted_prefixes:
continue
ifnotfunc_dict[prefix][func_name]:
continue
# if printed_prefixes:
# # Add some space between different check prefixes.
# output_lines.append('')
printed_prefixes.add(prefix)
log('Adding {} lines for {}'.format(prefix, func_name), verbose)
add_check_lines(test, output_lines, prefix, func_name, single_bb,
func_dict[prefix][func_name].splitlines())
break
returnoutput_lines
defadd_check_lines(test, output_lines, prefix, func_name, single_bb,
func_body):
ifsingle_bb:
# Don't bother checking the basic block label for a single BB
func_body.pop(0)
ifnotfunc_body:
common.warn('Function has no instructions to check: {}'.format(func_name),
test_file=test)
return
first_line=func_body[0]
indent=len(first_line) -len(first_line.lstrip(' '))
# A check comment, indented the appropriate amount
check='{:>{}}; {}'.format('', indent, prefix)
output_lines.append('{}-LABEL: name: {}'.format(check, func_name))
first_check=True
vreg_map= {}
forfunc_lineinfunc_body:
ifnotfunc_line.strip():
# The mir printer prints leading whitespace so we can't use CHECK-EMPTY:
output_lines.append(check+'-NEXT: {{'+func_line+'$}}')
continue
m=VREG_DEF_RE.match(func_line)
ifm:
forvreginVREG_RE.finditer(m.group('vregs')):
name=mangle_vreg(m.group('opcode'), vreg_map.values())
vreg_map[vreg.group(1)] =name
func_line=func_line.replace(
vreg.group(1), '[[{}:%[0-9]+]]'.format(name), 1)
fornumber, nameinvreg_map.items():
func_line=re.sub(r'{}\b'.format(number), '[[{}]]'.format(name),
func_line)
filecheck_directive=checkiffirst_checkelsecheck+'-NEXT'
first_check=False
check_line='{}: {}'.format(filecheck_directive, func_line[indent:]).rstrip()
output_lines.append(check_line)
defmangle_vreg(opcode, current_names):
base=opcode
# Simplify some common prefixes and suffixes
ifopcode.startswith('G_'):
base=base[len('G_'):]
ifopcode.endswith('_PSEUDO'):
base=base[:len('_PSEUDO')]
# Shorten some common opcodes with long-ish names
base=dict(IMPLICIT_DEF='DEF',
GLOBAL_VALUE='GV',
CONSTANT='C',
FCONSTANT='C',
MERGE_VALUES='MV',
UNMERGE_VALUES='UV',
INTRINSIC='INT',
INTRINSIC_W_SIDE_EFFECTS='INT',
INSERT_VECTOR_ELT='IVEC',
EXTRACT_VECTOR_ELT='EVEC',
SHUFFLE_VECTOR='SHUF').get(base, base)
# Avoid ambiguity when opcodes end in numbers
iflen(base.rstrip('0123456789')) <len(base):
base+='_'
i=0
fornameincurrent_names:
ifname.rstrip('0123456789') ==base:
i+=1
ifi:
return'{}{}'.format(base, i)
returnbase
defshould_add_line_to_output(input_line, prefix_set):
# Skip any check lines that we're handling.
m=common.CHECK_RE.match(input_line)
ifmandm.group(1) inprefix_set:
returnFalse
returnTrue
defupdate_test_file(args, test):
withopen(test) asfd:
input_lines= [l.rstrip() forlinfd]
script_name=os.path.basename(__file__)
first_line=input_lines[0] ifinput_lineselse""
if'autogenerated'infirst_lineandscript_namenotinfirst_line:
common.warn("Skipping test which wasn't autogenerated by "+
script_name+": "+test)
return
ifargs.update_only:
ifnotfirst_lineor'autogenerated'notinfirst_line:
common.warn("Skipping test which isn't autogenerated: "+test)
return
triple_in_ir=find_triple_in_ir(input_lines, args.verbose)
run_lines=common.find_run_lines(test, input_lines)
run_list, common_prefixes=build_run_list(test, run_lines, args.verbose)
simple_functions=find_functions_with_one_bb(input_lines, args.verbose)
func_dict= {}
forruninrun_list:
forprefixinrun.prefixes:
func_dict.update({prefix: dict()})
forprefixes, llc_args, triple_in_cmdinrun_list:
log('Extracted LLC cmd: llc {}'.format(llc_args), args.verbose)
log('Extracted FileCheck prefixes: {}'.format(prefixes), args.verbose)
raw_tool_output=args.llc(llc_args, test)
ifnottriple_in_cmdandnottriple_in_ir:
common.warn('No triple found: skipping file', test_file=test)
return
build_function_body_dictionary(test, raw_tool_output,
triple_in_cmdortriple_in_ir,
prefixes, func_dict, args.verbose)
state='toplevel'
func_name=None
prefix_set=set([prefixforruninrun_listforprefixinrun.prefixes])
log('Rewriting FileCheck prefixes: {}'.format(prefix_set), args.verbose)
ifargs.remove_common_prefixes:
prefix_set.update(common_prefixes)
elifcommon_prefixes:
common.warn('Ignoring common prefixes: {}'.format(common_prefixes),
test_file=test)
comment_char='#'iftest.endswith('.mir') else';'
autogenerated_note= ('{} NOTE: Assertions have been autogenerated by '
'utils/{}'.format(comment_char, script_name))
output_lines= []
output_lines.append(autogenerated_note)
forinput_lineininput_lines:
ifinput_line==autogenerated_note:
continue
ifstate=='toplevel':
m=IR_FUNC_NAME_RE.match(input_line)
ifm:
state='ir function prefix'
func_name=m.group('func')
ifinput_line.rstrip('| \r\n') =='---':
state='document'
output_lines.append(input_line)
elifstate=='document':
m=MIR_FUNC_NAME_RE.match(input_line)
ifm:
state='mir function metadata'
func_name=m.group('func')
ifinput_line.strip() =='...':
state='toplevel'
func_name=None
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
elifstate=='mir function metadata':
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
m=MIR_BODY_BEGIN_RE.match(input_line)
ifm:
iffunc_nameinsimple_functions:
# If there's only one block, put the checks inside it
state='mir function prefix'
continue
state='mir function body'
add_checks_for_function(test, output_lines, run_list,
func_dict, func_name, single_bb=False,
verbose=args.verbose)
elifstate=='mir function prefix':
m=MIR_PREFIX_DATA_RE.match(input_line)
ifnotm:
state='mir function body'
add_checks_for_function(test, output_lines, run_list,
func_dict, func_name, single_bb=True,
verbose=args.verbose)
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
elifstate=='mir function body':
ifinput_line.strip() =='...':
state='toplevel'
func_name=None
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
elifstate=='ir function prefix':
m=IR_PREFIX_DATA_RE.match(input_line)
ifnotm:
state='ir function body'
add_checks_for_function(test, output_lines, run_list,
func_dict, func_name, single_bb=False,
verbose=args.verbose)
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
elifstate=='ir function body':
ifinput_line.strip() =='}':
state='toplevel'
func_name=None
ifshould_add_line_to_output(input_line, prefix_set):
output_lines.append(input_line)
log('Writing {} lines to {}...'.format(len(output_lines), test), args.verbose)
withopen(test, 'wb') asfd:
fd.writelines(['{}\n'.format(l).encode('utf-8') forlinoutput_lines])
defmain():
parser=argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--llc-binary', dest='llc', default='llc', type=LLC,
help='The "llc" binary to generate the test case with')
parser.add_argument('--remove-common-prefixes', action='store_true',
help='Remove existing check lines whose prefixes are '
'shared between multiple commands')
parser.add_argument('tests', nargs='+')
args=common.parse_commandline_args(parser)
test_paths= [testforpatterninargs.testsfortestinglob.glob(pattern)]
fortestintest_paths:
try:
update_test_file(args, test)
exceptException:
common.warn('Error processing file', test_file=test)
raise
if__name__=='__main__':
main()