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