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