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