1 /*
   2  * Copyright (c) 2014, 2025, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2015, 2025 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "asm/macroAssembler.inline.hpp"
  27 #include "classfile/javaClasses.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/barrierSetAssembler.hpp"
  30 #include "interpreter/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/method.hpp"
  38 #include "oops/methodCounters.hpp"
  39 #include "oops/methodData.hpp"
  40 #include "oops/oop.inline.hpp"
  41 #include "oops/resolvedIndyEntry.hpp"
  42 #include "oops/resolvedMethodEntry.hpp"
  43 #include "prims/jvmtiExport.hpp"
  44 #include "prims/jvmtiThreadState.hpp"
  45 #include "runtime/arguments.hpp"
  46 #include "runtime/deoptimization.hpp"
  47 #include "runtime/frame.inline.hpp"
  48 #include "runtime/jniHandles.hpp"
  49 #include "runtime/sharedRuntime.hpp"
  50 #include "runtime/stubRoutines.hpp"
  51 #include "runtime/synchronizer.hpp"
  52 #include "runtime/timer.hpp"
  53 #include "runtime/vframeArray.hpp"
  54 #include "runtime/vm_version.hpp"
  55 #include "utilities/debug.hpp"
  56 #include "utilities/macros.hpp"
  57 
  58 #undef __
  59 #define __ Disassembler::hook<InterpreterMacroAssembler>(__FILE__, __LINE__, _masm)->
  60 
  61 // Size of interpreter code.  Increase if too small.  Interpreter will
  62 // fail with a guarantee ("not enough space for interpreter generation");
  63 // if too small.
  64 // Run with +PrintInterpreter to get the VM to print out the size.
  65 // Max size with JVMTI
  66 int TemplateInterpreter::InterpreterCodeSize = 256*K;
  67 
  68 #ifdef PRODUCT
  69 #define BLOCK_COMMENT(str) /* nothing */
  70 #else
  71 #define BLOCK_COMMENT(str) __ block_comment(str)
  72 #endif
  73 
  74 #define BIND(label)        __ bind(label); BLOCK_COMMENT(#label ":")
  75 
  76 //-----------------------------------------------------------------------------
  77 
  78 address TemplateInterpreterGenerator::generate_slow_signature_handler() {
  79   // Slow_signature handler that respects the PPC C calling conventions.
  80   //
  81   // We get called by the native entry code with our output register
  82   // area == 8. First we call InterpreterRuntime::get_result_handler
  83   // to copy the pointer to the signature string temporarily to the
  84   // first C-argument and to return the result_handler in
  85   // R3_RET. Since native_entry will copy the jni-pointer to the
  86   // first C-argument slot later on, it is OK to occupy this slot
  87   // temporarily. Then we copy the argument list on the java
  88   // expression stack into native varargs format on the native stack
  89   // and load arguments into argument registers. Integer arguments in
  90   // the varargs vector will be sign-extended to 8 bytes.
  91   //
  92   // On entry:
  93   //   R3_ARG1        - intptr_t*     Address of java argument list in memory.
  94   //   R15_prev_state - BytecodeInterpreter* Address of interpreter state for
  95   //     this method
  96   //   R19_method
  97   //
  98   // On exit (just before return instruction):
  99   //   R3_RET            - contains the address of the result_handler.
 100   //   R4_ARG2           - is not updated for static methods and contains "this" otherwise.
 101   //   R5_ARG3-R10_ARG8: - When the (i-2)th Java argument is not of type float or double,
 102   //                       ARGi contains this argument. Otherwise, ARGi is not updated.
 103   //   F1_ARG1-F13_ARG13 - contain the first 13 arguments of type float or double.
 104 
 105   const int LogSizeOfTwoInstructions = 3;
 106 
 107   // FIXME: use Argument:: GL: Argument names different numbers!
 108   const int max_fp_register_arguments  = 13;
 109   const int max_int_register_arguments = 6;  // first 2 are reserved
 110 
 111   const Register arg_java       = R21_tmp1;
 112   const Register arg_c          = R22_tmp2;
 113   const Register signature      = R23_tmp3;  // is string
 114   const Register sig_byte       = R24_tmp4;
 115   const Register fpcnt          = R25_tmp5;
 116   const Register argcnt         = R26_tmp6;
 117   const Register intSlot        = R27_tmp7;
 118   const Register target_sp      = R28_tmp8;
 119   const FloatRegister floatSlot = F0;
 120 
 121   address entry = __ function_entry();
 122   int save_nonvolatile_registers_size = __ save_nonvolatile_registers_size(false, false);
 123 
 124   __ save_LR(R0);
 125   __ save_nonvolatile_registers(R1_SP, -save_nonvolatile_registers_size, false, false);
 126   // We use target_sp for storing arguments in the C frame.
 127   __ mr(target_sp, R1_SP);
 128   __ push_frame(frame::native_abi_reg_args_size + save_nonvolatile_registers_size, R11_scratch1);
 129 
 130   __ mr(arg_java, R3_ARG1);
 131 
 132   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_signature), R16_thread, R19_method);
 133 
 134   // Signature is in R3_RET. Signature is callee saved.
 135   __ mr(signature, R3_RET);
 136 
 137   // Get the result handler.
 138   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::get_result_handler), R16_thread, R19_method);
 139 
 140   {
 141     Label L;
 142     // test if static
 143     // _access_flags._flags must be at offset 0.
 144     // TODO PPC port: requires change in shared code.
 145     //assert(in_bytes(AccessFlags::flags_offset()) == 0,
 146     //       "MethodDesc._access_flags == MethodDesc._access_flags._flags");
 147     // _access_flags must be a 16 bit value.
 148     assert(sizeof(AccessFlags) == 2, "wrong size");
 149     __ lhz(R11_scratch1/*access_flags*/, method_(access_flags));
 150     // testbit with condition register.
 151     __ testbitdi(CR0, R0, R11_scratch1/*access_flags*/, JVM_ACC_STATIC_BIT);
 152     __ btrue(CR0, L);
 153     // For non-static functions, pass "this" in R4_ARG2 and copy it
 154     // to 2nd C-arg slot.
 155     // We need to box the Java object here, so we use arg_java
 156     // (address of current Java stack slot) as argument and don't
 157     // dereference it as in case of ints, floats, etc.
 158     __ mr(R4_ARG2, arg_java);
 159     __ addi(arg_java, arg_java, -BytesPerWord);
 160     __ std(R4_ARG2, _abi0(carg_2), target_sp);
 161     __ bind(L);
 162   }
 163 
 164   // Will be incremented directly after loop_start. argcnt=0
 165   // corresponds to 3rd C argument.
 166   __ li(argcnt, -1);
 167   // arg_c points to 3rd C argument
 168   __ addi(arg_c, target_sp, _abi0(carg_3));
 169   // no floating-point args parsed so far
 170   __ li(fpcnt, 0);
 171 
 172   Label move_intSlot_to_ARG, move_floatSlot_to_FARG;
 173   Label loop_start, loop_end;
 174   Label do_int, do_long, do_float, do_double, do_dontreachhere, do_object, do_array, do_boxed;
 175 
 176   // signature points to '(' at entry
 177 #ifdef ASSERT
 178   __ lbz(sig_byte, 0, signature);
 179   __ cmplwi(CR0, sig_byte, '(');
 180   __ bne(CR0, do_dontreachhere);
 181 #endif
 182 
 183   __ bind(loop_start);
 184 
 185   __ addi(argcnt, argcnt, 1);
 186   __ lbzu(sig_byte, 1, signature);
 187 
 188   __ cmplwi(CR0, sig_byte, ')'); // end of signature
 189   __ beq(CR0, loop_end);
 190 
 191   __ cmplwi(CR0, sig_byte, 'B'); // byte
 192   __ beq(CR0, do_int);
 193 
 194   __ cmplwi(CR0, sig_byte, 'C'); // char
 195   __ beq(CR0, do_int);
 196 
 197   __ cmplwi(CR0, sig_byte, 'D'); // double
 198   __ beq(CR0, do_double);
 199 
 200   __ cmplwi(CR0, sig_byte, 'F'); // float
 201   __ beq(CR0, do_float);
 202 
 203   __ cmplwi(CR0, sig_byte, 'I'); // int
 204   __ beq(CR0, do_int);
 205 
 206   __ cmplwi(CR0, sig_byte, 'J'); // long
 207   __ beq(CR0, do_long);
 208 
 209   __ cmplwi(CR0, sig_byte, 'S'); // short
 210   __ beq(CR0, do_int);
 211 
 212   __ cmplwi(CR0, sig_byte, 'Z'); // boolean
 213   __ beq(CR0, do_int);
 214 
 215   __ cmplwi(CR0, sig_byte, 'L'); // object
 216   __ beq(CR0, do_object);
 217 
 218   __ cmplwi(CR0, sig_byte, '['); // array
 219   __ beq(CR0, do_array);
 220 
 221   //  __ cmplwi(CR0, sig_byte, 'V'); // void cannot appear since we do not parse the return type
 222   //  __ beq(CR0, do_void);
 223 
 224   __ bind(do_dontreachhere);
 225 
 226   __ unimplemented("ShouldNotReachHere in slow_signature_handler");
 227 
 228   __ bind(do_array);
 229 
 230   {
 231     Label start_skip, end_skip;
 232 
 233     __ bind(start_skip);
 234     __ lbzu(sig_byte, 1, signature);
 235     __ cmplwi(CR0, sig_byte, '[');
 236     __ beq(CR0, start_skip); // skip further brackets
 237     __ cmplwi(CR0, sig_byte, '9');
 238     __ bgt(CR0, end_skip);   // no optional size
 239     __ cmplwi(CR0, sig_byte, '0');
 240     __ bge(CR0, start_skip); // skip optional size
 241     __ bind(end_skip);
 242 
 243     __ cmplwi(CR0, sig_byte, 'L');
 244     __ beq(CR0, do_object);  // for arrays of objects, the name of the object must be skipped
 245     __ b(do_boxed);          // otherwise, go directly to do_boxed
 246   }
 247 
 248   __ bind(do_object);
 249   {
 250     Label L;
 251     __ bind(L);
 252     __ lbzu(sig_byte, 1, signature);
 253     __ cmplwi(CR0, sig_byte, ';');
 254     __ bne(CR0, L);
 255    }
 256   // Need to box the Java object here, so we use arg_java (address of
 257   // current Java stack slot) as argument and don't dereference it as
 258   // in case of ints, floats, etc.
 259   Label do_null;
 260   __ bind(do_boxed);
 261   __ ld(R0,0, arg_java);
 262   __ cmpdi(CR0, R0, 0);
 263   __ li(intSlot,0);
 264   __ beq(CR0, do_null);
 265   __ mr(intSlot, arg_java);
 266   __ bind(do_null);
 267   __ std(intSlot, 0, arg_c);
 268   __ addi(arg_java, arg_java, -BytesPerWord);
 269   __ addi(arg_c, arg_c, BytesPerWord);
 270   __ cmplwi(CR0, argcnt, max_int_register_arguments);
 271   __ blt(CR0, move_intSlot_to_ARG);
 272   __ b(loop_start);
 273 
 274   __ bind(do_int);
 275   __ lwa(intSlot, 0, arg_java);
 276   __ std(intSlot, 0, arg_c);
 277   __ addi(arg_java, arg_java, -BytesPerWord);
 278   __ addi(arg_c, arg_c, BytesPerWord);
 279   __ cmplwi(CR0, argcnt, max_int_register_arguments);
 280   __ blt(CR0, move_intSlot_to_ARG);
 281   __ b(loop_start);
 282 
 283   __ bind(do_long);
 284   __ ld(intSlot, -BytesPerWord, arg_java);
 285   __ std(intSlot, 0, arg_c);
 286   __ addi(arg_java, arg_java, - 2 * BytesPerWord);
 287   __ addi(arg_c, arg_c, BytesPerWord);
 288   __ cmplwi(CR0, argcnt, max_int_register_arguments);
 289   __ blt(CR0, move_intSlot_to_ARG);
 290   __ b(loop_start);
 291 
 292   __ bind(do_float);
 293   __ lfs(floatSlot, 0, arg_java);
 294   __ stfs(floatSlot, Argument::float_on_stack_offset_in_bytes_c, arg_c);
 295   __ addi(arg_java, arg_java, -BytesPerWord);
 296   __ addi(arg_c, arg_c, BytesPerWord);
 297   __ cmplwi(CR0, fpcnt, max_fp_register_arguments);
 298   __ blt(CR0, move_floatSlot_to_FARG);
 299   __ b(loop_start);
 300 
 301   __ bind(do_double);
 302   __ lfd(floatSlot, - BytesPerWord, arg_java);
 303   __ stfd(floatSlot, 0, arg_c);
 304   __ addi(arg_java, arg_java, - 2 * BytesPerWord);
 305   __ addi(arg_c, arg_c, BytesPerWord);
 306   __ cmplwi(CR0, fpcnt, max_fp_register_arguments);
 307   __ blt(CR0, move_floatSlot_to_FARG);
 308   __ b(loop_start);
 309 
 310   __ bind(loop_end);
 311 
 312   __ pop_frame();
 313   __ restore_nonvolatile_registers(R1_SP, -save_nonvolatile_registers_size, false, false);
 314   __ restore_LR(R0);
 315 
 316   __ blr();
 317 
 318   Label move_int_arg, move_float_arg;
 319   __ bind(move_int_arg); // each case must consist of 2 instructions (otherwise adapt LogSizeOfTwoInstructions)
 320   __ mr(R5_ARG3, intSlot);  __ b(loop_start);
 321   __ mr(R6_ARG4, intSlot);  __ b(loop_start);
 322   __ mr(R7_ARG5, intSlot);  __ b(loop_start);
 323   __ mr(R8_ARG6, intSlot);  __ b(loop_start);
 324   __ mr(R9_ARG7, intSlot);  __ b(loop_start);
 325   __ mr(R10_ARG8, intSlot); __ b(loop_start);
 326 
 327   __ bind(move_float_arg); // each case must consist of 2 instructions (otherwise adapt LogSizeOfTwoInstructions)
 328   __ fmr(F1_ARG1, floatSlot);   __ b(loop_start);
 329   __ fmr(F2_ARG2, floatSlot);   __ b(loop_start);
 330   __ fmr(F3_ARG3, floatSlot);   __ b(loop_start);
 331   __ fmr(F4_ARG4, floatSlot);   __ b(loop_start);
 332   __ fmr(F5_ARG5, floatSlot);   __ b(loop_start);
 333   __ fmr(F6_ARG6, floatSlot);   __ b(loop_start);
 334   __ fmr(F7_ARG7, floatSlot);   __ b(loop_start);
 335   __ fmr(F8_ARG8, floatSlot);   __ b(loop_start);
 336   __ fmr(F9_ARG9, floatSlot);   __ b(loop_start);
 337   __ fmr(F10_ARG10, floatSlot); __ b(loop_start);
 338   __ fmr(F11_ARG11, floatSlot); __ b(loop_start);
 339   __ fmr(F12_ARG12, floatSlot); __ b(loop_start);
 340   __ fmr(F13_ARG13, floatSlot); __ b(loop_start);
 341 
 342   __ bind(move_intSlot_to_ARG);
 343   __ sldi(R0, argcnt, LogSizeOfTwoInstructions);
 344   __ load_const(R11_scratch1, move_int_arg); // Label must be bound here.
 345   __ add(R11_scratch1, R0, R11_scratch1);
 346   __ mtctr(R11_scratch1/*branch_target*/);
 347   __ bctr();
 348   __ bind(move_floatSlot_to_FARG);
 349   __ sldi(R0, fpcnt, LogSizeOfTwoInstructions);
 350   __ addi(fpcnt, fpcnt, 1);
 351   __ load_const(R11_scratch1, move_float_arg); // Label must be bound here.
 352   __ add(R11_scratch1, R0, R11_scratch1);
 353   __ mtctr(R11_scratch1/*branch_target*/);
 354   __ bctr();
 355 
 356   return entry;
 357 }
 358 
 359 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 360   //
 361   // Registers alive
 362   //   R3_RET
 363   //   LR
 364   //
 365   // Registers updated
 366   //   R3_RET
 367   //
 368 
 369   Label done;
 370   address entry = __ pc();
 371 
 372   switch (type) {
 373   case T_BOOLEAN:
 374     // convert !=0 to 1
 375     __ normalize_bool(R3_RET);
 376     break;
 377   case T_BYTE:
 378      // sign extend 8 bits
 379      __ extsb(R3_RET, R3_RET);
 380      break;
 381   case T_CHAR:
 382      // zero extend 16 bits
 383      __ clrldi(R3_RET, R3_RET, 48);
 384      break;
 385   case T_SHORT:
 386      // sign extend 16 bits
 387      __ extsh(R3_RET, R3_RET);
 388      break;
 389   case T_INT:
 390      // sign extend 32 bits
 391      __ extsw(R3_RET, R3_RET);
 392      break;
 393   case T_LONG:
 394      break;
 395   case T_OBJECT:
 396     // JNIHandles::resolve result.
 397     __ resolve_jobject(R3_RET, R11_scratch1, R31, MacroAssembler::PRESERVATION_FRAME_LR); // kills R31
 398     break;
 399   case T_FLOAT:
 400      break;
 401   case T_DOUBLE:
 402      break;
 403   case T_VOID:
 404      break;
 405   default: ShouldNotReachHere();
 406   }
 407 
 408   BIND(done);
 409   __ blr();
 410 
 411   return entry;
 412 }
 413 
 414 // Abstract method entry.
 415 //
 416 address TemplateInterpreterGenerator::generate_abstract_entry(void) {
 417   address entry = __ pc();
 418 
 419   //
 420   // Registers alive
 421   //   R16_thread     - JavaThread*
 422   //   R19_method     - callee's method (method to be invoked)
 423   //   R1_SP          - SP prepared such that caller's outgoing args are near top
 424   //   LR             - return address to caller
 425   //
 426   // Stack layout at this point:
 427   //
 428   //   0       [TOP_IJAVA_FRAME_ABI]         <-- R1_SP
 429   //           alignment (optional)
 430   //           [outgoing Java arguments]
 431   //           ...
 432   //   PARENT  [PARENT_IJAVA_FRAME_ABI]
 433   //            ...
 434   //
 435 
 436   // Can't use call_VM here because we have not set up a new
 437   // interpreter state. Make the call to the vm and make it look like
 438   // our caller set up the JavaFrameAnchor.
 439   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
 440 
 441   // Push a new C frame and save LR.
 442   __ save_LR(R0);
 443   __ push_frame_reg_args(0, R11_scratch1);
 444 
 445   // This is not a leaf but we have a JavaFrameAnchor now and we will
 446   // check (create) exceptions afterward so this is ok.
 447   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_AbstractMethodErrorWithMethod),
 448                   R16_thread, R19_method);
 449 
 450   // Pop the C frame and restore LR.
 451   __ pop_frame();
 452   __ restore_LR(R0);
 453 
 454   // Reset JavaFrameAnchor from call_VM_leaf above.
 455   __ reset_last_Java_frame();
 456 
 457   // We don't know our caller, so jump to the general forward exception stub,
 458   // which will also pop our full frame off. Satisfy the interface of
 459   // SharedRuntime::generate_forward_exception()
 460   __ load_const_optimized(R11_scratch1, StubRoutines::forward_exception_entry(), R0);
 461   __ mtctr(R11_scratch1);
 462   __ bctr();
 463 
 464   return entry;
 465 }
 466 
 467 // Interpreter intrinsic for WeakReference.get().
 468 // 1. Don't push a full blown frame and go on dispatching, but fetch the value
 469 //    into R8 and return quickly
 470 // 2. If G1 is active we *must* execute this intrinsic for corrrectness:
 471 //    It contains a GC barrier which puts the reference into the satb buffer
 472 //    to indicate that someone holds a strong reference to the object the
 473 //    weak ref points to!
 474 address TemplateInterpreterGenerator::generate_Reference_get_entry(void) {
 475   // Code: _aload_0, _getfield, _areturn
 476   // parameter size = 1
 477   //
 478   // The code that gets generated by this routine is split into 2 parts:
 479   //    1. the "intrinsified" code for G1 (or any SATB based GC),
 480   //    2. the slow path - which is an expansion of the regular method entry.
 481   //
 482   // Notes:
 483   // * In the G1 code we do not check whether we need to block for
 484   //   a safepoint. If G1 is enabled then we must execute the specialized
 485   //   code for Reference.get (except when the Reference object is null)
 486   //   so that we can log the value in the referent field with an SATB
 487   //   update buffer.
 488   //   If the code for the getfield template is modified so that the
 489   //   G1 pre-barrier code is executed when the current method is
 490   //   Reference.get() then going through the normal method entry
 491   //   will be fine.
 492   // * The G1 code can, however, check the receiver object (the instance
 493   //   of java.lang.Reference) and jump to the slow path if null. If the
 494   //   Reference object is null then we obviously cannot fetch the referent
 495   //   and so we don't need to call the G1 pre-barrier. Thus we can use the
 496   //   regular method entry code to generate the NPE.
 497   //
 498 
 499   address entry = __ pc();
 500 
 501   const int referent_offset = java_lang_ref_Reference::referent_offset();
 502 
 503   Label slow_path;
 504 
 505   // Debugging not possible, so can't use __ skip_if_jvmti_mode(slow_path, GR31_SCRATCH);
 506 
 507   // In the G1 code we don't check if we need to reach a safepoint. We
 508   // continue and the thread will safepoint at the next bytecode dispatch.
 509 
 510   // If the receiver is null then it is OK to jump to the slow path.
 511   __ ld(R3_RET, Interpreter::stackElementSize, R15_esp); // get receiver
 512 
 513   // Check if receiver == nullptr and go the slow path.
 514   __ cmpdi(CR0, R3_RET, 0);
 515   __ beq(CR0, slow_path);
 516 
 517   __ load_heap_oop(R3_RET, referent_offset, R3_RET,
 518                    /* non-volatile temp */ R31, R11_scratch1,
 519                    MacroAssembler::PRESERVATION_FRAME_LR,
 520                    ON_WEAK_OOP_REF);
 521 
 522   // Generate the G1 pre-barrier code to log the value of
 523   // the referent field in an SATB buffer. Note with
 524   // these parameters the pre-barrier does not generate
 525   // the load of the previous value.
 526 
 527   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
 528   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
 529 
 530   __ blr();
 531 
 532   __ bind(slow_path);
 533   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
 534   return entry;
 535 }
 536 
 537 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
 538   address entry = __ pc();
 539 
 540   // Expression stack must be empty before entering the VM if an
 541   // exception happened.
 542   __ empty_expression_stack();
 543   // Throw exception.
 544   __ call_VM(noreg,
 545              CAST_FROM_FN_PTR(address,
 546                               InterpreterRuntime::throw_StackOverflowError));
 547   return entry;
 548 }
 549 
 550 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler() {
 551   address entry = __ pc();
 552   __ empty_expression_stack();
 553   // R4_ARG2 already contains the array.
 554   // Index is in R17_tos.
 555   __ mr(R5_ARG3, R17_tos);
 556   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException), R4_ARG2, R5_ARG3);
 557   return entry;
 558 }
 559 
 560 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 561   address entry = __ pc();
 562   // Expression stack must be empty before entering the VM if an
 563   // exception happened.
 564   __ empty_expression_stack();
 565 
 566   // Load exception object.
 567   // Thread will be loaded to R3_ARG1.
 568   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException), R17_tos);
 569 #ifdef ASSERT
 570   // Above call must not return here since exception pending.
 571   __ should_not_reach_here();
 572 #endif
 573   return entry;
 574 }
 575 
 576 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 577   address entry = __ pc();
 578   //__ untested("generate_exception_handler_common");
 579   Register Rexception = R17_tos;
 580 
 581   // Expression stack must be empty before entering the VM if an exception happened.
 582   __ empty_expression_stack();
 583 
 584   __ load_const_optimized(R4_ARG2, (address) name, R11_scratch1);
 585   if (pass_oop) {
 586     __ mr(R5_ARG3, Rexception);
 587     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception));
 588   } else {
 589     __ load_const_optimized(R5_ARG3, (address) message, R11_scratch1);
 590     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception));
 591   }
 592 
 593   // Throw exception.
 594   __ mr(R3_ARG1, Rexception);
 595   __ load_const_optimized(R11_scratch1, Interpreter::throw_exception_entry(), R12_scratch2);
 596   __ mtctr(R11_scratch1);
 597   __ bctr();
 598 
 599   return entry;
 600 }
 601 
 602 // This entry is returned to when a call returns to the interpreter.
 603 // When we arrive here, we expect that the callee stack frame is already popped.
 604 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 605   address entry = __ pc();
 606 
 607   // Move the value out of the return register back to the TOS cache of current frame.
 608   switch (state) {
 609     case ltos:
 610     case btos:
 611     case ztos:
 612     case ctos:
 613     case stos:
 614     case atos:
 615     case itos: __ mr(R17_tos, R3_RET); break;   // RET -> TOS cache
 616     case ftos:
 617     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 618     case vtos: break;                           // Nothing to do, this was a void return.
 619     default  : ShouldNotReachHere();
 620   }
 621 
 622   __ restore_interpreter_state(R11_scratch1, false /*bcp_and_mdx_only*/, true /*restore_top_frame_sp*/);
 623 
 624   // Compiled code destroys templateTableBase, reload.
 625   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
 626 
 627   if (state == atos) {
 628     __ profile_return_type(R3_RET, R11_scratch1, R12_scratch2);
 629   }
 630 
 631   const Register cache = R11_scratch1;
 632   const Register size  = R12_scratch2;
 633   if (index_size == sizeof(u4)) {
 634     __ load_resolved_indy_entry(cache, size /* tmp */);
 635     __ lhz(size, in_bytes(ResolvedIndyEntry::num_parameters_offset()), cache);
 636   } else {
 637     assert(index_size == sizeof(u2), "Can only be u2");
 638     __ load_method_entry(cache, size /* tmp */);
 639     __ lhz(size, in_bytes(ResolvedMethodEntry::num_parameters_offset()), cache);
 640   }
 641   __ sldi(size, size, Interpreter::logStackElementSize);
 642   __ add(R15_esp, R15_esp, size);
 643 
 644  __ check_and_handle_popframe(R11_scratch1);
 645  __ check_and_handle_earlyret(R11_scratch1);
 646 
 647   __ dispatch_next(state, step);
 648   return entry;
 649 }
 650 
 651 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step, address continuation) {
 652   address entry = __ pc();
 653   // If state != vtos, we're returning from a native method, which put it's result
 654   // into the result register. So move the value out of the return register back
 655   // to the TOS cache of current frame.
 656 
 657   switch (state) {
 658     case ltos:
 659     case btos:
 660     case ztos:
 661     case ctos:
 662     case stos:
 663     case atos:
 664     case itos: __ mr(R17_tos, R3_RET); break;   // GR_RET -> TOS cache
 665     case ftos:
 666     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 667     case vtos: break;                           // Nothing to do, this was a void return.
 668     default  : ShouldNotReachHere();
 669   }
 670 
 671   // Load LcpoolCache @@@ should be already set!
 672   __ get_constant_pool_cache(R27_constPoolCache);
 673 
 674   // Handle a pending exception, fall through if none.
 675   __ check_and_forward_exception(R11_scratch1, R12_scratch2);
 676 
 677   // Start executing bytecodes.
 678   if (continuation == nullptr) {
 679     __ dispatch_next(state, step);
 680   } else {
 681     __ jump_to_entry(continuation, R11_scratch1);
 682   }
 683 
 684   return entry;
 685 }
 686 
 687 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 688   address entry = __ pc();
 689 
 690   __ push(state);
 691   __ push_cont_fastpath();
 692   __ call_VM(noreg, runtime_entry);
 693   __ pop_cont_fastpath();
 694   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 695 
 696   return entry;
 697 }
 698 
 699 address TemplateInterpreterGenerator::generate_cont_resume_interpreter_adapter() {
 700   if (!Continuations::enabled()) return nullptr;
 701   address start = __ pc();
 702 
 703   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
 704   __ restore_interpreter_state(R11_scratch1, false, true /*restore_top_frame_sp*/);
 705   // Restore registers that are preserved across vthread preemption
 706   assert(__ nonvolatile_accross_vthread_preemtion(R31) && __ nonvolatile_accross_vthread_preemtion(R24), "");
 707   __ ld(R3_ARG1, _abi0(callers_sp), R1_SP); // load FP
 708   __ ld(R31, _ijava_state_neg(lresult), R3_ARG1);
 709   __ ld(R24, _ijava_state_neg(fresult), R3_ARG1);
 710   __ blr();
 711 
 712   return start;
 713 }
 714 
 715 // Helpers for commoning out cases in the various type of method entries.
 716 
 717 // Increment invocation count & check for overflow.
 718 //
 719 // Note: checking for negative value instead of overflow
 720 //       so we have a 'sticky' overflow test.
 721 //
 722 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow) {
 723   // Note: In tiered we increment either counters in method or in MDO depending if we're profiling or not.
 724   Register Rscratch1   = R11_scratch1;
 725   Register Rscratch2   = R12_scratch2;
 726   Register R3_counters = R3_ARG1;
 727   Label done;
 728 
 729   const int increment = InvocationCounter::count_increment;
 730   Label no_mdo;
 731   if (ProfileInterpreter) {
 732     const Register Rmdo = R3_counters;
 733     __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
 734     __ cmpdi(CR0, Rmdo, 0);
 735     __ beq(CR0, no_mdo);
 736 
 737     // Increment invocation counter in the MDO.
 738     const int mdo_ic_offs = in_bytes(MethodData::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 739     __ lwz(Rscratch2, mdo_ic_offs, Rmdo);
 740     __ lwz(Rscratch1, in_bytes(MethodData::invoke_mask_offset()), Rmdo);
 741     __ addi(Rscratch2, Rscratch2, increment);
 742     __ stw(Rscratch2, mdo_ic_offs, Rmdo);
 743     __ and_(Rscratch1, Rscratch2, Rscratch1);
 744     __ bne(CR0, done);
 745     __ b(*overflow);
 746   }
 747 
 748   // Increment counter in MethodCounters*.
 749   const int mo_ic_offs = in_bytes(MethodCounters::invocation_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 750   __ bind(no_mdo);
 751   __ get_method_counters(R19_method, R3_counters, done);
 752   __ lwz(Rscratch2, mo_ic_offs, R3_counters);
 753   __ lwz(Rscratch1, in_bytes(MethodCounters::invoke_mask_offset()), R3_counters);
 754   __ addi(Rscratch2, Rscratch2, increment);
 755   __ stw(Rscratch2, mo_ic_offs, R3_counters);
 756   __ and_(Rscratch1, Rscratch2, Rscratch1);
 757   __ beq(CR0, *overflow);
 758 
 759   __ bind(done);
 760 }
 761 
 762 // Generate code to initiate compilation on invocation counter overflow.
 763 void TemplateInterpreterGenerator::generate_counter_overflow(Label& continue_entry) {
 764   // Generate code to initiate compilation on the counter overflow.
 765 
 766   // InterpreterRuntime::frequency_counter_overflow takes one arguments,
 767   // which indicates if the counter overflow occurs at a backwards branch (null bcp)
 768   // We pass zero in.
 769   // The call returns the address of the verified entry point for the method or null
 770   // if the compilation did not complete (either went background or bailed out).
 771   //
 772   // Unlike the C++ interpreter above: Check exceptions!
 773   // Assumption: Caller must set the flag "do_not_unlock_if_sychronized" if the monitor of a sync'ed
 774   // method has not yet been created. Thus, no unlocking of a non-existing monitor can occur.
 775 
 776   __ li(R4_ARG2, 0);
 777   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
 778 
 779   // Returns verified_entry_point or null.
 780   // We ignore it in any case.
 781   __ b(continue_entry);
 782 }
 783 
 784 // See if we've got enough room on the stack for locals plus overhead below
 785 // JavaThread::stack_overflow_limit(). If not, throw a StackOverflowError
 786 // without going through the signal handler, i.e., reserved and yellow zones
 787 // will not be made usable. The shadow zone must suffice to handle the
 788 // overflow.
 789 //
 790 // Kills Rmem_frame_size, Rscratch1.
 791 void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rmem_frame_size, Register Rscratch1) {
 792   Label done;
 793   assert_different_registers(Rmem_frame_size, Rscratch1);
 794 
 795   BLOCK_COMMENT("stack_overflow_check_with_compare {");
 796   __ sub(Rmem_frame_size, R1_SP, Rmem_frame_size);
 797   __ ld(Rscratch1, thread_(stack_overflow_limit));
 798   __ cmpld(CR0/*is_stack_overflow*/, Rmem_frame_size, Rscratch1);
 799   __ bgt(CR0/*is_stack_overflow*/, done);
 800 
 801   // The stack overflows. Load target address of the runtime stub and call it.
 802   assert(SharedRuntime::throw_StackOverflowError_entry() != nullptr, "generated in wrong order");
 803   __ load_const_optimized(Rscratch1, (SharedRuntime::throw_StackOverflowError_entry()), R0);
 804   __ mtctr(Rscratch1);
 805   // Restore caller_sp (c2i adapter may exist, but no shrinking of interpreted caller frame).
 806 #ifdef ASSERT
 807   Label frame_not_shrunk;
 808   __ cmpld(CR0, R1_SP, R21_sender_SP);
 809   __ ble(CR0, frame_not_shrunk);
 810   __ stop("frame shrunk");
 811   __ bind(frame_not_shrunk);
 812   __ ld(Rscratch1, 0, R1_SP);
 813   __ ld(R0, 0, R21_sender_SP);
 814   __ cmpd(CR0, R0, Rscratch1);
 815   __ asm_assert_eq("backlink");
 816 #endif // ASSERT
 817   __ mr(R1_SP, R21_sender_SP);
 818   __ bctr();
 819 
 820   __ align(32, 12);
 821   __ bind(done);
 822   BLOCK_COMMENT("} stack_overflow_check_with_compare");
 823 }
 824 
 825 // Lock the current method, interpreter register window must be set up!
 826 void TemplateInterpreterGenerator::lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded) {
 827   const Register Robj_to_lock = Rscratch2;
 828 
 829   {
 830     if (!flags_preloaded) {
 831       __ lhz(Rflags, method_(access_flags));
 832     }
 833 
 834 #ifdef ASSERT
 835     // Check if methods needs synchronization.
 836     {
 837       Label Lok;
 838       __ testbitdi(CR0, R0, Rflags, JVM_ACC_SYNCHRONIZED_BIT);
 839       __ btrue(CR0,Lok);
 840       __ stop("method doesn't need synchronization");
 841       __ bind(Lok);
 842     }
 843 #endif // ASSERT
 844   }
 845 
 846   // Get synchronization object to Rscratch2.
 847   {
 848     Label Lstatic;
 849     Label Ldone;
 850 
 851     __ testbitdi(CR0, R0, Rflags, JVM_ACC_STATIC_BIT);
 852     __ btrue(CR0, Lstatic);
 853 
 854     // Non-static case: load receiver obj from stack and we're done.
 855     __ ld(Robj_to_lock, R18_locals);
 856     __ b(Ldone);
 857 
 858     __ bind(Lstatic); // Static case: Lock the java mirror
 859     // Load mirror from interpreter frame.
 860     __ ld(Robj_to_lock, _abi0(callers_sp), R1_SP);
 861     __ ld(Robj_to_lock, _ijava_state_neg(mirror), Robj_to_lock);
 862 
 863     __ bind(Ldone);
 864     __ verify_oop(Robj_to_lock);
 865   }
 866 
 867   // Got the oop to lock => execute!
 868   __ add_monitor_to_stack(true, Rscratch1, R0);
 869 
 870   __ std(Robj_to_lock, in_bytes(BasicObjectLock::obj_offset()), R26_monitor);
 871   __ lock_object(R26_monitor, Robj_to_lock);
 872 }
 873 
 874 // Generate a fixed interpreter frame for pure interpreter
 875 // and I2N native transition frames.
 876 //
 877 // Before (stack grows downwards):
 878 //
 879 //         |  ...         |
 880 //         |------------- |
 881 //         |  java arg0   |
 882 //         |  ...         |
 883 //         |  java argn   |
 884 //         |              |   <-   R15_esp
 885 //         |              |
 886 //         |--------------|
 887 //         | abi_112      |
 888 //         |              |   <-   R1_SP
 889 //         |==============|
 890 //
 891 //
 892 // After:
 893 //
 894 //         |  ...         |
 895 //         |  java arg0   |<-   R18_locals
 896 //         |  ...         |
 897 //         |  java argn   |
 898 //         |--------------|
 899 //         |              |
 900 //         |  java locals |
 901 //         |              |
 902 //         |--------------|
 903 //         |  abi_48      |
 904 //         |==============|
 905 //         |              |
 906 //         |   istate     |
 907 //         |              |
 908 //         |--------------|
 909 //         |   monitor    |<-   R26_monitor
 910 //         |--------------|
 911 //         |              |<-   R15_esp
 912 //         | expression   |
 913 //         | stack        |
 914 //         |              |
 915 //         |--------------|
 916 //         |              |
 917 //         | abi_112      |<-   R1_SP
 918 //         |==============|
 919 //
 920 // The top most frame needs an abi space of 112 bytes. This space is needed,
 921 // since we call to c. The c function may spill their arguments to the caller
 922 // frame. When we call to java, we don't need these spill slots. In order to save
 923 // space on the stack, we resize the caller. However, java locals reside in
 924 // the caller frame and the frame has to be increased. The frame_size for the
 925 // current frame was calculated based on max_stack as size for the expression
 926 // stack. At the call, just a part of the expression stack might be used.
 927 // We don't want to waste this space and cut the frame back accordingly.
 928 // The resulting amount for resizing is calculated as follows:
 929 // resize =   (number_of_locals - number_of_arguments) * slot_size
 930 //          + (R1_SP - R15_esp) + 48
 931 //
 932 // The size for the callee frame is calculated:
 933 // framesize = 112 + max_stack + monitor + state_size
 934 //
 935 // maxstack:   Max number of slots on the expression stack, loaded from the method.
 936 // monitor:    We statically reserve room for one monitor object.
 937 // state_size: We save the current state of the interpreter to this area.
 938 //
 939 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals) {
 940   Register Rparent_frame_resize = R6_ARG4, // Frame will grow by this number of bytes.
 941            Rtop_frame_size      = R7_ARG5,
 942            Rconst_method        = R8_ARG6,
 943            Rconst_pool          = R9_ARG7,
 944            Rmirror              = R10_ARG8;
 945 
 946   assert_different_registers(Rsize_of_parameters, Rsize_of_locals, Rparent_frame_resize, Rtop_frame_size,
 947                              Rconst_method, Rconst_pool);
 948 
 949   __ ld(Rconst_method, method_(const));
 950   __ lhz(Rsize_of_parameters /* number of params */,
 951          in_bytes(ConstMethod::size_of_parameters_offset()), Rconst_method);
 952   if (native_call) {
 953     // If we're calling a native method, we reserve space for the worst-case signature
 954     // handler varargs vector, which is max(Argument::n_int_register_parameters_c, parameter_count+2).
 955     // We add two slots to the parameter_count, one for the jni
 956     // environment and one for a possible native mirror.
 957     Label skip_native_calculate_max_stack;
 958     __ addi(Rtop_frame_size, Rsize_of_parameters, 2);
 959     __ cmpwi(CR0, Rtop_frame_size, Argument::n_int_register_parameters_c);
 960     __ bge(CR0, skip_native_calculate_max_stack);
 961     __ li(Rtop_frame_size, Argument::n_int_register_parameters_c);
 962     __ bind(skip_native_calculate_max_stack);
 963     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 964     __ sldi(Rtop_frame_size, Rtop_frame_size, Interpreter::logStackElementSize);
 965     __ sub(Rparent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 966     assert(Rsize_of_locals == noreg, "Rsize_of_locals not initialized"); // Only relevant value is Rsize_of_parameters.
 967   } else {
 968     __ lhz(Rsize_of_locals /* number of params */, in_bytes(ConstMethod::size_of_locals_offset()), Rconst_method);
 969     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 970     __ sldi(Rsize_of_locals, Rsize_of_locals, Interpreter::logStackElementSize);
 971     __ lhz(Rtop_frame_size, in_bytes(ConstMethod::max_stack_offset()), Rconst_method);
 972     __ sub(R11_scratch1, Rsize_of_locals, Rsize_of_parameters); // >=0
 973     __ sub(Rparent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 974     __ sldi(Rtop_frame_size, Rtop_frame_size, Interpreter::logStackElementSize);
 975     __ add(Rparent_frame_resize, Rparent_frame_resize, R11_scratch1);
 976   }
 977 
 978   // Compute top frame size.
 979   __ addi(Rtop_frame_size, Rtop_frame_size, frame::top_ijava_frame_abi_size + frame::ijava_state_size);
 980 
 981   // Cut back area between esp and max_stack.
 982   __ addi(Rparent_frame_resize, Rparent_frame_resize, frame::parent_ijava_frame_abi_size - Interpreter::stackElementSize);
 983 
 984   __ round_to(Rtop_frame_size, frame::alignment_in_bytes);
 985   __ round_to(Rparent_frame_resize, frame::alignment_in_bytes);
 986   // Rparent_frame_resize = (locals-parameters) - (ESP-SP-ABI48) Rounded to frame alignment size.
 987   // Enlarge by locals-parameters (not in case of native_call), shrink by ESP-SP-ABI48.
 988 
 989   if (!native_call) {
 990     // Stack overflow check.
 991     // Native calls don't need the stack size check since they have no
 992     // expression stack and the arguments are already on the stack and
 993     // we only add a handful of words to the stack.
 994     __ add(R11_scratch1, Rparent_frame_resize, Rtop_frame_size);
 995     generate_stack_overflow_check(R11_scratch1, R12_scratch2);
 996   }
 997 
 998   // Set up interpreter state registers.
 999 
1000   __ add(R18_locals, R15_esp, Rsize_of_parameters);
1001   __ ld(Rconst_pool, in_bytes(ConstMethod::constants_offset()), Rconst_method);
1002   __ ld(R27_constPoolCache, ConstantPool::cache_offset(), Rconst_pool);
1003 
1004   // Set method data pointer.
1005   if (ProfileInterpreter) {
1006     Label zero_continue;
1007     __ ld(R28_mdx, method_(method_data));
1008     __ cmpdi(CR0, R28_mdx, 0);
1009     __ beq(CR0, zero_continue);
1010     __ addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
1011     __ bind(zero_continue);
1012   }
1013 
1014   if (native_call) {
1015     __ li(R14_bcp, 0); // Must initialize.
1016   } else {
1017     __ addi(R14_bcp, Rconst_method, in_bytes(ConstMethod::codes_offset()));
1018   }
1019 
1020   // Resize parent frame.
1021   __ mflr(R12_scratch2);
1022   __ neg(Rparent_frame_resize, Rparent_frame_resize);
1023   __ resize_frame(Rparent_frame_resize, R11_scratch1);
1024   __ std(R12_scratch2, _abi0(lr), R1_SP);
1025 
1026   // Get mirror and store it in the frame as GC root for this Method*.
1027   __ ld(Rmirror, ConstantPool::pool_holder_offset(), Rconst_pool);
1028   __ ld(Rmirror, in_bytes(Klass::java_mirror_offset()), Rmirror);
1029   __ resolve_oop_handle(Rmirror, R11_scratch1, R12_scratch2, MacroAssembler::PRESERVATION_FRAME_LR_GP_REGS);
1030 
1031   __ addi(R26_monitor, R1_SP, -frame::ijava_state_size);
1032   __ addi(R15_esp, R26_monitor, -Interpreter::stackElementSize);
1033 
1034   // Store values.
1035   __ std(R19_method, _ijava_state_neg(method), R1_SP);
1036   __ std(Rmirror, _ijava_state_neg(mirror), R1_SP);
1037   __ sub(R12_scratch2, R18_locals, R1_SP);
1038   __ srdi(R12_scratch2, R12_scratch2, Interpreter::logStackElementSize);
1039   // Store relativized R18_locals, see frame::interpreter_frame_locals().
1040   __ std(R12_scratch2, _ijava_state_neg(locals), R1_SP);
1041   __ std(R27_constPoolCache, _ijava_state_neg(cpoolCache), R1_SP);
1042 
1043   // Note: esp, bcp, monitor, mdx live in registers. Hence, the correct version can only
1044   // be found in the frame after save_interpreter_state is done. This is always true
1045   // for non-top frames. But when a signal occurs, dumping the top frame can go wrong,
1046   // because e.g. frame::interpreter_frame_bcp() will not access the correct value
1047   // (Enhanced Stack Trace).
1048   // The signal handler does not save the interpreter state into the frame.
1049 
1050   // We have to initialize some of these frame slots for native calls (accessed by GC).
1051   // Also initialize them for non-native calls for better tool support (even though
1052   // you may not get the most recent version as described above).
1053   __ li(R0, 0);
1054   __ li(R12_scratch2, -(frame::ijava_state_size / wordSize));
1055   __ std(R12_scratch2, _ijava_state_neg(monitors), R1_SP);
1056   __ std(R14_bcp, _ijava_state_neg(bcp), R1_SP);
1057   if (ProfileInterpreter) { __ std(R28_mdx, _ijava_state_neg(mdx), R1_SP); }
1058   __ sub(R12_scratch2, R15_esp, R1_SP);
1059   __ sradi(R12_scratch2, R12_scratch2, Interpreter::logStackElementSize);
1060   __ std(R12_scratch2, _ijava_state_neg(esp), R1_SP);
1061   __ std(R0, _ijava_state_neg(oop_tmp), R1_SP); // only used for native_call
1062 
1063   // Store sender's SP and this frame's top SP.
1064   __ std(R21_sender_SP, _ijava_state_neg(sender_sp), R1_SP);
1065   __ neg(R12_scratch2, Rtop_frame_size);
1066   __ sradi(R12_scratch2, R12_scratch2, Interpreter::logStackElementSize);
1067   // Store relativized top_frame_sp
1068   __ std(R12_scratch2, _ijava_state_neg(top_frame_sp), R1_SP);
1069 
1070   // Push top frame.
1071   __ push_frame(Rtop_frame_size, R11_scratch1);
1072 }
1073 
1074 // End of helpers
1075 
1076 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
1077 
1078   // Decide what to do: Use same platform specific instructions and runtime calls as compilers.
1079   bool use_instruction = false;
1080   address runtime_entry = nullptr;
1081   int num_args = 1;
1082   bool double_precision = true;
1083 
1084   // PPC64 specific:
1085   switch (kind) {
1086     case Interpreter::java_lang_math_sqrt: use_instruction = true; break;
1087     case Interpreter::java_lang_math_abs:  use_instruction = true; break;
1088     case Interpreter::java_lang_math_fmaF:
1089     case Interpreter::java_lang_math_fmaD: use_instruction = UseFMA; break;
1090     default: break; // Fall back to runtime call.
1091   }
1092 
1093   switch (kind) {
1094     case Interpreter::java_lang_math_sin  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dsin);   break;
1095     case Interpreter::java_lang_math_cos  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dcos);   break;
1096     case Interpreter::java_lang_math_tan  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dtan);   break;
1097     case Interpreter::java_lang_math_sinh : /* run interpreted */ break;
1098     case Interpreter::java_lang_math_tanh : /* run interpreted */ break;
1099     case Interpreter::java_lang_math_cbrt : /* run interpreted */ break;
1100     case Interpreter::java_lang_math_abs  : /* run interpreted */ break;
1101     case Interpreter::java_lang_math_sqrt : /* run interpreted */  break;
1102     case Interpreter::java_lang_math_log  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog);   break;
1103     case Interpreter::java_lang_math_log10: runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dlog10); break;
1104     case Interpreter::java_lang_math_pow  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dpow); num_args = 2; break;
1105     case Interpreter::java_lang_math_exp  : runtime_entry = CAST_FROM_FN_PTR(address, SharedRuntime::dexp);   break;
1106     case Interpreter::java_lang_math_fmaF : /* run interpreted */ num_args = 3; double_precision = false; break;
1107     case Interpreter::java_lang_math_fmaD : /* run interpreted */ num_args = 3; break;
1108     default: ShouldNotReachHere();
1109   }
1110 
1111   // Use normal entry if neither instruction nor runtime call is used.
1112   if (!use_instruction && runtime_entry == nullptr) return nullptr;
1113 
1114   address entry = __ pc();
1115 
1116   // Load arguments
1117   assert(num_args <= 13, "passed in registers");
1118   if (double_precision) {
1119     int offset = (2 * num_args - 1) * Interpreter::stackElementSize;
1120     for (int i = 0; i < num_args; ++i) {
1121       __ lfd(as_FloatRegister(F1_ARG1->encoding() + i), offset, R15_esp);
1122       offset -= 2 * Interpreter::stackElementSize;
1123     }
1124   } else {
1125     int offset = num_args * Interpreter::stackElementSize;
1126     for (int i = 0; i < num_args; ++i) {
1127       __ lfs(as_FloatRegister(F1_ARG1->encoding() + i), offset, R15_esp);
1128       offset -= Interpreter::stackElementSize;
1129     }
1130   }
1131 
1132   if (use_instruction) {
1133     switch (kind) {
1134       case Interpreter::java_lang_math_sqrt: __ fsqrt(F1_RET, F1);          break;
1135       case Interpreter::java_lang_math_abs:  __ fabs(F1_RET, F1);           break;
1136       case Interpreter::java_lang_math_fmaF: __ fmadds(F1_RET, F1, F2, F3); break;
1137       case Interpreter::java_lang_math_fmaD: __ fmadd(F1_RET, F1, F2, F3);  break;
1138       default: ShouldNotReachHere();
1139     }
1140   } else {
1141     // Comment: Can use tail call if the unextended frame is always C ABI compliant:
1142     //__ load_const_optimized(R12_scratch2, runtime_entry, R0);
1143     //__ call_c_and_return_to_caller(R12_scratch2);
1144 
1145     // Push a new C frame and save LR.
1146     __ save_LR(R0);
1147     __ push_frame_reg_args(0, R11_scratch1);
1148 
1149     __ call_VM_leaf(runtime_entry);
1150 
1151     // Pop the C frame and restore LR.
1152     __ pop_frame();
1153     __ restore_LR(R0);
1154   }
1155 
1156   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1157   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1158   __ blr();
1159 
1160   __ flush();
1161 
1162   return entry;
1163 }
1164 
1165 address TemplateInterpreterGenerator::generate_Float_floatToFloat16_entry() {
1166   if (!VM_Version::supports_float16()) return nullptr;
1167 
1168   address entry = __ pc();
1169 
1170   __ lfs(F1, Interpreter::stackElementSize, R15_esp);
1171   __ f2hf(R3_RET, F1, F0);
1172 
1173   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1174   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1175   __ blr();
1176 
1177   __ flush();
1178 
1179   return entry;
1180 }
1181 
1182 address TemplateInterpreterGenerator::generate_Float_float16ToFloat_entry() {
1183   if (!VM_Version::supports_float16()) return nullptr;
1184 
1185   address entry = __ pc();
1186 
1187   // Note: Could also use:
1188   //__ li(R3, Interpreter::stackElementSize);
1189   //__ lfiwax(F1_RET, R15_esp, R3); // short stored as 32 bit integer
1190   //__ xscvhpdp(F1_RET->to_vsr(), F1_RET->to_vsr());
1191   __ lwa(R3, Interpreter::stackElementSize, R15_esp);
1192   __ hf2f(F1_RET, R3);
1193 
1194   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1195   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1196   __ blr();
1197 
1198   __ flush();
1199 
1200   return entry;
1201 }
1202 
1203 void TemplateInterpreterGenerator::bang_stack_shadow_pages(bool native_call) {
1204   // Quick & dirty stack overflow checking: bang the stack & handle trap.
1205   // Note that we do the banging after the frame is setup, since the exception
1206   // handling code expects to find a valid interpreter frame on the stack.
1207   // Doing the banging earlier fails if the caller frame is not an interpreter
1208   // frame.
1209   // (Also, the exception throwing code expects to unlock any synchronized
1210   // method receiever, so do the banging after locking the receiver.)
1211 
1212   // Bang each page in the shadow zone. We can't assume it's been done for
1213   // an interpreter frame with greater than a page of locals, so each page
1214   // needs to be checked.  Only true for non-native.
1215   const size_t page_size = os::vm_page_size();
1216   const int n_shadow_pages = StackOverflow::stack_shadow_zone_size() / page_size;
1217   const int start_page = native_call ? n_shadow_pages : 1;
1218   BLOCK_COMMENT("bang_stack_shadow_pages:");
1219   for (int pages = start_page; pages <= n_shadow_pages; pages++) {
1220     __ bang_stack_with_offset(pages*page_size);
1221   }
1222 }
1223 
1224 // Interpreter stub for calling a native method. (asm interpreter)
1225 // This sets up a somewhat different looking stack for calling the
1226 // native method than the typical interpreter frame setup.
1227 //
1228 // On entry:
1229 //   R19_method    - method
1230 //   R16_thread    - JavaThread*
1231 //   R15_esp       - intptr_t* sender tos
1232 //
1233 //   abstract stack (grows up)
1234 //     [  IJava (caller of JNI callee)  ]  <-- ASP
1235 //        ...
1236 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized, bool runtime_upcalls) {
1237 
1238   address entry = __ pc();
1239 
1240   const bool inc_counter = (UseCompiler || CountCompiledCalls) && !PreloadOnly;
1241 
1242   // -----------------------------------------------------------------------------
1243   // Allocate a new frame that represents the native callee (i2n frame).
1244   // This is not a full-blown interpreter frame, but in particular, the
1245   // following registers are valid after this:
1246   // - R19_method
1247   // - R18_local (points to start of arguments to native function)
1248   //
1249   //   abstract stack (grows up)
1250   //     [  IJava (caller of JNI callee)  ]  <-- ASP
1251   //        ...
1252 
1253   const Register signature_handler_fd = R11_scratch1;
1254   const Register pending_exception    = R0;
1255   const Register result_handler_addr  = R31;
1256   const Register native_method_fd     = R12_scratch2; // preferred in MacroAssembler::branch_to
1257   const Register access_flags         = R24_tmp4;
1258   const Register active_handles       = R11_scratch1; // R26_monitor saved to state.
1259   const Register sync_state           = R12_scratch2;
1260   const Register sync_state_addr      = sync_state;   // Address is dead after use.
1261   const Register suspend_flags        = R11_scratch1;
1262 
1263   //=============================================================================
1264   // Allocate new frame and initialize interpreter state.
1265 
1266   Label exception_return;
1267   Label exception_return_sync_check;
1268   Label stack_overflow_return;
1269 
1270   Register size_of_parameters = R22_tmp2;
1271 
1272   generate_fixed_frame(true, size_of_parameters, noreg /* unused */);
1273 
1274   //=============================================================================
1275   // Increment invocation counter. On overflow, entry to JNI method
1276   // will be compiled.
1277   Label invocation_counter_overflow, continue_after_compile;
1278   if (inc_counter) {
1279     if (synchronized) {
1280       // Since at this point in the method invocation the exception handler
1281       // would try to exit the monitor of synchronized methods which hasn't
1282       // been entered yet, we set the thread local variable
1283       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1284       // runtime, exception handling i.e. unlock_if_synchronized_method will
1285       // check this thread local flag.
1286       // This flag has two effects, one is to force an unwind in the topmost
1287       // interpreter frame and not perform an unlock while doing so.
1288       __ li(R0, 1);
1289       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1290     }
1291     generate_counter_incr(&invocation_counter_overflow);
1292 
1293     BIND(continue_after_compile);
1294   }
1295 
1296   bang_stack_shadow_pages(true);
1297 
1298   if (inc_counter) {
1299     // Reset the _do_not_unlock_if_synchronized flag.
1300     if (synchronized) {
1301       __ li(R0, 0);
1302       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1303     }
1304   }
1305 
1306   // access_flags = method->access_flags();
1307   // Load access flags.
1308   assert(__ nonvolatile_accross_vthread_preemtion(access_flags),
1309          "access_flags not preserved");
1310   // Type check.
1311   assert(2 == sizeof(AccessFlags), "unexpected field size");
1312   __ lhz(access_flags, method_(access_flags));
1313 
1314   // We don't want to reload R19_method and access_flags after calls
1315   // to some helper functions.
1316   assert(R19_method->is_nonvolatile(),
1317          "R19_method must be a non-volatile register");
1318 
1319   // Check for synchronized methods. Must happen AFTER invocation counter
1320   // check, so method is not locked if counter overflows.
1321 
1322   if (synchronized) {
1323     lock_method(access_flags, R11_scratch1, R12_scratch2, true);
1324 
1325     // Update monitor in state.
1326     __ ld(R11_scratch1, 0, R1_SP);
1327     __ sub(R12_scratch2, R26_monitor, R11_scratch1);
1328     __ sradi(R12_scratch2, R12_scratch2, Interpreter::logStackElementSize);
1329     __ std(R12_scratch2, _ijava_state_neg(monitors), R11_scratch1);
1330   }
1331 
1332   // jvmti/jvmpi support
1333   __ notify_method_entry();
1334 
1335   //=============================================================================
1336   // Get and call the signature handler.
1337 
1338   __ ld(signature_handler_fd, method_(signature_handler));
1339   Label call_signature_handler;
1340 
1341   __ cmpdi(CR0, signature_handler_fd, 0);
1342   __ bne(CR0, call_signature_handler);
1343 
1344   // Method has never been called. Either generate a specialized
1345   // handler or point to the slow one.
1346   //
1347   // Pass parameter 'false' to avoid exception check in call_VM.
1348   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), R19_method, false);
1349 
1350   // Check for an exception while looking up the target method. If we
1351   // incurred one, bail.
1352   __ ld(pending_exception, thread_(pending_exception));
1353   __ cmpdi(CR0, pending_exception, 0);
1354   __ bne(CR0, exception_return_sync_check); // Has pending exception.
1355 
1356   // Reload signature handler, it may have been created/assigned in the meanwhile.
1357   __ ld(signature_handler_fd, method_(signature_handler));
1358   __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
1359 
1360   BIND(call_signature_handler);
1361 
1362   // Before we call the signature handler we push a new frame to
1363   // protect the interpreter frame volatile registers when we return
1364   // from jni but before we can get back to Java.
1365 
1366   // First set the frame anchor while the SP/FP registers are
1367   // convenient and the slow signature handler can use this same frame
1368   // anchor.
1369 
1370   bool support_vthread_preemption = Continuations::enabled();
1371 
1372   // We have a TOP_IJAVA_FRAME here, which belongs to us.
1373   Label last_java_pc;
1374   Label *resume_pc = support_vthread_preemption ? &last_java_pc : nullptr;
1375   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R3_ARG1/*tmp*/, resume_pc);
1376 
1377   // Now the interpreter frame (and its call chain) have been
1378   // invalidated and flushed. We are now protected against eager
1379   // being enabled in native code. Even if it goes eager the
1380   // registers will be reloaded as clean and we will invalidate after
1381   // the call so no spurious flush should be possible.
1382 
1383   // Call signature handler and pass locals address.
1384   //
1385   // Our signature handlers copy required arguments to the C stack
1386   // (outgoing C args), R3_ARG1 to R10_ARG8, and FARG1 to FARG13.
1387   __ mr(R3_ARG1, R18_locals);
1388 #if !defined(ABI_ELFv2)
1389   __ ld(signature_handler_fd, 0, signature_handler_fd);
1390 #endif
1391 
1392   __ call_stub(signature_handler_fd);
1393 
1394   assert(__ nonvolatile_accross_vthread_preemtion(result_handler_addr),
1395          "result_handler_addr not preserved");
1396   // Save across call to native method.
1397   __ mr(result_handler_addr, R3_RET);
1398   __ ld(R11_scratch1, _abi0(callers_sp), R1_SP); // load FP
1399 
1400   __ isync(); // Acquire signature handler before trying to fetch the native entry point and klass mirror.
1401 
1402   // Set up fixed parameters and call the native method.
1403   // If the method is static, get mirror into R4_ARG2.
1404   {
1405     Label method_is_not_static;
1406     // Access_flags is non-volatile and still, no need to restore it.
1407 
1408     // Restore access flags.
1409     __ testbitdi(CR0, R0, access_flags, JVM_ACC_STATIC_BIT);
1410     __ bfalse(CR0, method_is_not_static);
1411 
1412     // Load mirror from interpreter frame (FP in R11_scratch1)
1413     __ ld(R21_tmp1, _ijava_state_neg(mirror), R11_scratch1);
1414     // R4_ARG2 = &state->_oop_temp;
1415     __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
1416     __ std(R21_tmp1/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
1417     BIND(method_is_not_static);
1418   }
1419 
1420   // At this point, arguments have been copied off the stack into
1421   // their JNI positions. Oops are boxed in-place on the stack, with
1422   // handles copied to arguments. The result handler address is in a
1423   // register.
1424 
1425   // Pass JNIEnv address as first parameter.
1426   __ addir(R3_ARG1, thread_(jni_environment));
1427 
1428   // Load the native_method entry before we change the thread state.
1429   __ ld(native_method_fd, method_(native_function));
1430 
1431   //=============================================================================
1432   // Transition from _thread_in_Java to _thread_in_native. As soon as
1433   // we make this change the safepoint code needs to be certain that
1434   // the last Java frame we established is good. The pc in that frame
1435   // just needs to be near here not an actual return address.
1436 
1437   // We use release_store_fence to update values like the thread state, where
1438   // we don't want the current thread to continue until all our prior memory
1439   // accesses (including the new thread state) are visible to other threads.
1440   __ li(R0, _thread_in_native);
1441   __ release();
1442 
1443   // TODO PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
1444   __ stw(R0, thread_(thread_state));
1445 
1446   //=============================================================================
1447   // Call the native method. Argument registers must not have been
1448   // overwritten since "__ call_stub(signature_handler);" (except for
1449   // ARG1 and ARG2 for static methods).
1450 
1451   if (support_vthread_preemption) {
1452     // result_handler_addr is a nonvolatile register. Its value will be preserved across
1453     // the native call but only if the call isn't preempted. To preserve its value even
1454     // in the case of preemption we save it in the lresult slot. It is restored at
1455     // resume_pc if, and only if the call was preempted. This works because only
1456     // j.l.Object::wait calls are preempted which don't return a result.
1457     __ std(result_handler_addr, _ijava_state_neg(lresult), R11_scratch1);
1458   }
1459   __ push_cont_fastpath();
1460   __ call_c(native_method_fd);
1461   __ pop_cont_fastpath();
1462 
1463   __ li(R0, 0);
1464   __ ld(R11_scratch1, 0, R1_SP);
1465   __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1466   __ stfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1467   __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1); // reset
1468 
1469   // Note: C++ interpreter needs the following here:
1470   // The frame_manager_lr field, which we use for setting the last
1471   // java frame, gets overwritten by the signature handler. Restore
1472   // it now.
1473   //__ get_PC_trash_LR(R11_scratch1);
1474   //__ std(R11_scratch1, _top_ijava_frame_abi(frame_manager_lr), R1_SP);
1475 
1476   // Because of GC R19_method may no longer be valid.
1477 
1478   // Block, if necessary, before resuming in _thread_in_Java state.
1479   // In order for GC to work, don't clear the last_Java_sp until after
1480   // blocking.
1481 
1482   //=============================================================================
1483   // Switch thread to "native transition" state before reading the
1484   // synchronization state. This additional state is necessary
1485   // because reading and testing the synchronization state is not
1486   // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
1487   // in _thread_in_native state, loads _not_synchronized and is
1488   // preempted. VM thread changes sync state to synchronizing and
1489   // suspends threads for GC. Thread A is resumed to finish this
1490   // native method, but doesn't block here since it didn't see any
1491   // synchronization in progress, and escapes.
1492 
1493   // We use release_store_fence to update values like the thread state, where
1494   // we don't want the current thread to continue until all our prior memory
1495   // accesses (including the new thread state) are visible to other threads.
1496   __ li(R0/*thread_state*/, _thread_in_native_trans);
1497   __ release();
1498   __ stw(R0/*thread_state*/, thread_(thread_state));
1499   if (!UseSystemMemoryBarrier) {
1500     __ fence();
1501   }
1502 
1503   // Now before we return to java we must look for a current safepoint
1504   // (a new safepoint can not start since we entered native_trans).
1505   // We must check here because a current safepoint could be modifying
1506   // the callers registers right this moment.
1507 
1508   // Acquire isn't strictly necessary here because of the fence, but
1509   // sync_state is declared to be volatile, so we do it anyway
1510   // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
1511 
1512   Label do_safepoint, sync_check_done;
1513   // No synchronization in progress nor yet synchronized.
1514   __ safepoint_poll(do_safepoint, sync_state, true /* at_return */, false /* in_nmethod */);
1515 
1516   // Not suspended.
1517   // TODO PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
1518   __ lwz(suspend_flags, thread_(suspend_flags));
1519   __ cmpwi(CR1, suspend_flags, 0);
1520   __ beq(CR1, sync_check_done);
1521 
1522   __ bind(do_safepoint);
1523   __ isync();
1524   // Block. We do the call directly and leave the current
1525   // last_Java_frame setup undisturbed. We must save any possible
1526   // native result across the call. No oop is present.
1527 
1528   __ mr(R3_ARG1, R16_thread);
1529   __ call_c(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans));
1530 
1531   __ bind(sync_check_done);
1532 
1533   //=============================================================================
1534   // <<<<<< Back in Interpreter Frame >>>>>
1535 
1536   // We are in thread_in_native_trans here and back in the normal
1537   // interpreter frame. We don't have to do anything special about
1538   // safepoints and we can switch to Java mode anytime we are ready.
1539 
1540   // Note: frame::interpreter_frame_result has a dependency on how the
1541   // method result is saved across the call to post_method_exit. For
1542   // native methods it assumes that the non-FPU/non-void result is
1543   // saved in _native_lresult and a FPU result in _native_fresult. If
1544   // this changes then the interpreter_frame_result implementation
1545   // will need to be updated too.
1546 
1547   // On PPC64, we have stored the result directly after the native call.
1548 
1549   //=============================================================================
1550   // Back in Java
1551 
1552   // We use release_store_fence to update values like the thread state, where
1553   // we don't want the current thread to continue until all our prior memory
1554   // accesses (including the new thread state) are visible to other threads.
1555   __ li(R0/*thread_state*/, _thread_in_Java);
1556   __ lwsync(); // Acquire safepoint and suspend state, release thread state.
1557   __ stw(R0/*thread_state*/, thread_(thread_state));
1558 
1559   if (support_vthread_preemption) {
1560     // Check preemption for Object.wait()
1561     Label not_preempted;
1562     __ ld(R0, in_bytes(JavaThread::preempt_alternate_return_offset()), R16_thread);
1563     __ cmpdi(CR0, R0, 0);
1564     __ beq(CR0, not_preempted);
1565     __ mtlr(R0);
1566     __ li(R0, 0);
1567     __ std(R0, in_bytes(JavaThread::preempt_alternate_return_offset()), R16_thread);
1568     __ blr();
1569 
1570     // Execution will be resumed here when the vthread becomes runnable again.
1571     __ bind(*resume_pc);
1572     __ restore_after_resume(R11_scratch1 /* fp */);
1573     // We saved the result handler before the call
1574     __ ld(result_handler_addr, _ijava_state_neg(lresult), R11_scratch1);
1575 #ifdef ASSERT
1576     // Clobber result slots. Only native methods returning void can be preemted currently.
1577     __ load_const(R3_RET, UCONST64(0xbad01001));
1578     __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1579     __ std(R3_RET, _ijava_state_neg(fresult), R11_scratch1);
1580     // reset_last_Java_frame() below asserts that a last java sp is set
1581     __ asm_assert_mem8_is_zero(in_bytes(JavaThread::last_Java_sp_offset()),
1582         R16_thread, FILE_AND_LINE ": Last java sp should not be set when resuming");
1583     __ std(R3_RET, in_bytes(JavaThread::last_Java_sp_offset()), R16_thread);
1584 #endif
1585     __ bind(not_preempted);
1586   }
1587 
1588   if (CheckJNICalls) {
1589     // clear_pending_jni_exception_check
1590     __ load_const_optimized(R0, 0L);
1591     __ st_ptr(R0, JavaThread::pending_jni_exception_check_fn_offset(), R16_thread);
1592   }
1593 
1594   #if INCLUDE_JFR
1595   __ enter_jfr_critical_section();
1596 
1597   // This poll test is to uphold the invariant that a JFR sampled frame
1598   // must not return to its caller without a prior safepoint poll check.
1599   // The earlier poll check in this routine is insufficient for this purpose
1600   // because the thread has transitioned back to Java.
1601 
1602   Label slow_path, fast_path;
1603   __ safepoint_poll(slow_path, R11_scratch1, true /* at_return */, false /* in_nmethod */);
1604   __ b(fast_path);
1605   __ bind(slow_path);
1606   __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::at_unwind), R16_thread);
1607   __ align(32);
1608   __ bind(fast_path);
1609 
1610 #endif // INCLUDE_JFR
1611 
1612   __ reset_last_Java_frame();
1613 
1614   // Jvmdi/jvmpi support. Whether we've got an exception pending or
1615   // not, and whether unlocking throws an exception or not, we notify
1616   // on native method exit. If we do have an exception, we'll end up
1617   // in the caller's context to handle it, so if we don't do the
1618   // notify here, we'll drop it on the floor.
1619   __ notify_method_exit(true/*native method*/,
1620                         ilgl /*illegal state (not used for native methods)*/,
1621                         InterpreterMacroAssembler::NotifyJVMTI,
1622                         false /*check_exceptions*/);
1623 
1624   //=============================================================================
1625   // Handle exceptions
1626 
1627   if (synchronized) {
1628     __ unlock_object(R26_monitor); // Can also unlock methods.
1629   }
1630 
1631   // Reset active handles after returning from native.
1632   // thread->active_handles()->clear();
1633   __ ld(active_handles, thread_(active_handles));
1634   // TODO PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
1635   __ li(R0, 0);
1636   __ stw(R0, in_bytes(JNIHandleBlock::top_offset()), active_handles);
1637 
1638   Label exception_return_sync_check_already_unlocked;
1639   __ ld(R0/*pending_exception*/, thread_(pending_exception));
1640   __ cmpdi(CR0, R0/*pending_exception*/, 0);
1641   __ bne(CR0, exception_return_sync_check_already_unlocked);
1642 
1643   //-----------------------------------------------------------------------------
1644   // No exception pending.
1645 
1646   // Move native method result back into proper registers and return.
1647   // Invoke result handler (may unbox/promote).
1648   __ ld(R11_scratch1, 0, R1_SP);
1649   __ ld(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1650   __ lfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1651   __ call_stub(result_handler_addr);
1652 
1653   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R12_scratch2, R11_scratch1, R0);
1654   JFR_ONLY(__ leave_jfr_critical_section();)
1655 
1656   // Must use the return pc which was loaded from the caller's frame
1657   // as the VM uses return-pc-patching for deoptimization.
1658   __ mtlr(R12_scratch2);
1659   __ blr();
1660 
1661   //-----------------------------------------------------------------------------
1662   // An exception is pending. We call into the runtime only if the
1663   // caller was not interpreted. If it was interpreted the
1664   // interpreter will do the correct thing. If it isn't interpreted
1665   // (call stub/compiled code) we will change our return and continue.
1666 
1667   BIND(exception_return_sync_check);
1668 
1669   if (synchronized) {
1670     __ unlock_object(R26_monitor); // Can also unlock methods.
1671   }
1672   BIND(exception_return_sync_check_already_unlocked);
1673 
1674   const Register return_pc = R31;
1675 
1676   __ ld(return_pc, 0, R1_SP);
1677   __ ld(return_pc, _abi0(lr), return_pc);
1678 
1679   // Get the address of the exception handler.
1680   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1681                   R16_thread,
1682                   return_pc /* return pc */);
1683   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, noreg, R11_scratch1, R12_scratch2);
1684 
1685   // Load the PC of the exception handler into LR.
1686   __ mtlr(R3_RET);
1687 
1688   // Load exception into R3_ARG1 and clear pending exception in thread.
1689   __ ld(R3_ARG1/*exception*/, thread_(pending_exception));
1690   __ li(R4_ARG2, 0);
1691   __ std(R4_ARG2, thread_(pending_exception));
1692 
1693   // Load the original return pc into R4_ARG2.
1694   __ mr(R4_ARG2/*issuing_pc*/, return_pc);
1695 
1696   // Return to exception handler.
1697   __ blr();
1698 
1699   //=============================================================================
1700   // Counter overflow.
1701 
1702   if (inc_counter) {
1703     // Handle invocation counter overflow.
1704     __ bind(invocation_counter_overflow);
1705 
1706     generate_counter_overflow(continue_after_compile);
1707   }
1708 
1709   return entry;
1710 }
1711 
1712 // Generic interpreted method entry to (asm) interpreter.
1713 //
1714 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized, bool runtime_upcalls) {
1715   bool inc_counter = (UseCompiler || CountCompiledCalls) && !PreloadOnly;
1716   address entry = __ pc();
1717   // Generate the code to allocate the interpreter stack frame.
1718   Register Rsize_of_parameters = R4_ARG2, // Written by generate_fixed_frame.
1719            Rsize_of_locals     = R5_ARG3; // Written by generate_fixed_frame.
1720 
1721   // Does also a stack check to assure this frame fits on the stack.
1722   generate_fixed_frame(false, Rsize_of_parameters, Rsize_of_locals);
1723 
1724   // --------------------------------------------------------------------------
1725   // Zero out non-parameter locals.
1726   // Note: *Always* zero out non-parameter locals as Sparc does. It's not
1727   // worth to ask the flag, just do it.
1728   Register Rslot_addr = R6_ARG4,
1729            Rnum       = R7_ARG5;
1730   Label Lno_locals, Lzero_loop;
1731 
1732   // Set up the zeroing loop.
1733   __ subf(Rnum, Rsize_of_parameters, Rsize_of_locals);
1734   __ subf(Rslot_addr, Rsize_of_parameters, R18_locals);
1735   __ srdi_(Rnum, Rnum, Interpreter::logStackElementSize);
1736   __ beq(CR0, Lno_locals);
1737   __ li(R0, 0);
1738   __ mtctr(Rnum);
1739 
1740   // The zero locals loop.
1741   __ bind(Lzero_loop);
1742   __ std(R0, 0, Rslot_addr);
1743   __ addi(Rslot_addr, Rslot_addr, -Interpreter::stackElementSize);
1744   __ bdnz(Lzero_loop);
1745 
1746   __ bind(Lno_locals);
1747 
1748   // --------------------------------------------------------------------------
1749   // Counter increment and overflow check.
1750   Label invocation_counter_overflow;
1751   Label continue_after_compile;
1752   if (inc_counter || ProfileInterpreter) {
1753 
1754     Register Rdo_not_unlock_if_synchronized_addr = R11_scratch1;
1755     if (synchronized) {
1756       // Since at this point in the method invocation the exception handler
1757       // would try to exit the monitor of synchronized methods which hasn't
1758       // been entered yet, we set the thread local variable
1759       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1760       // runtime, exception handling i.e. unlock_if_synchronized_method will
1761       // check this thread local flag.
1762       // This flag has two effects, one is to force an unwind in the topmost
1763       // interpreter frame and not perform an unlock while doing so.
1764       __ li(R0, 1);
1765       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1766     }
1767 
1768     // Argument and return type profiling.
1769     __ profile_parameters_type(R3_ARG1, R4_ARG2, R5_ARG3, R6_ARG4);
1770 
1771     // Increment invocation counter and check for overflow.
1772     if (inc_counter) {
1773       generate_counter_incr(&invocation_counter_overflow);
1774     }
1775 
1776     __ bind(continue_after_compile);
1777   }
1778 
1779   bang_stack_shadow_pages(false);
1780 
1781   if (inc_counter || ProfileInterpreter) {
1782     // Reset the _do_not_unlock_if_synchronized flag.
1783     if (synchronized) {
1784       __ li(R0, 0);
1785       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1786     }
1787   }
1788 
1789   // --------------------------------------------------------------------------
1790   // Locking of synchronized methods. Must happen AFTER invocation_counter
1791   // check and stack overflow check, so method is not locked if overflows.
1792   if (synchronized) {
1793     lock_method(R3_ARG1, R4_ARG2, R5_ARG3);
1794   }
1795 #ifdef ASSERT
1796   else {
1797     Label Lok;
1798     __ lhz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1799     __ andi_(R0, R0, JVM_ACC_SYNCHRONIZED);
1800     __ asm_assert_eq("method needs synchronization");
1801     __ bind(Lok);
1802   }
1803 #endif // ASSERT
1804 
1805   // --------------------------------------------------------------------------
1806   // JVMTI support
1807   __ notify_method_entry();
1808 
1809   // --------------------------------------------------------------------------
1810   // Start executing instructions.
1811   __ dispatch_next(vtos);
1812 
1813   // --------------------------------------------------------------------------
1814   if (inc_counter) {
1815     // Handle invocation counter overflow.
1816     __ bind(invocation_counter_overflow);
1817     generate_counter_overflow(continue_after_compile);
1818   }
1819   return entry;
1820 }
1821 
1822 // CRC32 Intrinsics.
1823 //
1824 // Contract on scratch and work registers.
1825 // =======================================
1826 //
1827 // On ppc, the register set {R2..R12} is available in the interpreter as scratch/work registers.
1828 // You should, however, keep in mind that {R3_ARG1..R10_ARG8} is the C-ABI argument register set.
1829 // You can't rely on these registers across calls.
1830 //
1831 // The generators for CRC32_update and for CRC32_updateBytes use the
1832 // scratch/work register set internally, passing the work registers
1833 // as arguments to the MacroAssembler emitters as required.
1834 //
1835 // R3_ARG1..R6_ARG4 are preset to hold the incoming java arguments.
1836 // Their contents is not constant but may change according to the requirements
1837 // of the emitted code.
1838 //
1839 // All other registers from the scratch/work register set are used "internally"
1840 // and contain garbage (i.e. unpredictable values) once blr() is reached.
1841 // Basically, only R3_RET contains a defined value which is the function result.
1842 //
1843 /**
1844  * Method entry for static native methods:
1845  *   int java.util.zip.CRC32.update(int crc, int b)
1846  */
1847 address TemplateInterpreterGenerator::generate_CRC32_update_entry() {
1848   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1849   address start = __ pc();  // Remember stub start address (is rtn value).
1850   Label slow_path;
1851 
1852   // Safepoint check
1853   const Register sync_state = R11_scratch1;
1854   __ safepoint_poll(slow_path, sync_state, false /* at_return */, false /* in_nmethod */);
1855 
1856   // We don't generate local frame and don't align stack because
1857   // we not even call stub code (we generate the code inline)
1858   // and there is no safepoint on this path.
1859 
1860   // Load java parameters.
1861   // R15_esp is callers operand stack pointer, i.e. it points to the parameters.
1862   const Register argP    = R15_esp;
1863   const Register crc     = R3_ARG1;  // crc value
1864   const Register data    = R4_ARG2;
1865   const Register table   = R5_ARG3;  // address of crc32 table
1866 
1867   BLOCK_COMMENT("CRC32_update {");
1868 
1869   // Arguments are reversed on java expression stack
1870 #ifdef VM_LITTLE_ENDIAN
1871   int data_offs = 0+1*wordSize;      // (stack) address of byte value. Emitter expects address, not value.
1872                                      // Being passed as an int, the single byte is at offset +0.
1873 #else
1874   int data_offs = 3+1*wordSize;      // (stack) address of byte value. Emitter expects address, not value.
1875                                      // Being passed from java as an int, the single byte is at offset +3.
1876 #endif
1877   __ lwz(crc, 2*wordSize, argP);     // Current crc state, zero extend to 64 bit to have a clean register.
1878   __ lbz(data, data_offs, argP);     // Byte from buffer, zero-extended.
1879   __ load_const_optimized(table, StubRoutines::crc_table_addr(), R0);
1880   __ kernel_crc32_singleByteReg(crc, data, table, true);
1881 
1882   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1883   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1884   __ blr();
1885 
1886   // Generate a vanilla native entry as the slow path.
1887   BLOCK_COMMENT("} CRC32_update");
1888   BIND(slow_path);
1889   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), R11_scratch1);
1890   return start;
1891 }
1892 
1893 /**
1894  * Method entry for static native methods:
1895  *   int java.util.zip.CRC32.updateBytes(     int crc, byte[] b,  int off, int len)
1896  *   int java.util.zip.CRC32.updateByteBuffer(int crc, long* buf, int off, int len)
1897  */
1898 address TemplateInterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1899   assert(UseCRC32Intrinsics, "this intrinsic is not supported");
1900   address start = __ pc();  // Remember stub start address (is rtn value).
1901   Label slow_path;
1902 
1903   // Safepoint check
1904   const Register sync_state = R11_scratch1;
1905   __ safepoint_poll(slow_path, sync_state, false /* at_return */, false /* in_nmethod */);
1906 
1907   // We don't generate local frame and don't align stack because
1908   // we not even call stub code (we generate the code inline)
1909   // and there is no safepoint on this path.
1910 
1911   // Load parameters.
1912   // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1913   const Register argP    = R15_esp;
1914   const Register crc     = R3_ARG1;  // crc value
1915   const Register data    = R4_ARG2;  // address of java byte array
1916   const Register dataLen = R5_ARG3;  // source data len
1917   const Register tmp     = R11_scratch1;
1918 
1919   // Arguments are reversed on java expression stack.
1920   // Calculate address of start element.
1921   if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { // Used for "updateByteBuffer direct".
1922     BLOCK_COMMENT("CRC32_updateByteBuffer {");
1923     // crc     @ (SP + 5W) (32bit)
1924     // buf     @ (SP + 3W) (64bit ptr to long array)
1925     // off     @ (SP + 2W) (32bit)
1926     // dataLen @ (SP + 1W) (32bit)
1927     // data = buf + off
1928     __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1929     __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1930     __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1931     __ lwz( crc,     5*wordSize, argP);  // current crc state
1932     __ add( data, data, tmp);            // Add byte buffer offset.
1933   } else {                                                         // Used for "updateBytes update".
1934     BLOCK_COMMENT("CRC32_updateBytes {");
1935     // crc     @ (SP + 4W) (32bit)
1936     // buf     @ (SP + 3W) (64bit ptr to byte array)
1937     // off     @ (SP + 2W) (32bit)
1938     // dataLen @ (SP + 1W) (32bit)
1939     // data = buf + off + base_offset
1940     __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1941     __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1942     __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1943     __ add( data, data, tmp);            // add byte buffer offset
1944     __ lwz( crc,     4*wordSize, argP);  // current crc state
1945     __ addi(data, data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
1946   }
1947 
1948   __ crc32(crc, data, dataLen, R2, R6, R7, R8, R9, R10, R11, R12, false);
1949 
1950   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
1951   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
1952   __ blr();
1953 
1954   // Generate a vanilla native entry as the slow path.
1955   BLOCK_COMMENT("} CRC32_updateBytes(Buffer)");
1956   BIND(slow_path);
1957   __ jump_to_entry(Interpreter::entry_for_kind(Interpreter::native), R11_scratch1);
1958   return start;
1959 }
1960 
1961 
1962 /**
1963  * Method entry for intrinsic-candidate (non-native) methods:
1964  *   int java.util.zip.CRC32C.updateBytes(           int crc, byte[] b,  int off, int end)
1965  *   int java.util.zip.CRC32C.updateDirectByteBuffer(int crc, long* buf, int off, int end)
1966  * Unlike CRC32, CRC32C does not have any methods marked as native
1967  * CRC32C also uses an "end" variable instead of the length variable CRC32 uses
1968  **/
1969 address TemplateInterpreterGenerator::generate_CRC32C_updateBytes_entry(AbstractInterpreter::MethodKind kind) {
1970   assert(UseCRC32CIntrinsics, "this intrinsic is not supported");
1971   address start = __ pc();  // Remember stub start address (is rtn value).
1972 
1973   // We don't generate local frame and don't align stack because
1974   // we not even call stub code (we generate the code inline)
1975   // and there is no safepoint on this path.
1976 
1977   // Load parameters.
1978   // Z_esp is callers operand stack pointer, i.e. it points to the parameters.
1979   const Register argP    = R15_esp;
1980   const Register crc     = R3_ARG1;  // crc value
1981   const Register data    = R4_ARG2;  // address of java byte array
1982   const Register dataLen = R5_ARG3;  // source data len
1983   const Register tmp     = R11_scratch1;
1984 
1985   // Arguments are reversed on java expression stack.
1986   // Calculate address of start element.
1987   if (kind == Interpreter::java_util_zip_CRC32C_updateDirectByteBuffer) { // Used for "updateDirectByteBuffer".
1988     BLOCK_COMMENT("CRC32C_updateDirectByteBuffer {");
1989     // crc     @ (SP + 5W) (32bit)
1990     // buf     @ (SP + 3W) (64bit ptr to long array)
1991     // off     @ (SP + 2W) (32bit)
1992     // dataLen @ (SP + 1W) (32bit)
1993     // data = buf + off
1994     __ ld(  data,    3*wordSize, argP);  // start of byte buffer
1995     __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
1996     __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
1997     __ lwz( crc,     5*wordSize, argP);  // current crc state
1998     __ add( data, data, tmp);            // Add byte buffer offset.
1999     __ sub( dataLen, dataLen, tmp);      // (end_index - offset)
2000   } else {                                                         // Used for "updateBytes update".
2001     BLOCK_COMMENT("CRC32C_updateBytes {");
2002     // crc     @ (SP + 4W) (32bit)
2003     // buf     @ (SP + 3W) (64bit ptr to byte array)
2004     // off     @ (SP + 2W) (32bit)
2005     // dataLen @ (SP + 1W) (32bit)
2006     // data = buf + off + base_offset
2007     __ ld(  data,    3*wordSize, argP);  // start of byte buffer
2008     __ lwa( tmp,     2*wordSize, argP);  // byte buffer offset
2009     __ lwa( dataLen, 1*wordSize, argP);  // #bytes to process
2010     __ add( data, data, tmp);            // add byte buffer offset
2011     __ sub( dataLen, dataLen, tmp);      // (end_index - offset)
2012     __ lwz( crc,     4*wordSize, argP);  // current crc state
2013     __ addi(data, data, arrayOopDesc::base_offset_in_bytes(T_BYTE));
2014   }
2015 
2016   __ crc32(crc, data, dataLen, R2, R6, R7, R8, R9, R10, R11, R12, true);
2017 
2018   // Restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
2019   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
2020   __ blr();
2021 
2022   BLOCK_COMMENT("} CRC32C_update{Bytes|DirectByteBuffer}");
2023   return start;
2024 }
2025 
2026 address TemplateInterpreterGenerator::generate_currentThread() {
2027   address entry_point = __ pc();
2028 
2029   __ ld(R3_RET, JavaThread::vthread_offset(), R16_thread);
2030   __ resolve_oop_handle(R3_RET, R11_scratch1, R12_scratch2, MacroAssembler::PRESERVATION_FRAME_LR);
2031 
2032   // restore caller sp for c2i case (from compiled) and for resized sender frame (from interpreted).
2033   __ resize_frame_absolute(R21_sender_SP, R11_scratch1, R0);
2034   __ blr();
2035 
2036   return entry_point;
2037 }
2038 
2039 // =============================================================================
2040 // Exceptions
2041 
2042 void TemplateInterpreterGenerator::generate_throw_exception() {
2043   Register Rexception    = R17_tos,
2044            Rcontinuation = R3_RET;
2045 
2046   // --------------------------------------------------------------------------
2047   // Entry point if an method returns with a pending exception (rethrow).
2048   Interpreter::_rethrow_exception_entry = __ pc();
2049   {
2050     __ restore_interpreter_state(R11_scratch1, false /*bcp_and_mdx_only*/, true /*restore_top_frame_sp*/);
2051 
2052     // Compiled code destroys templateTableBase, reload.
2053     __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2054   }
2055 
2056   // Entry point if a interpreted method throws an exception (throw).
2057   Interpreter::_throw_exception_entry = __ pc();
2058   {
2059     __ mr(Rexception, R3_RET);
2060 
2061     __ verify_oop(Rexception);
2062 
2063     // Expression stack must be empty before entering the VM in case of an exception.
2064     __ empty_expression_stack();
2065     // Find exception handler address and preserve exception oop.
2066     // Call C routine to find handler and jump to it.
2067     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Rexception);
2068     __ mtctr(Rcontinuation);
2069     // Push exception for exception handler bytecodes.
2070     __ push_ptr(Rexception);
2071 
2072     // Jump to exception handler (may be remove activation entry!).
2073     __ bctr();
2074   }
2075 
2076   // If the exception is not handled in the current frame the frame is
2077   // removed and the exception is rethrown (i.e. exception
2078   // continuation is _rethrow_exception).
2079   //
2080   // Note: At this point the bci is still the bxi for the instruction
2081   // which caused the exception and the expression stack is
2082   // empty. Thus, for any VM calls at this point, GC will find a legal
2083   // oop map (with empty expression stack).
2084 
2085   // In current activation
2086   // tos: exception
2087   // bcp: exception bcp
2088 
2089   // --------------------------------------------------------------------------
2090   // JVMTI PopFrame support
2091 
2092   Interpreter::_remove_activation_preserving_args_entry = __ pc();
2093   {
2094     // Set the popframe_processing bit in popframe_condition indicating that we are
2095     // currently handling popframe, so that call_VMs that may happen later do not
2096     // trigger new popframe handling cycles.
2097     __ lwz(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2098     __ ori(R11_scratch1, R11_scratch1, JavaThread::popframe_processing_bit);
2099     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2100 
2101     // Empty the expression stack, as in normal exception handling.
2102     __ empty_expression_stack();
2103     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
2104 
2105     // Check to see whether we are returning to a deoptimized frame.
2106     // (The PopFrame call ensures that the caller of the popped frame is
2107     // either interpreted or compiled and deoptimizes it if compiled.)
2108     // Note that we don't compare the return PC against the
2109     // deoptimization blob's unpack entry because of the presence of
2110     // adapter frames in C2.
2111     Label Lcaller_not_deoptimized;
2112     Register return_pc = R3_ARG1;
2113     __ ld(return_pc, 0, R1_SP);
2114     __ ld(return_pc, _abi0(lr), return_pc);
2115     __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), return_pc);
2116     __ cmpdi(CR0, R3_RET, 0);
2117     __ bne(CR0, Lcaller_not_deoptimized);
2118 
2119     // The deoptimized case.
2120     // In this case, we can't call dispatch_next() after the frame is
2121     // popped, but instead must save the incoming arguments and restore
2122     // them after deoptimization has occurred.
2123     __ ld(R4_ARG2, in_bytes(Method::const_offset()), R19_method);
2124     __ lhz(R4_ARG2 /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), R4_ARG2);
2125     __ slwi(R4_ARG2, R4_ARG2, Interpreter::logStackElementSize);
2126     __ addi(R5_ARG3, R18_locals, Interpreter::stackElementSize);
2127     __ subf(R5_ARG3, R4_ARG2, R5_ARG3);
2128     // Save these arguments.
2129     __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), R16_thread, R4_ARG2, R5_ARG3);
2130 
2131     // Inform deoptimization that it is responsible for restoring these arguments.
2132     __ load_const_optimized(R11_scratch1, JavaThread::popframe_force_deopt_reexecution_bit);
2133     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2134 
2135     // Return from the current method into the deoptimization blob. Will eventually
2136     // end up in the deopt interpreter entry, deoptimization prepared everything that
2137     // we will reexecute the call that called us.
2138     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*reload return_pc*/ return_pc, R11_scratch1, R12_scratch2);
2139     __ mtlr(return_pc);
2140     __ pop_cont_fastpath();
2141     __ blr();
2142 
2143     // The non-deoptimized case.
2144     __ bind(Lcaller_not_deoptimized);
2145 
2146     // Clear the popframe condition flag.
2147     __ li(R0, 0);
2148     __ stw(R0, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
2149 
2150     // Get out of the current method and re-execute the call that called us.
2151     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
2152     __ pop_cont_fastpath();
2153     __ restore_interpreter_state(R11_scratch1, false /*bcp_and_mdx_only*/, true /*restore_top_frame_sp*/);
2154     if (ProfileInterpreter) {
2155       __ set_method_data_pointer_for_bcp();
2156       __ ld(R11_scratch1, 0, R1_SP);
2157       __ std(R28_mdx, _ijava_state_neg(mdx), R11_scratch1);
2158     }
2159 #if INCLUDE_JVMTI
2160     Label L_done;
2161 
2162     __ lbz(R11_scratch1, 0, R14_bcp);
2163     __ cmpwi(CR0, R11_scratch1, Bytecodes::_invokestatic);
2164     __ bne(CR0, L_done);
2165 
2166     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
2167     // Detect such a case in the InterpreterRuntime function and return the member name argument, or null.
2168     __ ld(R4_ARG2, 0, R18_locals);
2169     __ call_VM(R4_ARG2, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null), R4_ARG2, R19_method, R14_bcp);
2170 
2171     __ cmpdi(CR0, R4_ARG2, 0);
2172     __ beq(CR0, L_done);
2173     __ std(R4_ARG2, wordSize, R15_esp);
2174     __ bind(L_done);
2175 #endif // INCLUDE_JVMTI
2176     __ dispatch_next(vtos);
2177   }
2178   // end of JVMTI PopFrame support
2179 
2180   // --------------------------------------------------------------------------
2181   // Remove activation exception entry.
2182   // This is jumped to if an interpreted method can't handle an exception itself
2183   // (we come from the throw/rethrow exception entry above). We're going to call
2184   // into the VM to find the exception handler in the caller, pop the current
2185   // frame and return the handler we calculated.
2186   Interpreter::_remove_activation_entry = __ pc();
2187   {
2188     __ pop_ptr(Rexception);
2189     __ verify_oop(Rexception);
2190     __ std(Rexception, in_bytes(JavaThread::vm_result_oop_offset()), R16_thread);
2191 
2192     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, true);
2193     __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI, false);
2194 
2195     __ get_vm_result_oop(Rexception);
2196 
2197     // We are done with this activation frame; find out where to go next.
2198     // The continuation point will be an exception handler, which expects
2199     // the following registers set up:
2200     //
2201     // RET:  exception oop
2202     // ARG2: Issuing PC (see generate_exception_blob()), only used if the caller is compiled.
2203 
2204     Register return_pc = R31; // Needs to survive the runtime call.
2205     __ ld(return_pc, 0, R1_SP);
2206     __ ld(return_pc, _abi0(lr), return_pc);
2207     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), R16_thread, return_pc);
2208 
2209     // Remove the current activation.
2210     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
2211     __ pop_cont_fastpath();
2212 
2213     __ mr(R4_ARG2, return_pc);
2214     __ mtlr(R3_RET);
2215     __ mr(R3_RET, Rexception);
2216     __ blr();
2217   }
2218 }
2219 
2220 // JVMTI ForceEarlyReturn support.
2221 // Returns "in the middle" of a method with a "fake" return value.
2222 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
2223 
2224   Register Rscratch1 = R11_scratch1,
2225            Rscratch2 = R12_scratch2;
2226 
2227   address entry = __ pc();
2228   __ empty_expression_stack();
2229 
2230   __ load_earlyret_value(state, Rscratch1);
2231 
2232   __ ld(Rscratch1, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
2233   // Clear the earlyret state.
2234   __ li(R0, 0);
2235   __ stw(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rscratch1);
2236 
2237   __ remove_activation(state, false, false);
2238   // Copied from TemplateTable::_return.
2239   // Restoration of lr done by remove_activation.
2240   switch (state) {
2241     // Narrow result if state is itos but result type is smaller.
2242     case btos:
2243     case ztos:
2244     case ctos:
2245     case stos:
2246     case itos: __ narrow(R17_tos); /* fall through */
2247     case ltos:
2248     case atos: __ mr(R3_RET, R17_tos); break;
2249     case ftos:
2250     case dtos: __ fmr(F1_RET, F15_ftos); break;
2251     case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
2252                // to get visible before the reference to the object gets stored anywhere.
2253                __ membar(Assembler::StoreStore); break;
2254     default  : ShouldNotReachHere();
2255   }
2256   __ blr();
2257 
2258   return entry;
2259 } // end of ForceEarlyReturn support
2260 
2261 //-----------------------------------------------------------------------------
2262 // Helper for vtos entry point generation
2263 
2264 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
2265                                                          address& bep,
2266                                                          address& cep,
2267                                                          address& sep,
2268                                                          address& aep,
2269                                                          address& iep,
2270                                                          address& lep,
2271                                                          address& fep,
2272                                                          address& dep,
2273                                                          address& vep) {
2274   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
2275   Label L;
2276 
2277   aep = __ pc();  __ push_ptr();  __ b(L);
2278   fep = __ pc();  __ push_f();    __ b(L);
2279   dep = __ pc();  __ push_d();    __ b(L);
2280   lep = __ pc();  __ push_l();    __ b(L);
2281   __ align(32, 12, 24); // align L
2282   bep = cep = sep =
2283   iep = __ pc();  __ push_i();
2284   vep = __ pc();
2285   __ bind(L);
2286   generate_and_dispatch(t);
2287 }
2288 
2289 //-----------------------------------------------------------------------------
2290 
2291 // Non-product code
2292 #ifndef PRODUCT
2293 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
2294   //__ flush_bundle();
2295   address entry = __ pc();
2296 
2297   const char *bname = nullptr;
2298   uint tsize = 0;
2299   switch(state) {
2300   case ftos:
2301     bname = "trace_code_ftos {";
2302     tsize = 2;
2303     break;
2304   case btos:
2305     bname = "trace_code_btos {";
2306     tsize = 2;
2307     break;
2308   case ztos:
2309     bname = "trace_code_ztos {";
2310     tsize = 2;
2311     break;
2312   case ctos:
2313     bname = "trace_code_ctos {";
2314     tsize = 2;
2315     break;
2316   case stos:
2317     bname = "trace_code_stos {";
2318     tsize = 2;
2319     break;
2320   case itos:
2321     bname = "trace_code_itos {";
2322     tsize = 2;
2323     break;
2324   case ltos:
2325     bname = "trace_code_ltos {";
2326     tsize = 3;
2327     break;
2328   case atos:
2329     bname = "trace_code_atos {";
2330     tsize = 2;
2331     break;
2332   case vtos:
2333     // Note: In case of vtos, the topmost of stack value could be a int or doubl
2334     // In case of a double (2 slots) we won't see the 2nd stack value.
2335     // Maybe we simply should print the topmost 3 stack slots to cope with the problem.
2336     bname = "trace_code_vtos {";
2337     tsize = 2;
2338 
2339     break;
2340   case dtos:
2341     bname = "trace_code_dtos {";
2342     tsize = 3;
2343     break;
2344   default:
2345     ShouldNotReachHere();
2346   }
2347   BLOCK_COMMENT(bname);
2348 
2349   // Support short-cut for TraceBytecodesAt.
2350   // Don't call into the VM if we don't want to trace to speed up things.
2351   Label Lskip_vm_call;
2352   if (TraceBytecodesAt > 0) {
2353     int offs1 = __ load_const_optimized(R11_scratch1, (address) &TraceBytecodesAt, R0, true);
2354     int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
2355     __ ld(R11_scratch1, offs1, R11_scratch1);
2356     __ ld(R12_scratch2, offs2, R12_scratch2);
2357     __ cmpd(CR0, R12_scratch2, R11_scratch1);
2358     __ blt(CR0, Lskip_vm_call);
2359   }
2360 
2361   __ push(state);
2362   // Load 2 topmost expression stack values.
2363   __ ld(R6_ARG4, tsize*Interpreter::stackElementSize, R15_esp);
2364   __ ld(R5_ARG3, Interpreter::stackElementSize, R15_esp);
2365   __ mflr(R31);
2366   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::trace_bytecode), /* unused */ R4_ARG2, R5_ARG3, R6_ARG4, false);
2367   __ mtlr(R31);
2368   __ pop(state);
2369 
2370   if (TraceBytecodesAt > 0) {
2371     __ bind(Lskip_vm_call);
2372   }
2373   __ blr();
2374   BLOCK_COMMENT("} trace_code");
2375   return entry;
2376 }
2377 #endif //PRODUCT
2378 
2379 void TemplateInterpreterGenerator::count_bytecode() {
2380   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeCounter::_counter_value, R12_scratch2, true);
2381   __ ld(R12_scratch2, offs, R11_scratch1);
2382   __ addi(R12_scratch2, R12_scratch2, 1);
2383   __ std(R12_scratch2, offs, R11_scratch1);
2384 }
2385 
2386 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
2387   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeHistogram::_counters[t->bytecode()], R12_scratch2, true);
2388   __ lwz(R12_scratch2, offs, R11_scratch1);
2389   __ addi(R12_scratch2, R12_scratch2, 1);
2390   __ stw(R12_scratch2, offs, R11_scratch1);
2391 }
2392 
2393 #ifndef PRODUCT
2394 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
2395   const Register addr = R11_scratch1,
2396                  tmp  = R12_scratch2;
2397   // Get index, shift out old bytecode, bring in new bytecode, and store it.
2398   // _index = (_index >> log2_number_of_codes) |
2399   //          (bytecode << log2_number_of_codes);
2400   int offs1 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_index, tmp, true);
2401   __ lwz(tmp, offs1, addr);
2402   __ srwi(tmp, tmp, BytecodePairHistogram::log2_number_of_codes);
2403   __ ori(tmp, tmp, ((int) t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
2404   __ stw(tmp, offs1, addr);
2405 
2406   // Bump bucket contents.
2407   // _counters[_index] ++;
2408   int offs2 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_counters, R0, true);
2409   __ sldi(tmp, tmp, LogBytesPerInt);
2410   __ add(addr, tmp, addr);
2411   __ lwz(tmp, offs2, addr);
2412   __ addi(tmp, tmp, 1);
2413   __ stw(tmp, offs2, addr);
2414 }
2415 
2416 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
2417   // Call a little run-time stub to avoid blow-up for each bytecode.
2418   // The run-time runtime saves the right registers, depending on
2419   // the tosca in-state for the given template.
2420 
2421   assert(Interpreter::trace_code(t->tos_in()) != nullptr,
2422          "entry must have been generated");
2423 
2424   // Note: we destroy LR here.
2425   __ bl(Interpreter::trace_code(t->tos_in()));
2426 }
2427 
2428 void TemplateInterpreterGenerator::stop_interpreter_at() {
2429   Label L;
2430   int offs1 = __ load_const_optimized(R11_scratch1, (address) &StopInterpreterAt, R0, true);
2431   int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
2432   __ ld(R11_scratch1, offs1, R11_scratch1);
2433   __ ld(R12_scratch2, offs2, R12_scratch2);
2434   __ cmpd(CR0, R12_scratch2, R11_scratch1);
2435   __ bne(CR0, L);
2436   __ illtrap();
2437   __ bind(L);
2438 }
2439 
2440 #endif // !PRODUCT