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