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