1from __future__ import print_function 2 3import copy 4import glob 5import os 6import re 7import subprocess 8import sys 9 10if sys.version_info[0] > 2: 11 class string: 12 expandtabs = str.expandtabs 13else: 14 import string 15 16##### Common utilities for update_*test_checks.py 17 18 19_verbose = False 20_prefix_filecheck_ir_name = '' 21 22def parse_commandline_args(parser): 23 parser.add_argument('--include-generated-funcs', action='store_true', 24 help='Output checks for functions not in source') 25 parser.add_argument('-v', '--verbose', action='store_true', 26 help='Show verbose output') 27 parser.add_argument('-u', '--update-only', action='store_true', 28 help='Only update test if it was already autogened') 29 parser.add_argument('--force-update', action='store_true', 30 help='Update test even if it was autogened by a different script') 31 parser.add_argument('--enable', action='store_true', dest='enabled', default=True, 32 help='Activate CHECK line generation from this point forward') 33 parser.add_argument('--disable', action='store_false', dest='enabled', 34 help='Deactivate CHECK line generation from this point forward') 35 parser.add_argument('--replace-value-regex', nargs='+', default=[], 36 help='List of regular expressions to replace matching value names') 37 parser.add_argument('--prefix-filecheck-ir-name', default='', 38 help='Add a prefix to FileCheck IR value names to avoid conflicts with scripted names') 39 parser.add_argument('--global-value-regex', nargs='+', default=[], 40 help='List of regular expressions that a global value declaration must match to generate a check (has no effect if checking globals is not enabled)') 41 parser.add_argument('--global-hex-value-regex', nargs='+', default=[], 42 help='List of regular expressions such that, for matching global value declarations, literal integer values should be encoded in hex in the associated FileCheck directives') 43 args = parser.parse_args() 44 global _verbose, _global_value_regex, _global_hex_value_regex 45 _verbose = args.verbose 46 _global_value_regex = args.global_value_regex 47 _global_hex_value_regex = args.global_hex_value_regex 48 return args 49 50 51class InputLineInfo(object): 52 def __init__(self, line, line_number, args, argv): 53 self.line = line 54 self.line_number = line_number 55 self.args = args 56 self.argv = argv 57 58 59class TestInfo(object): 60 def __init__(self, test, parser, script_name, input_lines, args, argv, 61 comment_prefix, argparse_callback): 62 self.parser = parser 63 self.argparse_callback = argparse_callback 64 self.path = test 65 self.args = args 66 if args.prefix_filecheck_ir_name: 67 global _prefix_filecheck_ir_name 68 _prefix_filecheck_ir_name = args.prefix_filecheck_ir_name 69 self.argv = argv 70 self.input_lines = input_lines 71 self.run_lines = find_run_lines(test, self.input_lines) 72 self.comment_prefix = comment_prefix 73 if self.comment_prefix is None: 74 if self.path.endswith('.mir'): 75 self.comment_prefix = '#' 76 else: 77 self.comment_prefix = ';' 78 self.autogenerated_note_prefix = self.comment_prefix + ' ' + UTC_ADVERT 79 self.test_autogenerated_note = self.autogenerated_note_prefix + script_name 80 self.test_autogenerated_note += get_autogennote_suffix(parser, self.args) 81 82 def ro_iterlines(self): 83 for line_num, input_line in enumerate(self.input_lines): 84 args, argv = check_for_command(input_line, self.parser, 85 self.args, self.argv, self.argparse_callback) 86 yield InputLineInfo(input_line, line_num, args, argv) 87 88 def iterlines(self, output_lines): 89 output_lines.append(self.test_autogenerated_note) 90 for line_info in self.ro_iterlines(): 91 input_line = line_info.line 92 # Discard any previous script advertising. 93 if input_line.startswith(self.autogenerated_note_prefix): 94 continue 95 self.args = line_info.args 96 self.argv = line_info.argv 97 if not self.args.enabled: 98 output_lines.append(input_line) 99 continue 100 yield line_info 101 102def itertests(test_patterns, parser, script_name, comment_prefix=None, argparse_callback=None): 103 for pattern in test_patterns: 104 # On Windows we must expand the patterns ourselves. 105 tests_list = glob.glob(pattern) 106 if not tests_list: 107 warn("Test file pattern '%s' was not found. Ignoring it." % (pattern,)) 108 continue 109 for test in tests_list: 110 with open(test) as f: 111 input_lines = [l.rstrip() for l in f] 112 args = parser.parse_args() 113 if argparse_callback is not None: 114 argparse_callback(args) 115 argv = sys.argv[:] 116 first_line = input_lines[0] if input_lines else "" 117 if UTC_ADVERT in first_line: 118 if script_name not in first_line and not args.force_update: 119 warn("Skipping test which wasn't autogenerated by " + script_name, test) 120 continue 121 args, argv = check_for_command(first_line, parser, args, argv, argparse_callback) 122 elif args.update_only: 123 assert UTC_ADVERT not in first_line 124 warn("Skipping test which isn't autogenerated: " + test) 125 continue 126 yield TestInfo(test, parser, script_name, input_lines, args, argv, 127 comment_prefix, argparse_callback) 128 129 130def should_add_line_to_output(input_line, prefix_set, skip_global_checks = False, comment_marker = ';'): 131 # Skip any blank comment lines in the IR. 132 if not skip_global_checks and input_line.strip() == comment_marker: 133 return False 134 # Skip a special double comment line we use as a separator. 135 if input_line.strip() == comment_marker + SEPARATOR: 136 return False 137 # Skip any blank lines in the IR. 138 #if input_line.strip() == '': 139 # return False 140 # And skip any CHECK lines. We're building our own. 141 m = CHECK_RE.match(input_line) 142 if m and m.group(1) in prefix_set: 143 if skip_global_checks: 144 global_ir_value_re = re.compile('\[\[', flags=(re.M)) 145 return not global_ir_value_re.search(input_line) 146 return False 147 148 return True 149 150# Perform lit-like substitutions 151def getSubstitutions(sourcepath): 152 sourcedir = os.path.dirname(sourcepath) 153 return [('%s', sourcepath), 154 ('%S', sourcedir), 155 ('%p', sourcedir), 156 ('%{pathsep}', os.pathsep)] 157 158def applySubstitutions(s, substitutions): 159 for a,b in substitutions: 160 s = s.replace(a, b) 161 return s 162 163# Invoke the tool that is being tested. 164def invoke_tool(exe, cmd_args, ir, preprocess_cmd=None, verbose=False): 165 with open(ir) as ir_file: 166 substitutions = getSubstitutions(ir) 167 168 # TODO Remove the str form which is used by update_test_checks.py and 169 # update_llc_test_checks.py 170 # The safer list form is used by update_cc_test_checks.py 171 if preprocess_cmd: 172 # Allow pre-processing the IR file (e.g. using sed): 173 assert isinstance(preprocess_cmd, str) # TODO: use a list instead of using shell 174 preprocess_cmd = applySubstitutions(preprocess_cmd, substitutions).strip() 175 if verbose: 176 print('Pre-processing input file: ', ir, " with command '", 177 preprocess_cmd, "'", sep="", file=sys.stderr) 178 # Python 2.7 doesn't have subprocess.DEVNULL: 179 with open(os.devnull, 'w') as devnull: 180 pp = subprocess.Popen(preprocess_cmd, shell=True, stdin=devnull, 181 stdout=subprocess.PIPE) 182 ir_file = pp.stdout 183 184 if isinstance(cmd_args, list): 185 args = [applySubstitutions(a, substitutions) for a in cmd_args] 186 stdout = subprocess.check_output([exe] + args, stdin=ir_file) 187 else: 188 stdout = subprocess.check_output(exe + ' ' + applySubstitutions(cmd_args, substitutions), 189 shell=True, stdin=ir_file) 190 if sys.version_info[0] > 2: 191 stdout = stdout.decode() 192 # Fix line endings to unix CR style. 193 return stdout.replace('\r\n', '\n') 194 195##### LLVM IR parser 196RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$') 197CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)') 198PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$') 199CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:') 200 201UTC_ARGS_KEY = 'UTC_ARGS:' 202UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$') 203UTC_ADVERT = 'NOTE: Assertions have been autogenerated by ' 204 205OPT_FUNCTION_RE = re.compile( 206 r'^(\s*;\s*Function\sAttrs:\s(?P<attrs>[\w\s]+?))?\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.$-]+?)\s*' 207 r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*\{)\n(?P<body>.*?)^\}$', 208 flags=(re.M | re.S)) 209 210ANALYZE_FUNCTION_RE = re.compile( 211 r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.$-]+?)\':' 212 r'\s*\n(?P<body>.*)$', 213 flags=(re.X | re.S)) 214 215IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@"?([\w.$-]+)"?\s*\(') 216TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$') 217TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)') 218MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)') 219 220SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)') 221SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M) 222SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M) 223SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE 224SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M) 225SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') 226SCRUB_LOOP_COMMENT_RE = re.compile( 227 r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M) 228SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M) 229 230SEPARATOR = '.' 231 232def error(msg, test_file=None): 233 if test_file: 234 msg = '{}: {}'.format(msg, test_file) 235 print('ERROR: {}'.format(msg), file=sys.stderr) 236 237def warn(msg, test_file=None): 238 if test_file: 239 msg = '{}: {}'.format(msg, test_file) 240 print('WARNING: {}'.format(msg), file=sys.stderr) 241 242def debug(*args, **kwargs): 243 # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs): 244 if 'file' not in kwargs: 245 kwargs['file'] = sys.stderr 246 if _verbose: 247 print(*args, **kwargs) 248 249def find_run_lines(test, lines): 250 debug('Scanning for RUN lines in test file:', test) 251 raw_lines = [m.group(1) 252 for m in [RUN_LINE_RE.match(l) for l in lines] if m] 253 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] 254 for l in raw_lines[1:]: 255 if run_lines[-1].endswith('\\'): 256 run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l 257 else: 258 run_lines.append(l) 259 debug('Found {} RUN lines in {}:'.format(len(run_lines), test)) 260 for l in run_lines: 261 debug(' RUN: {}'.format(l)) 262 return run_lines 263 264def scrub_body(body): 265 # Scrub runs of whitespace out of the assembly, but leave the leading 266 # whitespace in place. 267 body = SCRUB_WHITESPACE_RE.sub(r' ', body) 268 # Expand the tabs used for indentation. 269 body = string.expandtabs(body, 2) 270 # Strip trailing whitespace. 271 body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body) 272 return body 273 274def do_scrub(body, scrubber, scrubber_args, extra): 275 if scrubber_args: 276 local_args = copy.deepcopy(scrubber_args) 277 local_args[0].extra_scrub = extra 278 return scrubber(body, *local_args) 279 return scrubber(body, *scrubber_args) 280 281# Build up a dictionary of all the function bodies. 282class function_body(object): 283 def __init__(self, string, extra, args_and_sig, attrs): 284 self.scrub = string 285 self.extrascrub = extra 286 self.args_and_sig = args_and_sig 287 self.attrs = attrs 288 def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs, is_asm): 289 arg_names = set() 290 def drop_arg_names(match): 291 arg_names.add(match.group(variable_group_in_ir_value_match)) 292 if match.group(attribute_group_in_ir_value_match): 293 attr = match.group(attribute_group_in_ir_value_match) 294 else: 295 attr = '' 296 return match.group(1) + attr + match.group(match.lastindex) 297 def repl_arg_names(match): 298 if match.group(variable_group_in_ir_value_match) is not None and match.group(variable_group_in_ir_value_match) in arg_names: 299 return match.group(1) + match.group(match.lastindex) 300 return match.group(1) + match.group(2) + match.group(match.lastindex) 301 if self.attrs != attrs: 302 return False 303 ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig) 304 ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig) 305 if ans0 != ans1: 306 return False 307 if is_asm: 308 # Check without replacements, the replacements are not applied to the 309 # body for asm checks. 310 return self.extrascrub == extrascrub 311 312 es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub) 313 es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub) 314 es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0) 315 es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1) 316 return es0 == es1 317 318 def __str__(self): 319 return self.scrub 320 321class FunctionTestBuilder: 322 def __init__(self, run_list, flags, scrubber_args, path): 323 self._verbose = flags.verbose 324 self._record_args = flags.function_signature 325 self._check_attributes = flags.check_attributes 326 self._scrubber_args = scrubber_args 327 self._path = path 328 # Strip double-quotes if input was read by UTC_ARGS 329 self._replace_value_regex = list(map(lambda x: x.strip('"'), flags.replace_value_regex)) 330 self._func_dict = {} 331 self._func_order = {} 332 self._global_var_dict = {} 333 for tuple in run_list: 334 for prefix in tuple[0]: 335 self._func_dict.update({prefix:dict()}) 336 self._func_order.update({prefix: []}) 337 self._global_var_dict.update({prefix:dict()}) 338 339 def finish_and_get_func_dict(self): 340 for prefix in self._get_failed_prefixes(): 341 warn('Prefix %s had conflicting output from different RUN lines for all functions in test %s' % (prefix,self._path,)) 342 return self._func_dict 343 344 def func_order(self): 345 return self._func_order 346 347 def global_var_dict(self): 348 return self._global_var_dict 349 350 def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes, is_asm): 351 build_global_values_dictionary(self._global_var_dict, raw_tool_output, prefixes) 352 for m in function_re.finditer(raw_tool_output): 353 if not m: 354 continue 355 func = m.group('func') 356 body = m.group('body') 357 attrs = m.group('attrs') if self._check_attributes else '' 358 # Determine if we print arguments, the opening brace, or nothing after the 359 # function name 360 if self._record_args and 'args_and_sig' in m.groupdict(): 361 args_and_sig = scrub_body(m.group('args_and_sig').strip()) 362 elif 'args_and_sig' in m.groupdict(): 363 args_and_sig = '(' 364 else: 365 args_and_sig = '' 366 scrubbed_body = do_scrub(body, scrubber, self._scrubber_args, 367 extra=False) 368 scrubbed_extra = do_scrub(body, scrubber, self._scrubber_args, 369 extra=True) 370 if 'analysis' in m.groupdict(): 371 analysis = m.group('analysis') 372 if analysis.lower() != 'cost model analysis': 373 warn('Unsupported analysis mode: %r!' % (analysis,)) 374 if func.startswith('stress'): 375 # We only use the last line of the function body for stress tests. 376 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:]) 377 if self._verbose: 378 print('Processing function: ' + func, file=sys.stderr) 379 for l in scrubbed_body.splitlines(): 380 print(' ' + l, file=sys.stderr) 381 for prefix in prefixes: 382 # Replace function names matching the regex. 383 for regex in self._replace_value_regex: 384 # Pattern that matches capture groups in the regex in leftmost order. 385 group_regex = re.compile('\(.*?\)') 386 # Replace function name with regex. 387 match = re.match(regex, func) 388 if match: 389 func_repl = regex 390 # Replace any capture groups with their matched strings. 391 for g in match.groups(): 392 func_repl = group_regex.sub(re.escape(g), func_repl, count=1) 393 func = re.sub(func_repl, '{{' + func_repl + '}}', func) 394 395 # Replace all calls to regex matching functions. 396 matches = re.finditer(regex, scrubbed_body) 397 for match in matches: 398 func_repl = regex 399 # Replace any capture groups with their matched strings. 400 for g in match.groups(): 401 func_repl = group_regex.sub(re.escape(g), func_repl, count=1) 402 # Substitute function call names that match the regex with the same 403 # capture groups set. 404 scrubbed_body = re.sub(func_repl, '{{' + func_repl + '}}', 405 scrubbed_body) 406 407 if func in self._func_dict[prefix]: 408 if (self._func_dict[prefix][func] is None or 409 str(self._func_dict[prefix][func]) != scrubbed_body or 410 self._func_dict[prefix][func].args_and_sig != args_and_sig or 411 self._func_dict[prefix][func].attrs != attrs): 412 if (self._func_dict[prefix][func] is not None and 413 self._func_dict[prefix][func].is_same_except_arg_names( 414 scrubbed_extra, 415 args_and_sig, 416 attrs, 417 is_asm)): 418 self._func_dict[prefix][func].scrub = scrubbed_extra 419 self._func_dict[prefix][func].args_and_sig = args_and_sig 420 continue 421 else: 422 # This means a previous RUN line produced a body for this function 423 # that is different from the one produced by this current RUN line, 424 # so the body can't be common accross RUN lines. We use None to 425 # indicate that. 426 self._func_dict[prefix][func] = None 427 continue 428 429 self._func_dict[prefix][func] = function_body( 430 scrubbed_body, scrubbed_extra, args_and_sig, attrs) 431 self._func_order[prefix].append(func) 432 433 def _get_failed_prefixes(self): 434 # This returns the list of those prefixes that failed to match any function, 435 # because there were conflicting bodies produced by different RUN lines, in 436 # all instances of the prefix. Effectively, this prefix is unused and should 437 # be removed. 438 for prefix in self._func_dict: 439 if (self._func_dict[prefix] and 440 (not [fct for fct in self._func_dict[prefix] 441 if self._func_dict[prefix][fct] is not None])): 442 yield prefix 443 444 445##### Generator of LLVM IR CHECK lines 446 447SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*') 448 449# TODO: We should also derive check lines for global, debug, loop declarations, etc.. 450 451class NamelessValue: 452 def __init__(self, check_prefix, check_key, ir_prefix, global_ir_prefix, global_ir_prefix_regexp, 453 ir_regexp, global_ir_rhs_regexp, is_before_functions): 454 self.check_prefix = check_prefix 455 self.check_key = check_key 456 self.ir_prefix = ir_prefix 457 self.global_ir_prefix = global_ir_prefix 458 self.global_ir_prefix_regexp = global_ir_prefix_regexp 459 self.ir_regexp = ir_regexp 460 self.global_ir_rhs_regexp = global_ir_rhs_regexp 461 self.is_before_functions = is_before_functions 462 463# Description of the different "unnamed" values we match in the IR, e.g., 464# (local) ssa values, (debug) metadata, etc. 465nameless_values = [ 466 NamelessValue(r'TMP' , '%' , r'%' , None , None , r'[\w$.-]+?' , None , False) , 467 NamelessValue(r'ATTR' , '#' , r'#' , None , None , r'[0-9]+' , None , False) , 468 NamelessValue(r'ATTR' , '#' , None , r'attributes #' , r'[0-9]+' , None , r'{[^}]*}' , False) , 469 NamelessValue(r'GLOB' , '@' , r'@' , None , None , r'[0-9]+' , None , False) , 470 NamelessValue(r'GLOB' , '@' , None , r'@' , r'[a-zA-Z0-9_$"\\.-]+' , None , r'.+' , True) , 471 NamelessValue(r'DBG' , '!' , r'!dbg ' , None , None , r'![0-9]+' , None , False) , 472 NamelessValue(r'PROF' , '!' , r'!prof ' , None , None , r'![0-9]+' , None , False) , 473 NamelessValue(r'TBAA' , '!' , r'!tbaa ' , None , None , r'![0-9]+' , None , False) , 474 NamelessValue(r'RNG' , '!' , r'!range ' , None , None , r'![0-9]+' , None , False) , 475 NamelessValue(r'LOOP' , '!' , r'!llvm.loop ' , None , None , r'![0-9]+' , None , False) , 476 NamelessValue(r'META' , '!' , r'metadata ' , None , None , r'![0-9]+' , None , False) , 477 NamelessValue(r'META' , '!' , None , r'' , r'![0-9]+' , None , r'(?:distinct |)!.*' , False) , 478] 479 480def createOrRegexp(old, new): 481 if not old: 482 return new 483 if not new: 484 return old 485 return old + '|' + new 486 487def createPrefixMatch(prefix_str, prefix_re): 488 if prefix_str is None or prefix_re is None: 489 return '' 490 return '(?:' + prefix_str + '(' + prefix_re + '))' 491 492# Build the regexp that matches an "IR value". This can be a local variable, 493# argument, global, or metadata, anything that is "named". It is important that 494# the PREFIX and SUFFIX below only contain a single group, if that changes 495# other locations will need adjustment as well. 496IR_VALUE_REGEXP_PREFIX = r'(\s*)' 497IR_VALUE_REGEXP_STRING = r'' 498for nameless_value in nameless_values: 499 lcl_match = createPrefixMatch(nameless_value.ir_prefix, nameless_value.ir_regexp) 500 glb_match = createPrefixMatch(nameless_value.global_ir_prefix, nameless_value.global_ir_prefix_regexp) 501 assert((lcl_match or glb_match) and not (lcl_match and glb_match)) 502 if lcl_match: 503 IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, lcl_match) 504 elif glb_match: 505 IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, '^' + glb_match) 506IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)' 507IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX) 508 509# The entire match is group 0, the prefix has one group (=1), the entire 510# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start. 511first_nameless_group_in_ir_value_match = 3 512 513# constants for the group id of special matches 514variable_group_in_ir_value_match = 3 515attribute_group_in_ir_value_match = 4 516 517# Check a match for IR_VALUE_RE and inspect it to determine if it was a local 518# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above. 519def get_idx_from_ir_value_match(match): 520 for i in range(first_nameless_group_in_ir_value_match, match.lastindex): 521 if match.group(i) is not None: 522 return i - first_nameless_group_in_ir_value_match 523 error("Unable to identify the kind of IR value from the match!") 524 return 0 525 526# See get_idx_from_ir_value_match 527def get_name_from_ir_value_match(match): 528 return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match) 529 530# Return the nameless prefix we use for this kind or IR value, see also 531# get_idx_from_ir_value_match 532def get_nameless_check_prefix_from_ir_value_match(match): 533 return nameless_values[get_idx_from_ir_value_match(match)].check_prefix 534 535# Return the IR prefix and check prefix we use for this kind or IR value, e.g., (%, TMP) for locals, 536# see also get_idx_from_ir_value_match 537def get_ir_prefix_from_ir_value_match(match): 538 idx = get_idx_from_ir_value_match(match) 539 if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix): 540 return nameless_values[idx].ir_prefix, nameless_values[idx].check_prefix 541 return nameless_values[idx].global_ir_prefix, nameless_values[idx].check_prefix 542 543def get_check_key_from_ir_value_match(match): 544 idx = get_idx_from_ir_value_match(match) 545 return nameless_values[idx].check_key 546 547# Return the IR regexp we use for this kind or IR value, e.g., [\w.-]+? for locals, 548# see also get_idx_from_ir_value_match 549def get_ir_prefix_from_ir_value_re_match(match): 550 # for backwards compatibility we check locals with '.*' 551 if is_local_def_ir_value_match(match): 552 return '.*' 553 idx = get_idx_from_ir_value_match(match) 554 if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix): 555 return nameless_values[idx].ir_regexp 556 return nameless_values[idx].global_ir_prefix_regexp 557 558# Return true if this kind of IR value is "local", basically if it matches '%{{.*}}'. 559def is_local_def_ir_value_match(match): 560 return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%' 561 562# Return true if this kind of IR value is "global", basically if it matches '#{{.*}}'. 563def is_global_scope_ir_value_match(match): 564 return nameless_values[get_idx_from_ir_value_match(match)].global_ir_prefix is not None 565 566# Return true if var clashes with the scripted FileCheck check_prefix. 567def may_clash_with_default_check_prefix_name(check_prefix, var): 568 return check_prefix and re.match(r'^' + check_prefix + r'[0-9]+?$', var, re.IGNORECASE) 569 570# Create a FileCheck variable name based on an IR name. 571def get_value_name(var, check_prefix): 572 var = var.replace('!', '') 573 # This is a nameless value, prepend check_prefix. 574 if var.isdigit(): 575 var = check_prefix + var 576 else: 577 # This is a named value that clashes with the check_prefix, prepend with _prefix_filecheck_ir_name, 578 # if it has been defined. 579 if may_clash_with_default_check_prefix_name(check_prefix, var) and _prefix_filecheck_ir_name: 580 var = _prefix_filecheck_ir_name + var 581 var = var.replace('.', '_') 582 var = var.replace('-', '_') 583 return var.upper() 584 585# Create a FileCheck variable from regex. 586def get_value_definition(var, match): 587 # for backwards compatibility we check locals with '.*' 588 if is_local_def_ir_value_match(match): 589 return '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + \ 590 get_ir_prefix_from_ir_value_match(match)[0] + get_ir_prefix_from_ir_value_re_match(match) + ']]' 591 prefix = get_ir_prefix_from_ir_value_match(match)[0] 592 return prefix + '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + get_ir_prefix_from_ir_value_re_match(match) + ']]' 593 594# Use a FileCheck variable. 595def get_value_use(var, match, check_prefix): 596 if is_local_def_ir_value_match(match): 597 return '[[' + get_value_name(var, check_prefix) + ']]' 598 prefix = get_ir_prefix_from_ir_value_match(match)[0] 599 return prefix + '[[' + get_value_name(var, check_prefix) + ']]' 600 601# Replace IR value defs and uses with FileCheck variables. 602def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen): 603 # This gets called for each match that occurs in 604 # a line. We transform variables we haven't seen 605 # into defs, and variables we have seen into uses. 606 def transform_line_vars(match): 607 pre, check = get_ir_prefix_from_ir_value_match(match) 608 var = get_name_from_ir_value_match(match) 609 for nameless_value in nameless_values: 610 if may_clash_with_default_check_prefix_name(nameless_value.check_prefix, var): 611 warn("Change IR value name '%s' or use -prefix-ir-filecheck-name to prevent possible conflict" 612 " with scripted FileCheck name." % (var,)) 613 key = (var, get_check_key_from_ir_value_match(match)) 614 is_local_def = is_local_def_ir_value_match(match) 615 if is_local_def and key in vars_seen: 616 rv = get_value_use(var, match, get_nameless_check_prefix_from_ir_value_match(match)) 617 elif not is_local_def and key in global_vars_seen: 618 rv = get_value_use(var, match, global_vars_seen[key]) 619 else: 620 if is_local_def: 621 vars_seen.add(key) 622 else: 623 global_vars_seen[key] = get_nameless_check_prefix_from_ir_value_match(match) 624 rv = get_value_definition(var, match) 625 # re.sub replaces the entire regex match 626 # with whatever you return, so we have 627 # to make sure to hand it back everything 628 # including the commas and spaces. 629 return match.group(1) + rv + match.group(match.lastindex) 630 631 lines_with_def = [] 632 633 for i, line in enumerate(lines): 634 # An IR variable named '%.' matches the FileCheck regex string. 635 line = line.replace('%.', '%dot') 636 for regex in _global_hex_value_regex: 637 if re.match('^@' + regex + ' = ', line): 638 line = re.sub(r'\bi([0-9]+) ([0-9]+)', 639 lambda m : 'i' + m.group(1) + ' [[#' + hex(int(m.group(2))) + ']]', 640 line) 641 break 642 # Ignore any comments, since the check lines will too. 643 scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line) 644 lines[i] = scrubbed_line 645 if not is_analyze: 646 # It can happen that two matches are back-to-back and for some reason sub 647 # will not replace both of them. For now we work around this by 648 # substituting until there is no more match. 649 changed = True 650 while changed: 651 (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1) 652 return lines 653 654 655def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict): 656 # prefix_exclusions are prefixes we cannot use to print the function because it doesn't exist in run lines that use these prefixes as well. 657 prefix_exclusions = set() 658 printed_prefixes = [] 659 for p in prefix_list: 660 checkprefixes = p[0] 661 # If not all checkprefixes of this run line produced the function we cannot check for it as it does not 662 # exist for this run line. A subset of the check prefixes might know about the function but only because 663 # other run lines created it. 664 if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)): 665 prefix_exclusions |= set(checkprefixes) 666 continue 667 668 # prefix_exclusions is constructed, we can now emit the output 669 for p in prefix_list: 670 global_vars_seen = {} 671 checkprefixes = p[0] 672 for checkprefix in checkprefixes: 673 if checkprefix in global_vars_seen_dict: 674 global_vars_seen.update(global_vars_seen_dict[checkprefix]) 675 else: 676 global_vars_seen_dict[checkprefix] = {} 677 if checkprefix in printed_prefixes: 678 break 679 680 # Check if the prefix is excluded. 681 if checkprefix in prefix_exclusions: 682 continue 683 684 # If we do not have output for this prefix we skip it. 685 if not func_dict[checkprefix][func_name]: 686 continue 687 688 # Add some space between different check prefixes, but not after the last 689 # check line (before the test code). 690 if is_asm: 691 if len(printed_prefixes) != 0: 692 output_lines.append(comment_marker) 693 694 if checkprefix not in global_vars_seen_dict: 695 global_vars_seen_dict[checkprefix] = {} 696 697 global_vars_seen_before = [key for key in global_vars_seen.keys()] 698 699 vars_seen = set() 700 printed_prefixes.append(checkprefix) 701 attrs = str(func_dict[checkprefix][func_name].attrs) 702 attrs = '' if attrs == 'None' else attrs 703 if attrs: 704 output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs)) 705 args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig) 706 args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0] 707 if '[[' in args_and_sig: 708 output_lines.append(check_label_format % (checkprefix, func_name, '')) 709 output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig)) 710 else: 711 output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig)) 712 func_body = str(func_dict[checkprefix][func_name]).splitlines() 713 714 # For ASM output, just emit the check lines. 715 if is_asm: 716 output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 717 for func_line in func_body[1:]: 718 if func_line.strip() == '': 719 output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix)) 720 else: 721 output_lines.append('%s %s-NEXT: %s' % (comment_marker, checkprefix, func_line)) 722 break 723 724 # For IR output, change all defs to FileCheck variables, so we're immune 725 # to variable naming fashions. 726 func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen) 727 728 # This could be selectively enabled with an optional invocation argument. 729 # Disabled for now: better to check everything. Be safe rather than sorry. 730 731 # Handle the first line of the function body as a special case because 732 # it's often just noise (a useless asm comment or entry label). 733 #if func_body[0].startswith("#") or func_body[0].startswith("entry:"): 734 # is_blank_line = True 735 #else: 736 # output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 737 # is_blank_line = False 738 739 is_blank_line = False 740 741 for func_line in func_body: 742 if func_line.strip() == '': 743 is_blank_line = True 744 continue 745 # Do not waste time checking IR comments. 746 func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line) 747 748 # Skip blank lines instead of checking them. 749 if is_blank_line: 750 output_lines.append('{} {}: {}'.format( 751 comment_marker, checkprefix, func_line)) 752 else: 753 output_lines.append('{} {}-NEXT: {}'.format( 754 comment_marker, checkprefix, func_line)) 755 is_blank_line = False 756 757 # Add space between different check prefixes and also before the first 758 # line of code in the test function. 759 output_lines.append(comment_marker) 760 761 # Remembe new global variables we have not seen before 762 for key in global_vars_seen: 763 if key not in global_vars_seen_before: 764 global_vars_seen_dict[checkprefix][key] = global_vars_seen[key] 765 break 766 767def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict, 768 func_name, preserve_names, function_sig, global_vars_seen_dict): 769 # Label format is based on IR string. 770 function_def_regex = 'define {{[^@]+}}' if function_sig else '' 771 check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex) 772 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 773 check_label_format, False, preserve_names, global_vars_seen_dict) 774 775def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name): 776 check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker) 777 global_vars_seen_dict = {} 778 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 779 check_label_format, False, True, global_vars_seen_dict) 780 781def build_global_values_dictionary(glob_val_dict, raw_tool_output, prefixes): 782 for nameless_value in nameless_values: 783 if nameless_value.global_ir_prefix is None: 784 continue 785 786 lhs_re_str = nameless_value.global_ir_prefix + nameless_value.global_ir_prefix_regexp 787 rhs_re_str = nameless_value.global_ir_rhs_regexp 788 789 global_ir_value_re_str = r'^' + lhs_re_str + r'\s=\s' + rhs_re_str + r'$' 790 global_ir_value_re = re.compile(global_ir_value_re_str, flags=(re.M)) 791 lines = [] 792 for m in global_ir_value_re.finditer(raw_tool_output): 793 lines.append(m.group(0)) 794 795 for prefix in prefixes: 796 if glob_val_dict[prefix] is None: 797 continue 798 if nameless_value.check_prefix in glob_val_dict[prefix]: 799 if lines == glob_val_dict[prefix][nameless_value.check_prefix]: 800 continue 801 if prefix == prefixes[-1]: 802 warn('Found conflicting asm under the same prefix: %r!' % (prefix,)) 803 else: 804 glob_val_dict[prefix][nameless_value.check_prefix] = None 805 continue 806 glob_val_dict[prefix][nameless_value.check_prefix] = lines 807 808def add_global_checks(glob_val_dict, comment_marker, prefix_list, output_lines, global_vars_seen_dict, is_analyze, is_before_functions): 809 printed_prefixes = set() 810 for nameless_value in nameless_values: 811 if nameless_value.global_ir_prefix is None: 812 continue 813 if nameless_value.is_before_functions != is_before_functions: 814 continue 815 for p in prefix_list: 816 global_vars_seen = {} 817 checkprefixes = p[0] 818 if checkprefixes is None: 819 continue 820 for checkprefix in checkprefixes: 821 if checkprefix in global_vars_seen_dict: 822 global_vars_seen.update(global_vars_seen_dict[checkprefix]) 823 else: 824 global_vars_seen_dict[checkprefix] = {} 825 if (checkprefix, nameless_value.check_prefix) in printed_prefixes: 826 break 827 if not glob_val_dict[checkprefix]: 828 continue 829 if nameless_value.check_prefix not in glob_val_dict[checkprefix]: 830 continue 831 if not glob_val_dict[checkprefix][nameless_value.check_prefix]: 832 continue 833 834 check_lines = [] 835 global_vars_seen_before = [key for key in global_vars_seen.keys()] 836 for line in glob_val_dict[checkprefix][nameless_value.check_prefix]: 837 if _global_value_regex: 838 matched = False 839 for regex in _global_value_regex: 840 if re.match('^@' + regex + ' = ', line): 841 matched = True 842 break 843 if not matched: 844 continue 845 tmp = generalize_check_lines([line], is_analyze, set(), global_vars_seen) 846 check_line = '%s %s: %s' % (comment_marker, checkprefix, tmp[0]) 847 check_lines.append(check_line) 848 if not check_lines: 849 continue 850 851 output_lines.append(comment_marker + SEPARATOR) 852 for check_line in check_lines: 853 output_lines.append(check_line) 854 855 printed_prefixes.add((checkprefix, nameless_value.check_prefix)) 856 857 # Remembe new global variables we have not seen before 858 for key in global_vars_seen: 859 if key not in global_vars_seen_before: 860 global_vars_seen_dict[checkprefix][key] = global_vars_seen[key] 861 break 862 863 if printed_prefixes: 864 output_lines.append(comment_marker + SEPARATOR) 865 866 867def check_prefix(prefix): 868 if not PREFIX_RE.match(prefix): 869 hint = "" 870 if ',' in prefix: 871 hint = " Did you mean '--check-prefixes=" + prefix + "'?" 872 warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) % 873 (prefix)) 874 875 876def verify_filecheck_prefixes(fc_cmd): 877 fc_cmd_parts = fc_cmd.split() 878 for part in fc_cmd_parts: 879 if "check-prefix=" in part: 880 prefix = part.split('=', 1)[1] 881 check_prefix(prefix) 882 elif "check-prefixes=" in part: 883 prefixes = part.split('=', 1)[1].split(',') 884 for prefix in prefixes: 885 check_prefix(prefix) 886 if prefixes.count(prefix) > 1: 887 warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,)) 888 889 890def get_autogennote_suffix(parser, args): 891 autogenerated_note_args = '' 892 for action in parser._actions: 893 if not hasattr(args, action.dest): 894 continue # Ignore options such as --help that aren't included in args 895 # Ignore parameters such as paths to the binary or the list of tests 896 if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary', 897 'clang', 'opt', 'llvm_bin', 'verbose'): 898 continue 899 value = getattr(args, action.dest) 900 if action.const is not None: # action stores a constant (usually True/False) 901 # Skip actions with different constant values (this happens with boolean 902 # --foo/--no-foo options) 903 if value != action.const: 904 continue 905 if parser.get_default(action.dest) == value: 906 continue # Don't add default values 907 autogenerated_note_args += action.option_strings[0] + ' ' 908 if action.const is None: # action takes a parameter 909 if action.nargs == '+': 910 value = ' '.join(map(lambda v: '"' + v.strip('"') + '"', value)) 911 autogenerated_note_args += '%s ' % value 912 if autogenerated_note_args: 913 autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1]) 914 return autogenerated_note_args 915 916 917def check_for_command(line, parser, args, argv, argparse_callback): 918 cmd_m = UTC_ARGS_CMD.match(line) 919 if cmd_m: 920 for option in cmd_m.group('cmd').strip().split(' '): 921 if option: 922 argv.append(option) 923 args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv)) 924 if argparse_callback is not None: 925 argparse_callback(args) 926 return args, argv 927 928def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global): 929 result = get_arg_to_check(test_info.args) 930 if not result and is_global: 931 # See if this has been specified via UTC_ARGS. This is a "global" option 932 # that affects the entire generation of test checks. If it exists anywhere 933 # in the test, apply it to everything. 934 saw_line = False 935 for line_info in test_info.ro_iterlines(): 936 line = line_info.line 937 if not line.startswith(';') and line.strip() != '': 938 saw_line = True 939 result = get_arg_to_check(line_info.args) 940 if result: 941 if warn and saw_line: 942 # We saw the option after already reading some test input lines. 943 # Warn about it. 944 print('WARNING: Found {} in line following test start: '.format(arg_string) 945 + line, file=sys.stderr) 946 print('WARNING: Consider moving {} to top of file'.format(arg_string), 947 file=sys.stderr) 948 break 949 return result 950 951def dump_input_lines(output_lines, test_info, prefix_set, comment_string): 952 for input_line_info in test_info.iterlines(output_lines): 953 line = input_line_info.line 954 args = input_line_info.args 955 if line.strip() == comment_string: 956 continue 957 if line.strip() == comment_string + SEPARATOR: 958 continue 959 if line.lstrip().startswith(comment_string): 960 m = CHECK_RE.match(line) 961 if m and m.group(1) in prefix_set: 962 continue 963 output_lines.append(line.rstrip('\n')) 964 965def add_checks_at_end(output_lines, prefix_list, func_order, 966 comment_string, check_generator): 967 added = set() 968 for prefix in prefix_list: 969 prefixes = prefix[0] 970 tool_args = prefix[1] 971 for prefix in prefixes: 972 for func in func_order[prefix]: 973 if added: 974 output_lines.append(comment_string) 975 added.add(func) 976 977 # The add_*_checks routines expect a run list whose items are 978 # tuples that have a list of prefixes as their first element and 979 # tool command args string as their second element. They output 980 # checks for each prefix in the list of prefixes. By doing so, it 981 # implicitly assumes that for each function every run line will 982 # generate something for that function. That is not the case for 983 # generated functions as some run lines might not generate them 984 # (e.g. -fopenmp vs. no -fopenmp). 985 # 986 # Therefore, pass just the prefix we're interested in. This has 987 # the effect of generating all of the checks for functions of a 988 # single prefix before moving on to the next prefix. So checks 989 # are ordered by prefix instead of by function as in "normal" 990 # mode. 991 check_generator(output_lines, 992 [([prefix], tool_args)], 993 func) 994