Debian Codegraph @

rpython/jit/codewriter/format.py

raw symbols SCIP
1 from __future__ import print_function
2
3 import py
4 from rpython.flowspace.model import Constant
5 from rpython.rtyper.lltypesystem import lltype
6 from rpython.jit.codewriter.flatten import SSARepr, Label, TLabel, Register
7 from rpython.jit.codewriter.flatten import ListOfKind, IndirectCallTargets
8 from rpython.jit.codewriter.jitcode import SwitchDictDescr
9 from rpython.jit.metainterp.history import AbstractDescr
10
11
12 def format_assembler(ssarepr):
13 """For testing: format a SSARepr as a multiline string."""
14 from cStringIO import StringIO
15
16 def repr(x):
17 if isinstance(x, Register):
18 return '%%%s%d' % (x.kind[0], x.index) # e.g. %i1 or %r2 or %f3
19 elif isinstance(x, Constant):
20 if (isinstance(x.concretetype, lltype.Ptr) and
21 isinstance(x.concretetype.TO, lltype.Struct)):
22 return '$<* struct %s>' % (x.concretetype.TO._name,)
23 return '$%r' % (x.value,)
24 elif isinstance(x, TLabel):
25 return getlabelname(x)
26 elif isinstance(x, ListOfKind):
27 return '%s[%s]' % (x.kind[0].upper(), ', '.join(map(repr, x)))
28 elif isinstance(x, SwitchDictDescr):
29 return '<SwitchDictDescr %s>' % (
30 ', '.join(['%s:%s' % (key, getlabelname(lbl))
31 for key, lbl in x._labels]))
32 elif isinstance(x, (AbstractDescr, IndirectCallTargets)):
33 return '%r' % (x,)
34 else:
35 return '<unknown object: %r>' % (x,)
36
37 seenlabels = {}
38 for asm in ssarepr.insns:
39 for x in asm:
40 if isinstance(x, TLabel):
41 seenlabels[x.name] = -1
42 elif isinstance(x, SwitchDictDescr):
43 for _, switch in x._labels:
44 seenlabels[switch.name] = -1
45 labelcount = [0]
46 def getlabelname(lbl):
47 if seenlabels[lbl.name] == -1:
48 labelcount[0] += 1
49 seenlabels[lbl.name] = labelcount[0]
50 return 'L%d' % seenlabels[lbl.name]
51
52 output = StringIO()
53 insns = ssarepr.insns
54 if insns and insns[-1] == ('---',):
55 insns = insns[:-1]
56 for i, asm in enumerate(insns):
57 if ssarepr._insns_pos:
58 prefix = '%4d ' % ssarepr._insns_pos[i]
59 else:
60 prefix = ''
61 if isinstance(asm[0], Label):
62 if asm[0].name in seenlabels:
63 print(prefix + '%s:' % getlabelname(asm[0]), file=output)
64 else:
65 print(prefix + asm[0], end="", file=output)
66 if len(asm) > 1:
67 print(' ', end="", file=output)
68 if asm[-2] == '->':
69 if len(asm) == 3:
70 print('->', repr(asm[-1]), file=output)
71 else:
72 lst = map(repr, asm[1:-2])
73 print(', '.join(lst), '->', repr(asm[-1]), file=output)
74 else:
75 lst = map(repr, asm[1:])
76 if asm[0] == '-live-': lst.sort()
77 print(', '.join(lst), file=output)
78 else:
79 print(file=output)
80 res = output.getvalue()
81 return res
82
83 def assert_format(ssarepr, expected):
84 asm = format_assembler(ssarepr)
85 if expected != '':
86 expected = str(py.code.Source(expected)).strip() + '\n'
87 asmlines = asm.split("\n")
88 explines = expected.split("\n")
89 for asm, exp in zip(asmlines, explines):
90 if asm != exp:
91 msg = [""]
92 msg.append("Got: " + asm)
93 msg.append("Expected: " + exp)
94 lgt = 0
95 for i in range(min(len(asm), len(exp))):
96 if exp[i] == asm[i]:
97 lgt += 1
98 else:
99 break
100 msg.append(" " + " " * lgt + "^^^^")
101 raise AssertionError('\n'.join(msg))
102 assert len(asmlines) == len(explines)
103
104 def unformat_assembler(text, registers=None):
105 # XXX limited to simple assembler right now
106 #
107 def unformat_arg(s):
108 if s.endswith(','):
109 s = s[:-1].rstrip()
110 if s[0] == '%':
111 try:
112 return registers[s]
113 except KeyError:
114 num = int(s[2:])
115 if s[1] == 'i': reg = Register('int', num)
116 elif s[1] == 'r': reg = Register('ref', num)
117 elif s[1] == 'f': reg = Register('float', num)
118 else: raise AssertionError("bad register type")
119 registers[s] = reg
120 return reg
121 elif s[0] == '$':
122 intvalue = int(s[1:])
123 return Constant(intvalue, lltype.Signed)
124 elif s[0] == 'L':
125 return TLabel(s)
126 elif s[0] in 'IRF' and s[1] == '[' and s[-1] == ']':
127 items = split_words(s[2:-1])
128 items = map(unformat_arg, items)
129 return ListOfKind({'I': 'int', 'R': 'ref', 'F': 'float'}[s[0]],
130 items)
131 elif s.startswith('<SwitchDictDescr '):
132 assert s.endswith('>')
133 switchdict = SwitchDictDescr()
134 switchdict._labels = []
135 items = split_words(s[len('<SwitchDictDescr '):-1])
136 for item in items:
137 key, value = item.split(':')
138 value = value.rstrip(',')
139 switchdict._labels.append((int(key), TLabel(value)))
140 return switchdict
141 else:
142 raise AssertionError("unsupported argument: %r" % (s,))
143 #
144 if registers is None:
145 registers = {}
146 ssarepr = SSARepr('test')
147 for line in text.splitlines():
148 line = line.strip()
149 if not line:
150 continue
151 if line.startswith('L') and line.endswith(':'):
152 ssarepr.insns.append((Label(line[:-1]),))
153 else:
154 try:
155 opname, line = line.split(None, 1)
156 except ValueError:
157 opname, line = line, ''
158 words = list(split_words(line))
159 if '->' in words:
160 assert words.index('->') == len(words) - 2
161 extra = ['->', unformat_arg(words[-1])]
162 del words[-2:]
163 else:
164 extra = []
165 insn = [opname] + [unformat_arg(s) for s in words] + extra
166 ssarepr.insns.append(tuple(insn))
167 return ssarepr
168
169
170 def split_words(line):
171 word = ''
172 nested = 0
173 for i, c in enumerate(line):
174 if c == ' ' and nested == 0:
175 if word:
176 yield word
177 word = ''
178 else:
179 word += c
180 if c in '<([':
181 nested += 1
182 if c in '])>' and (' '+line)[i:i+4] != ' -> ':
183 nested -= 1
184 assert nested >= 0
185 if word:
186 yield word
187 assert nested == 0