1/*
2 * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2012, 2016 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
27#include "precompiled.hpp"
28#include "asm/macroAssembler.inline.hpp"
29#include "interp_masm_ppc.hpp"
30#include "interpreter/interpreterRuntime.hpp"
31#include "prims/jvmtiThreadState.hpp"
32#include "runtime/sharedRuntime.hpp"
33
34#ifdef PRODUCT
35#define BLOCK_COMMENT(str) // nothing
36#else
37#define BLOCK_COMMENT(str) block_comment(str)
38#endif
39
40void InterpreterMacroAssembler::null_check_throw(Register a, int offset, Register temp_reg) {
41  address exception_entry = Interpreter::throw_NullPointerException_entry();
42  MacroAssembler::null_check_throw(a, offset, temp_reg, exception_entry);
43}
44
45void InterpreterMacroAssembler::jump_to_entry(address entry, Register Rscratch) {
46  assert(entry, "Entry must have been generated by now");
47  if (is_within_range_of_b(entry, pc())) {
48    b(entry);
49  } else {
50    load_const_optimized(Rscratch, entry, R0);
51    mtctr(Rscratch);
52    bctr();
53  }
54}
55
56void InterpreterMacroAssembler::dispatch_next(TosState state, int bcp_incr) {
57  Register bytecode = R12_scratch2;
58  if (bcp_incr != 0) {
59    lbzu(bytecode, bcp_incr, R14_bcp);
60  } else {
61    lbz(bytecode, 0, R14_bcp);
62  }
63
64  dispatch_Lbyte_code(state, bytecode, Interpreter::dispatch_table(state));
65}
66
67void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
68  // Load current bytecode.
69  Register bytecode = R12_scratch2;
70  lbz(bytecode, 0, R14_bcp);
71  dispatch_Lbyte_code(state, bytecode, table);
72}
73
74// Dispatch code executed in the prolog of a bytecode which does not do it's
75// own dispatch. The dispatch address is computed and placed in R24_dispatch_addr.
76void InterpreterMacroAssembler::dispatch_prolog(TosState state, int bcp_incr) {
77  Register bytecode = R12_scratch2;
78  lbz(bytecode, bcp_incr, R14_bcp);
79
80  load_dispatch_table(R24_dispatch_addr, Interpreter::dispatch_table(state));
81
82  sldi(bytecode, bytecode, LogBytesPerWord);
83  ldx(R24_dispatch_addr, R24_dispatch_addr, bytecode);
84}
85
86// Dispatch code executed in the epilog of a bytecode which does not do it's
87// own dispatch. The dispatch address in R24_dispatch_addr is used for the
88// dispatch.
89void InterpreterMacroAssembler::dispatch_epilog(TosState state, int bcp_incr) {
90  if (bcp_incr) { addi(R14_bcp, R14_bcp, bcp_incr); }
91  mtctr(R24_dispatch_addr);
92  bcctr(bcondAlways, 0, bhintbhBCCTRisNotPredictable);
93}
94
95void InterpreterMacroAssembler::check_and_handle_popframe(Register scratch_reg) {
96  assert(scratch_reg != R0, "can't use R0 as scratch_reg here");
97  if (JvmtiExport::can_pop_frame()) {
98    Label L;
99
100    // Check the "pending popframe condition" flag in the current thread.
101    lwz(scratch_reg, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
102
103    // Initiate popframe handling only if it is not already being
104    // processed. If the flag has the popframe_processing bit set, it
105    // means that this code is called *during* popframe handling - we
106    // don't want to reenter.
107    andi_(R0, scratch_reg, JavaThread::popframe_pending_bit);
108    beq(CCR0, L);
109
110    andi_(R0, scratch_reg, JavaThread::popframe_processing_bit);
111    bne(CCR0, L);
112
113    // Call the Interpreter::remove_activation_preserving_args_entry()
114    // func to get the address of the same-named entrypoint in the
115    // generated interpreter code.
116#if defined(ABI_ELFv2)
117    call_c(CAST_FROM_FN_PTR(address,
118                            Interpreter::remove_activation_preserving_args_entry),
119           relocInfo::none);
120#else
121    call_c(CAST_FROM_FN_PTR(FunctionDescriptor*,
122                            Interpreter::remove_activation_preserving_args_entry),
123           relocInfo::none);
124#endif
125
126    // Jump to Interpreter::_remove_activation_preserving_args_entry.
127    mtctr(R3_RET);
128    bctr();
129
130    align(32, 12);
131    bind(L);
132  }
133}
134
135void InterpreterMacroAssembler::check_and_handle_earlyret(Register scratch_reg) {
136  const Register Rthr_state_addr = scratch_reg;
137  if (JvmtiExport::can_force_early_return()) {
138    Label Lno_early_ret;
139    ld(Rthr_state_addr, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
140    cmpdi(CCR0, Rthr_state_addr, 0);
141    beq(CCR0, Lno_early_ret);
142
143    lwz(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rthr_state_addr);
144    cmpwi(CCR0, R0, JvmtiThreadState::earlyret_pending);
145    bne(CCR0, Lno_early_ret);
146
147    // Jump to Interpreter::_earlyret_entry.
148    lwz(R3_ARG1, in_bytes(JvmtiThreadState::earlyret_tos_offset()), Rthr_state_addr);
149    call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry));
150    mtlr(R3_RET);
151    blr();
152
153    align(32, 12);
154    bind(Lno_early_ret);
155  }
156}
157
158void InterpreterMacroAssembler::load_earlyret_value(TosState state, Register Rscratch1) {
159  const Register RjvmtiState = Rscratch1;
160  const Register Rscratch2   = R0;
161
162  ld(RjvmtiState, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
163  li(Rscratch2, 0);
164
165  switch (state) {
166    case atos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
167               std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_oop_offset()), RjvmtiState);
168               break;
169    case ltos: ld(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
170               break;
171    case btos: // fall through
172    case ztos: // fall through
173    case ctos: // fall through
174    case stos: // fall through
175    case itos: lwz(R17_tos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
176               break;
177    case ftos: lfs(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
178               break;
179    case dtos: lfd(F15_ftos, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
180               break;
181    case vtos: break;
182    default  : ShouldNotReachHere();
183  }
184
185  // Clean up tos value in the jvmti thread state.
186  std(Rscratch2, in_bytes(JvmtiThreadState::earlyret_value_offset()), RjvmtiState);
187  // Set tos state field to illegal value.
188  li(Rscratch2, ilgl);
189  stw(Rscratch2, in_bytes(JvmtiThreadState::earlyret_tos_offset()), RjvmtiState);
190}
191
192// Common code to dispatch and dispatch_only.
193// Dispatch value in Lbyte_code and increment Lbcp.
194
195void InterpreterMacroAssembler::load_dispatch_table(Register dst, address* table) {
196  address table_base = (address)Interpreter::dispatch_table((TosState)0);
197  intptr_t table_offs = (intptr_t)table - (intptr_t)table_base;
198  if (is_simm16(table_offs)) {
199    addi(dst, R25_templateTableBase, (int)table_offs);
200  } else {
201    load_const_optimized(dst, table, R0);
202  }
203}
204
205void InterpreterMacroAssembler::dispatch_Lbyte_code(TosState state, Register bytecode,
206                                                    address* table, bool verify) {
207  if (verify) {
208    unimplemented("dispatch_Lbyte_code: verify"); // See Sparc Implementation to implement this
209  }
210
211  assert_different_registers(bytecode, R11_scratch1);
212
213  // Calc dispatch table address.
214  load_dispatch_table(R11_scratch1, table);
215
216  sldi(R12_scratch2, bytecode, LogBytesPerWord);
217  ldx(R11_scratch1, R11_scratch1, R12_scratch2);
218
219  // Jump off!
220  mtctr(R11_scratch1);
221  bcctr(bcondAlways, 0, bhintbhBCCTRisNotPredictable);
222}
223
224void InterpreterMacroAssembler::load_receiver(Register Rparam_count, Register Rrecv_dst) {
225  sldi(Rrecv_dst, Rparam_count, Interpreter::logStackElementSize);
226  ldx(Rrecv_dst, Rrecv_dst, R15_esp);
227}
228
229// helpers for expression stack
230
231void InterpreterMacroAssembler::pop_i(Register r) {
232  lwzu(r, Interpreter::stackElementSize, R15_esp);
233}
234
235void InterpreterMacroAssembler::pop_ptr(Register r) {
236  ldu(r, Interpreter::stackElementSize, R15_esp);
237}
238
239void InterpreterMacroAssembler::pop_l(Register r) {
240  ld(r, Interpreter::stackElementSize, R15_esp);
241  addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
242}
243
244void InterpreterMacroAssembler::pop_f(FloatRegister f) {
245  lfsu(f, Interpreter::stackElementSize, R15_esp);
246}
247
248void InterpreterMacroAssembler::pop_d(FloatRegister f) {
249  lfd(f, Interpreter::stackElementSize, R15_esp);
250  addi(R15_esp, R15_esp, 2 * Interpreter::stackElementSize);
251}
252
253void InterpreterMacroAssembler::push_i(Register r) {
254  stw(r, 0, R15_esp);
255  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
256}
257
258void InterpreterMacroAssembler::push_ptr(Register r) {
259  std(r, 0, R15_esp);
260  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
261}
262
263void InterpreterMacroAssembler::push_l(Register r) {
264  // Clear unused slot.
265  load_const_optimized(R0, 0L);
266  std(R0, 0, R15_esp);
267  std(r, - Interpreter::stackElementSize, R15_esp);
268  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
269}
270
271void InterpreterMacroAssembler::push_f(FloatRegister f) {
272  stfs(f, 0, R15_esp);
273  addi(R15_esp, R15_esp, - Interpreter::stackElementSize );
274}
275
276void InterpreterMacroAssembler::push_d(FloatRegister f)   {
277  stfd(f, - Interpreter::stackElementSize, R15_esp);
278  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
279}
280
281void InterpreterMacroAssembler::push_2ptrs(Register first, Register second) {
282  std(first, 0, R15_esp);
283  std(second, -Interpreter::stackElementSize, R15_esp);
284  addi(R15_esp, R15_esp, - 2 * Interpreter::stackElementSize );
285}
286
287void InterpreterMacroAssembler::push_l_pop_d(Register l, FloatRegister d) {
288  std(l, 0, R15_esp);
289  lfd(d, 0, R15_esp);
290}
291
292void InterpreterMacroAssembler::push_d_pop_l(FloatRegister d, Register l) {
293  stfd(d, 0, R15_esp);
294  ld(l, 0, R15_esp);
295}
296
297void InterpreterMacroAssembler::push(TosState state) {
298  switch (state) {
299    case atos: push_ptr();                break;
300    case btos:
301    case ztos:
302    case ctos:
303    case stos:
304    case itos: push_i();                  break;
305    case ltos: push_l();                  break;
306    case ftos: push_f();                  break;
307    case dtos: push_d();                  break;
308    case vtos: /* nothing to do */        break;
309    default  : ShouldNotReachHere();
310  }
311}
312
313void InterpreterMacroAssembler::pop(TosState state) {
314  switch (state) {
315    case atos: pop_ptr();            break;
316    case btos:
317    case ztos:
318    case ctos:
319    case stos:
320    case itos: pop_i();              break;
321    case ltos: pop_l();              break;
322    case ftos: pop_f();              break;
323    case dtos: pop_d();              break;
324    case vtos: /* nothing to do */   break;
325    default  : ShouldNotReachHere();
326  }
327  verify_oop(R17_tos, state);
328}
329
330void InterpreterMacroAssembler::empty_expression_stack() {
331  addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
332}
333
334void InterpreterMacroAssembler::get_2_byte_integer_at_bcp(int         bcp_offset,
335                                                          Register    Rdst,
336                                                          signedOrNot is_signed) {
337#if defined(VM_LITTLE_ENDIAN)
338  if (bcp_offset) {
339    load_const_optimized(Rdst, bcp_offset);
340    lhbrx(Rdst, R14_bcp, Rdst);
341  } else {
342    lhbrx(Rdst, R14_bcp);
343  }
344  if (is_signed == Signed) {
345    extsh(Rdst, Rdst);
346  }
347#else
348  // Read Java big endian format.
349  if (is_signed == Signed) {
350    lha(Rdst, bcp_offset, R14_bcp);
351  } else {
352    lhz(Rdst, bcp_offset, R14_bcp);
353  }
354#endif
355}
356
357void InterpreterMacroAssembler::get_4_byte_integer_at_bcp(int         bcp_offset,
358                                                          Register    Rdst,
359                                                          signedOrNot is_signed) {
360#if defined(VM_LITTLE_ENDIAN)
361  if (bcp_offset) {
362    load_const_optimized(Rdst, bcp_offset);
363    lwbrx(Rdst, R14_bcp, Rdst);
364  } else {
365    lwbrx(Rdst, R14_bcp);
366  }
367  if (is_signed == Signed) {
368    extsw(Rdst, Rdst);
369  }
370#else
371  // Read Java big endian format.
372  if (bcp_offset & 3) { // Offset unaligned?
373    load_const_optimized(Rdst, bcp_offset);
374    if (is_signed == Signed) {
375      lwax(Rdst, R14_bcp, Rdst);
376    } else {
377      lwzx(Rdst, R14_bcp, Rdst);
378    }
379  } else {
380    if (is_signed == Signed) {
381      lwa(Rdst, bcp_offset, R14_bcp);
382    } else {
383      lwz(Rdst, bcp_offset, R14_bcp);
384    }
385  }
386#endif
387}
388
389
390// Load the constant pool cache index from the bytecode stream.
391//
392// Kills / writes:
393//   - Rdst, Rscratch
394void InterpreterMacroAssembler::get_cache_index_at_bcp(Register Rdst, int bcp_offset,
395                                                       size_t index_size) {
396  assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
397  // Cache index is always in the native format, courtesy of Rewriter.
398  if (index_size == sizeof(u2)) {
399    lhz(Rdst, bcp_offset, R14_bcp);
400  } else if (index_size == sizeof(u4)) {
401    if (bcp_offset & 3) {
402      load_const_optimized(Rdst, bcp_offset);
403      lwax(Rdst, R14_bcp, Rdst);
404    } else {
405      lwa(Rdst, bcp_offset, R14_bcp);
406    }
407    assert(ConstantPool::decode_invokedynamic_index(~123) == 123, "else change next line");
408    nand(Rdst, Rdst, Rdst); // convert to plain index
409  } else if (index_size == sizeof(u1)) {
410    lbz(Rdst, bcp_offset, R14_bcp);
411  } else {
412    ShouldNotReachHere();
413  }
414  // Rdst now contains cp cache index.
415}
416
417void InterpreterMacroAssembler::get_cache_and_index_at_bcp(Register cache, int bcp_offset,
418                                                           size_t index_size) {
419  get_cache_index_at_bcp(cache, bcp_offset, index_size);
420  sldi(cache, cache, exact_log2(in_words(ConstantPoolCacheEntry::size()) * BytesPerWord));
421  add(cache, R27_constPoolCache, cache);
422}
423
424// Load 4-byte signed or unsigned integer in Java format (that is, big-endian format)
425// from (Rsrc)+offset.
426void InterpreterMacroAssembler::get_u4(Register Rdst, Register Rsrc, int offset,
427                                       signedOrNot is_signed) {
428#if defined(VM_LITTLE_ENDIAN)
429  if (offset) {
430    load_const_optimized(Rdst, offset);
431    lwbrx(Rdst, Rdst, Rsrc);
432  } else {
433    lwbrx(Rdst, Rsrc);
434  }
435  if (is_signed == Signed) {
436    extsw(Rdst, Rdst);
437  }
438#else
439  if (is_signed == Signed) {
440    lwa(Rdst, offset, Rsrc);
441  } else {
442    lwz(Rdst, offset, Rsrc);
443  }
444#endif
445}
446
447// Load object from cpool->resolved_references(index).
448void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result, Register index, Label *is_null) {
449  assert_different_registers(result, index);
450  get_constant_pool(result);
451
452  // Convert from field index to resolved_references() index and from
453  // word index to byte offset. Since this is a java object, it can be compressed.
454  Register tmp = index;  // reuse
455  sldi(tmp, index, LogBytesPerHeapOop);
456  // Load pointer for resolved_references[] objArray.
457  ld(result, ConstantPool::resolved_references_offset_in_bytes(), result);
458  // JNIHandles::resolve(result)
459  ld(result, 0, result);
460#ifdef ASSERT
461  Label index_ok;
462  lwa(R0, arrayOopDesc::length_offset_in_bytes(), result);
463  sldi(R0, R0, LogBytesPerHeapOop);
464  cmpd(CCR0, tmp, R0);
465  blt(CCR0, index_ok);
466  stop("resolved reference index out of bounds", 0x09256);
467  bind(index_ok);
468#endif
469  // Add in the index.
470  add(result, tmp, result);
471  load_heap_oop(result, arrayOopDesc::base_offset_in_bytes(T_OBJECT), result, is_null);
472}
473
474// Generate a subtype check: branch to ok_is_subtype if sub_klass is
475// a subtype of super_klass. Blows registers Rsub_klass, tmp1, tmp2.
476void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass, Register Rsuper_klass, Register Rtmp1,
477                                                  Register Rtmp2, Register Rtmp3, Label &ok_is_subtype) {
478  // Profile the not-null value's klass.
479  profile_typecheck(Rsub_klass, Rtmp1, Rtmp2);
480  check_klass_subtype(Rsub_klass, Rsuper_klass, Rtmp1, Rtmp2, ok_is_subtype);
481  profile_typecheck_failed(Rtmp1, Rtmp2);
482}
483
484// Separate these two to allow for delay slot in middle.
485// These are used to do a test and full jump to exception-throwing code.
486
487// Check that index is in range for array, then shift index by index_shift,
488// and put arrayOop + shifted_index into res.
489// Note: res is still shy of address by array offset into object.
490
491void InterpreterMacroAssembler::index_check_without_pop(Register Rarray, Register Rindex,
492                                                        int index_shift, Register Rtmp, Register Rres) {
493  // Check that index is in range for array, then shift index by index_shift,
494  // and put arrayOop + shifted_index into res.
495  // Note: res is still shy of address by array offset into object.
496  // Kills:
497  //   - Rindex
498  // Writes:
499  //   - Rres: Address that corresponds to the array index if check was successful.
500  verify_oop(Rarray);
501  const Register Rlength   = R0;
502  const Register RsxtIndex = Rtmp;
503  Label LisNull, LnotOOR;
504
505  // Array nullcheck
506  if (!ImplicitNullChecks) {
507    cmpdi(CCR0, Rarray, 0);
508    beq(CCR0, LisNull);
509  } else {
510    null_check_throw(Rarray, arrayOopDesc::length_offset_in_bytes(), /*temp*/RsxtIndex);
511  }
512
513  // Rindex might contain garbage in upper bits (remember that we don't sign extend
514  // during integer arithmetic operations). So kill them and put value into same register
515  // where ArrayIndexOutOfBounds would expect the index in.
516  rldicl(RsxtIndex, Rindex, 0, 32); // zero extend 32 bit -> 64 bit
517
518  // Index check
519  lwz(Rlength, arrayOopDesc::length_offset_in_bytes(), Rarray);
520  cmplw(CCR0, Rindex, Rlength);
521  sldi(RsxtIndex, RsxtIndex, index_shift);
522  blt(CCR0, LnotOOR);
523  // Index should be in R17_tos, array should be in R4_ARG2.
524  mr_if_needed(R17_tos, Rindex);
525  mr_if_needed(R4_ARG2, Rarray);
526  load_dispatch_table(Rtmp, (address*)Interpreter::_throw_ArrayIndexOutOfBoundsException_entry);
527  mtctr(Rtmp);
528  bctr();
529
530  if (!ImplicitNullChecks) {
531    bind(LisNull);
532    load_dispatch_table(Rtmp, (address*)Interpreter::_throw_NullPointerException_entry);
533    mtctr(Rtmp);
534    bctr();
535  }
536
537  align(32, 16);
538  bind(LnotOOR);
539
540  // Calc address
541  add(Rres, RsxtIndex, Rarray);
542}
543
544void InterpreterMacroAssembler::index_check(Register array, Register index,
545                                            int index_shift, Register tmp, Register res) {
546  // pop array
547  pop_ptr(array);
548
549  // check array
550  index_check_without_pop(array, index, index_shift, tmp, res);
551}
552
553void InterpreterMacroAssembler::get_const(Register Rdst) {
554  ld(Rdst, in_bytes(Method::const_offset()), R19_method);
555}
556
557void InterpreterMacroAssembler::get_constant_pool(Register Rdst) {
558  get_const(Rdst);
559  ld(Rdst, in_bytes(ConstMethod::constants_offset()), Rdst);
560}
561
562void InterpreterMacroAssembler::get_constant_pool_cache(Register Rdst) {
563  get_constant_pool(Rdst);
564  ld(Rdst, ConstantPool::cache_offset_in_bytes(), Rdst);
565}
566
567void InterpreterMacroAssembler::get_cpool_and_tags(Register Rcpool, Register Rtags) {
568  get_constant_pool(Rcpool);
569  ld(Rtags, ConstantPool::tags_offset_in_bytes(), Rcpool);
570}
571
572// Unlock if synchronized method.
573//
574// Unlock the receiver if this is a synchronized method.
575// Unlock any Java monitors from synchronized blocks.
576//
577// If there are locked Java monitors
578//   If throw_monitor_exception
579//     throws IllegalMonitorStateException
580//   Else if install_monitor_exception
581//     installs IllegalMonitorStateException
582//   Else
583//     no error processing
584void InterpreterMacroAssembler::unlock_if_synchronized_method(TosState state,
585                                                              bool throw_monitor_exception,
586                                                              bool install_monitor_exception) {
587  Label Lunlocked, Lno_unlock;
588  {
589    Register Rdo_not_unlock_flag = R11_scratch1;
590    Register Raccess_flags       = R12_scratch2;
591
592    // Check if synchronized method or unlocking prevented by
593    // JavaThread::do_not_unlock_if_synchronized flag.
594    lbz(Rdo_not_unlock_flag, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
595    lwz(Raccess_flags, in_bytes(Method::access_flags_offset()), R19_method);
596    li(R0, 0);
597    stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread); // reset flag
598
599    push(state);
600
601    // Skip if we don't have to unlock.
602    rldicl_(R0, Raccess_flags, 64-JVM_ACC_SYNCHRONIZED_BIT, 63); // Extract bit and compare to 0.
603    beq(CCR0, Lunlocked);
604
605    cmpwi(CCR0, Rdo_not_unlock_flag, 0);
606    bne(CCR0, Lno_unlock);
607  }
608
609  // Unlock
610  {
611    Register Rmonitor_base = R11_scratch1;
612
613    Label Lunlock;
614    // If it's still locked, everything is ok, unlock it.
615    ld(Rmonitor_base, 0, R1_SP);
616    addi(Rmonitor_base, Rmonitor_base,
617         -(frame::ijava_state_size + frame::interpreter_frame_monitor_size_in_bytes())); // Monitor base
618
619    ld(R0, BasicObjectLock::obj_offset_in_bytes(), Rmonitor_base);
620    cmpdi(CCR0, R0, 0);
621    bne(CCR0, Lunlock);
622
623    // If it's already unlocked, throw exception.
624    if (throw_monitor_exception) {
625      call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
626      should_not_reach_here();
627    } else {
628      if (install_monitor_exception) {
629        call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
630        b(Lunlocked);
631      }
632    }
633
634    bind(Lunlock);
635    unlock_object(Rmonitor_base);
636  }
637
638  // Check that all other monitors are unlocked. Throw IllegelMonitorState exception if not.
639  bind(Lunlocked);
640  {
641    Label Lexception, Lrestart;
642    Register Rcurrent_obj_addr = R11_scratch1;
643    const int delta = frame::interpreter_frame_monitor_size_in_bytes();
644    assert((delta & LongAlignmentMask) == 0, "sizeof BasicObjectLock must be even number of doublewords");
645
646    bind(Lrestart);
647    // Set up search loop: Calc num of iterations.
648    {
649      Register Riterations = R12_scratch2;
650      Register Rmonitor_base = Rcurrent_obj_addr;
651      ld(Rmonitor_base, 0, R1_SP);
652      addi(Rmonitor_base, Rmonitor_base, - frame::ijava_state_size);  // Monitor base
653
654      subf_(Riterations, R26_monitor, Rmonitor_base);
655      ble(CCR0, Lno_unlock);
656
657      addi(Rcurrent_obj_addr, Rmonitor_base,
658           BasicObjectLock::obj_offset_in_bytes() - frame::interpreter_frame_monitor_size_in_bytes());
659      // Check if any monitor is on stack, bail out if not
660      srdi(Riterations, Riterations, exact_log2(delta));
661      mtctr(Riterations);
662    }
663
664    // The search loop: Look for locked monitors.
665    {
666      const Register Rcurrent_obj = R0;
667      Label Lloop;
668
669      ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
670      addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
671      bind(Lloop);
672
673      // Check if current entry is used.
674      cmpdi(CCR0, Rcurrent_obj, 0);
675      bne(CCR0, Lexception);
676      // Preload next iteration's compare value.
677      ld(Rcurrent_obj, 0, Rcurrent_obj_addr);
678      addi(Rcurrent_obj_addr, Rcurrent_obj_addr, -delta);
679      bdnz(Lloop);
680    }
681    // Fell through: Everything's unlocked => finish.
682    b(Lno_unlock);
683
684    // An object is still locked => need to throw exception.
685    bind(Lexception);
686    if (throw_monitor_exception) {
687      call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_illegal_monitor_state_exception));
688      should_not_reach_here();
689    } else {
690      // Stack unrolling. Unlock object and if requested, install illegal_monitor_exception.
691      // Unlock does not block, so don't have to worry about the frame.
692      Register Rmonitor_addr = R11_scratch1;
693      addi(Rmonitor_addr, Rcurrent_obj_addr, -BasicObjectLock::obj_offset_in_bytes() + delta);
694      unlock_object(Rmonitor_addr);
695      if (install_monitor_exception) {
696        call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::new_illegal_monitor_state_exception));
697      }
698      b(Lrestart);
699    }
700  }
701
702  align(32, 12);
703  bind(Lno_unlock);
704  pop(state);
705}
706
707// Support function for remove_activation & Co.
708void InterpreterMacroAssembler::merge_frames(Register Rsender_sp, Register return_pc,
709                                             Register Rscratch1, Register Rscratch2) {
710  // Pop interpreter frame.
711  ld(Rscratch1, 0, R1_SP); // *SP
712  ld(Rsender_sp, _ijava_state_neg(sender_sp), Rscratch1); // top_frame_sp
713  ld(Rscratch2, 0, Rscratch1); // **SP
714#ifdef ASSERT
715  {
716    Label Lok;
717    ld(R0, _ijava_state_neg(ijava_reserved), Rscratch1);
718    cmpdi(CCR0, R0, 0x5afe);
719    beq(CCR0, Lok);
720    stop("frame corrupted (remove activation)", 0x5afe);
721    bind(Lok);
722  }
723#endif
724  if (return_pc!=noreg) {
725    ld(return_pc, _abi(lr), Rscratch1); // LR
726  }
727
728  // Merge top frames.
729  subf(Rscratch1, R1_SP, Rsender_sp); // top_frame_sp - SP
730  stdux(Rscratch2, R1_SP, Rscratch1); // atomically set *(SP = top_frame_sp) = **SP
731}
732
733void InterpreterMacroAssembler::narrow(Register result) {
734  Register ret_type = R11_scratch1;
735  ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
736  lbz(ret_type, in_bytes(ConstMethod::result_type_offset()), R11_scratch1);
737
738  Label notBool, notByte, notChar, done;
739
740  // common case first
741  cmpwi(CCR0, ret_type, T_INT);
742  beq(CCR0, done);
743
744  cmpwi(CCR0, ret_type, T_BOOLEAN);
745  bne(CCR0, notBool);
746  andi(result, result, 0x1);
747  b(done);
748
749  bind(notBool);
750  cmpwi(CCR0, ret_type, T_BYTE);
751  bne(CCR0, notByte);
752  extsb(result, result);
753  b(done);
754
755  bind(notByte);
756  cmpwi(CCR0, ret_type, T_CHAR);
757  bne(CCR0, notChar);
758  andi(result, result, 0xffff);
759  b(done);
760
761  bind(notChar);
762  // cmpwi(CCR0, ret_type, T_SHORT);  // all that's left
763  // bne(CCR0, done);
764  extsh(result, result);
765
766  // Nothing to do for T_INT
767  bind(done);
768}
769
770// Remove activation.
771//
772// Unlock the receiver if this is a synchronized method.
773// Unlock any Java monitors from synchronized blocks.
774// Remove the activation from the stack.
775//
776// If there are locked Java monitors
777//    If throw_monitor_exception
778//       throws IllegalMonitorStateException
779//    Else if install_monitor_exception
780//       installs IllegalMonitorStateException
781//    Else
782//       no error processing
783void InterpreterMacroAssembler::remove_activation(TosState state,
784                                                  bool throw_monitor_exception,
785                                                  bool install_monitor_exception) {
786  BLOCK_COMMENT("remove_activation {");
787  unlock_if_synchronized_method(state, throw_monitor_exception, install_monitor_exception);
788
789  // Save result (push state before jvmti call and pop it afterwards) and notify jvmti.
790  notify_method_exit(false, state, NotifyJVMTI, true);
791
792  BLOCK_COMMENT("reserved_stack_check:");
793  if (StackReservedPages > 0) {
794    // Test if reserved zone needs to be enabled.
795    Label no_reserved_zone_enabling;
796
797    // Compare frame pointers. There is no good stack pointer, as with stack
798    // frame compression we can get different SPs when we do calls. A subsequent
799    // call could have a smaller SP, so that this compare succeeds for an
800    // inner call of the method annotated with ReservedStack.
801    ld_ptr(R0, JavaThread::reserved_stack_activation_offset(), R16_thread);
802    ld_ptr(R11_scratch1, _abi(callers_sp), R1_SP); // Load frame pointer.
803    cmpld(CCR0, R11_scratch1, R0);
804    blt_predict_taken(CCR0, no_reserved_zone_enabling);
805
806    // Enable reserved zone again, throw stack overflow exception.
807    call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), R16_thread);
808    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_delayed_StackOverflowError));
809
810    should_not_reach_here();
811
812    bind(no_reserved_zone_enabling);
813  }
814
815  verify_oop(R17_tos, state);
816  verify_thread();
817
818  merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
819  mtlr(R0);
820  BLOCK_COMMENT("} remove_activation");
821}
822
823// Lock object
824//
825// Registers alive
826//   monitor - Address of the BasicObjectLock to be used for locking,
827//             which must be initialized with the object to lock.
828//   object  - Address of the object to be locked.
829//
830void InterpreterMacroAssembler::lock_object(Register monitor, Register object) {
831  if (UseHeavyMonitors) {
832    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
833            monitor, /*check_for_exceptions=*/true);
834  } else {
835    // template code:
836    //
837    // markOop displaced_header = obj->mark().set_unlocked();
838    // monitor->lock()->set_displaced_header(displaced_header);
839    // if (Atomic::cmpxchg_ptr(/*ex=*/monitor, /*addr*/obj->mark_addr(), /*cmp*/displaced_header) == displaced_header) {
840    //   // We stored the monitor address into the object's mark word.
841    // } else if (THREAD->is_lock_owned((address)displaced_header))
842    //   // Simple recursive case.
843    //   monitor->lock()->set_displaced_header(NULL);
844    // } else {
845    //   // Slow path.
846    //   InterpreterRuntime::monitorenter(THREAD, monitor);
847    // }
848
849    const Register displaced_header = R7_ARG5;
850    const Register object_mark_addr = R8_ARG6;
851    const Register current_header   = R9_ARG7;
852    const Register tmp              = R10_ARG8;
853
854    Label done;
855    Label cas_failed, slow_case;
856
857    assert_different_registers(displaced_header, object_mark_addr, current_header, tmp);
858
859    // markOop displaced_header = obj->mark().set_unlocked();
860
861    // Load markOop from object into displaced_header.
862    ld(displaced_header, oopDesc::mark_offset_in_bytes(), object);
863
864    if (UseBiasedLocking) {
865      biased_locking_enter(CCR0, object, displaced_header, tmp, current_header, done, &slow_case);
866    }
867
868    // Set displaced_header to be (markOop of object | UNLOCK_VALUE).
869    ori(displaced_header, displaced_header, markOopDesc::unlocked_value);
870
871    // monitor->lock()->set_displaced_header(displaced_header);
872
873    // Initialize the box (Must happen before we update the object mark!).
874    std(displaced_header, BasicObjectLock::lock_offset_in_bytes() +
875        BasicLock::displaced_header_offset_in_bytes(), monitor);
876
877    // if (Atomic::cmpxchg_ptr(/*ex=*/monitor, /*addr*/obj->mark_addr(), /*cmp*/displaced_header) == displaced_header) {
878
879    // Store stack address of the BasicObjectLock (this is monitor) into object.
880    addi(object_mark_addr, object, oopDesc::mark_offset_in_bytes());
881
882    // Must fence, otherwise, preceding store(s) may float below cmpxchg.
883    // CmpxchgX sets CCR0 to cmpX(current, displaced).
884    cmpxchgd(/*flag=*/CCR0,
885             /*current_value=*/current_header,
886             /*compare_value=*/displaced_header, /*exchange_value=*/monitor,
887             /*where=*/object_mark_addr,
888             MacroAssembler::MemBarRel | MacroAssembler::MemBarAcq,
889             MacroAssembler::cmpxchgx_hint_acquire_lock(),
890             noreg,
891             &cas_failed,
892             /*check without membar and ldarx first*/true);
893
894    // If the compare-and-exchange succeeded, then we found an unlocked
895    // object and we have now locked it.
896    b(done);
897    bind(cas_failed);
898
899    // } else if (THREAD->is_lock_owned((address)displaced_header))
900    //   // Simple recursive case.
901    //   monitor->lock()->set_displaced_header(NULL);
902
903    // We did not see an unlocked object so try the fast recursive case.
904
905    // Check if owner is self by comparing the value in the markOop of object
906    // (current_header) with the stack pointer.
907    sub(current_header, current_header, R1_SP);
908
909    assert(os::vm_page_size() > 0xfff, "page size too small - change the constant");
910    load_const_optimized(tmp, ~(os::vm_page_size()-1) | markOopDesc::lock_mask_in_place);
911
912    and_(R0/*==0?*/, current_header, tmp);
913    // If condition is true we are done and hence we can store 0 in the displaced
914    // header indicating it is a recursive lock.
915    bne(CCR0, slow_case);
916    std(R0/*==0!*/, BasicObjectLock::lock_offset_in_bytes() +
917        BasicLock::displaced_header_offset_in_bytes(), monitor);
918    b(done);
919
920    // } else {
921    //   // Slow path.
922    //   InterpreterRuntime::monitorenter(THREAD, monitor);
923
924    // None of the above fast optimizations worked so we have to get into the
925    // slow case of monitor enter.
926    bind(slow_case);
927    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
928            monitor, /*check_for_exceptions=*/true);
929    // }
930    align(32, 12);
931    bind(done);
932  }
933}
934
935// Unlocks an object. Used in monitorexit bytecode and remove_activation.
936//
937// Registers alive
938//   monitor - Address of the BasicObjectLock to be used for locking,
939//             which must be initialized with the object to lock.
940//
941// Throw IllegalMonitorException if object is not locked by current thread.
942void InterpreterMacroAssembler::unlock_object(Register monitor, bool check_for_exceptions) {
943  if (UseHeavyMonitors) {
944    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit),
945            monitor, check_for_exceptions);
946  } else {
947
948    // template code:
949    //
950    // if ((displaced_header = monitor->displaced_header()) == NULL) {
951    //   // Recursive unlock. Mark the monitor unlocked by setting the object field to NULL.
952    //   monitor->set_obj(NULL);
953    // } else if (Atomic::cmpxchg_ptr(displaced_header, obj->mark_addr(), monitor) == monitor) {
954    //   // We swapped the unlocked mark in displaced_header into the object's mark word.
955    //   monitor->set_obj(NULL);
956    // } else {
957    //   // Slow path.
958    //   InterpreterRuntime::monitorexit(THREAD, monitor);
959    // }
960
961    const Register object           = R7_ARG5;
962    const Register displaced_header = R8_ARG6;
963    const Register object_mark_addr = R9_ARG7;
964    const Register current_header   = R10_ARG8;
965
966    Label free_slot;
967    Label slow_case;
968
969    assert_different_registers(object, displaced_header, object_mark_addr, current_header);
970
971    if (UseBiasedLocking) {
972      // The object address from the monitor is in object.
973      ld(object, BasicObjectLock::obj_offset_in_bytes(), monitor);
974      assert(oopDesc::mark_offset_in_bytes() == 0, "offset of _mark is not 0");
975      biased_locking_exit(CCR0, object, displaced_header, free_slot);
976    }
977
978    // Test first if we are in the fast recursive case.
979    ld(displaced_header, BasicObjectLock::lock_offset_in_bytes() +
980           BasicLock::displaced_header_offset_in_bytes(), monitor);
981
982    // If the displaced header is zero, we have a recursive unlock.
983    cmpdi(CCR0, displaced_header, 0);
984    beq(CCR0, free_slot); // recursive unlock
985
986    // } else if (Atomic::cmpxchg_ptr(displaced_header, obj->mark_addr(), monitor) == monitor) {
987    //   // We swapped the unlocked mark in displaced_header into the object's mark word.
988    //   monitor->set_obj(NULL);
989
990    // If we still have a lightweight lock, unlock the object and be done.
991
992    // The object address from the monitor is in object.
993    if (!UseBiasedLocking) { ld(object, BasicObjectLock::obj_offset_in_bytes(), monitor); }
994    addi(object_mark_addr, object, oopDesc::mark_offset_in_bytes());
995
996    // We have the displaced header in displaced_header. If the lock is still
997    // lightweight, it will contain the monitor address and we'll store the
998    // displaced header back into the object's mark word.
999    // CmpxchgX sets CCR0 to cmpX(current, monitor).
1000    cmpxchgd(/*flag=*/CCR0,
1001             /*current_value=*/current_header,
1002             /*compare_value=*/monitor, /*exchange_value=*/displaced_header,
1003             /*where=*/object_mark_addr,
1004             MacroAssembler::MemBarRel,
1005             MacroAssembler::cmpxchgx_hint_release_lock(),
1006             noreg,
1007             &slow_case);
1008    b(free_slot);
1009
1010    // } else {
1011    //   // Slow path.
1012    //   InterpreterRuntime::monitorexit(THREAD, monitor);
1013
1014    // The lock has been converted into a heavy lock and hence
1015    // we need to get into the slow case.
1016    bind(slow_case);
1017    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit),
1018            monitor, check_for_exceptions);
1019    // }
1020
1021    Label done;
1022    b(done); // Monitor register may be overwritten! Runtime has already freed the slot.
1023
1024    // Exchange worked, do monitor->set_obj(NULL);
1025    align(32, 12);
1026    bind(free_slot);
1027    li(R0, 0);
1028    std(R0, BasicObjectLock::obj_offset_in_bytes(), monitor);
1029    bind(done);
1030  }
1031}
1032
1033// Load compiled (i2c) or interpreter entry when calling from interpreted and
1034// do the call. Centralized so that all interpreter calls will do the same actions.
1035// If jvmti single stepping is on for a thread we must not call compiled code.
1036//
1037// Input:
1038//   - Rtarget_method: method to call
1039//   - Rret_addr:      return address
1040//   - 2 scratch regs
1041//
1042void InterpreterMacroAssembler::call_from_interpreter(Register Rtarget_method, Register Rret_addr,
1043                                                      Register Rscratch1, Register Rscratch2) {
1044  assert_different_registers(Rscratch1, Rscratch2, Rtarget_method, Rret_addr);
1045  // Assume we want to go compiled if available.
1046  const Register Rtarget_addr = Rscratch1;
1047  const Register Rinterp_only = Rscratch2;
1048
1049  ld(Rtarget_addr, in_bytes(Method::from_interpreted_offset()), Rtarget_method);
1050
1051  if (JvmtiExport::can_post_interpreter_events()) {
1052    lwz(Rinterp_only, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
1053
1054    // JVMTI events, such as single-stepping, are implemented partly by avoiding running
1055    // compiled code in threads for which the event is enabled. Check here for
1056    // interp_only_mode if these events CAN be enabled.
1057    Label done;
1058    verify_thread();
1059    cmpwi(CCR0, Rinterp_only, 0);
1060    beq(CCR0, done);
1061    ld(Rtarget_addr, in_bytes(Method::interpreter_entry_offset()), Rtarget_method);
1062    align(32, 12);
1063    bind(done);
1064  }
1065
1066#ifdef ASSERT
1067  {
1068    Label Lok;
1069    cmpdi(CCR0, Rtarget_addr, 0);
1070    bne(CCR0, Lok);
1071    stop("null entry point");
1072    bind(Lok);
1073  }
1074#endif // ASSERT
1075
1076  mr(R21_sender_SP, R1_SP);
1077
1078  // Calc a precise SP for the call. The SP value we calculated in
1079  // generate_fixed_frame() is based on the max_stack() value, so we would waste stack space
1080  // if esp is not max. Also, the i2c adapter extends the stack space without restoring
1081  // our pre-calced value, so repeating calls via i2c would result in stack overflow.
1082  // Since esp already points to an empty slot, we just have to sub 1 additional slot
1083  // to meet the abi scratch requirements.
1084  // The max_stack pointer will get restored by means of the GR_Lmax_stack local in
1085  // the return entry of the interpreter.
1086  addi(Rscratch2, R15_esp, Interpreter::stackElementSize - frame::abi_reg_args_size);
1087  clrrdi(Rscratch2, Rscratch2, exact_log2(frame::alignment_in_bytes)); // round towards smaller address
1088  resize_frame_absolute(Rscratch2, Rscratch2, R0);
1089
1090  mr_if_needed(R19_method, Rtarget_method);
1091  mtctr(Rtarget_addr);
1092  mtlr(Rret_addr);
1093
1094  save_interpreter_state(Rscratch2);
1095#ifdef ASSERT
1096  ld(Rscratch1, _ijava_state_neg(top_frame_sp), Rscratch2); // Rscratch2 contains fp
1097  cmpd(CCR0, R21_sender_SP, Rscratch1);
1098  asm_assert_eq("top_frame_sp incorrect", 0x951);
1099#endif
1100
1101  bctr();
1102}
1103
1104// Set the method data pointer for the current bcp.
1105void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1106  assert(ProfileInterpreter, "must be profiling interpreter");
1107  Label get_continue;
1108  ld(R28_mdx, in_bytes(Method::method_data_offset()), R19_method);
1109  test_method_data_pointer(get_continue);
1110  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), R19_method, R14_bcp);
1111
1112  addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
1113  add(R28_mdx, R28_mdx, R3_RET);
1114  bind(get_continue);
1115}
1116
1117// Test ImethodDataPtr. If it is null, continue at the specified label.
1118void InterpreterMacroAssembler::test_method_data_pointer(Label& zero_continue) {
1119  assert(ProfileInterpreter, "must be profiling interpreter");
1120  cmpdi(CCR0, R28_mdx, 0);
1121  beq(CCR0, zero_continue);
1122}
1123
1124void InterpreterMacroAssembler::verify_method_data_pointer() {
1125  assert(ProfileInterpreter, "must be profiling interpreter");
1126#ifdef ASSERT
1127  Label verify_continue;
1128  test_method_data_pointer(verify_continue);
1129
1130  // If the mdp is valid, it will point to a DataLayout header which is
1131  // consistent with the bcp. The converse is highly probable also.
1132  lhz(R11_scratch1, in_bytes(DataLayout::bci_offset()), R28_mdx);
1133  ld(R12_scratch2, in_bytes(Method::const_offset()), R19_method);
1134  addi(R11_scratch1, R11_scratch1, in_bytes(ConstMethod::codes_offset()));
1135  add(R11_scratch1, R12_scratch2, R12_scratch2);
1136  cmpd(CCR0, R11_scratch1, R14_bcp);
1137  beq(CCR0, verify_continue);
1138
1139  call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp ), R19_method, R14_bcp, R28_mdx);
1140
1141  bind(verify_continue);
1142#endif
1143}
1144
1145void InterpreterMacroAssembler::test_invocation_counter_for_mdp(Register invocation_count,
1146                                                                Register method_counters,
1147                                                                Register Rscratch,
1148                                                                Label &profile_continue) {
1149  assert(ProfileInterpreter, "must be profiling interpreter");
1150  // Control will flow to "profile_continue" if the counter is less than the
1151  // limit or if we call profile_method().
1152  Label done;
1153
1154  // If no method data exists, and the counter is high enough, make one.
1155  lwz(Rscratch, in_bytes(MethodCounters::interpreter_profile_limit_offset()), method_counters);
1156
1157  cmpdi(CCR0, R28_mdx, 0);
1158  // Test to see if we should create a method data oop.
1159  cmpd(CCR1, Rscratch, invocation_count);
1160  bne(CCR0, done);
1161  bge(CCR1, profile_continue);
1162
1163  // Build it now.
1164  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1165  set_method_data_pointer_for_bcp();
1166  b(profile_continue);
1167
1168  align(32, 12);
1169  bind(done);
1170}
1171
1172void InterpreterMacroAssembler::test_backedge_count_for_osr(Register backedge_count, Register method_counters,
1173                                                            Register target_bcp, Register disp, Register Rtmp) {
1174  assert_different_registers(backedge_count, target_bcp, disp, Rtmp, R4_ARG2);
1175  assert(UseOnStackReplacement,"Must UseOnStackReplacement to test_backedge_count_for_osr");
1176
1177  Label did_not_overflow;
1178  Label overflow_with_error;
1179
1180  lwz(Rtmp, in_bytes(MethodCounters::interpreter_backward_branch_limit_offset()), method_counters);
1181  cmpw(CCR0, backedge_count, Rtmp);
1182
1183  blt(CCR0, did_not_overflow);
1184
1185  // When ProfileInterpreter is on, the backedge_count comes from the
1186  // methodDataOop, which value does not get reset on the call to
1187  // frequency_counter_overflow(). To avoid excessive calls to the overflow
1188  // routine while the method is being compiled, add a second test to make sure
1189  // the overflow function is called only once every overflow_frequency.
1190  if (ProfileInterpreter) {
1191    const int overflow_frequency = 1024;
1192    andi_(Rtmp, backedge_count, overflow_frequency-1);
1193    bne(CCR0, did_not_overflow);
1194  }
1195
1196  // Overflow in loop, pass branch bytecode.
1197  subf(R4_ARG2, disp, target_bcp); // Compute branch bytecode (previous bcp).
1198  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
1199
1200  // Was an OSR adapter generated?
1201  cmpdi(CCR0, R3_RET, 0);
1202  beq(CCR0, overflow_with_error);
1203
1204  // Has the nmethod been invalidated already?
1205  lbz(Rtmp, nmethod::state_offset(), R3_RET);
1206  cmpwi(CCR0, Rtmp, nmethod::in_use);
1207  bne(CCR0, overflow_with_error);
1208
1209  // Migrate the interpreter frame off of the stack.
1210  // We can use all registers because we will not return to interpreter from this point.
1211
1212  // Save nmethod.
1213  const Register osr_nmethod = R31;
1214  mr(osr_nmethod, R3_RET);
1215  set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R11_scratch1);
1216  call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::OSR_migration_begin), R16_thread);
1217  reset_last_Java_frame();
1218  // OSR buffer is in ARG1
1219
1220  // Remove the interpreter frame.
1221  merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
1222
1223  // Jump to the osr code.
1224  ld(R11_scratch1, nmethod::osr_entry_point_offset(), osr_nmethod);
1225  mtlr(R0);
1226  mtctr(R11_scratch1);
1227  bctr();
1228
1229  align(32, 12);
1230  bind(overflow_with_error);
1231  bind(did_not_overflow);
1232}
1233
1234// Store a value at some constant offset from the method data pointer.
1235void InterpreterMacroAssembler::set_mdp_data_at(int constant, Register value) {
1236  assert(ProfileInterpreter, "must be profiling interpreter");
1237
1238  std(value, constant, R28_mdx);
1239}
1240
1241// Increment the value at some constant offset from the method data pointer.
1242void InterpreterMacroAssembler::increment_mdp_data_at(int constant,
1243                                                      Register counter_addr,
1244                                                      Register Rbumped_count,
1245                                                      bool decrement) {
1246  // Locate the counter at a fixed offset from the mdp:
1247  addi(counter_addr, R28_mdx, constant);
1248  increment_mdp_data_at(counter_addr, Rbumped_count, decrement);
1249}
1250
1251// Increment the value at some non-fixed (reg + constant) offset from
1252// the method data pointer.
1253void InterpreterMacroAssembler::increment_mdp_data_at(Register reg,
1254                                                      int constant,
1255                                                      Register scratch,
1256                                                      Register Rbumped_count,
1257                                                      bool decrement) {
1258  // Add the constant to reg to get the offset.
1259  add(scratch, R28_mdx, reg);
1260  // Then calculate the counter address.
1261  addi(scratch, scratch, constant);
1262  increment_mdp_data_at(scratch, Rbumped_count, decrement);
1263}
1264
1265void InterpreterMacroAssembler::increment_mdp_data_at(Register counter_addr,
1266                                                      Register Rbumped_count,
1267                                                      bool decrement) {
1268  assert(ProfileInterpreter, "must be profiling interpreter");
1269
1270  // Load the counter.
1271  ld(Rbumped_count, 0, counter_addr);
1272
1273  if (decrement) {
1274    // Decrement the register. Set condition codes.
1275    addi(Rbumped_count, Rbumped_count, - DataLayout::counter_increment);
1276    // Store the decremented counter, if it is still negative.
1277    std(Rbumped_count, 0, counter_addr);
1278    // Note: add/sub overflow check are not ported, since 64 bit
1279    // calculation should never overflow.
1280  } else {
1281    // Increment the register. Set carry flag.
1282    addi(Rbumped_count, Rbumped_count, DataLayout::counter_increment);
1283    // Store the incremented counter.
1284    std(Rbumped_count, 0, counter_addr);
1285  }
1286}
1287
1288// Set a flag value at the current method data pointer position.
1289void InterpreterMacroAssembler::set_mdp_flag_at(int flag_constant,
1290                                                Register scratch) {
1291  assert(ProfileInterpreter, "must be profiling interpreter");
1292  // Load the data header.
1293  lbz(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
1294  // Set the flag.
1295  ori(scratch, scratch, flag_constant);
1296  // Store the modified header.
1297  stb(scratch, in_bytes(DataLayout::flags_offset()), R28_mdx);
1298}
1299
1300// Test the location at some offset from the method data pointer.
1301// If it is not equal to value, branch to the not_equal_continue Label.
1302void InterpreterMacroAssembler::test_mdp_data_at(int offset,
1303                                                 Register value,
1304                                                 Label& not_equal_continue,
1305                                                 Register test_out) {
1306  assert(ProfileInterpreter, "must be profiling interpreter");
1307
1308  ld(test_out, offset, R28_mdx);
1309  cmpd(CCR0,  value, test_out);
1310  bne(CCR0, not_equal_continue);
1311}
1312
1313// Update the method data pointer by the displacement located at some fixed
1314// offset from the method data pointer.
1315void InterpreterMacroAssembler::update_mdp_by_offset(int offset_of_disp,
1316                                                     Register scratch) {
1317  assert(ProfileInterpreter, "must be profiling interpreter");
1318
1319  ld(scratch, offset_of_disp, R28_mdx);
1320  add(R28_mdx, scratch, R28_mdx);
1321}
1322
1323// Update the method data pointer by the displacement located at the
1324// offset (reg + offset_of_disp).
1325void InterpreterMacroAssembler::update_mdp_by_offset(Register reg,
1326                                                     int offset_of_disp,
1327                                                     Register scratch) {
1328  assert(ProfileInterpreter, "must be profiling interpreter");
1329
1330  add(scratch, reg, R28_mdx);
1331  ld(scratch, offset_of_disp, scratch);
1332  add(R28_mdx, scratch, R28_mdx);
1333}
1334
1335// Update the method data pointer by a simple constant displacement.
1336void InterpreterMacroAssembler::update_mdp_by_constant(int constant) {
1337  assert(ProfileInterpreter, "must be profiling interpreter");
1338  addi(R28_mdx, R28_mdx, constant);
1339}
1340
1341// Update the method data pointer for a _ret bytecode whose target
1342// was not among our cached targets.
1343void InterpreterMacroAssembler::update_mdp_for_ret(TosState state,
1344                                                   Register return_bci) {
1345  assert(ProfileInterpreter, "must be profiling interpreter");
1346
1347  push(state);
1348  assert(return_bci->is_nonvolatile(), "need to protect return_bci");
1349  call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret), return_bci);
1350  pop(state);
1351}
1352
1353// Increments the backedge counter.
1354// Returns backedge counter + invocation counter in Rdst.
1355void InterpreterMacroAssembler::increment_backedge_counter(const Register Rcounters, const Register Rdst,
1356                                                           const Register Rtmp1, Register Rscratch) {
1357  assert(UseCompiler, "incrementing must be useful");
1358  assert_different_registers(Rdst, Rtmp1);
1359  const Register invocation_counter = Rtmp1;
1360  const Register counter = Rdst;
1361  // TODO: PPC port: assert(4 == InvocationCounter::sz_counter(), "unexpected field size.");
1362
1363  // Load backedge counter.
1364  lwz(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
1365               in_bytes(InvocationCounter::counter_offset()), Rcounters);
1366  // Load invocation counter.
1367  lwz(invocation_counter, in_bytes(MethodCounters::invocation_counter_offset()) +
1368                          in_bytes(InvocationCounter::counter_offset()), Rcounters);
1369
1370  // Add the delta to the backedge counter.
1371  addi(counter, counter, InvocationCounter::count_increment);
1372
1373  // Mask the invocation counter.
1374  andi(invocation_counter, invocation_counter, InvocationCounter::count_mask_value);
1375
1376  // Store new counter value.
1377  stw(counter, in_bytes(MethodCounters::backedge_counter_offset()) +
1378               in_bytes(InvocationCounter::counter_offset()), Rcounters);
1379  // Return invocation counter + backedge counter.
1380  add(counter, counter, invocation_counter);
1381}
1382
1383// Count a taken branch in the bytecodes.
1384void InterpreterMacroAssembler::profile_taken_branch(Register scratch, Register bumped_count) {
1385  if (ProfileInterpreter) {
1386    Label profile_continue;
1387
1388    // If no method data exists, go to profile_continue.
1389    test_method_data_pointer(profile_continue);
1390
1391    // We are taking a branch. Increment the taken count.
1392    increment_mdp_data_at(in_bytes(JumpData::taken_offset()), scratch, bumped_count);
1393
1394    // The method data pointer needs to be updated to reflect the new target.
1395    update_mdp_by_offset(in_bytes(JumpData::displacement_offset()), scratch);
1396    bind (profile_continue);
1397  }
1398}
1399
1400// Count a not-taken branch in the bytecodes.
1401void InterpreterMacroAssembler::profile_not_taken_branch(Register scratch1, Register scratch2) {
1402  if (ProfileInterpreter) {
1403    Label profile_continue;
1404
1405    // If no method data exists, go to profile_continue.
1406    test_method_data_pointer(profile_continue);
1407
1408    // We are taking a branch. Increment the not taken count.
1409    increment_mdp_data_at(in_bytes(BranchData::not_taken_offset()), scratch1, scratch2);
1410
1411    // The method data pointer needs to be updated to correspond to the
1412    // next bytecode.
1413    update_mdp_by_constant(in_bytes(BranchData::branch_data_size()));
1414    bind (profile_continue);
1415  }
1416}
1417
1418// Count a non-virtual call in the bytecodes.
1419void InterpreterMacroAssembler::profile_call(Register scratch1, Register scratch2) {
1420  if (ProfileInterpreter) {
1421    Label profile_continue;
1422
1423    // If no method data exists, go to profile_continue.
1424    test_method_data_pointer(profile_continue);
1425
1426    // We are making a call. Increment the count.
1427    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1428
1429    // The method data pointer needs to be updated to reflect the new target.
1430    update_mdp_by_constant(in_bytes(CounterData::counter_data_size()));
1431    bind (profile_continue);
1432  }
1433}
1434
1435// Count a final call in the bytecodes.
1436void InterpreterMacroAssembler::profile_final_call(Register scratch1, Register scratch2) {
1437  if (ProfileInterpreter) {
1438    Label profile_continue;
1439
1440    // If no method data exists, go to profile_continue.
1441    test_method_data_pointer(profile_continue);
1442
1443    // We are making a call. Increment the count.
1444    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1445
1446    // The method data pointer needs to be updated to reflect the new target.
1447    update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
1448    bind (profile_continue);
1449  }
1450}
1451
1452// Count a virtual call in the bytecodes.
1453void InterpreterMacroAssembler::profile_virtual_call(Register Rreceiver,
1454                                                     Register Rscratch1,
1455                                                     Register Rscratch2,
1456                                                     bool receiver_can_be_null) {
1457  if (!ProfileInterpreter) { return; }
1458  Label profile_continue;
1459
1460  // If no method data exists, go to profile_continue.
1461  test_method_data_pointer(profile_continue);
1462
1463  Label skip_receiver_profile;
1464  if (receiver_can_be_null) {
1465    Label not_null;
1466    cmpdi(CCR0, Rreceiver, 0);
1467    bne(CCR0, not_null);
1468    // We are making a call. Increment the count for null receiver.
1469    increment_mdp_data_at(in_bytes(CounterData::count_offset()), Rscratch1, Rscratch2);
1470    b(skip_receiver_profile);
1471    bind(not_null);
1472  }
1473
1474  // Record the receiver type.
1475  record_klass_in_profile(Rreceiver, Rscratch1, Rscratch2, true);
1476  bind(skip_receiver_profile);
1477
1478  // The method data pointer needs to be updated to reflect the new target.
1479  update_mdp_by_constant(in_bytes(VirtualCallData::virtual_call_data_size()));
1480  bind (profile_continue);
1481}
1482
1483void InterpreterMacroAssembler::profile_typecheck(Register Rklass, Register Rscratch1, Register Rscratch2) {
1484  if (ProfileInterpreter) {
1485    Label profile_continue;
1486
1487    // If no method data exists, go to profile_continue.
1488    test_method_data_pointer(profile_continue);
1489
1490    int mdp_delta = in_bytes(BitData::bit_data_size());
1491    if (TypeProfileCasts) {
1492      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1493
1494      // Record the object type.
1495      record_klass_in_profile(Rklass, Rscratch1, Rscratch2, false);
1496    }
1497
1498    // The method data pointer needs to be updated.
1499    update_mdp_by_constant(mdp_delta);
1500
1501    bind (profile_continue);
1502  }
1503}
1504
1505void InterpreterMacroAssembler::profile_typecheck_failed(Register Rscratch1, Register Rscratch2) {
1506  if (ProfileInterpreter && TypeProfileCasts) {
1507    Label profile_continue;
1508
1509    // If no method data exists, go to profile_continue.
1510    test_method_data_pointer(profile_continue);
1511
1512    int count_offset = in_bytes(CounterData::count_offset());
1513    // Back up the address, since we have already bumped the mdp.
1514    count_offset -= in_bytes(VirtualCallData::virtual_call_data_size());
1515
1516    // *Decrement* the counter. We expect to see zero or small negatives.
1517    increment_mdp_data_at(count_offset, Rscratch1, Rscratch2, true);
1518
1519    bind (profile_continue);
1520  }
1521}
1522
1523// Count a ret in the bytecodes.
1524void InterpreterMacroAssembler::profile_ret(TosState state, Register return_bci,
1525                                            Register scratch1, Register scratch2) {
1526  if (ProfileInterpreter) {
1527    Label profile_continue;
1528    uint row;
1529
1530    // If no method data exists, go to profile_continue.
1531    test_method_data_pointer(profile_continue);
1532
1533    // Update the total ret count.
1534    increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2 );
1535
1536    for (row = 0; row < RetData::row_limit(); row++) {
1537      Label next_test;
1538
1539      // See if return_bci is equal to bci[n]:
1540      test_mdp_data_at(in_bytes(RetData::bci_offset(row)), return_bci, next_test, scratch1);
1541
1542      // return_bci is equal to bci[n]. Increment the count.
1543      increment_mdp_data_at(in_bytes(RetData::bci_count_offset(row)), scratch1, scratch2);
1544
1545      // The method data pointer needs to be updated to reflect the new target.
1546      update_mdp_by_offset(in_bytes(RetData::bci_displacement_offset(row)), scratch1);
1547      b(profile_continue);
1548      bind(next_test);
1549    }
1550
1551    update_mdp_for_ret(state, return_bci);
1552
1553    bind (profile_continue);
1554  }
1555}
1556
1557// Count the default case of a switch construct.
1558void InterpreterMacroAssembler::profile_switch_default(Register scratch1,  Register scratch2) {
1559  if (ProfileInterpreter) {
1560    Label profile_continue;
1561
1562    // If no method data exists, go to profile_continue.
1563    test_method_data_pointer(profile_continue);
1564
1565    // Update the default case count
1566    increment_mdp_data_at(in_bytes(MultiBranchData::default_count_offset()),
1567                          scratch1, scratch2);
1568
1569    // The method data pointer needs to be updated.
1570    update_mdp_by_offset(in_bytes(MultiBranchData::default_displacement_offset()),
1571                         scratch1);
1572
1573    bind (profile_continue);
1574  }
1575}
1576
1577// Count the index'th case of a switch construct.
1578void InterpreterMacroAssembler::profile_switch_case(Register index,
1579                                                    Register scratch1,
1580                                                    Register scratch2,
1581                                                    Register scratch3) {
1582  if (ProfileInterpreter) {
1583    assert_different_registers(index, scratch1, scratch2, scratch3);
1584    Label profile_continue;
1585
1586    // If no method data exists, go to profile_continue.
1587    test_method_data_pointer(profile_continue);
1588
1589    // Build the base (index * per_case_size_in_bytes()) + case_array_offset_in_bytes().
1590    li(scratch3, in_bytes(MultiBranchData::case_array_offset()));
1591
1592    assert (in_bytes(MultiBranchData::per_case_size()) == 16, "so that shladd works");
1593    sldi(scratch1, index, exact_log2(in_bytes(MultiBranchData::per_case_size())));
1594    add(scratch1, scratch1, scratch3);
1595
1596    // Update the case count.
1597    increment_mdp_data_at(scratch1, in_bytes(MultiBranchData::relative_count_offset()), scratch2, scratch3);
1598
1599    // The method data pointer needs to be updated.
1600    update_mdp_by_offset(scratch1, in_bytes(MultiBranchData::relative_displacement_offset()), scratch2);
1601
1602    bind (profile_continue);
1603  }
1604}
1605
1606void InterpreterMacroAssembler::profile_null_seen(Register Rscratch1, Register Rscratch2) {
1607  if (ProfileInterpreter) {
1608    assert_different_registers(Rscratch1, Rscratch2);
1609    Label profile_continue;
1610
1611    // If no method data exists, go to profile_continue.
1612    test_method_data_pointer(profile_continue);
1613
1614    set_mdp_flag_at(BitData::null_seen_byte_constant(), Rscratch1);
1615
1616    // The method data pointer needs to be updated.
1617    int mdp_delta = in_bytes(BitData::bit_data_size());
1618    if (TypeProfileCasts) {
1619      mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1620    }
1621    update_mdp_by_constant(mdp_delta);
1622
1623    bind (profile_continue);
1624  }
1625}
1626
1627void InterpreterMacroAssembler::record_klass_in_profile(Register Rreceiver,
1628                                                        Register Rscratch1, Register Rscratch2,
1629                                                        bool is_virtual_call) {
1630  assert(ProfileInterpreter, "must be profiling");
1631  assert_different_registers(Rreceiver, Rscratch1, Rscratch2);
1632
1633  Label done;
1634  record_klass_in_profile_helper(Rreceiver, Rscratch1, Rscratch2, 0, done, is_virtual_call);
1635  bind (done);
1636}
1637
1638void InterpreterMacroAssembler::record_klass_in_profile_helper(
1639                                        Register receiver, Register scratch1, Register scratch2,
1640                                        int start_row, Label& done, bool is_virtual_call) {
1641  if (TypeProfileWidth == 0) {
1642    if (is_virtual_call) {
1643      increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1644    }
1645    return;
1646  }
1647
1648  int last_row = VirtualCallData::row_limit() - 1;
1649  assert(start_row <= last_row, "must be work left to do");
1650  // Test this row for both the receiver and for null.
1651  // Take any of three different outcomes:
1652  //   1. found receiver => increment count and goto done
1653  //   2. found null => keep looking for case 1, maybe allocate this cell
1654  //   3. found something else => keep looking for cases 1 and 2
1655  // Case 3 is handled by a recursive call.
1656  for (int row = start_row; row <= last_row; row++) {
1657    Label next_test;
1658    bool test_for_null_also = (row == start_row);
1659
1660    // See if the receiver is receiver[n].
1661    int recvr_offset = in_bytes(VirtualCallData::receiver_offset(row));
1662    test_mdp_data_at(recvr_offset, receiver, next_test, scratch1);
1663    // delayed()->tst(scratch);
1664
1665    // The receiver is receiver[n]. Increment count[n].
1666    int count_offset = in_bytes(VirtualCallData::receiver_count_offset(row));
1667    increment_mdp_data_at(count_offset, scratch1, scratch2);
1668    b(done);
1669    bind(next_test);
1670
1671    if (test_for_null_also) {
1672      Label found_null;
1673      // Failed the equality check on receiver[n]... Test for null.
1674      if (start_row == last_row) {
1675        // The only thing left to do is handle the null case.
1676        if (is_virtual_call) {
1677          // Scratch1 contains test_out from test_mdp_data_at.
1678          cmpdi(CCR0, scratch1, 0);
1679          beq(CCR0, found_null);
1680          // Receiver did not match any saved receiver and there is no empty row for it.
1681          // Increment total counter to indicate polymorphic case.
1682          increment_mdp_data_at(in_bytes(CounterData::count_offset()), scratch1, scratch2);
1683          b(done);
1684          bind(found_null);
1685        } else {
1686          cmpdi(CCR0, scratch1, 0);
1687          bne(CCR0, done);
1688        }
1689        break;
1690      }
1691      // Since null is rare, make it be the branch-taken case.
1692      cmpdi(CCR0, scratch1, 0);
1693      beq(CCR0, found_null);
1694
1695      // Put all the "Case 3" tests here.
1696      record_klass_in_profile_helper(receiver, scratch1, scratch2, start_row + 1, done, is_virtual_call);
1697
1698      // Found a null. Keep searching for a matching receiver,
1699      // but remember that this is an empty (unused) slot.
1700      bind(found_null);
1701    }
1702  }
1703
1704  // In the fall-through case, we found no matching receiver, but we
1705  // observed the receiver[start_row] is NULL.
1706
1707  // Fill in the receiver field and increment the count.
1708  int recvr_offset = in_bytes(VirtualCallData::receiver_offset(start_row));
1709  set_mdp_data_at(recvr_offset, receiver);
1710  int count_offset = in_bytes(VirtualCallData::receiver_count_offset(start_row));
1711  li(scratch1, DataLayout::counter_increment);
1712  set_mdp_data_at(count_offset, scratch1);
1713  if (start_row > 0) {
1714    b(done);
1715  }
1716}
1717
1718// Argument and return type profilig.
1719// kills: tmp, tmp2, R0, CR0, CR1
1720void InterpreterMacroAssembler::profile_obj_type(Register obj, Register mdo_addr_base,
1721                                                 RegisterOrConstant mdo_addr_offs,
1722                                                 Register tmp, Register tmp2) {
1723  Label do_nothing, do_update;
1724
1725  // tmp2 = obj is allowed
1726  assert_different_registers(obj, mdo_addr_base, tmp, R0);
1727  assert_different_registers(tmp2, mdo_addr_base, tmp, R0);
1728  const Register klass = tmp2;
1729
1730  verify_oop(obj);
1731
1732  ld(tmp, mdo_addr_offs, mdo_addr_base);
1733
1734  // Set null_seen if obj is 0.
1735  cmpdi(CCR0, obj, 0);
1736  ori(R0, tmp, TypeEntries::null_seen);
1737  beq(CCR0, do_update);
1738
1739  load_klass(klass, obj);
1740
1741  clrrdi(R0, tmp, exact_log2(-TypeEntries::type_klass_mask));
1742  // Basically same as andi(R0, tmp, TypeEntries::type_klass_mask);
1743  cmpd(CCR1, R0, klass);
1744  // Klass seen before, nothing to do (regardless of unknown bit).
1745  //beq(CCR1, do_nothing);
1746
1747  andi_(R0, klass, TypeEntries::type_unknown);
1748  // Already unknown. Nothing to do anymore.
1749  //bne(CCR0, do_nothing);
1750  crorc(CCR0, Assembler::equal, CCR1, Assembler::equal); // cr0 eq = cr1 eq or cr0 ne
1751  beq(CCR0, do_nothing);
1752
1753  clrrdi_(R0, tmp, exact_log2(-TypeEntries::type_mask));
1754  orr(R0, klass, tmp); // Combine klass and null_seen bit (only used if (tmp & type_mask)==0).
1755  beq(CCR0, do_update); // First time here. Set profile type.
1756
1757  // Different than before. Cannot keep accurate profile.
1758  ori(R0, tmp, TypeEntries::type_unknown);
1759
1760  bind(do_update);
1761  // update profile
1762  std(R0, mdo_addr_offs, mdo_addr_base);
1763
1764  align(32, 12);
1765  bind(do_nothing);
1766}
1767
1768void InterpreterMacroAssembler::profile_arguments_type(Register callee,
1769                                                       Register tmp1, Register tmp2,
1770                                                       bool is_virtual) {
1771  if (!ProfileInterpreter) {
1772    return;
1773  }
1774
1775  assert_different_registers(callee, tmp1, tmp2, R28_mdx);
1776
1777  if (MethodData::profile_arguments() || MethodData::profile_return()) {
1778    Label profile_continue;
1779
1780    test_method_data_pointer(profile_continue);
1781
1782    int off_to_start = is_virtual ?
1783      in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
1784
1785    lbz(tmp1, in_bytes(DataLayout::tag_offset()) - off_to_start, R28_mdx);
1786    cmpwi(CCR0, tmp1, is_virtual ? DataLayout::virtual_call_type_data_tag : DataLayout::call_type_data_tag);
1787    bne(CCR0, profile_continue);
1788
1789    if (MethodData::profile_arguments()) {
1790      Label done;
1791      int off_to_args = in_bytes(TypeEntriesAtCall::args_data_offset());
1792      add(R28_mdx, off_to_args, R28_mdx);
1793
1794      for (int i = 0; i < TypeProfileArgsLimit; i++) {
1795        if (i > 0 || MethodData::profile_return()) {
1796          // If return value type is profiled we may have no argument to profile.
1797          ld(tmp1, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, R28_mdx);
1798          cmpdi(CCR0, tmp1, (i+1)*TypeStackSlotEntries::per_arg_count());
1799          addi(tmp1, tmp1, -i*TypeStackSlotEntries::per_arg_count());
1800          blt(CCR0, done);
1801        }
1802        ld(tmp1, in_bytes(Method::const_offset()), callee);
1803        lhz(tmp1, in_bytes(ConstMethod::size_of_parameters_offset()), tmp1);
1804        // Stack offset o (zero based) from the start of the argument
1805        // list, for n arguments translates into offset n - o - 1 from
1806        // the end of the argument list. But there's an extra slot at
1807        // the top of the stack. So the offset is n - o from Lesp.
1808        ld(tmp2, in_bytes(TypeEntriesAtCall::stack_slot_offset(i))-off_to_args, R28_mdx);
1809        subf(tmp1, tmp2, tmp1);
1810
1811        sldi(tmp1, tmp1, Interpreter::logStackElementSize);
1812        ldx(tmp1, tmp1, R15_esp);
1813
1814        profile_obj_type(tmp1, R28_mdx, in_bytes(TypeEntriesAtCall::argument_type_offset(i))-off_to_args, tmp2, tmp1);
1815
1816        int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
1817        addi(R28_mdx, R28_mdx, to_add);
1818        off_to_args += to_add;
1819      }
1820
1821      if (MethodData::profile_return()) {
1822        ld(tmp1, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args, R28_mdx);
1823        addi(tmp1, tmp1, -TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
1824      }
1825
1826      bind(done);
1827
1828      if (MethodData::profile_return()) {
1829        // We're right after the type profile for the last
1830        // argument. tmp1 is the number of cells left in the
1831        // CallTypeData/VirtualCallTypeData to reach its end. Non null
1832        // if there's a return to profile.
1833        assert(ReturnTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(),
1834               "can't move past ret type");
1835        sldi(tmp1, tmp1, exact_log2(DataLayout::cell_size));
1836        add(R28_mdx, tmp1, R28_mdx);
1837      }
1838    } else {
1839      assert(MethodData::profile_return(), "either profile call args or call ret");
1840      update_mdp_by_constant(in_bytes(TypeEntriesAtCall::return_only_size()));
1841    }
1842
1843    // Mdp points right after the end of the
1844    // CallTypeData/VirtualCallTypeData, right after the cells for the
1845    // return value type if there's one.
1846    align(32, 12);
1847    bind(profile_continue);
1848  }
1849}
1850
1851void InterpreterMacroAssembler::profile_return_type(Register ret, Register tmp1, Register tmp2) {
1852  assert_different_registers(ret, tmp1, tmp2);
1853  if (ProfileInterpreter && MethodData::profile_return()) {
1854    Label profile_continue;
1855
1856    test_method_data_pointer(profile_continue);
1857
1858    if (MethodData::profile_return_jsr292_only()) {
1859      // If we don't profile all invoke bytecodes we must make sure
1860      // it's a bytecode we indeed profile. We can't go back to the
1861      // begining of the ProfileData we intend to update to check its
1862      // type because we're right after it and we don't known its
1863      // length.
1864      lbz(tmp1, 0, R14_bcp);
1865      lbz(tmp2, Method::intrinsic_id_offset_in_bytes(), R19_method);
1866      cmpwi(CCR0, tmp1, Bytecodes::_invokedynamic);
1867      cmpwi(CCR1, tmp1, Bytecodes::_invokehandle);
1868      cror(CCR0, Assembler::equal, CCR1, Assembler::equal);
1869      cmpwi(CCR1, tmp2, vmIntrinsics::_compiledLambdaForm);
1870      cror(CCR0, Assembler::equal, CCR1, Assembler::equal);
1871      bne(CCR0, profile_continue);
1872    }
1873
1874    profile_obj_type(ret, R28_mdx, -in_bytes(ReturnTypeEntry::size()), tmp1, tmp2);
1875
1876    align(32, 12);
1877    bind(profile_continue);
1878  }
1879}
1880
1881void InterpreterMacroAssembler::profile_parameters_type(Register tmp1, Register tmp2,
1882                                                        Register tmp3, Register tmp4) {
1883  if (ProfileInterpreter && MethodData::profile_parameters()) {
1884    Label profile_continue, done;
1885
1886    test_method_data_pointer(profile_continue);
1887
1888    // Load the offset of the area within the MDO used for
1889    // parameters. If it's negative we're not profiling any parameters.
1890    lwz(tmp1, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset()), R28_mdx);
1891    cmpwi(CCR0, tmp1, 0);
1892    blt(CCR0, profile_continue);
1893
1894    // Compute a pointer to the area for parameters from the offset
1895    // and move the pointer to the slot for the last
1896    // parameters. Collect profiling from last parameter down.
1897    // mdo start + parameters offset + array length - 1
1898
1899    // Pointer to the parameter area in the MDO.
1900    const Register mdp = tmp1;
1901    add(mdp, tmp1, R28_mdx);
1902
1903    // Offset of the current profile entry to update.
1904    const Register entry_offset = tmp2;
1905    // entry_offset = array len in number of cells
1906    ld(entry_offset, in_bytes(ArrayData::array_len_offset()), mdp);
1907
1908    int off_base = in_bytes(ParametersTypeData::stack_slot_offset(0));
1909    assert(off_base % DataLayout::cell_size == 0, "should be a number of cells");
1910
1911    // entry_offset (number of cells)  = array len - size of 1 entry + offset of the stack slot field
1912    addi(entry_offset, entry_offset, -TypeStackSlotEntries::per_arg_count() + (off_base / DataLayout::cell_size));
1913    // entry_offset in bytes
1914    sldi(entry_offset, entry_offset, exact_log2(DataLayout::cell_size));
1915
1916    Label loop;
1917    align(32, 12);
1918    bind(loop);
1919
1920    // Load offset on the stack from the slot for this parameter.
1921    ld(tmp3, entry_offset, mdp);
1922    sldi(tmp3, tmp3, Interpreter::logStackElementSize);
1923    neg(tmp3, tmp3);
1924    // Read the parameter from the local area.
1925    ldx(tmp3, tmp3, R18_locals);
1926
1927    // Make entry_offset now point to the type field for this parameter.
1928    int type_base = in_bytes(ParametersTypeData::type_offset(0));
1929    assert(type_base > off_base, "unexpected");
1930    addi(entry_offset, entry_offset, type_base - off_base);
1931
1932    // Profile the parameter.
1933    profile_obj_type(tmp3, mdp, entry_offset, tmp4, tmp3);
1934
1935    // Go to next parameter.
1936    int delta = TypeStackSlotEntries::per_arg_count() * DataLayout::cell_size + (type_base - off_base);
1937    cmpdi(CCR0, entry_offset, off_base + delta);
1938    addi(entry_offset, entry_offset, -delta);
1939    bge(CCR0, loop);
1940
1941    align(32, 12);
1942    bind(profile_continue);
1943  }
1944}
1945
1946// Add a InterpMonitorElem to stack (see frame_sparc.hpp).
1947void InterpreterMacroAssembler::add_monitor_to_stack(bool stack_is_empty, Register Rtemp1, Register Rtemp2) {
1948
1949  // Very-local scratch registers.
1950  const Register esp  = Rtemp1;
1951  const Register slot = Rtemp2;
1952
1953  // Extracted monitor_size.
1954  int monitor_size = frame::interpreter_frame_monitor_size_in_bytes();
1955  assert(Assembler::is_aligned((unsigned int)monitor_size,
1956                               (unsigned int)frame::alignment_in_bytes),
1957         "size of a monitor must respect alignment of SP");
1958
1959  resize_frame(-monitor_size, /*temp*/esp); // Allocate space for new monitor
1960  std(R1_SP, _ijava_state_neg(top_frame_sp), esp); // esp contains fp
1961
1962  // Shuffle expression stack down. Recall that stack_base points
1963  // just above the new expression stack bottom. Old_tos and new_tos
1964  // are used to scan thru the old and new expression stacks.
1965  if (!stack_is_empty) {
1966    Label copy_slot, copy_slot_finished;
1967    const Register n_slots = slot;
1968
1969    addi(esp, R15_esp, Interpreter::stackElementSize); // Point to first element (pre-pushed stack).
1970    subf(n_slots, esp, R26_monitor);
1971    srdi_(n_slots, n_slots, LogBytesPerWord);          // Compute number of slots to copy.
1972    assert(LogBytesPerWord == 3, "conflicts assembler instructions");
1973    beq(CCR0, copy_slot_finished);                     // Nothing to copy.
1974
1975    mtctr(n_slots);
1976
1977    // loop
1978    bind(copy_slot);
1979    ld(slot, 0, esp);              // Move expression stack down.
1980    std(slot, -monitor_size, esp); // distance = monitor_size
1981    addi(esp, esp, BytesPerWord);
1982    bdnz(copy_slot);
1983
1984    bind(copy_slot_finished);
1985  }
1986
1987  addi(R15_esp, R15_esp, -monitor_size);
1988  addi(R26_monitor, R26_monitor, -monitor_size);
1989
1990  // Restart interpreter
1991}
1992
1993// ============================================================================
1994// Java locals access
1995
1996// Load a local variable at index in Rindex into register Rdst_value.
1997// Also puts address of local into Rdst_address as a service.
1998// Kills:
1999//   - Rdst_value
2000//   - Rdst_address
2001void InterpreterMacroAssembler::load_local_int(Register Rdst_value, Register Rdst_address, Register Rindex) {
2002  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2003  subf(Rdst_address, Rdst_address, R18_locals);
2004  lwz(Rdst_value, 0, Rdst_address);
2005}
2006
2007// Load a local variable at index in Rindex into register Rdst_value.
2008// Also puts address of local into Rdst_address as a service.
2009// Kills:
2010//   - Rdst_value
2011//   - Rdst_address
2012void InterpreterMacroAssembler::load_local_long(Register Rdst_value, Register Rdst_address, Register Rindex) {
2013  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2014  subf(Rdst_address, Rdst_address, R18_locals);
2015  ld(Rdst_value, -8, Rdst_address);
2016}
2017
2018// Load a local variable at index in Rindex into register Rdst_value.
2019// Also puts address of local into Rdst_address as a service.
2020// Input:
2021//   - Rindex:      slot nr of local variable
2022// Kills:
2023//   - Rdst_value
2024//   - Rdst_address
2025void InterpreterMacroAssembler::load_local_ptr(Register Rdst_value,
2026                                               Register Rdst_address,
2027                                               Register Rindex) {
2028  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2029  subf(Rdst_address, Rdst_address, R18_locals);
2030  ld(Rdst_value, 0, Rdst_address);
2031}
2032
2033// Load a local variable at index in Rindex into register Rdst_value.
2034// Also puts address of local into Rdst_address as a service.
2035// Kills:
2036//   - Rdst_value
2037//   - Rdst_address
2038void InterpreterMacroAssembler::load_local_float(FloatRegister Rdst_value,
2039                                                 Register Rdst_address,
2040                                                 Register Rindex) {
2041  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2042  subf(Rdst_address, Rdst_address, R18_locals);
2043  lfs(Rdst_value, 0, Rdst_address);
2044}
2045
2046// Load a local variable at index in Rindex into register Rdst_value.
2047// Also puts address of local into Rdst_address as a service.
2048// Kills:
2049//   - Rdst_value
2050//   - Rdst_address
2051void InterpreterMacroAssembler::load_local_double(FloatRegister Rdst_value,
2052                                                  Register Rdst_address,
2053                                                  Register Rindex) {
2054  sldi(Rdst_address, Rindex, Interpreter::logStackElementSize);
2055  subf(Rdst_address, Rdst_address, R18_locals);
2056  lfd(Rdst_value, -8, Rdst_address);
2057}
2058
2059// Store an int value at local variable slot Rindex.
2060// Kills:
2061//   - Rindex
2062void InterpreterMacroAssembler::store_local_int(Register Rvalue, Register Rindex) {
2063  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2064  subf(Rindex, Rindex, R18_locals);
2065  stw(Rvalue, 0, Rindex);
2066}
2067
2068// Store a long value at local variable slot Rindex.
2069// Kills:
2070//   - Rindex
2071void InterpreterMacroAssembler::store_local_long(Register Rvalue, Register Rindex) {
2072  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2073  subf(Rindex, Rindex, R18_locals);
2074  std(Rvalue, -8, Rindex);
2075}
2076
2077// Store an oop value at local variable slot Rindex.
2078// Kills:
2079//   - Rindex
2080void InterpreterMacroAssembler::store_local_ptr(Register Rvalue, Register Rindex) {
2081  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2082  subf(Rindex, Rindex, R18_locals);
2083  std(Rvalue, 0, Rindex);
2084}
2085
2086// Store an int value at local variable slot Rindex.
2087// Kills:
2088//   - Rindex
2089void InterpreterMacroAssembler::store_local_float(FloatRegister Rvalue, Register Rindex) {
2090  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2091  subf(Rindex, Rindex, R18_locals);
2092  stfs(Rvalue, 0, Rindex);
2093}
2094
2095// Store an int value at local variable slot Rindex.
2096// Kills:
2097//   - Rindex
2098void InterpreterMacroAssembler::store_local_double(FloatRegister Rvalue, Register Rindex) {
2099  sldi(Rindex, Rindex, Interpreter::logStackElementSize);
2100  subf(Rindex, Rindex, R18_locals);
2101  stfd(Rvalue, -8, Rindex);
2102}
2103
2104// Read pending exception from thread and jump to interpreter.
2105// Throw exception entry if one if pending. Fall through otherwise.
2106void InterpreterMacroAssembler::check_and_forward_exception(Register Rscratch1, Register Rscratch2) {
2107  assert_different_registers(Rscratch1, Rscratch2, R3);
2108  Register Rexception = Rscratch1;
2109  Register Rtmp       = Rscratch2;
2110  Label Ldone;
2111  // Get pending exception oop.
2112  ld(Rexception, thread_(pending_exception));
2113  cmpdi(CCR0, Rexception, 0);
2114  beq(CCR0, Ldone);
2115  li(Rtmp, 0);
2116  mr_if_needed(R3, Rexception);
2117  std(Rtmp, thread_(pending_exception)); // Clear exception in thread
2118  if (Interpreter::rethrow_exception_entry() != NULL) {
2119    // Already got entry address.
2120    load_dispatch_table(Rtmp, (address*)Interpreter::rethrow_exception_entry());
2121  } else {
2122    // Dynamically load entry address.
2123    int simm16_rest = load_const_optimized(Rtmp, &Interpreter::_rethrow_exception_entry, R0, true);
2124    ld(Rtmp, simm16_rest, Rtmp);
2125  }
2126  mtctr(Rtmp);
2127  save_interpreter_state(Rtmp);
2128  bctr();
2129
2130  align(32, 12);
2131  bind(Ldone);
2132}
2133
2134void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point, bool check_exceptions) {
2135  save_interpreter_state(R11_scratch1);
2136
2137  MacroAssembler::call_VM(oop_result, entry_point, false);
2138
2139  restore_interpreter_state(R11_scratch1, /*bcp_and_mdx_only*/ true);
2140
2141  check_and_handle_popframe(R11_scratch1);
2142  check_and_handle_earlyret(R11_scratch1);
2143  // Now check exceptions manually.
2144  if (check_exceptions) {
2145    check_and_forward_exception(R11_scratch1, R12_scratch2);
2146  }
2147}
2148
2149void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2150                                        Register arg_1, bool check_exceptions) {
2151  // ARG1 is reserved for the thread.
2152  mr_if_needed(R4_ARG2, arg_1);
2153  call_VM(oop_result, entry_point, check_exceptions);
2154}
2155
2156void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2157                                        Register arg_1, Register arg_2,
2158                                        bool check_exceptions) {
2159  // ARG1 is reserved for the thread.
2160  mr_if_needed(R4_ARG2, arg_1);
2161  assert(arg_2 != R4_ARG2, "smashed argument");
2162  mr_if_needed(R5_ARG3, arg_2);
2163  call_VM(oop_result, entry_point, check_exceptions);
2164}
2165
2166void InterpreterMacroAssembler::call_VM(Register oop_result, address entry_point,
2167                                        Register arg_1, Register arg_2, Register arg_3,
2168                                        bool check_exceptions) {
2169  // ARG1 is reserved for the thread.
2170  mr_if_needed(R4_ARG2, arg_1);
2171  assert(arg_2 != R4_ARG2, "smashed argument");
2172  mr_if_needed(R5_ARG3, arg_2);
2173  assert(arg_3 != R4_ARG2 && arg_3 != R5_ARG3, "smashed argument");
2174  mr_if_needed(R6_ARG4, arg_3);
2175  call_VM(oop_result, entry_point, check_exceptions);
2176}
2177
2178void InterpreterMacroAssembler::save_interpreter_state(Register scratch) {
2179  ld(scratch, 0, R1_SP);
2180  std(R15_esp, _ijava_state_neg(esp), scratch);
2181  std(R14_bcp, _ijava_state_neg(bcp), scratch);
2182  std(R26_monitor, _ijava_state_neg(monitors), scratch);
2183  if (ProfileInterpreter) { std(R28_mdx, _ijava_state_neg(mdx), scratch); }
2184  // Other entries should be unchanged.
2185}
2186
2187void InterpreterMacroAssembler::restore_interpreter_state(Register scratch, bool bcp_and_mdx_only) {
2188  ld(scratch, 0, R1_SP);
2189  ld(R14_bcp, _ijava_state_neg(bcp), scratch); // Changed by VM code (exception).
2190  if (ProfileInterpreter) { ld(R28_mdx, _ijava_state_neg(mdx), scratch); } // Changed by VM code.
2191  if (!bcp_and_mdx_only) {
2192    // Following ones are Metadata.
2193    ld(R19_method, _ijava_state_neg(method), scratch);
2194    ld(R27_constPoolCache, _ijava_state_neg(cpoolCache), scratch);
2195    // Following ones are stack addresses and don't require reload.
2196    ld(R15_esp, _ijava_state_neg(esp), scratch);
2197    ld(R18_locals, _ijava_state_neg(locals), scratch);
2198    ld(R26_monitor, _ijava_state_neg(monitors), scratch);
2199  }
2200#ifdef ASSERT
2201  {
2202    Label Lok;
2203    subf(R0, R1_SP, scratch);
2204    cmpdi(CCR0, R0, frame::abi_reg_args_size + frame::ijava_state_size);
2205    bge(CCR0, Lok);
2206    stop("frame too small (restore istate)", 0x5432);
2207    bind(Lok);
2208  }
2209  {
2210    Label Lok;
2211    ld(R0, _ijava_state_neg(ijava_reserved), scratch);
2212    cmpdi(CCR0, R0, 0x5afe);
2213    beq(CCR0, Lok);
2214    stop("frame corrupted (restore istate)", 0x5afe);
2215    bind(Lok);
2216  }
2217#endif
2218}
2219
2220void InterpreterMacroAssembler::get_method_counters(Register method,
2221                                                    Register Rcounters,
2222                                                    Label& skip) {
2223  BLOCK_COMMENT("Load and ev. allocate counter object {");
2224  Label has_counters;
2225  ld(Rcounters, in_bytes(Method::method_counters_offset()), method);
2226  cmpdi(CCR0, Rcounters, 0);
2227  bne(CCR0, has_counters);
2228  call_VM(noreg, CAST_FROM_FN_PTR(address,
2229                                  InterpreterRuntime::build_method_counters), method, false);
2230  ld(Rcounters, in_bytes(Method::method_counters_offset()), method);
2231  cmpdi(CCR0, Rcounters, 0);
2232  beq(CCR0, skip); // No MethodCounters, OutOfMemory.
2233  BLOCK_COMMENT("} Load and ev. allocate counter object");
2234
2235  bind(has_counters);
2236}
2237
2238void InterpreterMacroAssembler::increment_invocation_counter(Register Rcounters,
2239                                                             Register iv_be_count,
2240                                                             Register Rtmp_r0) {
2241  assert(UseCompiler || LogTouchedMethods, "incrementing must be useful");
2242  Register invocation_count = iv_be_count;
2243  Register backedge_count   = Rtmp_r0;
2244  int delta = InvocationCounter::count_increment;
2245
2246  // Load each counter in a register.
2247  //  ld(inv_counter, Rtmp);
2248  //  ld(be_counter, Rtmp2);
2249  int inv_counter_offset = in_bytes(MethodCounters::invocation_counter_offset() +
2250                                    InvocationCounter::counter_offset());
2251  int be_counter_offset  = in_bytes(MethodCounters::backedge_counter_offset() +
2252                                    InvocationCounter::counter_offset());
2253
2254  BLOCK_COMMENT("Increment profiling counters {");
2255
2256  // Load the backedge counter.
2257  lwz(backedge_count, be_counter_offset, Rcounters); // is unsigned int
2258  // Mask the backedge counter.
2259  andi(backedge_count, backedge_count, InvocationCounter::count_mask_value);
2260
2261  // Load the invocation counter.
2262  lwz(invocation_count, inv_counter_offset, Rcounters); // is unsigned int
2263  // Add the delta to the invocation counter and store the result.
2264  addi(invocation_count, invocation_count, delta);
2265  // Store value.
2266  stw(invocation_count, inv_counter_offset, Rcounters);
2267
2268  // Add invocation counter + backedge counter.
2269  add(iv_be_count, backedge_count, invocation_count);
2270
2271  // Note that this macro must leave the backedge_count + invocation_count in
2272  // register iv_be_count!
2273  BLOCK_COMMENT("} Increment profiling counters");
2274}
2275
2276void InterpreterMacroAssembler::verify_oop(Register reg, TosState state) {
2277  if (state == atos) { MacroAssembler::verify_oop(reg); }
2278}
2279
2280// Local helper function for the verify_oop_or_return_address macro.
2281static bool verify_return_address(Method* m, int bci) {
2282#ifndef PRODUCT
2283  address pc = (address)(m->constMethod()) + in_bytes(ConstMethod::codes_offset()) + bci;
2284  // Assume it is a valid return address if it is inside m and is preceded by a jsr.
2285  if (!m->contains(pc))                                            return false;
2286  address jsr_pc;
2287  jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr);
2288  if (*jsr_pc == Bytecodes::_jsr   && jsr_pc >= m->code_base())    return true;
2289  jsr_pc = pc - Bytecodes::length_for(Bytecodes::_jsr_w);
2290  if (*jsr_pc == Bytecodes::_jsr_w && jsr_pc >= m->code_base())    return true;
2291#endif // PRODUCT
2292  return false;
2293}
2294
2295void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
2296  if (VerifyFPU) {
2297    unimplemented("verfiyFPU");
2298  }
2299}
2300
2301void InterpreterMacroAssembler::verify_oop_or_return_address(Register reg, Register Rtmp) {
2302  if (!VerifyOops) return;
2303
2304  // The VM documentation for the astore[_wide] bytecode allows
2305  // the TOS to be not only an oop but also a return address.
2306  Label test;
2307  Label skip;
2308  // See if it is an address (in the current method):
2309
2310  const int log2_bytecode_size_limit = 16;
2311  srdi_(Rtmp, reg, log2_bytecode_size_limit);
2312  bne(CCR0, test);
2313
2314  address fd = CAST_FROM_FN_PTR(address, verify_return_address);
2315  const int nbytes_save = MacroAssembler::num_volatile_regs * 8;
2316  save_volatile_gprs(R1_SP, -nbytes_save); // except R0
2317  save_LR_CR(Rtmp); // Save in old frame.
2318  push_frame_reg_args(nbytes_save, Rtmp);
2319
2320  load_const_optimized(Rtmp, fd, R0);
2321  mr_if_needed(R4_ARG2, reg);
2322  mr(R3_ARG1, R19_method);
2323  call_c(Rtmp); // call C
2324
2325  pop_frame();
2326  restore_LR_CR(Rtmp);
2327  restore_volatile_gprs(R1_SP, -nbytes_save); // except R0
2328  b(skip);
2329
2330  // Perform a more elaborate out-of-line call.
2331  // Not an address; verify it:
2332  bind(test);
2333  verify_oop(reg);
2334  bind(skip);
2335}
2336
2337// Inline assembly for:
2338//
2339// if (thread is in interp_only_mode) {
2340//   InterpreterRuntime::post_method_entry();
2341// }
2342// if (*jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_ENTRY ) ||
2343//     *jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_ENTRY2)   ) {
2344//   SharedRuntime::jvmpi_method_entry(method, receiver);
2345// }
2346void InterpreterMacroAssembler::notify_method_entry() {
2347  // JVMTI
2348  // Whenever JVMTI puts a thread in interp_only_mode, method
2349  // entry/exit events are sent for that thread to track stack
2350  // depth. If it is possible to enter interp_only_mode we add
2351  // the code to check if the event should be sent.
2352  if (JvmtiExport::can_post_interpreter_events()) {
2353    Label jvmti_post_done;
2354
2355    lwz(R0, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
2356    cmpwi(CCR0, R0, 0);
2357    beq(CCR0, jvmti_post_done);
2358    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_entry),
2359            /*check_exceptions=*/true);
2360
2361    bind(jvmti_post_done);
2362  }
2363}
2364
2365// Inline assembly for:
2366//
2367// if (thread is in interp_only_mode) {
2368//   // save result
2369//   InterpreterRuntime::post_method_exit();
2370//   // restore result
2371// }
2372// if (*jvmpi::event_flags_array_at_addr(JVMPI_EVENT_METHOD_EXIT)) {
2373//   // save result
2374//   SharedRuntime::jvmpi_method_exit();
2375//   // restore result
2376// }
2377//
2378// Native methods have their result stored in d_tmp and l_tmp.
2379// Java methods have their result stored in the expression stack.
2380void InterpreterMacroAssembler::notify_method_exit(bool is_native_method, TosState state,
2381                                                   NotifyMethodExitMode mode, bool check_exceptions) {
2382  // JVMTI
2383  // Whenever JVMTI puts a thread in interp_only_mode, method
2384  // entry/exit events are sent for that thread to track stack
2385  // depth. If it is possible to enter interp_only_mode we add
2386  // the code to check if the event should be sent.
2387  if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2388    Label jvmti_post_done;
2389
2390    lwz(R0, in_bytes(JavaThread::interp_only_mode_offset()), R16_thread);
2391    cmpwi(CCR0, R0, 0);
2392    beq(CCR0, jvmti_post_done);
2393    if (!is_native_method) { push(state); } // Expose tos to GC.
2394    call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit),
2395            /*check_exceptions=*/check_exceptions);
2396    if (!is_native_method) { pop(state); }
2397
2398    align(32, 12);
2399    bind(jvmti_post_done);
2400  }
2401
2402  // Dtrace support not implemented.
2403}
2404
2405