Debian Codegraph @

pypy/interpreter/astcompiler/optimize.py

raw symbols SCIP
1 """codegen helpers and AST constant folding."""
2 import sys
3
4 from pypy.interpreter.astcompiler import ast, consts, misc
5 from pypy.tool import stdlib_opcode as ops
6 from pypy.interpreter.error import OperationError
7 from rpython.rlib.unroll import unrolling_iterable
8 from rpython.rlib.rutf8 import MAXUNICODE
9 from rpython.rlib.objectmodel import specialize
10
11
12 def optimize_ast(space, tree, compile_info):
13 return tree.mutate_over(OptimizingVisitor(space, compile_info))
14
15
16 CONST_NOT_CONST = -1
17 CONST_FALSE = 0
18 CONST_TRUE = 1
19
20
21 class __extend__(ast.AST):
22
23 def as_constant_truth(self, space, compile_info):
24 """Return the truth of this node if known."""
25 const = self.as_constant(space, compile_info)
26 if const is None:
27 return CONST_NOT_CONST
28 return int(space.is_true(const))
29
30 def as_constant(self, space, compile_info):
31 """Return the value of this node as a wrapped constant if possible."""
32 return None
33
34 def accept_jump_if(self, gen, condition, target):
35 raise AssertionError("only for expressions")
36
37
38 class __extend__(ast.expr):
39
40 def accept_jump_if(self, gen, condition, target):
41 test_constant = self.as_constant_truth(
42 gen.space, gen.compile_info)
43 if test_constant == CONST_NOT_CONST:
44 self.walkabout(gen)
45 if condition:
46 gen.emit_jump(ops.POP_JUMP_IF_TRUE, target)
47 else:
48 gen.emit_jump(ops.POP_JUMP_IF_FALSE, target)
49 return
50 gen.emit_line_tracing_nop(self)
51 if test_constant == condition:
52 gen.emit_jump(ops.JUMP_FORWARD, target)
53
54
55 class __extend__(ast.Constant):
56
57 def as_constant(self, space, compile_info):
58 return self.value
59
60 class __extend__(ast.Name):
61 def as_constant(self, space, compile_info):
62 if self.id == '__debug__':
63 return space.newbool(compile_info.optimize == 0)
64 else:
65 return None
66
67 class __extend__(ast.Slice):
68 def as_constant(self, space, compile_info):
69 # XXX: this ought to return a slice object if all the indices are
70 # constants
71 return None
72
73 class __extend__(ast.UnaryOp):
74
75 def accept_jump_if(self, gen, condition, target):
76 if self.op == ast.Not:
77 self.operand.accept_jump_if(gen, not condition, target)
78 else:
79 ast.expr.accept_jump_if(self, gen, condition, target)
80
81
82
83 class __extend__(ast.BoolOp):
84
85 def _accept_jump_if_any_is(self, gen, condition, target, skip_last=0):
86 for i in range(len(self.values) - skip_last):
87 self.values[i].accept_jump_if(gen, condition, target)
88
89 def accept_jump_if(self, gen, condition, target):
90 if condition and self.op == ast.And or \
91 (not condition and self.op == ast.Or):
92 end = gen.new_block()
93 self._accept_jump_if_any_is(gen, not condition, end, skip_last=1)
94 self.values[-1].accept_jump_if(gen, condition, target)
95 gen.use_next_block(end)
96 else:
97 self._accept_jump_if_any_is(gen, condition, target)
98
99
100 def _binary_fold(name):
101 def do_fold(space, left, right):
102 return getattr(space, name)(left, right)
103 return do_fold
104
105 def _unary_fold(name):
106 def do_fold(space, operand):
107 return getattr(space, name)(operand)
108 return do_fold
109
110 def _fold_pow(space, w_left, w_right):
111 # don't constant-fold if "w_left" and "w_right" are integers and
112 # the estimated bit length of the power is unreasonably large
113 space.appexec([w_left, w_right], """(left, right):
114 if isinstance(left, int) and isinstance(right, int):
115 if left.bit_length() * right > 5000:
116 raise OverflowError
117 """)
118 return space.pow(w_left, w_right, space.w_None)
119
120 def _fold_lshift(space, w_left, w_right):
121 # don't constant-fold if "w_left" and "w_right" are integers and
122 # the estimated bit length of the result is unreasonably large
123 space.appexec([w_left, w_right], """(left, right):
124 if isinstance(left, int) and isinstance(right, int):
125 if left.bit_length() + right > 1000:
126 raise OverflowError
127 """)
128 return space.lshift(w_left, w_right)
129
130 def _fold_not(space, operand):
131 return space.newbool(not space.is_true(operand))
132
133
134 binary_folders = {
135 ast.Add : _binary_fold("add"),
136 ast.Sub : _binary_fold("sub"),
137 ast.Mult : _binary_fold("mul"),
138 ast.Div : _binary_fold("truediv"),
139 ast.FloorDiv : _binary_fold("floordiv"),
140 ast.Mod : _binary_fold("mod"),
141 ast.Pow : _fold_pow,
142 ast.LShift : _fold_lshift,
143 ast.RShift : _binary_fold("rshift"),
144 ast.BitOr : _binary_fold("or_"),
145 ast.BitXor : _binary_fold("xor"),
146 ast.BitAnd : _binary_fold("and_"),
147 ast.MatMult : _binary_fold("matmul"),
148 }
149 unrolling_binary_folders = unrolling_iterable(binary_folders.items())
150
151 unary_folders = {
152 ast.Not : _fold_not,
153 ast.USub : _unary_fold("neg"),
154 ast.UAdd : _unary_fold("pos"),
155 ast.Invert : _unary_fold("invert")
156 }
157 unrolling_unary_folders = unrolling_iterable(unary_folders.items())
158
159 for folder in binary_folders.values() + unary_folders.values():
160 folder._always_inline_ = 'try'
161 del folder
162
163 opposite_compare_operations = misc.dict_to_switch({
164 ast.Is : ast.IsNot,
165 ast.IsNot : ast.Is,
166 ast.In : ast.NotIn,
167 ast.NotIn : ast.In
168 })
169
170
171 class OptimizingVisitor(ast.ASTVisitor):
172 """Constant folds AST."""
173
174 def __init__(self, space, compile_info):
175 self.space = space
176 self.compile_info = compile_info
177
178 @specialize.argtype(1)
179 def default_visitor(self, node):
180 return node
181
182 def visit_BinOp(self, binop):
183 left = binop.left.as_constant(self.space, self.compile_info)
184 if left is not None:
185 right = binop.right.as_constant(self.space, self.compile_info)
186 if right is not None:
187 op = binop.op
188 try:
189 for op_kind, folder in unrolling_binary_folders:
190 if op_kind == op:
191 w_const = folder(self.space, left, right)
192 break
193 else:
194 raise AssertionError("unknown binary operation")
195 # Let all errors be found at runtime.
196 except OperationError:
197 pass
198 else:
199 # To avoid blowing up the size of pyc files, we only fold
200 # reasonably sized sequences.
201 try:
202 w_len = self.space.len(w_const)
203 except OperationError:
204 pass
205 else:
206 if self.space.int_w(w_len) > 20:
207 return binop
208 return self.new_constant(w_const, binop)
209 return binop
210
211 def visit_UnaryOp(self, unary):
212 w_operand = unary.operand.as_constant(self.space, self.compile_info)
213 op = unary.op
214 if w_operand is not None:
215 try:
216 for op_kind, folder in unrolling_unary_folders:
217 if op_kind == op:
218 w_const = folder(self.space, w_operand)
219 break
220 else:
221 raise AssertionError("unknown unary operation")
222 w_minint = self.space.newint(-sys.maxint - 1)
223 # This makes sure the result is an integer.
224 if self.space.eq_w(w_minint, w_const):
225 w_const = w_minint
226 except OperationError:
227 pass
228 else:
229 return self.new_constant(w_const, unary)
230 elif op == ast.Not:
231 compare = unary.operand
232 if isinstance(compare, ast.Compare) and len(compare.ops) == 1:
233 cmp_op = compare.ops[0]
234 try:
235 opposite = opposite_compare_operations(cmp_op)
236 except KeyError:
237 pass
238 else:
239 compare.ops[0] = opposite
240 return compare
241 return unary
242
243 def visit_Name(self, name):
244 """Turn loading None, True, and False into a constant lookup."""
245 if name.ctx == ast.Del or name.ctx == ast.Store:
246 return name
247 space = self.space
248 w_const = None
249 if name.id == '__debug__':
250 w_const = space.newbool(self.compile_info.optimize == 0)
251 if w_const is not None:
252 return self.new_constant(w_const, name)
253 return name
254
255 def visit_Tuple(self, tup):
256 """Try to turn tuple building into a constant."""
257 if tup.ctx != ast.Load:
258 return tup # Don't do the rest for assignment or delete targets.
259 # It would replace Tuple([]) with Constant('()')!
260 if tup.elts:
261 consts_w = [None]*len(tup.elts)
262 for i in range(len(tup.elts)):
263 node = tup.elts[i]
264 w_const = node.as_constant(self.space, self.compile_info)
265 if w_const is None:
266 new_elts = self._optimize_constant_star_unpacks(tup.elts)
267 if new_elts is not None:
268 return ast.Tuple(new_elts, ast.Load, tup.lineno, tup.col_offset, tup.end_lineno, tup.end_col_offset)
269 return tup
270 consts_w[i] = w_const
271 # intern the string constants packed into the tuple here,
272 # because assemble.py will see the result as just a tuple constant
273 for i in range(len(consts_w)):
274 consts_w[i] = misc.intern_if_common_string(
275 self.space, consts_w[i])
276 else:
277 consts_w = []
278 w_consts = self.space.newtuple(consts_w)
279 return self.new_constant(w_consts, tup)
280
281 def _make_starred_tuple_const(self, consts_w, firstelt):
282 w_consts = self.space.newtuple(consts_w[:])
283 return ast.Starred(self.new_constant(
284 w_consts, firstelt),
285 ast.Load, firstelt.lineno, firstelt.col_offset,
286 firstelt.end_lineno, firstelt.end_col_offset)
287
288 def _optimize_constant_star_unpacks(self, elts):
289 # turn (1, 2, 3, *a) into (*(1, 2, 3), *a) with a constant (1, 2, 3)
290 # or similarly, for lists
291 contains_starred = False
292 for i in range(len(elts)):
293 elt = elts[i]
294 if isinstance(elt, ast.Starred):
295 contains_starred = True
296 break
297 if not contains_starred:
298 return None
299 new_elts = []
300 changed = False
301 const_since_last_star_w = []
302 after_last_star_index = 0
303 for i in range(len(elts)):
304 elt = elts[i]
305 if isinstance(elt, ast.Starred):
306 if (const_since_last_star_w is not None and
307 len(const_since_last_star_w) > 0):
308 firstelt = elts[after_last_star_index]
309 new_elts.append(self._make_starred_tuple_const(
310 const_since_last_star_w, firstelt))
311 changed = True
312 const_since_last_star_w = []
313 after_last_star_index = i + 1
314 new_elts.append(elt)
315 elif const_since_last_star_w is not None:
316 w_const = elt.as_constant(self.space, self.compile_info)
317 if w_const is None:
318 new_elts.extend(elts[after_last_star_index:i + 1])
319 const_since_last_star_w = None
320 else:
321 const_since_last_star_w.append(w_const)
322 else:
323 new_elts.append(elt)
324 if after_last_star_index != len(elts) and const_since_last_star_w is not None:
325 firstelt = elts[after_last_star_index]
326 new_elts.append(self._make_starred_tuple_const(
327 const_since_last_star_w, firstelt))
328 changed = True
329 if changed:
330 return new_elts
331
332 def visit_List(self, l):
333 if l.ctx == ast.Load and l.elts:
334 new_elts = self._optimize_constant_star_unpacks(l.elts)
335 if new_elts:
336 return ast.List(new_elts, ast.Load, l.lineno, l.col_offset, l.end_lineno, l.end_col_offset)
337 return l
338
339 def visit_Subscript(self, subs):
340 if subs.ctx == ast.Load:
341 w_obj = subs.value.as_constant(self.space, self.compile_info)
342 if w_obj is not None:
343 w_idx = subs.slice.as_constant(self.space, self.compile_info)
344 if w_idx is not None:
345 try:
346 w_const = self.space.getitem(w_obj, w_idx)
347 except OperationError:
348 # Let exceptions propagate at runtime.
349 return subs
350
351 # CPython issue5057: if v is unicode, there might
352 # be differences between wide and narrow builds in
353 # cases like u'\U00012345'[0].
354 # Wide builds will return a non-BMP char, whereas
355 # narrow builds will return a surrogate. In both
356 # the cases skip the optimization in order to
357 # produce compatible pycs.
358 if (self.space.isinstance_w(w_obj, self.space.w_unicode) and
359 self.space.isinstance_w(w_const, self.space.w_unicode)):
360 #unistr = self.space.utf8_w(w_const)
361 #if len(unistr) == 1:
362 # ch = ord(unistr[0])
363 #else:
364 # ch = 0
365 #if (ch > 0xFFFF or
366 # (MAXUNICODE == 0xFFFF and 0xD800 <= ch <= 0xDFFF)):
367 # --XXX-- for now we always disable optimization of
368 # u'...'[constant] because the tests above are not
369 # enough to fix issue5057 (CPython has the same
370 # problem as of April 24, 2012).
371 # See test_const_fold_unicode_subscr
372 return subs
373
374 return self.new_constant(w_const, subs)
375
376 return subs
377
378 def new_constant(self, const, node):
379 return ast.Constant(const, self.space.w_None, node.lineno, node.col_offset,
380 node.end_lineno, node.end_col_offset)