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