PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/utils/update_test_checks.py

http://github.com/earl/llvm-mirror
Python | 219 lines | 201 code | 15 blank | 3 comment | 11 complexity | 7eceb8f78683003c77bc65adbd013c60 MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0
  1. #!/usr/bin/env python
  2. """A script to generate FileCheck statements for 'opt' regression tests.
  3. This script is a utility to update LLVM opt test cases with new
  4. FileCheck patterns. It can either update all of the tests in the file or
  5. a single test function.
  6. Example usage:
  7. $ update_test_checks.py --opt=../bin/opt test/foo.ll
  8. Workflow:
  9. 1. Make a compiler patch that requires updating some number of FileCheck lines
  10. in regression test files.
  11. 2. Save the patch and revert it from your local work area.
  12. 3. Update the RUN-lines in the affected regression tests to look canonical.
  13. Example: "; RUN: opt < %s -instcombine -S | FileCheck %s"
  14. 4. Refresh the FileCheck lines for either the entire file or select functions by
  15. running this script.
  16. 5. Commit the fresh baseline of checks.
  17. 6. Apply your patch from step 1 and rebuild your local binaries.
  18. 7. Re-run this script on affected regression tests.
  19. 8. Check the diffs to ensure the script has done something reasonable.
  20. 9. Submit a patch including the regression test diffs for review.
  21. A common pattern is to have the script insert complete checking of every
  22. instruction. Then, edit it down to only check the relevant instructions.
  23. The script is designed to make adding checks to a test case fast, it is *not*
  24. designed to be authoratitive about what constitutes a good test!
  25. """
  26. from __future__ import print_function
  27. import argparse
  28. import glob
  29. import itertools
  30. import os # Used to advertise this file's name ("autogenerated_note").
  31. import string
  32. import subprocess
  33. import sys
  34. import tempfile
  35. import re
  36. from UpdateTestChecks import common
  37. ADVERT = '; NOTE: Assertions have been autogenerated by '
  38. # RegEx: this is where the magic happens.
  39. IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@([\w-]+)\s*\(')
  40. def main():
  41. from argparse import RawTextHelpFormatter
  42. parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
  43. parser.add_argument('-v', '--verbose', action='store_true',
  44. help='Show verbose output')
  45. parser.add_argument('--opt-binary', default='opt',
  46. help='The opt binary used to generate the test case')
  47. parser.add_argument(
  48. '--function', help='The function in the test file to update')
  49. parser.add_argument('-u', '--update-only', action='store_true',
  50. help='Only update test if it was already autogened')
  51. parser.add_argument('-p', '--preserve-names', action='store_true',
  52. help='Do not scrub IR names')
  53. parser.add_argument('tests', nargs='+')
  54. args = parser.parse_args()
  55. script_name = os.path.basename(__file__)
  56. autogenerated_note = (ADVERT + 'utils/' + script_name)
  57. opt_basename = os.path.basename(args.opt_binary)
  58. if not re.match(r'^opt(-\d+)?$', opt_basename):
  59. common.error('Unexpected opt name: ' + opt_basename)
  60. sys.exit(1)
  61. opt_basename = 'opt'
  62. for test in args.tests:
  63. if not glob.glob(test):
  64. common.warn("Test file pattern '%s' was not found. Ignoring it." % (test,))
  65. continue
  66. # On Windows we must expand the patterns ourselves.
  67. test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
  68. for test in test_paths:
  69. if args.verbose:
  70. print('Scanning for RUN lines in test file: ' + test, file=sys.stderr)
  71. with open(test) as f:
  72. input_lines = [l.rstrip() for l in f]
  73. first_line = input_lines[0] if input_lines else ""
  74. if 'autogenerated' in first_line and script_name not in first_line:
  75. common.warn("Skipping test which wasn't autogenerated by " + script_name, test)
  76. continue
  77. if args.update_only:
  78. if not first_line or 'autogenerated' not in first_line:
  79. common.warn("Skipping test which isn't autogenerated: " + test)
  80. continue
  81. raw_lines = [m.group(1)
  82. for m in [common.RUN_LINE_RE.match(l) for l in input_lines] if m]
  83. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  84. for l in raw_lines[1:]:
  85. if run_lines[-1].endswith('\\'):
  86. run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
  87. else:
  88. run_lines.append(l)
  89. if args.verbose:
  90. print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
  91. for l in run_lines:
  92. print(' RUN: ' + l, file=sys.stderr)
  93. prefix_list = []
  94. for l in run_lines:
  95. if '|' not in l:
  96. common.warn('Skipping unparseable RUN line: ' + l)
  97. continue
  98. (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
  99. common.verify_filecheck_prefixes(filecheck_cmd)
  100. if not tool_cmd.startswith(opt_basename + ' '):
  101. common.warn('Skipping non-%s RUN line: %s' % (opt_basename, l))
  102. continue
  103. if not filecheck_cmd.startswith('FileCheck '):
  104. common.warn('Skipping non-FileChecked RUN line: ' + l)
  105. continue
  106. tool_cmd_args = tool_cmd[len(opt_basename):].strip()
  107. tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
  108. check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  109. for item in m.group(1).split(',')]
  110. if not check_prefixes:
  111. check_prefixes = ['CHECK']
  112. # FIXME: We should use multiple check prefixes to common check lines. For
  113. # now, we just ignore all but the last.
  114. prefix_list.append((check_prefixes, tool_cmd_args))
  115. func_dict = {}
  116. for prefixes, _ in prefix_list:
  117. for prefix in prefixes:
  118. func_dict.update({prefix: dict()})
  119. for prefixes, opt_args in prefix_list:
  120. if args.verbose:
  121. print('Extracted opt cmd: ' + opt_basename + ' ' + opt_args, file=sys.stderr)
  122. print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
  123. raw_tool_output = common.invoke_tool(args.opt_binary, opt_args, test)
  124. common.build_function_body_dictionary(
  125. common.OPT_FUNCTION_RE, common.scrub_body, [],
  126. raw_tool_output, prefixes, func_dict, args.verbose)
  127. is_in_function = False
  128. is_in_function_start = False
  129. prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
  130. if args.verbose:
  131. print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
  132. output_lines = []
  133. output_lines.append(autogenerated_note)
  134. for input_line in input_lines:
  135. if is_in_function_start:
  136. if input_line == '':
  137. continue
  138. if input_line.lstrip().startswith(';'):
  139. m = common.CHECK_RE.match(input_line)
  140. if not m or m.group(1) not in prefix_set:
  141. output_lines.append(input_line)
  142. continue
  143. # Print out the various check lines here.
  144. common.add_ir_checks(output_lines, ';', prefix_list, func_dict,
  145. func_name, args.preserve_names)
  146. is_in_function_start = False
  147. if is_in_function:
  148. if common.should_add_line_to_output(input_line, prefix_set):
  149. # This input line of the function body will go as-is into the output.
  150. # Except make leading whitespace uniform: 2 spaces.
  151. input_line = common.SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line)
  152. output_lines.append(input_line)
  153. else:
  154. continue
  155. if input_line.strip() == '}':
  156. is_in_function = False
  157. continue
  158. # Discard any previous script advertising.
  159. if input_line.startswith(ADVERT):
  160. continue
  161. # If it's outside a function, it just gets copied to the output.
  162. output_lines.append(input_line)
  163. m = IR_FUNCTION_RE.match(input_line)
  164. if not m:
  165. continue
  166. func_name = m.group(1)
  167. if args.function is not None and func_name != args.function:
  168. # When filtering on a specific function, skip all others.
  169. continue
  170. is_in_function = is_in_function_start = True
  171. if args.verbose:
  172. print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
  173. with open(test, 'wb') as f:
  174. f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])
  175. if __name__ == '__main__':
  176. main()