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