1 /*
   2  * Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "asm/macroAssembler.hpp"
  26 #include "classfile/javaClasses.hpp"
  27 #include "compiler/compiler_globals.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interpreter/bytecodeHistogram.hpp"
  31 #include "interpreter/interp_masm.hpp"
  32 #include "interpreter/interpreter.hpp"
  33 #include "interpreter/interpreterRuntime.hpp"
  34 #include "interpreter/templateInterpreterGenerator.hpp"
  35 #include "interpreter/templateTable.hpp"
  36 #include "oops/arrayOop.hpp"
  37 #include "oops/methodCounters.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "oops/method.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "oops/inlineKlass.hpp"
  42 #include "oops/resolvedIndyEntry.hpp"
  43 #include "oops/resolvedMethodEntry.hpp"
  44 #include "prims/jvmtiExport.hpp"
  45 #include "prims/jvmtiThreadState.hpp"
  46 #include "runtime/continuation.hpp"
  47 #include "runtime/deoptimization.hpp"
  48 #include "runtime/frame.inline.hpp"
  49 #include "runtime/globals.hpp"
  50 #include "runtime/jniHandles.hpp"
  51 #include "runtime/sharedRuntime.hpp"
  52 #include "runtime/stubRoutines.hpp"
  53 #include "runtime/synchronizer.hpp"
  54 #include "runtime/timer.hpp"
  55 #include "runtime/vframeArray.hpp"
  56 #include "utilities/checkedCast.hpp"
  57 #include "utilities/debug.hpp"
  58 #include "utilities/macros.hpp"
  59 
  60 #define __ Disassembler::hook<InterpreterMacroAssembler>(__FILE__, __LINE__, _masm)->
  61 
  62 // Size of interpreter code.  Increase if too small.  Interpreter will
  63 // fail with a guarantee ("not enough space for interpreter generation");
  64 // if too small.
  65 // Run with +PrintInterpreter to get the VM to print out the size.
  66 // Max size with JVMTI
  67 int TemplateInterpreter::InterpreterCodeSize = 268 * 1024;
  68 
  69 // Global Register Names
  70 static const Register rbcp     = r13;
  71 static const Register rlocals  = r14;
  72 
  73 const int method_offset = frame::interpreter_frame_method_offset * wordSize;
  74 const int bcp_offset    = frame::interpreter_frame_bcp_offset    * wordSize;
  75 const int locals_offset = frame::interpreter_frame_locals_offset * wordSize;
  76 
  77 
  78 //-----------------------------------------------------------------------------
  79 
  80 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
  81   address entry = __ pc();
  82 
  83 #ifdef ASSERT
  84   {
  85     Label L;
  86     __ movptr(rax, Address(rbp,
  87                            frame::interpreter_frame_monitor_block_top_offset *
  88                            wordSize));
  89     __ lea(rax, Address(rbp, rax, Address::times_ptr));
  90     __ cmpptr(rax, rsp); // rax = maximal rsp for current rbp (stack
  91                          // grows negative)
  92     __ jcc(Assembler::aboveEqual, L); // check if frame is complete
  93     __ stop ("interpreter frame not set up");
  94     __ bind(L);
  95   }
  96 #endif // ASSERT
  97   // Restore bcp under the assumption that the current frame is still
  98   // interpreted
  99   __ restore_bcp();
 100 
 101   // expression stack must be empty before entering the VM if an
 102   // exception happened
 103   __ empty_expression_stack();
 104   // throw exception
 105   __ call_VM(noreg,
 106              CAST_FROM_FN_PTR(address,
 107                               InterpreterRuntime::throw_StackOverflowError));
 108   return entry;
 109 }
 110 
 111 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 112   address entry = __ pc();
 113   // The expression stack must be empty before entering the VM if an
 114   // exception happened.
 115   __ empty_expression_stack();
 116 
 117   // Setup parameters.
 118   // ??? convention: expect aberrant index in register ebx/rbx.
 119   // Pass array to create more detailed exceptions.
 120   __ call_VM(noreg,
 121              CAST_FROM_FN_PTR(address,
 122                               InterpreterRuntime::
 123                               throw_ArrayIndexOutOfBoundsException),
 124              c_rarg1, rbx);
 125   return entry;
 126 }
 127 
 128 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 129   address entry = __ pc();
 130 
 131   // object is at TOS
 132   __ pop(c_rarg1);
 133 
 134   // expression stack must be empty before entering the VM if an
 135   // exception happened
 136   __ empty_expression_stack();
 137 
 138   __ call_VM(noreg,
 139              CAST_FROM_FN_PTR(address,
 140                               InterpreterRuntime::
 141                               throw_ClassCastException),
 142              c_rarg1);
 143   return entry;
 144 }
 145 
 146 address TemplateInterpreterGenerator::generate_exception_handler_common(
 147         const char* name, const char* message, bool pass_oop) {
 148   assert(!pass_oop || message == nullptr, "either oop or message but not both");
 149   address entry = __ pc();
 150 
 151   if (pass_oop) {
 152     // object is at TOS
 153     __ pop(c_rarg2);
 154   }
 155   // expression stack must be empty before entering the VM if an
 156   // exception happened
 157   __ empty_expression_stack();
 158   // setup parameters
 159   __ lea(c_rarg1, ExternalAddress((address)name));
 160   if (pass_oop) {
 161     __ call_VM(rax, CAST_FROM_FN_PTR(address,
 162                                      InterpreterRuntime::
 163                                      create_klass_exception),
 164                c_rarg1, c_rarg2);
 165   } else {
 166     __ lea(c_rarg2, ExternalAddress((address)message));
 167     __ call_VM(rax,
 168                CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception),
 169                c_rarg1, c_rarg2);
 170   }
 171   // throw exception
 172   __ jump(RuntimeAddress(Interpreter::throw_exception_entry()));
 173   return entry;
 174 }
 175 
 176 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 177   address entry = __ pc();
 178 
 179   // Restore stack bottom in case i2c adjusted stack
 180   __ movptr(rscratch1, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
 181   __ lea(rsp, Address(rbp, rscratch1, Address::times_ptr));
 182   // and null it as marker that esp is now tos until next java call
 183   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 184 
 185   if (state == atos && InlineTypeReturnedAsFields) {
 186     __ store_inline_type_fields_to_buf(nullptr);
 187   }
 188 
 189   __ restore_bcp();
 190   __ restore_locals();
 191 
 192   if (state == atos) {
 193     Register mdp = rbx;
 194     Register tmp = rcx;
 195     __ profile_return_type(mdp, rax, tmp);
 196   }
 197 
 198   const Register cache = rbx;
 199   const Register index = rcx;
 200   if (index_size == sizeof(u4)) {
 201     __ load_resolved_indy_entry(cache, index);
 202     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedIndyEntry::num_parameters_offset())));
 203     __ lea(rsp, Address(rsp, cache, Interpreter::stackElementScale()));
 204   } else {
 205     assert(index_size == sizeof(u2), "Can only be u2");
 206     __ load_method_entry(cache, index);
 207     __ load_unsigned_short(cache, Address(cache, in_bytes(ResolvedMethodEntry::num_parameters_offset())));
 208     __ lea(rsp, Address(rsp, cache, Interpreter::stackElementScale()));
 209   }
 210 
 211    if (JvmtiExport::can_pop_frame()) {
 212      __ check_and_handle_popframe();
 213    }
 214    if (JvmtiExport::can_force_early_return()) {
 215      __ check_and_handle_earlyret();
 216    }
 217 
 218   __ dispatch_next(state, step);
 219 
 220   return entry;
 221 }
 222 
 223 
 224 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step, address continuation) {
 225   address entry = __ pc();
 226 
 227   // null last_sp until next java call
 228   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 229   __ restore_bcp();
 230   __ restore_locals();
 231   const Register thread = r15_thread;
 232   // handle exceptions
 233   {
 234     Label L;
 235     __ cmpptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
 236     __ jcc(Assembler::zero, L);
 237     __ call_VM(noreg,
 238                CAST_FROM_FN_PTR(address,
 239                                 InterpreterRuntime::throw_pending_exception));
 240     __ should_not_reach_here();
 241     __ bind(L);
 242   }
 243   if (continuation == nullptr) {
 244     __ dispatch_next(state, step);
 245   } else {
 246     __ jump_to_entry(continuation);
 247   }
 248   return entry;
 249 }
 250 
 251 address TemplateInterpreterGenerator::generate_result_handler_for(
 252         BasicType type) {
 253   address entry = __ pc();
 254   switch (type) {
 255   case T_BOOLEAN: __ c2bool(rax);            break;
 256   case T_CHAR   : __ movzwl(rax, rax);       break;
 257   case T_BYTE   : __ sign_extend_byte(rax);  break;
 258   case T_SHORT  : __ sign_extend_short(rax); break;
 259   case T_INT    : /* nothing to do */        break;
 260   case T_LONG   : /* nothing to do */        break;
 261   case T_VOID   : /* nothing to do */        break;
 262   case T_FLOAT  : /* nothing to do */        break;
 263   case T_DOUBLE : /* nothing to do */        break;
 264 
 265   case T_OBJECT :
 266     // retrieve result from frame
 267     __ movptr(rax, Address(rbp, frame::interpreter_frame_oop_temp_offset*wordSize));
 268     // and verify it
 269     __ verify_oop(rax);
 270     break;
 271   default       : ShouldNotReachHere();
 272   }
 273   __ ret(0);                                   // return from result handler
 274   return entry;
 275 }
 276 
 277 address TemplateInterpreterGenerator::generate_safept_entry_for(
 278         TosState state,
 279         address runtime_entry) {
 280   address entry = __ pc();
 281 
 282   __ push(state);
 283   __ push_cont_fastpath();
 284   __ call_VM(noreg, runtime_entry);
 285   __ pop_cont_fastpath();
 286 
 287   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 288   return entry;
 289 }
 290 
 291 address TemplateInterpreterGenerator::generate_cont_resume_interpreter_adapter() {
 292   if (!Continuations::enabled()) return nullptr;
 293   address start = __ pc();
 294 
 295   __ restore_bcp();
 296   __ restore_locals();
 297 
 298   // Get return address before adjusting rsp
 299   __ movptr(rax, Address(rsp, 0));
 300 
 301   // Restore stack bottom
 302   __ movptr(rcx, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
 303   __ lea(rsp, Address(rbp, rcx, Address::times_ptr));
 304   // and null it as marker that esp is now tos until next java call
 305   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
 306 
 307   __ jmp(rax);
 308 
 309   return start;
 310 }
 311 
 312 
 313 // Helpers for commoning out cases in the various type of method entries.
 314 //
 315 
 316 
 317 // increment invocation count & check for overflow
 318 //
 319 // Note: checking for negative value instead of overflow
 320 //       so we have a 'sticky' overflow test
 321 //
 322 // rbx: method
 323 // rcx: invocation counter
 324 //
 325 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 326   Label done;
 327   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
 328   Label no_mdo;
 329   if (ProfileInterpreter) {
 330     // Are we profiling?
 331     __ movptr(rax, Address(rbx, Method::method_data_offset()));
 332     __ testptr(rax, rax);
 333     __ jccb(Assembler::zero, no_mdo);
 334     // Increment counter in the MDO
 335     const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) +
 336         in_bytes(InvocationCounter::counter_offset()));
 337     const Address mask(rax, in_bytes(MethodData::invoke_mask_offset()));
 338     __ increment_mask_and_jump(mdo_invocation_counter, mask, rcx, overflow);
 339     __ jmp(done);
 340   }
 341   __ bind(no_mdo);
 342   // Increment counter in MethodCounters
 343   const Address invocation_counter(rax,
 344       MethodCounters::invocation_counter_offset() +
 345       InvocationCounter::counter_offset());
 346   __ get_method_counters(rbx, rax, done);
 347   const Address mask(rax, in_bytes(MethodCounters::invoke_mask_offset()));
 348   __ increment_mask_and_jump(invocation_counter, mask, rcx, overflow);
 349   __ bind(done);
 350 }
 351 
 352 void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
 353 
 354   // Asm interpreter on entry
 355   // r14/rdi - locals
 356   // r13/rsi - bcp
 357   // rbx - method
 358   // rdx - cpool --- DOES NOT APPEAR TO BE TRUE
 359   // rbp - interpreter frame
 360 
 361   // On return (i.e. jump to entry_point) [ back to invocation of interpreter ]
 362   // Everything as it was on entry
 363   // rdx is not restored. Doesn't appear to really be set.
 364 
 365   // InterpreterRuntime::frequency_counter_overflow takes two
 366   // arguments, the first (thread) is passed by call_VM, the second
 367   // indicates if the counter overflow occurs at a backwards branch
 368   // (null bcp).  We pass zero for it.  The call returns the address
 369   // of the verified entry point for the method or null if the
 370   // compilation did not complete (either went background or bailed
 371   // out).
 372   __ movl(c_rarg1, 0);
 373   __ call_VM(noreg,
 374              CAST_FROM_FN_PTR(address,
 375                               InterpreterRuntime::frequency_counter_overflow),
 376              c_rarg1);
 377 
 378   __ movptr(rbx, Address(rbp, method_offset));   // restore Method*
 379   // Preserve invariant that r13/r14 contain bcp/locals of sender frame
 380   // and jump to the interpreted entry.
 381   __ jmp(do_continue, relocInfo::none);
 382 }
 383 
 384 // See if we've got enough room on the stack for locals plus overhead below
 385 // JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 386 // without going through the signal handler, i.e., reserved and yellow zones
 387 // will not be made usable. The shadow zone must suffice to handle the
 388 // overflow.
 389 // The expression stack grows down incrementally, so the normal guard
 390 // page mechanism will work for that.
 391 //
 392 // NOTE: Since the additional locals are also always pushed (wasn't
 393 // obvious in generate_fixed_frame) so the guard should work for them
 394 // too.
 395 //
 396 // Args:
 397 //      rdx: number of additional locals this frame needs (what we must check)
 398 //      rbx: Method*
 399 //
 400 // Kills:
 401 //      rax
 402 void TemplateInterpreterGenerator::generate_stack_overflow_check(void) {
 403 
 404   // monitor entry size: see picture of stack in frame_x86.hpp
 405   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 406 
 407   // total overhead size: entry_size + (saved rbp through expr stack
 408   // bottom).  be sure to change this if you add/subtract anything
 409   // to/from the overhead area
 410   const int overhead_size =
 411     -(frame::interpreter_frame_initial_sp_offset * wordSize) + entry_size;
 412 
 413   const int page_size = (int)os::vm_page_size();
 414 
 415   Label after_frame_check;
 416 
 417   // see if the frame is greater than one page in size. If so,
 418   // then we need to verify there is enough stack space remaining
 419   // for the additional locals.
 420   __ cmpl(rdx, (page_size - overhead_size) / Interpreter::stackElementSize);
 421   __ jcc(Assembler::belowEqual, after_frame_check);
 422 
 423   // compute rsp as if this were going to be the last frame on
 424   // the stack before the red zone
 425 
 426   Label after_frame_check_pop;
 427 
 428   const Address stack_limit(r15_thread, JavaThread::stack_overflow_limit_offset());
 429 
 430   // locals + overhead, in bytes
 431   __ mov(rax, rdx);
 432   __ shlptr(rax, Interpreter::logStackElementSize); // Convert parameter count to bytes.
 433   __ addptr(rax, overhead_size);
 434 
 435 #ifdef ASSERT
 436   Label limit_okay;
 437   // Verify that thread stack overflow limit is non-zero.
 438   __ cmpptr(stack_limit, NULL_WORD);
 439   __ jcc(Assembler::notEqual, limit_okay);
 440   __ stop("stack overflow limit is zero");
 441   __ bind(limit_okay);
 442 #endif
 443 
 444   // Add locals/frame size to stack limit.
 445   __ addptr(rax, stack_limit);
 446 
 447   // Check against the current stack bottom.
 448   __ cmpptr(rsp, rax);
 449 
 450   __ jcc(Assembler::above, after_frame_check_pop);
 451 
 452   // Restore sender's sp as SP. This is necessary if the sender's
 453   // frame is an extended compiled frame (see gen_c2i_adapter())
 454   // and safer anyway in case of JSR292 adaptations.
 455 
 456   __ pop(rax); // return address must be moved if SP is changed
 457   __ mov(rsp, rbcp);
 458   __ push(rax);
 459 
 460   // Note: the restored frame is not necessarily interpreted.
 461   // Use the shared runtime version of the StackOverflowError.
 462   assert(SharedRuntime::throw_StackOverflowError_entry() != nullptr, "stub not yet generated");
 463   __ jump(RuntimeAddress(SharedRuntime::throw_StackOverflowError_entry()));
 464   // all done with frame size check
 465   __ bind(after_frame_check_pop);
 466 
 467   // all done with frame size check
 468   __ bind(after_frame_check);
 469 }
 470 
 471 // Allocate monitor and lock method (asm interpreter)
 472 //
 473 // Args:
 474 //      rbx: Method*
 475 //      r14/rdi: locals
 476 //
 477 // Kills:
 478 //      rax
 479 //      c_rarg0, c_rarg1, c_rarg2, c_rarg3, ...(param regs)
 480 //      rscratch1, rscratch2 (scratch regs)
 481 void TemplateInterpreterGenerator::lock_method() {
 482   // synchronize method
 483   const Address access_flags(rbx, Method::access_flags_offset());
 484   const Address monitor_block_top(
 485         rbp,
 486         frame::interpreter_frame_monitor_block_top_offset * wordSize);
 487   const int entry_size = frame::interpreter_frame_monitor_size_in_bytes();
 488 
 489 #ifdef ASSERT
 490   {
 491     Label L;
 492     __ load_unsigned_short(rax, access_flags);
 493     __ testl(rax, JVM_ACC_SYNCHRONIZED);
 494     __ jcc(Assembler::notZero, L);
 495     __ stop("method doesn't need synchronization");
 496     __ bind(L);
 497   }
 498 #endif // ASSERT
 499 
 500   // get synchronization object
 501   {
 502     Label done;
 503     __ load_unsigned_short(rax, access_flags);
 504     __ testl(rax, JVM_ACC_STATIC);
 505     // get receiver (assume this is frequent case)
 506     __ movptr(rax, Address(rlocals, Interpreter::local_offset_in_bytes(0)));
 507     __ jcc(Assembler::zero, done);
 508     __ load_mirror(rax, rbx, rscratch2);
 509 
 510 #ifdef ASSERT
 511     {
 512       Label L;
 513       __ testptr(rax, rax);
 514       __ jcc(Assembler::notZero, L);
 515       __ stop("synchronization object is null");
 516       __ bind(L);
 517     }
 518 #endif // ASSERT
 519 
 520     __ bind(done);
 521   }
 522 
 523   // add space for monitor & lock
 524   __ subptr(rsp, entry_size); // add space for a monitor entry
 525   __ subptr(monitor_block_top, entry_size / wordSize); // set new monitor block top
 526   // store object
 527   __ movptr(Address(rsp, BasicObjectLock::obj_offset()), rax);
 528   __ movptr(c_rarg1, rsp); // object address
 529   __ lock_object(c_rarg1);
 530 }
 531 
 532 // Generate a fixed interpreter frame. This is identical setup for
 533 // interpreted methods and for native methods hence the shared code.
 534 //
 535 // Args:
 536 //      rax: return address
 537 //      rbx: Method*
 538 //      r14/rdi: pointer to locals
 539 //      r13/rsi: sender sp
 540 //      rdx: cp cache
 541 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
 542   // initialize fixed part of activation frame
 543   __ push(rax);         // save return address
 544   __ enter();           // save old & set new rbp
 545   __ push(rbcp);        // set sender sp
 546 
 547   // Resolve ConstMethod* -> ConstantPool*.
 548   // Get codebase, while we still have ConstMethod*.
 549   // Save ConstantPool* in rax for later use.
 550   __ movptr(rax, Address(rbx, Method::const_offset()));
 551   __ lea(rbcp, Address(rax, ConstMethod::codes_offset()));
 552   __ movptr(rax, Address(rax, ConstMethod::constants_offset()));
 553 
 554   __ push(NULL_WORD);  // leave last_sp as null
 555   __ push(rbx);        // save Method*
 556 
 557   // Get mirror and store it in the frame as GC root for this Method*.
 558   // rax is still ConstantPool*, resolve ConstantPool* -> InstanceKlass* -> Java mirror.
 559   __ movptr(rdx, Address(rax, ConstantPool::pool_holder_offset()));
 560   __ movptr(rdx, Address(rdx, in_bytes(Klass::java_mirror_offset())));
 561   __ resolve_oop_handle(rdx, rscratch2);
 562   __ push(rdx);
 563 
 564   if (ProfileInterpreter) {
 565     Label method_data_continue;
 566     __ movptr(rdx, Address(rbx, in_bytes(Method::method_data_offset())));
 567     __ testptr(rdx, rdx);
 568     __ jccb(Assembler::zero, method_data_continue);
 569     __ addptr(rdx, in_bytes(MethodData::data_offset()));
 570     __ bind(method_data_continue);
 571     __ push(rdx);      // set the mdp (method data pointer)
 572   } else {
 573     __ push(NULL_WORD);
 574   }
 575 
 576   // rax is still ConstantPool*, set the constant pool cache
 577   __ movptr(rdx, Address(rax, ConstantPool::cache_offset()));
 578   __ push(rdx);
 579 
 580   __ movptr(rax, rlocals);
 581   __ subptr(rax, rbp);
 582   __ shrptr(rax, Interpreter::logStackElementSize);  // rax = rlocals - fp();
 583   __ push(rax); // set relativized rlocals, see frame::interpreter_frame_locals()
 584 
 585   if (native_call) {
 586     __ push(NULL_WORD); // no bcp
 587   } else {
 588     __ push(rbcp); // set bcp
 589   }
 590   // initialize relativized pointer to expression stack bottom
 591   __ push(frame::interpreter_frame_initial_sp_offset);
 592 }
 593 
 594 // End of helpers
 595 
 596 // Method entry for java.lang.ref.Reference.get.
 597 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 598   // Code: _aload_0, _getfield, _areturn
 599   // parameter size = 1
 600   //
 601   // The code that gets generated by this routine is split into 2 parts:
 602   //    1. The "intrinsified" code performing an ON_WEAK_OOP_REF load,
 603   //    2. The slow path - which is an expansion of the regular method entry.
 604   //
 605   // Notes:-
 606   // * An intrinsic is always executed, where an ON_WEAK_OOP_REF load is performed.
 607   // * We may jump to the slow path iff the receiver is null. If the
 608   //   Reference object is null then we no longer perform an ON_WEAK_OOP_REF load
 609   //   Thus we can use the regular method entry code to generate the NPE.
 610   //
 611   // rbx: Method*
 612 
 613   // r13: senderSP must preserve for slow path, set SP to it on fast path
 614 
 615   address entry = __ pc();
 616 
 617   const int referent_offset = java_lang_ref_Reference::referent_offset();
 618 
 619   Label slow_path;
 620   // rbx: method
 621 
 622   // Check if local 0 != null
 623   // If the receiver is null then it is OK to jump to the slow path.
 624   __ movptr(rax, Address(rsp, wordSize));
 625 
 626   __ testptr(rax, rax);
 627   __ jcc(Assembler::zero, slow_path);
 628 
 629   // rax: local 0
 630   // rbx: method (but can be used as scratch now)
 631   // rdx: scratch
 632   // rdi: scratch
 633 
 634   // Load the value of the referent field.
 635   const Address field_address(rax, referent_offset);
 636   __ load_heap_oop(rax, field_address, /*tmp1*/ rbx, ON_WEAK_OOP_REF);
 637 
 638   // _areturn
 639   __ pop(rdi);                // get return address
 640   __ mov(rsp, r13);           // set sp to sender sp
 641   __ jmp(rdi);
 642   __ ret(0);
 643 
 644   // generate a vanilla interpreter entry as the slow path
 645   __ bind(slow_path);
 646   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals));
 647   return entry;
 648 }
 649 
 650 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
 651   // See more discussion in stackOverflow.hpp.
 652 
 653   // Note that we do the banging after the frame is setup, since the exception
 654   // handling code expects to find a valid interpreter frame on the stack.
 655   // Doing the banging earlier fails if the caller frame is not an interpreter
 656   // frame.
 657   // (Also, the exception throwing code expects to unlock any synchronized
 658   // method receiver, so do the banging after locking the receiver.)
 659 
 660   const int shadow_zone_size = checked_cast<int>(StackOverflow::stack_shadow_zone_size());
 661   const int page_size = (int)os::vm_page_size();
 662   const int n_shadow_pages = shadow_zone_size / page_size;
 663 
 664   const Register thread = r15_thread;
 665 
 666 #ifdef ASSERT
 667   Label L_good_limit;
 668   __ cmpptr(Address(thread, JavaThread::shadow_zone_safe_limit()), NULL_WORD);
 669   __ jcc(Assembler::notEqual, L_good_limit);
 670   __ stop("shadow zone safe limit is not initialized");
 671   __ bind(L_good_limit);
 672 
 673   Label L_good_watermark;
 674   __ cmpptr(Address(thread, JavaThread::shadow_zone_growth_watermark()), NULL_WORD);
 675   __ jcc(Assembler::notEqual, L_good_watermark);
 676   __ stop("shadow zone growth watermark is not initialized");
 677   __ bind(L_good_watermark);
 678 #endif
 679 
 680   Label L_done;
 681 
 682   __ cmpptr(rsp, Address(thread, JavaThread::shadow_zone_growth_watermark()));
 683   __ jcc(Assembler::above, L_done);
 684 
 685   for (int p = 1; p <= n_shadow_pages; p++) {
 686     __ bang_stack_with_offset(p*page_size);
 687   }
 688 
 689   // Record the new watermark, but only if update is above the safe limit.
 690   // Otherwise, the next time around the check above would pass the safe limit.
 691   __ cmpptr(rsp, Address(thread, JavaThread::shadow_zone_safe_limit()));
 692   __ jccb(Assembler::belowEqual, L_done);
 693   __ movptr(Address(thread, JavaThread::shadow_zone_growth_watermark()), rsp);
 694 
 695   __ bind(L_done);
 696 }
 697 
 698 // Interpreter stub for calling a native method. (asm interpreter)
 699 // This sets up a somewhat different looking stack for calling the
 700 // native method than the typical interpreter frame setup.
 701 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
 702   // determine code generation flags
 703   bool inc_counter  = UseCompiler || CountCompiledCalls;
 704 
 705   // rbx: Method*
 706   // rbcp: sender sp
 707 
 708   address entry_point = __ pc();
 709 
 710   const Address constMethod       (rbx, Method::const_offset());
 711   const Address access_flags      (rbx, Method::access_flags_offset());
 712   const Address size_of_parameters(rcx, ConstMethod::
 713                                         size_of_parameters_offset());
 714 
 715 
 716   // get parameter size (always needed)
 717   __ movptr(rcx, constMethod);
 718   __ load_unsigned_short(rcx, size_of_parameters);
 719 
 720   // native calls don't need the stack size check since they have no
 721   // expression stack and the arguments are already on the stack and
 722   // we only add a handful of words to the stack
 723 
 724   // rbx: Method*
 725   // rcx: size of parameters
 726   // rbcp: sender sp
 727   __ pop(rax);                                       // get return address
 728 
 729   // for natives the size of locals is zero
 730 
 731   // compute beginning of parameters
 732   __ lea(rlocals, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
 733 
 734   // add 2 zero-initialized slots for native calls
 735   // initialize result_handler slot
 736   __ push(NULL_WORD);
 737   // slot for oop temp
 738   // (static native method holder mirror/jni oop result)
 739   __ push(NULL_WORD);
 740 
 741   // initialize fixed part of activation frame
 742   generate_fixed_frame(true);
 743 
 744   // make sure method is native & not abstract
 745 #ifdef ASSERT
 746   __ load_unsigned_short(rax, access_flags);
 747   {
 748     Label L;
 749     __ testl(rax, JVM_ACC_NATIVE);
 750     __ jcc(Assembler::notZero, L);
 751     __ stop("tried to execute non-native method as native");
 752     __ bind(L);
 753   }
 754   {
 755     Label L;
 756     __ testl(rax, JVM_ACC_ABSTRACT);
 757     __ jcc(Assembler::zero, L);
 758     __ stop("tried to execute abstract method in interpreter");
 759     __ bind(L);
 760   }
 761 #endif
 762 
 763   // Since at this point in the method invocation the exception handler
 764   // would try to exit the monitor of synchronized methods which hasn't
 765   // been entered yet, we set the thread local variable
 766   // _do_not_unlock_if_synchronized to true. The remove_activation will
 767   // check this flag.
 768 
 769   const Address do_not_unlock_if_synchronized(r15_thread,
 770         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
 771   __ movbool(do_not_unlock_if_synchronized, true);
 772 
 773   // increment invocation count & check for overflow
 774   Label invocation_counter_overflow;
 775   if (inc_counter) {
 776     generate_counter_incr(&invocation_counter_overflow);
 777   }
 778 
 779   Label continue_after_compile;
 780   __ bind(continue_after_compile);
 781 
 782   bang_stack_shadow_pages(true);
 783 
 784   // reset the _do_not_unlock_if_synchronized flag
 785   __ movbool(do_not_unlock_if_synchronized, false);
 786 
 787   // check for synchronized methods
 788   // Must happen AFTER invocation_counter check and stack overflow check,
 789   // so method is not locked if overflows.
 790   if (synchronized) {
 791     lock_method();
 792   } else {
 793     // no synchronization necessary
 794 #ifdef ASSERT
 795     {
 796       Label L;
 797       __ load_unsigned_short(rax, access_flags);
 798       __ testl(rax, JVM_ACC_SYNCHRONIZED);
 799       __ jcc(Assembler::zero, L);
 800       __ stop("method needs synchronization");
 801       __ bind(L);
 802     }
 803 #endif
 804   }
 805 
 806   // start execution
 807 #ifdef ASSERT
 808   {
 809     Label L;
 810     const Address monitor_block_top(rbp,
 811                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
 812     __ movptr(rax, monitor_block_top);
 813     __ lea(rax, Address(rbp, rax, Address::times_ptr));
 814     __ cmpptr(rax, rsp);
 815     __ jcc(Assembler::equal, L);
 816     __ stop("broken stack frame setup in interpreter 5");
 817     __ bind(L);
 818   }
 819 #endif
 820 
 821   // jvmti support
 822   __ notify_method_entry();
 823 
 824   // work registers
 825   const Register method = rbx;
 826   const Register thread = r15_thread;
 827   const Register t      = r11;
 828 
 829   // allocate space for parameters
 830   __ get_method(method);
 831   __ movptr(t, Address(method, Method::const_offset()));
 832   __ load_unsigned_short(t, Address(t, ConstMethod::size_of_parameters_offset()));
 833 
 834   __ shll(t, Interpreter::logStackElementSize);
 835 
 836   __ subptr(rsp, t);
 837   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
 838   __ andptr(rsp, -16); // must be 16 byte boundary (see amd64 ABI)
 839 
 840   // get signature handler
 841   {
 842     Label L;
 843     __ movptr(t, Address(method, Method::signature_handler_offset()));
 844     __ testptr(t, t);
 845     __ jcc(Assembler::notZero, L);
 846     __ call_VM(noreg,
 847                CAST_FROM_FN_PTR(address,
 848                                 InterpreterRuntime::prepare_native_call),
 849                method);
 850     __ get_method(method);
 851     __ movptr(t, Address(method, Method::signature_handler_offset()));
 852     __ bind(L);
 853   }
 854 
 855   // call signature handler
 856   assert(InterpreterRuntime::SignatureHandlerGenerator::from() == rlocals,
 857          "adjust this code");
 858   assert(InterpreterRuntime::SignatureHandlerGenerator::to() == rsp,
 859          "adjust this code");
 860   assert(InterpreterRuntime::SignatureHandlerGenerator::temp() == rscratch1,
 861          "adjust this code");
 862 
 863   // The generated handlers do not touch RBX (the method).
 864   // However, large signatures cannot be cached and are generated
 865   // each time here.  The slow-path generator can do a GC on return,
 866   // so we must reload it after the call.
 867   __ call(t);
 868   __ get_method(method);        // slow path can do a GC, reload RBX
 869 
 870 
 871   // result handler is in rax
 872   // set result handler
 873   __ movptr(Address(rbp,
 874                     (frame::interpreter_frame_result_handler_offset) * wordSize),
 875             rax);
 876 
 877   // pass mirror handle if static call
 878   {
 879     Label L;
 880     __ load_unsigned_short(t, Address(method, Method::access_flags_offset()));
 881     __ testl(t, JVM_ACC_STATIC);
 882     __ jcc(Assembler::zero, L);
 883     // get mirror
 884     __ load_mirror(t, method, rax);
 885     // copy mirror into activation frame
 886     __ movptr(Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize),
 887             t);
 888     // pass handle to mirror
 889     __ lea(c_rarg1,
 890            Address(rbp, frame::interpreter_frame_oop_temp_offset * wordSize));
 891     __ bind(L);
 892   }
 893 
 894   // get native function entry point
 895   {
 896     Label L;
 897     __ movptr(rax, Address(method, Method::native_function_offset()));
 898     ExternalAddress unsatisfied(SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 899     __ cmpptr(rax, unsatisfied.addr(), rscratch1);
 900     __ jcc(Assembler::notEqual, L);
 901     __ call_VM(noreg,
 902                CAST_FROM_FN_PTR(address,
 903                                 InterpreterRuntime::prepare_native_call),
 904                method);
 905     __ get_method(method);
 906     __ movptr(rax, Address(method, Method::native_function_offset()));
 907     __ bind(L);
 908   }
 909 
 910   // pass JNIEnv
 911    __ lea(c_rarg0, Address(r15_thread, JavaThread::jni_environment_offset()));
 912 
 913    // It is enough that the pc() points into the right code
 914    // segment. It does not have to be the correct return pc.
 915    // For convenience we use the pc we want to resume to in
 916    // case of preemption on Object.wait.
 917    Label native_return;
 918    __ set_last_Java_frame(rsp, rbp, native_return, rscratch1);
 919 
 920   // change thread state
 921 #ifdef ASSERT
 922   {
 923     Label L;
 924     __ movl(t, Address(thread, JavaThread::thread_state_offset()));
 925     __ cmpl(t, _thread_in_Java);
 926     __ jcc(Assembler::equal, L);
 927     __ stop("Wrong thread state in native stub");
 928     __ bind(L);
 929   }
 930 #endif
 931 
 932   // Change state to native
 933 
 934   __ movl(Address(thread, JavaThread::thread_state_offset()),
 935           _thread_in_native);
 936 
 937   __ push_cont_fastpath();
 938 
 939   // Call the native method.
 940   __ call(rax);
 941   // 32: result potentially in rdx:rax or ST0
 942   // 64: result potentially in rax or xmm0
 943 
 944   __ pop_cont_fastpath();
 945 
 946   // Verify or restore cpu control state after JNI call
 947   __ restore_cpu_control_state_after_jni(rscratch1);
 948 
 949   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
 950   // in order to extract the result of a method call. If the order of these
 951   // pushes change or anything else is added to the stack then the code in
 952   // interpreter_frame_result must also change.
 953 
 954   __ push(dtos);
 955   __ push(ltos);
 956 
 957   // change thread state
 958   __ movl(Address(thread, JavaThread::thread_state_offset()),
 959           _thread_in_native_trans);
 960 
 961   // Force this write out before the read below
 962   if (!UseSystemMemoryBarrier) {
 963     __ membar(Assembler::Membar_mask_bits(
 964                 Assembler::LoadLoad | Assembler::LoadStore |
 965                 Assembler::StoreLoad | Assembler::StoreStore));
 966   }
 967 
 968   // check for safepoint operation in progress and/or pending suspend requests
 969   {
 970     Label Continue;
 971     Label slow_path;
 972 
 973     __ safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
 974 
 975     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
 976     __ jcc(Assembler::equal, Continue);
 977     __ bind(slow_path);
 978 
 979     // Don't use call_VM as it will see a possible pending exception
 980     // and forward it and never return here preventing us from
 981     // clearing _last_native_pc down below.  Also can't use
 982     // call_VM_leaf either as it will check to see if r13 & r14 are
 983     // preserved and correspond to the bcp/locals pointers. So we do a
 984     // runtime call by hand.
 985     //
 986     __ mov(c_rarg0, r15_thread);
 987     __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
 988     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
 989     __ andptr(rsp, -16); // align stack as required by ABI
 990     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
 991     __ mov(rsp, r12); // restore sp
 992     __ reinit_heapbase();
 993     __ bind(Continue);
 994   }
 995 
 996   // change thread state
 997   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
 998 
 999   // Check preemption for Object.wait()
1000   Label not_preempted;
1001   __ movptr(rscratch1, Address(r15_thread, JavaThread::preempt_alternate_return_offset()));
1002   __ cmpptr(rscratch1, NULL_WORD);
1003   __ jccb(Assembler::equal, not_preempted);
1004   __ movptr(Address(r15_thread, JavaThread::preempt_alternate_return_offset()), NULL_WORD);
1005   __ jmp(rscratch1);
1006   __ bind(native_return);
1007   __ restore_after_resume(true /* is_native */);
1008   __ bind(not_preempted);
1009 
1010   // reset_last_Java_frame
1011   __ reset_last_Java_frame(true);
1012 
1013   if (CheckJNICalls) {
1014     // clear_pending_jni_exception_check
1015     __ movptr(Address(thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
1016   }
1017 
1018   // reset handle block
1019   __ movptr(t, Address(thread, JavaThread::active_handles_offset()));
1020   __ movl(Address(t, JNIHandleBlock::top_offset()), NULL_WORD);
1021 
1022   // If result is an oop unbox and store it in frame where gc will see it
1023   // and result handler will pick it up
1024 
1025   {
1026     Label no_oop;
1027     __ lea(t, ExternalAddress(AbstractInterpreter::result_handler(T_OBJECT)));
1028     __ cmpptr(t, Address(rbp, frame::interpreter_frame_result_handler_offset*wordSize));
1029     __ jcc(Assembler::notEqual, no_oop);
1030     // retrieve result
1031     __ pop(ltos);
1032     // Unbox oop result, e.g. JNIHandles::resolve value.
1033     __ resolve_jobject(rax /* value */,
1034                        t /* tmp */);
1035     __ movptr(Address(rbp, frame::interpreter_frame_oop_temp_offset*wordSize), rax);
1036     // keep stack depth as expected by pushing oop which will eventually be discarded
1037     __ push(ltos);
1038     __ bind(no_oop);
1039   }
1040 
1041 
1042   {
1043     Label no_reguard;
1044     __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()),
1045             StackOverflow::stack_guard_yellow_reserved_disabled);
1046     __ jcc(Assembler::notEqual, no_reguard);
1047 
1048     __ pusha(); // XXX only save smashed registers
1049     __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
1050     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1051     __ andptr(rsp, -16); // align stack as required by ABI
1052     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1053     __ mov(rsp, r12); // restore sp
1054     __ popa(); // XXX only restore smashed registers
1055     __ reinit_heapbase();
1056 
1057     __ bind(no_reguard);
1058   }
1059 
1060 
1061   // The method register is junk from after the thread_in_native transition
1062   // until here.  Also can't call_VM until the bcp has been
1063   // restored.  Need bcp for throwing exception below so get it now.
1064   __ get_method(method);
1065 
1066   // restore to have legal interpreter frame, i.e., bci == 0 <=> code_base()
1067   __ movptr(rbcp, Address(method, Method::const_offset()));   // get ConstMethod*
1068   __ lea(rbcp, Address(rbcp, ConstMethod::codes_offset()));    // get codebase
1069 
1070   // handle exceptions (exception handling will handle unlocking!)
1071   {
1072     Label L;
1073     __ cmpptr(Address(thread, Thread::pending_exception_offset()), NULL_WORD);
1074     __ jcc(Assembler::zero, L);
1075     // Note: At some point we may want to unify this with the code
1076     // used in call_VM_base(); i.e., we should use the
1077     // StubRoutines::forward_exception code. For now this doesn't work
1078     // here because the rsp is not correctly set at this point.
1079     __ MacroAssembler::call_VM(noreg,
1080                                CAST_FROM_FN_PTR(address,
1081                                InterpreterRuntime::throw_pending_exception));
1082     __ should_not_reach_here();
1083     __ bind(L);
1084   }
1085 
1086   // do unlocking if necessary
1087   {
1088     Label L;
1089     __ load_unsigned_short(t, Address(method, Method::access_flags_offset()));
1090     __ testl(t, JVM_ACC_SYNCHRONIZED);
1091     __ jcc(Assembler::zero, L);
1092     // the code below should be shared with interpreter macro
1093     // assembler implementation
1094     {
1095       Label unlock;
1096       // BasicObjectLock will be first in list, since this is a
1097       // synchronized method. However, need to check that the object
1098       // has not been unlocked by an explicit monitorexit bytecode.
1099       const Address monitor(rbp,
1100                             (intptr_t)(frame::interpreter_frame_initial_sp_offset *
1101                                        wordSize - (int)sizeof(BasicObjectLock)));
1102 
1103       const Register regmon = c_rarg1;
1104 
1105       // monitor expect in c_rarg1 for slow unlock path
1106       __ lea(regmon, monitor); // address of first monitor
1107 
1108       __ movptr(t, Address(regmon, BasicObjectLock::obj_offset()));
1109       __ testptr(t, t);
1110       __ jcc(Assembler::notZero, unlock);
1111 
1112       // Entry already unlocked, need to throw exception
1113       __ MacroAssembler::call_VM(noreg,
1114                                  CAST_FROM_FN_PTR(address,
1115                    InterpreterRuntime::throw_illegal_monitor_state_exception));
1116       __ should_not_reach_here();
1117 
1118       __ bind(unlock);
1119       __ unlock_object(regmon);
1120     }
1121     __ bind(L);
1122   }
1123 
1124 #if INCLUDE_JFR
1125   __ enter_jfr_critical_section();
1126 
1127   // This poll test is to uphold the invariant that a JFR sampled frame
1128   // must not return to its caller without a prior safepoint poll check.
1129   // The earlier poll check in this routine is insufficient for this purpose
1130   // because the thread has transitioned back to Java.
1131 
1132   Label slow_path;
1133   Label fast_path;
1134   __ safepoint_poll(slow_path, true /* at_return */, false /* in_nmethod */);
1135   __ jmp(fast_path);
1136   __ bind(slow_path);
1137   __ push(dtos);
1138   __ push(ltos);
1139   __ set_last_Java_frame(noreg, rbp, (address)__ pc(), rscratch1);
1140   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), r15_thread);
1141   __ reset_last_Java_frame(true);
1142   __ pop(ltos);
1143   __ pop(dtos);
1144   __ bind(fast_path);
1145 
1146 #endif // INCLUDE_JFR
1147 
1148   // jvmti support
1149   // Note: This must happen _after_ handling/throwing any exceptions since
1150   //       the exception handler code notifies the runtime of method exits
1151   //       too. If this happens before, method entry/exit notifications are
1152   //       not properly paired (was bug - gri 11/22/99).
1153   __ notify_method_exit(vtos, InterpreterMacroAssembler::NotifyJVMTI);
1154 
1155   // restore potential result in edx:eax, call result handler to
1156   // restore potential result in ST0 & handle result
1157 
1158   __ pop(ltos);
1159   __ pop(dtos);
1160 
1161   __ movptr(t, Address(rbp,
1162                        (frame::interpreter_frame_result_handler_offset) * wordSize));
1163   __ call(t);
1164 
1165   // remove activation
1166   __ movptr(t, Address(rbp,
1167                        frame::interpreter_frame_sender_sp_offset *
1168                        wordSize)); // get sender sp
1169   __ leave();                                // remove frame anchor
1170 
1171   JFR_ONLY(__ leave_jfr_critical_section();)
1172 
1173   __ pop(rdi);                               // get return address
1174   __ mov(rsp, t);                            // set sp to sender sp
1175 
1176   __ jmp(rdi);
1177 
1178   if (inc_counter) {
1179     // Handle overflow of counter and compile method
1180     __ bind(invocation_counter_overflow);
1181     generate_counter_overflow(continue_after_compile);
1182   }
1183 
1184   return entry_point;
1185 }
1186 
1187 // Abstract method entry
1188 // Attempt to execute abstract method. Throw exception
1189 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
1190 
1191   address entry_point = __ pc();
1192 
1193   // abstract method entry
1194 
1195   //  pop return address, reset last_sp to null
1196   __ empty_expression_stack();
1197   __ restore_bcp();      // rsi must be correct for exception handler   (was destroyed)
1198   __ restore_locals();   // make sure locals pointer is correct as well (was destroyed)
1199 
1200   // throw exception
1201   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodErrorWithMethod), rbx);
1202   // the call_VM checks for exception, so we should never return here.
1203   __ should_not_reach_here();
1204 
1205   return entry_point;
1206 }
1207 
1208 //
1209 // Generic interpreted method entry to (asm) interpreter
1210 //
1211 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized, bool object_init) {
1212   // determine code generation flags
1213   bool inc_counter  = UseCompiler || CountCompiledCalls;
1214 
1215   // ebx: Method*
1216   // rbcp: sender sp (set in InterpreterMacroAssembler::prepare_to_jump_from_interpreted / generate_call_stub)
1217   address entry_point = __ pc();
1218 
1219   const Address constMethod(rbx, Method::const_offset());
1220   const Address access_flags(rbx, Method::access_flags_offset());
1221   const Address size_of_parameters(rdx,
1222                                    ConstMethod::size_of_parameters_offset());
1223   const Address size_of_locals(rdx, ConstMethod::size_of_locals_offset());
1224 
1225 
1226   // get parameter size (always needed)
1227   __ movptr(rdx, constMethod);
1228   __ load_unsigned_short(rcx, size_of_parameters);
1229 
1230   // rbx: Method*
1231   // rcx: size of parameters
1232   // rbcp: sender_sp (could differ from sp+wordSize if we were called via c2i )
1233 
1234   __ load_unsigned_short(rdx, size_of_locals); // get size of locals in words
1235   __ subl(rdx, rcx); // rdx = no. of additional locals
1236 
1237   // YYY
1238 //   __ incrementl(rdx);
1239 //   __ andl(rdx, -2);
1240 
1241   // see if we've got enough room on the stack for locals plus overhead.
1242   generate_stack_overflow_check();
1243 
1244   // get return address
1245   __ pop(rax);
1246 
1247   // compute beginning of parameters
1248   __ lea(rlocals, Address(rsp, rcx, Interpreter::stackElementScale(), -wordSize));
1249 
1250   // rdx - # of additional locals
1251   // allocate space for locals
1252   // explicitly initialize locals
1253   {
1254     Label exit, loop;
1255     __ testl(rdx, rdx);
1256     __ jccb(Assembler::lessEqual, exit); // do nothing if rdx <= 0
1257     __ bind(loop);
1258     __ push(NULL_WORD); // initialize local variables
1259     __ decrementl(rdx); // until everything initialized
1260     __ jccb(Assembler::greater, loop);
1261     __ bind(exit);
1262   }
1263 
1264   // initialize fixed part of activation frame
1265   generate_fixed_frame(false);
1266 
1267   // make sure method is not native & not abstract
1268 #ifdef ASSERT
1269   __ load_unsigned_short(rax, access_flags);
1270   {
1271     Label L;
1272     __ testl(rax, JVM_ACC_NATIVE);
1273     __ jcc(Assembler::zero, L);
1274     __ stop("tried to execute native method as non-native");
1275     __ bind(L);
1276   }
1277   {
1278     Label L;
1279     __ testl(rax, JVM_ACC_ABSTRACT);
1280     __ jcc(Assembler::zero, L);
1281     __ stop("tried to execute abstract method in interpreter");
1282     __ bind(L);
1283   }
1284 #endif
1285 
1286   // Since at this point in the method invocation the exception
1287   // handler would try to exit the monitor of synchronized methods
1288   // which hasn't been entered yet, we set the thread local variable
1289   // _do_not_unlock_if_synchronized to true. The remove_activation
1290   // will check this flag.
1291 
1292   const Address do_not_unlock_if_synchronized(r15_thread,
1293         in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()));
1294   __ movbool(do_not_unlock_if_synchronized, true);
1295 
1296   __ profile_parameters_type(rax, rcx, rdx);
1297   // increment invocation count & check for overflow
1298   Label invocation_counter_overflow;
1299   if (inc_counter) {
1300     generate_counter_incr(&invocation_counter_overflow);
1301   }
1302 
1303   Label continue_after_compile;
1304   __ bind(continue_after_compile);
1305 
1306   // check for synchronized interpreted methods
1307   bang_stack_shadow_pages(false);
1308 
1309   // reset the _do_not_unlock_if_synchronized flag
1310   __ movbool(do_not_unlock_if_synchronized, false);
1311 
1312   // check for synchronized methods
1313   // Must happen AFTER invocation_counter check and stack overflow check,
1314   // so method is not locked if overflows.
1315   if (synchronized) {
1316     // Allocate monitor and lock method
1317     lock_method();
1318   } else {
1319     // no synchronization necessary
1320 #ifdef ASSERT
1321     {
1322       Label L;
1323       __ load_unsigned_short(rax, access_flags);
1324       __ testl(rax, JVM_ACC_SYNCHRONIZED);
1325       __ jcc(Assembler::zero, L);
1326       __ stop("method needs synchronization");
1327       __ bind(L);
1328     }
1329 #endif
1330   }
1331 
1332   // If object_init == true, we should insert a StoreStore barrier here to
1333   // prevent strict fields initial default values from being observable.
1334   // However, x86 is a TSO platform, so if `this` escapes, strict fields
1335   // initialized values are guaranteed to be the ones observed, so the
1336   // barrier can be elided.
1337 
1338   // start execution
1339 #ifdef ASSERT
1340   {
1341     Label L;
1342      const Address monitor_block_top (rbp,
1343                  frame::interpreter_frame_monitor_block_top_offset * wordSize);
1344     __ movptr(rax, monitor_block_top);
1345     __ lea(rax, Address(rbp, rax, Address::times_ptr));
1346     __ cmpptr(rax, rsp);
1347     __ jcc(Assembler::equal, L);
1348     __ stop("broken stack frame setup in interpreter 6");
1349     __ bind(L);
1350   }
1351 #endif
1352 
1353   // jvmti support
1354   __ notify_method_entry();
1355 
1356   __ dispatch_next(vtos);
1357 
1358   // invocation counter overflow
1359   if (inc_counter) {
1360     // Handle overflow of counter and compile method
1361     __ bind(invocation_counter_overflow);
1362     generate_counter_overflow(continue_after_compile);
1363   }
1364 
1365   return entry_point;
1366 }
1367 
1368 //-----------------------------------------------------------------------------
1369 // Exceptions
1370 
1371 void TemplateInterpreterGenerator::generate_throw_exception() {
1372   // Entry point in previous activation (i.e., if the caller was
1373   // interpreted)
1374   Interpreter::_rethrow_exception_entry = __ pc();
1375   // Restore sp to interpreter_frame_last_sp even though we are going
1376   // to empty the expression stack for the exception processing.
1377   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1378   // rax: exception
1379   // rdx: return address/pc that threw exception
1380   __ restore_bcp();    // r13/rsi points to call/send
1381   __ restore_locals();
1382   __ reinit_heapbase();  // restore r12 as heapbase.
1383   // Entry point for exceptions thrown within interpreter code
1384   Interpreter::_throw_exception_entry = __ pc();
1385   // expression stack is undefined here
1386   // rax: exception
1387   // r13/rsi: exception bcp
1388   __ verify_oop(rax);
1389   __ mov(c_rarg1, rax);
1390 
1391   // expression stack must be empty before entering the VM in case of
1392   // an exception
1393   __ empty_expression_stack();
1394   // find exception handler address and preserve exception oop
1395   __ call_VM(rdx,
1396              CAST_FROM_FN_PTR(address,
1397                           InterpreterRuntime::exception_handler_for_exception),
1398              c_rarg1);
1399   // rax: exception handler entry point
1400   // rdx: preserved exception oop
1401   // r13/rsi: bcp for exception handler
1402   __ push_ptr(rdx); // push exception which is now the only value on the stack
1403   __ jmp(rax); // jump to exception handler (may be _remove_activation_entry!)
1404 
1405   // If the exception is not handled in the current frame the frame is
1406   // removed and the exception is rethrown (i.e. exception
1407   // continuation is _rethrow_exception).
1408   //
1409   // Note: At this point the bci is still the bxi for the instruction
1410   // which caused the exception and the expression stack is
1411   // empty. Thus, for any VM calls at this point, GC will find a legal
1412   // oop map (with empty expression stack).
1413 
1414   // In current activation
1415   // tos: exception
1416   // esi: exception bcp
1417 
1418   //
1419   // JVMTI PopFrame support
1420   //
1421 
1422   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1423   __ empty_expression_stack();
1424   __ restore_bcp(); // We could have returned from deoptimizing this frame, so restore rbcp.
1425   // Set the popframe_processing bit in pending_popframe_condition
1426   // indicating that we are currently handling popframe, so that
1427   // call_VMs that may happen later do not trigger new popframe
1428   // handling cycles.
1429   const Register thread = r15_thread;
1430   __ movl(rdx, Address(thread, JavaThread::popframe_condition_offset()));
1431   __ orl(rdx, JavaThread::popframe_processing_bit);
1432   __ movl(Address(thread, JavaThread::popframe_condition_offset()), rdx);
1433 
1434   {
1435     // Check to see whether we are returning to a deoptimized frame.
1436     // (The PopFrame call ensures that the caller of the popped frame is
1437     // either interpreted or compiled and deoptimizes it if compiled.)
1438     // In this case, we can't call dispatch_next() after the frame is
1439     // popped, but instead must save the incoming arguments and restore
1440     // them after deoptimization has occurred.
1441     //
1442     // Note that we don't compare the return PC against the
1443     // deoptimization blob's unpack entry because of the presence of
1444     // adapter frames in C2.
1445     Label caller_not_deoptimized;
1446     __ movptr(c_rarg1, Address(rbp, frame::return_addr_offset * wordSize));
1447     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1448                                InterpreterRuntime::interpreter_contains), c_rarg1);
1449     __ testl(rax, rax);
1450     __ jcc(Assembler::notZero, caller_not_deoptimized);
1451 
1452     // Compute size of arguments for saving when returning to
1453     // deoptimized caller
1454     __ get_method(rax);
1455     __ movptr(rax, Address(rax, Method::const_offset()));
1456     __ load_unsigned_short(rax, Address(rax, in_bytes(ConstMethod::
1457                                                 size_of_parameters_offset())));
1458     __ shll(rax, Interpreter::logStackElementSize);
1459     __ restore_locals();
1460     __ subptr(rlocals, rax);
1461     __ addptr(rlocals, wordSize);
1462     // Save these arguments
1463     __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1464                                            Deoptimization::
1465                                            popframe_preserve_args),
1466                           thread, rax, rlocals);
1467 
1468     __ remove_activation(vtos, rdx,
1469                          /* throw_monitor_exception */ false,
1470                          /* install_monitor_exception */ false,
1471                          /* notify_jvmdi */ false);
1472 
1473     // Inform deoptimization that it is responsible for restoring
1474     // these arguments
1475     __ movl(Address(thread, JavaThread::popframe_condition_offset()),
1476             JavaThread::popframe_force_deopt_reexecution_bit);
1477 
1478     // Continue in deoptimization handler
1479     __ jmp(rdx);
1480 
1481     __ bind(caller_not_deoptimized);
1482   }
1483 
1484   __ remove_activation(vtos, rdx, /* rdx result (retaddr) is not used */
1485                        /* throw_monitor_exception */ false,
1486                        /* install_monitor_exception */ false,
1487                        /* notify_jvmdi */ false);
1488 
1489   // Finish with popframe handling
1490   // A previous I2C followed by a deoptimization might have moved the
1491   // outgoing arguments further up the stack. PopFrame expects the
1492   // mutations to those outgoing arguments to be preserved and other
1493   // constraints basically require this frame to look exactly as
1494   // though it had previously invoked an interpreted activation with
1495   // no space between the top of the expression stack (current
1496   // last_sp) and the top of stack. Rather than force deopt to
1497   // maintain this kind of invariant all the time we call a small
1498   // fixup routine to move the mutated arguments onto the top of our
1499   // expression stack if necessary.
1500   __ mov(c_rarg1, rsp);
1501   __ movptr(c_rarg2, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1502   __ lea(c_rarg2, Address(rbp, c_rarg2, Address::times_ptr));
1503   // PC must point into interpreter here
1504   __ set_last_Java_frame(noreg, rbp, __ pc(), rscratch1);
1505   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::popframe_move_outgoing_args), r15_thread, c_rarg1, c_rarg2);
1506   __ reset_last_Java_frame(true);
1507 
1508   // Restore the last_sp and null it out
1509   __ movptr(rcx, Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize));
1510   __ lea(rsp, Address(rbp, rcx, Address::times_ptr));
1511   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
1512 
1513   __ restore_bcp();
1514   __ restore_locals();
1515   // The method data pointer was incremented already during
1516   // call profiling. We have to restore the mdp for the current bcp.
1517   if (ProfileInterpreter) {
1518     __ set_method_data_pointer_for_bcp();
1519   }
1520 
1521   // Clear the popframe condition flag
1522   __ movl(Address(thread, JavaThread::popframe_condition_offset()),
1523           JavaThread::popframe_inactive);
1524 
1525 #if INCLUDE_JVMTI
1526   {
1527     Label L_done;
1528     const Register local0 = rlocals;
1529 
1530     __ cmpb(Address(rbcp, 0), Bytecodes::_invokestatic);
1531     __ jcc(Assembler::notEqual, L_done);
1532 
1533     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1534     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
1535 
1536     __ get_method(rdx);
1537     __ movptr(rax, Address(local0, 0));
1538     __ call_VM(rax, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), rax, rdx, rbcp);
1539 
1540     __ testptr(rax, rax);
1541     __ jcc(Assembler::zero, L_done);
1542 
1543     __ movptr(Address(rbx, 0), rax);
1544     __ bind(L_done);
1545   }
1546 #endif // INCLUDE_JVMTI
1547 
1548   __ dispatch_next(vtos);
1549   // end of PopFrame support
1550 
1551   Interpreter::_remove_activation_entry = __ pc();
1552 
1553   // preserve exception over this code sequence
1554   __ pop_ptr(rax);
1555   __ movptr(Address(thread, JavaThread::vm_result_oop_offset()), rax);
1556   // remove the activation (without doing throws on illegalMonitorExceptions)
1557   __ remove_activation(vtos, rdx, false, true, false);
1558   // restore exception
1559   __ get_vm_result_oop(rax);
1560 
1561   // In between activations - previous activation type unknown yet
1562   // compute continuation point - the continuation point expects the
1563   // following registers set up:
1564   //
1565   // rax: exception
1566   // rdx: return address/pc that threw exception
1567   // rsp: expression stack of caller
1568   // rbp: ebp of caller
1569   __ push(rax);                                  // save exception
1570   __ push(rdx);                                  // save return address
1571   __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
1572                           SharedRuntime::exception_handler_for_return_address),
1573                         thread, rdx);
1574   __ mov(rbx, rax);                              // save exception handler
1575   __ pop(rdx);                                   // restore return address
1576   __ pop(rax);                                   // restore exception
1577   // Note that an "issuing PC" is actually the next PC after the call
1578   __ jmp(rbx);                                   // jump to exception
1579                                                  // handler of caller
1580 }
1581 
1582 
1583 //
1584 // JVMTI ForceEarlyReturn support
1585 //
1586 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1587   address entry = __ pc();
1588 
1589   __ restore_bcp();
1590   __ restore_locals();
1591   __ empty_expression_stack();
1592   __ load_earlyret_value(state);  // 32 bits returns value in rdx, so don't reuse
1593 
1594   __ movptr(rcx, Address(r15_thread, JavaThread::jvmti_thread_state_offset()));
1595   Address cond_addr(rcx, JvmtiThreadState::earlyret_state_offset());
1596 
1597   // Clear the earlyret state
1598   __ movl(cond_addr, JvmtiThreadState::earlyret_inactive);
1599 
1600   __ remove_activation(state, rsi,
1601                        false, /* throw_monitor_exception */
1602                        false, /* install_monitor_exception */
1603                        true); /* notify_jvmdi */
1604   __ jmp(rsi);
1605 
1606   return entry;
1607 } // end of ForceEarlyReturn support
1608 
1609 
1610 //-----------------------------------------------------------------------------
1611 // Helper for vtos entry point generation
1612 
1613 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
1614                                                          address& bep,
1615                                                          address& cep,
1616                                                          address& sep,
1617                                                          address& aep,
1618                                                          address& iep,
1619                                                          address& lep,
1620                                                          address& fep,
1621                                                          address& dep,
1622                                                          address& vep) {
1623   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1624   Label L;
1625   fep = __ pc();     // ftos entry point
1626       __ push_f(xmm0);
1627       __ jmpb(L);
1628   dep = __ pc();     // dtos entry point
1629       __ push_d(xmm0);
1630       __ jmpb(L);
1631   lep = __ pc();     // ltos entry point
1632       __ push_l();
1633       __ jmpb(L);
1634   aep = bep = cep = sep = iep = __ pc();      // [abcsi]tos entry point
1635       __ push_i_or_ptr();
1636   vep = __ pc();    // vtos entry point
1637   __ bind(L);
1638   generate_and_dispatch(t);
1639 }
1640 
1641 //-----------------------------------------------------------------------------
1642 
1643 // Non-product code
1644 #ifndef PRODUCT
1645 
1646 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1647   address entry = __ pc();
1648 
1649   __ push(state);
1650   __ push(c_rarg0);
1651   __ push(c_rarg1);
1652   __ push(c_rarg2);
1653   __ push(c_rarg3);
1654   __ mov(c_rarg2, rax);  // Pass itos
1655 #ifdef _WIN64
1656   __ movflt(xmm3, xmm0); // Pass ftos
1657 #endif
1658   __ call_VM(noreg,
1659              CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode),
1660              c_rarg1, c_rarg2, c_rarg3);
1661   __ pop(c_rarg3);
1662   __ pop(c_rarg2);
1663   __ pop(c_rarg1);
1664   __ pop(c_rarg0);
1665   __ pop(state);
1666   __ ret(0);                                   // return from result handler
1667 
1668   return entry;
1669 }
1670 
1671 void TemplateInterpreterGenerator::count_bytecode() {
1672   __ incrementq(ExternalAddress((address) &BytecodeCounter::_counter_value), rscratch1);
1673 }
1674 
1675 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1676   __ incrementl(ExternalAddress((address) &BytecodeHistogram::_counters[t->bytecode()]), rscratch1);
1677 }
1678 
1679 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1680   __ mov32(rbx, ExternalAddress((address) &BytecodePairHistogram::_index));
1681   __ shrl(rbx, BytecodePairHistogram::log2_number_of_codes);
1682   __ orl(rbx,
1683          ((int) t->bytecode()) <<
1684          BytecodePairHistogram::log2_number_of_codes);
1685   __ mov32(ExternalAddress((address) &BytecodePairHistogram::_index), rbx, rscratch1);
1686   __ lea(rscratch1, ExternalAddress((address) BytecodePairHistogram::_counters));
1687   __ incrementl(Address(rscratch1, rbx, Address::times_4));
1688 }
1689 
1690 
1691 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
1692   // Call a little run-time stub to avoid blow-up for each bytecode.
1693   // The run-time runtime saves the right registers, depending on
1694   // the tosca in-state for the given template.
1695 
1696   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
1697          "entry must have been generated");
1698   __ mov(r12, rsp); // remember sp (can only use r12 if not using call_VM)
1699   __ andptr(rsp, -16); // align stack as required by ABI
1700   __ call(RuntimeAddress(Interpreter::trace_code(t->tos_in())));
1701   __ mov(rsp, r12); // restore sp
1702   __ reinit_heapbase();
1703 }
1704 
1705 
1706 void TemplateInterpreterGenerator::stop_interpreter_at() {
1707   Label L;
1708   __ mov64(rscratch1, StopInterpreterAt);
1709   __ cmp64(rscratch1, ExternalAddress((address) &BytecodeCounter::_counter_value), rscratch2);
1710   __ jcc(Assembler::notEqual, L);
1711   __ int3();
1712   __ bind(L);
1713 }
1714 #endif // !PRODUCT