update_test_checks.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. #!/usr/bin/env python2.7
  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 itertools
  29. import os # Used to advertise this file's name ("autogenerated_note").
  30. import string
  31. import subprocess
  32. import sys
  33. import tempfile
  34. import re
  35. from UpdateTestChecks import common
  36. ADVERT = '; NOTE: Assertions have been autogenerated by '
  37. # RegEx: this is where the magic happens.
  38. IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@([\w-]+)\s*\(')
  39. def main():
  40. from argparse import RawTextHelpFormatter
  41. parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
  42. parser.add_argument('-v', '--verbose', action='store_true',
  43. help='Show verbose output')
  44. parser.add_argument('--opt-binary', default='opt',
  45. help='The opt binary used to generate the test case')
  46. parser.add_argument(
  47. '--function', help='The function in the test file to update')
  48. parser.add_argument('tests', nargs='+')
  49. args = parser.parse_args()
  50. autogenerated_note = (ADVERT + 'utils/' + os.path.basename(__file__))
  51. opt_basename = os.path.basename(args.opt_binary)
  52. if (opt_basename != "opt"):
  53. print('ERROR: Unexpected opt name: ' + opt_basename, file=sys.stderr)
  54. sys.exit(1)
  55. for test in args.tests:
  56. if args.verbose:
  57. print('Scanning for RUN lines in test file: %s' % (test,), file=sys.stderr)
  58. with open(test) as f:
  59. input_lines = [l.rstrip() for l in f]
  60. raw_lines = [m.group(1)
  61. for m in [common.RUN_LINE_RE.match(l) for l in input_lines] if m]
  62. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  63. for l in raw_lines[1:]:
  64. if run_lines[-1].endswith("\\"):
  65. run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
  66. else:
  67. run_lines.append(l)
  68. if args.verbose:
  69. print('Found %d RUN lines:' % (len(run_lines),), file=sys.stderr)
  70. for l in run_lines:
  71. print(' RUN: ' + l, file=sys.stderr)
  72. prefix_list = []
  73. for l in run_lines:
  74. (tool_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
  75. if not tool_cmd.startswith(opt_basename + ' '):
  76. print('WARNING: Skipping non-%s RUN line: %s' % (opt_basename, l), file=sys.stderr)
  77. continue
  78. if not filecheck_cmd.startswith('FileCheck '):
  79. print('WARNING: Skipping non-FileChecked RUN line: ' + l, file=sys.stderr)
  80. continue
  81. tool_cmd_args = tool_cmd[len(opt_basename):].strip()
  82. tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
  83. check_prefixes = [item for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  84. for item in m.group(1).split(',')]
  85. if not check_prefixes:
  86. check_prefixes = ['CHECK']
  87. # FIXME: We should use multiple check prefixes to common check lines. For
  88. # now, we just ignore all but the last.
  89. prefix_list.append((check_prefixes, tool_cmd_args))
  90. func_dict = {}
  91. for prefixes, _ in prefix_list:
  92. for prefix in prefixes:
  93. func_dict.update({prefix: dict()})
  94. for prefixes, opt_args in prefix_list:
  95. if args.verbose:
  96. print('Extracted opt cmd: ' + opt_basename + ' ' + opt_args, file=sys.stderr)
  97. print('Extracted FileCheck prefixes: ' + str(prefixes), file=sys.stderr)
  98. raw_tool_output = common.invoke_tool(args.opt_binary, opt_args, test)
  99. common.build_function_body_dictionary(
  100. common.OPT_FUNCTION_RE, common.scrub_body, [],
  101. raw_tool_output, prefixes, func_dict, args.verbose)
  102. is_in_function = False
  103. is_in_function_start = False
  104. prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
  105. if args.verbose:
  106. print('Rewriting FileCheck prefixes: %s' % (prefix_set,), file=sys.stderr)
  107. output_lines = []
  108. output_lines.append(autogenerated_note)
  109. for input_line in input_lines:
  110. if is_in_function_start:
  111. if input_line == '':
  112. continue
  113. if input_line.lstrip().startswith(';'):
  114. m = common.CHECK_RE.match(input_line)
  115. if not m or m.group(1) not in prefix_set:
  116. output_lines.append(input_line)
  117. continue
  118. # Print out the various check lines here.
  119. common.add_ir_checks(output_lines, ';', prefix_list, func_dict, func_name)
  120. is_in_function_start = False
  121. if is_in_function:
  122. if common.should_add_line_to_output(input_line, prefix_set):
  123. # This input line of the function body will go as-is into the output.
  124. # Except make leading whitespace uniform: 2 spaces.
  125. input_line = common.SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line)
  126. output_lines.append(input_line)
  127. else:
  128. continue
  129. if input_line.strip() == '}':
  130. is_in_function = False
  131. continue
  132. # Discard any previous script advertising.
  133. if input_line.startswith(ADVERT):
  134. continue
  135. # If it's outside a function, it just gets copied to the output.
  136. output_lines.append(input_line)
  137. m = IR_FUNCTION_RE.match(input_line)
  138. if not m:
  139. continue
  140. func_name = m.group(1)
  141. if args.function is not None and func_name != args.function:
  142. # When filtering on a specific function, skip all others.
  143. continue
  144. is_in_function = is_in_function_start = True
  145. if args.verbose:
  146. print('Writing %d lines to %s...' % (len(output_lines), test), file=sys.stderr)
  147. with open(test, 'wb') as f:
  148. f.writelines([l + '\n' for l in output_lines])
  149. if __name__ == '__main__':
  150. main()