1 /*
   2  * Copyright (c) 2003, 2024, 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/disassembler.hpp"
  30 #include "compiler/compiler_globals.hpp"
  31 #include "gc/shared/barrierSetAssembler.hpp"
  32 #include "interpreter/bytecodeHistogram.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "interpreter/interpreterRuntime.hpp"
  35 #include "interpreter/interp_masm.hpp"
  36 #include "interpreter/templateInterpreterGenerator.hpp"
  37 #include "interpreter/templateTable.hpp"
  38 #include "interpreter/bytecodeTracer.hpp"
  39 #include "memory/resourceArea.hpp"
  40 #include "oops/arrayOop.hpp"
  41 #include "oops/method.hpp"
  42 #include "oops/methodCounters.hpp"
  43 #include "oops/methodData.hpp"
  44 #include "oops/oop.inline.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   __ restore_bcp();
 472   __ restore_locals();
 473   __ restore_constant_pool_cache();
 474   __ get_method(rmethod);
 475 
 476   if (state == atos) {
 477     Register obj = r0;
 478     Register mdp = r1;
 479     Register tmp = r2;
 480     __ profile_return_type(mdp, obj, tmp);
 481   }
 482 
 483   const Register cache = r1;
 484   const Register index = r2;
 485 
 486   if (index_size == sizeof(u4)) {
 487     __ load_resolved_indy_entry(cache, index);
 488     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedIndyEntry::num_parameters_offset())));
 489     __ add(esp, esp, cache, Assembler::LSL, 3);
 490   } else {
 491     // Pop N words from the stack
 492     assert(index_size == sizeof(u2), "Can only be u2");
 493     __ load_method_entry(cache, index);
 494     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedMethodEntry::num_parameters_offset())));
 495     __ add(esp, esp, cache, Assembler::LSL, 3);
 496   }
 497 
 498   // Restore machine SP
 499   __ restore_sp_after_call();
 500 
 501   __ check_and_handle_popframe(rthread);
 502   __ check_and_handle_earlyret(rthread);
 503 
 504   __ get_dispatch();
 505   __ dispatch_next(state, step);
 506 
 507   return entry;
 508 }
 509 
 510 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state,
 511                                                                int step,
 512                                                                address continuation) {
 513   address entry = __ pc();
 514   __ restore_bcp();
 515   __ restore_locals();
 516   __ restore_constant_pool_cache();
 517   __ get_method(rmethod);
 518   __ get_dispatch();
 519 
 520   __ restore_sp_after_call();  // Restore SP to extended SP
 521 
 522   // Restore expression stack pointer
 523   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 524   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
 525   // null last_sp until next java call
 526   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
 527 
 528 #if INCLUDE_JVMCI
 529   // Check if we need to take lock at entry of synchronized method.  This can
 530   // only occur on method entry so emit it only for vtos with step 0.
 531   if (EnableJVMCI && state == vtos && step == 0) {
 532     Label L;
 533     __ ldrb(rscratch1, Address(rthread, JavaThread::pending_monitorenter_offset()));
 534     __ cbz(rscratch1, L);
 535     // Clear flag.
 536     __ strb(zr, Address(rthread, JavaThread::pending_monitorenter_offset()));
 537     // Take lock.
 538     lock_method();
 539     __ bind(L);
 540   } else {
 541 #ifdef ASSERT
 542     if (EnableJVMCI) {
 543       Label L;
 544       __ ldrb(rscratch1, Address(rthread, JavaThread::pending_monitorenter_offset()));
 545       __ cbz(rscratch1, L);
 546       __ stop("unexpected pending monitor in deopt entry");
 547       __ bind(L);
 548     }
 549 #endif
 550   }
 551 #endif
 552   // handle exceptions
 553   {
 554     Label L;
 555     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
 556     __ cbz(rscratch1, L);
 557     __ call_VM(noreg,
 558                CAST_FROM_FN_PTR(address,
 559                                 InterpreterRuntime::throw_pending_exception));
 560     __ should_not_reach_here();
 561     __ bind(L);
 562   }
 563 
 564   if (continuation == nullptr) {
 565     __ dispatch_next(state, step);
 566   } else {
 567     __ jump_to_entry(continuation);
 568   }
 569   return entry;
 570 }
 571 
 572 address TemplateInterpreterGenerator::generate_result_handler_for(
 573         BasicType type) {
 574     address entry = __ pc();
 575   switch (type) {
 576   case T_BOOLEAN: __ c2bool(r0);         break;
 577   case T_CHAR   : __ uxth(r0, r0);       break;
 578   case T_BYTE   : __ sxtb(r0, r0);        break;
 579   case T_SHORT  : __ sxth(r0, r0);        break;
 580   case T_INT    : __ uxtw(r0, r0);        break;  // FIXME: We almost certainly don't need this
 581   case T_LONG   : /* nothing to do */        break;
 582   case T_VOID   : /* nothing to do */        break;
 583   case T_FLOAT  : /* nothing to do */        break;
 584   case T_DOUBLE : /* nothing to do */        break;
 585   case T_OBJECT :
 586     // retrieve result from frame
 587     __ ldr(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
 588     // and verify it
 589     __ verify_oop(r0);
 590     break;
 591   default       : ShouldNotReachHere();
 592   }
 593   __ ret(lr);                                  // return from result handler
 594   return entry;
 595 }
 596 
 597 address TemplateInterpreterGenerator::generate_safept_entry_for(
 598         TosState state,
 599         address runtime_entry) {
 600   address entry = __ pc();
 601   __ push(state);
 602   __ push_cont_fastpath(rthread);
 603   __ call_VM(noreg, runtime_entry);
 604   __ pop_cont_fastpath(rthread);
 605   __ membar(Assembler::AnyAny);
 606   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 607   return entry;
 608 }
 609 
 610 // Helpers for commoning out cases in the various type of method entries.
 611 //
 612 
 613 
 614 // increment invocation count & check for overflow
 615 //
 616 // Note: checking for negative value instead of overflow
 617 //       so we have a 'sticky' overflow test
 618 //
 619 // rmethod: method
 620 //
 621 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 622   Label done;
 623   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 624   int increment = InvocationCounter::count_increment;
 625   Label no_mdo;
 626   if (ProfileInterpreter) {
 627     // Are we profiling?
 628     __ ldr(r0, Address(rmethod, Method::method_data_offset()));
 629     __ cbz(r0, no_mdo);
 630     // Increment counter in the MDO
 631     const Address mdo_invocation_counter(r0, in_bytes(MethodData::invocation_counter_offset()) +
 632                                               in_bytes(InvocationCounter::counter_offset()));
 633     const Address mask(r0, in_bytes(MethodData::invoke_mask_offset()));
 634     __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rscratch1, rscratch2, false, Assembler::EQ, overflow);
 635     __ b(done);
 636   }
 637   __ bind(no_mdo);
 638   // Increment counter in MethodCounters
 639   const Address invocation_counter(rscratch2,
 640                 MethodCounters::invocation_counter_offset() +
 641                 InvocationCounter::counter_offset());
 642   __ get_method_counters(rmethod, rscratch2, done);
 643   const Address mask(rscratch2, in_bytes(MethodCounters::invoke_mask_offset()));
 644   __ increment_mask_and_jump(invocation_counter, increment, mask, rscratch1, r1, false, Assembler::EQ, overflow);
 645   __ bind(done);
 646 }
 647 
 648 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 649 
 650   // Asm interpreter on entry
 651   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 652   // Everything as it was on entry
 653 
 654   // InterpreterRuntime::frequency_counter_overflow takes two
 655   // arguments, the first (thread) is passed by call_VM, the second
 656   // indicates if the counter overflow occurs at a backwards branch
 657   // (null bcp).  We pass zero for it.  The call returns the address
 658   // of the verified entry point for the method or null if the
 659   // compilation did not complete (either went background or bailed
 660   // out).
 661   __ mov(c_rarg1, 0);
 662   __ call_VM(noreg,
 663              CAST_FROM_FN_PTR(address,
 664                               InterpreterRuntime::frequency_counter_overflow),
 665              c_rarg1);
 666 
 667   __ b(do_continue);
 668 }
 669 
 670 // See if we've got enough room on the stack for locals plus overhead
 671 // below JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 672 // without going through the signal handler, i.e., reserved and yellow zones
 673 // will not be made usable. The shadow zone must suffice to handle the
 674 // overflow.
 675 // The expression stack grows down incrementally, so the normal guard
 676 // page mechanism will work for that.
 677 //
 678 // NOTE: Since the additional locals are also always pushed (wasn't
 679 // obvious in generate_method_entry) so the guard should work for them
 680 // too.
 681 //
 682 // Args:
 683 //      r3: number of additional locals this frame needs (what we must check)
 684 //      rmethod: Method*
 685 //
 686 // Kills:
 687 //      r0
 688 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 689 
 690   // monitor entry size: see picture of stack set
 691   // (generate_method_entry) and frame_amd64.hpp
 692   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 693 
 694   // total overhead size: entry_size + (saved rbp through expr stack
 695   // bottom).  be sure to change this if you add/subtract anything
 696   // to/from the overhead area
 697   const int overhead_size =
 698     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 699 
 700   const size_t page_size = os::vm_page_size();
 701 
 702   Label after_frame_check;
 703 
 704   // see if the frame is greater than one page in size. If so,
 705   // then we need to verify there is enough stack space remaining
 706   // for the additional locals.
 707   //
 708   // Note that we use SUBS rather than CMP here because the immediate
 709   // field of this instruction may overflow.  SUBS can cope with this
 710   // because it is a macro that will expand to some number of MOV
 711   // instructions and a register operation.
 712   __ subs(rscratch1, r3, (page_size - overhead_size) / Interpreter::stackElementSize);
 713   __ br(Assembler::LS, after_frame_check);
 714 
 715   // compute rsp as if this were going to be the last frame on
 716   // the stack before the red zone
 717 
 718   // locals + overhead, in bytes
 719   __ mov(r0, overhead_size);
 720   __ add(r0, r0, r3, Assembler::LSL, Interpreter::logStackElementSize);  // 2 slots per parameter.
 721 
 722   const Address stack_limit(rthread, JavaThread::stack_overflow_limit_offset());
 723   __ ldr(rscratch1, stack_limit);
 724 
 725 #ifdef ASSERT
 726   Label limit_okay;
 727   // Verify that thread stack limit is non-zero.
 728   __ cbnz(rscratch1, limit_okay);
 729   __ stop("stack overflow limit is zero");
 730   __ bind(limit_okay);
 731 #endif
 732 
 733   // Add stack limit to locals.
 734   __ add(r0, r0, rscratch1);
 735 
 736   // Check against the current stack bottom.
 737   __ cmp(sp, r0);
 738   __ br(Assembler::HI, after_frame_check);
 739 
 740   // Remove the incoming args, peeling the machine SP back to where it
 741   // was in the caller.  This is not strictly necessary, but unless we
 742   // do so the stack frame may have a garbage FP; this ensures a
 743   // correct call stack that we can always unwind.  The ANDR should be
 744   // unnecessary because the sender SP in r19 is always aligned, but
 745   // it doesn't hurt.
 746   __ andr(sp, r19_sender_sp, -16);
 747 
 748   // Note: the restored frame is not necessarily interpreted.
 749   // Use the shared runtime version of the StackOverflowError.
 750   assert(SharedRuntime::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 751   __ far_jump(RuntimeAddress(SharedRuntime::throw_StackOverflowError_entry()));
 752 
 753   // all done with frame size check
 754   __ bind(after_frame_check);
 755 }
 756 
 757 // Allocate monitor and lock method (asm interpreter)
 758 //
 759 // Args:
 760 //      rmethod: Method*
 761 //      rlocals: locals
 762 //
 763 // Kills:
 764 //      r0
 765 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 766 //      rscratch1, rscratch2 (scratch regs)
 767 void TemplateInterpreterGenerator::lock_method() {
 768   // synchronize method
 769   const Address access_flags(rmethod, Method::access_flags_offset());
 770   const Address monitor_block_top(
 771         rfp,
 772         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 773   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 774 
 775 #ifdef ASSERT
 776   {
 777     Label L;
 778     __ ldrw(r0, access_flags);
 779     __ tst(r0, JVM_ACC_SYNCHRONIZED);
 780     __ br(Assembler::NE, L);
 781     __ stop("method doesn't need synchronization");
 782     __ bind(L);
 783   }
 784 #endif // ASSERT
 785 
 786   // get synchronization object
 787   {
 788     Label done;
 789     __ ldrw(r0, access_flags);
 790     __ tst(r0, JVM_ACC_STATIC);
 791     // get receiver (assume this is frequent case)
 792     __ ldr(r0, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 793     __ br(Assembler::EQ, done);
 794     __ load_mirror(r0, rmethod, r5, rscratch2);
 795 
 796 #ifdef ASSERT
 797     {
 798       Label L;
 799       __ cbnz(r0, L);
 800       __ stop("synchronization object is null");
 801       __ bind(L);
 802     }
 803 #endif // ASSERT
 804 
 805     __ bind(done);
 806   }
 807 
 808   // add space for monitor & lock
 809   __ check_extended_sp();
 810   __ sub(sp, sp, entry_size); // add space for a monitor entry
 811   __ sub(esp, esp, entry_size);
 812   __ sub(rscratch1, sp, rfp);
 813   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 814   __ str(rscratch1, Address(rfp, frame::interpreter_frame_extended_sp_offset * wordSize));
 815   __ sub(rscratch1, esp, rfp);
 816   __ asr(rscratch1, rscratch1, Interpreter::logStackElementSize);
 817   __ str(rscratch1, monitor_block_top);  // set new monitor block top
 818 
 819   // store object
 820   __ str(r0, Address(esp, BasicObjectLock::obj_offset()));
 821   __ mov(c_rarg1, esp); // object address
 822   __ lock_object(c_rarg1);
 823 }
 824 
 825 // Generate a fixed interpreter frame. This is identical setup for
 826 // interpreted methods and for native methods hence the shared code.
 827 //
 828 // Args:
 829 //      lr: return address
 830 //      rmethod: Method*
 831 //      rlocals: pointer to locals
 832 //      rcpool: cp cache
 833 //      stack_pointer: previous sp
 834 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 835   // initialize fixed part of activation frame
 836   if (native_call) {
 837     __ sub(esp, sp, 14 *  wordSize);
 838     __ mov(rbcp, zr);
 839     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 840     __ stp(rscratch1, zr, Address(__ pre(sp, -14 * wordSize)));
 841     // add 2 zero-initialized slots for native calls
 842     __ stp(zr, zr, Address(sp, 12 * wordSize));
 843   } else {
 844     __ sub(esp, sp, 12 *  wordSize);
 845     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));    // get ConstMethod
 846     __ add(rbcp, rscratch1, in_bytes(ConstMethod::codes_offset())); // get codebase
 847     __ mov(rscratch1, frame::interpreter_frame_initial_sp_offset);
 848     __ stp(rscratch1, rbcp, Address(__ pre(sp, -12 * wordSize)));
 849   }
 850 
 851   if (ProfileInterpreter) {
 852     Label method_data_continue;
 853     __ ldr(rscratch1, Address(rmethod, Method::method_data_offset()));
 854     __ cbz(rscratch1, method_data_continue);
 855     __ lea(rscratch1, Address(rscratch1, in_bytes(MethodData::data_offset())));
 856     __ bind(method_data_continue);
 857     __ stp(rscratch1, rmethod, Address(sp, 6 * wordSize));  // save Method* and mdp (method data pointer)
 858   } else {
 859     __ stp(zr, rmethod, Address(sp, 6 * wordSize));         // save Method* (no mdp)
 860   }
 861 
 862   __ protect_return_address();
 863   __ stp(rfp, lr, Address(sp, 10 * wordSize));
 864   __ lea(rfp, Address(sp, 10 * wordSize));
 865 
 866   __ ldr(rcpool, Address(rmethod, Method::const_offset()));
 867   __ ldr(rcpool, Address(rcpool, ConstMethod::constants_offset()));
 868   __ ldr(rcpool, Address(rcpool, ConstantPool::cache_offset()));
 869   __ sub(rscratch1, rlocals, rfp);
 870   __ lsr(rscratch1, rscratch1, Interpreter::logStackElementSize);   // rscratch1 = rlocals - fp();
 871   // Store relativized rlocals, see frame::interpreter_frame_locals().
 872   __ stp(rscratch1, rcpool, Address(sp, 2 * wordSize));
 873 
 874   // set sender sp
 875   // leave last_sp as null
 876   __ stp(zr, r19_sender_sp, Address(sp, 8 * wordSize));
 877 
 878   // Get mirror
 879   __ load_mirror(r10, rmethod, r5, rscratch2);
 880   if (! native_call) {
 881     __ ldr(rscratch1, Address(rmethod, Method::const_offset()));
 882     __ ldrh(rscratch1, Address(rscratch1, ConstMethod::max_stack_offset()));
 883     __ add(rscratch1, rscratch1, MAX2(3, Method::extra_stack_entries()));
 884     __ sub(rscratch1, sp, rscratch1, ext::uxtw, 3);
 885     __ andr(rscratch1, rscratch1, -16);
 886     __ sub(rscratch2, rscratch1, rfp);
 887     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 888     // Store extended SP and mirror
 889     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 890     // Move SP out of the way
 891     __ mov(sp, rscratch1);
 892   } else {
 893     // Make sure there is room for the exception oop pushed in case method throws
 894     // an exception (see TemplateInterpreterGenerator::generate_throw_exception())
 895     __ sub(rscratch1, sp, 2 * wordSize);
 896     __ sub(rscratch2, rscratch1, rfp);
 897     __ asr(rscratch2, rscratch2, Interpreter::logStackElementSize);
 898     __ stp(r10, rscratch2, Address(sp, 4 * wordSize));
 899     __ mov(sp, rscratch1);
 900   }
 901 }
 902 
 903 // End of helpers
 904 
 905 // Various method entries
 906 //------------------------------------------------------------------------------------------------------------------------
 907 //
 908 //
 909 
 910 // Method entry for java.lang.ref.Reference.get.
 911 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 912   // Code: _aload_0, _getfield, _areturn
 913   // parameter size = 1
 914   //
 915   // The code that gets generated by this routine is split into 2 parts:
 916   //    1. The "intrinsified" code for G1 (or any SATB based GC),
 917   //    2. The slow path - which is an expansion of the regular method entry.
 918   //
 919   // Notes:-
 920   // * In the G1 code we do not check whether we need to block for
 921   //   a safepoint. If G1 is enabled then we must execute the specialized
 922   //   code for Reference.get (except when the Reference object is null)
 923   //   so that we can log the value in the referent field with an SATB
 924   //   update buffer.
 925   //   If the code for the getfield template is modified so that the
 926   //   G1 pre-barrier code is executed when the current method is
 927   //   Reference.get() then going through the normal method entry
 928   //   will be fine.
 929   // * The G1 code can, however, check the receiver object (the instance
 930   //   of java.lang.Reference) and jump to the slow path if null. If the
 931   //   Reference object is null then we obviously cannot fetch the referent
 932   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 933   //   regular method entry code to generate the NPE.
 934   //
 935   // This code is based on generate_accessor_entry.
 936   //
 937   // rmethod: Method*
 938   // r19_sender_sp: senderSP must preserve for slow path, set SP to it on fast path
 939 
 940   // LR is live.  It must be saved around calls.
 941 
 942   address entry = __ pc();
 943 
 944   const int referent_offset = java_lang_ref_Reference::referent_offset();
 945 
 946   Label slow_path;
 947   const Register local_0 = c_rarg0;
 948   // Check if local 0 != null
 949   // If the receiver is null then it is OK to jump to the slow path.
 950   __ ldr(local_0, Address(esp, 0));
 951   __ cbz(local_0, slow_path);
 952 
 953   // Load the value of the referent field.
 954   const Address field_address(local_0, referent_offset);
 955   BarrierSetAssembler *bs = BarrierSet::barrier_set()->barrier_set_assembler();
 956   bs->load_at(_masm, IN_HEAP | ON_WEAK_OOP_REF, T_OBJECT, local_0, field_address, /*tmp1*/ rscratch1, /*tmp2*/ rscratch2);
 957 
 958   // areturn
 959   __ andr(sp, r19_sender_sp, -16);  // done with stack
 960   __ ret(lr);
 961 
 962   // generate a vanilla interpreter entry as the slow path
 963   __ bind(slow_path);
 964   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 965   return entry;
 966 
 967 }
 968 
 969 /**
 970  * Method entry for static native methods:
 971  *   int java.util.zip.CRC32.update(int crc, int b)
 972  */
 973 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
 974   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
 975   address entry = __ pc();
 976 
 977   // rmethod: Method*
 978   // r19_sender_sp: senderSP must preserved for slow path
 979   // esp: args
 980 
 981   Label slow_path;
 982   // If we need a safepoint check, generate full interpreter entry.
 983   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
 984 
 985   // We don't generate local frame and don't align stack because
 986   // we call stub code and there is no safepoint on this path.
 987 
 988   // Load parameters
 989   const Register crc = c_rarg0;  // crc
 990   const Register val = c_rarg1;  // source java byte value
 991   const Register tbl = c_rarg2;  // scratch
 992 
 993   // Arguments are reversed on java expression stack
 994   __ ldrw(val, Address(esp, 0));              // byte value
 995   __ ldrw(crc, Address(esp, wordSize));       // Initial CRC
 996 
 997   uint64_t offset;
 998   __ adrp(tbl, ExternalAddress(StubRoutines::crc_table_addr()), offset);
 999   __ add(tbl, tbl, offset);
