Debian Codegraph @

rpython/jit/tl/tiny3_hotpath.py

raw symbols SCIP
1 """
2 An interpreter for a strange word-based language: the program is a list
3 of space-separated words. Most words push themselves on a stack; some
4 words have another action. The result is the space-separated words
5 from the stack.
6
7 6 7 ADD => '13' 'ADD' is a special word
8 7 * 5 = 7 5 MUL => '7 * 5 = 35' '*' and '=' are not special words
9 3.8 => 3.8
10
11 Arithmetic on integers and floats automatically casts arguments
12 to floats (always).
13
14 3.8 1 ADD => 4.8
15
16 Input arguments can be passed on the command-line, and used as #1, #2, etc.:
17
18 #1 1 ADD => one more than the argument on the command-line,
19 or if it was not an integer, concatenates '+1'
20
21 You can store back into an (existing) argument index with ->#N:
22
23 #1 5 ADD ->#1
24
25 Braces { } delimitate a loop. Don't forget spaces around each one.
26 The '}' pops an integer value off the stack and loops if it is not zero:
27
28 { #1 #1 1 SUB ->#1 #1 } => when called with 5, gives '5 4 3 2 1'
29
30 """
31 from rpython.rlib.jit import promote, hint, JitDriver
32 from rpython.rlib.objectmodel import specialize
33
34 #
35 # See pypy/doc/jit.txt for a higher-level overview of the JIT techniques
36 # detailed in the following comments.
37 #
38
39
40 class Box:
41 # Although all words are in theory strings, we use two subclasses
42 # to represent the strings differently from the words known to be integers.
43 # This is an optimization that is essential for the JIT and merely
44 # useful for the basic interpreter.
45 pass
46
47 class IntBox(Box):
48 _immutable_ = True
49 def __init__(self, intval):
50 self.intval = intval
51 def as_int(self):
52 return self.intval
53 def as_float(self):
54 return myfloat(self.intval)
55 def as_str(self):
56 return str(self.intval)
57
58 class FloatBox(Box):
59 _immutable_ = True
60 def __init__(self, floatval):
61 self.floatval = floatval
62 def as_int(self):
63 return int(self.floatval)
64 def as_float(self):
65 return self.floatval
66 def as_str(self):
67 return str(self.floatval)
68
69 # consider if we need both
70 def func_add_int(ix, iy): return ix + iy
71 def func_sub_int(ix, iy): return ix - iy
72 def func_mul_int(ix, iy): return ix * iy
73
74 def func_add_float(fx, fy): return fx + fy
75 def func_sub_float(fx, fy): return fx - fy
76 def func_mul_float(fx, fy): return fx * fy
77
78 def op2(stack, func_int, func_float):
79 # Operate on the top two stack items. The promotion hints force the
80 # class of each arguments (IntBox or FloatBox) to turn into a compile-time
81 # constant if they weren't already. The effect we seek is to make the
82 # calls to as_int() direct calls at compile-time, instead of indirect
83 # ones. The JIT compiler cannot look into indirect calls, but it
84 # can analyze and inline the code in directly-called functions.
85 stack, y = stack.pop()
86 promote(y.__class__)
87 stack, x = stack.pop()
88 promote(x.__class__)
89 if isinstance(x, IntBox) and isinstance(y, IntBox):
90 z = IntBox(func_int(x.as_int(), y.as_int()))
91 else:
92 z = FloatBox(func_float(x.as_float(), y.as_float()))
93 stack = Stack(z, stack)
94 return stack
95
96 class Stack(object):
97 def __init__(self, value, next=None):
98 self.next = next
99 self.value = value
100
101 def pop(self):
102 return self.next, self.value
103
104 def empty_stack():
105 return None
106
107 class TinyJitDriver(JitDriver):
108 reds = ['args', 'loops', 'stack']
109 greens = ['bytecode', 'pos']
110
111 def compute_invariants(self, reds, bytecode, pos):
112 # Some of the information that we maintain only really depends on
113 # bytecode and pos: the whole 'loops' list has this property.
114 # By being a bit careful we could also put len(args) in the
115 # invariants, but although it doesn't make much sense it is a
116 # priori possible for the same bytecode to be run with
117 # different len(args).
118 return reds.loops
119
120 def on_enter_jit(self, invariants, reds, bytecode, pos):
121 # Now some strange code that makes a copy of the 'args' list in
122 # a complicated way... this is a workaround forcing the whole 'args'
123 # list to be virtual. It is a way to tell the JIT compiler that it
124 # doesn't have to worry about the 'args' list being unpredictably
125 # modified.
126 oldloops = invariants
127 oldargs = reds.args
128 argcount = promote(len(oldargs))
129 args = []
130 n = 0
131 while n < argcount:
132 hint(n, concrete=True)
133 args.append(oldargs[n])
134 n += 1
135 reds.args = args
136 # turn the green 'loops' from 'invariants' into a virtual list
137 oldloops = hint(oldloops, deepfreeze=True)
138 argcount = len(oldloops)
139 loops = []
140 n = 0
141 while n < argcount:
142 hint(n, concrete=True)
143 loops.append(oldloops[n])
144 n += 1
145 reds.loops = loops
146
147 tinyjitdriver = TinyJitDriver()
148
149 def interpret(bytecode, args):
150 """The interpreter's entry point and portal function.
151 """
152 loops = []
153 stack = empty_stack()
154 pos = 0
155 while True:
156 tinyjitdriver.jit_merge_point(args=args, loops=loops, stack=stack,
157 bytecode=bytecode, pos=pos)
158 bytecode = hint(bytecode, deepfreeze=True)
159 if pos >= len(bytecode):
160 break
161 opcode = bytecode[pos]
162 hint(opcode, concrete=True) # same as in tiny1.py
163 pos += 1
164 if opcode == 'ADD':
165 stack = op2(stack, func_add_int, func_add_float)
166 elif opcode == 'SUB':
167 stack = op2(stack, func_sub_int, func_sub_float)
168 elif opcode == 'MUL':
169 stack = op2(stack, func_mul_int, func_mul_float)
170 elif opcode[0] == '#':
171 n = myint(opcode, start=1)
172 stack = Stack(args[n-1], stack)
173 elif opcode.startswith('->#'):
174 n = myint(opcode, start=3)
175 if n > len(args):
176 raise IndexError
177 stack, args[n-1] = stack.pop()
178 elif opcode == '{':
179 loops.append(pos)
180 elif opcode == '}':
181 stack, flag = stack.pop()
182 if flag.as_int() == 0:
183 loops.pop()
184 else:
185 pos = loops[-1]
186 # A common problem when interpreting loops or jumps: the 'pos'
187 # above is read out of a list, so the hint-annotator thinks
188 # it must be red (not a compile-time constant). But the
189 # hint(opcode, concrete=True) in the next iteration of the
190 # loop requires all variables the 'opcode' depends on to be
191 # green, including this 'pos'. We promote 'pos' to a green
192 # here, as early as possible. Note that in practice the 'pos'
193 # read out of the 'loops' list will be a compile-time constant
194 # because it was pushed as a compile-time constant by the '{'
195 # case above into 'loops', which is a virtual list, so the
196 # promotion below is just a way to make the colors match.
197 pos = promote(pos)
198 tinyjitdriver.can_enter_jit(args=args, loops=loops, stack=stack,
199 bytecode=bytecode, pos=pos)
200 else:
201 try:
202 try:
203 v = IntBox(int(opcode))
204 except ValueError:
205 v = FloatBox(myfloat(opcode))
206 stack = Stack(v, stack)
207 except ValueError:
208 pass # ignore rest
209 return stack
210
211
212 def repr(stack):
213 # this bit moved out of the portal function because JIT'ing it is not
214 # very useful, and the JIT generator is confused by the 'for' right now...
215 lst = []
216 while stack:
217 stack, x = stack.pop()
218 lst.append(x.as_str())
219 lst.reverse()
220 return ' '.join(lst)
221
222
223 # ------------------------------
224 # Pure workaround code! It will eventually be unnecessary.
225 # For now, myint(s, n) is a JIT-friendly way to spell int(s[n:]).
226 # We don't support negative numbers, though.
227 def myint_internal(s, start=0):
228 if start >= len(s):
229 return -1
230 res = 0
231 while start < len(s):
232 c = s[start]
233 n = ord(c) - ord('0')
234 if not (0 <= n <= 9):
235 return -1
236 res = res * 10 + n
237 start += 1
238 return res
239 def myint(s, start=0):
240 n = myint_internal(s, start)
241 if n < 0:
242 raise ValueError
243 return n
244
245 @specialize.argtype(0)
246 def myfloat(i):
247 return float(i)
248 # ------------------------------
249
250
251 def test_main():
252 main = """#1 5 ADD""".split()
253 res = interpret(main, [IntBox(20)])
254 assert repr(res) == '25'
255 res = interpret(main, [FloatBox(3.2)])
256 assert repr(res) == '8.2'
257
258 FACTORIAL = """The factorial of #1 is
259 1 { #1 MUL #1 1 SUB ->#1 #1 }""".split()
260
261 def test_factorial():
262 res = interpret(FACTORIAL, [IntBox(5)])
263 assert repr(res) == '5 120'
264
265 FIBONACCI = """Fibonacci numbers:
266 { #1 #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 }""".split()
267
268 def test_fibonacci():
269 res = interpret(FIBONACCI, [IntBox(1), IntBox(1), IntBox(10)])
270 assert repr(res) == "1 1 2 3 5 8 13 21 34 55"
271
272
273 FIBONACCI_SINGLE = """#3 1 SUB ->#3 { #2 #1 #2 ADD ->#2 ->#1 #3 1 SUB ->#3 #3 } #1""".split()
274
275 def test_fibonacci_single():
276 res = interpret(FIBONACCI_SINGLE, [IntBox(1), IntBox(1), IntBox(11)])
277 assert repr(res) == "89"