xref: /netbsd-src/external/apache2/llvm/dist/llvm/utils/UpdateTestChecks/common.py (revision 82d56013d7b633d116a93943de88e08335357a7c)
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):
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    # Strip double-quotes if input was read by UTC_ARGS
300    self._replace_value_regex = list(map(lambda x: x.strip('"'), flags.replace_value_regex))
301    self._func_dict = {}
302    self._func_order = {}
303    self._global_var_dict = {}
304    for tuple in run_list:
305      for prefix in tuple[0]:
306        self._func_dict.update({prefix:dict()})
307        self._func_order.update({prefix: []})
308        self._global_var_dict.update({prefix:dict()})
309
310  def finish_and_get_func_dict(self):
311    for prefix in self._get_failed_prefixes():
312      warn('Prefix %s had conflicting output from different RUN lines for all functions' % (prefix,))
313    return self._func_dict
314
315  def func_order(self):
316    return self._func_order
317
318  def global_var_dict(self):
319    return self._global_var_dict
320
321  def process_run_line(self, function_re, scrubber, raw_tool_output, prefixes):
322    build_global_values_dictionary(self._global_var_dict, raw_tool_output, prefixes)
323    for m in function_re.finditer(raw_tool_output):
324      if not m:
325        continue
326      func = m.group('func')
327      body = m.group('body')
328      attrs = m.group('attrs') if self._check_attributes else ''
329      # Determine if we print arguments, the opening brace, or nothing after the
330      # function name
331      if self._record_args and 'args_and_sig' in m.groupdict():
332          args_and_sig = scrub_body(m.group('args_and_sig').strip())
333      elif 'args_and_sig' in m.groupdict():
334          args_and_sig = '('
335      else:
336          args_and_sig = ''
337      scrubbed_body = do_scrub(body, scrubber, self._scrubber_args,
338                               extra=False)
339      scrubbed_extra = do_scrub(body, scrubber, self._scrubber_args,
340                                extra=True)
341      if 'analysis' in m.groupdict():
342        analysis = m.group('analysis')
343        if analysis.lower() != 'cost model analysis':
344          warn('Unsupported analysis mode: %r!' % (analysis,))
345      if func.startswith('stress'):
346        # We only use the last line of the function body for stress tests.
347        scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
348      if self._verbose:
349        print('Processing function: ' + func, file=sys.stderr)
350        for l in scrubbed_body.splitlines():
351          print('  ' + l, file=sys.stderr)
352      for prefix in prefixes:
353        if func in self._func_dict[prefix]:
354          if (self._func_dict[prefix][func] is None or
355              str(self._func_dict[prefix][func]) != scrubbed_body or
356              self._func_dict[prefix][func].args_and_sig != args_and_sig or
357                  self._func_dict[prefix][func].attrs != attrs):
358            if (self._func_dict[prefix][func] is not None and
359                self._func_dict[prefix][func].is_same_except_arg_names(
360                scrubbed_extra,
361                args_and_sig,
362                attrs)):
363              self._func_dict[prefix][func].scrub = scrubbed_extra
364              self._func_dict[prefix][func].args_and_sig = args_and_sig
365              continue
366            else:
367              # This means a previous RUN line produced a body for this function
368              # that is different from the one produced by this current RUN line,
369              # so the body can't be common accross RUN lines. We use None to
370              # indicate that.
371              self._func_dict[prefix][func] = None
372              continue
373
374        # Replace function names matching the regex.
375        for regex in self._replace_value_regex:
376          # Pattern that matches capture groups in the regex in leftmost order.
377          group_regex = re.compile('\(.*?\)')
378          # Replace function name with regex.
379          match = re.match(regex, func)
380          if match:
381            func_repl = regex
382            # Replace any capture groups with their matched strings.
383            for g in match.groups():
384              func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
385            func = re.sub(func_repl, '{{' + func_repl + '}}', func)
386
387          # Replace all calls to regex matching functions.
388          matches = re.finditer(regex, scrubbed_body)
389          for match in matches:
390            func_repl = regex
391            # Replace any capture groups with their matched strings.
392            for g in match.groups():
393                func_repl = group_regex.sub(re.escape(g), func_repl, count=1)
394            # Substitute function call names that match the regex with the same
395            # capture groups set.
396            scrubbed_body = re.sub(func_repl, '{{' + func_repl + '}}', scrubbed_body)
397
398        self._func_dict[prefix][func] = function_body(
399            scrubbed_body, scrubbed_extra, args_and_sig, attrs)
400        self._func_order[prefix].append(func)
401
402  def _get_failed_prefixes(self):
403    # This returns the list of those prefixes that failed to match any function,
404    # because there were conflicting bodies produced by different RUN lines, in
405    # all instances of the prefix. Effectively, this prefix is unused and should
406    # be removed.
407    for prefix in self._func_dict:
408      if (self._func_dict[prefix] and
409          (not [fct for fct in self._func_dict[prefix]
410                if self._func_dict[prefix][fct] is not None])):
411        yield prefix
412
413
414##### Generator of LLVM IR CHECK lines
415
416SCRUB_IR_COMMENT_RE = re.compile(r'\s*;.*')
417
418# TODO: We should also derive check lines for global, debug, loop declarations, etc..
419
420class NamelessValue:
421    def __init__(self, check_prefix, check_key, ir_prefix, global_ir_prefix, global_ir_prefix_regexp,
422                 ir_regexp, global_ir_rhs_regexp, is_before_functions):
423        self.check_prefix = check_prefix
424        self.check_key = check_key
425        self.ir_prefix = ir_prefix
426        self.global_ir_prefix = global_ir_prefix
427        self.global_ir_prefix_regexp = global_ir_prefix_regexp
428        self.ir_regexp = ir_regexp
429        self.global_ir_rhs_regexp = global_ir_rhs_regexp
430        self.is_before_functions = is_before_functions
431
432# Description of the different "unnamed" values we match in the IR, e.g.,
433# (local) ssa values, (debug) metadata, etc.
434nameless_values = [
435    NamelessValue(r'TMP'  , '%' , r'%'           , None            , None                   , r'[\w$.-]+?' , None                 , False) ,
436    NamelessValue(r'ATTR' , '#' , r'#'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
437    NamelessValue(r'ATTR' , '#' , None           , r'attributes #' , r'[0-9]+'              , None         , r'{[^}]*}'           , False) ,
438    NamelessValue(r'GLOB' , '@' , r'@'           , None            , None                   , r'[0-9]+'    , None                 , False) ,
439    NamelessValue(r'GLOB' , '@' , None           , r'@'            , r'[a-zA-Z0-9_$"\\.-]+' , None         , r'.+'                , True)  ,
440    NamelessValue(r'DBG'  , '!' , r'!dbg '       , None            , None                   , r'![0-9]+'   , None                 , False) ,
441    NamelessValue(r'PROF' , '!' , r'!prof '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
442    NamelessValue(r'TBAA' , '!' , r'!tbaa '      , None            , None                   , r'![0-9]+'   , None                 , False) ,
443    NamelessValue(r'RNG'  , '!' , r'!range '     , None            , None                   , r'![0-9]+'   , None                 , False) ,
444    NamelessValue(r'LOOP' , '!' , r'!llvm.loop ' , None            , None                   , r'![0-9]+'   , None                 , False) ,
445    NamelessValue(r'META' , '!' , r'metadata '   , None            , None                   , r'![0-9]+'   , None                 , False) ,
446    NamelessValue(r'META' , '!' , None           , r''             , r'![0-9]+'             , None         , r'(?:distinct |)!.*' , False) ,
447]
448
449def createOrRegexp(old, new):
450    if not old:
451        return new
452    if not new:
453        return old
454    return old + '|' + new
455
456def createPrefixMatch(prefix_str, prefix_re):
457    if prefix_str is None or prefix_re is None:
458        return ''
459    return '(?:' + prefix_str + '(' + prefix_re + '))'
460
461# Build the regexp that matches an "IR value". This can be a local variable,
462# argument, global, or metadata, anything that is "named". It is important that
463# the PREFIX and SUFFIX below only contain a single group, if that changes
464# other locations will need adjustment as well.
465IR_VALUE_REGEXP_PREFIX = r'(\s*)'
466IR_VALUE_REGEXP_STRING = r''
467for nameless_value in nameless_values:
468    lcl_match = createPrefixMatch(nameless_value.ir_prefix, nameless_value.ir_regexp)
469    glb_match = createPrefixMatch(nameless_value.global_ir_prefix, nameless_value.global_ir_prefix_regexp)
470    assert((lcl_match or glb_match) and not (lcl_match and glb_match))
471    if lcl_match:
472        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, lcl_match)
473    elif glb_match:
474        IR_VALUE_REGEXP_STRING = createOrRegexp(IR_VALUE_REGEXP_STRING, '^' + glb_match)
475IR_VALUE_REGEXP_SUFFIX = r'([,\s\(\)]|\Z)'
476IR_VALUE_RE = re.compile(IR_VALUE_REGEXP_PREFIX + r'(' + IR_VALUE_REGEXP_STRING + r')' + IR_VALUE_REGEXP_SUFFIX)
477
478# The entire match is group 0, the prefix has one group (=1), the entire
479# IR_VALUE_REGEXP_STRING is one group (=2), and then the nameless values start.
480first_nameless_group_in_ir_value_match = 3
481
482# constants for the group id of special matches
483variable_group_in_ir_value_match = 3
484attribute_group_in_ir_value_match = 4
485
486# Check a match for IR_VALUE_RE and inspect it to determine if it was a local
487# value, %..., global @..., debug number !dbg !..., etc. See the PREFIXES above.
488def get_idx_from_ir_value_match(match):
489    for i in range(first_nameless_group_in_ir_value_match, match.lastindex):
490        if match.group(i) is not None:
491            return i - first_nameless_group_in_ir_value_match
492    error("Unable to identify the kind of IR value from the match!")
493    return 0
494
495# See get_idx_from_ir_value_match
496def get_name_from_ir_value_match(match):
497    return match.group(get_idx_from_ir_value_match(match) + first_nameless_group_in_ir_value_match)
498
499# Return the nameless prefix we use for this kind or IR value, see also
500# get_idx_from_ir_value_match
501def get_nameless_check_prefix_from_ir_value_match(match):
502    return nameless_values[get_idx_from_ir_value_match(match)].check_prefix
503
504# Return the IR prefix and check prefix we use for this kind or IR value, e.g., (%, TMP) for locals,
505# see also get_idx_from_ir_value_match
506def get_ir_prefix_from_ir_value_match(match):
507    idx = get_idx_from_ir_value_match(match)
508    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
509        return nameless_values[idx].ir_prefix, nameless_values[idx].check_prefix
510    return nameless_values[idx].global_ir_prefix, nameless_values[idx].check_prefix
511
512def get_check_key_from_ir_value_match(match):
513    idx = get_idx_from_ir_value_match(match)
514    return nameless_values[idx].check_key
515
516# Return the IR regexp we use for this kind or IR value, e.g., [\w.-]+? for locals,
517# see also get_idx_from_ir_value_match
518def get_ir_prefix_from_ir_value_re_match(match):
519    # for backwards compatibility we check locals with '.*'
520    if is_local_def_ir_value_match(match):
521        return '.*'
522    idx = get_idx_from_ir_value_match(match)
523    if nameless_values[idx].ir_prefix and match.group(0).strip().startswith(nameless_values[idx].ir_prefix):
524        return nameless_values[idx].ir_regexp
525    return nameless_values[idx].global_ir_prefix_regexp
526
527# Return true if this kind of IR value is "local", basically if it matches '%{{.*}}'.
528def is_local_def_ir_value_match(match):
529    return nameless_values[get_idx_from_ir_value_match(match)].ir_prefix == '%'
530
531# Return true if this kind of IR value is "global", basically if it matches '#{{.*}}'.
532def is_global_scope_ir_value_match(match):
533    return nameless_values[get_idx_from_ir_value_match(match)].global_ir_prefix is not None
534
535# Return true if var clashes with the scripted FileCheck check_prefix.
536def may_clash_with_default_check_prefix_name(check_prefix, var):
537  return check_prefix and re.match(r'^' + check_prefix + r'[0-9]+?$', var, re.IGNORECASE)
538
539# Create a FileCheck variable name based on an IR name.
540def get_value_name(var, check_prefix):
541  var = var.replace('!', '')
542  # This is a nameless value, prepend check_prefix.
543  if var.isdigit():
544    var = check_prefix + var
545  else:
546    # This is a named value that clashes with the check_prefix, prepend with _prefix_filecheck_ir_name,
547    # if it has been defined.
548    if may_clash_with_default_check_prefix_name(check_prefix, var) and _prefix_filecheck_ir_name:
549      var = _prefix_filecheck_ir_name + var
550  var = var.replace('.', '_')
551  var = var.replace('-', '_')
552  return var.upper()
553
554# Create a FileCheck variable from regex.
555def get_value_definition(var, match):
556  # for backwards compatibility we check locals with '.*'
557  if is_local_def_ir_value_match(match):
558    return '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + \
559            get_ir_prefix_from_ir_value_match(match)[0] + get_ir_prefix_from_ir_value_re_match(match) + ']]'
560  prefix = get_ir_prefix_from_ir_value_match(match)[0]
561  return prefix + '[[' + get_value_name(var, get_nameless_check_prefix_from_ir_value_match(match)) + ':' + get_ir_prefix_from_ir_value_re_match(match) + ']]'
562
563# Use a FileCheck variable.
564def get_value_use(var, match, check_prefix):
565  if is_local_def_ir_value_match(match):
566    return '[[' + get_value_name(var, check_prefix) + ']]'
567  prefix = get_ir_prefix_from_ir_value_match(match)[0]
568  return prefix + '[[' + get_value_name(var, check_prefix) + ']]'
569
570# Replace IR value defs and uses with FileCheck variables.
571def generalize_check_lines(lines, is_analyze, vars_seen, global_vars_seen):
572  # This gets called for each match that occurs in
573  # a line. We transform variables we haven't seen
574  # into defs, and variables we have seen into uses.
575  def transform_line_vars(match):
576    pre, check = get_ir_prefix_from_ir_value_match(match)
577    var = get_name_from_ir_value_match(match)
578    for nameless_value in nameless_values:
579        if may_clash_with_default_check_prefix_name(nameless_value.check_prefix, var):
580          warn("Change IR value name '%s' or use -prefix-ir-filecheck-name to prevent possible conflict"
581            " with scripted FileCheck name." % (var,))
582    key = (var, get_check_key_from_ir_value_match(match))
583    is_local_def = is_local_def_ir_value_match(match)
584    if is_local_def and key in vars_seen:
585      rv = get_value_use(var, match, get_nameless_check_prefix_from_ir_value_match(match))
586    elif not is_local_def and key in global_vars_seen:
587      rv = get_value_use(var, match, global_vars_seen[key])
588    else:
589      if is_local_def:
590         vars_seen.add(key)
591      else:
592         global_vars_seen[key] = get_nameless_check_prefix_from_ir_value_match(match)
593      rv = get_value_definition(var, match)
594    # re.sub replaces the entire regex match
595    # with whatever you return, so we have
596    # to make sure to hand it back everything
597    # including the commas and spaces.
598    return match.group(1) + rv + match.group(match.lastindex)
599
600  lines_with_def = []
601
602  for i, line in enumerate(lines):
603    # An IR variable named '%.' matches the FileCheck regex string.
604    line = line.replace('%.', '%dot')
605    # Ignore any comments, since the check lines will too.
606    scrubbed_line = SCRUB_IR_COMMENT_RE.sub(r'', line)
607    lines[i] = scrubbed_line
608    if not is_analyze:
609      # It can happen that two matches are back-to-back and for some reason sub
610      # will not replace both of them. For now we work around this by
611      # substituting until there is no more match.
612      changed = True
613      while changed:
614          (lines[i], changed) = IR_VALUE_RE.subn(transform_line_vars, lines[i], count=1)
615  return lines
616
617
618def add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name, check_label_format, is_asm, is_analyze, global_vars_seen_dict):
619  # 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.
620  prefix_exclusions = set()
621  printed_prefixes = []
622  for p in prefix_list:
623    checkprefixes = p[0]
624    # If not all checkprefixes of this run line produced the function we cannot check for it as it does not
625    # exist for this run line. A subset of the check prefixes might know about the function but only because
626    # other run lines created it.
627    if any(map(lambda checkprefix: func_name not in func_dict[checkprefix], checkprefixes)):
628        prefix_exclusions |= set(checkprefixes)
629        continue
630
631  # prefix_exclusions is constructed, we can now emit the output
632  for p in prefix_list:
633    global_vars_seen = {}
634    checkprefixes = p[0]
635    for checkprefix in checkprefixes:
636      if checkprefix in global_vars_seen_dict:
637        global_vars_seen.update(global_vars_seen_dict[checkprefix])
638      else:
639        global_vars_seen_dict[checkprefix] = {}
640      if checkprefix in printed_prefixes:
641        break
642
643      # Check if the prefix is excluded.
644      if checkprefix in prefix_exclusions:
645        continue
646
647      # If we do not have output for this prefix we skip it.
648      if not func_dict[checkprefix][func_name]:
649        continue
650
651      # Add some space between different check prefixes, but not after the last
652      # check line (before the test code).
653      if is_asm:
654        if len(printed_prefixes) != 0:
655          output_lines.append(comment_marker)
656
657      if checkprefix not in global_vars_seen_dict:
658          global_vars_seen_dict[checkprefix] = {}
659
660      global_vars_seen_before = [key for key in global_vars_seen.keys()]
661
662      vars_seen = set()
663      printed_prefixes.append(checkprefix)
664      attrs = str(func_dict[checkprefix][func_name].attrs)
665      attrs = '' if attrs == 'None' else attrs
666      if attrs:
667        output_lines.append('%s %s: Function Attrs: %s' % (comment_marker, checkprefix, attrs))
668      args_and_sig = str(func_dict[checkprefix][func_name].args_and_sig)
669      args_and_sig = generalize_check_lines([args_and_sig], is_analyze, vars_seen, global_vars_seen)[0]
670      if '[[' in args_and_sig:
671        output_lines.append(check_label_format % (checkprefix, func_name, ''))
672        output_lines.append('%s %s-SAME: %s' % (comment_marker, checkprefix, args_and_sig))
673      else:
674        output_lines.append(check_label_format % (checkprefix, func_name, args_and_sig))
675      func_body = str(func_dict[checkprefix][func_name]).splitlines()
676
677      # For ASM output, just emit the check lines.
678      if is_asm:
679        output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
680        for func_line in func_body[1:]:
681          if func_line.strip() == '':
682            output_lines.append('%s %s-EMPTY:' % (comment_marker, checkprefix))
683          else:
684            output_lines.append('%s %s-NEXT:  %s' % (comment_marker, checkprefix, func_line))
685        break
686
687      # For IR output, change all defs to FileCheck variables, so we're immune
688      # to variable naming fashions.
689      func_body = generalize_check_lines(func_body, is_analyze, vars_seen, global_vars_seen)
690
691      # This could be selectively enabled with an optional invocation argument.
692      # Disabled for now: better to check everything. Be safe rather than sorry.
693
694      # Handle the first line of the function body as a special case because
695      # it's often just noise (a useless asm comment or entry label).
696      #if func_body[0].startswith("#") or func_body[0].startswith("entry:"):
697      #  is_blank_line = True
698      #else:
699      #  output_lines.append('%s %s:       %s' % (comment_marker, checkprefix, func_body[0]))
700      #  is_blank_line = False
701
702      is_blank_line = False
703
704      for func_line in func_body:
705        if func_line.strip() == '':
706          is_blank_line = True
707          continue
708        # Do not waste time checking IR comments.
709        func_line = SCRUB_IR_COMMENT_RE.sub(r'', func_line)
710
711        # Skip blank lines instead of checking them.
712        if is_blank_line:
713          output_lines.append('{} {}:       {}'.format(
714              comment_marker, checkprefix, func_line))
715        else:
716          output_lines.append('{} {}-NEXT:  {}'.format(
717              comment_marker, checkprefix, func_line))
718        is_blank_line = False
719
720      # Add space between different check prefixes and also before the first
721      # line of code in the test function.
722      output_lines.append(comment_marker)
723
724      # Remembe new global variables we have not seen before
725      for key in global_vars_seen:
726          if key not in global_vars_seen_before:
727              global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
728      break
729
730def add_ir_checks(output_lines, comment_marker, prefix_list, func_dict,
731                  func_name, preserve_names, function_sig, global_vars_seen_dict):
732  # Label format is based on IR string.
733  function_def_regex = 'define {{[^@]+}}' if function_sig else ''
734  check_label_format = '{} %s-LABEL: {}@%s%s'.format(comment_marker, function_def_regex)
735  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
736             check_label_format, False, preserve_names, global_vars_seen_dict)
737
738def add_analyze_checks(output_lines, comment_marker, prefix_list, func_dict, func_name):
739  check_label_format = '{} %s-LABEL: \'%s%s\''.format(comment_marker)
740  global_vars_seen_dict = {}
741  add_checks(output_lines, comment_marker, prefix_list, func_dict, func_name,
742             check_label_format, False, True, global_vars_seen_dict)
743
744def build_global_values_dictionary(glob_val_dict, raw_tool_output, prefixes):
745  for nameless_value in nameless_values:
746    if nameless_value.global_ir_prefix is None:
747      continue
748
749    lhs_re_str = nameless_value.global_ir_prefix + nameless_value.global_ir_prefix_regexp
750    rhs_re_str = nameless_value.global_ir_rhs_regexp
751
752    global_ir_value_re_str = r'^' + lhs_re_str + r'\s=\s' + rhs_re_str + r'$'
753    global_ir_value_re = re.compile(global_ir_value_re_str, flags=(re.M))
754    lines = []
755    for m in global_ir_value_re.finditer(raw_tool_output):
756        lines.append(m.group(0))
757
758    for prefix in prefixes:
759      if glob_val_dict[prefix] is None:
760        continue
761      if nameless_value.check_prefix in glob_val_dict[prefix]:
762        if lines == glob_val_dict[prefix][nameless_value.check_prefix]:
763          continue
764        if prefix == prefixes[-1]:
765          warn('Found conflicting asm under the same prefix: %r!' % (prefix,))
766        else:
767          glob_val_dict[prefix][nameless_value.check_prefix] = None
768          continue
769      glob_val_dict[prefix][nameless_value.check_prefix] = lines
770
771def add_global_checks(glob_val_dict, comment_marker, prefix_list, output_lines, global_vars_seen_dict, is_analyze, is_before_functions):
772  printed_prefixes = set()
773  for nameless_value in nameless_values:
774    if nameless_value.global_ir_prefix is None:
775        continue
776    if nameless_value.is_before_functions != is_before_functions:
777        continue
778    for p in prefix_list:
779      global_vars_seen = {}
780      checkprefixes = p[0]
781      for checkprefix in checkprefixes:
782        if checkprefix in global_vars_seen_dict:
783            global_vars_seen.update(global_vars_seen_dict[checkprefix])
784        else:
785            global_vars_seen_dict[checkprefix] = {}
786        if (checkprefix, nameless_value.check_prefix) in printed_prefixes:
787          break
788        if not glob_val_dict[checkprefix]:
789          continue
790        if nameless_value.check_prefix not in glob_val_dict[checkprefix]:
791          continue
792        if not glob_val_dict[checkprefix][nameless_value.check_prefix]:
793          continue
794
795        output_lines.append(SEPARATOR)
796
797        global_vars_seen_before = [key for key in global_vars_seen.keys()]
798        for line in glob_val_dict[checkprefix][nameless_value.check_prefix]:
799          tmp = generalize_check_lines([line], is_analyze, set(), global_vars_seen)
800          check_line = '%s %s: %s' % (comment_marker, checkprefix, tmp[0])
801          output_lines.append(check_line)
802        printed_prefixes.add((checkprefix, nameless_value.check_prefix))
803
804        # Remembe new global variables we have not seen before
805        for key in global_vars_seen:
806            if key not in global_vars_seen_before:
807                global_vars_seen_dict[checkprefix][key] = global_vars_seen[key]
808        break
809
810  if printed_prefixes:
811      output_lines.append(SEPARATOR)
812
813
814def check_prefix(prefix):
815  if not PREFIX_RE.match(prefix):
816        hint = ""
817        if ',' in prefix:
818          hint = " Did you mean '--check-prefixes=" + prefix + "'?"
819        warn(("Supplied prefix '%s' is invalid. Prefix must contain only alphanumeric characters, hyphens and underscores." + hint) %
820             (prefix))
821
822
823def verify_filecheck_prefixes(fc_cmd):
824  fc_cmd_parts = fc_cmd.split()
825  for part in fc_cmd_parts:
826    if "check-prefix=" in part:
827      prefix = part.split('=', 1)[1]
828      check_prefix(prefix)
829    elif "check-prefixes=" in part:
830      prefixes = part.split('=', 1)[1].split(',')
831      for prefix in prefixes:
832        check_prefix(prefix)
833        if prefixes.count(prefix) > 1:
834          warn("Supplied prefix '%s' is not unique in the prefix list." % (prefix,))
835
836
837def get_autogennote_suffix(parser, args):
838  autogenerated_note_args = ''
839  for action in parser._actions:
840    if not hasattr(args, action.dest):
841      continue  # Ignore options such as --help that aren't included in args
842    # Ignore parameters such as paths to the binary or the list of tests
843    if action.dest in ('tests', 'update_only', 'opt_binary', 'llc_binary',
844                       'clang', 'opt', 'llvm_bin', 'verbose'):
845      continue
846    value = getattr(args, action.dest)
847    if action.const is not None:  # action stores a constant (usually True/False)
848      # Skip actions with different constant values (this happens with boolean
849      # --foo/--no-foo options)
850      if value != action.const:
851        continue
852    if parser.get_default(action.dest) == value:
853      continue  # Don't add default values
854    autogenerated_note_args += action.option_strings[0] + ' '
855    if action.const is None:  # action takes a parameter
856      if action.nargs == '+':
857        value = ' '.join(map(lambda v: '"' + v.strip('"') + '"', value))
858      autogenerated_note_args += '%s ' % value
859  if autogenerated_note_args:
860    autogenerated_note_args = ' %s %s' % (UTC_ARGS_KEY, autogenerated_note_args[:-1])
861  return autogenerated_note_args
862
863
864def check_for_command(line, parser, args, argv, argparse_callback):
865    cmd_m = UTC_ARGS_CMD.match(line)
866    if cmd_m:
867        for option in cmd_m.group('cmd').strip().split(' '):
868            if option:
869                argv.append(option)
870        args = parser.parse_args(filter(lambda arg: arg not in args.tests, argv))
871        if argparse_callback is not None:
872          argparse_callback(args)
873    return args, argv
874
875def find_arg_in_test(test_info, get_arg_to_check, arg_string, is_global):
876  result = get_arg_to_check(test_info.args)
877  if not result and is_global:
878    # See if this has been specified via UTC_ARGS.  This is a "global" option
879    # that affects the entire generation of test checks.  If it exists anywhere
880    # in the test, apply it to everything.
881    saw_line = False
882    for line_info in test_info.ro_iterlines():
883      line = line_info.line
884      if not line.startswith(';') and line.strip() != '':
885        saw_line = True
886      result = get_arg_to_check(line_info.args)
887      if result:
888        if warn and saw_line:
889          # We saw the option after already reading some test input lines.
890          # Warn about it.
891          print('WARNING: Found {} in line following test start: '.format(arg_string)
892                + line, file=sys.stderr)
893          print('WARNING: Consider moving {} to top of file'.format(arg_string),
894                file=sys.stderr)
895        break
896  return result
897
898def dump_input_lines(output_lines, test_info, prefix_set, comment_string):
899  for input_line_info in test_info.iterlines(output_lines):
900    line = input_line_info.line
901    args = input_line_info.args
902    if line.strip() == comment_string:
903      continue
904    if line.strip() == SEPARATOR:
905      continue
906    if line.lstrip().startswith(comment_string):
907      m = CHECK_RE.match(line)
908      if m and m.group(1) in prefix_set:
909        continue
910    output_lines.append(line.rstrip('\n'))
911
912def add_checks_at_end(output_lines, prefix_list, func_order,
913                      comment_string, check_generator):
914  added = set()
915  for prefix in prefix_list:
916    prefixes = prefix[0]
917    tool_args = prefix[1]
918    for prefix in prefixes:
919      for func in func_order[prefix]:
920        if added:
921          output_lines.append(comment_string)
922        added.add(func)
923
924        # The add_*_checks routines expect a run list whose items are
925        # tuples that have a list of prefixes as their first element and
926        # tool command args string as their second element.  They output
927        # checks for each prefix in the list of prefixes.  By doing so, it
928        # implicitly assumes that for each function every run line will
929        # generate something for that function.  That is not the case for
930        # generated functions as some run lines might not generate them
931        # (e.g. -fopenmp vs. no -fopenmp).
932        #
933        # Therefore, pass just the prefix we're interested in.  This has
934        # the effect of generating all of the checks for functions of a
935        # single prefix before moving on to the next prefix.  So checks
936        # are ordered by prefix instead of by function as in "normal"
937        # mode.
938        check_generator(output_lines,
939                        [([prefix], tool_args)],
940                        func)
941