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