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