Debian Codegraph @

rpython/jit/backend/zarch/test/test_auto_encoding.py

raw symbols SCIP
1 import os, random, struct
2 import subprocess
3 import py
4 from rpython.jit.backend.zarch import codebuilder
5 from rpython.rlib.rarithmetic import intmask
6 from rpython.tool.udir import udir
7 import itertools
8 import re
9
10 INPUTNAME = 'checkfile_%s.s'
11 FILENAME = 'checkfile_%s.o'
12 BEGIN_TAG = '<<<zarch-test-begin>>>'
13 END_TAG = '<<<zarch-test-end>>>'
14
15 class CodeCheckerMixin(object):
16 def __init__(self, expected, accept_unnecessary_prefix):
17 self.expected = expected
18 self.accept_unnecessary_prefix = accept_unnecessary_prefix
19 self.index = 0
20
21 def begin(self, op):
22 self.op = op
23 self.instrindex = self.index
24
25 def writechar(self, char):
26 if char != self.expected[self.index:self.index+1]:
27 if (char == self.accept_unnecessary_prefix
28 and self.index == self.instrindex):
29 return # ignore the extra character '\x40'
30 post = self.expected[self.index+1:self.index+15]
31 generated = "\x09from codebuilder.py: " + hexdump(self.expected[self.instrindex:self.index]) + "!" + \
32 hexdump([char])+ "!" +hexdump(post) + "..."
33 expected = "\x09from gnu as: " + hexdump(self.expected[self.instrindex:self.index+15])+"..."
34 raise Exception("Asm line:" + self.op + "\n" + generated + "\n" + expected)
35 self.index += 1
36
37 def done(self):
38 assert len(self.expected) == self.index
39
40 def stack_frame_size_delta(self, delta):
41 pass # ignored
42
43 def check_stack_size_at_ret(self):
44 pass # ignored
45
46 class CodeCheckerZARCH(CodeCheckerMixin, codebuilder.InstrBuilder):
47 pass
48
49 def hexdump(s):
50 return ' '.join(["%02X" % ord(c) for c in s])
51
52 def reduce_to_32bit(s):
53 if s[:2] != '%r':
54 return s
55 if s[2:].isdigit():
56 return s + 'd'
57 else:
58 return '%e' + s[2:]
59
60 # ____________________________________________________________
61
62 COUNT1 = 15
63 suffixes = {0:'', 1:'b', 2:'w', 4:'l', 8:'q'}
64
65 class FakeIndexBaseDisplace(object):
66 def __init__(self, index, base, disp):
67 self.index = index
68 self.base = base
69 self.displace = disp
70
71 def __str__(self):
72 disp = self.displace
73 index = self.index
74 base = self.base
75 return "{disp}(%r{index},%r{base})".format(**locals())
76
77 __repr__ = __str__
78
79 class FakeBaseDisplace(object):
80 def __init__(self, base, disp):
81 self.base = base
82 self.displace = disp
83
84 def __str__(self):
85 disp = self.displace
86 base = self.base
87 return "{disp}(%r{base})".format(**locals())
88
89 __repr__ = __str__
90
91 class FakeLengthBaseDisplace(object):
92 def __init__(self, len, base, disp):
93 self.length = len
94 self.base = base
95 self.displace = disp
96
97 def __str__(self):
98 disp = self.displace
99 base = self.base
100 length = self.length + 1
101 return "{disp}({length},%r{base})".format(**locals())
102
103 __repr__ = __str__
104
105 def range_of_bits(bits, signed=False, count=24):
106 if isinstance(bits, tuple):
107 bits, signed = bits
108 if signed:
109 bits -= 1
110 maximum = 2**bits
111 return [-maximum,-1,0,1,maximum-1] + [random.randrange(-maximum,maximum) for i in range(count)]
112 maximum = 2**bits
113 return [0,1,maximum-1] + [random.randrange(0,maximum) for i in range(count)]
114
115 def range_of_halfword_bits(bits, signed=True, count=24):
116 elems = range_of_bits(bits, signed, count)
117 for i,e in enumerate(elems):
118 elems[i] = e >> 1
119 return elems
120
121 def build_fake(clazz, *arg_bits):
122 possibilities = itertools.product(*[range_of_bits(b) for b in arg_bits])
123 results = []
124 i = 0
125 for args in possibilities:
126 results.append(clazz(*args))
127 i+=1
128 if i > 20:
129 break
130 return results
131
132 REGS = range(16)
133 EVEN_REGS = range(0,16,2)
134 REGNAMES = ['%%r%d' % i for i in REGS]
135 FP_REGS = range(16)
136 FP_REGNAMES = ['%%f%d' % i for i in FP_REGS]
137 VEC_REGS = ['%%v%d' % i for i in range(16,32)]
138 TEST_CASE_GENERATE = {
139 '-': [],
140 'r': REGS,
141 'f': FP_REGS,
142 'eo': EVEN_REGS,
143 'r/m': REGS,
144 'v': VEC_REGS,
145 'm': range_of_bits(4),
146 'i4': range_of_bits(4, signed=True),
147 'i8': range_of_bits(8, signed=True),
148 'i16': range_of_bits(16, signed=True),
149 'i32': range_of_bits(32, signed=True),
150 'i64': range_of_bits(64, signed=True),
151 'h32': range_of_halfword_bits(32, signed=True),
152 'u4': range_of_bits(4),
153 'u8': range_of_bits(8),
154 'u16': range_of_bits(16),
155 'u32': range_of_bits(32),
156 'u64': range_of_bits(64),
157 'bd': build_fake(FakeBaseDisplace,4,12),
158 'bdl': build_fake(FakeBaseDisplace,4,19),
159 'bid': build_fake(FakeIndexBaseDisplace,4,4,12),
160 'bidl': build_fake(FakeIndexBaseDisplace,4,4,(20,True)),
161 'l8bd': build_fake(FakeLengthBaseDisplace,8,4,12),
162 'l4bd': build_fake(FakeLengthBaseDisplace,4,4,12),
163 }
164
165 class TestZARCH(object):
166 WORD = 4
167 TESTDIR = 'zarch'
168 accept_unnecessary_prefix = None
169 methname = '?'
170
171 def get_func_arg_types(self, methodname):
172 from rpython.jit.backend.zarch.instruction_builder import get_arg_types_of
173 return get_arg_types_of(methodname)
174
175 def operand_combinations(self, methodname, modes, arguments):
176 mapping = {
177 'r': (lambda num: REGNAMES[num]),
178 'eo': (lambda num: REGNAMES[num]),
179 'r/m': (lambda num: REGNAMES[num]),
180 'f': (lambda num: FP_REGNAMES[num]),
181 'h32': (lambda num: str(num << 1)),
182 }
183 arg_types = self.get_func_arg_types(methodname)
184 for mode, args in zip(arg_types, arguments):
185 yield mapping.get(mode, lambda x: str(x))(args)
186
187 def run_test(self, methname, instrname, argmodes, args_lists,
188 instr_suffix=None):
189 global labelcount
190 labelcount = 0
191 oplist = []
192 testdir = udir.ensure(self.TESTDIR, dir=1)
193 inputname = str(testdir.join(INPUTNAME % methname))
194 filename = str(testdir.join(FILENAME % methname))
195 with open(inputname, 'w') as g:
196 g.write('\x09.string "%s"\n' % BEGIN_TAG)
197 #
198 for args in args_lists:
199 suffix = ""
200 if instr_suffix is not None:
201 suffix = instr_suffix # overwrite
202 #
203 ops = self.operand_combinations(methname, argmodes, args)
204 op = '\t%s%s %s' % (instrname.lower(), suffix,
205 ', '.join(ops))
206 g.write('%s\n' % op)
207 oplist.append(op)
208 g.write('\t.string "%s"\n' % END_TAG)
209 proc = subprocess.Popen(['as', '-m64', '-mzarch', '-march=z196',
210 inputname, '-o', filename],
211 stdout=subprocess.PIPE,
212 stderr=subprocess.PIPE)
213 stdout, stderr = proc.communicate()
214 if proc.returncode or stderr:
215 raise Exception("could not execute assembler. error:\n%s" % (stderr))
216 with open(inputname, 'r') as g:
217 got = g.read()
218 error = [line for line in got.splitlines() if 'error' in line.lower()]
219 if error:
220 raise Exception("Assembler got an error: %r" % error[0])
221 error = [line for line in got.splitlines()
222 if 'warning' in line.lower()]
223 if error:
224 raise Exception("Assembler got a warning: %r" % error[0])
225 try:
226 with open(filename, 'rb') as f:
227 data = f.read()
228 i = data.find(BEGIN_TAG)
229 assert i>=0
230 j = data.find(END_TAG, i)
231 assert j>=0
232 as_code = data[i+len(BEGIN_TAG)+1:j]
233 except IOError:
234 raise Exception("Assembler did not produce output?")
235 return oplist, as_code
236
237 def modes(self, mode):
238 return mode
239
240 def make_all_tests(self, methname, modes, args=[]):
241 if methname.startswith("RIS"):
242 return []
243 arg_types = self.get_func_arg_types(methname)
244 combinations = []
245 for i,m in enumerate(arg_types):
246 elems = TEST_CASE_GENERATE[m]
247 #random.shuffle(elems)
248 combinations.append(elems)
249 results = []
250 for args in itertools.product(*combinations):
251 results.append(args)
252 return results
253
254 def should_skip_instruction(self, instrname, argmodes):
255 return False
256
257 def complete_test(self, methname):
258 if '_' in methname:
259 instrname, argmodes = methname.split('_')[:2]
260 else:
261 instrname, argmodes = methname, ''
262 argmodes = self.modes(argmodes)
263
264 if self.should_skip_instruction(instrname, argmodes):
265 print "Skipping %s" % methname
266 return
267
268 instr_suffix = None
269
270 print "Testing %s with argmodes=%r" % (instrname, argmodes)
271 self.methname = methname
272 ilist = self.make_all_tests(methname, argmodes)
273 oplist, as_code = self.run_test(methname, instrname, argmodes, ilist,
274 instr_suffix)
275 cc = CodeCheckerZARCH(as_code, self.accept_unnecessary_prefix)
276 for op, args in zip(oplist, ilist):
277 if op:
278 cc.begin(op)
279 getattr(cc, methname)(*args)
280 cc.done()
281
282 def setup_class(cls):
283 import os
284 g = os.popen('as -version </dev/null -o /dev/null 2>&1')
285 data = g.read()
286 g.close()
287 if not data.startswith('GNU assembler'):
288 py.test.skip("full tests require the GNU 'as' assembler")
289
290 @py.test.mark.parametrize("name", codebuilder.all_instructions)
291 def test_all(self, name):
292 if name.startswith('V'):
293 py.test.skip("objdump might not be able to assemble z13 instr.")
294 self.complete_test(name)