1from __future__ import print_function 2 3import copy 4import glob 5import re 6import subprocess 7import sys 8 9if sys.version_info[0] > 2: 10 class string: 11 expandtabs = str.expandtabs 12else: 13 import string 14 15##### Common utilities for update_*test_checks.py 16 17 18_verbose = False 19 20def parse_commandline_args(parser): 21 parser.add_argument('--include-generated-funcs', action='store_true', 22 help='Output checks for functions not in source') 23 parser.add_argument('-v', '--verbose', action='store_true', 24 help='Show verbose output') 25 parser.add_argument('-u', '--update-only', action='store_true', 26 help='Only update test if it was already autogened') 27 parser.add_argument('--force-update', action='store_true', 28 help='Update test even if it was autogened by a different script') 29 parser.add_argument('--enable', action='store_true', dest='enabled', default=True, 30 help='Activate CHECK line generation from this point forward') 31 parser.add_argument('--disable', action='store_false', dest='enabled', 32 help='Deactivate CHECK line generation from this point forward') 33 args = parser.parse_args() 34 global _verbose 35 _verbose = args.verbose 36 return args 37 38 39class InputLineInfo(object): 40 def __init__(self, line, line_number, args, argv): 41 self.line = line 42 self.line_number = line_number 43 self.args = args 44 self.argv = argv 45 46 47class TestInfo(object): 48 def __init__(self, test, parser, script_name, input_lines, args, argv, 49 comment_prefix, argparse_callback): 50 self.parser = parser 51 self.argparse_callback = argparse_callback 52 self.path = test 53 self.args = args 54 self.argv = argv 55 self.input_lines = input_lines 56 self.run_lines = find_run_lines(test, self.input_lines) 57 self.comment_prefix = comment_prefix 58 if self.comment_prefix is None: 59 if self.path.endswith('.mir'): 60 self.comment_prefix = '#' 61 else: 62 self.comment_prefix = ';' 63 self.autogenerated_note_prefix = self.comment_prefix + ' ' + UTC_ADVERT 64 self.test_autogenerated_note = self.autogenerated_note_prefix + script_name 65 self.test_autogenerated_note += get_autogennote_suffix(parser, self.args) 66 67 def ro_iterlines(self): 68 for line_num, input_line in enumerate(self.input_lines): 69 args, argv = check_for_command(input_line, self.parser, 70 self.args, self.argv, self.argparse_callback) 71 yield InputLineInfo(input_line, line_num, args, argv) 72 73 def iterlines(self, output_lines): 74 output_lines.append(self.test_autogenerated_note) 75 for line_info in self.ro_iterlines(): 76 input_line = line_info.line 77 # Discard any previous script advertising. 78 if input_line.startswith(self.autogenerated_note_prefix): 79 continue 80 self.args = line_info.args 81 self.argv = line_info.argv 82 if not self.args.enabled: 83 output_lines.append(input_line) 84 continue 85 yield line_info 86 87def itertests(test_patterns, parser, script_name, comment_prefix=None, argparse_callback=None): 88 for pattern in test_patterns: 89 # On Windows we must expand the patterns ourselves. 90 tests_list = glob.glob(pattern) 91 if not tests_list: 92 warn("Test file pattern '%s' was not found. Ignoring it." % (pattern,)) 93 continue 94 for test in tests_list: 95 with open(test) as f: 96 input_lines = [l.rstrip() for l in f] 97 args = parser.parse_args() 98 if argparse_callback is not None: 99 argparse_callback(args) 100 argv = sys.argv[:] 101 first_line = input_lines[0] if input_lines else "" 102 if UTC_ADVERT in first_line: 103 if script_name not in first_line and not args.force_update: 104 warn("Skipping test which wasn't autogenerated by " + script_name, test) 105 continue 106 args, argv = check_for_command(first_line, parser, args, argv, argparse_callback) 107 elif args.update_only: 108 assert UTC_ADVERT not in first_line 109 warn("Skipping test which isn't autogenerated: " + test) 110 continue 111 yield TestInfo(test, parser, script_name, input_lines, args, argv, 112 comment_prefix, argparse_callback) 113 114 115def should_add_line_to_output(input_line, prefix_set): 116 # Skip any blank comment lines in the IR. 117 if input_line.strip() == ';': 118 return False 119 # Skip any blank lines in the IR. 120 #if input_line.strip() == '': 121 # return False 122 # And skip any CHECK lines. We're building our own. 123 m = CHECK_RE.match(input_line) 124 if m and m.group(1) in prefix_set: 125 return False 126 127 return True 128 129# Invoke the tool that is being tested. 130def invoke_tool(exe, cmd_args, ir): 131 with open(ir) as ir_file: 132 # TODO Remove the str form which is used by update_test_checks.py and 133 # update_llc_test_checks.py 134 # The safer list form is used by update_cc_test_checks.py 135 if isinstance(cmd_args, list): 136 stdout = subprocess.check_output([exe] + cmd_args, stdin=ir_file) 137 else: 138 stdout = subprocess.check_output(exe + ' ' + cmd_args, 139 shell=True, stdin=ir_file) 140 if sys.version_info[0] > 2: 141 stdout = stdout.decode() 142 # Fix line endings to unix CR style. 143 return stdout.replace('\r\n', '\n') 144 145##### LLVM IR parser 146RUN_LINE_RE = re.compile(r'^\s*(?://|[;#])\s*RUN:\s*(.*)$') 147CHECK_PREFIX_RE = re.compile(r'--?check-prefix(?:es)?[= ](\S+)') 148PREFIX_RE = re.compile('^[a-zA-Z0-9_-]+$') 149CHECK_RE = re.compile(r'^\s*(?://|[;#])\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL|-SAME|-EMPTY)?:') 150 151UTC_ARGS_KEY = 'UTC_ARGS:' 152UTC_ARGS_CMD = re.compile(r'.*' + UTC_ARGS_KEY + '\s*(?P<cmd>.*)\s*$') 153UTC_ADVERT = 'NOTE: Assertions have been autogenerated by ' 154 155OPT_FUNCTION_RE = re.compile( 156 r'^(\s*;\s*Function\sAttrs:\s(?P<attrs>[\w\s]+?))?\s*define\s+(?:internal\s+)?[^@]*@(?P<func>[\w.$-]+?)\s*' 157 r'(?P<args_and_sig>\((\)|(.*?[\w.-]+?)\))[^{]*\{)\n(?P<body>.*?)^\}$', 158 flags=(re.M | re.S)) 159 160ANALYZE_FUNCTION_RE = re.compile( 161 r'^\s*\'(?P<analysis>[\w\s-]+?)\'\s+for\s+function\s+\'(?P<func>[\w.$-]+?)\':' 162 r'\s*\n(?P<body>.*)$', 163 flags=(re.X | re.S)) 164 165IR_FUNCTION_RE = re.compile(r'^\s*define\s+(?:internal\s+)?[^@]*@"?([\w.$-]+)"?\s*\(') 166TRIPLE_IR_RE = re.compile(r'^\s*target\s+triple\s*=\s*"([^"]+)"$') 167TRIPLE_ARG_RE = re.compile(r'-mtriple[= ]([^ ]+)') 168MARCH_ARG_RE = re.compile(r'-march[= ]([^ ]+)') 169 170SCRUB_LEADING_WHITESPACE_RE = re.compile(r'^(\s+)') 171SCRUB_WHITESPACE_RE = re.compile(r'(?!^(| \w))[ \t]+', flags=re.M) 172SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M) 173SCRUB_TRAILING_WHITESPACE_TEST_RE = SCRUB_TRAILING_WHITESPACE_RE 174SCRUB_TRAILING_WHITESPACE_AND_ATTRIBUTES_RE = re.compile(r'([ \t]|(#[0-9]+))+$', flags=re.M) 175SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n') 176SCRUB_LOOP_COMMENT_RE = re.compile( 177 r'# =>This Inner Loop Header:.*|# in Loop:.*', flags=re.M) 178SCRUB_TAILING_COMMENT_TOKEN_RE = re.compile(r'(?<=\S)+[ \t]*#$', flags=re.M) 179 180 181def error(msg, test_file=None): 182 if test_file: 183 msg = '{}: {}'.format(msg, test_file) 184 print('ERROR: {}'.format(msg), file=sys.stderr) 185 186def warn(msg, test_file=None): 187 if test_file: 188 msg = '{}: {}'.format(msg, test_file) 189 print('WARNING: {}'.format(msg), file=sys.stderr) 190 191def debug(*args, **kwargs): 192 # Python2 does not allow def debug(*args, file=sys.stderr, **kwargs): 193 if 'file' not in kwargs: 194 kwargs['file'] = sys.stderr 195 if _verbose: 196 print(*args, **kwargs) 197 198def find_run_lines(test, lines): 199 debug('Scanning for RUN lines in test file:', test) 200 raw_lines = [m.group(1) 201 for m in [RUN_LINE_RE.match(l) for l in lines] if m] 202 run_lines = [raw_lines[0]] if len(raw_lines) > 0 else [] 203 for l in raw_lines[1:]: 204 if run_lines[-1].endswith('\\'): 205 run_lines[-1] = run_lines[-1].rstrip('\\') + ' ' + l 206 else: 207 run_lines.append(l) 208 debug('Found {} RUN lines in {}:'.format(len(run_lines), test)) 209 for l in run_lines: 210 debug(' RUN: {}'.format(l)) 211 return run_lines 212 213def scrub_body(body): 214 # Scrub runs of whitespace out of the assembly, but leave the leading 215 # whitespace in place. 216 body = SCRUB_WHITESPACE_RE.sub(r' ', body) 217 # Expand the tabs used for indentation. 218 body = string.expandtabs(body, 2) 219 # Strip trailing whitespace. 220 body = SCRUB_TRAILING_WHITESPACE_TEST_RE.sub(r'', body) 221 return body 222 223def do_scrub(body, scrubber, scrubber_args, extra): 224 if scrubber_args: 225 local_args = copy.deepcopy(scrubber_args) 226 local_args[0].extra_scrub = extra 227 return scrubber(body, *local_args) 228 return scrubber(body, *scrubber_args) 229 230# Build up a dictionary of all the function bodies. 231class function_body(object): 232 def __init__(self, string, extra, args_and_sig, attrs): 233 self.scrub = string 234 self.extrascrub = extra 235 self.args_and_sig = args_and_sig 236 self.attrs = attrs 237 def is_same_except_arg_names(self, extrascrub, args_and_sig, attrs): 238 arg_names = set() 239 def drop_arg_names(match): 240 arg_names.add(match.group(3)) 241 return match.group(1) + match.group(match.lastindex) 242 def repl_arg_names(match): 243 if match.group(3) is not None and match.group(3) in arg_names: 244 return match.group(1) + match.group(match.lastindex) 245 return match.group(1) + match.group(2) + match.group(match.lastindex) 246 if self.attrs != attrs: 247 return False 248 ans0 = IR_VALUE_RE.sub(drop_arg_names, self.args_and_sig) 249 ans1 = IR_VALUE_RE.sub(drop_arg_names, args_and_sig) 250 if ans0 != ans1: 251 return False 252 es0 = IR_VALUE_RE.sub(repl_arg_names, self.extrascrub) 253 es1 = IR_VALUE_RE.sub(repl_arg_names, extrascrub) 254 es0 = SCRUB_IR_COMMENT_RE.sub(r'', es0) 255 es1 = SCRUB_IR_COMMENT_RE.sub(r'', es1) 256 return es0 == es1 257 258 def __str__(self): 259 return self.scrub 260 261def build_function_body_dictionary(function_re, scrubber, scrubber_args, raw_tool_output, prefixes, func_dict, func_order, verbose, record_args, check_attributes): 262 for m in function_re.finditer(raw_tool_output): 263 if not m: 264 continue 265 func = m.group('func') 266 body = m.group('body') 267 attrs = m.group('attrs') if check_attributes else '' 268 # Determine if we print arguments, the opening brace, or nothing after the function name 269 if record_args and 'args_and_sig' in m.groupdict(): 270 args_and_sig = scrub_body(m.group('args_and_sig').strip()) 271 elif 'args_and_sig' in m.groupdict(): 272 args_and_sig = '(' 273 else: 274 args_and_sig = '' 275 scrubbed_body = do_scrub(body, scrubber, scrubber_args, extra = False) 276 scrubbed_extra = do_scrub(body, scrubber, scrubber_args, extra = True) 277 if 'analysis' in m.groupdict(): 278 analysis = m.group('analysis') 279 if analysis.lower() != 'cost model analysis': 280 warn('Unsupported analysis mode: %r!' % (analysis,)) 281 if func.startswith('stress'): 282 # We only use the last line of the function body for stress tests. 283 scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:]) 284 if verbose: 285 print('Processing function: ' + func, file=sys.stderr) 286 for l in scrubbed_body.splitlines(): 287 print(' ' + l, file=sys.stderr) 288 for prefix in prefixes: 289 if func in func_dict[prefix]: 290 if str(func_dict[prefix][func]) != scrubbed_body or (func_dict[prefix][func] and (func_dict[prefix][func].args_and_sig != args_and_sig or func_dict[prefix][func].attrs != attrs)): 291 if func_dict[prefix][func] and func_dict[prefix][func].is_same_except_arg_names(scrubbed_extra, args_and_sig, attrs): 292 func_dict[prefix][func].scrub = scrubbed_extra 293 func_dict[prefix][func].args_and_sig = args_and_sig 294 continue 295 else: 296 if prefix == prefixes[-1]: 297 warn('Found conflicting asm under the same prefix: %r!' % (prefix,)) 298 else: 299 func_dict[prefix][func] = None 300 continue 301 302 func_dict[prefix][func] = function_body(scrubbed_body, scrubbed_extra, args_and_sig, attrs) 303 func_order[prefix].append(func) 304 305##### Generator of LLVM IR CHECK lines 306 307SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*') 308 309# TODO: We should also derive check lines for global, debug, loop declarations, etc.. 310 311class NamelessValue: 312 def __init__(self, check_prefix, ir_prefix, ir_regexp): 313 self.check_prefix = check_prefix 314 self.ir_prefix = ir_prefix 315 self.ir_regexp = ir_regexp 316 317# Description of the different "unnamed" values we match in the IR, e.g., 318# (local) ssa values, (debug) metadata, etc. 319nameless_values = [ 320 NamelessValue(r'TMP', r'%', r'[\w.-]+?'), 321 NamelessValue(r'GLOB', r'@', r'[0-9]+?'), 322 NamelessValue(r'ATTR', r'#', r'[0-9]+?'), 323 NamelessValue(r'DBG', r'!dbg !', r'[0-9]+?'), 324 NamelessValue(r'TBAA', r'!tbaa !', r'[0-9]+?'), 325 NamelessValue(r'RNG', r'!range !', r'[0-9]+?'), 326 NamelessValue(r'LOOP', r'!llvm.loop !', r'[0-9]+?'), 327 NamelessValue(r'META', r'metadata !', r'[0-9]+?'), 328] 329 330# Build the regexp that matches an "IR value". This can be a local variable, 331# argument, global, or metadata, anything that is "named". It is important that 332# the PREFIX and SUFFIX below only contain a single group, if that changes 333# other locations will need adjustment as well. 334IR_VALUE_REGEXP_PREFIX = r'(\s+)' 335IR_VALUE_REGEXP_STRING = r'' 336for nameless_value in nameless_values: 337 if IR_VALUE_REGEXP_STRING: 338 IR_VALUE_REGEXP_STRING += '|' 339 IR_VALUE_REGEXP_STRING += nameless_value.ir_prefix + r'(' + nameless_value.ir_regexp + r')' 340IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)' 341IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX) 342 343# The entire match is group 0, the prefix has one group (=1), the entire 344# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start. 345first_nameless_group_in_ir_value_match = 3 346 347# Check a match for IR_VALUE_RE and inspect it to determine if it was a local 348# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above. 349def get_idx_from_ir_value_match(match): 350 for i in range(first_nameless_group_in_ir_value_match, match.lastindex): 351 if match.group(i) is not None: 352 return i - first_nameless_group_in_ir_value_match 353 error("Unable to identify the kind of IR value from the match!") 354 return 0; 355 356# See get_idx_from_ir_value_match 357def get_name_from_ir_value_match(match): 358 return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match) 359 360# Return the nameless prefix we use for this kind or IR value, see also 361# get_idx_from_ir_value_match 362def get_nameless_check_prefix_from_ir_value_match(match): 363 return nameless_values[get_idx_from_ir_value_match(match)].check_prefix 364 365# Return the IR prefix we use for this kind or IR value, e.g., % for locals, 366# see also get_idx_from_ir_value_match 367def get_ir_prefix_from_ir_value_match(match): 368 return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix 369 370# Return true if this kind or IR value is "local", basically if it matches '%{{.*}}'. 371def is_local_ir_value_match(match): 372 return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%' 373 374# Create a FileCheck variable name based on an IR name. 375def get_value_name(var, match): 376 if var.isdigit(): 377 var = get_nameless_check_prefix_from_ir_value_match(match) + var 378 var = var.replace('.', '_') 379 var = var.replace('-', '_') 380 return var.upper() 381 382# Create a FileCheck variable from regex. 383def get_value_definition(var, match): 384 return '[[' + get_value_name(var, match) + ':' + get_ir_prefix_from_ir_value_match(match) + '.*]]' 385 386# Use a FileCheck variable. 387def get_value_use(var, match): 388 return '[[' + get_value_name(var, match) + ']]' 389 390# Replace IR value defs and uses with FileCheck variables. 391def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen): 392 # This gets called for each match that occurs in 393 # a line. We transform variables we haven't seen 394 # into defs, and variables we have seen into uses. 395 def transform_line_vars(match): 396 pre = get_ir_prefix_from_ir_value_match(match) 397 var = get_name_from_ir_value_match(match) 398 for nameless_value in nameless_values: 399 if re.match(r'^' + nameless_value.check_prefix + r'[0-9]+?$', var, re.IGNORECASE): 400 warn("Change IR value name '%s' to prevent possible conflict with scripted FileCheck name." % (var,)) 401 if (pre, var) in vars_seen or (pre, var) in global_vars_seen: 402 rv = get_value_use(var, match) 403 else: 404 if is_local_ir_value_match(match): 405 vars_seen.add((pre, var)) 406 else: 407 global_vars_seen.add((pre, var)) 408 rv = get_value_definition(var, match) 409 # re.sub replaces the entire regex match 410 # with whatever you return, so we have 411 # to make sure to hand it back everything 412 # including the commas and spaces. 413 return match.group(1) + rv + match.group(match.lastindex) 414 415 lines_with_def = [] 416 417 for i, line in enumerate(lines): 418 # An IR variable named '%.' matches the FileCheck regex string. 419 line = line.replace('%.', '%dot') 420 # Ignore any comments, since the check lines will too. 421 scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line) 422 lines[i] = scrubbed_line 423 if not is_analyze: 424 # It can happen that two matches are back-to-back and for some reason sub 425 # will not replace both of them. For now we work around this by 426 # substituting until there is no more match. 427 changed = True 428 while changed: 429 (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1) 430 return lines 431 432 433def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict): 434 # 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. 435 prefix_exclusions = set() 436 printed_prefixes = [] 437 for p in prefix_list: 438 checkprefixes = p[0] 439 # If not all checkprefixes of this run line produced the function we cannot check for it as it does not 440 # exist for this run line. A subset of the check prefixes might know about the function but only because 441 # other run lines created it. 442 if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)): 443 prefix_exclusions |= set(checkprefixes) 444 continue 445 446 # prefix_exclusions is constructed, we can now emit the output 447 for p in prefix_list: 448 checkprefixes = p[0] 449 for checkprefix in checkprefixes: 450 if checkprefix in printed_prefixes: 451 break 452 453 # Check if the prefix is excluded. 454 if checkprefix in prefix_exclusions: 455 continue 456 457 # If we do not have output for this prefix we skip it. 458 if not func_dict[checkprefix][func_name]: 459 continue 460 461 # Add some space between different check prefixes, but not after the last 462 # check line (before the test code). 463 if is_asm: 464 if len(printed_prefixes) != 0: 465 output_lines.append(comment_marker) 466 467 if checkprefix not in global_vars_seen_dict: 468 global_vars_seen_dict[checkprefix] = set() 469 global_vars_seen = global_vars_seen_dict[checkprefix] 470 471 vars_seen = set() 472 printed_prefixes.append(checkprefix) 473 attrs = str(func_dict[checkprefix][func_name].attrs) 474 attrs = '' if attrs == 'None' else attrs 475 if attrs: 476 output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs)) 477 args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig) 478 args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0] 479 if '[[' in args_and_sig: 480 output_lines.append(check_label_format % (checkprefix, func_name, '')) 481 output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig)) 482 else: 483 output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig)) 484 func_body = str(func_dict[checkprefix][func_name]).splitlines() 485 486 # For ASM output, just emit the check lines. 487 if is_asm: 488 output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 489 for func_line in func_body[1:]: 490 if func_line.strip() == '': 491 output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix)) 492 else: 493 output_lines.append('%s %s-NEXT: %s' % (comment_marker, checkprefix, func_line)) 494 break 495 496 # For IR output, change all defs to FileCheck variables, so we're immune 497 # to variable naming fashions. 498 func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen) 499 500 # This could be selectively enabled with an optional invocation argument. 501 # Disabled for now: better to check everything. Be safe rather than sorry. 502 503 # Handle the first line of the function body as a special case because 504 # it's often just noise (a useless asm comment or entry label). 505 #if func_body[0].startswith("#") or func_body[0].startswith("entry:"): 506 # is_blank_line = True 507 #else: 508 # output_lines.append('%s %s: %s' % (comment_marker, checkprefix, func_body[0])) 509 # is_blank_line = False 510 511 is_blank_line = False 512 513 for func_line in func_body: 514 if func_line.strip() == '': 515 is_blank_line = True 516 continue 517 # Do not waste time checking IR comments. 518 func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line) 519 520 # Skip blank lines instead of checking them. 521 if is_blank_line: 522 output_lines.append('{} {}: {}'.format( 523 comment_marker, checkprefix, func_line)) 524 else: 525 output_lines.append('{} {}-NEXT: {}'.format( 526 comment_marker, checkprefix, func_line)) 527 is_blank_line = False 528 529 # Add space between different check prefixes and also before the first 530 # line of code in the test function. 531 output_lines.append(comment_marker) 532 break 533 534def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict, 535 func_name, preserve_names, function_sig, global_vars_seen_dict): 536 # Label format is based on IR string. 537 function_def_regex = 'define {{[^@]+}}' if function_sig else '' 538 check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex) 539 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 540 check_label_format, False, preserve_names, global_vars_seen_dict) 541 542def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name): 543 check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker) 544 global_vars_seen_dict = {} 545 add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, 546 check_label_format, False, True, global_vars_seen_dict) 547 548 549def check_prefix(prefix): 550 if not PREFIX_RE.match(prefix): 551 hint = "" 552 if ',' in prefix: 553 hint = " Did you mean '--check-prefixes=" + prefix + "'?" 554 warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) % 555 (prefix)) 556 557 558def verify_filecheck_prefixes(fc_cmd): 559 fc_cmd_parts = fc_cmd.split() 560 for part in fc_cmd_parts: 561 if "check-prefix=" in part: 562 prefix = part.split('=', 1)[1] 563 check_prefix(prefix) 564 elif "check-prefixes=" in part: 565 prefixes = part.split('=', 1)[1].split(',') 566 for prefix in prefixes: 567 check_prefix(prefix) 568 if prefixes.count(prefix) > 1: 569 warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,)) 570 571 572def get_autogennote_suffix(parser, args): 573 autogenerated_note_args = '' 574 for action in parser._actions: 575 if not hasattr(args, action.dest): 576 continue # Ignore options such as --help that aren't included in args 577 # Ignore parameters such as paths to the binary or the list of tests 578 if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary', 579 'clang', 'opt', 'llvm_bin', 'verbose'): 580 continue 581 value = getattr(args, action.dest) 582 if action.const is not None: # action stores a constant (usually True/False) 583 # Skip actions with different constant values (this happens with boolean 584 # --foo/--no-foo options) 585 if value != action.const: 586 continue 587 if parser.get_default(action.dest) == value: 588 continue # Don't add default values 589 autogenerated_note_args += action.option_strings[0] + ' ' 590 if action.const is None: # action takes a parameter 591 autogenerated_note_args += '%s ' % value 592 if autogenerated_note_args: 593 autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1]) 594 return autogenerated_note_args 595 596 597def check_for_command(line, parser, args, argv, argparse_callback): 598 cmd_m = UTC_ARGS_CMD.match(line) 599 if cmd_m: 600 cmd = cmd_m.group('cmd').strip().split(' ') 601 argv = argv + cmd 602 args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv)) 603 if argparse_callback is not None: 604 argparse_callback(args) 605 return args, argv 606 607def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global): 608 result = get_arg_to_check(test_info.args) 609 if not result and is_global: 610 # See if this has been specified via UTC_ARGS. This is a "global" option 611 # that affects the entire generation of test checks. If it exists anywhere 612 # in the test, apply it to everything. 613 saw_line = False 614 for line_info in test_info.ro_iterlines(): 615 line = line_info.line 616 if not line.startswith(';') and line.strip() != '': 617 saw_line = True 618 result = get_arg_to_check(line_info.args) 619 if result: 620 if warn and saw_line: 621 # We saw the option after already reading some test input lines. 622 # Warn about it. 623 print('WARNING: Found {} in line following test start: '.format(arg_string) 624 + line, file=sys.stderr) 625 print('WARNING: Consider moving {} to top of file'.format(arg_string), 626 file=sys.stderr) 627 break 628 return result 629 630def dump_input_lines(output_lines, test_info, prefix_set, comment_string): 631 for input_line_info in test_info.iterlines(output_lines): 632 line = input_line_info.line 633 args = input_line_info.args 634 if line.strip() == comment_string: 635 continue 636 if line.lstrip().startswith(comment_string): 637 m = CHECK_RE.match(line) 638 if m and m.group(1) in prefix_set: 639 continue 640 output_lines.append(line.rstrip('\n')) 641 642def add_checks_at_end(output_lines, prefix_list, func_order, 643 comment_string, check_generator): 644 added = set() 645 for prefix in prefix_list: 646 prefixes = prefix[0] 647 tool_args = prefix[1] 648 for prefix in prefixes: 649 for func in func_order[prefix]: 650 if added: 651 output_lines.append(comment_string) 652 added.add(func) 653 654 # The add_*_checks routines expect a run list whose items are 655 # tuples that have a list of prefixes as their first element and 656 # tool command args string as their second element. They output 657 # checks for each prefix in the list of prefixes. By doing so, it 658 # implicitly assumes that for each function every run line will 659 # generate something for that function. That is not the case for 660 # generated functions as some run lines might not generate them 661 # (e.g. -fopenmp vs. no -fopenmp). 662 # 663 # Therefore, pass just the prefix we're interested in. This has 664 # the effect of generating all of the checks for functions of a 665 # single prefix before moving on to the next prefix. So checks 666 # are ordered by prefix instead of by function as in "normal" 667 # mode. 668 check_generator(output_lines, 669 [([prefix], tool_args)], 670 func) 671