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