Debian Codegraph @

rpython/jit/backend/llsupport/regalloc.py

raw symbols SCIP
1 import sys
2 from rpython.jit.metainterp.history import Const, REF, JitCellToken
3 from rpython.rlib.objectmodel import we_are_translated, specialize
4 from rpython.jit.metainterp.resoperation import rop, AbstractResOpOrInputArg
5 from rpython.jit.metainterp.optimizeopt.info import AbstractInfo
6 from rpython.rtyper.lltypesystem import lltype
7 from rpython.rtyper.lltypesystem.lloperation import llop
8
9 try:
10 from collections import OrderedDict
11 except ImportError:
12 OrderedDict = dict # too bad
13
14 SAVE_DEFAULT_REGS = 0
15 SAVE_GCREF_REGS = 2
16 SAVE_ALL_REGS = 1
17
18 class TempVar(AbstractResOpOrInputArg): # this base class to get get_forwarded and set_forwarded
19 def __init__(self):
20 pass
21
22 def __repr__(self):
23 return "<TempVar at %s>" % (id(self),)
24
25 class NoVariableToSpill(Exception):
26 pass
27
28
29 def get_lifetime(box):
30 lifetime = box.get_forwarded()
31 if lifetime is None:
32 return None
33 assert isinstance(lifetime, Lifetime)
34 return lifetime
35
36 class BindingsIterItems(object):
37 def __init__(self, fm):
38 self.fm = fm
39 self.index = 0
40
41 def next(self):
42 while True:
43 index = self.index
44 if index >= self.fm.current_frame_depth:
45 raise StopIteration
46 box = self.fm.boxes_in_frame[index]
47 if box is None:
48 self.index = index + 1
49 continue
50 self.index = index + self.fm.frame_size(box.type)
51 lifetime = get_lifetime(box)
52 assert lifetime is not None
53 loc = lifetime.current_frame_loc
54 assert loc is not None
55 assert self.fm.get_loc_index(loc) == index
56 return box, lifetime.current_frame_loc
57
58 def __iter__(self):
59 return self
60
61
62 class FrameManager(object):
63 """ Manage frame positions
64
65 start_free_depth is the start where we can allocate in whatever order
66 we like.
67 """
68 def __init__(self, start_free_depth=0, freelist=None):
69 self.current_frame_depth = start_free_depth
70 self.boxes_in_frame = [None] * self.current_frame_depth
71
72 def freelist_len_for_tests(self):
73 res = 0
74 for box in self.boxes_in_frame:
75 res += int(box is None)
76 return res
77
78 def bindings_len_for_tests(self):
79 return len(self.boxes_in_frame) - self.freelist_len_for_tests()
80
81 def get_frame_depth(self):
82 return self.current_frame_depth
83
84 def _increase_frame_depth(self, incby):
85 self.current_frame_depth += incby
86 for i in range(incby):
87 self.boxes_in_frame.append(None)
88
89 def get(self, box):
90 lifetime = get_lifetime(box)
91 if lifetime is None:
92 return None
93 return lifetime.current_frame_loc
94
95 def loc(self, box, must_exist=False):
96 """Return or create the frame location associated with 'box'."""
97 # first check if it's already in the frame_manager
98 res = self.get(box)
99 if res is not None:
100 return res
101 if must_exist:
102 raise KeyError
103 return self.get_new_loc(box)
104
105 def get_new_loc(self, box):
106 size = self.frame_size(box.type)
107 hint = self.get_frame_pos_hint(box)
108 # frame_depth is rounded up to a multiple of 'size', assuming
109 # that 'size' is a power of two. The reason for doing so is to
110 # avoid obscure issues in jump.py with stack locations that try
111 # to move from position (6,7) to position (7,8).
112 newloc = self._find_frame_location(size, box.type, hint)
113 if newloc is None:
114 #
115 index = self.get_frame_depth()
116 if size == 2 and index & 1 == 1:
117 # we can't allocate it at odd position
118 if self.boxes_in_frame[index - 1] is None:
119 index -= 1
120 else:
121 index += 1
122 newloc = self.frame_pos(index, box.type)
123 self._increase_frame_depth(index + size - self.current_frame_depth)
124 else:
125 newloc = self.frame_pos(index, box.type)
126 self._increase_frame_depth(size)
127 #
128 if not we_are_translated(): # extra testing
129 testindex = self.get_loc_index(newloc)
130 assert testindex == index
131 for index in range(testindex, testindex+size):
132 assert self.boxes_in_frame[index] is None
133 #
134 if not we_are_translated():
135 assert self.boxes_in_frame[self.get_loc_index(newloc)] is None
136
137 self.bind(box, newloc)
138 if not we_are_translated():
139 self._check_invariants()
140 return newloc
141
142 def _find_frame_location(self, size, tp, hint=-1):
143 assert size == 1 or size == 2
144 if size == 1:
145 if (0 <= hint < self.current_frame_depth and
146 self.boxes_in_frame[hint] is None):
147 resindex = hint
148 else:
149 for resindex in range(self.current_frame_depth):
150 if self.boxes_in_frame[resindex] is None:
151 break
152 else:
153 return None # no free location that fits
154 else:
155 assert size == 2
156 for resindex in range(0, (self.current_frame_depth >> 1) << 1, 2):
157 if (self.boxes_in_frame[resindex] is None and
158 self.boxes_in_frame[resindex + 1] is None):
159 break
160 else:
161 return None
162 return self.frame_pos(resindex, tp)
163
164 def bind(self, box, loc):
165 pos = self.get_loc_index(loc)
166 size = self.frame_size(box.type)
167 if pos + size > self.current_frame_depth:
168 self._increase_frame_depth(pos + size - self.current_frame_depth)
169 assert self.boxes_in_frame[pos] is None
170 if not we_are_translated():
171 assert box not in self.boxes_in_frame
172 for index in range(pos, pos + size):
173 self.boxes_in_frame[index] = box
174 lifetime = get_lifetime(box)
175 assert lifetime is not None
176 lifetime.current_frame_loc = loc
177
178 def bindings_iteritems(self):
179 return BindingsIterItems(self)
180
181 def finish_binding(self):
182 if not we_are_translated():
183 self._check_invariants()
184
185 def mark_as_free(self, box):
186 loc = self.get(box)
187 if loc is None:
188 return # not in frame
189 lifetime = get_lifetime(box)
190 assert lifetime.current_frame_loc is loc
191 lifetime.current_frame_loc = None
192 pos = self.get_loc_index(loc)
193 size = self.frame_size(box.type)
194 assert self.boxes_in_frame[pos] is box
195 for index in range(pos, pos + size):
196 self.boxes_in_frame[index] = None
197
198 if not we_are_translated():
199 self._check_invariants()
200
201 def add_frame_pos_hint(self, box, loc):
202 lifetime = get_lifetime(box)
203 assert lifetime is not None
204 lifetime.hint_frame_pos = self.get_loc_index(loc)
205
206 def get_frame_pos_hint(self, box):
207 lifetime = get_lifetime(box)
208 if lifetime is None:
209 return -1
210 return lifetime.hint_frame_pos
211
212 def _check_invariants(self):
213 assert len(self.boxes_in_frame) == self.current_frame_depth
214 all = [False] * self.get_frame_depth()
215 for b, loc in self.bindings_iteritems():
216 size = self.frame_size(b.type)
217 pos = self.get_loc_index(loc)
218 for i in range(pos, pos + size):
219 assert not all[i]
220 all[i] = True
221 assert self.boxes_in_frame[i] is b
222
223 @staticmethod
224 def _gather_gcroots(lst, var):
225 lst.append(var)
226
227 # abstract methods that need to be overwritten for specific assemblers
228
229 def frame_pos(loc, type):
230 raise NotImplementedError("Purely abstract")
231
232 @staticmethod
233 def frame_size(type):
234 return 1
235
236 @staticmethod
237 def get_loc_index(loc):
238 raise NotImplementedError("Purely abstract")
239
240 @staticmethod
241 def newloc(pos, size, tp):
242 """ Reverse of get_loc_index
243 """
244 raise NotImplementedError("Purely abstract")
245
246 class RegBindingsDict(object):
247 def __init__(self, regman):
248 self.regman = regman
249
250 def _register_index(self, reg):
251 return self.regman.all_regs.index(reg)
252
253 def __contains__(self, box):
254 lifetime = get_lifetime(box)
255 if lifetime is None:
256 return False
257 index = lifetime.current_register_index
258 return index >= 0
259
260 def __getitem__(self, box):
261 res = self.regman.reg_bindings_get(box)
262 if res is None:
263 raise KeyError
264 return res
265
266 def get(self, box, default=None):
267 return self.regman.reg_bindings_get(box, default)
268
269 def pop(self, box):
270 lifetime = get_lifetime(box)
271 if lifetime is None:
272 raise KeyError
273 index = lifetime.current_register_index
274 if index >= 0:
275 result = self.regman.all_regs[index]
276 self.regman.reg_bindings_list[index] = None
277 lifetime.current_register_index = -1
278 return result
279 raise KeyError
280
281 def __setitem__(self, box, reg):
282 lifetime = get_lifetime(box)
283 assert lifetime is not None
284 index = lifetime.current_register_index
285 if index >= 0:
286 self.regman.reg_bindings_list[index] = None
287 newindex = lifetime.current_register_index = self._register_index(reg)
288 self.regman.reg_bindings_list[newindex] = box
289
290 def __delitem__(self, box):
291 lifetime = get_lifetime(box)
292 assert lifetime is not None
293 index = lifetime.current_register_index
294 if index < 0:
295 raise KeyError
296 self.regman.reg_bindings_list[lifetime.current_register_index] = None
297 lifetime.current_register_index = -1
298
299 def __len__(self):
300 res = 0
301 for box in self.regman.reg_bindings_list:
302 if box is not None:
303 res += 1
304 return res
305
306 def values(self):
307 res = []
308 for i in range(len(self.regman.all_regs)):
309 box = self.regman.reg_bindings_list[i]
310 if box is not None:
311 res.append(self.regman.all_regs[i])
312 return res
313
314 def keys(self):
315 return [box for box in self.regman.reg_bindings_list if box is not None]
316
317 def items(self):
318 res = []
319 for i in range(len(self.regman.all_regs)):
320 box = self.regman.reg_bindings_list[i]
321 if box is not None:
322 res.append((box, self.regman.all_regs[i]))
323 return res
324
325 def iteritems(self):
326 return self.regman.reg_bindings_iteritems()
327
328 def __nonzero__(self):
329 assert False, '__nonzero__ is not rpython'
330
331 class RegBindingsIterItems(object):
332 def __init__(self, rm):
333 self.rm = rm
334 self.index = -1
335
336 def next(self):
337 index = self.index = RegBindingsIterItems._next(self.index + 1, self.rm)
338 return self.rm.reg_bindings_list[index], self.rm.all_regs[index]
339
340 @staticmethod
341 def _next(index, rm):
342 while True:
343 if index >= len(rm.reg_bindings_list):
344 raise StopIteration
345 box = rm.reg_bindings_list[index]
346 if box is None:
347 index += 1
348 continue
349 return index
350
351 def __iter__(self):
352 return self
353
354
355
356 class RegisterManager(object):
357
358 """ Class that keeps track of register allocations
359 """
360
361 box_types = None # or a list of acceptable types
362 all_regs = []
363 no_lower_byte_regs = []
364 save_around_call_regs = []
365 frame_reg = None
366 FORBID_TEMP_BOXES = False
367
368 def __init__(self, longevity, frame_manager=None, assembler=None):
369 self.free_regs = self.all_regs[:]
370 self.free_regs.reverse()
371 self.reg_bindings_list = [None] * len(self.all_regs)
372 self.longevity = longevity
373 self.temp_boxes = []
374 self.reg_bindings = RegBindingsDict(self)
375 self.box_currently_in_frame_reg = None
376 self.position = -1
377 self.frame_manager = frame_manager
378 self.assembler = assembler
379
380 def is_still_alive(self, v):
381 # Check if 'v' is alive at the current position.
382 # Return False if the last usage is strictly before.
383 return self.longevity[v].last_usage >= self.position
384
385 def stays_alive(self, v):
386 # Check if 'v' stays alive after the current position.
387 # Return False if the last usage is before or at position.
388 return self.longevity[v].last_usage > self.position
389
390 def next_instruction(self, incr=1):
391 self.position += incr
392
393 def reg_bindings_get(self, box, default=None):
394 lifetime = get_lifetime(box)
395 if lifetime is None:
396 return default
397 index = lifetime.current_register_index
398 if index >= 0:
399 return self.all_regs[index]
400 return default
401
402 def reg_bindings_iteritems(self):
403 return RegBindingsIterItems(self)
404
405 def _check_type(self, v):
406 if not we_are_translated() and self.box_types is not None:
407 assert isinstance(v, TempVar) or v.type in self.box_types
408
409 def possibly_free_var(self, v):
410 """ If v is stored in a register and v is not used beyond the
411 current position, then free it. Must be called at some
412 point for all variables that might be in registers.
413 """
414 self._check_type(v)
415 if isinstance(v, Const):
416 return
417 if v not in self.longevity or self.longevity[v].last_usage <= self.position:
418 reg = self.reg_bindings_get(v)
419 if reg is not None:
420 self.free_regs.append(reg)
421 del self.reg_bindings[v]
422 if v is self.box_currently_in_frame_reg:
423 self.box_currently_in_frame_reg = None
424 if self.frame_manager is not None:
425 self.frame_manager.mark_as_free(v)
426
427 def possibly_free_vars(self, vars):
428 """ Same as 'possibly_free_var', but for all v in vars.
429 """
430 for v in vars:
431 self.possibly_free_var(v)
432
433 def possibly_free_vars_for_op(self, op):
434 for i in range(op.numargs()):
435 self.possibly_free_var(op.getarg(i))
436
437 def free_temp_vars(self):
438 self.possibly_free_vars(self.temp_boxes)
439 self.temp_boxes = []
440
441 def _check_invariants(self):
442 if not we_are_translated():
443 # make sure no duplicates
444 assert len(dict.fromkeys(self.reg_bindings.values())) == len(self.reg_bindings)
445 rev_regs = dict.fromkeys(self.reg_bindings.values())
446 for reg in self.free_regs:
447 assert reg not in rev_regs
448 assert len(rev_regs) + len(self.free_regs) == len(self.all_regs)
449 for index, reg in enumerate(self.all_regs):
450 box = self.reg_bindings_list[index]
451 if reg not in self.free_regs:
452 lifetime = self.longevity[box]
453 assert lifetime is not None
454 assert lifetime.current_register_index == index
455 assert lifetime.last_usage > self.position
456 else:
457 assert box is None
458 assert len(self.temp_boxes) == 0
459
460 def try_allocate_reg(self, v, selected_reg=None, need_lower_byte=False):
461 """ Try to allocate a register, if we have one free.
462 need_lower_byte - if True, allocate one that has a lower byte reg
463 (e.g. eax has al)
464 selected_reg - if not None, force a specific register
465
466 returns allocated register or None, if not possible.
467 """
468 self._check_type(v)
469 if isinstance(v, TempVar):
470 self.longevity[v] = Lifetime(self.position, self.position)
471 # YYY all subtly similar code
472 assert not isinstance(v, Const)
473 if selected_reg is not None:
474 res = self.reg_bindings_get(v)
475 if res is not None:
476 if res is selected_reg:
477 return res
478 else:
479 del self.reg_bindings[v]
480 self.free_regs.append(res)
481 if selected_reg in self.free_regs:
482 self.free_regs = [reg for reg in self.free_regs
483 if reg is not selected_reg]
484 self.reg_bindings[v] = selected_reg
485 return selected_reg
486 return None
487 if need_lower_byte:
488 loc = self.reg_bindings_get(v)
489 if loc is not None and loc not in self.no_lower_byte_regs:
490 return loc
491 free_regs = [reg for reg in self.free_regs
492 if reg not in self.no_lower_byte_regs]
493 newloc = self.longevity.try_pick_free_reg(
494 self.position, v, free_regs)
495 if newloc is None:
496 return None
497 self.free_regs.remove(newloc)
498 if loc is not None:
499 self.free_regs.append(loc)
500 self.reg_bindings[v] = newloc
501 return newloc
502 res = self.reg_bindings_get(v)
503 if res is not None:
504 return res
505 else:
506 loc = self.longevity.try_pick_free_reg(
507 self.position, v, self.free_regs)
508 if loc is None:
509 return None
510 self.reg_bindings[v] = loc
511 self.free_regs.remove(loc)
512 return loc
513
514 def _spill_var(self, forbidden_vars, selected_reg,
515 need_lower_byte=False):
516 v_to_spill = self._pick_variable_to_spill(forbidden_vars,
517 selected_reg, need_lower_byte=need_lower_byte)
518 loc = self.reg_bindings[v_to_spill]
519 self._sync_var_to_stack(v_to_spill)
520 del self.reg_bindings[v_to_spill]
521 return loc
522
523 def _pick_variable_to_spill(self, forbidden_vars, selected_reg=None,
524 need_lower_byte=False, regs=None):
525
526 # try to spill a variable that has no further real usages, ie that only
527 # appears in failargs or in a jump
528 # if that doesn't exist, spill the variable that has a real_usage that
529 # is the furthest away from the current position
530
531 # YYY check for fixed variable usages
532 if regs is None:
533 regs = self.reg_bindings.keys()
534
535 cur_max_use_distance = -1
536 position = self.position
537 candidate = None
538 cur_max_age_failargs = -1
539 candidate_from_failargs = None
540 for next in regs:
541 reg = self.reg_bindings[next]
542 if next in forbidden_vars:
543 continue
544 if self.FORBID_TEMP_BOXES and next in self.temp_boxes:
545 continue
546 if selected_reg is not None:
547 if reg is selected_reg:
548 return next
549 else:
550 continue
551 if need_lower_byte and reg in self.no_lower_byte_regs:
552 continue
553 lifetime = self.longevity[next]
554 if lifetime.is_last_real_use_before(position):
555 # this variable has no "real" use as an argument to an op left
556 # it is only used in failargs, and maybe in a jump. spilling is
557 # fine
558 max_age = lifetime.last_usage
559 if cur_max_age_failargs < max_age:
560 cur_max_age_failargs = max_age
561 candidate_from_failargs = next
562 else:
563 use_distance = lifetime.next_real_usage(position) - position
564 if cur_max_use_distance < use_distance:
565 cur_max_use_distance = use_distance
566 candidate = next
567 if candidate_from_failargs is not None:
568 return candidate_from_failargs
569 if candidate is not None:
570 return candidate
571 raise NoVariableToSpill
572
573 def force_allocate_reg(self, v, forbidden_vars=[], selected_reg=None,
574 need_lower_byte=False):
575 """ Forcibly allocate a register for the new variable v.
576 It must not be used so far. If we don't have a free register,
577 spill some other variable, according to algorithm described in
578 '_pick_variable_to_spill'.
579
580 Will not spill a variable from 'forbidden_vars'.
581 """
582 self._check_type(v)
583 if isinstance(v, TempVar):
584 self.longevity[v] = Lifetime(self.position, self.position)
585 loc = self.try_allocate_reg(v, selected_reg,
586 need_lower_byte=need_lower_byte)
587 if loc:
588 return loc
589 loc = self._spill_var(forbidden_vars, selected_reg,
590 need_lower_byte=need_lower_byte)
591 prev_loc = self.reg_bindings_get(v)
592 if prev_loc is not None:
593 self.free_regs.append(prev_loc)
594 self.reg_bindings[v] = loc
595 return loc
596
597 def force_allocate_frame_reg(self, v):
598 """ Allocate the new variable v in the frame register."""
599 assert self.box_currently_in_frame_reg is None
600 self.box_currently_in_frame_reg = v
601
602 def force_spill_var(self, var):
603 self._sync_var_to_stack(var)
604 try:
605 loc = self.reg_bindings[var]
606 del self.reg_bindings[var]
607 self.free_regs.append(loc)
608 except KeyError:
609 pass # 'var' is already not in a register
610
611 def loc(self, box, must_exist=False):
612 """ Return the location of 'box'.
613 """
614 self._check_type(box)
615 if isinstance(box, Const):
616 return self.convert_to_imm(box)
617 res = self.reg_bindings_get(box)
618 if res is not None:
619 return res
620 if box is self.box_currently_in_frame_reg:
621 return self.frame_reg
622 return self.frame_manager.loc(box, must_exist)
623
624
625 def return_constant(self, v, forbidden_vars=[], selected_reg=None):
626 """ Return the location of the constant v. If 'selected_reg' is
627 not None, it will first load its value into this register.
628 """
629 self._check_type(v)
630 assert isinstance(v, Const)
631 immloc = self.convert_to_imm(v)
632 if selected_reg:
633 if selected_reg in self.free_regs:
634 self.assembler.regalloc_mov(immloc, selected_reg)
635 return selected_reg
636 loc = self._spill_var(forbidden_vars, selected_reg)
637 self.free_regs.append(loc)
638 self.assembler.regalloc_mov(immloc, loc)
639 return loc
640 return immloc
641
642 def make_sure_var_in_reg(self, v, forbidden_vars=[], selected_reg=None,
643 need_lower_byte=False):
644 """ Make sure that an already-allocated variable v is in some
645 register. Return the register. See 'force_allocate_reg' for
646 the meaning of the optional arguments.
647 """
648 self._check_type(v)
649 if isinstance(v, Const):
650 return self.return_constant(v, forbidden_vars, selected_reg)
651 prev_loc = self.loc(v, must_exist=True)
652 if prev_loc is self.frame_reg and selected_reg is None:
653 return prev_loc
654 loc = self.force_allocate_reg(v, forbidden_vars, selected_reg,
655 need_lower_byte=need_lower_byte)
656 if prev_loc is not loc:
657 self.assembler.num_reloads += 1
658 self.assembler.regalloc_mov(prev_loc, loc)
659 return loc
660
661 def _reallocate_from_to(self, from_v, to_v):
662 reg = self.reg_bindings[from_v]
663 del self.reg_bindings[from_v]
664 self.reg_bindings[to_v] = reg
665 return reg
666
667 def force_result_in_reg(self, result_v, v, forbidden_vars=[]):
668 """ Make sure that result is in the same register as v.
669 The variable v is copied away if it's further used. The meaning
670 of 'forbidden_vars' is the same as in 'force_allocate_reg'.
671 """
672 self._check_type(result_v)
673 self._check_type(v)
674 if isinstance(v, Const):
675 result_loc = self.force_allocate_reg(result_v, forbidden_vars)
676 self.assembler.regalloc_mov(self.convert_to_imm(v), result_loc)
677 return result_loc
678 v_keeps_living = self.longevity[v].last_usage > self.position
679 # there are two cases where we should allocate a new register for
680 # result:
681 # 1) v is itself not in a register
682 # 2) v keeps on being live. if there is a free register, we need a move
683 # anyway, so we can use force_allocate_reg on result_v to make sure any
684 # fixed registers are used
685 if (v not in self.reg_bindings or (v_keeps_living and self.free_regs)):
686 v_loc = self.loc(v)
687 result_loc = self.force_allocate_reg(result_v, forbidden_vars)
688 self.assembler.regalloc_mov(v_loc, result_loc)
689 return result_loc
690 if v_keeps_living:
691 # since there are no free registers, v needs to go to the stack.
692 # sync it there.
693 self._sync_var_to_stack(v)
694 return self._reallocate_from_to(v, result_v)
695
696 def _sync_var_to_stack(self, v):
697 self.assembler.num_spills += 1
698 if not self.frame_manager.get(v):
699 reg = self.reg_bindings[v]
700 to = self.frame_manager.loc(v)
701 self.assembler.regalloc_mov(reg, to)
702 else:
703 self.assembler.num_spills_to_existing += 1
704 # otherwise it's clean
705
706 def _bc_spill(self, v, new_free_regs):
707 self._sync_var_to_stack(v)
708 new_free_regs.append(self.reg_bindings.pop(v))
709
710 def before_call(self, force_store=[], save_all_regs=0):
711 self.spill_or_move_registers_before_call(self.save_around_call_regs,
712 force_store, save_all_regs)
713
714 def spill_or_move_registers_before_call(self, save_sublist,
715 force_store=[],
716 save_all_regs=SAVE_DEFAULT_REGS):
717 """Spill or move some registers before a call.
718
719 By default, this means: for every register in 'save_sublist',
720 if there is a variable there and it survives longer than
721 the current operation, then it is spilled/moved somewhere else.
722
723 WARNING: this might do the equivalent of possibly_free_vars()
724 on variables dying in the current operation. It won't
725 immediately overwrite registers that used to be occupied by
726 these variables, though. Use this function *after* you finished
727 calling self.loc() or self.make_sure_var_in_reg(), i.e. when you
728 know the location of all input arguments. These locations stay
729 valid, but only *if they are in self.save_around_call_regs,*
730 not if they are callee-saved registers!
731
732 'save_all_regs' can be SAVE_DEFAULT_REGS (default set of registers),
733 SAVE_ALL_REGS (do that for all registers), or SAVE_GCREF_REGS (default
734 + gc ptrs).
735
736 Overview of what we do (the implementation does it differently,
737 for the same result):
738
739 * we first check the set of registers that are free: call it F.
740
741 * possibly_free_vars() is implied for all variables (except
742 the ones listed in force_store): if they don't survive past
743 the current operation, they are forgotten now. (Their
744 register remain not in F, because they are typically
745 arguments to the call, so they should not be overwritten by
746 the next step.)
747
748 * then for every variable that needs to be spilled/moved: if
749 there is an entry in F that is acceptable, pick it and emit a
750 move. Otherwise, emit a spill. Start doing this with the
751 variables that survive the shortest time, to give them a
752 better change to remain in a register---similar algo as
753 _pick_variable_to_spill().
754
755 Note: when a register is moved, it often (but not always) means
756 we could have been more clever and picked a better register in
757 the first place, when we did so earlier. It is done this way
758 anyway, as a local hack in this function, because on x86 CPUs
759 such register-register moves are almost free.
760 """
761 if not we_are_translated():
762 # 'save_sublist' is either the whole
763 # 'self.save_around_call_regs', or a sublist thereof, and
764 # then only those registers are spilled/moved. But when
765 # we move them, we never move them to other registers in
766 # 'self.save_around_call_regs', to avoid ping-pong effects
767 # where the same value is constantly moved around.
768 for reg in save_sublist:
769 assert reg in self.save_around_call_regs
770
771 new_free_regs = []
772 move_or_spill = []
773
774 for v, reg in self.reg_bindings.items():
775 max_age = self.longevity[v].last_usage
776 if v not in force_store and max_age <= self.position:
777 # variable dies
778 del self.reg_bindings[v]
779 new_free_regs.append(reg)
780 continue
781
782 if save_all_regs == SAVE_ALL_REGS:
783 # we need to spill all registers in this mode
784 self._bc_spill(v, new_free_regs)
785 #
786 elif save_all_regs == SAVE_GCREF_REGS and v.type == REF:
787 # we need to spill all GC ptrs in this mode
788 self._bc_spill(v, new_free_regs)
789 #
790 elif reg not in save_sublist:
791 continue # in a register like ebx/rbx: it is fine where it is
792 #
793 else:
794 # this is a register like eax/rax, which needs either
795 # spilling or moving.
796 move_or_spill.append(v)
797
798 if len(move_or_spill) > 0:
799 free_regs = [reg for reg in self.free_regs
800 if reg not in self.save_around_call_regs]
801 # chose which to spill using the usual spill heuristics
802 while len(move_or_spill) > len(free_regs):
803 v = self._pick_variable_to_spill([], regs=move_or_spill)
804 self._bc_spill(v, new_free_regs)
805 move_or_spill.remove(v)
806 assert len(move_or_spill) <= len(free_regs)
807 for v in move_or_spill:
808 # search next good reg
809 new_reg = None
810 while True:
811 new_reg = self.free_regs.pop()
812 if new_reg in self.save_around_call_regs:
813 new_free_regs.append(new_reg) # not this register...
814 continue
815 break
816 assert new_reg is not None # must succeed
817 reg = self.reg_bindings[v]
818 self.assembler.num_moves_calls += 1
819 self.assembler.regalloc_mov(reg, new_reg)
820 self.reg_bindings[v] = new_reg # change the binding
821 new_free_regs.append(reg)
822
823 # re-add registers in 'new_free_regs', but in reverse order,
824 # so that the last ones (added just above, from
825 # save_around_call_regs) are picked last by future '.pop()'
826 while len(new_free_regs) > 0:
827 self.free_regs.append(new_free_regs.pop())
828
829 def after_call(self, v):
830 """ Adjust registers according to the result of the call,
831 which is in variable v.
832 """
833 self._check_type(v)
834 r = self.call_result_location(v)
835 if not we_are_translated():
836 assert r not in self.reg_bindings.values()
837 self.reg_bindings[v] = r
838 self.free_regs = [fr for fr in self.free_regs if fr is not r]
839 return r
840
841 # abstract methods, override
842
843 def convert_to_imm(self, c):
844 """ Platform specific - convert a constant to imm
845 """
846 raise NotImplementedError("Abstract")
847
848 def call_result_location(self, v):
849 """ Platform specific - tell where the result of a call will
850 be stored by the cpu, according to the variable type
851 """
852 raise NotImplementedError("Abstract")
853
854 def get_scratch_reg(self, type, forbidden_vars=[], selected_reg=None):
855 """ Platform specific - Allocates a temporary register """
856 raise NotImplementedError("Abstract")
857
858 class BaseRegalloc(object):
859 """ Base class on which all the backend regallocs should be based
860 """
861 def _set_initial_bindings(self, inputargs, looptoken):
862 """ Set the bindings at the start of the loop
863 """
864 locs = []
865 base_ofs = self.assembler.cpu.get_baseofs_of_frame_field()
866 for box in inputargs:
867 assert not isinstance(box, Const)
868 loc = self.fm.get_new_loc(box)
869 locs.append(loc.value - base_ofs)
870 if looptoken.compiled_loop_token is not None: # <- for tests
871 looptoken.compiled_loop_token._ll_initial_locs = locs
872
873 def next_op_can_accept_cc(self, operations, i):
874 op = operations[i]
875 next_op = operations[i + 1]
876 opnum = next_op.getopnum()
877 if (opnum != rop.GUARD_TRUE and opnum != rop.GUARD_FALSE
878 and opnum != rop.COND_CALL):
879 return False
880 # NB: don't list COND_CALL_VALUE_I/R here, these two variants
881 # of COND_CALL don't accept a cc as input
882 if next_op.getarg(0) is not op:
883 return False
884 if self.longevity[op].last_usage > i + 1:
885 return False
886 if opnum != rop.COND_CALL:
887 if op in operations[i + 1].getfailargs():
888 return False
889 else:
890 if op in operations[i + 1].getarglist()[1:]:
891 return False
892 return True
893
894 def locs_for_call_assembler(self, op):
895 descr = op.getdescr()
896 assert isinstance(descr, JitCellToken)
897 if op.numargs() == 2:
898 self.rm._sync_var_to_stack(op.getarg(1))
899 return [self.loc(op.getarg(0)), self.fm.loc(op.getarg(1))]
900 else:
901 assert op.numargs() == 1
902 return [self.loc(op.getarg(0))]
903
904
905 # ____________________________________________________________
906
907
908
909 UNDEF_POS = -42
910
911 class Lifetime(AbstractInfo):
912 def __init__(self, definition_pos=UNDEF_POS, last_usage=UNDEF_POS):
913 # all positions are indexes into the operations list
914
915 # the position where the variable is defined
916 self.definition_pos = definition_pos
917 # the position where the variable is last used. this includes failargs
918 # and jumps
919 self.last_usage = last_usage
920
921 # *real* usages, ie as an argument to an operation (as opposed to jump
922 # arguments or in failargs)
923 self.real_usages = None
924
925 # fixed registers are positions where the variable *needs* to be in a
926 # specific register
927 self.fixed_positions = None
928
929 # another Lifetime that lives after the current one that would like to
930 # share a register with this variable
931 self.share_with = None
932
933 # the other lifetime will have this variable set to self.definition_pos
934 self._definition_pos_shared = UNDEF_POS
935
936 # the current register index where the backend stores the box
937 # the index is for the relevant RegisterManager's all_regs list
938 self.current_register_index = -1
939
940 # the frame location where the box currently lives
941 self.current_frame_loc = None
942
943 # the hinted frame location (at the end of the trace)
944 self.hint_frame_pos = -1
945
946 def last_usage_including_sharing(self):
947 while self.share_with is not None:
948 self = self.share_with
949 return self.last_usage
950
951 def is_last_real_use_before(self, position):
952 if self.real_usages is None:
953 return True
954 return self.real_usages[-1] <= position
955
956 def next_real_usage(self, position):
957 assert position >= self.definition_pos
958 # binary search
959 l = self.real_usages
960 low = 0
961 high = len(l)
962 if position >= l[-1]:
963 return -1
964 while low < high:
965 mid = low + (high - low) // 2 # no overflow ;-)
966 if position < l[mid]:
967 high = mid
968 else:
969 low = mid + 1
970 return l[low]
971
972 def definition_pos_shared(self):
973 if self._definition_pos_shared != UNDEF_POS:
974 return self._definition_pos_shared
975 else:
976 return self.definition_pos
977
978 def fixed_register(self, position, reg):
979 """ registers a fixed register use for the variable at position in
980 register reg. returns the position from where on the register should be
981 held free. """
982 assert self.definition_pos <= position <= self.last_usage
983 if self.fixed_positions is None:
984 self.fixed_positions = []
985 res = self.definition_pos_shared()
986 else:
987 assert position > self.fixed_positions[-1][0]
988 res = self.fixed_positions[-1][0]
989 self.fixed_positions.append((position, reg))
990 return res
991
992 def find_fixed_register(self, opindex):
993 # XXX could use binary search
994 if self.fixed_positions is not None:
995 for (index, reg) in self.fixed_positions:
996 if opindex <= index:
997 return reg
998 if self.share_with is not None:
999 return self.share_with.find_fixed_register(opindex)
1000
1001 def _check_invariants(self):
1002 assert self.definition_pos <= self.last_usage
1003 if self.real_usages is not None:
1004 assert sorted(self.real_usages) == self.real_usages
1005 assert self.last_usage >= max(self.real_usages)
1006 assert self.definition_pos < min(self.real_usages)
1007
1008 def __repr__(self):
1009 if self.fixed_positions:
1010 s = " " + ", ".join("@%s in %s" % (index, reg) for (index, reg) in self.fixed_positions)
1011 else:
1012 s = ""
1013 register = ""
1014 if self.current_register_index >= 0:
1015 register = " current register index: %s" % (self.current_register_index, )
1016 frame = ""
1017 if self.current_frame_loc:
1018 frame = " curren frame loc: %s" % (self.current_frame_loc, )
1019 frame_hint = ""
1020 if self.hint_frame_pos >= 0:
1021 frame_hint = " frame hint: %s" % (self.hint_frame_pos, )
1022 return "%s:%s(%s)%s%s%s%s" % (self.definition_pos, self.real_usages, self.last_usage, s, register, frame, frame_hint)
1023
1024
1025 class FixedRegisterPositions(object):
1026 def __init__(self, register):
1027 self.register = register
1028
1029 self.index_lifetimes = []
1030
1031 def fixed_register(self, opindex, definition_pos):
1032 if self.index_lifetimes:
1033 assert opindex > self.index_lifetimes[-1][0]
1034 self.index_lifetimes.append((opindex, definition_pos))
1035
1036 def free_until_pos(self, opindex):
1037 # XXX could use binary search
1038 for (index, definition_pos) in self.index_lifetimes:
1039 if opindex <= index:
1040 if definition_pos >= opindex:
1041 return definition_pos
1042 else:
1043 # the variable doesn't exist or didn't make it into the
1044 # register despite being defined already. so we don't care
1045 # too much, and can say that the variable is free until
1046 # index
1047 return index
1048 return sys.maxint
1049
1050 def __repr__(self):
1051 return "%s: fixed at %s" % (self.register, self.index_lifetimes)
1052
1053
1054 class LifetimeManager(object):
1055 def __init__(self, longevity=None):
1056 if we_are_translated():
1057 assert longevity is None
1058 else:
1059 if longevity:
1060 # old interface for tests
1061 for box, lifetime in longevity.iteritems():
1062 self[box] = lifetime
1063 # dictionary maps register to FixedRegisterPositions
1064 self.fixed_register_use = {}
1065
1066 def fixed_register(self, opindex, register, var=None):
1067 """ Tell the LifetimeManager that variable var *must* be in register at
1068 operation opindex. var can be None, if no variable at all can be in
1069 that register at the point."""
1070 if var is None:
1071 definition_pos = opindex
1072 else:
1073 varlifetime = self[var]
1074 definition_pos = varlifetime.fixed_register(opindex, register)
1075 if register not in self.fixed_register_use:
1076 self.fixed_register_use[register] = FixedRegisterPositions(register)
1077 self.fixed_register_use[register].fixed_register(opindex, definition_pos)
1078
1079 def try_use_same_register(self, v0, v1):
1080 """ Try to arrange things to put v0 and v1 into the same register.
1081 v0 must be defined before v1"""
1082 # only works in limited situations now
1083 longevityvar0 = self[v0]
1084 longevityvar1 = self[v1]
1085 assert longevityvar0.definition_pos < longevityvar1.definition_pos
1086 if longevityvar0.last_usage != longevityvar1.definition_pos:
1087 return # not supported for now
1088 longevityvar0.share_with = longevityvar1
1089 longevityvar1._definition_pos_shared = longevityvar0.definition_pos_shared()
1090
1091 def longest_free_reg(self, position, free_regs):
1092 """ for every register in free_regs, compute how far into the future
1093 that register can remain free, according to the constraints of the
1094 fixed registers. Find the register that is free the longest. Return a
1095 tuple (reg, free_until_pos). """
1096 max_free_pos = position
1097 best_reg = None
1098 # reverse for compatibility with old code
1099 for i in range(len(free_regs) - 1, -1, -1):
1100 reg = free_regs[i]
1101 fixed_reg_pos = self.fixed_register_use.get(reg, None)
1102 if fixed_reg_pos is None:
1103 return reg, sys.maxint
1104 else:
1105 free_until_pos = fixed_reg_pos.free_until_pos(position)
1106 if free_until_pos > max_free_pos:
1107 best_reg = reg
1108 max_free_pos = free_until_pos
1109 return best_reg, max_free_pos
1110
1111 def free_reg_whole_lifetime(self, position, v, free_regs):
1112 """ try to find a register from free_regs for v at position that's
1113 free for the whole lifetime of v. pick the one that is blocked first
1114 *after* the lifetime of v. """
1115 longevityvar = self[v]
1116 min_fixed_use_after = sys.maxint
1117 best_reg = None
1118 unfixed_reg = None
1119 for reg in free_regs:
1120 fixed_reg_pos = self.fixed_register_use.get(reg, None)
1121 if fixed_reg_pos is None:
1122 unfixed_reg = reg
1123 continue
1124 use_after = fixed_reg_pos.free_until_pos(position)
1125 if use_after <= longevityvar.last_usage_including_sharing():
1126 # can't fit
1127 continue
1128 assert use_after >= longevityvar.last_usage_including_sharing()
1129 if use_after < min_fixed_use_after:
1130 best_reg = reg
1131 min_fixed_use_after = use_after
1132 if best_reg is not None:
1133 return best_reg
1134
1135 # no fitting fixed registers. pick a non-fixed one
1136 return unfixed_reg
1137
1138 def try_pick_free_reg(self, position, v, free_regs):
1139 if not free_regs:
1140 return None
1141 longevityvar = self[v]
1142 # check whether there is a fixed register and whether it's free
1143 reg = longevityvar.find_fixed_register(position)
1144 if reg is not None and reg in free_regs:
1145 return reg
1146
1147 # try to find a register that's free for the whole lifetime of v
1148 # pick the one that is blocked first *after* the lifetime of v
1149 loc = self.free_reg_whole_lifetime(position, v, free_regs)
1150 if loc is not None:
1151 return loc
1152
1153 # can't fit v completely, so pick the register that's free the longest
1154 loc, free_until = self.longest_free_reg(position, free_regs)
1155 if loc is not None:
1156 return loc
1157 # YYY could check whether it's best to spill v here, but hard
1158 # to do in the current system
1159 return None
1160
1161 def __contains__(self, op):
1162 info = op.get_forwarded()
1163 return info is not None
1164
1165 def __getitem__(self, op):
1166 return get_lifetime(op)
1167
1168 def __setitem__(self, op, lifetime):
1169 assert op not in self or isinstance(op, TempVar)
1170 op.set_forwarded(lifetime)
1171
1172
1173 def compute_vars_longevity(inputargs, operations):
1174 # compute Lifetime information for every variable, storing it in the
1175 # forwarded field of every operation and input arg.
1176 # if a variable has no Lifetime, the operation is dead because its
1177 # side-effect-free and the result is unused
1178 longevity = LifetimeManager()
1179 for i in range(len(operations)-1, -1, -1):
1180 op = operations[i]
1181 opnum = op.getopnum()
1182 if op not in longevity:
1183 if op.type != 'v' and rop.has_no_side_effect(opnum):
1184 # result not used, operation has no side-effect, it can be
1185 # removed
1186 continue
1187 longevity[op] = Lifetime(definition_pos=i, last_usage=i)
1188 else:
1189 longevity[op].definition_pos = i
1190 for j in range(op.numargs()):
1191 arg = op.getarg(j)
1192 if isinstance(arg, Const):
1193 continue
1194 if arg not in longevity:
1195 lifetime = longevity[arg] = Lifetime(last_usage=i)
1196 else:
1197 lifetime = longevity[arg]
1198 if opnum != rop.JUMP and opnum != rop.LABEL:
1199 if lifetime.real_usages is None:
1200 lifetime.real_usages = []
1201 lifetime.real_usages.append(i)
1202 if rop.is_guard(op.opnum):
1203 for arg in op.getfailargs():
1204 if arg is None: # hole
1205 continue
1206 assert not isinstance(arg, Const)
1207 if arg not in longevity:
1208 longevity[arg] = Lifetime(last_usage=i)
1209 #
1210 for arg in inputargs:
1211 assert not isinstance(arg, Const)
1212 if arg not in longevity:
1213 longevity[arg] = Lifetime(-1, -1)
1214
1215 if not we_are_translated():
1216 produced = {}
1217 for arg in inputargs:
1218 produced[arg] = None
1219 for op in operations:
1220 for arg in op.getarglist():
1221 if not isinstance(arg, Const):
1222 assert arg in produced
1223 produced[op] = None
1224 for op in operations:
1225 if op not in longevity:
1226 continue
1227 lifetime = longevity[op]
1228 if lifetime.real_usages is not None:
1229 lifetime.real_usages.reverse()
1230 if not we_are_translated():
1231 lifetime._check_invariants()
1232
1233 return longevity
1234
1235
1236 def valid_addressing_size(size):
1237 return size == 1 or size == 2 or size == 4 or size == 8
1238
1239 def get_scale(size):
1240 assert valid_addressing_size(size)
1241 if size < 4:
1242 return size - 1 # 1, 2 => 0, 1
1243 else:
1244 return (size >> 2) + 1 # 4, 8 => 2, 3
1245
1246
1247 def not_implemented(msg):
1248 msg = '[llsupport/regalloc] %s\n' % msg
1249 if we_are_translated():
1250 llop.debug_print(lltype.Void, msg)
1251 raise NotImplementedError(msg)