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