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