rev 49800 : 8201593: Print array length in ArrayIndexOutOfBoundsException.

   1 /*
   2  * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2016, 2017 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 (SAPJVM extension) 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 (os::is_MP()) {
2159       if (UseMembar) {
2160         // Force this write out before the read below.
2161         __ z_fence();
2162       } else {
2163         // Write serialization page so VM thread can do a pseudo remote membar.
2164         // We use the current thread pointer to calculate a thread specific
2165         // offset to write to within the page. This minimizes bus traffic
2166         // due to cache line collision.
2167         __ serialize_memory(Z_thread, Z_R1, Z_R2);
2168       }
2169     }
2170     __ safepoint_poll(sync, Z_R1);
2171 
2172     __ load_and_test_int(Z_R0, Address(Z_thread, JavaThread::suspend_flags_offset()));
2173     __ z_bre(no_block);
2174 
2175     // Block. Save any potential method result value before the operation and
2176     // use a leaf call to leave the last_Java_frame setup undisturbed. Doing this
2177     // lets us share the oopMap we used when we went native rather than create
2178     // a distinct one for this pc.
2179     //
2180     __ bind(sync);
2181     __ z_acquire();
2182 
2183     address entry_point = is_critical_native ? CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)
2184                                              : CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans);
2185 
2186     __ call_VM_leaf(entry_point, Z_thread);
2187 
2188     if (is_critical_native) {
2189       restore_native_result(masm, ret_type, workspace_slot_offset);
2190       __ z_bru(after_transition); // No thread state transition here.
2191     }
2192     __ bind(no_block);
2193     restore_native_result(masm, ret_type, workspace_slot_offset);
2194   }
2195 
2196   //--------------------------------------------------------------------
2197   // Thread state is thread_in_native_trans. Any safepoint blocking has
2198   // already happened so we can now change state to _thread_in_Java.
2199   //--------------------------------------------------------------------
2200   // Transition from _thread_in_native_trans to _thread_in_Java.
2201   __ set_thread_state(_thread_in_Java);
2202   __ bind(after_transition);
2203 
2204 
2205   //--------------------------------------------------------------------
2206   // Reguard any pages if necessary.
2207   // Protect native result from being destroyed.
2208   //--------------------------------------------------------------------
2209 
2210   Label no_reguard;
2211 
2212   __ z_cli(Address(Z_thread, JavaThread::stack_guard_state_offset() + in_ByteSize(sizeof(JavaThread::StackGuardState) - 1)),
2213            JavaThread::stack_guard_yellow_reserved_disabled);
2214 
2215   __ z_bre(no_reguard);
2216 
2217   save_native_result(masm, ret_type, workspace_slot_offset);
2218   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages), Z_method);
2219   restore_native_result(masm, ret_type, workspace_slot_offset);
2220 
2221   __ bind(no_reguard);
2222 
2223 
2224   // Synchronized methods (slow path only)
2225   // No pending exceptions for now.
2226   //--------------------------------------------------------------------
2227   // Handle possibly pending exception (will unlock if necessary).
2228   // Native result is, if any is live, in Z_FRES or Z_RES.
2229   //--------------------------------------------------------------------
2230   // Unlock
2231   //--------------------------------------------------------------------
2232   if (method->is_synchronized()) {
2233     const Register r_oop        = Z_R11;
2234     const Register r_box        = Z_R12;
2235     const Register r_tmp1       = Z_R13;
2236     const Register r_tmp2       = Z_R7;
2237     Label done;
2238 
2239     // Get unboxed oop of class mirror or object ...
2240     int   offset = method_is_static ? klass_offset : receiver_offset;
2241 
2242     assert(offset != -1, "");
2243     __ z_lg(r_oop, offset, Z_SP);
2244 
2245     // ... and address of lock object box.
2246     __ add2reg(r_box, lock_offset, Z_SP);
2247 
2248     // Try fastpath for unlocking.
2249     __ compiler_fast_unlock_object(r_oop, r_box, r_tmp1, r_tmp2); // Don't use R1 as temp.
2250     __ z_bre(done);
2251 
2252     // Slow path for unlocking.
2253     // Save and restore any potential method result value around the unlocking operation.
2254     const Register R_exc = Z_R11;
2255 
2256     save_native_result(masm, ret_type, workspace_slot_offset);
2257 
2258     // Must save pending exception around the slow-path VM call. Since it's a
2259     // leaf call, the pending exception (if any) can be kept in a register.
2260     __ z_lg(R_exc, Address(Z_thread, Thread::pending_exception_offset()));
2261     assert(R_exc->is_nonvolatile(), "exception register must be non-volatile");
2262 
2263     // Must clear pending-exception before re-entering the VM. Since this is
2264     // a leaf call, pending-exception-oop can be safely kept in a register.
2265     __ clear_mem(Address(Z_thread, Thread::pending_exception_offset()), sizeof(intptr_t));
2266 
2267     // Inline a special case of call_VM that disallows any pending_exception.
2268 
2269     // Get locked oop from the handle we passed to jni.
2270     __ z_lg(Z_ARG1, offset, Z_SP);
2271     __ add2reg(Z_ARG2, lock_offset, Z_SP);
2272     __ z_lgr(Z_ARG3, Z_thread);
2273 
2274     __ load_const_optimized(Z_R1_scratch, CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C));
2275 
2276     __ call(Z_R1_scratch);
2277 
2278 #ifdef ASSERT
2279     {
2280       Label L;
2281       __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
2282       __ z_bre(L);
2283       __ stop("no pending exception allowed on exit from IR::monitorexit");
2284       __ bind(L);
2285     }
2286 #endif
2287 
2288     // Check_forward_pending_exception jump to forward_exception if any pending
2289     // exception is set. The forward_exception routine expects to see the
2290     // exception in pending_exception and not in a register. Kind of clumsy,
2291     // since all folks who branch to forward_exception must have tested
2292     // pending_exception first and hence have it in a register already.
2293     __ z_stg(R_exc, Address(Z_thread, Thread::pending_exception_offset()));
2294     restore_native_result(masm, ret_type, workspace_slot_offset);
2295     __ z_bru(done);
2296     __ z_illtrap(0x66);
2297 
2298     __ bind(done);
2299   }
2300 
2301 
2302   //--------------------------------------------------------------------
2303   // Clear "last Java frame" SP and PC.
2304   //--------------------------------------------------------------------
2305   __ verify_thread(); // Z_thread must be correct.
2306 
2307   __ reset_last_Java_frame();
2308 
2309   // Unpack oop result, e.g. JNIHandles::resolve result.
2310   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2311     __ resolve_jobject(Z_RET, /* tmp1 */ Z_R13, /* tmp2 */ Z_R7);
2312   }
2313 
2314   if (CheckJNICalls) {
2315     // clear_pending_jni_exception_check
2316     __ clear_mem(Address(Z_thread, JavaThread::pending_jni_exception_check_fn_offset()), sizeof(oop));
2317   }
2318 
2319   // Reset handle block.
2320   if (!is_critical_native) {
2321     __ z_lg(Z_R1_scratch, Address(Z_thread, JavaThread::active_handles_offset()));
2322     __ clear_mem(Address(Z_R1_scratch, JNIHandleBlock::top_offset_in_bytes()), 4);
2323 
2324     // Check for pending exceptions.
2325     __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
2326     __ z_brne(handle_pending_exception);
2327   }
2328 
2329 
2330   //////////////////////////////////////////////////////////////////////
2331   // Return
2332   //////////////////////////////////////////////////////////////////////
2333 
2334 
2335 #ifndef USE_RESIZE_FRAME
2336   __ pop_frame();                     // Pop wrapper frame.
2337 #else
2338   __ resize_frame(frame_size_in_bytes, Z_R0_scratch);  // Revert stack extension.
2339 #endif
2340   __ restore_return_pc();             // This is the way back to the caller.
2341   __ z_br(Z_R14);
2342 
2343 
2344   //////////////////////////////////////////////////////////////////////
2345   // Out-of-line calls to the runtime.
2346   //////////////////////////////////////////////////////////////////////
2347 
2348 
2349   if (!is_critical_native) {
2350 
2351     //---------------------------------------------------------------------
2352     // Handler for pending exceptions (out-of-line).
2353     //---------------------------------------------------------------------
2354     // Since this is a native call, we know the proper exception handler
2355     // is the empty function. We just pop this frame and then jump to
2356     // forward_exception_entry. Z_R14 will contain the native caller's
2357     // return PC.
2358     __ bind(handle_pending_exception);
2359     __ pop_frame();
2360     __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
2361     __ restore_return_pc();
2362     __ z_br(Z_R1_scratch);
2363 
2364     //---------------------------------------------------------------------
2365     // Handler for a cache miss (out-of-line)
2366     //---------------------------------------------------------------------
2367     __ call_ic_miss_handler(ic_miss, 0x77, 0, Z_R1_scratch);
2368   }
2369   __ flush();
2370 
2371 
2372   //////////////////////////////////////////////////////////////////////
2373   // end of code generation
2374   //////////////////////////////////////////////////////////////////////
2375 
2376 
2377   nmethod *nm = nmethod::new_native_nmethod(method,
2378                                             compile_id,
2379                                             masm->code(),
2380                                             (int)(wrapper_VEPStart-wrapper_CodeStart),
2381                                             (int)(wrapper_FrameDone-wrapper_CodeStart),
2382                                             stack_slots / VMRegImpl::slots_per_word,
2383                                             (method_is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2384                                             in_ByteSize(lock_offset),
2385                                             oop_maps);
2386 
2387   if (is_critical_native) {
2388     nm->set_lazy_critical_native(true);
2389   }
2390 
2391   return nm;
2392 #else
2393   ShouldNotReachHere();
2394   return NULL;
2395 #endif // COMPILER2
2396 }
2397 
2398 static address gen_c2i_adapter(MacroAssembler  *masm,
2399                                int total_args_passed,
2400                                int comp_args_on_stack,
2401                                const BasicType *sig_bt,
2402                                const VMRegPair *regs,
2403                                Label &skip_fixup) {
2404   // Before we get into the guts of the C2I adapter, see if we should be here
2405   // at all. We've come from compiled code and are attempting to jump to the
2406   // interpreter, which means the caller made a static call to get here
2407   // (vcalls always get a compiled target if there is one). Check for a
2408   // compiled target. If there is one, we need to patch the caller's call.
2409 
2410   // These two defs MUST MATCH code in gen_i2c2i_adapter!
2411   const Register ientry = Z_R11;
2412   const Register code   = Z_R11;
2413 
2414   address c2i_entrypoint;
2415   Label   patch_callsite;
2416 
2417   // Regular (verified) c2i entry point.
2418   c2i_entrypoint = __ pc();
2419 
2420   // Call patching needed?
2421   __ load_and_test_long(Z_R0_scratch, method_(code));
2422   __ z_lg(ientry, method_(interpreter_entry));  // Preload interpreter entry (also if patching).
2423   __ z_brne(patch_callsite);                    // Patch required if code != NULL (compiled target exists).
2424 
2425   __ bind(skip_fixup);  // Return point from patch_callsite.
2426 
2427   // Since all args are passed on the stack, total_args_passed*wordSize is the
2428   // space we need. We need ABI scratch area but we use the caller's since
2429   // it has already been allocated.
2430 
2431   const int abi_scratch = frame::z_top_ijava_frame_abi_size;
2432   int       extraspace  = align_up(total_args_passed, 2)*wordSize + abi_scratch;
2433   Register  sender_SP   = Z_R10;
2434   Register  value       = Z_R12;
2435 
2436   // Remember the senderSP so we can pop the interpreter arguments off of the stack.
2437   // In addition, frame manager expects initial_caller_sp in Z_R10.
2438   __ z_lgr(sender_SP, Z_SP);
2439 
2440   // This should always fit in 14 bit immediate.
2441   __ resize_frame(-extraspace, Z_R0_scratch);
2442 
2443   // We use the caller's ABI scratch area (out_preserved_stack_slots) for the initial
2444   // args. This essentially moves the callers ABI scratch area from the top to the
2445   // bottom of the arg area.
2446 
2447   int st_off =  extraspace - wordSize;
2448 
2449   // Now write the args into the outgoing interpreter space.
2450   for (int i = 0; i < total_args_passed; i++) {
2451     VMReg r_1 = regs[i].first();
2452     VMReg r_2 = regs[i].second();
2453     if (!r_1->is_valid()) {
2454       assert(!r_2->is_valid(), "");
2455       continue;
2456     }
2457     if (r_1->is_stack()) {
2458       // The calling convention produces OptoRegs that ignore the preserve area (abi scratch).
2459       // We must account for it here.
2460       int ld_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
2461 
2462       if (!r_2->is_valid()) {
2463         __ z_mvc(Address(Z_SP, st_off), Address(sender_SP, ld_off), sizeof(void*));
2464       } else {
2465         // longs are given 2 64-bit slots in the interpreter,
2466         // but the data is passed in only 1 slot.
2467         if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
2468 #ifdef ASSERT
2469           __ clear_mem(Address(Z_SP, st_off), sizeof(void *));
2470 #endif
2471           st_off -= wordSize;
2472         }
2473         __ z_mvc(Address(Z_SP, st_off), Address(sender_SP, ld_off), sizeof(void*));
2474       }
2475     } else {
2476       if (r_1->is_Register()) {
2477         if (!r_2->is_valid()) {
2478           __ z_st(r_1->as_Register(), st_off, Z_SP);
2479         } else {
2480           // longs are given 2 64-bit slots in the interpreter, but the
2481           // data is passed in only 1 slot.
2482           if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
2483 #ifdef ASSERT
2484             __ clear_mem(Address(Z_SP, st_off), sizeof(void *));
2485 #endif
2486             st_off -= wordSize;
2487           }
2488           __ z_stg(r_1->as_Register(), st_off, Z_SP);
2489         }
2490       } else {
2491         assert(r_1->is_FloatRegister(), "");
2492         if (!r_2->is_valid()) {
2493           __ z_ste(r_1->as_FloatRegister(), st_off, Z_SP);
2494         } else {
2495           // In 64bit, doubles are given 2 64-bit slots in the interpreter, but the
2496           // data is passed in only 1 slot.
2497           // One of these should get known junk...
2498 #ifdef ASSERT
2499           __ z_lzdr(Z_F1);
2500           __ z_std(Z_F1, st_off, Z_SP);
2501 #endif
2502           st_off-=wordSize;
2503           __ z_std(r_1->as_FloatRegister(), st_off, Z_SP);
2504         }
2505       }
2506     }
2507     st_off -= wordSize;
2508   }
2509 
2510 
2511   // Jump to the interpreter just as if interpreter was doing it.
2512   __ add2reg(Z_esp, st_off, Z_SP);
2513 
2514   // Frame_manager expects initial_caller_sp (= SP without resize by c2i) in Z_R10.
2515   __ z_br(ientry);
2516 
2517 
2518   // Prevent illegal entry to out-of-line code.
2519   __ z_illtrap(0x22);
2520 
2521   // Generate out-of-line runtime call to patch caller,
2522   // then continue as interpreted.
2523 
2524   // IF you lose the race you go interpreted.
2525   // We don't see any possible endless c2i -> i2c -> c2i ...
2526   // transitions no matter how rare.
2527   __ bind(patch_callsite);
2528 
2529   RegisterSaver::save_live_registers(masm, RegisterSaver::arg_registers);
2530   __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite), Z_method, Z_R14);
2531   RegisterSaver::restore_live_registers(masm, RegisterSaver::arg_registers);
2532   __ z_bru(skip_fixup);
2533 
2534   // end of out-of-line code
2535 
2536   return c2i_entrypoint;
2537 }
2538 
2539 // On entry, the following registers are set
2540 //
2541 //    Z_thread  r8  - JavaThread*
2542 //    Z_method  r9  - callee's method (method to be invoked)
2543 //    Z_esp     r7  - operand (or expression) stack pointer of caller. one slot above last arg.
2544 //    Z_SP      r15 - SP prepared by call stub such that caller's outgoing args are near top
2545 //
2546 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
2547                                     int total_args_passed,
2548                                     int comp_args_on_stack,
2549                                     const BasicType *sig_bt,
2550                                     const VMRegPair *regs) {
2551   const Register value = Z_R12;
2552   const Register ld_ptr= Z_esp;
2553 
2554   int ld_offset = total_args_passed * wordSize;
2555 
2556   // Cut-out for having no stack args.
2557   if (comp_args_on_stack) {
2558     // Sig words on the stack are greater than VMRegImpl::stack0. Those in
2559     // registers are below. By subtracting stack0, we either get a negative
2560     // number (all values in registers) or the maximum stack slot accessed.
2561     // Convert VMRegImpl (4 byte) stack slots to words.
2562     int comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
2563     // Round up to miminum stack alignment, in wordSize
2564     comp_words_on_stack = align_up(comp_words_on_stack, 2);
2565 
2566     __ resize_frame(-comp_words_on_stack*wordSize, Z_R0_scratch);
2567   }
2568 
2569   // Now generate the shuffle code. Pick up all register args and move the
2570   // rest through register value=Z_R12.
2571   for (int i = 0; i < total_args_passed; i++) {
2572     if (sig_bt[i] == T_VOID) {
2573       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
2574       continue;
2575     }
2576 
2577     // Pick up 0, 1 or 2 words from ld_ptr.
2578     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
2579            "scrambled load targets?");
2580     VMReg r_1 = regs[i].first();
2581     VMReg r_2 = regs[i].second();
2582     if (!r_1->is_valid()) {
2583       assert(!r_2->is_valid(), "");
2584       continue;
2585     }
2586     if (r_1->is_FloatRegister()) {
2587       if (!r_2->is_valid()) {
2588         __ z_le(r_1->as_FloatRegister(), ld_offset, ld_ptr);
2589         ld_offset-=wordSize;
2590       } else {
2591         // Skip the unused interpreter slot.
2592         __ z_ld(r_1->as_FloatRegister(), ld_offset - wordSize, ld_ptr);
2593         ld_offset -= 2 * wordSize;
2594       }
2595     } else {
2596       if (r_1->is_stack()) {
2597         // Must do a memory to memory move.
2598         int st_off = (r_1->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
2599 
2600         if (!r_2->is_valid()) {
2601           __ z_mvc(Address(Z_SP, st_off), Address(ld_ptr, ld_offset), sizeof(void*));
2602         } else {
2603           // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
2604           // data is passed in only 1 slot.
2605           if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
2606             ld_offset -= wordSize;
2607           }
2608           __ z_mvc(Address(Z_SP, st_off), Address(ld_ptr, ld_offset), sizeof(void*));
2609         }
2610       } else {
2611         if (!r_2->is_valid()) {
2612           // Not sure we need to do this but it shouldn't hurt.
2613           if (sig_bt[i] == T_OBJECT || sig_bt[i] == T_ADDRESS || sig_bt[i] == T_ARRAY) {
2614             __ z_lg(r_1->as_Register(), ld_offset, ld_ptr);
2615           } else {
2616             __ z_l(r_1->as_Register(), ld_offset, ld_ptr);
2617           }
2618         } else {
2619           // In 64bit, longs are given 2 64-bit slots in the interpreter, but the
2620           // data is passed in only 1 slot.
2621           if (sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
2622             ld_offset -= wordSize;
2623           }
2624           __ z_lg(r_1->as_Register(), ld_offset, ld_ptr);
2625         }
2626       }
2627       ld_offset -= wordSize;
2628     }
2629   }
2630 
2631   // Jump to the compiled code just as if compiled code was doing it.
2632   // load target address from method oop:
2633   __ z_lg(Z_R1_scratch, Address(Z_method, Method::from_compiled_offset()));
2634 
2635   // Store method oop into thread->callee_target.
2636   // 6243940: We might end up in handle_wrong_method if
2637   // the callee is deoptimized as we race thru here. If that
2638   // happens we don't want to take a safepoint because the
2639   // caller frame will look interpreted and arguments are now
2640   // "compiled" so it is much better to make this transition
2641   // invisible to the stack walking code. Unfortunately, if
2642   // we try and find the callee by normal means a safepoint
2643   // is possible. So we stash the desired callee in the thread
2644   // and the vm will find it there should this case occur.
2645   __ z_stg(Z_method, thread_(callee_target));
2646 
2647   __ z_br(Z_R1_scratch);
2648 }
2649 
2650 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
2651                                                             int total_args_passed,
2652                                                             int comp_args_on_stack,
2653                                                             const BasicType *sig_bt,
2654                                                             const VMRegPair *regs,
2655                                                             AdapterFingerPrint* fingerprint) {
2656   __ align(CodeEntryAlignment);
2657   address i2c_entry = __ pc();
2658   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
2659 
2660   address c2i_unverified_entry;
2661 
2662   Label skip_fixup;
2663   {
2664     Label ic_miss;
2665     const int klass_offset           = oopDesc::klass_offset_in_bytes();
2666     const int holder_klass_offset    = CompiledICHolder::holder_klass_offset();
2667     const int holder_metadata_offset = CompiledICHolder::holder_metadata_offset();
2668 
2669     // Out-of-line call to ic_miss handler.
2670     __ call_ic_miss_handler(ic_miss, 0x11, 0, Z_R1_scratch);
2671 
2672     // Unverified Entry Point UEP
2673     __ align(CodeEntryAlignment);
2674     c2i_unverified_entry = __ pc();
2675 
2676     // Check the pointers.
2677     if (!ImplicitNullChecks || MacroAssembler::needs_explicit_null_check(klass_offset)) {
2678       __ z_ltgr(Z_ARG1, Z_ARG1);
2679       __ z_bre(ic_miss);
2680     }
2681     __ verify_oop(Z_ARG1);
2682 
2683     // Check ic: object class <-> cached class
2684     // Compress cached class for comparison. That's more efficient.
2685     if (UseCompressedClassPointers) {
2686       __ z_lg(Z_R11, holder_klass_offset, Z_method);             // Z_R11 is overwritten a few instructions down anyway.
2687       __ compare_klass_ptr(Z_R11, klass_offset, Z_ARG1, false); // Cached class can't be zero.
2688     } else {
2689       __ z_clc(klass_offset, sizeof(void *)-1, Z_ARG1, holder_klass_offset, Z_method);
2690     }
2691     __ z_brne(ic_miss);  // Cache miss: call runtime to handle this.
2692 
2693     // This def MUST MATCH code in gen_c2i_adapter!
2694     const Register code = Z_R11;
2695 
2696     __ z_lg(Z_method, holder_metadata_offset, Z_method);
2697     __ load_and_test_long(Z_R0, method_(code));
2698     __ z_brne(ic_miss);  // Cache miss: call runtime to handle this.
2699 
2700     // Fallthru to VEP. Duplicate LTG, but saved taken branch.
2701   }
2702 
2703   address c2i_entry;
2704   c2i_entry = gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
2705 
2706   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
2707 }
2708 
2709 // This function returns the adjust size (in number of words) to a c2i adapter
2710 // activation for use during deoptimization.
2711 //
2712 // Actually only compiled frames need to be adjusted, but it
2713 // doesn't harm to adjust entry and interpreter frames, too.
2714 //
2715 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals) {
2716   assert(callee_locals >= callee_parameters,
2717           "test and remove; got more parms than locals");
2718   // Handle the abi adjustment here instead of doing it in push_skeleton_frames.
2719   return (callee_locals - callee_parameters) * Interpreter::stackElementWords +
2720          frame::z_parent_ijava_frame_abi_size / BytesPerWord;
2721 }
2722 
2723 uint SharedRuntime::out_preserve_stack_slots() {
2724   return frame::z_jit_out_preserve_size/VMRegImpl::stack_slot_size;
2725 }
2726 
2727 //
2728 // Frame generation for deopt and uncommon trap blobs.
2729 //
2730 static void push_skeleton_frame(MacroAssembler* masm,
2731                           /* Unchanged */
2732                           Register frame_sizes_reg,
2733                           Register pcs_reg,
2734                           /* Invalidate */
2735                           Register frame_size_reg,
2736                           Register pc_reg) {
2737   BLOCK_COMMENT("  push_skeleton_frame {");
2738    __ z_lg(pc_reg, 0, pcs_reg);
2739    __ z_lg(frame_size_reg, 0, frame_sizes_reg);
2740    __ z_stg(pc_reg, _z_abi(return_pc), Z_SP);
2741    Register fp = pc_reg;
2742    __ push_frame(frame_size_reg, fp);
2743 #ifdef ASSERT
2744    // The magic is required for successful walking skeletal frames.
2745    __ load_const_optimized(frame_size_reg/*tmp*/, frame::z_istate_magic_number);
2746    __ z_stg(frame_size_reg, _z_ijava_state_neg(magic), fp);
2747    // Fill other slots that are supposedly not necessary with eye catchers.
2748    __ load_const_optimized(frame_size_reg/*use as tmp*/, 0xdeadbad1);
2749    __ z_stg(frame_size_reg, _z_ijava_state_neg(top_frame_sp), fp);
2750    // The sender_sp of the bottom frame is set before pushing it.
2751    // The sender_sp of non bottom frames is their caller's top_frame_sp, which
2752    // is unknown here. Luckily it is not needed before filling the frame in
2753    // layout_activation(), we assert this by setting an eye catcher (see
2754    // comments on sender_sp in frame_s390.hpp).
2755    __ z_stg(frame_size_reg, _z_ijava_state_neg(sender_sp), Z_SP);
2756 #endif // ASSERT
2757   BLOCK_COMMENT("  } push_skeleton_frame");
2758 }
2759 
2760 // Loop through the UnrollBlock info and create new frames.
2761 static void push_skeleton_frames(MacroAssembler* masm, bool deopt,
2762                             /* read */
2763                             Register unroll_block_reg,
2764                             /* invalidate */
2765                             Register frame_sizes_reg,
2766                             Register number_of_frames_reg,
2767                             Register pcs_reg,
2768                             Register tmp1,
2769                             Register tmp2) {
2770   BLOCK_COMMENT("push_skeleton_frames {");
2771   // _number_of_frames is of type int (deoptimization.hpp).
2772   __ z_lgf(number_of_frames_reg,
2773            Address(unroll_block_reg, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2774   __ z_lg(pcs_reg,
2775           Address(unroll_block_reg, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2776   __ z_lg(frame_sizes_reg,
2777           Address(unroll_block_reg, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2778 
2779   // stack: (caller_of_deoptee, ...).
2780 
2781   // If caller_of_deoptee is a compiled frame, then we extend it to make
2782   // room for the callee's locals and the frame::z_parent_ijava_frame_abi.
2783   // See also Deoptimization::last_frame_adjust() above.
2784   // Note: entry and interpreted frames are adjusted, too. But this doesn't harm.
2785 
2786   __ z_lgf(Z_R1_scratch,
2787            Address(unroll_block_reg, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2788   __ z_lgr(tmp1, Z_SP);  // Save the sender sp before extending the frame.
2789   __ resize_frame_sub(Z_R1_scratch, tmp2/*tmp*/);
2790   // The oldest skeletal frame requires a valid sender_sp to make it walkable
2791   // (it is required to find the original pc of caller_of_deoptee if it is marked
2792   // for deoptimization - see nmethod::orig_pc_addr()).
2793   __ z_stg(tmp1, _z_ijava_state_neg(sender_sp), Z_SP);
2794 
2795   // Now push the new interpreter frames.
2796   Label loop, loop_entry;
2797 
2798   // Make sure that there is at least one entry in the array.
2799   DEBUG_ONLY(__ z_ltgr(number_of_frames_reg, number_of_frames_reg));
2800   __ asm_assert_ne("array_size must be > 0", 0x205);
2801 
2802   __ z_bru(loop_entry);
2803 
2804   __ bind(loop);
2805 
2806   __ add2reg(frame_sizes_reg, wordSize);
2807   __ add2reg(pcs_reg, wordSize);
2808 
2809   __ bind(loop_entry);
2810 
2811   // Allocate a new frame, fill in the pc.
2812   push_skeleton_frame(masm, frame_sizes_reg, pcs_reg, tmp1, tmp2);
2813 
2814   __ z_aghi(number_of_frames_reg, -1);  // Emit AGHI, because it sets the condition code
2815   __ z_brne(loop);
2816 
2817   // Set the top frame's return pc.
2818   __ add2reg(pcs_reg, wordSize);
2819   __ z_lg(Z_R0_scratch, 0, pcs_reg);
2820   __ z_stg(Z_R0_scratch, _z_abi(return_pc), Z_SP);
2821   BLOCK_COMMENT("} push_skeleton_frames");
2822 }
2823 
2824 //------------------------------generate_deopt_blob----------------------------
2825 void SharedRuntime::generate_deopt_blob() {
2826   // Allocate space for the code.
2827   ResourceMark rm;
2828   // Setup code generation tools.
2829   CodeBuffer buffer("deopt_blob", 2048, 1024);
2830   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
2831   Label exec_mode_initialized;
2832   OopMap* map = NULL;
2833   OopMapSet *oop_maps = new OopMapSet();
2834 
2835   unsigned int start_off = __ offset();
2836   Label cont;
2837 
2838   // --------------------------------------------------------------------------
2839   // Normal entry (non-exception case)
2840   //
2841   // We have been called from the deopt handler of the deoptee.
2842   // Z_R14 points behind the call in the deopt handler. We adjust
2843   // it such that it points to the start of the deopt handler.
2844   // The return_pc has been stored in the frame of the deoptee and
2845   // will replace the address of the deopt_handler in the call
2846   // to Deoptimization::fetch_unroll_info below.
2847   // The (int) cast is necessary, because -((unsigned int)14)
2848   // is an unsigned int.
2849   __ add2reg(Z_R14, -(int)HandlerImpl::size_deopt_handler());
2850 
2851   const Register   exec_mode_reg = Z_tmp_1;
2852 
2853   // stack: (deoptee, caller of deoptee, ...)
2854 
2855   // pushes an "unpack" frame
2856   // R14 contains the return address pointing into the deoptimized
2857   // nmethod that was valid just before the nmethod was deoptimized.
2858   // save R14 into the deoptee frame.  the `fetch_unroll_info'
2859   // procedure called below will read it from there.
2860   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers);
2861 
2862   // note the entry point.
2863   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_deopt);
2864   __ z_bru(exec_mode_initialized);
2865 
2866 #ifndef COMPILER1
2867   int reexecute_offset = 1; // odd offset will produce odd pc, which triggers an hardware trap
2868 #else
2869   // --------------------------------------------------------------------------
2870   // Reexecute entry
2871   // - Z_R14 = Deopt Handler in nmethod
2872 
2873   int reexecute_offset = __ offset() - start_off;
2874 
2875   // No need to update map as each call to save_live_registers will produce identical oopmap
2876   (void) RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers);
2877 
2878   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_reexecute);
2879   __ z_bru(exec_mode_initialized);
2880 #endif
2881 
2882 
2883   // --------------------------------------------------------------------------
2884   // Exception entry. We reached here via a branch. Registers on entry:
2885   // - Z_EXC_OOP (Z_ARG1) = exception oop
2886   // - Z_EXC_PC  (Z_ARG2) = the exception pc.
2887 
2888   int exception_offset = __ offset() - start_off;
2889 
2890   // all registers are dead at this entry point, except for Z_EXC_OOP, and
2891   // Z_EXC_PC which contain the exception oop and exception pc
2892   // respectively.  Set them in TLS and fall thru to the
2893   // unpack_with_exception_in_tls entry point.
2894 
2895   // Store exception oop and pc in thread (location known to GC).
2896   // Need this since the call to "fetch_unroll_info()" may safepoint.
2897   __ z_stg(Z_EXC_OOP, Address(Z_thread, JavaThread::exception_oop_offset()));
2898   __ z_stg(Z_EXC_PC,  Address(Z_thread, JavaThread::exception_pc_offset()));
2899 
2900   // fall through
2901 
2902   int exception_in_tls_offset = __ offset() - start_off;
2903 
2904   // new implementation because exception oop is now passed in JavaThread
2905 
2906   // Prolog for exception case
2907   // All registers must be preserved because they might be used by LinearScan
2908   // Exceptiop oop and throwing PC are passed in JavaThread
2909 
2910   // load throwing pc from JavaThread and us it as the return address of the current frame.
2911   __ z_lg(Z_R1_scratch, Address(Z_thread, JavaThread::exception_pc_offset()));
2912 
2913   // Save everything in sight.
2914   (void) RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers, Z_R1_scratch);
2915 
2916   // Now it is safe to overwrite any register
2917 
2918   // Clear the exception pc field in JavaThread
2919   __ clear_mem(Address(Z_thread, JavaThread::exception_pc_offset()), 8);
2920 
2921   // Deopt during an exception.  Save exec mode for unpack_frames.
2922   __ load_const_optimized(exec_mode_reg, Deoptimization::Unpack_exception);
2923 
2924 
2925 #ifdef ASSERT
2926   // verify that there is really an exception oop in JavaThread
2927   __ z_lg(Z_ARG1, Address(Z_thread, JavaThread::exception_oop_offset()));
2928   __ verify_oop(Z_ARG1);
2929 
2930   // verify that there is no pending exception
2931   __ asm_assert_mem8_is_zero(in_bytes(Thread::pending_exception_offset()), Z_thread,
2932                              "must not have pending exception here", __LINE__);
2933 #endif
2934 
2935   // --------------------------------------------------------------------------
2936   // At this point, the live registers are saved and
2937   // the exec_mode_reg has been set up correctly.
2938   __ bind(exec_mode_initialized);
2939 
2940   // stack: ("unpack" frame, deoptee, caller_of_deoptee, ...).
2941 
2942   {
2943   const Register unroll_block_reg  = Z_tmp_2;
2944 
2945   // we need to set `last_Java_frame' because `fetch_unroll_info' will
2946   // call `last_Java_frame()'.  however we can't block and no gc will
2947   // occur so we don't need an oopmap. the value of the pc in the
2948   // frame is not particularly important.  it just needs to identify the blob.
2949 
2950   // Don't set last_Java_pc anymore here (is implicitly NULL then).
2951   // the correct PC is retrieved in pd_last_frame() in that case.
2952   __ set_last_Java_frame(/*sp*/Z_SP, noreg);
2953   // With EscapeAnalysis turned on, this call may safepoint
2954   // despite it's marked as "leaf call"!
2955   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info), Z_thread, exec_mode_reg);
2956   // Set an oopmap for the call site this describes all our saved volatile registers
2957   int offs = __ offset();
2958   oop_maps->add_gc_map(offs, map);
2959 
2960   __ reset_last_Java_frame();
2961   // save the return value.
2962   __ z_lgr(unroll_block_reg, Z_RET);
2963   // restore the return registers that have been saved
2964   // (among other registers) by save_live_registers(...).
2965   RegisterSaver::restore_result_registers(masm);
2966 
2967   // reload the exec mode from the UnrollBlock (it might have changed)
2968   __ z_llgf(exec_mode_reg, Address(unroll_block_reg, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
2969 
2970   // In excp_deopt_mode, restore and clear exception oop which we
2971   // stored in the thread during exception entry above. The exception
2972   // oop will be the return value of this stub.
2973   NearLabel skip_restore_excp;
2974   __ compare64_and_branch(exec_mode_reg, Deoptimization::Unpack_exception, Assembler::bcondNotEqual, skip_restore_excp);
2975   __ z_lg(Z_RET, thread_(exception_oop));
2976   __ clear_mem(thread_(exception_oop), 8);
2977   __ bind(skip_restore_excp);
2978 
2979   // remove the "unpack" frame
2980   __ pop_frame();
2981 
2982   // stack: (deoptee, caller of deoptee, ...).
2983 
2984   // pop the deoptee's frame
2985   __ pop_frame();
2986 
2987   // stack: (caller_of_deoptee, ...).
2988 
2989   // loop through the `UnrollBlock' info and create interpreter frames.
2990   push_skeleton_frames(masm, true/*deopt*/,
2991                   unroll_block_reg,
2992                   Z_tmp_3,
2993                   Z_tmp_4,
2994                   Z_ARG5,
2995                   Z_ARG4,
2996                   Z_ARG3);
2997 
2998   // stack: (skeletal interpreter frame, ..., optional skeletal
2999   // interpreter frame, caller of deoptee, ...).
3000   }
3001 
3002   // push an "unpack" frame taking care of float / int return values.
3003   __ push_frame(RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers));
3004 
3005   // stack: (unpack frame, skeletal interpreter frame, ..., optional
3006   // skeletal interpreter frame, caller of deoptee, ...).
3007 
3008   // spill live volatile registers since we'll do a call.
3009   __ z_stg(Z_RET, offset_of(frame::z_abi_160_spill, spill[0]), Z_SP);
3010   __ z_std(Z_FRET, offset_of(frame::z_abi_160_spill, spill[1]), Z_SP);
3011 
3012   // let the unpacker layout information in the skeletal frames just allocated.
3013   __ get_PC(Z_RET);
3014   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_RET);
3015   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames),
3016                   Z_thread/*thread*/, exec_mode_reg/*exec_mode*/);
3017 
3018   __ reset_last_Java_frame();
3019 
3020   // restore the volatiles saved above.
3021   __ z_lg(Z_RET, offset_of(frame::z_abi_160_spill, spill[0]), Z_SP);
3022   __ z_ld(Z_FRET, offset_of(frame::z_abi_160_spill, spill[1]), Z_SP);
3023 
3024   // pop the "unpack" frame.
3025   __ pop_frame();
3026   __ restore_return_pc();
3027 
3028   // stack: (top interpreter frame, ..., optional interpreter frame,
3029   // caller of deoptee, ...).
3030 
3031   __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // restore frame pointer
3032   __ restore_bcp();
3033   __ restore_locals();
3034   __ restore_esp();
3035 
3036   // return to the interpreter entry point.
3037   __ z_br(Z_R14);
3038 
3039   // Make sure all code is generated
3040   masm->flush();
3041 
3042   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers)/wordSize);
3043   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
3044 }
3045 
3046 
3047 #ifdef COMPILER2
3048 //------------------------------generate_uncommon_trap_blob--------------------
3049 void SharedRuntime::generate_uncommon_trap_blob() {
3050   // Allocate space for the code
3051   ResourceMark rm;
3052   // Setup code generation tools
3053   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
3054   InterpreterMacroAssembler* masm = new InterpreterMacroAssembler(&buffer);
3055 
3056   Register unroll_block_reg = Z_tmp_1;
3057   Register klass_index_reg  = Z_ARG2;
3058   Register unc_trap_reg     = Z_ARG2;
3059 
3060   // stack: (deoptee, caller_of_deoptee, ...).
3061 
3062   // push a dummy "unpack" frame and call
3063   // `Deoptimization::uncommon_trap' to pack the compiled frame into a
3064   // vframe array and return the `UnrollBlock' information.
3065 
3066   // save R14 to compiled frame.
3067   __ save_return_pc();
3068   // push the "unpack_frame".
3069   __ push_frame_abi160(0);
3070 
3071   // stack: (unpack frame, deoptee, caller_of_deoptee, ...).
3072 
3073   // set the "unpack" frame as last_Java_frame.
3074   // `Deoptimization::uncommon_trap' expects it and considers its
3075   // sender frame as the deoptee frame.
3076   __ get_PC(Z_R1_scratch);
3077   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_R1_scratch);
3078 
3079   __ z_lgr(klass_index_reg, Z_ARG1);  // passed implicitly as ARG2
3080   __ z_lghi(Z_ARG3, Deoptimization::Unpack_uncommon_trap);  // passed implicitly as ARG3
3081   BLOCK_COMMENT("call Deoptimization::uncommon_trap()");
3082   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap), Z_thread);
3083 
3084   __ reset_last_Java_frame();
3085 
3086   // pop the "unpack" frame
3087   __ pop_frame();
3088 
3089   // stack: (deoptee, caller_of_deoptee, ...).
3090 
3091   // save the return value.
3092   __ z_lgr(unroll_block_reg, Z_RET);
3093 
3094   // pop the deoptee frame.
3095   __ pop_frame();
3096 
3097   // stack: (caller_of_deoptee, ...).
3098 
3099 #ifdef ASSERT
3100   assert(Immediate::is_uimm8(Deoptimization::Unpack_LIMIT), "Code not fit for larger immediates");
3101   assert(Immediate::is_uimm8(Deoptimization::Unpack_uncommon_trap), "Code not fit for larger immediates");
3102   const int unpack_kind_byte_offset = Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()
3103 #ifndef VM_LITTLE_ENDIAN
3104   + 3
3105 #endif
3106   ;
3107   if (Displacement::is_shortDisp(unpack_kind_byte_offset)) {
3108     __ z_cli(unpack_kind_byte_offset, unroll_block_reg, Deoptimization::Unpack_uncommon_trap);
3109   } else {
3110     __ z_cliy(unpack_kind_byte_offset, unroll_block_reg, Deoptimization::Unpack_uncommon_trap);
3111   }
3112   __ asm_assert_eq("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap", 0);
3113 #endif
3114 
3115   __ zap_from_to(Z_SP, Z_SP, Z_R0_scratch, Z_R1, 500, -1);
3116 
3117   // allocate new interpreter frame(s) and possibly resize the caller's frame
3118   // (no more adapters !)
3119   push_skeleton_frames(masm, false/*deopt*/,
3120                   unroll_block_reg,
3121                   Z_tmp_2,
3122                   Z_tmp_3,
3123                   Z_tmp_4,
3124                   Z_ARG5,
3125                   Z_ARG4);
3126 
3127   // stack: (skeletal interpreter frame, ..., optional skeletal
3128   // interpreter frame, (resized) caller of deoptee, ...).
3129 
3130   // push a dummy "unpack" frame taking care of float return values.
3131   // call `Deoptimization::unpack_frames' to layout information in the
3132   // interpreter frames just created
3133 
3134   // push the "unpack" frame
3135    const unsigned int framesize_in_bytes = __ push_frame_abi160(0);
3136 
3137   // stack: (unpack frame, skeletal interpreter frame, ..., optional
3138   // skeletal interpreter frame, (resized) caller of deoptee, ...).
3139 
3140   // set the "unpack" frame as last_Java_frame
3141   __ get_PC(Z_R1_scratch);
3142   __ set_last_Java_frame(/*sp*/Z_SP, /*pc*/Z_R1_scratch);
3143 
3144   // indicate it is the uncommon trap case
3145   BLOCK_COMMENT("call Deoptimization::Unpack_uncommon_trap()");
3146   __ load_const_optimized(unc_trap_reg, Deoptimization::Unpack_uncommon_trap);
3147   // let the unpacker layout information in the skeletal frames just allocated.
3148   __ call_VM_leaf(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames), Z_thread);
3149 
3150   __ reset_last_Java_frame();
3151   // pop the "unpack" frame
3152   __ pop_frame();
3153   // restore LR from top interpreter frame
3154   __ restore_return_pc();
3155 
3156   // stack: (top interpreter frame, ..., optional interpreter frame,
3157   // (resized) caller of deoptee, ...).
3158 
3159   __ z_lg(Z_fp, _z_abi(callers_sp), Z_SP); // restore frame pointer
3160   __ restore_bcp();
3161   __ restore_locals();
3162   __ restore_esp();
3163 
3164   // return to the interpreter entry point
3165   __ z_br(Z_R14);
3166 
3167   masm->flush();
3168   _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, NULL, framesize_in_bytes/wordSize);
3169 }
3170 #endif // COMPILER2
3171 
3172 
3173 //------------------------------generate_handler_blob------
3174 //
3175 // Generate a special Compile2Runtime blob that saves all registers,
3176 // and setup oopmap.
3177 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3178   assert(StubRoutines::forward_exception_entry() != NULL,
3179          "must be generated before");
3180 
3181   ResourceMark rm;
3182   OopMapSet *oop_maps = new OopMapSet();
3183   OopMap* map;
3184 
3185   // Allocate space for the code. Setup code generation tools.
3186   CodeBuffer buffer("handler_blob", 2048, 1024);
3187   MacroAssembler* masm = new MacroAssembler(&buffer);
3188 
3189   unsigned int start_off = __ offset();
3190   address call_pc = NULL;
3191   int frame_size_in_bytes;
3192 
3193   bool cause_return = (poll_type == POLL_AT_RETURN);
3194   // Make room for return address (or push it again)
3195   if (!cause_return) {
3196     __ z_lg(Z_R14, Address(Z_thread, JavaThread::saved_exception_pc_offset()));
3197   }
3198 
3199   // Save registers, fpu state, and flags
3200   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers);
3201 
3202   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
3203     // Keep a copy of the return pc to detect if it gets modified.
3204     __ z_lgr(Z_R6, Z_R14);
3205   }
3206 
3207   // The following is basically a call_VM. However, we need the precise
3208   // address of the call in order to generate an oopmap. Hence, we do all the
3209   // work outselves.
3210   __ set_last_Java_frame(Z_SP, noreg);
3211 
3212   // call into the runtime to handle the safepoint poll
3213   __ call_VM_leaf(call_ptr, Z_thread);
3214 
3215 
3216   // Set an oopmap for the call site. This oopmap will map all
3217   // oop-registers and debug-info registers as callee-saved. This
3218   // will allow deoptimization at this safepoint to find all possible
3219   // debug-info recordings, as well as let GC find all oops.
3220 
3221   oop_maps->add_gc_map((int)(__ offset()-start_off), map);
3222 
3223   Label noException;
3224 
3225   __ reset_last_Java_frame();
3226 
3227   __ load_and_test_long(Z_R1, thread_(pending_exception));
3228   __ z_bre(noException);
3229 
3230   // Pending exception case, used (sporadically) by
3231   // api/java_lang/Thread.State/index#ThreadState et al.
3232   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3233 
3234   // Jump to forward_exception_entry, with the issuing PC in Z_R14
3235   // so it looks like the original nmethod called forward_exception_entry.
3236   __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
3237   __ z_br(Z_R1_scratch);
3238 
3239   // No exception case
3240   __ bind(noException);
3241 
3242   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
3243     Label no_adjust;
3244      // If our stashed return pc was modified by the runtime we avoid touching it
3245     const int offset_of_return_pc = _z_abi16(return_pc) + RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers);
3246     __ z_cg(Z_R6, offset_of_return_pc, Z_SP);
3247     __ z_brne(no_adjust);
3248 
3249     // Adjust return pc forward to step over the safepoint poll instruction
3250     __ instr_size(Z_R1_scratch, Z_R6);
3251     __ z_agr(Z_R6, Z_R1_scratch);
3252     __ z_stg(Z_R6, offset_of_return_pc, Z_SP);
3253 
3254     __ bind(no_adjust);
3255   }
3256 
3257   // Normal exit, restore registers and exit.
3258   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3259 
3260   __ z_br(Z_R14);
3261 
3262   // Make sure all code is generated
3263   masm->flush();
3264 
3265   // Fill-out other meta info
3266   return SafepointBlob::create(&buffer, oop_maps, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers)/wordSize);
3267 }
3268 
3269 
3270 //
3271 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3272 //
3273 // Generate a stub that calls into vm to find out the proper destination
3274 // of a Java call. All the argument registers are live at this point
3275 // but since this is generic code we don't know what they are and the caller
3276 // must do any gc of the args.
3277 //
3278 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3279   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3280 
3281   // allocate space for the code
3282   ResourceMark rm;
3283 
3284   CodeBuffer buffer(name, 1000, 512);
3285   MacroAssembler* masm                = new MacroAssembler(&buffer);
3286 
3287   OopMapSet *oop_maps = new OopMapSet();
3288   OopMap* map = NULL;
3289 
3290   unsigned int start_off = __ offset();
3291 
3292   map = RegisterSaver::save_live_registers(masm, RegisterSaver::all_registers);
3293 
3294   // We must save a PC from within the stub as return PC
3295   // C code doesn't store the LR where we expect the PC,
3296   // so we would run into trouble upon stack walking.
3297   __ get_PC(Z_R1_scratch);
3298 
3299   unsigned int frame_complete = __ offset();
3300 
3301   __ set_last_Java_frame(/*sp*/Z_SP, Z_R1_scratch);
3302 
3303   __ call_VM_leaf(destination, Z_thread, Z_method);
3304 
3305 
3306   // Set an oopmap for the call site.
3307   // We need this not only for callee-saved registers, but also for volatile
3308   // registers that the compiler might be keeping live across a safepoint.
3309 
3310   oop_maps->add_gc_map((int)(frame_complete-start_off), map);
3311 
3312   // clear last_Java_sp
3313   __ reset_last_Java_frame();
3314 
3315   // check for pending exceptions
3316   Label pending;
3317   __ load_and_test_long(Z_R0, Address(Z_thread, Thread::pending_exception_offset()));
3318   __ z_brne(pending);
3319 
3320   __ z_lgr(Z_R1_scratch, Z_R2); // r1 is neither saved nor restored, r2 contains the continuation.
3321   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3322 
3323   // get the returned method
3324   __ get_vm_result_2(Z_method);
3325 
3326   // We are back the the original state on entry and ready to go.
3327   __ z_br(Z_R1_scratch);
3328 
3329   // Pending exception after the safepoint
3330 
3331   __ bind(pending);
3332 
3333   RegisterSaver::restore_live_registers(masm, RegisterSaver::all_registers);
3334 
3335   // exception pending => remove activation and forward to exception handler
3336 
3337   __ z_lgr(Z_R2, Z_R0); // pending_exception
3338   __ clear_mem(Address(Z_thread, JavaThread::vm_result_offset()), sizeof(jlong));
3339   __ load_const_optimized(Z_R1_scratch, StubRoutines::forward_exception_entry());
3340   __ z_br(Z_R1_scratch);
3341 
3342   // -------------
3343   // make sure all code is generated
3344   masm->flush();
3345 
3346   // return the blob
3347   // frame_size_words or bytes??
3348   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, RegisterSaver::live_reg_frame_size(RegisterSaver::all_registers)/wordSize,
3349                                        oop_maps, true);
3350 
3351 }
3352 
3353 //------------------------------Montgomery multiplication------------------------
3354 //
3355 
3356 // Subtract 0:b from carry:a. Return carry.
3357 static unsigned long
3358 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3359   unsigned long i, c = 8 * (unsigned long)(len - 1);
3360   __asm__ __volatile__ (
3361     "SLGR   %[i], %[i]         \n" // initialize to 0 and pre-set carry
3362     "LGHI   0, 8               \n" // index increment (for BRXLG)
3363     "LGR    1, %[c]            \n" // index limit (for BRXLG)
3364     "0:                        \n"
3365     "LG     %[c], 0(%[i],%[a]) \n"
3366     "SLBG   %[c], 0(%[i],%[b]) \n" // subtract with borrow
3367     "STG    %[c], 0(%[i],%[a]) \n"
3368     "BRXLG  %[i], 0, 0b        \n" // while ((i+=8)<limit);
3369     "SLBGR  %[c], %[c]         \n" // save carry - 1
3370     : [i]"=&a"(i), [c]"+r"(c)
3371     : [a]"a"(a), [b]"a"(b)
3372     : "cc", "memory", "r0", "r1"
3373  );
3374   return carry + c;
3375 }
3376 
3377 // Multiply (unsigned) Long A by Long B, accumulating the double-
3378 // length result into the accumulator formed of T0, T1, and T2.
3379 inline void MACC(unsigned long A[], long A_ind,
3380                  unsigned long B[], long B_ind,
3381                  unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3382   long A_si = 8 * A_ind,
3383        B_si = 8 * B_ind;
3384   __asm__ __volatile__ (
3385     "LG     1, 0(%[A_si],%[A]) \n"
3386     "MLG    0, 0(%[B_si],%[B]) \n" // r0r1 = A * B
3387     "ALGR   %[T0], 1           \n"
3388     "LGHI   1, 0               \n" // r1 = 0
3389     "ALCGR  %[T1], 0           \n"
3390     "ALCGR  %[T2], 1           \n"
3391     : [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3392     : [A]"r"(A), [A_si]"r"(A_si), [B]"r"(B), [B_si]"r"(B_si)
3393     : "cc", "r0", "r1"
3394  );
3395 }
3396 
3397 // As above, but add twice the double-length result into the
3398 // accumulator.
3399 inline void MACC2(unsigned long A[], long A_ind,
3400                   unsigned long B[], long B_ind,
3401                   unsigned long &T0, unsigned long &T1, unsigned long &T2) {
3402   const unsigned long zero = 0;
3403   long A_si = 8 * A_ind,
3404        B_si = 8 * B_ind;
3405   __asm__ __volatile__ (
3406     "LG     1, 0(%[A_si],%[A]) \n"
3407     "MLG    0, 0(%[B_si],%[B]) \n" // r0r1 = A * B
3408     "ALGR   %[T0], 1           \n"
3409     "ALCGR  %[T1], 0           \n"
3410     "ALCGR  %[T2], %[zero]     \n"
3411     "ALGR   %[T0], 1           \n"
3412     "ALCGR  %[T1], 0           \n"
3413     "ALCGR  %[T2], %[zero]     \n"
3414     : [T0]"+r"(T0), [T1]"+r"(T1), [T2]"+r"(T2)
3415     : [A]"r"(A), [A_si]"r"(A_si), [B]"r"(B), [B_si]"r"(B_si), [zero]"r"(zero)
3416     : "cc", "r0", "r1"
3417  );
3418 }
3419 
3420 // Fast Montgomery multiplication. The derivation of the algorithm is
3421 // in "A Cryptographic Library for the Motorola DSP56000,
3422 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237".
3423 static void
3424 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3425                     unsigned long m[], unsigned long inv, int len) {
3426   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3427   int i;
3428 
3429   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3430 
3431   for (i = 0; i < len; i++) {
3432     int j;
3433     for (j = 0; j < i; j++) {
3434       MACC(a, j, b, i-j, t0, t1, t2);
3435       MACC(m, j, n, i-j, t0, t1, t2);
3436     }
3437     MACC(a, i, b, 0, t0, t1, t2);
3438     m[i] = t0 * inv;
3439     MACC(m, i, n, 0, t0, t1, t2);
3440 
3441     assert(t0 == 0, "broken Montgomery multiply");
3442 
3443     t0 = t1; t1 = t2; t2 = 0;
3444   }
3445 
3446   for (i = len; i < 2 * len; i++) {
3447     int j;
3448     for (j = i - len + 1; j < len; j++) {
3449       MACC(a, j, b, i-j, t0, t1, t2);
3450       MACC(m, j, n, i-j, t0, t1, t2);
3451     }
3452     m[i-len] = t0;
3453     t0 = t1; t1 = t2; t2 = 0;
3454   }
3455 
3456   while (t0) {
3457     t0 = sub(m, n, t0, len);
3458   }
3459 }
3460 
3461 // Fast Montgomery squaring. This uses asymptotically 25% fewer
3462 // multiplies so it should be up to 25% faster than Montgomery
3463 // multiplication. However, its loop control is more complex and it
3464 // may actually run slower on some machines.
3465 static void
3466 montgomery_square(unsigned long a[], unsigned long n[],
3467                   unsigned long m[], unsigned long inv, int len) {
3468   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3469   int i;
3470 
3471   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3472 
3473   for (i = 0; i < len; i++) {
3474     int j;
3475     int end = (i+1)/2;
3476     for (j = 0; j < end; j++) {
3477       MACC2(a, j, a, i-j, t0, t1, t2);
3478       MACC(m, j, n, i-j, t0, t1, t2);
3479     }
3480     if ((i & 1) == 0) {
3481       MACC(a, j, a, j, t0, t1, t2);
3482     }
3483     for (; j < i; j++) {
3484       MACC(m, j, n, i-j, t0, t1, t2);
3485     }
3486     m[i] = t0 * inv;
3487     MACC(m, i, n, 0, t0, t1, t2);
3488 
3489     assert(t0 == 0, "broken Montgomery square");
3490 
3491     t0 = t1; t1 = t2; t2 = 0;
3492   }
3493 
3494   for (i = len; i < 2*len; i++) {
3495     int start = i-len+1;
3496     int end = start + (len - start)/2;
3497     int j;
3498     for (j = start; j < end; j++) {
3499       MACC2(a, j, a, i-j, t0, t1, t2);
3500       MACC(m, j, n, i-j, t0, t1, t2);
3501     }
3502     if ((i & 1) == 0) {
3503       MACC(a, j, a, j, t0, t1, t2);
3504     }
3505     for (; j < len; j++) {
3506       MACC(m, j, n, i-j, t0, t1, t2);
3507     }
3508     m[i-len] = t0;
3509     t0 = t1; t1 = t2; t2 = 0;
3510   }
3511 
3512   while (t0) {
3513     t0 = sub(m, n, t0, len);
3514   }
3515 }
3516 
3517 // The threshold at which squaring is advantageous was determined
3518 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3519 // Value seems to be ok for other platforms, too.
3520 #define MONTGOMERY_SQUARING_THRESHOLD 64
3521 
3522 // Copy len longwords from s to d, word-swapping as we go. The
3523 // destination array is reversed.
3524 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3525   d += len;
3526   while(len-- > 0) {
3527     d--;
3528     unsigned long s_val = *s;
3529     // Swap words in a longword on little endian machines.
3530 #ifdef VM_LITTLE_ENDIAN
3531      Unimplemented();
3532 #endif
3533     *d = s_val;
3534     s++;
3535   }
3536 }
3537 
3538 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3539                                         jint len, jlong inv,
3540                                         jint *m_ints) {
3541   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3542   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3543   int longwords = len/2;
3544 
3545   // Make very sure we don't use so much space that the stack might
3546   // overflow. 512 jints corresponds to an 16384-bit integer and
3547   // will use here a total of 8k bytes of stack space.
3548   int total_allocation = longwords * sizeof (unsigned long) * 4;
3549   guarantee(total_allocation <= 8192, "must be");
3550   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3551 
3552   // Local scratch arrays
3553   unsigned long
3554     *a = scratch + 0 * longwords,
3555     *b = scratch + 1 * longwords,
3556     *n = scratch + 2 * longwords,
3557     *m = scratch + 3 * longwords;
3558 
3559   reverse_words((unsigned long *)a_ints, a, longwords);
3560   reverse_words((unsigned long *)b_ints, b, longwords);
3561   reverse_words((unsigned long *)n_ints, n, longwords);
3562 
3563   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3564 
3565   reverse_words(m, (unsigned long *)m_ints, longwords);
3566 }
3567 
3568 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3569                                       jint len, jlong inv,
3570                                       jint *m_ints) {
3571   len = len & 0x7fffFFFF; // C2 does not respect int to long conversion for stub calls.
3572   assert(len % 2 == 0, "array length in montgomery_square must be even");
3573   int longwords = len/2;
3574 
3575   // Make very sure we don't use so much space that the stack might
3576   // overflow. 512 jints corresponds to an 16384-bit integer and
3577   // will use here a total of 6k bytes of stack space.
3578   int total_allocation = longwords * sizeof (unsigned long) * 3;
3579   guarantee(total_allocation <= 8192, "must be");
3580   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3581 
3582   // Local scratch arrays
3583   unsigned long
3584     *a = scratch + 0 * longwords,
3585     *n = scratch + 1 * longwords,
3586     *m = scratch + 2 * longwords;
3587 
3588   reverse_words((unsigned long *)a_ints, a, longwords);
3589   reverse_words((unsigned long *)n_ints, n, longwords);
3590 
3591   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3592     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3593   } else {
3594     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3595   }
3596 
3597   reverse_words(m, (unsigned long *)m_ints, longwords);
3598 }
3599 
3600 extern "C"
3601 int SpinPause() {
3602   return 0;
3603 }
--- EOF ---