1/*
2 * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2016, 2017, SAP SE. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26#include "precompiled.hpp"
27#include "asm/macroAssembler.inline.hpp"
28#include "interpreter/abstractInterpreter.hpp"
29#include "interpreter/bytecodeHistogram.hpp"
30#include "interpreter/interpreter.hpp"
31#include "interpreter/interpreterRuntime.hpp"
32#include "interpreter/interp_masm.hpp"
33#include "interpreter/templateInterpreterGenerator.hpp"
34#include "interpreter/templateTable.hpp"
35#include "oops/arrayOop.hpp"
36#include "oops/oop.inline.hpp"
37#include "prims/jvmtiExport.hpp"
38#include "prims/jvmtiThreadState.hpp"
39#include "runtime/arguments.hpp"
40#include "runtime/deoptimization.hpp"
41#include "runtime/frame.inline.hpp"
42#include "runtime/sharedRuntime.hpp"
43#include "runtime/stubRoutines.hpp"
44#include "runtime/synchronizer.hpp"
45#include "runtime/timer.hpp"
46#include "runtime/vframeArray.hpp"
47#include "utilities/debug.hpp"
48
49
50// Size of interpreter code.  Increase if too small.  Interpreter will
51// fail with a guarantee ("not enough space for interpreter generation");
52// if too small.
53// Run with +PrintInterpreter to get the VM to print out the size.
54// Max size with JVMTI
55int TemplateInterpreter::InterpreterCodeSize = 320*K;
56
57#undef  __
58#ifdef PRODUCT
59  #define __ _masm->
60#else
61  #define __ _masm->
62//  #define __ (Verbose ? (_masm->block_comment(FILE_AND_LINE),_masm):_masm)->
63#endif
64
65#define BLOCK_COMMENT(str) __ block_comment(str)
66#define BIND(label)        __ bind(label); BLOCK_COMMENT(#label ":")
67
68#define oop_tmp_offset     _z_ijava_state_neg(oop_tmp)
69
70//-----------------------------------------------------------------------------
71
72address TemplateInterpreterGenerator::generate_slow_signature_handler() {
73  //
74  // New slow_signature handler that respects the z/Architecture
75  // C calling conventions.
76  //
77  // We get called by the native entry code with our output register
78  // area == 8. First we call InterpreterRuntime::get_result_handler
79  // to copy the pointer to the signature string temporarily to the
80  // first C-argument and to return the result_handler in
81  // Z_RET. Since native_entry will copy the jni-pointer to the
82  // first C-argument slot later on, it's OK to occupy this slot
83  // temporarily. Then we copy the argument list on the java
84  // expression stack into native varargs format on the native stack
85  // and load arguments into argument registers. Integer arguments in
86  // the varargs vector will be sign-extended to 8 bytes.
87  //
88  // On entry:
89  //   Z_ARG1  - intptr_t*       Address of java argument list in memory.
90  //   Z_state - cppInterpreter* Address of interpreter state for
91  //                               this method
92  //   Z_method
93  //
94  // On exit (just before return instruction):
95  //   Z_RET contains the address of the result_handler.
96  //   Z_ARG2 is not updated for static methods and contains "this" otherwise.
97  //   Z_ARG3-Z_ARG5 contain the first 3 arguments of types other than float and double.
98  //   Z_FARG1-Z_FARG4 contain the first 4 arguments of type float or double.
99
100  const int LogSizeOfCase = 3;
101
102  const int max_fp_register_arguments   = Argument::n_float_register_parameters;
103  const int max_int_register_arguments  = Argument::n_register_parameters - 2;  // First 2 are reserved.
104
105  const Register arg_java       = Z_tmp_2;
106  const Register arg_c          = Z_tmp_3;
107  const Register signature      = Z_R1_scratch; // Is a string.
108  const Register fpcnt          = Z_R0_scratch;
109  const Register argcnt         = Z_tmp_4;
110  const Register intSlot        = Z_tmp_1;
111  const Register sig_end        = Z_tmp_1; // Assumed end of signature (only used in do_object).
112  const Register target_sp      = Z_tmp_1;
113  const FloatRegister floatSlot = Z_F1;
114
115  const int d_signature         = _z_abi(gpr6); // Only spill space, register contents not affected.
116  const int d_fpcnt             = _z_abi(gpr7); // Only spill space, register contents not affected.
117
118  unsigned int entry_offset = __ offset();
119
120  BLOCK_COMMENT("slow_signature_handler {");
121
122  // We use target_sp for storing arguments in the C frame.
123  __ save_return_pc();
124  __ push_frame_abi160(4*BytesPerWord);                 // Reserve space to save the tmp_[1..4] registers.
125  __ z_stmg(Z_R10, Z_R13, frame::z_abi_160_size, Z_SP); // Save registers only after frame is pushed.
126
127  __ z_lgr(arg_java, Z_ARG1);
128
129  Register   method = Z_ARG2; // Directly load into correct argument register.
130
131  __ get_method(method);
132  __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_signature), Z_thread, method);
133
134  // Move signature to callee saved register.
135  // Don't directly write to stack. Frame is used by VM call.
136  __ z_lgr(Z_tmp_1, Z_RET);
137
138  // Reload method. Register may have been altered by VM call.
139  __ get_method(method);
140
141  // Get address of result handler.
142  __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_result_handler), Z_thread, method);
143
144  // Save signature address to stack.
145  __ z_stg(Z_tmp_1, d_signature, Z_SP);
146
147  // Don't overwrite return value (Z_RET, Z_ARG1) in rest of the method !
148
149  {
150    Label   isStatic;
151
152    // Test if static.
153    // We can test the bit directly.
154    // Path is Z_method->_access_flags._flags.
155    // We only support flag bits in the least significant byte (assert !).
156    // Therefore add 3 to address that byte within "_flags".
157    // Reload method. VM call above may have destroyed register contents
158    __ get_method(method);
159    __ testbit(method2_(method, access_flags), JVM_ACC_STATIC_BIT);
160    method = noreg;  // end of life
161    __ z_btrue(isStatic);
162
163    // For non-static functions, pass "this" in Z_ARG2 and copy it to 2nd C-arg slot.
164    // Need to box the Java object here, so we use arg_java
165    // (address of current Java stack slot) as argument and
166    // don't dereference it as in case of ints, floats, etc..
167    __ z_lgr(Z_ARG2, arg_java);
168    __ add2reg(arg_java, -BytesPerWord);
169    __ bind(isStatic);
170  }
171
172  // argcnt == 0 corresponds to 3rd C argument.
173  //   arg #1 (result handler) and
174  //   arg #2 (this, for non-statics), unused else
175  // are reserved and pre-filled above.
176  // arg_java points to the corresponding Java argument here. It
177  // has been decremented by one argument (this) in case of non-static.
178  __ clear_reg(argcnt, true, false);  // Don't set CC.
179  __ z_lg(target_sp, 0, Z_SP);
180  __ add2reg(arg_c, _z_abi(remaining_cargs), target_sp);
181  // No floating-point args parsed so far.
182  __ clear_mem(Address(Z_SP, d_fpcnt), 8);
183
184  NearLabel   move_intSlot_to_ARG, move_floatSlot_to_FARG;
185  NearLabel   loop_start, loop_start_restore, loop_end;
186  NearLabel   do_int, do_long, do_float, do_double;
187  NearLabel   do_dontreachhere, do_object, do_array, do_boxed;
188
189#ifdef ASSERT
190  // Signature needs to point to '(' (== 0x28) at entry.
191  __ z_lg(signature, d_signature, Z_SP);
192  __ z_cli(0, signature, (int) '(');
193  __ z_brne(do_dontreachhere);
194#endif
195
196  __ bind(loop_start_restore);
197  __ z_lg(signature, d_signature, Z_SP);  // Restore signature ptr, destroyed by move_XX_to_ARG.
198
199  BIND(loop_start);
200  // Advance to next argument type token from the signature.
201  __ add2reg(signature, 1);
202
203  // Use CLI, works well on all CPU versions.
204    __ z_cli(0, signature, (int) ')');
205    __ z_bre(loop_end);                // end of signature
206    __ z_cli(0, signature, (int) 'L');
207    __ z_bre(do_object);               // object     #9
208    __ z_cli(0, signature, (int) 'F');
209    __ z_bre(do_float);                // float      #7
210    __ z_cli(0, signature, (int) 'J');
211    __ z_bre(do_long);                 // long       #6
212    __ z_cli(0, signature, (int) 'B');
213    __ z_bre(do_int);                  // byte       #1
214    __ z_cli(0, signature, (int) 'Z');
215    __ z_bre(do_int);                  // boolean    #2
216    __ z_cli(0, signature, (int) 'C');
217    __ z_bre(do_int);                  // char       #3
218    __ z_cli(0, signature, (int) 'S');
219    __ z_bre(do_int);                  // short      #4
220    __ z_cli(0, signature, (int) 'I');
221    __ z_bre(do_int);                  // int        #5
222    __ z_cli(0, signature, (int) 'D');
223    __ z_bre(do_double);               // double     #8
224    __ z_cli(0, signature, (int) '[');
225    __ z_bre(do_array);                // array      #10
226
227  __ bind(do_dontreachhere);
228
229  __ unimplemented("ShouldNotReachHere in slow_signature_handler", 120);
230
231  // Array argument
232  BIND(do_array);
233
234  {
235    Label   start_skip, end_skip;
236
237    __ bind(start_skip);
238
239    // Advance to next type tag from signature.
240    __ add2reg(signature, 1);
241
242    // Use CLI, works well on all CPU versions.
243    __ z_cli(0, signature, (int) '[');
244    __ z_bre(start_skip);               // Skip further brackets.
245
246    __ z_cli(0, signature, (int) '9');
247    __ z_brh(end_skip);                 // no optional size
248
249    __ z_cli(0, signature, (int) '0');
250    __ z_brnl(start_skip);              // Skip optional size.
251
252    __ bind(end_skip);
253
254    __ z_cli(0, signature, (int) 'L');
255    __ z_brne(do_boxed);                // If not array of objects: go directly to do_boxed.
256  }
257
258  //  OOP argument
259  BIND(do_object);
260  // Pass by an object's type name.
261  {
262    Label   L;
263
264    __ add2reg(sig_end, 4095, signature);     // Assume object type name is shorter than 4k.
265    __ load_const_optimized(Z_R0, (int) ';'); // Type name terminator (must be in Z_R0!).
266    __ MacroAssembler::search_string(sig_end, signature);
267    __ z_brl(L);
268    __ z_illtrap();  // No semicolon found: internal error or object name too long.
269    __ bind(L);
270    __ z_lgr(signature, sig_end);
271    // fallthru to do_boxed
272  }
273
274  // Need to box the Java object here, so we use arg_java
275  // (address of current Java stack slot) as argument and
276  // don't dereference it as in case of ints, floats, etc..
277
278  // UNBOX argument
279  // Load reference and check for NULL.
280  Label  do_int_Entry4Boxed;
281  __ bind(do_boxed);
282  {
283    __ load_and_test_long(intSlot, Address(arg_java));
284    __ z_bre(do_int_Entry4Boxed);
285    __ z_lgr(intSlot, arg_java);
286    __ z_bru(do_int_Entry4Boxed);
287  }
288
289  // INT argument
290
291  // (also for byte, boolean, char, short)
292  // Use lgf for load (sign-extend) and stg for store.
293  BIND(do_int);
294  __ z_lgf(intSlot, 0, arg_java);
295
296  __ bind(do_int_Entry4Boxed);
297  __ add2reg(arg_java, -BytesPerWord);
298  // If argument fits into argument register, go and handle it, otherwise continue.
299  __ compare32_and_branch(argcnt, max_int_register_arguments,
300                          Assembler::bcondLow, move_intSlot_to_ARG);
301  __ z_stg(intSlot, 0, arg_c);
302  __ add2reg(arg_c, BytesPerWord);
303  __ z_bru(loop_start);
304
305  // LONG argument
306
307  BIND(do_long);
308  __ add2reg(arg_java, -2*BytesPerWord);  // Decrement first to have positive displacement for lg.
309  __ z_lg(intSlot, BytesPerWord, arg_java);
310  // If argument fits into argument register, go and handle it, otherwise continue.
311  __ compare32_and_branch(argcnt, max_int_register_arguments,
312                          Assembler::bcondLow, move_intSlot_to_ARG);
313  __ z_stg(intSlot, 0, arg_c);
314  __ add2reg(arg_c, BytesPerWord);
315  __ z_bru(loop_start);
316
317  // FLOAT argumen
318
319  BIND(do_float);
320  __ z_le(floatSlot, 0, arg_java);
321  __ add2reg(arg_java, -BytesPerWord);
322  assert(max_fp_register_arguments <= 255, "always true");  // safety net
323  __ z_cli(d_fpcnt+7, Z_SP, max_fp_register_arguments);
324  __ z_brl(move_floatSlot_to_FARG);
325  __ z_ste(floatSlot, 4, arg_c);
326  __ add2reg(arg_c, BytesPerWord);
327  __ z_bru(loop_start);
328
329  // DOUBLE argument
330
331  BIND(do_double);
332  __ add2reg(arg_java, -2*BytesPerWord);  // Decrement first to have positive displacement for lg.
333  __ z_ld(floatSlot, BytesPerWord, arg_java);
334  assert(max_fp_register_arguments <= 255, "always true");  // safety net
335  __ z_cli(d_fpcnt+7, Z_SP, max_fp_register_arguments);
336  __ z_brl(move_floatSlot_to_FARG);
337  __ z_std(floatSlot, 0, arg_c);
338  __ add2reg(arg_c, BytesPerWord);
339  __ z_bru(loop_start);
340
341  // Method exit, all arguments proocessed.
342  __ bind(loop_end);
343  __ z_lmg(Z_R10, Z_R13, frame::z_abi_160_size, Z_SP); // restore registers before frame is popped.
344  __ pop_frame();
345  __ restore_return_pc();
346  __ z_br(Z_R14);
347
348  // Copy int arguments.
349
350  Label  iarg_caselist;   // Distance between each case has to be a power of 2
351                          // (= 1 << LogSizeOfCase).
352  __ align(16);
353  BIND(iarg_caselist);
354  __ z_lgr(Z_ARG3, intSlot);    // 4 bytes
355  __ z_bru(loop_start_restore); // 4 bytes
356
357  __ z_lgr(Z_ARG4, intSlot);
358  __ z_bru(loop_start_restore);
359
360  __ z_lgr(Z_ARG5, intSlot);
361  __ z_bru(loop_start_restore);
362
363  __ align(16);
364  __ bind(move_intSlot_to_ARG);
365  __ z_stg(signature, d_signature, Z_SP);       // Spill since signature == Z_R1_scratch.
366  __ z_larl(Z_R1_scratch, iarg_caselist);
367  __ z_sllg(Z_R0_scratch, argcnt, LogSizeOfCase);
368  __ add2reg(argcnt, 1);
369  __ z_agr(Z_R1_scratch, Z_R0_scratch);
370  __ z_bcr(Assembler::bcondAlways, Z_R1_scratch);
371
372  // Copy float arguments.
373
374  Label  farg_caselist;   // Distance between each case has to be a power of 2
375                          // (= 1 << logSizeOfCase, padded with nop.
376  __ align(16);
377  BIND(farg_caselist);
378  __ z_ldr(Z_FARG1, floatSlot); // 2 bytes
379  __ z_bru(loop_start_restore); // 4 bytes
380  __ z_nop();                   // 2 bytes
381
382  __ z_ldr(Z_FARG2, floatSlot);
383  __ z_bru(loop_start_restore);
384  __ z_nop();
385
386  __ z_ldr(Z_FARG3, floatSlot);
387  __ z_bru(loop_start_restore);
388  __ z_nop();
389
390  __ z_ldr(Z_FARG4, floatSlot);
391  __ z_bru(loop_start_restore);
392  __ z_nop();
393
394  __ align(16);
395  __ bind(move_floatSlot_to_FARG);
396  __ z_stg(signature, d_signature, Z_SP);        // Spill since signature == Z_R1_scratch.
397  __ z_lg(Z_R0_scratch, d_fpcnt, Z_SP);          // Need old value for indexing.
398  __ add2mem_64(Address(Z_SP, d_fpcnt), 1, Z_R1_scratch); // Increment index.
399  __ z_larl(Z_R1_scratch, farg_caselist);
400  __ z_sllg(Z_R0_scratch, Z_R0_scratch, LogSizeOfCase);
401  __ z_agr(Z_R1_scratch, Z_R0_scratch);
402  __ z_bcr(Assembler::bcondAlways, Z_R1_scratch);
403
404  BLOCK_COMMENT("} slow_signature_handler");
405
406  return __ addr_at(entry_offset);
407}
408
409address TemplateInterpreterGenerator::generate_result_handler_for (BasicType type) {
410  address entry = __ pc();
411
412  assert(Z_tos == Z_RET, "Result handler: must move result!");
413  assert(Z_ftos == Z_FRET, "Result handler: must move float result!");
414
415  switch (type) {
416    case T_BOOLEAN:
417      __ c2bool(Z_tos);
418      break;
419    case T_CHAR:
420      __ and_imm(Z_tos, 0xffff);
421      break;
422    case T_BYTE:
423      __ z_lbr(Z_tos, Z_tos);
424      break;
425    case T_SHORT:
426      __ z_lhr(Z_tos, Z_tos);
427      break;
428    case T_INT:
429    case T_LONG:
430    case T_VOID:
431    case T_FLOAT:
432    case T_DOUBLE:
433      break;
434    case T_OBJECT:
435      // Retrieve result from frame...
436      __ mem2reg_opt(Z_tos, Address(Z_fp, oop_tmp_offset));
437      // and verify it.
438      __ verify_oop(Z_tos);
439      break;
440    default:
441      ShouldNotReachHere();
442  }
443  __ z_br(Z_R14);      // Return from result handler.
444  return entry;
445}
446
447// Abstract method entry.
448// Attempt to execute abstract method. Throw exception.
449address TemplateInterpreterGenerator::generate_abstract_entry(void) {
450  unsigned int entry_offset = __ offset();
451
452  // Caller could be the call_stub or a compiled method (x86 version is wrong!).
453
454  BLOCK_COMMENT("abstract_entry {");
455
456  // Implement call of InterpreterRuntime::throw_AbstractMethodError.
457  __ set_top_ijava_frame_at_SP_as_last_Java_frame(Z_SP, Z_R1);
458  __ save_return_pc();       // Save Z_R14.
459  __ push_frame_abi160(0);   // Without new frame the RT call could overwrite the saved Z_R14.
460
461  __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodError), Z_thread);
462
463  __ pop_frame();
464  __ restore_return_pc();    // Restore Z_R14.
465  __ reset_last_Java_frame();
466
467  // Restore caller sp for c2i case.
468  __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
469
470  // branch to SharedRuntime::generate_forward_exception() which handles all possible callers,
471  // i.e. call stub, compiled method, interpreted method.
472  __ load_absolute_address(Z_tmp_1, StubRoutines::forward_exception_entry());
473  __ z_br(Z_tmp_1);
474
475  BLOCK_COMMENT("} abstract_entry");
476
477  return __ addr_at(entry_offset);
478}
479
480address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
481#if INCLUDE_ALL_GCS
482  if (UseG1GC) {
483    // Inputs:
484    //  Z_ARG1 - receiver
485    //
486    // What we do:
487    //  - Load the referent field address.
488    //  - Load the value in the referent field.
489    //  - Pass that value to the pre-barrier.
490    //
491    // In the case of G1 this will record the value of the
492    // referent in an SATB buffer if marking is active.
493    // This will cause concurrent marking to mark the referent
494    // field as live.
495
496    Register  scratch1 = Z_tmp_2;
497    Register  scratch2 = Z_tmp_3;
498    Register  pre_val  = Z_RET;   // return value
499    // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
500    Register  Rargp    = Z_esp;
501
502    Label     slow_path;
503    address   entry = __ pc();
504
505    const int referent_offset = java_lang_ref_Reference::referent_offset;
506    guarantee(referent_offset > 0, "referent offset not initialized");
507
508    BLOCK_COMMENT("Reference_get {");
509
510    //  If the receiver is null then it is OK to jump to the slow path.
511    __ load_and_test_long(pre_val, Address(Rargp, Interpreter::stackElementSize)); // Get receiver.
512    __ z_bre(slow_path);
513
514    //  Load the value of the referent field.
515    __ load_heap_oop(pre_val, referent_offset, pre_val);
516
517    // Restore caller sp for c2i case.
518    __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
519
520    // Generate the G1 pre-barrier code to log the value of
521    // the referent field in an SATB buffer.
522    // Note:
523    //   With these parameters the write_barrier_pre does not
524    //   generate instructions to load the previous value.
525    __ g1_write_barrier_pre(noreg,      // obj
526                            noreg,      // offset
527                            pre_val,    // pre_val
528                            noreg,      // no new val to preserve
529                            scratch1,   // tmp
530                            scratch2,   // tmp
531                            true);      // pre_val_needed
532
533    __ z_br(Z_R14);
534
535    // Branch to previously generated regular method entry.
536    __ bind(slow_path);
537
538    address meth_entry = Interpreter::entry_for_kind(Interpreter::zerolocals);
539    __ jump_to_entry(meth_entry, Z_R1);
540
541    BLOCK_COMMENT("} Reference_get");
542
543    return entry;
544  }
545#endif // INCLUDE_ALL_GCS
546
547  return NULL;
548}
549
550address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
551  address entry = __ pc();
552
553  DEBUG_ONLY(__ verify_esp(Z_esp, Z_ARG5));
554
555  // Restore bcp under the assumption that the current frame is still
556  // interpreted.
557  __ restore_bcp();
558
559  // Expression stack must be empty before entering the VM if an
560  // exception happened.
561  __ empty_expression_stack();
562  // Throw exception.
563  __ call_VM(noreg,
564             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_StackOverflowError));
565  return entry;
566}
567
568//
569// Args:
570//   Z_ARG3: aberrant index
571//
572address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char * name) {
573  address entry = __ pc();
574  address excp = CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException);
575
576  // Expression stack must be empty before entering the VM if an
577  // exception happened.
578  __ empty_expression_stack();
579
580  // Setup parameters.
581  // Leave out the name and use register for array to create more detailed exceptions.
582  __ load_absolute_address(Z_ARG2, (address) name);
583  __ call_VM(noreg, excp, Z_ARG2, Z_ARG3);
584  return entry;
585}
586
587address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
588  address entry = __ pc();
589
590  // Object is at TOS.
591  __ pop_ptr(Z_ARG2);
592
593  // Expression stack must be empty before entering the VM if an
594  // exception happened.
595  __ empty_expression_stack();
596
597  __ call_VM(Z_ARG1,
598             CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException),
599             Z_ARG2);
600
601  DEBUG_ONLY(__ should_not_reach_here();)
602
603  return entry;
604}
605
606address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
607  assert(!pass_oop || message == NULL, "either oop or message but not both");
608  address entry = __ pc();
609
610  BLOCK_COMMENT("exception_handler_common {");
611
612  // Expression stack must be empty before entering the VM if an
613  // exception happened.
614  __ empty_expression_stack();
615  if (name != NULL) {
616    __ load_absolute_address(Z_ARG2, (address)name);
617  } else {
618    __ clear_reg(Z_ARG2, true, false);
619  }
620
621  if (pass_oop) {
622    __ call_VM(Z_tos,
623               CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception),
624               Z_ARG2, Z_tos /*object (see TT::aastore())*/);
625  } else {
626    if (message != NULL) {
627      __ load_absolute_address(Z_ARG3, (address)message);
628    } else {
629      __ clear_reg(Z_ARG3, true, false);
630    }
631    __ call_VM(Z_tos,
632               CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception),
633               Z_ARG2, Z_ARG3);
634  }
635  // Throw exception.
636  __ load_absolute_address(Z_R1_scratch, Interpreter::throw_exception_entry());
637  __ z_br(Z_R1_scratch);
638
639  BLOCK_COMMENT("} exception_handler_common");
640
641  return entry;
642}
643
644address TemplateInterpreterGenerator::generate_return_entry_for (TosState state, int step, size_t index_size) {
645  address entry = __ pc();
646
647  BLOCK_COMMENT("return_entry {");
648
649  // Pop i2c extension or revert top-2-parent-resize done by interpreted callees.
650  Register sp_before_i2c_extension = Z_bcp;
651  __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // Restore frame pointer.
652  __ z_lg(sp_before_i2c_extension, Address(Z_fp, _z_ijava_state_neg(top_frame_sp)));
653  __ resize_frame_absolute(sp_before_i2c_extension, Z_locals/*tmp*/, true/*load_fp*/);
654
655  // TODO(ZASM): necessary??
656  //  // and NULL it as marker that esp is now tos until next java call
657  //  __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD);
658
659  __ restore_bcp();
660  __ restore_locals();
661  __ restore_esp();
662
663  if (state == atos) {
664    __ profile_return_type(Z_tmp_1, Z_tos, Z_tmp_2);
665  }
666
667  Register cache  = Z_tmp_1;
668  Register size   = Z_tmp_1;
669  Register offset = Z_tmp_2;
670  const int flags_offset = in_bytes(ConstantPoolCache::base_offset() +
671                                    ConstantPoolCacheEntry::flags_offset());
672  __ get_cache_and_index_at_bcp(cache, offset, 1, index_size);
673
674  // #args is in rightmost byte of the _flags field.
675  __ z_llgc(size, Address(cache, offset, flags_offset+(sizeof(size_t)-1)));
676  __ z_sllg(size, size, Interpreter::logStackElementSize); // Each argument size in bytes.
677  __ z_agr(Z_esp, size);                                   // Pop arguments.
678
679  __ check_and_handle_popframe(Z_thread);
680  __ check_and_handle_earlyret(Z_thread);
681
682  __ dispatch_next(state, step);
683
684  BLOCK_COMMENT("} return_entry");
685
686  return entry;
687}
688
689address TemplateInterpreterGenerator::generate_deopt_entry_for (TosState state,
690                                                               int step) {
691  address entry = __ pc();
692
693  BLOCK_COMMENT("deopt_entry {");
694
695  // TODO(ZASM): necessary? NULL last_sp until next java call
696  // __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD);
697  __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // Restore frame pointer.
698  __ restore_bcp();
699  __ restore_locals();
700  __ restore_esp();
701
702  // Handle exceptions.
703  {
704    Label L;
705    __ load_and_test_long(Z_R0/*pending_exception*/, thread_(pending_exception));
706    __ z_bre(L);
707    __ call_VM(noreg,
708               CAST_FROM_FN_PTR(address,
709                                InterpreterRuntime::throw_pending_exception));
710    __ should_not_reach_here();
711    __ bind(L);
712  }
713  __ dispatch_next(state, step);
714
715  BLOCK_COMMENT("} deopt_entry");
716
717  return entry;
718}
719
720address TemplateInterpreterGenerator::generate_safept_entry_for (TosState state,
721                                                                address runtime_entry) {
722  address entry = __ pc();
723  __ push(state);
724  __ call_VM(noreg, runtime_entry);
725  __ dispatch_via(vtos, Interpreter::_normal_table.table_for (vtos));
726  return entry;
727}
728
729//
730// Helpers for commoning out cases in the various type of method entries.
731//
732
733// Increment invocation count & check for overflow.
734//
735// Note: checking for negative value instead of overflow
736// so we have a 'sticky' overflow test.
737//
738// Z_ARG2: method (see generate_fixed_frame())
739//
740void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
741  Label done;
742  Register method = Z_ARG2; // Generate_fixed_frame() copies Z_method into Z_ARG2.
743  Register m_counters = Z_ARG4;
744
745  BLOCK_COMMENT("counter_incr {");
746
747  // Note: In tiered we increment either counters in method or in MDO depending
748  // if we are profiling or not.
749  if (TieredCompilation) {
750    int increment = InvocationCounter::count_increment;
751    if (ProfileInterpreter) {
752      NearLabel no_mdo;
753      Register mdo = m_counters;
754      // Are we profiling?
755      __ load_and_test_long(mdo, method2_(method, method_data));
756      __ branch_optimized(Assembler::bcondZero, no_mdo);
757      // Increment counter in the MDO.
758      const Address mdo_invocation_counter(mdo, MethodData::invocation_counter_offset() +
759                                           InvocationCounter::counter_offset());
760      const Address mask(mdo, MethodData::invoke_mask_offset());
761      __ increment_mask_and_jump(mdo_invocation_counter, increment, mask,
762                                 Z_R1_scratch, false, Assembler::bcondZero,
763                                 overflow);
764      __ z_bru(done);
765      __ bind(no_mdo);
766    }
767
768    // Increment counter in MethodCounters.
769    const Address invocation_counter(m_counters,
770                                     MethodCounters::invocation_counter_offset() +
771                                     InvocationCounter::counter_offset());
772    // Get address of MethodCounters object.
773    __ get_method_counters(method, m_counters, done);
774    const Address mask(m_counters, MethodCounters::invoke_mask_offset());
775    __ increment_mask_and_jump(invocation_counter,
776                               increment, mask,
777                               Z_R1_scratch, false, Assembler::bcondZero,
778                               overflow);
779  } else {
780    Register counter_sum = Z_ARG3; // The result of this piece of code.
781    Register tmp         = Z_R1_scratch;
782#ifdef ASSERT
783    {
784      NearLabel ok;
785      __ get_method(tmp);
786      __ compare64_and_branch(method, tmp, Assembler::bcondEqual, ok);
787      __ z_illtrap(0x66);
788      __ bind(ok);
789    }
790#endif
791
792    // Get address of MethodCounters object.
793    __ get_method_counters(method, m_counters, done);
794    // Update standard invocation counters.
795    __ increment_invocation_counter(m_counters, counter_sum);
796    if (ProfileInterpreter) {
797      __ add2mem_32(Address(m_counters, MethodCounters::interpreter_invocation_counter_offset()), 1, tmp);
798      if (profile_method != NULL) {
799        const Address profile_limit(m_counters, MethodCounters::interpreter_profile_limit_offset());
800        __ z_cl(counter_sum, profile_limit);
801        __ branch_optimized(Assembler::bcondLow, *profile_method_continue);
802        // If no method data exists, go to profile_method.
803        __ test_method_data_pointer(tmp, *profile_method);
804      }
805    }
806
807    const Address invocation_limit(m_counters, MethodCounters::interpreter_invocation_limit_offset());
808    __ z_cl(counter_sum, invocation_limit);
809    __ branch_optimized(Assembler::bcondNotLow, *overflow);
810  }
811
812  __ bind(done);
813
814  BLOCK_COMMENT("} counter_incr");
815}
816
817void TemplateInterpreterGenerator::generate_counter_overflow(Label& do_continue) {
818  // InterpreterRuntime::frequency_counter_overflow takes two
819  // arguments, the first (thread) is passed by call_VM, the second
820  // indicates if the counter overflow occurs at a backwards branch
821  // (NULL bcp). We pass zero for it. The call returns the address
822  // of the verified entry point for the method or NULL if the
823  // compilation did not complete (either went background or bailed
824  // out).
825  __ clear_reg(Z_ARG2);
826  __ call_VM(noreg,
827             CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow),
828             Z_ARG2);
829  __ z_bru(do_continue);
830}
831
832void TemplateInterpreterGenerator::generate_stack_overflow_check(Register frame_size, Register tmp1) {
833  Register tmp2 = Z_R1_scratch;
834  const int page_size = os::vm_page_size();
835  NearLabel after_frame_check;
836
837  BLOCK_COMMENT("counter_overflow {");
838
839  assert_different_registers(frame_size, tmp1);
840
841  // Stack banging is sufficient overflow check if frame_size < page_size.
842  if (Immediate::is_uimm(page_size, 15)) {
843    __ z_chi(frame_size, page_size);
844    __ z_brl(after_frame_check);
845  } else {
846    __ load_const_optimized(tmp1, page_size);
847    __ compareU32_and_branch(frame_size, tmp1, Assembler::bcondLow, after_frame_check);
848  }
849
850  // Get the stack base, and in debug, verify it is non-zero.
851  __ z_lg(tmp1, thread_(stack_base));
852#ifdef ASSERT
853  address reentry = NULL;
854  NearLabel base_not_zero;
855  __ compareU64_and_branch(tmp1, (intptr_t)0L, Assembler::bcondNotEqual, base_not_zero);
856  reentry = __ stop_chain_static(reentry, "stack base is zero in generate_stack_overflow_check");
857  __ bind(base_not_zero);
858#endif
859
860  // Get the stack size, and in debug, verify it is non-zero.
861  assert(sizeof(size_t) == sizeof(intptr_t), "wrong load size");
862  __ z_lg(tmp2, thread_(stack_size));
863#ifdef ASSERT
864  NearLabel size_not_zero;
865  __ compareU64_and_branch(tmp2, (intptr_t)0L, Assembler::bcondNotEqual, size_not_zero);
866  reentry = __ stop_chain_static(reentry, "stack size is zero in generate_stack_overflow_check");
867  __ bind(size_not_zero);
868#endif
869
870  // Compute the beginning of the protected zone minus the requested frame size.
871  __ z_sgr(tmp1, tmp2);
872  __ add2reg(tmp1, JavaThread::stack_guard_zone_size());
873
874  // Add in the size of the frame (which is the same as subtracting it from the
875  // SP, which would take another register.
876  __ z_agr(tmp1, frame_size);
877
878  // The frame is greater than one page in size, so check against
879  // the bottom of the stack.
880  __ compareU64_and_branch(Z_SP, tmp1, Assembler::bcondHigh, after_frame_check);
881
882  // The stack will overflow, throw an exception.
883
884  // Restore SP to sender's sp. This is necessary if the sender's frame is an
885  // extended compiled frame (see gen_c2i_adapter()) and safer anyway in case of
886  // JSR292 adaptations.
887  __ resize_frame_absolute(Z_R10, tmp1, true/*load_fp*/);
888
889  // Note also that the restored frame is not necessarily interpreted.
890  // Use the shared runtime version of the StackOverflowError.
891  assert(StubRoutines::throw_StackOverflowError_entry() != NULL, "stub not yet generated");
892  AddressLiteral stub(StubRoutines::throw_StackOverflowError_entry());
893  __ load_absolute_address(tmp1, StubRoutines::throw_StackOverflowError_entry());
894  __ z_br(tmp1);
895
896  // If you get to here, then there is enough stack space.
897  __ bind(after_frame_check);
898
899  BLOCK_COMMENT("} counter_overflow");
900}
901
902// Allocate monitor and lock method (asm interpreter).
903//
904// Args:
905//   Z_locals: locals
906
907void TemplateInterpreterGenerator::lock_method(void) {
908
909  BLOCK_COMMENT("lock_method {");
910
911  // Synchronize method.
912  const Register method = Z_tmp_2;
913  __ get_method(method);
914
915#ifdef ASSERT
916  address reentry = NULL;
917  {
918    Label L;
919    __ testbit(method2_(method, access_flags), JVM_ACC_SYNCHRONIZED_BIT);
920    __ z_btrue(L);
921    reentry = __ stop_chain_static(reentry, "method doesn't need synchronization");
922    __ bind(L);
923  }
924#endif // ASSERT
925
926  // Get synchronization object.
927  const Register object = Z_tmp_2;
928
929  {
930    Label     done;
931    Label     static_method;
932
933    __ testbit(method2_(method, access_flags), JVM_ACC_STATIC_BIT);
934    __ z_btrue(static_method);
935
936    // non-static method: Load receiver obj from stack.
937    __ mem2reg_opt(object, Address(Z_locals, Interpreter::local_offset_in_bytes(0)));
938    __ z_bru(done);
939
940    __ bind(static_method);
941
942    // Lock the java mirror.
943    __ load_mirror(object, method);
944#ifdef ASSERT
945    {
946      NearLabel L;
947      __ compare64_and_branch(object, (intptr_t) 0, Assembler::bcondNotEqual, L);
948      reentry = __ stop_chain_static(reentry, "synchronization object is NULL");
949      __ bind(L);
950    }
951#endif // ASSERT
952
953    __ bind(done);
954  }
955
956  __ add_monitor_to_stack(true, Z_ARG3, Z_ARG4, Z_ARG5); // Allocate monitor elem.
957  // Store object and lock it.
958  __ get_monitors(Z_tmp_1);
959  __ reg2mem_opt(object, Address(Z_tmp_1, BasicObjectLock::obj_offset_in_bytes()));
960  __ lock_object(Z_tmp_1, object);
961
962  BLOCK_COMMENT("} lock_method");
963}
964
965// Generate a fixed interpreter frame. This is identical setup for
966// interpreted methods and for native methods hence the shared code.
967//
968// Registers alive
969//   Z_thread   - JavaThread*
970//   Z_SP       - old stack pointer
971//   Z_method   - callee's method
972//   Z_esp      - parameter list (slot 'above' last param)
973//   Z_R14      - return pc, to be stored in caller's frame
974//   Z_R10      - sender sp, note: Z_tmp_1 is Z_R10!
975//
976// Registers updated
977//   Z_SP       - new stack pointer
978//   Z_esp      - callee's operand stack pointer
979//                points to the slot above the value on top
980//   Z_locals   - used to access locals: locals[i] := *(Z_locals - i*BytesPerWord)
981//   Z_bcp      - the bytecode pointer
982//   Z_fp       - the frame pointer, thereby killing Z_method
983//   Z_ARG2     - copy of Z_method
984//
985void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call) {
986
987  //  stack layout
988  //
989  //   F1 [TOP_IJAVA_FRAME_ABI]              <-- Z_SP, Z_R10 (see note below)
990  //      [F1's operand stack (unused)]
991  //      [F1's outgoing Java arguments]     <-- Z_esp
992  //      [F1's operand stack (non args)]
993  //      [monitors]      (optional)
994  //      [IJAVA_STATE]
995  //
996  //   F2 [PARENT_IJAVA_FRAME_ABI]
997  //      ...
998  //
999  //  0x000
1000  //
1001  // Note: Z_R10, the sender sp, will be below Z_SP if F1 was extended by a c2i adapter.
1002
1003  //=============================================================================
1004  // Allocate space for locals other than the parameters, the
1005  // interpreter state, monitors, and the expression stack.
1006
1007  const Register local_count     = Z_ARG5;
1008  const Register fp              = Z_tmp_2;
1009
1010  BLOCK_COMMENT("generate_fixed_frame {");
1011
1012  {
1013  // local registers
1014  const Register top_frame_size  = Z_ARG2;
1015  const Register sp_after_resize = Z_ARG3;
1016  const Register max_stack       = Z_ARG4;
1017
1018  // local_count = method->constMethod->max_locals();
1019  __ z_lg(Z_R1_scratch, Address(Z_method, Method::const_offset()));
1020  __ z_llgh(local_count, Address(Z_R1_scratch, ConstMethod::size_of_locals_offset()));
1021
1022  if (native_call) {
1023    // If we're calling a native method, we replace max_stack (which is
1024    // zero) with space for the worst-case signature handler varargs
1025    // vector, which is:
1026    //   max_stack = max(Argument::n_register_parameters, parameter_count+2);
1027    //
1028    // We add two slots to the parameter_count, one for the jni
1029    // environment and one for a possible native mirror. We allocate
1030    // space for at least the number of ABI registers, even though
1031    // InterpreterRuntime::slow_signature_handler won't write more than
1032    // parameter_count+2 words when it creates the varargs vector at the
1033    // top of the stack. The generated slow signature handler will just
1034    // load trash into registers beyond the necessary number. We're
1035    // still going to cut the stack back by the ABI register parameter
1036    // count so as to get SP+16 pointing at the ABI outgoing parameter
1037    // area, so we need to allocate at least that much even though we're
1038    // going to throw it away.
1039    //
1040
1041    __ z_lg(Z_R1_scratch, Address(Z_method, Method::const_offset()));
1042    __ z_llgh(max_stack,  Address(Z_R1_scratch, ConstMethod::size_of_parameters_offset()));
1043    __ add2reg(max_stack, 2);
1044
1045    NearLabel passing_args_on_stack;
1046
1047    // max_stack in bytes
1048    __ z_sllg(max_stack, max_stack, LogBytesPerWord);
1049
1050    int argument_registers_in_bytes = Argument::n_register_parameters << LogBytesPerWord;
1051    __ compare64_and_branch(max_stack, argument_registers_in_bytes, Assembler::bcondNotLow, passing_args_on_stack);
1052
1053    __ load_const_optimized(max_stack, argument_registers_in_bytes);
1054
1055    __ bind(passing_args_on_stack);
1056  } else {
1057    // !native_call
1058    __ z_lg(max_stack, method_(const));
1059
1060    // Calculate number of non-parameter locals (in slots):
1061    __ z_lg(Z_R1_scratch, Address(Z_method, Method::const_offset()));
1062    __ z_sh(local_count, Address(Z_R1_scratch, ConstMethod::size_of_parameters_offset()));
1063
1064    // max_stack = method->max_stack();
1065    __ z_llgh(max_stack, Address(max_stack, ConstMethod::max_stack_offset()));
1066    // max_stack in bytes
1067    __ z_sllg(max_stack, max_stack, LogBytesPerWord);
1068  }
1069
1070  // Resize (i.e. normally shrink) the top frame F1 ...
1071  //   F1      [TOP_IJAVA_FRAME_ABI]          <-- Z_SP, Z_R10
1072  //           F1's operand stack (free)
1073  //           ...
1074  //           F1's operand stack (free)      <-- Z_esp
1075  //           F1's outgoing Java arg m
1076  //           ...
1077  //           F1's outgoing Java arg 0
1078  //           ...
1079  //
1080  //  ... into a parent frame (Z_R10 holds F1's SP before any modification, see also above)
1081  //
1082  //           +......................+
1083  //           :                      :        <-- Z_R10, saved below as F0's z_ijava_state.sender_sp
1084  //           :                      :
1085  //   F1      [PARENT_IJAVA_FRAME_ABI]        <-- Z_SP       \
1086  //           F0's non arg local                             | = delta
1087  //           ...                                            |
1088  //           F0's non arg local              <-- Z_esp      /
1089  //           F1's outgoing Java arg m
1090  //           ...
1091  //           F1's outgoing Java arg 0
1092  //           ...
1093  //
1094  // then push the new top frame F0.
1095  //
1096  //   F0      [TOP_IJAVA_FRAME_ABI]    = frame::z_top_ijava_frame_abi_size \
1097  //           [operand stack]          = max_stack                          | = top_frame_size
1098  //           [IJAVA_STATE]            = frame::z_ijava_state_size         /
1099
1100  // sp_after_resize = Z_esp - delta
1101  //
1102  // delta = PARENT_IJAVA_FRAME_ABI + (locals_count - params_count)
1103
1104  __ add2reg(sp_after_resize, (Interpreter::stackElementSize) - (frame::z_parent_ijava_frame_abi_size), Z_esp);
1105  __ z_sllg(Z_R0_scratch, local_count, LogBytesPerWord); // Params have already been subtracted from local_count.
1106  __ z_slgr(sp_after_resize, Z_R0_scratch);
1107
1108  // top_frame_size = TOP_IJAVA_FRAME_ABI + max_stack + size of interpreter state
1109  __ add2reg(top_frame_size,
1110             frame::z_top_ijava_frame_abi_size +
1111             frame::z_ijava_state_size +
1112             frame::interpreter_frame_monitor_size() * wordSize,
1113             max_stack);
1114
1115  if (!native_call) {
1116    // Stack overflow check.
1117    // Native calls don't need the stack size check since they have no
1118    // expression stack and the arguments are already on the stack and
1119    // we only add a handful of words to the stack.
1120    Register frame_size = max_stack; // Reuse the regiser for max_stack.
1121    __ z_lgr(frame_size, Z_SP);
1122    __ z_sgr(frame_size, sp_after_resize);
1123    __ z_agr(frame_size, top_frame_size);
1124    generate_stack_overflow_check(frame_size, fp/*tmp1*/);
1125  }
1126
1127  DEBUG_ONLY(__ z_cg(Z_R14, _z_abi16(return_pc), Z_SP));
1128  __ asm_assert_eq("killed Z_R14", 0);
1129  __ resize_frame_absolute(sp_after_resize, fp, true);
1130  __ save_return_pc(Z_R14);
1131
1132  // ... and push the new frame F0.
1133  __ push_frame(top_frame_size, fp, true /*copy_sp*/, false);
1134  }
1135
1136  //=============================================================================
1137  // Initialize the new frame F0: initialize interpreter state.
1138
1139  {
1140  // locals
1141  const Register local_addr = Z_ARG4;
1142
1143  BLOCK_COMMENT("generate_fixed_frame: initialize interpreter state {");
1144
1145#ifdef ASSERT
1146  // Set the magic number (using local_addr as tmp register).
1147  __ load_const_optimized(local_addr, frame::z_istate_magic_number);
1148  __ z_stg(local_addr, _z_ijava_state_neg(magic), fp);
1149#endif
1150
1151  // Save sender SP from F1 (i.e. before it was potentially modified by an
1152  // adapter) into F0's interpreter state. We us it as well to revert
1153  // resizing the frame above.
1154  __ z_stg(Z_R10, _z_ijava_state_neg(sender_sp), fp);
1155
1156  // Load cp cache and save it at the and of this block.
1157  __ z_lg(Z_R1_scratch, Address(Z_method,    Method::const_offset()));
1158  __ z_lg(Z_R1_scratch, Address(Z_R1_scratch, ConstMethod::constants_offset()));
1159  __ z_lg(Z_R1_scratch, Address(Z_R1_scratch, ConstantPool::cache_offset_in_bytes()));
1160
1161  // z_ijava_state->method = method;
1162  __ z_stg(Z_method, _z_ijava_state_neg(method), fp);
1163
1164  // Point locals at the first argument. Method's locals are the
1165  // parameters on top of caller's expression stack.
1166  // Tos points past last Java argument.
1167
1168  __ z_lg(Z_locals, Address(Z_method, Method::const_offset()));
1169  __ z_llgh(Z_locals /*parameter_count words*/,
1170            Address(Z_locals, ConstMethod::size_of_parameters_offset()));
1171  __ z_sllg(Z_locals /*parameter_count bytes*/, Z_locals /*parameter_count*/, LogBytesPerWord);
1172  __ z_agr(Z_locals, Z_esp);
1173  // z_ijava_state->locals - i*BytesPerWord points to i-th Java local (i starts at 0)
1174  // z_ijava_state->locals = Z_esp + parameter_count bytes
1175  __ z_stg(Z_locals, _z_ijava_state_neg(locals), fp);
1176
1177  // z_ijava_state->oop_temp = NULL;
1178  __ store_const(Address(fp, oop_tmp_offset), 0);
1179
1180  // Initialize z_ijava_state->mdx.
1181  Register Rmdp = Z_bcp;
1182  // native_call: assert that mdo == NULL
1183  const bool check_for_mdo = !native_call DEBUG_ONLY(|| native_call);
1184  if (ProfileInterpreter && check_for_mdo) {
1185    Label get_continue;
1186
1187    __ load_and_test_long(Rmdp, method_(method_data));
1188    __ z_brz(get_continue);
1189    DEBUG_ONLY(if (native_call) __ stop("native methods don't have a mdo"));
1190    __ add2reg(Rmdp, in_bytes(MethodData::data_offset()));
1191    __ bind(get_continue);
1192  }
1193  __ z_stg(Rmdp, _z_ijava_state_neg(mdx), fp);
1194
1195  // Initialize z_ijava_state->bcp and Z_bcp.
1196  if (native_call) {
1197    __ clear_reg(Z_bcp); // Must initialize. Will get written into frame where GC reads it.
1198  } else {
1199    __ z_lg(Z_bcp, method_(const));
1200    __ add2reg(Z_bcp, in_bytes(ConstMethod::codes_offset()));
1201  }
1202  __ z_stg(Z_bcp, _z_ijava_state_neg(bcp), fp);
1203
1204  // no monitors and empty operand stack
1205  // => z_ijava_state->monitors points to the top slot in IJAVA_STATE.
1206  // => Z_ijava_state->esp points one slot above into the operand stack.
1207  // z_ijava_state->monitors = fp - frame::z_ijava_state_size - Interpreter::stackElementSize;
1208  // z_ijava_state->esp = Z_esp = z_ijava_state->monitors;
1209  __ add2reg(Z_esp, -frame::z_ijava_state_size, fp);
1210  __ z_stg(Z_esp, _z_ijava_state_neg(monitors), fp);
1211  __ add2reg(Z_esp, -Interpreter::stackElementSize);
1212  __ z_stg(Z_esp, _z_ijava_state_neg(esp), fp);
1213
1214  // z_ijava_state->cpoolCache = Z_R1_scratch (see load above);
1215  __ z_stg(Z_R1_scratch, _z_ijava_state_neg(cpoolCache), fp);
1216
1217  // Get mirror and store it in the frame as GC root for this Method*.
1218  __ load_mirror(Z_R1_scratch, Z_method);
1219  __ z_stg(Z_R1_scratch, _z_ijava_state_neg(mirror), fp);
1220
1221  BLOCK_COMMENT("} generate_fixed_frame: initialize interpreter state");
1222
1223  //=============================================================================
1224  if (!native_call) {
1225    // Fill locals with 0x0s.
1226    NearLabel locals_zeroed;
1227    NearLabel doXC;
1228
1229    // Local_count is already num_locals_slots - num_param_slots.
1230    __ compare64_and_branch(local_count, (intptr_t)0L, Assembler::bcondNotHigh, locals_zeroed);
1231
1232    // Advance local_addr to point behind locals (creates positive incr. in loop).
1233    __ z_lg(Z_R1_scratch, Address(Z_method, Method::const_offset()));
1234    __ z_llgh(Z_R0_scratch, Address(Z_R1_scratch, ConstMethod::size_of_locals_offset()));
1235    __ add2reg(Z_R0_scratch, -1);
1236
1237    __ z_lgr(local_addr/*locals*/, Z_locals);
1238    __ z_sllg(Z_R0_scratch, Z_R0_scratch, LogBytesPerWord);
1239    __ z_sllg(local_count, local_count, LogBytesPerWord); // Local_count are non param locals.
1240    __ z_sgr(local_addr, Z_R0_scratch);
1241
1242    if (VM_Version::has_Prefetch()) {
1243      __ z_pfd(0x02, 0, Z_R0, local_addr);
1244      __ z_pfd(0x02, 256, Z_R0, local_addr);
1245    }
1246
1247    // Can't optimise for Z10 using "compare and branch" (immediate value is too big).
1248    __ z_cghi(local_count, 256);
1249    __ z_brnh(doXC);
1250
1251    // MVCLE: Initialize if quite a lot locals.
1252    //  __ bind(doMVCLE);
1253    __ z_lgr(Z_R0_scratch, local_addr);
1254    __ z_lgr(Z_R1_scratch, local_count);
1255    __ clear_reg(Z_ARG2);        // Src len of MVCLE is zero.
1256
1257    __ MacroAssembler::move_long_ext(Z_R0_scratch, Z_ARG1, 0);
1258    __ z_bru(locals_zeroed);
1259
1260    Label  XC_template;
1261    __ bind(XC_template);
1262    __ z_xc(0, 0, local_addr, 0, local_addr);
1263
1264    __ bind(doXC);
1265    __ z_bctgr(local_count, Z_R0);                  // Get #bytes-1 for EXECUTE.
1266    if (VM_Version::has_ExecuteExtensions()) {
1267      __ z_exrl(local_count, XC_template);          // Execute XC with variable length.
1268    } else {
1269      __ z_larl(Z_R1_scratch, XC_template);
1270      __ z_ex(local_count, 0, Z_R0, Z_R1_scratch);  // Execute XC with variable length.
1271    }
1272
1273    __ bind(locals_zeroed);
1274  }
1275
1276  }
1277  // Finally set the frame pointer, destroying Z_method.
1278  assert(Z_fp == Z_method, "maybe set Z_fp earlier if other register than Z_method");
1279  // Oprofile analysis suggests to keep a copy in a register to be used by
1280  // generate_counter_incr().
1281  __ z_lgr(Z_ARG2, Z_method);
1282  __ z_lgr(Z_fp, fp);
1283
1284  BLOCK_COMMENT("} generate_fixed_frame");
1285}
1286
1287// Various method entries
1288
1289// Math function, frame manager must set up an interpreter state, etc.
1290address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
1291
1292  // Decide what to do: Use same platform specific instructions and runtime calls as compilers.
1293  bool use_instruction = false;
1294  address runtime_entry = NULL;
1295  int num_args = 1;
1296  bool double_precision = true;
1297
1298  // s390 specific:
1299  switch (kind) {
1300    case Interpreter::java_lang_math_sqrt:
1301    case Interpreter::java_lang_math_abs:  use_instruction = true; break;
1302    case Interpreter::java_lang_math_fmaF:
1303    case Interpreter::java_lang_math_fmaD: use_instruction = UseFMA; break;
1304    default: break; // Fall back to runtime call.
1305  }
1306
1307  switch (kind) {
1308    case Interpreter::java_lang_math_sin  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);   break;
1309    case Interpreter::java_lang_math_cos  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);   break;
1310    case Interpreter::java_lang_math_tan  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);   break;
1311    case Interpreter::java_lang_math_abs  : /* run interpreted */ break;
1312    case Interpreter::java_lang_math_sqrt : /* runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsqrt); not available */ break;
1313    case Interpreter::java_lang_math_log  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);   break;
1314    case Interpreter::java_lang_math_log10: runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10); break;
1315    case Interpreter::java_lang_math_pow  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dpow); num_args = 2; break;
1316    case Interpreter::java_lang_math_exp  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);   break;
1317    case Interpreter::java_lang_math_fmaF : /* run interpreted */ num_args = 3; double_precision = false; break;
1318    case Interpreter::java_lang_math_fmaD : /* run interpreted */ num_args = 3; break;
1319    default: ShouldNotReachHere();
1320  }
1321
1322  // Use normal entry if neither instruction nor runtime call is used.
1323  if (!use_instruction && runtime_entry == NULL) return NULL;
1324
1325  address entry = __ pc();
1326
1327  if (use_instruction) {
1328    switch (kind) {
1329      case Interpreter::java_lang_math_sqrt:
1330        // Can use memory operand directly.
1331        __ z_sqdb(Z_FRET, Interpreter::stackElementSize, Z_esp);
1332        break;
1333      case Interpreter::java_lang_math_abs:
1334        // Load operand from stack.
1335        __ mem2freg_opt(Z_FRET, Address(Z_esp, Interpreter::stackElementSize));
1336        __ z_lpdbr(Z_FRET);
1337        break;
1338      case Interpreter::java_lang_math_fmaF:
1339        __ mem2freg_opt(Z_FRET,  Address(Z_esp,     Interpreter::stackElementSize)); // result reg = arg3
1340        __ mem2freg_opt(Z_FARG2, Address(Z_esp, 3 * Interpreter::stackElementSize)); // arg1
1341        __ z_maeb(Z_FRET, Z_FARG2, Address(Z_esp, 2 * Interpreter::stackElementSize));
1342        break;
1343      case Interpreter::java_lang_math_fmaD:
1344        __ mem2freg_opt(Z_FRET,  Address(Z_esp,     Interpreter::stackElementSize)); // result reg = arg3
1345        __ mem2freg_opt(Z_FARG2, Address(Z_esp, 5 * Interpreter::stackElementSize)); // arg1
1346        __ z_madb(Z_FRET, Z_FARG2, Address(Z_esp, 3 * Interpreter::stackElementSize));
1347        break;
1348      default: ShouldNotReachHere();
1349    }
1350  } else {
1351    // Load arguments
1352    assert(num_args <= 4, "passed in registers");
1353    if (double_precision) {
1354      int offset = (2 * num_args - 1) * Interpreter::stackElementSize;
1355      for (int i = 0; i < num_args; ++i) {
1356        __ mem2freg_opt(as_FloatRegister(Z_FARG1->encoding() + 2 * i), Address(Z_esp, offset));
1357        offset -= 2 * Interpreter::stackElementSize;
1358      }
1359    } else {
1360      int offset = num_args * Interpreter::stackElementSize;
1361      for (int i = 0; i < num_args; ++i) {
1362        __ mem2freg_opt(as_FloatRegister(Z_FARG1->encoding() + 2 * i), Address(Z_esp, offset));
1363        offset -= Interpreter::stackElementSize;
1364      }
1365    }
1366    // Call runtime
1367    __ save_return_pc();       // Save Z_R14.
1368    __ push_frame_abi160(0);   // Without new frame the RT call could overwrite the saved Z_R14.
1369
1370    __ call_VM_leaf(runtime_entry);
1371
1372    __ pop_frame();
1373    __ restore_return_pc();    // Restore Z_R14.
1374  }
1375
1376  // Pop c2i arguments (if any) off when we return.
1377  __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
1378
1379  __ z_br(Z_R14);
1380
1381  return entry;
1382}
1383
1384// Interpreter stub for calling a native method. (asm interpreter).
1385// This sets up a somewhat different looking stack for calling the
1386// native method than the typical interpreter frame setup.
1387address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
1388  // Determine code generation flags.
1389  bool inc_counter = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1390
1391  // Interpreter entry for ordinary Java methods.
1392  //
1393  // Registers alive
1394  //   Z_SP          - stack pointer
1395  //   Z_thread      - JavaThread*
1396  //   Z_method      - callee's method (method to be invoked)
1397  //   Z_esp         - operand (or expression) stack pointer of caller. one slot above last arg.
1398  //   Z_R10         - sender sp (before modifications, e.g. by c2i adapter
1399  //                   and as well by generate_fixed_frame below)
1400  //   Z_R14         - return address to caller (call_stub or c2i_adapter)
1401  //
1402  // Registers updated
1403  //   Z_SP          - stack pointer
1404  //   Z_fp          - callee's framepointer
1405  //   Z_esp         - callee's operand stack pointer
1406  //                   points to the slot above the value on top
1407  //   Z_locals      - used to access locals: locals[i] := *(Z_locals - i*BytesPerWord)
1408  //   Z_tos         - integer result, if any
1409  //   z_ftos        - floating point result, if any
1410  //
1411  // Stack layout at this point:
1412  //
1413  //   F1      [TOP_IJAVA_FRAME_ABI]         <-- Z_SP, Z_R10 (Z_R10 will be below Z_SP if
1414  //                                                          frame was extended by c2i adapter)
1415  //           [outgoing Java arguments]     <-- Z_esp
1416  //           ...
1417  //   PARENT  [PARENT_IJAVA_FRAME_ABI]
1418  //           ...
1419  //
1420
1421  address entry_point = __ pc();
1422
1423  // Make sure registers are different!
1424  assert_different_registers(Z_thread, Z_method, Z_esp);
1425
1426  BLOCK_COMMENT("native_entry {");
1427
1428  // Make sure method is native and not abstract.
1429#ifdef ASSERT
1430  address reentry = NULL;
1431  { Label L;
1432    __ testbit(method_(access_flags), JVM_ACC_NATIVE_BIT);
1433    __ z_btrue(L);
1434    reentry = __ stop_chain_static(reentry, "tried to execute non-native method as native");
1435    __ bind(L);
1436  }
1437  { Label L;
1438    __ testbit(method_(access_flags), JVM_ACC_ABSTRACT_BIT);
1439    __ z_bfalse(L);
1440    reentry = __ stop_chain_static(reentry, "tried to execute abstract method as non-abstract");
1441    __ bind(L);
1442  }
1443#endif // ASSERT
1444
1445#ifdef ASSERT
1446  // Save the return PC into the callers frame for assertion in generate_fixed_frame.
1447  __ save_return_pc(Z_R14);
1448#endif
1449
1450  // Generate the code to allocate the interpreter stack frame.
1451  generate_fixed_frame(true);
1452
1453  const Address do_not_unlock_if_synchronized(Z_thread, JavaThread::do_not_unlock_if_synchronized_offset());
1454  // Since at this point in the method invocation the exception handler
1455  // would try to exit the monitor of synchronized methods which hasn't
1456  // been entered yet, we set the thread local variable
1457  // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1458  // runtime, exception handling i.e. unlock_if_synchronized_method will
1459  // check this thread local flag.
1460  __ z_mvi(do_not_unlock_if_synchronized, true);
1461
1462  // Increment invocation count and check for overflow.
1463  NearLabel invocation_counter_overflow;
1464  if (inc_counter) {
1465    generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
1466  }
1467
1468  Label continue_after_compile;
1469  __ bind(continue_after_compile);
1470
1471  bang_stack_shadow_pages(true);
1472
1473  // Reset the _do_not_unlock_if_synchronized flag.
1474  __ z_mvi(do_not_unlock_if_synchronized, false);
1475
1476  // Check for synchronized methods.
1477  // This mst happen AFTER invocation_counter check and stack overflow check,
1478  // so method is not locked if overflows.
1479  if (synchronized) {
1480    lock_method();
1481  } else {
1482    // No synchronization necessary.
1483#ifdef ASSERT
1484    { Label L;
1485      __ get_method(Z_R1_scratch);
1486      __ testbit(method2_(Z_R1_scratch, access_flags), JVM_ACC_SYNCHRONIZED_BIT);
1487      __ z_bfalse(L);
1488      reentry = __ stop_chain_static(reentry, "method needs synchronization");
1489      __ bind(L);
1490    }
1491#endif // ASSERT
1492  }
1493
1494  // start execution
1495
1496  // jvmti support
1497  __ notify_method_entry();
1498
1499  //=============================================================================
1500  // Get and call the signature handler.
1501  const Register Rmethod                 = Z_tmp_2;
1502  const Register signature_handler_entry = Z_tmp_1;
1503  const Register Rresult_handler         = Z_tmp_3;
1504  Label call_signature_handler;
1505
1506  assert_different_registers(Z_fp, Rmethod, signature_handler_entry, Rresult_handler);
1507  assert(Rresult_handler->is_nonvolatile(), "Rresult_handler must be in a non-volatile register");
1508
1509  // Reload method.
1510  __ get_method(Rmethod);
1511
1512  // Check for signature handler.
1513  __ load_and_test_long(signature_handler_entry, method2_(Rmethod, signature_handler));
1514  __ z_brne(call_signature_handler);
1515
1516  // Method has never been called. Either generate a specialized
1517  // handler or point to the slow one.
1518  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call),
1519             Rmethod);
1520
1521  // Reload method.
1522  __ get_method(Rmethod);
1523
1524  // Reload signature handler, it must have been created/assigned in the meantime.
1525  __ z_lg(signature_handler_entry, method2_(Rmethod, signature_handler));
1526
1527  __ bind(call_signature_handler);
1528
1529  // We have a TOP_IJAVA_FRAME here, which belongs to us.
1530  __ set_top_ijava_frame_at_SP_as_last_Java_frame(Z_SP, Z_R1/*tmp*/);
1531
1532  // Call signature handler and pass locals address in Z_ARG1.
1533  __ z_lgr(Z_ARG1, Z_locals);
1534  __ call_stub(signature_handler_entry);
1535  // Save result handler returned by signature handler.
1536  __ z_lgr(Rresult_handler, Z_RET);
1537
1538  // Reload method (the slow signature handler may block for GC).
1539  __ get_method(Rmethod);
1540
1541  // Pass mirror handle if static call.
1542  {
1543    Label method_is_not_static;
1544    __ testbit(method2_(Rmethod, access_flags), JVM_ACC_STATIC_BIT);
1545    __ z_bfalse(method_is_not_static);
1546    // Get mirror.
1547    __ load_mirror(Z_R1, Rmethod);
1548    // z_ijava_state.oop_temp = pool_holder->klass_part()->java_mirror();
1549    __ z_stg(Z_R1, oop_tmp_offset, Z_fp);
1550    // Pass handle to mirror as 2nd argument to JNI method.
1551    __ add2reg(Z_ARG2, oop_tmp_offset, Z_fp);
1552    __ bind(method_is_not_static);
1553  }
1554
1555  // Pass JNIEnv address as first parameter.
1556  __ add2reg(Z_ARG1, in_bytes(JavaThread::jni_environment_offset()), Z_thread);
1557
1558  // Note: last java frame has been set above already. The pc from there
1559  // is precise enough.
1560
1561  // Get native function entry point before we change the thread state.
1562  __ z_lg(Z_R1/*native_method_entry*/, method2_(Rmethod, native_function));
1563
1564  //=============================================================================
1565  // Transition from _thread_in_Java to _thread_in_native. As soon as
1566  // we make this change the safepoint code needs to be certain that
1567  // the last Java frame we established is good. The pc in that frame
1568  // just need to be near here not an actual return address.
1569#ifdef ASSERT
1570  {
1571    NearLabel L;
1572    __ mem2reg_opt(Z_R14, Address(Z_thread, JavaThread::thread_state_offset()), false /*32 bits*/);
1573    __ compareU32_and_branch(Z_R14, _thread_in_Java, Assembler::bcondEqual, L);
1574    reentry = __ stop_chain_static(reentry, "Wrong thread state in native stub");
1575    __ bind(L);
1576  }
1577#endif
1578
1579  // Memory ordering: Z does not reorder store/load with subsequent load. That's strong enough.
1580  __ set_thread_state(_thread_in_native);
1581
1582  //=============================================================================
1583  // Call the native method. Argument registers must not have been
1584  // overwritten since "__ call_stub(signature_handler);" (except for
1585  // ARG1 and ARG2 for static methods).
1586
1587  __ call_c(Z_R1/*native_method_entry*/);
1588
1589  // NOTE: frame::interpreter_frame_result() depends on these stores.
1590  __ z_stg(Z_RET, _z_ijava_state_neg(lresult), Z_fp);
1591  __ freg2mem_opt(Z_FRET, Address(Z_fp, _z_ijava_state_neg(fresult)));
1592  const Register Rlresult = signature_handler_entry;
1593  assert(Rlresult->is_nonvolatile(), "Rlresult must be in a non-volatile register");
1594  __ z_lgr(Rlresult, Z_RET);
1595
1596  // Z_method may no longer be valid, because of GC.
1597
1598  // Block, if necessary, before resuming in _thread_in_Java state.
1599  // In order for GC to work, don't clear the last_Java_sp until after
1600  // blocking.
1601
1602  //=============================================================================
1603  // Switch thread to "native transition" state before reading the
1604  // synchronization state. This additional state is necessary
1605  // because reading and testing the synchronization state is not
1606  // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
1607  // in _thread_in_native state, loads _not_synchronized and is
1608  // preempted. VM thread changes sync state to synchronizing and
1609  // suspends threads for GC. Thread A is resumed to finish this
1610  // native method, but doesn't block here since it didn't see any
1611  // synchronization is progress, and escapes.
1612
1613  __ set_thread_state(_thread_in_native_trans);
1614  if (UseMembar) {
1615    __ z_fence();
1616  } else {
1617    // Write serialization page so VM thread can do a pseudo remote
1618    // membar. We use the current thread pointer to calculate a thread
1619    // specific offset to write to within the page. This minimizes bus
1620    // traffic due to cache line collision.
1621    __ serialize_memory(Z_thread, Z_R1, Z_R0);
1622  }
1623  // Now before we return to java we must look for a current safepoint
1624  // (a new safepoint can not start since we entered native_trans).
1625  // We must check here because a current safepoint could be modifying
1626  // the callers registers right this moment.
1627
1628  // Check for safepoint operation in progress and/or pending suspend requests.
1629  {
1630    Label Continue, do_safepoint;
1631    __ generate_safepoint_check(do_safepoint, Z_R1, true);
1632    // Check for suspend.
1633    __ load_and_test_int(Z_R0/*suspend_flags*/, thread_(suspend_flags));
1634    __ z_bre(Continue); // 0 -> no flag set -> not suspended
1635    __ bind(do_safepoint);
1636    __ z_lgr(Z_ARG1, Z_thread);
1637    __ call_c(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans));
1638    __ bind(Continue);
1639  }
1640
1641  //=============================================================================
1642  // Back in Interpreter Frame.
1643
1644  // We are in thread_in_native_trans here and back in the normal
1645  // interpreter frame. We don't have to do anything special about
1646  // safepoints and we can switch to Java mode anytime we are ready.
1647
1648  // Note: frame::interpreter_frame_result has a dependency on how the
1649  // method result is saved across the call to post_method_exit. For
1650  // native methods it assumes that the non-FPU/non-void result is
1651  // saved in z_ijava_state.lresult and a FPU result in z_ijava_state.fresult. If
1652  // this changes then the interpreter_frame_result implementation
1653  // will need to be updated too.
1654
1655  //=============================================================================
1656  // Back in Java.
1657
1658  // Memory ordering: Z does not reorder store/load with subsequent
1659  // load. That's strong enough.
1660  __ set_thread_state(_thread_in_Java);
1661
1662  __ reset_last_Java_frame();
1663
1664  // We reset the JNI handle block only after unboxing the result; see below.
1665
1666  // The method register is junk from after the thread_in_native transition
1667  // until here. Also can't call_VM until the bcp has been
1668  // restored. Need bcp for throwing exception below so get it now.
1669  __ get_method(Rmethod);
1670
1671  // Restore Z_bcp to have legal interpreter frame,
1672  // i.e., bci == 0 <=> Z_bcp == code_base().
1673  __ z_lg(Z_bcp, Address(Rmethod, Method::const_offset())); // get constMethod
1674  __ add2reg(Z_bcp, in_bytes(ConstMethod::codes_offset())); // get codebase
1675
1676  if (CheckJNICalls) {
1677    // clear_pending_jni_exception_check
1678    __ clear_mem(Address(Z_thread, JavaThread::pending_jni_exception_check_fn_offset()), sizeof(oop));
1679  }
1680
1681  // Check if the native method returns an oop, and if so, move it
1682  // from the jni handle to z_ijava_state.oop_temp. This is
1683  // necessary, because we reset the jni handle block below.
1684  // NOTE: frame::interpreter_frame_result() depends on this, too.
1685  { NearLabel no_oop_result;
1686  __ load_absolute_address(Z_R1, AbstractInterpreter::result_handler(T_OBJECT));
1687  __ compareU64_and_branch(Z_R1, Rresult_handler, Assembler::bcondNotEqual, no_oop_result);
1688  __ resolve_jobject(Rlresult, /* tmp1 */ Rmethod, /* tmp2 */ Z_R1);
1689  __ z_stg(Rlresult, oop_tmp_offset, Z_fp);
1690  __ bind(no_oop_result);
1691  }
1692
1693  // Reset handle block.
1694  __ z_lg(Z_R1/*active_handles*/, thread_(active_handles));
1695  __ clear_mem(Address(Z_R1, JNIHandleBlock::top_offset_in_bytes()), 4);
1696
1697  // Bandle exceptions (exception handling will handle unlocking!).
1698  {
1699    Label L;
1700    __ load_and_test_long(Z_R0/*pending_exception*/, thread_(pending_exception));
1701    __ z_bre(L);
1702    __ MacroAssembler::call_VM(noreg,
1703                               CAST_FROM_FN_PTR(address,
1704                               InterpreterRuntime::throw_pending_exception));
1705    __ should_not_reach_here();
1706    __ bind(L);
1707  }
1708
1709  if (synchronized) {
1710    Register Rfirst_monitor = Z_ARG2;
1711    __ add2reg(Rfirst_monitor, -(frame::z_ijava_state_size + (int)sizeof(BasicObjectLock)), Z_fp);
1712#ifdef ASSERT
1713    NearLabel ok;
1714    __ z_lg(Z_R1, _z_ijava_state_neg(monitors), Z_fp);
1715    __ compareU64_and_branch(Rfirst_monitor, Z_R1, Assembler::bcondEqual, ok);
1716    reentry = __ stop_chain_static(reentry, "native_entry:unlock: inconsistent z_ijava_state.monitors");
1717    __ bind(ok);
1718#endif
1719    __ unlock_object(Rfirst_monitor);
1720  }
1721
1722  // JVMTI support. Result has already been saved above to the frame.
1723  __ notify_method_exit(true/*native_method*/, ilgl, InterpreterMacroAssembler::NotifyJVMTI);
1724
1725  // Move native method result back into proper registers and return.
1726  // C++ interpreter does not use result handler. So do we need to here? TODO(ZASM): check if correct.
1727  { NearLabel no_oop_or_null;
1728  __ mem2freg_opt(Z_FRET, Address(Z_fp, _z_ijava_state_neg(fresult)));
1729  __ load_and_test_long(Z_RET, Address(Z_fp, _z_ijava_state_neg(lresult)));
1730  __ z_bre(no_oop_or_null); // No unboxing if the result is NULL.
1731  __ load_absolute_address(Z_R1, AbstractInterpreter::result_handler(T_OBJECT));
1732  __ compareU64_and_branch(Z_R1, Rresult_handler, Assembler::bcondNotEqual, no_oop_or_null);
1733  __ z_lg(Z_RET, oop_tmp_offset, Z_fp);
1734  __ verify_oop(Z_RET);
1735  __ bind(no_oop_or_null);
1736  }
1737
1738  // Pop the native method's interpreter frame.
1739  __ pop_interpreter_frame(Z_R14 /*return_pc*/, Z_ARG2/*tmp1*/, Z_ARG3/*tmp2*/);
1740
1741  // Return to caller.
1742  __ z_br(Z_R14);
1743
1744  if (inc_counter) {
1745    // Handle overflow of counter and compile method.
1746    __ bind(invocation_counter_overflow);
1747    generate_counter_overflow(continue_after_compile);
1748  }
1749
1750  BLOCK_COMMENT("} native_entry");
1751
1752  return entry_point;
1753}
1754
1755//
1756// Generic interpreted method entry to template interpreter.
1757//
1758address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1759  address entry_point = __ pc();
1760
1761  bool inc_counter = UseCompiler || CountCompiledCalls || LogTouchedMethods;
1762
1763  // Interpreter entry for ordinary Java methods.
1764  //
1765  // Registers alive
1766  //   Z_SP       - stack pointer
1767  //   Z_thread   - JavaThread*
1768  //   Z_method   - callee's method (method to be invoked)
1769  //   Z_esp      - operand (or expression) stack pointer of caller. one slot above last arg.
1770  //   Z_R10      - sender sp (before modifications, e.g. by c2i adapter
1771  //                           and as well by generate_fixed_frame below)
1772  //   Z_R14      - return address to caller (call_stub or c2i_adapter)
1773  //
1774  // Registers updated
1775  //   Z_SP       - stack pointer
1776  //   Z_fp       - callee's framepointer
1777  //   Z_esp      - callee's operand stack pointer
1778  //                points to the slot above the value on top
1779  //   Z_locals   - used to access locals: locals[i] := *(Z_locals - i*BytesPerWord)
1780  //   Z_tos      - integer result, if any
1781  //   z_ftos     - floating point result, if any
1782  //
1783  //
1784  // stack layout at this point:
1785  //
1786  //   F1      [TOP_IJAVA_FRAME_ABI]         <-- Z_SP, Z_R10 (Z_R10 will be below Z_SP if
1787  //                                                          frame was extended by c2i adapter)
1788  //           [outgoing Java arguments]     <-- Z_esp
1789  //           ...
1790  //   PARENT  [PARENT_IJAVA_FRAME_ABI]
1791  //           ...
1792  //
1793  // stack layout before dispatching the first bytecode:
1794  //
1795  //   F0      [TOP_IJAVA_FRAME_ABI]         <-- Z_SP
1796  //           [operand stack]               <-- Z_esp
1797  //           monitor (optional, can grow)
1798  //           [IJAVA_STATE]
1799  //   F1      [PARENT_IJAVA_FRAME_ABI]      <-- Z_fp (== *Z_SP)
1800  //           [F0's locals]                 <-- Z_locals
1801  //           [F1's operand stack]
1802  //           [F1's monitors] (optional)
1803  //           [IJAVA_STATE]
1804
1805  // Make sure registers are different!
1806  assert_different_registers(Z_thread, Z_method, Z_esp);
1807
1808  BLOCK_COMMENT("normal_entry {");
1809
1810  // Make sure method is not native and not abstract.
1811  // Rethink these assertions - they can be simplified and shared.
1812#ifdef ASSERT
1813  address reentry = NULL;
1814  { Label L;
1815    __ testbit(method_(access_flags), JVM_ACC_NATIVE_BIT);
1816    __ z_bfalse(L);
1817    reentry = __ stop_chain_static(reentry, "tried to execute native method as non-native");
1818    __ bind(L);
1819  }
1820  { Label L;
1821    __ testbit(method_(access_flags), JVM_ACC_ABSTRACT_BIT);
1822    __ z_bfalse(L);
1823    reentry = __ stop_chain_static(reentry, "tried to execute abstract method as non-abstract");
1824    __ bind(L);
1825  }
1826#endif // ASSERT
1827
1828#ifdef ASSERT
1829  // Save the return PC into the callers frame for assertion in generate_fixed_frame.
1830  __ save_return_pc(Z_R14);
1831#endif
1832
1833  // Generate the code to allocate the interpreter stack frame.
1834  generate_fixed_frame(false);
1835
1836  const Address do_not_unlock_if_synchronized(Z_thread, JavaThread::do_not_unlock_if_synchronized_offset());
1837  // Since at this point in the method invocation the exception handler
1838  // would try to exit the monitor of synchronized methods which hasn't
1839  // been entered yet, we set the thread local variable
1840  // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1841  // runtime, exception handling i.e. unlock_if_synchronized_method will
1842  // check this thread local flag.
1843  __ z_mvi(do_not_unlock_if_synchronized, true);
1844
1845  __ profile_parameters_type(Z_tmp_2, Z_ARG3, Z_ARG4);
1846
1847  // Increment invocation counter and check for overflow.
1848  //
1849  // Note: checking for negative value instead of overflow so we have a 'sticky'
1850  // overflow test (may be of importance as soon as we have true MT/MP).
1851  NearLabel invocation_counter_overflow;
1852  NearLabel profile_method;
1853  NearLabel profile_method_continue;
1854  NearLabel Lcontinue;
1855  if (inc_counter) {
1856    generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
1857    if (ProfileInterpreter) {
1858      __ bind(profile_method_continue);
1859    }
1860  }
1861  __ bind(Lcontinue);
1862
1863  bang_stack_shadow_pages(false);
1864
1865  // Reset the _do_not_unlock_if_synchronized flag.
1866  __ z_mvi(do_not_unlock_if_synchronized, false);
1867
1868  // Check for synchronized methods.
1869  // Must happen AFTER invocation_counter check and stack overflow check,
1870  // so method is not locked if overflows.
1871  if (synchronized) {
1872    // Allocate monitor and lock method.
1873    lock_method();
1874  } else {
1875#ifdef ASSERT
1876    { Label L;
1877      __ get_method(Z_R1_scratch);
1878      __ testbit(method2_(Z_R1_scratch, access_flags), JVM_ACC_SYNCHRONIZED_BIT);
1879      __ z_bfalse(L);
1880      reentry = __ stop_chain_static(reentry, "method needs synchronization");
1881      __ bind(L);
1882    }
1883#endif // ASSERT
1884  }
1885
1886  // start execution
1887
1888#ifdef ASSERT
1889  __ verify_esp(Z_esp, Z_R1_scratch);
1890
1891  __ verify_thread();
1892#endif
1893
1894  // jvmti support
1895  __ notify_method_entry();
1896
1897  // Start executing instructions.
1898  __ dispatch_next(vtos);
1899  // Dispatch_next does not return.
1900  DEBUG_ONLY(__ should_not_reach_here());
1901
1902  // Invocation counter overflow.
1903  if (inc_counter) {
1904    if (ProfileInterpreter) {
1905      // We have decided to profile this method in the interpreter.
1906      __ bind(profile_method);
1907
1908      __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1909      __ set_method_data_pointer_for_bcp();
1910      __ z_bru(profile_method_continue);
1911    }
1912
1913    // Handle invocation counter overflow.
1914    __ bind(invocation_counter_overflow);
1915    generate_counter_overflow(Lcontinue);
1916  }
1917
1918  BLOCK_COMMENT("} normal_entry");
1919
1920  return entry_point;
1921}
1922
1923
1924/**
1925 * Method entry for static native methods:
1926 *   int java.util.zip.CRC32.update(int crc, int b)
1927 */
1928address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
1929
1930  if (UseCRC32Intrinsics) {
1931    uint64_t entry_off = __ offset();
1932    Label    slow_path;
1933
1934    // If we need a safepoint check, generate full interpreter entry.
1935    __ generate_safepoint_check(slow_path, Z_R1, false);
1936
1937    BLOCK_COMMENT("CRC32_update {");
1938
1939    // We don't generate local frame and don't align stack because
1940    // we not even call stub code (we generate the code inline)
1941    // and there is no safepoint on this path.
1942
1943    // Load java parameters.
1944    // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1945    const Register argP    = Z_esp;
1946    const Register crc     = Z_ARG1;  // crc value
1947    const Register data    = Z_ARG2;  // address of java byte value (kernel_crc32 needs address)
1948    const Register dataLen = Z_ARG3;  // source data len (1 byte). Not used because calling the single-byte emitter.
1949    const Register table   = Z_ARG4;  // address of crc32 table
1950
1951    // Arguments are reversed on java expression stack.
1952    __ z_la(data, 3+1*wordSize, argP);  // byte value (stack address).
1953                                        // Being passed as an int, the single byte is at offset +3.
1954    __ z_llgf(crc, 2 * wordSize, argP); // Current crc state, zero extend to 64 bit to have a clean register.
1955
1956    StubRoutines::zarch::generate_load_crc_table_addr(_masm, table);
1957    __ kernel_crc32_singleByte(crc, data, dataLen, table, Z_R1, true);
1958
1959    // Restore caller sp for c2i case.
1960    __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
1961
1962    __ z_br(Z_R14);
1963
1964    BLOCK_COMMENT("} CRC32_update");
1965
1966    // Use a previously generated vanilla native entry as the slow path.
1967    BIND(slow_path);
1968    __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), Z_R1);
1969    return __ addr_at(entry_off);
1970  }
1971
1972  return NULL;
1973}
1974
1975
1976/**
1977 * Method entry for static native methods:
1978 *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
1979 *   int java.util.zip.CRC32.updateByteBuffer(int crc, long* buf, int off, int len)
1980 */
1981address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1982
1983  if (UseCRC32Intrinsics) {
1984    uint64_t entry_off = __ offset();
1985    Label    slow_path;
1986
1987    // If we need a safepoint check, generate full interpreter entry.
1988    __ generate_safepoint_check(slow_path, Z_R1, false);
1989
1990    // We don't generate local frame and don't align stack because
1991    // we call stub code and there is no safepoint on this path.
1992
1993    // Load parameters.
1994    // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1995    const Register argP    = Z_esp;
1996    const Register crc     = Z_ARG1;  // crc value
1997    const Register data    = Z_ARG2;  // address of java byte array
1998    const Register dataLen = Z_ARG3;  // source data len
1999    const Register table   = Z_ARG4;  // address of crc32 table
2000    const Register t0      = Z_R10;   // work reg for kernel* emitters
2001    const Register t1      = Z_R11;   // work reg for kernel* emitters
2002    const Register t2      = Z_R12;   // work reg for kernel* emitters
2003    const Register t3      = Z_R13;   // work reg for kernel* emitters
2004
2005    // Arguments are reversed on java expression stack.
2006    // Calculate address of start element.
2007    if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { // Used for "updateByteBuffer direct".
2008      // crc     @ (SP + 5W) (32bit)
2009      // buf     @ (SP + 3W) (64bit ptr to long array)
2010      // off     @ (SP + 2W) (32bit)
2011      // dataLen @ (SP + 1W) (32bit)
2012      // data = buf + off
2013      BLOCK_COMMENT("CRC32_updateByteBuffer {");
2014      __ z_llgf(crc,    5*wordSize, argP);  // current crc state
2015      __ z_lg(data,     3*wordSize, argP);  // start of byte buffer
2016      __ z_agf(data,    2*wordSize, argP);  // Add byte buffer offset.
2017      __ z_lgf(dataLen, 1*wordSize, argP);  // #bytes to process
2018    } else {                                                         // Used for "updateBytes update".
2019      // crc     @ (SP + 4W) (32bit)
2020      // buf     @ (SP + 3W) (64bit ptr to byte array)
2021      // off     @ (SP + 2W) (32bit)
2022      // dataLen @ (SP + 1W) (32bit)
2023      // data = buf + off + base_offset
2024      BLOCK_COMMENT("CRC32_updateBytes {");
2025      __ z_llgf(crc,    4*wordSize, argP);  // current crc state
2026      __ z_lg(data,     3*wordSize, argP);  // start of byte buffer
2027      __ z_agf(data,    2*wordSize, argP);  // Add byte buffer offset.
2028      __ z_lgf(dataLen, 1*wordSize, argP);  // #bytes to process
2029      __ z_aghi(data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
2030    }
2031
2032    StubRoutines::zarch::generate_load_crc_table_addr(_masm, table);
2033
2034    __ resize_frame(-(6*8), Z_R0, true); // Resize frame to provide add'l space to spill 5 registers.
2035    __ z_stmg(t0, t3, 1*8, Z_SP);        // Spill regs 10..13 to make them available as work registers.
2036    __ kernel_crc32_1word(crc, data, dataLen, table, t0, t1, t2, t3, true);
2037    __ z_lmg(t0, t3, 1*8, Z_SP);         // Spill regs 10..13 back from stack.
2038
2039    // Restore caller sp for c2i case.
2040    __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
2041
2042    __ z_br(Z_R14);
2043
2044    BLOCK_COMMENT("} CRC32_update{Bytes|ByteBuffer}");
2045
2046    // Use a previously generated vanilla native entry as the slow path.
2047    BIND(slow_path);
2048    __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), Z_R1);
2049    return __ addr_at(entry_off);
2050  }
2051
2052  return NULL;
2053}
2054
2055
2056/**
2057 * Method entry for intrinsic-candidate (non-native) methods:
2058 *   int java.util.zip.CRC32C.updateBytes(           int crc, byte[] b,  int off, int end)
2059 *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long* buf, int off, int end)
2060 * Unlike CRC32, CRC32C does not have any methods marked as native
2061 * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
2062 */
2063address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
2064
2065  if (UseCRC32CIntrinsics) {
2066    uint64_t entry_off = __ offset();
2067
2068    // We don't generate local frame and don't align stack because
2069    // we call stub code and there is no safepoint on this path.
2070
2071    // Load parameters.
2072    // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
2073    const Register argP    = Z_esp;
2074    const Register crc     = Z_ARG1;  // crc value
2075    const Register data    = Z_ARG2;  // address of java byte array
2076    const Register dataLen = Z_ARG3;  // source data len
2077    const Register table   = Z_ARG4;  // address of crc32 table
2078    const Register t0      = Z_R10;   // work reg for kernel* emitters
2079    const Register t1      = Z_R11;   // work reg for kernel* emitters
2080    const Register t2      = Z_R12;   // work reg for kernel* emitters
2081    const Register t3      = Z_R13;   // work reg for kernel* emitters
2082
2083    // Arguments are reversed on java expression stack.
2084    // Calculate address of start element.
2085    if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) { // Used for "updateByteBuffer direct".
2086      // crc     @ (SP + 5W) (32bit)
2087      // buf     @ (SP + 3W) (64bit ptr to long array)
2088      // off     @ (SP + 2W) (32bit)
2089      // dataLen @ (SP + 1W) (32bit)
2090      // data = buf + off
2091      BLOCK_COMMENT("CRC32C_updateDirectByteBuffer {");
2092      __ z_llgf(crc,    5*wordSize, argP);  // current crc state
2093      __ z_lg(data,     3*wordSize, argP);  // start of byte buffer
2094      __ z_agf(data,    2*wordSize, argP);  // Add byte buffer offset.
2095      __ z_lgf(dataLen, 1*wordSize, argP);  // #bytes to process, calculated as
2096      __ z_sgf(dataLen, Address(argP, 2*wordSize));  // (end_index - offset)
2097    } else {                                                                // Used for "updateBytes update".
2098      // crc     @ (SP + 4W) (32bit)
2099      // buf     @ (SP + 3W) (64bit ptr to byte array)
2100      // off     @ (SP + 2W) (32bit)
2101      // dataLen @ (SP + 1W) (32bit)
2102      // data = buf + off + base_offset
2103      BLOCK_COMMENT("CRC32C_updateBytes {");
2104      __ z_llgf(crc,    4*wordSize, argP);  // current crc state
2105      __ z_lg(data,     3*wordSize, argP);  // start of byte buffer
2106      __ z_agf(data,    2*wordSize, argP);  // Add byte buffer offset.
2107      __ z_lgf(dataLen, 1*wordSize, argP);  // #bytes to process, calculated as
2108      __ z_sgf(dataLen, Address(argP, 2*wordSize));  // (end_index - offset)
2109      __ z_aghi(data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
2110    }
2111
2112    StubRoutines::zarch::generate_load_crc32c_table_addr(_masm, table);
2113
2114    __ resize_frame(-(6*8), Z_R0, true); // Resize frame to provide add'l space to spill 5 registers.
2115    __ z_stmg(t0, t3, 1*8, Z_SP);        // Spill regs 10..13 to make them available as work registers.
2116    __ kernel_crc32_1word(crc, data, dataLen, table, t0, t1, t2, t3, false);
2117    __ z_lmg(t0, t3, 1*8, Z_SP);         // Spill regs 10..13 back from stack.
2118
2119    // Restore caller sp for c2i case.
2120    __ resize_frame_absolute(Z_R10, Z_R0, true); // Cut the stack back to where the caller started.
2121
2122    __ z_br(Z_R14);
2123
2124    BLOCK_COMMENT("} CRC32C_update{Bytes|DirectByteBuffer}");
2125    return __ addr_at(entry_off);
2126  }
2127
2128  return NULL;
2129}
2130
2131void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
2132  // Quick & dirty stack overflow checking: bang the stack & handle trap.
2133  // Note that we do the banging after the frame is setup, since the exception
2134  // handling code expects to find a valid interpreter frame on the stack.
2135  // Doing the banging earlier fails if the caller frame is not an interpreter
2136  // frame.
2137  // (Also, the exception throwing code expects to unlock any synchronized
2138  // method receiver, so do the banging after locking the receiver.)
2139
2140  // Bang each page in the shadow zone. We can't assume it's been done for
2141  // an interpreter frame with greater than a page of locals, so each page
2142  // needs to be checked. Only true for non-native. For native, we only bang the last page.
2143  if (UseStackBanging) {
2144    const int page_size      = os::vm_page_size();
2145    const int n_shadow_pages = (int)(JavaThread::stack_shadow_zone_size()/page_size);
2146    const int start_page_num = native_call ? n_shadow_pages : 1;
2147    for (int pages = start_page_num; pages <= n_shadow_pages; pages++) {
2148      __ bang_stack_with_offset(pages*page_size);
2149    }
2150  }
2151}
2152
2153//-----------------------------------------------------------------------------
2154// Exceptions
2155
2156void TemplateInterpreterGenerator::generate_throw_exception() {
2157
2158  BLOCK_COMMENT("throw_exception {");
2159
2160  // Entry point in previous activation (i.e., if the caller was interpreted).
2161  Interpreter::_rethrow_exception_entry = __ pc();
2162  __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // Frame accessors use Z_fp.
2163  // Z_ARG1 (==Z_tos): exception
2164  // Z_ARG2          : Return address/pc that threw exception.
2165  __ restore_bcp();    // R13 points to call/send.
2166  __ restore_locals();
2167
2168  // Fallthrough, no need to restore Z_esp.
2169
2170  // Entry point for exceptions thrown within interpreter code.
2171  Interpreter::_throw_exception_entry = __ pc();
2172  // Expression stack is undefined here.
2173  // Z_ARG1 (==Z_tos): exception
2174  // Z_bcp: exception bcp
2175  __ verify_oop(Z_ARG1);
2176  __ z_lgr(Z_ARG2, Z_ARG1);
2177
2178  // Expression stack must be empty before entering the VM in case of
2179  // an exception.
2180  __ empty_expression_stack();
2181  // Find exception handler address and preserve exception oop.
2182  const Register Rpreserved_exc_oop = Z_tmp_1;
2183  __ call_VM(Rpreserved_exc_oop,
2184             CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception),
2185             Z_ARG2);
2186  // Z_RET: exception handler entry point
2187  // Z_bcp: bcp for exception handler
2188  __ push_ptr(Rpreserved_exc_oop); // Push exception which is now the only value on the stack.
2189  __ z_br(Z_RET); // Jump to exception handler (may be _remove_activation_entry!).
2190
2191  // If the exception is not handled in the current frame the frame is
2192  // removed and the exception is rethrown (i.e. exception
2193  // continuation is _rethrow_exception).
2194  //
2195  // Note: At this point the bci is still the bci for the instruction
2196  // which caused the exception and the expression stack is
2197  // empty. Thus, for any VM calls at this point, GC will find a legal
2198  // oop map (with empty expression stack).
2199
2200  //
2201  // JVMTI PopFrame support
2202  //
2203
2204  Interpreter::_remove_activation_preserving_args_entry = __ pc();
2205  __ z_lg(Z_fp, _z_parent_ijava_frame_abi(callers_sp), Z_SP);
2206  __ empty_expression_stack();
2207  // Set the popframe_processing bit in pending_popframe_condition
2208  // indicating that we are currently handling popframe, so that
2209  // call_VMs that may happen later do not trigger new popframe
2210  // handling cycles.
2211  __ load_sized_value(Z_tmp_1, Address(Z_thread, JavaThread::popframe_condition_offset()), 4, false /*signed*/);
2212  __ z_oill(Z_tmp_1, JavaThread::popframe_processing_bit);
2213  __ z_sty(Z_tmp_1, thread_(popframe_condition));
2214
2215  {
2216    // Check to see whether we are returning to a deoptimized frame.
2217    // (The PopFrame call ensures that the caller of the popped frame is
2218    // either interpreted or compiled and deoptimizes it if compiled.)
2219    // In this case, we can't call dispatch_next() after the frame is
2220    // popped, but instead must save the incoming arguments and restore
2221    // them after deoptimization has occurred.
2222    //
2223    // Note that we don't compare the return PC against the
2224    // deoptimization blob's unpack entry because of the presence of
2225    // adapter frames in C2.
2226    NearLabel caller_not_deoptimized;
2227    __ z_lg(Z_ARG1, _z_parent_ijava_frame_abi(return_pc), Z_fp);
2228    __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), Z_ARG1);
2229    __ compareU64_and_branch(Z_RET, (intptr_t)0, Assembler::bcondNotEqual, caller_not_deoptimized);
2230
2231    // Compute size of arguments for saving when returning to
2232    // deoptimized caller.
2233    __ get_method(Z_ARG2);
2234    __ z_lg(Z_ARG2, Address(Z_ARG2, Method::const_offset()));
2235    __ z_llgh(Z_ARG2, Address(Z_ARG2, ConstMethod::size_of_parameters_offset()));
2236    __ z_sllg(Z_ARG2, Z_ARG2, Interpreter::logStackElementSize); // slots 2 bytes
2237    __ restore_locals();
2238    // Compute address of args to be saved.
2239    __ z_lgr(Z_ARG3, Z_locals);
2240    __ z_slgr(Z_ARG3, Z_ARG2);
2241    __ add2reg(Z_ARG3, wordSize);
2242    // Save these arguments.
2243    __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args),
2244                    Z_thread, Z_ARG2, Z_ARG3);
2245
2246    __ remove_activation(vtos, Z_R14,
2247                         /* throw_monitor_exception */ false,
2248                         /* install_monitor_exception */ false,
2249                         /* notify_jvmdi */ false);
2250
2251    // Inform deoptimization that it is responsible for restoring
2252    // these arguments.
2253    __ store_const(thread_(popframe_condition),
2254                   JavaThread::popframe_force_deopt_reexecution_bit,
2255                   Z_tmp_1, false);
2256
2257    // Continue in deoptimization handler.
2258    __ z_br(Z_R14);
2259
2260    __ bind(caller_not_deoptimized);
2261  }
2262
2263  // Clear the popframe condition flag.
2264  __ clear_mem(thread_(popframe_condition), sizeof(int));
2265
2266  __ remove_activation(vtos,
2267                       noreg,  // Retaddr is not used.
2268                       false,  // throw_monitor_exception
2269                       false,  // install_monitor_exception
2270                       false); // notify_jvmdi
2271  __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // Restore frame pointer.
2272  __ restore_bcp();
2273  __ restore_locals();
2274  __ restore_esp();
2275  // The method data pointer was incremented already during
2276  // call profiling. We have to restore the mdp for the current bcp.
2277  if (ProfileInterpreter) {
2278    __ set_method_data_pointer_for_bcp();
2279  }
2280#if INCLUDE_JVMTI
2281  {
2282    Label L_done;
2283
2284    __ z_cli(0, Z_bcp, Bytecodes::_invokestatic);
2285    __ z_brc(Assembler::bcondNotEqual, L_done);
2286
2287    // The member name argument must be restored if _invokestatic is
2288    // re-executed after a PopFrame call.  Detect such a case in the
2289    // InterpreterRuntime function and return the member name
2290    // argument, or NULL.
2291    __ z_lg(Z_ARG2, Address(Z_locals));
2292    __ get_method(Z_ARG3);
2293    __ call_VM(Z_tmp_1,
2294               CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null),
2295               Z_ARG2, Z_ARG3, Z_bcp);
2296
2297    __ z_ltgr(Z_tmp_1, Z_tmp_1);
2298    __ z_brc(Assembler::bcondEqual, L_done);
2299
2300    __ z_stg(Z_tmp_1, Address(Z_esp, wordSize));
2301    __ bind(L_done);
2302  }
2303#endif // INCLUDE_JVMTI
2304  __ dispatch_next(vtos);
2305  // End of PopFrame support.
2306  Interpreter::_remove_activation_entry = __ pc();
2307
2308  // In between activations - previous activation type unknown yet
2309  // compute continuation point - the continuation point expects the
2310  // following registers set up:
2311  //
2312  // Z_ARG1 (==Z_tos): exception
2313  // Z_ARG2          : return address/pc that threw exception
2314
2315  Register return_pc = Z_tmp_1;
2316  Register handler   = Z_tmp_2;
2317   assert(return_pc->is_nonvolatile(), "use non-volatile reg. to preserve exception pc");
2318   assert(handler->is_nonvolatile(),   "use non-volatile reg. to handler pc");
2319  __ asm_assert_ijava_state_magic(return_pc/*tmp*/); // The top frame should be an interpreter frame.
2320  __ z_lg(return_pc, _z_parent_ijava_frame_abi(return_pc), Z_fp);
2321
2322  // Moved removing the activation after VM call, because the new top
2323  // frame does not necessarily have the z_abi_160 required for a VM
2324  // call (e.g. if it is compiled).
2325
2326  __ super_call_VM_leaf(CAST_FROM_FN_PTR(address,
2327                                         SharedRuntime::exception_handler_for_return_address),
2328                        Z_thread, return_pc);
2329  __ z_lgr(handler, Z_RET); // Save exception handler.
2330
2331  // Preserve exception over this code sequence.
2332  __ pop_ptr(Z_ARG1);
2333  __ set_vm_result(Z_ARG1);
2334  // Remove the activation (without doing throws on illegalMonitorExceptions).
2335  __ remove_activation(vtos, noreg/*ret.pc already loaded*/, false/*throw exc*/, true/*install exc*/, false/*notify jvmti*/);
2336  __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // Restore frame pointer.
2337
2338  __ get_vm_result(Z_ARG1);     // Restore exception.
2339  __ verify_oop(Z_ARG1);
2340  __ z_lgr(Z_ARG2, return_pc);  // Restore return address.
2341
2342#ifdef ASSERT
2343  // The return_pc in the new top frame is dead... at least that's my
2344  // current understanding. To assert this I overwrite it.
2345  // Note: for compiled frames the handler is the deopt blob
2346  // which writes Z_ARG2 into the return_pc slot.
2347  __ load_const_optimized(return_pc, 0xb00b1);
2348  __ z_stg(return_pc, _z_parent_ijava_frame_abi(return_pc), Z_SP);
2349#endif
2350
2351  // Z_ARG1 (==Z_tos): exception
2352  // Z_ARG2          : return address/pc that threw exception
2353
2354  // Note that an "issuing PC" is actually the next PC after the call.
2355  __ z_br(handler);         // Jump to exception handler of caller.
2356
2357  BLOCK_COMMENT("} throw_exception");
2358}
2359
2360//
2361// JVMTI ForceEarlyReturn support
2362//
2363address TemplateInterpreterGenerator::generate_earlyret_entry_for (TosState state) {
2364  address entry = __ pc();
2365
2366  BLOCK_COMMENT("earlyret_entry {");
2367
2368  __ z_lg(Z_fp, _z_parent_ijava_frame_abi(callers_sp), Z_SP);
2369  __ restore_bcp();
2370  __ restore_locals();
2371  __ restore_esp();
2372  __ empty_expression_stack();
2373  __ load_earlyret_value(state);
2374
2375  Register RjvmtiState = Z_tmp_1;
2376  __ z_lg(RjvmtiState, thread_(jvmti_thread_state));
2377  __ store_const(Address(RjvmtiState, JvmtiThreadState::earlyret_state_offset()),
2378                 JvmtiThreadState::earlyret_inactive, 4, 4, Z_R0_scratch);
2379
2380  __ remove_activation(state,
2381                       Z_tmp_1, // retaddr
2382                       false,   // throw_monitor_exception
2383                       false,   // install_monitor_exception
2384                       true);   // notify_jvmdi
2385  __ z_br(Z_tmp_1);
2386
2387  BLOCK_COMMENT("} earlyret_entry");
2388
2389  return entry;
2390}
2391
2392//-----------------------------------------------------------------------------
2393// Helper for vtos entry point generation.
2394
2395void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2396                                                         address& bep,
2397                                                         address& cep,
2398                                                         address& sep,
2399                                                         address& aep,
2400                                                         address& iep,
2401                                                         address& lep,
2402                                                         address& fep,
2403                                                         address& dep,
2404                                                         address& vep) {
2405  assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2406  Label L;
2407  aep = __ pc(); __ push_ptr(); __ z_bru(L);
2408  fep = __ pc(); __ push_f();   __ z_bru(L);
2409  dep = __ pc(); __ push_d();   __ z_bru(L);
2410  lep = __ pc(); __ push_l();   __ z_bru(L);
2411  bep = cep = sep =
2412  iep = __ pc(); __ push_i();
2413  vep = __ pc();
2414  __ bind(L);
2415  generate_and_dispatch(t);
2416}
2417
2418//-----------------------------------------------------------------------------
2419
2420#ifndef PRODUCT
2421address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2422  address entry = __ pc();
2423  NearLabel counter_below_trace_threshold;
2424
2425  if (TraceBytecodesAt > 0) {
2426    // Skip runtime call, if the trace threshold is not yet reached.
2427    __ load_absolute_address(Z_tmp_1, (address)&BytecodeCounter::_counter_value);
2428    __ load_absolute_address(Z_tmp_2, (address)&TraceBytecodesAt);
2429    __ load_sized_value(Z_tmp_1, Address(Z_tmp_1), 4, false /*signed*/);
2430    __ load_sized_value(Z_tmp_2, Address(Z_tmp_2), 8, false /*signed*/);
2431    __ compareU64_and_branch(Z_tmp_1, Z_tmp_2, Assembler::bcondLow, counter_below_trace_threshold);
2432  }
2433
2434  int offset2 = state == ltos || state == dtos ? 2 : 1;
2435
2436  __ push(state);
2437  // Preserved return pointer is in Z_R14.
2438  // InterpreterRuntime::trace_bytecode() preserved and returns the value passed as second argument.
2439  __ z_lgr(Z_ARG2, Z_R14);
2440  __ z_lg(Z_ARG3, Address(Z_esp, Interpreter::expr_offset_in_bytes(0)));
2441  if (WizardMode) {
2442    __ z_lgr(Z_ARG4, Z_esp); // Trace Z_esp in WizardMode.
2443  } else {
2444    __ z_lg(Z_ARG4, Address(Z_esp, Interpreter::expr_offset_in_bytes(offset2)));
2445  }
2446  __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode), Z_ARG2, Z_ARG3, Z_ARG4);
2447  __ z_lgr(Z_R14, Z_RET); // Estore return address (see above).
2448  __ pop(state);
2449
2450  __ bind(counter_below_trace_threshold);
2451  __ z_br(Z_R14); // return
2452
2453  return entry;
2454}
2455
2456// Make feasible for old CPUs.
2457void TemplateInterpreterGenerator::count_bytecode() {
2458  __ load_absolute_address(Z_R1_scratch, (address) &BytecodeCounter::_counter_value);
2459  __ add2mem_32(Address(Z_R1_scratch), 1, Z_R0_scratch);
2460}
2461
2462void TemplateInterpreterGenerator::histogram_bytecode(Template * t) {
2463  __ load_absolute_address(Z_R1_scratch, (address)&BytecodeHistogram::_counters[ t->bytecode() ]);
2464  __ add2mem_32(Address(Z_R1_scratch), 1, Z_tmp_1);
2465}
2466
2467void TemplateInterpreterGenerator::histogram_bytecode_pair(Template * t) {
2468  Address  index_addr(Z_tmp_1, (intptr_t) 0);
2469  Register index = Z_tmp_2;
2470
2471  // Load previous index.
2472  __ load_absolute_address(Z_tmp_1, (address) &BytecodePairHistogram::_index);
2473  __ mem2reg_opt(index, index_addr, false);
2474
2475  // Mask with current bytecode and store as new previous index.
2476  __ z_srl(index, BytecodePairHistogram::log2_number_of_codes);
2477  __ load_const_optimized(Z_R0_scratch,
2478                          (int)t->bytecode() << BytecodePairHistogram::log2_number_of_codes);
2479  __ z_or(index, Z_R0_scratch);
2480  __ reg2mem_opt(index, index_addr, false);
2481
2482  // Load counter array's address.
2483  __ z_lgfr(index, index);   // Sign extend for addressing.
2484  __ z_sllg(index, index, LogBytesPerInt);  // index2bytes
2485  __ load_absolute_address(Z_R1_scratch,
2486                           (address) &BytecodePairHistogram::_counters);
2487  // Add index and increment counter.
2488  __ z_agr(Z_R1_scratch, index);
2489  __ add2mem_32(Address(Z_R1_scratch), 1, Z_tmp_1);
2490}
2491
2492void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2493  // Call a little run-time stub to avoid blow-up for each bytecode.
2494  // The run-time runtime saves the right registers, depending on
2495  // the tosca in-state for the given template.
2496  address entry = Interpreter::trace_code(t->tos_in());
2497  guarantee(entry != NULL, "entry must have been generated");
2498  __ call_stub(entry);
2499}
2500
2501void TemplateInterpreterGenerator::stop_interpreter_at() {
2502  NearLabel L;
2503
2504  __ load_absolute_address(Z_tmp_1, (address)&BytecodeCounter::_counter_value);
2505  __ load_absolute_address(Z_tmp_2, (address)&StopInterpreterAt);
2506  __ load_sized_value(Z_tmp_1, Address(Z_tmp_1), 4, false /*signed*/);
2507  __ load_sized_value(Z_tmp_2, Address(Z_tmp_2), 8, false /*signed*/);
2508  __ compareU64_and_branch(Z_tmp_1, Z_tmp_2, Assembler::bcondLow, L);
2509  assert(Z_tmp_1->is_nonvolatile(), "must be nonvolatile to preserve Z_tos");
2510  assert(Z_F8->is_nonvolatile(), "must be nonvolatile to preserve Z_ftos");
2511  __ z_lgr(Z_tmp_1, Z_tos);      // Save tos.
2512  __ z_lgr(Z_tmp_2, Z_bytecode); // Save Z_bytecode.
2513  __ z_ldr(Z_F8, Z_ftos);        // Save ftos.
2514  // Use -XX:StopInterpreterAt=<num> to set the limit
2515  // and break at breakpoint().
2516  __ call_VM(noreg, CAST_FROM_FN_PTR(address, breakpoint), false);
2517  __ z_lgr(Z_tos, Z_tmp_1);      // Restore tos.
2518  __ z_lgr(Z_bytecode, Z_tmp_2); // Save Z_bytecode.
2519  __ z_ldr(Z_ftos, Z_F8);        // Restore ftos.
2520  __ bind(L);
2521}
2522
2523#endif // !PRODUCT
2524