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