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