1000 
1001   __ mvnw(crc, crc); // ~crc
1002   __ update_byte_crc32(crc, val, tbl);
1003   __ mvnw(crc, crc); // ~crc
1004 
1005   // result in c_rarg0
1006 
1007   __ andr(sp, r19_sender_sp, -16);
1008   __ ret(lr);
1009 
1010   // generate a vanilla native entry as the slow path
1011   __ bind(slow_path);
1012   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1013   return entry;
1014 }
1015 
1016 /**
1017  * Method entry for static native methods:
1018  *   int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len)
1019  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len)
1020  */
1021 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1022   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1023   address entry = __ pc();
1024 
1025   // rmethod,: Method*
1026   // r19_sender_sp: senderSP must preserved for slow path
1027 
1028   Label slow_path;
1029   // If we need a safepoint check, generate full interpreter entry.
1030   __ safepoint_poll(slow_path, false /* at_return */, false /* acquire */, false /* in_nmethod */);
1031 
1032   // We don't generate local frame and don't align stack because
1033   // we call stub code and there is no safepoint on this path.
1034 
1035   // Load parameters
1036   const Register crc = c_rarg0;  // crc
1037   const Register buf = c_rarg1;  // source java byte array address
1038   const Register len = c_rarg2;  // length
1039   const Register off = len;      // offset (never overlaps with 'len')
1040 
1041   // Arguments are reversed on java expression stack
1042   // Calculate address of start element
1043   if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) {
1044     __ ldr(buf, Address(esp, 2*wordSize)); // long buf
1045     __ ldrw(off, Address(esp, wordSize)); // offset
1046     __ add(buf, buf, off); // + offset
1047     __ ldrw(crc,   Address(esp, 4*wordSize)); // Initial CRC
1048   } else {
1049     __ ldr(buf, Address(esp, 2*wordSize)); // byte[] array
1050     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1051     __ ldrw(off, Address(esp, wordSize)); // offset
1052     __ add(buf, buf, off); // + offset
1053     __ ldrw(crc,   Address(esp, 3*wordSize)); // Initial CRC
1054   }
1055   // Can now load 'len' since we're finished with 'off'
1056   __ ldrw(len, Address(esp, 0x0)); // Length
1057 
1058   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1059 
1060   // We are frameless so we can just jump to the stub.
1061   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()));
1062 
1063   // generate a vanilla native entry as the slow path
1064   __ bind(slow_path);
1065   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native));
1066   return entry;
1067 }
1068 
1069 /**
1070  * Method entry for intrinsic-candidate (non-native) methods:
1071  *   int java.util.zip.CRC32C.updateBytes(int crc, byte[] b, int off, int end)
1072  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long buf, int off, int end)
1073  * Unlike CRC32, CRC32C does not have any methods marked as native
1074  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1075  */
1076 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1077   assert(UseCRC32CIntrinsics, "this intrinsic is not supported");
1078   address entry = __ pc();
1079 
1080   // Prepare jump to stub using parameters from the stack
1081   const Register crc = c_rarg0; // initial crc
1082   const Register buf = c_rarg1; // source java byte array address
1083   const Register len = c_rarg2; // len argument to the kernel
1084 
1085   const Register end = len; // index of last element to process
1086   const Register off = crc; // offset
1087 
1088   __ ldrw(end, Address(esp)); // int end
1089   __ ldrw(off, Address(esp, wordSize)); // int offset
1090   __ sub(len, end, off);
1091   __ ldr(buf, Address(esp, 2*wordSize)); // byte[] buf | long buf
1092   __ add(buf, buf, off); // + offset
1093   if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) {
1094     __ ldrw(crc, Address(esp, 4*wordSize)); // long crc
1095   } else {
1096     __ add(buf, buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size
1097     __ ldrw(crc, Address(esp, 3*wordSize)); // long crc
1098   }
1099 
1100   __ andr(sp, r19_sender_sp, -16); // Restore the caller's SP
1101 
1102   // Jump to the stub.
1103   __ b(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32C()));
1104 
1105   return entry;
1106 }
1107 
1108 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1109   // See more discussion in stackOverflow.hpp.
1110 
1111   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
1112   const int page_size = (int)os::vm_page_size();
1113   const int n_shadow_pages = shadow_zone_size / page_size;
1114 
1115 #ifdef ASSERT
1116   Label L_good_limit;
1117   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1118   __ cbnz(rscratch1, L_good_limit);
1119   __ stop("shadow zone safe limit is not initialized");
1120   __ bind(L_good_limit);
1121 
1122   Label L_good_watermark;
1123   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1124   __ cbnz(rscratch1, L_good_watermark);
1125   __ stop("shadow zone growth watermark is not initialized");
1126   __ bind(L_good_watermark);
1127 #endif
1128 
1129   Label L_done;
1130 
1131   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1132   __ cmp(sp, rscratch1);
1133   __ br(Assembler::HI, L_done);
1134 
1135   for (int p = 1; p <= n_shadow_pages; p++) {
1136     __ sub(rscratch2, sp, p*page_size);
1137     __ str(zr, Address(rscratch2));
1138   }
1139 
1140   // Record the new watermark, but only if the update is above the safe limit.
1141   // Otherwise, the next time around the check above would pass the safe limit.
1142   __ ldr(rscratch1, Address(rthread, JavaThread::shadow_zone_safe_limit()));
1143   __ cmp(sp, rscratch1);
1144   __ br(Assembler::LS, L_done);
1145   __ mov(rscratch1, sp);
1146   __ str(rscratch1, Address(rthread, JavaThread::shadow_zone_growth_watermark()));
1147 
1148   __ bind(L_done);
1149 }
1150 
1151 // Interpreter stub for calling a native method. (asm interpreter)
1152 // This sets up a somewhat different looking stack for calling the
1153 // native method than the typical interpreter frame setup.
1154 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1155   // determine code generation flags
1156   bool inc_counter  = UseCompiler || CountCompiledCalls;
1157 
1158   // r1: Method*
1159   // rscratch1: sender sp
1160 
1161   address entry_point = __ pc();
1162 
1163   const Address constMethod       (rmethod, Method::const_offset());
1164   const Address access_flags      (rmethod, Method::access_flags_offset());
1165   const Address size_of_parameters(r2, ConstMethod::
1166                                        size_of_parameters_offset());
1167 
1168   // get parameter size (always needed)
1169   __ ldr(r2, constMethod);
1170   __ load_unsigned_short(r2, size_of_parameters);
1171 
1172   // Native calls don't need the stack size check since they have no
1173   // expression stack and the arguments are already on the stack and
1174   // we only add a handful of words to the stack.
1175 
1176   // rmethod: Method*
1177   // r2: size of parameters
1178   // rscratch1: sender sp
1179 
1180   // for natives the size of locals is zero
1181 
1182   // compute beginning of parameters (rlocals)
1183   __ add(rlocals, esp, r2, ext::uxtx, 3);
1184   __ add(rlocals, rlocals, -wordSize);
1185 
1186   // Pull SP back to minimum size: this avoids holes in the stack
1187   __ andr(sp, esp, -16);
1188 
1189   // initialize fixed part of activation frame
1190   generate_fixed_frame(true);
1191 
1192   // make sure method is native & not abstract
1193 #ifdef ASSERT
1194   __ ldrw(r0, access_flags);
1195   {
1196     Label L;
1197     __ tst(r0, JVM_ACC_NATIVE);
1198     __ br(Assembler::NE, L);
1199     __ stop("tried to execute non-native method as native");
1200     __ bind(L);
1201   }
1202   {
1203     Label L;
1204     __ tst(r0, JVM_ACC_ABSTRACT);
1205     __ br(Assembler::EQ, L);
1206     __ stop("tried to execute abstract method in interpreter");
1207     __ bind(L);
1208   }
1209 #endif
1210 
1211   // Since at this point in the method invocation the exception
1212   // handler would try to exit the monitor of synchronized methods
1213   // which hasn't been entered yet, we set the thread local variable
1214   // _do_not_unlock_if_synchronized to true. The remove_activation
1215   // will check this flag.
1216 
1217    const Address do_not_unlock_if_synchronized(rthread,
1218         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1219   __ mov(rscratch2, true);
1220   __ strb(rscratch2, do_not_unlock_if_synchronized);
1221 
1222   // increment invocation count & check for overflow
1223   Label invocation_counter_overflow;
1224   if (inc_counter) {
1225     generate_counter_incr(&invocation_counter_overflow);
1226   }
1227 
1228   Label continue_after_compile;
1229   __ bind(continue_after_compile);
1230 
1231   bang_stack_shadow_pages(true);
1232 
1233   // reset the _do_not_unlock_if_synchronized flag
1234   __ strb(zr, do_not_unlock_if_synchronized);
1235 
1236   // check for synchronized methods
1237   // Must happen AFTER invocation_counter check and stack overflow check,
1238   // so method is not locked if overflows.
1239   if (synchronized) {
1240     lock_method();
1241   } else {
1242     // no synchronization necessary
1243 #ifdef ASSERT
1244     {
1245       Label L;
1246       __ ldrw(r0, access_flags);
1247       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1248       __ br(Assembler::EQ, L);
1249       __ stop("method needs synchronization");
1250       __ bind(L);
1251     }
1252 #endif
1253   }
1254 
1255   // start execution
1256 #ifdef ASSERT
1257   {
1258     Label L;
1259     const Address monitor_block_top(rfp,
1260                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1261     __ ldr(rscratch1, monitor_block_top);
1262     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1263     __ cmp(esp, rscratch1);
1264     __ br(Assembler::EQ, L);
1265     __ stop("broken stack frame setup in interpreter 1");
1266     __ bind(L);
1267   }
1268 #endif
1269 
1270   // jvmti support
1271   __ notify_method_entry();
1272 
1273   // work registers
1274   const Register t = r17;
1275   const Register result_handler = r19;
1276 
1277   // allocate space for parameters
1278   __ ldr(t, Address(rmethod, Method::const_offset()));
1279   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
1280 
1281   __ sub(rscratch1, esp, t, ext::uxtx, Interpreter::logStackElementSize);
1282   __ andr(sp, rscratch1, -16);
1283   __ mov(esp, rscratch1);
1284 
1285   // get signature handler
1286   {
1287     Label L;
1288     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1289     __ cbnz(t, L);
1290     __ call_VM(noreg,
1291                CAST_FROM_FN_PTR(address,
1292                                 InterpreterRuntime::prepare_native_call),
1293                rmethod);
1294     __ ldr(t, Address(rmethod, Method::signature_handler_offset()));
1295     __ bind(L);
1296   }
1297 
1298   // call signature handler
1299   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
1300          "adjust this code");
1301   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == sp,
1302          "adjust this code");
1303   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
1304           "adjust this code");
1305 
1306   // The generated handlers do not touch rmethod (the method).
1307   // However, large signatures cannot be cached and are generated
1308   // each time here.  The slow-path generator can do a GC on return,
1309   // so we must reload it after the call.
1310   __ blr(t);
1311   __ get_method(rmethod);        // slow path can do a GC, reload rmethod
1312 
1313 
1314   // result handler is in r0
1315   // set result handler
1316   __ mov(result_handler, r0);
1317   // pass mirror handle if static call
1318   {
1319     Label L;
1320     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1321     __ tbz(t, exact_log2(JVM_ACC_STATIC), L);
1322     // get mirror
1323     __ load_mirror(t, rmethod, r10, rscratch2);
1324     // copy mirror into activation frame
1325     __ str(t, Address(rfp, frame::interpreter_frame_oop_temp_offset * wordSize));
1326     // pass handle to mirror
1327     __ add(c_rarg1, rfp, frame::interpreter_frame_oop_temp_offset * wordSize);
1328     __ bind(L);
1329   }
1330 
1331   // get native function entry point in r10
1332   {
1333     Label L;
1334     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1335     ExternalAddress unsatisfied(SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
1336     __ lea(rscratch2, unsatisfied);
1337     __ ldr(rscratch2, rscratch2);
1338     __ cmp(r10, rscratch2);
1339     __ br(Assembler::NE, L);
1340     __ call_VM(noreg,
1341                CAST_FROM_FN_PTR(address,
1342                                 InterpreterRuntime::prepare_native_call),
1343                rmethod);
1344     __ get_method(rmethod);
1345     __ ldr(r10, Address(rmethod, Method::native_function_offset()));
1346     __ bind(L);
1347   }
1348 
1349   // pass JNIEnv
1350   __ add(c_rarg0, rthread, in_bytes(JavaThread::jni_environment_offset()));
1351 
1352   // Set the last Java PC in the frame anchor to be the return address from
1353   // the call to the native method: this will allow the debugger to
1354   // generate an accurate stack trace.
1355   Label native_return;
1356   __ set_last_Java_frame(esp, rfp, native_return, rscratch1);
1357 
1358   // change thread state
1359 #ifdef ASSERT
1360   {
1361     Label L;
1362     __ ldrw(t, Address(rthread, JavaThread::thread_state_offset()));
1363     __ cmp(t, (u1)_thread_in_Java);
1364     __ br(Assembler::EQ, L);
1365     __ stop("Wrong thread state in native stub");
1366     __ bind(L);
1367   }
1368 #endif
1369 
1370   // Change state to native
1371   __ mov(rscratch1, _thread_in_native);
1372   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1373   __ stlrw(rscratch1, rscratch2);
1374 
1375   // Call the native method.
1376   __ blr(r10);
1377   __ bind(native_return);
1378   __ get_method(rmethod);
1379   // result potentially in r0 or v0
1380 
1381   // Restore cpu control state after JNI call
1382   __ restore_cpu_control_state_after_jni(rscratch1, rscratch2);
1383 
1384   // make room for the pushes we're about to do
1385   __ sub(rscratch1, esp, 4 * wordSize);
1386   __ andr(sp, rscratch1, -16);
1387 
1388   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
1389   // in order to extract the result of a method call. If the order of these
1390   // pushes change or anything else is added to the stack then the code in
1391   // interpreter_frame_result must also change.
1392   __ push(dtos);
1393   __ push(ltos);
1394 
1395   __ verify_sve_vector_length();
1396 
1397   // change thread state
1398   __ mov(rscratch1, _thread_in_native_trans);
1399   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1400   __ stlrw(rscratch1, rscratch2);
1401 
1402   // Force this write out before the read below
1403   if (!UseSystemMemoryBarrier) {
1404     __ dmb(Assembler::ISH);
1405   }
1406 
1407   // check for safepoint operation in progress and/or pending suspend requests
1408   {
1409     Label L, Continue;
1410 
1411     // No need for acquire as Java threads always disarm themselves.
1412     __ safepoint_poll(L, true /* at_return */, false /* acquire */, false /* in_nmethod */);
1413     __ ldrw(rscratch2, Address(rthread, JavaThread::suspend_flags_offset()));
1414     __ cbz(rscratch2, Continue);
1415     __ bind(L);
1416 
1417     // Don't use call_VM as it will see a possible pending exception
1418     // and forward it and never return here preventing us from
1419     // clearing _last_native_pc down below. So we do a runtime call by
1420     // hand.
1421     //
1422     __ mov(c_rarg0, rthread);
1423     __ lea(rscratch2, RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1424     __ blr(rscratch2);
1425     __ get_method(rmethod);
1426     __ reinit_heapbase();
1427     __ bind(Continue);
1428   }
1429 
1430   // change thread state
1431   __ mov(rscratch1, _thread_in_Java);
1432   __ lea(rscratch2, Address(rthread, JavaThread::thread_state_offset()));
1433   __ stlrw(rscratch1, rscratch2);
1434 
1435   // reset_last_Java_frame
1436   __ reset_last_Java_frame(true);
1437 
1438   if (CheckJNICalls) {
1439     // clear_pending_jni_exception_check
1440     __ str(zr, Address(rthread, JavaThread::pending_jni_exception_check_fn_offset()));
1441   }
1442 
1443   // reset handle block
1444   __ ldr(t, Address(rthread, JavaThread::active_handles_offset()));
1445   __ str(zr, Address(t, JNIHandleBlock::top_offset()));
1446 
1447   // If result is an oop unbox and store it in frame where gc will see it
1448   // and result handler will pick it up
1449 
1450   {
1451     Label no_oop;
1452     __ adr(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1453     __ cmp(t, result_handler);
1454     __ br(Assembler::NE, no_oop);
1455     // Unbox oop result, e.g. JNIHandles::resolve result.
1456     __ pop(ltos);
1457     __ resolve_jobject(r0, t, rscratch2);
1458     __ str(r0, Address(rfp, frame::interpreter_frame_oop_temp_offset*wordSize));
1459     // keep stack depth as expected by pushing oop which will eventually be discarded
1460     __ push(ltos);
1461     __ bind(no_oop);
1462   }
1463 
1464   {
1465     Label no_reguard;
1466     __ lea(rscratch1, Address(rthread, in_bytes(JavaThread::stack_guard_state_offset())));
1467     __ ldrw(rscratch1, Address(rscratch1));
1468     __ cmp(rscratch1, (u1)StackOverflow::stack_guard_yellow_reserved_disabled);
1469     __ br(Assembler::NE, no_reguard);
1470 
1471     __ push_call_clobbered_registers();
1472     __ mov(c_rarg0, rthread);
1473     __ lea(rscratch2, RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1474     __ blr(rscratch2);
1475     __ pop_call_clobbered_registers();
1476 
1477     __ bind(no_reguard);
1478   }
1479 
1480   // The method register is junk from after the thread_in_native transition
1481   // until here.  Also can't call_VM until the bcp has been
1482   // restored.  Need bcp for throwing exception below so get it now.
1483   __ get_method(rmethod);
1484 
1485   // restore bcp to have legal interpreter frame, i.e., bci == 0 <=>
1486   // rbcp == code_base()
1487   __ ldr(rbcp, Address(rmethod, Method::const_offset()));   // get ConstMethod*
1488   __ add(rbcp, rbcp, in_bytes(ConstMethod::codes_offset()));          // get codebase
1489   // handle exceptions (exception handling will handle unlocking!)
1490   {
1491     Label L;
1492     __ ldr(rscratch1, Address(rthread, Thread::pending_exception_offset()));
1493     __ cbz(rscratch1, L);
1494     // Note: At some point we may want to unify this with the code
1495     // used in call_VM_base(); i.e., we should use the
1496     // StubRoutines::forward_exception code. For now this doesn't work
1497     // here because the rsp is not correctly set at this point.
1498     __ MacroAssembler::call_VM(noreg,
1499                                CAST_FROM_FN_PTR(address,
1500                                InterpreterRuntime::throw_pending_exception));
1501     __ should_not_reach_here();
1502     __ bind(L);
1503   }
1504 
1505   // do unlocking if necessary
1506   {
1507     Label L;
1508     __ ldrw(t, Address(rmethod, Method::access_flags_offset()));
1509     __ tbz(t, exact_log2(JVM_ACC_SYNCHRONIZED), L);
1510     // the code below should be shared with interpreter macro
1511     // assembler implementation
1512     {
1513       Label unlock;
1514       // BasicObjectLock will be first in list, since this is a
1515       // synchronized method. However, need to check that the object
1516       // has not been unlocked by an explicit monitorexit bytecode.
1517 
1518       // monitor expect in c_rarg1 for slow unlock path
1519       __ lea (c_rarg1, Address(rfp,   // address of first monitor
1520                                (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1521                                           wordSize - sizeof(BasicObjectLock))));
1522 
1523       __ ldr(t, Address(c_rarg1, BasicObjectLock::obj_offset()));
1524       __ cbnz(t, unlock);
1525 
1526       // Entry already unlocked, need to throw exception
1527       __ MacroAssembler::call_VM(noreg,
1528                                  CAST_FROM_FN_PTR(address,
1529                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1530       __ should_not_reach_here();
1531 
1532       __ bind(unlock);
1533       __ unlock_object(c_rarg1);
1534     }
1535     __ bind(L);
1536   }
1537 
1538   // jvmti support
1539   // Note: This must happen _after_ handling/throwing any exceptions since
1540   //       the exception handler code notifies the runtime of method exits
1541   //       too. If this happens before, method entry/exit notifications are
1542   //       not properly paired (was bug - gri 11/22/99).
1543   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1544 
1545   // restore potential result in r0:d0, call result handler to
1546   // restore potential result in ST0 & handle result
1547 
1548   __ pop(ltos);
1549   __ pop(dtos);
1550 
1551   __ blr(result_handler);
1552 
1553   // remove activation
1554   __ ldr(esp, Address(rfp,
1555                     frame::interpreter_frame_sender_sp_offset *
1556                     wordSize)); // get sender sp
1557   // remove frame anchor
1558   __ leave();
1559 
1560   // restore sender sp
1561   __ mov(sp, esp);
1562 
1563   __ ret(lr);
1564 
1565   if (inc_counter) {
1566     // Handle overflow of counter and compile method
1567     __ bind(invocation_counter_overflow);
1568     generate_counter_overflow(continue_after_compile);
1569   }
1570 
1571   return entry_point;
1572 }
1573 
1574 //
1575 // Generic interpreted method entry to (asm) interpreter
1576 //
1577 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1578   // determine code generation flags
1579   bool inc_counter  = UseCompiler || CountCompiledCalls;
1580 
1581   // rscratch1: sender sp
1582   address entry_point = __ pc();
1583 
1584   const Address constMethod(rmethod, Method::const_offset());
1585   const Address access_flags(rmethod, Method::access_flags_offset());
1586   const Address size_of_parameters(r3,
1587                                    ConstMethod::size_of_parameters_offset());
1588   const Address size_of_locals(r3, ConstMethod::size_of_locals_offset());
1589 
1590   // get parameter size (always needed)
1591   // need to load the const method first
1592   __ ldr(r3, constMethod);
1593   __ load_unsigned_short(r2, size_of_parameters);
1594 
1595   // r2: size of parameters
1596 
1597   __ load_unsigned_short(r3, size_of_locals); // get size of locals in words
1598   __ sub(r3, r3, r2); // r3 = no. of additional locals
1599 
1600   // see if we've got enough room on the stack for locals plus overhead.
1601   generate_stack_overflow_check();
1602 
1603   // compute beginning of parameters (rlocals)
1604   __ add(rlocals, esp, r2, ext::uxtx, 3);
1605   __ sub(rlocals, rlocals, wordSize);
1606 
1607   __ mov(rscratch1, esp);
1608 
1609   // r3 - # of additional locals
1610   // allocate space for locals
1611   // explicitly initialize locals
1612   // Initializing memory allocated for locals in the same direction as
1613   // the stack grows to ensure page initialization order according
1614   // to windows-aarch64 stack page growth requirement (see
1615   // https://docs.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-160#stack)
1616   {
1617     Label exit, loop;
1618     __ ands(zr, r3, r3);
1619     __ br(Assembler::LE, exit); // do nothing if r3 <= 0
1620     __ bind(loop);
1621     __ str(zr, Address(__ pre(rscratch1, -wordSize)));
1622     __ sub(r3, r3, 1); // until everything initialized
1623     __ cbnz(r3, loop);
1624     __ bind(exit);
1625   }
1626 
1627   // Padding between locals and fixed part of activation frame to ensure
1628   // SP is always 16-byte aligned.
1629   __ andr(sp, rscratch1, -16);
1630 
1631   // And the base dispatch table
1632   __ get_dispatch();
1633 
1634   // initialize fixed part of activation frame
1635   generate_fixed_frame(false);
1636 
1637   // make sure method is not native & not abstract
1638 #ifdef ASSERT
1639   __ ldrw(r0, access_flags);
1640   {
1641     Label L;
1642     __ tst(r0, JVM_ACC_NATIVE);
1643     __ br(Assembler::EQ, L);
1644     __ stop("tried to execute native method as non-native");
1645     __ bind(L);
1646   }
1647  {
1648     Label L;
1649     __ tst(r0, JVM_ACC_ABSTRACT);
1650     __ br(Assembler::EQ, L);
1651     __ stop("tried to execute abstract method in interpreter");
1652     __ bind(L);
1653   }
1654 #endif
1655 
1656   // Since at this point in the method invocation the exception
1657   // handler would try to exit the monitor of synchronized methods
1658   // which hasn't been entered yet, we set the thread local variable
1659   // _do_not_unlock_if_synchronized to true. The remove_activation
1660   // will check this flag.
1661 
1662    const Address do_not_unlock_if_synchronized(rthread,
1663         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1664   __ mov(rscratch2, true);
1665   __ strb(rscratch2, do_not_unlock_if_synchronized);
1666 
1667   Register mdp = r3;
1668   __ profile_parameters_type(mdp, r1, r2);
1669 
1670   // increment invocation count & check for overflow
1671   Label invocation_counter_overflow;
1672   if (inc_counter) {
1673     generate_counter_incr(&invocation_counter_overflow);
1674   }
1675 
1676   Label continue_after_compile;
1677   __ bind(continue_after_compile);
1678 
1679   bang_stack_shadow_pages(false);
1680 
1681   // reset the _do_not_unlock_if_synchronized flag
1682   __ strb(zr, do_not_unlock_if_synchronized);
1683 
1684   // check for synchronized methods
1685   // Must happen AFTER invocation_counter check and stack overflow check,
1686   // so method is not locked if overflows.
1687   if (synchronized) {
1688     // Allocate monitor and lock method
1689     lock_method();
1690   } else {
1691     // no synchronization necessary
1692 #ifdef ASSERT
1693     {
1694       Label L;
1695       __ ldrw(r0, access_flags);
1696       __ tst(r0, JVM_ACC_SYNCHRONIZED);
1697       __ br(Assembler::EQ, L);
1698       __ stop("method needs synchronization");
1699       __ bind(L);
1700     }
1701 #endif
1702   }
1703 
1704   // start execution
1705 #ifdef ASSERT
1706   {
1707     Label L;
1708      const Address monitor_block_top (rfp,
1709                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1710     __ ldr(rscratch1, monitor_block_top);
1711     __ lea(rscratch1, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1712     __ cmp(esp, rscratch1);
1713     __ br(Assembler::EQ, L);
1714     __ stop("broken stack frame setup in interpreter 2");
1715     __ bind(L);
1716   }
1717 #endif
1718 
1719   // jvmti support
1720   __ notify_method_entry();
1721 
1722   __ dispatch_next(vtos);
1723 
1724   // invocation counter overflow
1725   if (inc_counter) {
1726     // Handle overflow of counter and compile method
1727     __ bind(invocation_counter_overflow);
1728     generate_counter_overflow(continue_after_compile);
1729   }
1730 
1731   return entry_point;
1732 }
1733 
1734 // Method entry for java.lang.Thread.currentThread
1735 address TemplateInterpreterGenerator::generate_currentThread() {
1736   address entry_point = __ pc();
1737 
1738   __ ldr(r0, Address(rthread, JavaThread::vthread_offset()));
1739   __ resolve_oop_handle(r0, rscratch1, rscratch2);
1740   __ ret(lr);
1741 
1742   return entry_point;
1743 }
1744 
1745 // Not supported
1746 address TemplateInterpreterGenerator::generate_Float_intBitsToFloat_entry() { return nullptr; }
1747 address TemplateInterpreterGenerator::generate_Float_floatToRawIntBits_entry() { return nullptr; }
1748 address TemplateInterpreterGenerator::generate_Double_longBitsToDouble_entry() { return nullptr; }
1749 address TemplateInterpreterGenerator::generate_Double_doubleToRawLongBits_entry() { return nullptr; }
1750 
1751 //-----------------------------------------------------------------------------
1752 // Exceptions
1753 
1754 void TemplateInterpreterGenerator::generate_throw_exception() {
1755   // Entry point in previous activation (i.e., if the caller was
1756   // interpreted)
1757   Interpreter::_rethrow_exception_entry = __ pc();
1758   // Restore sp to interpreter_frame_last_sp even though we are going
1759   // to empty the expression stack for the exception processing.
1760   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1761   // r0: exception
1762   // r3: return address/pc that threw exception
1763   __ restore_bcp();    // rbcp points to call/send
1764   __ restore_locals();
1765   __ restore_constant_pool_cache();
1766   __ reinit_heapbase();  // restore rheapbase as heapbase.
1767   __ get_dispatch();
1768 
1769   // Entry point for exceptions thrown within interpreter code
1770   Interpreter::_throw_exception_entry = __ pc();
1771   // If we came here via a NullPointerException on the receiver of a
1772   // method, rmethod may be corrupt.
1773   __ get_method(rmethod);
1774   // expression stack is undefined here
1775   // r0: exception
1776   // rbcp: exception bcp
1777   __ verify_oop(r0);
1778   __ mov(c_rarg1, r0);
1779 
1780   // expression stack must be empty before entering the VM in case of
1781   // an exception
1782   __ empty_expression_stack();
1783   // find exception handler address and preserve exception oop
1784   __ call_VM(r3,
1785              CAST_FROM_FN_PTR(address,
1786                           InterpreterRuntime::exception_handler_for_exception),
1787              c_rarg1);
1788 
1789   // Restore machine SP
1790   __ restore_sp_after_call();
1791 
1792   // r0: exception handler entry point
1793   // r3: preserved exception oop
1794   // rbcp: bcp for exception handler
1795   __ push_ptr(r3); // push exception which is now the only value on the stack
1796   __ br(r0); // jump to exception handler (may be _remove_activation_entry!)
1797 
1798   // If the exception is not handled in the current frame the frame is
1799   // removed and the exception is rethrown (i.e. exception
1800   // continuation is _rethrow_exception).
1801   //
1802   // Note: At this point the bci is still the bxi for the instruction
1803   // which caused the exception and the expression stack is
1804   // empty. Thus, for any VM calls at this point, GC will find a legal
1805   // oop map (with empty expression stack).
1806 
1807   //
1808   // JVMTI PopFrame support
1809   //
1810 
1811   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1812   __ empty_expression_stack();
1813   // Set the popframe_processing bit in pending_popframe_condition
1814   // indicating that we are currently handling popframe, so that
1815   // call_VMs that may happen later do not trigger new popframe
1816   // handling cycles.
1817   __ ldrw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1818   __ orr(r3, r3, JavaThread::popframe_processing_bit);
1819   __ strw(r3, Address(rthread, JavaThread::popframe_condition_offset()));
1820 
1821   {
1822     // Check to see whether we are returning to a deoptimized frame.
1823     // (The PopFrame call ensures that the caller of the popped frame is
1824     // either interpreted or compiled and deoptimizes it if compiled.)
1825     // In this case, we can't call dispatch_next() after the frame is
1826     // popped, but instead must save the incoming arguments and restore
1827     // them after deoptimization has occurred.
1828     //
1829     // Note that we don't compare the return PC against the
1830     // deoptimization blob's unpack entry because of the presence of
1831     // adapter frames in C2.
1832     Label caller_not_deoptimized;
1833     __ ldr(c_rarg1, Address(rfp, frame::return_addr_offset * wordSize));
1834     // This is a return address, so requires authenticating for PAC.
1835     __ authenticate_return_address(c_rarg1);
1836     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1837                                InterpreterRuntime::interpreter_contains), c_rarg1);
1838     __ cbnz(r0, caller_not_deoptimized);
1839 
1840     // Compute size of arguments for saving when returning to
1841     // deoptimized caller
1842     __ get_method(r0);
1843     __ ldr(r0, Address(r0, Method::const_offset()));
1844     __ load_unsigned_short(r0, Address(r0, in_bytes(ConstMethod::
1845                                                     size_of_parameters_offset())));
1846     __ lsl(r0, r0, Interpreter::logStackElementSize);
1847     __ restore_locals(); // XXX do we need this?
1848     __ sub(rlocals, rlocals, r0);
1849     __ add(rlocals, rlocals, wordSize);
1850     // Save these arguments
1851     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1852                                            Deoptimization::
1853                                            popframe_preserve_args),
1854                           rthread, r0, rlocals);
1855 
1856     __ remove_activation(vtos,
1857                          /* throw_monitor_exception */ false,
1858                          /* install_monitor_exception */ false,
1859                          /* notify_jvmdi */ false);
1860 
1861     // Inform deoptimization that it is responsible for restoring
1862     // these arguments
1863     __ mov(rscratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1864     __ strw(rscratch1, Address(rthread, JavaThread::popframe_condition_offset()));
1865 
1866     // Continue in deoptimization handler
1867     __ ret(lr);
1868 
1869     __ bind(caller_not_deoptimized);
1870   }
1871 
1872   __ remove_activation(vtos,
1873                        /* throw_monitor_exception */ false,
1874                        /* install_monitor_exception */ false,
1875                        /* notify_jvmdi */ false);
1876 
1877   // Restore the last_sp and null it out
1878   __ ldr(rscratch1, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1879   __ lea(esp, Address(rfp, rscratch1, Address::lsl(Interpreter::logStackElementSize)));
1880   __ str(zr, Address(rfp, frame::interpreter_frame_last_sp_offset * wordSize));
1881 
1882   __ restore_bcp();
1883   __ restore_locals();
1884   __ restore_constant_pool_cache();
1885   __ get_method(rmethod);
1886   __ get_dispatch();
1887 
1888   // The method data pointer was incremented already during
1889   // call profiling. We have to restore the mdp for the current bcp.
1890   if (ProfileInterpreter) {
1891     __ set_method_data_pointer_for_bcp();
1892   }
1893 
1894   // Clear the popframe condition flag
1895   __ strw(zr, Address(rthread, JavaThread::popframe_condition_offset()));
1896   assert(JavaThread::popframe_inactive == 0, "fix popframe_inactive");
1897 
1898 #if INCLUDE_JVMTI
1899   {
1900     Label L_done;
1901 
1902     __ ldrb(rscratch1, Address(rbcp, 0));
1903     __ cmpw(rscratch1, Bytecodes::_invokestatic);
1904     __ br(Assembler::NE, L_done);
1905 
1906     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1907     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1908 
1909     __ ldr(c_rarg0, Address(rlocals, 0));
1910     __ call_VM(r0, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), c_rarg0, rmethod, rbcp);
1911 
1912     __ cbz(r0, L_done);
1913 
1914     __ str(r0, Address(esp, 0));
1915     __ bind(L_done);
1916   }
1917 #endif // INCLUDE_JVMTI
1918 
1919   // Restore machine SP
1920   __ restore_sp_after_call();
1921 
1922   __ dispatch_next(vtos);
1923   // end of PopFrame support
1924 
1925   Interpreter::_remove_activation_entry = __ pc();
1926 
1927   // preserve exception over this code sequence
1928   __ pop_ptr(r0);
1929   __ str(r0, Address(rthread, JavaThread::vm_result_offset()));
1930   // remove the activation (without doing throws on illegalMonitorExceptions)
1931   __ remove_activation(vtos, false, true, false);
1932   // restore exception
1933   __ get_vm_result(r0, rthread);
1934 
1935   // In between activations - previous activation type unknown yet
1936   // compute continuation point - the continuation point expects the
1937   // following registers set up:
1938   //
1939   // r0: exception
1940   // lr: return address/pc that threw exception
1941   // esp: expression stack of caller
1942   // rfp: fp of caller
1943   __ stp(r0, lr, Address(__ pre(sp, -2 * wordSize)));  // save exception & return address
1944   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1945                           SharedRuntime::exception_handler_for_return_address),
1946                         rthread, lr);
1947   __ mov(r1, r0);                               // save exception handler
1948   __ ldp(r0, lr, Address(__ post(sp, 2 * wordSize)));  // restore exception & return address
1949   // We might be returning to a deopt handler that expects r3 to
1950   // contain the exception pc
1951   __ mov(r3, lr);
1952   // Note that an "issuing PC" is actually the next PC after the call
1953   __ br(r1);                                    // jump to exception
1954                                                 // handler of caller
1955 }
1956 
1957 
1958 //
1959 // JVMTI ForceEarlyReturn support
1960 //
1961 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1962   address entry = __ pc();
1963 
1964   __ restore_bcp();
1965   __ restore_locals();
1966   __ empty_expression_stack();
1967   __ load_earlyret_value(state);
1968 
1969   __ ldr(rscratch1, Address(rthread, JavaThread::jvmti_thread_state_offset()));
1970   Address cond_addr(rscratch1, JvmtiThreadState::earlyret_state_offset());
1971 
1972   // Clear the earlyret state
1973   assert(JvmtiThreadState::earlyret_inactive == 0, "should be");
1974   __ str(zr, cond_addr);
1975 
1976   __ remove_activation(state,
1977                        false, /* throw_monitor_exception */
1978                        false, /* install_monitor_exception */
1979                        true); /* notify_jvmdi */
1980   __ ret(lr);
1981 
1982   return entry;
1983 } // end of ForceEarlyReturn support
1984 
1985 
1986 
1987 //-----------------------------------------------------------------------------
1988 // Helper for vtos entry point generation
1989 
1990 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
1991                                                          address& bep,
1992                                                          address& cep,
1993                                                          address& sep,
1994                                                          address& aep,
1995                                                          address& iep,
1996                                                          address& lep,
1997                                                          address& fep,
1998                                                          address& dep,
1999                                                          address& vep) {
2000   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2001   Label L;
2002   aep = __ pc();     // atos entry point
2003       __ push_ptr();
2004       __ b(L);
2005   fep = __ pc();     // ftos entry point
2006       __ push_f();
2007       __ b(L);
2008   dep = __ pc();     // dtos entry point
2009       __ push_d();
2010       __ b(L);
2011   lep = __ pc();     // ltos entry point
2012       __ push_l();
2013       __ b(L);
2014   bep = cep = sep = iep = __ pc();     // [bcsi]tos entry point
2015       __ push_i();
2016   vep = __ pc();     // vtos entry point
2017   __ bind(L);
2018   generate_and_dispatch(t);
2019 }
2020 
2021 //-----------------------------------------------------------------------------
2022 
2023 // Non-product code
2024 #ifndef PRODUCT
2025 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2026   address entry = __ pc();
2027 
2028   __ protect_return_address();
2029   __ push(lr);
2030   __ push(state);
2031   __ push(RegSet::range(r0, r15), sp);
2032   __ mov(c_rarg2, r0);  // Pass itos
2033   __ call_VM(noreg,
2034              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
2035              c_rarg1, c_rarg2, c_rarg3);
2036   __ pop(RegSet::range(r0, r15), sp);
2037   __ pop(state);
2038   __ pop(lr);
2039   __ authenticate_return_address();
2040   __ ret(lr);                                   // return from result handler
2041 
2042   return entry;
2043 }
2044 
2045 void TemplateInterpreterGenerator::count_bytecode() {
2046   __ mov(r10, (address) &BytecodeCounter::_counter_value);
2047   __ atomic_addw(noreg, 1, r10);
2048 }
2049 
2050 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2051   __ mov(r10, (address) &BytecodeHistogram::_counters[t->bytecode()]);
2052   __ atomic_addw(noreg, 1, r10);
2053 }
2054 
2055 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2056   // Calculate new index for counter:
2057   //   _index = (_index >> log2_number_of_codes) |
2058   //            (bytecode << log2_number_of_codes);
2059   Register index_addr = rscratch1;
2060   Register index = rscratch2;
2061   __ mov(index_addr, (address) &BytecodePairHistogram::_index);
2062   __ ldrw(index, index_addr);
2063   __ mov(r10,
2064          ((int)t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2065   __ orrw(index, r10, index, Assembler::LSR,
2066           BytecodePairHistogram::log2_number_of_codes);
2067   __ strw(index, index_addr);
2068 
2069   // Bump bucket contents:
2070   //   _counters[_index] ++;
2071   Register counter_addr = rscratch1;
2072   __ mov(r10, (address) &BytecodePairHistogram::_counters);
2073   __ lea(counter_addr, Address(r10, index, Address::lsl(LogBytesPerInt)));
2074   __ atomic_addw(noreg, 1, counter_addr);
2075 }
2076 
2077 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2078   // Call a little run-time stub to avoid blow-up for each bytecode.
2079   // The run-time runtime saves the right registers, depending on
2080   // the tosca in-state for the given template.
2081 
2082   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
2083          "entry must have been generated");
2084   __ bl(RuntimeAddress(Interpreter::trace_code(t->tos_in())));
2085   __ reinit_heapbase();
2086 }
2087 
2088 
2089 void TemplateInterpreterGenerator::stop_interpreter_at() {
2090   Label L;
2091   __ push(rscratch1);
2092   __ mov(rscratch1, (address) &BytecodeCounter::_counter_value);
2093   __ ldr(rscratch1, Address(rscratch1));
2094   __ mov(rscratch2, StopInterpreterAt);
2095   __ cmpw(rscratch1, rscratch2);
2096   __ br(Assembler::NE, L);
2097   __ brk(0);
2098   __ bind(L);
2099   __ pop(rscratch1);
2100 }
2101 
2102 #endif // !PRODUCT