Debian Codegraph @

rpython/jit/backend/zarch/assembler.py

raw symbols SCIP
1 from rpython.jit.backend.llsupport.assembler import (GuardToken, BaseAssembler,
2 DEBUG_COUNTER)
3 from rpython.jit.backend.llsupport.asmmemmgr import MachineDataBlockWrapper
4 from rpython.jit.backend.llsupport import jitframe, rewrite
5 from rpython.jit.backend.model import CompiledLoopToken
6 from rpython.jit.backend.zarch import conditions as c
7 from rpython.jit.backend.zarch import registers as r
8 from rpython.jit.backend.zarch import locations as l
9 from rpython.jit.backend.zarch.pool import LiteralPool
10 from rpython.rtyper.lltypesystem.lloperation import llop
11 from rpython.jit.backend.llsupport.jump import remap_frame_layout_mixed
12 from rpython.jit.backend.zarch.codebuilder import (InstrBuilder,
13 OverwritingBuilder)
14 from rpython.jit.backend.zarch.helper.regalloc import check_imm_value
15 from rpython.jit.backend.zarch.registers import JITFRAME_FIXED_SIZE
16 from rpython.jit.backend.zarch.regalloc import ZARCHRegisterManager
17 from rpython.jit.backend.zarch.arch import (WORD,
18 STD_FRAME_SIZE_IN_BYTES, THREADLOCAL_ADDR_OFFSET,
19 RECOVERY_GCMAP_POOL_OFFSET, RECOVERY_TARGET_POOL_OFFSET,
20 JUMPABS_TARGET_ADDR__POOL_OFFSET, JUMPABS_POOL_ADDR_POOL_OFFSET,
21 THREADLOCAL_ON_ENTER_JIT, JIT_ENTER_EXTRA_STACK_SPACE)
22 from rpython.jit.backend.zarch.opassembler import OpAssembler
23 from rpython.jit.backend.zarch.regalloc import Regalloc
24 from rpython.jit.codewriter.effectinfo import EffectInfo
25 from rpython.jit.metainterp.resoperation import rop
26 from rpython.jit.metainterp.compile import ResumeGuardDescr
27 from rpython.rlib.debug import (debug_print, debug_start, debug_stop,
28 have_debug_prints)
29 from rpython.jit.metainterp.history import (INT, REF, FLOAT, TargetToken)
30 from rpython.rlib.rarithmetic import r_uint
31 from rpython.rlib.objectmodel import we_are_translated, specialize, compute_unique_id
32 from rpython.rlib import rgc
33 from rpython.rlib.longlong2float import float2longlong
34 from rpython.rtyper.lltypesystem import lltype, rffi, llmemory
35 from rpython.rtyper.annlowlevel import llhelper, cast_instance_to_gcref
36 from rpython.rlib.jit import AsmInfo
37 from rpython.rlib.rjitlog import rjitlog as jl
38 from rpython.jit.backend.zarch import vector_ext
39
40 class JitFrameTooDeep(Exception):
41 pass
42
43 class AssemblerZARCH(BaseAssembler, OpAssembler,
44 vector_ext.VectorAssembler):
45
46 def __init__(self, cpu, translate_support_code=False):
47 BaseAssembler.__init__(self, cpu, translate_support_code)
48 self.mc = None
49 self.current_clt = None
50 self._regalloc = None
51 self.datablockwrapper = None
52 self.propagate_exception_path = 0
53 self.stack_check_slowpath = 0
54 self.loop_run_counters = []
55 self.gcrootmap_retaddr_forced = 0
56 self.failure_recovery_code = [0, 0, 0, 0]
57 self.wb_slowpath = [0,0,0,0,0]
58 self.pool = None
59
60 def setup(self, looptoken):
61 BaseAssembler.setup(self, looptoken)
62 assert self.memcpy_addr != 0, 'setup_once() not called?'
63 if we_are_translated():
64 self.debug = False
65 self.current_clt = looptoken.compiled_loop_token
66 self.pool = LiteralPool()
67 self.mc = InstrBuilder(None)
68 self.pending_guard_tokens = []
69 self.pending_guard_tokens_recovered = 0
70 #assert self.datablockwrapper is None --- but obscure case
71 # possible, e.g. getting MemoryError and continuing
72 allblocks = self.get_asmmemmgr_blocks(looptoken)
73 self.datablockwrapper = MachineDataBlockWrapper(self.cpu.asmmemmgr,
74 allblocks)
75 self.mc.datablockwrapper = self.datablockwrapper
76 self.target_tokens_currently_compiling = {}
77 self.frame_depth_to_patch = []
78
79 def teardown(self):
80 self.pending_guard_tokens = None
81 self.current_clt = None
82 self._regalloc = None
83 self.mc = None
84 self.pool = None
85
86 def target_arglocs(self, looptoken):
87 return looptoken._zarch_arglocs
88
89 def get_asmmemmgr_blocks(self, looptoken):
90 clt = looptoken.compiled_loop_token
91 if clt.asmmemmgr_blocks is None:
92 clt.asmmemmgr_blocks = []
93 return clt.asmmemmgr_blocks
94
95 def jmpto(self, register):
96 # unconditional jump
97 self.mc.BCR_rr(0xf, register.value)
98
99 def _build_failure_recovery(self, exc, withfloats=False):
100 mc = InstrBuilder(None)
101 self.mc = mc
102 # fill in the jf_descr and jf_gcmap fields of the frame according
103 # to which failure we are resuming from. These are set before
104 # this function is called (see generate_quick_failure()).
105
106 ofs = self.cpu.get_ofs_of_frame_field('jf_descr')
107 ofs2 = self.cpu.get_ofs_of_frame_field('jf_gcmap')
108 self.mc.STG(r.SCRATCH2, l.addr(ofs2, r.SPP))
109 self.mc.STG(r.SCRATCH, l.addr(ofs, r.SPP))
110
111 self._push_core_regs_to_jitframe(mc)
112 if withfloats:
113 self._push_fp_regs_to_jitframe(mc)
114
115 if exc:
116 # We might have an exception pending.
117 mc.load_imm(r.SCRATCH, self.cpu.pos_exc_value())
118 # Copy it into 'jf_guard_exc'
119 offset = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
120 mc.LG(r.SCRATCH2, l.addr(0, r.SCRATCH))
121 mc.STG(r.SCRATCH2, l.addr(offset, r.SPP))
122 # Zero out the exception fields
123 diff = self.cpu.pos_exception() - self.cpu.pos_exc_value()
124 assert check_imm_value(diff)
125 mc.LGHI(r.SCRATCH2, l.imm(0))
126 mc.STG(r.SCRATCH2, l.addr(0, r.SCRATCH))
127 mc.STG(r.SCRATCH2, l.addr(diff, r.SCRATCH))
128
129 # now we return from the complete frame, which starts from
130 # _call_header_with_stack_check(). The _call_footer below does it.
131 self._call_footer()
132 rawstart = mc.materialize(self.cpu, [])
133 self.failure_recovery_code[exc + 2 * withfloats] = rawstart
134 self.mc = None
135
136 def generate_quick_failure(self, guardtok, regalloc):
137 startpos = self.mc.currpos()
138 # accum vecopt
139 self._update_at_exit(guardtok.fail_locs, guardtok.failargs,
140 guardtok.faildescr, regalloc)
141 pos = self.mc.currpos()
142 guardtok.rel_recovery_prefix = pos - startpos
143
144 faildescrindex, target = self.store_info_on_descr(startpos, guardtok)
145 assert target != 0
146
147 self.load_gcref_into(r.SCRATCH, faildescrindex)
148
149 self.load_gcmap(self.mc, r.SCRATCH2, gcmap=guardtok.gcmap)
150 self.mc.load_imm(r.r14, target)
151 self.mc.BCR(c.ANY, r.r14)
152
153 return startpos
154
155 def load_gcref_into(self, register, index):
156 topoff = index * WORD
157 size = self.pool.gcref_table_size
158 self.mc.LG(register, l.addr(-size + topoff, r.POOL))
159
160 def _build_wb_slowpath(self, withcards, withfloats=False, for_frame=False):
161 descr = self.cpu.gc_ll_descr.write_barrier_descr
162 if descr is None:
163 return
164 if not withcards:
165 func = descr.get_write_barrier_fn(self.cpu)
166 else:
167 if descr.jit_wb_cards_set == 0:
168 return
169 func = descr.get_write_barrier_from_array_fn(self.cpu)
170 if func == 0:
171 return
172 #
173 # This builds a helper function called from the slow path of
174 # write barriers. It must save all registers, and optionally
175 # all fp registers. It takes its single argument in r0
176 # (or in SPP if 'for_frame').
177 if for_frame:
178 argument_loc = r.SPP
179 else:
180 argument_loc = r.r0
181
182 mc = InstrBuilder()
183 old_mc = self.mc
184 self.mc = mc
185
186 # save the information
187 mc.store_link()
188 mc.push_std_frame()
189
190 RCS2 = r.r10
191 RCS3 = r.r11
192
193 # r9,r10,r11,r2,f0 -> makes exactly 4 words + 8 byte
194 extra_stack_size = 4 * WORD + 8
195 if for_frame:
196 # NOTE: don't save registers on the jitframe here! It might
197 # override already-saved values that will be restored
198 # later...
199 #
200 # This 'for_frame' version is called after a CALL. It does not
201 # need to save many registers: the registers that are anyway
202 # destroyed by the call can be ignored (VOLATILES), and the
203 # non-volatile registers won't be changed here. It only needs
204 # to save r2 and f0 (possible results of the call),
205 # and two more non-volatile registers (used to store
206 # the RPython exception that occurred in the CALL, if any).
207 #
208 off = STD_FRAME_SIZE_IN_BYTES
209 mc.LG(r.SCRATCH, l.addr(0, r.SP))
210 mc.STG(r.SCRATCH, l.addr(-extra_stack_size, r.SP))
211 mc.LAY(r.SP, l.addr(-extra_stack_size, r.SP))
212 mc.STMG(r.r9, r.r11, l.addr(off, r.SP))
213 mc.STG(r.r2, l.addr(off+3*WORD, r.SP))
214 # OK to use STD, because offset is not negative
215 mc.STD(r.f0, l.addr(off+4*WORD, r.SP))
216 saved_regs = None
217 saved_fp_regs = None
218 else:
219 # push all volatile registers, sometimes push RCS2
220 if withcards:
221 saved_regs = r.VOLATILES + [RCS2]
222 else:
223 saved_regs = r.VOLATILES
224 if withfloats:
225 saved_fp_regs = r.MANAGED_FP_REGS
226 else:
227 saved_fp_regs = []
228
229 self._push_core_regs_to_jitframe(mc, saved_regs)
230 self._push_fp_regs_to_jitframe(mc, saved_fp_regs)
231
232 if for_frame:
233 # note that it's safe to store the exception in register,
234 # since the call to write barrier can't collect
235 # (and this is assumed a bit left and right here, like lack
236 # of _reload_frame_if_necessary)
237 # This trashes r0 and r1, which is fine in this case
238 assert argument_loc is not r.r0
239 assert argument_loc is not r.r1
240 self._store_and_reset_exception(mc, RCS2, RCS3)
241
242 if withcards:
243 mc.LGR(RCS2, argument_loc)
244 func = rffi.cast(lltype.Signed, func)
245 # Note: if not 'for_frame', argument_loc is r0, which must carefully
246 # not be overwritten above
247 mc.load_imm(mc.RAW_CALL_REG, func)
248 mc.LGR(r.r2, argument_loc)
249 mc.raw_call()
250
251 if for_frame:
252 self._restore_exception(mc, RCS2, RCS3)
253
254 if withcards:
255 # A final NILL before the return to the caller. Careful to
256 # not follow this instruction with another one that changes
257 # the status of the condition code
258 card_marking_mask = descr.jit_wb_cards_set_singlebyte
259 mc.LLGC(RCS2, l.addr(descr.jit_wb_if_flag_byteofs, RCS2))
260 mc.NILL(RCS2, l.imm(card_marking_mask & 0xFF))
261
262 if for_frame:
263 off = STD_FRAME_SIZE_IN_BYTES
264 mc.LMG(r.r9, r.r11, l.addr(off, r.SP))
265 mc.LG(r.r2, l.addr(off+3*WORD, r.SP))
266 mc.LD(r.f0, l.addr(off+4*WORD, r.SP))
267 mc.LAY(r.SP, l.addr(extra_stack_size, r.SP))
268 else:
269 self._pop_core_regs_from_jitframe(mc, saved_regs)
270 self._pop_fp_regs_from_jitframe(mc, saved_fp_regs)
271
272 mc.restore_link()
273 mc.BCR(c.ANY, r.RETURN)
274
275 self.mc = old_mc
276 rawstart = mc.materialize(self.cpu, [])
277 if for_frame:
278 self.wb_slowpath[4] = rawstart
279 else:
280 self.wb_slowpath[withcards + 2 * withfloats] = rawstart
281
282 def _store_and_reset_exception(self, mc, excvalloc, exctploc=None):
283 """Reset the exception, after fetching it inside the two regs.
284 """
285 mc.load_imm(r.SCRATCH, self.cpu.pos_exc_value())
286 diff = self.cpu.pos_exception() - self.cpu.pos_exc_value()
287 assert check_imm_value(diff)
288 # Load the exception fields into the two registers
289 mc.LG(excvalloc, l.addr(0,r.SCRATCH))
290 if exctploc is not None:
291 mc.LG(exctploc, l.addr(diff, r.SCRATCH))
292 # Zero out the exception fields
293 mc.XGR(r.SCRATCH2, r.SCRATCH2)
294 mc.STG(r.SCRATCH2, l.addr(0, r.SCRATCH))
295 mc.STG(r.SCRATCH2, l.addr(diff, r.SCRATCH))
296
297 def _restore_exception(self, mc, excvalloc, exctploc):
298 mc.load_imm(r.SCRATCH, self.cpu.pos_exc_value())
299 diff = self.cpu.pos_exception() - self.cpu.pos_exc_value()
300 assert check_imm_value(diff)
301 # Store the exception fields from the two registers
302 mc.STG(excvalloc, l.addr(0, r.SCRATCH))
303 mc.STG(exctploc, l.addr(diff, r.SCRATCH))
304
305 def build_frame_realloc_slowpath(self):
306 # this code should do the following steps
307 # a) store all registers in the jitframe
308 # b) fish for the arguments passed by the caller
309 # c) store the gcmap in the jitframe
310 # d) call realloc_frame
311 # e) set the fp to point to the new jitframe
312 # f) store the address of the new jitframe in the shadowstack
313 # c) set the gcmap field to 0 in the new jitframe
314 # g) restore registers and return
315 mc = InstrBuilder()
316 self.mc = mc
317
318 mc.store_link()
319 mc.push_std_frame()
320
321 # signature of this _frame_realloc_slowpath function:
322 # * on entry, r0 is the new size
323 # * no managed register must be modified
324
325 # caller already did push_gcmap(store=True)
326
327 self._push_core_regs_to_jitframe(mc, r.MANAGED_REGS)
328 self._push_fp_regs_to_jitframe(mc)
329
330
331 # First argument is SPP, which is the jitframe
332 mc.LGR(r.r2, r.SPP)
333
334 # no need to move second argument (frame_depth),
335 # it is already in register r3!
336 mc.LGR(r.r3, r.SCRATCH2)
337
338 RCS2 = r.r10
339 RCS3 = r.r11
340
341 self._store_and_reset_exception(mc, RCS2, RCS3)
342
343 # Do the call
344 adr = rffi.cast(lltype.Signed, self.cpu.realloc_frame)
345 mc.load_imm(mc.RAW_CALL_REG, adr)
346 mc.raw_call()
347
348 # The result is stored back into SPP (= r31)
349 mc.LGR(r.SPP, r.r2)
350
351 self._restore_exception(mc, RCS2, RCS3)
352
353 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
354 if gcrootmap and gcrootmap.is_shadow_stack:
355 diff = mc.load_imm(r.r5, gcrootmap.get_root_stack_top_addr())
356 mc.load(r.r5, r.r5, 0)
357 mc.store(r.r2, r.r5, -WORD)
358
359 self.pop_gcmap(mc) # cancel the push_gcmap(store=True) in the caller
360 self._pop_core_regs_from_jitframe(mc, r.MANAGED_REGS)
361 self._pop_fp_regs_from_jitframe(mc)
362
363 mc.restore_link()
364 mc.BCR(c.ANY, r.RETURN)
365
366 self._frame_realloc_slowpath = mc.materialize(self.cpu, [])
367 self.mc = None
368
369 def _build_propagate_exception_path(self):
370 self.mc = InstrBuilder()
371 #
372 # read and reset the current exception
373
374 propagate_exception_descr = rffi.cast(lltype.Signed,
375 cast_instance_to_gcref(self.cpu.propagate_exception_descr))
376 ofs3 = self.cpu.get_ofs_of_frame_field('jf_guard_exc')
377 ofs4 = self.cpu.get_ofs_of_frame_field('jf_descr')
378
379 self._store_and_reset_exception(self.mc, r.r2)
380 self.mc.load_imm(r.r3, propagate_exception_descr)
381 self.mc.STG(r.r2, l.addr(ofs3, r.SPP))
382 self.mc.STG(r.r3, l.addr(ofs4, r.SPP))
383 #
384 self._call_footer()
385 rawstart = self.mc.materialize(self.cpu, [])
386 self.propagate_exception_path = rawstart
387 self.mc = None
388
389 def _build_cond_call_slowpath(self, supports_floats, callee_only):
390 """ This builds a general call slowpath, for whatever call happens to
391 come.
392 """
393 # signature of these cond_call_slowpath functions:
394 # * on entry, r11 contains the function to call
395 # * r2, r3, r4, r5 contain arguments for the call
396 # * gcmap is pushed
397 # * the old value of these regs must already be stored in the jitframe
398 # * on exit, all registers are restored from the jitframe
399 # * the result of the call is moved to register r1
400
401 mc = InstrBuilder()
402 self.mc = mc
403 mc.store_link()
404 mc.push_std_frame()
405
406 # copy registers to the frame, with the exception of r2 to r5 and r11,
407 # because these have already been saved by the caller. Note that
408 # this is not symmetrical: these 5 registers are saved by the caller
409 # but restored here at the end of this function.
410 if callee_only:
411 saved_regs = ZARCHRegisterManager.save_around_call_regs
412 else:
413 saved_regs = ZARCHRegisterManager.all_regs
414 regs = [reg for reg in saved_regs
415 if reg is not r.r2 and
416 reg is not r.r3 and
417 reg is not r.r4 and
418 reg is not r.r5 and
419 reg is not r.r11]
420 # the caller already did push_gcmap(store=True)
421 self._push_core_regs_to_jitframe(mc, regs)
422 if supports_floats:
423 self._push_fp_regs_to_jitframe(mc)
424
425 mc.raw_call(r.r11)
426
427 # Finish
428 self._reload_frame_if_necessary(mc)
429
430 self.pop_gcmap(mc) # cancel the push_gcmap(store=True) in the caller
431
432 mc.LGR(r.SCRATCH2, r.RES)
433
434 self._pop_core_regs_from_jitframe(mc, saved_regs)
435 if supports_floats:
436 self._pop_fp_regs_from_jitframe(mc)
437 mc.restore_link()
438 mc.BCR(c.ANY, r.RETURN)
439 self.mc = None
440 return mc.materialize(self.cpu, [])
441
442 def _build_malloc_slowpath(self, kind):
443 """ While arriving on slowpath, we have a gcmap in r1.
444 The arguments are passed in r.RES and r.RSZ, as follows:
445
446 kind == 'fixed': nursery_head in r.RES and the size in r.RSZ - r.RES.
447
448 kind == 'str/unicode': length of the string to allocate in r.RES.
449
450 kind == 'var': itemsize in r.RES, length to allocate in r.RSZ,
451 and tid in r.r0.
452
453 This function must preserve all registers apart from r.RES and r.RSZ.
454 On return, SCRATCH must contain the address of nursery_free.
455 """
456 assert kind in ['fixed', 'str', 'unicode', 'var']
457 mc = InstrBuilder()
458 self.mc = mc
459 # alloc a frame for the callee
460 mc.store_link()
461 mc.push_std_frame()
462 #
463 saved_regs = [reg for reg in r.MANAGED_REGS
464 if reg is not r.RES and reg is not r.RSZ]
465 self._push_core_regs_to_jitframe(mc, saved_regs)
466 self._push_fp_regs_to_jitframe(mc)
467 # the caller already did push_gcmap(store=True)
468 #
469 if kind == 'fixed':
470 addr = self.cpu.gc_ll_descr.get_malloc_slowpath_addr()
471 elif kind == 'str':
472 addr = self.cpu.gc_ll_descr.get_malloc_fn_addr('malloc_str')
473 elif kind == 'unicode':
474 addr = self.cpu.gc_ll_descr.get_malloc_fn_addr('malloc_unicode')
475 else:
476 addr = self.cpu.gc_ll_descr.get_malloc_slowpath_array_addr()
477
478 if kind == 'fixed':
479 # compute the size we want
480 mc.SGRK(r.r2, r.RSZ, r.RES)
481 if hasattr(self.cpu.gc_ll_descr, 'passes_frame'):
482 # for tests only
483 mc.LGR(r.r3, r.SPP)
484 elif kind == 'str' or kind == 'unicode':
485 pass # length is already in r2
486 else:
487 # arguments to the called function are [itemsize, tid, length]
488 # itemsize is already in r2
489 mc.LGR(r.r4, r.RSZ) # length
490 mc.LGR(r.r3, r.r0) # tid
491
492 # Do the call
493 addr = rffi.cast(lltype.Signed, addr)
494 mc.load_imm(mc.RAW_CALL_REG, addr)
495 mc.raw_call()
496
497 self._reload_frame_if_necessary(mc)
498
499 # Check that we don't get NULL; if we do, we always interrupt the
500 # current loop, as a "good enough" approximation (same as
501 # emit_call_malloc_gc()).
502 self.propagate_memoryerror_if_reg_is_null(r.r2, True)
503
504 self._pop_core_regs_from_jitframe(mc, saved_regs)
505 self._pop_fp_regs_from_jitframe(mc)
506
507 nursery_free_adr = self.cpu.gc_ll_descr.get_nursery_free_addr()
508 self.mc.load_imm(r.r1, nursery_free_adr)
509
510 # r.r1 is now the address of nursery_free
511 # r.RES is still the result of the call done above
512 # r.RSZ is loaded from [r1], to make the caller's store a no-op here
513 mc.load(r.RSZ, r.r1, 0)
514 #
515 mc.restore_link()
516 mc.BCR(c.ANY, r.r14)
517 self.mc = None
518 return mc.materialize(self.cpu, [])
519
520
521 def _build_stack_check_slowpath(self):
522 _, _, slowpathaddr = self.cpu.insert_stack_check()
523 if slowpathaddr == 0 or not self.cpu.propagate_exception_descr:
524 return # no stack check (for tests, or non-translated)
525 #
526 # make a regular function that is called from a point near the start
527 # of an assembler function (after it adjusts the stack and saves
528 # registers).
529 mc = InstrBuilder()
530 #
531 # store the link backwards
532 mc.store_link()
533 mc.push_std_frame()
534
535 mc.LGR(r.r2, r.SP)
536 mc.load_imm(mc.RAW_CALL_REG, slowpathaddr)
537 mc.raw_call()
538 #
539 # Check if it raised StackOverflow
540 mc.load_imm(r.SCRATCH, self.cpu.pos_exception())
541 mc.LG(r.SCRATCH, l.addr(0, r.SCRATCH))
542 # if this comparison is true, then everything is ok,
543 # else we have an exception
544 mc.cmp_op(r.SCRATCH, l.imm(0), imm=True)
545 #
546 mc.restore_link()
547 # So we return to our caller, conditionally if "EQ"
548 mc.BCR(c.EQ, r.r14)
549 #
550 # Else, jump to propagate_exception_path
551 assert self.propagate_exception_path
552 mc.branch_absolute(self.propagate_exception_path)
553 #
554 rawstart = mc.materialize(self.cpu, [])
555 self.stack_check_slowpath = rawstart
556
557 def new_stack_loc(self, i, tp):
558 base_ofs = self.cpu.get_baseofs_of_frame_field()
559 loc = l.StackLocation(i, l.get_fp_offset(base_ofs, i), tp)
560 return loc
561
562 def _call_header_with_stack_check(self):
563 self._call_header()
564 if self.stack_check_slowpath == 0:
565 pass # not translated
566 else:
567 endaddr, lengthaddr, _ = self.cpu.insert_stack_check()
568 diff = lengthaddr - endaddr
569 assert check_imm_value(diff)
570
571 mc = self.mc
572 mc.load_imm(r.r1, endaddr)
573 mc.load(r.r0, r.r1, 0) # ld r0, [end]
574 mc.load(r.r1, r.r1, diff) # ld r1, [length]
575 mc.SGRK(r.r0, r.SP, r.r0)
576 jmp_pos = self.mc.get_relative_pos()
577 mc.reserve_cond_jump()
578 mc.load_imm(r.r14, self.stack_check_slowpath)
579 mc.BASR(r.r14, r.r14)
580
581 currpos = self.mc.currpos()
582 pmc = OverwritingBuilder(self.mc, jmp_pos, 1)
583 pmc.CLGRJ(r.r0, r.r1, c.LE, l.imm(currpos - jmp_pos))
584 pmc.overwrite()
585
586 def _check_frame_depth(self, mc, gcmap):
587 """ check if the frame is of enough depth to follow this bridge.
588 Otherwise reallocate the frame in a helper.
589 """
590 descrs = self.cpu.gc_ll_descr.getframedescrs(self.cpu)
591 ofs = self.cpu.unpack_fielddescr(descrs.arraydescr.lendescr)
592 mc.LG(r.r1, l.addr(ofs, r.SPP))
593 patch_pos = mc.currpos()
594 # placeholder for the following instructions
595 # CGFI r1, ... (6 bytes)
596 # BRC c, ... (4 bytes)
597 # LGHI r0, ... (4 bytes)
598 # sum -> (14 bytes)
599 mc.write('\x00'*14)
600 mc.load_imm(r.RETURN, self._frame_realloc_slowpath)
601 self.push_gcmap(mc, gcmap, store=True)
602 mc.raw_call()
603
604 self.frame_depth_to_patch.append((patch_pos, mc.currpos()))
605
606 def patch_stack_checks(self, frame_depth):
607 if frame_depth > 0x7fff:
608 raise JitFrameTooDeep
609 for traps_pos, jmp_target in self.frame_depth_to_patch:
610 pmc = OverwritingBuilder(self.mc, traps_pos, 3)
611 # patch 3 instructions as shown above
612 pmc.CGFI(r.r1, l.imm(frame_depth))
613 pmc.BRC(c.GE, l.imm(jmp_target - (traps_pos + 6)))
614 pmc.LGHI(r.r0, l.imm(frame_depth))
615 pmc.overwrite()
616
617 @rgc.no_release_gil
618 def assemble_loop(self, jd_id, unique_id, logger, loopname, inputargs,
619 operations, looptoken, log):
620 clt = CompiledLoopToken(self.cpu, looptoken.number)
621 looptoken.compiled_loop_token = clt
622 clt._debug_nbargs = len(inputargs)
623 if not we_are_translated():
624 # Arguments should be unique
625 assert len(set(inputargs)) == len(inputargs)
626
627 self.setup(looptoken)
628 frame_info = self.datablockwrapper.malloc_aligned(
629 jitframe.JITFRAMEINFO_SIZE, alignment=WORD)
630 clt.frame_info = rffi.cast(jitframe.JITFRAMEINFOPTR, frame_info)
631 clt.frame_info.clear() # for now
632
633 if log:
634 operations = self._inject_debugging_code(looptoken, operations,
635 'e', looptoken.number)
636
637 regalloc = Regalloc(assembler=self)
638 #
639 allgcrefs = []
640 operations = regalloc.prepare_loop(inputargs, operations,
641 looptoken, allgcrefs)
642 # reserve_gcref_table is handled in pool
643 self.pool.pre_assemble(self, operations, allgcrefs)
644 functionpos = self.mc.get_relative_pos()
645 self._call_header_with_stack_check()
646 looppos = self.mc.get_relative_pos()
647 frame_depth_no_fixed_size = self._assemble(regalloc, inputargs,
648 operations)
649 self.update_frame_depth(frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
650 #
651 size_excluding_failure_stuff = self.mc.get_relative_pos()
652 #
653 self.write_pending_failure_recoveries(regalloc)
654 full_size = self.mc.get_relative_pos()
655 #
656 self.patch_stack_checks(frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
657 #
658 if not we_are_translated():
659 self.mc.trap() # should be never reached
660 rawstart = self.materialize_loop(looptoken)
661 self.patch_gcref_table(looptoken, rawstart)
662 looptoken._ll_function_addr = rawstart + functionpos
663 #
664 looptoken._ll_loop_code = looppos + rawstart
665 debug_start("jit-backend-addr")
666 debug_print("Loop %d (%s) has address 0x%x to 0x%x (bootstrap 0x%x)" % (
667 looptoken.number, loopname,
668 r_uint(rawstart + looppos),
669 r_uint(rawstart + size_excluding_failure_stuff),
670 r_uint(rawstart + functionpos)))
671 debug_print(" gc table: 0x%x" % r_uint(self.gc_table_addr))
672 debug_print(" function: 0x%x" % r_uint(rawstart + functionpos))
673 debug_print(" resops: 0x%x" % r_uint(rawstart + looppos))
674 debug_print(" failures: 0x%x" % r_uint(rawstart +
675 size_excluding_failure_stuff))
676 debug_print(" end: 0x%x" % r_uint(rawstart + full_size))
677 debug_stop("jit-backend-addr")
678 #
679 self.patch_pending_failure_recoveries(rawstart)
680 #
681 ops_offset = self.mc.ops_offset
682 if not we_are_translated():
683 # used only by looptoken.dump() -- useful in tests
684 looptoken._zarch_rawstart = rawstart
685 looptoken._zarch_fullsize = full_size
686 looptoken._zarch_ops_offset = ops_offset
687
688 if logger:
689 log = logger.log_trace(jl.MARK_TRACE_ASM, None, self.mc)
690 log.write(inputargs, operations, ops_offset=ops_offset)
691
692 # legacy
693 if logger.logger_ops:
694 logger.logger_ops.log_loop(inputargs, operations, 0,
695 "rewritten", name=loopname,
696 ops_offset=ops_offset)
697
698 self.fixup_target_tokens(rawstart)
699 self.teardown()
700 #print(hex(rawstart+looppos))
701 #import pdb; pdb.set_trace()
702 return AsmInfo(ops_offset, rawstart + looppos,
703 size_excluding_failure_stuff - looppos, rawstart)
704
705 @rgc.no_release_gil
706 def assemble_bridge(self, faildescr, inputargs, operations,
707 original_loop_token, log, logger):
708 if not we_are_translated():
709 # Arguments should be unique
710 assert len(set(inputargs)) == len(inputargs)
711
712 self.setup(original_loop_token)
713 descr_number = compute_unique_id(faildescr)
714 if log:
715 operations = self._inject_debugging_code(faildescr, operations,
716 'b', descr_number)
717
718 arglocs = self.rebuild_faillocs_from_descr(faildescr, inputargs)
719 regalloc = Regalloc(assembler=self)
720 allgcrefs = []
721 operations = regalloc.prepare_bridge(inputargs, arglocs,
722 operations, allgcrefs,
723 self.current_clt.frame_info)
724 # reserve gcref table is handled in pre_assemble
725 self.pool.pre_assemble(self, operations, allgcrefs, bridge=True)
726 startpos = self.mc.get_relative_pos()
727 self._update_at_exit(arglocs, inputargs, faildescr, regalloc)
728 self._check_frame_depth(self.mc, regalloc.get_gcmap())
729 bridgestartpos = self.mc.get_relative_pos()
730 self.mc.LARL(r.POOL, l.halfword(self.pool.pool_start - bridgestartpos))
731 frame_depth_no_fixed_size = self._assemble(regalloc, inputargs, operations)
732 codeendpos = self.mc.get_relative_pos()
733 #self.pool.post_assemble(self)
734 self.write_pending_failure_recoveries(regalloc)
735 fullsize = self.mc.get_relative_pos()
736 #
737 self.patch_stack_checks(frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
738 #
739 rawstart = self.materialize_loop(original_loop_token)
740 self.patch_gcref_table(original_loop_token, rawstart)
741 debug_start("jit-backend-addr")
742 debug_print("bridge out of Guard 0x%x has address 0x%x to 0x%x" %
743 (r_uint(descr_number), r_uint(rawstart + startpos),
744 r_uint(rawstart + codeendpos)))
745 debug_print(" gc table: 0x%x" % r_uint(self.gc_table_addr))
746 debug_print(" jump target: 0x%x" % r_uint(rawstart + startpos))
747 debug_print(" resops: 0x%x" % r_uint(rawstart + bridgestartpos))
748 debug_print(" failures: 0x%x" % r_uint(rawstart + codeendpos))
749 debug_print(" end: 0x%x" % r_uint(rawstart + fullsize))
750 debug_stop("jit-backend-addr")
751 self.patch_pending_failure_recoveries(rawstart)
752 # patch the jump from original guard
753 self.patch_jump_for_descr(faildescr, rawstart + startpos)
754 ops_offset = self.mc.ops_offset
755 frame_depth = max(self.current_clt.frame_info.jfi_frame_depth,
756 frame_depth_no_fixed_size + JITFRAME_FIXED_SIZE)
757
758 if logger:
759 log = logger.log_trace(jl.MARK_TRACE_ASM, None, self.mc)
760 log.write(inputargs, operations, ops_offset)
761 # log that the already written bridge is stitched to a descr!
762 logger.log_patch_guard(descr_number, rawstart)
763
764 # legacy
765 if logger.logger_ops:
766 logger.logger_ops.log_bridge(inputargs, operations, "rewritten",
767 faildescr, ops_offset=ops_offset)
768
769 self.fixup_target_tokens(rawstart)
770 self.update_frame_depth(frame_depth)
771 self.teardown()
772 return AsmInfo(ops_offset, rawstart + startpos, codeendpos - startpos,
773 rawstart + bridgestartpos)
774
775 def patch_gcref_table(self, looptoken, rawstart):
776 self.gc_table_addr = rawstart
777 tracer = self.cpu.gc_ll_descr.make_gcref_tracer(rawstart,
778 self._allgcrefs)
779 gcreftracers = self.get_asmmemmgr_gcreftracers(looptoken)
780 gcreftracers.append(tracer) # keepalive
781 self.teardown_gcrefs_list()
782
783 def get_asmmemmgr_gcreftracers(self, looptoken):
784 clt = looptoken.compiled_loop_token
785 if clt.asmmemmgr_gcreftracers is None:
786 clt.asmmemmgr_gcreftracers = []
787 return clt.asmmemmgr_gcreftracers
788
789 def patch_jump_for_descr(self, faildescr, adr_new_target):
790 # 'faildescr.adr_jump_offset' is the address of an instruction that is a
791 # conditional jump. We must patch this conditional jump to go
792 # to 'adr_new_target'.
793 mc = InstrBuilder()
794 mc.b_abs(adr_new_target)
795 mc.copy_to_raw_memory(faildescr.adr_jump_offset)
796 assert faildescr.adr_jump_offset != 0
797 faildescr.adr_jump_offset = 0 # means "patched"
798
799 def fixup_target_tokens(self, rawstart):
800 for targettoken in self.target_tokens_currently_compiling:
801 assert isinstance(targettoken, TargetToken)
802 targettoken._ll_loop_code += rawstart
803 self.target_tokens_currently_compiling = None
804
805 def flush_cc(self, condition, result_loc):
806 # After emitting an instruction that leaves a boolean result in
807 # a condition code (cc), call this. In the common case, result_loc
808 # will be set to 'fp' by the regalloc, which in this case means
809 # "propagate it between this operation and the next guard by keeping
810 # it in the cc". In the uncommon case, result_loc is another
811 # register, and we emit a load from the cc into this register.
812 assert self.guard_success_cc == c.cond_none
813 if result_loc is r.SPP:
814 self.guard_success_cc = condition
815 else:
816 # sadly we cannot use LOCGHI
817 # it is included in some extension that seem to be NOT installed
818 # by default.
819 self.mc.LGHI(result_loc, l.imm(1))
820 off = self.mc.XGR_byte_count + self.mc.BRC_byte_count
821 self.mc.BRC(condition, l.imm(off)) # branch over XGR
822 self.mc.XGR(result_loc, result_loc)
823
824 def propagate_memoryerror_if_reg_is_null(self, reg, pop_one_stackframe=False):
825 # if self.propagate_exception_path == 0 (tests), this may jump to 0
826 # and segfaults. too bad. the alternative is to continue anyway
827 # with reg==0, but that will segfault too.
828 jmp_pos = self.mc.get_relative_pos()
829 # bails to propagate exception path if reg != 0
830 self.mc.reserve_cond_jump()
831
832 self.mc.load_imm(r.RETURN, self.propagate_exception_path)
833 if pop_one_stackframe:
834 self.mc.LAY(r.SP, l.addr(STD_FRAME_SIZE_IN_BYTES, r.SP))
835 self.mc.BCR(c.ANY, r.RETURN)
836
837 curpos = self.mc.currpos()
838 pmc = OverwritingBuilder(self.mc, jmp_pos, 1)
839 pmc.CGIJ(reg, l.imm(0), c.NE, l.imm(curpos - jmp_pos))
840 pmc.overwrite()
841
842 def regalloc_push(self, loc, already_pushed):
843 """Pushes the value stored in loc to the stack
844 Can trash the current value of SCRATCH when pushing a stack
845 loc"""
846
847 index = WORD * (~already_pushed)
848
849 if loc.type == FLOAT:
850 if not loc.is_fp_reg():
851 self.regalloc_mov(loc, r.FP_SCRATCH)
852 loc = r.FP_SCRATCH
853 self.mc.STDY(loc, l.addr(index, r.SP))
854 else:
855 if not loc.is_core_reg():
856 self.regalloc_mov(loc, r.SCRATCH)
857 loc = r.SCRATCH
858 self.mc.STG(loc, l.addr(index, r.SP))
859
860 def regalloc_pop(self, loc, already_pushed):
861 """Pops the value on top of the stack to loc. Can trash the current
862 value of SCRATCH when popping to a stack loc"""
863 index = WORD * (~already_pushed)
864
865 if loc.type == FLOAT:
866 if loc.is_fp_reg():
867 self.mc.LDY(loc, l.addr(index, r.SP))
868 else:
869 self.mc.LDY(r.FP_SCRATCH, l.addr(index, r.SP))
870 self.regalloc_mov(r.FP_SCRATCH, loc)
871 else:
872 if loc.is_core_reg():
873 self.mc.LG(loc, l.addr(index, r.SP))
874 else:
875 self.mc.LG(r.SCRATCH, l.addr(index, r.SP))
876 self.regalloc_mov(r.SCRATCH, loc)
877
878 def regalloc_prepare_move(self, src, dst, tmp):
879 if dst.is_stack() and src.is_stack():
880 self.regalloc_mov(src, tmp)
881 return tmp
882 if dst.is_stack() and src.is_in_pool():
883 self.regalloc_mov(src, tmp)
884 return tmp
885 return src
886
887 def push_gcmap(self, mc, gcmap, store=True):
888 # (called from callbuilder.py and ../llsupport/callbuilder.py)
889 assert store is True
890 self.load_gcmap(mc, r.SCRATCH, gcmap)
891 ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
892 mc.STG(r.SCRATCH, l.addr(ofs, r.SPP))
893
894 def pop_gcmap(self, mc):
895 ofs = self.cpu.get_ofs_of_frame_field('jf_gcmap')
896 mc.LG(r.SCRATCH, l.addr(ofs, r.SPP))
897
898 def break_long_loop(self, regalloc):
899 # If the loop is too long, the guards in it will jump forward
900 # more than 32 KB. We use an approximate hack to know if we
901 # should break the loop here with an unconditional "b" that
902 # jumps over the target code.
903 jmp_pos = self.mc.currpos()
904 self.mc.reserve_cond_jump()
905
906 self.write_pending_failure_recoveries(regalloc)
907
908 currpos = self.mc.currpos()
909 pmc = OverwritingBuilder(self.mc, jmp_pos, 1)
910 pmc.BRCL(c.ANY, l.imm(currpos - jmp_pos))
911 pmc.overwrite()
912
913 def _assemble(self, regalloc, inputargs, operations):
914 self._regalloc = regalloc
915 self.guard_success_cc = c.cond_none
916 regalloc.compute_hint_frame_locations(operations)
917 regalloc.walk_operations(inputargs, operations)
918 assert self.guard_success_cc == c.cond_none
919 if we_are_translated() or self.cpu.dont_keepalive_stuff:
920 self._regalloc = None # else keep it around for debugging
921 frame_depth = regalloc.get_final_frame_depth()
922 jump_target_descr = regalloc.jump_target_descr
923 if jump_target_descr is not None:
924 tgt_depth = jump_target_descr._zarch_clt.frame_info.jfi_frame_depth
925 target_frame_depth = tgt_depth - JITFRAME_FIXED_SIZE
926 frame_depth = max(frame_depth, target_frame_depth)
927 return frame_depth
928
929 def regalloc_mov(self, prev_loc, loc):
930 if prev_loc.is_vector_reg():
931 assert loc.is_vector_reg()
932 self.mc.VLR(loc, prev_loc)
933 return
934 if prev_loc.is_imm():
935 value = prev_loc.getint()
936 # move immediate value to register
937 if loc.is_reg():
938 self.mc.load_imm(loc, value)
939 return
940 # move immediate value to memory
941 elif loc.is_stack():
942 offset = loc.value
943 self.mc.load_imm(r.SCRATCH, prev_loc.value)
944 self.mc.STG(r.SCRATCH, l.addr(offset, r.SPP))
945 return
946 assert 0, "not supported location"
947 elif prev_loc.is_imm_float():
948 self.mc.load_imm(r.SCRATCH, prev_loc.value)
949 if loc.is_fp_reg():
950 self.mc.LDY(loc, l.addr(0, r.SCRATCH))
951 return
952 elif loc.is_stack():
953 src_adr = l.addr(0, r.SCRATCH)
954 tgt_adr = l.AddressLocation(r.SPP, None, loc.value, l.imm(7))
955 self.mc.MVC(tgt_adr, src_adr)
956 return
957 elif prev_loc.is_stack():
958 offset = prev_loc.value
959 # move from memory to register
960 if loc.is_reg():
961 self.mc.load(loc, r.SPP, offset)
962 return
963 # move in memory
964 elif loc.is_stack():
965 target_offset = loc.value
966 self.mc.load(r.SCRATCH, r.SPP, offset)
967 self.mc.store(r.SCRATCH, r.SPP, target_offset)
968 return
969 # move from memory to fp register
970 elif loc.is_fp_reg():
971 assert prev_loc.type == FLOAT, 'source not float location'
972 self.mc.LDY(loc, l.addr(offset, r.SPP))
973 return
974 assert 0, "not supported location"
975 elif prev_loc.is_reg():
976 # move to another register
977 if loc.is_reg():
978 self.mc.LGR(loc, prev_loc)
979 return
980 # move to memory
981 elif loc.is_stack():
982 offset = loc.value
983 self.mc.STG(prev_loc, l.addr(offset, r.SPP))
984 return
985 assert 0, "not supported location"
986 elif prev_loc.is_in_pool():
987 if loc.is_core_reg():
988 self.mc.LG(loc, prev_loc)
989 return
990 # move immediate value to fp register
991 if loc.is_fp_reg():
992 self.mc.LDY(loc, prev_loc)
993 return
994 # move immediate value to memory
995 elif loc.is_stack():
996 offset = loc.value
997 self.mc.LDY(r.FP_SCRATCH, prev_loc)
998 self.mc.STDY(r.FP_SCRATCH, l.addr(offset, r.SPP))
999 return
1000 assert 0, "not supported location"
1001 elif prev_loc.is_fp_reg():
1002 # move to another fp register
1003 if loc.is_fp_reg():
1004 self.mc.LDR(loc, prev_loc)
1005 return
1006 # move from fp register to memory
1007 elif loc.is_stack():
1008 assert prev_loc.type == FLOAT, "source is not a float location"
1009 offset = loc.value
1010 self.mc.STDY(prev_loc, l.addr(offset, r.SPP))
1011 return
1012 assert 0, "not supported location"
1013 assert 0, "not supported location"
1014
1015 def update_frame_depth(self, frame_depth):
1016 if frame_depth > 0x7fff:
1017 raise JitFrameTooDeep
1018 baseofs = self.cpu.get_baseofs_of_frame_field()
1019 self.current_clt.frame_info.update_frame_depth(baseofs, frame_depth)
1020
1021 def write_pending_failure_recoveries(self, regalloc):
1022 # for each pending guard, generate the code of the recovery stub
1023 # at the end of self.mc.
1024 for i in range(self.pending_guard_tokens_recovered,
1025 len(self.pending_guard_tokens)):
1026 tok = self.pending_guard_tokens[i]
1027 tok.pos_recovery_stub = self.generate_quick_failure(tok, regalloc)
1028 self.pending_guard_tokens_recovered = len(self.pending_guard_tokens)
1029
1030 def materialize_loop(self, looptoken):
1031 self.datablockwrapper.done()
1032 self.datablockwrapper = None
1033 allblocks = self.get_asmmemmgr_blocks(looptoken)
1034 start = self.mc.materialize(self.cpu, allblocks,
1035 self.cpu.gc_ll_descr.gcrootmap)
1036 return start
1037
1038 def _reload_frame_if_necessary(self, mc, shadowstack_reg=None):
1039 # might trash the VOLATILE registers different from r2 and f0
1040 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
1041 if gcrootmap:
1042 if gcrootmap.is_shadow_stack:
1043 if shadowstack_reg is None:
1044 diff = mc.load_imm(r.SPP, gcrootmap.get_root_stack_top_addr())
1045 mc.load(r.SPP, r.SPP, 0)
1046 shadowstack_reg = r.SPP
1047 mc.load(r.SPP, shadowstack_reg, -WORD)
1048 wbdescr = self.cpu.gc_ll_descr.write_barrier_descr
1049 if gcrootmap and wbdescr:
1050 # frame never uses card marking, so we enforce this is not
1051 # an array
1052 self._write_barrier_fastpath(mc, wbdescr, [r.SPP], regalloc=None,
1053 array=False, is_frame=True)
1054
1055 def patch_pending_failure_recoveries(self, rawstart):
1056 assert (self.pending_guard_tokens_recovered ==
1057 len(self.pending_guard_tokens))
1058 clt = self.current_clt
1059 for tok in self.pending_guard_tokens:
1060 addr = rawstart + tok.pos_jump_offset
1061 #
1062 tok.faildescr.adr_jump_offset = rawstart + tok.pos_recovery_stub + tok.rel_recovery_prefix
1063 relative_target = tok.pos_recovery_stub - tok.pos_jump_offset
1064 #
1065 if not tok.guard_not_invalidated():
1066 mc = InstrBuilder()
1067 mc.b_cond_offset(relative_target, tok.fcond)
1068 mc.copy_to_raw_memory(addr)
1069 else:
1070 # GUARD_NOT_INVALIDATED, record an entry in
1071 # clt.invalidate_positions of the form:
1072 # (addr-in-the-code-of-the-not-yet-written-jump-target,
1073 # relative-target-to-use)
1074 relpos = tok.pos_jump_offset
1075 clt.invalidate_positions.append((rawstart + relpos,
1076 relative_target))
1077
1078 def _call_header(self):
1079 # Build a new stackframe of size STD_FRAME_SIZE_IN_BYTES
1080 fpoff = JIT_ENTER_EXTRA_STACK_SPACE
1081 self.mc.STMG(r.r6, r.r15, l.addr(-fpoff+6*WORD, r.SP))
1082 self.mc.LARL(r.POOL, l.halfword(self.pool.pool_start - self.mc.get_relative_pos()))
1083 # f8 through f15 are saved registers (= non volatile)
1084 for i,reg in enumerate([r.f8, r.f9, r.f10, r.f11,
1085 r.f12, r.f13, r.f14, r.f15]):
1086 off = -fpoff + STD_FRAME_SIZE_IN_BYTES
1087 assert off > 0
1088 self.mc.STD(reg, l.addr(off + i*8, r.SP))
1089
1090 # save r3, the second argument, to the thread local position
1091 self.mc.STG(r.r3, l.addr(-fpoff+THREADLOCAL_ON_ENTER_JIT, r.SP))
1092
1093 # push a standard frame for any within the jit trace
1094 self.mc.push_std_frame(fpoff)
1095
1096 # move the first argument to SPP: the jitframe object
1097 self.mc.LGR(r.SPP, r.r2)
1098
1099 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
1100 if gcrootmap and gcrootmap.is_shadow_stack:
1101 self._call_header_shadowstack(gcrootmap)
1102
1103
1104 def _call_header_shadowstack(self, gcrootmap):
1105 # we need to put one word into the shadowstack: the jitframe (SPP)
1106 # we saved all registers to the stack
1107 RCS1 = r.r3
1108 RCS2 = r.r4
1109 RCS3 = r.r5
1110 mc = self.mc
1111 mc.load_imm(RCS1, gcrootmap.get_root_stack_top_addr())
1112 mc.load(RCS2, RCS1, 0) # ld RCS2, [rootstacktop]
1113 #
1114 mc.LGR(RCS3, RCS2)
1115 mc.AGHI(RCS3, l.imm(WORD)) # add RCS3, RCS2, WORD
1116 mc.store(r.SPP, RCS2, 0) # std SPP, RCS2
1117 #
1118 mc.store(RCS3, RCS1, 0) # std RCS3, [rootstacktop]
1119
1120 def _call_footer_shadowstack(self, gcrootmap):
1121 # r6 -> r15 can be used freely, they will be restored by
1122 # _call_footer after this call
1123 RCS1 = r.r8
1124 RCS2 = r.r7
1125 mc = self.mc
1126 mc.load_imm(RCS1, gcrootmap.get_root_stack_top_addr())
1127 mc.load(RCS2, RCS1, 0) # ld RCS2, [rootstacktop]
1128 mc.AGHI(RCS2, l.imm(-WORD)) # sub RCS2, RCS2, WORD
1129 mc.store(RCS2, RCS1, 0) # std RCS2, [rootstacktop]
1130
1131 def _call_footer(self):
1132
1133 gcrootmap = self.cpu.gc_ll_descr.gcrootmap
1134 if gcrootmap and gcrootmap.is_shadow_stack:
1135 self._call_footer_shadowstack(gcrootmap)
1136
1137 # the return value is the jitframe
1138 self.mc.LGR(r.r2, r.SPP)
1139
1140 size = STD_FRAME_SIZE_IN_BYTES
1141 # f8 through f15 are saved registers (= non volatile)
1142 for i,reg in enumerate([r.f8, r.f9, r.f10, r.f11,
1143 r.f12, r.f13, r.f14, r.f15]):
1144 self.mc.LD(reg, l.addr(size + size + i*8, r.SP))
1145 # restore registers r6-r15
1146 self.mc.LMG(r.r6, r.r15, l.addr(size+6*WORD, r.SP))
1147 self.jmpto(r.r14)
1148
1149 def _push_core_regs_to_jitframe(self, mc, includes=r.MANAGED_REGS):
1150 self._multiple_to_or_from_jitframe(mc, includes, store=True)
1151
1152 @specialize.arg(3)
1153 def _multiple_to_or_from_jitframe(self, mc, includes, store):
1154 if len(includes) == 0:
1155 return
1156 base_ofs = self.cpu.get_baseofs_of_frame_field()
1157 if len(includes) == 1:
1158 iv = includes[0]
1159 v = r.ALL_REG_INDEXES[iv]
1160 addr = l.addr(base_ofs + v * WORD, r.SPP)
1161 if store:
1162 mc.STG(iv, addr)
1163 else:
1164 mc.LG(iv, addr)
1165 return
1166
1167 val = includes[0].value
1168 # includes[i => j]
1169 # for each continous sequence in the registers are stored
1170 # with STMG instead of STG, in the best case this only leads
1171 # to 1 instruction to store r.ri -> r.rj (if it is continuous)
1172 i = 0
1173 j = 1
1174 for register in includes[1:]:
1175 if i >= j:
1176 j += 1
1177 continue
1178 regval = register.value
1179 if regval != (val+1):
1180 iv = includes[i]
1181 diff = (val - iv.value)
1182 v = r.ALL_REG_INDEXES[iv]
1183 addr = l.addr(base_ofs + v * WORD, r.SPP)
1184 if diff > 0:
1185 if store:
1186 mc.STMG(iv, includes[i+diff], addr)
1187 else:
1188 mc.LMG(iv, includes[i+diff], addr)
1189 i = j
1190 else:
1191 if store:
1192 mc.STG(iv, addr)
1193 else:
1194 mc.LG(iv, addr)
1195 i = j
1196 val = regval
1197 j += 1
1198 if i >= len(includes):
1199 # all have been stored
1200 return
1201 diff = (val - includes[i].value)
1202 iv = includes[i]
1203 v = r.ALL_REG_INDEXES[iv]
1204 addr = l.addr(base_ofs + v * WORD, r.SPP)
1205 if diff > 0:
1206 if store:
1207 mc.STMG(iv, includes[-1], addr)
1208 else:
1209 mc.LMG(iv, includes[-1], addr)
1210 else:
1211 if store:
1212 mc.STG(iv, addr)
1213 else:
1214 mc.LG(iv, addr)
1215
1216 def _pop_core_regs_from_jitframe(self, mc, includes=r.MANAGED_REGS):
1217 self._multiple_to_or_from_jitframe(mc, includes, store=False)
1218
1219 def _push_fp_regs_to_jitframe(self, mc, includes=r.MANAGED_FP_REGS):
1220 if len(includes) == 0:
1221 return
1222 base_ofs = self.cpu.get_baseofs_of_frame_field()
1223 for reg in includes:
1224 v = r.ALL_REG_INDEXES[reg]
1225 offset = base_ofs + v * WORD
1226 mc.STD(reg, l.addr(offset, r.SPP))
1227
1228 def _pop_fp_regs_from_jitframe(self, mc, includes=r.MANAGED_FP_REGS):
1229 base_ofs = self.cpu.get_baseofs_of_frame_field()
1230 for reg in includes:
1231 v = r.ALL_REG_INDEXES[reg]
1232 offset = base_ofs + v * WORD
1233 mc.LD(reg, l.addr(offset, r.SPP))
1234
1235
1236 # ________________________________________
1237 # ASSEMBLER EMISSION
1238
1239 def emit_label(self, op, arglocs, regalloc):
1240 offset = self.pool.pool_start - self.mc.get_relative_pos()
1241 # load the pool address at each label
1242 self.mc.LARL(r.POOL, l.halfword(offset))
1243
1244 def emit_jump(self, op, arglocs, regalloc):
1245 # The backend's logic assumes that the target code is in a piece of
1246 # assembler that was also called with the same number of arguments,
1247 # so that the locations [ebp+8..] of the input arguments are valid
1248 # stack locations both before and after the jump.
1249 #
1250 descr = op.getdescr()
1251 assert isinstance(descr, TargetToken)
1252 my_nbargs = self.current_clt._debug_nbargs
1253 target_nbargs = descr._zarch_clt._debug_nbargs
1254 assert my_nbargs == target_nbargs
1255
1256 if descr in self.target_tokens_currently_compiling:
1257 # a label has a LARL instruction that does not need
1258 # to be executed, thus remove the first opcode
1259 self.mc.b_offset(descr._ll_loop_code + self.mc.LARL_byte_count)
1260 else:
1261 self.mc.load_imm(r.SCRATCH, descr._ll_loop_code)
1262 self.mc.BCR(c.ANY, r.SCRATCH)
1263
1264
1265
1266 def emit_finish(self, op, arglocs, regalloc):
1267 base_ofs = self.cpu.get_baseofs_of_frame_field()
1268 if len(arglocs) > 0:
1269 [return_val] = arglocs
1270 if op.getarg(0).type == FLOAT:
1271 if return_val.is_in_pool():
1272 self.mc.LDY(r.FP_SCRATCH, return_val)
1273 return_val = r.FP_SCRATCH
1274 self.mc.STDY(return_val, l.addr(base_ofs, r.SPP))
1275 else:
1276 if return_val.is_in_pool():
1277 self.mc.LG(r.SCRATCH, return_val)
1278 return_val = r.SCRATCH
1279 self.mc.STG(return_val, l.addr(base_ofs, r.SPP))
1280
1281 ofs = self.cpu.get_ofs_of_frame_field('jf_descr')
1282 ofs2 = self.cpu.get_ofs_of_frame_field('jf_gcmap')
1283
1284 # gcmap logic here:
1285 arglist = op.getarglist()
1286 if arglist and arglist[0].type == REF:
1287 if self._finish_gcmap:
1288 # we're returning with a guard_not_forced_2, and
1289 # additionally we need to say that the result contains
1290 # a reference too:
1291 self._finish_gcmap[0] |= r_uint(1)
1292 gcmap = self._finish_gcmap
1293 else:
1294 gcmap = self.gcmap_for_finish
1295 elif self._finish_gcmap:
1296 # we're returning with a guard_not_forced_2
1297 gcmap = self._finish_gcmap
1298 else:
1299 gcmap = lltype.nullptr(jitframe.GCMAP)
1300 self.load_gcmap(self.mc, r.r9, gcmap)
1301
1302 descr = op.getdescr()
1303 faildescrindex = self.get_gcref_from_faildescr(descr)
1304 self.load_gcref_into(r.r10, faildescrindex)
1305 self.mc.STG(r.r9, l.addr(ofs2, r.SPP))
1306 self.mc.STG(r.r10, l.addr(ofs, r.SPP))
1307
1308 # exit function
1309 self._call_footer()
1310
1311 def _store_and_reset_exception(self, mc, excvalloc, exctploc=None):
1312 """Reset the exception, after fetching it inside the two regs.
1313 """
1314 mc.load_imm(r.SCRATCH, self.cpu.pos_exc_value())
1315 diff = self.cpu.pos_exception() - self.cpu.pos_exc_value()
1316 assert check_imm_value(diff)
1317 # Load the exception fields into the two registers
1318 mc.load(excvalloc, r.SCRATCH, 0)
1319 if exctploc is not None:
1320 mc.load(exctploc, r.SCRATCH, diff)
1321 # Zero out the exception fields
1322 mc.LGHI(r.SCRATCH2, l.imm(0))
1323 mc.STG(r.SCRATCH2, l.addr(0, r.SCRATCH))
1324 mc.STG(r.SCRATCH2, l.addr(diff, r.SCRATCH))
1325
1326 def _restore_exception(self, mc, excvalloc, exctploc):
1327 mc.load_imm(r.SCRATCH, self.cpu.pos_exc_value())
1328 diff = self.cpu.pos_exception() - self.cpu.pos_exc_value()
1329 assert check_imm_value(diff)
1330 # Store the exception fields from the two registers
1331 mc.STG(excvalloc, l.addr(0, r.SCRATCH))
1332 mc.STG(exctploc, l.addr(diff, r.SCRATCH))
1333
1334 def load_gcmap(self, mc, reg, gcmap):
1335 # load the current gcmap into register 'reg'
1336 ptr = rffi.cast(lltype.Signed, gcmap)
1337 mc.load_imm(reg, ptr)
1338
1339 def malloc_cond(self, nursery_free_adr, nursery_top_adr, size, gcmap):
1340 assert size & (WORD-1) == 0 # must be correctly aligned
1341
1342 # We load into RES the address stored at nursery_free_adr. We
1343 # calculate the new value for nursery_free_adr and store it in
1344 # RSZ. Then we load the address stored in nursery_top_adr
1345 # into SCRATCH. In the rare case where the value in RSZ is
1346 # (unsigned) bigger than the one in SCRATCH we call
1347 # malloc_slowpath. In the common case where malloc_slowpath
1348 # is not called, we must still write RSZ back into
1349 # nursery_free_adr (r1); so we do it always, even if we called
1350 # malloc_slowpath.
1351
1352 diff = nursery_top_adr - nursery_free_adr
1353 assert check_imm_value(diff)
1354 mc = self.mc
1355 mc.load_imm(r.r1, nursery_free_adr)
1356
1357 mc.load(r.RES, r.r1, 0) # load nursery_free
1358 mc.load(r.r0, r.r1, diff) # load nursery_top
1359
1360 if check_imm_value(size):
1361 mc.AGHIK(r.RSZ, r.RES, l.imm(size))
1362 else:
1363 mc.load_imm(r.RSZ, size)
1364 mc.AGRK(r.RSZ, r.RES, r.RSZ)
1365
1366 mc.cmp_op(r.RSZ, r.r0, signed=False)
1367
1368 fast_jmp_pos = mc.currpos()
1369 mc.reserve_cond_jump(short=True) # conditional jump, patched later
1370
1371
1372 # new value of nursery_free_adr in RSZ and the adr of the new object
1373 # in RES.
1374 self.push_gcmap(mc, gcmap, store=True)
1375 mc.branch_absolute(self.malloc_slowpath)
1376
1377 # here r1 holds nursery_free_addr
1378
1379 offset = mc.currpos() - fast_jmp_pos
1380 pmc = OverwritingBuilder(mc, fast_jmp_pos, 1)
1381 pmc.BRC(c.LE, l.imm(offset)) # jump if LE (not GT), predicted to be true
1382 pmc.overwrite()
1383
1384 mc.STG(r.RSZ, l.addr(0, r.r1)) # store into nursery_free
1385
1386
1387 def malloc_cond_varsize_frame(self, nursery_free_adr, nursery_top_adr,
1388 sizeloc, gcmap):
1389 diff = nursery_top_adr - nursery_free_adr
1390 assert check_imm_value(diff)
1391 mc = self.mc
1392 mc.load_imm(r.r1, nursery_free_adr)
1393
1394 if sizeloc is r.RES:
1395 mc.LGR(r.RSZ, r.RES)
1396 sizeloc = r.RSZ
1397
1398 mc.load(r.RES, r.r1, 0) # load nursery_free
1399 mc.load(r.r0, r.r1, diff) # load nursery_top
1400
1401 mc.AGRK(r.RSZ, r.RES, sizeloc)
1402
1403 mc.cmp_op(r.RSZ, r.r0, signed=False)
1404
1405 fast_jmp_pos = mc.currpos()
1406 mc.reserve_cond_jump(short=True) # conditional jump, patched later
1407
1408 # new value of nursery_free_adr in RSZ and the adr of the new object
1409 # in RES.
1410 self.push_gcmap(mc, gcmap, store=True)
1411 mc.branch_absolute(self.malloc_slowpath)
1412
1413 offset = mc.currpos() - fast_jmp_pos
1414 pmc = OverwritingBuilder(mc, fast_jmp_pos, 1)
1415 pmc.BRC(c.LE, l.imm(offset)) # jump if LE (not GT), predicted to be true
1416 pmc.overwrite()
1417
1418 mc.STG(r.RSZ, l.addr(0, r.r1)) # store into nursery_free
1419
1420 SIZE2SCALE = dict([(1<<_i, _i) for _i in range(32)])
1421 def _multiply_by_constant(self, loc, multiply_by, scratch_loc):
1422 assert loc.is_reg()
1423 if multiply_by == 1:
1424 return loc
1425 try:
1426 scale = self.SIZE2SCALE[multiply_by]
1427 except KeyError:
1428 if check_imm_value(multiply_by, lower_bound=-2**31, upper_bound=2**31-1):
1429 self.mc.LGR(scratch_loc, loc)
1430 self.mc.MSGFI(scratch_loc, l.imm(multiply_by))
1431 else:
1432 self.mc.load_imm(scratch_loc, multiply_by)
1433 self.mc.MSGR(scratch_loc, loc)
1434 else:
1435 self.mc.SLLG(scratch_loc, loc, l.addr(scale))
1436 return scratch_loc
1437
1438 def malloc_cond_varsize(self, kind, nursery_free_adr, nursery_top_adr,
1439 lengthloc, itemsize, maxlength, gcmap,
1440 arraydescr):
1441 from rpython.jit.backend.llsupport.descr import ArrayDescr
1442 assert isinstance(arraydescr, ArrayDescr)
1443
1444 # lengthloc is the length of the array, which we must not modify!
1445 assert lengthloc is not r.RES and lengthloc is not r.RSZ
1446 assert lengthloc.is_reg()
1447
1448 assert maxlength >= 0
1449 if maxlength > 2**16-1:
1450 maxlength = 2**16-1 # makes things easier
1451 mc = self.mc
1452 mc.cmp_op(lengthloc, l.imm(maxlength), imm=True, signed=False)
1453
1454 jmp_adr0 = mc.currpos()
1455 mc.reserve_cond_jump(short=True) # conditional jump, patched later
1456
1457 # ------------------------------------------------------------
1458 # block of code for the case: the length is <= maxlength
1459
1460 diff = nursery_top_adr - nursery_free_adr
1461 assert check_imm_value(diff)
1462 mc.load_imm(r.r1, nursery_free_adr)
1463
1464 varsizeloc = self._multiply_by_constant(lengthloc, itemsize, r.RSZ)
1465
1466 # varsizeloc is either RSZ here, or equal to lengthloc if
1467 # itemsize == 1. It is the size of the variable part of the
1468 # array, in bytes.
1469
1470 mc.load(r.RES, r.r1, 0) # load nursery_free
1471 mc.load(r.SCRATCH2, r.r1, diff) # load nursery_top
1472
1473 assert arraydescr.basesize >= self.gc_minimal_size_in_nursery
1474 constsize = arraydescr.basesize + self.gc_size_of_header
1475 force_realignment = (itemsize % WORD) != 0
1476 if force_realignment:
1477 constsize += WORD - 1
1478 mc.AGHIK(r.RSZ, varsizeloc, l.imm(constsize))
1479 if force_realignment:
1480 # "& ~(WORD-1)"
1481 mc.RISBG(r.RSZ, r.RSZ, l.imm(0), l.imm(0x80 | 60), l.imm(0))
1482
1483 mc.AGRK(r.RSZ, r.RES, r.RSZ)
1484 # now RSZ contains the total size in bytes, rounded up to a multiple
1485 # of WORD, plus nursery_free_adr
1486
1487 mc.cmp_op(r.RSZ, r.SCRATCH2, signed=False)
1488
1489 jmp_adr1 = mc.currpos()
1490 mc.reserve_cond_jump(short=True) # conditional jump, patched later
1491
1492 # ------------------------------------------------------------
1493 # block of code for two cases: either the length is > maxlength
1494 # (jump from jmp_adr0), or the length is small enough but there
1495 # is not enough space in the nursery (fall-through)
1496 #
1497 offset = mc.currpos() - jmp_adr0
1498 pmc = OverwritingBuilder(mc, jmp_adr0, 1)
1499 pmc.BRC(c.GT, l.imm(offset)) # jump if GT
1500 pmc.overwrite()
1501 #
1502 # save the gcmap
1503 self.push_gcmap(mc, gcmap, store=True)
1504 #
1505 # load the function into r14 and jump
1506 if kind == rewrite.FLAG_ARRAY:
1507 addr = self.malloc_slowpath_varsize
1508 elif kind == rewrite.FLAG_STR:
1509 addr = self.malloc_slowpath_str
1510 elif kind == rewrite.FLAG_UNICODE:
1511 addr = self.malloc_slowpath_unicode
1512 else:
1513 raise AssertionError(kind)
1514 #
1515 # load the argument(s)
1516 if kind == rewrite.FLAG_ARRAY:
1517 mc.LGR(r.RSZ, lengthloc)
1518 mc.load_imm(r.RES, itemsize)
1519 mc.load_imm(r.SCRATCH2, arraydescr.tid)
1520 else:
1521 mc.LGR(r.RES, lengthloc)
1522 #
1523 #
1524 # call!
1525 mc.branch_absolute(addr)
1526
1527 jmp_location = mc.currpos()
1528 mc.reserve_cond_jump(short=True) # jump forward, patched later
1529
1530 # ------------------------------------------------------------
1531 # block of code for the common case: the length is <= maxlength
1532 # and there is enough space in the nursery
1533
1534 offset = mc.currpos() - jmp_adr1
1535 pmc = OverwritingBuilder(mc, jmp_adr1, 1)
1536 pmc.BRC(c.LE, l.imm(offset)) # jump if LE
1537 pmc.overwrite()
1538 #
1539 # write down the tid, but only in this case (not in other cases
1540 # where r.RES is the result of the CALL)
1541 mc.load_imm(r.SCRATCH2, arraydescr.tid)
1542 mc.STG(r.SCRATCH2, l.addr(0, r.RES))
1543 # while we're at it, this line is not needed if we've done the CALL
1544 mc.STG(r.RSZ, l.addr(0, r.r1)) # store into nursery_free
1545
1546 # ------------------------------------------------------------
1547 offset = mc.currpos() - jmp_location
1548 pmc = OverwritingBuilder(mc, jmp_location, 1)
1549 pmc.BRC(c.ANY, l.imm(offset)) # jump always
1550 pmc.overwrite()
1551
1552 def stitch_bridge(self, faildescr, target):
1553 """ Stitching means that one can enter a bridge with a complete different register
1554 allocation. This needs remapping which is done here for both normal registers
1555 and accumulation registers.
1556 """
1557 asminfo, bridge_faildescr, version, looptoken = target
1558 assert isinstance(bridge_faildescr, ResumeGuardDescr)
1559 assert isinstance(faildescr, ResumeGuardDescr)
1560 assert asminfo.rawstart != 0
1561 self.mc = InstrBuilder()
1562 allblocks = self.get_asmmemmgr_blocks(looptoken)
1563 self.datablockwrapper = MachineDataBlockWrapper(self.cpu.asmmemmgr,
1564 allblocks)
1565 frame_info = self.datablockwrapper.malloc_aligned(
1566 jitframe.JITFRAMEINFO_SIZE, alignment=WORD)
1567
1568 # if accumulation is saved at the guard, we need to update it here!
1569 guard_locs = self.rebuild_faillocs_from_descr(faildescr, version.inputargs)
1570 bridge_locs = self.rebuild_faillocs_from_descr(bridge_faildescr, version.inputargs)
1571 guard_accum_info = faildescr.rd_vector_info
1572 # O(n**2), but usually you only have at most 1 fail argument
1573 while guard_accum_info:
1574 bridge_accum_info = bridge_faildescr.rd_vector_info
1575 while bridge_accum_info:
1576 if bridge_accum_info.failargs_pos == guard_accum_info.failargs_pos:
1577 # the mapping might be wrong!
1578 if bridge_accum_info.location is not guard_accum_info.location:
1579 self.regalloc_mov(guard_accum_info.location, bridge_accum_info.location)
1580 bridge_accum_info = bridge_accum_info.next()
1581 guard_accum_info = guard_accum_info.next()
1582
1583 # register mapping is most likely NOT valid, thus remap it
1584 src_locations1 = []
1585 dst_locations1 = []
1586 src_locations2 = []
1587 dst_locations2 = []
1588
1589 # Build the four lists
1590 assert len(guard_locs) == len(bridge_locs)
1591 for i,src_loc in enumerate(guard_locs):
1592 dst_loc = bridge_locs[i]
1593 if not src_loc.is_fp_reg():
1594 src_locations1.append(src_loc)
1595 dst_locations1.append(dst_loc)
1596 else:
1597 src_locations2.append(src_loc)
1598 dst_locations2.append(dst_loc)
1599 remap_frame_layout_mixed(self, src_locations1, dst_locations1, r.SCRATCH,
1600 src_locations2, dst_locations2, r.FP_SCRATCH, WORD)
1601
1602 self.mc.b_abs(asminfo.asmaddr)
1603
1604 rawstart = self.materialize_loop(looptoken)
1605 # update the guard to jump right to this custom piece of assembler
1606 self.patch_jump_for_descr(faildescr, rawstart)
1607
1608 def notimplemented_op(asm, op, arglocs, regalloc):
1609 msg = "[zarch/asm] %s not implemented\n" % op.getopname()
1610 if we_are_translated():
1611 llop.debug_print(lltype.Void, msg)
1612 raise NotImplementedError(msg)
1613
1614 asm_operations = [notimplemented_op] * (rop._LAST + 1)
1615 asm_extra_operations = {}
1616
1617 for key, value in rop.__dict__.items():
1618 key = key.lower()
1619 if key.startswith('_'):
1620 continue
1621 methname = 'emit_%s' % key
1622 if hasattr(AssemblerZARCH, methname):
1623 func = getattr(AssemblerZARCH, methname).im_func
1624 asm_operations[value] = func