update_llc_test_checks.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. #!/usr/bin/env python2.7
  2. """A test case update script.
  3. This script is a utility to update LLVM X86 'llc' based 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. """
  7. import argparse
  8. import itertools
  9. import string
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import re
  14. def llc(args, cmd_args, ir):
  15. with open(ir) as ir_file:
  16. stdout = subprocess.check_output(args.llc_binary + ' ' + cmd_args,
  17. shell=True, stdin=ir_file)
  18. return stdout
  19. ASM_SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M)
  20. ASM_SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
  21. ASM_SCRUB_SHUFFLES_RE = (
  22. re.compile(
  23. r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem) = .*)$',
  24. flags=re.M))
  25. ASM_SCRUB_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
  26. ASM_SCRUB_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
  27. ASM_SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
  28. def scrub_asm(asm):
  29. # Scrub runs of whitespace out of the assembly, but leave the leading
  30. # whitespace in place.
  31. asm = ASM_SCRUB_WHITESPACE_RE.sub(r' ', asm)
  32. # Expand the tabs used for indentation.
  33. asm = string.expandtabs(asm, 2)
  34. # Detect shuffle asm comments and hide the operands in favor of the comments.
  35. asm = ASM_SCRUB_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
  36. # Generically match the stack offset of a memory operand.
  37. asm = ASM_SCRUB_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
  38. # Generically match a RIP-relative memory operand.
  39. asm = ASM_SCRUB_RIP_RE.sub(r'{{.*}}(%rip)', asm)
  40. # Strip kill operands inserted into the asm.
  41. asm = ASM_SCRUB_KILL_COMMENT_RE.sub('', asm)
  42. # Strip trailing whitespace.
  43. asm = ASM_SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
  44. return asm
  45. def main():
  46. parser = argparse.ArgumentParser(description=__doc__)
  47. parser.add_argument('-v', '--verbose', action='store_true',
  48. help='Show verbose output')
  49. parser.add_argument('--llc-binary', default='llc',
  50. help='The "llc" binary to use to generate the test case')
  51. parser.add_argument(
  52. '--function', help='The function in the test file to update')
  53. parser.add_argument('tests', nargs='+')
  54. args = parser.parse_args()
  55. run_line_re = re.compile('^\s*;\s*RUN:\s*(.*)$')
  56. ir_function_re = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(')
  57. asm_function_re = re.compile(
  58. r'^_?(?P<f>[^:]+):[ \t]*#+[ \t]*@(?P=f)\n[^:]*?'
  59. r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
  60. r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
  61. flags=(re.M | re.S))
  62. check_prefix_re = re.compile('--check-prefix=(\S+)')
  63. check_re = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
  64. for test in args.tests:
  65. if args.verbose:
  66. print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
  67. with open(test) as f:
  68. test_lines = [l.rstrip() for l in f]
  69. run_lines = [m.group(1)
  70. for m in [run_line_re.match(l) for l in test_lines] if m]
  71. if args.verbose:
  72. print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
  73. for l in run_lines:
  74. print >>sys.stderr, ' RUN: ' + l
  75. checks = []
  76. for l in run_lines:
  77. (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
  78. if not llc_cmd.startswith('llc '):
  79. print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
  80. continue
  81. if not filecheck_cmd.startswith('FileCheck '):
  82. print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
  83. continue
  84. llc_cmd_args = llc_cmd[len('llc'):].strip()
  85. llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
  86. check_prefixes = [m.group(1)
  87. for m in check_prefix_re.finditer(filecheck_cmd)]
  88. if not check_prefixes:
  89. check_prefixes = ['CHECK']
  90. # FIXME: We should use multiple check prefixes to common check lines. For
  91. # now, we just ignore all but the last.
  92. checks.append((check_prefixes, llc_cmd_args))
  93. asm = {}
  94. for prefixes, _ in checks:
  95. for prefix in prefixes:
  96. asm.update({prefix: dict()})
  97. for prefixes, llc_args in checks:
  98. if args.verbose:
  99. print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
  100. print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
  101. raw_asm = llc(args, llc_args, test)
  102. # Build up a dictionary of all the function bodies.
  103. for m in asm_function_re.finditer(raw_asm):
  104. if not m:
  105. continue
  106. f = m.group('f')
  107. f_asm = scrub_asm(m.group('body'))
  108. if f.startswith('stress'):
  109. # We only use the last line of the asm for stress tests.
  110. f_asm = '\n'.join(f_asm.splitlines()[-1:])
  111. if args.verbose:
  112. print >>sys.stderr, 'Processing asm for function: ' + f
  113. for l in f_asm.splitlines():
  114. print >>sys.stderr, ' ' + l
  115. for prefix in prefixes:
  116. if f in asm[prefix] and asm[prefix][f] != f_asm:
  117. if prefix == prefixes[-1]:
  118. print >>sys.stderr, ('WARNING: Found conflicting asm under the '
  119. 'same prefix!')
  120. else:
  121. asm[prefix][f] = None
  122. continue
  123. asm[prefix][f] = f_asm
  124. is_in_function = False
  125. is_in_function_start = False
  126. prefix_set = set([prefix for prefixes, _ in checks for prefix in prefixes])
  127. if args.verbose:
  128. print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
  129. fixed_lines = []
  130. for l in test_lines:
  131. if is_in_function_start:
  132. if l.lstrip().startswith(';'):
  133. m = check_re.match(l)
  134. if not m or m.group(1) not in prefix_set:
  135. fixed_lines.append(l)
  136. continue
  137. # Print out the various check lines here
  138. printed_prefixes = []
  139. for prefixes, _ in checks:
  140. for prefix in prefixes:
  141. if prefix in printed_prefixes:
  142. break
  143. if not asm[prefix][name]:
  144. continue
  145. if len(printed_prefixes) != 0:
  146. fixed_lines.append(';')
  147. printed_prefixes.append(prefix)
  148. fixed_lines.append('; %s-LABEL: %s:' % (prefix, name))
  149. asm_lines = asm[prefix][name].splitlines()
  150. fixed_lines.append('; %s: %s' % (prefix, asm_lines[0]))
  151. for asm_line in asm_lines[1:]:
  152. fixed_lines.append('; %s-NEXT: %s' % (prefix, asm_line))
  153. break
  154. is_in_function_start = False
  155. if is_in_function:
  156. # Skip any blank comment lines in the IR.
  157. if l.strip() == ';':
  158. continue
  159. # And skip any CHECK lines. We'll build our own.
  160. m = check_re.match(l)
  161. if m and m.group(1) in prefix_set:
  162. continue
  163. # Collect the remaining lines in the function body and look for the end
  164. # of the function.
  165. fixed_lines.append(l)
  166. if l.strip() == '}':
  167. is_in_function = False
  168. continue
  169. fixed_lines.append(l)
  170. m = ir_function_re.match(l)
  171. if not m:
  172. continue
  173. name = m.group(1)
  174. if args.function is not None and name != args.function:
  175. # When filtering on a specific function, skip all others.
  176. continue
  177. is_in_function = is_in_function_start = True
  178. if args.verbose:
  179. print>>sys.stderr, 'Writing %d fixed lines to %s...' % (
  180. len(fixed_lines), test)
  181. with open(test, 'w') as f:
  182. f.writelines([l + '\n' for l in fixed_lines])
  183. if __name__ == '__main__':
  184. main()