1/*
2 * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2016, 2017 SAP SE. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26// Major contributions by AHa, AS, JL, ML.
27
28#include "precompiled.hpp"
29#include "asm/macroAssembler.inline.hpp"
30#include "interp_masm_s390.hpp"
31#include "interpreter/interpreter.hpp"
32#include "interpreter/interpreterRuntime.hpp"
33#include "oops/arrayOop.hpp"
34#include "oops/markOop.hpp"
35#include "prims/jvmtiExport.hpp"
36#include "prims/jvmtiThreadState.hpp"
37#include "runtime/basicLock.hpp"
38#include "runtime/biasedLocking.hpp"
39#include "runtime/sharedRuntime.hpp"
40#include "runtime/thread.inline.hpp"
41
42// Implementation of InterpreterMacroAssembler.
43// This file specializes the assember with interpreter-specific macros.
44
45#ifdef PRODUCT
46#define BLOCK_COMMENT(str)
47#define BIND(label)        bind(label);
48#else
49#define BLOCK_COMMENT(str) block_comment(str)
50#define BIND(label)        bind(label); BLOCK_COMMENT(#label ":")
51#endif
52
53void InterpreterMacroAssembler::jump_to_entry(address entry, Register Rscratch) {
54  assert(entry != NULL, "Entry must have been generated by now");
55  assert(Rscratch != Z_R0, "Can't use R0 for addressing");
56  branch_optimized(Assembler::bcondAlways, entry);
57}
58
59void InterpreterMacroAssembler::empty_expression_stack(void) {
60  get_monitors(Z_R1_scratch);
61  add2reg(Z_esp, -Interpreter::stackElementSize, Z_R1_scratch);
62}
63
64// Dispatch code executed in the prolog of a bytecode which does not do it's
65// own dispatch.
66void InterpreterMacroAssembler::dispatch_prolog(TosState state, int bcp_incr) {
67  // On z/Architecture we are short on registers, therefore we do not preload the
68  // dispatch address of the next bytecode.
69}
70
71// Dispatch code executed in the epilog of a bytecode which does not do it's
72// own dispatch.
73void InterpreterMacroAssembler::dispatch_epilog(TosState state, int step) {
74  dispatch_next(state, step);
75}
76
77void InterpreterMacroAssembler::dispatch_next(TosState state, int bcp_incr) {
78  z_llgc(Z_bytecode, bcp_incr, Z_R0, Z_bcp);  // Load next bytecode.
79  add2reg(Z_bcp, bcp_incr);                   // Advance bcp. Add2reg produces optimal code.
80  dispatch_base(state, Interpreter::dispatch_table(state));
81}
82
83// Common code to dispatch and dispatch_only.
84// Dispatch value in Lbyte_code and increment Lbcp.
85
86void InterpreterMacroAssembler::dispatch_base(TosState state, address* table) {
87  verify_FPU(1, state);
88
89#ifdef ASSERT
90  address reentry = NULL;
91  { Label OK;
92    // Check if the frame pointer in Z_fp is correct.
93    z_cg(Z_fp, 0, Z_SP);
94    z_bre(OK);
95    reentry = stop_chain_static(reentry, "invalid frame pointer Z_fp: " FILE_AND_LINE);
96    bind(OK);
97  }
98  { Label OK;
99    // check if the locals pointer in Z_locals is correct
100    z_cg(Z_locals, _z_ijava_state_neg(locals), Z_fp);
101    z_bre(OK);
102    reentry = stop_chain_static(reentry, "invalid locals pointer Z_locals: " FILE_AND_LINE);
103    bind(OK);
104  }
105#endif
106
107  // TODO: Maybe implement +VerifyActivationFrameSize here.
108  // verify_thread(); // Too slow. We will just verify on method entry & exit.
109  verify_oop(Z_tos, state);
110
111  // Dispatch table to use.
112  load_absolute_address(Z_tmp_1, (address) table);  // Z_tmp_1 = table;
113
114  // 0 <= Z_bytecode < 256 => Use a 32 bit shift, because it is shorter than sllg.
115  // Z_bytecode must have been loaded zero-extended for this approach to be correct.
116  z_sll(Z_bytecode, LogBytesPerWord, Z_R0);   // Multiply by wordSize.
117  z_lg(Z_tmp_1, 0, Z_bytecode, Z_tmp_1);      // Get entry addr.
118
119  z_br(Z_tmp_1);
120}
121
122void InterpreterMacroAssembler::dispatch_only(TosState state) {
123  dispatch_base(state, Interpreter::dispatch_table(state));
124}
125
126void InterpreterMacroAssembler::dispatch_only_normal(TosState state) {
127  dispatch_base(state, Interpreter::normal_table(state));
128}
129
130void InterpreterMacroAssembler::dispatch_via(TosState state, address *table) {
131  // Load current bytecode.
132  z_llgc(Z_bytecode, Address(Z_bcp, (intptr_t)0));
133  dispatch_base(state, table);
134}
135
136// The following call_VM*_base() methods overload and mask the respective
137// declarations/definitions in class MacroAssembler. They are meant as a "detour"
138// to perform additional, template interpreter specific tasks before actually
139// calling their MacroAssembler counterparts.
140
141void InterpreterMacroAssembler::call_VM_leaf_base(address entry_point) {
142  bool allow_relocation = true; // Fenerally valid variant. Assume code is relocated.
143  // interpreter specific
144  // Note: No need to save/restore bcp (Z_R13) pointer since these are callee
145  // saved registers and no blocking/ GC can happen in leaf calls.
146
147  // super call
148  MacroAssembler::call_VM_leaf_base(entry_point, allow_relocation);
149}
150
151void InterpreterMacroAssembler::call_VM_leaf_base(address entry_point, bool allow_relocation) {
152  // interpreter specific
153  // Note: No need to save/restore bcp (Z_R13) pointer since these are callee
154  // saved registers and no blocking/ GC can happen in leaf calls.
155
156  // super call
157  MacroAssembler::call_VM_leaf_base(entry_point, allow_relocation);
158}
159
160void InterpreterMacroAssembler::call_VM_base(Register oop_result, Register last_java_sp,
161                                             address entry_point, bool check_exceptions) {
162  bool allow_relocation = true; // Fenerally valid variant. Assume code is relocated.
163  // interpreter specific
164
165  save_bcp();
166  save_esp();
167  // super call
168  MacroAssembler::call_VM_base(oop_result, last_java_sp,
169                               entry_point, allow_relocation, check_exceptions);
170  restore_bcp();
171}
172
173void InterpreterMacroAssembler::call_VM_base(Register oop_result, Register last_java_sp,
174                                             address entry_point, bool allow_relocation,
175                                             bool check_exceptions) {
176  // interpreter specific
177
178  save_bcp();
179  save_esp();
180  // super call
181  MacroAssembler::call_VM_base(oop_result, last_java_sp,
182                               entry_point, allow_relocation, check_exceptions);
183  restore_bcp();
184}
185
186void InterpreterMacroAssembler::check_and_handle_popframe(Register scratch_reg) {
187  if (JvmtiExport::can_pop_frame()) {
188    BLOCK_COMMENT("check_and_handle_popframe {");
189    Label L;
190    // Initiate popframe handling only if it is not already being
191    // processed. If the flag has the popframe_processing bit set, it
192    // means that this code is called *during* popframe handling - we
193    // don't want to reenter.
194    // TODO: Check if all four state combinations could be visible.
195    // If (processing and !pending) is an invisible/impossible state,
196    // there is optimization potential by testing both bits at once.
197    // Then, All_Zeroes and All_Ones means skip, Mixed means doit.
198    testbit(Address(Z_thread, JavaThread::popframe_condition_offset()),
199            exact_log2(JavaThread::popframe_pending_bit));
200    z_bfalse(L);
201    testbit(Address(Z_thread, JavaThread::popframe_condition_offset()),
202            exact_log2(JavaThread::popframe_processing_bit));
203    z_btrue(L);
204
205    // Call Interpreter::remove_activation_preserving_args_entry() to get the
206    // address of the same-named entrypoint in the generated interpreter code.
207    call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry));
208    // The above call should (as its only effect) return the contents of the field
209    // _remove_activation_preserving_args_entry in Z_RET.
210    // We just jump there to have the work done.
211    z_br(Z_RET);
212    // There is no way for control to fall thru here.
213
214    bind(L);
215    BLOCK_COMMENT("} check_and_handle_popframe");
216  }
217}
218
219
220void InterpreterMacroAssembler::load_earlyret_value(TosState state) {
221  Register RjvmtiState = Z_R1_scratch;
222  int      tos_off     = in_bytes(JvmtiThreadState::earlyret_tos_offset());
223  int      oop_off     = in_bytes(JvmtiThreadState::earlyret_oop_offset());
224  int      val_off     = in_bytes(JvmtiThreadState::earlyret_value_offset());
225  int      state_off   = in_bytes(JavaThread::jvmti_thread_state_offset());
226
227  z_lg(RjvmtiState, state_off, Z_thread);
228
229  switch (state) {
230    case atos: z_lg(Z_tos, oop_off, RjvmtiState);
231      store_const(Address(RjvmtiState, oop_off), 0L, 8, 8, Z_R0_scratch);
232                                                    break;
233    case ltos: z_lg(Z_tos, val_off, RjvmtiState);   break;
234    case btos: // fall through
235    case ztos: // fall through
236    case ctos: // fall through
237    case stos: // fall through
238    case itos: z_llgf(Z_tos, val_off, RjvmtiState); break;
239    case ftos: z_le(Z_ftos, val_off, RjvmtiState);  break;
240    case dtos: z_ld(Z_ftos, val_off, RjvmtiState);  break;
241    case vtos:   /* nothing to do */                break;
242    default  : ShouldNotReachHere();
243  }
244
245  // Clean up tos value in the jvmti thread state.
246  store_const(Address(RjvmtiState, val_off),   0L, 8, 8, Z_R0_scratch);
247  // Set tos state field to illegal value.
248  store_const(Address(RjvmtiState, tos_off), ilgl, 4, 1, Z_R0_scratch);
249}
250
251void InterpreterMacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
252  if (JvmtiExport::can_force_early_return()) {
253    BLOCK_COMMENT("check_and_handle_earlyret {");
254    Label L;
255    // arg regs are save, because we are just behind the call in call_VM_base
256    Register jvmti_thread_state = Z_ARG2;
257    Register tmp                = Z_ARG3;
258    load_and_test_long(jvmti_thread_state, Address(Z_thread, JavaThread::jvmti_thread_state_offset()));
259    z_bre(L); // if (thread->jvmti_thread_state() == NULL) exit;
260
261    // Initiate earlyret handling only if it is not already being processed.
262    // If the flag has the earlyret_processing bit set, it means that this code
263    // is called *during* earlyret handling - we don't want to reenter.
264
265    assert((JvmtiThreadState::earlyret_pending != 0) && (JvmtiThreadState::earlyret_inactive == 0),
266          "must fix this check, when changing the values of the earlyret enum");
267    assert(JvmtiThreadState::earlyret_pending == 1, "must fix this check, when changing the values of the earlyret enum");
268
269    load_and_test_int(tmp, Address(jvmti_thread_state, JvmtiThreadState::earlyret_state_offset()));
270    z_brz(L); // if (thread->jvmti_thread_state()->_earlyret_state != JvmtiThreadState::earlyret_pending) exit;
271
272    // Call Interpreter::remove_activation_early_entry() to get the address of the
273    // same-named entrypoint in the generated interpreter code.
274    assert(sizeof(TosState) == 4, "unexpected size");
275    z_l(Z_ARG1, Address(jvmti_thread_state, JvmtiThreadState::earlyret_tos_offset()));
276    call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), Z_ARG1);
277    // The above call should (as its only effect) return the contents of the field
278    // _remove_activation_preserving_args_entry in Z_RET.
279    // We just jump there to have the work done.
280    z_br(Z_RET);
281    // There is no way for control to fall thru here.
282
283    bind(L);
284    BLOCK_COMMENT("} check_and_handle_earlyret");
285  }
286}
287
288void InterpreterMacroAssembler::super_call_VM_leaf(address entry_point, Register arg_1, Register arg_2) {
289  lgr_if_needed(Z_ARG1, arg_1);
290  assert(arg_2 != Z_ARG1, "smashed argument");
291  lgr_if_needed(Z_ARG2, arg_2);
292  MacroAssembler::call_VM_leaf_base(entry_point, true);
293}
294
295void InterpreterMacroAssembler::get_cache_index_at_bcp(Register index, int bcp_offset, size_t index_size) {
296  Address param(Z_bcp, bcp_offset);
297
298  BLOCK_COMMENT("get_cache_index_at_bcp {");
299  assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
300  if (index_size == sizeof(u2)) {
301    load_sized_value(index, param, 2, false /*signed*/);
302  } else if (index_size == sizeof(u4)) {
303
304    load_sized_value(index, param, 4, false);
305
306    // Check if the secondary index definition is still ~x, otherwise
307    // we have to change the following assembler code to calculate the
308    // plain index.
309    assert(ConstantPool::decode_invokedynamic_index(~123) == 123, "else change next line");
310    not_(index);  // Convert to plain index.
311  } else if (index_size == sizeof(u1)) {
312    z_llgc(index, param);
313  } else {
314    ShouldNotReachHere();
315  }
316  BLOCK_COMMENT("}");
317}
318
319
320void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache, Register cpe_offset,
321                                                           int bcp_offset, size_t index_size) {
322  BLOCK_COMMENT("get_cache_and_index_at_bcp {");
323  assert_different_registers(cache, cpe_offset);
324  get_cache_index_at_bcp(cpe_offset, bcp_offset, index_size);
325  z_lg(cache, Address(Z_fp, _z_ijava_state_neg(cpoolCache)));
326  // Convert from field index to ConstantPoolCache offset in bytes.
327  z_sllg(cpe_offset, cpe_offset, exact_log2(in_words(ConstantPoolCacheEntry::size()) * BytesPerWord));
328  BLOCK_COMMENT("}");
329}
330
331// Kills Z_R0_scratch.
332void InterpreterMacroAssembler::get_cache_and_index_and_bytecode_at_bcp(Register cache,
333                                                                        Register cpe_offset,
334                                                                        Register bytecode,
335                                                                        int byte_no,
336                                                                        int bcp_offset,
337                                                                        size_t index_size) {
338  BLOCK_COMMENT("get_cache_and_index_and_bytecode_at_bcp {");
339  get_cache_and_index_at_bcp(cache, cpe_offset, bcp_offset, index_size);
340
341  // We want to load (from CP cache) the bytecode that corresponds to the passed-in byte_no.
342  // It is located at (cache + cpe_offset + base_offset + indices_offset + (8-1) (last byte in DW) - (byte_no+1).
343  // Instead of loading, shifting and masking a DW, we just load that one byte of interest with z_llgc (unsigned).
344  const int base_ix_off = in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::indices_offset());
345  const int off_in_DW   = (8-1) - (1+byte_no);
346  assert(ConstantPoolCacheEntry::bytecode_1_mask == ConstantPoolCacheEntry::bytecode_2_mask, "common mask");
347  assert(ConstantPoolCacheEntry::bytecode_1_mask == 0xff, "");
348  load_sized_value(bytecode, Address(cache, cpe_offset, base_ix_off+off_in_DW), 1, false /*signed*/);
349
350  BLOCK_COMMENT("}");
351}
352
353// Load object from cpool->resolved_references(index).
354void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result, Register index) {
355  assert_different_registers(result, index);
356  get_constant_pool(result);
357
358  // Convert
359  //  - from field index to resolved_references() index and
360  //  - from word index to byte offset.
361  // Since this is a java object, it is potentially compressed.
362  Register tmp = index;  // reuse
363  z_sllg(index, index, LogBytesPerHeapOop); // Offset into resolved references array.
364  // Load pointer for resolved_references[] objArray.
365  z_lg(result, ConstantPool::cache_offset_in_bytes(), result);
366  z_lg(result, ConstantPoolCache::resolved_references_offset_in_bytes(), result);
367  resolve_oop_handle(result); // Load resolved references array itself.
368#ifdef ASSERT
369  NearLabel index_ok;
370  z_lgf(Z_R0, Address(result, arrayOopDesc::length_offset_in_bytes()));
371  z_sllg(Z_R0, Z_R0, LogBytesPerHeapOop);
372  compare64_and_branch(tmp, Z_R0, Assembler::bcondLow, index_ok);
373  stop("resolved reference index out of bounds", 0x09256);
374  bind(index_ok);
375#endif
376  z_agr(result, index);    // Address of indexed array element.
377  load_heap_oop(result, arrayOopDesc::base_offset_in_bytes(T_OBJECT), result);
378}
379
380// load cpool->resolved_klass_at(index)
381void InterpreterMacroAssembler::load_resolved_klass_at_offset(Register cpool, Register offset, Register iklass) {
382  // int value = *(Rcpool->int_at_addr(which));
383  // int resolved_klass_index = extract_low_short_from_int(value);
384  z_llgh(offset, Address(cpool, offset, sizeof(ConstantPool) + 2)); // offset = resolved_klass_index (s390 is big-endian)
385  z_sllg(offset, offset, LogBytesPerWord);                          // Convert 'index' to 'offset'
386  z_lg(iklass, Address(cpool, ConstantPool::resolved_klasses_offset_in_bytes())); // iklass = cpool->_resolved_klasses
387  z_lg(iklass, Address(iklass, offset, Array<Klass*>::base_offset_in_bytes()));
388}
389
390void InterpreterMacroAssembler::get_cache_entry_pointer_at_bcp(Register cache,
391                                                               Register tmp,
392                                                               int bcp_offset,
393                                                               size_t index_size) {
394  BLOCK_COMMENT("get_cache_entry_pointer_at_bcp {");
395    get_cache_and_index_at_bcp(cache, tmp, bcp_offset, index_size);
396    add2reg_with_index(cache, in_bytes(ConstantPoolCache::base_offset()), tmp, cache);
397  BLOCK_COMMENT("}");
398}
399
400// Generate a subtype check: branch to ok_is_subtype if sub_klass is
401// a subtype of super_klass. Blows registers Rsuper_klass, Rsub_klass, tmp1, tmp2.
402void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass,
403                                                  Register Rsuper_klass,
404                                                  Register Rtmp1,
405                                                  Register Rtmp2,
406                                                  Label &ok_is_subtype) {
407  // Profile the not-null value's klass.
408  profile_typecheck(Rtmp1, Rsub_klass, Rtmp2);
409
410  // Do the check.
411  check_klass_subtype(Rsub_klass, Rsuper_klass, Rtmp1, Rtmp2, ok_is_subtype);
412
413  // Profile the failure of the check.
414  profile_typecheck_failed(Rtmp1, Rtmp2);
415}
416
417// Pop topmost element from stack. It just disappears.
418// Useful if consumed previously by access via stackTop().
419void InterpreterMacroAssembler::popx(int len) {
420  add2reg(Z_esp, len*Interpreter::stackElementSize);
421  debug_only(verify_esp(Z_esp, Z_R1_scratch));
422}
423
424// Get Address object of stack top. No checks. No pop.
425// Purpose: - Provide address of stack operand to exploit reg-mem operations.
426//          - Avoid RISC-like mem2reg - reg-reg-op sequence.
427Address InterpreterMacroAssembler::stackTop() {
428  return Address(Z_esp, Interpreter::expr_offset_in_bytes(0));
429}
430
431void InterpreterMacroAssembler::pop_i(Register r) {
432  z_l(r, Interpreter::expr_offset_in_bytes(0), Z_esp);
433  add2reg(Z_esp, Interpreter::stackElementSize);
434  assert_different_registers(r, Z_R1_scratch);
435  debug_only(verify_esp(Z_esp, Z_R1_scratch));
436}
437
438void InterpreterMacroAssembler::pop_ptr(Register r) {
439  z_lg(r, Interpreter::expr_offset_in_bytes(0), Z_esp);
440  add2reg(Z_esp, Interpreter::stackElementSize);
441  assert_different_registers(r, Z_R1_scratch);
442  debug_only(verify_esp(Z_esp, Z_R1_scratch));
443}
444
445void InterpreterMacroAssembler::pop_l(Register r) {
446  z_lg(r, Interpreter::expr_offset_in_bytes(0), Z_esp);
447  add2reg(Z_esp, 2*Interpreter::stackElementSize);
448  assert_different_registers(r, Z_R1_scratch);
449  debug_only(verify_esp(Z_esp, Z_R1_scratch));
450}
451
452void InterpreterMacroAssembler::pop_f(FloatRegister f) {
453  mem2freg_opt(f, Address(Z_esp, Interpreter::expr_offset_in_bytes(0)), false);
454  add2reg(Z_esp, Interpreter::stackElementSize);
455  debug_only(verify_esp(Z_esp, Z_R1_scratch));
456}
457
458void InterpreterMacroAssembler::pop_d(FloatRegister f) {
459  mem2freg_opt(f, Address(Z_esp, Interpreter::expr_offset_in_bytes(0)), true);
460  add2reg(Z_esp, 2*Interpreter::stackElementSize);
461  debug_only(verify_esp(Z_esp, Z_R1_scratch));
462}
463
464void InterpreterMacroAssembler::push_i(Register r) {
465  assert_different_registers(r, Z_R1_scratch);
466  debug_only(verify_esp(Z_esp, Z_R1_scratch));
467  z_st(r, Address(Z_esp));
468  add2reg(Z_esp, -Interpreter::stackElementSize);
469}
470
471void InterpreterMacroAssembler::push_ptr(Register r) {
472  z_stg(r, Address(Z_esp));
473  add2reg(Z_esp, -Interpreter::stackElementSize);
474}
475
476void InterpreterMacroAssembler::push_l(Register r) {
477  assert_different_registers(r, Z_R1_scratch);
478  debug_only(verify_esp(Z_esp, Z_R1_scratch));
479  int offset = -Interpreter::stackElementSize;
480  z_stg(r, Address(Z_esp, offset));
481  clear_mem(Address(Z_esp), Interpreter::stackElementSize);
482  add2reg(Z_esp, 2 * offset);
483}
484
485void InterpreterMacroAssembler::push_f(FloatRegister f) {
486  debug_only(verify_esp(Z_esp, Z_R1_scratch));
487  freg2mem_opt(f, Address(Z_esp), false);
488  add2reg(Z_esp, -Interpreter::stackElementSize);
489}
490
491void InterpreterMacroAssembler::push_d(FloatRegister d) {
492  debug_only(verify_esp(Z_esp, Z_R1_scratch));
493  int offset = -Interpreter::stackElementSize;
494  freg2mem_opt(d, Address(Z_esp, offset));
495  add2reg(Z_esp, 2 * offset);
496}
497
498void InterpreterMacroAssembler::push(TosState state) {
499  verify_oop(Z_tos, state);
500  switch (state) {
501    case atos: push_ptr();           break;
502    case btos: push_i();             break;
503    case ztos:
504    case ctos:
505    case stos: push_i();             break;
506    case itos: push_i();             break;
507    case ltos: push_l();             break;
508    case ftos: push_f();             break;
509    case dtos: push_d();             break;
510    case vtos: /* nothing to do */   break;
511    default  : ShouldNotReachHere();
512  }
513}
514
515void InterpreterMacroAssembler::pop(TosState state) {
516  switch (state) {
517    case atos: pop_ptr(Z_tos);       break;
518    case btos: pop_i(Z_tos);         break;
519    case ztos:
520    case ctos:
521    case stos: pop_i(Z_tos);         break;
522    case itos: pop_i(Z_tos);         break;
523    case ltos: pop_l(Z_tos);         break;
524    case ftos: pop_f(Z_ftos);        break;
525    case dtos: pop_d(Z_ftos);        break;
526    case vtos: /* nothing to do */   break;
527    default  : ShouldNotReachHere();
528  }
529  verify_oop(Z_tos, state);
530}
531
532// Helpers for swap and dup.
533void InterpreterMacroAssembler::load_ptr(int n, Register val) {
534  z_lg(val, Address(Z_esp, Interpreter::expr_offset_in_bytes(n)));
535}
536
537void InterpreterMacroAssembler::store_ptr(int n, Register val) {
538  z_stg(val, Address(Z_esp, Interpreter::expr_offset_in_bytes(n)));
539}
540
541void InterpreterMacroAssembler::prepare_to_jump_from_interpreted(Register method) {
542  // Satisfy interpreter calling convention (see generate_normal_entry()).
543  z_lgr(Z_R10, Z_SP); // Set sender sp (aka initial caller sp, aka unextended sp).
544  // Record top_frame_sp, because the callee might modify it, if it's compiled.
545  z_stg(Z_SP, _z_ijava_state_neg(top_frame_sp), Z_fp);
546  save_bcp();
547  save_esp();
548  z_lgr(Z_method, method); // Set Z_method (kills Z_fp!).
549}
550
551// Jump to from_interpreted entry of a call unless single stepping is possible
552// in this thread in which case we must call the i2i entry.
553void InterpreterMacroAssembler::jump_from_interpreted(Register method, Register temp) {
554  assert_different_registers(method, Z_R10 /*used for initial_caller_sp*/, temp);
555  prepare_to_jump_from_interpreted(method);
556
557  if (JvmtiExport::can_post_interpreter_events()) {
558    // JVMTI events, such as single-stepping, are implemented partly by avoiding running
559    // compiled code in threads for which the event is enabled. Check here for
560    // interp_only_mode if these events CAN be enabled.
561    z_lg(Z_R1_scratch, Address(method, Method::from_interpreted_offset()));
562    MacroAssembler::load_and_test_int(Z_R0_scratch, Address(Z_thread, JavaThread::interp_only_mode_offset()));
563    z_bcr(bcondEqual, Z_R1_scratch); // Run compiled code if zero.
564    // Run interpreted.
565    z_lg(Z_R1_scratch, Address(method, Method::interpreter_entry_offset()));
566    z_br(Z_R1_scratch);
567  } else {
568    // Run compiled code.
569    z_lg(Z_R1_scratch, Address(method, Method::from_interpreted_offset()));
570    z_br(Z_R1_scratch);
571  }
572}
573
574#ifdef ASSERT
575void InterpreterMacroAssembler::verify_esp(Register Resp, Register Rtemp) {
576  // About to read or write Resp[0].
577  // Make sure it is not in the monitors or the TOP_IJAVA_FRAME_ABI.
578  address reentry = NULL;
579
580  {
581    // Check if the frame pointer in Z_fp is correct.
582    NearLabel OK;
583    z_cg(Z_fp, 0, Z_SP);
584    z_bre(OK);
585    reentry = stop_chain_static(reentry, "invalid frame pointer Z_fp");
586    bind(OK);
587  }
588  {
589    // Resp must not point into or below the operand stack,
590    // i.e. IJAVA_STATE.monitors > Resp.
591    NearLabel OK;
592    Register Rmonitors = Rtemp;
593    z_lg(Rmonitors, _z_ijava_state_neg(monitors), Z_fp);
594    compareU64_and_branch(Rmonitors, Resp, bcondHigh, OK);
595    reentry = stop_chain_static(reentry, "too many pops: Z_esp points into monitor area");
596    bind(OK);
597  }
598  {
599    // Resp may point to the last word of TOP_IJAVA_FRAME_ABI, but not below
600    // i.e. !(Z_SP + frame::z_top_ijava_frame_abi_size - Interpreter::stackElementSize > Resp).
601    NearLabel OK;
602    Register Rabi_bottom = Rtemp;
603    add2reg(Rabi_bottom, frame::z_top_ijava_frame_abi_size - Interpreter::stackElementSize, Z_SP);
604    compareU64_and_branch(Rabi_bottom, Resp, bcondNotHigh, OK);
605    reentry = stop_chain_static(reentry, "too many pushes: Z_esp points into TOP_IJAVA_FRAME_ABI");
606    bind(OK);
607  }
608}
609
610void InterpreterMacroAssembler::asm_assert_ijava_state_magic(Register tmp) {
611  Label magic_ok;
612  load_const_optimized(tmp, frame::z_istate_magic_number);
613  z_cg(tmp, Address(Z_fp, _z_ijava_state_neg(magic)));
614  z_bre(magic_ok);
615  stop_static("error: wrong magic number in ijava_state access");
616  bind(magic_ok);
617}
618#endif // ASSERT
619
620void InterpreterMacroAssembler::save_bcp() {
621  z_stg(Z_bcp, Address(Z_fp, _z_ijava_state_neg(bcp)));
622  asm_assert_ijava_state_magic(Z_bcp);
623  NOT_PRODUCT(z_lg(Z_bcp, Address(Z_fp, _z_ijava_state_neg(bcp))));
624}
625
626void InterpreterMacroAssembler::restore_bcp() {
627  asm_assert_ijava_state_magic(Z_bcp);
628  z_lg(Z_bcp, Address(Z_fp, _z_ijava_state_neg(bcp)));
629}
630
631void InterpreterMacroAssembler::save_esp() {
632  z_stg(Z_esp, Address(Z_fp, _z_ijava_state_neg(esp)));
633}
634
635void InterpreterMacroAssembler::restore_esp() {
636  asm_assert_ijava_state_magic(Z_esp);
637  z_lg(Z_esp, Address(Z_fp, _z_ijava_state_neg(esp)));
638}
639
640void InterpreterMacroAssembler::get_monitors(Register reg) {
641  asm_assert_ijava_state_magic(reg);
642  mem2reg_opt(reg, Address(Z_fp, _z_ijava_state_neg(monitors)));
643}
644
645void InterpreterMacroAssembler::save_monitors(Register reg) {
646  reg2mem_opt(reg, Address(Z_fp, _z_ijava_state_neg(monitors)));
647}
648
649void InterpreterMacroAssembler::get_mdp(Register mdp) {
650  z_lg(mdp, _z_ijava_state_neg(mdx), Z_fp);
651}
652
653void InterpreterMacroAssembler::save_mdp(Register mdp) {
654  z_stg(mdp, _z_ijava_state_neg(mdx), Z_fp);
655}
656
657// Values that are only read (besides initialization).
658void InterpreterMacroAssembler::restore_locals() {
659  asm_assert_ijava_state_magic(Z_locals);
660  z_lg(Z_locals, Address(Z_fp, _z_ijava_state_neg(locals)));
661}
662
663void InterpreterMacroAssembler::get_method(Register reg) {
664  asm_assert_ijava_state_magic(reg);
665  z_lg(reg, Address(Z_fp, _z_ijava_state_neg(method)));
666}
667
668void InterpreterMacroAssembler::get_2_byte_integer_at_bcp(Register Rdst, int bcp_offset,
669                                                          signedOrNot is_signed) {
670  // Rdst is an 8-byte return value!!!
671
672  // Unaligned loads incur only a small penalty on z/Architecture. The penalty
673  // is a few (2..3) ticks, even when the load crosses a cache line
674  // boundary. In case of a cache miss, the stall could, of course, be
675  // much longer.
676
677  switch (is_signed) {
678    case Signed:
679      z_lgh(Rdst, bcp_offset, Z_R0, Z_bcp);
680     break;
681   case Unsigned:
682     z_llgh(Rdst, bcp_offset, Z_R0, Z_bcp);
683     break;
684   default:
685     ShouldNotReachHere();
686  }
687}
688
689
690void InterpreterMacroAssembler::get_4_byte_integer_at_bcp(Register Rdst, int bcp_offset,
691                                                          setCCOrNot set_cc) {
692  // Rdst is an 8-byte return value!!!
693
694  // Unaligned loads incur only a small penalty on z/Architecture. The penalty
695  // is a few (2..3) ticks, even when the load crosses a cache line
696  // boundary. In case of a cache miss, the stall could, of course, be
697  // much longer.
698
699  // Both variants implement a sign-extending int2long load.
700  if (set_cc == set_CC) {
701    load_and_test_int2long(Rdst, Address(Z_bcp, (intptr_t)bcp_offset));
702  } else {
703    mem2reg_signed_opt(    Rdst, Address(Z_bcp, (intptr_t)bcp_offset));
704  }
705}
706
707void InterpreterMacroAssembler::get_constant_pool(Register Rdst) {
708  get_method(Rdst);
709  mem2reg_opt(Rdst, Address(Rdst, Method::const_offset()));
710  mem2reg_opt(Rdst, Address(Rdst, ConstMethod::constants_offset()));
711}
712
713void InterpreterMacroAssembler::get_cpool_and_tags(Register Rcpool, Register Rtags) {
714  get_constant_pool(Rcpool);
715  mem2reg_opt(Rtags, Address(Rcpool, ConstantPool::tags_offset_in_bytes()));
716}
717
718// Unlock if synchronized method.
719//
720// Unlock the receiver if this is a synchronized method.
721// Unlock any Java monitors from syncronized blocks.
722//
723// If there are locked Java monitors
724//   If throw_monitor_exception
725//     throws IllegalMonitorStateException
726//   Else if install_monitor_exception
727//     installs IllegalMonitorStateException
728//   Else
729//     no error processing
730void InterpreterMacroAssembler::unlock_if_synchronized_method(TosState state,
731                                                              bool throw_monitor_exception,
732                                                              bool install_monitor_exception) {
733  NearLabel unlocked, unlock, no_unlock;
734
735  {
736    Register R_method = Z_ARG2;
737    Register R_do_not_unlock_if_synchronized = Z_ARG3;
738
739    // Get the value of _do_not_unlock_if_synchronized into G1_scratch.
740    const Address do_not_unlock_if_synchronized(Z_thread,
741                                                JavaThread::do_not_unlock_if_synchronized_offset());
742    load_sized_value(R_do_not_unlock_if_synchronized, do_not_unlock_if_synchronized, 1, false /*unsigned*/);
743    z_mvi(do_not_unlock_if_synchronized, false); // Reset the flag.
744
745    // Check if synchronized method.
746    get_method(R_method);
747    verify_oop(Z_tos, state);
748    push(state); // Save tos/result.
749    testbit(method2_(R_method, access_flags), JVM_ACC_SYNCHRONIZED_BIT);
750    z_bfalse(unlocked);
751
752    // Don't unlock anything if the _do_not_unlock_if_synchronized flag
753    // is set.
754    compareU64_and_branch(R_do_not_unlock_if_synchronized, (intptr_t)0L, bcondNotEqual, no_unlock);
755  }
756
757  // unlock monitor
758
759  // BasicObjectLock will be first in list, since this is a
760  // synchronized method. However, need to check that the object has
761  // not been unlocked by an explicit monitorexit bytecode.
762  const Address monitor(Z_fp, -(frame::z_ijava_state_size + (int) sizeof(BasicObjectLock)));
763  // We use Z_ARG2 so that if we go slow path it will be the correct
764  // register for unlock_object to pass to VM directly.
765  load_address(Z_ARG2, monitor); // Address of first monitor.
766  z_lg(Z_ARG3, Address(Z_ARG2, BasicObjectLock::obj_offset_in_bytes()));
767  compareU64_and_branch(Z_ARG3, (intptr_t)0L, bcondNotEqual, unlock);
768
769  if (throw_monitor_exception) {
770    // Entry already unlocked need to throw an exception.
771    MacroAssembler::call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
772    should_not_reach_here();
773  } else {
774    // Monitor already unlocked during a stack unroll.
775    // If requested, install an illegal_monitor_state_exception.
776    // Continue with stack unrolling.
777    if (install_monitor_exception) {
778      MacroAssembler::call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
779    }
780   z_bru(unlocked);
781  }
782
783  bind(unlock);
784
785  unlock_object(Z_ARG2);
786
787  bind(unlocked);
788
789  // I0, I1: Might contain return value
790
791  // Check that all monitors are unlocked.
792  {
793    NearLabel loop, exception, entry, restart;
794    const int entry_size = frame::interpreter_frame_monitor_size() * wordSize;
795    // We use Z_ARG2 so that if we go slow path it will be the correct
796    // register for unlock_object to pass to VM directly.
797    Register R_current_monitor = Z_ARG2;
798    Register R_monitor_block_bot = Z_ARG1;
799    const Address monitor_block_top(Z_fp, _z_ijava_state_neg(monitors));
800    const Address monitor_block_bot(Z_fp, -frame::z_ijava_state_size);
801
802    bind(restart);
803    // Starting with top-most entry.
804    z_lg(R_current_monitor, monitor_block_top);
805    // Points to word before bottom of monitor block.
806    load_address(R_monitor_block_bot, monitor_block_bot);
807    z_bru(entry);
808
809    // Entry already locked, need to throw exception.
810    bind(exception);
811
812    if (throw_monitor_exception) {
813      // Throw exception.
814      MacroAssembler::call_VM(noreg,
815                              CAST_FROM_FN_PTR(address, InterpreterRuntime::
816                                               throw_illegal_monitor_state_exception));
817      should_not_reach_here();
818    } else {
819      // Stack unrolling. Unlock object and install illegal_monitor_exception.
820      // Unlock does not block, so don't have to worry about the frame.
821      // We don't have to preserve c_rarg1 since we are going to throw an exception.
822      unlock_object(R_current_monitor);
823      if (install_monitor_exception) {
824        call_VM(noreg, CAST_FROM_FN_PTR(address,
825                                        InterpreterRuntime::
826                                        new_illegal_monitor_state_exception));
827      }
828      z_bru(restart);
829    }
830
831    bind(loop);
832    // Check if current entry is used.
833    load_and_test_long(Z_R0_scratch, Address(R_current_monitor, BasicObjectLock::obj_offset_in_bytes()));
834    z_brne(exception);
835
836    add2reg(R_current_monitor, entry_size); // Otherwise advance to next entry.
837    bind(entry);
838    compareU64_and_branch(R_current_monitor, R_monitor_block_bot, bcondNotEqual, loop);
839  }
840
841  bind(no_unlock);
842  pop(state);
843  verify_oop(Z_tos, state);
844}
845
846// remove activation
847//
848// Unlock the receiver if this is a synchronized method.
849// Unlock any Java monitors from syncronized blocks.
850// Remove the activation from the stack.
851//
852// If there are locked Java monitors
853//   If throw_monitor_exception
854//     throws IllegalMonitorStateException
855//   Else if install_monitor_exception
856//     installs IllegalMonitorStateException
857//   Else
858//     no error processing
859void InterpreterMacroAssembler::remove_activation(TosState state,
860                                                  Register return_pc,
861                                                  bool throw_monitor_exception,
862                                                  bool install_monitor_exception,
863                                                  bool notify_jvmti) {
864  BLOCK_COMMENT("remove_activation {");
865  unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception);
866
867  // Save result (push state before jvmti call and pop it afterwards) and notify jvmti.
868  notify_method_exit(false, state, notify_jvmti ? NotifyJVMTI : SkipNotifyJVMTI);
869
870  if (StackReservedPages > 0) {
871    BLOCK_COMMENT("reserved_stack_check:");
872    // Test if reserved zone needs to be enabled.
873    Label no_reserved_zone_enabling;
874
875    // Compare frame pointers. There is no good stack pointer, as with stack
876    // frame compression we can get different SPs when we do calls. A subsequent
877    // call could have a smaller SP, so that this compare succeeds for an
878    // inner call of the method annotated with ReservedStack.
879    z_lg(Z_R0, Address(Z_SP, (intptr_t)_z_abi(callers_sp)));
880    z_clg(Z_R0, Address(Z_thread, JavaThread::reserved_stack_activation_offset())); // Compare with frame pointer in memory.
881    z_brl(no_reserved_zone_enabling);
882
883    // Enable reserved zone again, throw stack overflow exception.
884    call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), Z_thread);
885    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_delayed_StackOverflowError));
886
887    should_not_reach_here();
888
889    bind(no_reserved_zone_enabling);
890  }
891
892  verify_oop(Z_tos, state);
893  verify_thread();
894
895  pop_interpreter_frame(return_pc, Z_ARG2, Z_ARG3);
896  BLOCK_COMMENT("} remove_activation");
897}
898
899// lock object
900//
901// Registers alive
902//   monitor - Address of the BasicObjectLock to be used for locking,
903//             which must be initialized with the object to lock.
904//   object  - Address of the object to be locked.
905void InterpreterMacroAssembler::lock_object(Register monitor, Register object) {
906
907  if (UseHeavyMonitors) {
908    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
909            monitor, /*check_for_exceptions=*/false);
910    return;
911  }
912
913  // template code:
914  //
915  // markOop displaced_header = obj->mark().set_unlocked();
916  // monitor->lock()->set_displaced_header(displaced_header);
917  // if (Atomic::cmpxchg_ptr(/*ex=*/monitor, /*addr*/obj->mark_addr(), /*cmp*/displaced_header) == displaced_header) {
918  //   // We stored the monitor address into the object's mark word.
919  // } else if (THREAD->is_lock_owned((address)displaced_header))
920  //   // Simple recursive case.
921  //   monitor->lock()->set_displaced_header(NULL);
922  // } else {
923  //   // Slow path.
924  //   InterpreterRuntime::monitorenter(THREAD, monitor);
925  // }
926
927  const Register displaced_header = Z_ARG5;
928  const Register object_mark_addr = Z_ARG4;
929  const Register current_header   = Z_ARG5;
930
931  NearLabel done;
932  NearLabel slow_case;
933
934  // markOop displaced_header = obj->mark().set_unlocked();
935
936  // Load markOop from object into displaced_header.
937  z_lg(displaced_header, oopDesc::mark_offset_in_bytes(), object);
938
939  if (UseBiasedLocking) {
940    biased_locking_enter(object, displaced_header, Z_R1, Z_R0, done, &slow_case);
941  }
942
943  // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
944  z_oill(displaced_header, markOopDesc::unlocked_value);
945
946  // monitor->lock()->set_displaced_header(displaced_header);
947
948  // Initialize the box (Must happen before we update the object mark!).
949  z_stg(displaced_header, BasicObjectLock::lock_offset_in_bytes() +
950                          BasicLock::displaced_header_offset_in_bytes(), monitor);
951
952  // if (Atomic::cmpxchg_ptr(/*ex=*/monitor, /*addr*/obj->mark_addr(), /*cmp*/displaced_header) == displaced_header) {
953
954  // Store stack address of the BasicObjectLock (this is monitor) into object.
955  add2reg(object_mark_addr, oopDesc::mark_offset_in_bytes(), object);
956
957  z_csg(displaced_header, monitor, 0, object_mark_addr);
958  assert(current_header==displaced_header, "must be same register"); // Identified two registers from z/Architecture.
959
960  z_bre(done);
961
962  // } else if (THREAD->is_lock_owned((address)displaced_header))
963  //   // Simple recursive case.
964  //   monitor->lock()->set_displaced_header(NULL);
965
966  // We did not see an unlocked object so try the fast recursive case.
967
968  // Check if owner is self by comparing the value in the markOop of object
969  // (current_header) with the stack pointer.
970  z_sgr(current_header, Z_SP);
971
972  assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
973
974  // The prior sequence "LGR, NGR, LTGR" can be done better
975  // (Z_R1 is temp and not used after here).
976  load_const_optimized(Z_R0, (~(os::vm_page_size()-1) | markOopDesc::lock_mask_in_place));
977  z_ngr(Z_R0, current_header); // AND sets CC (result eq/ne 0)
978
979  // If condition is true we are done and hence we can store 0 in the displaced
980  // header indicating it is a recursive lock and be done.
981  z_brne(slow_case);
982  z_release();  // Membar unnecessary on zarch AND because the above csg does a sync before and after.
983  z_stg(Z_R0/*==0!*/, BasicObjectLock::lock_offset_in_bytes() +
984                      BasicLock::displaced_header_offset_in_bytes(), monitor);
985  z_bru(done);
986
987  // } else {
988  //   // Slow path.
989  //   InterpreterRuntime::monitorenter(THREAD, monitor);
990
991  // None of the above fast optimizations worked so we have to get into the
992  // slow case of monitor enter.
993  bind(slow_case);
994
995  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
996          monitor, /*check_for_exceptions=*/false);
997
998  // }
999
1000  bind(done);
1001}
1002
1003// Unlocks an object. Used in monitorexit bytecode and remove_activation.
1004//
1005// Registers alive
1006//   monitor - address of the BasicObjectLock to be used for locking,
1007//             which must be initialized with the object to lock.
1008//
1009// Throw IllegalMonitorException if object is not locked by current thread.
1010void InterpreterMacroAssembler::unlock_object(Register monitor, Register object) {
1011
1012  if (UseHeavyMonitors) {
1013    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit),
1014            monitor, /*check_for_exceptions=*/ true);
1015    return;
1016  }
1017
1018// else {
1019  // template code:
1020  //
1021  // if ((displaced_header = monitor->displaced_header()) == NULL) {
1022  //   // Recursive unlock. Mark the monitor unlocked by setting the object field to NULL.
1023  //   monitor->set_obj(NULL);
1024  // } else if (Atomic::cmpxchg_ptr(displaced_header, obj->mark_addr(), monitor) == monitor) {
1025  //   // We swapped the unlocked mark in displaced_header into the object's mark word.
1026  //   monitor->set_obj(NULL);
1027  // } else {
1028  //   // Slow path.
1029  //   InterpreterRuntime::monitorexit(THREAD, monitor);
1030  // }
1031
1032  const Register displaced_header = Z_ARG4;
1033  const Register current_header   = Z_R1;
1034  Address obj_entry(monitor, BasicObjectLock::obj_offset_in_bytes());
1035  Label done;
1036
1037  if (object == noreg) {
1038    // In the template interpreter, we must assure that the object
1039    // entry in the monitor is cleared on all paths. Thus we move
1040    // loading up to here, and clear the entry afterwards.
1041    object = Z_ARG3; // Use Z_ARG3 if caller didn't pass object.
1042    z_lg(object, obj_entry);
1043  }
1044
1045  assert_different_registers(monitor, object, displaced_header, current_header);
1046
1047  // if ((displaced_header = monitor->displaced_header()) == NULL) {
1048  //   // Recursive unlock. Mark the monitor unlocked by setting the object field to NULL.
1049  //   monitor->set_obj(NULL);
1050
1051  clear_mem(obj_entry, sizeof(oop));
1052
1053  if (UseBiasedLocking) {
1054    // The object address from the monitor is in object.
1055    assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
1056    biased_locking_exit(object, displaced_header, done);
1057  }
1058
1059  // Test first if we are in the fast recursive case.
1060  MacroAssembler::load_and_test_long(displaced_header,
1061                                     Address(monitor, BasicObjectLock::lock_offset_in_bytes() +
1062                                                      BasicLock::displaced_header_offset_in_bytes()));
1063  z_bre(done); // displaced_header == 0 -> goto done
1064
1065  // } else if (Atomic::cmpxchg_ptr(displaced_header, obj->mark_addr(), monitor) == monitor) {
1066  //   // We swapped the unlocked mark in displaced_header into the object's mark word.
1067  //   monitor->set_obj(NULL);
1068
1069  // If we still have a lightweight lock, unlock the object and be done.
1070
1071  // The markword is expected to be at offset 0.
1072  assert(oopDesc::mark_offset_in_bytes() == 0, "unlock_object: review code below");
1073
1074  // We have the displaced header in displaced_header. If the lock is still
1075  // lightweight, it will contain the monitor address and we'll store the
1076  // displaced header back into the object's mark word.
1077  z_lgr(current_header, monitor);
1078  z_csg(current_header, displaced_header, 0, object);
1079  z_bre(done);
1080
1081  // } else {
1082  //   // Slow path.
1083  //   InterpreterRuntime::monitorexit(THREAD, monitor);
1084
1085  // The lock has been converted into a heavy lock and hence
1086  // we need to get into the slow case.
1087  z_stg(object, obj_entry);   // Restore object entry, has been cleared above.
1088  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit),
1089          monitor,  /*check_for_exceptions=*/false);
1090
1091  // }
1092
1093  bind(done);
1094}
1095
1096void InterpreterMacroAssembler::test_method_data_pointer(Register mdp, Label& zero_continue) {
1097  assert(ProfileInterpreter, "must be profiling interpreter");
1098  load_and_test_long(mdp, Address(Z_fp, _z_ijava_state_neg(mdx)));
1099  z_brz(zero_continue);
1100}
1101
1102// Set the method data pointer for the current bcp.
1103void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1104  assert(ProfileInterpreter, "must be profiling interpreter");
1105  Label    set_mdp;
1106  Register mdp    = Z_ARG4;
1107  Register method = Z_ARG5;
1108
1109  get_method(method);
1110  // Test MDO to avoid the call if it is NULL.
1111  load_and_test_long(mdp, method2_(method, method_data));
1112  z_brz(set_mdp);
1113
1114  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), method, Z_bcp);
1115  // Z_RET: mdi
1116  // Mdo is guaranteed to be non-zero here, we checked for it before the call.
1117  assert(method->is_nonvolatile(), "choose nonvolatile reg or reload from frame");
1118  z_lg(mdp, method2_(method, method_data)); // Must reload, mdp is volatile reg.
1119  add2reg_with_index(mdp, in_bytes(MethodData::data_offset()), Z_RET, mdp);
1120
1121  bind(set_mdp);
1122  save_mdp(mdp);
1123}
1124
1125void InterpreterMacroAssembler::verify_method_data_pointer() {
1126  assert(ProfileInterpreter, "must be profiling interpreter");
1127#ifdef ASSERT
1128  NearLabel verify_continue;
1129  Register bcp_expected = Z_ARG3;
1130  Register mdp    = Z_ARG4;
1131  Register method = Z_ARG5;
1132
1133  test_method_data_pointer(mdp, verify_continue); // If mdp is zero, continue
1134  get_method(method);
1135
1136  // If the mdp is valid, it will point to a DataLayout header which is
1137  // consistent with the bcp. The converse is highly probable also.
1138  load_sized_value(bcp_expected, Address(mdp, DataLayout::bci_offset()), 2, false /*signed*/);
1139  z_ag(bcp_expected, Address(method, Method::const_offset()));
1140  load_address(bcp_expected, Address(bcp_expected, ConstMethod::codes_offset()));
1141  compareU64_and_branch(bcp_expected, Z_bcp, bcondEqual, verify_continue);
1142  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp), method, Z_bcp, mdp);
1143  bind(verify_continue);
1144#endif // ASSERT
1145}
1146
1147void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in, int constant, Register value) {
1148  assert(ProfileInterpreter, "must be profiling interpreter");
1149  z_stg(value, constant, mdp_in);
1150}
1151
1152void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1153                                                      int constant,
1154                                                      Register tmp,
1155                                                      bool decrement) {
1156  assert_different_registers(mdp_in, tmp);
1157  // counter address
1158  Address data(mdp_in, constant);
1159  const int delta = decrement ? -DataLayout::counter_increment : DataLayout::counter_increment;
1160  add2mem_64(Address(mdp_in, constant), delta, tmp);
1161}
1162
1163void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1164                                                int flag_byte_constant) {
1165  assert(ProfileInterpreter, "must be profiling interpreter");
1166  // Set the flag.
1167  z_oi(Address(mdp_in, DataLayout::flags_offset()), flag_byte_constant);
1168}
1169
1170void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1171                                                 int offset,
1172                                                 Register value,
1173                                                 Register test_value_out,
1174                                                 Label& not_equal_continue) {
1175  assert(ProfileInterpreter, "must be profiling interpreter");
1176  if (test_value_out == noreg) {
1177    z_cg(value, Address(mdp_in, offset));
1178    z_brne(not_equal_continue);
1179  } else {
1180    // Put the test value into a register, so caller can use it:
1181    z_lg(test_value_out, Address(mdp_in, offset));
1182    compareU64_and_branch(test_value_out, value, bcondNotEqual, not_equal_continue);
1183  }
1184}
1185
1186void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in, int offset_of_disp) {
1187  update_mdp_by_offset(mdp_in, noreg, offset_of_disp);
1188}
1189
1190void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1191                                                     Register dataidx,
1192                                                     int offset_of_disp) {
1193  assert(ProfileInterpreter, "must be profiling interpreter");
1194  Address disp_address(mdp_in, dataidx, offset_of_disp);
1195  Assembler::z_ag(mdp_in, disp_address);
1196  save_mdp(mdp_in);
1197}
1198
1199void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in, int constant) {
1200  assert(ProfileInterpreter, "must be profiling interpreter");
1201  add2reg(mdp_in, constant);
1202  save_mdp(mdp_in);
1203}
1204
1205void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1206  assert(ProfileInterpreter, "must be profiling interpreter");
1207  assert(return_bci->is_nonvolatile(), "choose nonvolatile reg or save/restore");
1208  call_VM(noreg,
1209          CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1210          return_bci);
1211}
1212
1213void InterpreterMacroAssembler::profile_taken_branch(Register mdp, Register bumped_count) {
1214  if (ProfileInterpreter) {
1215    Label profile_continue;
1216
1217    // If no method data exists, go to profile_continue.
1218    // Otherwise, assign to mdp.
1219    test_method_data_pointer(mdp, profile_continue);
1220
1221    // We are taking a branch. Increment the taken count.
1222    // We inline increment_mdp_data_at to return bumped_count in a register
1223    //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset()));
1224    Address data(mdp, JumpData::taken_offset());
1225    z_lg(bumped_count, data);
1226    // 64-bit overflow is very unlikely. Saturation to 32-bit values is
1227    // performed when reading the counts.
1228    add2reg(bumped_count, DataLayout::counter_increment);
1229    z_stg(bumped_count, data); // Store back out
1230
1231    // The method data pointer needs to be updated to reflect the new target.
1232    update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1233    bind(profile_continue);
1234  }
1235}
1236
1237// Kills Z_R1_scratch.
1238void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) {
1239  if (ProfileInterpreter) {
1240    Label profile_continue;
1241
1242    // If no method data exists, go to profile_continue.
1243    test_method_data_pointer(mdp, profile_continue);
1244
1245    // We are taking a branch. Increment the not taken count.
1246    increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()), Z_R1_scratch);
1247
1248    // The method data pointer needs to be updated to correspond to
1249    // the next bytecode.
1250    update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size()));
1251    bind(profile_continue);
1252  }
1253}
1254
1255// Kills: Z_R1_scratch.
1256void InterpreterMacroAssembler::profile_call(Register mdp) {
1257  if (ProfileInterpreter) {
1258    Label profile_continue;
1259
1260    // If no method data exists, go to profile_continue.
1261    test_method_data_pointer(mdp, profile_continue);
1262
1263    // We are making a call. Increment the count.
1264    increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1265
1266    // The method data pointer needs to be updated to reflect the new target.
1267    update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1268    bind(profile_continue);
1269  }
1270}
1271
1272void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1273  if (ProfileInterpreter) {
1274    Label profile_continue;
1275
1276    // If no method data exists, go to profile_continue.
1277    test_method_data_pointer(mdp, profile_continue);
1278
1279    // We are making a call. Increment the count.
1280    increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1281
1282    // The method data pointer needs to be updated to reflect the new target.
1283    update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1284    bind(profile_continue);
1285  }
1286}
1287
1288void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1289                                                     Register mdp,
1290                                                     Register reg2,
1291                                                     bool receiver_can_be_null) {
1292  if (ProfileInterpreter) {
1293    NearLabel profile_continue;
1294
1295    // If no method data exists, go to profile_continue.
1296    test_method_data_pointer(mdp, profile_continue);
1297
1298    NearLabel skip_receiver_profile;
1299    if (receiver_can_be_null) {
1300      NearLabel not_null;
1301      compareU64_and_branch(receiver, (intptr_t)0L, bcondNotEqual, not_null);
1302      // We are making a call. Increment the count for null receiver.
1303      increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1304      z_bru(skip_receiver_profile);
1305      bind(not_null);
1306    }
1307
1308    // Record the receiver type.
1309    record_klass_in_profile(receiver, mdp, reg2, true);
1310    bind(skip_receiver_profile);
1311
1312    // The method data pointer needs to be updated to reflect the new target.
1313    update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1314    bind(profile_continue);
1315  }
1316}
1317
1318// This routine creates a state machine for updating the multi-row
1319// type profile at a virtual call site (or other type-sensitive bytecode).
1320// The machine visits each row (of receiver/count) until the receiver type
1321// is found, or until it runs out of rows. At the same time, it remembers
1322// the location of the first empty row. (An empty row records null for its
1323// receiver, and can be allocated for a newly-observed receiver type.)
1324// Because there are two degrees of freedom in the state, a simple linear
1325// search will not work; it must be a decision tree. Hence this helper
1326// function is recursive, to generate the required tree structured code.
1327// It's the interpreter, so we are trading off code space for speed.
1328// See below for example code.
1329void InterpreterMacroAssembler::record_klass_in_profile_helper(
1330                                        Register receiver, Register mdp,
1331                                        Register reg2, int start_row,
1332                                        Label& done, bool is_virtual_call) {
1333  if (TypeProfileWidth == 0) {
1334    if (is_virtual_call) {
1335      increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1336    }
1337    return;
1338  }
1339
1340  int last_row = VirtualCallData::row_limit() - 1;
1341  assert(start_row <= last_row, "must be work left to do");
1342  // Test this row for both the receiver and for null.
1343  // Take any of three different outcomes:
1344  //   1. found receiver => increment count and goto done
1345  //   2. found null => keep looking for case 1, maybe allocate this cell
1346  //   3. found something else => keep looking for cases 1 and 2
1347  // Case 3 is handled by a recursive call.
1348  for (int row = start_row; row <= last_row; row++) {
1349    NearLabel next_test;
1350    bool test_for_null_also = (row == start_row);
1351
1352    // See if the receiver is receiver[n].
1353    int recvr_offset = in_bytes(VirtualCallData::receiver_offset(row));
1354    test_mdp_data_at(mdp, recvr_offset, receiver,
1355                     (test_for_null_also ? reg2 : noreg),
1356                     next_test);
1357    // (Reg2 now contains the receiver from the CallData.)
1358
1359    // The receiver is receiver[n]. Increment count[n].
1360    int count_offset = in_bytes(VirtualCallData::receiver_count_offset(row));
1361    increment_mdp_data_at(mdp, count_offset);
1362    z_bru(done);
1363    bind(next_test);
1364
1365    if (test_for_null_also) {
1366      Label found_null;
1367      // Failed the equality check on receiver[n]... Test for null.
1368      z_ltgr(reg2, reg2);
1369      if (start_row == last_row) {
1370        // The only thing left to do is handle the null case.
1371        if (is_virtual_call) {
1372          z_brz(found_null);
1373          // Receiver did not match any saved receiver and there is no empty row for it.
1374          // Increment total counter to indicate polymorphic case.
1375          increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1376          z_bru(done);
1377          bind(found_null);
1378        } else {
1379          z_brnz(done);
1380        }
1381        break;
1382      }
1383      // Since null is rare, make it be the branch-taken case.
1384      z_brz(found_null);
1385
1386      // Put all the "Case 3" tests here.
1387      record_klass_in_profile_helper(receiver, mdp, reg2, start_row + 1, done, is_virtual_call);
1388
1389      // Found a null. Keep searching for a matching receiver,
1390      // but remember that this is an empty (unused) slot.
1391      bind(found_null);
1392    }
1393  }
1394
1395  // In the fall-through case, we found no matching receiver, but we
1396  // observed the receiver[start_row] is NULL.
1397
1398  // Fill in the receiver field and increment the count.
1399  int recvr_offset = in_bytes(VirtualCallData::receiver_offset(start_row));
1400  set_mdp_data_at(mdp, recvr_offset, receiver);
1401  int count_offset = in_bytes(VirtualCallData::receiver_count_offset(start_row));
1402  load_const_optimized(reg2, DataLayout::counter_increment);
1403  set_mdp_data_at(mdp, count_offset, reg2);
1404  if (start_row > 0) {
1405    z_bru(done);
1406  }
1407}
1408
1409// Example state machine code for three profile rows:
1410//   // main copy of decision tree, rooted at row[1]
1411//   if (row[0].rec == rec) { row[0].incr(); goto done; }
1412//   if (row[0].rec != NULL) {
1413//     // inner copy of decision tree, rooted at row[1]
1414//     if (row[1].rec == rec) { row[1].incr(); goto done; }
1415//     if (row[1].rec != NULL) {
1416//       // degenerate decision tree, rooted at row[2]
1417//       if (row[2].rec == rec) { row[2].incr(); goto done; }
1418//       if (row[2].rec != NULL) { count.incr(); goto done; } // overflow
1419//       row[2].init(rec); goto done;
1420//     } else {
1421//       // remember row[1] is empty
1422//       if (row[2].rec == rec) { row[2].incr(); goto done; }
1423//       row[1].init(rec); goto done;
1424//     }
1425//   } else {
1426//     // remember row[0] is empty
1427//     if (row[1].rec == rec) { row[1].incr(); goto done; }
1428//     if (row[2].rec == rec) { row[2].incr(); goto done; }
1429//     row[0].init(rec); goto done;
1430//   }
1431//   done:
1432
1433void InterpreterMacroAssembler::record_klass_in_profile(Register receiver,
1434                                                        Register mdp, Register reg2,
1435                                                        bool is_virtual_call) {
1436  assert(ProfileInterpreter, "must be profiling");
1437  Label done;
1438
1439  record_klass_in_profile_helper(receiver, mdp, reg2, 0, done, is_virtual_call);
1440
1441  bind (done);
1442}
1443
1444void InterpreterMacroAssembler::profile_ret(Register return_bci, Register mdp) {
1445  if (ProfileInterpreter) {
1446    NearLabel profile_continue;
1447    uint row;
1448
1449    // If no method data exists, go to profile_continue.
1450    test_method_data_pointer(mdp, profile_continue);
1451
1452    // Update the total ret count.
1453    increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1454
1455    for (row = 0; row < RetData::row_limit(); row++) {
1456      NearLabel next_test;
1457
1458      // See if return_bci is equal to bci[n]:
1459      test_mdp_data_at(mdp,
1460                       in_bytes(RetData::bci_offset(row)),
1461                       return_bci, noreg,
1462                       next_test);
1463
1464      // Return_bci is equal to bci[n]. Increment the count.
1465      increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1466
1467      // The method data pointer needs to be updated to reflect the new target.
1468      update_mdp_by_offset(mdp, in_bytes(RetData::bci_displacement_offset(row)));
1469      z_bru(profile_continue);
1470      bind(next_test);
1471    }
1472
1473    update_mdp_for_ret(return_bci);
1474
1475    bind(profile_continue);
1476  }
1477}
1478
1479void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1480  if (ProfileInterpreter) {
1481    Label profile_continue;
1482
1483    // If no method data exists, go to profile_continue.
1484    test_method_data_pointer(mdp, profile_continue);
1485
1486    set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1487
1488    // The method data pointer needs to be updated.
1489    int mdp_delta = in_bytes(BitData::bit_data_size());
1490    if (TypeProfileCasts) {
1491      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1492    }
1493    update_mdp_by_constant(mdp, mdp_delta);
1494
1495    bind(profile_continue);
1496  }
1497}
1498
1499void InterpreterMacroAssembler::profile_typecheck_failed(Register mdp, Register tmp) {
1500  if (ProfileInterpreter && TypeProfileCasts) {
1501    Label profile_continue;
1502
1503    // If no method data exists, go to profile_continue.
1504    test_method_data_pointer(mdp, profile_continue);
1505
1506    int count_offset = in_bytes(CounterData::count_offset());
1507    // Back up the address, since we have already bumped the mdp.
1508    count_offset -= in_bytes(VirtualCallData::virtual_call_data_size());
1509
1510    // *Decrement* the counter. We expect to see zero or small negatives.
1511    increment_mdp_data_at(mdp, count_offset, tmp, true);
1512
1513    bind (profile_continue);
1514  }
1515}
1516
1517void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1518  if (ProfileInterpreter) {
1519    Label profile_continue;
1520
1521    // If no method data exists, go to profile_continue.
1522    test_method_data_pointer(mdp, profile_continue);
1523
1524    // The method data pointer needs to be updated.
1525    int mdp_delta = in_bytes(BitData::bit_data_size());
1526    if (TypeProfileCasts) {
1527      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1528
1529      // Record the object type.
1530      record_klass_in_profile(klass, mdp, reg2, false);
1531    }
1532    update_mdp_by_constant(mdp, mdp_delta);
1533
1534    bind(profile_continue);
1535  }
1536}
1537
1538void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1539  if (ProfileInterpreter) {
1540    Label profile_continue;
1541
1542    // If no method data exists, go to profile_continue.
1543    test_method_data_pointer(mdp, profile_continue);
1544
1545    // Update the default case count.
1546    increment_mdp_data_at(mdp, in_bytes(MultiBranchData::default_count_offset()));
1547
1548    // The method data pointer needs to be updated.
1549    update_mdp_by_offset(mdp, in_bytes(MultiBranchData::default_displacement_offset()));
1550
1551    bind(profile_continue);
1552  }
1553}
1554
1555// Kills: index, scratch1, scratch2.
1556void InterpreterMacroAssembler::profile_switch_case(Register index,
1557                                                    Register mdp,
1558                                                    Register scratch1,
1559                                                    Register scratch2) {
1560  if (ProfileInterpreter) {
1561    Label profile_continue;
1562    assert_different_registers(index, mdp, scratch1, scratch2);
1563
1564    // If no method data exists, go to profile_continue.
1565    test_method_data_pointer(mdp, profile_continue);
1566
1567    // Build the base (index * per_case_size_in_bytes()) +
1568    // case_array_offset_in_bytes().
1569    z_sllg(index, index, exact_log2(in_bytes(MultiBranchData::per_case_size())));
1570    add2reg(index, in_bytes(MultiBranchData::case_array_offset()));
1571
1572    // Add the calculated base to the mdp -> address of the case' data.
1573    Address case_data_addr(mdp, index);
1574    Register case_data = scratch1;
1575    load_address(case_data, case_data_addr);
1576
1577    // Update the case count.
1578    increment_mdp_data_at(case_data,
1579                          in_bytes(MultiBranchData::relative_count_offset()),
1580                          scratch2);
1581
1582    // The method data pointer needs to be updated.
1583    update_mdp_by_offset(mdp,
1584                         index,
1585                         in_bytes(MultiBranchData::relative_displacement_offset()));
1586
1587    bind(profile_continue);
1588  }
1589}
1590
1591// kills: R0, R1, flags, loads klass from obj (if not null)
1592void InterpreterMacroAssembler::profile_obj_type(Register obj, Address mdo_addr, Register klass, bool cmp_done) {
1593  NearLabel null_seen, init_klass, do_nothing, do_update;
1594
1595  // Klass = obj is allowed.
1596  const Register tmp = Z_R1;
1597  assert_different_registers(obj, mdo_addr.base(), tmp, Z_R0);
1598  assert_different_registers(klass, mdo_addr.base(), tmp, Z_R0);
1599
1600  z_lg(tmp, mdo_addr);
1601  if (cmp_done) {
1602    z_brz(null_seen);
1603  } else {
1604    compareU64_and_branch(obj, (intptr_t)0, Assembler::bcondEqual, null_seen);
1605  }
1606
1607  verify_oop(obj);
1608  load_klass(klass, obj);
1609
1610  // Klass seen before, nothing to do (regardless of unknown bit).
1611  z_lgr(Z_R0, tmp);
1612  assert(Immediate::is_uimm(~TypeEntries::type_klass_mask, 16), "or change following instruction");
1613  z_nill(Z_R0, TypeEntries::type_klass_mask & 0xFFFF);
1614  compareU64_and_branch(Z_R0, klass, Assembler::bcondEqual, do_nothing);
1615
1616  // Already unknown. Nothing to do anymore.
1617  z_tmll(tmp, TypeEntries::type_unknown);
1618  z_brc(Assembler::bcondAllOne, do_nothing);
1619
1620  z_lgr(Z_R0, tmp);
1621  assert(Immediate::is_uimm(~TypeEntries::type_mask, 16), "or change following instruction");
1622  z_nill(Z_R0, TypeEntries::type_mask & 0xFFFF);
1623  compareU64_and_branch(Z_R0, (intptr_t)0, Assembler::bcondEqual, init_klass);
1624
1625  // Different than before. Cannot keep accurate profile.
1626  z_oill(tmp, TypeEntries::type_unknown);
1627  z_bru(do_update);
1628
1629  bind(init_klass);
1630  // Combine klass and null_seen bit (only used if (tmp & type_mask)==0).
1631  z_ogr(tmp, klass);
1632  z_bru(do_update);
1633
1634  bind(null_seen);
1635  // Set null_seen if obj is 0.
1636  z_oill(tmp, TypeEntries::null_seen);
1637  // fallthru: z_bru(do_update);
1638
1639  bind(do_update);
1640  z_stg(tmp, mdo_addr);
1641
1642  bind(do_nothing);
1643}
1644
1645void InterpreterMacroAssembler::profile_arguments_type(Register mdp, Register callee, Register tmp, bool is_virtual) {
1646  if (!ProfileInterpreter) {
1647    return;
1648  }
1649
1650  assert_different_registers(mdp, callee, tmp);
1651
1652  if (MethodData::profile_arguments() || MethodData::profile_return()) {
1653    Label profile_continue;
1654
1655    test_method_data_pointer(mdp, profile_continue);
1656
1657    int off_to_start = is_virtual ? in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
1658
1659    z_cliy(in_bytes(DataLayout::tag_offset()) - off_to_start, mdp,
1660           is_virtual ? DataLayout::virtual_call_type_data_tag : DataLayout::call_type_data_tag);
1661    z_brne(profile_continue);
1662
1663    if (MethodData::profile_arguments()) {
1664      NearLabel done;
1665      int off_to_args = in_bytes(TypeEntriesAtCall::args_data_offset());
1666      add2reg(mdp, off_to_args);
1667
1668      for (int i = 0; i < TypeProfileArgsLimit; i++) {
1669        if (i > 0 || MethodData::profile_return()) {
1670          // If return value type is profiled we may have no argument to profile.
1671          z_lg(tmp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, mdp);
1672          add2reg(tmp, -i*TypeStackSlotEntries::per_arg_count());
1673          compare64_and_branch(tmp, TypeStackSlotEntries::per_arg_count(), Assembler::bcondLow, done);
1674        }
1675        z_lg(tmp, Address(callee, Method::const_offset()));
1676        z_lgh(tmp, Address(tmp, ConstMethod::size_of_parameters_offset()));
1677        // Stack offset o (zero based) from the start of the argument
1678        // list. For n arguments translates into offset n - o - 1 from
1679        // the end of the argument list. But there is an extra slot at
1680        // the top of the stack. So the offset is n - o from Lesp.
1681        z_sg(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::stack_slot_offset(i))-off_to_args));
1682        z_sllg(tmp, tmp, Interpreter::logStackElementSize);
1683        Address stack_slot_addr(tmp, Z_esp);
1684        z_ltg(tmp, stack_slot_addr);
1685
1686        Address mdo_arg_addr(mdp, in_bytes(TypeEntriesAtCall::argument_type_offset(i))-off_to_args);
1687        profile_obj_type(tmp, mdo_arg_addr, tmp, /*ltg did compare to 0*/ true);
1688
1689        int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
1690        add2reg(mdp, to_add);
1691        off_to_args += to_add;
1692      }
1693
1694      if (MethodData::profile_return()) {
1695        z_lg(tmp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, mdp);
1696        add2reg(tmp, -TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
1697      }
1698
1699      bind(done);
1700
1701      if (MethodData::profile_return()) {
1702        // We're right after the type profile for the last
1703        // argument. Tmp is the number of cells left in the
1704        // CallTypeData/VirtualCallTypeData to reach its end. Non null
1705        // if there's a return to profile.
1706        assert(ReturnTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(), "can't move past ret type");
1707        z_sllg(tmp, tmp, exact_log2(DataLayout::cell_size));
1708        z_agr(mdp, tmp);
1709      }
1710      z_stg(mdp, _z_ijava_state_neg(mdx), Z_fp);
1711    } else {
1712      assert(MethodData::profile_return(), "either profile call args or call ret");
1713      update_mdp_by_constant(mdp, in_bytes(TypeEntriesAtCall::return_only_size()));
1714    }
1715
1716    // Mdp points right after the end of the
1717    // CallTypeData/VirtualCallTypeData, right after the cells for the
1718    // return value type if there's one.
1719    bind(profile_continue);
1720  }
1721}
1722
1723void InterpreterMacroAssembler::profile_return_type(Register mdp, Register ret, Register tmp) {
1724  assert_different_registers(mdp, ret, tmp);
1725  if (ProfileInterpreter && MethodData::profile_return()) {
1726    Label profile_continue;
1727
1728    test_method_data_pointer(mdp, profile_continue);
1729
1730    if (MethodData::profile_return_jsr292_only()) {
1731      // If we don't profile all invoke bytecodes we must make sure
1732      // it's a bytecode we indeed profile. We can't go back to the
1733      // beginning of the ProfileData we intend to update to check its
1734      // type because we're right after it and we don't known its
1735      // length.
1736      NearLabel do_profile;
1737      Address bc(Z_bcp);
1738      z_lb(tmp, bc);
1739      compare32_and_branch(tmp, Bytecodes::_invokedynamic, Assembler::bcondEqual, do_profile);
1740      compare32_and_branch(tmp, Bytecodes::_invokehandle, Assembler::bcondEqual, do_profile);
1741      get_method(tmp);
1742      // Supplement to 8139891: _intrinsic_id exceeded 1-byte size limit.
1743      if (Method::intrinsic_id_size_in_bytes() == 1) {
1744        z_cli(Method::intrinsic_id_offset_in_bytes(), tmp, vmIntrinsics::_compiledLambdaForm);
1745      } else {
1746        assert(Method::intrinsic_id_size_in_bytes() == 2, "size error: check Method::_intrinsic_id");
1747        z_lh(tmp, Method::intrinsic_id_offset_in_bytes(), Z_R0, tmp);
1748        z_chi(tmp, vmIntrinsics::_compiledLambdaForm);
1749      }
1750      z_brne(profile_continue);
1751
1752      bind(do_profile);
1753    }
1754
1755    Address mdo_ret_addr(mdp, -in_bytes(ReturnTypeEntry::size()));
1756    profile_obj_type(ret, mdo_ret_addr, tmp);
1757
1758    bind(profile_continue);
1759  }
1760}
1761
1762void InterpreterMacroAssembler::profile_parameters_type(Register mdp, Register tmp1, Register tmp2) {
1763  if (ProfileInterpreter && MethodData::profile_parameters()) {
1764    Label profile_continue, done;
1765
1766    test_method_data_pointer(mdp, profile_continue);
1767
1768    // Load the offset of the area within the MDO used for
1769    // parameters. If it's negative we're not profiling any parameters.
1770    Address parm_di_addr(mdp, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset()));
1771    load_and_test_int2long(tmp1, parm_di_addr);
1772    z_brl(profile_continue);
1773
1774    // Compute a pointer to the area for parameters from the offset
1775    // and move the pointer to the slot for the last
1776    // parameters. Collect profiling from last parameter down.
1777    // mdo start + parameters offset + array length - 1
1778
1779    // Pointer to the parameter area in the MDO.
1780    z_agr(mdp, tmp1);
1781
1782    // Offset of the current profile entry to update.
1783    const Register entry_offset = tmp1;
1784    // entry_offset = array len in number of cells.
1785    z_lg(entry_offset, Address(mdp, ArrayData::array_len_offset()));
1786    // entry_offset (number of cells) = array len - size of 1 entry
1787    add2reg(entry_offset, -TypeStackSlotEntries::per_arg_count());
1788    // entry_offset in bytes
1789    z_sllg(entry_offset, entry_offset, exact_log2(DataLayout::cell_size));
1790
1791    Label loop;
1792    bind(loop);
1793
1794    Address arg_off(mdp, entry_offset, ParametersTypeData::stack_slot_offset(0));
1795    Address arg_type(mdp, entry_offset, ParametersTypeData::type_offset(0));
1796
1797    // Load offset on the stack from the slot for this parameter.
1798    z_lg(tmp2, arg_off);
1799    z_sllg(tmp2, tmp2, Interpreter::logStackElementSize);
1800    z_lcgr(tmp2); // Negate.
1801
1802    // Profile the parameter.
1803    z_ltg(tmp2, Address(Z_locals, tmp2));
1804    profile_obj_type(tmp2, arg_type, tmp2, /*ltg did compare to 0*/ true);
1805
1806    // Go to next parameter.
1807    z_aghi(entry_offset, -TypeStackSlotEntries::per_arg_count() * DataLayout::cell_size);
1808    z_brnl(loop);
1809
1810    bind(profile_continue);
1811  }
1812}
1813
1814// Jump if ((*counter_addr += increment) & mask) satisfies the condition.
1815void InterpreterMacroAssembler::increment_mask_and_jump(Address          counter_addr,
1816                                                        int              increment,
1817                                                        Address          mask,
1818                                                        Register         scratch,
1819                                                        bool             preloaded,
1820                                                        branch_condition cond,
1821                                                        Label           *where) {
1822  assert_different_registers(counter_addr.base(), scratch);
1823  if (preloaded) {
1824    add2reg(scratch, increment);
1825    reg2mem_opt(scratch, counter_addr, false);
1826  } else {
1827    if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(increment) && counter_addr.is_RSYform()) {
1828      z_alsi(counter_addr.disp20(), counter_addr.base(), increment);
1829      mem2reg_signed_opt(scratch, counter_addr);
1830    } else {
1831      mem2reg_signed_opt(scratch, counter_addr);
1832      add2reg(scratch, increment);
1833      reg2mem_opt(scratch, counter_addr, false);
1834    }
1835  }
1836  z_n(scratch, mask);
1837  if (where) { z_brc(cond, *where); }
1838}
1839
1840// Get MethodCounters object for given method. Lazily allocated if necessary.
1841//   method    - Ptr to Method object.
1842//   Rcounters - Ptr to MethodCounters object associated with Method object.
1843//   skip      - Exit point if MethodCounters object can't be created (OOM condition).
1844void InterpreterMacroAssembler::get_method_counters(Register Rmethod,
1845                                                    Register Rcounters,
1846                                                    Label& skip) {
1847  assert_different_registers(Rmethod, Rcounters);
1848
1849  BLOCK_COMMENT("get MethodCounters object {");
1850
1851  Label has_counters;
1852  load_and_test_long(Rcounters, Address(Rmethod, Method::method_counters_offset()));
1853  z_brnz(has_counters);
1854
1855  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::build_method_counters), Rmethod, false);
1856  z_ltgr(Rcounters, Z_RET); // Runtime call returns MethodCounters object.
1857  z_brz(skip); // No MethodCounters, out of memory.
1858
1859  bind(has_counters);
1860
1861  BLOCK_COMMENT("} get MethodCounters object");
1862}
1863
1864// Increment invocation counter in MethodCounters object.
1865// Return (invocation_counter+backedge_counter) as "result" in RctrSum.
1866// Counter values are all unsigned.
1867void InterpreterMacroAssembler::increment_invocation_counter(Register Rcounters, Register RctrSum) {
1868  assert(UseCompiler || LogTouchedMethods, "incrementing must be useful");
1869  assert_different_registers(Rcounters, RctrSum);
1870
1871  int increment          = InvocationCounter::count_increment;
1872  int inv_counter_offset = in_bytes(MethodCounters::invocation_counter_offset() + InvocationCounter::counter_offset());
1873  int be_counter_offset  = in_bytes(MethodCounters::backedge_counter_offset()   + InvocationCounter::counter_offset());
1874
1875  BLOCK_COMMENT("Increment invocation counter {");
1876
1877  if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(increment)) {
1878    // Increment the invocation counter in place,
1879    // then add the incremented value to the backedge counter.
1880    z_l(RctrSum, be_counter_offset, Rcounters);
1881    z_alsi(inv_counter_offset, Rcounters, increment);     // Atomic increment @no extra cost!
1882    z_nilf(RctrSum, InvocationCounter::count_mask_value); // Mask off state bits.
1883    z_al(RctrSum, inv_counter_offset, Z_R0, Rcounters);
1884  } else {
1885    // This path is optimized for low register consumption
1886    // at the cost of somewhat higher operand delays.
1887    // It does not need an extra temp register.
1888
1889    // Update the invocation counter.
1890    z_l(RctrSum, inv_counter_offset, Rcounters);
1891    if (RctrSum == Z_R0) {
1892      z_ahi(RctrSum, increment);
1893    } else {
1894      add2reg(RctrSum, increment);
1895    }
1896    z_st(RctrSum, inv_counter_offset, Rcounters);
1897
1898    // Mask off the state bits.
1899    z_nilf(RctrSum, InvocationCounter::count_mask_value);
1900
1901    // Add the backedge counter to the updated invocation counter to
1902    // form the result.
1903    z_al(RctrSum, be_counter_offset, Z_R0, Rcounters);
1904  }
1905
1906  BLOCK_COMMENT("} Increment invocation counter");
1907
1908  // Note that this macro must leave the backedge_count + invocation_count in Rtmp!
1909}
1910
1911
1912// increment backedge counter in MethodCounters object.
1913// return (invocation_counter+backedge_counter) as "result" in RctrSum
1914// counter values are all unsigned!
1915void InterpreterMacroAssembler::increment_backedge_counter(Register Rcounters, Register RctrSum) {
1916  assert(UseCompiler, "incrementing must be useful");
1917  assert_different_registers(Rcounters, RctrSum);
1918
1919  int increment          = InvocationCounter::count_increment;
1920  int inv_counter_offset = in_bytes(MethodCounters::invocation_counter_offset() + InvocationCounter::counter_offset());
1921  int be_counter_offset  = in_bytes(MethodCounters::backedge_counter_offset()   + InvocationCounter::counter_offset());
1922
1923  BLOCK_COMMENT("Increment backedge counter {");
1924
1925  if (VM_Version::has_MemWithImmALUOps() && Immediate::is_simm8(increment)) {
1926    // Increment the invocation counter in place,
1927    // then add the incremented value to the backedge counter.
1928    z_l(RctrSum, inv_counter_offset, Rcounters);
1929    z_alsi(be_counter_offset, Rcounters, increment);      // Atomic increment @no extra cost!
1930    z_nilf(RctrSum, InvocationCounter::count_mask_value); // Mask off state bits.
1931    z_al(RctrSum, be_counter_offset, Z_R0, Rcounters);
1932  } else {
1933    // This path is optimized for low register consumption
1934    // at the cost of somewhat higher operand delays.
1935    // It does not need an extra temp register.
1936
1937    // Update the invocation counter.
1938    z_l(RctrSum, be_counter_offset, Rcounters);
1939    if (RctrSum == Z_R0) {
1940      z_ahi(RctrSum, increment);
1941    } else {
1942      add2reg(RctrSum, increment);
1943    }
1944    z_st(RctrSum, be_counter_offset, Rcounters);
1945
1946    // Mask off the state bits.
1947    z_nilf(RctrSum, InvocationCounter::count_mask_value);
1948
1949    // Add the backedge counter to the updated invocation counter to
1950    // form the result.
1951    z_al(RctrSum, inv_counter_offset, Z_R0, Rcounters);
1952  }
1953
1954  BLOCK_COMMENT("} Increment backedge counter");
1955
1956  // Note that this macro must leave the backedge_count + invocation_count in Rtmp!
1957}
1958
1959// Add an InterpMonitorElem to stack (see frame_s390.hpp).
1960void InterpreterMacroAssembler::add_monitor_to_stack(bool     stack_is_empty,
1961                                                     Register Rtemp1,
1962                                                     Register Rtemp2,
1963                                                     Register Rtemp3) {
1964
1965  const Register Rcurr_slot = Rtemp1;
1966  const Register Rlimit     = Rtemp2;
1967  const jint delta = -frame::interpreter_frame_monitor_size() * wordSize;
1968
1969  assert((delta & LongAlignmentMask) == 0,
1970         "sizeof BasicObjectLock must be even number of doublewords");
1971  assert(2 * wordSize == -delta, "this works only as long as delta == -2*wordSize");
1972  assert(Rcurr_slot != Z_R0, "Register must be usable as base register");
1973  assert_different_registers(Rlimit, Rcurr_slot, Rtemp3);
1974
1975  get_monitors(Rlimit);
1976
1977  // Adjust stack pointer for additional monitor entry.
1978  resize_frame(RegisterOrConstant((intptr_t) delta), Z_fp, false);
1979
1980  if (!stack_is_empty) {
1981    // Must copy stack contents down.
1982    NearLabel next, done;
1983
1984    // Rtemp := addr(Tos), Z_esp is pointing below it!
1985    add2reg(Rcurr_slot, wordSize, Z_esp);
1986
1987    // Nothing to do, if already at monitor area.
1988    compareU64_and_branch(Rcurr_slot, Rlimit, bcondNotLow, done);
1989
1990    bind(next);
1991
1992    // Move one stack slot.
1993    mem2reg_opt(Rtemp3, Address(Rcurr_slot));
1994    reg2mem_opt(Rtemp3, Address(Rcurr_slot, delta));
1995    add2reg(Rcurr_slot, wordSize);
1996    compareU64_and_branch(Rcurr_slot, Rlimit, bcondLow, next); // Are we done?
1997
1998    bind(done);
1999    // Done copying stack.
2000  }
2001
2002  // Adjust expression stack and monitor pointers.
2003  add2reg(Z_esp, delta);
2004  add2reg(Rlimit, delta);
2005  save_monitors(Rlimit);
2006}
2007
2008// Note: Index holds the offset in bytes afterwards.
2009// You can use this to store a new value (with Llocals as the base).
2010void InterpreterMacroAssembler::access_local_int(Register index, Register dst) {
2011  z_sllg(index, index, LogBytesPerWord);
2012  mem2reg_opt(dst, Address(Z_locals, index), false);
2013}
2014
2015void InterpreterMacroAssembler::verify_oop(Register reg, TosState state) {
2016  if (state == atos) { MacroAssembler::verify_oop(reg); }
2017}
2018
2019// Inline assembly for:
2020//
2021// if (thread is in interp_only_mode) {
2022//   InterpreterRuntime::post_method_entry();
2023// }
2024
2025void InterpreterMacroAssembler::notify_method_entry() {
2026
2027  // JVMTI
2028  // Whenever JVMTI puts a thread in interp_only_mode, method
2029  // entry/exit events are sent for that thread to track stack
2030  // depth. If it is possible to enter interp_only_mode we add
2031  // the code to check if the event should be sent.
2032  if (JvmtiExport::can_post_interpreter_events()) {
2033    Label jvmti_post_done;
2034    MacroAssembler::load_and_test_int(Z_R0, Address(Z_thread, JavaThread::interp_only_mode_offset()));
2035    z_bre(jvmti_post_done);
2036    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_entry), /*check_exceptions=*/false);
2037    bind(jvmti_post_done);
2038  }
2039}
2040
2041// Inline assembly for:
2042//
2043// if (thread is in interp_only_mode) {
2044//   if (!native_method) save result
2045//   InterpreterRuntime::post_method_exit();
2046//   if (!native_method) restore result
2047// }
2048// if (DTraceMethodProbes) {
2049//   SharedRuntime::dtrace_method_exit(thread, method);
2050// }
2051//
2052// For native methods their result is stored in z_ijava_state.lresult
2053// and z_ijava_state.fresult before coming here.
2054// Java methods have their result stored in the expression stack.
2055//
2056// Notice the dependency to frame::interpreter_frame_result().
2057void InterpreterMacroAssembler::notify_method_exit(bool native_method,
2058                                                   TosState state,
2059                                                   NotifyMethodExitMode mode) {
2060  // JVMTI
2061  // Whenever JVMTI puts a thread in interp_only_mode, method
2062  // entry/exit events are sent for that thread to track stack
2063  // depth. If it is possible to enter interp_only_mode we add
2064  // the code to check if the event should be sent.
2065  if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2066    Label jvmti_post_done;
2067    MacroAssembler::load_and_test_int(Z_R0, Address(Z_thread, JavaThread::interp_only_mode_offset()));
2068    z_bre(jvmti_post_done);
2069    if (!native_method) push(state); // see frame::interpreter_frame_result()
2070    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit), /*check_exceptions=*/false);
2071    if (!native_method) pop(state);
2072    bind(jvmti_post_done);
2073  }
2074
2075#if 0
2076  // Dtrace currently not supported on z/Architecture.
2077  {
2078    SkipIfEqual skip(this, &DTraceMethodProbes, false);
2079    push(state);
2080    get_method(c_rarg1);
2081    call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2082                 r15_thread, c_rarg1);
2083    pop(state);
2084  }
2085#endif
2086}
2087
2088void InterpreterMacroAssembler::skip_if_jvmti_mode(Label &Lskip, Register Rscratch) {
2089  if (!JvmtiExport::can_post_interpreter_events()) {
2090    return;
2091  }
2092
2093  load_and_test_int(Rscratch, Address(Z_thread, JavaThread::interp_only_mode_offset()));
2094  z_brnz(Lskip);
2095
2096}
2097
2098// Pop the topmost TOP_IJAVA_FRAME and set it's sender_sp as new Z_SP.
2099// The return pc is loaded into the register return_pc.
2100//
2101// Registers updated:
2102//     return_pc  - The return pc of the calling frame.
2103//     tmp1, tmp2 - scratch
2104void InterpreterMacroAssembler::pop_interpreter_frame(Register return_pc, Register tmp1, Register tmp2) {
2105  // F0  Z_SP -> caller_sp (F1's)
2106  //             ...
2107  //             sender_sp (F1's)
2108  //             ...
2109  // F1  Z_fp -> caller_sp (F2's)
2110  //             return_pc (Continuation after return from F0.)
2111  //             ...
2112  // F2          caller_sp
2113
2114  // Remove F0's activation. Restoring Z_SP to sender_sp reverts modifications
2115  // (a) by a c2i adapter and (b) by generate_fixed_frame().
2116  // In case (a) the new top frame F1 is an unextended compiled frame.
2117  // In case (b) F1 is converted from PARENT_IJAVA_FRAME to TOP_IJAVA_FRAME.
2118
2119  // Case (b) seems to be redundant when returning to a interpreted caller,
2120  // because then the caller's top_frame_sp is installed as sp (see
2121  // TemplateInterpreterGenerator::generate_return_entry_for ()). But
2122  // pop_interpreter_frame() is also used in exception handling and there the
2123  // frame type of the caller is unknown, therefore top_frame_sp cannot be used,
2124  // so it is important that sender_sp is the caller's sp as TOP_IJAVA_FRAME.
2125
2126  Register R_f1_sender_sp = tmp1;
2127  Register R_f2_sp = tmp2;
2128
2129  // Tirst check the for the interpreter frame's magic.
2130  asm_assert_ijava_state_magic(R_f2_sp/*tmp*/);
2131  z_lg(R_f2_sp, _z_parent_ijava_frame_abi(callers_sp), Z_fp);
2132  z_lg(R_f1_sender_sp, _z_ijava_state_neg(sender_sp), Z_fp);
2133  if (return_pc->is_valid())
2134    z_lg(return_pc, _z_parent_ijava_frame_abi(return_pc), Z_fp);
2135  // Pop F0 by resizing to R_f1_sender_sp and using R_f2_sp as fp.
2136  resize_frame_absolute(R_f1_sender_sp, R_f2_sp, false/*load fp*/);
2137
2138#ifdef ASSERT
2139  // The return_pc in the new top frame is dead... at least that's my
2140  // current understanding; to assert this I overwrite it.
2141  load_const_optimized(Z_ARG3, 0xb00b1);
2142  z_stg(Z_ARG3, _z_parent_ijava_frame_abi(return_pc), Z_SP);
2143#endif
2144}
2145
2146void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
2147  if (VerifyFPU) {
2148    unimplemented("verfiyFPU");
2149  }
2150}
2151
2152