1#!/usr/bin/env python2.7
2
3"""A test case update script.
4
5This script is a utility to update LLVM opt or llc test cases with new
6FileCheck patterns. It can either update all of the tests in the file or
7a single test function.
8"""
9
10import argparse
11import itertools
12import os         # Used to advertise this file's name ("autogenerated_note").
13import string
14import subprocess
15import sys
16import tempfile
17import re
18
19
20# RegEx: this is where the magic happens.
21
22SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)')
23SCRUB_WHITESPACE_RE = re.compile(r'(?!^(|  \w))[ \t]+', flags=re.M)
24SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
25SCRUB_X86_SHUFFLES_RE = (
26    re.compile(
27        r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem) = .*)$',
28        flags=re.M))
29SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
30SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
31SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
32SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
33
34RUN_LINE_RE = re.compile('^\s*;\s*RUN:\s*(.*)$')
35IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@([\w-]+)\s*\(')
36LLC_FUNCTION_RE = re.compile(
37    r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?'
38    r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
39    r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
40    flags=(re.M | re.S))
41OPT_FUNCTION_RE = re.compile(
42    r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w-]+?)\s*\('
43    r'(\s+)?[^{]*\{\n(?P<body>.*?)\}',
44    flags=(re.M | re.S))
45CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)')
46CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
47IR_VALUE_DEF_RE = re.compile(r'\s+%(.*) =')
48
49
50# Invoke the tool that is being tested.
51def invoke_tool(args, cmd_args, ir):
52  with open(ir) as ir_file:
53    stdout = subprocess.check_output(args.tool_binary + ' ' + cmd_args,
54                                     shell=True, stdin=ir_file)
55  # Fix line endings to unix CR style.
56  stdout = stdout.replace('\r\n', '\n')
57  return stdout
58
59
60# FIXME: Separate the x86-specific scrubbers, so this can be used for other targets.
61def scrub_asm(asm):
62  # Detect shuffle asm comments and hide the operands in favor of the comments.
63  asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
64  # Generically match the stack offset of a memory operand.
65  asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
66  # Generically match a RIP-relative memory operand.
67  asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
68  # Strip kill operands inserted into the asm.
69  asm = SCRUB_KILL_COMMENT_RE.sub('', asm)
70  return asm
71
72
73def scrub_body(body, tool_basename):
74  # Scrub runs of whitespace out of the assembly, but leave the leading
75  # whitespace in place.
76  body = SCRUB_WHITESPACE_RE.sub(r' ', body)
77  # Expand the tabs used for indentation.
78  body = string.expandtabs(body, 2)
79  # Strip trailing whitespace.
80  body = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', body)
81  if tool_basename == "llc":
82    body = scrub_asm(body)
83  return body
84
85
86# Build up a dictionary of all the function bodies.
87def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose, tool_basename):
88  if tool_basename == "llc":
89    func_regex = LLC_FUNCTION_RE
90  else:
91    func_regex = OPT_FUNCTION_RE
92  for m in func_regex.finditer(raw_tool_output):
93    if not m:
94      continue
95    func = m.group('func')
96    scrubbed_body = scrub_body(m.group('body'), tool_basename)
97    if func.startswith('stress'):
98      # We only use the last line of the function body for stress tests.
99      scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
100    if verbose:
101      print >>sys.stderr, 'Processing function: ' + func
102      for l in scrubbed_body.splitlines():
103        print >>sys.stderr, '  ' + l
104    for prefix in prefixes:
105      if func in func_dict[prefix] and func_dict[prefix][func] != scrubbed_body:
106        if prefix == prefixes[-1]:
107          print >>sys.stderr, ('WARNING: Found conflicting asm under the '
108                               'same prefix: %r!' % (prefix,))
109        else:
110          func_dict[prefix][func] = None
111          continue
112
113      func_dict[prefix][func] = scrubbed_body
114
115
116# Create a FileCheck variable name based on an IR name.
117def get_value_name(var):
118  if var.isdigit():
119    var = 'TMP' + var
120  var = var.replace('.', '_')
121  return var.upper()
122
123
124# Create a FileCheck variable from regex.
125def get_value_definition(var):
126  return '[[' + get_value_name(var) + ':%.*]]'
127
128
129# Use a FileCheck variable.
130def get_value_use(var):
131  return '[[' + get_value_name(var) + ']]'
132
133
134# Replace IR value defs and uses with FileCheck variables.
135def genericize_check_lines(lines):
136  lines_with_def = []
137  vars_seen = []
138  for line in lines:
139    # An IR variable named '%.' matches the FileCheck regex string.
140    line = line.replace('%.', '%dot')
141    m = IR_VALUE_DEF_RE.match(line)
142    if m:
143      vars_seen.append(m.group(1))
144      line = line.replace('%' + m.group(1), get_value_definition(m.group(1)))
145
146    lines_with_def.append(line)
147
148  # A single def isn't worth replacing?
149  #if len(vars_seen) < 2:
150  #  return lines
151
152  output_lines = []
153  vars_seen.sort(key=len, reverse=True)
154  for line in lines_with_def:
155    for var in vars_seen:
156      line = line.replace('%' + var, get_value_use(var))
157    output_lines.append(line)
158
159  return output_lines
160
161
162def add_checks(output_lines, prefix_list, func_dict, func_name, tool_basename):
163  # Select a label format based on the whether we're checking asm or IR.
164  if tool_basename == "llc":
165    check_label_format = "; %s-LABEL: %s:"
166  else:
167    check_label_format = "; %s-LABEL: @%s("
168
169  printed_prefixes = []
170  for checkprefixes, _ in prefix_list:
171    for checkprefix in checkprefixes:
172      if checkprefix in printed_prefixes:
173        break
174      if not func_dict[checkprefix][func_name]:
175        continue
176      # Add some space between different check prefixes, but not after the last
177      # check line (before the test code).
178      #if len(printed_prefixes) != 0:
179      #  output_lines.append(';')
180      printed_prefixes.append(checkprefix)
181      output_lines.append(check_label_format % (checkprefix, func_name))
182      func_body = func_dict[checkprefix][func_name].splitlines()
183
184      # For IR output, change all defs to FileCheck variables, so we're immune
185      # to variable naming fashions.
186      if tool_basename == "opt":
187        func_body = genericize_check_lines(func_body)
188
189      # Handle the first line of the function body as a special case because
190      # it's often just noise (a useless asm comment or entry label).
191      if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
192        is_blank_line = True
193      else:
194        output_lines.append('; %s:       %s' % (checkprefix, func_body[0]))
195        is_blank_line = False
196
197      for func_line in func_body[1:]:
198        if func_line.strip() == '':
199          is_blank_line = True
200          continue
201        # Do not waste time checking IR comments.
202        if tool_basename == "opt":
203          func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
204
205        # Skip blank lines instead of checking them.
206        if is_blank_line == True:
207          output_lines.append('; %s:       %s' % (checkprefix, func_line))
208        else:
209          output_lines.append('; %s-NEXT:  %s' % (checkprefix, func_line))
210        is_blank_line = False
211
212      # Add space between different check prefixes and also before the first
213      # line of code in the test function.
214      output_lines.append(';')
215      break
216  return output_lines
217
218
219def should_add_line_to_output(input_line, prefix_set):
220  # Skip any blank comment lines in the IR.
221  if input_line.strip() == ';':
222    return False
223  # Skip any blank lines in the IR.
224  #if input_line.strip() == '':
225  #  return False
226  # And skip any CHECK lines. We're building our own.
227  m = CHECK_RE.match(input_line)
228  if m and m.group(1) in prefix_set:
229    return False
230
231  return True
232
233
234def main():
235  parser = argparse.ArgumentParser(description=__doc__)
236  parser.add_argument('-v', '--verbose', action='store_true',
237                      help='Show verbose output')
238  parser.add_argument('--tool-binary', default='llc',
239                      help='The tool used to generate the test case')
240  parser.add_argument(
241      '--function', help='The function in the test file to update')
242  parser.add_argument('tests', nargs='+')
243  args = parser.parse_args()
244
245  autogenerated_note = ('; NOTE: Assertions have been autogenerated by '
246                        + os.path.basename(__file__))
247
248  tool_basename = os.path.basename(args.tool_binary)
249  if (tool_basename != "llc" and tool_basename != "opt"):
250    print >>sys.stderr, 'ERROR: Unexpected tool name: ' + tool_basename
251    sys.exit(1)
252
253  for test in args.tests:
254    if args.verbose:
255      print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
256    with open(test) as f:
257      input_lines = [l.rstrip() for l in f]
258
259    run_lines = [m.group(1)
260                 for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
261    if args.verbose:
262      print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
263      for l in run_lines:
264        print >>sys.stderr, '  RUN: ' + l
265
266    prefix_list = []
267    for l in run_lines:
268      (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
269
270      if not tool_cmd.startswith(tool_basename + ' '):
271        print >>sys.stderr, 'WARNING: Skipping non-%s RUN line: %s' % (tool_basename, l)
272        continue
273
274      if not filecheck_cmd.startswith('FileCheck '):
275        print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
276        continue
277
278      tool_cmd_args = tool_cmd[len(tool_basename):].strip()
279      tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
280
281      check_prefixes = [m.group(1)
282                        for m in CHECK_PREFIX_RE.finditer(filecheck_cmd)]
283      if not check_prefixes:
284        check_prefixes = ['CHECK']
285
286      # FIXME: We should use multiple check prefixes to common check lines. For
287      # now, we just ignore all but the last.
288      prefix_list.append((check_prefixes, tool_cmd_args))
289
290    func_dict = {}
291    for prefixes, _ in prefix_list:
292      for prefix in prefixes:
293        func_dict.update({prefix: dict()})
294    for prefixes, tool_args in prefix_list:
295      if args.verbose:
296        print >>sys.stderr, 'Extracted tool cmd: ' + tool_basename + ' ' + tool_args
297        print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
298
299      raw_tool_output = invoke_tool(args, tool_args, test)
300      build_function_body_dictionary(raw_tool_output, prefixes, func_dict, args.verbose, tool_basename)
301
302    is_in_function = False
303    is_in_function_start = False
304    prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
305    if args.verbose:
306      print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
307    output_lines = []
308    output_lines.append(autogenerated_note)
309
310    for input_line in input_lines:
311      if is_in_function_start:
312        if input_line == '':
313          continue
314        if input_line.lstrip().startswith(';'):
315          m = CHECK_RE.match(input_line)
316          if not m or m.group(1) not in prefix_set:
317            output_lines.append(input_line)
318            continue
319
320        # Print out the various check lines here.
321        output_lines = add_checks(output_lines, prefix_list, func_dict, name, tool_basename)
322        is_in_function_start = False
323
324      if is_in_function:
325        if should_add_line_to_output(input_line, prefix_set) == True:
326          # This input line of the function body will go as-is into the output.
327          # Except make leading whitespace uniform: 2 spaces.
328          input_line = SCRUB_LEADING_WHITESPACE_RE.sub(r'  ', input_line)
329          output_lines.append(input_line)
330        else:
331          continue
332        if input_line.strip() == '}':
333          is_in_function = False
334        continue
335
336      if input_line == autogenerated_note:
337        continue
338
339      # If it's outside a function, it just gets copied to the output.
340      output_lines.append(input_line)
341
342      m = IR_FUNCTION_RE.match(input_line)
343      if not m:
344        continue
345      name = m.group(1)
346      if args.function is not None and name != args.function:
347        # When filtering on a specific function, skip all others.
348        continue
349      is_in_function = is_in_function_start = True
350
351    if args.verbose:
352      print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
353
354    with open(test, 'wb') as f:
355      f.writelines([l + '\n' for l in output_lines])
356
357
358if __name__ == '__main__':
359  main()
360
361