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