1 /*
   2  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright 2013, 2014 SAP AG. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #ifndef CC_INTERP
  28 #include "asm/macroAssembler.inline.hpp"
  29 #include "interpreter/bytecodeHistogram.hpp"
  30 #include "interpreter/interpreter.hpp"
  31 #include "interpreter/interpreterGenerator.hpp"
  32 #include "interpreter/interpreterRuntime.hpp"
  33 #include "interpreter/interp_masm.hpp"
  34 #include "interpreter/templateTable.hpp"
  35 #include "oops/arrayOop.hpp"
  36 #include "oops/methodData.hpp"
  37 #include "oops/method.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "prims/jvmtiExport.hpp"
  40 #include "prims/jvmtiThreadState.hpp"
  41 #include "runtime/arguments.hpp"
  42 #include "runtime/deoptimization.hpp"
  43 #include "runtime/frame.inline.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/stubRoutines.hpp"
  46 #include "runtime/synchronizer.hpp"
  47 #include "runtime/timer.hpp"
  48 #include "runtime/vframeArray.hpp"
  49 #include "utilities/debug.hpp"
  50 #include "utilities/macros.hpp"
  51 
  52 #undef __
  53 #define __ _masm->
  54 
  55 #ifdef PRODUCT
  56 #define BLOCK_COMMENT(str) /* nothing */
  57 #else
  58 #define BLOCK_COMMENT(str) __ block_comment(str)
  59 #endif
  60 
  61 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  62 
  63 //-----------------------------------------------------------------------------
  64 
  65 // Actually we should never reach here since we do stack overflow checks before pushing any frame.
  66 address TemplateInterpreterGenerator::generate_StackOverflowError_handler() {
  67   address entry = __ pc();
  68   __ unimplemented("generate_StackOverflowError_handler");
  69   return entry;
  70 }
  71 
  72 address TemplateInterpreterGenerator::generate_ArrayIndexOutOfBounds_handler(const char* name) {
  73   address entry = __ pc();
  74   __ empty_expression_stack();
  75   __ load_const_optimized(R4_ARG2, (address) name);
  76   // Index is in R17_tos.
  77   __ mr(R5_ARG3, R17_tos);
  78   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException));
  79   return entry;
  80 }
  81 
  82 #if 0
  83 // Call special ClassCastException constructor taking object to cast
  84 // and target class as arguments.
  85 address TemplateInterpreterGenerator::generate_ClassCastException_verbose_handler() {
  86   address entry = __ pc();
  87 
  88   // Expression stack must be empty before entering the VM if an
  89   // exception happened.
  90   __ empty_expression_stack();
  91 
  92   // Thread will be loaded to R3_ARG1.
  93   // Target class oop is in register R5_ARG3 by convention!
  94   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException_verbose, R17_tos, R5_ARG3));
  95   // Above call must not return here since exception pending.
  96   DEBUG_ONLY(__ should_not_reach_here();)
  97   return entry;
  98 }
  99 #endif
 100 
 101 address TemplateInterpreterGenerator::generate_ClassCastException_handler() {
 102   address entry = __ pc();
 103   // Expression stack must be empty before entering the VM if an
 104   // exception happened.
 105   __ empty_expression_stack();
 106 
 107   // Load exception object.
 108   // Thread will be loaded to R3_ARG1.
 109   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::throw_ClassCastException), R17_tos);
 110 #ifdef ASSERT
 111   // Above call must not return here since exception pending.
 112   __ should_not_reach_here();
 113 #endif
 114   return entry;
 115 }
 116 
 117 address TemplateInterpreterGenerator::generate_exception_handler_common(const char* name, const char* message, bool pass_oop) {
 118   address entry = __ pc();
 119   //__ untested("generate_exception_handler_common");
 120   Register Rexception = R17_tos;
 121 
 122   // Expression stack must be empty before entering the VM if an exception happened.
 123   __ empty_expression_stack();
 124 
 125   __ load_const_optimized(R4_ARG2, (address) name, R11_scratch1);
 126   if (pass_oop) {
 127     __ mr(R5_ARG3, Rexception);
 128     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_klass_exception), false);
 129   } else {
 130     __ load_const_optimized(R5_ARG3, (address) message, R11_scratch1);
 131     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::create_exception), false);
 132   }
 133 
 134   // Throw exception.
 135   __ mr(R3_ARG1, Rexception);
 136   __ load_const_optimized(R11_scratch1, Interpreter::throw_exception_entry(), R12_scratch2);
 137   __ mtctr(R11_scratch1);
 138   __ bctr();
 139 
 140   return entry;
 141 }
 142 
 143 address TemplateInterpreterGenerator::generate_continuation_for(TosState state) {
 144   address entry = __ pc();
 145   __ unimplemented("generate_continuation_for");
 146   return entry;
 147 }
 148 
 149 // This entry is returned to when a call returns to the interpreter.
 150 // When we arrive here, we expect that the callee stack frame is already popped.
 151 address TemplateInterpreterGenerator::generate_return_entry_for(TosState state, int step, size_t index_size) {
 152   address entry = __ pc();
 153 
 154   // Move the value out of the return register back to the TOS cache of current frame.
 155   switch (state) {
 156     case ltos:
 157     case btos:
 158     case ctos:
 159     case stos:
 160     case atos:
 161     case itos: __ mr(R17_tos, R3_RET); break;   // RET -> TOS cache
 162     case ftos:
 163     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 164     case vtos: break;                           // Nothing to do, this was a void return.
 165     default  : ShouldNotReachHere();
 166   }
 167 
 168   __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
 169   __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
 170   __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
 171 
 172   // Compiled code destroys templateTableBase, reload.
 173   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R12_scratch2);
 174 
 175   const Register cache = R11_scratch1;
 176   const Register size  = R12_scratch2;
 177   __ get_cache_and_index_at_bcp(cache, 1, index_size);
 178 
 179   // Big Endian (get least significant byte of 64 bit value):
 180   __ lbz(size, in_bytes(ConstantPoolCache::base_offset() + ConstantPoolCacheEntry::flags_offset()) + 7, cache);
 181   __ sldi(size, size, Interpreter::logStackElementSize);
 182   __ add(R15_esp, R15_esp, size);
 183   __ dispatch_next(state, step);
 184   return entry;
 185 }
 186 
 187 address TemplateInterpreterGenerator::generate_deopt_entry_for(TosState state, int step) {
 188   address entry = __ pc();
 189   // If state != vtos, we're returning from a native method, which put it's result
 190   // into the result register. So move the value out of the return register back
 191   // to the TOS cache of current frame.
 192 
 193   switch (state) {
 194     case ltos:
 195     case btos:
 196     case ctos:
 197     case stos:
 198     case atos:
 199     case itos: __ mr(R17_tos, R3_RET); break;   // GR_RET -> TOS cache
 200     case ftos:
 201     case dtos: __ fmr(F15_ftos, F1_RET); break; // TOS cache -> GR_FRET
 202     case vtos: break;                           // Nothing to do, this was a void return.
 203     default  : ShouldNotReachHere();
 204   }
 205 
 206   // Load LcpoolCache @@@ should be already set!
 207   __ get_constant_pool_cache(R27_constPoolCache);
 208 
 209   // Handle a pending exception, fall through if none.
 210   __ check_and_forward_exception(R11_scratch1, R12_scratch2);
 211 
 212   // Start executing bytecodes.
 213   __ dispatch_next(state, step);
 214 
 215   return entry;
 216 }
 217 
 218 // A result handler converts the native result into java format.
 219 // Use the shared code between c++ and template interpreter.
 220 address TemplateInterpreterGenerator::generate_result_handler_for(BasicType type) {
 221   return AbstractInterpreterGenerator::generate_result_handler_for(type);
 222 }
 223 
 224 address TemplateInterpreterGenerator::generate_safept_entry_for(TosState state, address runtime_entry) {
 225   address entry = __ pc();
 226 
 227   __ push(state);
 228   __ call_VM(noreg, runtime_entry);
 229   __ dispatch_via(vtos, Interpreter::_normal_table.table_for(vtos));
 230 
 231   return entry;
 232 }
 233 
 234 // Helpers for commoning out cases in the various type of method entries.
 235 
 236 // Increment invocation count & check for overflow.
 237 //
 238 // Note: checking for negative value instead of overflow
 239 //       so we have a 'sticky' overflow test.
 240 //
 241 void TemplateInterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
 242   // Note: In tiered we increment either counters in method or in MDO depending if we're profiling or not.
 243   Register Rscratch1   = R11_scratch1;
 244   Register Rscratch2   = R12_scratch2;
 245   Register R3_counters = R3_ARG1;
 246   Label done;
 247 
 248   if (TieredCompilation) {
 249     const int increment = InvocationCounter::count_increment;
 250     const int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift;
 251     Label no_mdo;
 252     if (ProfileInterpreter) {
 253       const Register Rmdo = Rscratch1;
 254       // If no method data exists, go to profile_continue.
 255       __ ld(Rmdo, in_bytes(Method::method_data_offset()), R19_method);
 256       __ cmpdi(CCR0, Rmdo, 0);
 257       __ beq(CCR0, no_mdo);
 258 
 259       // Increment backedge counter in the MDO.
 260       const int mdo_bc_offs = in_bytes(MethodData::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 261       __ lwz(Rscratch2, mdo_bc_offs, Rmdo);
 262       __ addi(Rscratch2, Rscratch2, increment);
 263       __ stw(Rscratch2, mdo_bc_offs, Rmdo);
 264       __ load_const_optimized(Rscratch1, mask, R0);
 265       __ and_(Rscratch1, Rscratch2, Rscratch1);
 266       __ bne(CCR0, done);
 267       __ b(*overflow);
 268     }
 269 
 270     // Increment counter in MethodCounters*.
 271     const int mo_bc_offs = in_bytes(MethodCounters::backedge_counter_offset()) + in_bytes(InvocationCounter::counter_offset());
 272     __ bind(no_mdo);
 273     __ get_method_counters(R19_method, R3_counters, done);
 274     __ lwz(Rscratch2, mo_bc_offs, R3_counters);
 275     __ addi(Rscratch2, Rscratch2, increment);
 276     __ stw(Rscratch2, mo_bc_offs, R3_counters);
 277     __ load_const_optimized(Rscratch1, mask, R0);
 278     __ and_(Rscratch1, Rscratch2, Rscratch1);
 279     __ beq(CCR0, *overflow);
 280 
 281     __ bind(done);
 282 
 283   } else {
 284 
 285     // Update standard invocation counters.
 286     Register Rsum_ivc_bec = R4_ARG2;
 287     __ get_method_counters(R19_method, R3_counters, done);
 288     __ increment_invocation_counter(R3_counters, Rsum_ivc_bec, R12_scratch2);
 289     // Increment interpreter invocation counter.
 290     if (ProfileInterpreter) {  // %%% Merge this into methodDataOop.
 291       __ lwz(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
 292       __ addi(R12_scratch2, R12_scratch2, 1);
 293       __ stw(R12_scratch2, in_bytes(MethodCounters::interpreter_invocation_counter_offset()), R3_counters);
 294     }
 295     // Check if we must create a method data obj.
 296     if (ProfileInterpreter && profile_method != NULL) {
 297       const Register profile_limit = Rscratch1;
 298       int pl_offs = __ load_const_optimized(profile_limit, &InvocationCounter::InterpreterProfileLimit, R0, true);
 299       __ lwz(profile_limit, pl_offs, profile_limit);
 300       // Test to see if we should create a method data oop.
 301       __ cmpw(CCR0, Rsum_ivc_bec, profile_limit);
 302       __ blt(CCR0, *profile_method_continue);
 303       // If no method data exists, go to profile_method.
 304       __ test_method_data_pointer(*profile_method);
 305     }
 306     // Finally check for counter overflow.
 307     if (overflow) {
 308       const Register invocation_limit = Rscratch1;
 309       int il_offs = __ load_const_optimized(invocation_limit, &InvocationCounter::InterpreterInvocationLimit, R0, true);
 310       __ lwz(invocation_limit, il_offs, invocation_limit);
 311       assert(4 == sizeof(InvocationCounter::InterpreterInvocationLimit), "unexpected field size");
 312       __ cmpw(CCR0, Rsum_ivc_bec, invocation_limit);
 313       __ bge(CCR0, *overflow);
 314     }
 315 
 316     __ bind(done);
 317   }
 318 }
 319 
 320 // Generate code to initiate compilation on invocation counter overflow.
 321 void TemplateInterpreterGenerator::generate_counter_overflow(Label& continue_entry) {
 322   // Generate code to initiate compilation on the counter overflow.
 323 
 324   // InterpreterRuntime::frequency_counter_overflow takes one arguments,
 325   // which indicates if the counter overflow occurs at a backwards branch (NULL bcp)
 326   // We pass zero in.
 327   // The call returns the address of the verified entry point for the method or NULL
 328   // if the compilation did not complete (either went background or bailed out).
 329   //
 330   // Unlike the C++ interpreter above: Check exceptions!
 331   // Assumption: Caller must set the flag "do_not_unlock_if_sychronized" if the monitor of a sync'ed
 332   // method has not yet been created. Thus, no unlocking of a non-existing monitor can occur.
 333 
 334   __ li(R4_ARG2, 0);
 335   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), R4_ARG2, true);
 336 
 337   // Returns verified_entry_point or NULL.
 338   // We ignore it in any case.
 339   __ b(continue_entry);
 340 }
 341 
 342 void TemplateInterpreterGenerator::generate_stack_overflow_check(Register Rmem_frame_size, Register Rscratch1) {
 343   assert_different_registers(Rmem_frame_size, Rscratch1);
 344   __ generate_stack_overflow_check_with_compare_and_throw(Rmem_frame_size, Rscratch1);
 345 }
 346 
 347 void TemplateInterpreterGenerator::unlock_method(bool check_exceptions) {
 348   __ unlock_object(R26_monitor, check_exceptions);
 349 }
 350 
 351 // Lock the current method, interpreter register window must be set up!
 352 void TemplateInterpreterGenerator::lock_method(Register Rflags, Register Rscratch1, Register Rscratch2, bool flags_preloaded) {
 353   const Register Robj_to_lock = Rscratch2;
 354 
 355   {
 356     if (!flags_preloaded) {
 357       __ lwz(Rflags, method_(access_flags));
 358     }
 359 
 360 #ifdef ASSERT
 361     // Check if methods needs synchronization.
 362     {
 363       Label Lok;
 364       __ testbitdi(CCR0, R0, Rflags, JVM_ACC_SYNCHRONIZED_BIT);
 365       __ btrue(CCR0,Lok);
 366       __ stop("method doesn't need synchronization");
 367       __ bind(Lok);
 368     }
 369 #endif // ASSERT
 370   }
 371 
 372   // Get synchronization object to Rscratch2.
 373   {
 374     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 375     Label Lstatic;
 376     Label Ldone;
 377 
 378     __ testbitdi(CCR0, R0, Rflags, JVM_ACC_STATIC_BIT);
 379     __ btrue(CCR0, Lstatic);
 380 
 381     // Non-static case: load receiver obj from stack and we're done.
 382     __ ld(Robj_to_lock, R18_locals);
 383     __ b(Ldone);
 384 
 385     __ bind(Lstatic); // Static case: Lock the java mirror
 386     __ ld(Robj_to_lock, in_bytes(Method::const_offset()), R19_method);
 387     __ ld(Robj_to_lock, in_bytes(ConstMethod::constants_offset()), Robj_to_lock);
 388     __ ld(Robj_to_lock, ConstantPool::pool_holder_offset_in_bytes(), Robj_to_lock);
 389     __ ld(Robj_to_lock, mirror_offset, Robj_to_lock);
 390 
 391     __ bind(Ldone);
 392     __ verify_oop(Robj_to_lock);
 393   }
 394 
 395   // Got the oop to lock => execute!
 396   __ add_monitor_to_stack(true, Rscratch1, R0);
 397 
 398   __ std(Robj_to_lock, BasicObjectLock::obj_offset_in_bytes(), R26_monitor);
 399   __ lock_object(R26_monitor, Robj_to_lock);
 400 }
 401 
 402 // Generate a fixed interpreter frame for pure interpreter
 403 // and I2N native transition frames.
 404 //
 405 // Before (stack grows downwards):
 406 //
 407 //         |  ...         |
 408 //         |------------- |
 409 //         |  java arg0   |
 410 //         |  ...         |
 411 //         |  java argn   |
 412 //         |              |   <-   R15_esp
 413 //         |              |
 414 //         |--------------|
 415 //         | abi_112      |
 416 //         |              |   <-   R1_SP
 417 //         |==============|
 418 //
 419 //
 420 // After:
 421 //
 422 //         |  ...         |
 423 //         |  java arg0   |<-   R18_locals
 424 //         |  ...         |
 425 //         |  java argn   |
 426 //         |--------------|
 427 //         |              |
 428 //         |  java locals |
 429 //         |              |
 430 //         |--------------|
 431 //         |  abi_48      |
 432 //         |==============|
 433 //         |              |
 434 //         |   istate     |
 435 //         |              |
 436 //         |--------------|
 437 //         |   monitor    |<-   R26_monitor
 438 //         |--------------|
 439 //         |              |<-   R15_esp
 440 //         | expression   |
 441 //         | stack        |
 442 //         |              |
 443 //         |--------------|
 444 //         |              |
 445 //         | abi_112      |<-   R1_SP
 446 //         |==============|
 447 //
 448 // The top most frame needs an abi space of 112 bytes. This space is needed,
 449 // since we call to c. The c function may spill their arguments to the caller
 450 // frame. When we call to java, we don't need these spill slots. In order to save
 451 // space on the stack, we resize the caller. However, java local reside in
 452 // the caller frame and the frame has to be increased. The frame_size for the
 453 // current frame was calculated based on max_stack as size for the expression
 454 // stack. At the call, just a part of the expression stack might be used.
 455 // We don't want to waste this space and cut the frame back accordingly.
 456 // The resulting amount for resizing is calculated as follows:
 457 // resize =   (number_of_locals - number_of_arguments) * slot_size
 458 //          + (R1_SP - R15_esp) + 48
 459 //
 460 // The size for the callee frame is calculated:
 461 // framesize = 112 + max_stack + monitor + state_size
 462 //
 463 // maxstack:   Max number of slots on the expression stack, loaded from the method.
 464 // monitor:    We statically reserve room for one monitor object.
 465 // state_size: We save the current state of the interpreter to this area.
 466 //
 467 void TemplateInterpreterGenerator::generate_fixed_frame(bool native_call, Register Rsize_of_parameters, Register Rsize_of_locals) {
 468   Register parent_frame_resize = R6_ARG4, // Frame will grow by this number of bytes.
 469            top_frame_size      = R7_ARG5,
 470            Rconst_method       = R8_ARG6;
 471 
 472   assert_different_registers(Rsize_of_parameters, Rsize_of_locals, parent_frame_resize, top_frame_size);
 473 
 474   __ ld(Rconst_method, method_(const));
 475   __ lhz(Rsize_of_parameters /* number of params */,
 476          in_bytes(ConstMethod::size_of_parameters_offset()), Rconst_method);
 477   if (native_call) {
 478     // If we're calling a native method, we reserve space for the worst-case signature
 479     // handler varargs vector, which is max(Argument::n_register_parameters, parameter_count+2).
 480     // We add two slots to the parameter_count, one for the jni
 481     // environment and one for a possible native mirror.
 482     Label skip_native_calculate_max_stack;
 483     __ addi(top_frame_size, Rsize_of_parameters, 2);
 484     __ cmpwi(CCR0, top_frame_size, Argument::n_register_parameters);
 485     __ bge(CCR0, skip_native_calculate_max_stack);
 486     __ li(top_frame_size, Argument::n_register_parameters);
 487     __ bind(skip_native_calculate_max_stack);
 488     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 489     __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
 490     __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 491     assert(Rsize_of_locals == noreg, "Rsize_of_locals not initialized"); // Only relevant value is Rsize_of_parameters.
 492   } else {
 493     __ lhz(Rsize_of_locals /* number of params */, in_bytes(ConstMethod::size_of_locals_offset()), Rconst_method);
 494     __ sldi(Rsize_of_parameters, Rsize_of_parameters, Interpreter::logStackElementSize);
 495     __ sldi(Rsize_of_locals, Rsize_of_locals, Interpreter::logStackElementSize);
 496     __ lhz(top_frame_size, in_bytes(ConstMethod::max_stack_offset()), Rconst_method);
 497     __ sub(R11_scratch1, Rsize_of_locals, Rsize_of_parameters); // >=0
 498     __ sub(parent_frame_resize, R1_SP, R15_esp); // <0, off by Interpreter::stackElementSize!
 499     __ sldi(top_frame_size, top_frame_size, Interpreter::logStackElementSize);
 500     __ add(parent_frame_resize, parent_frame_resize, R11_scratch1);
 501   }
 502 
 503   // Compute top frame size.
 504   __ addi(top_frame_size, top_frame_size, frame::abi_reg_args_size + frame::ijava_state_size);
 505 
 506   // Cut back area between esp and max_stack.
 507   __ addi(parent_frame_resize, parent_frame_resize, frame::abi_minframe_size - Interpreter::stackElementSize);
 508 
 509   __ round_to(top_frame_size, frame::alignment_in_bytes);
 510   __ round_to(parent_frame_resize, frame::alignment_in_bytes);
 511   // parent_frame_resize = (locals-parameters) - (ESP-SP-ABI48) Rounded to frame alignment size.
 512   // Enlarge by locals-parameters (not in case of native_call), shrink by ESP-SP-ABI48.
 513 
 514   {
 515     // --------------------------------------------------------------------------
 516     // Stack overflow check
 517 
 518     Label cont;
 519     __ add(R11_scratch1, parent_frame_resize, top_frame_size);
 520     generate_stack_overflow_check(R11_scratch1, R12_scratch2);
 521   }
 522 
 523   // Set up interpreter state registers.
 524 
 525   __ add(R18_locals, R15_esp, Rsize_of_parameters);
 526   __ ld(R27_constPoolCache, in_bytes(ConstMethod::constants_offset()), Rconst_method);
 527   __ ld(R27_constPoolCache, ConstantPool::cache_offset_in_bytes(), R27_constPoolCache);
 528 
 529   // Set method data pointer.
 530   if (ProfileInterpreter) {
 531     Label zero_continue;
 532     __ ld(R28_mdx, method_(method_data));
 533     __ cmpdi(CCR0, R28_mdx, 0);
 534     __ beq(CCR0, zero_continue);
 535     __ addi(R28_mdx, R28_mdx, in_bytes(MethodData::data_offset()));
 536     __ bind(zero_continue);
 537   }
 538 
 539   if (native_call) {
 540     __ li(R14_bcp, 0); // Must initialize.
 541   } else {
 542     __ add(R14_bcp, in_bytes(ConstMethod::codes_offset()), Rconst_method);
 543   }
 544 
 545   // Resize parent frame.
 546   __ mflr(R12_scratch2);
 547   __ neg(parent_frame_resize, parent_frame_resize);
 548   __ resize_frame(parent_frame_resize, R11_scratch1);
 549   __ std(R12_scratch2, _abi(lr), R1_SP);
 550 
 551   __ addi(R26_monitor, R1_SP, - frame::ijava_state_size);
 552   __ addi(R15_esp, R26_monitor, - Interpreter::stackElementSize);
 553 
 554   // Store values.
 555   // R15_esp, R14_bcp, R26_monitor, R28_mdx are saved at java calls
 556   // in InterpreterMacroAssembler::call_from_interpreter.
 557   __ std(R19_method, _ijava_state_neg(method), R1_SP);
 558   __ std(R21_sender_SP, _ijava_state_neg(sender_sp), R1_SP);
 559   __ std(R27_constPoolCache, _ijava_state_neg(cpoolCache), R1_SP);
 560   __ std(R18_locals, _ijava_state_neg(locals), R1_SP);
 561 
 562   // Note: esp, bcp, monitor, mdx live in registers. Hence, the correct version can only
 563   // be found in the frame after save_interpreter_state is done. This is always true
 564   // for non-top frames. But when a signal occurs, dumping the top frame can go wrong,
 565   // because e.g. frame::interpreter_frame_bcp() will not access the correct value
 566   // (Enhanced Stack Trace).
 567   // The signal handler does not save the interpreter state into the frame.
 568   __ li(R0, 0);
 569 #ifdef ASSERT
 570   // Fill remaining slots with constants.
 571   __ load_const_optimized(R11_scratch1, 0x5afe);
 572   __ load_const_optimized(R12_scratch2, 0xdead);
 573 #endif
 574   // We have to initialize some frame slots for native calls (accessed by GC).
 575   if (native_call) {
 576     __ std(R26_monitor, _ijava_state_neg(monitors), R1_SP);
 577     __ std(R14_bcp, _ijava_state_neg(bcp), R1_SP);
 578     if (ProfileInterpreter) { __ std(R28_mdx, _ijava_state_neg(mdx), R1_SP); }
 579   }
 580 #ifdef ASSERT
 581   else {
 582     __ std(R12_scratch2, _ijava_state_neg(monitors), R1_SP);
 583     __ std(R12_scratch2, _ijava_state_neg(bcp), R1_SP);
 584     __ std(R12_scratch2, _ijava_state_neg(mdx), R1_SP);
 585   }
 586   __ std(R11_scratch1, _ijava_state_neg(ijava_reserved), R1_SP);
 587   __ std(R12_scratch2, _ijava_state_neg(esp), R1_SP);
 588   __ std(R12_scratch2, _ijava_state_neg(lresult), R1_SP);
 589   __ std(R12_scratch2, _ijava_state_neg(fresult), R1_SP);
 590 #endif
 591   __ subf(R12_scratch2, top_frame_size, R1_SP);
 592   __ std(R0, _ijava_state_neg(oop_tmp), R1_SP);
 593   __ std(R12_scratch2, _ijava_state_neg(top_frame_sp), R1_SP);
 594 
 595   // Push top frame.
 596   __ push_frame(top_frame_size, R11_scratch1);
 597 }
 598 
 599 // End of helpers
 600 
 601 // ============================================================================
 602 // Various method entries
 603 //
 604 
 605 // Empty method, generate a very fast return. We must skip this entry if
 606 // someone's debugging, indicated by the flag
 607 // "interp_mode" in the Thread obj.
 608 // Note: empty methods are generated mostly methods that do assertions, which are
 609 // disabled in the "java opt build".
 610 address TemplateInterpreterGenerator::generate_empty_entry(void) {
 611   if (!UseFastEmptyMethods) {
 612     NOT_PRODUCT(__ should_not_reach_here();)
 613     return Interpreter::entry_for_kind(Interpreter::zerolocals);
 614   }
 615 
 616   Label Lslow_path;
 617   const Register Rjvmti_mode = R11_scratch1;
 618   address entry = __ pc();
 619 
 620   __ lwz(Rjvmti_mode, thread_(interp_only_mode));
 621   __ cmpwi(CCR0, Rjvmti_mode, 0);
 622   __ bne(CCR0, Lslow_path); // jvmti_mode!=0
 623 
 624   // Noone's debuggin: Simply return.
 625   // Pop c2i arguments (if any) off when we return.
 626 #ifdef ASSERT
 627     __ ld(R9_ARG7, 0, R1_SP);
 628     __ ld(R10_ARG8, 0, R21_sender_SP);
 629     __ cmpd(CCR0, R9_ARG7, R10_ARG8);
 630     __ asm_assert_eq("backlink", 0x545);
 631 #endif // ASSERT
 632   __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
 633 
 634   // And we're done.
 635   __ blr();
 636 
 637   __ bind(Lslow_path);
 638   __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R11_scratch1);
 639   __ flush();
 640 
 641   return entry;
 642 }
 643 
 644 // Support abs and sqrt like in compiler.
 645 // For others we can use a normal (native) entry.
 646 
 647 inline bool math_entry_available(AbstractInterpreter::MethodKind kind) {
 648   // Provide math entry with debugging on demand.
 649   // Note: Debugging changes which code will get executed:
 650   // Debugging or disabled InlineIntrinsics: java method will get interpreted and performs a native call.
 651   // Not debugging and enabled InlineIntrinics: processor instruction will get used.
 652   // Result might differ slightly due to rounding etc.
 653   if (!InlineIntrinsics && (!FLAG_IS_ERGO(InlineIntrinsics))) return false; // Generate a vanilla entry.
 654 
 655   return ((kind==Interpreter::java_lang_math_sqrt && VM_Version::has_fsqrt()) ||
 656           (kind==Interpreter::java_lang_math_abs));
 657 }
 658 
 659 address TemplateInterpreterGenerator::generate_math_entry(AbstractInterpreter::MethodKind kind) {
 660   if (!math_entry_available(kind)) {
 661     NOT_PRODUCT(__ should_not_reach_here();)
 662     return Interpreter::entry_for_kind(Interpreter::zerolocals);
 663   }
 664 
 665   Label Lslow_path;
 666   const Register Rjvmti_mode = R11_scratch1;
 667   address entry = __ pc();
 668 
 669   // Provide math entry with debugging on demand.
 670   __ lwz(Rjvmti_mode, thread_(interp_only_mode));
 671   __ cmpwi(CCR0, Rjvmti_mode, 0);
 672   __ bne(CCR0, Lslow_path); // jvmti_mode!=0
 673 
 674   __ lfd(F1_RET, Interpreter::stackElementSize, R15_esp);
 675 
 676   // Pop c2i arguments (if any) off when we return.
 677 #ifdef ASSERT
 678   __ ld(R9_ARG7, 0, R1_SP);
 679   __ ld(R10_ARG8, 0, R21_sender_SP);
 680   __ cmpd(CCR0, R9_ARG7, R10_ARG8);
 681   __ asm_assert_eq("backlink", 0x545);
 682 #endif // ASSERT
 683   __ mr(R1_SP, R21_sender_SP); // Cut the stack back to where the caller started.
 684 
 685   if (kind == Interpreter::java_lang_math_sqrt) {
 686     __ fsqrt(F1_RET, F1_RET);
 687   } else if (kind == Interpreter::java_lang_math_abs) {
 688     __ fabs(F1_RET, F1_RET);
 689   } else {
 690     ShouldNotReachHere();
 691   }
 692 
 693   // And we're done.
 694   __ blr();
 695 
 696   // Provide slow path for JVMTI case.
 697   __ bind(Lslow_path);
 698   __ branch_to_entry(Interpreter::entry_for_kind(Interpreter::zerolocals), R12_scratch2);
 699   __ flush();
 700 
 701   return entry;
 702 }
 703 
 704 // Interpreter stub for calling a native method. (asm interpreter)
 705 // This sets up a somewhat different looking stack for calling the
 706 // native method than the typical interpreter frame setup.
 707 //
 708 // On entry:
 709 //   R19_method    - method
 710 //   R16_thread    - JavaThread*
 711 //   R15_esp       - intptr_t* sender tos
 712 //
 713 //   abstract stack (grows up)
 714 //     [  IJava (caller of JNI callee)  ]  <-- ASP
 715 //        ...
 716 address TemplateInterpreterGenerator::generate_native_entry(bool synchronized) {
 717 
 718   address entry = __ pc();
 719 
 720   const bool inc_counter = UseCompiler || CountCompiledCalls;
 721 
 722   // -----------------------------------------------------------------------------
 723   // Allocate a new frame that represents the native callee (i2n frame).
 724   // This is not a full-blown interpreter frame, but in particular, the
 725   // following registers are valid after this:
 726   // - R19_method
 727   // - R18_local (points to start of argumuments to native function)
 728   //
 729   //   abstract stack (grows up)
 730   //     [  IJava (caller of JNI callee)  ]  <-- ASP
 731   //        ...
 732 
 733   const Register signature_handler_fd = R11_scratch1;
 734   const Register pending_exception    = R0;
 735   const Register result_handler_addr  = R31;
 736   const Register native_method_fd     = R11_scratch1;
 737   const Register access_flags         = R22_tmp2;
 738   const Register active_handles       = R11_scratch1; // R26_monitor saved to state.
 739   const Register sync_state           = R12_scratch2;
 740   const Register sync_state_addr      = sync_state;   // Address is dead after use.
 741   const Register suspend_flags        = R11_scratch1;
 742 
 743   //=============================================================================
 744   // Allocate new frame and initialize interpreter state.
 745 
 746   Label exception_return;
 747   Label exception_return_sync_check;
 748   Label stack_overflow_return;
 749 
 750   // Generate new interpreter state and jump to stack_overflow_return in case of
 751   // a stack overflow.
 752   //generate_compute_interpreter_state(stack_overflow_return);
 753 
 754   Register size_of_parameters = R22_tmp2;
 755 
 756   generate_fixed_frame(true, size_of_parameters, noreg /* unused */);
 757 
 758   //=============================================================================
 759   // Increment invocation counter. On overflow, entry to JNI method
 760   // will be compiled.
 761   Label invocation_counter_overflow, continue_after_compile;
 762   if (inc_counter) {
 763     if (synchronized) {
 764       // Since at this point in the method invocation the exception handler
 765       // would try to exit the monitor of synchronized methods which hasn't
 766       // been entered yet, we set the thread local variable
 767       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
 768       // runtime, exception handling i.e. unlock_if_synchronized_method will
 769       // check this thread local flag.
 770       // This flag has two effects, one is to force an unwind in the topmost
 771       // interpreter frame and not perform an unlock while doing so.
 772       __ li(R0, 1);
 773       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
 774     }
 775     generate_counter_incr(&invocation_counter_overflow, NULL, NULL);
 776 
 777     __ BIND(continue_after_compile);
 778     // Reset the _do_not_unlock_if_synchronized flag.
 779     if (synchronized) {
 780       __ li(R0, 0);
 781       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
 782     }
 783   }
 784 
 785   // access_flags = method->access_flags();
 786   // Load access flags.
 787   assert(access_flags->is_nonvolatile(),
 788          "access_flags must be in a non-volatile register");
 789   // Type check.
 790   assert(4 == sizeof(AccessFlags), "unexpected field size");
 791   __ lwz(access_flags, method_(access_flags));
 792 
 793   // We don't want to reload R19_method and access_flags after calls
 794   // to some helper functions.
 795   assert(R19_method->is_nonvolatile(),
 796          "R19_method must be a non-volatile register");
 797 
 798   // Check for synchronized methods. Must happen AFTER invocation counter
 799   // check, so method is not locked if counter overflows.
 800 
 801   if (synchronized) {
 802     lock_method(access_flags, R11_scratch1, R12_scratch2, true);
 803 
 804     // Update monitor in state.
 805     __ ld(R11_scratch1, 0, R1_SP);
 806     __ std(R26_monitor, _ijava_state_neg(monitors), R11_scratch1);
 807   }
 808 
 809   // jvmti/jvmpi support
 810   __ notify_method_entry();
 811 
 812   //=============================================================================
 813   // Get and call the signature handler.
 814 
 815   __ ld(signature_handler_fd, method_(signature_handler));
 816   Label call_signature_handler;
 817 
 818   __ cmpdi(CCR0, signature_handler_fd, 0);
 819   __ bne(CCR0, call_signature_handler);
 820 
 821   // Method has never been called. Either generate a specialized
 822   // handler or point to the slow one.
 823   //
 824   // Pass parameter 'false' to avoid exception check in call_VM.
 825   __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::prepare_native_call), R19_method, false);
 826 
 827   // Check for an exception while looking up the target method. If we
 828   // incurred one, bail.
 829   __ ld(pending_exception, thread_(pending_exception));
 830   __ cmpdi(CCR0, pending_exception, 0);
 831   __ bne(CCR0, exception_return_sync_check); // Has pending exception.
 832 
 833   // Reload signature handler, it may have been created/assigned in the meanwhile.
 834   __ ld(signature_handler_fd, method_(signature_handler));
 835   __ twi_0(signature_handler_fd); // Order wrt. load of klass mirror and entry point (isync is below).
 836 
 837   __ BIND(call_signature_handler);
 838 
 839   // Before we call the signature handler we push a new frame to
 840   // protect the interpreter frame volatile registers when we return
 841   // from jni but before we can get back to Java.
 842 
 843   // First set the frame anchor while the SP/FP registers are
 844   // convenient and the slow signature handler can use this same frame
 845   // anchor.
 846 
 847   // We have a TOP_IJAVA_FRAME here, which belongs to us.
 848   __ set_top_ijava_frame_at_SP_as_last_Java_frame(R1_SP, R12_scratch2/*tmp*/);
 849 
 850   // Now the interpreter frame (and its call chain) have been
 851   // invalidated and flushed. We are now protected against eager
 852   // being enabled in native code. Even if it goes eager the
 853   // registers will be reloaded as clean and we will invalidate after
 854   // the call so no spurious flush should be possible.
 855 
 856   // Call signature handler and pass locals address.
 857   //
 858   // Our signature handlers copy required arguments to the C stack
 859   // (outgoing C args), R3_ARG1 to R10_ARG8, and FARG1 to FARG13.
 860   __ mr(R3_ARG1, R18_locals);
 861   __ ld(signature_handler_fd, 0, signature_handler_fd);
 862 
 863   __ call_stub(signature_handler_fd);
 864 
 865   // Remove the register parameter varargs slots we allocated in
 866   // compute_interpreter_state. SP+16 ends up pointing to the ABI
 867   // outgoing argument area.
 868   //
 869   // Not needed on PPC64.
 870   //__ add(SP, SP, Argument::n_register_parameters*BytesPerWord);
 871 
 872   assert(result_handler_addr->is_nonvolatile(), "result_handler_addr must be in a non-volatile register");
 873   // Save across call to native method.
 874   __ mr(result_handler_addr, R3_RET);
 875 
 876   __ isync(); // Acquire signature handler before trying to fetch the native entry point and klass mirror.
 877 
 878   // Set up fixed parameters and call the native method.
 879   // If the method is static, get mirror into R4_ARG2.
 880   {
 881     Label method_is_not_static;
 882     // Access_flags is non-volatile and still, no need to restore it.
 883 
 884     // Restore access flags.
 885     __ testbitdi(CCR0, R0, access_flags, JVM_ACC_STATIC_BIT);
 886     __ bfalse(CCR0, method_is_not_static);
 887 
 888     // constants = method->constants();
 889     __ ld(R11_scratch1, in_bytes(Method::const_offset()), R19_method);
 890     __ ld(R11_scratch1, in_bytes(ConstMethod::constants_offset()), R11_scratch1);
 891     // pool_holder = method->constants()->pool_holder();
 892     __ ld(R11_scratch1/*pool_holder*/, ConstantPool::pool_holder_offset_in_bytes(),
 893           R11_scratch1/*constants*/);
 894 
 895     const int mirror_offset = in_bytes(Klass::java_mirror_offset());
 896 
 897     // mirror = pool_holder->klass_part()->java_mirror();
 898     __ ld(R0/*mirror*/, mirror_offset, R11_scratch1/*pool_holder*/);
 899     // state->_native_mirror = mirror;
 900 
 901     __ ld(R11_scratch1, 0, R1_SP);
 902     __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1);
 903     // R4_ARG2 = &state->_oop_temp;
 904     __ addi(R4_ARG2, R11_scratch1, _ijava_state_neg(oop_tmp));
 905     __ BIND(method_is_not_static);
 906   }
 907 
 908   // At this point, arguments have been copied off the stack into
 909   // their JNI positions. Oops are boxed in-place on the stack, with
 910   // handles copied to arguments. The result handler address is in a
 911   // register.
 912 
 913   // Pass JNIEnv address as first parameter.
 914   __ addir(R3_ARG1, thread_(jni_environment));
 915 
 916   // Load the native_method entry before we change the thread state.
 917   __ ld(native_method_fd, method_(native_function));
 918 
 919   //=============================================================================
 920   // Transition from _thread_in_Java to _thread_in_native. As soon as
 921   // we make this change the safepoint code needs to be certain that
 922   // the last Java frame we established is good. The pc in that frame
 923   // just needs to be near here not an actual return address.
 924 
 925   // We use release_store_fence to update values like the thread state, where
 926   // we don't want the current thread to continue until all our prior memory
 927   // accesses (including the new thread state) are visible to other threads.
 928   __ li(R0, _thread_in_native);
 929   __ release();
 930 
 931   // TODO PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
 932   __ stw(R0, thread_(thread_state));
 933 
 934   if (UseMembar) {
 935     __ fence();
 936   }
 937 
 938   //=============================================================================
 939   // Call the native method. Argument registers must not have been
 940   // overwritten since "__ call_stub(signature_handler);" (except for
 941   // ARG1 and ARG2 for static methods).
 942   __ call_c(native_method_fd);
 943 
 944   __ li(R0, 0);
 945   __ ld(R11_scratch1, 0, R1_SP);
 946   __ std(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
 947   __ stfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
 948   __ std(R0/*mirror*/, _ijava_state_neg(oop_tmp), R11_scratch1); // reset
 949 
 950   // Note: C++ interpreter needs the following here:
 951   // The frame_manager_lr field, which we use for setting the last
 952   // java frame, gets overwritten by the signature handler. Restore
 953   // it now.
 954   //__ get_PC_trash_LR(R11_scratch1);
 955   //__ std(R11_scratch1, _top_ijava_frame_abi(frame_manager_lr), R1_SP);
 956 
 957   // Because of GC R19_method may no longer be valid.
 958 
 959   // Block, if necessary, before resuming in _thread_in_Java state.
 960   // In order for GC to work, don't clear the last_Java_sp until after
 961   // blocking.
 962 
 963   //=============================================================================
 964   // Switch thread to "native transition" state before reading the
 965   // synchronization state. This additional state is necessary
 966   // because reading and testing the synchronization state is not
 967   // atomic w.r.t. GC, as this scenario demonstrates: Java thread A,
 968   // in _thread_in_native state, loads _not_synchronized and is
 969   // preempted. VM thread changes sync state to synchronizing and
 970   // suspends threads for GC. Thread A is resumed to finish this
 971   // native method, but doesn't block here since it didn't see any
 972   // synchronization in progress, and escapes.
 973 
 974   // We use release_store_fence to update values like the thread state, where
 975   // we don't want the current thread to continue until all our prior memory
 976   // accesses (including the new thread state) are visible to other threads.
 977   __ li(R0/*thread_state*/, _thread_in_native_trans);
 978   __ release();
 979   __ stw(R0/*thread_state*/, thread_(thread_state));
 980   if (UseMembar) {
 981     __ fence();
 982   }
 983   // Write serialization page so that the VM thread can do a pseudo remote
 984   // membar. We use the current thread pointer to calculate a thread
 985   // specific offset to write to within the page. This minimizes bus
 986   // traffic due to cache line collision.
 987   else {
 988     __ serialize_memory(R16_thread, R11_scratch1, R12_scratch2);
 989   }
 990 
 991   // Now before we return to java we must look for a current safepoint
 992   // (a new safepoint can not start since we entered native_trans).
 993   // We must check here because a current safepoint could be modifying
 994   // the callers registers right this moment.
 995 
 996   // Acquire isn't strictly necessary here because of the fence, but
 997   // sync_state is declared to be volatile, so we do it anyway
 998   // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
 999   int sync_state_offs = __ load_const_optimized(sync_state_addr, SafepointSynchronize::address_of_state(), /*temp*/R0, true);
1000 
1001   // TODO PPC port assert(4 == SafepointSynchronize::sz_state(), "unexpected field size");
1002   __ lwz(sync_state, sync_state_offs, sync_state_addr);
1003 
1004   // TODO PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
1005   __ lwz(suspend_flags, thread_(suspend_flags));
1006 
1007   Label sync_check_done;
1008   Label do_safepoint;
1009   // No synchronization in progress nor yet synchronized.
1010   __ cmpwi(CCR0, sync_state, SafepointSynchronize::_not_synchronized);
1011   // Not suspended.
1012   __ cmpwi(CCR1, suspend_flags, 0);
1013 
1014   __ bne(CCR0, do_safepoint);
1015   __ beq(CCR1, sync_check_done);
1016   __ bind(do_safepoint);
1017   __ isync();
1018   // Block. We do the call directly and leave the current
1019   // last_Java_frame setup undisturbed. We must save any possible
1020   // native result across the call. No oop is present.
1021 
1022   __ mr(R3_ARG1, R16_thread);
1023   __ call_c(CAST_FROM_FN_PTR(FunctionDescriptor*, JavaThread::check_special_condition_for_native_trans),
1024             relocInfo::none);
1025 
1026   __ bind(sync_check_done);
1027 
1028   //=============================================================================
1029   // <<<<<< Back in Interpreter Frame >>>>>
1030 
1031   // We are in thread_in_native_trans here and back in the normal
1032   // interpreter frame. We don't have to do anything special about
1033   // safepoints and we can switch to Java mode anytime we are ready.
1034 
1035   // Note: frame::interpreter_frame_result has a dependency on how the
1036   // method result is saved across the call to post_method_exit. For
1037   // native methods it assumes that the non-FPU/non-void result is
1038   // saved in _native_lresult and a FPU result in _native_fresult. If
1039   // this changes then the interpreter_frame_result implementation
1040   // will need to be updated too.
1041 
1042   // On PPC64, we have stored the result directly after the native call.
1043 
1044   //=============================================================================
1045   // Back in Java
1046 
1047   // We use release_store_fence to update values like the thread state, where
1048   // we don't want the current thread to continue until all our prior memory
1049   // accesses (including the new thread state) are visible to other threads.
1050   __ li(R0/*thread_state*/, _thread_in_Java);
1051   __ release();
1052   __ stw(R0/*thread_state*/, thread_(thread_state));
1053   if (UseMembar) {
1054     __ fence();
1055   }
1056 
1057   __ reset_last_Java_frame();
1058 
1059   // Jvmdi/jvmpi support. Whether we've got an exception pending or
1060   // not, and whether unlocking throws an exception or not, we notify
1061   // on native method exit. If we do have an exception, we'll end up
1062   // in the caller's context to handle it, so if we don't do the
1063   // notify here, we'll drop it on the floor.
1064   __ notify_method_exit(true/*native method*/,
1065                         ilgl /*illegal state (not used for native methods)*/,
1066                         InterpreterMacroAssembler::NotifyJVMTI,
1067                         false /*check_exceptions*/);
1068 
1069   //=============================================================================
1070   // Handle exceptions
1071 
1072   if (synchronized) {
1073     // Don't check for exceptions since we're still in the i2n frame. Do that
1074     // manually afterwards.
1075     unlock_method(false);
1076   }
1077 
1078   // Reset active handles after returning from native.
1079   // thread->active_handles()->clear();
1080   __ ld(active_handles, thread_(active_handles));
1081   // TODO PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
1082   __ li(R0, 0);
1083   __ stw(R0, JNIHandleBlock::top_offset_in_bytes(), active_handles);
1084 
1085   Label exception_return_sync_check_already_unlocked;
1086   __ ld(R0/*pending_exception*/, thread_(pending_exception));
1087   __ cmpdi(CCR0, R0/*pending_exception*/, 0);
1088   __ bne(CCR0, exception_return_sync_check_already_unlocked);
1089 
1090   //-----------------------------------------------------------------------------
1091   // No exception pending.
1092 
1093   // Move native method result back into proper registers and return.
1094   // Invoke result handler (may unbox/promote).
1095   __ ld(R11_scratch1, 0, R1_SP);
1096   __ ld(R3_RET, _ijava_state_neg(lresult), R11_scratch1);
1097   __ lfd(F1_RET, _ijava_state_neg(fresult), R11_scratch1);
1098   __ call_stub(result_handler_addr);
1099 
1100   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ R0, R11_scratch1, R12_scratch2);
1101 
1102   // Must use the return pc which was loaded from the caller's frame
1103   // as the VM uses return-pc-patching for deoptimization.
1104   __ mtlr(R0);
1105   __ blr();
1106 
1107   //-----------------------------------------------------------------------------
1108   // An exception is pending. We call into the runtime only if the
1109   // caller was not interpreted. If it was interpreted the
1110   // interpreter will do the correct thing. If it isn't interpreted
1111   // (call stub/compiled code) we will change our return and continue.
1112 
1113   __ BIND(exception_return_sync_check);
1114 
1115   if (synchronized) {
1116     // Don't check for exceptions since we're still in the i2n frame. Do that
1117     // manually afterwards.
1118     unlock_method(false);
1119   }
1120   __ BIND(exception_return_sync_check_already_unlocked);
1121 
1122   const Register return_pc = R31;
1123 
1124   __ ld(return_pc, 0, R1_SP);
1125   __ ld(return_pc, _abi(lr), return_pc);
1126 
1127   // Get the address of the exception handler.
1128   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address),
1129                   R16_thread,
1130                   return_pc /* return pc */);
1131   __ merge_frames(/*top_frame_sp*/ R21_sender_SP, noreg, R11_scratch1, R12_scratch2);
1132 
1133   // Load the PC of the the exception handler into LR.
1134   __ mtlr(R3_RET);
1135 
1136   // Load exception into R3_ARG1 and clear pending exception in thread.
1137   __ ld(R3_ARG1/*exception*/, thread_(pending_exception));
1138   __ li(R4_ARG2, 0);
1139   __ std(R4_ARG2, thread_(pending_exception));
1140 
1141   // Load the original return pc into R4_ARG2.
1142   __ mr(R4_ARG2/*issuing_pc*/, return_pc);
1143 
1144   // Return to exception handler.
1145   __ blr();
1146 
1147   //=============================================================================
1148   // Counter overflow.
1149 
1150   if (inc_counter) {
1151     // Handle invocation counter overflow.
1152     __ bind(invocation_counter_overflow);
1153 
1154     generate_counter_overflow(continue_after_compile);
1155   }
1156 
1157   return entry;
1158 }
1159 
1160 // Generic interpreted method entry to (asm) interpreter.
1161 //
1162 address TemplateInterpreterGenerator::generate_normal_entry(bool synchronized) {
1163   bool inc_counter = UseCompiler || CountCompiledCalls;
1164   address entry = __ pc();
1165   // Generate the code to allocate the interpreter stack frame.
1166   Register Rsize_of_parameters = R4_ARG2, // Written by generate_fixed_frame.
1167            Rsize_of_locals     = R5_ARG3; // Written by generate_fixed_frame.
1168 
1169   generate_fixed_frame(false, Rsize_of_parameters, Rsize_of_locals);
1170 
1171 #ifdef FAST_DISPATCH
1172   __ unimplemented("Fast dispatch in generate_normal_entry");
1173 #if 0
1174   __ set((intptr_t)Interpreter::dispatch_table(), IdispatchTables);
1175   // Set bytecode dispatch table base.
1176 #endif
1177 #endif
1178 
1179   // --------------------------------------------------------------------------
1180   // Zero out non-parameter locals.
1181   // Note: *Always* zero out non-parameter locals as Sparc does. It's not
1182   // worth to ask the flag, just do it.
1183   Register Rslot_addr = R6_ARG4,
1184            Rnum       = R7_ARG5;
1185   Label Lno_locals, Lzero_loop;
1186 
1187   // Set up the zeroing loop.
1188   __ subf(Rnum, Rsize_of_parameters, Rsize_of_locals);
1189   __ subf(Rslot_addr, Rsize_of_parameters, R18_locals);
1190   __ srdi_(Rnum, Rnum, Interpreter::logStackElementSize);
1191   __ beq(CCR0, Lno_locals);
1192   __ li(R0, 0);
1193   __ mtctr(Rnum);
1194 
1195   // The zero locals loop.
1196   __ bind(Lzero_loop);
1197   __ std(R0, 0, Rslot_addr);
1198   __ addi(Rslot_addr, Rslot_addr, -Interpreter::stackElementSize);
1199   __ bdnz(Lzero_loop);
1200 
1201   __ bind(Lno_locals);
1202 
1203   // --------------------------------------------------------------------------
1204   // Counter increment and overflow check.
1205   Label invocation_counter_overflow,
1206         profile_method,
1207         profile_method_continue;
1208   if (inc_counter || ProfileInterpreter) {
1209 
1210     Register Rdo_not_unlock_if_synchronized_addr = R11_scratch1;
1211     if (synchronized) {
1212       // Since at this point in the method invocation the exception handler
1213       // would try to exit the monitor of synchronized methods which hasn't
1214       // been entered yet, we set the thread local variable
1215       // _do_not_unlock_if_synchronized to true. If any exception was thrown by
1216       // runtime, exception handling i.e. unlock_if_synchronized_method will
1217       // check this thread local flag.
1218       // This flag has two effects, one is to force an unwind in the topmost
1219       // interpreter frame and not perform an unlock while doing so.
1220       __ li(R0, 1);
1221       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1222     }
1223     // Increment invocation counter and check for overflow.
1224     if (inc_counter) {
1225       generate_counter_incr(&invocation_counter_overflow, &profile_method, &profile_method_continue);
1226     }
1227 
1228     __ bind(profile_method_continue);
1229 
1230     // Reset the _do_not_unlock_if_synchronized flag.
1231     if (synchronized) {
1232       __ li(R0, 0);
1233       __ stb(R0, in_bytes(JavaThread::do_not_unlock_if_synchronized_offset()), R16_thread);
1234     }
1235   }
1236 
1237   // --------------------------------------------------------------------------
1238   // Locking of synchronized methods. Must happen AFTER invocation_counter
1239   // check and stack overflow check, so method is not locked if overflows.
1240   if (synchronized) {
1241     lock_method(R3_ARG1, R4_ARG2, R5_ARG3);
1242   }
1243 #ifdef ASSERT
1244   else {
1245     Label Lok;
1246     __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1247     __ andi_(R0, R0, JVM_ACC_SYNCHRONIZED);
1248     __ asm_assert_eq("method needs synchronization", 0x8521);
1249     __ bind(Lok);
1250   }
1251 #endif // ASSERT
1252 
1253   __ verify_thread();
1254 
1255   // --------------------------------------------------------------------------
1256   // JVMTI support
1257   __ notify_method_entry();
1258 
1259   // --------------------------------------------------------------------------
1260   // Start executing instructions.
1261   __ dispatch_next(vtos);
1262 
1263   // --------------------------------------------------------------------------
1264   // Out of line counter overflow and MDO creation code.
1265   if (ProfileInterpreter) {
1266     // We have decided to profile this method in the interpreter.
1267     __ bind(profile_method);
1268     __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::profile_method));
1269     __ set_method_data_pointer_for_bcp();
1270     __ b(profile_method_continue);
1271   }
1272 
1273   if (inc_counter) {
1274     // Handle invocation counter overflow.
1275     __ bind(invocation_counter_overflow);
1276     generate_counter_overflow(profile_method_continue);
1277   }
1278   return entry;
1279 }
1280 
1281 // =============================================================================
1282 // Entry points
1283 
1284 address AbstractInterpreterGenerator::generate_method_entry(
1285                                         AbstractInterpreter::MethodKind kind) {
1286   // Determine code generation flags.
1287   bool synchronized = false;
1288   address entry_point = NULL;
1289 
1290   switch (kind) {
1291   case Interpreter::zerolocals             :                                                                             break;
1292   case Interpreter::zerolocals_synchronized: synchronized = true;                                                        break;
1293   case Interpreter::native                 : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(false); break;
1294   case Interpreter::native_synchronized    : entry_point = ((InterpreterGenerator*) this)->generate_native_entry(true);  break;
1295   case Interpreter::empty                  : entry_point = ((InterpreterGenerator*) this)->generate_empty_entry();       break;
1296   case Interpreter::accessor               : entry_point = ((InterpreterGenerator*) this)->generate_accessor_entry();    break;
1297   case Interpreter::abstract               : entry_point = ((InterpreterGenerator*) this)->generate_abstract_entry();    break;
1298 
1299   case Interpreter::java_lang_math_sin     : // fall thru
1300   case Interpreter::java_lang_math_cos     : // fall thru
1301   case Interpreter::java_lang_math_tan     : // fall thru
1302   case Interpreter::java_lang_math_abs     : // fall thru
1303   case Interpreter::java_lang_math_log     : // fall thru
1304   case Interpreter::java_lang_math_log10   : // fall thru
1305   case Interpreter::java_lang_math_sqrt    : // fall thru
1306   case Interpreter::java_lang_math_pow     : // fall thru
1307   case Interpreter::java_lang_math_exp     : entry_point = ((InterpreterGenerator*) this)->generate_math_entry(kind);    break;
1308   case Interpreter::java_lang_ref_reference_get
1309                                            : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break;
1310   default                                  : ShouldNotReachHere();                                                       break;
1311   }
1312 
1313   if (entry_point) {
1314     return entry_point;
1315   }
1316 
1317   return ((InterpreterGenerator*) this)->generate_normal_entry(synchronized);
1318 }
1319 
1320 // These should never be compiled since the interpreter will prefer
1321 // the compiled version to the intrinsic version.
1322 bool AbstractInterpreter::can_be_compiled(methodHandle m) {
1323   return !math_entry_available(method_kind(m));
1324 }
1325 
1326 // How much stack a method activation needs in stack slots.
1327 // We must calc this exactly like in generate_fixed_frame.
1328 // Note: This returns the conservative size assuming maximum alignment.
1329 int AbstractInterpreter::size_top_interpreter_activation(Method* method) {
1330   const int max_alignment_size = 2;
1331   const int abi_scratch = frame::abi_reg_args_size;
1332   return method->max_locals() + method->max_stack() +
1333          frame::interpreter_frame_monitor_size() + max_alignment_size + abi_scratch;
1334 }
1335 
1336 // Returns number of stackElementWords needed for the interpreter frame with the
1337 // given sections.
1338 // This overestimates the stack by one slot in case of alignments.
1339 int AbstractInterpreter::size_activation(int max_stack,
1340                                          int temps,
1341                                          int extra_args,
1342                                          int monitors,
1343                                          int callee_params,
1344                                          int callee_locals,
1345                                          bool is_top_frame) {
1346   // Note: This calculation must exactly parallel the frame setup
1347   // in AbstractInterpreterGenerator::generate_method_entry.
1348   assert(Interpreter::stackElementWords == 1, "sanity");
1349   const int max_alignment_space = StackAlignmentInBytes / Interpreter::stackElementSize;
1350   const int abi_scratch = is_top_frame ? (frame::abi_reg_args_size / Interpreter::stackElementSize) :
1351                                          (frame::abi_minframe_size / Interpreter::stackElementSize);
1352   const int size =
1353     max_stack                                                +
1354     (callee_locals - callee_params)                          +
1355     monitors * frame::interpreter_frame_monitor_size()       +
1356     max_alignment_space                                      +
1357     abi_scratch                                              +
1358     frame::ijava_state_size / Interpreter::stackElementSize;
1359 
1360   // Fixed size of an interpreter frame, align to 16-byte.
1361   return (size & -2);
1362 }
1363 
1364 // Fills a sceletal interpreter frame generated during deoptimizations.
1365 //
1366 // Parameters:
1367 //
1368 // interpreter_frame != NULL:
1369 //   set up the method, locals, and monitors.
1370 //   The frame interpreter_frame, if not NULL, is guaranteed to be the
1371 //   right size, as determined by a previous call to this method.
1372 //   It is also guaranteed to be walkable even though it is in a skeletal state
1373 //
1374 // is_top_frame == true:
1375 //   We're processing the *oldest* interpreter frame!
1376 //
1377 // pop_frame_extra_args:
1378 //   If this is != 0 we are returning to a deoptimized frame by popping
1379 //   off the callee frame. We want to re-execute the call that called the
1380 //   callee interpreted, but since the return to the interpreter would pop
1381 //   the arguments off advance the esp by dummy popframe_extra_args slots.
1382 //   Popping off those will establish the stack layout as it was before the call.
1383 //
1384 void AbstractInterpreter::layout_activation(Method* method,
1385                                             int tempcount,
1386                                             int popframe_extra_args,
1387                                             int moncount,
1388                                             int caller_actual_parameters,
1389                                             int callee_param_count,
1390                                             int callee_locals_count,
1391                                             frame* caller,
1392                                             frame* interpreter_frame,
1393                                             bool is_top_frame,
1394                                             bool is_bottom_frame) {
1395 
1396   const int abi_scratch = is_top_frame ? (frame::abi_reg_args_size / Interpreter::stackElementSize) :
1397                                          (frame::abi_minframe_size / Interpreter::stackElementSize);
1398 
1399   intptr_t* locals_base  = (caller->is_interpreted_frame()) ?
1400     caller->interpreter_frame_esp() + caller_actual_parameters :
1401     caller->sp() + method->max_locals() - 1 + (frame::abi_minframe_size / Interpreter::stackElementSize) ;
1402 
1403   intptr_t* monitor_base = caller->sp() - frame::ijava_state_size / Interpreter::stackElementSize ;
1404   intptr_t* monitor      = monitor_base - (moncount * frame::interpreter_frame_monitor_size());
1405   intptr_t* esp_base     = monitor - 1;
1406   intptr_t* esp          = esp_base - tempcount - popframe_extra_args;
1407   intptr_t* sp           = (intptr_t *) (((intptr_t) (esp_base - callee_locals_count + callee_param_count - method->max_stack()- abi_scratch)) & -StackAlignmentInBytes);
1408   intptr_t* sender_sp    = caller->sp() + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
1409   intptr_t* top_frame_sp = is_top_frame ? sp : sp + (frame::abi_minframe_size - frame::abi_reg_args_size) / Interpreter::stackElementSize;
1410 
1411   interpreter_frame->interpreter_frame_set_method(method);
1412   interpreter_frame->interpreter_frame_set_locals(locals_base);
1413   interpreter_frame->interpreter_frame_set_cpcache(method->constants()->cache());
1414   interpreter_frame->interpreter_frame_set_esp(esp);
1415   interpreter_frame->interpreter_frame_set_monitor_end((BasicObjectLock *)monitor);
1416   interpreter_frame->interpreter_frame_set_top_frame_sp(top_frame_sp);
1417   if (!is_bottom_frame) {
1418     interpreter_frame->interpreter_frame_set_sender_sp(sender_sp);
1419   }
1420 }
1421 
1422 // =============================================================================
1423 // Exceptions
1424 
1425 void TemplateInterpreterGenerator::generate_throw_exception() {
1426   Register Rexception    = R17_tos,
1427            Rcontinuation = R3_RET;
1428 
1429   // --------------------------------------------------------------------------
1430   // Entry point if an method returns with a pending exception (rethrow).
1431   Interpreter::_rethrow_exception_entry = __ pc();
1432   {
1433     __ restore_interpreter_state(R11_scratch1); // Sets R11_scratch1 = fp.
1434     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
1435     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
1436 
1437     // Compiled code destroys templateTableBase, reload.
1438     __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
1439   }
1440 
1441   // Entry point if a interpreted method throws an exception (throw).
1442   Interpreter::_throw_exception_entry = __ pc();
1443   {
1444     __ mr(Rexception, R3_RET);
1445 
1446     __ verify_thread();
1447     __ verify_oop(Rexception);
1448 
1449     // Expression stack must be empty before entering the VM in case of an exception.
1450     __ empty_expression_stack();
1451     // Find exception handler address and preserve exception oop.
1452     // Call C routine to find handler and jump to it.
1453     __ call_VM(Rexception, CAST_FROM_FN_PTR(address, InterpreterRuntime::exception_handler_for_exception), Rexception);
1454     __ mtctr(Rcontinuation);
1455     // Push exception for exception handler bytecodes.
1456     __ push_ptr(Rexception);
1457 
1458     // Jump to exception handler (may be remove activation entry!).
1459     __ bctr();
1460   }
1461 
1462   // If the exception is not handled in the current frame the frame is
1463   // removed and the exception is rethrown (i.e. exception
1464   // continuation is _rethrow_exception).
1465   //
1466   // Note: At this point the bci is still the bxi for the instruction
1467   // which caused the exception and the expression stack is
1468   // empty. Thus, for any VM calls at this point, GC will find a legal
1469   // oop map (with empty expression stack).
1470 
1471   // In current activation
1472   // tos: exception
1473   // bcp: exception bcp
1474 
1475   // --------------------------------------------------------------------------
1476   // JVMTI PopFrame support
1477 
1478   Interpreter::_remove_activation_preserving_args_entry = __ pc();
1479   {
1480     // Set the popframe_processing bit in popframe_condition indicating that we are
1481     // currently handling popframe, so that call_VMs that may happen later do not
1482     // trigger new popframe handling cycles.
1483     __ lwz(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1484     __ ori(R11_scratch1, R11_scratch1, JavaThread::popframe_processing_bit);
1485     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1486 
1487     // Empty the expression stack, as in normal exception handling.
1488     __ empty_expression_stack();
1489     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, /* install_monitor_exception */ false);
1490 
1491     // Check to see whether we are returning to a deoptimized frame.
1492     // (The PopFrame call ensures that the caller of the popped frame is
1493     // either interpreted or compiled and deoptimizes it if compiled.)
1494     // Note that we don't compare the return PC against the
1495     // deoptimization blob's unpack entry because of the presence of
1496     // adapter frames in C2.
1497     Label Lcaller_not_deoptimized;
1498     Register return_pc = R3_ARG1;
1499     __ ld(return_pc, 0, R1_SP);
1500     __ ld(return_pc, _abi(lr), return_pc);
1501     __ call_VM_leaf(CAST_FROM_FN_PTR(address, InterpreterRuntime::interpreter_contains), return_pc);
1502     __ cmpdi(CCR0, R3_RET, 0);
1503     __ bne(CCR0, Lcaller_not_deoptimized);
1504 
1505     // The deoptimized case.
1506     // In this case, we can't call dispatch_next() after the frame is
1507     // popped, but instead must save the incoming arguments and restore
1508     // them after deoptimization has occurred.
1509     __ ld(R4_ARG2, in_bytes(Method::const_offset()), R19_method);
1510     __ lhz(R4_ARG2 /* number of params */, in_bytes(ConstMethod::size_of_parameters_offset()), R4_ARG2);
1511     __ slwi(R4_ARG2, R4_ARG2, Interpreter::logStackElementSize);
1512     __ addi(R5_ARG3, R18_locals, Interpreter::stackElementSize);
1513     __ subf(R5_ARG3, R4_ARG2, R5_ARG3);
1514     // Save these arguments.
1515     __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::popframe_preserve_args), R16_thread, R4_ARG2, R5_ARG3);
1516 
1517     // Inform deoptimization that it is responsible for restoring these arguments.
1518     __ load_const_optimized(R11_scratch1, JavaThread::popframe_force_deopt_reexecution_bit);
1519     __ stw(R11_scratch1, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1520 
1521     // Return from the current method into the deoptimization blob. Will eventually
1522     // end up in the deopt interpeter entry, deoptimization prepared everything that
1523     // we will reexecute the call that called us.
1524     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*reload return_pc*/ return_pc, R11_scratch1, R12_scratch2);
1525     __ mtlr(return_pc);
1526     __ blr();
1527 
1528     // The non-deoptimized case.
1529     __ bind(Lcaller_not_deoptimized);
1530 
1531     // Clear the popframe condition flag.
1532     __ li(R0, 0);
1533     __ stw(R0, in_bytes(JavaThread::popframe_condition_offset()), R16_thread);
1534 
1535     // Get out of the current method and re-execute the call that called us.
1536     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
1537     __ restore_interpreter_state(R11_scratch1);
1538     __ ld(R12_scratch2, _ijava_state_neg(top_frame_sp), R11_scratch1);
1539     __ resize_frame_absolute(R12_scratch2, R11_scratch1, R0);
1540     if (ProfileInterpreter) {
1541       __ set_method_data_pointer_for_bcp();
1542     }
1543 #if INCLUDE_JVMTI
1544     Label L_done;
1545 
1546     __ lbz(R11_scratch1, 0, R14_bcp);
1547     __ cmpwi(CCR0, R11_scratch1, Bytecodes::_invokestatic);
1548     __ bne(CCR0, L_done);
1549 
1550     // The member name argument must be restored if _invokestatic is re-executed after a PopFrame call.
1551     // Detect such a case in the InterpreterRuntime function and return the member name argument, or NULL.
1552     __ ld(R4_ARG2, 0, R18_locals);
1553     __ call_VM(R11_scratch1, CAST_FROM_FN_PTR(address, InterpreterRuntime::member_name_arg_or_null),
1554                R4_ARG2, R19_method, R14_bcp);
1555 
1556     __ cmpdi(CCR0, R11_scratch1, 0);
1557     __ beq(CCR0, L_done);
1558 
1559     __ std(R11_scratch1, wordSize, R15_esp);
1560     __ bind(L_done);
1561 #endif // INCLUDE_JVMTI
1562     __ dispatch_next(vtos);
1563   }
1564   // end of JVMTI PopFrame support
1565 
1566   // --------------------------------------------------------------------------
1567   // Remove activation exception entry.
1568   // This is jumped to if an interpreted method can't handle an exception itself
1569   // (we come from the throw/rethrow exception entry above). We're going to call
1570   // into the VM to find the exception handler in the caller, pop the current
1571   // frame and return the handler we calculated.
1572   Interpreter::_remove_activation_entry = __ pc();
1573   {
1574     __ pop_ptr(Rexception);
1575     __ verify_thread();
1576     __ verify_oop(Rexception);
1577     __ std(Rexception, in_bytes(JavaThread::vm_result_offset()), R16_thread);
1578 
1579     __ unlock_if_synchronized_method(vtos, /* throw_monitor_exception */ false, true);
1580     __ notify_method_exit(false, vtos, InterpreterMacroAssembler::SkipNotifyJVMTI, false);
1581 
1582     __ get_vm_result(Rexception);
1583 
1584     // We are done with this activation frame; find out where to go next.
1585     // The continuation point will be an exception handler, which expects
1586     // the following registers set up:
1587     //
1588     // RET:  exception oop
1589     // ARG2: Issuing PC (see generate_exception_blob()), only used if the caller is compiled.
1590 
1591     Register return_pc = R31; // Needs to survive the runtime call.
1592     __ ld(return_pc, 0, R1_SP);
1593     __ ld(return_pc, _abi(lr), return_pc);
1594     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::exception_handler_for_return_address), R16_thread, return_pc);
1595 
1596     // Remove the current activation.
1597     __ merge_frames(/*top_frame_sp*/ R21_sender_SP, /*return_pc*/ noreg, R11_scratch1, R12_scratch2);
1598 
1599     __ mr(R4_ARG2, return_pc);
1600     __ mtlr(R3_RET);
1601     __ mr(R3_RET, Rexception);
1602     __ blr();
1603   }
1604 }
1605 
1606 // JVMTI ForceEarlyReturn support.
1607 // Returns "in the middle" of a method with a "fake" return value.
1608 address TemplateInterpreterGenerator::generate_earlyret_entry_for(TosState state) {
1609 
1610   Register Rscratch1 = R11_scratch1,
1611            Rscratch2 = R12_scratch2;
1612 
1613   address entry = __ pc();
1614   __ empty_expression_stack();
1615 
1616   __ load_earlyret_value(state, Rscratch1);
1617 
1618   __ ld(Rscratch1, in_bytes(JavaThread::jvmti_thread_state_offset()), R16_thread);
1619   // Clear the earlyret state.
1620   __ li(R0, 0);
1621   __ stw(R0, in_bytes(JvmtiThreadState::earlyret_state_offset()), Rscratch1);
1622 
1623   __ remove_activation(state, false, false);
1624   // Copied from TemplateTable::_return.
1625   // Restoration of lr done by remove_activation.
1626   switch (state) {
1627     case ltos:
1628     case btos:
1629     case ctos:
1630     case stos:
1631     case atos:
1632     case itos: __ mr(R3_RET, R17_tos); break;
1633     case ftos:
1634     case dtos: __ fmr(F1_RET, F15_ftos); break;
1635     case vtos: // This might be a constructor. Final fields (and volatile fields on PPC64) need
1636                // to get visible before the reference to the object gets stored anywhere.
1637                __ membar(Assembler::StoreStore); break;
1638     default  : ShouldNotReachHere();
1639   }
1640   __ blr();
1641 
1642   return entry;
1643 } // end of ForceEarlyReturn support
1644 
1645 //-----------------------------------------------------------------------------
1646 // Helper for vtos entry point generation
1647 
1648 void TemplateInterpreterGenerator::set_vtos_entry_points(Template* t,
1649                                                          address& bep,
1650                                                          address& cep,
1651                                                          address& sep,
1652                                                          address& aep,
1653                                                          address& iep,
1654                                                          address& lep,
1655                                                          address& fep,
1656                                                          address& dep,
1657                                                          address& vep) {
1658   assert(t->is_valid() && t->tos_in() == vtos, "illegal template");
1659   Label L;
1660 
1661   aep = __ pc();  __ push_ptr();  __ b(L);
1662   fep = __ pc();  __ push_f();    __ b(L);
1663   dep = __ pc();  __ push_d();    __ b(L);
1664   lep = __ pc();  __ push_l();    __ b(L);
1665   __ align(32, 12, 24); // align L
1666   bep = cep = sep =
1667   iep = __ pc();  __ push_i();
1668   vep = __ pc();
1669   __ bind(L);
1670   generate_and_dispatch(t);
1671 }
1672 
1673 //-----------------------------------------------------------------------------
1674 // Generation of individual instructions
1675 
1676 // helpers for generate_and_dispatch
1677 
1678 InterpreterGenerator::InterpreterGenerator(StubQueue* code)
1679   : TemplateInterpreterGenerator(code) {
1680   generate_all(); // Down here so it can be "virtual".
1681 }
1682 
1683 //-----------------------------------------------------------------------------
1684 
1685 // Non-product code
1686 #ifndef PRODUCT
1687 address TemplateInterpreterGenerator::generate_trace_code(TosState state) {
1688   //__ flush_bundle();
1689   address entry = __ pc();
1690 
1691   const char *bname = NULL;
1692   uint tsize = 0;
1693   switch(state) {
1694   case ftos:
1695     bname = "trace_code_ftos {";
1696     tsize = 2;
1697     break;
1698   case btos:
1699     bname = "trace_code_btos {";
1700     tsize = 2;
1701     break;
1702   case ctos:
1703     bname = "trace_code_ctos {";
1704     tsize = 2;
1705     break;
1706   case stos:
1707     bname = "trace_code_stos {";
1708     tsize = 2;
1709     break;
1710   case itos:
1711     bname = "trace_code_itos {";
1712     tsize = 2;
1713     break;
1714   case ltos:
1715     bname = "trace_code_ltos {";
1716     tsize = 3;
1717     break;
1718   case atos:
1719     bname = "trace_code_atos {";
1720     tsize = 2;
1721     break;
1722   case vtos:
1723     // Note: In case of vtos, the topmost of stack value could be a int or doubl
1724     // In case of a double (2 slots) we won't see the 2nd stack value.
1725     // Maybe we simply should print the topmost 3 stack slots to cope with the problem.
1726     bname = "trace_code_vtos {";
1727     tsize = 2;
1728 
1729     break;
1730   case dtos:
1731     bname = "trace_code_dtos {";
1732     tsize = 3;
1733     break;
1734   default:
1735     ShouldNotReachHere();
1736   }
1737   BLOCK_COMMENT(bname);
1738 
1739   // Support short-cut for TraceBytecodesAt.
1740   // Don't call into the VM if we don't want to trace to speed up things.
1741   Label Lskip_vm_call;
1742   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
1743     int offs1 = __ load_const_optimized(R11_scratch1, (address) &TraceBytecodesAt, R0, true);
1744     int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
1745     __ ld(R11_scratch1, offs1, R11_scratch1);
1746     __ lwa(R12_scratch2, offs2, R12_scratch2);
1747     __ cmpd(CCR0, R12_scratch2, R11_scratch1);
1748     __ blt(CCR0, Lskip_vm_call);
1749   }
1750 
1751   __ push(state);
1752   // Load 2 topmost expression stack values.
1753   __ ld(R6_ARG4, tsize*Interpreter::stackElementSize, R15_esp);
1754   __ ld(R5_ARG3, Interpreter::stackElementSize, R15_esp);
1755   __ mflr(R31);
1756   __ call_VM(noreg, CAST_FROM_FN_PTR(address, SharedRuntime::trace_bytecode), /* unused */ R4_ARG2, R5_ARG3, R6_ARG4, false);
1757   __ mtlr(R31);
1758   __ pop(state);
1759 
1760   if (TraceBytecodesAt > 0 && TraceBytecodesAt < max_intx) {
1761     __ bind(Lskip_vm_call);
1762   }
1763   __ blr();
1764   BLOCK_COMMENT("} trace_code");
1765   return entry;
1766 }
1767 
1768 void TemplateInterpreterGenerator::count_bytecode() {
1769   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeCounter::_counter_value, R12_scratch2, true);
1770   __ lwz(R12_scratch2, offs, R11_scratch1);
1771   __ addi(R12_scratch2, R12_scratch2, 1);
1772   __ stw(R12_scratch2, offs, R11_scratch1);
1773 }
1774 
1775 void TemplateInterpreterGenerator::histogram_bytecode(Template* t) {
1776   int offs = __ load_const_optimized(R11_scratch1, (address) &BytecodeHistogram::_counters[t->bytecode()], R12_scratch2, true);
1777   __ lwz(R12_scratch2, offs, R11_scratch1);
1778   __ addi(R12_scratch2, R12_scratch2, 1);
1779   __ stw(R12_scratch2, offs, R11_scratch1);
1780 }
1781 
1782 void TemplateInterpreterGenerator::histogram_bytecode_pair(Template* t) {
1783   const Register addr = R11_scratch1,
1784                  tmp  = R12_scratch2;
1785   // Get index, shift out old bytecode, bring in new bytecode, and store it.
1786   // _index = (_index >> log2_number_of_codes) |
1787   //          (bytecode << log2_number_of_codes);
1788   int offs1 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_index, tmp, true);
1789   __ lwz(tmp, offs1, addr);
1790   __ srwi(tmp, tmp, BytecodePairHistogram::log2_number_of_codes);
1791   __ ori(tmp, tmp, ((int) t->bytecode()) << BytecodePairHistogram::log2_number_of_codes);
1792   __ stw(tmp, offs1, addr);
1793 
1794   // Bump bucket contents.
1795   // _counters[_index] ++;
1796   int offs2 = __ load_const_optimized(addr, (address)&BytecodePairHistogram::_counters, R0, true);
1797   __ sldi(tmp, tmp, LogBytesPerInt);
1798   __ add(addr, tmp, addr);
1799   __ lwz(tmp, offs2, addr);
1800   __ addi(tmp, tmp, 1);
1801   __ stw(tmp, offs2, addr);
1802 }
1803 
1804 void TemplateInterpreterGenerator::trace_bytecode(Template* t) {
1805   // Call a little run-time stub to avoid blow-up for each bytecode.
1806   // The run-time runtime saves the right registers, depending on
1807   // the tosca in-state for the given template.
1808 
1809   assert(Interpreter::trace_code(t->tos_in()) != NULL,
1810          "entry must have been generated");
1811 
1812   // Note: we destroy LR here.
1813   __ bl(Interpreter::trace_code(t->tos_in()));
1814 }
1815 
1816 void TemplateInterpreterGenerator::stop_interpreter_at() {
1817   Label L;
1818   int offs1 = __ load_const_optimized(R11_scratch1, (address) &StopInterpreterAt, R0, true);
1819   int offs2 = __ load_const_optimized(R12_scratch2, (address) &BytecodeCounter::_counter_value, R0, true);
1820   __ ld(R11_scratch1, offs1, R11_scratch1);
1821   __ lwa(R12_scratch2, offs2, R12_scratch2);
1822   __ cmpd(CCR0, R12_scratch2, R11_scratch1);
1823   __ bne(CCR0, L);
1824   __ illtrap();
1825   __ bind(L);
1826 }
1827 
1828 #endif // !PRODUCT
1829 #endif // !CC_INTERP