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