Home | History | Annotate | Download | only in utils
      1 #!/usr/bin/env python2.7
      2 
      3 """A test case update script.
      4 
      5 This script is a utility to update LLVM X86 'llc' based test cases with new
      6 FileCheck patterns. It can either update all of the tests in the file or
      7 a single test function.
      8 """
      9 
     10 import argparse
     11 import itertools
     12 import os         # Used to advertise this file's name ("autogenerated_note").
     13 import string
     14 import subprocess
     15 import sys
     16 import tempfile
     17 import re
     18 
     19 # Invoke the tool that is being tested.
     20 def llc(args, cmd_args, ir):
     21   with open(ir) as ir_file:
     22     stdout = subprocess.check_output(args.llc_binary + ' ' + cmd_args,
     23                                      shell=True, stdin=ir_file)
     24   # Fix line endings to unix CR style.
     25   stdout = stdout.replace('\r\n', '\n')
     26   return stdout
     27 
     28 
     29 # RegEx: this is where the magic happens.
     30 
     31 SCRUB_WHITESPACE_RE = re.compile(r'(?!^(|  \w))[ \t]+', flags=re.M)
     32 SCRUB_TRAILING_WHITESPACE_RE = re.compile(r'[ \t]+$', flags=re.M)
     33 SCRUB_X86_SHUFFLES_RE = (
     34     re.compile(
     35         r'^(\s*\w+) [^#\n]+#+ ((?:[xyz]mm\d+|mem)( \{%k\d+\}( \{z\})?)? = .*)$',
     36         flags=re.M))
     37 SCRUB_X86_SP_RE = re.compile(r'\d+\(%(esp|rsp)\)')
     38 SCRUB_X86_RIP_RE = re.compile(r'[.\w]+\(%rip\)')
     39 SCRUB_X86_LCP_RE = re.compile(r'\.LCPI[0-9]+_[0-9]+')
     40 SCRUB_KILL_COMMENT_RE = re.compile(r'^ *#+ +kill:.*\n')
     41 
     42 RUN_LINE_RE = re.compile('^\s*;\s*RUN:\s*(.*)$')
     43 IR_FUNCTION_RE = re.compile('^\s*define\s+(?:internal\s+)?[^@]*@(\w+)\s*\(')
     44 ASM_FUNCTION_RE = re.compile(
     45     r'^_?(?P<func>[^:]+):[ \t]*#+[ \t]*@(?P=func)\n[^:]*?'
     46     r'(?P<body>^##?[ \t]+[^:]+:.*?)\s*'
     47     r'^\s*(?:[^:\n]+?:\s*\n\s*\.size|\.cfi_endproc|\.globl|\.comm|\.(?:sub)?section)',
     48     flags=(re.M | re.S))
     49 CHECK_PREFIX_RE = re.compile('--check-prefix=(\S+)')
     50 CHECK_RE = re.compile(r'^\s*;\s*([^:]+?)(?:-NEXT|-NOT|-DAG|-LABEL)?:')
     51 
     52 
     53 def scrub_asm(asm):
     54   # Scrub runs of whitespace out of the assembly, but leave the leading
     55   # whitespace in place.
     56   asm = SCRUB_WHITESPACE_RE.sub(r' ', asm)
     57   # Expand the tabs used for indentation.
     58   asm = string.expandtabs(asm, 2)
     59   # Detect shuffle asm comments and hide the operands in favor of the comments.
     60   asm = SCRUB_X86_SHUFFLES_RE.sub(r'\1 {{.*#+}} \2', asm)
     61   # Generically match the stack offset of a memory operand.
     62   asm = SCRUB_X86_SP_RE.sub(r'{{[0-9]+}}(%\1)', asm)
     63   # Generically match a RIP-relative memory operand.
     64   asm = SCRUB_X86_RIP_RE.sub(r'{{.*}}(%rip)', asm)
     65   # Generically match a LCP symbol.
     66   asm = SCRUB_X86_LCP_RE.sub(r'{{\.LCPI.*}}', asm)
     67   # Strip kill operands inserted into the asm.
     68   asm = SCRUB_KILL_COMMENT_RE.sub('', asm)
     69   # Strip trailing whitespace.
     70   asm = SCRUB_TRAILING_WHITESPACE_RE.sub(r'', asm)
     71   return asm
     72 
     73 
     74 # Build up a dictionary of all the function bodies.
     75 def build_function_body_dictionary(raw_tool_output, prefixes, func_dict, verbose):
     76   for m in ASM_FUNCTION_RE.finditer(raw_tool_output):
     77     if not m:
     78       continue
     79     func = m.group('func')
     80     scrubbed_body = scrub_asm(m.group('body'))
     81     if func.startswith('stress'):
     82       # We only use the last line of the function body for stress tests.
     83       scrubbed_body = '\n'.join(scrubbed_body.splitlines()[-1:])
     84     if verbose:
     85       print >>sys.stderr, 'Processing function: ' + func
     86       for l in scrubbed_body.splitlines():
     87         print >>sys.stderr, '  ' + l
     88     for prefix in prefixes:
     89       if func in func_dict[prefix] and func_dict[prefix][func] != scrubbed_body:
     90         if prefix == prefixes[-1]:
     91           print >>sys.stderr, ('WARNING: Found conflicting asm under the '
     92                                'same prefix: %r!' % (prefix,))
     93         else:
     94           func_dict[prefix][func] = None
     95           continue
     96 
     97       func_dict[prefix][func] = scrubbed_body
     98 
     99 
    100 def add_checks(output_lines, prefix_list, func_dict, func_name):
    101   printed_prefixes = []
    102   for checkprefixes, _ in prefix_list:
    103     for checkprefix in checkprefixes:
    104       if checkprefix in printed_prefixes:
    105         break
    106       if not func_dict[checkprefix][func_name]:
    107         continue
    108       # Add some space between different check prefixes.
    109       if len(printed_prefixes) != 0:
    110         output_lines.append(';')
    111       printed_prefixes.append(checkprefix)
    112       output_lines.append('; %s-LABEL: %s:' % (checkprefix, func_name))
    113       func_body = func_dict[checkprefix][func_name].splitlines()
    114       output_lines.append('; %s:       %s' % (checkprefix, func_body[0]))
    115       for func_line in func_body[1:]:
    116         output_lines.append('; %s-NEXT:  %s' % (checkprefix, func_line))
    117       # Add space between different check prefixes and the first line of code.
    118       # output_lines.append(';')
    119       break
    120   return output_lines
    121 
    122 
    123 def should_add_line_to_output(input_line, prefix_set):
    124   # Skip any blank comment lines in the IR.
    125   if input_line.strip() == ';':
    126     return False
    127   # Skip any blank lines in the IR.
    128   #if input_line.strip() == '':
    129   #  return False
    130   # And skip any CHECK lines. We're building our own.
    131   m = CHECK_RE.match(input_line)
    132   if m and m.group(1) in prefix_set:
    133     return False
    134 
    135   return True
    136 
    137 
    138 def main():
    139   parser = argparse.ArgumentParser(description=__doc__)
    140   parser.add_argument('-v', '--verbose', action='store_true',
    141                       help='Show verbose output')
    142   parser.add_argument('--llc-binary', default='llc',
    143                       help='The "llc" binary to use to generate the test case')
    144   parser.add_argument(
    145       '--function', help='The function in the test file to update')
    146   parser.add_argument('tests', nargs='+')
    147   args = parser.parse_args()
    148 
    149   autogenerated_note = ('; NOTE: Assertions have been autogenerated by '
    150                         'utils/' + os.path.basename(__file__))
    151 
    152   for test in args.tests:
    153     if args.verbose:
    154       print >>sys.stderr, 'Scanning for RUN lines in test file: %s' % (test,)
    155     with open(test) as f:
    156       input_lines = [l.rstrip() for l in f]
    157 
    158     run_lines = [m.group(1)
    159                  for m in [RUN_LINE_RE.match(l) for l in input_lines] if m]
    160     if args.verbose:
    161       print >>sys.stderr, 'Found %d RUN lines:' % (len(run_lines),)
    162       for l in run_lines:
    163         print >>sys.stderr, '  RUN: ' + l
    164 
    165     prefix_list = []
    166     for l in run_lines:
    167       (llc_cmd, filecheck_cmd) = tuple([cmd.strip() for cmd in l.split('|', 1)])
    168       if not llc_cmd.startswith('llc '):
    169         print >>sys.stderr, 'WARNING: Skipping non-llc RUN line: ' + l
    170         continue
    171 
    172       if not filecheck_cmd.startswith('FileCheck '):
    173         print >>sys.stderr, 'WARNING: Skipping non-FileChecked RUN line: ' + l
    174         continue
    175 
    176       llc_cmd_args = llc_cmd[len('llc'):].strip()
    177       llc_cmd_args = llc_cmd_args.replace('< %s', '').replace('%s', '').strip()
    178 
    179       check_prefixes = [m.group(1)
    180                         for m in CHECK_PREFIX_RE.finditer(filecheck_cmd)]
    181       if not check_prefixes:
    182         check_prefixes = ['CHECK']
    183 
    184       # FIXME: We should use multiple check prefixes to common check lines. For
    185       # now, we just ignore all but the last.
    186       prefix_list.append((check_prefixes, llc_cmd_args))
    187 
    188     func_dict = {}
    189     for prefixes, _ in prefix_list:
    190       for prefix in prefixes:
    191         func_dict.update({prefix: dict()})
    192     for prefixes, llc_args in prefix_list:
    193       if args.verbose:
    194         print >>sys.stderr, 'Extracted LLC cmd: llc ' + llc_args
    195         print >>sys.stderr, 'Extracted FileCheck prefixes: ' + str(prefixes)
    196 
    197       raw_tool_output = llc(args, llc_args, test)
    198       build_function_body_dictionary(raw_tool_output, prefixes, func_dict, args.verbose)
    199 
    200     is_in_function = False
    201     is_in_function_start = False
    202     prefix_set = set([prefix for prefixes, _ in prefix_list for prefix in prefixes])
    203     if args.verbose:
    204       print >>sys.stderr, 'Rewriting FileCheck prefixes: %s' % (prefix_set,)
    205     output_lines = []
    206     output_lines.append(autogenerated_note)
    207 
    208     for input_line in input_lines:
    209       if is_in_function_start:
    210         if input_line == '':
    211           continue
    212         if input_line.lstrip().startswith(';'):
    213           m = CHECK_RE.match(input_line)
    214           if not m or m.group(1) not in prefix_set:
    215             output_lines.append(input_line)
    216             continue
    217 
    218         # Print out the various check lines here.
    219         output_lines = add_checks(output_lines, prefix_list, func_dict, name)
    220         is_in_function_start = False
    221 
    222       if is_in_function:
    223         if should_add_line_to_output(input_line, prefix_set) == True:
    224           # This input line of the function body will go as-is into the output.
    225           output_lines.append(input_line)
    226         else:
    227           continue
    228         if input_line.strip() == '}':
    229           is_in_function = False
    230         continue
    231 
    232       if input_line == autogenerated_note:
    233         continue
    234 
    235       # If it's outside a function, it just gets copied to the output.
    236       output_lines.append(input_line)
    237 
    238       m = IR_FUNCTION_RE.match(input_line)
    239       if not m:
    240         continue
    241       name = m.group(1)
    242       if args.function is not None and name != args.function:
    243         # When filtering on a specific function, skip all others.
    244         continue
    245       is_in_function = is_in_function_start = True
    246 
    247     if args.verbose:
    248       print>>sys.stderr, 'Writing %d lines to %s...' % (len(output_lines), test)
    249 
    250     with open(test, 'wb') as f:
    251       f.writelines([l + '\n' for l in output_lines])
    252 
    253 
    254 if __name__ == '__main__':
    255   main()
    256