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