1 /*
   2  * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2012, 2021 SAP SE. All rights reserved.
   4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5  *
   6  * This code is free software; you can redistribute it and/or modify it
   7  * under the terms of the GNU General Public License version 2 only, as
   8  * published by the Free Software Foundation.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  *
  24  */
  25 
  26 #include "precompiled.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/vtableStubs.hpp"
  31 #include "frame_ppc.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/shared/gcLocker.hpp"
  34 #include "interpreter/interpreter.hpp"
  35 #include "interpreter/interp_masm.hpp"
  36 #include "memory/resourceArea.hpp"
  37 #include "oops/compiledICHolder.hpp"
  38 #include "oops/klass.inline.hpp"
  39 #include "prims/methodHandles.hpp"
  40 #include "runtime/jniHandles.hpp"
  41 #include "runtime/os.inline.hpp"
  42 #include "runtime/safepointMechanism.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/signature.hpp"
  45 #include "runtime/stubRoutines.hpp"
  46 #include "runtime/vframeArray.hpp"
  47 #include "utilities/align.hpp"
  48 #include "utilities/macros.hpp"
  49 #include "vmreg_ppc.inline.hpp"
  50 #ifdef COMPILER1
  51 #include "c1/c1_Runtime1.hpp"
  52 #endif
  53 #ifdef COMPILER2
  54 #include "opto/ad.hpp"
  55 #include "opto/runtime.hpp"
  56 #endif
  57 
  58 #include <alloca.h>
  59 
  60 #define __ masm->
  61 
  62 #ifdef PRODUCT
  63 #define BLOCK_COMMENT(str) // nothing
  64 #else
  65 #define BLOCK_COMMENT(str) __ block_comment(str)
  66 #endif
  67 
  68 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  69 
  70 
  71 class RegisterSaver {
  72  // Used for saving volatile registers.
  73  public:
  74 
  75   // Support different return pc locations.
  76   enum ReturnPCLocation {
  77     return_pc_is_lr,
  78     return_pc_is_pre_saved,
  79     return_pc_is_thread_saved_exception_pc
  80   };
  81 
  82   static OopMap* push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
  83                          int* out_frame_size_in_bytes,
  84                          bool generate_oop_map,
  85                          int return_pc_adjustment,
  86                          ReturnPCLocation return_pc_location,
  87                          bool save_vectors = false);
  88   static void    restore_live_registers_and_pop_frame(MacroAssembler* masm,
  89                          int frame_size_in_bytes,
  90                          bool restore_ctr,
  91                          bool save_vectors = false);
  92 
  93   static void push_frame_and_save_argument_registers(MacroAssembler* masm,
  94                          Register r_temp,
  95                          int frame_size,
  96                          int total_args,
  97                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
  98   static void restore_argument_registers_and_pop_frame(MacroAssembler*masm,
  99                          int frame_size,
 100                          int total_args,
 101                          const VMRegPair *regs, const VMRegPair *regs2 = NULL);
 102 
 103   // During deoptimization only the result registers need to be restored
 104   // all the other values have already been extracted.
 105   static void restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes);
 106 
 107   // Constants and data structures:
 108 
 109   typedef enum {
 110     int_reg,
 111     float_reg,
 112     special_reg,
 113     vs_reg
 114   } RegisterType;
 115 
 116   typedef enum {
 117     reg_size          = 8,
 118     half_reg_size     = reg_size / 2,
 119     vs_reg_size       = 16
 120   } RegisterConstants;
 121 
 122   typedef struct {
 123     RegisterType        reg_type;
 124     int                 reg_num;
 125     VMReg               vmreg;
 126   } LiveRegType;
 127 };
 128 
 129 
 130 #define RegisterSaver_LiveIntReg(regname) \
 131   { RegisterSaver::int_reg,     regname->encoding(), regname->as_VMReg() }
 132 
 133 #define RegisterSaver_LiveFloatReg(regname) \
 134   { RegisterSaver::float_reg,   regname->encoding(), regname->as_VMReg() }
 135 
 136 #define RegisterSaver_LiveSpecialReg(regname) \
 137   { RegisterSaver::special_reg, regname->encoding(), regname->as_VMReg() }
 138 
 139 #define RegisterSaver_LiveVSReg(regname) \
 140   { RegisterSaver::vs_reg,      regname->encoding(), regname->as_VMReg() }
 141 
 142 static const RegisterSaver::LiveRegType RegisterSaver_LiveRegs[] = {
 143   // Live registers which get spilled to the stack. Register
 144   // positions in this array correspond directly to the stack layout.
 145 
 146   //
 147   // live special registers:
 148   //
 149   RegisterSaver_LiveSpecialReg(SR_CTR),
 150   //
 151   // live float registers:
 152   //
 153   RegisterSaver_LiveFloatReg( F0  ),
 154   RegisterSaver_LiveFloatReg( F1  ),
 155   RegisterSaver_LiveFloatReg( F2  ),
 156   RegisterSaver_LiveFloatReg( F3  ),
 157   RegisterSaver_LiveFloatReg( F4  ),
 158   RegisterSaver_LiveFloatReg( F5  ),
 159   RegisterSaver_LiveFloatReg( F6  ),
 160   RegisterSaver_LiveFloatReg( F7  ),
 161   RegisterSaver_LiveFloatReg( F8  ),
 162   RegisterSaver_LiveFloatReg( F9  ),
 163   RegisterSaver_LiveFloatReg( F10 ),
 164   RegisterSaver_LiveFloatReg( F11 ),
 165   RegisterSaver_LiveFloatReg( F12 ),
 166   RegisterSaver_LiveFloatReg( F13 ),
 167   RegisterSaver_LiveFloatReg( F14 ),
 168   RegisterSaver_LiveFloatReg( F15 ),
 169   RegisterSaver_LiveFloatReg( F16 ),
 170   RegisterSaver_LiveFloatReg( F17 ),
 171   RegisterSaver_LiveFloatReg( F18 ),
 172   RegisterSaver_LiveFloatReg( F19 ),
 173   RegisterSaver_LiveFloatReg( F20 ),
 174   RegisterSaver_LiveFloatReg( F21 ),
 175   RegisterSaver_LiveFloatReg( F22 ),
 176   RegisterSaver_LiveFloatReg( F23 ),
 177   RegisterSaver_LiveFloatReg( F24 ),
 178   RegisterSaver_LiveFloatReg( F25 ),
 179   RegisterSaver_LiveFloatReg( F26 ),
 180   RegisterSaver_LiveFloatReg( F27 ),
 181   RegisterSaver_LiveFloatReg( F28 ),
 182   RegisterSaver_LiveFloatReg( F29 ),
 183   RegisterSaver_LiveFloatReg( F30 ),
 184   RegisterSaver_LiveFloatReg( F31 ),
 185   //
 186   // live integer registers:
 187   //
 188   RegisterSaver_LiveIntReg(   R0  ),
 189   //RegisterSaver_LiveIntReg( R1  ), // stack pointer
 190   RegisterSaver_LiveIntReg(   R2  ),
 191   RegisterSaver_LiveIntReg(   R3  ),
 192   RegisterSaver_LiveIntReg(   R4  ),
 193   RegisterSaver_LiveIntReg(   R5  ),
 194   RegisterSaver_LiveIntReg(   R6  ),
 195   RegisterSaver_LiveIntReg(   R7  ),
 196   RegisterSaver_LiveIntReg(   R8  ),
 197   RegisterSaver_LiveIntReg(   R9  ),
 198   RegisterSaver_LiveIntReg(   R10 ),
 199   RegisterSaver_LiveIntReg(   R11 ),
 200   RegisterSaver_LiveIntReg(   R12 ),
 201   //RegisterSaver_LiveIntReg( R13 ), // system thread id
 202   RegisterSaver_LiveIntReg(   R14 ),
 203   RegisterSaver_LiveIntReg(   R15 ),
 204   RegisterSaver_LiveIntReg(   R16 ),
 205   RegisterSaver_LiveIntReg(   R17 ),
 206   RegisterSaver_LiveIntReg(   R18 ),
 207   RegisterSaver_LiveIntReg(   R19 ),
 208   RegisterSaver_LiveIntReg(   R20 ),
 209   RegisterSaver_LiveIntReg(   R21 ),
 210   RegisterSaver_LiveIntReg(   R22 ),
 211   RegisterSaver_LiveIntReg(   R23 ),
 212   RegisterSaver_LiveIntReg(   R24 ),
 213   RegisterSaver_LiveIntReg(   R25 ),
 214   RegisterSaver_LiveIntReg(   R26 ),
 215   RegisterSaver_LiveIntReg(   R27 ),
 216   RegisterSaver_LiveIntReg(   R28 ),
 217   RegisterSaver_LiveIntReg(   R29 ),
 218   RegisterSaver_LiveIntReg(   R30 ),
 219   RegisterSaver_LiveIntReg(   R31 )  // must be the last register (see save/restore functions below)
 220 };
 221 
 222 static const RegisterSaver::LiveRegType RegisterSaver_LiveVSRegs[] = {
 223   //
 224   // live vector scalar registers (optional, only these ones are used by C2):
 225   //
 226   RegisterSaver_LiveVSReg( VSR32 ),
 227   RegisterSaver_LiveVSReg( VSR33 ),
 228   RegisterSaver_LiveVSReg( VSR34 ),
 229   RegisterSaver_LiveVSReg( VSR35 ),
 230   RegisterSaver_LiveVSReg( VSR36 ),
 231   RegisterSaver_LiveVSReg( VSR37 ),
 232   RegisterSaver_LiveVSReg( VSR38 ),
 233   RegisterSaver_LiveVSReg( VSR39 ),
 234   RegisterSaver_LiveVSReg( VSR40 ),
 235   RegisterSaver_LiveVSReg( VSR41 ),
 236   RegisterSaver_LiveVSReg( VSR42 ),
 237   RegisterSaver_LiveVSReg( VSR43 ),
 238   RegisterSaver_LiveVSReg( VSR44 ),
 239   RegisterSaver_LiveVSReg( VSR45 ),
 240   RegisterSaver_LiveVSReg( VSR46 ),
 241   RegisterSaver_LiveVSReg( VSR47 ),
 242   RegisterSaver_LiveVSReg( VSR48 ),
 243   RegisterSaver_LiveVSReg( VSR49 ),
 244   RegisterSaver_LiveVSReg( VSR50 ),
 245   RegisterSaver_LiveVSReg( VSR51 )
 246 };
 247 
 248 
 249 OopMap* RegisterSaver::push_frame_reg_args_and_save_live_registers(MacroAssembler* masm,
 250                          int* out_frame_size_in_bytes,
 251                          bool generate_oop_map,
 252                          int return_pc_adjustment,
 253                          ReturnPCLocation return_pc_location,
 254                          bool save_vectors) {
 255   // Push an abi_reg_args-frame and store all registers which may be live.
 256   // If requested, create an OopMap: Record volatile registers as
 257   // callee-save values in an OopMap so their save locations will be
 258   // propagated to the RegisterMap of the caller frame during
 259   // StackFrameStream construction (needed for deoptimization; see
 260   // compiledVFrame::create_stack_value).
 261   // If return_pc_adjustment != 0 adjust the return pc by return_pc_adjustment.
 262   // Updated return pc is returned in R31 (if not return_pc_is_pre_saved).
 263 
 264   // calculate frame size
 265   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 266                                    sizeof(RegisterSaver::LiveRegType);
 267   const int vsregstosave_num     = save_vectors ? (sizeof(RegisterSaver_LiveVSRegs) /
 268                                                    sizeof(RegisterSaver::LiveRegType))
 269                                                 : 0;
 270   const int register_save_size   = regstosave_num * reg_size + vsregstosave_num * vs_reg_size;
 271   const int frame_size_in_bytes  = align_up(register_save_size, frame::alignment_in_bytes)
 272                                    + frame::abi_reg_args_size;
 273 
 274   *out_frame_size_in_bytes       = frame_size_in_bytes;
 275   const int frame_size_in_slots  = frame_size_in_bytes / sizeof(jint);
 276   const int register_save_offset = frame_size_in_bytes - register_save_size;
 277 
 278   // OopMap frame size is in c2 stack slots (sizeof(jint)) not bytes or words.
 279   OopMap* map = generate_oop_map ? new OopMap(frame_size_in_slots, 0) : NULL;
 280 
 281   BLOCK_COMMENT("push_frame_reg_args_and_save_live_registers {");
 282 
 283   // push a new frame
 284   __ push_frame(frame_size_in_bytes, noreg);
 285 
 286   // Save some registers in the last (non-vector) slots of the new frame so we
 287   // can use them as scratch regs or to determine the return pc.
 288   __ std(R31, frame_size_in_bytes -   reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 289   __ std(R30, frame_size_in_bytes - 2*reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 290 
 291   // save the flags
 292   // Do the save_LR_CR by hand and adjust the return pc if requested.
 293   __ mfcr(R30);
 294   __ std(R30, frame_size_in_bytes + _abi0(cr), R1_SP);
 295   switch (return_pc_location) {
 296     case return_pc_is_lr: __ mflr(R31); break;
 297     case return_pc_is_pre_saved: assert(return_pc_adjustment == 0, "unsupported"); break;
 298     case return_pc_is_thread_saved_exception_pc: __ ld(R31, thread_(saved_exception_pc)); break;
 299     default: ShouldNotReachHere();
 300   }
 301   if (return_pc_location != return_pc_is_pre_saved) {
 302     if (return_pc_adjustment != 0) {
 303       __ addi(R31, R31, return_pc_adjustment);
 304     }
 305     __ std(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
 306   }
 307 
 308   // save all registers (ints and floats)
 309   int offset = register_save_offset;
 310 
 311   for (int i = 0; i < regstosave_num; i++) {
 312     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 313     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 314 
 315     switch (reg_type) {
 316       case RegisterSaver::int_reg: {
 317         if (reg_num < 30) { // We spilled R30-31 right at the beginning.
 318           __ std(as_Register(reg_num), offset, R1_SP);
 319         }
 320         break;
 321       }
 322       case RegisterSaver::float_reg: {
 323         __ stfd(as_FloatRegister(reg_num), offset, R1_SP);
 324         break;
 325       }
 326       case RegisterSaver::special_reg: {
 327         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 328           __ mfctr(R30);
 329           __ std(R30, offset, R1_SP);
 330         } else {
 331           Unimplemented();
 332         }
 333         break;
 334       }
 335       default:
 336         ShouldNotReachHere();
 337     }
 338 
 339     if (generate_oop_map) {
 340       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 341                             RegisterSaver_LiveRegs[i].vmreg);
 342       map->set_callee_saved(VMRegImpl::stack2reg((offset + half_reg_size)>>2),
 343                             RegisterSaver_LiveRegs[i].vmreg->next());
 344     }
 345     offset += reg_size;
 346   }
 347 
 348   for (int i = 0; i < vsregstosave_num; i++) {
 349     int reg_num  = RegisterSaver_LiveVSRegs[i].reg_num;
 350     int reg_type = RegisterSaver_LiveVSRegs[i].reg_type;
 351 
 352     __ li(R30, offset);
 353     __ stxvd2x(as_VectorSRegister(reg_num), R30, R1_SP);
 354 
 355     if (generate_oop_map) {
 356       map->set_callee_saved(VMRegImpl::stack2reg(offset>>2),
 357                             RegisterSaver_LiveVSRegs[i].vmreg);
 358     }
 359     offset += vs_reg_size;
 360   }
 361 
 362   assert(offset == frame_size_in_bytes, "consistency check");
 363 
 364   BLOCK_COMMENT("} push_frame_reg_args_and_save_live_registers");
 365 
 366   // And we're done.
 367   return map;
 368 }
 369 
 370 
 371 // Pop the current frame and restore all the registers that we
 372 // saved.
 373 void RegisterSaver::restore_live_registers_and_pop_frame(MacroAssembler* masm,
 374                                                          int frame_size_in_bytes,
 375                                                          bool restore_ctr,
 376                                                          bool save_vectors) {
 377   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 378                                    sizeof(RegisterSaver::LiveRegType);
 379   const int vsregstosave_num     = save_vectors ? (sizeof(RegisterSaver_LiveVSRegs) /
 380                                                    sizeof(RegisterSaver::LiveRegType))
 381                                                 : 0;
 382   const int register_save_size   = regstosave_num * reg_size + vsregstosave_num * vs_reg_size;
 383 
 384   const int register_save_offset = frame_size_in_bytes - register_save_size;
 385 
 386   BLOCK_COMMENT("restore_live_registers_and_pop_frame {");
 387 
 388   // restore all registers (ints and floats)
 389   int offset = register_save_offset;
 390 
 391   for (int i = 0; i < regstosave_num; i++) {
 392     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 393     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 394 
 395     switch (reg_type) {
 396       case RegisterSaver::int_reg: {
 397         if (reg_num != 31) // R31 restored at the end, it's the tmp reg!
 398           __ ld(as_Register(reg_num), offset, R1_SP);
 399         break;
 400       }
 401       case RegisterSaver::float_reg: {
 402         __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 403         break;
 404       }
 405       case RegisterSaver::special_reg: {
 406         if (reg_num == SR_CTR_SpecialRegisterEnumValue) {
 407           if (restore_ctr) { // Nothing to do here if ctr already contains the next address.
 408             __ ld(R31, offset, R1_SP);
 409             __ mtctr(R31);
 410           }
 411         } else {
 412           Unimplemented();
 413         }
 414         break;
 415       }
 416       default:
 417         ShouldNotReachHere();
 418     }
 419     offset += reg_size;
 420   }
 421 
 422   for (int i = 0; i < vsregstosave_num; i++) {
 423     int reg_num  = RegisterSaver_LiveVSRegs[i].reg_num;
 424     int reg_type = RegisterSaver_LiveVSRegs[i].reg_type;
 425 
 426     __ li(R31, offset);
 427     __ lxvd2x(as_VectorSRegister(reg_num), R31, R1_SP);
 428 
 429     offset += vs_reg_size;
 430   }
 431 
 432   assert(offset == frame_size_in_bytes, "consistency check");
 433 
 434   // restore link and the flags
 435   __ ld(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
 436   __ mtlr(R31);
 437 
 438   __ ld(R31, frame_size_in_bytes + _abi0(cr), R1_SP);
 439   __ mtcr(R31);
 440 
 441   // restore scratch register's value
 442   __ ld(R31, frame_size_in_bytes - reg_size - vsregstosave_num * vs_reg_size, R1_SP);
 443 
 444   // pop the frame
 445   __ addi(R1_SP, R1_SP, frame_size_in_bytes);
 446 
 447   BLOCK_COMMENT("} restore_live_registers_and_pop_frame");
 448 }
 449 
 450 void RegisterSaver::push_frame_and_save_argument_registers(MacroAssembler* masm, Register r_temp,
 451                                                            int frame_size,int total_args, const VMRegPair *regs,
 452                                                            const VMRegPair *regs2) {
 453   __ push_frame(frame_size, r_temp);
 454   int st_off = frame_size - wordSize;
 455   for (int i = 0; i < total_args; i++) {
 456     VMReg r_1 = regs[i].first();
 457     VMReg r_2 = regs[i].second();
 458     if (!r_1->is_valid()) {
 459       assert(!r_2->is_valid(), "");
 460       continue;
 461     }
 462     if (r_1->is_Register()) {
 463       Register r = r_1->as_Register();
 464       __ std(r, st_off, R1_SP);
 465       st_off -= wordSize;
 466     } else if (r_1->is_FloatRegister()) {
 467       FloatRegister f = r_1->as_FloatRegister();
 468       __ stfd(f, st_off, R1_SP);
 469       st_off -= wordSize;
 470     }
 471   }
 472   if (regs2 != NULL) {
 473     for (int i = 0; i < total_args; i++) {
 474       VMReg r_1 = regs2[i].first();
 475       VMReg r_2 = regs2[i].second();
 476       if (!r_1->is_valid()) {
 477         assert(!r_2->is_valid(), "");
 478         continue;
 479       }
 480       if (r_1->is_Register()) {
 481         Register r = r_1->as_Register();
 482         __ std(r, st_off, R1_SP);
 483         st_off -= wordSize;
 484       } else if (r_1->is_FloatRegister()) {
 485         FloatRegister f = r_1->as_FloatRegister();
 486         __ stfd(f, st_off, R1_SP);
 487         st_off -= wordSize;
 488       }
 489     }
 490   }
 491 }
 492 
 493 void RegisterSaver::restore_argument_registers_and_pop_frame(MacroAssembler*masm, int frame_size,
 494                                                              int total_args, const VMRegPair *regs,
 495                                                              const VMRegPair *regs2) {
 496   int st_off = frame_size - wordSize;
 497   for (int i = 0; i < total_args; i++) {
 498     VMReg r_1 = regs[i].first();
 499     VMReg r_2 = regs[i].second();
 500     if (r_1->is_Register()) {
 501       Register r = r_1->as_Register();
 502       __ ld(r, st_off, R1_SP);
 503       st_off -= wordSize;
 504     } else if (r_1->is_FloatRegister()) {
 505       FloatRegister f = r_1->as_FloatRegister();
 506       __ lfd(f, st_off, R1_SP);
 507       st_off -= wordSize;
 508     }
 509   }
 510   if (regs2 != NULL)
 511     for (int i = 0; i < total_args; i++) {
 512       VMReg r_1 = regs2[i].first();
 513       VMReg r_2 = regs2[i].second();
 514       if (r_1->is_Register()) {
 515         Register r = r_1->as_Register();
 516         __ ld(r, st_off, R1_SP);
 517         st_off -= wordSize;
 518       } else if (r_1->is_FloatRegister()) {
 519         FloatRegister f = r_1->as_FloatRegister();
 520         __ lfd(f, st_off, R1_SP);
 521         st_off -= wordSize;
 522       }
 523     }
 524   __ pop_frame();
 525 }
 526 
 527 // Restore the registers that might be holding a result.
 528 void RegisterSaver::restore_result_registers(MacroAssembler* masm, int frame_size_in_bytes) {
 529   const int regstosave_num       = sizeof(RegisterSaver_LiveRegs) /
 530                                    sizeof(RegisterSaver::LiveRegType);
 531   const int register_save_size   = regstosave_num * reg_size; // VS registers not relevant here.
 532   const int register_save_offset = frame_size_in_bytes - register_save_size;
 533 
 534   // restore all result registers (ints and floats)
 535   int offset = register_save_offset;
 536   for (int i = 0; i < regstosave_num; i++) {
 537     int reg_num  = RegisterSaver_LiveRegs[i].reg_num;
 538     int reg_type = RegisterSaver_LiveRegs[i].reg_type;
 539     switch (reg_type) {
 540       case RegisterSaver::int_reg: {
 541         if (as_Register(reg_num)==R3_RET) // int result_reg
 542           __ ld(as_Register(reg_num), offset, R1_SP);
 543         break;
 544       }
 545       case RegisterSaver::float_reg: {
 546         if (as_FloatRegister(reg_num)==F1_RET) // float result_reg
 547           __ lfd(as_FloatRegister(reg_num), offset, R1_SP);
 548         break;
 549       }
 550       case RegisterSaver::special_reg: {
 551         // Special registers don't hold a result.
 552         break;
 553       }
 554       default:
 555         ShouldNotReachHere();
 556     }
 557     offset += reg_size;
 558   }
 559 
 560   assert(offset == frame_size_in_bytes, "consistency check");
 561 }
 562 
 563 // Is vector's size (in bytes) bigger than a size saved by default?
 564 bool SharedRuntime::is_wide_vector(int size) {
 565   // Note, MaxVectorSize == 8/16 on PPC64.
 566   assert(size <= (SuperwordUseVSX ? 16 : 8), "%d bytes vectors are not supported", size);
 567   return size > 8;
 568 }
 569 
 570 static int reg2slot(VMReg r) {
 571   return r->reg2stack() + SharedRuntime::out_preserve_stack_slots();
 572 }
 573 
 574 static int reg2offset(VMReg r) {
 575   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 576 }
 577 
 578 // ---------------------------------------------------------------------------
 579 // Read the array of BasicTypes from a signature, and compute where the
 580 // arguments should go. Values in the VMRegPair regs array refer to 4-byte
 581 // quantities. Values less than VMRegImpl::stack0 are registers, those above
 582 // refer to 4-byte stack slots. All stack slots are based off of the stack pointer
 583 // as framesizes are fixed.
 584 // VMRegImpl::stack0 refers to the first slot 0(sp).
 585 // and VMRegImpl::stack0+1 refers to the memory word 4-bytes higher. Register
 586 // up to RegisterImpl::number_of_registers) are the 64-bit
 587 // integer registers.
 588 
 589 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 590 // either 32-bit or 64-bit depending on the build. The OUTPUTS are in 32-bit
 591 // units regardless of build. Of course for i486 there is no 64 bit build
 592 
 593 // The Java calling convention is a "shifted" version of the C ABI.
 594 // By skipping the first C ABI register we can call non-static jni methods
 595 // with small numbers of arguments without having to shuffle the arguments
 596 // at all. Since we control the java ABI we ought to at least get some
 597 // advantage out of it.
 598 
 599 const VMReg java_iarg_reg[8] = {
 600   R3->as_VMReg(),
 601   R4->as_VMReg(),
 602   R5->as_VMReg(),
 603   R6->as_VMReg(),
 604   R7->as_VMReg(),
 605   R8->as_VMReg(),
 606   R9->as_VMReg(),
 607   R10->as_VMReg()
 608 };
 609 
 610 const VMReg java_farg_reg[13] = {
 611   F1->as_VMReg(),
 612   F2->as_VMReg(),
 613   F3->as_VMReg(),
 614   F4->as_VMReg(),
 615   F5->as_VMReg(),
 616   F6->as_VMReg(),
 617   F7->as_VMReg(),
 618   F8->as_VMReg(),
 619   F9->as_VMReg(),
 620   F10->as_VMReg(),
 621   F11->as_VMReg(),
 622   F12->as_VMReg(),
 623   F13->as_VMReg()
 624 };
 625 
 626 const int num_java_iarg_registers = sizeof(java_iarg_reg) / sizeof(java_iarg_reg[0]);
 627 const int num_java_farg_registers = sizeof(java_farg_reg) / sizeof(java_farg_reg[0]);
 628 
 629 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 630                                            VMRegPair *regs,
 631                                            int total_args_passed) {
 632   // C2c calling conventions for compiled-compiled calls.
 633   // Put 8 ints/longs into registers _AND_ 13 float/doubles into
 634   // registers _AND_ put the rest on the stack.
 635 
 636   const int inc_stk_for_intfloat   = 1; // 1 slots for ints and floats
 637   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 638 
 639   int i;
 640   VMReg reg;
 641   int stk = 0;
 642   int ireg = 0;
 643   int freg = 0;
 644 
 645   // We put the first 8 arguments into registers and the rest on the
 646   // stack, float arguments are already in their argument registers
 647   // due to c2c calling conventions (see calling_convention).
 648   for (int i = 0; i < total_args_passed; ++i) {
 649     switch(sig_bt[i]) {
 650     case T_BOOLEAN:
 651     case T_CHAR:
 652     case T_BYTE:
 653     case T_SHORT:
 654     case T_INT:
 655       if (ireg < num_java_iarg_registers) {
 656         // Put int/ptr in register
 657         reg = java_iarg_reg[ireg];
 658         ++ireg;
 659       } else {
 660         // Put int/ptr on stack.
 661         reg = VMRegImpl::stack2reg(stk);
 662         stk += inc_stk_for_intfloat;
 663       }
 664       regs[i].set1(reg);
 665       break;
 666     case T_LONG:
 667       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 668       if (ireg < num_java_iarg_registers) {
 669         // Put long in register.
 670         reg = java_iarg_reg[ireg];
 671         ++ireg;
 672       } else {
 673         // Put long on stack. They must be aligned to 2 slots.
 674         if (stk & 0x1) ++stk;
 675         reg = VMRegImpl::stack2reg(stk);
 676         stk += inc_stk_for_longdouble;
 677       }
 678       regs[i].set2(reg);
 679       break;
 680     case T_OBJECT:
 681     case T_ARRAY:
 682     case T_ADDRESS:
 683       if (ireg < num_java_iarg_registers) {
 684         // Put ptr in register.
 685         reg = java_iarg_reg[ireg];
 686         ++ireg;
 687       } else {
 688         // Put ptr on stack. Objects must be aligned to 2 slots too,
 689         // because "64-bit pointers record oop-ishness on 2 aligned
 690         // adjacent registers." (see OopFlow::build_oop_map).
 691         if (stk & 0x1) ++stk;
 692         reg = VMRegImpl::stack2reg(stk);
 693         stk += inc_stk_for_longdouble;
 694       }
 695       regs[i].set2(reg);
 696       break;
 697     case T_FLOAT:
 698       if (freg < num_java_farg_registers) {
 699         // Put float in register.
 700         reg = java_farg_reg[freg];
 701         ++freg;
 702       } else {
 703         // Put float on stack.
 704         reg = VMRegImpl::stack2reg(stk);
 705         stk += inc_stk_for_intfloat;
 706       }
 707       regs[i].set1(reg);
 708       break;
 709     case T_DOUBLE:
 710       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 711       if (freg < num_java_farg_registers) {
 712         // Put double in register.
 713         reg = java_farg_reg[freg];
 714         ++freg;
 715       } else {
 716         // Put double on stack. They must be aligned to 2 slots.
 717         if (stk & 0x1) ++stk;
 718         reg = VMRegImpl::stack2reg(stk);
 719         stk += inc_stk_for_longdouble;
 720       }
 721       regs[i].set2(reg);
 722       break;
 723     case T_VOID:
 724       // Do not count halves.
 725       regs[i].set_bad();
 726       break;
 727     default:
 728       ShouldNotReachHere();
 729     }
 730   }
 731   return align_up(stk, 2);
 732 }
 733 
 734 #if defined(COMPILER1) || defined(COMPILER2)
 735 // Calling convention for calling C code.
 736 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 737                                         VMRegPair *regs,
 738                                         VMRegPair *regs2,
 739                                         int total_args_passed) {
 740   // Calling conventions for C runtime calls and calls to JNI native methods.
 741   //
 742   // PPC64 convention: Hoist the first 8 int/ptr/long's in the first 8
 743   // int regs, leaving int regs undefined if the arg is flt/dbl. Hoist
 744   // the first 13 flt/dbl's in the first 13 fp regs but additionally
 745   // copy flt/dbl to the stack if they are beyond the 8th argument.
 746 
 747   const VMReg iarg_reg[8] = {
 748     R3->as_VMReg(),
 749     R4->as_VMReg(),
 750     R5->as_VMReg(),
 751     R6->as_VMReg(),
 752     R7->as_VMReg(),
 753     R8->as_VMReg(),
 754     R9->as_VMReg(),
 755     R10->as_VMReg()
 756   };
 757 
 758   const VMReg farg_reg[13] = {
 759     F1->as_VMReg(),
 760     F2->as_VMReg(),
 761     F3->as_VMReg(),
 762     F4->as_VMReg(),
 763     F5->as_VMReg(),
 764     F6->as_VMReg(),
 765     F7->as_VMReg(),
 766     F8->as_VMReg(),
 767     F9->as_VMReg(),
 768     F10->as_VMReg(),
 769     F11->as_VMReg(),
 770     F12->as_VMReg(),
 771     F13->as_VMReg()
 772   };
 773 
 774   // Check calling conventions consistency.
 775   assert(sizeof(iarg_reg) / sizeof(iarg_reg[0]) == Argument::n_int_register_parameters_c &&
 776          sizeof(farg_reg) / sizeof(farg_reg[0]) == Argument::n_float_register_parameters_c,
 777          "consistency");
 778 
 779   // `Stk' counts stack slots. Due to alignment, 32 bit values occupy
 780   // 2 such slots, like 64 bit values do.
 781   const int inc_stk_for_intfloat   = 2; // 2 slots for ints and floats
 782   const int inc_stk_for_longdouble = 2; // 2 slots for longs and doubles
 783 
 784   int i;
 785   VMReg reg;
 786   // Leave room for C-compatible ABI_REG_ARGS.
 787   int stk = (frame::abi_reg_args_size - frame::jit_out_preserve_size) / VMRegImpl::stack_slot_size;
 788   int arg = 0;
 789   int freg = 0;
 790 
 791   // Avoid passing C arguments in the wrong stack slots.
 792 #if defined(ABI_ELFv2)
 793   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 96,
 794          "passing C arguments in wrong stack slots");
 795 #else
 796   assert((SharedRuntime::out_preserve_stack_slots() + stk) * VMRegImpl::stack_slot_size == 112,
 797          "passing C arguments in wrong stack slots");
 798 #endif
 799   // We fill-out regs AND regs2 if an argument must be passed in a
 800   // register AND in a stack slot. If regs2 is NULL in such a
 801   // situation, we bail-out with a fatal error.
 802   for (int i = 0; i < total_args_passed; ++i, ++arg) {
 803     // Initialize regs2 to BAD.
 804     if (regs2 != NULL) regs2[i].set_bad();
 805 
 806     switch(sig_bt[i]) {
 807 
 808     //
 809     // If arguments 0-7 are integers, they are passed in integer registers.
 810     // Argument i is placed in iarg_reg[i].
 811     //
 812     case T_BOOLEAN:
 813     case T_CHAR:
 814     case T_BYTE:
 815     case T_SHORT:
 816     case T_INT:
 817       // We must cast ints to longs and use full 64 bit stack slots
 818       // here.  Thus fall through, handle as long.
 819     case T_LONG:
 820     case T_OBJECT:
 821     case T_ARRAY:
 822     case T_ADDRESS:
 823     case T_METADATA:
 824       // Oops are already boxed if required (JNI).
 825       if (arg < Argument::n_int_register_parameters_c) {
 826         reg = iarg_reg[arg];
 827       } else {
 828         reg = VMRegImpl::stack2reg(stk);
 829         stk += inc_stk_for_longdouble;
 830       }
 831       regs[i].set2(reg);
 832       break;
 833 
 834     //
 835     // Floats are treated differently from int regs:  The first 13 float arguments
 836     // are passed in registers (not the float args among the first 13 args).
 837     // Thus argument i is NOT passed in farg_reg[i] if it is float.  It is passed
 838     // in farg_reg[j] if argument i is the j-th float argument of this call.
 839     //
 840     case T_FLOAT:
 841 #if defined(LINUX)
 842       // Linux uses ELF ABI. Both original ELF and ELFv2 ABIs have float
 843       // in the least significant word of an argument slot.
 844 #if defined(VM_LITTLE_ENDIAN)
 845 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 846 #else
 847 #define FLOAT_WORD_OFFSET_IN_SLOT 1
 848 #endif
 849 #elif defined(AIX)
 850       // Although AIX runs on big endian CPU, float is in the most
 851       // significant word of an argument slot.
 852 #define FLOAT_WORD_OFFSET_IN_SLOT 0
 853 #else
 854 #error "unknown OS"
 855 #endif
 856       if (freg < Argument::n_float_register_parameters_c) {
 857         // Put float in register ...
 858         reg = farg_reg[freg];
 859         ++freg;
 860 
 861         // Argument i for i > 8 is placed on the stack even if it's
 862         // placed in a register (if it's a float arg). Aix disassembly
 863         // shows that xlC places these float args on the stack AND in
 864         // a register. This is not documented, but we follow this
 865         // convention, too.
 866         if (arg >= Argument::n_regs_not_on_stack_c) {
 867           // ... and on the stack.
 868           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 869           VMReg reg2 = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 870           regs2[i].set1(reg2);
 871           stk += inc_stk_for_intfloat;
 872         }
 873 
 874       } else {
 875         // Put float on stack.
 876         reg = VMRegImpl::stack2reg(stk + FLOAT_WORD_OFFSET_IN_SLOT);
 877         stk += inc_stk_for_intfloat;
 878       }
 879       regs[i].set1(reg);
 880       break;
 881     case T_DOUBLE:
 882       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "expecting half");
 883       if (freg < Argument::n_float_register_parameters_c) {
 884         // Put double in register ...
 885         reg = farg_reg[freg];
 886         ++freg;
 887 
 888         // Argument i for i > 8 is placed on the stack even if it's
 889         // placed in a register (if it's a double arg). Aix disassembly
 890         // shows that xlC places these float args on the stack AND in
 891         // a register. This is not documented, but we follow this
 892         // convention, too.
 893         if (arg >= Argument::n_regs_not_on_stack_c) {
 894           // ... and on the stack.
 895           guarantee(regs2 != NULL, "must pass float in register and stack slot");
 896           VMReg reg2 = VMRegImpl::stack2reg(stk);
 897           regs2[i].set2(reg2);
 898           stk += inc_stk_for_longdouble;
 899         }
 900       } else {
 901         // Put double on stack.
 902         reg = VMRegImpl::stack2reg(stk);
 903         stk += inc_stk_for_longdouble;
 904       }
 905       regs[i].set2(reg);
 906       break;
 907 
 908     case T_VOID:
 909       // Do not count halves.
 910       regs[i].set_bad();
 911       --arg;
 912       break;
 913     default:
 914       ShouldNotReachHere();
 915     }
 916   }
 917 
 918   return align_up(stk, 2);
 919 }
 920 #endif // COMPILER2
 921 
 922 int SharedRuntime::vector_calling_convention(VMRegPair *regs,
 923                                              uint num_bits,
 924                                              uint total_args_passed) {
 925   Unimplemented();
 926   return 0;
 927 }
 928 
 929 static address gen_c2i_adapter(MacroAssembler *masm,
 930                             int total_args_passed,
 931                             int comp_args_on_stack,
 932                             const BasicType *sig_bt,
 933                             const VMRegPair *regs,
 934                             Label& call_interpreter,
 935                             const Register& ientry) {
 936 
 937   address c2i_entrypoint;
 938 
 939   const Register sender_SP = R21_sender_SP; // == R21_tmp1
 940   const Register code      = R22_tmp2;
 941   //const Register ientry  = R23_tmp3;
 942   const Register value_regs[] = { R24_tmp4, R25_tmp5, R26_tmp6 };
 943   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
 944   int value_regs_index = 0;
 945 
 946   const Register return_pc = R27_tmp7;
 947   const Register tmp       = R28_tmp8;
 948 
 949   assert_different_registers(sender_SP, code, ientry, return_pc, tmp);
 950 
 951   // Adapter needs TOP_IJAVA_FRAME_ABI.
 952   const int adapter_size = frame::top_ijava_frame_abi_size +
 953                            align_up(total_args_passed * wordSize, frame::alignment_in_bytes);
 954 
 955   // regular (verified) c2i entry point
 956   c2i_entrypoint = __ pc();
 957 
 958   // Does compiled code exists? If yes, patch the caller's callsite.
 959   __ ld(code, method_(code));
 960   __ cmpdi(CCR0, code, 0);
 961   __ ld(ientry, method_(interpreter_entry)); // preloaded
 962   __ beq(CCR0, call_interpreter);
 963 
 964 
 965   // Patch caller's callsite, method_(code) was not NULL which means that
 966   // compiled code exists.
 967   __ mflr(return_pc);
 968   __ std(return_pc, _abi0(lr), R1_SP);
 969   RegisterSaver::push_frame_and_save_argument_registers(masm, tmp, adapter_size, total_args_passed, regs);
 970 
 971   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite), R19_method, return_pc);
 972 
 973   RegisterSaver::restore_argument_registers_and_pop_frame(masm, adapter_size, total_args_passed, regs);
 974   __ ld(return_pc, _abi0(lr), R1_SP);
 975   __ ld(ientry, method_(interpreter_entry)); // preloaded
 976   __ mtlr(return_pc);
 977 
 978 
 979   // Call the interpreter.
 980   __ BIND(call_interpreter);
 981   __ mtctr(ientry);
 982 
 983   // Get a copy of the current SP for loading caller's arguments.
 984   __ mr(sender_SP, R1_SP);
 985 
 986   // Add space for the adapter.
 987   __ resize_frame(-adapter_size, R12_scratch2);
 988 
 989   int st_off = adapter_size - wordSize;
 990 
 991   // Write the args into the outgoing interpreter space.
 992   for (int i = 0; i < total_args_passed; i++) {
 993     VMReg r_1 = regs[i].first();
 994     VMReg r_2 = regs[i].second();
 995     if (!r_1->is_valid()) {
 996       assert(!r_2->is_valid(), "");
 997       continue;
 998     }
 999     if (r_1->is_stack()) {
1000       Register tmp_reg = value_regs[value_regs_index];
1001       value_regs_index = (value_regs_index + 1) % num_value_regs;
1002       // The calling convention produces OptoRegs that ignore the out
1003       // preserve area (JIT's ABI). We must account for it here.
1004       int ld_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
1005       if (!r_2->is_valid()) {
1006         __ lwz(tmp_reg, ld_off, sender_SP);
1007       } else {
1008         __ ld(tmp_reg, ld_off, sender_SP);
1009       }
1010       // Pretend stack targets were loaded into tmp_reg.
1011       r_1 = tmp_reg->as_VMReg();
1012     }
1013 
1014     if (r_1->is_Register()) {
1015       Register r = r_1->as_Register();
1016       if (!r_2->is_valid()) {
1017         __ stw(r, st_off, R1_SP);
1018         st_off-=wordSize;
1019       } else {
1020         // Longs are given 2 64-bit slots in the interpreter, but the
1021         // data is passed in only 1 slot.
1022         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
1023           DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
1024           st_off-=wordSize;
1025         }
1026         __ std(r, st_off, R1_SP);
1027         st_off-=wordSize;
1028       }
1029     } else {
1030       assert(r_1->is_FloatRegister(), "");
1031       FloatRegister f = r_1->as_FloatRegister();
1032       if (!r_2->is_valid()) {
1033         __ stfs(f, st_off, R1_SP);
1034         st_off-=wordSize;
1035       } else {
1036         // In 64bit, doubles are given 2 64-bit slots in the interpreter, but the
1037         // data is passed in only 1 slot.
1038         // One of these should get known junk...
1039         DEBUG_ONLY( __ li(tmp, 0); __ std(tmp, st_off, R1_SP); )
1040         st_off-=wordSize;
1041         __ stfd(f, st_off, R1_SP);
1042         st_off-=wordSize;
1043       }
1044     }
1045   }
1046 
1047   // Jump to the interpreter just as if interpreter was doing it.
1048 
1049   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
1050 
1051   // load TOS
1052   __ addi(R15_esp, R1_SP, st_off);
1053 
1054   // Frame_manager expects initial_caller_sp (= SP without resize by c2i) in R21_tmp1.
1055   assert(sender_SP == R21_sender_SP, "passing initial caller's SP in wrong register");
1056   __ bctr();
1057 
1058   return c2i_entrypoint;
1059 }
1060 
1061 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
1062                                     int total_args_passed,
1063                                     int comp_args_on_stack,
1064                                     const BasicType *sig_bt,
1065                                     const VMRegPair *regs) {
1066 
1067   // Load method's entry-point from method.
1068   __ ld(R12_scratch2, in_bytes(Method::from_compiled_offset()), R19_method);
1069   __ mtctr(R12_scratch2);
1070 
1071   // We will only enter here from an interpreted frame and never from after
1072   // passing thru a c2i. Azul allowed this but we do not. If we lose the
1073   // race and use a c2i we will remain interpreted for the race loser(s).
1074   // This removes all sorts of headaches on the x86 side and also eliminates
1075   // the possibility of having c2i -> i2c -> c2i -> ... endless transitions.
1076 
1077   // Note: r13 contains the senderSP on entry. We must preserve it since
1078   // we may do a i2c -> c2i transition if we lose a race where compiled
1079   // code goes non-entrant while we get args ready.
1080   // In addition we use r13 to locate all the interpreter args as
1081   // we must align the stack to 16 bytes on an i2c entry else we
1082   // lose alignment we expect in all compiled code and register
1083   // save code can segv when fxsave instructions find improperly
1084   // aligned stack pointer.
1085 
1086   const Register ld_ptr = R15_esp;
1087   const Register value_regs[] = { R22_tmp2, R23_tmp3, R24_tmp4, R25_tmp5, R26_tmp6 };
1088   const int num_value_regs = sizeof(value_regs) / sizeof(Register);
1089   int value_regs_index = 0;
1090 
1091   int ld_offset = total_args_passed*wordSize;
1092 
1093   // Cut-out for having no stack args. Since up to 2 int/oop args are passed
1094   // in registers, we will occasionally have no stack args.
1095   int comp_words_on_stack = 0;
1096   if (comp_args_on_stack) {
1097     // Sig words on the stack are greater-than VMRegImpl::stack0. Those in
1098     // registers are below. By subtracting stack0, we either get a negative
1099     // number (all values in registers) or the maximum stack slot accessed.
1100 
1101     // Convert 4-byte c2 stack slots to words.
1102     comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
1103     // Round up to miminum stack alignment, in wordSize.
1104     comp_words_on_stack = align_up(comp_words_on_stack, 2);
1105     __ resize_frame(-comp_words_on_stack * wordSize, R11_scratch1);
1106   }
1107 
1108   // Now generate the shuffle code.  Pick up all register args and move the
1109   // rest through register value=Z_R12.
1110   BLOCK_COMMENT("Shuffle arguments");
1111   for (int i = 0; i < total_args_passed; i++) {
1112     if (sig_bt[i] == T_VOID) {
1113       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
1114       continue;
1115     }
1116 
1117     // Pick up 0, 1 or 2 words from ld_ptr.
1118     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
1119             "scrambled load targets?");
1120     VMReg r_1 = regs[i].first();
1121     VMReg r_2 = regs[i].second();
1122     if (!r_1->is_valid()) {
1123       assert(!r_2->is_valid(), "");
1124       continue;
1125     }
1126     if (r_1->is_FloatRegister()) {
1127       if (!r_2->is_valid()) {
1128         __ lfs(r_1->as_FloatRegister(), ld_offset, ld_ptr);
1129         ld_offset-=wordSize;
1130       } else {
1131         // Skip the unused interpreter slot.
1132         __ lfd(r_1->as_FloatRegister(), ld_offset-wordSize, ld_ptr);
1133         ld_offset-=2*wordSize;
1134       }
1135     } else {
1136       Register r;
1137       if (r_1->is_stack()) {
1138         // Must do a memory to memory move thru "value".
1139         r = value_regs[value_regs_index];
1140         value_regs_index = (value_regs_index + 1) % num_value_regs;
1141       } else {
1142         r = r_1->as_Register();
1143       }
1144       if (!r_2->is_valid()) {
1145         // Not sure we need to do this but it shouldn't hurt.
1146         if (is_reference_type(sig_bt[i]) || sig_bt[i] == T_ADDRESS) {
1147           __ ld(r, ld_offset, ld_ptr);
1148           ld_offset-=wordSize;
1149         } else {
1150           __ lwz(r, ld_offset, ld_ptr);
1151           ld_offset-=wordSize;
1152         }
1153       } else {
1154         // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
1155         // data is passed in only 1 slot.
1156         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
1157           ld_offset-=wordSize;
1158         }
1159         __ ld(r, ld_offset, ld_ptr);
1160         ld_offset-=wordSize;
1161       }
1162 
1163       if (r_1->is_stack()) {
1164         // Now store value where the compiler expects it
1165         int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots())*VMRegImpl::stack_slot_size;
1166 
1167         if (sig_bt[i] == T_INT   || sig_bt[i] == T_FLOAT ||sig_bt[i] == T_BOOLEAN ||
1168             sig_bt[i] == T_SHORT || sig_bt[i] == T_CHAR  || sig_bt[i] == T_BYTE) {
1169           __ stw(r, st_off, R1_SP);
1170         } else {
1171           __ std(r, st_off, R1_SP);
1172         }
1173       }
1174     }
1175   }
1176 
1177   BLOCK_COMMENT("Store method");
1178   // Store method into thread->callee_target.
1179   // We might end up in handle_wrong_method if the callee is
1180   // deoptimized as we race thru here. If that happens we don't want
1181   // to take a safepoint because the caller frame will look
1182   // interpreted and arguments are now "compiled" so it is much better
1183   // to make this transition invisible to the stack walking
1184   // code. Unfortunately if we try and find the callee by normal means
1185   // a safepoint is possible. So we stash the desired callee in the
1186   // thread and the vm will find there should this case occur.
1187   __ std(R19_method, thread_(callee_target));
1188 
1189   // Jump to the compiled code just as if compiled code was doing it.
1190   __ bctr();
1191 }
1192 
1193 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
1194                                                             int total_args_passed,
1195                                                             int comp_args_on_stack,
1196                                                             const BasicType *sig_bt,
1197                                                             const VMRegPair *regs,
1198                                                             AdapterFingerPrint* fingerprint) {
1199   address i2c_entry;
1200   address c2i_unverified_entry;
1201   address c2i_entry;
1202 
1203 
1204   // entry: i2c
1205 
1206   __ align(CodeEntryAlignment);
1207   i2c_entry = __ pc();
1208   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
1209 
1210 
1211   // entry: c2i unverified
1212 
1213   __ align(CodeEntryAlignment);
1214   BLOCK_COMMENT("c2i unverified entry");
1215   c2i_unverified_entry = __ pc();
1216 
1217   // inline_cache contains a compiledICHolder
1218   const Register ic             = R19_method;
1219   const Register ic_klass       = R11_scratch1;
1220   const Register receiver_klass = R12_scratch2;
1221   const Register code           = R21_tmp1;
1222   const Register ientry         = R23_tmp3;
1223 
1224   assert_different_registers(ic, ic_klass, receiver_klass, R3_ARG1, code, ientry);
1225   assert(R11_scratch1 == R11, "need prologue scratch register");
1226 
1227   Label call_interpreter;
1228 
1229   assert(!MacroAssembler::needs_explicit_null_check(oopDesc::klass_offset_in_bytes()),
1230          "klass offset should reach into any page");
1231   // Check for NULL argument if we don't have implicit null checks.
1232   if (!ImplicitNullChecks || !os::zero_page_read_protected()) {
1233     if (TrapBasedNullChecks) {
1234       __ trap_null_check(R3_ARG1);
1235     } else {
1236       Label valid;
1237       __ cmpdi(CCR0, R3_ARG1, 0);
1238       __ bne_predict_taken(CCR0, valid);
1239       // We have a null argument, branch to ic_miss_stub.
1240       __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1241                        relocInfo::runtime_call_type);
1242       __ BIND(valid);
1243     }
1244   }
1245   // Assume argument is not NULL, load klass from receiver.
1246   __ load_klass(receiver_klass, R3_ARG1);
1247 
1248   __ ld(ic_klass, CompiledICHolder::holder_klass_offset(), ic);
1249 
1250   if (TrapBasedICMissChecks) {
1251     __ trap_ic_miss_check(receiver_klass, ic_klass);
1252   } else {
1253     Label valid;
1254     __ cmpd(CCR0, receiver_klass, ic_klass);
1255     __ beq_predict_taken(CCR0, valid);
1256     // We have an unexpected klass, branch to ic_miss_stub.
1257     __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
1258                      relocInfo::runtime_call_type);
1259     __ BIND(valid);
1260   }
1261 
1262   // Argument is valid and klass is as expected, continue.
1263 
1264   // Extract method from inline cache, verified entry point needs it.
1265   __ ld(R19_method, CompiledICHolder::holder_metadata_offset(), ic);
1266   assert(R19_method == ic, "the inline cache register is dead here");
1267 
1268   __ ld(code, method_(code));
1269   __ cmpdi(CCR0, code, 0);
1270   __ ld(ientry, method_(interpreter_entry)); // preloaded
1271   __ beq_predict_taken(CCR0, call_interpreter);
1272 
1273   // Branch to ic_miss_stub.
1274   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(), relocInfo::runtime_call_type);
1275 
1276   // entry: c2i
1277 
1278   c2i_entry = __ pc();
1279 
1280   // Class initialization barrier for static methods
1281   address c2i_no_clinit_check_entry = NULL;
1282   if (VM_Version::supports_fast_class_init_checks()) {
1283     Label L_skip_barrier;
1284 
1285     { // Bypass the barrier for non-static methods
1286       __ lwz(R0, in_bytes(Method::access_flags_offset()), R19_method);
1287       __ andi_(R0, R0, JVM_ACC_STATIC);
1288       __ beq(CCR0, L_skip_barrier); // non-static
1289     }
1290 
1291     Register klass = R11_scratch1;
1292     __ load_method_holder(klass, R19_method);
1293     __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
1294 
1295     __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
1296     __ mtctr(klass);
1297     __ bctr();
1298 
1299     __ bind(L_skip_barrier);
1300     c2i_no_clinit_check_entry = __ pc();
1301   }
1302 
1303   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1304   bs->c2i_entry_barrier(masm, /* tmp register*/ ic_klass, /* tmp register*/ receiver_klass, /* tmp register*/ code);
1305 
1306   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, call_interpreter, ientry);
1307 
1308   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry,
1309                                           c2i_no_clinit_check_entry);
1310 }
1311 
1312 // An oop arg. Must pass a handle not the oop itself.
1313 static void object_move(MacroAssembler* masm,
1314                         int frame_size_in_slots,
1315                         OopMap* oop_map, int oop_handle_offset,
1316                         bool is_receiver, int* receiver_offset,
1317                         VMRegPair src, VMRegPair dst,
1318                         Register r_caller_sp, Register r_temp_1, Register r_temp_2) {
1319   assert(!is_receiver || (is_receiver && (*receiver_offset == -1)),
1320          "receiver has already been moved");
1321 
1322   // We must pass a handle. First figure out the location we use as a handle.
1323 
1324   if (src.first()->is_stack()) {
1325     // stack to stack or reg
1326 
1327     const Register r_handle = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1328     Label skip;
1329     const int oop_slot_in_callers_frame = reg2slot(src.first());
1330 
1331     guarantee(!is_receiver, "expecting receiver in register");
1332     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot_in_callers_frame + frame_size_in_slots));
1333 
1334     __ addi(r_handle, r_caller_sp, reg2offset(src.first()));
1335     __ ld(  r_temp_2, reg2offset(src.first()), r_caller_sp);
1336     __ cmpdi(CCR0, r_temp_2, 0);
1337     __ bne(CCR0, skip);
1338     // Use a NULL handle if oop is NULL.
1339     __ li(r_handle, 0);
1340     __ bind(skip);
1341 
1342     if (dst.first()->is_stack()) {
1343       // stack to stack
1344       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1345     } else {
1346       // stack to reg
1347       // Nothing to do, r_handle is already the dst register.
1348     }
1349   } else {
1350     // reg to stack or reg
1351     const Register r_oop      = src.first()->as_Register();
1352     const Register r_handle   = dst.first()->is_stack() ? r_temp_1 : dst.first()->as_Register();
1353     const int oop_slot        = (r_oop->encoding()-R3_ARG1->encoding()) * VMRegImpl::slots_per_word
1354                                 + oop_handle_offset; // in slots
1355     const int oop_offset = oop_slot * VMRegImpl::stack_slot_size;
1356     Label skip;
1357 
1358     if (is_receiver) {
1359       *receiver_offset = oop_offset;
1360     }
1361     oop_map->set_oop(VMRegImpl::stack2reg(oop_slot));
1362 
1363     __ std( r_oop,    oop_offset, R1_SP);
1364     __ addi(r_handle, R1_SP, oop_offset);
1365 
1366     __ cmpdi(CCR0, r_oop, 0);
1367     __ bne(CCR0, skip);
1368     // Use a NULL handle if oop is NULL.
1369     __ li(r_handle, 0);
1370     __ bind(skip);
1371 
1372     if (dst.first()->is_stack()) {
1373       // reg to stack
1374       __ std(r_handle, reg2offset(dst.first()), R1_SP);
1375     } else {
1376       // reg to reg
1377       // Nothing to do, r_handle is already the dst register.
1378     }
1379   }
1380 }
1381 
1382 static void int_move(MacroAssembler*masm,
1383                      VMRegPair src, VMRegPair dst,
1384                      Register r_caller_sp, Register r_temp) {
1385   assert(src.first()->is_valid(), "incoming must be int");
1386   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1387 
1388   if (src.first()->is_stack()) {
1389     if (dst.first()->is_stack()) {
1390       // stack to stack
1391       __ lwa(r_temp, reg2offset(src.first()), r_caller_sp);
1392       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1393     } else {
1394       // stack to reg
1395       __ lwa(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1396     }
1397   } else if (dst.first()->is_stack()) {
1398     // reg to stack
1399     __ extsw(r_temp, src.first()->as_Register());
1400     __ std(r_temp, reg2offset(dst.first()), R1_SP);
1401   } else {
1402     // reg to reg
1403     __ extsw(dst.first()->as_Register(), src.first()->as_Register());
1404   }
1405 }
1406 
1407 static void long_move(MacroAssembler*masm,
1408                       VMRegPair src, VMRegPair dst,
1409                       Register r_caller_sp, Register r_temp) {
1410   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be long");
1411   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be long");
1412 
1413   if (src.first()->is_stack()) {
1414     if (dst.first()->is_stack()) {
1415       // stack to stack
1416       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1417       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1418     } else {
1419       // stack to reg
1420       __ ld(dst.first()->as_Register(), reg2offset(src.first()), r_caller_sp);
1421     }
1422   } else if (dst.first()->is_stack()) {
1423     // reg to stack
1424     __ std(src.first()->as_Register(), reg2offset(dst.first()), R1_SP);
1425   } else {
1426     // reg to reg
1427     if (dst.first()->as_Register() != src.first()->as_Register())
1428       __ mr(dst.first()->as_Register(), src.first()->as_Register());
1429   }
1430 }
1431 
1432 static void float_move(MacroAssembler*masm,
1433                        VMRegPair src, VMRegPair dst,
1434                        Register r_caller_sp, Register r_temp) {
1435   assert(src.first()->is_valid() && !src.second()->is_valid(), "incoming must be float");
1436   assert(dst.first()->is_valid() && !dst.second()->is_valid(), "outgoing must be float");
1437 
1438   if (src.first()->is_stack()) {
1439     if (dst.first()->is_stack()) {
1440       // stack to stack
1441       __ lwz(r_temp, reg2offset(src.first()), r_caller_sp);
1442       __ stw(r_temp, reg2offset(dst.first()), R1_SP);
1443     } else {
1444       // stack to reg
1445       __ lfs(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1446     }
1447   } else if (dst.first()->is_stack()) {
1448     // reg to stack
1449     __ stfs(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1450   } else {
1451     // reg to reg
1452     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1453       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1454   }
1455 }
1456 
1457 static void double_move(MacroAssembler*masm,
1458                         VMRegPair src, VMRegPair dst,
1459                         Register r_caller_sp, Register r_temp) {
1460   assert(src.first()->is_valid() && src.second() == src.first()->next(), "incoming must be double");
1461   assert(dst.first()->is_valid() && dst.second() == dst.first()->next(), "outgoing must be double");
1462 
1463   if (src.first()->is_stack()) {
1464     if (dst.first()->is_stack()) {
1465       // stack to stack
1466       __ ld( r_temp, reg2offset(src.first()), r_caller_sp);
1467       __ std(r_temp, reg2offset(dst.first()), R1_SP);
1468     } else {
1469       // stack to reg
1470       __ lfd(dst.first()->as_FloatRegister(), reg2offset(src.first()), r_caller_sp);
1471     }
1472   } else if (dst.first()->is_stack()) {
1473     // reg to stack
1474     __ stfd(src.first()->as_FloatRegister(), reg2offset(dst.first()), R1_SP);
1475   } else {
1476     // reg to reg
1477     if (dst.first()->as_FloatRegister() != src.first()->as_FloatRegister())
1478       __ fmr(dst.first()->as_FloatRegister(), src.first()->as_FloatRegister());
1479   }
1480 }
1481 
1482 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1483   switch (ret_type) {
1484     case T_BOOLEAN:
1485     case T_CHAR:
1486     case T_BYTE:
1487     case T_SHORT:
1488     case T_INT:
1489       __ stw (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1490       break;
1491     case T_ARRAY:
1492     case T_OBJECT:
1493     case T_LONG:
1494       __ std (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1495       break;
1496     case T_FLOAT:
1497       __ stfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1498       break;
1499     case T_DOUBLE:
1500       __ stfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1501       break;
1502     case T_VOID:
1503       break;
1504     default:
1505       ShouldNotReachHere();
1506       break;
1507   }
1508 }
1509 
1510 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1511   switch (ret_type) {
1512     case T_BOOLEAN:
1513     case T_CHAR:
1514     case T_BYTE:
1515     case T_SHORT:
1516     case T_INT:
1517       __ lwz(R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1518       break;
1519     case T_ARRAY:
1520     case T_OBJECT:
1521     case T_LONG:
1522       __ ld (R3_RET,  frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1523       break;
1524     case T_FLOAT:
1525       __ lfs(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1526       break;
1527     case T_DOUBLE:
1528       __ lfd(F1_RET, frame_slots*VMRegImpl::stack_slot_size, R1_SP);
1529       break;
1530     case T_VOID:
1531       break;
1532     default:
1533       ShouldNotReachHere();
1534       break;
1535   }
1536 }
1537 
1538 static void verify_oop_args(MacroAssembler* masm,
1539                             const methodHandle& method,
1540                             const BasicType* sig_bt,
1541                             const VMRegPair* regs) {
1542   Register temp_reg = R19_method;  // not part of any compiled calling seq
1543   if (VerifyOops) {
1544     for (int i = 0; i < method->size_of_parameters(); i++) {
1545       if (is_reference_type(sig_bt[i])) {
1546         VMReg r = regs[i].first();
1547         assert(r->is_valid(), "bad oop arg");
1548         if (r->is_stack()) {
1549           __ ld(temp_reg, reg2offset(r), R1_SP);
1550           __ verify_oop(temp_reg, FILE_AND_LINE);
1551         } else {
1552           __ verify_oop(r->as_Register(), FILE_AND_LINE);
1553         }
1554       }
1555     }
1556   }
1557 }
1558 
1559 static void gen_special_dispatch(MacroAssembler* masm,
1560                                  const methodHandle& method,
1561                                  const BasicType* sig_bt,
1562                                  const VMRegPair* regs) {
1563   verify_oop_args(masm, method, sig_bt, regs);
1564   vmIntrinsics::ID iid = method->intrinsic_id();
1565 
1566   // Now write the args into the outgoing interpreter space
1567   bool     has_receiver   = false;
1568   Register receiver_reg   = noreg;
1569   int      member_arg_pos = -1;
1570   Register member_reg     = noreg;
1571   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1572   if (ref_kind != 0) {
1573     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1574     member_reg = R19_method;  // known to be free at this point
1575     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1576   } else if (iid == vmIntrinsics::_invokeBasic) {
1577     has_receiver = true;
1578   } else if (iid == vmIntrinsics::_linkToNative) {
1579     member_arg_pos = method->size_of_parameters() - 1;  // trailing NativeEntryPoint argument
1580     member_reg = R19_method;  // known to be free at this point
1581   } else {
1582     fatal("unexpected intrinsic id %d", vmIntrinsics::as_int(iid));
1583   }
1584 
1585   if (member_reg != noreg) {
1586     // Load the member_arg into register, if necessary.
1587     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1588     VMReg r = regs[member_arg_pos].first();
1589     if (r->is_stack()) {
1590       __ ld(member_reg, reg2offset(r), R1_SP);
1591     } else {
1592       // no data motion is needed
1593       member_reg = r->as_Register();
1594     }
1595   }
1596 
1597   if (has_receiver) {
1598     // Make sure the receiver is loaded into a register.
1599     assert(method->size_of_parameters() > 0, "oob");
1600     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1601     VMReg r = regs[0].first();
1602     assert(r->is_valid(), "bad receiver arg");
1603     if (r->is_stack()) {
1604       // Porting note:  This assumes that compiled calling conventions always
1605       // pass the receiver oop in a register.  If this is not true on some
1606       // platform, pick a temp and load the receiver from stack.
1607       fatal("receiver always in a register");
1608       receiver_reg = R11_scratch1;  // TODO (hs24): is R11_scratch1 really free at this point?
1609       __ ld(receiver_reg, reg2offset(r), R1_SP);
1610     } else {
1611       // no data motion is needed
1612       receiver_reg = r->as_Register();
1613     }
1614   }
1615 
1616   // Figure out which address we are really jumping to:
1617   MethodHandles::generate_method_handle_dispatch(masm, iid,
1618                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1619 }
1620 
1621 // ---------------------------------------------------------------------------
1622 // Generate a native wrapper for a given method. The method takes arguments
1623 // in the Java compiled code convention, marshals them to the native
1624 // convention (handlizes oops, etc), transitions to native, makes the call,
1625 // returns to java state (possibly blocking), unhandlizes any result and
1626 // returns.
1627 //
1628 // Critical native functions are a shorthand for the use of
1629 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1630 // functions.  The wrapper is expected to unpack the arguments before
1631 // passing them to the callee. Critical native functions leave the state _in_Java,
1632 // since they cannot stop for GC.
1633 // Some other parts of JNI setup are skipped like the tear down of the JNI handle
1634 // block and the check for pending exceptions it's impossible for them
1635 // to be thrown.
1636 //
1637 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1638                                                 const methodHandle& method,
1639                                                 int compile_id,
1640                                                 BasicType *in_sig_bt,
1641                                                 VMRegPair *in_regs,
1642                                                 BasicType ret_type) {
1643   if (method->is_method_handle_intrinsic()) {
1644     vmIntrinsics::ID iid = method->intrinsic_id();
1645     intptr_t start = (intptr_t)__ pc();
1646     int vep_offset = ((intptr_t)__ pc()) - start;
1647     gen_special_dispatch(masm,
1648                          method,
1649                          in_sig_bt,
1650                          in_regs);
1651     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1652     __ flush();
1653     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1654     return nmethod::new_native_nmethod(method,
1655                                        compile_id,
1656                                        masm->code(),
1657                                        vep_offset,
1658                                        frame_complete,
1659                                        stack_slots / VMRegImpl::slots_per_word,
1660                                        in_ByteSize(-1),
1661                                        in_ByteSize(-1),
1662                                        (OopMapSet*)NULL);
1663   }
1664 
1665   address native_func = method->native_function();
1666   assert(native_func != NULL, "must have function");
1667 
1668   // First, create signature for outgoing C call
1669   // --------------------------------------------------------------------------
1670 
1671   int total_in_args = method->size_of_parameters();
1672   // We have received a description of where all the java args are located
1673   // on entry to the wrapper. We need to convert these args to where
1674   // the jni function will expect them. To figure out where they go
1675   // we convert the java signature to a C signature by inserting
1676   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1677 
1678   // Calculate the total number of C arguments and create arrays for the
1679   // signature and the outgoing registers.
1680   // On ppc64, we have two arrays for the outgoing registers, because
1681   // some floating-point arguments must be passed in registers _and_
1682   // in stack locations.
1683   bool method_is_static = method->is_static();
1684   int  total_c_args     = total_in_args + (method_is_static ? 2 : 1);
1685 
1686   BasicType *out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1687   VMRegPair *out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1688   VMRegPair *out_regs2  = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1689   BasicType* in_elem_bt = NULL;
1690 
1691   // Create the signature for the C call:
1692   //   1) add the JNIEnv*
1693   //   2) add the class if the method is static
1694   //   3) copy the rest of the incoming signature (shifted by the number of
1695   //      hidden arguments).
1696 
1697   int argc = 0;
1698   out_sig_bt[argc++] = T_ADDRESS;
1699   if (method->is_static()) {
1700     out_sig_bt[argc++] = T_OBJECT;
1701   }
1702 
1703   for (int i = 0; i < total_in_args ; i++ ) {
1704     out_sig_bt[argc++] = in_sig_bt[i];
1705   }
1706 
1707 
1708   // Compute the wrapper's frame size.
1709   // --------------------------------------------------------------------------
1710 
1711   // Now figure out where the args must be stored and how much stack space
1712   // they require.
1713   //
1714   // Compute framesize for the wrapper. We need to handlize all oops in
1715   // incoming registers.
1716   //
1717   // Calculate the total number of stack slots we will need:
1718   //   1) abi requirements
1719   //   2) outgoing arguments
1720   //   3) space for inbound oop handle area
1721   //   4) space for handlizing a klass if static method
1722   //   5) space for a lock if synchronized method
1723   //   6) workspace for saving return values, int <-> float reg moves, etc.
1724   //   7) alignment
1725   //
1726   // Layout of the native wrapper frame:
1727   // (stack grows upwards, memory grows downwards)
1728   //
1729   // NW     [ABI_REG_ARGS]             <-- 1) R1_SP
1730   //        [outgoing arguments]       <-- 2) R1_SP + out_arg_slot_offset
1731   //        [oopHandle area]           <-- 3) R1_SP + oop_handle_offset
1732   //        klass                      <-- 4) R1_SP + klass_offset
1733   //        lock                       <-- 5) R1_SP + lock_offset
1734   //        [workspace]                <-- 6) R1_SP + workspace_offset
1735   //        [alignment] (optional)     <-- 7)
1736   // caller [JIT_TOP_ABI_48]           <-- r_callers_sp
1737   //
1738   // - *_slot_offset Indicates offset from SP in number of stack slots.
1739   // - *_offset      Indicates offset from SP in bytes.
1740 
1741   int stack_slots = c_calling_convention(out_sig_bt, out_regs, out_regs2, total_c_args) + // 1+2)
1742                     SharedRuntime::out_preserve_stack_slots(); // See c_calling_convention.
1743 
1744   // Now the space for the inbound oop handle area.
1745   int total_save_slots = num_java_iarg_registers * VMRegImpl::slots_per_word;
1746 
1747   int oop_handle_slot_offset = stack_slots;
1748   stack_slots += total_save_slots;                                                // 3)
1749 
1750   int klass_slot_offset = 0;
1751   int klass_offset      = -1;
1752   if (method_is_static) {                                                         // 4)
1753     klass_slot_offset  = stack_slots;
1754     klass_offset       = klass_slot_offset * VMRegImpl::stack_slot_size;
1755     stack_slots       += VMRegImpl::slots_per_word;
1756   }
1757 
1758   int lock_slot_offset = 0;
1759   int lock_offset      = -1;
1760   if (method->is_synchronized()) {                                                // 5)
1761     lock_slot_offset   = stack_slots;
1762     lock_offset        = lock_slot_offset * VMRegImpl::stack_slot_size;
1763     stack_slots       += VMRegImpl::slots_per_word;
1764   }
1765 
1766   int workspace_slot_offset = stack_slots;                                        // 6)
1767   stack_slots         += 2;
1768 
1769   // Now compute actual number of stack words we need.
1770   // Rounding to make stack properly aligned.
1771   stack_slots = align_up(stack_slots,                                             // 7)
1772                          frame::alignment_in_bytes / VMRegImpl::stack_slot_size);
1773   int frame_size_in_bytes = stack_slots * VMRegImpl::stack_slot_size;
1774 
1775 
1776   // Now we can start generating code.
1777   // --------------------------------------------------------------------------
1778 
1779   intptr_t start_pc = (intptr_t)__ pc();
1780   intptr_t vep_start_pc;
1781   intptr_t frame_done_pc;
1782   intptr_t oopmap_pc;
1783 
1784   Label    ic_miss;
1785   Label    handle_pending_exception;
1786 
1787   Register r_callers_sp = R21;
1788   Register r_temp_1     = R22;
1789   Register r_temp_2     = R23;
1790   Register r_temp_3     = R24;
1791   Register r_temp_4     = R25;
1792   Register r_temp_5     = R26;
1793   Register r_temp_6     = R27;
1794   Register r_return_pc  = R28;
1795 
1796   Register r_carg1_jnienv        = noreg;
1797   Register r_carg2_classorobject = noreg;
1798   r_carg1_jnienv        = out_regs[0].first()->as_Register();
1799   r_carg2_classorobject = out_regs[1].first()->as_Register();
1800 
1801 
1802   // Generate the Unverified Entry Point (UEP).
1803   // --------------------------------------------------------------------------
1804   assert(start_pc == (intptr_t)__ pc(), "uep must be at start");
1805 
1806   // Check ic: object class == cached class?
1807   if (!method_is_static) {
1808   Register ic = R19_inline_cache_reg;
1809   Register receiver_klass = r_temp_1;
1810 
1811   __ cmpdi(CCR0, R3_ARG1, 0);
1812   __ beq(CCR0, ic_miss);
1813   __ verify_oop(R3_ARG1, FILE_AND_LINE);
1814   __ load_klass(receiver_klass, R3_ARG1);
1815 
1816   __ cmpd(CCR0, receiver_klass, ic);
1817   __ bne(CCR0, ic_miss);
1818   }
1819 
1820 
1821   // Generate the Verified Entry Point (VEP).
1822   // --------------------------------------------------------------------------
1823   vep_start_pc = (intptr_t)__ pc();
1824 
1825   if (UseRTMLocking) {
1826     // Abort RTM transaction before calling JNI
1827     // because critical section can be large and
1828     // abort anyway. Also nmethod can be deoptimized.
1829     __ tabort_();
1830   }
1831 
1832   if (VM_Version::supports_fast_class_init_checks() && method->needs_clinit_barrier()) {
1833     Label L_skip_barrier;
1834     Register klass = r_temp_1;
1835     // Notify OOP recorder (don't need the relocation)
1836     AddressLiteral md = __ constant_metadata_address(method->method_holder());
1837     __ load_const_optimized(klass, md.value(), R0);
1838     __ clinit_barrier(klass, R16_thread, &L_skip_barrier /*L_fast_path*/);
1839 
1840     __ load_const_optimized(klass, SharedRuntime::get_handle_wrong_method_stub(), R0);
1841     __ mtctr(klass);
1842     __ bctr();
1843 
1844     __ bind(L_skip_barrier);
1845   }
1846 
1847   __ save_LR_CR(r_temp_1);
1848   __ generate_stack_overflow_check(frame_size_in_bytes); // Check before creating frame.
1849   __ mr(r_callers_sp, R1_SP);                            // Remember frame pointer.
1850   __ push_frame(frame_size_in_bytes, r_temp_1);          // Push the c2n adapter's frame.
1851 
1852   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
1853   bs->nmethod_entry_barrier(masm, r_temp_1);
1854 
1855   frame_done_pc = (intptr_t)__ pc();
1856 
1857   __ verify_thread();
1858 
1859   // Native nmethod wrappers never take possession of the oop arguments.
1860   // So the caller will gc the arguments.
1861   // The only thing we need an oopMap for is if the call is static.
1862   //
1863   // An OopMap for lock (and class if static), and one for the VM call itself.
1864   OopMapSet *oop_maps = new OopMapSet();
1865   OopMap    *oop_map  = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1866 
1867   // Move arguments from register/stack to register/stack.
1868   // --------------------------------------------------------------------------
1869   //
1870   // We immediately shuffle the arguments so that for any vm call we have
1871   // to make from here on out (sync slow path, jvmti, etc.) we will have
1872   // captured the oops from our caller and have a valid oopMap for them.
1873   //
1874   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1875   // (derived from JavaThread* which is in R16_thread) and, if static,
1876   // the class mirror instead of a receiver. This pretty much guarantees that
1877   // register layout will not match. We ignore these extra arguments during
1878   // the shuffle. The shuffle is described by the two calling convention
1879   // vectors we have in our possession. We simply walk the java vector to
1880   // get the source locations and the c vector to get the destinations.
1881 
1882   // Record sp-based slot for receiver on stack for non-static methods.
1883   int receiver_offset = -1;
1884 
1885   // We move the arguments backward because the floating point registers
1886   // destination will always be to a register with a greater or equal
1887   // register number or the stack.
1888   //   in  is the index of the incoming Java arguments
1889   //   out is the index of the outgoing C arguments
1890 
1891 #ifdef ASSERT
1892   bool reg_destroyed[RegisterImpl::number_of_registers];
1893   bool freg_destroyed[FloatRegisterImpl::number_of_registers];
1894   for (int r = 0 ; r < RegisterImpl::number_of_registers ; r++) {
1895     reg_destroyed[r] = false;
1896   }
1897   for (int f = 0 ; f < FloatRegisterImpl::number_of_registers ; f++) {
1898     freg_destroyed[f] = false;
1899   }
1900 #endif // ASSERT
1901 
1902   for (int in = total_in_args - 1, out = total_c_args - 1; in >= 0 ; in--, out--) {
1903 
1904 #ifdef ASSERT
1905     if (in_regs[in].first()->is_Register()) {
1906       assert(!reg_destroyed[in_regs[in].first()->as_Register()->encoding()], "ack!");
1907     } else if (in_regs[in].first()->is_FloatRegister()) {
1908       assert(!freg_destroyed[in_regs[in].first()->as_FloatRegister()->encoding()], "ack!");
1909     }
1910     if (out_regs[out].first()->is_Register()) {
1911       reg_destroyed[out_regs[out].first()->as_Register()->encoding()] = true;
1912     } else if (out_regs[out].first()->is_FloatRegister()) {
1913       freg_destroyed[out_regs[out].first()->as_FloatRegister()->encoding()] = true;
1914     }
1915     if (out_regs2[out].first()->is_Register()) {
1916       reg_destroyed[out_regs2[out].first()->as_Register()->encoding()] = true;
1917     } else if (out_regs2[out].first()->is_FloatRegister()) {
1918       freg_destroyed[out_regs2[out].first()->as_FloatRegister()->encoding()] = true;
1919     }
1920 #endif // ASSERT
1921 
1922     switch (in_sig_bt[in]) {
1923       case T_BOOLEAN:
1924       case T_CHAR:
1925       case T_BYTE:
1926       case T_SHORT:
1927       case T_INT:
1928         // Move int and do sign extension.
1929         int_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1930         break;
1931       case T_LONG:
1932         long_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1933         break;
1934       case T_ARRAY:
1935       case T_OBJECT:
1936         object_move(masm, stack_slots,
1937                     oop_map, oop_handle_slot_offset,
1938                     ((in == 0) && (!method_is_static)), &receiver_offset,
1939                     in_regs[in], out_regs[out],
1940                     r_callers_sp, r_temp_1, r_temp_2);
1941         break;
1942       case T_VOID:
1943         break;
1944       case T_FLOAT:
1945         float_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1946         if (out_regs2[out].first()->is_valid()) {
1947           float_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
1948         }
1949         break;
1950       case T_DOUBLE:
1951         double_move(masm, in_regs[in], out_regs[out], r_callers_sp, r_temp_1);
1952         if (out_regs2[out].first()->is_valid()) {
1953           double_move(masm, in_regs[in], out_regs2[out], r_callers_sp, r_temp_1);
1954         }
1955         break;
1956       case T_ADDRESS:
1957         fatal("found type (T_ADDRESS) in java args");
1958         break;
1959       default:
1960         ShouldNotReachHere();
1961         break;
1962     }
1963   }
1964 
1965   // Pre-load a static method's oop into ARG2.
1966   // Used both by locking code and the normal JNI call code.
1967   if (method_is_static) {
1968     __ set_oop_constant(JNIHandles::make_local(method->method_holder()->java_mirror()),
1969                         r_carg2_classorobject);
1970 
1971     // Now handlize the static class mirror in carg2. It's known not-null.
1972     __ std(r_carg2_classorobject, klass_offset, R1_SP);
1973     oop_map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1974     __ addi(r_carg2_classorobject, R1_SP, klass_offset);
1975   }
1976 
1977   // Get JNIEnv* which is first argument to native.
1978   __ addi(r_carg1_jnienv, R16_thread, in_bytes(JavaThread::jni_environment_offset()));
1979 
1980   // NOTE:
1981   //
1982   // We have all of the arguments setup at this point.
1983   // We MUST NOT touch any outgoing regs from this point on.
1984   // So if we must call out we must push a new frame.
1985 
1986   // Get current pc for oopmap, and load it patchable relative to global toc.
1987   oopmap_pc = (intptr_t) __ pc();
1988   __ calculate_address_from_global_toc(r_return_pc, (address)oopmap_pc, true, true, true, true);
1989 
1990   // We use the same pc/oopMap repeatedly when we call out.
1991   oop_maps->add_gc_map(oopmap_pc - start_pc, oop_map);
1992 
1993   // r_return_pc now has the pc loaded that we will use when we finally call
1994   // to native.
1995 
1996   // Make sure that thread is non-volatile; it crosses a bunch of VM calls below.
1997   assert(R16_thread->is_nonvolatile(), "thread must be in non-volatile register");
1998 
1999 # if 0
2000   // DTrace method entry
2001 # endif
2002 
2003   // Lock a synchronized method.
2004   // --------------------------------------------------------------------------
2005 
2006   if (method->is_synchronized()) {
2007     ConditionRegister r_flag = CCR1;
2008     Register          r_oop  = r_temp_4;
2009     const Register    r_box  = r_temp_5;
2010     Label             done, locked;
2011 
2012     // Load the oop for the object or class. r_carg2_classorobject contains
2013     // either the handlized oop from the incoming arguments or the handlized
2014     // class mirror (if the method is static).
2015     __ ld(r_oop, 0, r_carg2_classorobject);
2016 
2017     // Get the lock box slot's address.
2018     __ addi(r_box, R1_SP, lock_offset);
2019 
2020     // Try fastpath for locking.
2021     // fast_lock kills r_temp_1, r_temp_2, r_temp_3.
2022     __ compiler_fast_lock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2023     __ beq(r_flag, locked);
2024 
2025     // None of the above fast optimizations worked so we have to get into the
2026     // slow case of monitor enter. Inline a special case of call_VM that
2027     // disallows any pending_exception.
2028 
2029     // Save argument registers and leave room for C-compatible ABI_REG_ARGS.
2030     int frame_size = frame::abi_reg_args_size + align_up(total_c_args * wordSize, frame::alignment_in_bytes);
2031     __ mr(R11_scratch1, R1_SP);
2032     RegisterSaver::push_frame_and_save_argument_registers(masm, R12_scratch2, frame_size, total_c_args, out_regs, out_regs2);
2033 
2034     // Do the call.
2035     __ set_last_Java_frame(R11_scratch1, r_return_pc);
2036     assert(r_return_pc->is_nonvolatile(), "expecting return pc to be in non-volatile register");
2037     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), r_oop, r_box, R16_thread);
2038     __ reset_last_Java_frame();
2039 
2040     RegisterSaver::restore_argument_registers_and_pop_frame(masm, frame_size, total_c_args, out_regs, out_regs2);
2041 
2042     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2043        "no pending exception allowed on exit from SharedRuntime::complete_monitor_locking_C");
2044 
2045     __ bind(locked);
2046   }
2047 
2048   // Use that pc we placed in r_return_pc a while back as the current frame anchor.
2049   __ set_last_Java_frame(R1_SP, r_return_pc);
2050 
2051   // Publish thread state
2052   // --------------------------------------------------------------------------
2053 
2054   // Transition from _thread_in_Java to _thread_in_native.
2055   __ li(R0, _thread_in_native);
2056   __ release();
2057   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2058   __ stw(R0, thread_(thread_state));
2059 
2060 
2061   // The JNI call
2062   // --------------------------------------------------------------------------
2063 #if defined(ABI_ELFv2)
2064   __ call_c(native_func, relocInfo::runtime_call_type);
2065 #else
2066   FunctionDescriptor* fd_native_method = (FunctionDescriptor*) native_func;
2067   __ call_c(fd_native_method, relocInfo::runtime_call_type);
2068 #endif
2069 
2070 
2071   // Now, we are back from the native code.
2072 
2073 
2074   // Unpack the native result.
2075   // --------------------------------------------------------------------------
2076 
2077   // For int-types, we do any needed sign-extension required.
2078   // Care must be taken that the return values (R3_RET and F1_RET)
2079   // will survive any VM calls for blocking or unlocking.
2080   // An OOP result (handle) is done specially in the slow-path code.
2081 
2082   switch (ret_type) {
2083     case T_VOID:    break;        // Nothing to do!
2084     case T_FLOAT:   break;        // Got it where we want it (unless slow-path).
2085     case T_DOUBLE:  break;        // Got it where we want it (unless slow-path).
2086     case T_LONG:    break;        // Got it where we want it (unless slow-path).
2087     case T_OBJECT:  break;        // Really a handle.
2088                                   // Cannot de-handlize until after reclaiming jvm_lock.
2089     case T_ARRAY:   break;
2090 
2091     case T_BOOLEAN: {             // 0 -> false(0); !0 -> true(1)
2092       Label skip_modify;
2093       __ cmpwi(CCR0, R3_RET, 0);
2094       __ beq(CCR0, skip_modify);
2095       __ li(R3_RET, 1);
2096       __ bind(skip_modify);
2097       break;
2098       }
2099     case T_BYTE: {                // sign extension
2100       __ extsb(R3_RET, R3_RET);
2101       break;
2102       }
2103     case T_CHAR: {                // unsigned result
2104       __ andi(R3_RET, R3_RET, 0xffff);
2105       break;
2106       }
2107     case T_SHORT: {               // sign extension
2108       __ extsh(R3_RET, R3_RET);
2109       break;
2110       }
2111     case T_INT:                   // nothing to do
2112       break;
2113     default:
2114       ShouldNotReachHere();
2115       break;
2116   }
2117 
2118   Label after_transition;
2119 
2120   // Publish thread state
2121   // --------------------------------------------------------------------------
2122 
2123   // Switch thread to "native transition" state before reading the
2124   // synchronization state. This additional state is necessary because reading
2125   // and testing the synchronization state is not atomic w.r.t. GC, as this
2126   // scenario demonstrates:
2127   //   - Java thread A, in _thread_in_native state, loads _not_synchronized
2128   //     and is preempted.
2129   //   - VM thread changes sync state to synchronizing and suspends threads
2130   //     for GC.
2131   //   - Thread A is resumed to finish this native method, but doesn't block
2132   //     here since it didn't see any synchronization in progress, and escapes.
2133 
2134   // Transition from _thread_in_native to _thread_in_native_trans.
2135   __ li(R0, _thread_in_native_trans);
2136   __ release();
2137   // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2138   __ stw(R0, thread_(thread_state));
2139 
2140 
2141   // Must we block?
2142   // --------------------------------------------------------------------------
2143 
2144   // Block, if necessary, before resuming in _thread_in_Java state.
2145   // In order for GC to work, don't clear the last_Java_sp until after blocking.
2146   {
2147     Label no_block, sync;
2148 
2149     // Force this write out before the read below.
2150     if (!UseSystemMemoryBarrier) {
2151       __ fence();
2152     }
2153 
2154     Register sync_state_addr = r_temp_4;
2155     Register sync_state      = r_temp_5;
2156     Register suspend_flags   = r_temp_6;
2157 
2158     // No synchronization in progress nor yet synchronized
2159     // (cmp-br-isync on one path, release (same as acquire on PPC64) on the other path).
2160     __ safepoint_poll(sync, sync_state, true /* at_return */, false /* in_nmethod */);
2161 
2162     // Not suspended.
2163     // TODO: PPC port assert(4 == Thread::sz_suspend_flags(), "unexpected field size");
2164     __ lwz(suspend_flags, thread_(suspend_flags));
2165     __ cmpwi(CCR1, suspend_flags, 0);
2166     __ beq(CCR1, no_block);
2167 
2168     // Block. Save any potential method result value before the operation and
2169     // use a leaf call to leave the last_Java_frame setup undisturbed. Doing this
2170     // lets us share the oopMap we used when we went native rather than create
2171     // a distinct one for this pc.
2172     __ bind(sync);
2173     __ isync();
2174 
2175     address entry_point =
2176       CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans);
2177     save_native_result(masm, ret_type, workspace_slot_offset);
2178     __ call_VM_leaf(entry_point, R16_thread);
2179     restore_native_result(masm, ret_type, workspace_slot_offset);
2180 
2181     __ bind(no_block);
2182 
2183     // Publish thread state.
2184     // --------------------------------------------------------------------------
2185 
2186     // Thread state is thread_in_native_trans. Any safepoint blocking has
2187     // already happened so we can now change state to _thread_in_Java.
2188 
2189     // Transition from _thread_in_native_trans to _thread_in_Java.
2190     __ li(R0, _thread_in_Java);
2191     __ lwsync(); // Acquire safepoint and suspend state, release thread state.
2192     // TODO: PPC port assert(4 == JavaThread::sz_thread_state(), "unexpected field size");
2193     __ stw(R0, thread_(thread_state));
2194     __ bind(after_transition);
2195   }
2196 
2197   // Reguard any pages if necessary.
2198   // --------------------------------------------------------------------------
2199 
2200   Label no_reguard;
2201   __ lwz(r_temp_1, thread_(stack_guard_state));
2202   __ cmpwi(CCR0, r_temp_1, StackOverflow::stack_guard_yellow_reserved_disabled);
2203   __ bne(CCR0, no_reguard);
2204 
2205   save_native_result(masm, ret_type, workspace_slot_offset);
2206   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages));
2207   restore_native_result(masm, ret_type, workspace_slot_offset);
2208 
2209   __ bind(no_reguard);
2210 
2211 
2212   // Unlock
2213   // --------------------------------------------------------------------------
2214 
2215   if (method->is_synchronized()) {
2216 
2217     ConditionRegister r_flag   = CCR1;
2218     const Register r_oop       = r_temp_4;
2219     const Register r_box       = r_temp_5;
2220     const Register r_exception = r_temp_6;
2221     Label done;
2222 
2223     // Get oop and address of lock object box.
2224     if (method_is_static) {
2225       assert(klass_offset != -1, "");
2226       __ ld(r_oop, klass_offset, R1_SP);
2227     } else {
2228       assert(receiver_offset != -1, "");
2229       __ ld(r_oop, receiver_offset, R1_SP);
2230     }
2231     __ addi(r_box, R1_SP, lock_offset);
2232 
2233     // Try fastpath for unlocking.
2234     __ compiler_fast_unlock_object(r_flag, r_oop, r_box, r_temp_1, r_temp_2, r_temp_3);
2235     __ beq(r_flag, done);
2236 
2237     // Save and restore any potential method result value around the unlocking operation.
2238     save_native_result(masm, ret_type, workspace_slot_offset);
2239 
2240     // Must save pending exception around the slow-path VM call. Since it's a
2241     // leaf call, the pending exception (if any) can be kept in a register.
2242     __ ld(r_exception, thread_(pending_exception));
2243     assert(r_exception->is_nonvolatile(), "exception register must be non-volatile");
2244     __ li(R0, 0);
2245     __ std(R0, thread_(pending_exception));
2246 
2247     // Slow case of monitor enter.
2248     // Inline a special case of call_VM that disallows any pending_exception.
2249     // Arguments are (oop obj, BasicLock* lock, JavaThread* thread).
2250     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C), r_oop, r_box, R16_thread);
2251 
2252     __ asm_assert_mem8_is_zero(thread_(pending_exception),
2253        "no pending exception allowed on exit from SharedRuntime::complete_monitor_unlocking_C");
2254 
2255     restore_native_result(masm, ret_type, workspace_slot_offset);
2256 
2257     // Check_forward_pending_exception jump to forward_exception if any pending
2258     // exception is set. The forward_exception routine expects to see the
2259     // exception in pending_exception and not in a register. Kind of clumsy,
2260     // since all folks who branch to forward_exception must have tested
2261     // pending_exception first and hence have it in a register already.
2262     __ std(r_exception, thread_(pending_exception));
2263 
2264     __ bind(done);
2265   }
2266 
2267 # if 0
2268   // DTrace method exit
2269 # endif
2270 
2271   // Clear "last Java frame" SP and PC.
2272   // --------------------------------------------------------------------------
2273 
2274   __ reset_last_Java_frame();
2275 
2276   // Unbox oop result, e.g. JNIHandles::resolve value.
2277   // --------------------------------------------------------------------------
2278 
2279   if (is_reference_type(ret_type)) {
2280     __ resolve_jobject(R3_RET, r_temp_1, r_temp_2, MacroAssembler::PRESERVATION_NONE);
2281   }
2282 
2283   if (CheckJNICalls) {
2284     // clear_pending_jni_exception_check
2285     __ load_const_optimized(R0, 0L);
2286     __ st_ptr(R0, JavaThread::pending_jni_exception_check_fn_offset(), R16_thread);
2287   }
2288 
2289   // Reset handle block.
2290   // --------------------------------------------------------------------------
2291   __ ld(r_temp_1, thread_(active_handles));
2292   // TODO: PPC port assert(4 == JNIHandleBlock::top_size_in_bytes(), "unexpected field size");
2293   __ li(r_temp_2, 0);
2294   __ stw(r_temp_2, JNIHandleBlock::top_offset_in_bytes(), r_temp_1);
2295 
2296 
2297   // Check for pending exceptions.
2298   // --------------------------------------------------------------------------
2299   __ ld(r_temp_2, thread_(pending_exception));
2300   __ cmpdi(CCR0, r_temp_2, 0);
2301   __ bne(CCR0, handle_pending_exception);
2302 
2303   // Return
2304   // --------------------------------------------------------------------------
2305 
2306   __ pop_frame();
2307   __ restore_LR_CR(R11);
2308   __ blr();
2309 
2310 
2311   // Handler for pending exceptions (out-of-line).
2312   // --------------------------------------------------------------------------
2313   // Since this is a native call, we know the proper exception handler
2314   // is the empty function. We just pop this frame and then jump to
2315   // forward_exception_entry.
2316   __ bind(handle_pending_exception);
2317 
2318   __ pop_frame();
2319   __ restore_LR_CR(R11);
2320   __ b64_patchable((address)StubRoutines::forward_exception_entry(),
2321                        relocInfo::runtime_call_type);
2322 
2323   // Handler for a cache miss (out-of-line).
2324   // --------------------------------------------------------------------------
2325 
2326   if (!method_is_static) {
2327   __ bind(ic_miss);
2328 
2329   __ b64_patchable((address)SharedRuntime::get_ic_miss_stub(),
2330                        relocInfo::runtime_call_type);
2331   }
2332 
2333   // Done.
2334   // --------------------------------------------------------------------------
2335 
2336   __ flush();
2337 
2338   nmethod *nm = nmethod::new_native_nmethod(method,
2339                                             compile_id,
2340                                             masm->code(),
2341                                             vep_start_pc-start_pc,
2342                                             frame_done_pc-start_pc,
2343                                             stack_slots / VMRegImpl::slots_per_word,
2344                                             (method_is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2345                                             in_ByteSize(lock_offset),
2346                                             oop_maps);
2347 
2348   return nm;
2349 }
2350 
2351 // This function returns the adjust size (in number of words) to a c2i adapter
2352 // activation for use during deoptimization.
2353 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2354   return align_up((callee_locals - callee_parameters) * Interpreter::stackElementWords, frame::alignment_in_bytes);
2355 }
2356 
2357 uint SharedRuntime::in_preserve_stack_slots() {
2358   return frame::jit_in_preserve_size / VMRegImpl::stack_slot_size;
2359 }
2360 
2361 uint SharedRuntime::out_preserve_stack_slots() {
2362 #if defined(COMPILER1) || defined(COMPILER2)
2363   return frame::jit_out_preserve_size / VMRegImpl::stack_slot_size;
2364 #else
2365   return 0;
2366 #endif
2367 }
2368 
2369 #if defined(COMPILER1) || defined(COMPILER2)
2370 // Frame generation for deopt and uncommon trap blobs.
2371 static void push_skeleton_frame(MacroAssembler* masm, bool deopt,
2372                                 /* Read */
2373                                 Register unroll_block_reg,
2374                                 /* Update */
2375                                 Register frame_sizes_reg,
2376                                 Register number_of_frames_reg,
2377                                 Register pcs_reg,
2378                                 /* Invalidate */
2379                                 Register frame_size_reg,
2380                                 Register pc_reg) {
2381 
2382   __ ld(pc_reg, 0, pcs_reg);
2383   __ ld(frame_size_reg, 0, frame_sizes_reg);
2384   __ std(pc_reg, _abi0(lr), R1_SP);
2385   __ push_frame(frame_size_reg, R0/*tmp*/);
2386   __ std(R1_SP, _ijava_state_neg(sender_sp), R1_SP);
2387   __ addi(number_of_frames_reg, number_of_frames_reg, -1);
2388   __ addi(frame_sizes_reg, frame_sizes_reg, wordSize);
2389   __ addi(pcs_reg, pcs_reg, wordSize);
2390 }
2391 
2392 // Loop through the UnrollBlock info and create new frames.
2393 static void push_skeleton_frames(MacroAssembler* masm, bool deopt,
2394                                  /* read */
2395                                  Register unroll_block_reg,
2396                                  /* invalidate */
2397                                  Register frame_sizes_reg,
2398                                  Register number_of_frames_reg,
2399                                  Register pcs_reg,
2400                                  Register frame_size_reg,
2401                                  Register pc_reg) {
2402   Label loop;
2403 
2404  // _number_of_frames is of type int (deoptimization.hpp)
2405   __ lwa(number_of_frames_reg,
2406              Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes(),
2407              unroll_block_reg);
2408   __ ld(pcs_reg,
2409             Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes(),
2410             unroll_block_reg);
2411   __ ld(frame_sizes_reg,
2412             Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes(),
2413             unroll_block_reg);
2414 
2415   // stack: (caller_of_deoptee, ...).
2416 
2417   // At this point we either have an interpreter frame or a compiled
2418   // frame on top of stack. If it is a compiled frame we push a new c2i
2419   // adapter here
2420 
2421   // Memorize top-frame stack-pointer.
2422   __ mr(frame_size_reg/*old_sp*/, R1_SP);
2423 
2424   // Resize interpreter top frame OR C2I adapter.
2425 
2426   // At this moment, the top frame (which is the caller of the deoptee) is
2427   // an interpreter frame or a newly pushed C2I adapter or an entry frame.
2428   // The top frame has a TOP_IJAVA_FRAME_ABI and the frame contains the
2429   // outgoing arguments.
2430   //
2431   // In order to push the interpreter frame for the deoptee, we need to
2432   // resize the top frame such that we are able to place the deoptee's
2433   // locals in the frame.
2434   // Additionally, we have to turn the top frame's TOP_IJAVA_FRAME_ABI
2435   // into a valid PARENT_IJAVA_FRAME_ABI.
2436 
2437   __ lwa(R11_scratch1,
2438              Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes(),
2439              unroll_block_reg);
2440   __ neg(R11_scratch1, R11_scratch1);
2441 
2442   // R11_scratch1 contains size of locals for frame resizing.
2443   // R12_scratch2 contains top frame's lr.
2444 
2445   // Resize frame by complete frame size prevents TOC from being
2446   // overwritten by locals. A more stack space saving way would be
2447   // to copy the TOC to its location in the new abi.
2448   __ addi(R11_scratch1, R11_scratch1, - frame::parent_ijava_frame_abi_size);
2449 
2450   // now, resize the frame
2451   __ resize_frame(R11_scratch1, pc_reg/*tmp*/);
2452 
2453   // In the case where we have resized a c2i frame above, the optional
2454   // alignment below the locals has size 32 (why?).
2455   __ std(R12_scratch2, _abi0(lr), R1_SP);
2456 
2457   // Initialize initial_caller_sp.
2458  __ std(frame_size_reg, _ijava_state_neg(sender_sp), R1_SP);
2459 
2460 #ifdef ASSERT
2461   // Make sure that there is at least one entry in the array.
2462   __ cmpdi(CCR0, number_of_frames_reg, 0);
2463   __ asm_assert_ne("array_size must be > 0");
2464 #endif
2465 
2466   // Now push the new interpreter frames.
2467   //
2468   __ bind(loop);
2469   // Allocate a new frame, fill in the pc.
2470   push_skeleton_frame(masm, deopt,
2471                       unroll_block_reg,
2472                       frame_sizes_reg,
2473                       number_of_frames_reg,
2474                       pcs_reg,
2475                       frame_size_reg,
2476                       pc_reg);
2477   __ cmpdi(CCR0, number_of_frames_reg, 0);
2478   __ bne(CCR0, loop);
2479 
2480   // Get the return address pointing into the frame manager.
2481   __ ld(R0, 0, pcs_reg);
2482   // Store it in the top interpreter frame.
2483   __ std(R0, _abi0(lr), R1_SP);
2484   // Initialize frame_manager_lr of interpreter top frame.
2485 }
2486 #endif
2487 
2488 void SharedRuntime::generate_deopt_blob() {
2489   // Allocate space for the code
2490   ResourceMark rm;
2491   // Setup code generation tools
2492   CodeBuffer buffer("deopt_blob", 2048, 1024);
2493   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2494   Label exec_mode_initialized;
2495   int frame_size_in_words;
2496   OopMap* map = NULL;
2497   OopMapSet *oop_maps = new OopMapSet();
2498 
2499   // size of ABI112 plus spill slots for R3_RET and F1_RET.
2500   const int frame_size_in_bytes = frame::abi_reg_args_spill_size;
2501   const int frame_size_in_slots = frame_size_in_bytes / sizeof(jint);
2502   int first_frame_size_in_bytes = 0; // frame size of "unpack frame" for call to fetch_unroll_info.
2503 
2504   const Register exec_mode_reg = R21_tmp1;
2505 
2506   const address start = __ pc();
2507 
2508 #if defined(COMPILER1) || defined(COMPILER2)
2509   // --------------------------------------------------------------------------
2510   // Prolog for non exception case!
2511 
2512   // We have been called from the deopt handler of the deoptee.
2513   //
2514   // deoptee:
2515   //                      ...
2516   //                      call X
2517   //                      ...
2518   //  deopt_handler:      call_deopt_stub
2519   //  cur. return pc  --> ...
2520   //
2521   // So currently SR_LR points behind the call in the deopt handler.
2522   // We adjust it such that it points to the start of the deopt handler.
2523   // The return_pc has been stored in the frame of the deoptee and
2524   // will replace the address of the deopt_handler in the call
2525   // to Deoptimization::fetch_unroll_info below.
2526   // We can't grab a free register here, because all registers may
2527   // contain live values, so let the RegisterSaver do the adjustment
2528   // of the return pc.
2529   const int return_pc_adjustment_no_exception = -MacroAssembler::bl64_patchable_size;
2530 
2531   // Push the "unpack frame"
2532   // Save everything in sight.
2533   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2534                                                                    &first_frame_size_in_bytes,
2535                                                                    /*generate_oop_map=*/ true,
2536                                                                    return_pc_adjustment_no_exception,
2537                                                                    RegisterSaver::return_pc_is_lr);
2538   assert(map != NULL, "OopMap must have been created");
2539 
2540   __ li(exec_mode_reg, Deoptimization::Unpack_deopt);
2541   // Save exec mode for unpack_frames.
2542   __ b(exec_mode_initialized);
2543 
2544   // --------------------------------------------------------------------------
2545   // Prolog for exception case
2546 
2547   // An exception is pending.
2548   // We have been called with a return (interpreter) or a jump (exception blob).
2549   //
2550   // - R3_ARG1: exception oop
2551   // - R4_ARG2: exception pc
2552 
2553   int exception_offset = __ pc() - start;
2554 
2555   BLOCK_COMMENT("Prolog for exception case");
2556 
2557   // Store exception oop and pc in thread (location known to GC).
2558   // This is needed since the call to "fetch_unroll_info()" may safepoint.
2559   __ std(R3_ARG1, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2560   __ std(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2561   __ std(R4_ARG2, _abi0(lr), R1_SP);
2562 
2563   // Vanilla deoptimization with an exception pending in exception_oop.
2564   int exception_in_tls_offset = __ pc() - start;
2565 
2566   // Push the "unpack frame".
2567   // Save everything in sight.
2568   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2569                                                              &first_frame_size_in_bytes,
2570                                                              /*generate_oop_map=*/ false,
2571                                                              /*return_pc_adjustment_exception=*/ 0,
2572                                                              RegisterSaver::return_pc_is_pre_saved);
2573 
2574   // Deopt during an exception. Save exec mode for unpack_frames.
2575   __ li(exec_mode_reg, Deoptimization::Unpack_exception);
2576 
2577   // fall through
2578 
2579   int reexecute_offset = 0;
2580 #ifdef COMPILER1
2581   __ b(exec_mode_initialized);
2582 
2583   // Reexecute entry, similar to c2 uncommon trap
2584   reexecute_offset = __ pc() - start;
2585 
2586   RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2587                                                              &first_frame_size_in_bytes,
2588                                                              /*generate_oop_map=*/ false,
2589                                                              /*return_pc_adjustment_reexecute=*/ 0,
2590                                                              RegisterSaver::return_pc_is_pre_saved);
2591   __ li(exec_mode_reg, Deoptimization::Unpack_reexecute);
2592 #endif
2593 
2594   // --------------------------------------------------------------------------
2595   __ BIND(exec_mode_initialized);
2596 
2597   const Register unroll_block_reg = R22_tmp2;
2598 
2599   // We need to set `last_Java_frame' because `fetch_unroll_info' will
2600   // call `last_Java_frame()'. The value of the pc in the frame is not
2601   // particularly important. It just needs to identify this blob.
2602   __ set_last_Java_frame(R1_SP, noreg);
2603 
2604   // With EscapeAnalysis turned on, this call may safepoint!
2605   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info), R16_thread, exec_mode_reg);
2606   address calls_return_pc = __ last_calls_return_pc();
2607   // Set an oopmap for the call site that describes all our saved registers.
2608   oop_maps->add_gc_map(calls_return_pc - start, map);
2609 
2610   __ reset_last_Java_frame();
2611   // Save the return value.
2612   __ mr(unroll_block_reg, R3_RET);
2613 
2614   // Restore only the result registers that have been saved
2615   // by save_volatile_registers(...).
2616   RegisterSaver::restore_result_registers(masm, first_frame_size_in_bytes);
2617 
2618   // reload the exec mode from the UnrollBlock (it might have changed)
2619   __ lwz(exec_mode_reg, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2620   // In excp_deopt_mode, restore and clear exception oop which we
2621   // stored in the thread during exception entry above. The exception
2622   // oop will be the return value of this stub.
2623   Label skip_restore_excp;
2624   __ cmpdi(CCR0, exec_mode_reg, Deoptimization::Unpack_exception);
2625   __ bne(CCR0, skip_restore_excp);
2626   __ ld(R3_RET, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2627   __ ld(R4_ARG2, in_bytes(JavaThread::exception_pc_offset()), R16_thread);
2628   __ li(R0, 0);
2629   __ std(R0, in_bytes(JavaThread::exception_pc_offset()),  R16_thread);
2630   __ std(R0, in_bytes(JavaThread::exception_oop_offset()), R16_thread);
2631   __ BIND(skip_restore_excp);
2632 
2633   __ pop_frame();
2634 
2635   // stack: (deoptee, optional i2c, caller of deoptee, ...).
2636 
2637   // pop the deoptee's frame
2638   __ pop_frame();
2639 
2640   // stack: (caller_of_deoptee, ...).
2641 
2642   // Loop through the `UnrollBlock' info and create interpreter frames.
2643   push_skeleton_frames(masm, true/*deopt*/,
2644                        unroll_block_reg,
2645                        R23_tmp3,
2646                        R24_tmp4,
2647                        R25_tmp5,
2648                        R26_tmp6,
2649                        R27_tmp7);
2650 
2651   // stack: (skeletal interpreter frame, ..., optional skeletal
2652   // interpreter frame, optional c2i, caller of deoptee, ...).
2653 
2654   // push an `unpack_frame' taking care of float / int return values.
2655   __ push_frame(frame_size_in_bytes, R0/*tmp*/);
2656 
2657   // stack: (unpack frame, skeletal interpreter frame, ..., optional
2658   // skeletal interpreter frame, optional c2i, caller of deoptee,
2659   // ...).
2660 
2661   // Spill live volatile registers since we'll do a call.
2662   __ std( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2663   __ stfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2664 
2665   // Let the unpacker layout information in the skeletal frames just
2666   // allocated.
2667   __ calculate_address_from_global_toc(R3_RET, calls_return_pc, true, true, true, true);
2668   __ set_last_Java_frame(/*sp*/R1_SP, /*pc*/R3_RET);
2669   // This is a call to a LEAF method, so no oop map is required.
2670   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
2671                   R16_thread/*thread*/, exec_mode_reg/*exec_mode*/);
2672   __ reset_last_Java_frame();
2673 
2674   // Restore the volatiles saved above.
2675   __ ld( R3_RET, _abi_reg_args_spill(spill_ret),  R1_SP);
2676   __ lfd(F1_RET, _abi_reg_args_spill(spill_fret), R1_SP);
2677 
2678   // Pop the unpack frame.
2679   __ pop_frame();
2680   __ restore_LR_CR(R0);
2681 
2682   // stack: (top interpreter frame, ..., optional interpreter frame,
2683   // optional c2i, caller of deoptee, ...).
2684 
2685   // Initialize R14_state.
2686   __ restore_interpreter_state(R11_scratch1);
2687   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2688 
2689   // Return to the interpreter entry point.
2690   __ blr();
2691   __ flush();
2692 #else // COMPILER2
2693   __ unimplemented("deopt blob needed only with compiler");
2694   int exception_offset = __ pc() - start;
2695 #endif // COMPILER2
2696 
2697   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset,
2698                                            reexecute_offset, first_frame_size_in_bytes / wordSize);
2699   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2700 }
2701 
2702 #ifdef COMPILER2
2703 void SharedRuntime::generate_uncommon_trap_blob() {
2704   // Allocate space for the code.
2705   ResourceMark rm;
2706   // Setup code generation tools.
2707   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2708   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2709   address start = __ pc();
2710 
2711   if (UseRTMLocking) {
2712     // Abort RTM transaction before possible nmethod deoptimization.
2713     __ tabort_();
2714   }
2715 
2716   Register unroll_block_reg = R21_tmp1;
2717   Register klass_index_reg  = R22_tmp2;
2718   Register unc_trap_reg     = R23_tmp3;
2719   Register r_return_pc      = R27_tmp7;
2720 
2721   OopMapSet* oop_maps = new OopMapSet();
2722   int frame_size_in_bytes = frame::abi_reg_args_size;
2723   OopMap* map = new OopMap(frame_size_in_bytes / sizeof(jint), 0);
2724 
2725   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2726 
2727   // Push a dummy `unpack_frame' and call
2728   // `Deoptimization::uncommon_trap' to pack the compiled frame into a
2729   // vframe array and return the `UnrollBlock' information.
2730 
2731   // Save LR to compiled frame.
2732   __ save_LR_CR(R11_scratch1);
2733 
2734   // Push an "uncommon_trap" frame.
2735   __ push_frame_reg_args(0, R11_scratch1);
2736 
2737   // stack: (unpack frame, deoptee, optional i2c, caller_of_deoptee, ...).
2738 
2739   // Set the `unpack_frame' as last_Java_frame.
2740   // `Deoptimization::uncommon_trap' expects it and considers its
2741   // sender frame as the deoptee frame.
2742   // Remember the offset of the instruction whose address will be
2743   // moved to R11_scratch1.
2744   address gc_map_pc = __ pc();
2745   __ calculate_address_from_global_toc(r_return_pc, gc_map_pc, true, true, true, true);
2746   __ set_last_Java_frame(/*sp*/R1_SP, r_return_pc);
2747 
2748   __ mr(klass_index_reg, R3);
2749   __ li(R5_ARG3, Deoptimization::Unpack_uncommon_trap);
2750   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap),
2751                   R16_thread, klass_index_reg, R5_ARG3);
2752 
2753   // Set an oopmap for the call site.
2754   oop_maps->add_gc_map(gc_map_pc - start, map);
2755 
2756   __ reset_last_Java_frame();
2757 
2758   // Pop the `unpack frame'.
2759   __ pop_frame();
2760 
2761   // stack: (deoptee, optional i2c, caller_of_deoptee, ...).
2762 
2763   // Save the return value.
2764   __ mr(unroll_block_reg, R3_RET);
2765 
2766   // Pop the uncommon_trap frame.
2767   __ pop_frame();
2768 
2769   // stack: (caller_of_deoptee, ...).
2770 
2771 #ifdef ASSERT
2772   __ lwz(R22_tmp2, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes(), unroll_block_reg);
2773   __ cmpdi(CCR0, R22_tmp2, (unsigned)Deoptimization::Unpack_uncommon_trap);
2774   __ asm_assert_eq("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
2775 #endif
2776 
2777   // Allocate new interpreter frame(s) and possibly a c2i adapter
2778   // frame.
2779   push_skeleton_frames(masm, false/*deopt*/,
2780                        unroll_block_reg,
2781                        R22_tmp2,
2782                        R23_tmp3,
2783                        R24_tmp4,
2784                        R25_tmp5,
2785                        R26_tmp6);
2786 
2787   // stack: (skeletal interpreter frame, ..., optional skeletal
2788   // interpreter frame, optional c2i, caller of deoptee, ...).
2789 
2790   // Push a dummy `unpack_frame' taking care of float return values.
2791   // Call `Deoptimization::unpack_frames' to layout information in the
2792   // interpreter frames just created.
2793 
2794   // Push a simple "unpack frame" here.
2795   __ push_frame_reg_args(0, R11_scratch1);
2796 
2797   // stack: (unpack frame, skeletal interpreter frame, ..., optional
2798   // skeletal interpreter frame, optional c2i, caller of deoptee,
2799   // ...).
2800 
2801   // Set the "unpack_frame" as last_Java_frame.
2802   __ set_last_Java_frame(/*sp*/R1_SP, r_return_pc);
2803 
2804   // Indicate it is the uncommon trap case.
2805   __ li(unc_trap_reg, Deoptimization::Unpack_uncommon_trap);
2806   // Let the unpacker layout information in the skeletal frames just
2807   // allocated.
2808   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
2809                   R16_thread, unc_trap_reg);
2810 
2811   __ reset_last_Java_frame();
2812   // Pop the `unpack frame'.
2813   __ pop_frame();
2814   // Restore LR from top interpreter frame.
2815   __ restore_LR_CR(R11_scratch1);
2816 
2817   // stack: (top interpreter frame, ..., optional interpreter frame,
2818   // optional c2i, caller of deoptee, ...).
2819 
2820   __ restore_interpreter_state(R11_scratch1);
2821   __ load_const_optimized(R25_templateTableBase, (address)Interpreter::dispatch_table((TosState)0), R11_scratch1);
2822 
2823   // Return to the interpreter entry point.
2824   __ blr();
2825 
2826   masm->flush();
2827 
2828   _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, frame_size_in_bytes/wordSize);
2829 }
2830 #endif // COMPILER2
2831 
2832 // Generate a special Compile2Runtime blob that saves all registers, and setup oopmap.
2833 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2834   assert(StubRoutines::forward_exception_entry() != NULL,
2835          "must be generated before");
2836 
2837   ResourceMark rm;
2838   OopMapSet *oop_maps = new OopMapSet();
2839   OopMap* map;
2840 
2841   // Allocate space for the code. Setup code generation tools.
2842   CodeBuffer buffer("handler_blob", 2048, 1024);
2843   MacroAssembler* masm = new MacroAssembler(&buffer);
2844 
2845   address start = __ pc();
2846   int frame_size_in_bytes = 0;
2847 
2848   RegisterSaver::ReturnPCLocation return_pc_location;
2849   bool cause_return = (poll_type == POLL_AT_RETURN);
2850   if (cause_return) {
2851     // Nothing to do here. The frame has already been popped in MachEpilogNode.
2852     // Register LR already contains the return pc.
2853     return_pc_location = RegisterSaver::return_pc_is_pre_saved;
2854   } else {
2855     // Use thread()->saved_exception_pc() as return pc.
2856     return_pc_location = RegisterSaver::return_pc_is_thread_saved_exception_pc;
2857   }
2858 
2859   if (UseRTMLocking) {
2860     // Abort RTM transaction before calling runtime
2861     // because critical section can be large and so
2862     // will abort anyway. Also nmethod can be deoptimized.
2863     __ tabort_();
2864   }
2865 
2866   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2867 
2868   // Save registers, fpu state, and flags. Set R31 = return pc.
2869   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2870                                                                    &frame_size_in_bytes,
2871                                                                    /*generate_oop_map=*/ true,
2872                                                                    /*return_pc_adjustment=*/0,
2873                                                                    return_pc_location, save_vectors);
2874 
2875   // The following is basically a call_VM. However, we need the precise
2876   // address of the call in order to generate an oopmap. Hence, we do all the
2877   // work ourselves.
2878   __ set_last_Java_frame(/*sp=*/R1_SP, /*pc=*/noreg);
2879 
2880   // The return address must always be correct so that the frame constructor
2881   // never sees an invalid pc.
2882 
2883   // Do the call
2884   __ call_VM_leaf(call_ptr, R16_thread);
2885   address calls_return_pc = __ last_calls_return_pc();
2886 
2887   // Set an oopmap for the call site. This oopmap will map all
2888   // oop-registers and debug-info registers as callee-saved. This
2889   // will allow deoptimization at this safepoint to find all possible
2890   // debug-info recordings, as well as let GC find all oops.
2891   oop_maps->add_gc_map(calls_return_pc - start, map);
2892 
2893   Label noException;
2894 
2895   // Clear the last Java frame.
2896   __ reset_last_Java_frame();
2897 
2898   BLOCK_COMMENT("  Check pending exception.");
2899   const Register pending_exception = R0;
2900   __ ld(pending_exception, thread_(pending_exception));
2901   __ cmpdi(CCR0, pending_exception, 0);
2902   __ beq(CCR0, noException);
2903 
2904   // Exception pending
2905   RegisterSaver::restore_live_registers_and_pop_frame(masm,
2906                                                       frame_size_in_bytes,
2907                                                       /*restore_ctr=*/true, save_vectors);
2908 
2909   BLOCK_COMMENT("  Jump to forward_exception_entry.");
2910   // Jump to forward_exception_entry, with the issuing PC in LR
2911   // so it looks like the original nmethod called forward_exception_entry.
2912   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
2913 
2914   // No exception case.
2915   __ BIND(noException);
2916 
2917   if (!cause_return) {
2918     Label no_adjust;
2919     // If our stashed return pc was modified by the runtime we avoid touching it
2920     __ ld(R0, frame_size_in_bytes + _abi0(lr), R1_SP);
2921     __ cmpd(CCR0, R0, R31);
2922     __ bne(CCR0, no_adjust);
2923 
2924     // Adjust return pc forward to step over the safepoint poll instruction
2925     __ addi(R31, R31, 4);
2926     __ std(R31, frame_size_in_bytes + _abi0(lr), R1_SP);
2927 
2928     __ bind(no_adjust);
2929   }
2930 
2931   // Normal exit, restore registers and exit.
2932   RegisterSaver::restore_live_registers_and_pop_frame(masm,
2933                                                       frame_size_in_bytes,
2934                                                       /*restore_ctr=*/true, save_vectors);
2935 
2936   __ blr();
2937 
2938   // Make sure all code is generated
2939   masm->flush();
2940 
2941   // Fill-out other meta info
2942   // CodeBlob frame size is in words.
2943   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_bytes / wordSize);
2944 }
2945 
2946 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss)
2947 //
2948 // Generate a stub that calls into the vm to find out the proper destination
2949 // of a java call. All the argument registers are live at this point
2950 // but since this is generic code we don't know what they are and the caller
2951 // must do any gc of the args.
2952 //
2953 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
2954 
2955   // allocate space for the code
2956   ResourceMark rm;
2957 
2958   CodeBuffer buffer(name, 1000, 512);
2959   MacroAssembler* masm = new MacroAssembler(&buffer);
2960 
2961   int frame_size_in_bytes;
2962 
2963   OopMapSet *oop_maps = new OopMapSet();
2964   OopMap* map = NULL;
2965 
2966   address start = __ pc();
2967 
2968   map = RegisterSaver::push_frame_reg_args_and_save_live_registers(masm,
2969                                                                    &frame_size_in_bytes,
2970                                                                    /*generate_oop_map*/ true,
2971                                                                    /*return_pc_adjustment*/ 0,
2972                                                                    RegisterSaver::return_pc_is_lr);
2973 
2974   // Use noreg as last_Java_pc, the return pc will be reconstructed
2975   // from the physical frame.
2976   __ set_last_Java_frame(/*sp*/R1_SP, noreg);
2977 
2978   int frame_complete = __ offset();
2979 
2980   // Pass R19_method as 2nd (optional) argument, used by
2981   // counter_overflow_stub.
2982   __ call_VM_leaf(destination, R16_thread, R19_method);
2983   address calls_return_pc = __ last_calls_return_pc();
2984   // Set an oopmap for the call site.
2985   // We need this not only for callee-saved registers, but also for volatile
2986   // registers that the compiler might be keeping live across a safepoint.
2987   // Create the oopmap for the call's return pc.
2988   oop_maps->add_gc_map(calls_return_pc - start, map);
2989 
2990   // R3_RET contains the address we are going to jump to assuming no exception got installed.
2991 
2992   // clear last_Java_sp
2993   __ reset_last_Java_frame();
2994 
2995   // Check for pending exceptions.
2996   BLOCK_COMMENT("Check for pending exceptions.");
2997   Label pending;
2998   __ ld(R11_scratch1, thread_(pending_exception));
2999   __ cmpdi(CCR0, R11_scratch1, 0);
3000   __ bne(CCR0, pending);
3001 
3002   __ mtctr(R3_RET); // Ctr will not be touched by restore_live_registers_and_pop_frame.
3003 
3004   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ false);
3005 
3006   // Get the returned method.
3007   __ get_vm_result_2(R19_method);
3008 
3009   __ bctr();
3010 
3011 
3012   // Pending exception after the safepoint.
3013   __ BIND(pending);
3014 
3015   RegisterSaver::restore_live_registers_and_pop_frame(masm, frame_size_in_bytes, /*restore_ctr*/ true);
3016 
3017   // exception pending => remove activation and forward to exception handler
3018 
3019   __ li(R11_scratch1, 0);
3020   __ ld(R3_ARG1, thread_(pending_exception));
3021   __ std(R11_scratch1, in_bytes(JavaThread::vm_result_offset()), R16_thread);
3022   __ b64_patchable(StubRoutines::forward_exception_entry(), relocInfo::runtime_call_type);
3023 
3024   // -------------
3025   // Make sure all code is generated.
3026   masm->flush();
3027 
3028   // return the blob
3029   // frame_size_words or bytes??
3030   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_bytes/wordSize,
3031                                        oop_maps, true);
3032 }
3033 
3034 
3035 //------------------------------Montgomery multiplication------------------------
3036 //
3037 
3038 // Subtract 0:b from carry:a. Return carry.
3039 static unsigned long
3040 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3041   long i = 0;
3042   unsigned long tmp, tmp2;
3043   __asm__ __volatile__ (
3044     "subfc  %[tmp], %[tmp], %[tmp]   \n" // pre-set CA
3045     "mtctr  %[len]                   \n"
3046     "0:                              \n"
3047     "ldx    %[tmp], %[i], %[a]       \n"
3048     "ldx    %[tmp2], %[i], %[b]      \n"
3049     "subfe  %[tmp], %[tmp2], %[tmp]  \n" // subtract extended
3050     "stdx   %[tmp], %[i], %[a]       \n"
3051     "addi   %[i], %[i], 8            \n"
3052     "bdnz   0b                       \n"
3053     "addme  %[tmp], %[carry]         \n" // carry + CA - 1
3054     : [i]"+b"(i), [tmp]"=&r"(tmp), [tmp2]"=&r"(tmp2)
3055     : [a]"r"(a), [b]"r"(b), [carry]"r"(carry), [len]"r"(len)
3056     : "ctr", "xer", "memory"
3057   );
3058   return tmp;
3059 }
3060 
3061 // Multiply (unsigned) Long A by Long B, accumulating the double-
3062 // length result into the accumulator formed of T0, T1, and T2.
3063 inline void MACC(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3064   unsigned long hi, lo;
3065   __asm__ __volatile__ (
3066     "mulld  %[lo], %[A], %[B]    \n"
3067     "mulhdu %[hi], %[A], %[B]    \n"
3068     "addc   %[T0], %[T0], %[lo]  \n"
3069     "adde   %[T1], %[T1], %[hi]  \n"
3070     "addze  %[T2], %[T2]         \n"
3071     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3072     : [A]"r"(A), [B]"r"(B)
3073     : "xer"
3074   );
3075 }
3076 
3077 // As above, but add twice the double-length result into the
3078 // accumulator.
3079 inline void MACC2(unsigned long A, unsigned long B, unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3080   unsigned long hi, lo;
3081   __asm__ __volatile__ (
3082     "mulld  %[lo], %[A], %[B]    \n"
3083     "mulhdu %[hi], %[A], %[B]    \n"
3084     "addc   %[T0], %[T0], %[lo]  \n"
3085     "adde   %[T1], %[T1], %[hi]  \n"
3086     "addze  %[T2], %[T2]         \n"
3087     "addc   %[T0], %[T0], %[lo]  \n"
3088     "adde   %[T1], %[T1], %[hi]  \n"
3089     "addze  %[T2], %[T2]         \n"
3090     : [hi]"=&r"(hi), [lo]"=&r"(lo), [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3091     : [A]"r"(A), [B]"r"(B)
3092     : "xer"
3093   );
3094 }
3095 
3096 // Fast Montgomery multiplication. The derivation of the algorithm is
3097 // in "A Cryptographic Library for the Motorola DSP56000,
3098 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
3099 static void
3100 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3101                     unsigned long m[], unsigned long inv, int len) {
3102   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3103   int i;
3104 
3105   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3106 
3107   for (i = 0; i < len; i++) {
3108     int j;
3109     for (j = 0; j < i; j++) {
3110       MACC(a[j], b[i-j], t0, t1, t2);
3111       MACC(m[j], n[i-j], t0, t1, t2);
3112     }
3113     MACC(a[i], b[0], t0, t1, t2);
3114     m[i] = t0 * inv;
3115     MACC(m[i], n[0], t0, t1, t2);
3116 
3117     assert(t0 == 0, "broken Montgomery multiply");
3118 
3119     t0 = t1; t1 = t2; t2 = 0;
3120   }
3121 
3122   for (i = len; i < 2*len; i++) {
3123     int j;
3124     for (j = i-len+1; j < len; j++) {
3125       MACC(a[j], b[i-j], t0, t1, t2);
3126       MACC(m[j], n[i-j], t0, t1, t2);
3127     }
3128     m[i-len] = t0;
3129     t0 = t1; t1 = t2; t2 = 0;
3130   }
3131 
3132   while (t0) {
3133     t0 = sub(m, n, t0, len);
3134   }
3135 }
3136 
3137 // Fast Montgomery squaring. This uses asymptotically 25% fewer
3138 // multiplies so it should be up to 25% faster than Montgomery
3139 // multiplication. However, its loop control is more complex and it
3140 // may actually run slower on some machines.
3141 static void
3142 montgomery_square(unsigned long a[], unsigned long n[],
3143                   unsigned long m[], unsigned long inv, int len) {
3144   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3145   int i;
3146 
3147   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3148 
3149   for (i = 0; i < len; i++) {
3150     int j;
3151     int end = (i+1)/2;
3152     for (j = 0; j < end; j++) {
3153       MACC2(a[j], a[i-j], t0, t1, t2);
3154       MACC(m[j], n[i-j], t0, t1, t2);
3155     }
3156     if ((i & 1) == 0) {
3157       MACC(a[j], a[j], t0, t1, t2);
3158     }
3159     for (; j < i; j++) {
3160       MACC(m[j], n[i-j], t0, t1, t2);
3161     }
3162     m[i] = t0 * inv;
3163     MACC(m[i], n[0], t0, t1, t2);
3164 
3165     assert(t0 == 0, "broken Montgomery square");
3166 
3167     t0 = t1; t1 = t2; t2 = 0;
3168   }
3169 
3170   for (i = len; i < 2*len; i++) {
3171     int start = i-len+1;
3172     int end = start + (len - start)/2;
3173     int j;
3174     for (j = start; j < end; j++) {
3175       MACC2(a[j], a[i-j], t0, t1, t2);
3176       MACC(m[j], n[i-j], t0, t1, t2);
3177     }
3178     if ((i & 1) == 0) {
3179       MACC(a[j], a[j], t0, t1, t2);
3180     }
3181     for (; j < len; j++) {
3182       MACC(m[j], n[i-j], t0, t1, t2);
3183     }
3184     m[i-len] = t0;
3185     t0 = t1; t1 = t2; t2 = 0;
3186   }
3187 
3188   while (t0) {
3189     t0 = sub(m, n, t0, len);
3190   }
3191 }
3192 
3193 // The threshold at which squaring is advantageous was determined
3194 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3195 // Doesn't seem to be relevant for Power8 so we use the same value.
3196 #define MONTGOMERY_SQUARING_THRESHOLD 64
3197 
3198 // Copy len longwords from s to d, word-swapping as we go. The
3199 // destination array is reversed.
3200 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3201   d += len;
3202   while(len-- > 0) {
3203     d--;
3204     unsigned long s_val = *s;
3205     // Swap words in a longword on little endian machines.
3206 #ifdef VM_LITTLE_ENDIAN
3207      s_val = (s_val << 32) | (s_val >> 32);
3208 #endif
3209     *d = s_val;
3210     s++;
3211   }
3212 }
3213 
3214 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3215                                         jint len, jlong inv,
3216                                         jint *m_ints) {
3217   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3218   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3219   int longwords = len/2;
3220 
3221   // Make very sure we don't use so much space that the stack might
3222   // overflow. 512 jints corresponds to an 16384-bit integer and
3223   // will use here a total of 8k bytes of stack space.
3224   int divisor = sizeof(unsigned long) * 4;
3225   guarantee(longwords <= 8192 / divisor, "must be");
3226   int total_allocation = longwords * sizeof (unsigned long) * 4;
3227   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3228 
3229   // Local scratch arrays
3230   unsigned long
3231     *a = scratch + 0 * longwords,
3232     *b = scratch + 1 * longwords,
3233     *n = scratch + 2 * longwords,
3234     *m = scratch + 3 * longwords;
3235 
3236   reverse_words((unsigned long *)a_ints, a, longwords);
3237   reverse_words((unsigned long *)b_ints, b, longwords);
3238   reverse_words((unsigned long *)n_ints, n, longwords);
3239 
3240   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3241 
3242   reverse_words(m, (unsigned long *)m_ints, longwords);
3243 }
3244 
3245 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3246                                       jint len, jlong inv,
3247                                       jint *m_ints) {
3248   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3249   assert(len % 2 == 0, "array length in montgomery_square must be even");
3250   int longwords = len/2;
3251 
3252   // Make very sure we don't use so much space that the stack might
3253   // overflow. 512 jints corresponds to an 16384-bit integer and
3254   // will use here a total of 6k bytes of stack space.
3255   int divisor = sizeof(unsigned long) * 3;
3256   guarantee(longwords <= (8192 / divisor), "must be");
3257   int total_allocation = longwords * sizeof (unsigned long) * 3;
3258   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3259 
3260   // Local scratch arrays
3261   unsigned long
3262     *a = scratch + 0 * longwords,
3263     *n = scratch + 1 * longwords,
3264     *m = scratch + 2 * longwords;
3265 
3266   reverse_words((unsigned long *)a_ints, a, longwords);
3267   reverse_words((unsigned long *)n_ints, n, longwords);
3268 
3269   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3270     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3271   } else {
3272     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3273   }
3274 
3275   reverse_words(m, (unsigned long *)m_ints, longwords);
3276 }