update_mir_test_checks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  1. #!/usr/bin/env python
  2. """Updates FileCheck checks in MIR tests.
  3. This script is a utility to update MIR based tests with new FileCheck
  4. patterns.
  5. The checks added by this script will cover the entire body of each
  6. function it handles. Virtual registers used are given names via
  7. FileCheck patterns, so if you do want to check a subset of the body it
  8. should be straightforward to trim out the irrelevant parts. None of
  9. the YAML metadata will be checked, other than function names.
  10. If there are multiple llc commands in a test, the full set of checks
  11. will be repeated for each different check pattern. Checks for patterns
  12. that are common between different commands will be left as-is by
  13. default, or removed if the --remove-common-prefixes flag is provided.
  14. """
  15. from __future__ import print_function
  16. import argparse
  17. import collections
  18. import glob
  19. import os
  20. import re
  21. import subprocess
  22. import sys
  23. from UpdateTestChecks import common
  24. MIR_FUNC_NAME_RE = re.compile(r' *name: *(?P<func>[A-Za-z0-9_.-]+)')
  25. MIR_BODY_BEGIN_RE = re.compile(r' *body: *\|')
  26. MIR_BASIC_BLOCK_RE = re.compile(r' *bb\.[0-9]+.*:$')
  27. VREG_RE = re.compile(r'(%[0-9]+)(?::[a-z0-9_]+)?(?:\([<>a-z0-9 ]+\))?')
  28. VREG_DEF_RE = re.compile(
  29. r'^ *(?P<vregs>{0}(?:, {0})*) '
  30. r'= (?P<opcode>[A-Zt][A-Za-z0-9_]+)'.format(VREG_RE.pattern))
  31. MIR_PREFIX_DATA_RE = re.compile(r'^ *(;|bb.[0-9].*: *$|[a-z]+:( |$)|$)')
  32. IR_FUNC_NAME_RE = re.compile(
  33. r'^\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[A-Za-z0-9_.]+)\s*\(')
  34. IR_PREFIX_DATA_RE = re.compile(r'^ *(;|$)')
  35. MIR_FUNC_RE = re.compile(
  36. r'^---$'
  37. r'\n'
  38. r'^ *name: *(?P<func>[A-Za-z0-9_.-]+)$'
  39. r'.*?'
  40. r'^ *body: *\|\n'
  41. r'(?P<body>.*?)\n'
  42. r'^\.\.\.$',
  43. flags=(re.M | re.S))
  44. class LLC:
  45. def __init__(self, bin):
  46. self.bin = bin
  47. def __call__(self, args, ir):
  48. if ir.endswith('.mir'):
  49. args = '{} -x mir'.format(args)
  50. with open(ir) as ir_file:
  51. stdout = subprocess.check_output('{} {}'.format(self.bin, args),
  52. shell=True, stdin=ir_file)
  53. if sys.version_info[0] > 2:
  54. stdout = stdout.decode()
  55. # Fix line endings to unix CR style.
  56. stdout = stdout.replace('\r\n', '\n')
  57. return stdout
  58. class Run:
  59. def __init__(self, prefixes, cmd_args, triple):
  60. self.prefixes = prefixes
  61. self.cmd_args = cmd_args
  62. self.triple = triple
  63. def __getitem__(self, index):
  64. return [self.prefixes, self.cmd_args, self.triple][index]
  65. def log(msg, verbose=True):
  66. if verbose:
  67. print(msg, file=sys.stderr)
  68. def find_triple_in_ir(lines, verbose=False):
  69. for l in lines:
  70. m = common.TRIPLE_IR_RE.match(l)
  71. if m:
  72. return m.group(1)
  73. return None
  74. def find_run_lines(test, lines, verbose=False):
  75. raw_lines = [m.group(1)
  76. for m in [common.RUN_LINE_RE.match(l) for l in lines] if m]
  77. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  78. for l in raw_lines[1:]:
  79. if run_lines[-1].endswith("\\"):
  80. run_lines[-1] = run_lines[-1].rstrip("\\") + " " + l
  81. else:
  82. run_lines.append(l)
  83. if verbose:
  84. log('Found {} RUN lines:'.format(len(run_lines)))
  85. for l in run_lines:
  86. log(' RUN: {}'.format(l))
  87. return run_lines
  88. def build_run_list(test, run_lines, verbose=False):
  89. run_list = []
  90. all_prefixes = []
  91. for l in run_lines:
  92. if '|' not in l:
  93. common.warn('Skipping unparseable RUN line: ' + l)
  94. continue
  95. commands = [cmd.strip() for cmd in l.split('|', 1)]
  96. llc_cmd = commands[0]
  97. filecheck_cmd = commands[1] if len(commands) > 1 else ''
  98. common.verify_filecheck_prefixes(filecheck_cmd)
  99. if not llc_cmd.startswith('llc '):
  100. common.warn('Skipping non-llc RUN line: {}'.format(l), test_file=test)
  101. continue
  102. if not filecheck_cmd.startswith('FileCheck '):
  103. common.warn('Skipping non-FileChecked RUN line: {}'.format(l),
  104. test_file=test)
  105. continue
  106. triple = None
  107. m = common.TRIPLE_ARG_RE.search(llc_cmd)
  108. if m:
  109. triple = m.group(1)
  110. # If we find -march but not -mtriple, use that.
  111. m = common.MARCH_ARG_RE.search(llc_cmd)
  112. if m and not triple:
  113. triple = '{}--'.format(m.group(1))
  114. cmd_args = llc_cmd[len('llc'):].strip()
  115. cmd_args = cmd_args.replace('< %s', '').replace('%s', '').strip()
  116. check_prefixes = [
  117. item
  118. for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  119. for item in m.group(1).split(',')]
  120. if not check_prefixes:
  121. check_prefixes = ['CHECK']
  122. all_prefixes += check_prefixes
  123. run_list.append(Run(check_prefixes, cmd_args, triple))
  124. # Remove any common prefixes. We'll just leave those entirely alone.
  125. common_prefixes = set([prefix for prefix in all_prefixes
  126. if all_prefixes.count(prefix) > 1])
  127. for run in run_list:
  128. run.prefixes = [p for p in run.prefixes if p not in common_prefixes]
  129. return run_list, common_prefixes
  130. def find_functions_with_one_bb(lines, verbose=False):
  131. result = []
  132. cur_func = None
  133. bbs = 0
  134. for line in lines:
  135. m = MIR_FUNC_NAME_RE.match(line)
  136. if m:
  137. if bbs == 1:
  138. result.append(cur_func)
  139. cur_func = m.group('func')
  140. bbs = 0
  141. m = MIR_BASIC_BLOCK_RE.match(line)
  142. if m:
  143. bbs += 1
  144. if bbs == 1:
  145. result.append(cur_func)
  146. return result
  147. def build_function_body_dictionary(test, raw_tool_output, triple, prefixes,
  148. func_dict, verbose):
  149. for m in MIR_FUNC_RE.finditer(raw_tool_output):
  150. func = m.group('func')
  151. body = m.group('body')
  152. if verbose:
  153. log('Processing function: {}'.format(func))
  154. for l in body.splitlines():
  155. log(' {}'.format(l))
  156. for prefix in prefixes:
  157. if func in func_dict[prefix] and func_dict[prefix][func] != body:
  158. common.warn('Found conflicting asm for prefix: {}'.format(prefix),
  159. test_file=test)
  160. func_dict[prefix][func] = body
  161. def add_checks_for_function(test, output_lines, run_list, func_dict, func_name,
  162. single_bb, verbose=False):
  163. printed_prefixes = set()
  164. for run in run_list:
  165. for prefix in run.prefixes:
  166. if prefix in printed_prefixes:
  167. continue
  168. if not func_dict[prefix][func_name]:
  169. continue
  170. # if printed_prefixes:
  171. # # Add some space between different check prefixes.
  172. # output_lines.append('')
  173. printed_prefixes.add(prefix)
  174. log('Adding {} lines for {}'.format(prefix, func_name), verbose)
  175. add_check_lines(test, output_lines, prefix, func_name, single_bb,
  176. func_dict[prefix][func_name].splitlines())
  177. break
  178. return output_lines
  179. def add_check_lines(test, output_lines, prefix, func_name, single_bb,
  180. func_body):
  181. if single_bb:
  182. # Don't bother checking the basic block label for a single BB
  183. func_body.pop(0)
  184. if not func_body:
  185. common.warn('Function has no instructions to check: {}'.format(func_name),
  186. test_file=test)
  187. return
  188. first_line = func_body[0]
  189. indent = len(first_line) - len(first_line.lstrip(' '))
  190. # A check comment, indented the appropriate amount
  191. check = '{:>{}}; {}'.format('', indent, prefix)
  192. output_lines.append('{}-LABEL: name: {}'.format(check, func_name))
  193. vreg_map = {}
  194. for func_line in func_body:
  195. if not func_line.strip():
  196. continue
  197. m = VREG_DEF_RE.match(func_line)
  198. if m:
  199. for vreg in VREG_RE.finditer(m.group('vregs')):
  200. name = mangle_vreg(m.group('opcode'), vreg_map.values())
  201. vreg_map[vreg.group(1)] = name
  202. func_line = func_line.replace(
  203. vreg.group(1), '[[{}:%[0-9]+]]'.format(name), 1)
  204. for number, name in vreg_map.items():
  205. func_line = re.sub(r'{}\b'.format(number), '[[{}]]'.format(name),
  206. func_line)
  207. check_line = '{}: {}'.format(check, func_line[indent:]).rstrip()
  208. output_lines.append(check_line)
  209. def mangle_vreg(opcode, current_names):
  210. base = opcode
  211. # Simplify some common prefixes and suffixes
  212. if opcode.startswith('G_'):
  213. base = base[len('G_'):]
  214. if opcode.endswith('_PSEUDO'):
  215. base = base[:len('_PSEUDO')]
  216. # Shorten some common opcodes with long-ish names
  217. base = dict(IMPLICIT_DEF='DEF',
  218. GLOBAL_VALUE='GV',
  219. CONSTANT='C',
  220. FCONSTANT='C',
  221. MERGE_VALUES='MV',
  222. UNMERGE_VALUES='UV',
  223. INTRINSIC='INT',
  224. INTRINSIC_W_SIDE_EFFECTS='INT',
  225. INSERT_VECTOR_ELT='IVEC',
  226. EXTRACT_VECTOR_ELT='EVEC',
  227. SHUFFLE_VECTOR='SHUF').get(base, base)
  228. # Avoid ambiguity when opcodes end in numbers
  229. if len(base.rstrip('0123456789')) < len(base):
  230. base += '_'
  231. i = 0
  232. for name in current_names:
  233. if name.rstrip('0123456789') == base:
  234. i += 1
  235. if i:
  236. return '{}{}'.format(base, i)
  237. return base
  238. def should_add_line_to_output(input_line, prefix_set):
  239. # Skip any check lines that we're handling.
  240. m = common.CHECK_RE.match(input_line)
  241. if m and m.group(1) in prefix_set:
  242. return False
  243. return True
  244. def update_test_file(args, test):
  245. log('Scanning for RUN lines in test file: {}'.format(test), args.verbose)
  246. with open(test) as fd:
  247. input_lines = [l.rstrip() for l in fd]
  248. script_name = os.path.basename(__file__)
  249. first_line = input_lines[0] if input_lines else ""
  250. if 'autogenerated' in first_line and script_name not in first_line:
  251. common.warn("Skipping test which wasn't autogenerated by " +
  252. script_name + ": " + test)
  253. return
  254. if args.update_only:
  255. if not first_line or 'autogenerated' not in first_line:
  256. common.warn("Skipping test which isn't autogenerated: " + test)
  257. return
  258. triple_in_ir = find_triple_in_ir(input_lines, args.verbose)
  259. run_lines = find_run_lines(test, input_lines, args.verbose)
  260. run_list, common_prefixes = build_run_list(test, run_lines, args.verbose)
  261. simple_functions = find_functions_with_one_bb(input_lines, args.verbose)
  262. func_dict = {}
  263. for run in run_list:
  264. for prefix in run.prefixes:
  265. func_dict.update({prefix: dict()})
  266. for prefixes, llc_args, triple_in_cmd in run_list:
  267. log('Extracted LLC cmd: llc {}'.format(llc_args), args.verbose)
  268. log('Extracted FileCheck prefixes: {}'.format(prefixes), args.verbose)
  269. raw_tool_output = args.llc(llc_args, test)
  270. if not triple_in_cmd and not triple_in_ir:
  271. common.warn('No triple found: skipping file', test_file=test)
  272. return
  273. build_function_body_dictionary(test, raw_tool_output,
  274. triple_in_cmd or triple_in_ir,
  275. prefixes, func_dict, args.verbose)
  276. state = 'toplevel'
  277. func_name = None
  278. prefix_set = set([prefix for run in run_list for prefix in run.prefixes])
  279. log('Rewriting FileCheck prefixes: {}'.format(prefix_set), args.verbose)
  280. if args.remove_common_prefixes:
  281. prefix_set.update(common_prefixes)
  282. elif common_prefixes:
  283. common.warn('Ignoring common prefixes: {}'.format(common_prefixes),
  284. test_file=test)
  285. comment_char = '#' if test.endswith('.mir') else ';'
  286. autogenerated_note = ('{} NOTE: Assertions have been autogenerated by '
  287. 'utils/{}'.format(comment_char, script_name))
  288. output_lines = []
  289. output_lines.append(autogenerated_note)
  290. for input_line in input_lines:
  291. if input_line == autogenerated_note:
  292. continue
  293. if state == 'toplevel':
  294. m = IR_FUNC_NAME_RE.match(input_line)
  295. if m:
  296. state = 'ir function prefix'
  297. func_name = m.group('func')
  298. if input_line.rstrip('| \r\n') == '---':
  299. state = 'document'
  300. output_lines.append(input_line)
  301. elif state == 'document':
  302. m = MIR_FUNC_NAME_RE.match(input_line)
  303. if m:
  304. state = 'mir function metadata'
  305. func_name = m.group('func')
  306. if input_line.strip() == '...':
  307. state = 'toplevel'
  308. func_name = None
  309. if should_add_line_to_output(input_line, prefix_set):
  310. output_lines.append(input_line)
  311. elif state == 'mir function metadata':
  312. if should_add_line_to_output(input_line, prefix_set):
  313. output_lines.append(input_line)
  314. m = MIR_BODY_BEGIN_RE.match(input_line)
  315. if m:
  316. if func_name in simple_functions:
  317. # If there's only one block, put the checks inside it
  318. state = 'mir function prefix'
  319. continue
  320. state = 'mir function body'
  321. add_checks_for_function(test, output_lines, run_list,
  322. func_dict, func_name, single_bb=False,
  323. verbose=args.verbose)
  324. elif state == 'mir function prefix':
  325. m = MIR_PREFIX_DATA_RE.match(input_line)
  326. if not m:
  327. state = 'mir function body'
  328. add_checks_for_function(test, output_lines, run_list,
  329. func_dict, func_name, single_bb=True,
  330. verbose=args.verbose)
  331. if should_add_line_to_output(input_line, prefix_set):
  332. output_lines.append(input_line)
  333. elif state == 'mir function body':
  334. if input_line.strip() == '...':
  335. state = 'toplevel'
  336. func_name = None
  337. if should_add_line_to_output(input_line, prefix_set):
  338. output_lines.append(input_line)
  339. elif state == 'ir function prefix':
  340. m = IR_PREFIX_DATA_RE.match(input_line)
  341. if not m:
  342. state = 'ir function body'
  343. add_checks_for_function(test, output_lines, run_list,
  344. func_dict, func_name, single_bb=False,
  345. verbose=args.verbose)
  346. if should_add_line_to_output(input_line, prefix_set):
  347. output_lines.append(input_line)
  348. elif state == 'ir function body':
  349. if input_line.strip() == '}':
  350. state = 'toplevel'
  351. func_name = None
  352. if should_add_line_to_output(input_line, prefix_set):
  353. output_lines.append(input_line)
  354. log('Writing {} lines to {}...'.format(len(output_lines), test), args.verbose)
  355. with open(test, 'wb') as fd:
  356. fd.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])
  357. def main():
  358. parser = argparse.ArgumentParser(
  359. description=__doc__, formatter_class=argparse.RawTextHelpFormatter)
  360. parser.add_argument('-v', '--verbose', action='store_true',
  361. help='Show verbose output')
  362. parser.add_argument('--llc-binary', dest='llc', default='llc', type=LLC,
  363. help='The "llc" binary to generate the test case with')
  364. parser.add_argument('--remove-common-prefixes', action='store_true',
  365. help='Remove existing check lines whose prefixes are '
  366. 'shared between multiple commands')
  367. parser.add_argument('-u', '--update-only', action='store_true',
  368. help='Only update test if it was already autogened')
  369. parser.add_argument('tests', nargs='+')
  370. args = parser.parse_args()
  371. test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
  372. for test in test_paths:
  373. try:
  374. update_test_file(args, test)
  375. except Exception:
  376. common.warn('Error processing file', test_file=test)
  377. raise
  378. if __name__ == '__main__':
  379. main()