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