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 // Unlock the receiver if this is a synchronized method.
 787 // Unlock any Java monitors from synchronized blocks.
 788 // Apply stack watermark barrier.
 789 // Notify JVMTI.
 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(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   // get the value of _do_not_unlock_if_synchronized into rdx
 813   const Address do_not_unlock_if_synchronized(rthread,
 814     in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
 815   movbool(rbx, do_not_unlock_if_synchronized);
 816   movbool(do_not_unlock_if_synchronized, false); // reset the flag
 817 
 818   // get method access flags
 819   movptr(rcx, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
 820   load_unsigned_short(rcx, Address(rcx, Method::access_flags_offset()));
 821   testl(rcx, JVM_ACC_SYNCHRONIZED);
 822   jcc(Assembler::zero, unlocked);
 823 
 824   // Don't unlock anything if the _do_not_unlock_if_synchronized flag
 825   // is set.
 826   testbool(rbx);
 827   jcc(Assembler::notZero, no_unlock);
 828 
 829   // unlock monitor
 830   push(state); // save result
 831 
 832   // BasicObjectLock will be first in list, since this is a
 833   // synchronized method. However, need to check that the object has
 834   // not been unlocked by an explicit monitorexit bytecode.
 835   const Address monitor(rbp, frame::interpreter_frame_initial_sp_offset *
 836                         wordSize - (int) sizeof(BasicObjectLock));
 837   // We use c_rarg1/rdx so that if we go slow path it will be the correct
 838   // register for unlock_object to pass to VM directly
 839   lea(robj, monitor); // address of first monitor
 840 
 841   movptr(rax, Address(robj, BasicObjectLock::obj_offset()));
 842   testptr(rax, rax);
 843   jcc(Assembler::notZero, unlock);
 844 
 845   pop(state);
 846   if (throw_monitor_exception) {
 847     // Entry already unlocked, need to throw exception
 848     call_VM(noreg, CAST_FROM_FN_PTR(address,
 849                    InterpreterRuntime::throw_illegal_monitor_state_exception));
 850     should_not_reach_here();
 851   } else {
 852     // Monitor already unlocked during a stack unroll. If requested,
 853     // install an illegal_monitor_state_exception.  Continue with
 854     // stack unrolling.
 855     if (install_monitor_exception) {
 856       call_VM(noreg, CAST_FROM_FN_PTR(address,
 857                      InterpreterRuntime::new_illegal_monitor_state_exception));
 858     }
 859     jmp(unlocked);
 860   }
 861 
 862   bind(unlock);
 863   unlock_object(robj);
 864   pop(state);
 865 
 866   // Check that for block-structured locking (i.e., that all locked
 867   // objects has been unlocked)
 868   bind(unlocked);
 869 
 870   // rax, rdx: Might contain return value
 871 
 872   // Check that all monitors are unlocked
 873   {
 874     Label loop, exception, entry, restart;
 875     const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 876     const Address monitor_block_top(
 877         rbp, frame::interpreter_frame_monitor_block_top_offset * wordSize);
 878     const Address monitor_block_bot(
 879         rbp, frame::interpreter_frame_initial_sp_offset * wordSize);
 880 
 881     bind(restart);
 882     // We use c_rarg1 so that if we go slow path it will be the correct
 883     // register for unlock_object to pass to VM directly
 884     movptr(rmon, monitor_block_top); // derelativize pointer
 885     lea(rmon, Address(rbp, rmon, Address::times_ptr));
 886     // c_rarg1 points to current entry, starting with top-most entry
 887 
 888     lea(rbx, monitor_block_bot);  // points to word before bottom of
 889                                   // monitor block
 890     jmp(entry);
 891 
 892     // Entry already locked, need to throw exception
 893     bind(exception);
 894 
 895     if (throw_monitor_exception) {
 896       // Throw exception
 897       MacroAssembler::call_VM(noreg,
 898                               CAST_FROM_FN_PTR(address, InterpreterRuntime::
 899                                    throw_illegal_monitor_state_exception));
 900       should_not_reach_here();
 901     } else {
 902       // Stack unrolling. Unlock object and install illegal_monitor_exception.
 903       // Unlock does not block, so don't have to worry about the frame.
 904       // We don't have to preserve c_rarg1 since we are going to throw an exception.
 905 
 906       push(state);
 907       mov(robj, rmon);   // nop if robj and rmon are the same
 908       unlock_object(robj);
 909       pop(state);
 910 
 911       if (install_monitor_exception) {
 912         call_VM(noreg, CAST_FROM_FN_PTR(address,
 913                                         InterpreterRuntime::
 914                                         new_illegal_monitor_state_exception));
 915       }
 916 
 917       jmp(restart);
 918     }
 919 
 920     bind(loop);
 921     // check if current entry is used
 922     cmpptr(Address(rmon, BasicObjectLock::obj_offset()), NULL_WORD);
 923     jcc(Assembler::notEqual, exception);
 924 
 925     addptr(rmon, entry_size); // otherwise advance to next entry
 926     bind(entry);
 927     cmpptr(rmon, rbx); // check if bottom reached
 928     jcc(Assembler::notEqual, loop); // if not at bottom then check this entry
 929   }
 930 
 931   bind(no_unlock);
 932 
 933   JFR_ONLY(enter_jfr_critical_section();)
 934 
 935   // The below poll is for the stack watermark barrier. It allows fixing up frames lazily,
 936   // that would normally not be safe to use. Such bad returns into unsafe territory of
 937   // the stack, will call InterpreterRuntime::at_unwind.
 938   Label slow_path;
 939   Label fast_path;
 940   safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
 941   jmp(fast_path);
 942   bind(slow_path);
 943   push(state);
 944   set_last_Java_frame(noreg, rbp, (address)pc(), rscratch1);
 945   super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), r15_thread);
 946   reset_last_Java_frame(true);
 947   pop(state);
 948   bind(fast_path);
 949 
 950   // JVMTI support. Make sure the safepoint poll test is issued prior.
 951   if (notify_jvmdi) {
 952     notify_method_exit(state, NotifyJVMTI);    // preserve TOSCA
 953   } else {
 954     notify_method_exit(state, SkipNotifyJVMTI); // preserve TOSCA
 955   }
 956 
 957   if (StackReservedPages > 0) {
 958     movptr(rbx,
 959                Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize));
 960     // testing if reserved zone needs to be re-enabled
 961     Register rthread = r15_thread;
 962     Label no_reserved_zone_enabling;
 963 
 964     // check if already enabled - if so no re-enabling needed
 965     assert(sizeof(StackOverflow::StackGuardState) == 4, "unexpected size");
 966     cmpl(Address(rthread, JavaThread::stack_guard_state_offset()), StackOverflow::stack_guard_enabled);
 967     jcc(Assembler::equal, no_reserved_zone_enabling);
 968 
 969     cmpptr(rbx, Address(rthread, JavaThread::reserved_stack_activation_offset()));
 970     jcc(Assembler::lessEqual, no_reserved_zone_enabling);
 971 
 972     JFR_ONLY(leave_jfr_critical_section();)
 973 
 974     call_VM_leaf(
 975       CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), rthread);
 976     call_VM(noreg, CAST_FROM_FN_PTR(address,
 977                    InterpreterRuntime::throw_delayed_StackOverflowError));
 978     should_not_reach_here();
 979 
 980     bind(no_reserved_zone_enabling);
 981   }
 982 
 983   // remove activation
 984   // get sender sp
 985   movptr(rbx,
 986          Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize));
 987 
 988   if (state == atos && InlineTypeReturnedAsFields) {
 989     Label skip;
 990     Label not_null;
 991     testptr(rax, rax);
 992     jcc(Assembler::notZero, not_null);
 993     // Returned value is null, zero all return registers because they may belong to oop fields
 994     xorq(j_rarg1, j_rarg1);
 995     xorq(j_rarg2, j_rarg2);
 996     xorq(j_rarg3, j_rarg3);
 997     xorq(j_rarg4, j_rarg4);
 998     xorq(j_rarg5, j_rarg5);
 999     jmp(skip);
1000     bind(not_null);
1001 
1002     // Check if we are returning an non-null inline type and load its fields into registers
1003     test_oop_is_not_inline_type(rax, rscratch1, skip, /* can_be_null= */ false);
1004 
1005 #ifndef _LP64
1006     super_call_VM_leaf(StubRoutines::load_inline_type_fields_in_regs());
1007 #else
1008     // Load fields from a buffered value with an inline class specific handler
1009     load_klass(rdi, rax, rscratch1);
1010     movptr(rdi, Address(rdi, InstanceKlass::adr_inlineklass_fixed_block_offset()));
1011     movptr(rdi, Address(rdi, InlineKlass::unpack_handler_offset()));
1012     // Unpack handler can be null if inline type is not scalarizable in returns
1013     testptr(rdi, rdi);
1014     jcc(Assembler::zero, skip);
1015     call(rdi);
1016 #endif
1017 #ifdef ASSERT
1018     // TODO 8284443 Enable
1019     if (StressCallingConvention && false) {
1020       Label skip_stress;
1021       movptr(rscratch1, Address(rbp, frame::interpreter_frame_method_offset * wordSize));
1022       movl(rscratch1, Address(rscratch1, Method::flags_offset()));
1023       testl(rcx, MethodFlags::has_scalarized_return_flag());
1024       jcc(Assembler::zero, skip_stress);
1025       load_klass(rax, rax, rscratch1);
1026       orptr(rax, 1);
1027       bind(skip_stress);
1028     }
1029 #endif
1030     // call above kills the value in rbx. Reload it.
1031     movptr(rbx, Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize));
1032     bind(skip);
1033   }
1034 
1035   leave();                           // remove frame anchor
1036 
1037   JFR_ONLY(leave_jfr_critical_section();)
1038 
1039   pop(ret_addr);                     // get return address
1040   mov(rsp, rbx);                     // set sp to sender sp
1041   pop_cont_fastpath();
1042 
1043 }
1044 
1045 #if INCLUDE_JFR
1046 void InterpreterMacroAssembler::enter_jfr_critical_section() {
1047   const Address sampling_critical_section(r15_thread, in_bytes(SAMPLING_CRITICAL_SECTION_OFFSET_JFR));
1048   movbool(sampling_critical_section, true);
1049 }
1050 
1051 void InterpreterMacroAssembler::leave_jfr_critical_section() {
1052   const Address sampling_critical_section(r15_thread, in_bytes(SAMPLING_CRITICAL_SECTION_OFFSET_JFR));
1053   movbool(sampling_critical_section, false);
1054 }
1055 #endif // INCLUDE_JFR
1056 
1057 void InterpreterMacroAssembler::get_method_counters(Register method,
1058                                                     Register mcs, Label& skip) {
1059   Label has_counters;
1060   movptr(mcs, Address(method, Method::method_counters_offset()));
1061   testptr(mcs, mcs);
1062   jcc(Assembler::notZero, has_counters);
1063   call_VM(noreg, CAST_FROM_FN_PTR(address,
1064           InterpreterRuntime::build_method_counters), method);
1065   movptr(mcs, Address(method,Method::method_counters_offset()));
1066   testptr(mcs, mcs);
1067   jcc(Assembler::zero, skip); // No MethodCounters allocated, OutOfMemory
1068   bind(has_counters);
1069 }
1070 
1071 void InterpreterMacroAssembler::allocate_instance(Register klass, Register new_obj,
1072                                                   Register t1, Register t2,
1073                                                   bool clear_fields, Label& alloc_failed) {
1074   MacroAssembler::allocate_instance(klass, new_obj, t1, t2, clear_fields, alloc_failed);
1075   if (DTraceAllocProbes) {
1076     // Trigger dtrace event for fastpath
1077     push(atos);
1078     call_VM_leaf(CAST_FROM_FN_PTR(address, static_cast<int (*)(oopDesc*)>(SharedRuntime::dtrace_object_alloc)), new_obj);
1079     pop(atos);
1080   }
1081 }
1082 
1083 void InterpreterMacroAssembler::read_flat_field(Register entry, Register tmp1, Register tmp2, Register obj) {
1084   Label alloc_failed, done;
1085   const Register alloc_temp = LP64_ONLY(rscratch1) NOT_LP64(rsi);
1086   const Register dst_temp   = LP64_ONLY(rscratch2) NOT_LP64(rdi);
1087   assert_different_registers(obj, entry, tmp1, tmp2, dst_temp, r8, r9);
1088 
1089   // FIXME: code below could be re-written to better use InlineLayoutInfo data structure
1090   // see aarch64 version
1091 
1092   // Grap the inline field klass
1093   const Register field_klass = tmp1;
1094   load_unsigned_short(tmp2, Address(entry, in_bytes(ResolvedFieldEntry::field_index_offset())));
1095   movptr(tmp1, Address(entry, ResolvedFieldEntry::field_holder_offset()));
1096   get_inline_type_field_klass(tmp1, tmp2, field_klass);
1097 
1098   // allocate buffer
1099   push(obj);  // push object being read from     // FIXME spilling on stack could probably be avoided by using tmp2
1100   allocate_instance(field_klass, obj, alloc_temp, dst_temp, false, alloc_failed);
1101 
1102   // Have an oop instance buffer, copy into it
1103   load_unsigned_short(r9, Address(entry, in_bytes(ResolvedFieldEntry::field_index_offset())));
1104   movptr(r8, Address(entry, in_bytes(ResolvedFieldEntry::field_holder_offset())));
1105   inline_layout_info(r8, r9, r8); // holder, index, info => InlineLayoutInfo into r8
1106 
1107   payload_addr(obj, dst_temp, field_klass);
1108   pop(alloc_temp);             // restore object being read from
1109   load_sized_value(tmp2, Address(entry, in_bytes(ResolvedFieldEntry::field_offset_offset())), sizeof(int), true /*is_signed*/);
1110   lea(tmp2, Address(alloc_temp, tmp2));
1111   // call_VM_leaf, clobbers a few regs, save restore new obj
1112   push(obj);
1113   // access_value_copy(IS_DEST_UNINITIALIZED, tmp2, dst_temp, field_klass);
1114   flat_field_copy(IS_DEST_UNINITIALIZED, tmp2, dst_temp, r8);
1115   pop(obj);
1116   jmp(done);
1117 
1118   bind(alloc_failed);
1119   pop(obj);
1120   call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::read_flat_field),
1121           obj, entry);
1122   get_vm_result_oop(obj);
1123   bind(done);
1124 }
1125 
1126 // Lock object
1127 //
1128 // Args:
1129 //      rdx, c_rarg1: BasicObjectLock to be used for locking
1130 //
1131 // Kills:
1132 //      rax, rbx
1133 void InterpreterMacroAssembler::lock_object(Register lock_reg) {
1134   assert(lock_reg == c_rarg1, "The argument is only for looks. It must be c_rarg1");
1135 
1136   if (LockingMode == LM_MONITOR) {
1137     call_VM_preemptable(noreg,
1138             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1139             lock_reg);
1140   } else {
1141     Label count_locking, done, slow_case;
1142 
1143     const Register swap_reg = rax; // Must use rax for cmpxchg instruction
1144     const Register tmp_reg = rbx;
1145     const Register obj_reg = c_rarg3; // Will contain the oop
1146     const Register rklass_decode_tmp = rscratch1;
1147 
1148     const int obj_offset = in_bytes(BasicObjectLock::obj_offset());
1149     const int lock_offset = in_bytes(BasicObjectLock::lock_offset());
1150     const int mark_offset = lock_offset +
1151                             BasicLock::displaced_header_offset_in_bytes();
1152 
1153     // Load object pointer into obj_reg
1154     movptr(obj_reg, Address(lock_reg, obj_offset));
1155 
1156     if (LockingMode == LM_LIGHTWEIGHT) {
1157       lightweight_lock(lock_reg, obj_reg, swap_reg, tmp_reg, slow_case);
1158     } else if (LockingMode == LM_LEGACY) {
1159       if (DiagnoseSyncOnValueBasedClasses != 0) {
1160         load_klass(tmp_reg, obj_reg, rklass_decode_tmp);
1161         testb(Address(tmp_reg, Klass::misc_flags_offset()), KlassFlags::_misc_is_value_based_class);
1162         jcc(Assembler::notZero, slow_case);
1163       }
1164 
1165       // Load immediate 1 into swap_reg %rax
1166       movl(swap_reg, 1);
1167 
1168       // Load (object->mark() | 1) into swap_reg %rax
1169       orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1170       if (EnableValhalla) {
1171         // Mask inline_type bit such that we go to the slow path if object is an inline type
1172         andptr(swap_reg, ~((int) markWord::inline_type_bit_in_place));
1173       }
1174 
1175       // Save (object->mark() | 1) into BasicLock's displaced header
1176       movptr(Address(lock_reg, mark_offset), swap_reg);
1177 
1178       assert(lock_offset == 0,
1179              "displaced header must be first word in BasicObjectLock");
1180 
1181       lock();
1182       cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1183       jcc(Assembler::zero, count_locking);
1184 
1185       const int zero_bits = 7;
1186 
1187       // Fast check for recursive lock.
1188       //
1189       // Can apply the optimization only if this is a stack lock
1190       // allocated in this thread. For efficiency, we can focus on
1191       // recently allocated stack locks (instead of reading the stack
1192       // base and checking whether 'mark' points inside the current
1193       // thread stack):
1194       //  1) (mark & zero_bits) == 0, and
1195       //  2) rsp <= mark < mark + os::pagesize()
1196       //
1197       // Warning: rsp + os::pagesize can overflow the stack base. We must
1198       // neither apply the optimization for an inflated lock allocated
1199       // just above the thread stack (this is why condition 1 matters)
1200       // nor apply the optimization if the stack lock is inside the stack
1201       // of another thread. The latter is avoided even in case of overflow
1202       // because we have guard pages at the end of all stacks. Hence, if
1203       // we go over the stack base and hit the stack of another thread,
1204       // this should not be in a writeable area that could contain a
1205       // stack lock allocated by that thread. As a consequence, a stack
1206       // lock less than page size away from rsp is guaranteed to be
1207       // owned by the current thread.
1208       //
1209       // These 3 tests can be done by evaluating the following
1210       // expression: ((mark - rsp) & (zero_bits - os::vm_page_size())),
1211       // assuming both stack pointer and pagesize have their
1212       // least significant bits clear.
1213       // NOTE: the mark is in swap_reg %rax as the result of cmpxchg
1214       subptr(swap_reg, rsp);
1215       andptr(swap_reg, zero_bits - (int)os::vm_page_size());
1216 
1217       // Save the test result, for recursive case, the result is zero
1218       movptr(Address(lock_reg, mark_offset), swap_reg);
1219       jcc(Assembler::notZero, slow_case);
1220 
1221       bind(count_locking);
1222       inc_held_monitor_count();
1223     }
1224     jmp(done);
1225 
1226     bind(slow_case);
1227 
1228     // Call the runtime routine for slow case
1229     call_VM_preemptable(noreg,
1230             CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorenter),
1231             lock_reg);
1232     bind(done);
1233   }
1234 }
1235 
1236 
1237 // Unlocks an object. Used in monitorexit bytecode and
1238 // remove_activation.  Throws an IllegalMonitorException if object is
1239 // not locked by current thread.
1240 //
1241 // Args:
1242 //      rdx, c_rarg1: BasicObjectLock for lock
1243 //
1244 // Kills:
1245 //      rax
1246 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ... (param regs)
1247 //      rscratch1 (scratch reg)
1248 // rax, rbx, rcx, rdx
1249 void InterpreterMacroAssembler::unlock_object(Register lock_reg) {
1250   assert(lock_reg == c_rarg1, "The argument is only for looks. It must be c_rarg1");
1251 
1252   if (LockingMode == LM_MONITOR) {
1253     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1254   } else {
1255     Label count_locking, done, slow_case;
1256 
1257     const Register swap_reg   = rax;  // Must use rax for cmpxchg instruction
1258     const Register header_reg = c_rarg2;  // Will contain the old oopMark
1259     const Register obj_reg    = c_rarg3;  // Will contain the oop
1260 
1261     save_bcp(); // Save in case of exception
1262 
1263     if (LockingMode != LM_LIGHTWEIGHT) {
1264       // Convert from BasicObjectLock structure to object and BasicLock
1265       // structure Store the BasicLock address into %rax
1266       lea(swap_reg, Address(lock_reg, BasicObjectLock::lock_offset()));
1267     }
1268 
1269     // Load oop into obj_reg(%c_rarg3)
1270     movptr(obj_reg, Address(lock_reg, BasicObjectLock::obj_offset()));
1271 
1272     // Free entry
1273     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), NULL_WORD);
1274 
1275     if (LockingMode == LM_LIGHTWEIGHT) {
1276       lightweight_unlock(obj_reg, swap_reg, header_reg, slow_case);
1277     } else if (LockingMode == LM_LEGACY) {
1278       // Load the old header from BasicLock structure
1279       movptr(header_reg, Address(swap_reg,
1280                                  BasicLock::displaced_header_offset_in_bytes()));
1281 
1282       // Test for recursion
1283       testptr(header_reg, header_reg);
1284 
1285       // zero for recursive case
1286       jcc(Assembler::zero, count_locking);
1287 
1288       // Atomic swap back the old header
1289       lock();
1290       cmpxchgptr(header_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1291 
1292       // zero for simple unlock of a stack-lock case
1293       jcc(Assembler::notZero, slow_case);
1294 
1295       bind(count_locking);
1296       dec_held_monitor_count();
1297     }
1298     jmp(done);
1299 
1300     bind(slow_case);
1301     // Call the runtime routine for slow case.
1302     movptr(Address(lock_reg, BasicObjectLock::obj_offset()), obj_reg); // restore obj
1303     call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::monitorexit), lock_reg);
1304 
1305     bind(done);
1306 
1307     restore_bcp();
1308   }
1309 }
1310 
1311 void InterpreterMacroAssembler::test_method_data_pointer(Register mdp,
1312                                                          Label& zero_continue) {
1313   assert(ProfileInterpreter, "must be profiling interpreter");
1314   movptr(mdp, Address(rbp, frame::interpreter_frame_mdp_offset * wordSize));
1315   testptr(mdp, mdp);
1316   jcc(Assembler::zero, zero_continue);
1317 }
1318 
1319 
1320 // Set the method data pointer for the current bcp.
1321 void InterpreterMacroAssembler::set_method_data_pointer_for_bcp() {
1322   assert(ProfileInterpreter, "must be profiling interpreter");
1323   Label set_mdp;
1324   push(rax);
1325   push(rbx);
1326 
1327   get_method(rbx);
1328   // Test MDO to avoid the call if it is null.
1329   movptr(rax, Address(rbx, in_bytes(Method::method_data_offset())));
1330   testptr(rax, rax);
1331   jcc(Assembler::zero, set_mdp);
1332   // rbx: method
1333   // _bcp_register: bcp
1334   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::bcp_to_di), rbx, _bcp_register);
1335   // rax: mdi
1336   // mdo is guaranteed to be non-zero here, we checked for it before the call.
1337   movptr(rbx, Address(rbx, in_bytes(Method::method_data_offset())));
1338   addptr(rbx, in_bytes(MethodData::data_offset()));
1339   addptr(rax, rbx);
1340   bind(set_mdp);
1341   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), rax);
1342   pop(rbx);
1343   pop(rax);
1344 }
1345 
1346 void InterpreterMacroAssembler::verify_method_data_pointer() {
1347   assert(ProfileInterpreter, "must be profiling interpreter");
1348 #ifdef ASSERT
1349   Label verify_continue;
1350   push(rax);
1351   push(rbx);
1352   Register arg3_reg = c_rarg3;
1353   Register arg2_reg = c_rarg2;
1354   push(arg3_reg);
1355   push(arg2_reg);
1356   test_method_data_pointer(arg3_reg, verify_continue); // If mdp is zero, continue
1357   get_method(rbx);
1358 
1359   // If the mdp is valid, it will point to a DataLayout header which is
1360   // consistent with the bcp.  The converse is highly probable also.
1361   load_unsigned_short(arg2_reg,
1362                       Address(arg3_reg, in_bytes(DataLayout::bci_offset())));
1363   addptr(arg2_reg, Address(rbx, Method::const_offset()));
1364   lea(arg2_reg, Address(arg2_reg, ConstMethod::codes_offset()));
1365   cmpptr(arg2_reg, _bcp_register);
1366   jcc(Assembler::equal, verify_continue);
1367   // rbx: method
1368   // _bcp_register: bcp
1369   // c_rarg3: mdp
1370   call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::verify_mdp),
1371                rbx, _bcp_register, arg3_reg);
1372   bind(verify_continue);
1373   pop(arg2_reg);
1374   pop(arg3_reg);
1375   pop(rbx);
1376   pop(rax);
1377 #endif // ASSERT
1378 }
1379 
1380 
1381 void InterpreterMacroAssembler::set_mdp_data_at(Register mdp_in,
1382                                                 int constant,
1383                                                 Register value) {
1384   assert(ProfileInterpreter, "must be profiling interpreter");
1385   Address data(mdp_in, constant);
1386   movptr(data, value);
1387 }
1388 
1389 
1390 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1391                                                       int constant) {
1392   assert(ProfileInterpreter, "must be profiling interpreter");
1393   Address data(mdp_in, constant);
1394   addptr(data, DataLayout::counter_increment);
1395 }
1396 
1397 
1398 void InterpreterMacroAssembler::increment_mdp_data_at(Register mdp_in,
1399                                                       Register index,
1400                                                       int constant) {
1401   assert(ProfileInterpreter, "must be profiling interpreter");
1402   Address data(mdp_in, index, Address::times_1, constant);
1403   addptr(data, DataLayout::counter_increment);
1404 }
1405 
1406 void InterpreterMacroAssembler::set_mdp_flag_at(Register mdp_in,
1407                                                 int flag_byte_constant) {
1408   assert(ProfileInterpreter, "must be profiling interpreter");
1409   int header_offset = in_bytes(DataLayout::flags_offset());
1410   int header_bits = flag_byte_constant;
1411   // Set the flag
1412   orb(Address(mdp_in, header_offset), header_bits);
1413 }
1414 
1415 
1416 
1417 void InterpreterMacroAssembler::test_mdp_data_at(Register mdp_in,
1418                                                  int offset,
1419                                                  Register value,
1420                                                  Register test_value_out,
1421                                                  Label& not_equal_continue) {
1422   assert(ProfileInterpreter, "must be profiling interpreter");
1423   if (test_value_out == noreg) {
1424     cmpptr(value, Address(mdp_in, offset));
1425   } else {
1426     // Put the test value into a register, so caller can use it:
1427     movptr(test_value_out, Address(mdp_in, offset));
1428     cmpptr(test_value_out, value);
1429   }
1430   jcc(Assembler::notEqual, not_equal_continue);
1431 }
1432 
1433 
1434 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1435                                                      int offset_of_disp) {
1436   assert(ProfileInterpreter, "must be profiling interpreter");
1437   Address disp_address(mdp_in, offset_of_disp);
1438   addptr(mdp_in, disp_address);
1439   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1440 }
1441 
1442 
1443 void InterpreterMacroAssembler::update_mdp_by_offset(Register mdp_in,
1444                                                      Register reg,
1445                                                      int offset_of_disp) {
1446   assert(ProfileInterpreter, "must be profiling interpreter");
1447   Address disp_address(mdp_in, reg, Address::times_1, offset_of_disp);
1448   addptr(mdp_in, disp_address);
1449   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1450 }
1451 
1452 
1453 void InterpreterMacroAssembler::update_mdp_by_constant(Register mdp_in,
1454                                                        int constant) {
1455   assert(ProfileInterpreter, "must be profiling interpreter");
1456   addptr(mdp_in, constant);
1457   movptr(Address(rbp, frame::interpreter_frame_mdp_offset * wordSize), mdp_in);
1458 }
1459 
1460 
1461 void InterpreterMacroAssembler::update_mdp_for_ret(Register return_bci) {
1462   assert(ProfileInterpreter, "must be profiling interpreter");
1463   push(return_bci); // save/restore across call_VM
1464   call_VM(noreg,
1465           CAST_FROM_FN_PTR(address, InterpreterRuntime::update_mdp_for_ret),
1466           return_bci);
1467   pop(return_bci);
1468 }
1469 
1470 
1471 void InterpreterMacroAssembler::profile_taken_branch(Register mdp,
1472                                                      Register bumped_count) {
1473   if (ProfileInterpreter) {
1474     Label profile_continue;
1475 
1476     // If no method data exists, go to profile_continue.
1477     // Otherwise, assign to mdp
1478     test_method_data_pointer(mdp, profile_continue);
1479 
1480     // We are taking a branch.  Increment the taken count.
1481     // We inline increment_mdp_data_at to return bumped_count in a register
1482     //increment_mdp_data_at(mdp, in_bytes(JumpData::taken_offset()));
1483     Address data(mdp, in_bytes(JumpData::taken_offset()));
1484     movptr(bumped_count, data);
1485     assert(DataLayout::counter_increment == 1,
1486             "flow-free idiom only works with 1");
1487     addptr(bumped_count, DataLayout::counter_increment);
1488     sbbptr(bumped_count, 0);
1489     movptr(data, bumped_count); // Store back out
1490 
1491     // The method data pointer needs to be updated to reflect the new target.
1492     update_mdp_by_offset(mdp, in_bytes(JumpData::displacement_offset()));
1493     bind(profile_continue);
1494   }
1495 }
1496 
1497 
1498 void InterpreterMacroAssembler::profile_not_taken_branch(Register mdp, bool acmp) {
1499   if (ProfileInterpreter) {
1500     Label profile_continue;
1501 
1502     // If no method data exists, go to profile_continue.
1503     test_method_data_pointer(mdp, profile_continue);
1504 
1505     // We are taking a branch.  Increment the not taken count.
1506     increment_mdp_data_at(mdp, in_bytes(BranchData::not_taken_offset()));
1507 
1508     // The method data pointer needs to be updated to correspond to
1509     // the next bytecode
1510     update_mdp_by_constant(mdp, acmp ? in_bytes(ACmpData::acmp_data_size()): in_bytes(BranchData::branch_data_size()));
1511     bind(profile_continue);
1512   }
1513 }
1514 
1515 void InterpreterMacroAssembler::profile_call(Register mdp) {
1516   if (ProfileInterpreter) {
1517     Label profile_continue;
1518 
1519     // If no method data exists, go to profile_continue.
1520     test_method_data_pointer(mdp, profile_continue);
1521 
1522     // We are making a call.  Increment the count.
1523     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1524 
1525     // The method data pointer needs to be updated to reflect the new target.
1526     update_mdp_by_constant(mdp, in_bytes(CounterData::counter_data_size()));
1527     bind(profile_continue);
1528   }
1529 }
1530 
1531 
1532 void InterpreterMacroAssembler::profile_final_call(Register mdp) {
1533   if (ProfileInterpreter) {
1534     Label profile_continue;
1535 
1536     // If no method data exists, go to profile_continue.
1537     test_method_data_pointer(mdp, profile_continue);
1538 
1539     // We are making a call.  Increment the count.
1540     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1541 
1542     // The method data pointer needs to be updated to reflect the new target.
1543     update_mdp_by_constant(mdp,
1544                            in_bytes(VirtualCallData::
1545                                     virtual_call_data_size()));
1546     bind(profile_continue);
1547   }
1548 }
1549 
1550 
1551 void InterpreterMacroAssembler::profile_virtual_call(Register receiver,
1552                                                      Register mdp,
1553                                                      Register reg2,
1554                                                      bool receiver_can_be_null) {
1555   if (ProfileInterpreter) {
1556     Label profile_continue;
1557 
1558     // If no method data exists, go to profile_continue.
1559     test_method_data_pointer(mdp, profile_continue);
1560 
1561     Label skip_receiver_profile;
1562     if (receiver_can_be_null) {
1563       Label not_null;
1564       testptr(receiver, receiver);
1565       jccb(Assembler::notZero, not_null);
1566       // We are making a call.  Increment the count for null receiver.
1567       increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1568       jmp(skip_receiver_profile);
1569       bind(not_null);
1570     }
1571 
1572     // Record the receiver type.
1573     record_klass_in_profile(receiver, mdp, reg2);
1574     bind(skip_receiver_profile);
1575 
1576     // The method data pointer needs to be updated to reflect the new target.
1577     update_mdp_by_constant(mdp, in_bytes(VirtualCallData::virtual_call_data_size()));
1578     bind(profile_continue);
1579   }
1580 }
1581 
1582 // This routine creates a state machine for updating the multi-row
1583 // type profile at a virtual call site (or other type-sensitive bytecode).
1584 // The machine visits each row (of receiver/count) until the receiver type
1585 // is found, or until it runs out of rows.  At the same time, it remembers
1586 // the location of the first empty row.  (An empty row records null for its
1587 // receiver, and can be allocated for a newly-observed receiver type.)
1588 // Because there are two degrees of freedom in the state, a simple linear
1589 // search will not work; it must be a decision tree.  Hence this helper
1590 // function is recursive, to generate the required tree structured code.
1591 // It's the interpreter, so we are trading off code space for speed.
1592 // See below for example code.
1593 void InterpreterMacroAssembler::record_klass_in_profile_helper(Register receiver, Register mdp,
1594                                                                Register reg2, int start_row,
1595                                                                Label& done) {
1596   if (TypeProfileWidth == 0) {
1597     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1598   } else {
1599     record_item_in_profile_helper(receiver, mdp, reg2, 0, done, TypeProfileWidth,
1600                                   &VirtualCallData::receiver_offset, &VirtualCallData::receiver_count_offset);
1601   }
1602 }
1603 
1604 void InterpreterMacroAssembler::record_item_in_profile_helper(Register item, Register mdp, Register reg2, int start_row,
1605                                                               Label& done, int total_rows,
1606                                                               OffsetFunction item_offset_fn,
1607                                                               OffsetFunction item_count_offset_fn) {
1608   int last_row = total_rows - 1;
1609   assert(start_row <= last_row, "must be work left to do");
1610   // Test this row for both the item and for null.
1611   // Take any of three different outcomes:
1612   //   1. found item => increment count and goto done
1613   //   2. found null => keep looking for case 1, maybe allocate this cell
1614   //   3. found something else => keep looking for cases 1 and 2
1615   // Case 3 is handled by a recursive call.
1616   for (int row = start_row; row <= last_row; row++) {
1617     Label next_test;
1618     bool test_for_null_also = (row == start_row);
1619 
1620     // See if the item is item[n].
1621     int item_offset = in_bytes(item_offset_fn(row));
1622     test_mdp_data_at(mdp, item_offset, item,
1623                      (test_for_null_also ? reg2 : noreg),
1624                      next_test);
1625     // (Reg2 now contains the item from the CallData.)
1626 
1627     // The item is item[n].  Increment count[n].
1628     int count_offset = in_bytes(item_count_offset_fn(row));
1629     increment_mdp_data_at(mdp, count_offset);
1630     jmp(done);
1631     bind(next_test);
1632 
1633     if (test_for_null_also) {
1634       // Failed the equality check on item[n]...  Test for null.
1635       testptr(reg2, reg2);
1636       if (start_row == last_row) {
1637         // The only thing left to do is handle the null case.
1638         Label found_null;
1639         jccb(Assembler::zero, found_null);
1640         // Item did not match any saved item and there is no empty row for it.
1641         // Increment total counter to indicate polymorphic case.
1642         increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1643         jmp(done);
1644         bind(found_null);
1645         break;
1646       }
1647       Label found_null;
1648       // Since null is rare, make it be the branch-taken case.
1649       jcc(Assembler::zero, found_null);
1650 
1651       // Put all the "Case 3" tests here.
1652       record_item_in_profile_helper(item, mdp, reg2, start_row + 1, done, total_rows,
1653                                     item_offset_fn, item_count_offset_fn);
1654 
1655       // Found a null.  Keep searching for a matching item,
1656       // but remember that this is an empty (unused) slot.
1657       bind(found_null);
1658     }
1659   }
1660 
1661   // In the fall-through case, we found no matching item, but we
1662   // observed the item[start_row] is null.
1663 
1664   // Fill in the item field and increment the count.
1665   int item_offset = in_bytes(item_offset_fn(start_row));
1666   set_mdp_data_at(mdp, item_offset, item);
1667   int count_offset = in_bytes(item_count_offset_fn(start_row));
1668   movl(reg2, DataLayout::counter_increment);
1669   set_mdp_data_at(mdp, count_offset, reg2);
1670   if (start_row > 0) {
1671     jmp(done);
1672   }
1673 }
1674 
1675 // Example state machine code for three profile rows:
1676 //   // main copy of decision tree, rooted at row[1]
1677 //   if (row[0].rec == rec) { row[0].incr(); goto done; }
1678 //   if (row[0].rec != nullptr) {
1679 //     // inner copy of decision tree, rooted at row[1]
1680 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1681 //     if (row[1].rec != nullptr) {
1682 //       // degenerate decision tree, rooted at row[2]
1683 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1684 //       if (row[2].rec != nullptr) { count.incr(); goto done; } // overflow
1685 //       row[2].init(rec); goto done;
1686 //     } else {
1687 //       // remember row[1] is empty
1688 //       if (row[2].rec == rec) { row[2].incr(); goto done; }
1689 //       row[1].init(rec); goto done;
1690 //     }
1691 //   } else {
1692 //     // remember row[0] is empty
1693 //     if (row[1].rec == rec) { row[1].incr(); goto done; }
1694 //     if (row[2].rec == rec) { row[2].incr(); goto done; }
1695 //     row[0].init(rec); goto done;
1696 //   }
1697 //   done:
1698 
1699 void InterpreterMacroAssembler::record_klass_in_profile(Register receiver, Register mdp, Register reg2) {
1700   assert(ProfileInterpreter, "must be profiling");
1701   Label done;
1702 
1703   record_klass_in_profile_helper(receiver, mdp, reg2, 0, done);
1704 
1705   bind (done);
1706 }
1707 
1708 void InterpreterMacroAssembler::profile_ret(Register return_bci,
1709                                             Register mdp) {
1710   if (ProfileInterpreter) {
1711     Label profile_continue;
1712     uint row;
1713 
1714     // If no method data exists, go to profile_continue.
1715     test_method_data_pointer(mdp, profile_continue);
1716 
1717     // Update the total ret count.
1718     increment_mdp_data_at(mdp, in_bytes(CounterData::count_offset()));
1719 
1720     for (row = 0; row < RetData::row_limit(); row++) {
1721       Label next_test;
1722 
1723       // See if return_bci is equal to bci[n]:
1724       test_mdp_data_at(mdp,
1725                        in_bytes(RetData::bci_offset(row)),
1726                        return_bci, noreg,
1727                        next_test);
1728 
1729       // return_bci is equal to bci[n].  Increment the count.
1730       increment_mdp_data_at(mdp, in_bytes(RetData::bci_count_offset(row)));
1731 
1732       // The method data pointer needs to be updated to reflect the new target.
1733       update_mdp_by_offset(mdp,
1734                            in_bytes(RetData::bci_displacement_offset(row)));
1735       jmp(profile_continue);
1736       bind(next_test);
1737     }
1738 
1739     update_mdp_for_ret(return_bci);
1740 
1741     bind(profile_continue);
1742   }
1743 }
1744 
1745 
1746 void InterpreterMacroAssembler::profile_null_seen(Register mdp) {
1747   if (ProfileInterpreter) {
1748     Label profile_continue;
1749 
1750     // If no method data exists, go to profile_continue.
1751     test_method_data_pointer(mdp, profile_continue);
1752 
1753     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1754 
1755     // The method data pointer needs to be updated.
1756     int mdp_delta = in_bytes(BitData::bit_data_size());
1757     if (TypeProfileCasts) {
1758       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1759     }
1760     update_mdp_by_constant(mdp, mdp_delta);
1761 
1762     bind(profile_continue);
1763   }
1764 }
1765 
1766 
1767 void InterpreterMacroAssembler::profile_typecheck(Register mdp, Register klass, Register reg2) {
1768   if (ProfileInterpreter) {
1769     Label profile_continue;
1770 
1771     // If no method data exists, go to profile_continue.
1772     test_method_data_pointer(mdp, profile_continue);
1773 
1774     // The method data pointer needs to be updated.
1775     int mdp_delta = in_bytes(BitData::bit_data_size());
1776     if (TypeProfileCasts) {
1777       mdp_delta = in_bytes(VirtualCallData::virtual_call_data_size());
1778 
1779       // Record the object type.
1780       record_klass_in_profile(klass, mdp, reg2);
1781     }
1782     update_mdp_by_constant(mdp, mdp_delta);
1783 
1784     bind(profile_continue);
1785   }
1786 }
1787 
1788 
1789 void InterpreterMacroAssembler::profile_switch_default(Register mdp) {
1790   if (ProfileInterpreter) {
1791     Label profile_continue;
1792 
1793     // If no method data exists, go to profile_continue.
1794     test_method_data_pointer(mdp, profile_continue);
1795 
1796     // Update the default case count
1797     increment_mdp_data_at(mdp,
1798                           in_bytes(MultiBranchData::default_count_offset()));
1799 
1800     // The method data pointer needs to be updated.
1801     update_mdp_by_offset(mdp,
1802                          in_bytes(MultiBranchData::
1803                                   default_displacement_offset()));
1804 
1805     bind(profile_continue);
1806   }
1807 }
1808 
1809 
1810 void InterpreterMacroAssembler::profile_switch_case(Register index,
1811                                                     Register mdp,
1812                                                     Register reg2) {
1813   if (ProfileInterpreter) {
1814     Label profile_continue;
1815 
1816     // If no method data exists, go to profile_continue.
1817     test_method_data_pointer(mdp, profile_continue);
1818 
1819     // Build the base (index * per_case_size_in_bytes()) +
1820     // case_array_offset_in_bytes()
1821     movl(reg2, in_bytes(MultiBranchData::per_case_size()));
1822     imulptr(index, reg2); // XXX l ?
1823     addptr(index, in_bytes(MultiBranchData::case_array_offset())); // XXX l ?
1824 
1825     // Update the case count
1826     increment_mdp_data_at(mdp,
1827                           index,
1828                           in_bytes(MultiBranchData::relative_count_offset()));
1829 
1830     // The method data pointer needs to be updated.
1831     update_mdp_by_offset(mdp,
1832                          index,
1833                          in_bytes(MultiBranchData::
1834                                   relative_displacement_offset()));
1835 
1836     bind(profile_continue);
1837   }
1838 }
1839 
1840 template <class ArrayData> void InterpreterMacroAssembler::profile_array_type(Register mdp,
1841                                                                               Register array,
1842                                                                               Register tmp) {
1843   if (ProfileInterpreter) {
1844     Label profile_continue;
1845 
1846     // If no method data exists, go to profile_continue.
1847     test_method_data_pointer(mdp, profile_continue);
1848 
1849     mov(tmp, array);
1850     profile_obj_type(tmp, Address(mdp, in_bytes(ArrayData::array_offset())));
1851 
1852     Label not_flat;
1853     test_non_flat_array_oop(array, tmp, not_flat);
1854 
1855     set_mdp_flag_at(mdp, ArrayData::flat_array_byte_constant());
1856 
1857     bind(not_flat);
1858 
1859     Label not_null_free;
1860     test_non_null_free_array_oop(array, tmp, not_null_free);
1861 
1862     set_mdp_flag_at(mdp, ArrayData::null_free_array_byte_constant());
1863 
1864     bind(not_null_free);
1865 
1866     bind(profile_continue);
1867   }
1868 }
1869 
1870 template void InterpreterMacroAssembler::profile_array_type<ArrayLoadData>(Register mdp,
1871                                                                            Register array,
1872                                                                            Register tmp);
1873 template void InterpreterMacroAssembler::profile_array_type<ArrayStoreData>(Register mdp,
1874                                                                             Register array,
1875                                                                             Register tmp);
1876 
1877 
1878 void InterpreterMacroAssembler::profile_multiple_element_types(Register mdp, Register element, Register tmp, const Register tmp2) {
1879   if (ProfileInterpreter) {
1880     Label profile_continue;
1881 
1882     // If no method data exists, go to profile_continue.
1883     test_method_data_pointer(mdp, profile_continue);
1884 
1885     Label done, update;
1886     testptr(element, element);
1887     jccb(Assembler::notZero, update);
1888     set_mdp_flag_at(mdp, BitData::null_seen_byte_constant());
1889     jmp(done);
1890 
1891     bind(update);
1892     load_klass(tmp, element, rscratch1);
1893 
1894     // Record the object type.
1895     record_klass_in_profile(tmp, mdp, tmp2);
1896 
1897     bind(done);
1898 
1899     // The method data pointer needs to be updated.
1900     update_mdp_by_constant(mdp, in_bytes(ArrayStoreData::array_store_data_size()));
1901 
1902     bind(profile_continue);
1903   }
1904 }
1905 
1906 void InterpreterMacroAssembler::profile_element_type(Register mdp,
1907                                                      Register element,
1908                                                      Register tmp) {
1909   if (ProfileInterpreter) {
1910     Label profile_continue;
1911 
1912     // If no method data exists, go to profile_continue.
1913     test_method_data_pointer(mdp, profile_continue);
1914 
1915     mov(tmp, element);
1916     profile_obj_type(tmp, Address(mdp, in_bytes(ArrayLoadData::element_offset())));
1917 
1918     // The method data pointer needs to be updated.
1919     update_mdp_by_constant(mdp, in_bytes(ArrayLoadData::array_load_data_size()));
1920 
1921     bind(profile_continue);
1922   }
1923 }
1924 
1925 void InterpreterMacroAssembler::profile_acmp(Register mdp,
1926                                              Register left,
1927                                              Register right,
1928                                              Register tmp) {
1929   if (ProfileInterpreter) {
1930     Label profile_continue;
1931 
1932     // If no method data exists, go to profile_continue.
1933     test_method_data_pointer(mdp, profile_continue);
1934 
1935     mov(tmp, left);
1936     profile_obj_type(tmp, Address(mdp, in_bytes(ACmpData::left_offset())));
1937 
1938     Label left_not_inline_type;
1939     test_oop_is_not_inline_type(left, tmp, left_not_inline_type);
1940     set_mdp_flag_at(mdp, ACmpData::left_inline_type_byte_constant());
1941     bind(left_not_inline_type);
1942 
1943     mov(tmp, right);
1944     profile_obj_type(tmp, Address(mdp, in_bytes(ACmpData::right_offset())));
1945 
1946     Label right_not_inline_type;
1947     test_oop_is_not_inline_type(right, tmp, right_not_inline_type);
1948     set_mdp_flag_at(mdp, ACmpData::right_inline_type_byte_constant());
1949     bind(right_not_inline_type);
1950 
1951     bind(profile_continue);
1952   }
1953 }
1954 
1955 
1956 void InterpreterMacroAssembler::_interp_verify_oop(Register reg, TosState state, const char* file, int line) {
1957   if (state == atos) {
1958     MacroAssembler::_verify_oop_checked(reg, "broken oop", file, line);
1959   }
1960 }
1961 
1962 
1963 // Jump if ((*counter_addr += increment) & mask) == 0
1964 void InterpreterMacroAssembler::increment_mask_and_jump(Address counter_addr, Address mask,
1965                                                         Register scratch, Label* where) {
1966   // This update is actually not atomic and can lose a number of updates
1967   // under heavy contention, but the alternative of using the (contended)
1968   // atomic update here penalizes profiling paths too much.
1969   movl(scratch, counter_addr);
1970   incrementl(scratch, InvocationCounter::count_increment);
1971   movl(counter_addr, scratch);
1972   andl(scratch, mask);
1973   if (where != nullptr) {
1974     jcc(Assembler::zero, *where);
1975   }
1976 }
1977 
1978 void InterpreterMacroAssembler::notify_method_entry() {
1979   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
1980   // track stack depth.  If it is possible to enter interp_only_mode we add
1981   // the code to check if the event should be sent.
1982   Register rthread = r15_thread;
1983   Register rarg = c_rarg1;
1984   if (JvmtiExport::can_post_interpreter_events()) {
1985     Label L;
1986     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
1987     testl(rdx, rdx);
1988     jcc(Assembler::zero, L);
1989     call_VM(noreg, CAST_FROM_FN_PTR(address,
1990                                     InterpreterRuntime::post_method_entry));
1991     bind(L);
1992   }
1993 
1994   if (DTraceMethodProbes) {
1995     get_method(rarg);
1996     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1997                  rthread, rarg);
1998   }
1999 
2000   // RedefineClasses() tracing support for obsolete method entry
2001   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2002     get_method(rarg);
2003     call_VM_leaf(
2004       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2005       rthread, rarg);
2006   }
2007 }
2008 
2009 
2010 void InterpreterMacroAssembler::notify_method_exit(
2011     TosState state, NotifyMethodExitMode mode) {
2012   // Whenever JVMTI is interp_only_mode, method entry/exit events are sent to
2013   // track stack depth.  If it is possible to enter interp_only_mode we add
2014   // the code to check if the event should be sent.
2015   Register rthread = r15_thread;
2016   Register rarg = c_rarg1;
2017   if (mode == NotifyJVMTI && JvmtiExport::can_post_interpreter_events()) {
2018     Label L;
2019     // Note: frame::interpreter_frame_result has a dependency on how the
2020     // method result is saved across the call to post_method_exit. If this
2021     // is changed then the interpreter_frame_result implementation will
2022     // need to be updated too.
2023 
2024     // template interpreter will leave the result on the top of the stack.
2025     push(state);
2026     movl(rdx, Address(rthread, JavaThread::interp_only_mode_offset()));
2027     testl(rdx, rdx);
2028     jcc(Assembler::zero, L);
2029     call_VM(noreg,
2030             CAST_FROM_FN_PTR(address, InterpreterRuntime::post_method_exit));
2031     bind(L);
2032     pop(state);
2033   }
2034 
2035   if (DTraceMethodProbes) {
2036     push(state);
2037     get_method(rarg);
2038     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2039                  rthread, rarg);
2040     pop(state);
2041   }
2042 }
2043 
2044 void InterpreterMacroAssembler::load_resolved_indy_entry(Register cache, Register index) {
2045   // Get index out of bytecode pointer
2046   get_cache_index_at_bcp(index, 1, sizeof(u4));
2047   // Get address of invokedynamic array
2048   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2049   movptr(cache, Address(cache, in_bytes(ConstantPoolCache::invokedynamic_entries_offset())));
2050   if (is_power_of_2(sizeof(ResolvedIndyEntry))) {
2051     shll(index, log2i_exact(sizeof(ResolvedIndyEntry))); // Scale index by power of 2
2052   } else {
2053     imull(index, index, sizeof(ResolvedIndyEntry)); // Scale the index to be the entry index * sizeof(ResolvedIndyEntry)
2054   }
2055   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedIndyEntry>::base_offset_in_bytes()));
2056 }
2057 
2058 void InterpreterMacroAssembler::load_field_entry(Register cache, Register index, int bcp_offset) {
2059   // Get index out of bytecode pointer
2060   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2061   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2062 
2063   movptr(cache, Address(cache, ConstantPoolCache::field_entries_offset()));
2064   // Take shortcut if the size is a power of 2
2065   if (is_power_of_2(sizeof(ResolvedFieldEntry))) {
2066     shll(index, log2i_exact(sizeof(ResolvedFieldEntry))); // Scale index by power of 2
2067   } else {
2068     imull(index, index, sizeof(ResolvedFieldEntry)); // Scale the index to be the entry index * sizeof(ResolvedFieldEntry)
2069   }
2070   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedFieldEntry>::base_offset_in_bytes()));
2071 }
2072 
2073 void InterpreterMacroAssembler::load_method_entry(Register cache, Register index, int bcp_offset) {
2074   // Get index out of bytecode pointer
2075   movptr(cache, Address(rbp, frame::interpreter_frame_cache_offset * wordSize));
2076   get_cache_index_at_bcp(index, bcp_offset, sizeof(u2));
2077 
2078   movptr(cache, Address(cache, ConstantPoolCache::method_entries_offset()));
2079   imull(index, index, sizeof(ResolvedMethodEntry)); // Scale the index to be the entry index * sizeof(ResolvedMethodEntry)
2080   lea(cache, Address(cache, index, Address::times_1, Array<ResolvedMethodEntry>::base_offset_in_bytes()));
2081 }