├── .gitignore ├── clr-python-avx2 ├── clr-python-avx512 ├── avxjudge.make ├── Makefile ├── README.md ├── filemap-verify.py ├── elf-move-test.sh ├── clr-avx2-move.pl ├── libdeps.py ├── elf-move.py ├── pypi-dep-fix.py ├── COPYING └── avxjudge.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.tar.gz 3 | -------------------------------------------------------------------------------- /clr-python-avx2: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | exec make -kf /usr/share/clr-avx-tools/avxjudge.make ARGS="-q -2" "$@" 3 | -------------------------------------------------------------------------------- /clr-python-avx512: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | exec make -kf /usr/share/clr-avx-tools/avxjudge.make ARGS="-q -5" "$@" 3 | 4 | -------------------------------------------------------------------------------- /avxjudge.make: -------------------------------------------------------------------------------- 1 | # -* makefile -*- 2 | MAKEFILE := $(lastword $(MAKEFILE_LIST)) 3 | MAKEFILEDIR := $(dir $(MAKEFILE)) 4 | 5 | .SUFFIXES: # Remove implicit rules 6 | .PHONY: force 7 | force: 8 | 9 | # Don't try to update this makefile 10 | $(MAKEFILE): 11 | : 12 | 13 | # For all other files, run avxjudge.py 14 | /%: force 15 | python3 $(MAKEFILEDIR)/avxjudge.py $(ARGS) $@ 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | prefix = $(DESTDIR)/usr 2 | bindir = $(prefix)/bin 3 | bin_PROGRAMS = \ 4 | clr-avx2-move.pl \ 5 | clr-python-avx2 \ 6 | clr-python-avx512 \ 7 | elf-move.py \ 8 | filemap-verify.py \ 9 | pypi-dep-fix.py 10 | 11 | datadir = $(prefix)/share/clr-avx-tools 12 | data_FILES = \ 13 | avxjudge.py \ 14 | avxjudge.make 15 | 16 | all: 17 | 18 | install: 19 | install -d $(bindir) $(datadir) 20 | install -m 755 -t $(bindir) $(bin_PROGRAMS) 21 | install -m 644 -t $(datadir) $(data_FILES) 22 | 23 | test: 24 | @./elf-move-test.sh 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## DISCONTINUATION OF PROJECT. 2 | 3 | This project will no longer be maintained by Intel. 4 | 5 | Intel will not provide or guarantee development of or support for this project, including but not limited to, maintenance, bug fixes, new releases or updates. Patches to this project are no longer accepted by Intel. If you have an ongoing need to use this project, are interested in independently developing it, or would like to maintain patches for the community, please create your own fork of the project. 6 | 7 | Contact: webadmin@linux.intel.com 8 | -------------------------------------------------------------------------------- /filemap-verify.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import hashlib 5 | import os 6 | import sys 7 | 8 | 9 | def get_full_map(fmdir): 10 | full_map = {} 11 | for fmfile in os.listdir(fmdir): 12 | if not fmfile.startswith('filemap-'): 13 | print(f"Skipping {fmfile}") 14 | continue 15 | with open(os.path.join(fmdir, fmfile), encoding='utf8') as mfile: 16 | iter_mfile = iter(mfile.readlines()) 17 | for line in iter_mfile: 18 | btype = line 19 | opath = next(iter_mfile) 20 | fhash = next(iter_mfile) 21 | full_map[fhash.strip()] = (btype.strip(), opath.strip()) 22 | return full_map 23 | 24 | 25 | def get_hash_map(path): 26 | hash_map = {} 27 | for root, dirs, files in os.walk(path): 28 | for fname in files: 29 | try: 30 | with open(os.path.join(root, fname), 'rb') as ifile: 31 | sha = hashlib.sha256() 32 | sha.update(ifile.read()) 33 | hash_map[sha.hexdigest()] = os.path.join(root, fname) 34 | except Exception: 35 | pass 36 | return hash_map 37 | 38 | 39 | def find_match(path, hash_map): 40 | sha = hashlib.sha256() 41 | with open(path, 'rb') as ifile: 42 | sha.update(ifile.read()) 43 | if sha in hash_map and hash_map[sha] != path: 44 | return hash_map[sha] 45 | 46 | 47 | def main(): 48 | parser = argparse.ArgumentParser() 49 | parser.add_argument('--fmdir', '-f', default='/usr/share/clear/filemap/', help='The filemap directory') 50 | parser.add_argument('--match_base', '-m', default='/usr/', help='The base directory of os content') 51 | parser.add_argument('--oedir', '-o', default='/usr/share/clear/optimized-elf/', help='The optimized elf directory') 52 | parser.add_argument('--quiet', '-q', action='store_true', default=False, help='Do not print results') 53 | args = parser.parse_args() 54 | 55 | full_map = get_full_map(args.fmdir) 56 | match_list = [] 57 | 58 | for root, _, files in os.walk(args.oedir): 59 | for oefile in files: 60 | if oefile in full_map and not args.quiet: 61 | print(f"{oefile} -> {full_map[oefile][1]}:{full_map[oefile][0]}") 62 | else: 63 | match_list.append((root, oefile)) 64 | 65 | if match_list: 66 | if not args.quiet: 67 | for _, oefile in match_list: 68 | print(f"Error: {oefile} not in filemap", file=sys.stderr) 69 | sys.exit(-1) 70 | 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /elf-move-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -eEu -o pipefail 4 | 5 | BUILDDIR2=$(mktemp -d) 6 | BUILDDIR512=$(mktemp -d) 7 | BUILDDIRA=$(mktemp -d) 8 | OUTDIR2=$(mktemp -d) 9 | OUTDIR512=$(mktemp -d) 10 | OUTDIRA=$(mktemp -d) 11 | 12 | function cleanup() { 13 | rm -fr "${BUILDDIR2}" 14 | rm -fr "${BUILDDIR512}" 15 | rm -fr "${BUILDDIRA}" 16 | rm -fr "${OUTDIR2}" 17 | rm -fr "${OUTDIR512}" 18 | rm -fr "${OUTDIRA}" 19 | } 20 | trap 'cleanup' EXIT 21 | 22 | function test_run() { 23 | local avx=$1 24 | if [ $avx = 2 ]; then 25 | eval local outdir='$OUTDIR2' 26 | local outdirv="${outdir}/V3" 27 | local elfarg="avx2" 28 | eval local builddir='$BUILDDIR2' 29 | elif [ $avx = 512 ]; then 30 | eval local outdir='$OUTDIR512' 31 | local outdirv="${outdir}/V4" 32 | local elfarg="avx512" 33 | eval local builddir='$BUILDDIR512' 34 | else 35 | eval local outdir='$OUTDIRA' 36 | local outdirv="${outdir}/VA" 37 | local elfarg="apx" 38 | eval local builddir='$BUILDDIRA' 39 | fi 40 | local bindir="${builddir}/usr/bin" 41 | local sbindir="${builddir}/usr/sbin" 42 | local libdir="${builddir}/usr/lib64" 43 | local othdir="${libdir}/other" 44 | local execdir="${builddir}/libexec" 45 | local testdir="${execdir}/installed-tests" 46 | local oddothdir="${builddir}/usr/foo/usr/lib64" 47 | 48 | local obindir="${outdirv}/usr/bin" 49 | local osbindir="${outdirv}/usr/bin" 50 | local olibdir="${outdirv}/usr/lib64" 51 | local oothdir="${olibdir}/other" 52 | local oexecdir="${outdirv}/libexec" 53 | local otestdir="${oexecdir}/installed-tests" 54 | local ooddothdir="${outdirv}/usr/foo/usr/lib64" 55 | 56 | mkdir -p "${othdir}" 57 | mkdir -p "${bindir}" 58 | mkdir -p "${sbindir}" 59 | mkdir -p "${testdir}" 60 | mkdir -p "${oddothdir}" 61 | mkdir -p "${oothdir}" 62 | mkdir -p "${obindir}" 63 | mkdir -p "${otestdir}" 64 | mkdir -p "${ooddothdir}" 65 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff > "${bindir}/bfile" 66 | ln -s "${bindir}/bfile" "${bindir}/lbfile" 67 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff > "${bindir}/sbfile" 68 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff > "${bindir}/setuid-file" 69 | chmod u+s "${bindir}/setuid-file" 70 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff > "${bindir}/skip-file" 71 | echo -n -e \\x00 > "${bindir}/keep-file" 72 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff\\xff > "${libdir}/lfile" 73 | ln -s "${libdir}/lfile" "${libdir}/llfile" 74 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff\\xff\\xff > "${othdir}/ofile" 75 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff\\xff\\xff\\xff > "${execdir}/efile" 76 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff\\xff\\xff\\xff\\xff > "${testdir}/tfile" 77 | echo -n -e \\x7f\\x45\\x4c\\x46\\xff\\xff\\xff\\xff\\xff\\xff > "${oddothdir}/oofile" 78 | 79 | python3 elf-move.py "${elfarg}" "${builddir}" "${outdir}" --skip-path /usr/bin/skip-file --path /usr/bin/keep-file &> /dev/null 80 | 81 | [ -f "${obindir}/bfile" ] 82 | [ ! -f "${obindir}/lbfile" ] 83 | [ -f "${obindir}/sbfile" ] 84 | [ ! -f "${obindir}/setuid-file" ] 85 | [ ! -f "${obindir}/skip-file" ] 86 | [ -f "${obindir}/keep-file" ] 87 | [ -f "${olibdir}/lfile" ] 88 | [ ! -f "${olibdir}/llfile" ] 89 | [ -f "${oothdir}/ofile" ] 90 | [ -f "${oexecdir}/efile" ] 91 | [ -f "${otestdir}/tfile" ] 92 | [ -f "${ooddothdir}/oofile" ] 93 | } 94 | 95 | test_run 2 96 | test_run 512 97 | test_run a 98 | -------------------------------------------------------------------------------- /clr-avx2-move.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | use strict; 3 | use File::Path qw(make_path); 4 | 5 | if (scalar @ARGV < 3) { 6 | print "clr-avx2-move.pl \n"; 7 | print "Examples:\n"; 8 | print " clr-avx2-move.pl haswell .avx2 /var/tmp/buildroot\n"; 9 | print " clr-avx2-move.pl haswell/avx512_1 .avx512 /var/tmp/buildroot\n"; 10 | exit 0; 11 | } 12 | 13 | my $libsubdir = shift @ARGV; 14 | my $pluginsuffix = shift @ARGV; 15 | my $root = shift @ARGV; 16 | my %moves; 17 | my %createddirs; 18 | 19 | sub scandir($$) { 20 | my $dir = $_[0]; 21 | my $lambda = $_[1]; 22 | 23 | # Only recurse into this dir if it exists and is not a symlink 24 | return unless (-d $dir && ! -l $dir); 25 | 26 | opendir(my $dh, $dir) or die "Couldn't open $dir: $!"; 27 | while (readdir $dh) { 28 | next if $_ eq "." || $_ eq ".."; 29 | 30 | $lambda->("$dir/$_"); 31 | } 32 | closedir $dh; 33 | } 34 | 35 | sub add_file($) { 36 | my $f = $_[0]; 37 | my $soname = 0; 38 | my $interpreter = 0; 39 | my $elftype; 40 | 41 | # Run readelf -hdl on the file to get the SONAME and INTERP 42 | open READELF, "-|", "readelf", "-hdl", $f; 43 | while () { 44 | $elftype = $1 if /^\s*Type:\s*(\w+)\b/; 45 | $soname = 1 if / *0x\w+ \(SONAME\)\s/; 46 | $interpreter = 1 if /^\s*INTERP\s/; 47 | } 48 | close READELF; 49 | 50 | return if $? >> 8; # not ELF, ignore (could be a script) 51 | return unless $elftype eq "EXEC" || $elftype eq "DYN"; 52 | 53 | my $to; 54 | if ($soname || $interpreter) { 55 | # This ELF file either has a SONAME (it's a library), an interpreter 56 | # (it's an executable), or both (it's an executable library). 57 | # Move it to the $libsubdir subdir. 58 | $f =~ m,^(.*?)/?([^/]+)$,; 59 | my $dirname = "$1/$libsubdir"; 60 | $to = "$dirname/$2"; 61 | 62 | my $ignored_error; 63 | make_path($dirname, { error => \$ignored_error }) 64 | unless defined($createddirs{$dirname}); 65 | $createddirs{$dirname} = 1; 66 | } else { 67 | # No SONAME or interpreter, it must be a plugin. 68 | $to = $f . $pluginsuffix; 69 | } 70 | $moves{$f} = $to; 71 | } 72 | 73 | # Save STDERR for us, but redirect it to /dev/null for readelf 74 | open(REAL_STDERR, ">&STDERR"); 75 | open(STDERR, ">/dev/null"); 76 | 77 | # Make sure readelf outputs in English 78 | $ENV{LC_ALL} = 'C'; 79 | 80 | # Build the file listing 81 | my $binlambda = sub { 82 | # executables must be regular files and +x 83 | my $f = $_[0]; 84 | add_file($f) if (-f $f && -x $f); 85 | }; 86 | scandir("$root/bin", $binlambda); 87 | scandir("$root/sbin", $binlambda); 88 | scandir("$root/usr/bin", $binlambda); 89 | scandir("$root/usr/sbin", $binlambda); 90 | scandir("$root/usr/local/bin", $binlambda); 91 | scandir("$root/usr/local/sbin", $binlambda); 92 | 93 | my $liblambda; 94 | $liblambda = sub { 95 | $_ = $_[0]; 96 | if (-f $_) { 97 | # It's a library if it's named *.so, *.so.* (except *.so.avx*) 98 | add_file($_) if /\.so($|\.(?!avx))/; 99 | } elsif (-d $_) { 100 | # Lib dirs are recursive 101 | scandir($_, $liblambda) unless m,/$libsubdir$,; 102 | } 103 | }; 104 | scandir("$root/usr/lib64", $liblambda); 105 | 106 | # Automatically flush STDOUT 107 | $| = 1; 108 | 109 | while (my ($f, $to) = each %moves) { 110 | rename($f, $to) and print "$f -> $to\n" 111 | or print REAL_STDERR "rename(\"$f\", \"$to\"): $!\n"; 112 | } 113 | -------------------------------------------------------------------------------- /libdeps.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import subprocess 4 | import sys 5 | import copy 6 | 7 | libprovides = dict() 8 | librequires = dict() 9 | 10 | matrix = dict() 11 | visited = dict() 12 | 13 | 14 | def add_provides(lib, function): 15 | global libprovides 16 | 17 | if not lib in libprovides.keys(): 18 | libprovides[lib] = dict() 19 | libprovides[lib][function] = "Yes" 20 | 21 | def add_requires(lib, function): 22 | global librequires 23 | 24 | if not lib in librequires.keys(): 25 | librequires[lib] = dict() 26 | librequires[lib][function] = "Yes" 27 | 28 | 29 | def add_from_to_func(req, prov, func): 30 | global matrix 31 | 32 | if not req in matrix.keys(): 33 | matrix[req] = dict() 34 | if not prov in matrix[req].keys(): 35 | matrix[req][prov] = list() 36 | 37 | matrix[req][prov].append(func) 38 | 39 | def process_library(filename): 40 | 41 | pipeout = subprocess.check_output(['nm', '-D', filename]).decode("utf-8") 42 | 43 | lines = pipeout.split('\n') 44 | for line in lines: 45 | words = line.split() 46 | 47 | if len(words) > 1: 48 | if words[0] == 'U': 49 | add_requires(filename, words[1]) 50 | if words[1] == 'T': 51 | add_provides(filename, words[2]) 52 | if words[1] == 'W': 53 | add_provides(filename, words[2]) 54 | 55 | 56 | 57 | def process_binary(filename): 58 | process_library(filename) 59 | pipeout = subprocess.check_output(['ldd', '-r', filename]).decode("utf-8").replace("\t","") 60 | lines = pipeout.split('\n') 61 | for line in lines: 62 | words = line.split() 63 | if len(words) > 2: 64 | process_library(words[2]) 65 | 66 | 67 | def create_matrix(): 68 | for file in librequires.keys(): 69 | for symbol in librequires[file].keys(): 70 | for file2 in libprovides.keys(): 71 | if file2 == '/usr/lib64/ld-linux-x86-64.so.2': 72 | continue 73 | if file2 == '/usr/lib64/libc.so.6': 74 | continue 75 | if file2 == '/usr/lib64/haswell/libc.so.6': 76 | continue 77 | 78 | if file2 == '/usr/lib64/libpthread.so.0': 79 | continue 80 | if file != file2 and symbol in libprovides[file2].keys(): 81 | add_from_to_func(file, file2, symbol) 82 | 83 | def print_matrix(req, level): 84 | if not req in matrix.keys(): 85 | return 86 | 87 | for prov in matrix[req].keys(): 88 | start = "" 89 | for i in range(level): 90 | start += "\t" 91 | reason = "(" + str(len(matrix[req][prov])) + ") " + matrix[req][prov][0] 92 | if len(matrix[req][prov]) > 1: 93 | reason += " " + matrix[req][prov][1] 94 | if len(matrix[req][prov]) > 2: 95 | reason += " " + matrix[req][prov][2] 96 | if len(matrix[req][prov]) > 3: 97 | reason += " " + matrix[req][prov][3] 98 | if len(matrix[req][prov]) > 4: 99 | reason += " " + matrix[req][prov][4] 100 | if len(matrix[req][prov]) > 5: 101 | reason += " " + matrix[req][prov][5] 102 | if len(matrix[req][prov]) > 5: 103 | reason += " ..." 104 | print(start, req, "pulls in", prov, "because of", reason) 105 | if prov in visited: 106 | continue 107 | 108 | visited[prov] = "Yes" 109 | print_matrix(prov, level + 1) 110 | 111 | def main(): 112 | process_binary(sys.argv[1]) 113 | create_matrix() 114 | print_matrix(sys.argv[1], 0) 115 | 116 | if __name__ == '__main__': 117 | main() 118 | -------------------------------------------------------------------------------- /elf-move.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import itertools 5 | import os 6 | import sys 7 | from collections import OrderedDict 8 | 9 | 10 | def setup_parser(): 11 | """Create commandline argument parser.""" 12 | parser = argparse.ArgumentParser() 13 | 14 | parser.add_argument("btype", help="Binary type [avx2, avx512, apx]") 15 | 16 | parser.add_argument("installdir", help="Content directory to scan") 17 | 18 | parser.add_argument("targetdir", help="Target directory for output") 19 | 20 | parser.add_argument("outfile", nargs='?', default="", 21 | help="Deprecated: unused") 22 | 23 | parser.add_argument("-s", "--skip", action="store_true", 24 | default=False, 25 | help="Don't process elf binaries") 26 | 27 | parser.add_argument("-v", "--verbose", action="store_true", 28 | default=False, 29 | help="Add output for unused files in the installdir") 30 | 31 | parser.add_argument("-S", "--skip-path", default=[], nargs=1, 32 | action="append", 33 | help="Don't process files with the target path(s)") 34 | 35 | parser.add_argument("-p", "--path", default=[], nargs=1, 36 | action="append", 37 | help="Handle path regardless of file type (overrides skip)") 38 | 39 | return parser 40 | 41 | 42 | def process_install(args): 43 | """Create output based on the installdir. 44 | 45 | Also output to stdout the non-elf file paths and hashes (useful to compare 46 | different build types). 47 | """ 48 | always_process = set() 49 | for item in args.path: 50 | always_process.add(item[0]) 51 | args.path = always_process 52 | filemap = OrderedDict() 53 | for root, _, files in os.walk(args.installdir): 54 | for name in files: 55 | filepath = os.path.join(root, name) 56 | if os.path.islink(filepath): 57 | continue 58 | try: 59 | if os.stat(filepath).st_mode & os.path.stat.S_ISUID != 0: 60 | continue 61 | except: 62 | continue 63 | data = bytearray(4096) 64 | memv = memoryview(data) 65 | virtpath = os.path.join('/', 66 | filepath.removeprefix(args.installdir)) 67 | 68 | with open(filepath, 'rb', buffering=0) as ifile: 69 | ifile.readinto(memv) 70 | elf = memv[:4] == b'\x7fELF' 71 | if elf or virtpath in args.path: 72 | filemap[virtpath] = [True, 73 | filepath] 74 | else: 75 | filemap[virtpath] = [False, 76 | filepath] 77 | return filemap 78 | 79 | 80 | def move_content(args, filemap): 81 | """Use the filemap to populate targetidr.""" 82 | if len(filemap) == 0: 83 | return 84 | 85 | skips = set(itertools.chain.from_iterable(args.skip_path)) 86 | 87 | if args.btype == 'avx2': 88 | optimized_prefix = 'V3' 89 | elif args.btype == 'avx512': 90 | optimized_prefix = 'V4' 91 | elif args.btype == 'apx': 92 | optimized_prefix = 'VA' 93 | else: 94 | return 95 | optimized_dir = os.path.join(args.targetdir, optimized_prefix) 96 | os.makedirs(optimized_dir, exist_ok=True) 97 | for virtpath, val in filemap.items(): 98 | elf = val[0] 99 | source = val[1] 100 | if virtpath in skips: 101 | if args.verbose: 102 | print(f"Skipping path {virtpath}") 103 | continue 104 | if elf: 105 | if args.skip and virtpath not in args.path: 106 | if args.verbose: 107 | print(f"Skipping elf file {virtpath}") 108 | continue 109 | vdname = os.path.dirname(virtpath) 110 | vbname = os.path.basename(virtpath) 111 | if vdname in ('/bin', '/sbin', '/usr/sbin'): 112 | virtpath = os.path.join('/usr/bin', vbname) 113 | elif vdname == '/lib': 114 | virtpath = os.path.join('/usr/lib', vbname) 115 | elif vdname == '/lib64': 116 | virtpath = os.path.join('/usr/lib64', vbname) 117 | dest = os.path.join(optimized_dir, virtpath[1:]) 118 | os.makedirs(os.path.dirname(dest), exist_ok=True) 119 | if args.verbose: 120 | print(f"Installing {dest}") 121 | os.rename(source, dest) 122 | elif args.verbose: 123 | print(f"{virtpath} not installed") 124 | 125 | 126 | def main(): 127 | """Entry point function.""" 128 | parser = setup_parser() 129 | args = parser.parse_args() 130 | if args.btype not in ("avx2", "avx512", "apx"): 131 | print(f"Error: btype '{args.btype}' not supported (needs to be either avx2, avx512 or apx)") 132 | sys.exit(-1) 133 | if args.outfile: 134 | print('Warning: outfile argument is longer used, ignoring.') 135 | if args.targetdir.endswith('/usr/share/clear/optimized-elf/'): 136 | # Catch previous invocation with targetdir being the 137 | # optimized-elf directory that is no longer correct. 138 | print('Error: Full path for optimized-elf detected!') 139 | print(' targetdir should be the root of the output directory.') 140 | sys.exit(-1) 141 | 142 | filemap = process_install(args) 143 | 144 | move_content(args, filemap) 145 | 146 | 147 | if __name__ == '__main__': 148 | main() 149 | -------------------------------------------------------------------------------- /pypi-dep-fix.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import ast 5 | import os 6 | import re 7 | 8 | 9 | def setup_parser(): 10 | """Create commandline argument parser.""" 11 | parser = argparse.ArgumentParser() 12 | 13 | parser.add_argument("targetdir", default="", nargs=1, 14 | help="Target source directory") 15 | 16 | parser.add_argument("modules", default="", nargs='+', 17 | help="Name(s) of the module(s) to remove version requirements on") 18 | 19 | return parser 20 | 21 | 22 | def run_search(patterns, line): 23 | """Test if the line matches any patterns.""" 24 | for module, pattern in patterns.items(): 25 | match = pattern.search(line) 26 | if match: 27 | return module, match 28 | return None, None 29 | 30 | 31 | def make_patterns(modules): 32 | """Create regex patterns for each module.""" 33 | patterns = {} 34 | for module in modules: 35 | patterns[module] = re.compile(f"^(Requires-Dist:)?[ ]*{module}[ ]*[[(!~=><]") 36 | return patterns 37 | 38 | 39 | def find_files(path, patterns): 40 | """Find potential files to modify dependencies on.""" 41 | dep_files = [] 42 | file_whitelist = set(['requires.txt', 'requirements.txt', 'setup.cfg', 43 | 'setup.py', 'METADATA', 'PKG-INFO']) 44 | for root, _, files in os.walk(path): 45 | for name in files: 46 | filepath = os.path.join(root, name) 47 | if os.path.islink(filepath): 48 | continue 49 | if name not in file_whitelist: 50 | continue 51 | with open(filepath, 'r', encoding='utf-8', 52 | errors='replace') as rfile: 53 | for line in rfile.readlines(): 54 | match, _ = run_search(patterns, line) 55 | if match: 56 | dep_files.append(filepath) 57 | break 58 | return dep_files 59 | 60 | 61 | def is_install_target(node): 62 | """Detect node is an assignment with the right target.""" 63 | if isinstance(node, ast.Assign): 64 | for target in node.targets: 65 | # not supporting tuple assignment at least yet 66 | if isinstance(target, ast.Name) and target.id == 'install_requires': 67 | return True 68 | return False 69 | 70 | 71 | class ReplaceLocation(): 72 | """Wrapper class for a location of a replacement target.""" 73 | def __init__(self, line, start, end, module): 74 | self.line = line 75 | self.start = start 76 | self.end = end 77 | self.module = module 78 | 79 | def __str__(self): 80 | return f"line: {self.line}, start: {self.start}, end: {self.end}, module: {self.module}" 81 | 82 | 83 | def find_locations(node, patterns): 84 | """Find replacement location target(s) to be updated.""" 85 | locations = [] 86 | if isinstance(node.value, ast.List): 87 | for elt in node.value.elts: 88 | if isinstance(elt, ast.Constant): 89 | module, _ = run_search(patterns, elt.value) 90 | if module: 91 | locations.append(ReplaceLocation(elt.end_lineno, elt.col_offset, 92 | elt.end_col_offset, module)) 93 | return locations 94 | 95 | 96 | def code_replace(path, patterns): 97 | """Parse python to update a dependency.""" 98 | contents = '' 99 | with open(path, encoding='utf-8', errors='replace') as pfile: 100 | contents = pfile.read() 101 | tree = ast.parse(contents) 102 | locations = [] 103 | for node in ast.walk(tree): 104 | if is_install_target(node): 105 | locations += find_locations(node, patterns) 106 | new_contents = contents.splitlines() 107 | for location in locations: 108 | line = new_contents[location.line-1] 109 | new_line = f"{line[:location.start]}'{location.module}'{line[location.end:]}" 110 | new_contents[location.line-1] = new_line 111 | with open(path, 'w', encoding='utf-8') as pfile: 112 | pfile.writelines('\n'.join(new_contents)) 113 | if contents.endswith('\n'): 114 | pfile.write('\n') 115 | 116 | 117 | def text_replace(path, patterns): 118 | """Parse text to update a dependency.""" 119 | new_contents = [] 120 | # A bit dirty to do replace here but these are unlikely to be 121 | # important strings to program correctness. 122 | with open(path, 'r', encoding='utf-8', errors='replace') as pfile: 123 | contents = pfile.readlines() 124 | for line in contents: 125 | module, _ = run_search(patterns, line) 126 | if module: 127 | # text file with expected format 128 | # ::whitespace::module_name::whitespace::version_info 129 | # only remove everything after module_name 130 | name_start = line.find(module) 131 | new_line = line[:name_start+len(module)] 132 | if line.endswith('\n'): 133 | new_line += '\n' 134 | else: 135 | new_line = line 136 | new_contents.append(new_line) 137 | with open(path, 'w', encoding='utf-8') as pfile: 138 | pfile.writelines(new_contents) 139 | 140 | 141 | def update_dependencies(paths, patterns): 142 | """Remove the version dependencies for the given packages.""" 143 | python_files = set(['setup.py']) 144 | for path in paths: 145 | if os.path.basename(path) in python_files: 146 | code_replace(path, patterns) 147 | else: 148 | text_replace(path, patterns) 149 | 150 | 151 | def main(): 152 | """Entry point function.""" 153 | parser = setup_parser() 154 | args = parser.parse_args() 155 | 156 | patterns = make_patterns(args.modules) 157 | paths = find_files(args.targetdir[0], patterns) 158 | update_dependencies(paths, patterns) 159 | 160 | 161 | if __name__ == '__main__': 162 | main() 163 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | -------------------------------------------------------------------------------- /avxjudge.py: -------------------------------------------------------------------------------- 1 | """ 2 | avxjudge.py is a tool that RPM builds use when building for AVX2 or AVX512 3 | optimisations. It attempts to heuristically guess whether the library file has 4 | enough AVX instructions to be worth keeping. 5 | """ 6 | #!/usr/bin/python3 7 | import subprocess 8 | import sys 9 | import re 10 | import argparse 11 | import os 12 | 13 | # MMX and SSE2 instructions 14 | sse_instructions_xmm = set([ 15 | "paddb", "paddd", "paddsb", "paddsw", "paddusb", "psubw", 16 | "paddusw", "paddw", "pmaddwd", "pmulhw", "pmullw", "psubb", "psubsb", 17 | "psubsw", "psubusb", "paddusw", "paddw", "pmaddwd", "pmulhw", "pmullw", 18 | "psubb", "psubd", "psubd", "psubsb", "psubsw", "psubusb", "psubusw" 19 | ]) 20 | 21 | # 0.1 value instructions 22 | avx2_instructions_lv = set(["shrx", "rorx", "shlx", "shrx", "shrx", "movbe"]) 23 | avx2_instructions_ymm = set([ 24 | "vpaddq", "vpaddd", "vpsubq", "vpsubd", "vmulpd", "vaddpd", "vsubpd", 25 | "vmulps", "vaddps", "vsubps", "vpmaxsq", "vpminsq", "vpmuludq", 26 | "vpand", "vpmaxud", "vpminud", "vpmaxsd", "vpmaxsw", "vpminsd", 27 | "vpminsw", "vpand", "vpor", "vpmulld" 28 | ]) 29 | avx512_instructions_lv = set() 30 | 31 | # 1.0 value instructions 32 | avx2_instructions = set([ 33 | "vfmadd132ss", "vfmadd213ss", "vfmadd231ss", "vfmadd132sd", 34 | "vfmadd231sd", "vfmadd213sd", 35 | "vfmsub132ss", "vfmsub213ss", "vfmsub231ss", "vfmsub132sd", "vfmsub231sd", 36 | "vfmsub213sd", 37 | "vfnmadd132ss", "vfnmadd213ss", "vfnmadd231ss", "vfnmadd132sd", 38 | "vfnmadd231sd", "vfnmadd213sd", 39 | "vfnmsub132ss", "vfnmsub213ss", "vfnmsub231ss", "vfnmsub132sd", 40 | "vfnmsub231sd", "vfnmsub213sd", 41 | ]) 42 | avx512_instructions = set(["kmovw", "vpcmpltd", "kshiftrw", "kmovb"]) 43 | 44 | # 2.0 value instructions 45 | avx2_instructions_hv = set([ 46 | "vpclmulhqlqdq", "vpclmullqhqdq", 47 | "vfmadd132ps", "vfmadd213ps", "vfmadd231ps", "vfmadd132pd", "vfmadd231pd", 48 | "vfmadd213pd", "vfmsub132ps", "vfmsub213ps", "vfmsub231ps", "vfmsub132pd", 49 | "vfmsub231pd", "vfmsub213pd", 50 | "vfnmadd132ps", "vfnmadd213ps", "vfnmadd231ps", "vfnmadd132pd", 51 | "vfnmadd231pd", "vfnmadd213pd", "vfnmsub132ps", "vfnmsub213ps", 52 | "vfnmsub231ps", "vfnmsub132pd", "vfnmsub231pd", "vfnmsub213pd", "vdivpd", 53 | ]) 54 | avx512_instructions_hv = set() 55 | 56 | # Minimum thresholds for keeping libraries 57 | min_count = 10 58 | min_score = 1.0 59 | 60 | debug = 0 61 | 62 | class FunctionRecord(): 63 | def __init__(self): 64 | self.scores = {"sse": 0.0, "avx2": 0.0, "avx512": 0.0} 65 | self.counts = {"sse": 0, "avx2": 0, "avx512": 0} 66 | self.instructions = 0 67 | self.name = "" 68 | 69 | 70 | class RecordKeeper(): 71 | def __init__(self, delete_type): 72 | self.total_counts = {"sse": 0, "avx2": 0, "avx512": 0} 73 | self.total_scores = {"sse": 0.0, "avx2": 0.0, "avx512": 0.0} 74 | self.functions = {"sse": dict(), "avx2": dict(), "avx512": dict()} 75 | self.ratios = {"sse": dict(), "avx2": dict(), "avx512": dict()} 76 | self.function_record = FunctionRecord() 77 | self.delete_type = delete_type 78 | 79 | def should_delete(self) -> bool: 80 | if self.delete_type and self.total_counts[self.delete_type] < min_count and self.total_scores[self.delete_type] <= min_score: 81 | return True 82 | return False 83 | 84 | def finalize_function_attrs(self): 85 | for i in ("sse", "avx2", "avx512"): 86 | if self.function_record.counts[i] >= 1: 87 | self.functions[i][self.function_record.name] = self.function_record.scores[i] 88 | self.ratios[i][self.function_record.name] = 100.0 * self.function_record.counts[i] / self.function_record.instructions 89 | self.total_scores[i] += self.function_record.scores[i] 90 | self.total_counts[i] += self.function_record.counts[i] 91 | 92 | 93 | def is_sse(instruction:str, args:str) -> float: 94 | 95 | val: float = -1.0 96 | if "%xmm" in args: 97 | if ("pd" in instruction or "ps" in instruction or instruction in sse_instructions_xmm): 98 | val = 1.0 99 | else: 100 | val = 0.01 101 | return val 102 | 103 | 104 | def is_avx2(instruction:str, args:str) -> float: 105 | val: float = -1.0 106 | 107 | if "%ymm" in args: 108 | if ("pd" in instruction or "ps" in instruction or instruction in avx2_instructions_ymm) and "xor" not in instruction and "vmov" not in instruction: 109 | val = 1.0 110 | else: 111 | val = 0.01 112 | 113 | if instruction in avx2_instructions_lv: 114 | val = max(val, 0.1) 115 | if instruction in avx2_instructions: 116 | val = max(val, 1.0) 117 | if instruction in avx2_instructions_hv: 118 | val = max(val, 2.0) 119 | 120 | return val 121 | 122 | def has_high_register(args: str) -> bool: 123 | return args.endswith(( 124 | 'mm16', 'mm17', 'mm18', 'mm19', 'mm20', 'mm21', 'mm22', 125 | 'mm23', 'mm24', 'mm25', 'mm26', 'mm27', 'mm28', 'mm29', 126 | 'mm30', 'mm31' 127 | )) 128 | 129 | def is_avx512(instruction:str, args:str) -> float: 130 | val: float = -1.0 131 | 132 | if instruction in avx512_instructions_lv: 133 | val = max(val, 0.1) 134 | if instruction in avx512_instructions: 135 | val = max(val, 1.0) 136 | if instruction in avx512_instructions_hv: 137 | val = max(val, 2.0) 138 | 139 | if "xor" not in instruction and "%ymm" in args and has_high_register(args): 140 | val = max(val, 0.2) 141 | if "xor" not in instruction and has_high_register(args): 142 | val = max(val, 0.1) 143 | 144 | if "{%k" in args: # predicate instructions 145 | val = max(val, 0.1) 146 | if "{1to" in args: # broadcast-as-part-of-mov this saves a whole other instruction 147 | val = max(val, 1.0) 148 | 149 | if "%zmm" in args: 150 | if ("pd" in instruction or "ps" in instruction or "vpadd" in instruction or "vpsub" in instruction or instruction in avx2_instructions_ymm) and "xor" not in instruction and "vmov" not in instruction: 151 | val = max(val, 1.0) 152 | else: 153 | val = max(val, 0.01) 154 | 155 | 156 | return val 157 | 158 | 159 | def ratio(f: float) -> str: 160 | f = f * 100 161 | f = round(f)/100.0 162 | return str(f) 163 | 164 | def print_top_functions(records:RecordKeeper) -> None: 165 | def summarize(table: dict, is_pct: bool, max_funcs: int = 5) -> None: 166 | for f in sorted(table, key=table.get, reverse=True)[:max_funcs]: 167 | f = " %-30s\t%s" % (f, ratio(table[f])) 168 | 169 | if is_pct: 170 | print(f, "%s") 171 | else: 172 | print(f) 173 | 174 | sets = ( 175 | ("SSE", records.functions["sse"], records.ratios["sse"]), 176 | ("AVX2", records.functions["avx2"], records.ratios["avx2"]), 177 | ("AVX512", records.functions["avx512"], records.ratios["avx512"]), 178 | ) 179 | 180 | for set_name, funcs, funcs_ratio in sets: 181 | print("Top %s functions by instruction count" % set_name) 182 | summarize(funcs_ratio, True) 183 | print() 184 | 185 | print("Top %s functions by value" % set_name) 186 | summarize(funcs, False) 187 | print() 188 | 189 | sse_avx2_duplicate_cnt = 0 190 | avx2_avx512_duplicate_cnt = 0 191 | 192 | def print_function_summary(records): 193 | print(records.function_record.name, 194 | "\t", ratio(records.function_record.counts["sse"] / records.function_record.instructions), 195 | "\t", ratio(records.function_record.counts["avx2"] / records.function_record.instructions), 196 | "\t", ratio(records.function_record.counts["avx512"] / records.function_record.instructions), 197 | "\t", records.function_record.scores["sse"], 198 | "\t", records.function_record.scores["avx2"], 199 | "\t", records.function_record.scores["avx512"]) 200 | 201 | def process_objdump_line(records:RecordKeeper, line:str, verbose:int, quiet:int) -> None: 202 | sse_score = -1.0 203 | avx2_score = -1.0 204 | avx512_score = -1.0 205 | sse_str = " " 206 | avx2_str = " " 207 | avx512_str = "" 208 | 209 | global sse_avx2_duplicate_cnt 210 | global avx2_avx512_duplicate_cnt 211 | global debug 212 | 213 | match = re.search("^$", line) 214 | if match: 215 | if records.function_record.instructions > 0 and verbose > 0: 216 | print() 217 | print_function_summary(records) 218 | if verbose > 0: 219 | print() 220 | if records.function_record.instructions > 0: 221 | records.finalize_function_attrs() 222 | records.function_record = FunctionRecord() 223 | return 224 | 225 | match = re.search("^(.*)\#.*", line) 226 | if match: 227 | line = match.group(1) 228 | 229 | match = re.search(".*[0-9a-f]+\:\t[0-9a-f\ ]+\t([a-zA-Z0-9]+) (.*)", line) 230 | if match: 231 | ins = match.group(1) 232 | arg = match.group(2) 233 | 234 | avx512_score = is_avx512(ins, arg) 235 | if avx512_score <= 0: 236 | avx2_score = is_avx2(ins, arg) 237 | if avx2_score <= 0 and avx512_score <= 0: 238 | sse_score = is_sse(ins, arg) 239 | 240 | records.function_record.instructions += 1 241 | 242 | match = re.search(r'^[0-9a-f]+ <(.+)>:$', line) 243 | if match: 244 | records.function_record.name = match.group(1) 245 | 246 | if sse_score >= 0.0: 247 | sse_str = str(sse_score) 248 | records.function_record.scores["sse"] += sse_score 249 | records.function_record.counts["sse"] += 1 250 | 251 | if avx2_score >= 0.0: 252 | avx2_str = str(avx2_score) 253 | records.function_record.scores["avx2"] += avx2_score 254 | records.function_record.counts["avx2"] += 1 255 | 256 | if avx512_score >= 0.0: 257 | avx512_str = str(avx512_score) 258 | records.function_record.scores["avx512"] += avx512_score 259 | records.function_record.counts["avx512"] += 1 260 | 261 | if sse_score >=0.0 and avx2_score >= 0.0 and debug: 262 | sse_avx2_duplicate_cnt +=1 263 | print("duplicate count for sse & avx2 ?", ins, arg, sse_avx2_duplicate_cnt) 264 | 265 | if avx512_score >= 0.0 and avx2_score >= 0.0 and debug: 266 | avx2_avx512_duplicate_cnt +=1 267 | print("duplicate count for avx2 & avx512 ?", ins, arg, avx2_avx512_duplicate_cnt) 268 | 269 | if not records.should_delete() and quiet != 0: 270 | sys.exit(0) 271 | 272 | if verbose > 0: 273 | print(sse_str,"\t",avx2_str,"\t", avx512_str,"\t", line) 274 | 275 | 276 | def do_file(filename: str, verbose:int, quiet:int, delete_type:str) -> None: 277 | global debug 278 | 279 | records = RecordKeeper(delete_type) 280 | 281 | if quiet == 0: 282 | print("Analyzing", filename) 283 | 284 | p = subprocess.Popen(["objdump","-d", filename], stdout=subprocess.PIPE) 285 | for line in p.stdout: 286 | process_objdump_line(records, line.decode("latin-1"), verbose, quiet) 287 | output, _ = p.communicate() 288 | for line in output.decode("latin-1").splitlines(): 289 | process_objdump_line(records, line, verbose, quiet) 290 | if quiet <= 0: 291 | print_top_functions(records) 292 | print() 293 | print("File total (SSE): ", records.total_counts["sse"],"instructions with score", round(records.total_scores["sse"])) 294 | print("File total (AVX2): ", records.total_counts["avx2"],"instructions with score", round(records.total_scores["avx2"])) 295 | print("File total (AVX512): ", records.total_counts["avx512"],"instructions with score", round(records.total_scores["avx512"])) 296 | print() 297 | if debug: 298 | print("File duplicate count of sse&avx2", sse_avx2_duplicate_cnt, ", duplicate count of avx2&avx512", avx2_avx512_duplicate_cnt) 299 | 300 | if records.should_delete(): 301 | print(filename, "\t", delete_type, "count:", records.total_counts[delete_type],"\t", delete_type, "value:", ratio(records.total_scores[delete_type])) 302 | try: 303 | os.unlink(filename) 304 | except: 305 | None 306 | 307 | 308 | def main(): 309 | global debug 310 | 311 | verbose = 0 312 | quiet = 0 313 | parser = argparse.ArgumentParser() 314 | parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") 315 | parser.add_argument("-q", "--quiet", help="decrease output verbosity", action="store_true") 316 | parser.add_argument("-d", "--debug", help="print out more debug info", action="store_true") 317 | parser.add_argument("filename", help = "The filename to inspect") 318 | group = parser.add_mutually_exclusive_group() 319 | group.add_argument("-1", "--unlinksse", help="unlink the file if it has no SSE instructions", action="store_true") 320 | group.add_argument("-2", "--unlinkavx2", help="unlink the file if it has no AVX2 instructions", action="store_true") 321 | group.add_argument("-5", "--unlinkavx512", help="unlink the file if it has no AVX512 instructions", action="store_true") 322 | 323 | args = parser.parse_args() 324 | if args.verbose: 325 | verbose = 1 326 | 327 | if args.quiet: 328 | verbose = 0 329 | quiet = 1 330 | 331 | if args.debug: 332 | debug = 1 333 | 334 | if args.unlinksse: 335 | deltype = "sse" 336 | elif args.unlinkavx2: 337 | deltype = "avx2" 338 | elif args.unlinkavx512: 339 | deltype = "avx512" 340 | else: 341 | deltype = "" 342 | 343 | do_file(args.filename, verbose, quiet, deltype) 344 | 345 | 346 | if __name__ == '__main__': 347 | main() 348 | --------------------------------------------------------------------------------