1 /*
   2  * Copyright (c) 2003, 2026, 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 "asm/macroAssembler.inline.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "compiler/compiler_globals.hpp"
  30 #include "gc/shared/barrierSetAssembler.hpp"
  31 #include "interpreter/bytecodeHistogram.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interpreterRuntime.hpp"
  34 #include "interpreter/interp_masm.hpp"
  35 #include "interpreter/templateInterpreterGenerator.hpp"
  36 #include "interpreter/templateTable.hpp"
  37 #include "interpreter/bytecodeTracer.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/arrayOop.hpp"
  40 #include "oops/method.hpp"
  41 #include "oops/methodCounters.hpp"
  42 #include "oops/methodData.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/inlineKlass.hpp"
  45 #include "oops/resolvedIndyEntry.hpp"
  46 #include "oops/resolvedMethodEntry.hpp"
  47 #include "prims/jvmtiExport.hpp"
  48 #include "prims/jvmtiThreadState.hpp"
  49 #include "runtime/arguments.hpp"
  50 #include "runtime/deoptimization.hpp"
  51 #include "runtime/frame.inline.hpp"
  52 #include "runtime/globals.hpp"
  53 #include "runtime/jniHandles.hpp"
  54 #include "runtime/sharedRuntime.hpp"
  55 #include "runtime/stubRoutines.hpp"
  56 #include "runtime/synchronizer.hpp"
  57 #include "runtime/timer.hpp"
  58 #include "runtime/vframeArray.hpp"
  59 #include "utilities/checkedCast.hpp"
  60 #include "utilities/debug.hpp"
  61 #include "utilities/powerOfTwo.hpp"
  62 #include <sys/types.h>
  63 
  64 // Size of interpreter code.  Increase if too small.  Interpreter will
  65 // fail with a guarantee ("not enough space for interpreter generation");
  66 // if too small.
  67 // Run with +PrintInterpreter to get the VM to print out the size.
  68 // Max size with JVMTI
  69 int TemplateInterpreter::InterpreterCodeSize = 200 * 1024;
  70 
  71 #define __ Disassembler::hook<InterpreterMacroAssembler>(__FILE__, __LINE__, _masm)->
  72 
  73 address TemplateInterpreterGenerator::generate_slow_signature_handler() {
  74   address entry = __ pc();
  75 
  76   __ andr(esp, esp, -16);
  77   __ mov(c_rarg3, esp);
  78   // rmethod
  79   // rlocals
  80   // c_rarg3: first stack arg - wordSize
  81 
  82   // adjust sp
  83   __ sub(sp, c_rarg3, 18 * wordSize);
  84   __ str(lr, Address(__ pre(sp, -2 * wordSize)));
  85   __ call_VM(noreg,
  86              CAST_FROM_FN_PTR(address,
  87                               InterpreterRuntime::slow_signature_handler),
  88              rmethod, rlocals, c_rarg3);
  89 
  90   // r0: result handler
  91 
  92   // Stack layout:
  93   // rsp: return address           <- sp
  94   //      1 garbage
  95   //      8 integer args (if static first is unused)
  96   //      1 float/double identifiers
  97   //      8 double args
  98   //        stack args              <- esp
  99   //        garbage
 100   //        expression stack bottom
 101   //        bcp (null)
 102   //        ...
 103 
 104   // Restore LR
 105   __ ldr(lr, Address(__ post(sp, 2 * wordSize)));
 106 
 107   // Do FP first so we can use c_rarg3 as temp
 108   __ ldrw(c_rarg3, Address(sp, 9 * wordSize)); // float/double identifiers
 109 
 110   for (int i = 0; i < Argument::n_float_register_parameters_c; i++) {
 111     const FloatRegister r = as_FloatRegister(i);
 112 
 113     Label d, done;
 114 
 115     __ tbnz(c_rarg3, i, d);
 116     __ ldrs(r, Address(sp, (10 + i) * wordSize));
 117     __ b(done);
 118     __ bind(d);
 119     __ ldrd(r, Address(sp, (10 + i) * wordSize));
 120     __ bind(done);
 121   }
 122 
 123   // c_rarg0 contains the result from the call of
 124   // InterpreterRuntime::slow_signature_handler so we don't touch it
 125   // here.  It will be loaded with the JNIEnv* later.
 126   __ ldr(c_rarg1, Address(sp, 1 * wordSize));
 127   for (int i = c_rarg2->encoding(); i <= c_rarg7->encoding(); i += 2) {
 128     Register rm = as_Register(i), rn = as_Register(i+1);
 129     __ ldp(rm, rn, Address(sp, i * wordSize));
 130   }
 131 
 132   __ add(sp, sp, 18 * wordSize);
 133   __ ret(lr);
 134 
 135   return entry;
 136 }
 137 
 138 
 139 //
 140 // Various method entries
 141 //
 142 
 143 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
 144   // rmethod: Method*
 145   // r19_sender_sp: sender sp
 146   // esp: args
 147 
 148   // These don't need a safepoint check because they aren't virtually
 149   // callable. We won't enter these intrinsics from compiled code.
 150   // If in the future we added an intrinsic which was virtually callable
 151   // we'd have to worry about how to safepoint so that this code is used.
 152 
 153   // mathematical functions inlined by compiler
 154   // (interpreter must provide identical implementation
 155   // in order to avoid monotonicity bugs when switching
 156   // from interpreter to compiler in the middle of some
 157   // computation)
 158   //
 159   // stack:
 160   //        [ arg ] <-- esp
 161   //        [ arg ]
 162   // retaddr in lr
 163 
 164   address entry_point = nullptr;
 165   Register continuation = lr;
 166   switch (kind) {
 167   case Interpreter::java_lang_math_abs:
 168     entry_point = __ pc();
 169     __ ldrd(v0, Address(esp));
 170     __ fabsd(v0, v0);
 171     __ mov(sp, r19_sender_sp); // Restore caller's SP
 172     break;
 173   case Interpreter::java_lang_math_sqrt:
 174     entry_point = __ pc();
 175     __ ldrd(v0, Address(esp));
 176     __ fsqrtd(v0, v0);
 177     __ mov(sp, r19_sender_sp);
 178     break;
 179   case Interpreter::java_lang_math_sin :
 180   case Interpreter::java_lang_math_cos :
 181   case Interpreter::java_lang_math_tan :
 182   case Interpreter::java_lang_math_log :
 183   case Interpreter::java_lang_math_log10 :
 184   case Interpreter::java_lang_math_exp :
 185     entry_point = __ pc();
 186     __ ldrd(v0, Address(esp));
 187     __ mov(sp, r19_sender_sp);
 188     __ mov(r23, lr);
 189     continuation = r23;  // The first free callee-saved register
 190     generate_transcendental_entry(kind, 1);
 191     break;
 192   case Interpreter::java_lang_math_pow :
 193     entry_point = __ pc();
 194     __ mov(r23, lr);
 195     continuation = r23;
 196     __ ldrd(v0, Address(esp, 2 * Interpreter::stackElementSize));
 197     __ ldrd(v1, Address(esp));
 198     __ mov(sp, r19_sender_sp);
 199     generate_transcendental_entry(kind, 2);
 200     break;
 201   case Interpreter::java_lang_math_fmaD :
 202     if (UseFMA) {
 203       entry_point = __ pc();
 204       __ ldrd(v0, Address(esp, 4 * Interpreter::stackElementSize));
 205       __ ldrd(v1, Address(esp, 2 * Interpreter::stackElementSize));
 206       __ ldrd(v2, Address(esp));
 207       __ fmaddd(v0, v0, v1, v2);
 208       __ mov(sp, r19_sender_sp); // Restore caller's SP
 209     }
 210     break;
 211   case Interpreter::java_lang_math_fmaF :
 212     if (UseFMA) {
 213       entry_point = __ pc();
 214       __ ldrs(v0, Address(esp, 2 * Interpreter::stackElementSize));
 215       __ ldrs(v1, Address(esp, Interpreter::stackElementSize));
 216       __ ldrs(v2, Address(esp));
 217       __ fmadds(v0, v0, v1, v2);
 218       __ mov(sp, r19_sender_sp); // Restore caller's SP
 219     }
 220     break;
 221   default:
 222     ;
 223   }
 224   if (entry_point) {
 225     __ br(continuation);
 226   }
 227 
 228   return entry_point;
 229 }
 230 
 231   // double trigonometrics and transcendentals
 232   // static jdouble dsin(jdouble x);
 233   // static jdouble dcos(jdouble x);
 234   // static jdouble dtan(jdouble x);
 235   // static jdouble dlog(jdouble x);
 236   // static jdouble dlog10(jdouble x);
 237   // static jdouble dexp(jdouble x);
 238   // static jdouble dpow(jdouble x, jdouble y);
 239 
 240 void TemplateInterpreterGenerator::generate_transcendental_entry(AbstractInterpreter::MethodKind kind, int fpargs) {
 241   address fn;
 242   switch (kind) {
 243   case Interpreter::java_lang_math_sin :
 244     if (StubRoutines::dsin() == nullptr) {
 245       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);
 246     } else {
 247       fn = CAST_FROM_FN_PTR(address, StubRoutines::dsin());
 248     }
 249     break;
 250   case Interpreter::java_lang_math_cos :
 251     if (StubRoutines::dcos() == nullptr) {
 252       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);
 253     } else {
 254       fn = CAST_FROM_FN_PTR(address, StubRoutines::dcos());
 255     }
 256     break;
 257   case Interpreter::java_lang_math_tan :
 258     if (StubRoutines::dtan() == nullptr) {
 259       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);
 260     } else {
 261       fn = CAST_FROM_FN_PTR(address, StubRoutines::dtan());
 262     }
 263     break;
 264   case Interpreter::java_lang_math_log :
 265     if (StubRoutines::dlog() == nullptr) {
 266       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);
 267     } else {
 268       fn = CAST_FROM_FN_PTR(address, StubRoutines::dlog());
 269     }
 270     break;
 271   case Interpreter::java_lang_math_log10 :
 272     if (StubRoutines::dlog10() == nullptr) {
 273       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10);
 274     } else {
 275       fn = CAST_FROM_FN_PTR(address, StubRoutines::dlog10());
 276     }
 277     break;
 278   case Interpreter::java_lang_math_exp :
 279     if (StubRoutines::dexp() == nullptr) {
 280       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);
 281     } else {
 282       fn = CAST_FROM_FN_PTR(address, StubRoutines::dexp());
 283     }
 284     break;
 285   case Interpreter::java_lang_math_pow :
 286     if (StubRoutines::dpow() == nullptr) {
 287       fn = CAST_FROM_FN_PTR(address, SharedRuntime::dpow);
 288     } else {
 289       fn = CAST_FROM_FN_PTR(address, StubRoutines::dpow());
 290     }
 291     break;
 292   default:
 293     ShouldNotReachHere();
 294     fn = nullptr;  // unreachable
 295   }
 296   __ mov(rscratch1, fn);
 297   __ blr(rscratch1);
 298 }
 299 
 300 address TemplateInterpreterGenerator::generate_Float_float16ToFloat_entry() {
 301   assert(VM_Version::supports_float16(), "this intrinsic is not supported");
 302   // r19_sender_sp: sender sp
 303   // stack:
 304   //        [ arg ] <-- esp
 305   //        [ arg ]
 306   // retaddr in lr
 307   // result in v0
 308 
 309   address entry_point = __ pc();
 310   __ ldrw(c_rarg0, Address(esp));
 311   __ flt16_to_flt(v0, c_rarg0, v1);
 312   __ mov(sp, r19_sender_sp); // Restore caller's SP
 313   __ br(lr);
 314   return entry_point;
 315 }
 316 
 317 address TemplateInterpreterGenerator::generate_Float_floatToFloat16_entry() {
 318   assert(VM_Version::supports_float16(), "this intrinsic is not supported");
 319   // r19_sender_sp: sender sp
 320   // stack:
 321   //        [ arg ] <-- esp
 322   //        [ arg ]
 323   // retaddr in lr
 324   // result in c_rarg0
 325 
 326   address entry_point = __ pc();
 327   __ ldrs(v0, Address(esp));
 328   __ flt_to_flt16(c_rarg0, v0, v1);
 329   __ mov(sp, r19_sender_sp); // Restore caller's SP
 330   __ br(lr);
 331   return entry_point;
 332 }
 333 
 334 // Abstract method entry
 335 // Attempt to execute abstract method. Throw exception
 336 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
 337   // rmethod: Method*
 338   // r19_sender_sp: sender SP
 339 
 340   address entry_point = __ pc();
 341 
 342   // abstract method entry
 343 
 344   //  pop return address, reset last_sp to null
 345   __ empty_expression_stack();
 346   __ restore_bcp();      // bcp must be correct for exception handler   (was destroyed)
 347   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
 348 
 349   // throw exception
 350   __ call_VM(noreg, CAST_FROM_FN_PTR(address,
 351                                      InterpreterRuntime::throw_AbstractMethodErrorWithMethod),
 352                                      rmethod);
 353   // the call_VM checks for exception, so we should never return here.
 354   __ should_not_reach_here();
 355 
 356   return entry_point;
 357 }
 358 
 359 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
 360   address entry = __ pc();
 361 
 362 #ifdef ASSERT
 363   {
 364     Label L;
 365     __ ldr(rscratch1, Address(rfp,
 366                        frame::interpreter_frame_monitor_block_top_offset *
 367                        wordSize));
 368     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 369     __ mov(rscratch2, sp);
 370     __ cmp(rscratch1, rscratch2); // maximal rsp for current rfp (stack
 371                            // grows negative)
 372     __ br(Assembler::HS, L); // check if frame is complete
 373     __ stop ("interpreter frame not set up");
 374     __ bind(L);
 375   }
 376 #endif // ASSERT
 377   // Restore bcp under the assumption that the current frame is still
 378   // interpreted
 379   __ restore_bcp();
 380 
 381   // expression stack must be empty before entering the VM if an
 382   // exception happened
 383   __ empty_expression_stack();
 384   // throw exception
 385   __ call_VM(noreg,
 386              CAST_FROM_FN_PTR(address,
 387                               InterpreterRuntime::throw_StackOverflowError));
 388   return entry;
 389 }
 390 
 391 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 392   address entry = __ pc();
 393   // expression stack must be empty before entering the VM if an
 394   // exception happened
 395   __ empty_expression_stack();
 396   // setup parameters
 397 
 398   // ??? convention: expect aberrant index in register r1
 399   __ movw(c_rarg2, r1);
 400   // ??? convention: expect array in register r3
 401   __ mov(c_rarg1, r3);
 402   __ call_VM(noreg,
 403              CAST_FROM_FN_PTR(address,
 404                               InterpreterRuntime::
 405                               throw_ArrayIndexOutOfBoundsException),
 406              c_rarg1, c_rarg2);
 407   return entry;
 408 }
 409 
 410 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 411   address entry = __ pc();
 412 
 413   // object is at TOS
 414   __ pop(c_rarg1);
 415 
 416   // expression stack must be empty before entering the VM if an
 417   // exception happened
 418   __ empty_expression_stack();
 419 
 420   __ call_VM(noreg,
 421              CAST_FROM_FN_PTR(address,
 422                               InterpreterRuntime::
 423                               throw_ClassCastException),
 424              c_rarg1);
 425   return entry;
 426 }
 427 
 428 address TemplateInterpreterGenerator::generate_exception_handler_common(
 429         const char* name, const char* message, bool pass_oop) {
 430   assert(!pass_oop || message == nullptr, "either oop or message but not both");
 431   address entry = __ pc();
 432   if (pass_oop) {
 433     // object is at TOS
 434     __ pop(c_rarg2);
 435   }
 436   // expression stack must be empty before entering the VM if an
 437   // exception happened
 438   __ empty_expression_stack();
 439   // setup parameters
 440   __ lea(c_rarg1, Address((address)name));
 441   if (pass_oop) {
 442     __ call_VM(r0, CAST_FROM_FN_PTR(address,
 443                                     InterpreterRuntime::
 444                                     create_klass_exception),
 445                c_rarg1, c_rarg2);
 446   } else {
 447     // kind of lame ExternalAddress can't take null because
 448     // external_word_Relocation will assert.
 449     if (message != nullptr) {
 450       __ lea(c_rarg2, Address((address)message));
 451     } else {
 452       __ mov(c_rarg2, NULL_WORD);
 453     }
 454     __ call_VM(r0,
 455                CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception),
 456                c_rarg1, c_rarg2);
 457   }
 458   // throw exception
 459   __ b(address(Interpreter::throw_exception_entry()));
 460   return entry;
 461 }
 462 
 463 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 464   address entry = __ pc();
 465 
 466   // Restore stack bottom in case i2c adjusted stack
 467   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 468   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 469   // and null it as marker that esp is now tos until next java call
 470   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 471 
 472   if (state == atos && InlineTypeReturnedAsFields) {
 473     __ store_inline_type_fields_to_buf(nullptr, true);
 474   }
 475 
 476   __ restore_bcp();
 477   __ restore_locals();
 478   __ restore_constant_pool_cache();
 479   __ get_method(rmethod);
 480 
 481   if (state == atos) {
 482     Register obj = r0;
 483     Register mdp = r1;
 484     Register tmp = r2;
 485     __ profile_return_type(mdp, obj, tmp);
 486   }
 487 
 488   const Register cache = r1;
 489   const Register index = r2;
 490 
 491   if (index_size == sizeof(u4)) {
 492     __ load_resolved_indy_entry(cache, index);
 493     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedIndyEntry::num_parameters_offset())));
 494     __ add(esp, esp, cache, Assembler::LSL, 3);
 495   } else {
 496     // Pop N words from the stack
 497     assert(index_size == sizeof(u2), "Can only be u2");
 498     __ load_method_entry(cache, index);
 499     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedMethodEntry::num_parameters_offset())));
 500     __ add(esp, esp, cache, Assembler::LSL, 3);
 501   }
 502 
 503   // Restore machine SP
 504   __ restore_sp_after_call();
 505 
 506   __ check_and_handle_popframe(rthread);
 507   __ check_and_handle_earlyret(rthread);
 508 
 509   __ get_dispatch();
 510   __ dispatch_next(state, step);
 511 
 512   return entry;
 513 }
 514 
 515 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state,
 516                                                                int step,
 517                                                                address continuation) {
 518   address entry = __ pc();
 519   __ restore_bcp();
 520   __ restore_locals();
 521   __ restore_constant_pool_cache();
 522   __ get_method(rmethod);
 523   __ get_dispatch();
 524 
 525   __ restore_sp_after_call();  // Restore SP to extended SP
 526 
 527   // Restore expression stack pointer
 528   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 529   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 530   // null last_sp until next java call
 531   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 532 
 533   // handle exceptions
 534   {
 535     Label L;
 536     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
 537     __ cbz(rscratch1, L);
 538     __ call_VM(noreg,
 539                CAST_FROM_FN_PTR(address,
 540                                 InterpreterRuntime::throw_pending_exception));
 541     __ should_not_reach_here();
 542     __ bind(L);
 543   }
 544 
 545   if (continuation == nullptr) {
 546     __ dispatch_next(state, step);
 547   } else {
 548     __ jump_to_entry(continuation);
 549   }
 550   return entry;
 551 }
 552 
 553 address TemplateInterpreterGenerator::generate_result_handler_for(
 554         BasicType type) {
 555     address entry = __ pc();
 556   switch (type) {
 557   case T_BOOLEAN: __ c2bool(r0);         break;
 558   case T_CHAR   : __ uxth(r0, r0);       break;
 559   case T_BYTE   : __ sxtb(r0, r0);        break;
 560   case T_SHORT  : __ sxth(r0, r0);        break;
 561   case T_INT    : __ uxtw(r0, r0);        break;  // FIXME: We almost certainly don't need this
 562   case T_LONG   : /* nothing to do */        break;
 563   case T_VOID   : /* nothing to do */        break;
 564   case T_FLOAT  : /* nothing to do */        break;
 565   case T_DOUBLE : /* nothing to do */        break;
 566   case T_OBJECT :
 567     // retrieve result from frame
 568     __ ldr(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
 569     // and verify it
 570     __ verify_oop(r0);
 571     break;
 572   default       : ShouldNotReachHere();
 573   }
 574   __ ret(lr);                                  // return from result handler
 575   return entry;
 576 }
 577 
 578 address TemplateInterpreterGenerator::generate_safept_entry_for(
 579         TosState state,
 580         address runtime_entry) {
 581   address entry = __ pc();
 582   __ push(state);
 583   __ push_cont_fastpath(rthread);
 584   __ call_VM(noreg, runtime_entry);
 585   __ pop_cont_fastpath(rthread);
 586   __ membar(Assembler::AnyAny);
 587   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 588   return entry;
 589 }
 590 
 591 address TemplateInterpreterGenerator::generate_cont_resume_interpreter_adapter() {
 592   if (!Continuations::enabled()) return nullptr;
 593   address start = __ pc();
 594 
 595   __ restore_bcp();
 596   __ restore_locals();
 597 
 598   // Restore constant pool cache
 599   __ ldr(rcpool, Address(rfp, frame::interpreter_frame_cache_offset * wordSize));
 600 
 601   // Restore Java expression stack pointer
 602   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 603   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 604   // and null it as marker that esp is now tos until next java call
 605   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 606 
 607   // Restore machine SP
 608   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 609   __ lea(sp, Address(rfp, rscratch1, Address::lsl(LogBytesPerWord)));
 610 
 611   // Restore method
 612   __ ldr(rmethod, Address(rfp, frame::interpreter_frame_method_offset * wordSize));
 613 
 614   // Restore dispatch
 615   uint64_t offset;
 616   __ adrp(rdispatch, ExternalAddress((address)Interpreter::dispatch_table()), offset);
 617   __ add(rdispatch, rdispatch, offset);
 618 
 619   __ ret(lr);
 620 
 621   return start;
 622 }
 623 
 624 
 625 // Helpers for commoning out cases in the various type of method entries.
 626 //
 627 
 628 
 629 // increment invocation count & check for overflow
 630 //
 631 // Note: checking for negative value instead of overflow
 632 //       so we have a 'sticky' overflow test
 633 //
 634 // rmethod: method
 635 //
 636 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 637   Label done;
 638   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 639   int increment = InvocationCounter::count_increment;
 640   Label no_mdo;
 641   if (ProfileInterpreter) {
 642     // Are we profiling?
 643     __ ldr(r0, Address(rmethod, Method::method_data_offset()));
 644     __ cbz(r0, no_mdo);
 645     // Increment counter in the MDO
 646     const Address mdo_invocation_counter(r0, in_bytes(MethodData::invocation_counter_offset()) +
 647                                               in_bytes(InvocationCounter::counter_offset()));
 648     const Address mask(r0, in_bytes(MethodData::invoke_mask_offset()));
 649     __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rscratch1, rscratch2, false, Assembler::EQ, overflow);
 650     __ b(done);
 651   }
 652   __ bind(no_mdo);
 653   // Increment counter in MethodCounters
 654   const Address invocation_counter(rscratch2,
 655                 MethodCounters::invocation_counter_offset() +
 656                 InvocationCounter::counter_offset());
 657   __ get_method_counters(rmethod, rscratch2, done);
 658   const Address mask(rscratch2, in_bytes(MethodCounters::invoke_mask_offset()));
 659   __ increment_mask_and_jump(invocation_counter, increment, mask, rscratch1, r1, false, Assembler::EQ, overflow);
 660   __ bind(done);
 661 }
 662 
 663 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 664 
 665   // Asm interpreter on entry
 666   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 667   // Everything as it was on entry
 668 
 669   // InterpreterRuntime::frequency_counter_overflow takes two
 670   // arguments, the first (thread) is passed by call_VM, the second
 671   // indicates if the counter overflow occurs at a backwards branch
 672   // (null bcp).  We pass zero for it.  The call returns the address
 673   // of the verified entry point for the method or null if the
 674   // compilation did not complete (either went background or bailed
 675   // out).
 676   __ mov(c_rarg1, 0);
 677   __ call_VM(noreg,
 678              CAST_FROM_FN_PTR(address,
 679                               InterpreterRuntime::frequency_counter_overflow),
 680              c_rarg1);
 681 
 682   __ b(do_continue);
 683 }
 684 
 685 // See if we've got enough room on the stack for locals plus overhead
 686 // below JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 687 // without going through the signal handler, i.e., reserved and yellow zones
 688 // will not be made usable. The shadow zone must suffice to handle the
 689 // overflow.
 690 // The expression stack grows down incrementally, so the normal guard
 691 // page mechanism will work for that.
 692 //
 693 // NOTE: Since the additional locals are also always pushed (wasn't
 694 // obvious in generate_method_entry) so the guard should work for them
 695 // too.
 696 //
 697 // Args:
 698 //      r3: number of additional locals this frame needs (what we must check)
 699 //      rmethod: Method*
 700 //
 701 // Kills:
 702 //      r0
 703 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 704 
 705   // monitor entry size: see picture of stack set
 706   // (generate_method_entry) and frame_amd64.hpp
 707   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 708 
 709   // total overhead size: entry_size + (saved rbp through expr stack
 710   // bottom).  be sure to change this if you add/subtract anything
 711   // to/from the overhead area
 712   const int overhead_size =
 713     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 714 
 715   const size_t page_size = os::vm_page_size();
 716 
 717   Label after_frame_check;
 718 
 719   // see if the frame is greater than one page in size. If so,
 720   // then we need to verify there is enough stack space remaining
 721   // for the additional locals.
 722   //
 723   // Note that we use SUBS rather than CMP here because the immediate
 724   // field of this instruction may overflow.  SUBS can cope with this
 725   // because it is a macro that will expand to some number of MOV
 726   // instructions and a register operation.
 727   __ subs(rscratch1, r3, (page_size - overhead_size) / Interpreter::stackElementSize);
 728   __ br(Assembler::LS, after_frame_check);
 729 
 730   // compute rsp as if this were going to be the last frame on
 731   // the stack before the red zone
 732 
 733   // locals + overhead, in bytes
 734   __ mov(r0, overhead_size);
 735   __ add(r0, r0, r3, Assembler::LSL, Interpreter::logStackElementSize);  // 2 slots per parameter.
 736 
 737   const Address stack_limit(rthread, JavaThread::stack_overflow_limit_offset());
 738   __ ldr(rscratch1, stack_limit);
 739 
 740 #ifdef ASSERT
 741   Label limit_okay;
 742   // Verify that thread stack limit is non-zero.
 743   __ cbnz(rscratch1, limit_okay);
 744   __ stop("stack overflow limit is zero");
 745   __ bind(limit_okay);
 746 #endif
 747 
 748   // Add stack limit to locals.
 749   __ add(r0, r0, rscratch1);
 750 
 751   // Check against the current stack bottom.
 752   __ cmp(sp, r0);
 753   __ br(Assembler::HI, after_frame_check);
 754 
 755   // Remove the incoming args, peeling the machine SP back to where it
 756   // was in the caller.  This is not strictly necessary, but unless we
 757   // do so the stack frame may have a garbage FP; this ensures a
 758   // correct call stack that we can always unwind.  The ANDR should be
 759   // unnecessary because the sender SP in r19 is always aligned, but
 760   // it doesn't hurt.
 761   __ andr(sp, r19_sender_sp, -16);
 762 
 763   // Note: the restored frame is not necessarily interpreted.
 764   // Use the shared runtime version of the StackOverflowError.
 765   assert(SharedRuntime::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 766   __ far_jump(RuntimeAddress(SharedRuntime::throw_StackOverflowError_entry()));
 767 
 768   // all done with frame size check
 769   __ bind(after_frame_check);
 770 }
 771 
 772 // Allocate monitor and lock method (asm interpreter)
 773 //
 774 // Args:
 775 //      rmethod: Method*
 776 //      rlocals: locals
 777 //
 778 // Kills:
 779 //      r0
 780 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 781 //      rscratch1, rscratch2 (scratch regs)
 782 void TemplateInterpreterGenerator::lock_method() {
 783   // synchronize method
 784   const Address access_flags(rmethod, Method::access_flags_offset());
 785   const Address monitor_block_top(
 786         rfp,
 787         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 788   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 789 
 790 #ifdef ASSERT
 791   {
 792     Label L;
 793     __ ldrh(r0, access_flags);
 794     __ tst(r0, JVM_ACC_SYNCHRONIZED);
 795     __ br(Assembler::NE, L);
 796     __ stop("method doesn't need synchronization");
 797     __ bind(L);
 798   }
 799 #endif // ASSERT
 800 
 801   // get synchronization object
 802   {
 803     Label done;
 804     __ ldrh(r0, access_flags);
 805     __ tst(r0, JVM_ACC_STATIC);
 806     // get receiver (assume this is frequent case)
 807     __ ldr(r0, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 808     __ br(Assembler::EQ, done);
 809     __ load_mirror(r0, rmethod, r5, rscratch2);
 810 
 811 #ifdef ASSERT
 812     {
 813       Label L;
 814       __ cbnz(r0, L);
 815       __ stop("synchronization object is null");
 816       __ bind(L);
 817     }
 818 #endif // ASSERT
 819 
 820     __ bind(done);
 821   }
 822 
 823   // add space for monitor & lock
 824   __ check_extended_sp();
 825   __ sub(sp, sp, entry_size); // add space for a monitor entry
 826   __ sub(esp, esp, entry_size);
 827   __ sub(rscratch1, sp, rfp);
 828   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 829   __ str(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 830   __ sub(rscratch1, esp, rfp);
 831   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 832   __ str(rscratch1, monitor_block_top);  // set new monitor block top
 833 
 834   // store object
 835   __ str(r0, Address(esp, BasicObjectLock::obj_offset()));
 836   __ mov(c_rarg1, esp); // object address
 837   __ lock_object(c_rarg1);
 838 }
 839 
 840 // Generate a fixed interpreter frame. This is identical setup for
 841 // interpreted methods and for native methods hence the shared code.
 842 //
 843 // Args:
 844 //      lr: return address
 845 //      rmethod: Method*
 846 //      rlocals: pointer to locals
 847 //      rcpool: cp cache
 848 //      stack_pointer: previous sp
 849 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 850   // Save ConstMethod* in r5_const_method for later use to avoid loading multiple times
 851   Register r5_const_method = r5;
 852   __ ldr(r5_const_method, Address(rmethod, Method::const_offset()));
 853 
 854   // initialize fixed part of activation frame
 855   if (native_call) {
 856     __ sub(esp, sp, 14 *  wordSize);
 857     __ mov(rbcp, zr);
 858     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 859     __ stp(rscratch1, zr, Address(__ pre(sp, -14 * wordSize)));
 860     // add 2 zero-initialized slots for native calls
 861     __ stp(zr, zr, Address(sp, 12 * wordSize));
 862   } else {
 863     __ sub(esp, sp, 12 *  wordSize);
 864     __ add(rbcp, r5_const_method, in_bytes(ConstMethod::codes_offset())); // get codebase
 865     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 866     __ stp(rscratch1, rbcp, Address(__ pre(sp, -12 * wordSize)));
 867   }
 868 
 869   if (ProfileInterpreter) {
 870     Label method_data_continue;
 871     __ ldr(rscratch1, Address(rmethod, Method::method_data_offset()));
 872     __ cbz(rscratch1, method_data_continue);
 873     __ lea(rscratch1, Address(rscratch1, in_bytes(MethodData::data_offset())));
 874     __ bind(method_data_continue);
 875     __ stp(rscratch1, rmethod, Address(sp, 6 * wordSize));  // save Method* and mdp (method data pointer)
 876   } else {
 877     __ stp(zr, rmethod, Address(sp, 6 * wordSize));         // save Method* (no mdp)
 878   }
 879 
 880   __ protect_return_address();
 881   __ stp(rfp, lr, Address(sp, 10 * wordSize));
 882   __ lea(rfp, Address(sp, 10 * wordSize));
 883 
 884   // Save ConstantPool* in r11_constants for later use to avoid loading multiple times
 885   Register r11_constants = r11;
 886   __ ldr(r11_constants, Address(r5_const_method, ConstMethod::constants_offset()));
 887   __ ldr(rcpool, Address(r11_constants, ConstantPool::cache_offset()));
 888   __ sub(rscratch1, rlocals, rfp);
 889   __ lsr(rscratch1, rscratch1, Interpreter::logStackElementSize);   // rscratch1 = rlocals - fp();
 890   // Store relativized rlocals, see frame::interpreter_frame_locals().
 891   __ stp(rscratch1, rcpool, Address(sp, 2 * wordSize));
 892 
 893   // set sender sp
 894   // leave last_sp as null
 895   __ stp(zr, r19_sender_sp, Address(sp, 8 * wordSize));
 896 
 897   // Get mirror. Resolve ConstantPool* -> InstanceKlass* -> Java mirror.
 898   __ ldr(r10, Address(r11_constants, ConstantPool::pool_holder_offset()));
 899   __ ldr(r10, Address(r10, in_bytes(Klass::java_mirror_offset())));
 900   __ resolve_oop_handle(r10, rscratch1, rscratch2);
 901   if (! native_call) {
 902     __ ldrh(rscratch1, Address(r5_const_method, ConstMethod::max_stack_offset()));
 903     __ add(rscratch1, rscratch1, MAX2(3, Method::extra_stack_entries()));
 904     __ sub(rscratch1, sp, rscratch1, ext::uxtw, 3);
 905     __ andr(rscratch1, rscratch1, -16);
 906     __ sub(rscratch2, rscratch1, rfp);
 907     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 908     // Store extended SP and mirror
 909     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 910     // Move SP out of the way
 911     __ mov(sp, rscratch1);
 912   } else {
 913     // Make sure there is room for the exception oop pushed in case method throws
 914     // an exception (see TemplateInterpreterGenerator::generate_throw_exception())
 915     __ sub(rscratch1, sp, 2 * wordSize);
 916     __ sub(rscratch2, rscratch1, rfp);
 917     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 918     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 919     __ mov(sp, rscratch1);
 920   }
 921 }
 922 
 923 // End of helpers
 924 
 925 // Various method entries
 926 //------------------------------------------------------------------------------------------------------------------------
 927 //
 928 //
 929 
 930 // Method entry for java.lang.ref.Reference.get.
 931 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 932   // Code: _aload_0, _getfield, _areturn
 933   // parameter size = 1
 934   //
 935   // The code that gets generated by this routine is split into 2 parts:
 936   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 937   //    2. The slow path - which is an expansion of the regular method entry.
 938   //
 939   // Notes:-
 940   // * In the G1 code we do not check whether we need to block for
 941   //   a safepoint. If G1 is enabled then we must execute the specialized
 942   //   code for Reference.get (except when the Reference object is null)
 943   //   so that we can log the value in the referent field with an SATB
 944   //   update buffer.
 945   //   If the code for the getfield template is modified so that the
 946   //   G1 pre-barrier code is executed when the current method is
 947   //   Reference.get() then going through the normal method entry
 948   //   will be fine.
 949   // * The G1 code can, however, check the receiver object (the instance
 950   //   of java.lang.Reference) and jump to the slow path if null. If the
 951   //   Reference object is null then we obviously cannot fetch the referent
 952   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 953   //   regular method entry code to generate the NPE.
 954   //
 955   // This code is based on generate_accessor_entry.
 956   //
 957   // rmethod: Method*
 958   // r19_sender_sp: senderSP must preserve for slow path, set SP to it on fast path
 959 
 960   // LR is live.  It must be saved around calls.
 961 
 962   address entry = __ pc();
 963 
 964   const int referent_offset = java_lang_ref_Reference::referent_offset();
 965 
 966   Label slow_path;
 967   const Register local_0 = c_rarg0;
 968   // Check if local 0 != null
 969   // If the receiver is null then it is OK to jump to the slow path.
 970   __ ldr(local_0, Address(esp, 0));
 971   __ cbz(local_0, slow_path);
 972 
 973   // Load the value of the referent field.
 974   const Address field_address(local_0, referent_offset);
 975   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 976   bs->load_at(_masm, IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT, local_0, field_address, /*tmp1*/ rscratch1, /*tmp2*/ rscratch2);
 977 
 978   // areturn
 979   __ andr(sp, r19_sender_sp, -16);  // done with stack
 980   __ ret(lr);
 981 
 982   // generate a vanilla interpreter entry as the slow path
 983   __ bind(slow_path);
 984   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 985   return entry;
 986 
 987 }
 988 
 989 /**
 990  * Method entry for static native methods:
 991  *   int java.util.zip.CRC32.update(int crc, int b)
 992  */
 993 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
 994   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
 995   address entry = __ pc();
 996 
 997   // rmethod: Method*
 998   // r19_sender_sp: senderSP must preserved for slow path
 999   // esp: args
1000 
1001   Label slow_path;
1002   // If we need a safepoint check, generate full interpreter entry.
1003   __ safepoint_poll(slow_path, false /* at_return */, false /* in_nmethod */);
1004 
1005   // We don't generate local frame and don't align stack because
1006   // we call stub code and there is no safepoint on this path.
1007 
1008   // Load parameters
1009   const Register crc = c_rarg0;  // crc
1010   const Register val = c_rarg1;  // source java byte value
1011   const Register tbl = c_rarg2;  // scratch
1012 
1013   // Arguments are reversed on java expression stack
1014   __ ldrw(val, Address(esp, 0));              // byte value
1015   __ ldrw(crc, Address(esp, wordSize));       // Initial CRC
1016 
1017   uint64_t offset;
1018   __ adrp(tbl, ExternalAddress(StubRoutines::crc_table_addr()), offset);
1019   __ add(tbl, tbl, offset);
1020 
1021   __ mvnw(crc, crc); // ~crc
1022   __ update_byte_crc32(crc, val, tbl);
1023   __ mvnw(crc, crc); // ~crc
1024 
1025   // result in c_rarg0
1026 
1027   __ andr(sp, r19_sender_sp, -16);
1028   __ ret(lr);
1029 
1030   // generate a vanilla native entry as the slow path
1031   __ bind(slow_path);
1032   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1033   return entry;
1034 }
1035 
1036 /**
1037  * Method entry for static native methods:
1038  *   int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len)
1039  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
1040  */
1041 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1042   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1043   address entry = __ pc();
1044 
1045   // rmethod,: Method*
1046   // r19_sender_sp: senderSP must preserved for slow path
1047 
1048   Label slow_path;
1049   // If we need a safepoint check, generate full interpreter entry.
1050   __ safepoint_poll(slow_path, false /* at_return */, false /* in_nmethod */);
1051 
1052   // We don't generate local frame and don't align stack because
1053   // we call stub code and there is no safepoint on this path.
1054 
1055   // Load parameters
1056   const Register crc = c_rarg0;  // crc
1057   const Register buf = c_rarg1;  // source java byte array address
1058   const Register len = c_rarg2;  // length
1059   const Register off = len;      // offset (never overlaps with 'len')
1060 
1061   // Arguments are reversed on java expression stack
1062   // Calculate address of start element
1063   if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) {
1064     __ ldr(buf, Address(esp, 2*wordSize)); // long buf
1065     __ ldrw(off, Address(esp, wordSize)); // offset
1066     __ add(buf, buf, off); // + offset
1067     __ ldrw(crc,   Address(esp, 4*wordSize)); // Initial CRC
1068   } else {
1069     __ ldr(buf, Address(esp, 2*wordSize)); // byte[] array
1070     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1071     __ ldrw(off, Address(esp, wordSize)); // offset
1072     __ add(buf, buf, off); // + offset
1073     __ ldrw(crc,   Address(esp, 3*wordSize)); // Initial CRC
1074   }
1075   // Can now load 'len' since we're finished with 'off'
1076   __ ldrw(len, Address(esp, 0x0)); // Length
1077 
1078   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1079 
1080   // We are frameless so we can just jump to the stub.
1081   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()));
1082 
1083   // generate a vanilla native entry as the slow path
1084   __ bind(slow_path);
1085   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1086   return entry;
1087 }
1088 
1089 /**
1090  * Method entry for intrinsic-candidate (non-native) methods:
1091  *   int java.util.zip.CRC32C.updateBytes(int crc, byte[] b, int off, int end)
1092  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
1093  * Unlike CRC32, CRC32C does not have any methods marked as native
1094  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1095  */
1096 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1097   assert(UseCRC32CIntrinsics, "this intrinsic is not supported");
1098   address entry = __ pc();
1099 
1100   // Prepare jump to stub using parameters from the stack
1101   const Register crc = c_rarg0; // initial crc
1102   const Register buf = c_rarg1; // source java byte array address
1103   const Register len = c_rarg2; // len argument to the kernel
1104 
1105   const Register end = len; // index of last element to process
1106   const Register off = crc; // offset
1107 
1108   __ ldrw(end, Address(esp)); // int end
1109   __ ldrw(off, Address(esp, wordSize)); // int offset
1110   __ sub(len, end, off);
1111   __ ldr(buf, Address(esp, 2*wordSize)); // byte[] buf | long buf
1112   __ add(buf, buf, off); // + offset
1113   if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) {
1114     __ ldrw(crc, Address(esp, 4*wordSize)); // long crc
1115   } else {
1116     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1117     __ ldrw(crc, Address(esp, 3*wordSize)); // long crc
1118   }
1119 
1120   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1121 
1122   // Jump to the stub.
1123   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32C()));
1124 
1125   return entry;
1126 }
1127 
1128 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1129   // See more discussion in stackOverflow.hpp.
1130 
1131   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
1132   const int page_size = (int)os::vm_page_size();
1133   const int n_shadow_pages = shadow_zone_size / page_size;
1134 
1135 #ifdef ASSERT
1136   Label L_good_limit;
1137   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1138   __ cbnz(rscratch1, L_good_limit);
1139   __ stop("shadow zone safe limit is not initialized");
1140   __ bind(L_good_limit);
1141 
1142   Label L_good_watermark;
1143   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1144   __ cbnz(rscratch1, L_good_watermark);
1145   __ stop("shadow zone growth watermark is not initialized");
1146   __ bind(L_good_watermark);
1147 #endif
1148 
1149   Label L_done;
1150 
1151   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1152   __ cmp(sp, rscratch1);
1153   __ br(Assembler::HI, L_done);
1154 
1155   for (int p = 1; p <= n_shadow_pages; p++) {
1156     __ sub(rscratch2, sp, p*page_size);
1157     __ str(zr, Address(rscratch2));
1158   }
1159 
1160   // Record the new watermark, but only if the update is above the safe limit.
1161   // Otherwise, the next time around the check above would pass the safe limit.
1162   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1163   __ cmp(sp, rscratch1);
1164   __ br(Assembler::LS, L_done);
1165   __ mov(rscratch1, sp);
1166   __ str(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1167 
1168   __ bind(L_done);
1169 }
1170 
1171 // Interpreter stub for calling a native method. (asm interpreter)
1172 // This sets up a somewhat different looking stack for calling the
1173 // native method than the typical interpreter frame setup.
1174 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1175   // determine code generation flags
1176   bool inc_counter  = UseCompiler || CountCompiledCalls;
1177 
1178   // r1: Method*
1179   // rscratch1: sender sp
1180 
1181   address entry_point = __ pc();
1182 
1183   const Address constMethod       (rmethod, Method::const_offset());
1184   const Address access_flags      (rmethod, Method::access_flags_offset());
1185   const Address size_of_parameters(r2, ConstMethod::
1186                                        size_of_parameters_offset());
1187 
1188   // get parameter size (always needed)
1189   __ ldr(r2, constMethod);
1190   __ load_unsigned_short(r2, size_of_parameters);
1191 
1192   // Native calls don't need the stack size check since they have no
1193   // expression stack and the arguments are already on the stack and
1194   // we only add a handful of words to the stack.
1195 
1196   // rmethod: Method*
1197   // r2: size of parameters
1198   // rscratch1: sender sp
1199 
1200   // for natives the size of locals is zero
1201 
1202   // compute beginning of parameters (rlocals)
1203   __ add(rlocals, esp, r2, ext::uxtx, 3);
1204   __ add(rlocals, rlocals, -wordSize);
1205 
1206   // Pull SP back to minimum size: this avoids holes in the stack
1207   __ andr(sp, esp, -16);
1208 
1209   // initialize fixed part of activation frame
1210   generate_fixed_frame(true);
1211 
1212   // make sure method is native & not abstract
1213 #ifdef ASSERT
1214   __ ldrh(r0, access_flags);
1215   {
1216     Label L;
1217     __ tst(r0, JVM_ACC_NATIVE);
1218     __ br(Assembler::NE, L);
1219     __ stop("tried to execute non-native method as native");
1220     __ bind(L);
1221   }
1222   {
1223     Label L;
1224     __ tst(r0, JVM_ACC_ABSTRACT);
1225     __ br(Assembler::EQ, L);
1226     __ stop("tried to execute abstract method in interpreter");
1227     __ bind(L);
1228   }
1229 #endif
1230 
1231   // Since at this point in the method invocation the exception
1232   // handler would try to exit the monitor of synchronized methods
1233   // which hasn't been entered yet, we set the thread local variable
1234   // _do_not_unlock_if_synchronized to true. The remove_activation
1235   // will check this flag.
1236 
1237    const Address do_not_unlock_if_synchronized(rthread,
1238         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1239   __ mov(rscratch2, true);
1240   __ strb(rscratch2, do_not_unlock_if_synchronized);
1241 
1242   // increment invocation count & check for overflow
1243   Label invocation_counter_overflow;
1244   if (inc_counter) {
1245     generate_counter_incr(&invocation_counter_overflow);
1246   }
1247 
1248   Label continue_after_compile;
1249   __ bind(continue_after_compile);
1250 
1251   bang_stack_shadow_pages(true);
1252 
1253   // reset the _do_not_unlock_if_synchronized flag
1254   __ strb(zr, do_not_unlock_if_synchronized);
1255 
1256   // check for synchronized methods
1257   // Must happen AFTER invocation_counter check and stack overflow check,
1258   // so method is not locked if overflows.
1259   if (synchronized) {
1260     lock_method();
1261   } else {
1262     // no synchronization necessary
1263 #ifdef ASSERT
1264     {
1265       Label L;
1266       __ ldrh(r0, access_flags);
1267       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1268       __ br(Assembler::EQ, L);
1269       __ stop("method needs synchronization");
1270       __ bind(L);
1271     }
1272 #endif
1273   }
1274 
1275   // start execution
1276 #ifdef ASSERT
1277   {
1278     Label L;
1279     const Address monitor_block_top(rfp,
1280                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1281     __ ldr(rscratch1, monitor_block_top);
1282     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1283     __ cmp(esp, rscratch1);
1284     __ br(Assembler::EQ, L);
1285     __ stop("broken stack frame setup in interpreter 1");
1286     __ bind(L);
1287   }
1288 #endif
1289 
1290   // jvmti support
1291   __ notify_method_entry();
1292 
1293   // work registers
1294   const Register t = r17;
1295   const Register result_handler = r19;
1296 
1297   // allocate space for parameters
1298   __ ldr(t, Address(rmethod, Method::const_offset()));
1299   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
1300 
1301   __ sub(rscratch1, esp, t, ext::uxtx, Interpreter::logStackElementSize);
1302   __ andr(sp, rscratch1, -16);
1303   __ mov(esp, rscratch1);
1304 
1305   // get signature handler
1306   {
1307     Label L;
1308     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1309     __ cbnz(t, L);
1310     __ call_VM(noreg,
1311                CAST_FROM_FN_PTR(address,
1312                                 InterpreterRuntime::prepare_native_call),
1313                rmethod);
1314     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1315     __ bind(L);
1316   }
1317 
1318   // call signature handler
1319   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
1320          "adjust this code");
1321   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == sp,
1322          "adjust this code");
1323   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
1324           "adjust this code");
1325 
1326   // The generated handlers do not touch rmethod (the method).
1327   // However, large signatures cannot be cached and are generated
1328   // each time here.  The slow-path generator can do a GC on return,
1329   // so we must reload it after the call.
1330   __ blr(t);
1331   __ get_method(rmethod);        // slow path can do a GC, reload rmethod
1332 
1333 
1334   // result handler is in r0
1335   // set result handler
1336   __ mov(result_handler, r0);
1337   // Save it in the frame in case of preemption; we cannot rely on callee saved registers.
1338   __ str(r0, Address(rfp, frame::interpreter_frame_result_handler_offset * wordSize));
1339 
1340   // pass mirror handle if static call
1341   {
1342     Label L;
1343     __ ldrh(t, Address(rmethod, Method::access_flags_offset()));
1344     __ tbz(t, exact_log2(JVM_ACC_STATIC), L);
1345     // get mirror
1346     __ load_mirror(t, rmethod, r10, rscratch2);
1347     // copy mirror into activation frame
1348     __ str(t, Address(rfp, frame::interpreter_frame_oop_temp_offset * wordSize));
1349     // pass handle to mirror
1350     __ add(c_rarg1, rfp, frame::interpreter_frame_oop_temp_offset * wordSize);
1351     __ bind(L);
1352   }
1353 
1354   // get native function entry point in r10
1355   {
1356     Label L;
1357     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1358     ExternalAddress unsatisfied(SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1359     __ lea(rscratch2, unsatisfied);
1360     __ cmp(r10, rscratch2);
1361     __ br(Assembler::NE, L);
1362     __ call_VM(noreg,
1363                CAST_FROM_FN_PTR(address,
1364                                 InterpreterRuntime::prepare_native_call),
1365                rmethod);
1366     __ get_method(rmethod);
1367     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1368     __ bind(L);
1369   }
1370 
1371   // pass JNIEnv
1372   __ add(c_rarg0, rthread, in_bytes(JavaThread::jni_environment_offset()));
1373 
1374   // It is enough that the pc() points into the right code
1375   // segment. It does not have to be the correct return pc.
1376   // For convenience we use the pc we want to resume to in
1377   // case of preemption on Object.wait.
1378   Label native_return;
1379   __ set_last_Java_frame(esp, rfp, native_return, rscratch1);
1380 
1381   // change thread state
1382 #ifdef ASSERT
1383   {
1384     Label L;
1385     __ ldrw(t, Address(rthread, JavaThread::thread_state_offset()));
1386     __ cmp(t, (u1)_thread_in_Java);
1387     __ br(Assembler::EQ, L);
1388     __ stop("Wrong thread state in native stub");
1389     __ bind(L);
1390   }
1391 #endif
1392 
1393   // Change state to native
1394   __ mov(rscratch1, _thread_in_native);
1395   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1396   __ stlrw(rscratch1, rscratch2);
1397 
1398   __ push_cont_fastpath();
1399 
1400   // Call the native method.
1401   __ blr(r10);
1402 
1403   __ pop_cont_fastpath();
1404 
1405   __ get_method(rmethod);
1406   // result potentially in r0 or v0
1407 
1408   // Restore cpu control state after JNI call
1409   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
1410 
1411   // make room for the pushes we're about to do
1412   __ sub(rscratch1, esp, 4 * wordSize);
1413   __ andr(sp, rscratch1, -16);
1414 
1415   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
1416   // in order to extract the result of a method call. If the order of these
1417   // pushes change or anything else is added to the stack then the code in
1418   // interpreter_frame_result must also change.
1419   __ push(dtos);
1420   __ push(ltos);
1421 
1422   __ verify_sve_vector_length();
1423 
1424   // change thread state
1425   __ mov(rscratch1, _thread_in_native_trans);
1426   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1427   __ stlrw(rscratch1, rscratch2);
1428 
1429   // Force this write out before the read below
1430   if (!UseSystemMemoryBarrier) {
1431     __ dmb(Assembler::ISH);
1432   }
1433 
1434   // check for safepoint operation in progress and/or pending suspend requests
1435   {
1436     Label L, Continue;
1437 
1438     // No need for acquire as Java threads always disarm themselves.
1439     __ safepoint_poll(L, true /* at_return */, false /* in_nmethod */);
1440     __ ldrw(rscratch2, Address(rthread, JavaThread::suspend_flags_offset()));
1441     __ cbz(rscratch2, Continue);
1442     __ bind(L);
1443 
1444     // Don't use call_VM as it will see a possible pending exception
1445     // and forward it and never return here preventing us from
1446     // clearing _last_native_pc down below. So we do a runtime call by
1447     // hand.
1448     //
1449     __ mov(c_rarg0, rthread);
1450     __ lea(rscratch2, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1451     __ blr(rscratch2);
1452     __ get_method(rmethod);
1453     __ reinit_heapbase();
1454     __ bind(Continue);
1455   }
1456 
1457   // change thread state
1458   __ mov(rscratch1, _thread_in_Java);
1459   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1460   __ stlrw(rscratch1, rscratch2);
1461 
1462   // Check preemption for Object.wait()
1463   Label not_preempted;
1464   __ ldr(rscratch1, Address(rthread, JavaThread::preempt_alternate_return_offset()));
1465   __ cbz(rscratch1, not_preempted);
1466   __ str(zr, Address(rthread, JavaThread::preempt_alternate_return_offset()));
1467   __ br(rscratch1);
1468   __ bind(native_return);
1469   __ restore_after_resume(true /* is_native */);
1470   // reload result_handler
1471   __ ldr(result_handler, Address(rfp, frame::interpreter_frame_result_handler_offset*wordSize));
1472   __ bind(not_preempted);
1473 
1474   // reset_last_Java_frame
1475   __ reset_last_Java_frame(true);
1476 
1477   if (CheckJNICalls) {
1478     // clear_pending_jni_exception_check
1479     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1480   }
1481 
1482   // reset handle block
1483   __ ldr(t, Address(rthread, JavaThread::active_handles_offset()));
1484   __ str(zr, Address(t, JNIHandleBlock::top_offset()));
1485 
1486   // If result is an oop unbox and store it in frame where gc will see it
1487   // and result handler will pick it up
1488 
1489   {
1490     Label no_oop;
1491     __ adr(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1492     __ cmp(t, result_handler);
1493     __ br(Assembler::NE, no_oop);
1494     // Unbox oop result, e.g. JNIHandles::resolve result.
1495     __ pop(ltos);
1496     __ resolve_jobject(r0, t, rscratch2);
1497     __ str(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
1498     // keep stack depth as expected by pushing oop which will eventually be discarded
1499     __ push(ltos);
1500     __ bind(no_oop);
1501   }
1502 
1503   {
1504     Label no_reguard;
1505     __ lea(rscratch1, Address(rthread, in_bytes(JavaThread::stack_guard_state_offset())));
1506     __ ldrw(rscratch1, Address(rscratch1));
1507     __ cmp(rscratch1, (u1)StackOverflow::stack_guard_yellow_reserved_disabled);
1508     __ br(Assembler::NE, no_reguard);
1509 
1510     __ push_call_clobbered_registers();
1511     __ mov(c_rarg0, rthread);
1512     __ lea(rscratch2, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1513     __ blr(rscratch2);
1514     __ pop_call_clobbered_registers();
1515 
1516     __ bind(no_reguard);
1517   }
1518 
1519   // The method register is junk from after the thread_in_native transition
1520   // until here.  Also can't call_VM until the bcp has been
1521   // restored.  Need bcp for throwing exception below so get it now.
1522   __ get_method(rmethod);
1523 
1524   // restore bcp to have legal interpreter frame, i.e., bci == 0 <=>
1525   // rbcp == code_base()
1526   __ ldr(rbcp, Address(rmethod, Method::const_offset()));   // get ConstMethod*
1527   __ add(rbcp, rbcp, in_bytes(ConstMethod::codes_offset()));          // get codebase
1528   // handle exceptions (exception handling will handle unlocking!)
1529   {
1530     Label L;
1531     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
1532     __ cbz(rscratch1, L);
1533     // Note: At some point we may want to unify this with the code
1534     // used in call_VM_base(); i.e., we should use the
1535     // StubRoutines::forward_exception code. For now this doesn't work
1536     // here because the rsp is not correctly set at this point.
1537     __ MacroAssembler::call_VM(noreg,
1538                                CAST_FROM_FN_PTR(address,
1539                                InterpreterRuntime::throw_pending_exception));
1540     __ should_not_reach_here();
1541     __ bind(L);
1542   }
1543 
1544   // do unlocking if necessary
1545   {
1546     Label L;
1547     __ ldrh(t, Address(rmethod, Method::access_flags_offset()));
1548     __ tbz(t, exact_log2(JVM_ACC_SYNCHRONIZED), L);
1549     // the code below should be shared with interpreter macro
1550     // assembler implementation
1551     {
1552       Label unlock;
1553       // BasicObjectLock will be first in list, since this is a
1554       // synchronized method. However, need to check that the object
1555       // has not been unlocked by an explicit monitorexit bytecode.
1556 
1557       // monitor expect in c_rarg1 for slow unlock path
1558       __ lea (c_rarg1, Address(rfp,   // address of first monitor
1559                                (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1560                                           wordSize - sizeof(BasicObjectLock))));
1561 
1562       __ ldr(t, Address(c_rarg1, BasicObjectLock::obj_offset()));
1563       __ cbnz(t, unlock);
1564 
1565       // Entry already unlocked, need to throw exception
1566       __ MacroAssembler::call_VM(noreg,
1567                                  CAST_FROM_FN_PTR(address,
1568                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1569       __ should_not_reach_here();
1570 
1571       __ bind(unlock);
1572       __ unlock_object(c_rarg1);
1573     }
1574     __ bind(L);
1575   }
1576 
1577   #if INCLUDE_JFR
1578   __ enter_jfr_critical_section();
1579 
1580   // This poll test is to uphold the invariant that a JFR sampled frame
1581   // must not return to its caller without a prior safepoint poll check.
1582   // The earlier poll check in this routine is insufficient for this purpose
1583   // because the thread has transitioned back to Java.
1584 
1585   Label slow_path;
1586   Label fast_path;
1587   __ safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
1588   __ br(Assembler::AL, fast_path);
1589   __ bind(slow_path);
1590   __ push(dtos);
1591   __ push(ltos);
1592   __ set_last_Java_frame(esp, rfp, __ pc(), rscratch1);
1593   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), rthread);
1594   __ reset_last_Java_frame(true);
1595   __ pop(ltos);
1596   __ pop(dtos);
1597   __ bind(fast_path);
1598 
1599 #endif // INCLUDE_JFR
1600 
1601   // jvmti support
1602   // Note: This must happen _after_ handling/throwing any exceptions since
1603   //       the exception handler code notifies the runtime of method exits
1604   //       too. If this happens before, method entry/exit notifications are
1605   //       not properly paired (was bug - gri 11/22/99).
1606   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1607 
1608   // restore potential result in r0:d0, call result handler to
1609   // restore potential result in ST0 & handle result
1610 
1611   __ pop(ltos);
1612   __ pop(dtos);
1613 
1614   __ blr(result_handler);
1615 
1616   // remove activation
1617   __ ldr(esp, Address(rfp,
1618                     frame::interpreter_frame_sender_sp_offset *
1619                     wordSize)); // get sender sp
1620   // remove frame anchor
1621   __ leave();
1622 
1623   JFR_ONLY(__ leave_jfr_critical_section();)
1624 
1625   // restore sender sp
1626   __ mov(sp, esp);
1627 
1628   __ ret(lr);
1629 
1630   if (inc_counter) {
1631     // Handle overflow of counter and compile method
1632     __ bind(invocation_counter_overflow);
1633     generate_counter_overflow(continue_after_compile);
1634   }
1635 
1636   return entry_point;
1637 }
1638 
1639 //
1640 // Generic interpreted method entry to (asm) interpreter
1641 //
1642 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized, bool object_init) {
1643   // determine code generation flags
1644   bool inc_counter  = UseCompiler || CountCompiledCalls;
1645 
1646   // rscratch1: sender sp
1647   address entry_point = __ pc();
1648 
1649   const Address constMethod(rmethod, Method::const_offset());
1650   const Address access_flags(rmethod, Method::access_flags_offset());
1651   const Address size_of_parameters(r3,
1652                                    ConstMethod::size_of_parameters_offset());
1653   const Address size_of_locals(r3, ConstMethod::size_of_locals_offset());
1654 
1655   // get parameter size (always needed)
1656   // need to load the const method first
1657   __ ldr(r3, constMethod);
1658   __ load_unsigned_short(r2, size_of_parameters);
1659 
1660   // r2: size of parameters
1661 
1662   __ load_unsigned_short(r3, size_of_locals); // get size of locals in words
1663   __ sub(r3, r3, r2); // r3 = no. of additional locals
1664 
1665   // see if we've got enough room on the stack for locals plus overhead.
1666   generate_stack_overflow_check();
1667 
1668   // compute beginning of parameters (rlocals)
1669   __ add(rlocals, esp, r2, ext::uxtx, 3);
1670   __ sub(rlocals, rlocals, wordSize);
1671 
1672   __ mov(rscratch1, esp);
1673 
1674   // r3 - # of additional locals
1675   // allocate space for locals
1676   // explicitly initialize locals
1677   // Initializing memory allocated for locals in the same direction as
1678   // the stack grows to ensure page initialization order according
1679   // to windows-aarch64 stack page growth requirement (see
1680   // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-160#stack)
1681   {
1682     Label exit, loop;
1683     __ ands(zr, r3, r3);
1684     __ br(Assembler::LE, exit); // do nothing if r3 <= 0
1685     __ bind(loop);
1686     __ str(zr, Address(__ pre(rscratch1, -wordSize)));
1687     __ sub(r3, r3, 1); // until everything initialized
1688     __ cbnz(r3, loop);
1689     __ bind(exit);
1690   }
1691 
1692   // Padding between locals and fixed part of activation frame to ensure
1693   // SP is always 16-byte aligned.
1694   __ andr(sp, rscratch1, -16);
1695 
1696   // And the base dispatch table
1697   __ get_dispatch();
1698 
1699   // initialize fixed part of activation frame
1700   generate_fixed_frame(false);
1701 
1702   // make sure method is not native & not abstract
1703 #ifdef ASSERT
1704   __ ldrh(r0, access_flags);
1705   {
1706     Label L;
1707     __ tst(r0, JVM_ACC_NATIVE);
1708     __ br(Assembler::EQ, L);
1709     __ stop("tried to execute native method as non-native");
1710     __ bind(L);
1711   }
1712  {
1713     Label L;
1714     __ tst(r0, JVM_ACC_ABSTRACT);
1715     __ br(Assembler::EQ, L);
1716     __ stop("tried to execute abstract method in interpreter");
1717     __ bind(L);
1718   }
1719 #endif
1720 
1721   // Since at this point in the method invocation the exception
1722   // handler would try to exit the monitor of synchronized methods
1723   // which hasn't been entered yet, we set the thread local variable
1724   // _do_not_unlock_if_synchronized to true. The remove_activation
1725   // will check this flag.
1726 
1727    const Address do_not_unlock_if_synchronized(rthread,
1728         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1729   __ mov(rscratch2, true);
1730   __ strb(rscratch2, do_not_unlock_if_synchronized);
1731 
1732   Register mdp = r3;
1733   __ profile_parameters_type(mdp, r1, r2);
1734 
1735   // increment invocation count & check for overflow
1736   Label invocation_counter_overflow;
1737   if (inc_counter) {
1738     generate_counter_incr(&invocation_counter_overflow);
1739   }
1740 
1741   Label continue_after_compile;
1742   __ bind(continue_after_compile);
1743 
1744   bang_stack_shadow_pages(false);
1745 
1746   // reset the _do_not_unlock_if_synchronized flag
1747   __ strb(zr, do_not_unlock_if_synchronized);
1748 
1749   // check for synchronized methods
1750   // Must happen AFTER invocation_counter check and stack overflow check,
1751   // so method is not locked if overflows.
1752   if (synchronized) {
1753     // Allocate monitor and lock method
1754     lock_method();
1755   } else {
1756     // no synchronization necessary
1757 #ifdef ASSERT
1758     {
1759       Label L;
1760       __ ldrh(r0, access_flags);
1761       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1762       __ br(Assembler::EQ, L);
1763       __ stop("method needs synchronization");
1764       __ bind(L);
1765     }
1766 #endif
1767   }
1768 
1769   // Issue a StoreStore barrier on entry to Object_init if the
1770   // class has strict field fields.  Be lazy, always do it.
1771   if (object_init) {
1772     __ membar(MacroAssembler::StoreStore);
1773   }
1774 
1775   // start execution
1776 #ifdef ASSERT
1777   {
1778     Label L;
1779      const Address monitor_block_top (rfp,
1780                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1781     __ ldr(rscratch1, monitor_block_top);
1782     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1783     __ cmp(esp, rscratch1);
1784     __ br(Assembler::EQ, L);
1785     __ stop("broken stack frame setup in interpreter 2");
1786     __ bind(L);
1787   }
1788 #endif
1789 
1790   // jvmti support
1791   __ notify_method_entry();
1792 
1793   __ dispatch_next(vtos);
1794 
1795   // invocation counter overflow
1796   if (inc_counter) {
1797     // Handle overflow of counter and compile method
1798     __ bind(invocation_counter_overflow);
1799     generate_counter_overflow(continue_after_compile);
1800   }
1801 
1802   return entry_point;
1803 }
1804 
1805 // Method entry for java.lang.Thread.currentThread
1806 address TemplateInterpreterGenerator::generate_currentThread() {
1807   address entry_point = __ pc();
1808 
1809   __ ldr(r0, Address(rthread, JavaThread::vthread_offset()));
1810   __ resolve_oop_handle(r0, rscratch1, rscratch2);
1811   __ ret(lr);
1812 
1813   return entry_point;
1814 }
1815 
1816 //-----------------------------------------------------------------------------
1817 // Exceptions
1818 
1819 void TemplateInterpreterGenerator::generate_throw_exception() {
1820   // Entry point in previous activation (i.e., if the caller was
1821   // interpreted)
1822   Interpreter::_rethrow_exception_entry = __ pc();
1823   // Restore sp to interpreter_frame_last_sp even though we are going
1824   // to empty the expression stack for the exception processing.
1825   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1826   // r0: exception
1827   // r3: return address/pc that threw exception
1828   __ restore_bcp();    // rbcp points to call/send
1829   __ restore_locals();
1830   __ restore_constant_pool_cache();
1831   __ reinit_heapbase();  // restore rheapbase as heapbase.
1832   __ get_dispatch();
1833 
1834   // Entry point for exceptions thrown within interpreter code
1835   Interpreter::_throw_exception_entry = __ pc();
1836   // If we came here via a NullPointerException on the receiver of a
1837   // method, rmethod may be corrupt.
1838   __ get_method(rmethod);
1839   // expression stack is undefined here
1840   // r0: exception
1841   // rbcp: exception bcp
1842   __ verify_oop(r0);
1843   __ mov(c_rarg1, r0);
1844 
1845   // expression stack must be empty before entering the VM in case of
1846   // an exception
1847   __ empty_expression_stack();
1848   // find exception handler address and preserve exception oop
1849   __ call_VM(r3,
1850              CAST_FROM_FN_PTR(address,
1851                           InterpreterRuntime::exception_handler_for_exception),
1852              c_rarg1);
1853 
1854   // Restore machine SP
1855   __ restore_sp_after_call();
1856 
1857   // r0: exception handler entry point
1858   // r3: preserved exception oop
1859   // rbcp: bcp for exception handler
1860   __ push_ptr(r3); // push exception which is now the only value on the stack
1861   __ br(r0); // jump to exception handler (may be _remove_activation_entry!)
1862 
1863   // If the exception is not handled in the current frame the frame is
1864   // removed and the exception is rethrown (i.e. exception
1865   // continuation is _rethrow_exception).
1866   //
1867   // Note: At this point the bci is still the bxi for the instruction
1868   // which caused the exception and the expression stack is
1869   // empty. Thus, for any VM calls at this point, GC will find a legal
1870   // oop map (with empty expression stack).
1871 
1872   //
1873   // JVMTI PopFrame support
1874   //
1875 
1876   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1877   __ empty_expression_stack();
1878   __ restore_bcp(); // We could have returned from deoptimizing this frame, so restore rbcp.
1879   // Set the popframe_processing bit in pending_popframe_condition
1880   // indicating that we are currently handling popframe, so that
1881   // call_VMs that may happen later do not trigger new popframe
1882   // handling cycles.
1883   __ ldrw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1884   __ orr(r3, r3, JavaThread::popframe_processing_bit);
1885   __ strw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1886 
1887   {
1888     // Check to see whether we are returning to a deoptimized frame.
1889     // (The PopFrame call ensures that the caller of the popped frame is
1890     // either interpreted or compiled and deoptimizes it if compiled.)
1891     // In this case, we can't call dispatch_next() after the frame is
1892     // popped, but instead must save the incoming arguments and restore
1893     // them after deoptimization has occurred.
1894     //
1895     // Note that we don't compare the return PC against the
1896     // deoptimization blob's unpack entry because of the presence of
1897     // adapter frames in C2.
1898     Label caller_not_deoptimized;
1899     __ ldr(c_rarg1, Address(rfp, frame::return_addr_offset * wordSize));
1900     // This is a return address, so requires authenticating for PAC.
1901     __ authenticate_return_address(c_rarg1);
1902     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1903                                InterpreterRuntime::interpreter_contains), c_rarg1);
1904     __ cbnz(r0, caller_not_deoptimized);
1905 
1906     // Compute size of arguments for saving when returning to
1907     // deoptimized caller
1908     __ get_method(r0);
1909     __ ldr(r0, Address(r0, Method::const_offset()));
1910     __ load_unsigned_short(r0, Address(r0, in_bytes(ConstMethod::
1911                                                     size_of_parameters_offset())));
1912     __ lsl(r0, r0, Interpreter::logStackElementSize);
1913     __ restore_locals(); // XXX do we need this?
1914     __ sub(rlocals, rlocals, r0);
1915     __ add(rlocals, rlocals, wordSize);
1916     // Save these arguments
1917     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1918                                            Deoptimization::
1919                                            popframe_preserve_args),
1920                           rthread, r0, rlocals);
1921 
1922     __ remove_activation(vtos,
1923                          /* throw_monitor_exception */ false,
1924                          /* install_monitor_exception */ false,
1925                          /* notify_jvmdi */ false);
1926 
1927     // Inform deoptimization that it is responsible for restoring
1928     // these arguments
1929     __ mov(rscratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1930     __ strw(rscratch1, Address(rthread, JavaThread::popframe_condition_offset()));
1931 
1932     // Continue in deoptimization handler
1933     __ ret(lr);
1934 
1935     __ bind(caller_not_deoptimized);
1936   }
1937 
1938   __ remove_activation(vtos,
1939                        /* throw_monitor_exception */ false,
1940                        /* install_monitor_exception */ false,
1941                        /* notify_jvmdi */ false);
1942 
1943   // Restore the last_sp and null it out
1944   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1945   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1946   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1947 
1948   __ restore_bcp();
1949   __ restore_locals();
1950   __ restore_constant_pool_cache();
1951   __ get_method(rmethod);
1952   __ get_dispatch();
1953 
1954   // The method data pointer was incremented already during
1955   // call profiling. We have to restore the mdp for the current bcp.
1956   if (ProfileInterpreter) {
1957     __ set_method_data_pointer_for_bcp();
1958   }
1959 
1960   // Clear the popframe condition flag
1961   __ strw(zr, Address(rthread, JavaThread::popframe_condition_offset()));
1962   assert(JavaThread::popframe_inactive == 0, "fix popframe_inactive");
1963 
1964 #if INCLUDE_JVMTI
1965   {
1966     Label L_done;
1967 
1968     __ ldrb(rscratch1, Address(rbcp, 0));
1969     __ cmpw(rscratch1, Bytecodes::_invokestatic);
1970     __ br(Assembler::NE, L_done);
1971 
1972     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1973     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1974 
1975     __ ldr(c_rarg0, Address(rlocals, 0));
1976     __ call_VM(r0, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), c_rarg0, rmethod, rbcp);
1977 
1978     __ cbz(r0, L_done);
1979 
1980     __ str(r0, Address(esp, 0));
1981     __ bind(L_done);
1982   }
1983 #endif // INCLUDE_JVMTI
1984 
1985   // Restore machine SP
1986   __ restore_sp_after_call();
1987 
1988   __ dispatch_next(vtos);
1989   // end of PopFrame support
1990 
1991   Interpreter::_remove_activation_entry = __ pc();
1992 
1993   // preserve exception over this code sequence
1994   __ pop_ptr(r0);
1995   __ str(r0, Address(rthread, JavaThread::vm_result_oop_offset()));
1996   // remove the activation (without doing throws on illegalMonitorExceptions)
1997   __ remove_activation(vtos, false, true, false);
1998   // restore exception
1999   __ get_vm_result_oop(r0, rthread);
2000 
2001   // In between activations - previous activation type unknown yet
2002   // compute continuation point - the continuation point expects the
2003   // following registers set up:
2004   //
2005   // r0: exception
2006   // lr: return address/pc that threw exception
2007   // esp: expression stack of caller
2008   // rfp: fp of caller
2009   __ stp(r0, lr, Address(__ pre(sp, -2 * wordSize)));  // save exception & return address
2010   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
2011                           SharedRuntime::exception_handler_for_return_address),
2012                         rthread, lr);
2013   __ mov(r1, r0);                               // save exception handler
2014   __ ldp(r0, lr, Address(__ post(sp, 2 * wordSize)));  // restore exception & return address
2015   // We might be returning to a deopt handler that expects r3 to
2016   // contain the exception pc
2017   __ mov(r3, lr);
2018   // Note that an "issuing PC" is actually the next PC after the call
2019   __ br(r1);                                    // jump to exception
2020                                                 // handler of caller
2021 }
2022 
2023 
2024 //
2025 // JVMTI ForceEarlyReturn support
2026 //
2027 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
2028   address entry = __ pc();
2029 
2030   __ restore_bcp();
2031   __ restore_locals();
2032   __ empty_expression_stack();
2033   __ load_earlyret_value(state);
2034 
2035   __ ldr(rscratch1, Address(rthread, JavaThread::jvmti_thread_state_offset()));
2036   Address cond_addr(rscratch1, JvmtiThreadState::earlyret_state_offset());
2037 
2038   // Clear the earlyret state
2039   assert(JvmtiThreadState::earlyret_inactive == 0, "should be");
2040   __ str(zr, cond_addr);
2041 
2042   __ remove_activation(state,
2043                        false, /* throw_monitor_exception */
2044                        false, /* install_monitor_exception */
2045                        true); /* notify_jvmdi */
2046   __ ret(lr);
2047 
2048   return entry;
2049 } // end of ForceEarlyReturn support
2050 
2051 
2052 
2053 //-----------------------------------------------------------------------------
2054 // Helper for vtos entry point generation
2055 
2056 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2057                                                          address& bep,
2058                                                          address& cep,
2059                                                          address& sep,
2060                                                          address& aep,
2061                                                          address& iep,
2062                                                          address& lep,
2063                                                          address& fep,
2064                                                          address& dep,
2065                                                          address& vep) {
2066   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2067   Label L;
2068   aep = __ pc();     // atos entry point
2069       __ push_ptr();
2070       __ b(L);
2071   fep = __ pc();     // ftos entry point
2072       __ push_f();
2073       __ b(L);
2074   dep = __ pc();     // dtos entry point
2075       __ push_d();
2076       __ b(L);
2077   lep = __ pc();     // ltos entry point
2078       __ push_l();
2079       __ b(L);
2080   bep = cep = sep = iep = __ pc();     // [bcsi]tos entry point
2081       __ push_i();
2082   vep = __ pc();     // vtos entry point
2083   __ bind(L);
2084   generate_and_dispatch(t);
2085 }
2086 
2087 //-----------------------------------------------------------------------------
2088 
2089 // Non-product code
2090 #ifndef PRODUCT
2091 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2092   address entry = __ pc();
2093 
2094   __ protect_return_address();
2095   __ push(lr);
2096   __ push(state);
2097   __ push(RegSet::range(r0, r15), sp);
2098   __ mov(c_rarg2, r0);  // Pass itos
2099   __ call_VM(noreg,
2100              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
2101              c_rarg1, c_rarg2, c_rarg3);
2102   __ pop(RegSet::range(r0, r15), sp);
2103   __ pop(state);
2104   __ pop(lr);
2105   __ authenticate_return_address();
2106   __ ret(lr);                                   // return from result handler
2107 
2108   return entry;
2109 }
2110 
2111 void TemplateInterpreterGenerator::count_bytecode() {
2112   __ mov(r10, (address) &BytecodeCounter::_counter_value);
2113   __ atomic_add(noreg, 1, r10);
2114 }
2115 
2116 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2117   __ mov(r10, (address) &BytecodeHistogram::_counters[t->bytecode()]);
2118   __ atomic_addw(noreg, 1, r10);
2119 }
2120 
2121 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2122   // Calculate new index for counter:
2123   //   _index = (_index >> log2_number_of_codes) |
2124   //            (bytecode << log2_number_of_codes);
2125   Register index_addr = rscratch1;
2126   Register index = rscratch2;
2127   __ mov(index_addr, (address) &BytecodePairHistogram::_index);
2128   __ ldrw(index, index_addr);
2129   __ mov(r10,
2130          ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2131   __ orrw(index, r10, index, Assembler::LSR,
2132           BytecodePairHistogram::log2_number_of_codes);
2133   __ strw(index, index_addr);
2134 
2135   // Bump bucket contents:
2136   //   _counters[_index] ++;
2137   Register counter_addr = rscratch1;
2138   __ mov(r10, (address) &BytecodePairHistogram::_counters);
2139   __ lea(counter_addr, Address(r10, index, Address::lsl(LogBytesPerInt)));
2140   __ atomic_addw(noreg, 1, counter_addr);
2141 }
2142 
2143 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2144   // Call a little run-time stub to avoid blow-up for each bytecode.
2145   // The run-time runtime saves the right registers, depending on
2146   // the tosca in-state for the given template.
2147 
2148   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
2149          "entry must have been generated");
2150   __ bl(RuntimeAddress(Interpreter::trace_code(t->tos_in())));
2151   __ reinit_heapbase();
2152 }
2153 
2154 
2155 void TemplateInterpreterGenerator::stop_interpreter_at() {
2156   Label L;
2157   __ push(rscratch1);
2158   __ mov(rscratch1, (address) &BytecodeCounter::_counter_value);
2159   __ ldr(rscratch1, Address(rscratch1));
2160   __ mov(rscratch2, StopInterpreterAt);
2161   __ cmp(rscratch1, rscratch2);
2162   __ br(Assembler::NE, L);
2163   __ brk(0);
2164   __ bind(L);
2165   __ pop(rscratch1);
2166 }
2167 
2168 #endif // !PRODUCT