1#!/usr/bin/env python3 2 3"""A script to generate FileCheck statements for 'opt' regression tests. 4 5This script is a utility to update LLVM opt test cases with new 6FileCheck patterns. It can either update all of the tests in the file or 7a single test function. 8 9Example usage: 10 11# Default to using `opt` as found in your PATH. 12$ update_test_checks.py test/foo.ll 13 14# Override the path lookup. 15$ update_test_checks.py --tool-binary=../bin/opt test/foo.ll 16 17# Use a custom tool instead of `opt`. 18$ update_test_checks.py --tool=yourtool test/foo.ll 19 20Workflow: 211. Make a compiler patch that requires updating some number of FileCheck lines 22 in regression test files. 232. Save the patch and revert it from your local work area. 243. Update the RUN-lines in the affected regression tests to look canonical. 25 Example: "; RUN: opt < %s -instcombine -S | FileCheck %s" 264. Refresh the FileCheck lines for either the entire file or select functions by 27 running this script. 285. Commit the fresh baseline of checks. 296. Apply your patch from step 1 and rebuild your local binaries. 307. Re-run this script on affected regression tests. 318. Check the diffs to ensure the script has done something reasonable. 329. Submit a patch including the regression test diffs for review. 33""" 34 35from __future__ import print_function 36 37import argparse 38import os # Used to advertise this file's name ("autogenerated_note"). 39import re 40import sys 41 42from UpdateTestChecks import common 43 44 45def main(): 46 from argparse import RawTextHelpFormatter 47 parser = argparse.ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter) 48 parser.add_argument('--tool', default='opt', 49 help='The name of the tool used to generate the test case (defaults to "opt")') 50 parser.add_argument('--tool-binary', '--opt-binary', 51 help='The tool binary used to generate the test case') 52 parser.add_argument( 53 '--function', help='The function in the test file to update') 54 parser.add_argument('-p', '--preserve-names', action='store_true', 55 help='Do not scrub IR names') 56 parser.add_argument('--function-signature', action='store_true', 57 help='Keep function signature information around for the check line') 58 parser.add_argument('--scrub-attributes', action='store_true', 59 help='Remove attribute annotations (#0) from the end of check line') 60 parser.add_argument('--check-attributes', action='store_true', 61 help='Check "Function Attributes" for functions') 62 parser.add_argument('--check-globals', action='store_true', 63 help='Check global entries (global variables, metadata, attribute sets, ...) for functions') 64 parser.add_argument('tests', nargs='+') 65 initial_args = common.parse_commandline_args(parser) 66 67 script_name = os.path.basename(__file__) 68 69 if initial_args.tool_binary: 70 tool_basename = os.path.basename(initial_args.tool_binary) 71 if not re.match(r'^%s(-\d+)?(\.exe)?$' % (initial_args.tool), tool_basename): 72 common.error('Unexpected tool name: ' + tool_basename) 73 sys.exit(1) 74 tool_basename = initial_args.tool 75 76 for ti in common.itertests(initial_args.tests, parser, 77 script_name='utils/' + script_name): 78 # If requested we scrub trailing attribute annotations, e.g., '#0', together with whitespaces 79 if ti.args.scrub_attributes: 80 common.SCRUB_TRAILING_WHITESPACE_TEST_RE = common.SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE 81 else: 82 common.SCRUB_TRAILING_WHITESPACE_TEST_RE = common.SCRUB_TRAILING_WHITESPACE_RE 83 84 prefix_list = [] 85 for l in ti.run_lines: 86 if '|' not in l: 87 common.warn('Skipping unparsable RUN line: ' + l) 88 continue 89 90 commands = [cmd.strip() for cmd in l.split('|')] 91 assert len(commands) >= 2 92 preprocess_cmd = None 93 if len(commands) > 2: 94 preprocess_cmd = " | ".join(commands[:-2]) 95 tool_cmd = commands[-2] 96 filecheck_cmd = commands[-1] 97 common.verify_filecheck_prefixes(filecheck_cmd) 98 if not tool_cmd.startswith(tool_basename + ' '): 99 common.warn('Skipping non-%s RUN line: %s' % (tool_basename, l)) 100 continue 101 102 if not filecheck_cmd.startswith('FileCheck '): 103 common.warn('Skipping non-FileChecked RUN line: ' + l) 104 continue 105 106 tool_cmd_args = tool_cmd[len(tool_basename):].strip() 107 tool_cmd_args = tool_cmd_args.replace('< %s', '').replace('%s', '').strip() 108 109 check_prefixes = [item for m in 110 common.CHECK_PREFIX_RE.finditer(filecheck_cmd) 111 for item in m.group(1).split(',')] 112 if not check_prefixes: 113 check_prefixes = ['CHECK'] 114 115 # FIXME: We should use multiple check prefixes to common check lines. For 116 # now, we just ignore all but the last. 117 prefix_list.append((check_prefixes, tool_cmd_args, preprocess_cmd)) 118 119 global_vars_seen_dict = {} 120 builder = common.FunctionTestBuilder( 121 run_list=prefix_list, 122 flags=ti.args, 123 scrubber_args=[], 124 path=ti.path) 125 126 tool_binary = ti.args.tool_binary 127 if not tool_binary: 128 tool_binary = tool_basename 129 130 for prefixes, tool_args, preprocess_cmd in prefix_list: 131 common.debug('Extracted tool cmd: ' + tool_basename + ' ' + tool_args) 132 common.debug('Extracted FileCheck prefixes: ' + str(prefixes)) 133 134 raw_tool_output = common.invoke_tool(tool_binary, tool_args, 135 ti.path, preprocess_cmd=preprocess_cmd, 136 verbose=ti.args.verbose) 137 builder.process_run_line(common.OPT_FUNCTION_RE, common.scrub_body, 138 raw_tool_output, prefixes, False) 139 builder.processed_prefixes(prefixes) 140 141 func_dict = builder.finish_and_get_func_dict() 142 is_in_function = False 143 is_in_function_start = False 144 has_checked_pre_function_globals = False 145 prefix_set = set([prefix for prefixes, _, _ in prefix_list for prefix in prefixes]) 146 common.debug('Rewriting FileCheck prefixes:', str(prefix_set)) 147 output_lines = [] 148 149 include_generated_funcs = common.find_arg_in_test(ti, 150 lambda args: ti.args.include_generated_funcs, 151 '--include-generated-funcs', 152 True) 153 generated_prefixes = [] 154 if include_generated_funcs: 155 # Generate the appropriate checks for each function. We need to emit 156 # these in the order according to the generated output so that CHECK-LABEL 157 # works properly. func_order provides that. 158 159 # We can't predict where various passes might insert functions so we can't 160 # be sure the input function order is maintained. Therefore, first spit 161 # out all the source lines. 162 common.dump_input_lines(output_lines, ti, prefix_set, ';') 163 164 args = ti.args 165 if args.check_globals: 166 generated_prefixes.extend( 167 common.add_global_checks(builder.global_var_dict(), ';', 168 prefix_list, output_lines, 169 global_vars_seen_dict, args.preserve_names, 170 True)) 171 172 # Now generate all the checks. 173 generated_prefixes.extend( 174 common.add_checks_at_end( 175 output_lines, prefix_list, builder.func_order(), ';', 176 lambda my_output_lines, prefixes, func: common.add_ir_checks( 177 my_output_lines, 178 ';', 179 prefixes, 180 func_dict, 181 func, 182 False, 183 args.function_signature, 184 global_vars_seen_dict, 185 is_filtered=builder.is_filtered()))) 186 else: 187 # "Normal" mode. 188 for input_line_info in ti.iterlines(output_lines): 189 input_line = input_line_info.line 190 args = input_line_info.args 191 if is_in_function_start: 192 if input_line == '': 193 continue 194 if input_line.lstrip().startswith(';'): 195 m = common.CHECK_RE.match(input_line) 196 if not m or m.group(1) not in prefix_set: 197 output_lines.append(input_line) 198 continue 199 200 # Print out the various check lines here. 201 generated_prefixes.extend( 202 common.add_ir_checks( 203 output_lines, 204 ';', 205 prefix_list, 206 func_dict, 207 func_name, 208 args.preserve_names, 209 args.function_signature, 210 global_vars_seen_dict, 211 is_filtered=builder.is_filtered())) 212 is_in_function_start = False 213 214 m = common.IR_FUNCTION_RE.match(input_line) 215 if m and not has_checked_pre_function_globals: 216 if args.check_globals: 217 generated_prefixes.extend( 218 common.add_global_checks(builder.global_var_dict(), ';', 219 prefix_list, output_lines, 220 global_vars_seen_dict, 221 args.preserve_names, True)) 222 has_checked_pre_function_globals = True 223 224 if common.should_add_line_to_output(input_line, prefix_set, not is_in_function): 225 # This input line of the function body will go as-is into the output. 226 # Except make leading whitespace uniform: 2 spaces. 227 input_line = common.SCRUB_LEADING_WHITESPACE_RE.sub(r' ', input_line) 228 output_lines.append(input_line) 229 if input_line.strip() == '}': 230 is_in_function = False 231 continue 232 233 if is_in_function: 234 continue 235 236 m = common.IR_FUNCTION_RE.match(input_line) 237 if not m: 238 continue 239 func_name = m.group(1) 240 if args.function is not None and func_name != args.function: 241 # When filtering on a specific function, skip all others. 242 continue 243 is_in_function = is_in_function_start = True 244 245 if args.check_globals: 246 generated_prefixes.extend( 247 common.add_global_checks(builder.global_var_dict(), ';', prefix_list, 248 output_lines, global_vars_seen_dict, 249 args.preserve_names, False)) 250 if ti.args.gen_unused_prefix_body: 251 output_lines.extend(ti.get_checks_for_unused_prefixes( 252 prefix_list, generated_prefixes)) 253 common.debug('Writing %d lines to %s...' % (len(output_lines), ti.path)) 254 255 with open(ti.path, 'wb') as f: 256 f.writelines(['{}\n'.format(l).encode('utf-8') for l in output_lines]) 257 258 259if __name__ == '__main__': 260 main() 261