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