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