1 /*
   2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "compiler/compiler_globals.hpp"
  27 #include "interp_masm_x86.hpp"
  28 #include "interpreter/interpreter.hpp"
  29 #include "interpreter/interpreterRuntime.hpp"
  30 #include "logging/log.hpp"
  31 #include "oops/arrayOop.hpp"
  32 #include "oops/markWord.hpp"
  33 #include "oops/methodData.hpp"
  34 #include "oops/method.hpp"
  35 #include "oops/resolvedFieldEntry.hpp"
  36 #include "oops/resolvedIndyEntry.hpp"
  37 #include "oops/resolvedMethodEntry.hpp"
  38 #include "prims/jvmtiExport.hpp"
  39 #include "prims/jvmtiThreadState.hpp"
  40 #include "runtime/basicLock.hpp"
  41 #include "runtime/frame.inline.hpp"
  42 #include "runtime/javaThread.hpp"
  43 #include "runtime/safepointMechanism.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "utilities/powerOfTwo.hpp"
  46 
  47 // Implementation of InterpreterMacroAssembler
  48 
  49 void InterpreterMacroAssembler::jump_to_entry(address entry) {
  50   assert(entry, "Entry must have been generated by now");
  51   jump(RuntimeAddress(entry));
  52 }
  53 
  54 void InterpreterMacroAssembler::profile_obj_type(Register obj, const Address& mdo_addr) {
  55   Label update, next, none;
  56 
  57 #ifdef _LP64
  58   assert_different_registers(obj, rscratch1, mdo_addr.base(), mdo_addr.index());
  59 #else
  60   assert_different_registers(obj, mdo_addr.base(), mdo_addr.index());
  61 #endif
  62 
  63   interp_verify_oop(obj, atos);
  64 
  65   testptr(obj, obj);
  66   jccb(Assembler::notZero, update);
  67   testptr(mdo_addr, TypeEntries::null_seen);
  68   jccb(Assembler::notZero, next); // null already seen. Nothing to do anymore.
  69   // atomic update to prevent overwriting Klass* with 0
  70   lock();
  71   orptr(mdo_addr, TypeEntries::null_seen);
  72   jmpb(next);
  73 
  74   bind(update);
  75   load_klass(obj, obj, rscratch1);
  76 #ifdef _LP64
  77   mov(rscratch1, obj);
  78 #endif
  79 
  80   xorptr(obj, mdo_addr);
  81   testptr(obj, TypeEntries::type_klass_mask);
  82   jccb(Assembler::zero, next); // klass seen before, nothing to
  83                                // do. The unknown bit may have been
  84                                // set already but no need to check.
  85 
  86   testptr(obj, TypeEntries::type_unknown);
  87   jccb(Assembler::notZero, next); // already unknown. Nothing to do anymore.
  88 
  89   cmpptr(mdo_addr, 0);
  90   jccb(Assembler::equal, none);
  91   cmpptr(mdo_addr, TypeEntries::null_seen);
  92   jccb(Assembler::equal, none);
  93 #ifdef _LP64
  94   // There is a chance that the checks above (re-reading profiling
  95   // data from memory) fail if another thread has just set the
  96   // profiling to this obj's klass
  97   mov(obj, rscratch1);
  98   xorptr(obj, mdo_addr);
  99   testptr(obj, TypeEntries::type_klass_mask);
 100   jccb(Assembler::zero, next);
 101 #endif
 102 
 103   // different than before. Cannot keep accurate profile.
 104   orptr(mdo_addr, TypeEntries::type_unknown);
 105   jmpb(next);
 106 
 107   bind(none);
 108   // first time here. Set profile type.
 109   movptr(mdo_addr, obj);
 110 #ifdef ASSERT
 111   andptr(obj, TypeEntries::type_klass_mask);
 112   verify_klass_ptr(obj);
 113 #endif
 114 
 115   bind(next);
 116 }
 117 
 118 void InterpreterMacroAssembler::profile_arguments_type(Register mdp, Register callee, Register tmp, bool is_virtual) {
 119   if (!ProfileInterpreter) {
 120     return;
 121   }
 122 
 123   if (MethodData::profile_arguments() || MethodData::profile_return()) {
 124     Label profile_continue;
 125 
 126     test_method_data_pointer(mdp, profile_continue);
 127 
 128     int off_to_start = is_virtual ? in_bytes(VirtualCallData::virtual_call_data_size()) : in_bytes(CounterData::counter_data_size());
 129 
 130     cmpb(Address(mdp, in_bytes(DataLayout::tag_offset()) - off_to_start), is_virtual ? DataLayout::virtual_call_type_data_tag : DataLayout::call_type_data_tag);
 131     jcc(Assembler::notEqual, profile_continue);
 132 
 133     if (MethodData::profile_arguments()) {
 134       Label done;
 135       int off_to_args = in_bytes(TypeEntriesAtCall::args_data_offset());
 136       addptr(mdp, off_to_args);
 137 
 138       for (int i = 0; i < TypeProfileArgsLimit; i++) {
 139         if (i > 0 || MethodData::profile_return()) {
 140           // If return value type is profiled we may have no argument to profile
 141           movptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args));
 142           subl(tmp, i*TypeStackSlotEntries::per_arg_count());
 143           cmpl(tmp, TypeStackSlotEntries::per_arg_count());
 144           jcc(Assembler::less, done);
 145         }
 146         movptr(tmp, Address(callee, Method::const_offset()));
 147         load_unsigned_short(tmp, Address(tmp, ConstMethod::size_of_parameters_offset()));
 148         // stack offset o (zero based) from the start of the argument
 149         // list, for n arguments translates into offset n - o - 1 from
 150         // the end of the argument list
 151         subptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::stack_slot_offset(i))-off_to_args));
 152         subl(tmp, 1);
 153         Address arg_addr = argument_address(tmp);
 154         movptr(tmp, arg_addr);
 155 
 156         Address mdo_arg_addr(mdp, in_bytes(TypeEntriesAtCall::argument_type_offset(i))-off_to_args);
 157         profile_obj_type(tmp, mdo_arg_addr);
 158 
 159         int to_add = in_bytes(TypeStackSlotEntries::per_arg_size());
 160         addptr(mdp, to_add);
 161         off_to_args += to_add;
 162       }
 163 
 164       if (MethodData::profile_return()) {
 165         movptr(tmp, Address(mdp, in_bytes(TypeEntriesAtCall::cell_count_offset())-off_to_args));
 166         subl(tmp, TypeProfileArgsLimit*TypeStackSlotEntries::per_arg_count());
 167       }
 168 
 169       bind(done);
 170 
 171       if (MethodData::profile_return()) {
 172         // We're right after the type profile for the last
 173         // argument. tmp is the number of cells left in the
 174         // CallTypeData/VirtualCallTypeData to reach its end. Non null
 175         // if there's a return to profile.
 176         assert(ReturnTypeEntry::static_cell_count() < TypeStackSlotEntries::per_arg_count(), "can't move past ret type");
 177         shll(tmp, log2i_exact((int)DataLayout::cell_size));
 178         addptr(mdp, tmp);
 179       }
 180       movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp);
 181     } else {
 182       assert(MethodData::profile_return(), "either profile call args or call ret");
 183       update_mdp_by_constant(mdp, in_bytes(TypeEntriesAtCall::return_only_size()));
 184     }
 185 
 186     // mdp points right after the end of the
 187     // CallTypeData/VirtualCallTypeData, right after the cells for the
 188     // return value type if there's one
 189 
 190     bind(profile_continue);
 191   }
 192 }
 193 
 194 void InterpreterMacroAssembler::profile_return_type(Register mdp, Register ret, Register tmp) {
 195   assert_different_registers(mdp, ret, tmp, _bcp_register);
 196   if (ProfileInterpreter && MethodData::profile_return()) {
 197     Label profile_continue;
 198 
 199     test_method_data_pointer(mdp, profile_continue);
 200 
 201     if (MethodData::profile_return_jsr292_only()) {
 202       assert(Method::intrinsic_id_size_in_bytes() == 2, "assuming Method::_intrinsic_id is u2");
 203 
 204       // If we don't profile all invoke bytecodes we must make sure
 205       // it's a bytecode we indeed profile. We can't go back to the
 206       // beginning of the ProfileData we intend to update to check its
 207       // type because we're right after it and we don't known its
 208       // length
 209       Label do_profile;
 210       cmpb(Address(_bcp_register, 0), Bytecodes::_invokedynamic);
 211       jcc(Assembler::equal, do_profile);
 212       cmpb(Address(_bcp_register, 0), Bytecodes::_invokehandle);
 213       jcc(Assembler::equal, do_profile);
 214       get_method(tmp);
 215       cmpw(Address(tmp, Method::intrinsic_id_offset()), static_cast<int>(vmIntrinsics::_compiledLambdaForm));
 216       jcc(Assembler::notEqual, profile_continue);
 217 
 218       bind(do_profile);
 219     }
 220 
 221     Address mdo_ret_addr(mdp, -in_bytes(ReturnTypeEntry::size()));
 222     mov(tmp, ret);
 223     profile_obj_type(tmp, mdo_ret_addr);
 224 
 225     bind(profile_continue);
 226   }
 227 }
 228 
 229 void InterpreterMacroAssembler::profile_parameters_type(Register mdp, Register tmp1, Register tmp2) {
 230   if (ProfileInterpreter && MethodData::profile_parameters()) {
 231     Label profile_continue;
 232 
 233     test_method_data_pointer(mdp, profile_continue);
 234 
 235     // Load the offset of the area within the MDO used for
 236     // parameters. If it's negative we're not profiling any parameters
 237     movl(tmp1, Address(mdp, in_bytes(MethodData::parameters_type_data_di_offset()) - in_bytes(MethodData::data_offset())));
 238     testl(tmp1, tmp1);
 239     jcc(Assembler::negative, profile_continue);
 240 
 241     // Compute a pointer to the area for parameters from the offset
 242     // and move the pointer to the slot for the last
 243     // parameters. Collect profiling from last parameter down.
 244     // mdo start + parameters offset + array length - 1
 245     addptr(mdp, tmp1);
 246     movptr(tmp1, Address(mdp, ArrayData::array_len_offset()));
 247     decrement(tmp1, TypeStackSlotEntries::per_arg_count());
 248 
 249     Label loop;
 250     bind(loop);
 251 
 252     int off_base = in_bytes(ParametersTypeData::stack_slot_offset(0));
 253     int type_base = in_bytes(ParametersTypeData::type_offset(0));
 254     Address::ScaleFactor per_arg_scale = Address::times(DataLayout::cell_size);
 255     Address arg_off(mdp, tmp1, per_arg_scale, off_base);
 256     Address arg_type(mdp, tmp1, per_arg_scale, type_base);
 257 
 258     // load offset on the stack from the slot for this parameter
 259     movptr(tmp2, arg_off);
 260     negptr(tmp2);
 261     // read the parameter from the local area
 262     movptr(tmp2, Address(_locals_register, tmp2, Interpreter::stackElementScale()));
 263 
 264     // profile the parameter
 265     profile_obj_type(tmp2, arg_type);
 266 
 267     // go to next parameter
 268     decrement(tmp1, TypeStackSlotEntries::per_arg_count());
 269     jcc(Assembler::positive, loop);
 270 
 271     bind(profile_continue);
 272   }
 273 }
 274 
 275 void InterpreterMacroAssembler::call_VM_leaf_base(address entry_point,
 276                                                   int number_of_arguments) {
 277   // interpreter specific
 278   //
 279   // Note: No need to save/restore bcp & locals registers
 280   //       since these are callee saved registers and no blocking/
 281   //       GC can happen in leaf calls.
 282   // Further Note: DO NOT save/restore bcp/locals. If a caller has
 283   // already saved them so that it can use rsi/rdi as temporaries
 284   // then a save/restore here will DESTROY the copy the caller
 285   // saved! There used to be a save_bcp() that only happened in
 286   // the ASSERT path (no restore_bcp). Which caused bizarre failures
 287   // when jvm built with ASSERTs.
 288 #ifdef ASSERT
 289   {
 290     Label L;
 291     cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 292     jcc(Assembler::equal, L);
 293     stop("InterpreterMacroAssembler::call_VM_leaf_base:"
 294          " last_sp != null");
 295     bind(L);
 296   }
 297 #endif
 298   // super call
 299   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
 300   // interpreter specific
 301   // LP64: Used to ASSERT that r13/r14 were equal to frame's bcp/locals
 302   // but since they may not have been saved (and we don't want to
 303   // save them here (see note above) the assert is invalid.
 304 }
 305 
 306 void InterpreterMacroAssembler::call_VM_base(Register oop_result,
 307                                              Register java_thread,
 308                                              Register last_java_sp,
 309                                              address  entry_point,
 310                                              int      number_of_arguments,
 311                                              bool     check_exceptions) {
 312   // interpreter specific
 313   //
 314   // Note: Could avoid restoring locals ptr (callee saved) - however doesn't
 315   //       really make a difference for these runtime calls, since they are
 316   //       slow anyway. Btw., bcp must be saved/restored since it may change
 317   //       due to GC.
 318   NOT_LP64(assert(java_thread == noreg , "not expecting a precomputed java thread");)
 319   save_bcp();
 320 #ifdef ASSERT
 321   {
 322     Label L;
 323     cmpptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 324     jcc(Assembler::equal, L);
 325     stop("InterpreterMacroAssembler::call_VM_base:"
 326          " last_sp isn't null");
 327     bind(L);
 328   }
 329 #endif /* ASSERT */
 330   // super call
 331   MacroAssembler::call_VM_base(oop_result, noreg, last_java_sp,
 332                                entry_point, number_of_arguments,
 333                                check_exceptions);
 334   // interpreter specific
 335   restore_bcp();
 336   restore_locals();
 337 }
 338 
 339 #ifdef _LP64
 340 void InterpreterMacroAssembler::call_VM_preemptable(Register oop_result,
 341                                                     address entry_point,
 342                                                     Register arg_1) {
 343   assert(arg_1 == c_rarg1, "");
 344   Label resume_pc, not_preempted;
 345 
 346 #ifdef ASSERT
 347   {
 348     Label L;
 349     cmpptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
 350     jcc(Assembler::equal, L);
 351     stop("Should not have alternate return address set");
 352     bind(L);
 353   }
 354 #endif /* ASSERT */
 355 
 356   // Force freeze slow path.
 357   push_cont_fastpath();
 358 
 359   // Make VM call. In case of preemption set last_pc to the one we want to resume to.
 360   // Note: call_VM_helper requires last_Java_pc for anchor to be at the top of the stack.
 361   lea(rscratch1, resume_pc);
 362   push(rscratch1);
 363   MacroAssembler::call_VM_helper(oop_result, entry_point, 1, false /*check_exceptions*/);
 364   pop(rscratch1);
 365 
 366   pop_cont_fastpath();
 367 
 368   // Check if preempted.
 369   movptr(rscratch1, Address(r15_thread, JavaThread::preempt_alternate_return_offset()));
 370   cmpptr(rscratch1, NULL_WORD);
 371   jccb(Assembler::zero, not_preempted);
 372   movptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
 373   jmp(rscratch1);
 374 
 375   // In case of preemption, this is where we will resume once we finally acquire the monitor.
 376   bind(resume_pc);
 377   restore_after_resume(false /* is_native */);
 378 
 379   bind(not_preempted);
 380 }
 381 
 382 void InterpreterMacroAssembler::restore_after_resume(bool is_native) {
 383   lea(rscratch1, ExternalAddress(Interpreter::cont_resume_interpreter_adapter()));
 384   call(rscratch1);
 385   if (is_native) {
 386     // On resume we need to set up stack as expected.
 387     push(dtos);
 388     push(ltos);
 389   }
 390 }
 391 #else
 392 void InterpreterMacroAssembler::call_VM_preemptable(Register oop_result,
 393                          address entry_point,
 394                          Register arg_1) {
 395   MacroAssembler::call_VM(oop_result, entry_point, arg_1);
 396 }
 397 #endif  // _LP64
 398 
 399 void InterpreterMacroAssembler::check_and_handle_popframe(Register java_thread) {
 400   if (JvmtiExport::can_pop_frame()) {
 401     Label L;
 402     // Initiate popframe handling only if it is not already being
 403     // processed.  If the flag has the popframe_processing bit set, it
 404     // means that this code is called *during* popframe handling - we
 405     // don't want to reenter.
 406     // This method is only called just after the call into the vm in
 407     // call_VM_base, so the arg registers are available.
 408     Register pop_cond = NOT_LP64(java_thread) // Not clear if any other register is available on 32 bit
 409                         LP64_ONLY(c_rarg0);
 410     movl(pop_cond, Address(java_thread, JavaThread::popframe_condition_offset()));
 411     testl(pop_cond, JavaThread::popframe_pending_bit);
 412     jcc(Assembler::zero, L);
 413     testl(pop_cond, JavaThread::popframe_processing_bit);
 414     jcc(Assembler::notZero, L);
 415     // Call Interpreter::remove_activation_preserving_args_entry() to get the
 416     // address of the same-named entrypoint in the generated interpreter code.
 417     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_preserving_args_entry));
 418     jmp(rax);
 419     bind(L);
 420     NOT_LP64(get_thread(java_thread);)
 421   }
 422 }
 423 
 424 void InterpreterMacroAssembler::load_earlyret_value(TosState state) {
 425   Register thread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
 426   NOT_LP64(get_thread(thread);)
 427   movptr(rcx, Address(thread, JavaThread::jvmti_thread_state_offset()));
 428   const Address tos_addr(rcx, JvmtiThreadState::earlyret_tos_offset());
 429   const Address oop_addr(rcx, JvmtiThreadState::earlyret_oop_offset());
 430   const Address val_addr(rcx, JvmtiThreadState::earlyret_value_offset());
 431 #ifdef _LP64
 432   switch (state) {
 433     case atos: movptr(rax, oop_addr);
 434                movptr(oop_addr, NULL_WORD);
 435                interp_verify_oop(rax, state);         break;
 436     case ltos: movptr(rax, val_addr);                 break;
 437     case btos:                                   // fall through
 438     case ztos:                                   // fall through
 439     case ctos:                                   // fall through
 440     case stos:                                   // fall through
 441     case itos: movl(rax, val_addr);                 break;
 442     case ftos: load_float(val_addr);                break;
 443     case dtos: load_double(val_addr);               break;
 444     case vtos: /* nothing to do */                  break;
 445     default  : ShouldNotReachHere();
 446   }
 447   // Clean up tos value in the thread object
 448   movl(tos_addr, ilgl);
 449   movl(val_addr, NULL_WORD);
 450 #else
 451   const Address val_addr1(rcx, JvmtiThreadState::earlyret_value_offset()
 452                              + in_ByteSize(wordSize));
 453   switch (state) {
 454     case atos: movptr(rax, oop_addr);
 455                movptr(oop_addr, NULL_WORD);
 456                interp_verify_oop(rax, state);         break;
 457     case ltos:
 458                movl(rdx, val_addr1);               // fall through
 459     case btos:                                     // fall through
 460     case ztos:                                     // fall through
 461     case ctos:                                     // fall through
 462     case stos:                                     // fall through
 463     case itos: movl(rax, val_addr);                   break;
 464     case ftos: load_float(val_addr);                  break;
 465     case dtos: load_double(val_addr);                 break;
 466     case vtos: /* nothing to do */                    break;
 467     default  : ShouldNotReachHere();
 468   }
 469 #endif // _LP64
 470   // Clean up tos value in the thread object
 471   movl(tos_addr, ilgl);
 472   movptr(val_addr, NULL_WORD);
 473   NOT_LP64(movptr(val_addr1, NULL_WORD);)
 474 }
 475 
 476 
 477 void InterpreterMacroAssembler::check_and_handle_earlyret(Register java_thread) {
 478   if (JvmtiExport::can_force_early_return()) {
 479     Label L;
 480     Register tmp = LP64_ONLY(c_rarg0) NOT_LP64(java_thread);
 481     Register rthread = LP64_ONLY(r15_thread) NOT_LP64(java_thread);
 482 
 483     movptr(tmp, Address(rthread, JavaThread::jvmti_thread_state_offset()));
 484     testptr(tmp, tmp);
 485     jcc(Assembler::zero, L); // if (thread->jvmti_thread_state() == nullptr) exit;
 486 
 487     // Initiate earlyret handling only if it is not already being processed.
 488     // If the flag has the earlyret_processing bit set, it means that this code
 489     // is called *during* earlyret handling - we don't want to reenter.
 490     movl(tmp, Address(tmp, JvmtiThreadState::earlyret_state_offset()));
 491     cmpl(tmp, JvmtiThreadState::earlyret_pending);
 492     jcc(Assembler::notEqual, L);
 493 
 494     // Call Interpreter::remove_activation_early_entry() to get the address of the
 495     // same-named entrypoint in the generated interpreter code.
 496     NOT_LP64(get_thread(java_thread);)
 497     movptr(tmp, Address(rthread, JavaThread::jvmti_thread_state_offset()));
 498 #ifdef _LP64
 499     movl(tmp, Address(tmp, JvmtiThreadState::earlyret_tos_offset()));
 500     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), tmp);
 501 #else
 502     pushl(Address(tmp, JvmtiThreadState::earlyret_tos_offset()));
 503     call_VM_leaf(CAST_FROM_FN_PTR(address, Interpreter::remove_activation_early_entry), 1);
 504 #endif // _LP64
 505     jmp(rax);
 506     bind(L);
 507     NOT_LP64(get_thread(java_thread);)
 508   }
 509 }
 510 
 511 void InterpreterMacroAssembler::get_unsigned_2_byte_index_at_bcp(Register reg, int bcp_offset) {
 512   assert(bcp_offset >= 0, "bcp is still pointing to start of bytecode");
 513   load_unsigned_short(reg, Address(_bcp_register, bcp_offset));
 514   bswapl(reg);
 515   shrl(reg, 16);
 516 }
 517 
 518 void InterpreterMacroAssembler::get_cache_index_at_bcp(Register index,
 519                                                        int bcp_offset,
 520                                                        size_t index_size) {
 521   assert(bcp_offset > 0, "bcp is still pointing to start of bytecode");
 522   if (index_size == sizeof(u2)) {
 523     load_unsigned_short(index, Address(_bcp_register, bcp_offset));
 524   } else if (index_size == sizeof(u4)) {
 525     movl(index, Address(_bcp_register, bcp_offset));
 526   } else if (index_size == sizeof(u1)) {
 527     load_unsigned_byte(index, Address(_bcp_register, bcp_offset));
 528   } else {
 529     ShouldNotReachHere();
 530   }
 531 }
 532 
 533 // Load object from cpool->resolved_references(index)
 534 void InterpreterMacroAssembler::load_resolved_reference_at_index(Register result,
 535                                                                  Register index,
 536                                                                  Register tmp) {
 537   assert_different_registers(result, index);
 538 
 539   get_constant_pool(result);
 540   // load pointer for resolved_references[] objArray
 541   movptr(result, Address(result, ConstantPool::cache_offset()));
 542   movptr(result, Address(result, ConstantPoolCache::resolved_references_offset()));
 543   resolve_oop_handle(result, tmp);
 544   load_heap_oop(result, Address(result, index,
 545                                 UseCompressedOops ? Address::times_4 : Address::times_ptr,
 546                                 arrayOopDesc::base_offset_in_bytes(T_OBJECT)), tmp);
 547 }
 548 
 549 // load cpool->resolved_klass_at(index)
 550 void InterpreterMacroAssembler::load_resolved_klass_at_index(Register klass,
 551                                                              Register cpool,
 552                                                              Register index) {
 553   assert_different_registers(cpool, index);
 554 
 555   movw(index, Address(cpool, index, Address::times_ptr, sizeof(ConstantPool)));
 556   Register resolved_klasses = cpool;
 557   movptr(resolved_klasses, Address(cpool, ConstantPool::resolved_klasses_offset()));
 558   movptr(klass, Address(resolved_klasses, index, Address::times_ptr, Array<Klass*>::base_offset_in_bytes()));
 559 }
 560 
 561 // Generate a subtype check: branch to ok_is_subtype if sub_klass is a
 562 // subtype of super_klass.
 563 //
 564 // Args:
 565 //      rax: superklass
 566 //      Rsub_klass: subklass
 567 //
 568 // Kills:
 569 //      rcx, rdi
 570 void InterpreterMacroAssembler::gen_subtype_check(Register Rsub_klass,
 571                                                   Label& ok_is_subtype) {
 572   assert(Rsub_klass != rax, "rax holds superklass");
 573   LP64_ONLY(assert(Rsub_klass != r14, "r14 holds locals");)
 574   LP64_ONLY(assert(Rsub_klass != r13, "r13 holds bcp");)
 575   assert(Rsub_klass != rcx, "rcx holds 2ndary super array length");
 576   assert(Rsub_klass != rdi, "rdi holds 2ndary super array scan ptr");
 577 
 578   // Profile the not-null value's klass.
 579   profile_typecheck(rcx, Rsub_klass, rdi); // blows rcx, reloads rdi
 580 
 581   // Do the check.
 582   check_klass_subtype(Rsub_klass, rax, rcx, ok_is_subtype); // blows rcx
 583 }
 584 
 585 
 586 #ifndef _LP64
 587 void InterpreterMacroAssembler::f2ieee() {
 588   if (IEEEPrecision) {
 589     fstp_s(Address(rsp, 0));
 590     fld_s(Address(rsp, 0));
 591   }
 592 }
 593 
 594 
 595 void InterpreterMacroAssembler::d2ieee() {
 596   if (IEEEPrecision) {
 597     fstp_d(Address(rsp, 0));
 598     fld_d(Address(rsp, 0));
 599   }
 600 }
 601 #endif // _LP64
 602 
 603 // Java Expression Stack
 604 
 605 void InterpreterMacroAssembler::pop_ptr(Register r) {
 606   pop(r);
 607 }
 608 
 609 void InterpreterMacroAssembler::push_ptr(Register r) {
 610   push(r);
 611 }
 612 
 613 void InterpreterMacroAssembler::push_i(Register r) {
 614   push(r);
 615 }
 616 
 617 void InterpreterMacroAssembler::push_i_or_ptr(Register r) {
 618   push(r);
 619 }
 620 
 621 void InterpreterMacroAssembler::push_f(XMMRegister r) {
 622   subptr(rsp, wordSize);
 623   movflt(Address(rsp, 0), r);
 624 }
 625 
 626 void InterpreterMacroAssembler::pop_f(XMMRegister r) {
 627   movflt(r, Address(rsp, 0));
 628   addptr(rsp, wordSize);
 629 }
 630 
 631 void InterpreterMacroAssembler::push_d(XMMRegister r) {
 632   subptr(rsp, 2 * wordSize);
 633   movdbl(Address(rsp, 0), r);
 634 }
 635 
 636 void InterpreterMacroAssembler::pop_d(XMMRegister r) {
 637   movdbl(r, Address(rsp, 0));
 638   addptr(rsp, 2 * Interpreter::stackElementSize);
 639 }
 640 
 641 #ifdef _LP64
 642 void InterpreterMacroAssembler::pop_i(Register r) {
 643   // XXX can't use pop currently, upper half non clean
 644   movl(r, Address(rsp, 0));
 645   addptr(rsp, wordSize);
 646 }
 647 
 648 void InterpreterMacroAssembler::pop_l(Register r) {
 649   movq(r, Address(rsp, 0));
 650   addptr(rsp, 2 * Interpreter::stackElementSize);
 651 }
 652 
 653 void InterpreterMacroAssembler::push_l(Register r) {
 654   subptr(rsp, 2 * wordSize);
 655   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(0)), r         );
 656   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(1)), NULL_WORD );
 657 }
 658 
 659 void InterpreterMacroAssembler::pop(TosState state) {
 660   switch (state) {
 661   case atos: pop_ptr();                 break;
 662   case btos:
 663   case ztos:
 664   case ctos:
 665   case stos:
 666   case itos: pop_i();                   break;
 667   case ltos: pop_l();                   break;
 668   case ftos: pop_f(xmm0);               break;
 669   case dtos: pop_d(xmm0);               break;
 670   case vtos: /* nothing to do */        break;
 671   default:   ShouldNotReachHere();
 672   }
 673   interp_verify_oop(rax, state);
 674 }
 675 
 676 void InterpreterMacroAssembler::push(TosState state) {
 677   interp_verify_oop(rax, state);
 678   switch (state) {
 679   case atos: push_ptr();                break;
 680   case btos:
 681   case ztos:
 682   case ctos:
 683   case stos:
 684   case itos: push_i();                  break;
 685   case ltos: push_l();                  break;
 686   case ftos: push_f(xmm0);              break;
 687   case dtos: push_d(xmm0);              break;
 688   case vtos: /* nothing to do */        break;
 689   default  : ShouldNotReachHere();
 690   }
 691 }
 692 #else
 693 void InterpreterMacroAssembler::pop_i(Register r) {
 694   pop(r);
 695 }
 696 
 697 void InterpreterMacroAssembler::pop_l(Register lo, Register hi) {
 698   pop(lo);
 699   pop(hi);
 700 }
 701 
 702 void InterpreterMacroAssembler::pop_f() {
 703   fld_s(Address(rsp, 0));
 704   addptr(rsp, 1 * wordSize);
 705 }
 706 
 707 void InterpreterMacroAssembler::pop_d() {
 708   fld_d(Address(rsp, 0));
 709   addptr(rsp, 2 * wordSize);
 710 }
 711 
 712 
 713 void InterpreterMacroAssembler::pop(TosState state) {
 714   switch (state) {
 715     case atos: pop_ptr(rax);                                 break;
 716     case btos:                                               // fall through
 717     case ztos:                                               // fall through
 718     case ctos:                                               // fall through
 719     case stos:                                               // fall through
 720     case itos: pop_i(rax);                                   break;
 721     case ltos: pop_l(rax, rdx);                              break;
 722     case ftos:
 723       if (UseSSE >= 1) {
 724         pop_f(xmm0);
 725       } else {
 726         pop_f();
 727       }
 728       break;
 729     case dtos:
 730       if (UseSSE >= 2) {
 731         pop_d(xmm0);
 732       } else {
 733         pop_d();
 734       }
 735       break;
 736     case vtos: /* nothing to do */                           break;
 737     default  : ShouldNotReachHere();
 738   }
 739   interp_verify_oop(rax, state);
 740 }
 741 
 742 
 743 void InterpreterMacroAssembler::push_l(Register lo, Register hi) {
 744   push(hi);
 745   push(lo);
 746 }
 747 
 748 void InterpreterMacroAssembler::push_f() {
 749   // Do not schedule for no AGI! Never write beyond rsp!
 750   subptr(rsp, 1 * wordSize);
 751   fstp_s(Address(rsp, 0));
 752 }
 753 
 754 void InterpreterMacroAssembler::push_d() {
 755   // Do not schedule for no AGI! Never write beyond rsp!
 756   subptr(rsp, 2 * wordSize);
 757   fstp_d(Address(rsp, 0));
 758 }
 759 
 760 
 761 void InterpreterMacroAssembler::push(TosState state) {
 762   interp_verify_oop(rax, state);
 763   switch (state) {
 764     case atos: push_ptr(rax); break;
 765     case btos:                                               // fall through
 766     case ztos:                                               // fall through
 767     case ctos:                                               // fall through
 768     case stos:                                               // fall through
 769     case itos: push_i(rax);                                    break;
 770     case ltos: push_l(rax, rdx);                               break;
 771     case ftos:
 772       if (UseSSE >= 1) {
 773         push_f(xmm0);
 774       } else {
 775         push_f();
 776       }
 777       break;
 778     case dtos:
 779       if (UseSSE >= 2) {
 780         push_d(xmm0);
 781       } else {
 782         push_d();
 783       }
 784       break;
 785     case vtos: /* nothing to do */                             break;
 786     default  : ShouldNotReachHere();
 787   }
 788 }
 789 #endif // _LP64
 790 
 791 
 792 // Helpers for swap and dup
 793 void InterpreterMacroAssembler::load_ptr(int n, Register val) {
 794   movptr(val, Address(rsp, Interpreter::expr_offset_in_bytes(n)));
 795 }
 796 
 797 void InterpreterMacroAssembler::store_ptr(int n, Register val) {
 798   movptr(Address(rsp, Interpreter::expr_offset_in_bytes(n)), val);
 799 }
 800 
 801 
 802 void InterpreterMacroAssembler::prepare_to_jump_from_interpreted() {
 803   // set sender sp
 804   lea(_bcp_register, Address(rsp, wordSize));
 805   // record last_sp
 806   mov(rcx, _bcp_register);
 807   subptr(rcx, rbp);
 808   sarptr(rcx, LogBytesPerWord);
 809   movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), rcx);
 810 }
 811 
 812 
 813 // Jump to from_interpreted entry of a call unless single stepping is possible
 814 // in this thread in which case we must call the i2i entry
 815 void InterpreterMacroAssembler::jump_from_interpreted(Register method, Register temp) {
 816   prepare_to_jump_from_interpreted();
 817 
 818   if (JvmtiExport::can_post_interpreter_events()) {
 819     Label run_compiled_code;
 820     // JVMTI events, such as single-stepping, are implemented partly by avoiding running
 821     // compiled code in threads for which the event is enabled.  Check here for
 822     // interp_only_mode if these events CAN be enabled.
 823     // interp_only is an int, on little endian it is sufficient to test the byte only
 824     // Is a cmpl faster?
 825     LP64_ONLY(temp = r15_thread;)
 826     NOT_LP64(get_thread(temp);)
 827     cmpb(Address(temp, JavaThread::interp_only_mode_offset()), 0);
 828     jccb(Assembler::zero, run_compiled_code);
 829     jmp(Address(method, Method::interpreter_entry_offset()));
 830     bind(run_compiled_code);
 831   }
 832 
 833   jmp(Address(method, Method::from_interpreted_offset()));
 834 }
 835 
 836 // The following two routines provide a hook so that an implementation
 837 // can schedule the dispatch in two parts.  x86 does not do this.
 838 void InterpreterMacroAssembler::dispatch_prolog(TosState state, int step) {
 839   // Nothing x86 specific to be done here
 840 }
 841 
 842 void InterpreterMacroAssembler::dispatch_epilog(TosState state, int step) {
 843   dispatch_next(state, step);
 844 }
 845 
 846 void InterpreterMacroAssembler::dispatch_base(TosState state,
 847                                               address* table,
 848                                               bool verifyoop,
 849                                               bool generate_poll) {
 850   verify_FPU(1, state);
 851   if (VerifyActivationFrameSize) {
 852     Label L;
 853     mov(rcx, rbp);
 854     subptr(rcx, rsp);
 855     int32_t min_frame_size =
 856       (frame::link_offset - frame::interpreter_frame_initial_sp_offset) *
 857       wordSize;
 858     cmpptr(rcx, min_frame_size);
 859     jcc(Assembler::greaterEqual, L);
 860     stop("broken stack frame");
 861     bind(L);
 862   }
 863   if (verifyoop) {
 864     interp_verify_oop(rax, state);
 865   }
 866 
 867   address* const safepoint_table = Interpreter::safept_table(state);
 868 #ifdef _LP64
 869   Label no_safepoint, dispatch;
 870   if (table != safepoint_table && generate_poll) {
 871     NOT_PRODUCT(block_comment("Thread-local Safepoint poll"));
 872     testb(Address(r15_thread, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
 873 
 874     jccb(Assembler::zero, no_safepoint);
 875     lea(rscratch1, ExternalAddress((address)safepoint_table));
 876     jmpb(dispatch);
 877   }
 878 
 879   bind(no_safepoint);
 880   lea(rscratch1, ExternalAddress((address)table));
 881   bind(dispatch);
 882   jmp(Address(rscratch1, rbx, Address::times_8));
 883 
 884 #else
 885   Address index(noreg, rbx, Address::times_ptr);
 886   if (table != safepoint_table && generate_poll) {
 887     NOT_PRODUCT(block_comment("Thread-local Safepoint poll"));
 888     Label no_safepoint;
 889     const Register thread = rcx;
 890     get_thread(thread);
 891     testb(Address(thread, JavaThread::polling_word_offset()), SafepointMechanism::poll_bit());
 892 
 893     jccb(Assembler::zero, no_safepoint);
 894     ArrayAddress dispatch_addr(ExternalAddress((address)safepoint_table), index);
 895     jump(dispatch_addr, noreg);
 896     bind(no_safepoint);
 897   }
 898 
 899   {
 900     ArrayAddress dispatch_addr(ExternalAddress((address)table), index);
 901     jump(dispatch_addr, noreg);
 902   }
 903 #endif // _LP64
 904 }
 905 
 906 void InterpreterMacroAssembler::dispatch_only(TosState state, bool generate_poll) {
 907   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll);
 908 }
 909 
 910 void InterpreterMacroAssembler::dispatch_only_normal(TosState state) {
 911   dispatch_base(state, Interpreter::normal_table(state));
 912 }
 913 
 914 void InterpreterMacroAssembler::dispatch_only_noverify(TosState state) {
 915   dispatch_base(state, Interpreter::normal_table(state), false);
 916 }
 917 
 918 
 919 void InterpreterMacroAssembler::dispatch_next(TosState state, int step, bool generate_poll) {
 920   // load next bytecode (load before advancing _bcp_register to prevent AGI)
 921   load_unsigned_byte(rbx, Address(_bcp_register, step));
 922   // advance _bcp_register
 923   increment(_bcp_register, step);
 924   dispatch_base(state, Interpreter::dispatch_table(state), true, generate_poll);
 925 }
 926 
 927 void InterpreterMacroAssembler::dispatch_via(TosState state, address* table) {
 928   // load current bytecode
 929   load_unsigned_byte(rbx, Address(_bcp_register, 0));
 930   dispatch_base(state, table);
 931 }
 932 
 933 void InterpreterMacroAssembler::narrow(Register result) {
 934 
 935   // Get method->_constMethod->_result_type
 936   movptr(rcx, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
 937   movptr(rcx, Address(rcx, Method::const_offset()));
 938   load_unsigned_byte(rcx, Address(rcx, ConstMethod::result_type_offset()));
 939 
 940   Label done, notBool, notByte, notChar;
 941 
 942   // common case first
 943   cmpl(rcx, T_INT);
 944   jcc(Assembler::equal, done);
 945 
 946   // mask integer result to narrower return type.
 947   cmpl(rcx, T_BOOLEAN);
 948   jcc(Assembler::notEqual, notBool);
 949   andl(result, 0x1);
 950   jmp(done);
 951 
 952   bind(notBool);
 953   cmpl(rcx, T_BYTE);
 954   jcc(Assembler::notEqual, notByte);
 955   LP64_ONLY(movsbl(result, result);)
 956   NOT_LP64(shll(result, 24);)      // truncate upper 24 bits
 957   NOT_LP64(sarl(result, 24);)      // and sign-extend byte
 958   jmp(done);
 959 
 960   bind(notByte);
 961   cmpl(rcx, T_CHAR);
 962   jcc(Assembler::notEqual, notChar);
 963   LP64_ONLY(movzwl(result, result);)
 964   NOT_LP64(andl(result, 0xFFFF);)  // truncate upper 16 bits
 965   jmp(done);
 966 
 967   bind(notChar);
 968   // cmpl(rcx, T_SHORT);  // all that's left
 969   // jcc(Assembler::notEqual, done);
 970   LP64_ONLY(movswl(result, result);)
 971   NOT_LP64(shll(result, 16);)      // truncate upper 16 bits
 972   NOT_LP64(sarl(result, 16);)      // and sign-extend short
 973 
 974   // Nothing to do for T_INT
 975   bind(done);
 976 }
 977 
 978 // remove activation
 979 //
 980 // Apply stack watermark barrier.
 981 // Unlock the receiver if this is a synchronized method.
 982 // Unlock any Java monitors from synchronized blocks.
 983 // Remove the activation from the stack.
 984 //
 985 // If there are locked Java monitors
 986 //    If throw_monitor_exception
 987 //       throws IllegalMonitorStateException
 988 //    Else if install_monitor_exception
 989 //       installs IllegalMonitorStateException
 990 //    Else
 991 //       no error processing
 992 void InterpreterMacroAssembler::remove_activation(
 993         TosState state,
 994         Register ret_addr,
 995         bool throw_monitor_exception,
 996         bool install_monitor_exception,
 997         bool notify_jvmdi) {
 998   // Note: Registers rdx xmm0 may be in use for the
 999   // result check if synchronized method
1000   Label unlocked, unlock, no_unlock;
1001 
1002   const Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1003   const Register robj    = LP64_ONLY(c_rarg1) NOT_LP64(rdx);
1004   const Register rmon    = LP64_ONLY(c_rarg1) NOT_LP64(rcx);
1005                               // monitor pointers need different register
1006                               // because rdx may have the result in it
1007   NOT_LP64(get_thread(rthread);)
1008 
1009   // The below poll is for the stack watermark barrier. It allows fixing up frames lazily,
1010   // that would normally not be safe to use. Such bad returns into unsafe territory of
1011   // the stack, will call InterpreterRuntime::at_unwind.
1012   Label slow_path;
1013   Label fast_path;
1014   safepoint_poll(slow_path, rthread, true /* at_return */, false /* in_nmethod */);
1015   jmp(fast_path);
1016   bind(slow_path);
1017   push(state);
1018   set_last_Java_frame(rthread, noreg, rbp, (address)pc(), rscratch1);
1019   super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), rthread);
1020   NOT_LP64(get_thread(rthread);) // call_VM clobbered it, restore
1021   reset_last_Java_frame(rthread, true);
1022   pop(state);
1023   bind(fast_path);
1024 
1025   // get the value of _do_not_unlock_if_synchronized into rdx
1026   const Address do_not_unlock_if_synchronized(rthread,
1027     in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1028   movbool(rbx, do_not_unlock_if_synchronized);
1029   movbool(do_not_unlock_if_synchronized, false); // reset the flag
1030 
1031  // get method access flags
1032   movptr(rcx, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
1033   movl(rcx, Address(rcx, Method::access_flags_offset()));
1034   testl(rcx, JVM_ACC_SYNCHRONIZED);
1035   jcc(Assembler::zero, unlocked);
1036 
1037   // Don't unlock anything if the _do_not_unlock_if_synchronized flag
1038   // is set.
1039   testbool(rbx);
1040   jcc(Assembler::notZero, no_unlock);
1041 
1042   // unlock monitor
1043   push(state); // save result
1044 
1045   // BasicObjectLock will be first in list, since this is a
1046   // synchronized method. However, need to check that the object has
1047   // not been unlocked by an explicit monitorexit bytecode.
1048   const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset *
1049                         wordSize - (int) sizeof(BasicObjectLock));
1050   // We use c_rarg1/rdx so that if we go slow path it will be the correct
1051   // register for unlock_object to pass to VM directly
1052   lea(robj, monitor); // address of first monitor
1053 
1054   movptr(rax, Address(robj, BasicObjectLock::obj_offset()));
1055   testptr(rax, rax);
1056   jcc(Assembler::notZero, unlock);
1057 
1058   pop(state);
1059   if (throw_monitor_exception) {
1060     // Entry already unlocked, need to throw exception
1061     NOT_LP64(empty_FPU_stack();)  // remove possible return value from FPU-stack, otherwise stack could overflow
1062     call_VM(noreg, CAST_FROM_FN_PTR(address,
1063                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1064     should_not_reach_here();
1065   } else {
1066     // Monitor already unlocked during a stack unroll. If requested,
1067     // install an illegal_monitor_state_exception.  Continue with
1068     // stack unrolling.
1069     if (install_monitor_exception) {
1070       NOT_LP64(empty_FPU_stack();)
1071       call_VM(noreg, CAST_FROM_FN_PTR(address,
1072                      InterpreterRuntime::new_illegal_monitor_state_exception));
1073     }
1074     jmp(unlocked);
1075   }
1076 
1077   bind(unlock);
1078   unlock_object(robj);
1079   pop(state);
1080 
1081   // Check that for block-structured locking (i.e., that all locked
1082   // objects has been unlocked)
1083   bind(unlocked);
1084 
1085   // rax, rdx: Might contain return value
1086 
1087   // Check that all monitors are unlocked
1088   {
1089     Label loop, exception, entry, restart;
1090     const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
1091     const Address monitor_block_top(
1092         rbp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
1093     const Address monitor_block_bot(
1094         rbp, frame::interpreter_frame_initial_sp_offset * wordSize);
1095 
1096     bind(restart);
1097     // We use c_rarg1 so that if we go slow path it will be the correct
1098     // register for unlock_object to pass to VM directly
1099     movptr(rmon, monitor_block_top); // derelativize pointer
1100     lea(rmon, Address(rbp, rmon, Address::times_ptr));
1101     // c_rarg1 points to current entry, starting with top-most entry
1102 
1103     lea(rbx, monitor_block_bot);  // points to word before bottom of
1104                                   // monitor block
1105     jmp(entry);
1106 
1107     // Entry already locked, need to throw exception
1108     bind(exception);
1109 
1110     if (throw_monitor_exception) {
1111       // Throw exception
1112       NOT_LP64(empty_FPU_stack();)
1113       MacroAssembler::call_VM(noreg,
1114                               CAST_FROM_FN_PTR(address, InterpreterRuntime::
1115                                    throw_illegal_monitor_state_exception));
1116       should_not_reach_here();
1117     } else {
1118       // Stack unrolling. Unlock object and install illegal_monitor_exception.
1119       // Unlock does not block, so don't have to worry about the frame.
1120       // We don't have to preserve c_rarg1 since we are going to throw an exception.
1121 
1122       push(state);
1123       mov(robj, rmon);   // nop if robj and rmon are the same
1124       unlock_object(robj);
1125       pop(state);
1126 
1127       if (install_monitor_exception) {
1128         NOT_LP64(empty_FPU_stack();)
1129         call_VM(noreg, CAST_FROM_FN_PTR(address,
1130                                         InterpreterRuntime::
1131                                         new_illegal_monitor_state_exception));
1132       }
1133 
1134       jmp(restart);
1135     }
1136 
1137     bind(loop);
1138     // check if current entry is used
1139     cmpptr(Address(rmon, BasicObjectLock::obj_offset()), NULL_WORD);
1140     jcc(Assembler::notEqual, exception);
1141 
1142     addptr(rmon, entry_size); // otherwise advance to next entry
1143     bind(entry);
1144     cmpptr(rmon, rbx); // check if bottom reached
1145     jcc(Assembler::notEqual, loop); // if not at bottom then check this entry
1146   }
1147 
1148   bind(no_unlock);
1149 
1150   // jvmti support
1151   if (notify_jvmdi) {
1152     notify_method_exit(state, NotifyJVMTI);    // preserve TOSCA
1153   } else {
1154     notify_method_exit(state, SkipNotifyJVMTI); // preserve TOSCA
1155   }
1156 
1157   // remove activation
1158   // get sender sp
1159   movptr(rbx,
1160          Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize));
1161   if (StackReservedPages > 0) {
1162     // testing if reserved zone needs to be re-enabled
1163     Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1164     Label no_reserved_zone_enabling;
1165 
1166     NOT_LP64(get_thread(rthread);)
1167 
1168     // check if already enabled - if so no re-enabling needed
1169     assert(sizeof(StackOverflow::StackGuardState) == 4, "unexpected size");
1170     cmpl(Address(rthread, JavaThread::stack_guard_state_offset()), StackOverflow::stack_guard_enabled);
1171     jcc(Assembler::equal, no_reserved_zone_enabling);
1172 
1173     cmpptr(rbx, Address(rthread, JavaThread::reserved_stack_activation_offset()));
1174     jcc(Assembler::lessEqual, no_reserved_zone_enabling);
1175 
1176     call_VM_leaf(
1177       CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), rthread);
1178     call_VM(noreg, CAST_FROM_FN_PTR(address,
1179                    InterpreterRuntime::throw_delayed_StackOverflowError));
1180     should_not_reach_here();
1181 
1182     bind(no_reserved_zone_enabling);
1183   }
1184   leave();                           // remove frame anchor
1185   pop(ret_addr);                     // get return address
1186   mov(rsp, rbx);                     // set sp to sender sp
1187   pop_cont_fastpath();
1188 }
1189 
1190 void InterpreterMacroAssembler::get_method_counters(Register method,
1191                                                     Register mcs, Label& skip) {
1192   Label has_counters;
1193   movptr(mcs, Address(method, Method::method_counters_offset()));
1194   testptr(mcs, mcs);
1195   jcc(Assembler::notZero, has_counters);
1196   call_VM(noreg, CAST_FROM_FN_PTR(address,
1197           InterpreterRuntime::build_method_counters), method);
1198   movptr(mcs, Address(method,Method::method_counters_offset()));
1199   testptr(mcs, mcs);
1200   jcc(Assembler::zero, skip); // No MethodCounters allocated, OutOfMemory
1201   bind(has_counters);
1202 }
1203 
1204 
1205 // Lock object
1206 //
1207 // Args:
1208 //      rdx, c_rarg1: BasicObjectLock to be used for locking
1209 //
1210 // Kills:
1211 //      rax, rbx
1212 void InterpreterMacroAssembler::lock_object(Register lock_reg) {
1213   assert(lock_reg == LP64_ONLY(c_rarg1) NOT_LP64(rdx),
1214          "The argument is only for looks. It must be c_rarg1");
1215 
1216   if (LockingMode == LM_MONITOR) {
1217     call_VM_preemptable(noreg,
1218             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1219             lock_reg);
1220   } else {
1221     Label count_locking, done, slow_case;
1222 
1223     const Register swap_reg = rax; // Must use rax for cmpxchg instruction
1224     const Register tmp_reg = rbx;
1225     const Register obj_reg = LP64_ONLY(c_rarg3) NOT_LP64(rcx); // Will contain the oop
1226     const Register rklass_decode_tmp = rscratch1;
1227 
1228     const int obj_offset = in_bytes(BasicObjectLock::obj_offset());
1229     const int lock_offset = in_bytes(BasicObjectLock::lock_offset());
1230     const int mark_offset = lock_offset +
1231                             BasicLock::displaced_header_offset_in_bytes();
1232 
1233     // Load object pointer into obj_reg
1234     movptr(obj_reg, Address(lock_reg, obj_offset));
1235 
1236     if (DiagnoseSyncOnValueBasedClasses != 0) {
1237       load_klass(tmp_reg, obj_reg, rklass_decode_tmp);
1238       testb(Address(tmp_reg, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
1239       jcc(Assembler::notZero, slow_case);
1240     }
1241 
1242     if (LockingMode == LM_LIGHTWEIGHT) {
1243 #ifdef _LP64
1244       const Register thread = r15_thread;
1245       lightweight_lock(lock_reg, obj_reg, swap_reg, thread, tmp_reg, slow_case);
1246 #else
1247       // Lacking registers and thread on x86_32. Always take slow path.
1248       jmp(slow_case);
1249 #endif
1250     } else if (LockingMode == LM_LEGACY) {
1251       // Load immediate 1 into swap_reg %rax
1252       movl(swap_reg, 1);
1253 
1254       // Load (object->mark() | 1) into swap_reg %rax
1255       orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1256 
1257       // Save (object->mark() | 1) into BasicLock's displaced header
1258       movptr(Address(lock_reg, mark_offset), swap_reg);
1259 
1260       assert(lock_offset == 0,
1261              "displaced header must be first word in BasicObjectLock");
1262 
1263       lock();
1264       cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1265       jcc(Assembler::zero, count_locking);
1266 
1267       const int zero_bits = LP64_ONLY(7) NOT_LP64(3);
1268 
1269       // Fast check for recursive lock.
1270       //
1271       // Can apply the optimization only if this is a stack lock
1272       // allocated in this thread. For efficiency, we can focus on
1273       // recently allocated stack locks (instead of reading the stack
1274       // base and checking whether 'mark' points inside the current
1275       // thread stack):
1276       //  1) (mark & zero_bits) == 0, and
1277       //  2) rsp <= mark < mark + os::pagesize()
1278       //
1279       // Warning: rsp + os::pagesize can overflow the stack base. We must
1280       // neither apply the optimization for an inflated lock allocated
1281       // just above the thread stack (this is why condition 1 matters)
1282       // nor apply the optimization if the stack lock is inside the stack
1283       // of another thread. The latter is avoided even in case of overflow
1284       // because we have guard pages at the end of all stacks. Hence, if
1285       // we go over the stack base and hit the stack of another thread,
1286       // this should not be in a writeable area that could contain a
1287       // stack lock allocated by that thread. As a consequence, a stack
1288       // lock less than page size away from rsp is guaranteed to be
1289       // owned by the current thread.
1290       //
1291       // These 3 tests can be done by evaluating the following
1292       // expression: ((mark - rsp) & (zero_bits - os::vm_page_size())),
1293       // assuming both stack pointer and pagesize have their
1294       // least significant bits clear.
1295       // NOTE: the mark is in swap_reg %rax as the result of cmpxchg
1296       subptr(swap_reg, rsp);
1297       andptr(swap_reg, zero_bits - (int)os::vm_page_size());
1298 
1299       // Save the test result, for recursive case, the result is zero
1300       movptr(Address(lock_reg, mark_offset), swap_reg);
1301       jcc(Assembler::notZero, slow_case);
1302 
1303       bind(count_locking);
1304       inc_held_monitor_count();
1305     }
1306     jmp(done);
1307 
1308     bind(slow_case);
1309 
1310     // Call the runtime routine for slow case
1311     call_VM_preemptable(noreg,
1312             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1313             lock_reg);
1314     bind(done);
1315   }
1316 }
1317 
1318 
1319 // Unlocks an object. Used in monitorexit bytecode and
1320 // remove_activation.  Throws an IllegalMonitorException if object is
1321 // not locked by current thread.
1322 //
1323 // Args:
1324 //      rdx, c_rarg1: BasicObjectLock for lock
1325 //
1326 // Kills:
1327 //      rax
1328 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ... (param regs)
1329 //      rscratch1 (scratch reg)
1330 // rax, rbx, rcx, rdx
1331 void InterpreterMacroAssembler::unlock_object(Register lock_reg) {
1332   assert(lock_reg == LP64_ONLY(c_rarg1) NOT_LP64(rdx),
1333          "The argument is only for looks. It must be c_rarg1");
1334 
1335   if (LockingMode == LM_MONITOR) {
1336     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1337   } else {
1338     Label count_locking, done, slow_case;
1339 
1340     const Register swap_reg   = rax;  // Must use rax for cmpxchg instruction
1341     const Register header_reg = LP64_ONLY(c_rarg2) NOT_LP64(rbx);  // Will contain the old oopMark
1342     const Register obj_reg    = LP64_ONLY(c_rarg3) NOT_LP64(rcx);  // Will contain the oop
1343 
1344     save_bcp(); // Save in case of exception
1345 
1346     if (LockingMode != LM_LIGHTWEIGHT) {
1347       // Convert from BasicObjectLock structure to object and BasicLock
1348       // structure Store the BasicLock address into %rax
1349       lea(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset()));
1350     }
1351 
1352     // Load oop into obj_reg(%c_rarg3)
1353     movptr(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset()));
1354 
1355     // Free entry
1356     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), NULL_WORD);
1357 
1358     if (LockingMode == LM_LIGHTWEIGHT) {
1359 #ifdef _LP64
1360       lightweight_unlock(obj_reg, swap_reg, r15_thread, header_reg, slow_case);
1361 #else
1362       // Lacking registers and thread on x86_32. Always take slow path.
1363       jmp(slow_case);
1364 #endif
1365     } else if (LockingMode == LM_LEGACY) {
1366       // Load the old header from BasicLock structure
1367       movptr(header_reg, Address(swap_reg,
1368                                  BasicLock::displaced_header_offset_in_bytes()));
1369 
1370       // Test for recursion
1371       testptr(header_reg, header_reg);
1372 
1373       // zero for recursive case
1374       jcc(Assembler::zero, count_locking);
1375 
1376       // Atomic swap back the old header
1377       lock();
1378       cmpxchgptr(header_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1379 
1380       // zero for simple unlock of a stack-lock case
1381       jcc(Assembler::notZero, slow_case);
1382 
1383       bind(count_locking);
1384       dec_held_monitor_count();
1385     }
1386     jmp(done);
1387 
1388     bind(slow_case);
1389     // Call the runtime routine for slow case.
1390     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), obj_reg); // restore obj
1391     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1392 
1393     bind(done);
1394 
1395     restore_bcp();
1396   }
1397 }
1398 
1399 void InterpreterMacroAssembler::test_method_data_pointer(Register mdp,
1400                                                          Label& zero_continue) {
1401   assert(ProfileInterpreter, "must be profiling interpreter");
1402   movptr(mdp, Address(rbp, frame::interpreter_frame_mdp_offset * wordSize));
1403   testptr(mdp, mdp);
1404   jcc(Assembler::zero, zero_continue);
1405 }
1406 
1407 
1408 // Set the method data pointer for the current bcp.
1409 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1410   assert(ProfileInterpreter, "must be profiling interpreter");
1411   Label set_mdp;
1412   push(rax);
1413   push(rbx);
1414 
1415   get_method(rbx);
1416   // Test MDO to avoid the call if it is null.
1417   movptr(rax, Address(rbx, in_bytes(Method::method_data_offset())));
1418   testptr(rax, rax);
1419   jcc(Assembler::zero, set_mdp);
1420   // rbx: method
1421   // _bcp_register: bcp
1422   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), rbx, _bcp_register);
1423   // rax: mdi
1424   // mdo is guaranteed to be non-zero here, we checked for it before the call.
1425   movptr(rbx, Address(rbx, in_bytes(Method::method_data_offset())));
1426   addptr(rbx, in_bytes(MethodData::data_offset()));
1427   addptr(rax, rbx);
1428   bind(set_mdp);
1429   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), rax);
1430   pop(rbx);
1431   pop(rax);
1432 }
1433 
1434 void InterpreterMacroAssembler::verify_method_data_pointer() {
1435   assert(ProfileInterpreter, "must be profiling interpreter");
1436 #ifdef ASSERT
1437   Label verify_continue;
1438   push(rax);
1439   push(rbx);
1440   Register arg3_reg = LP64_ONLY(c_rarg3) NOT_LP64(rcx);
1441   Register arg2_reg = LP64_ONLY(c_rarg2) NOT_LP64(rdx);
1442   push(arg3_reg);
1443   push(arg2_reg);
1444   test_method_data_pointer(arg3_reg, verify_continue); // If mdp is zero, continue
1445   get_method(rbx);
1446 
1447   // If the mdp is valid, it will point to a DataLayout header which is
1448   // consistent with the bcp.  The converse is highly probable also.
1449   load_unsigned_short(arg2_reg,
1450                       Address(arg3_reg, in_bytes(DataLayout::bci_offset())));
1451   addptr(arg2_reg, Address(rbx, Method::const_offset()));
1452   lea(arg2_reg, Address(arg2_reg, ConstMethod::codes_offset()));
1453   cmpptr(arg2_reg, _bcp_register);
1454   jcc(Assembler::equal, verify_continue);
1455   // rbx: method
1456   // _bcp_register: bcp
1457   // c_rarg3: mdp
1458   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp),
1459                rbx, _bcp_register, arg3_reg);
1460   bind(verify_continue);
1461   pop(arg2_reg);
1462   pop(arg3_reg);
1463   pop(rbx);
1464   pop(rax);
1465 #endif // ASSERT
1466 }
1467 
1468 
1469 void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in,
1470                                                 int constant,
1471                                                 Register value) {
1472   assert(ProfileInterpreter, "must be profiling interpreter");
1473   Address data(mdp_in, constant);
1474   movptr(data, value);
1475 }
1476 
1477 
1478 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1479                                                       int constant,
1480                                                       bool decrement) {
1481   // Counter address
1482   Address data(mdp_in, constant);
1483 
1484   increment_mdp_data_at(data, decrement);
1485 }
1486 
1487 void InterpreterMacroAssembler::increment_mdp_data_at(Address data,
1488                                                       bool decrement) {
1489   assert(ProfileInterpreter, "must be profiling interpreter");
1490   // %%% this does 64bit counters at best it is wasting space
1491   // at worst it is a rare bug when counters overflow
1492 
1493   if (decrement) {
1494     // Decrement the register.  Set condition codes.
1495     addptr(data, -DataLayout::counter_increment);
1496     // If the decrement causes the counter to overflow, stay negative
1497     Label L;
1498     jcc(Assembler::negative, L);
1499     addptr(data, DataLayout::counter_increment);
1500     bind(L);
1501   } else {
1502     assert(DataLayout::counter_increment == 1,
1503            "flow-free idiom only works with 1");
1504     // Increment the register.  Set carry flag.
1505     addptr(data, DataLayout::counter_increment);
1506     // If the increment causes the counter to overflow, pull back by 1.
1507     sbbptr(data, 0);
1508   }
1509 }
1510 
1511 
1512 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1513                                                       Register reg,
1514                                                       int constant,
1515                                                       bool decrement) {
1516   Address data(mdp_in, reg, Address::times_1, constant);
1517 
1518   increment_mdp_data_at(data, decrement);
1519 }
1520 
1521 void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1522                                                 int flag_byte_constant) {
1523   assert(ProfileInterpreter, "must be profiling interpreter");
1524   int header_offset = in_bytes(DataLayout::flags_offset());
1525   int header_bits = flag_byte_constant;
1526   // Set the flag
1527   orb(Address(mdp_in, header_offset), header_bits);
1528 }
1529 
1530 
1531 
1532 void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1533                                                  int offset,
1534                                                  Register value,
1535                                                  Register test_value_out,
1536                                                  Label& not_equal_continue) {
1537   assert(ProfileInterpreter, "must be profiling interpreter");
1538   if (test_value_out == noreg) {
1539     cmpptr(value, Address(mdp_in, offset));
1540   } else {
1541     // Put the test value into a register, so caller can use it:
1542     movptr(test_value_out, Address(mdp_in, offset));
1543     cmpptr(test_value_out, value);
1544   }
1545   jcc(Assembler::notEqual, not_equal_continue);
1546 }
1547 
1548 
1549 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1550                                                      int offset_of_disp) {
1551   assert(ProfileInterpreter, "must be profiling interpreter");
1552   Address disp_address(mdp_in, offset_of_disp);
1553   addptr(mdp_in, disp_address);
1554   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1555 }
1556 
1557 
1558 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1559                                                      Register reg,
1560                                                      int offset_of_disp) {
1561   assert(ProfileInterpreter, "must be profiling interpreter");
1562   Address disp_address(mdp_in, reg, Address::times_1, offset_of_disp);
1563   addptr(mdp_in, disp_address);
1564   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1565 }
1566 
1567 
1568 void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in,
1569                                                        int constant) {
1570   assert(ProfileInterpreter, "must be profiling interpreter");
1571   addptr(mdp_in, constant);
1572   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1573 }
1574 
1575 
1576 void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1577   assert(ProfileInterpreter, "must be profiling interpreter");
1578   push(return_bci); // save/restore across call_VM
1579   call_VM(noreg,
1580           CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1581           return_bci);
1582   pop(return_bci);
1583 }
1584 
1585 
1586 void InterpreterMacroAssembler::profile_taken_branch(Register mdp,
1587                                                      Register bumped_count) {
1588   if (ProfileInterpreter) {
1589     Label profile_continue;
1590 
1591     // If no method data exists, go to profile_continue.
1592     // Otherwise, assign to mdp
1593     test_method_data_pointer(mdp, profile_continue);
1594 
1595     // We are taking a branch.  Increment the taken count.
1596     // We inline increment_mdp_data_at to return bumped_count in a register
1597     //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset()));
1598     Address data(mdp, in_bytes(JumpData::taken_offset()));
1599     movptr(bumped_count, data);
1600     assert(DataLayout::counter_increment == 1,
1601             "flow-free idiom only works with 1");
1602     addptr(bumped_count, DataLayout::counter_increment);
1603     sbbptr(bumped_count, 0);
1604     movptr(data, bumped_count); // Store back out
1605 
1606     // The method data pointer needs to be updated to reflect the new target.
1607     update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1608     bind(profile_continue);
1609   }
1610 }
1611 
1612 
1613 void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp) {
1614   if (ProfileInterpreter) {
1615     Label profile_continue;
1616 
1617     // If no method data exists, go to profile_continue.
1618     test_method_data_pointer(mdp, profile_continue);
1619 
1620     // We are taking a branch.  Increment the not taken count.
1621     increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()));
1622 
1623     // The method data pointer needs to be updated to correspond to
1624     // the next bytecode
1625     update_mdp_by_constant(mdp, in_bytes(BranchData::branch_data_size()));
1626     bind(profile_continue);
1627   }
1628 }
1629 
1630 void InterpreterMacroAssembler::profile_call(Register mdp) {
1631   if (ProfileInterpreter) {
1632     Label profile_continue;
1633 
1634     // If no method data exists, go to profile_continue.
1635     test_method_data_pointer(mdp, profile_continue);
1636 
1637     // We are making a call.  Increment the count.
1638     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1639 
1640     // The method data pointer needs to be updated to reflect the new target.
1641     update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1642     bind(profile_continue);
1643   }
1644 }
1645 
1646 
1647 void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1648   if (ProfileInterpreter) {
1649     Label profile_continue;
1650 
1651     // If no method data exists, go to profile_continue.
1652     test_method_data_pointer(mdp, profile_continue);
1653 
1654     // We are making a call.  Increment the count.
1655     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1656 
1657     // The method data pointer needs to be updated to reflect the new target.
1658     update_mdp_by_constant(mdp,
1659                            in_bytes(VirtualCallData::
1660                                     virtual_call_data_size()));
1661     bind(profile_continue);
1662   }
1663 }
1664 
1665 
1666 void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1667                                                      Register mdp,
1668                                                      Register reg2,
1669                                                      bool receiver_can_be_null) {
1670   if (ProfileInterpreter) {
1671     Label profile_continue;
1672 
1673     // If no method data exists, go to profile_continue.
1674     test_method_data_pointer(mdp, profile_continue);
1675 
1676     Label skip_receiver_profile;
1677     if (receiver_can_be_null) {
1678       Label not_null;
1679       testptr(receiver, receiver);
1680       jccb(Assembler::notZero, not_null);
1681       // We are making a call.  Increment the count for null receiver.
1682       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1683       jmp(skip_receiver_profile);
1684       bind(not_null);
1685     }
1686 
1687     // Record the receiver type.
1688     record_klass_in_profile(receiver, mdp, reg2, true);
1689     bind(skip_receiver_profile);
1690 
1691     // The method data pointer needs to be updated to reflect the new target.
1692     update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1693     bind(profile_continue);
1694   }
1695 }
1696 
1697 // This routine creates a state machine for updating the multi-row
1698 // type profile at a virtual call site (or other type-sensitive bytecode).
1699 // The machine visits each row (of receiver/count) until the receiver type
1700 // is found, or until it runs out of rows.  At the same time, it remembers
1701 // the location of the first empty row.  (An empty row records null for its
1702 // receiver, and can be allocated for a newly-observed receiver type.)
1703 // Because there are two degrees of freedom in the state, a simple linear
1704 // search will not work; it must be a decision tree.  Hence this helper
1705 // function is recursive, to generate the required tree structured code.
1706 // It's the interpreter, so we are trading off code space for speed.
1707 // See below for example code.
1708 void InterpreterMacroAssembler::record_klass_in_profile_helper(
1709                                         Register receiver, Register mdp,
1710                                         Register reg2, int start_row,
1711                                         Label& done, bool is_virtual_call) {
1712   if (TypeProfileWidth == 0) {
1713     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1714   } else {
1715     record_item_in_profile_helper(receiver, mdp, reg2, 0, done, TypeProfileWidth,
1716                                   &VirtualCallData::receiver_offset, &VirtualCallData::receiver_count_offset);
1717   }
1718 }
1719 
1720 void InterpreterMacroAssembler::record_item_in_profile_helper(Register item, Register mdp, Register reg2, int start_row,
1721                                                               Label& done, int total_rows,
1722                                                               OffsetFunction item_offset_fn,
1723                                                               OffsetFunction item_count_offset_fn) {
1724   int last_row = total_rows - 1;
1725   assert(start_row <= last_row, "must be work left to do");
1726   // Test this row for both the item and for null.
1727   // Take any of three different outcomes:
1728   //   1. found item => increment count and goto done
1729   //   2. found null => keep looking for case 1, maybe allocate this cell
1730   //   3. found something else => keep looking for cases 1 and 2
1731   // Case 3 is handled by a recursive call.
1732   for (int row = start_row; row <= last_row; row++) {
1733     Label next_test;
1734     bool test_for_null_also = (row == start_row);
1735 
1736     // See if the item is item[n].
1737     int item_offset = in_bytes(item_offset_fn(row));
1738     test_mdp_data_at(mdp, item_offset, item,
1739                      (test_for_null_also ? reg2 : noreg),
1740                      next_test);
1741     // (Reg2 now contains the item from the CallData.)
1742 
1743     // The item is item[n].  Increment count[n].
1744     int count_offset = in_bytes(item_count_offset_fn(row));
1745     increment_mdp_data_at(mdp, count_offset);
1746     jmp(done);
1747     bind(next_test);
1748 
1749     if (test_for_null_also) {
1750       // Failed the equality check on item[n]...  Test for null.
1751       testptr(reg2, reg2);
1752       if (start_row == last_row) {
1753         // The only thing left to do is handle the null case.
1754         Label found_null;
1755         jccb(Assembler::zero, found_null);
1756         // Item did not match any saved item and there is no empty row for it.
1757         // Increment total counter to indicate polymorphic case.
1758         increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1759         jmp(done);
1760         bind(found_null);
1761         break;
1762       }
1763       Label found_null;
1764       // Since null is rare, make it be the branch-taken case.
1765       jcc(Assembler::zero, found_null);
1766 
1767       // Put all the "Case 3" tests here.
1768       record_item_in_profile_helper(item, mdp, reg2, start_row + 1, done, total_rows,
1769                                     item_offset_fn, item_count_offset_fn);
1770 
1771       // Found a null.  Keep searching for a matching item,
1772       // but remember that this is an empty (unused) slot.
1773       bind(found_null);
1774     }
1775   }
1776 
1777   // In the fall-through case, we found no matching item, but we
1778   // observed the item[start_row] is null.
1779 
1780   // Fill in the item field and increment the count.
1781   int item_offset = in_bytes(item_offset_fn(start_row));
1782   set_mdp_data_at(mdp, item_offset, item);
1783   int count_offset = in_bytes(item_count_offset_fn(start_row));
1784   movl(reg2, DataLayout::counter_increment);
1785   set_mdp_data_at(mdp, count_offset, reg2);
1786   if (start_row > 0) {
1787     jmp(done);
1788   }
1789 }
1790 
1791 // Example state machine code for three profile rows:
1792 //   // main copy of decision tree, rooted at row[1]
1793 //   if (row[0].rec == rec) { row[0].incr(); goto done; }
1794 //   if (row[0].rec != nullptr) {
1795 //     // inner copy of decision tree, rooted at row[1]
1796 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1797 //     if (row[1].rec != nullptr) {
1798 //       // degenerate decision tree, rooted at row[2]
1799 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1800 //       if (row[2].rec != nullptr) { count.incr(); goto done; } // overflow
1801 //       row[2].init(rec); goto done;
1802 //     } else {
1803 //       // remember row[1] is empty
1804 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1805 //       row[1].init(rec); goto done;
1806 //     }
1807 //   } else {
1808 //     // remember row[0] is empty
1809 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1810 //     if (row[2].rec == rec) { row[2].incr(); goto done; }
1811 //     row[0].init(rec); goto done;
1812 //   }
1813 //   done:
1814 
1815 void InterpreterMacroAssembler::record_klass_in_profile(Register receiver,
1816                                                         Register mdp, Register reg2,
1817                                                         bool is_virtual_call) {
1818   assert(ProfileInterpreter, "must be profiling");
1819   Label done;
1820 
1821   record_klass_in_profile_helper(receiver, mdp, reg2, 0, done, is_virtual_call);
1822 
1823   bind (done);
1824 }
1825 
1826 void InterpreterMacroAssembler::profile_ret(Register return_bci,
1827                                             Register mdp) {
1828   if (ProfileInterpreter) {
1829     Label profile_continue;
1830     uint row;
1831 
1832     // If no method data exists, go to profile_continue.
1833     test_method_data_pointer(mdp, profile_continue);
1834 
1835     // Update the total ret count.
1836     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1837 
1838     for (row = 0; row < RetData::row_limit(); row++) {
1839       Label next_test;
1840 
1841       // See if return_bci is equal to bci[n]:
1842       test_mdp_data_at(mdp,
1843                        in_bytes(RetData::bci_offset(row)),
1844                        return_bci, noreg,
1845                        next_test);
1846 
1847       // return_bci is equal to bci[n].  Increment the count.
1848       increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1849 
1850       // The method data pointer needs to be updated to reflect the new target.
1851       update_mdp_by_offset(mdp,
1852                            in_bytes(RetData::bci_displacement_offset(row)));
1853       jmp(profile_continue);
1854       bind(next_test);
1855     }
1856 
1857     update_mdp_for_ret(return_bci);
1858 
1859     bind(profile_continue);
1860   }
1861 }
1862 
1863 
1864 void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1865   if (ProfileInterpreter) {
1866     Label profile_continue;
1867 
1868     // If no method data exists, go to profile_continue.
1869     test_method_data_pointer(mdp, profile_continue);
1870 
1871     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1872 
1873     // The method data pointer needs to be updated.
1874     int mdp_delta = in_bytes(BitData::bit_data_size());
1875     if (TypeProfileCasts) {
1876       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1877     }
1878     update_mdp_by_constant(mdp, mdp_delta);
1879 
1880     bind(profile_continue);
1881   }
1882 }
1883 
1884 
1885 void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1886   if (ProfileInterpreter) {
1887     Label profile_continue;
1888 
1889     // If no method data exists, go to profile_continue.
1890     test_method_data_pointer(mdp, profile_continue);
1891 
1892     // The method data pointer needs to be updated.
1893     int mdp_delta = in_bytes(BitData::bit_data_size());
1894     if (TypeProfileCasts) {
1895       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1896 
1897       // Record the object type.
1898       record_klass_in_profile(klass, mdp, reg2, false);
1899       NOT_LP64(assert(reg2 == rdi, "we know how to fix this blown reg");)
1900       NOT_LP64(restore_locals();)         // Restore EDI
1901     }
1902     update_mdp_by_constant(mdp, mdp_delta);
1903 
1904     bind(profile_continue);
1905   }
1906 }
1907 
1908 
1909 void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1910   if (ProfileInterpreter) {
1911     Label profile_continue;
1912 
1913     // If no method data exists, go to profile_continue.
1914     test_method_data_pointer(mdp, profile_continue);
1915 
1916     // Update the default case count
1917     increment_mdp_data_at(mdp,
1918                           in_bytes(MultiBranchData::default_count_offset()));
1919 
1920     // The method data pointer needs to be updated.
1921     update_mdp_by_offset(mdp,
1922                          in_bytes(MultiBranchData::
1923                                   default_displacement_offset()));
1924 
1925     bind(profile_continue);
1926   }
1927 }
1928 
1929 
1930 void InterpreterMacroAssembler::profile_switch_case(Register index,
1931                                                     Register mdp,
1932                                                     Register reg2) {
1933   if (ProfileInterpreter) {
1934     Label profile_continue;
1935 
1936     // If no method data exists, go to profile_continue.
1937     test_method_data_pointer(mdp, profile_continue);
1938 
1939     // Build the base (index * per_case_size_in_bytes()) +
1940     // case_array_offset_in_bytes()
1941     movl(reg2, in_bytes(MultiBranchData::per_case_size()));
1942     imulptr(index, reg2); // XXX l ?
1943     addptr(index, in_bytes(MultiBranchData::case_array_offset())); // XXX l ?
1944 
1945     // Update the case count
1946     increment_mdp_data_at(mdp,
1947                           index,
1948                           in_bytes(MultiBranchData::relative_count_offset()));
1949 
1950     // The method data pointer needs to be updated.
1951     update_mdp_by_offset(mdp,
1952                          index,
1953                          in_bytes(MultiBranchData::
1954                                   relative_displacement_offset()));
1955 
1956     bind(profile_continue);
1957   }
1958 }
1959 
1960 
1961 
1962 void InterpreterMacroAssembler::_interp_verify_oop(Register reg, TosState state, const char* file, int line) {
1963   if (state == atos) {
1964     MacroAssembler::_verify_oop_checked(reg, "broken oop", file, line);
1965   }
1966 }
1967 
1968 void InterpreterMacroAssembler::verify_FPU(int stack_depth, TosState state) {
1969 #ifndef _LP64
1970   if ((state == ftos && UseSSE < 1) ||
1971       (state == dtos && UseSSE < 2)) {
1972     MacroAssembler::verify_FPU(stack_depth);
1973   }
1974 #endif
1975 }
1976 
1977 // Jump if ((*counter_addr += increment) & mask) == 0
1978 void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, Address mask,
1979                                                         Register scratch, Label* where) {
1980   // This update is actually not atomic and can lose a number of updates
1981   // under heavy contention, but the alternative of using the (contended)
1982   // atomic update here penalizes profiling paths too much.
1983   movl(scratch, counter_addr);
1984   incrementl(scratch, InvocationCounter::count_increment);
1985   movl(counter_addr, scratch);
1986   andl(scratch, mask);
1987   if (where != nullptr) {
1988     jcc(Assembler::zero, *where);
1989   }
1990 }
1991 
1992 void InterpreterMacroAssembler::notify_method_entry() {
1993   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
1994   // track stack depth.  If it is possible to enter interp_only_mode we add
1995   // the code to check if the event should be sent.
1996   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
1997   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
1998   if (JvmtiExport::can_post_interpreter_events()) {
1999     Label L;
2000     NOT_LP64(get_thread(rthread);)
2001     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2002     testl(rdx, rdx);
2003     jcc(Assembler::zero, L);
2004     call_VM(noreg, CAST_FROM_FN_PTR(address,
2005                                     InterpreterRuntime::post_method_entry));
2006     bind(L);
2007   }
2008 
2009   if (DTraceMethodProbes) {
2010     NOT_LP64(get_thread(rthread);)
2011     get_method(rarg);
2012     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2013                  rthread, rarg);
2014   }
2015 
2016   // RedefineClasses() tracing support for obsolete method entry
2017   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2018     NOT_LP64(get_thread(rthread);)
2019     get_method(rarg);
2020     call_VM_leaf(
2021       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2022       rthread, rarg);
2023   }
2024 }
2025 
2026 
2027 void InterpreterMacroAssembler::notify_method_exit(
2028     TosState state, NotifyMethodExitMode mode) {
2029   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
2030   // track stack depth.  If it is possible to enter interp_only_mode we add
2031   // the code to check if the event should be sent.
2032   Register rthread = LP64_ONLY(r15_thread) NOT_LP64(rcx);
2033   Register rarg = LP64_ONLY(c_rarg1) NOT_LP64(rbx);
2034   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2035     Label L;
2036     // Note: frame::interpreter_frame_result has a dependency on how the
2037     // method result is saved across the call to post_method_exit. If this
2038     // is changed then the interpreter_frame_result implementation will
2039     // need to be updated too.
2040 
2041     // template interpreter will leave the result on the top of the stack.
2042     push(state);
2043     NOT_LP64(get_thread(rthread);)
2044     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2045     testl(rdx, rdx);
2046     jcc(Assembler::zero, L);
2047     call_VM(noreg,
2048             CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit));
2049     bind(L);
2050     pop(state);
2051   }
2052 
2053   if (DTraceMethodProbes) {
2054     push(state);
2055     NOT_LP64(get_thread(rthread);)
2056     get_method(rarg);
2057     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2058                  rthread, rarg);
2059     pop(state);
2060   }
2061 }
2062 
2063 void InterpreterMacroAssembler::load_resolved_indy_entry(Register cache, Register index) {
2064   // Get index out of bytecode pointer
2065   get_cache_index_at_bcp(index, 1, sizeof(u4));
2066   // Get address of invokedynamic array
2067   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2068   movptr(cache, Address(cache, in_bytes(ConstantPoolCache::invokedynamic_entries_offset())));
2069   if (is_power_of_2(sizeof(ResolvedIndyEntry))) {
2070     shll(index, log2i_exact(sizeof(ResolvedIndyEntry))); // Scale index by power of 2
2071   } else {
2072     imull(index, index, sizeof(ResolvedIndyEntry)); // Scale the index to be the entry index * sizeof(ResolvedIndyEntry)
2073   }
2074   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedIndyEntry>::base_offset_in_bytes()));
2075 }
2076 
2077 void InterpreterMacroAssembler::load_field_entry(Register cache, Register index, int bcp_offset) {
2078   // Get index out of bytecode pointer
2079   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2080   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2081 
2082   movptr(cache, Address(cache, ConstantPoolCache::field_entries_offset()));
2083   // Take shortcut if the size is a power of 2
2084   if (is_power_of_2(sizeof(ResolvedFieldEntry))) {
2085     shll(index, log2i_exact(sizeof(ResolvedFieldEntry))); // Scale index by power of 2
2086   } else {
2087     imull(index, index, sizeof(ResolvedFieldEntry)); // Scale the index to be the entry index * sizeof(ResolvedFieldEntry)
2088   }
2089   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedFieldEntry>::base_offset_in_bytes()));
2090 }
2091 
2092 void InterpreterMacroAssembler::load_method_entry(Register cache, Register index, int bcp_offset) {
2093   // Get index out of bytecode pointer
2094   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2095   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2096 
2097   movptr(cache, Address(cache, ConstantPoolCache::method_entries_offset()));
2098   imull(index, index, sizeof(ResolvedMethodEntry)); // Scale the index to be the entry index * sizeof(ResolvedMethodEntry)
2099   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedMethodEntry>::base_offset_in_bytes()));
2100 }