update_mca_test_checks.py 21 KB

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