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