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