update_mca_test_checks.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. #!/usr/bin/env python
  2. """A test case update script.
  3. This script is a utility to update LLVM 'llvm-mca' based test cases with new
  4. FileCheck patterns.
  5. """
  6. import argparse
  7. from collections import defaultdict
  8. import glob
  9. import os
  10. import sys
  11. import warnings
  12. from UpdateTestChecks import common
  13. COMMENT_CHAR = '#'
  14. ADVERT_PREFIX = '{} NOTE: Assertions have been autogenerated by '.format(
  15. COMMENT_CHAR)
  16. ADVERT = '{}utils/{}'.format(ADVERT_PREFIX, os.path.basename(__file__))
  17. class Error(Exception):
  18. """ Generic Error that can be raised without printing a traceback.
  19. """
  20. pass
  21. def _warn(msg):
  22. """ Log a user warning to stderr.
  23. """
  24. warnings.warn(msg, Warning, stacklevel=2)
  25. def _configure_warnings(args):
  26. warnings.resetwarnings()
  27. if args.w:
  28. warnings.simplefilter('ignore')
  29. if args.Werror:
  30. warnings.simplefilter('error')
  31. def _showwarning(message, category, filename, lineno, file=None, line=None):
  32. """ Version of warnings.showwarning that won't attempt to print out the
  33. line at the location of the warning if the line text is not explicitly
  34. specified.
  35. """
  36. if file is None:
  37. file = sys.stderr
  38. if line is None:
  39. line = ''
  40. file.write(warnings.formatwarning(message, category, filename, lineno, line))
  41. def _parse_args():
  42. parser = argparse.ArgumentParser(description=__doc__)
  43. parser.add_argument('-v', '--verbose',
  44. action='store_true',
  45. help='show verbose output')
  46. parser.add_argument('-w',
  47. action='store_true',
  48. help='suppress warnings')
  49. parser.add_argument('-Werror',
  50. action='store_true',
  51. help='promote warnings to errors')
  52. parser.add_argument('--llvm-mca-binary',
  53. metavar='<path>',
  54. default='llvm-mca',
  55. help='the binary to use to generate the test case '
  56. '(default: llvm-mca)')
  57. parser.add_argument('tests',
  58. metavar='<test-path>',
  59. nargs='+')
  60. args = parser.parse_args()
  61. _configure_warnings(args)
  62. if not args.llvm_mca_binary:
  63. raise Error('--llvm-mca-binary value cannot be empty string')
  64. if 'llvm-mca' not in os.path.basename(args.llvm_mca_binary):
  65. _warn('unexpected binary name: {}'.format(args.llvm_mca_binary))
  66. return args
  67. def _find_run_lines(input_lines, args):
  68. raw_lines = [m.group(1)
  69. for m in [common.RUN_LINE_RE.match(l) for l in input_lines]
  70. if m]
  71. run_lines = [raw_lines[0]] if len(raw_lines) > 0 else []
  72. for l in raw_lines[1:]:
  73. if run_lines[-1].endswith(r'\\'):
  74. run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l
  75. else:
  76. run_lines.append(l)
  77. if args.verbose:
  78. sys.stderr.write('Found {} RUN line{}:\n'.format(
  79. len(run_lines), '' if len(run_lines) == 1 else 's'))
  80. for line in run_lines:
  81. sys.stderr.write(' RUN: {}\n'.format(line))
  82. return run_lines
  83. def _get_run_infos(run_lines, args):
  84. run_infos = []
  85. for run_line in run_lines:
  86. try:
  87. (tool_cmd, filecheck_cmd) = tuple([cmd.strip()
  88. for cmd in run_line.split('|', 1)])
  89. except ValueError:
  90. _warn('could not split tool and filecheck commands: {}'.format(run_line))
  91. continue
  92. common.verify_filecheck_prefixes(filecheck_cmd)
  93. tool_basename = os.path.splitext(os.path.basename(args.llvm_mca_binary))[0]
  94. if not tool_cmd.startswith(tool_basename + ' '):
  95. _warn('skipping non-{} RUN line: {}'.format(tool_basename, run_line))
  96. continue
  97. if not filecheck_cmd.startswith('FileCheck '):
  98. _warn('skipping non-FileCheck RUN line: {}'.format(run_line))
  99. continue
  100. tool_cmd_args = tool_cmd[len(tool_basename):].strip()
  101. tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip()
  102. check_prefixes = [item
  103. for m in common.CHECK_PREFIX_RE.finditer(filecheck_cmd)
  104. for item in m.group(1).split(',')]
  105. if not check_prefixes:
  106. check_prefixes = ['CHECK']
  107. run_infos.append((check_prefixes, tool_cmd_args))
  108. return run_infos
  109. def _break_down_block(block_info, common_prefix):
  110. """ Given a block_info, see if we can analyze it further to let us break it
  111. down by prefix per-line rather than per-block.
  112. """
  113. texts = block_info.keys()
  114. prefixes = list(block_info.values())
  115. # Split the lines from each of the incoming block_texts and zip them so that
  116. # each element contains the corresponding lines from each text. E.g.
  117. #
  118. # block_text_1: A # line 1
  119. # B # line 2
  120. #
  121. # block_text_2: A # line 1
  122. # C # line 2
  123. #
  124. # would become:
  125. #
  126. # [(A, A), # line 1
  127. # (B, C)] # line 2
  128. #
  129. line_tuples = list(zip(*list((text.splitlines() for text in texts))))
  130. # To simplify output, we'll only proceed if the very first line of the block
  131. # texts is common to each of them.
  132. if len(set(line_tuples[0])) != 1:
  133. return []
  134. result = []
  135. lresult = defaultdict(list)
  136. for i, line in enumerate(line_tuples):
  137. if len(set(line)) == 1:
  138. # We're about to output a line with the common prefix. This is a sync
  139. # point so flush any batched-up lines one prefix at a time to the output
  140. # first.
  141. for prefix in sorted(lresult):
  142. result.extend(lresult[prefix])
  143. lresult = defaultdict(list)
  144. # The line is common to each block so output with the common prefix.
  145. result.append((common_prefix, line[0]))
  146. else:
  147. # The line is not common to each block, or we don't have a common prefix.
  148. # If there are no prefixes available, warn and bail out.
  149. if not prefixes[0]:
  150. _warn('multiple lines not disambiguated by prefixes:\n{}\n'
  151. 'Some blocks may be skipped entirely as a result.'.format(
  152. '\n'.join(' - {}'.format(l) for l in line)))
  153. return []
  154. # Iterate through the line from each of the blocks and add the line with
  155. # the corresponding prefix to the current batch of results so that we can
  156. # later output them per-prefix.
  157. for i, l in enumerate(line):
  158. for prefix in prefixes[i]:
  159. lresult[prefix].append((prefix, l))
  160. # Flush any remaining batched-up lines one prefix at a time to the output.
  161. for prefix in sorted(lresult):
  162. result.extend(lresult[prefix])
  163. return result
  164. def _get_useful_prefix_info(run_infos):
  165. """ Given the run_infos, calculate any prefixes that are common to every one,
  166. and the length of the longest prefix string.
  167. """
  168. try:
  169. all_sets = [set(s) for s in list(zip(*run_infos))[0]]
  170. common_to_all = set.intersection(*all_sets)
  171. longest_prefix_len = max(len(p) for p in set.union(*all_sets))
  172. except IndexError:
  173. common_to_all = []
  174. longest_prefix_len = 0
  175. else:
  176. if len(common_to_all) > 1:
  177. _warn('Multiple prefixes common to all RUN lines: {}'.format(
  178. common_to_all))
  179. if common_to_all:
  180. common_to_all = sorted(common_to_all)[0]
  181. return common_to_all, longest_prefix_len
  182. def _align_matching_blocks(all_blocks, farthest_indexes):
  183. """ Some sub-sequences of blocks may be common to multiple lists of blocks,
  184. but at different indexes in each one.
  185. For example, in the following case, A,B,E,F, and H are common to both
  186. sets, but only A and B would be identified as such due to the indexes
  187. matching:
  188. index | 0 1 2 3 4 5 6
  189. ------+--------------
  190. setA | A B C D E F H
  191. setB | A B E F G H
  192. This function attempts to align the indexes of matching blocks by
  193. inserting empty blocks into the block list. With this approach, A, B, E,
  194. F, and H would now be able to be identified as matching blocks:
  195. index | 0 1 2 3 4 5 6 7
  196. ------+----------------
  197. setA | A B C D E F H
  198. setB | A B E F G H
  199. """
  200. # "Farthest block analysis": essentially, iterate over all blocks and find
  201. # the highest index into a block list for the first instance of each block.
  202. # This is relatively expensive, but we're dealing with small numbers of
  203. # blocks so it doesn't make a perceivable difference to user time.
  204. for blocks in all_blocks.values():
  205. for block in blocks:
  206. if not block:
  207. continue
  208. index = blocks.index(block)
  209. if index > farthest_indexes[block]:
  210. farthest_indexes[block] = index
  211. # Use the results of the above analysis to identify any blocks that can be
  212. # shunted along to match the farthest index value.
  213. for blocks in all_blocks.values():
  214. for index, block in enumerate(blocks):
  215. if not block:
  216. continue
  217. changed = False
  218. # If the block has not already been subject to alignment (i.e. if the
  219. # previous block is not empty) then insert empty blocks until the index
  220. # matches the farthest index identified for that block.
  221. if (index > 0) and blocks[index - 1]:
  222. while(index < farthest_indexes[block]):
  223. blocks.insert(index, '')
  224. index += 1
  225. changed = True
  226. if changed:
  227. # Bail out. We'll need to re-do the farthest block analysis now that
  228. # we've inserted some blocks.
  229. return True
  230. return False
  231. def _get_block_infos(run_infos, test_path, args, common_prefix): # noqa
  232. """ For each run line, run the tool with the specified args and collect the
  233. output. We use the concept of 'blocks' for uniquing, where a block is
  234. a series of lines of text with no more than one newline character between
  235. each one. For example:
  236. This
  237. is
  238. one
  239. block
  240. This is
  241. another block
  242. This is yet another block
  243. We then build up a 'block_infos' structure containing a dict where the
  244. text of each block is the key and a list of the sets of prefixes that may
  245. generate that particular block. This then goes through a series of
  246. transformations to minimise the amount of CHECK lines that need to be
  247. written by taking advantage of common prefixes.
  248. """
  249. def _block_key(tool_args, prefixes):
  250. """ Get a hashable key based on the current tool_args and prefixes.
  251. """
  252. return ' '.join([tool_args] + prefixes)
  253. all_blocks = {}
  254. max_block_len = 0
  255. # A cache of the furthest-back position in any block list of the first
  256. # instance of each block, indexed by the block itself.
  257. farthest_indexes = defaultdict(int)
  258. # Run the tool for each run line to generate all of the blocks.
  259. for prefixes, tool_args in run_infos:
  260. key = _block_key(tool_args, prefixes)
  261. raw_tool_output = common.invoke_tool(args.llvm_mca_binary,
  262. tool_args,
  263. test_path)
  264. # Replace any lines consisting of purely whitespace with empty lines.
  265. raw_tool_output = '\n'.join(line if line.strip() else ''
  266. for line in raw_tool_output.splitlines())
  267. # Split blocks, stripping all trailing whitespace, but keeping preceding
  268. # whitespace except for newlines so that columns will line up visually.
  269. all_blocks[key] = [b.lstrip('\n').rstrip()
  270. for b in raw_tool_output.split('\n\n')]
  271. max_block_len = max(max_block_len, len(all_blocks[key]))
  272. # Attempt to align matching blocks until no more changes can be made.
  273. made_changes = True
  274. while made_changes:
  275. made_changes = _align_matching_blocks(all_blocks, farthest_indexes)
  276. # If necessary, pad the lists of blocks with empty blocks so that they are
  277. # all the same length.
  278. for key in all_blocks:
  279. len_to_pad = max_block_len - len(all_blocks[key])
  280. all_blocks[key] += [''] * len_to_pad
  281. # Create the block_infos structure where it is a nested dict in the form of:
  282. # block number -> block text -> list of prefix sets
  283. block_infos = defaultdict(lambda: defaultdict(list))
  284. for prefixes, tool_args in run_infos:
  285. key = _block_key(tool_args, prefixes)
  286. for block_num, block_text in enumerate(all_blocks[key]):
  287. block_infos[block_num][block_text].append(set(prefixes))
  288. # Now go through the block_infos structure and attempt to smartly prune the
  289. # number of prefixes per block to the minimal set possible to output.
  290. for block_num in range(len(block_infos)):
  291. # When there are multiple block texts for a block num, remove any
  292. # prefixes that are common to more than one of them.
  293. # E.g. [ [{ALL,FOO}] , [{ALL,BAR}] ] -> [ [{FOO}] , [{BAR}] ]
  294. all_sets = [s for s in block_infos[block_num].values()]
  295. pruned_sets = []
  296. for i, setlist in enumerate(all_sets):
  297. other_set_values = set([elem for j, setlist2 in enumerate(all_sets)
  298. for set_ in setlist2 for elem in set_
  299. if i != j])
  300. pruned_sets.append([s - other_set_values for s in setlist])
  301. for i, block_text in enumerate(block_infos[block_num]):
  302. # When a block text matches multiple sets of prefixes, try removing any
  303. # prefixes that aren't common to all of them.
  304. # E.g. [ {ALL,FOO} , {ALL,BAR} ] -> [{ALL}]
  305. common_values = set.intersection(*pruned_sets[i])
  306. if common_values:
  307. pruned_sets[i] = [common_values]
  308. # Everything should be uniqued as much as possible by now. Apply the
  309. # newly pruned sets to the block_infos structure.
  310. # If there are any blocks of text that still match multiple prefixes,
  311. # output a warning.
  312. current_set = set()
  313. for s in pruned_sets[i]:
  314. s = sorted(list(s))
  315. if s:
  316. current_set.add(s[0])
  317. if len(s) > 1:
  318. _warn('Multiple prefixes generating same output: {} '
  319. '(discarding {})'.format(','.join(s), ','.join(s[1:])))
  320. if block_text and not current_set:
  321. raise Error(
  322. 'block not captured by existing prefixes:\n\n{}'.format(block_text))
  323. block_infos[block_num][block_text] = sorted(list(current_set))
  324. # If we have multiple block_texts, try to break them down further to avoid
  325. # the case where we have very similar block_texts repeated after each
  326. # other.
  327. if common_prefix and len(block_infos[block_num]) > 1:
  328. # We'll only attempt this if each of the block_texts have the same number
  329. # of lines as each other.
  330. same_num_Lines = (len(set(len(k.splitlines())
  331. for k in block_infos[block_num].keys())) == 1)
  332. if same_num_Lines:
  333. breakdown = _break_down_block(block_infos[block_num], common_prefix)
  334. if breakdown:
  335. block_infos[block_num] = breakdown
  336. return block_infos
  337. def _write_block(output, block, not_prefix_set, common_prefix, prefix_pad):
  338. """ Write an individual block, with correct padding on the prefixes.
  339. Returns a set of all of the prefixes that it has written.
  340. """
  341. end_prefix = ': '
  342. previous_prefix = None
  343. num_lines_of_prefix = 0
  344. written_prefixes = set()
  345. for prefix, line in block:
  346. if prefix in not_prefix_set:
  347. _warn('not writing for prefix {0} due to presence of "{0}-NOT:" '
  348. 'in input file.'.format(prefix))
  349. continue
  350. # If the previous line isn't already blank and we're writing more than one
  351. # line for the current prefix output a blank line first, unless either the
  352. # current of previous prefix is common to all.
  353. num_lines_of_prefix += 1
  354. if prefix != previous_prefix:
  355. if output and output[-1]:
  356. if num_lines_of_prefix > 1 or any(p == common_prefix
  357. for p in (prefix, previous_prefix)):
  358. output.append('')
  359. num_lines_of_prefix = 0
  360. previous_prefix = prefix
  361. written_prefixes.add(prefix)
  362. output.append(
  363. '{} {}{}{} {}'.format(COMMENT_CHAR,
  364. prefix,
  365. end_prefix,
  366. ' ' * (prefix_pad - len(prefix)),
  367. line).rstrip())
  368. end_prefix = '-NEXT:'
  369. output.append('')
  370. return written_prefixes
  371. def _write_output(test_path, input_lines, prefix_list, block_infos, # noqa
  372. args, common_prefix, prefix_pad):
  373. prefix_set = set([prefix for prefixes, _ in prefix_list
  374. for prefix in prefixes])
  375. not_prefix_set = set()
  376. output_lines = []
  377. for input_line in input_lines:
  378. if input_line.startswith(ADVERT_PREFIX):
  379. continue
  380. if input_line.startswith(COMMENT_CHAR):
  381. m = common.CHECK_RE.match(input_line)
  382. try:
  383. prefix = m.group(1)
  384. except AttributeError:
  385. prefix = None
  386. if '{}-NOT:'.format(prefix) in input_line:
  387. not_prefix_set.add(prefix)
  388. if prefix not in prefix_set or prefix in not_prefix_set:
  389. output_lines.append(input_line)
  390. continue
  391. if common.should_add_line_to_output(input_line, prefix_set):
  392. # This input line of the function body will go as-is into the output.
  393. # Except make leading whitespace uniform: 2 spaces.
  394. input_line = common.SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line)
  395. # Skip empty lines if the previous output line is also empty.
  396. if input_line or output_lines[-1]:
  397. output_lines.append(input_line)
  398. else:
  399. continue
  400. # Add a blank line before the new checks if required.
  401. if len(output_lines) > 0 and output_lines[-1]:
  402. output_lines.append('')
  403. output_check_lines = []
  404. used_prefixes = set()
  405. for block_num in range(len(block_infos)):
  406. if type(block_infos[block_num]) is list:
  407. # The block is of the type output from _break_down_block().
  408. used_prefixes |= _write_block(output_check_lines,
  409. block_infos[block_num],
  410. not_prefix_set,
  411. common_prefix,
  412. prefix_pad)
  413. else:
  414. # _break_down_block() was unable to do do anything so output the block
  415. # as-is.
  416. # Rather than writing out each block as soon we encounter it, save it
  417. # indexed by prefix so that we can write all of the blocks out sorted by
  418. # prefix at the end.
  419. output_blocks = defaultdict(list)
  420. for block_text in sorted(block_infos[block_num]):
  421. if not block_text:
  422. continue
  423. lines = block_text.split('\n')
  424. for prefix in block_infos[block_num][block_text]:
  425. assert prefix not in output_blocks
  426. used_prefixes |= _write_block(output_blocks[prefix],
  427. [(prefix, line) for line in lines],
  428. not_prefix_set,
  429. common_prefix,
  430. prefix_pad)
  431. for prefix in sorted(output_blocks):
  432. output_check_lines.extend(output_blocks[prefix])
  433. unused_prefixes = (prefix_set - not_prefix_set) - used_prefixes
  434. if unused_prefixes:
  435. raise Error('unused prefixes: {}'.format(sorted(unused_prefixes)))
  436. if output_check_lines:
  437. output_lines.insert(0, ADVERT)
  438. output_lines.extend(output_check_lines)
  439. # The file should not end with two newlines. It creates unnecessary churn.
  440. while len(output_lines) > 0 and output_lines[-1] == '':
  441. output_lines.pop()
  442. if input_lines == output_lines:
  443. sys.stderr.write(' [unchanged]\n')
  444. return
  445. sys.stderr.write(' [{} lines total]\n'.format(len(output_lines)))
  446. if args.verbose:
  447. sys.stderr.write(
  448. 'Writing {} lines to {}...\n\n'.format(len(output_lines), test_path))
  449. with open(test_path, 'wb') as f:
  450. f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines])
  451. def main():
  452. args = _parse_args()
  453. test_paths = [test for pattern in args.tests for test in glob.glob(pattern)]
  454. for test_path in test_paths:
  455. sys.stderr.write('Test: {}\n'.format(test_path))
  456. # Call this per test. By default each warning will only be written once
  457. # per source location. Reset the warning filter so that now each warning
  458. # will be written once per source location per test.
  459. _configure_warnings(args)
  460. if args.verbose:
  461. sys.stderr.write(
  462. 'Scanning for RUN lines in test file: {}\n'.format(test_path))
  463. if not os.path.isfile(test_path):
  464. raise Error('could not find test file: {}'.format(test_path))
  465. with open(test_path) as f:
  466. input_lines = [l.rstrip() for l in f]
  467. run_lines = _find_run_lines(input_lines, args)
  468. run_infos = _get_run_infos(run_lines, args)
  469. common_prefix, prefix_pad = _get_useful_prefix_info(run_infos)
  470. block_infos = _get_block_infos(run_infos, test_path, args, common_prefix)
  471. _write_output(test_path,
  472. input_lines,
  473. run_infos,
  474. block_infos,
  475. args,
  476. common_prefix,
  477. prefix_pad)
  478. return 0
  479. if __name__ == '__main__':
  480. try:
  481. warnings.showwarning = _showwarning
  482. sys.exit(main())
  483. except Error as e:
  484. sys.stdout.write('error: {}\n'.format(e))
  485. sys.exit(1)