1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #ifndef _WINDOWS
  27 #include "alloca.h"
  28 #endif
  29 #include "asm/macroAssembler.hpp"
  30 #include "asm/macroAssembler.inline.hpp"
  31 #include "code/debugInfoRec.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/nativeInst.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "gc/shared/gcLocker.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "logging/log.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compiledICHolder.hpp"
  40 #include "runtime/safepointMechanism.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/vframeArray.hpp"
  43 #include "utilities/align.hpp"
  44 #include "utilities/formatBuffer.hpp"
  45 #include "vm_version_x86.hpp"
  46 #include "vmreg_x86.inline.hpp"
  47 #ifdef COMPILER1
  48 #include "c1/c1_Runtime1.hpp"
  49 #endif
  50 #ifdef COMPILER2
  51 #include "opto/runtime.hpp"
  52 #endif
  53 #if INCLUDE_JVMCI
  54 #include "jvmci/jvmciJavaClasses.hpp"
  55 #endif
  56 
  57 #define __ masm->
  58 
  59 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  60 
  61 class SimpleRuntimeFrame {
  62 
  63   public:
  64 
  65   // Most of the runtime stubs have this simple frame layout.
  66   // This class exists to make the layout shared in one place.
  67   // Offsets are for compiler stack slots, which are jints.
  68   enum layout {
  69     // The frame sender code expects that rbp will be in the "natural" place and
  70     // will override any oopMap setting for it. We must therefore force the layout
  71     // so that it agrees with the frame sender code.
  72     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
  73     rbp_off2,
  74     return_off, return_off2,
  75     framesize
  76   };
  77 };
  78 
  79 class RegisterSaver {
  80   // Capture info about frame layout.  Layout offsets are in jint
  81   // units because compiler frame slots are jints.
  82 #define XSAVE_AREA_BEGIN 160
  83 #define XSAVE_AREA_YMM_BEGIN 576
  84 #define XSAVE_AREA_ZMM_BEGIN 1152
  85 #define XSAVE_AREA_UPPERBANK 1664
  86 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  87 #define DEF_YMM_OFFS(regnum) ymm ## regnum ## _off = ymm_off + (regnum)*16/BytesPerInt, ymm ## regnum ## H_off
  88 #define DEF_ZMM_OFFS(regnum) zmm ## regnum ## _off = zmm_off + (regnum-16)*64/BytesPerInt, zmm ## regnum ## H_off
  89   enum layout {
  90     fpu_state_off = frame::arg_reg_save_area_bytes/BytesPerInt, // fxsave save area
  91     xmm_off       = fpu_state_off + XSAVE_AREA_BEGIN/BytesPerInt,            // offset in fxsave save area
  92     DEF_XMM_OFFS(0),
  93     DEF_XMM_OFFS(1),
  94     // 2..15 are implied in range usage
  95     ymm_off = xmm_off + (XSAVE_AREA_YMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
  96     DEF_YMM_OFFS(0),
  97     DEF_YMM_OFFS(1),
  98     // 2..15 are implied in range usage
  99     zmm_high = xmm_off + (XSAVE_AREA_ZMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
 100     zmm_off = xmm_off + (XSAVE_AREA_UPPERBANK - XSAVE_AREA_BEGIN)/BytesPerInt,
 101     DEF_ZMM_OFFS(16),
 102     DEF_ZMM_OFFS(17),
 103     // 18..31 are implied in range usage
 104     fpu_state_end = fpu_state_off + ((FPUStateSizeInWords-1)*wordSize / BytesPerInt),
 105     fpu_stateH_end,
 106     r15_off, r15H_off,
 107     r14_off, r14H_off,
 108     r13_off, r13H_off,
 109     r12_off, r12H_off,
 110     r11_off, r11H_off,
 111     r10_off, r10H_off,
 112     r9_off,  r9H_off,
 113     r8_off,  r8H_off,
 114     rdi_off, rdiH_off,
 115     rsi_off, rsiH_off,
 116     ignore_off, ignoreH_off,  // extra copy of rbp
 117     rsp_off, rspH_off,
 118     rbx_off, rbxH_off,
 119     rdx_off, rdxH_off,
 120     rcx_off, rcxH_off,
 121     rax_off, raxH_off,
 122     // 16-byte stack alignment fill word: see MacroAssembler::push/pop_IU_state
 123     align_off, alignH_off,
 124     flags_off, flagsH_off,
 125     // The frame sender code expects that rbp will be in the "natural" place and
 126     // will override any oopMap setting for it. We must therefore force the layout
 127     // so that it agrees with the frame sender code.
 128     rbp_off, rbpH_off,        // copy of rbp we will restore
 129     return_off, returnH_off,  // slot for return address
 130     reg_save_size             // size in compiler stack slots
 131   };
 132 
 133  public:
 134   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors = false);
 135   static void restore_live_registers(MacroAssembler* masm, bool restore_vectors = false);
 136 
 137   // Offsets into the register save area
 138   // Used by deoptimization when it is managing result register
 139   // values on its own
 140 
 141   static int rax_offset_in_bytes(void)    { return BytesPerInt * rax_off; }
 142   static int rdx_offset_in_bytes(void)    { return BytesPerInt * rdx_off; }
 143   static int rbx_offset_in_bytes(void)    { return BytesPerInt * rbx_off; }
 144   static int xmm0_offset_in_bytes(void)   { return BytesPerInt * xmm0_off; }
 145   static int return_offset_in_bytes(void) { return BytesPerInt * return_off; }
 146 
 147   // During deoptimization only the result registers need to be restored,
 148   // all the other values have already been extracted.
 149   static void restore_result_registers(MacroAssembler* masm);
 150 };
 151 
 152 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors) {
 153   int off = 0;
 154   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 155   if (UseAVX < 3) {
 156     num_xmm_regs = num_xmm_regs/2;
 157   }
 158 #if COMPILER2_OR_JVMCI
 159   if (save_vectors) {
 160     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 161     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 162   }
 163 #else
 164   assert(!save_vectors, "vectors are generated only by C2 and JVMCI");
 165 #endif
 166 
 167   // Always make the frame size 16-byte aligned, both vector and non vector stacks are always allocated
 168   int frame_size_in_bytes = align_up(reg_save_size*BytesPerInt, num_xmm_regs);
 169   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 170   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 171   // CodeBlob frame size is in words.
 172   int frame_size_in_words = frame_size_in_bytes / wordSize;
 173   *total_frame_words = frame_size_in_words;
 174 
 175   // Save registers, fpu state, and flags.
 176   // We assume caller has already pushed the return address onto the
 177   // stack, so rsp is 8-byte aligned here.
 178   // We push rpb twice in this sequence because we want the real rbp
 179   // to be under the return like a normal enter.
 180 
 181   __ enter();          // rsp becomes 16-byte aligned here
 182   __ push_CPU_state(); // Push a multiple of 16 bytes
 183 
 184   // push cpu state handles this on EVEX enabled targets
 185   if (save_vectors) {
 186     // Save upper half of YMM registers(0..15)
 187     int base_addr = XSAVE_AREA_YMM_BEGIN;
 188     for (int n = 0; n < 16; n++) {
 189       __ vextractf128_high(Address(rsp, base_addr+n*16), as_XMMRegister(n));
 190     }
 191     if (VM_Version::supports_evex()) {
 192       // Save upper half of ZMM registers(0..15)
 193       base_addr = XSAVE_AREA_ZMM_BEGIN;
 194       for (int n = 0; n < 16; n++) {
 195         __ vextractf64x4_high(Address(rsp, base_addr+n*32), as_XMMRegister(n));
 196       }
 197       // Save full ZMM registers(16..num_xmm_regs)
 198       base_addr = XSAVE_AREA_UPPERBANK;
 199       off = 0;
 200       int vector_len = Assembler::AVX_512bit;
 201       for (int n = 16; n < num_xmm_regs; n++) {
 202         __ evmovdqul(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n), vector_len);
 203       }
 204     }
 205   } else {
 206     if (VM_Version::supports_evex()) {
 207       // Save upper bank of ZMM registers(16..31) for double/float usage
 208       int base_addr = XSAVE_AREA_UPPERBANK;
 209       off = 0;
 210       for (int n = 16; n < num_xmm_regs; n++) {
 211         __ movsd(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n));
 212       }
 213     }
 214   }
 215   __ vzeroupper();
 216   if (frame::arg_reg_save_area_bytes != 0) {
 217     // Allocate argument register save area
 218     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 219   }
 220 
 221   // Set an oopmap for the call site.  This oopmap will map all
 222   // oop-registers and debug-info registers as callee-saved.  This
 223   // will allow deoptimization at this safepoint to find all possible
 224   // debug-info recordings, as well as let GC find all oops.
 225 
 226   OopMapSet *oop_maps = new OopMapSet();
 227   OopMap* map = new OopMap(frame_size_in_slots, 0);
 228 
 229 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x))
 230 
 231   map->set_callee_saved(STACK_OFFSET( rax_off ), rax->as_VMReg());
 232   map->set_callee_saved(STACK_OFFSET( rcx_off ), rcx->as_VMReg());
 233   map->set_callee_saved(STACK_OFFSET( rdx_off ), rdx->as_VMReg());
 234   map->set_callee_saved(STACK_OFFSET( rbx_off ), rbx->as_VMReg());
 235   // rbp location is known implicitly by the frame sender code, needs no oopmap
 236   // and the location where rbp was saved by is ignored
 237   map->set_callee_saved(STACK_OFFSET( rsi_off ), rsi->as_VMReg());
 238   map->set_callee_saved(STACK_OFFSET( rdi_off ), rdi->as_VMReg());
 239   map->set_callee_saved(STACK_OFFSET( r8_off  ), r8->as_VMReg());
 240   map->set_callee_saved(STACK_OFFSET( r9_off  ), r9->as_VMReg());
 241   map->set_callee_saved(STACK_OFFSET( r10_off ), r10->as_VMReg());
 242   map->set_callee_saved(STACK_OFFSET( r11_off ), r11->as_VMReg());
 243   map->set_callee_saved(STACK_OFFSET( r12_off ), r12->as_VMReg());
 244   map->set_callee_saved(STACK_OFFSET( r13_off ), r13->as_VMReg());
 245   map->set_callee_saved(STACK_OFFSET( r14_off ), r14->as_VMReg());
 246   map->set_callee_saved(STACK_OFFSET( r15_off ), r15->as_VMReg());
 247   // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 248   // on EVEX enabled targets, we get it included in the xsave area
 249   off = xmm0_off;
 250   int delta = xmm1_off - off;
 251   for (int n = 0; n < 16; n++) {
 252     XMMRegister xmm_name = as_XMMRegister(n);
 253     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 254     off += delta;
 255   }
 256   if(UseAVX > 2) {
 257     // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 258     off = zmm16_off;
 259     delta = zmm17_off - off;
 260     for (int n = 16; n < num_xmm_regs; n++) {
 261       XMMRegister zmm_name = as_XMMRegister(n);
 262       map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg());
 263       off += delta;
 264     }
 265   }
 266 
 267 #if COMPILER2_OR_JVMCI
 268   if (save_vectors) {
 269     off = ymm0_off;
 270     int delta = ymm1_off - off;
 271     for (int n = 0; n < 16; n++) {
 272       XMMRegister ymm_name = as_XMMRegister(n);
 273       map->set_callee_saved(STACK_OFFSET(off), ymm_name->as_VMReg()->next(4));
 274       off += delta;
 275     }
 276   }
 277 #endif // COMPILER2_OR_JVMCI
 278 
 279   // %%% These should all be a waste but we'll keep things as they were for now
 280   if (true) {
 281     map->set_callee_saved(STACK_OFFSET( raxH_off ), rax->as_VMReg()->next());
 282     map->set_callee_saved(STACK_OFFSET( rcxH_off ), rcx->as_VMReg()->next());
 283     map->set_callee_saved(STACK_OFFSET( rdxH_off ), rdx->as_VMReg()->next());
 284     map->set_callee_saved(STACK_OFFSET( rbxH_off ), rbx->as_VMReg()->next());
 285     // rbp location is known implicitly by the frame sender code, needs no oopmap
 286     map->set_callee_saved(STACK_OFFSET( rsiH_off ), rsi->as_VMReg()->next());
 287     map->set_callee_saved(STACK_OFFSET( rdiH_off ), rdi->as_VMReg()->next());
 288     map->set_callee_saved(STACK_OFFSET( r8H_off  ), r8->as_VMReg()->next());
 289     map->set_callee_saved(STACK_OFFSET( r9H_off  ), r9->as_VMReg()->next());
 290     map->set_callee_saved(STACK_OFFSET( r10H_off ), r10->as_VMReg()->next());
 291     map->set_callee_saved(STACK_OFFSET( r11H_off ), r11->as_VMReg()->next());
 292     map->set_callee_saved(STACK_OFFSET( r12H_off ), r12->as_VMReg()->next());
 293     map->set_callee_saved(STACK_OFFSET( r13H_off ), r13->as_VMReg()->next());
 294     map->set_callee_saved(STACK_OFFSET( r14H_off ), r14->as_VMReg()->next());
 295     map->set_callee_saved(STACK_OFFSET( r15H_off ), r15->as_VMReg()->next());
 296     // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 297     // on EVEX enabled targets, we get it included in the xsave area
 298     off = xmm0H_off;
 299     delta = xmm1H_off - off;
 300     for (int n = 0; n < 16; n++) {
 301       XMMRegister xmm_name = as_XMMRegister(n);
 302       map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg()->next());
 303       off += delta;
 304     }
 305     if (UseAVX > 2) {
 306       // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 307       off = zmm16H_off;
 308       delta = zmm17H_off - off;
 309       for (int n = 16; n < num_xmm_regs; n++) {
 310         XMMRegister zmm_name = as_XMMRegister(n);
 311         map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg()->next());
 312         off += delta;
 313       }
 314     }
 315   }
 316 
 317   return map;
 318 }
 319 
 320 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 321   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 322   if (UseAVX < 3) {
 323     num_xmm_regs = num_xmm_regs/2;
 324   }
 325   if (frame::arg_reg_save_area_bytes != 0) {
 326     // Pop arg register save area
 327     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 328   }
 329 
 330 #if COMPILER2_OR_JVMCI
 331   if (restore_vectors) {
 332     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 333     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 334   }
 335 #else
 336   assert(!restore_vectors, "vectors are generated only by C2");
 337 #endif
 338 
 339   __ vzeroupper();
 340 
 341   // On EVEX enabled targets everything is handled in pop fpu state
 342   if (restore_vectors) {
 343     // Restore upper half of YMM registers (0..15)
 344     int base_addr = XSAVE_AREA_YMM_BEGIN;
 345     for (int n = 0; n < 16; n++) {
 346       __ vinsertf128_high(as_XMMRegister(n), Address(rsp, base_addr+n*16));
 347     }
 348     if (VM_Version::supports_evex()) {
 349       // Restore upper half of ZMM registers (0..15)
 350       base_addr = XSAVE_AREA_ZMM_BEGIN;
 351       for (int n = 0; n < 16; n++) {
 352         __ vinsertf64x4_high(as_XMMRegister(n), Address(rsp, base_addr+n*32));
 353       }
 354       // Restore full ZMM registers(16..num_xmm_regs)
 355       base_addr = XSAVE_AREA_UPPERBANK;
 356       int vector_len = Assembler::AVX_512bit;
 357       int off = 0;
 358       for (int n = 16; n < num_xmm_regs; n++) {
 359         __ evmovdqul(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)), vector_len);
 360       }
 361     }
 362   } else {
 363     if (VM_Version::supports_evex()) {
 364       // Restore upper bank of ZMM registers(16..31) for double/float usage
 365       int base_addr = XSAVE_AREA_UPPERBANK;
 366       int off = 0;
 367       for (int n = 16; n < num_xmm_regs; n++) {
 368         __ movsd(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)));
 369       }
 370     }
 371   }
 372 
 373   // Recover CPU state
 374   __ pop_CPU_state();
 375   // Get the rbp described implicitly by the calling convention (no oopMap)
 376   __ pop(rbp);
 377 }
 378 
 379 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 380 
 381   // Just restore result register. Only used by deoptimization. By
 382   // now any callee save register that needs to be restored to a c2
 383   // caller of the deoptee has been extracted into the vframeArray
 384   // and will be stuffed into the c2i adapter we create for later
 385   // restoration so only result registers need to be restored here.
 386 
 387   // Restore fp result register
 388   __ movdbl(xmm0, Address(rsp, xmm0_offset_in_bytes()));
 389   // Restore integer result register
 390   __ movptr(rax, Address(rsp, rax_offset_in_bytes()));
 391   __ movptr(rdx, Address(rsp, rdx_offset_in_bytes()));
 392 
 393   // Pop all of the register save are off the stack except the return address
 394   __ addptr(rsp, return_offset_in_bytes());
 395 }
 396 
 397 // Is vector's size (in bytes) bigger than a size saved by default?
 398 // 16 bytes XMM registers are saved by default using fxsave/fxrstor instructions.
 399 bool SharedRuntime::is_wide_vector(int size) {
 400   return size > 16;
 401 }
 402 
 403 size_t SharedRuntime::trampoline_size() {
 404   return 16;
 405 }
 406 
 407 void SharedRuntime::generate_trampoline(MacroAssembler *masm, address destination) {
 408   __ jump(RuntimeAddress(destination));
 409 }
 410 
 411 // The java_calling_convention describes stack locations as ideal slots on
 412 // a frame with no abi restrictions. Since we must observe abi restrictions
 413 // (like the placement of the register window) the slots must be biased by
 414 // the following value.
 415 static int reg2offset_in(VMReg r) {
 416   // Account for saved rbp and return address
 417   // This should really be in_preserve_stack_slots
 418   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 419 }
 420 
 421 static int reg2offset_out(VMReg r) {
 422   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 423 }
 424 
 425 // ---------------------------------------------------------------------------
 426 // Read the array of BasicTypes from a signature, and compute where the
 427 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 428 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 429 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 430 // as framesizes are fixed.
 431 // VMRegImpl::stack0 refers to the first slot 0(sp).
 432 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 433 // up to RegisterImpl::number_of_registers) are the 64-bit
 434 // integer registers.
 435 
 436 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 437 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 438 // units regardless of build. Of course for i486 there is no 64 bit build
 439 
 440 // The Java calling convention is a "shifted" version of the C ABI.
 441 // By skipping the first C ABI register we can call non-static jni methods
 442 // with small numbers of arguments without having to shuffle the arguments
 443 // at all. Since we control the java ABI we ought to at least get some
 444 // advantage out of it.
 445 
 446 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 447                                            VMRegPair *regs,
 448                                            int total_args_passed,
 449                                            int is_outgoing) {
 450 
 451   // Create the mapping between argument positions and
 452   // registers.
 453   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 454     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5
 455   };
 456   static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 457     j_farg0, j_farg1, j_farg2, j_farg3,
 458     j_farg4, j_farg5, j_farg6, j_farg7
 459   };
 460 
 461 
 462   uint int_args = 0;
 463   uint fp_args = 0;
 464   uint stk_args = 0; // inc by 2 each time
 465 
 466   for (int i = 0; i < total_args_passed; i++) {
 467     switch (sig_bt[i]) {
 468     case T_BOOLEAN:
 469     case T_CHAR:
 470     case T_BYTE:
 471     case T_SHORT:
 472     case T_INT:
 473       if (int_args < Argument::n_int_register_parameters_j) {
 474         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 475       } else {
 476         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 477         stk_args += 2;
 478       }
 479       break;
 480     case T_VOID:
 481       // halves of T_LONG or T_DOUBLE
 482       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 483       regs[i].set_bad();
 484       break;
 485     case T_LONG:
 486       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 487       // fall through
 488     case T_OBJECT:
 489     case T_ARRAY:
 490     case T_ADDRESS:
 491       if (int_args < Argument::n_int_register_parameters_j) {
 492         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 493       } else {
 494         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 495         stk_args += 2;
 496       }
 497       break;
 498     case T_FLOAT:
 499       if (fp_args < Argument::n_float_register_parameters_j) {
 500         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 501       } else {
 502         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 503         stk_args += 2;
 504       }
 505       break;
 506     case T_DOUBLE:
 507       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 508       if (fp_args < Argument::n_float_register_parameters_j) {
 509         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 510       } else {
 511         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 512         stk_args += 2;
 513       }
 514       break;
 515     default:
 516       ShouldNotReachHere();
 517       break;
 518     }
 519   }
 520 
 521   return align_up(stk_args, 2);
 522 }
 523 
 524 // Patch the callers callsite with entry to compiled code if it exists.
 525 static void patch_callers_callsite(MacroAssembler *masm) {
 526   Label L;
 527   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 528   __ jcc(Assembler::equal, L);
 529 
 530   // Save the current stack pointer
 531   __ mov(r13, rsp);
 532   // Schedule the branch target address early.
 533   // Call into the VM to patch the caller, then jump to compiled callee
 534   // rax isn't live so capture return address while we easily can
 535   __ movptr(rax, Address(rsp, 0));
 536 
 537   // align stack so push_CPU_state doesn't fault
 538   __ andptr(rsp, -(StackAlignmentInBytes));
 539   __ push_CPU_state();
 540   __ vzeroupper();
 541   // VM needs caller's callsite
 542   // VM needs target method
 543   // This needs to be a long call since we will relocate this adapter to
 544   // the codeBuffer and it may not reach
 545 
 546   // Allocate argument register save area
 547   if (frame::arg_reg_save_area_bytes != 0) {
 548     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 549   }
 550   __ mov(c_rarg0, rbx);
 551   __ mov(c_rarg1, rax);
 552   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 553 
 554   // De-allocate argument register save area
 555   if (frame::arg_reg_save_area_bytes != 0) {
 556     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 557   }
 558 
 559   __ vzeroupper();
 560   __ pop_CPU_state();
 561   // restore sp
 562   __ mov(rsp, r13);
 563   __ bind(L);
 564 }
 565 
 566 
 567 static void gen_c2i_adapter(MacroAssembler *masm,
 568                             int total_args_passed,
 569                             int comp_args_on_stack,
 570                             const BasicType *sig_bt,
 571                             const VMRegPair *regs,
 572                             Label& skip_fixup) {
 573   // Before we get into the guts of the C2I adapter, see if we should be here
 574   // at all.  We've come from compiled code and are attempting to jump to the
 575   // interpreter, which means the caller made a static call to get here
 576   // (vcalls always get a compiled target if there is one).  Check for a
 577   // compiled target.  If there is one, we need to patch the caller's call.
 578   patch_callers_callsite(masm);
 579 
 580   __ bind(skip_fixup);
 581 
 582   // Since all args are passed on the stack, total_args_passed *
 583   // Interpreter::stackElementSize is the space we need. Plus 1 because
 584   // we also account for the return address location since
 585   // we store it first rather than hold it in rax across all the shuffling
 586 
 587   int extraspace = (total_args_passed * Interpreter::stackElementSize) + wordSize;
 588 
 589   // stack is aligned, keep it that way
 590   extraspace = align_up(extraspace, 2*wordSize);
 591 
 592   // Get return address
 593   __ pop(rax);
 594 
 595   // set senderSP value
 596   __ mov(r13, rsp);
 597 
 598   __ subptr(rsp, extraspace);
 599 
 600   // Store the return address in the expected location
 601   __ movptr(Address(rsp, 0), rax);
 602 
 603   // Now write the args into the outgoing interpreter space
 604   for (int i = 0; i < total_args_passed; i++) {
 605     if (sig_bt[i] == T_VOID) {
 606       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 607       continue;
 608     }
 609 
 610     // offset to start parameters
 611     int st_off   = (total_args_passed - i) * Interpreter::stackElementSize;
 612     int next_off = st_off - Interpreter::stackElementSize;
 613 
 614     // Say 4 args:
 615     // i   st_off
 616     // 0   32 T_LONG
 617     // 1   24 T_VOID
 618     // 2   16 T_OBJECT
 619     // 3    8 T_BOOL
 620     // -    0 return address
 621     //
 622     // However to make thing extra confusing. Because we can fit a long/double in
 623     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 624     // leaves one slot empty and only stores to a single slot. In this case the
 625     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 626 
 627     VMReg r_1 = regs[i].first();
 628     VMReg r_2 = regs[i].second();
 629     if (!r_1->is_valid()) {
 630       assert(!r_2->is_valid(), "");
 631       continue;
 632     }
 633     if (r_1->is_stack()) {
 634       // memory to memory use rax
 635       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 636       if (!r_2->is_valid()) {
 637         // sign extend??
 638         __ movl(rax, Address(rsp, ld_off));
 639         __ movptr(Address(rsp, st_off), rax);
 640 
 641       } else {
 642 
 643         __ movq(rax, Address(rsp, ld_off));
 644 
 645         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 646         // T_DOUBLE and T_LONG use two slots in the interpreter
 647         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 648           // ld_off == LSW, ld_off+wordSize == MSW
 649           // st_off == MSW, next_off == LSW
 650           __ movq(Address(rsp, next_off), rax);
 651 #ifdef ASSERT
 652           // Overwrite the unused slot with known junk
 653           __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 654           __ movptr(Address(rsp, st_off), rax);
 655 #endif /* ASSERT */
 656         } else {
 657           __ movq(Address(rsp, st_off), rax);
 658         }
 659       }
 660     } else if (r_1->is_Register()) {
 661       Register r = r_1->as_Register();
 662       if (!r_2->is_valid()) {
 663         // must be only an int (or less ) so move only 32bits to slot
 664         // why not sign extend??
 665         __ movl(Address(rsp, st_off), r);
 666       } else {
 667         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 668         // T_DOUBLE and T_LONG use two slots in the interpreter
 669         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 670           // long/double in gpr
 671 #ifdef ASSERT
 672           // Overwrite the unused slot with known junk
 673           __ mov64(rax, CONST64(0xdeadffffdeadaaab));
 674           __ movptr(Address(rsp, st_off), rax);
 675 #endif /* ASSERT */
 676           __ movq(Address(rsp, next_off), r);
 677         } else {
 678           __ movptr(Address(rsp, st_off), r);
 679         }
 680       }
 681     } else {
 682       assert(r_1->is_XMMRegister(), "");
 683       if (!r_2->is_valid()) {
 684         // only a float use just part of the slot
 685         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 686       } else {
 687 #ifdef ASSERT
 688         // Overwrite the unused slot with known junk
 689         __ mov64(rax, CONST64(0xdeadffffdeadaaac));
 690         __ movptr(Address(rsp, st_off), rax);
 691 #endif /* ASSERT */
 692         __ movdbl(Address(rsp, next_off), r_1->as_XMMRegister());
 693       }
 694     }
 695   }
 696 
 697   // Schedule the branch target address early.
 698   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 699   __ jmp(rcx);
 700 }
 701 
 702 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 703                         address code_start, address code_end,
 704                         Label& L_ok) {
 705   Label L_fail;
 706   __ lea(temp_reg, ExternalAddress(code_start));
 707   __ cmpptr(pc_reg, temp_reg);
 708   __ jcc(Assembler::belowEqual, L_fail);
 709   __ lea(temp_reg, ExternalAddress(code_end));
 710   __ cmpptr(pc_reg, temp_reg);
 711   __ jcc(Assembler::below, L_ok);
 712   __ bind(L_fail);
 713 }
 714 
 715 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 716                                     int total_args_passed,
 717                                     int comp_args_on_stack,
 718                                     const BasicType *sig_bt,
 719                                     const VMRegPair *regs) {
 720 
 721   // Note: r13 contains the senderSP on entry. We must preserve it since
 722   // we may do a i2c -> c2i transition if we lose a race where compiled
 723   // code goes non-entrant while we get args ready.
 724   // In addition we use r13 to locate all the interpreter args as
 725   // we must align the stack to 16 bytes on an i2c entry else we
 726   // lose alignment we expect in all compiled code and register
 727   // save code can segv when fxsave instructions find improperly
 728   // aligned stack pointer.
 729 
 730   // Adapters can be frameless because they do not require the caller
 731   // to perform additional cleanup work, such as correcting the stack pointer.
 732   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 733   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 734   // even if a callee has modified the stack pointer.
 735   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 736   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 737   // up via the senderSP register).
 738   // In other words, if *either* the caller or callee is interpreted, we can
 739   // get the stack pointer repaired after a call.
 740   // This is why c2i and i2c adapters cannot be indefinitely composed.
 741   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 742   // both caller and callee would be compiled methods, and neither would
 743   // clean up the stack pointer changes performed by the two adapters.
 744   // If this happens, control eventually transfers back to the compiled
 745   // caller, but with an uncorrected stack, causing delayed havoc.
 746 
 747   // Pick up the return address
 748   __ movptr(rax, Address(rsp, 0));
 749 
 750   if (VerifyAdapterCalls &&
 751       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 752     // So, let's test for cascading c2i/i2c adapters right now.
 753     //  assert(Interpreter::contains($return_addr) ||
 754     //         StubRoutines::contains($return_addr),
 755     //         "i2c adapter must return to an interpreter frame");
 756     __ block_comment("verify_i2c { ");
 757     Label L_ok;
 758     if (Interpreter::code() != NULL)
 759       range_check(masm, rax, r11,
 760                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 761                   L_ok);
 762     if (StubRoutines::code1() != NULL)
 763       range_check(masm, rax, r11,
 764                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 765                   L_ok);
 766     if (StubRoutines::code2() != NULL)
 767       range_check(masm, rax, r11,
 768                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 769                   L_ok);
 770     const char* msg = "i2c adapter must return to an interpreter frame";
 771     __ block_comment(msg);
 772     __ stop(msg);
 773     __ bind(L_ok);
 774     __ block_comment("} verify_i2ce ");
 775   }
 776 
 777   // Must preserve original SP for loading incoming arguments because
 778   // we need to align the outgoing SP for compiled code.
 779   __ movptr(r11, rsp);
 780 
 781   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 782   // in registers, we will occasionally have no stack args.
 783   int comp_words_on_stack = 0;
 784   if (comp_args_on_stack) {
 785     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 786     // registers are below.  By subtracting stack0, we either get a negative
 787     // number (all values in registers) or the maximum stack slot accessed.
 788 
 789     // Convert 4-byte c2 stack slots to words.
 790     comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 791     // Round up to miminum stack alignment, in wordSize
 792     comp_words_on_stack = align_up(comp_words_on_stack, 2);
 793     __ subptr(rsp, comp_words_on_stack * wordSize);
 794   }
 795 
 796 
 797   // Ensure compiled code always sees stack at proper alignment
 798   __ andptr(rsp, -16);
 799 
 800   // push the return address and misalign the stack that youngest frame always sees
 801   // as far as the placement of the call instruction
 802   __ push(rax);
 803 
 804   // Put saved SP in another register
 805   const Register saved_sp = rax;
 806   __ movptr(saved_sp, r11);
 807 
 808   // Will jump to the compiled code just as if compiled code was doing it.
 809   // Pre-load the register-jump target early, to schedule it better.
 810   __ movptr(r11, Address(rbx, in_bytes(Method::from_compiled_offset())));
 811 
 812 #if INCLUDE_JVMCI
 813   if (EnableJVMCI || UseAOT) {
 814     // check if this call should be routed towards a specific entry point
 815     __ cmpptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 816     Label no_alternative_target;
 817     __ jcc(Assembler::equal, no_alternative_target);
 818     __ movptr(r11, Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 819     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 820     __ bind(no_alternative_target);
 821   }
 822 #endif // INCLUDE_JVMCI
 823 
 824   // Now generate the shuffle code.  Pick up all register args and move the
 825   // rest through the floating point stack top.
 826   for (int i = 0; i < total_args_passed; i++) {
 827     if (sig_bt[i] == T_VOID) {
 828       // Longs and doubles are passed in native word order, but misaligned
 829       // in the 32-bit build.
 830       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 831       continue;
 832     }
 833 
 834     // Pick up 0, 1 or 2 words from SP+offset.
 835 
 836     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 837             "scrambled load targets?");
 838     // Load in argument order going down.
 839     int ld_off = (total_args_passed - i)*Interpreter::stackElementSize;
 840     // Point to interpreter value (vs. tag)
 841     int next_off = ld_off - Interpreter::stackElementSize;
 842     //
 843     //
 844     //
 845     VMReg r_1 = regs[i].first();
 846     VMReg r_2 = regs[i].second();
 847     if (!r_1->is_valid()) {
 848       assert(!r_2->is_valid(), "");
 849       continue;
 850     }
 851     if (r_1->is_stack()) {
 852       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 853       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 854 
 855       // We can use r13 as a temp here because compiled code doesn't need r13 as an input
 856       // and if we end up going thru a c2i because of a miss a reasonable value of r13
 857       // will be generated.
 858       if (!r_2->is_valid()) {
 859         // sign extend???
 860         __ movl(r13, Address(saved_sp, ld_off));
 861         __ movptr(Address(rsp, st_off), r13);
 862       } else {
 863         //
 864         // We are using two optoregs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 865         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 866         // So we must adjust where to pick up the data to match the interpreter.
 867         //
 868         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 869         // are accessed as negative so LSW is at LOW address
 870 
 871         // ld_off is MSW so get LSW
 872         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 873                            next_off : ld_off;
 874         __ movq(r13, Address(saved_sp, offset));
 875         // st_off is LSW (i.e. reg.first())
 876         __ movq(Address(rsp, st_off), r13);
 877       }
 878     } else if (r_1->is_Register()) {  // Register argument
 879       Register r = r_1->as_Register();
 880       assert(r != rax, "must be different");
 881       if (r_2->is_valid()) {
 882         //
 883         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 884         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 885         // So we must adjust where to pick up the data to match the interpreter.
 886 
 887         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 888                            next_off : ld_off;
 889 
 890         // this can be a misaligned move
 891         __ movq(r, Address(saved_sp, offset));
 892       } else {
 893         // sign extend and use a full word?
 894         __ movl(r, Address(saved_sp, ld_off));
 895       }
 896     } else {
 897       if (!r_2->is_valid()) {
 898         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 899       } else {
 900         __ movdbl(r_1->as_XMMRegister(), Address(saved_sp, next_off));
 901       }
 902     }
 903   }
 904 
 905   // 6243940 We might end up in handle_wrong_method if
 906   // the callee is deoptimized as we race thru here. If that
 907   // happens we don't want to take a safepoint because the
 908   // caller frame will look interpreted and arguments are now
 909   // "compiled" so it is much better to make this transition
 910   // invisible to the stack walking code. Unfortunately if
 911   // we try and find the callee by normal means a safepoint
 912   // is possible. So we stash the desired callee in the thread
 913   // and the vm will find there should this case occur.
 914 
 915   __ movptr(Address(r15_thread, JavaThread::callee_target_offset()), rbx);
 916 
 917   // put Method* where a c2i would expect should we end up there
 918   // only needed becaus eof c2 resolve stubs return Method* as a result in
 919   // rax
 920   __ mov(rax, rbx);
 921   __ jmp(r11);
 922 }
 923 
 924 // ---------------------------------------------------------------
 925 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 926                                                             int total_args_passed,
 927                                                             int comp_args_on_stack,
 928                                                             const BasicType *sig_bt,
 929                                                             const VMRegPair *regs,
 930                                                             AdapterFingerPrint* fingerprint) {
 931   address i2c_entry = __ pc();
 932 
 933   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 934 
 935   // -------------------------------------------------------------------------
 936   // Generate a C2I adapter.  On entry we know rbx holds the Method* during calls
 937   // to the interpreter.  The args start out packed in the compiled layout.  They
 938   // need to be unpacked into the interpreter layout.  This will almost always
 939   // require some stack space.  We grow the current (compiled) stack, then repack
 940   // the args.  We  finally end in a jump to the generic interpreter entry point.
 941   // On exit from the interpreter, the interpreter will restore our SP (lest the
 942   // compiled code, which relys solely on SP and not RBP, get sick).
 943 
 944   address c2i_unverified_entry = __ pc();
 945   Label skip_fixup;
 946   Label ok;
 947 
 948   Register holder = rax;
 949   Register receiver = j_rarg0;
 950   Register temp = rbx;
 951 
 952   {
 953     __ load_klass(temp, receiver);
 954     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 955     __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
 956     __ jcc(Assembler::equal, ok);
 957     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 958 
 959     __ bind(ok);
 960     // Method might have been compiled since the call site was patched to
 961     // interpreted if that is the case treat it as a miss so we can get
 962     // the call site corrected.
 963     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 964     __ jcc(Assembler::equal, skip_fixup);
 965     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 966   }
 967 
 968   address c2i_entry = __ pc();
 969 
 970   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 971 
 972   __ flush();
 973   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 974 }
 975 
 976 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 977                                          VMRegPair *regs,
 978                                          VMRegPair *regs2,
 979                                          int total_args_passed) {
 980   assert(regs2 == NULL, "not needed on x86");
 981 // We return the amount of VMRegImpl stack slots we need to reserve for all
 982 // the arguments NOT counting out_preserve_stack_slots.
 983 
 984 // NOTE: These arrays will have to change when c1 is ported
 985 #ifdef _WIN64
 986     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 987       c_rarg0, c_rarg1, c_rarg2, c_rarg3
 988     };
 989     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 990       c_farg0, c_farg1, c_farg2, c_farg3
 991     };
 992 #else
 993     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 994       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5
 995     };
 996     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 997       c_farg0, c_farg1, c_farg2, c_farg3,
 998       c_farg4, c_farg5, c_farg6, c_farg7
 999     };
1000 #endif // _WIN64
1001 
1002 
1003     uint int_args = 0;
1004     uint fp_args = 0;
1005     uint stk_args = 0; // inc by 2 each time
1006 
1007     for (int i = 0; i < total_args_passed; i++) {
1008       switch (sig_bt[i]) {
1009       case T_BOOLEAN:
1010       case T_CHAR:
1011       case T_BYTE:
1012       case T_SHORT:
1013       case T_INT:
1014         if (int_args < Argument::n_int_register_parameters_c) {
1015           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1016 #ifdef _WIN64
1017           fp_args++;
1018           // Allocate slots for callee to stuff register args the stack.
1019           stk_args += 2;
1020 #endif
1021         } else {
1022           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1023           stk_args += 2;
1024         }
1025         break;
1026       case T_LONG:
1027         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1028         // fall through
1029       case T_OBJECT:
1030       case T_ARRAY:
1031       case T_ADDRESS:
1032       case T_METADATA:
1033         if (int_args < Argument::n_int_register_parameters_c) {
1034           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1035 #ifdef _WIN64
1036           fp_args++;
1037           stk_args += 2;
1038 #endif
1039         } else {
1040           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1041           stk_args += 2;
1042         }
1043         break;
1044       case T_FLOAT:
1045         if (fp_args < Argument::n_float_register_parameters_c) {
1046           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1047 #ifdef _WIN64
1048           int_args++;
1049           // Allocate slots for callee to stuff register args the stack.
1050           stk_args += 2;
1051 #endif
1052         } else {
1053           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1054           stk_args += 2;
1055         }
1056         break;
1057       case T_DOUBLE:
1058         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1059         if (fp_args < Argument::n_float_register_parameters_c) {
1060           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1061 #ifdef _WIN64
1062           int_args++;
1063           // Allocate slots for callee to stuff register args the stack.
1064           stk_args += 2;
1065 #endif
1066         } else {
1067           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1068           stk_args += 2;
1069         }
1070         break;
1071       case T_VOID: // Halves of longs and doubles
1072         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1073         regs[i].set_bad();
1074         break;
1075       default:
1076         ShouldNotReachHere();
1077         break;
1078       }
1079     }
1080 #ifdef _WIN64
1081   // windows abi requires that we always allocate enough stack space
1082   // for 4 64bit registers to be stored down.
1083   if (stk_args < 8) {
1084     stk_args = 8;
1085   }
1086 #endif // _WIN64
1087 
1088   return stk_args;
1089 }
1090 
1091 // On 64 bit we will store integer like items to the stack as
1092 // 64 bits items (sparc abi) even though java would only store
1093 // 32bits for a parameter. On 32bit it will simply be 32 bits
1094 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
1095 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1096   if (src.first()->is_stack()) {
1097     if (dst.first()->is_stack()) {
1098       // stack to stack
1099       __ movslq(rax, Address(rbp, reg2offset_in(src.first())));
1100       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1101     } else {
1102       // stack to reg
1103       __ movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1104     }
1105   } else if (dst.first()->is_stack()) {
1106     // reg to stack
1107     // Do we really have to sign extend???
1108     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1109     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1110   } else {
1111     // Do we really have to sign extend???
1112     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
1113     if (dst.first() != src.first()) {
1114       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1115     }
1116   }
1117 }
1118 
1119 static void move_ptr(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1120   if (src.first()->is_stack()) {
1121     if (dst.first()->is_stack()) {
1122       // stack to stack
1123       __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1124       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1125     } else {
1126       // stack to reg
1127       __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1128     }
1129   } else if (dst.first()->is_stack()) {
1130     // reg to stack
1131     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1132   } else {
1133     if (dst.first() != src.first()) {
1134       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1135     }
1136   }
1137 }
1138 
1139 // An oop arg. Must pass a handle not the oop itself
1140 static void object_move(MacroAssembler* masm,
1141                         OopMap* map,
1142                         int oop_handle_offset,
1143                         int framesize_in_slots,
1144                         VMRegPair src,
1145                         VMRegPair dst,
1146                         bool is_receiver,
1147                         int* receiver_offset) {
1148 
1149   // must pass a handle. First figure out the location we use as a handle
1150 
1151   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
1152 
1153   // See if oop is NULL if it is we need no handle
1154 
1155   if (src.first()->is_stack()) {
1156 
1157     // Oop is already on the stack as an argument
1158     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1159     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1160     if (is_receiver) {
1161       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1162     }
1163 
1164     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1165     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1166     // conditionally move a NULL
1167     __ cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
1168   } else {
1169 
1170     // Oop is in an a register we must store it to the space we reserve
1171     // on the stack for oop_handles and pass a handle if oop is non-NULL
1172 
1173     const Register rOop = src.first()->as_Register();
1174     int oop_slot;
1175     if (rOop == j_rarg0)
1176       oop_slot = 0;
1177     else if (rOop == j_rarg1)
1178       oop_slot = 1;
1179     else if (rOop == j_rarg2)
1180       oop_slot = 2;
1181     else if (rOop == j_rarg3)
1182       oop_slot = 3;
1183     else if (rOop == j_rarg4)
1184       oop_slot = 4;
1185     else {
1186       assert(rOop == j_rarg5, "wrong register");
1187       oop_slot = 5;
1188     }
1189 
1190     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1191     int offset = oop_slot*VMRegImpl::stack_slot_size;
1192 
1193     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1194     // Store oop in handle area, may be NULL
1195     __ movptr(Address(rsp, offset), rOop);
1196     if (is_receiver) {
1197       *receiver_offset = offset;
1198     }
1199 
1200     __ cmpptr(rOop, (int32_t)NULL_WORD);
1201     __ lea(rHandle, Address(rsp, offset));
1202     // conditionally move a NULL from the handle area where it was just stored
1203     __ cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
1204   }
1205 
1206   // If arg is on the stack then place it otherwise it is already in correct reg.
1207   if (dst.first()->is_stack()) {
1208     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1209   }
1210 }
1211 
1212 // A float arg may have to do float reg int reg conversion
1213 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1214   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1215 
1216   // The calling conventions assures us that each VMregpair is either
1217   // all really one physical register or adjacent stack slots.
1218   // This greatly simplifies the cases here compared to sparc.
1219 
1220   if (src.first()->is_stack()) {
1221     if (dst.first()->is_stack()) {
1222       __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1223       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1224     } else {
1225       // stack to reg
1226       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1227       __ movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
1228     }
1229   } else if (dst.first()->is_stack()) {
1230     // reg to stack
1231     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1232     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1233   } else {
1234     // reg to reg
1235     // In theory these overlap but the ordering is such that this is likely a nop
1236     if ( src.first() != dst.first()) {
1237       __ movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1238     }
1239   }
1240 }
1241 
1242 // A long move
1243 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1244 
1245   // The calling conventions assures us that each VMregpair is either
1246   // all really one physical register or adjacent stack slots.
1247   // This greatly simplifies the cases here compared to sparc.
1248 
1249   if (src.is_single_phys_reg() ) {
1250     if (dst.is_single_phys_reg()) {
1251       if (dst.first() != src.first()) {
1252         __ mov(dst.first()->as_Register(), src.first()->as_Register());
1253       }
1254     } else {
1255       assert(dst.is_single_reg(), "not a stack pair");
1256       __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1257     }
1258   } else if (dst.is_single_phys_reg()) {
1259     assert(src.is_single_reg(),  "not a stack pair");
1260     __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
1261   } else {
1262     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1263     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1264     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1265   }
1266 }
1267 
1268 // A double move
1269 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1270 
1271   // The calling conventions assures us that each VMregpair is either
1272   // all really one physical register or adjacent stack slots.
1273   // This greatly simplifies the cases here compared to sparc.
1274 
1275   if (src.is_single_phys_reg() ) {
1276     if (dst.is_single_phys_reg()) {
1277       // In theory these overlap but the ordering is such that this is likely a nop
1278       if ( src.first() != dst.first()) {
1279         __ movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
1280       }
1281     } else {
1282       assert(dst.is_single_reg(), "not a stack pair");
1283       __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1284     }
1285   } else if (dst.is_single_phys_reg()) {
1286     assert(src.is_single_reg(),  "not a stack pair");
1287     __ movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
1288   } else {
1289     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1290     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1291     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1292   }
1293 }
1294 
1295 
1296 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1297   // We always ignore the frame_slots arg and just use the space just below frame pointer
1298   // which by this time is free to use
1299   switch (ret_type) {
1300   case T_FLOAT:
1301     __ movflt(Address(rbp, -wordSize), xmm0);
1302     break;
1303   case T_DOUBLE:
1304     __ movdbl(Address(rbp, -wordSize), xmm0);
1305     break;
1306   case T_VOID:  break;
1307   default: {
1308     __ movptr(Address(rbp, -wordSize), rax);
1309     }
1310   }
1311 }
1312 
1313 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1314   // We always ignore the frame_slots arg and just use the space just below frame pointer
1315   // which by this time is free to use
1316   switch (ret_type) {
1317   case T_FLOAT:
1318     __ movflt(xmm0, Address(rbp, -wordSize));
1319     break;
1320   case T_DOUBLE:
1321     __ movdbl(xmm0, Address(rbp, -wordSize));
1322     break;
1323   case T_VOID:  break;
1324   default: {
1325     __ movptr(rax, Address(rbp, -wordSize));
1326     }
1327   }
1328 }
1329 
1330 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1331     for ( int i = first_arg ; i < arg_count ; i++ ) {
1332       if (args[i].first()->is_Register()) {
1333         __ push(args[i].first()->as_Register());
1334       } else if (args[i].first()->is_XMMRegister()) {
1335         __ subptr(rsp, 2*wordSize);
1336         __ movdbl(Address(rsp, 0), args[i].first()->as_XMMRegister());
1337       }
1338     }
1339 }
1340 
1341 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1342     for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1343       if (args[i].first()->is_Register()) {
1344         __ pop(args[i].first()->as_Register());
1345       } else if (args[i].first()->is_XMMRegister()) {
1346         __ movdbl(args[i].first()->as_XMMRegister(), Address(rsp, 0));
1347         __ addptr(rsp, 2*wordSize);
1348       }
1349     }
1350 }
1351 
1352 
1353 static void save_or_restore_arguments(MacroAssembler* masm,
1354                                       const int stack_slots,
1355                                       const int total_in_args,
1356                                       const int arg_save_area,
1357                                       OopMap* map,
1358                                       VMRegPair* in_regs,
1359                                       BasicType* in_sig_bt) {
1360   // if map is non-NULL then the code should store the values,
1361   // otherwise it should load them.
1362   int slot = arg_save_area;
1363   // Save down double word first
1364   for ( int i = 0; i < total_in_args; i++) {
1365     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1366       int offset = slot * VMRegImpl::stack_slot_size;
1367       slot += VMRegImpl::slots_per_word;
1368       assert(slot <= stack_slots, "overflow");
1369       if (map != NULL) {
1370         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1371       } else {
1372         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1373       }
1374     }
1375     if (in_regs[i].first()->is_Register() &&
1376         (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_ARRAY)) {
1377       int offset = slot * VMRegImpl::stack_slot_size;
1378       if (map != NULL) {
1379         __ movq(Address(rsp, offset), in_regs[i].first()->as_Register());
1380         if (in_sig_bt[i] == T_ARRAY) {
1381           map->set_oop(VMRegImpl::stack2reg(slot));;
1382         }
1383       } else {
1384         __ movq(in_regs[i].first()->as_Register(), Address(rsp, offset));
1385       }
1386       slot += VMRegImpl::slots_per_word;
1387     }
1388   }
1389   // Save or restore single word registers
1390   for ( int i = 0; i < total_in_args; i++) {
1391     if (in_regs[i].first()->is_Register()) {
1392       int offset = slot * VMRegImpl::stack_slot_size;
1393       slot++;
1394       assert(slot <= stack_slots, "overflow");
1395 
1396       // Value is in an input register pass we must flush it to the stack
1397       const Register reg = in_regs[i].first()->as_Register();
1398       switch (in_sig_bt[i]) {
1399         case T_BOOLEAN:
1400         case T_CHAR:
1401         case T_BYTE:
1402         case T_SHORT:
1403         case T_INT:
1404           if (map != NULL) {
1405             __ movl(Address(rsp, offset), reg);
1406           } else {
1407             __ movl(reg, Address(rsp, offset));
1408           }
1409           break;
1410         case T_ARRAY:
1411         case T_LONG:
1412           // handled above
1413           break;
1414         case T_OBJECT:
1415         default: ShouldNotReachHere();
1416       }
1417     } else if (in_regs[i].first()->is_XMMRegister()) {
1418       if (in_sig_bt[i] == T_FLOAT) {
1419         int offset = slot * VMRegImpl::stack_slot_size;
1420         slot++;
1421         assert(slot <= stack_slots, "overflow");
1422         if (map != NULL) {
1423           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1424         } else {
1425           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1426         }
1427       }
1428     } else if (in_regs[i].first()->is_stack()) {
1429       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1430         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1431         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1432       }
1433     }
1434   }
1435 }
1436 
1437 // Pin incoming array argument of java critical method
1438 static void pin_critical_native_array(MacroAssembler* masm,
1439                                       VMRegPair reg,
1440                                       int& pinned_slot) {
1441   __ block_comment("pin_critical_native_array {");
1442   Register tmp_reg = rax;
1443 
1444   Label is_null;
1445   VMRegPair tmp;
1446   VMRegPair in_reg = reg;
1447   bool on_stack = false;
1448 
1449   tmp.set_ptr(tmp_reg->as_VMReg());
1450   if (reg.first()->is_stack()) {
1451     // Load the arg up from the stack
1452     move_ptr(masm, reg, tmp);
1453     reg = tmp;
1454     on_stack = true;
1455   } else {
1456     __ movptr(rax, reg.first()->as_Register());
1457   }
1458   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1459   __ jccb(Assembler::equal, is_null);
1460 
1461   __ push(c_rarg0);
1462   __ push(c_rarg1);
1463   __ push(c_rarg2);
1464   __ push(c_rarg3);
1465 #ifdef _WIN64
1466   // caller-saved registers on Windows
1467   __ push(r10);
1468   __ push(r11);
1469 #else
1470   __ push(c_rarg4);
1471   __ push(c_rarg5);
1472 #endif
1473 
1474   if (reg.first()->as_Register() != c_rarg1) {
1475     __ movptr(c_rarg1, reg.first()->as_Register());
1476   }
1477   __ movptr(c_rarg0, r15_thread);
1478   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::pin_object)));
1479 
1480 #ifdef _WIN64
1481   __ pop(r11);
1482   __ pop(r10);
1483 #else
1484   __ pop(c_rarg5);
1485   __ pop(c_rarg4);
1486 #endif
1487   __ pop(c_rarg3);
1488   __ pop(c_rarg2);
1489   __ pop(c_rarg1);
1490   __ pop(c_rarg0);
1491 
1492   if (on_stack) {
1493     __ movptr(Address(rbp, reg2offset_in(in_reg.first())), rax);
1494     __ bind(is_null);
1495   } else {
1496     __ movptr(reg.first()->as_Register(), rax);
1497 
1498     // save on stack for unpinning later
1499     __ bind(is_null);
1500     assert(reg.first()->is_Register(), "Must be a register");
1501     int offset = pinned_slot * VMRegImpl::stack_slot_size;
1502     pinned_slot += VMRegImpl::slots_per_word;
1503     __ movq(Address(rsp, offset), rax);
1504   }
1505   __ block_comment("} pin_critical_native_array");
1506 }
1507 
1508 // Unpin array argument of java critical method
1509 static void unpin_critical_native_array(MacroAssembler* masm,
1510                                         VMRegPair reg,
1511                                         int& pinned_slot) {
1512   __ block_comment("unpin_critical_native_array {");
1513   Label is_null;
1514 
1515   if (reg.first()->is_stack()) {
1516     __ movptr(c_rarg1, Address(rbp, reg2offset_in(reg.first())));
1517   } else {
1518     int offset = pinned_slot * VMRegImpl::stack_slot_size;
1519     pinned_slot += VMRegImpl::slots_per_word;
1520     __ movq(c_rarg1, Address(rsp, offset));
1521   }
1522   __ testptr(c_rarg1, c_rarg1);
1523   __ jccb(Assembler::equal, is_null);
1524 
1525   __ movptr(c_rarg0, r15_thread);
1526   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::unpin_object)));
1527 
1528   __ bind(is_null);
1529   __ block_comment("} unpin_critical_native_array");
1530 }
1531 
1532 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1533 // keeps a new JNI critical region from starting until a GC has been
1534 // forced.  Save down any oops in registers and describe them in an
1535 // OopMap.
1536 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1537                                                int stack_slots,
1538                                                int total_c_args,
1539                                                int total_in_args,
1540                                                int arg_save_area,
1541                                                OopMapSet* oop_maps,
1542                                                VMRegPair* in_regs,
1543                                                BasicType* in_sig_bt) {
1544   __ block_comment("check GCLocker::needs_gc");
1545   Label cont;
1546   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1547   __ jcc(Assembler::equal, cont);
1548 
1549   // Save down any incoming oops and call into the runtime to halt for a GC
1550 
1551   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1552   save_or_restore_arguments(masm, stack_slots, total_in_args,
1553                             arg_save_area, map, in_regs, in_sig_bt);
1554 
1555   address the_pc = __ pc();
1556   oop_maps->add_gc_map( __ offset(), map);
1557   __ set_last_Java_frame(rsp, noreg, the_pc);
1558 
1559   __ block_comment("block_for_jni_critical");
1560   __ movptr(c_rarg0, r15_thread);
1561   __ mov(r12, rsp); // remember sp
1562   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1563   __ andptr(rsp, -16); // align stack as required by ABI
1564   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1565   __ mov(rsp, r12); // restore sp
1566   __ reinit_heapbase();
1567 
1568   __ reset_last_Java_frame(false);
1569 
1570   save_or_restore_arguments(masm, stack_slots, total_in_args,
1571                             arg_save_area, NULL, in_regs, in_sig_bt);
1572   __ bind(cont);
1573 #ifdef ASSERT
1574   if (StressCriticalJNINatives) {
1575     // Stress register saving
1576     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1577     save_or_restore_arguments(masm, stack_slots, total_in_args,
1578                               arg_save_area, map, in_regs, in_sig_bt);
1579     // Destroy argument registers
1580     for (int i = 0; i < total_in_args - 1; i++) {
1581       if (in_regs[i].first()->is_Register()) {
1582         const Register reg = in_regs[i].first()->as_Register();
1583         __ xorptr(reg, reg);
1584       } else if (in_regs[i].first()->is_XMMRegister()) {
1585         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1586       } else if (in_regs[i].first()->is_FloatRegister()) {
1587         ShouldNotReachHere();
1588       } else if (in_regs[i].first()->is_stack()) {
1589         // Nothing to do
1590       } else {
1591         ShouldNotReachHere();
1592       }
1593       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1594         i++;
1595       }
1596     }
1597 
1598     save_or_restore_arguments(masm, stack_slots, total_in_args,
1599                               arg_save_area, NULL, in_regs, in_sig_bt);
1600   }
1601 #endif
1602 }
1603 
1604 // Unpack an array argument into a pointer to the body and the length
1605 // if the array is non-null, otherwise pass 0 for both.
1606 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1607   Register tmp_reg = rax;
1608   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1609          "possible collision");
1610   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1611          "possible collision");
1612 
1613   __ block_comment("unpack_array_argument {");
1614 
1615   // Pass the length, ptr pair
1616   Label is_null, done;
1617   VMRegPair tmp;
1618   tmp.set_ptr(tmp_reg->as_VMReg());
1619   if (reg.first()->is_stack()) {
1620     // Load the arg up from the stack
1621     move_ptr(masm, reg, tmp);
1622     reg = tmp;
1623   }
1624   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1625   __ jccb(Assembler::equal, is_null);
1626   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1627   move_ptr(masm, tmp, body_arg);
1628   // load the length relative to the body.
1629   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1630                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1631   move32_64(masm, tmp, length_arg);
1632   __ jmpb(done);
1633   __ bind(is_null);
1634   // Pass zeros
1635   __ xorptr(tmp_reg, tmp_reg);
1636   move_ptr(masm, tmp, body_arg);
1637   move32_64(masm, tmp, length_arg);
1638   __ bind(done);
1639 
1640   __ block_comment("} unpack_array_argument");
1641 }
1642 
1643 
1644 // Different signatures may require very different orders for the move
1645 // to avoid clobbering other arguments.  There's no simple way to
1646 // order them safely.  Compute a safe order for issuing stores and
1647 // break any cycles in those stores.  This code is fairly general but
1648 // it's not necessary on the other platforms so we keep it in the
1649 // platform dependent code instead of moving it into a shared file.
1650 // (See bugs 7013347 & 7145024.)
1651 // Note that this code is specific to LP64.
1652 class ComputeMoveOrder: public StackObj {
1653   class MoveOperation: public ResourceObj {
1654     friend class ComputeMoveOrder;
1655    private:
1656     VMRegPair        _src;
1657     VMRegPair        _dst;
1658     int              _src_index;
1659     int              _dst_index;
1660     bool             _processed;
1661     MoveOperation*  _next;
1662     MoveOperation*  _prev;
1663 
1664     static int get_id(VMRegPair r) {
1665       return r.first()->value();
1666     }
1667 
1668    public:
1669     MoveOperation(int src_index, VMRegPair src, int dst_index, VMRegPair dst):
1670       _src(src)
1671     , _src_index(src_index)
1672     , _dst(dst)
1673     , _dst_index(dst_index)
1674     , _next(NULL)
1675     , _prev(NULL)
1676     , _processed(false) {
1677     }
1678 
1679     VMRegPair src() const              { return _src; }
1680     int src_id() const                 { return get_id(src()); }
1681     int src_index() const              { return _src_index; }
1682     VMRegPair dst() const              { return _dst; }
1683     void set_dst(int i, VMRegPair dst) { _dst_index = i, _dst = dst; }
1684     int dst_index() const              { return _dst_index; }
1685     int dst_id() const                 { return get_id(dst()); }
1686     MoveOperation* next() const       { return _next; }
1687     MoveOperation* prev() const       { return _prev; }
1688     void set_processed()               { _processed = true; }
1689     bool is_processed() const          { return _processed; }
1690 
1691     // insert
1692     void break_cycle(VMRegPair temp_register) {
1693       // create a new store following the last store
1694       // to move from the temp_register to the original
1695       MoveOperation* new_store = new MoveOperation(-1, temp_register, dst_index(), dst());
1696 
1697       // break the cycle of links and insert new_store at the end
1698       // break the reverse link.
1699       MoveOperation* p = prev();
1700       assert(p->next() == this, "must be");
1701       _prev = NULL;
1702       p->_next = new_store;
1703       new_store->_prev = p;
1704 
1705       // change the original store to save it's value in the temp.
1706       set_dst(-1, temp_register);
1707     }
1708 
1709     void link(GrowableArray<MoveOperation*>& killer) {
1710       // link this store in front the store that it depends on
1711       MoveOperation* n = killer.at_grow(src_id(), NULL);
1712       if (n != NULL) {
1713         assert(_next == NULL && n->_prev == NULL, "shouldn't have been set yet");
1714         _next = n;
1715         n->_prev = this;
1716       }
1717     }
1718   };
1719 
1720  private:
1721   GrowableArray<MoveOperation*> edges;
1722 
1723  public:
1724   ComputeMoveOrder(int total_in_args, VMRegPair* in_regs, int total_c_args, VMRegPair* out_regs,
1725                     BasicType* in_sig_bt, GrowableArray<int>& arg_order, VMRegPair tmp_vmreg) {
1726     // Move operations where the dest is the stack can all be
1727     // scheduled first since they can't interfere with the other moves.
1728     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1729       if (in_sig_bt[i] == T_ARRAY) {
1730         c_arg--;
1731         if (out_regs[c_arg].first()->is_stack() &&
1732             out_regs[c_arg + 1].first()->is_stack()) {
1733           arg_order.push(i);
1734           arg_order.push(c_arg);
1735         } else {
1736           if (out_regs[c_arg].first()->is_stack() ||
1737               in_regs[i].first() == out_regs[c_arg].first()) {
1738             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg + 1]);
1739           } else {
1740             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1741           }
1742         }
1743       } else if (in_sig_bt[i] == T_VOID) {
1744         arg_order.push(i);
1745         arg_order.push(c_arg);
1746       } else {
1747         if (out_regs[c_arg].first()->is_stack() ||
1748             in_regs[i].first() == out_regs[c_arg].first()) {
1749           arg_order.push(i);
1750           arg_order.push(c_arg);
1751         } else {
1752           add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1753         }
1754       }
1755     }
1756     // Break any cycles in the register moves and emit the in the
1757     // proper order.
1758     GrowableArray<MoveOperation*>* stores = get_store_order(tmp_vmreg);
1759     for (int i = 0; i < stores->length(); i++) {
1760       arg_order.push(stores->at(i)->src_index());
1761       arg_order.push(stores->at(i)->dst_index());
1762     }
1763  }
1764 
1765   // Collected all the move operations
1766   void add_edge(int src_index, VMRegPair src, int dst_index, VMRegPair dst) {
1767     if (src.first() == dst.first()) return;
1768     edges.append(new MoveOperation(src_index, src, dst_index, dst));
1769   }
1770 
1771   // Walk the edges breaking cycles between moves.  The result list
1772   // can be walked in order to produce the proper set of loads
1773   GrowableArray<MoveOperation*>* get_store_order(VMRegPair temp_register) {
1774     // Record which moves kill which values
1775     GrowableArray<MoveOperation*> killer;
1776     for (int i = 0; i < edges.length(); i++) {
1777       MoveOperation* s = edges.at(i);
1778       assert(killer.at_grow(s->dst_id(), NULL) == NULL, "only one killer");
1779       killer.at_put_grow(s->dst_id(), s, NULL);
1780     }
1781     assert(killer.at_grow(MoveOperation::get_id(temp_register), NULL) == NULL,
1782            "make sure temp isn't in the registers that are killed");
1783 
1784     // create links between loads and stores
1785     for (int i = 0; i < edges.length(); i++) {
1786       edges.at(i)->link(killer);
1787     }
1788 
1789     // at this point, all the move operations are chained together
1790     // in a doubly linked list.  Processing it backwards finds
1791     // the beginning of the chain, forwards finds the end.  If there's
1792     // a cycle it can be broken at any point,  so pick an edge and walk
1793     // backward until the list ends or we end where we started.
1794     GrowableArray<MoveOperation*>* stores = new GrowableArray<MoveOperation*>();
1795     for (int e = 0; e < edges.length(); e++) {
1796       MoveOperation* s = edges.at(e);
1797       if (!s->is_processed()) {
1798         MoveOperation* start = s;
1799         // search for the beginning of the chain or cycle
1800         while (start->prev() != NULL && start->prev() != s) {
1801           start = start->prev();
1802         }
1803         if (start->prev() == s) {
1804           start->break_cycle(temp_register);
1805         }
1806         // walk the chain forward inserting to store list
1807         while (start != NULL) {
1808           stores->append(start);
1809           start->set_processed();
1810           start = start->next();
1811         }
1812       }
1813     }
1814     return stores;
1815   }
1816 };
1817 
1818 static void verify_oop_args(MacroAssembler* masm,
1819                             const methodHandle& method,
1820                             const BasicType* sig_bt,
1821                             const VMRegPair* regs) {
1822   Register temp_reg = rbx;  // not part of any compiled calling seq
1823   if (VerifyOops) {
1824     for (int i = 0; i < method->size_of_parameters(); i++) {
1825       if (sig_bt[i] == T_OBJECT ||
1826           sig_bt[i] == T_ARRAY) {
1827         VMReg r = regs[i].first();
1828         assert(r->is_valid(), "bad oop arg");
1829         if (r->is_stack()) {
1830           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1831           __ verify_oop(temp_reg);
1832         } else {
1833           __ verify_oop(r->as_Register());
1834         }
1835       }
1836     }
1837   }
1838 }
1839 
1840 static void gen_special_dispatch(MacroAssembler* masm,
1841                                  const methodHandle& method,
1842                                  const BasicType* sig_bt,
1843                                  const VMRegPair* regs) {
1844   verify_oop_args(masm, method, sig_bt, regs);
1845   vmIntrinsics::ID iid = method->intrinsic_id();
1846 
1847   // Now write the args into the outgoing interpreter space
1848   bool     has_receiver   = false;
1849   Register receiver_reg   = noreg;
1850   int      member_arg_pos = -1;
1851   Register member_reg     = noreg;
1852   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1853   if (ref_kind != 0) {
1854     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1855     member_reg = rbx;  // known to be free at this point
1856     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1857   } else if (iid == vmIntrinsics::_invokeBasic) {
1858     has_receiver = true;
1859   } else {
1860     fatal("unexpected intrinsic id %d", iid);
1861   }
1862 
1863   if (member_reg != noreg) {
1864     // Load the member_arg into register, if necessary.
1865     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1866     VMReg r = regs[member_arg_pos].first();
1867     if (r->is_stack()) {
1868       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1869     } else {
1870       // no data motion is needed
1871       member_reg = r->as_Register();
1872     }
1873   }
1874 
1875   if (has_receiver) {
1876     // Make sure the receiver is loaded into a register.
1877     assert(method->size_of_parameters() > 0, "oob");
1878     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1879     VMReg r = regs[0].first();
1880     assert(r->is_valid(), "bad receiver arg");
1881     if (r->is_stack()) {
1882       // Porting note:  This assumes that compiled calling conventions always
1883       // pass the receiver oop in a register.  If this is not true on some
1884       // platform, pick a temp and load the receiver from stack.
1885       fatal("receiver always in a register");
1886       receiver_reg = j_rarg0;  // known to be free at this point
1887       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1888     } else {
1889       // no data motion is needed
1890       receiver_reg = r->as_Register();
1891     }
1892   }
1893 
1894   // Figure out which address we are really jumping to:
1895   MethodHandles::generate_method_handle_dispatch(masm, iid,
1896                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1897 }
1898 
1899 // ---------------------------------------------------------------------------
1900 // Generate a native wrapper for a given method.  The method takes arguments
1901 // in the Java compiled code convention, marshals them to the native
1902 // convention (handlizes oops, etc), transitions to native, makes the call,
1903 // returns to java state (possibly blocking), unhandlizes any result and
1904 // returns.
1905 //
1906 // Critical native functions are a shorthand for the use of
1907 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1908 // functions.  The wrapper is expected to unpack the arguments before
1909 // passing them to the callee and perform checks before and after the
1910 // native call to ensure that they GCLocker
1911 // lock_critical/unlock_critical semantics are followed.  Some other
1912 // parts of JNI setup are skipped like the tear down of the JNI handle
1913 // block and the check for pending exceptions it's impossible for them
1914 // to be thrown.
1915 //
1916 // They are roughly structured like this:
1917 //    if (GCLocker::needs_gc())
1918 //      SharedRuntime::block_for_jni_critical();
1919 //    tranistion to thread_in_native
1920 //    unpack arrray arguments and call native entry point
1921 //    check for safepoint in progress
1922 //    check if any thread suspend flags are set
1923 //      call into JVM and possible unlock the JNI critical
1924 //      if a GC was suppressed while in the critical native.
1925 //    transition back to thread_in_Java
1926 //    return to caller
1927 //
1928 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1929                                                 const methodHandle& method,
1930                                                 int compile_id,
1931                                                 BasicType* in_sig_bt,
1932                                                 VMRegPair* in_regs,
1933                                                 BasicType ret_type) {
1934   if (method->is_method_handle_intrinsic()) {
1935     vmIntrinsics::ID iid = method->intrinsic_id();
1936     intptr_t start = (intptr_t)__ pc();
1937     int vep_offset = ((intptr_t)__ pc()) - start;
1938     gen_special_dispatch(masm,
1939                          method,
1940                          in_sig_bt,
1941                          in_regs);
1942     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1943     __ flush();
1944     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1945     return nmethod::new_native_nmethod(method,
1946                                        compile_id,
1947                                        masm->code(),
1948                                        vep_offset,
1949                                        frame_complete,
1950                                        stack_slots / VMRegImpl::slots_per_word,
1951                                        in_ByteSize(-1),
1952                                        in_ByteSize(-1),
1953                                        (OopMapSet*)NULL);
1954   }
1955   bool is_critical_native = true;
1956   address native_func = method->critical_native_function();
1957   if (native_func == NULL) {
1958     native_func = method->native_function();
1959     is_critical_native = false;
1960   }
1961   assert(native_func != NULL, "must have function");
1962 
1963   // An OopMap for lock (and class if static)
1964   OopMapSet *oop_maps = new OopMapSet();
1965   intptr_t start = (intptr_t)__ pc();
1966 
1967   // We have received a description of where all the java arg are located
1968   // on entry to the wrapper. We need to convert these args to where
1969   // the jni function will expect them. To figure out where they go
1970   // we convert the java signature to a C signature by inserting
1971   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1972 
1973   const int total_in_args = method->size_of_parameters();
1974   int total_c_args = total_in_args;
1975   if (!is_critical_native) {
1976     total_c_args += 1;
1977     if (method->is_static()) {
1978       total_c_args++;
1979     }
1980   } else {
1981     for (int i = 0; i < total_in_args; i++) {
1982       if (in_sig_bt[i] == T_ARRAY) {
1983         total_c_args++;
1984       }
1985     }
1986   }
1987 
1988   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1989   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1990   BasicType* in_elem_bt = NULL;
1991 
1992   int argc = 0;
1993   if (!is_critical_native) {
1994     out_sig_bt[argc++] = T_ADDRESS;
1995     if (method->is_static()) {
1996       out_sig_bt[argc++] = T_OBJECT;
1997     }
1998 
1999     for (int i = 0; i < total_in_args ; i++ ) {
2000       out_sig_bt[argc++] = in_sig_bt[i];
2001     }
2002   } else {
2003     Thread* THREAD = Thread::current();
2004     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
2005     SignatureStream ss(method->signature());
2006     for (int i = 0; i < total_in_args ; i++ ) {
2007       if (in_sig_bt[i] == T_ARRAY) {
2008         // Arrays are passed as int, elem* pair
2009         out_sig_bt[argc++] = T_INT;
2010         out_sig_bt[argc++] = T_ADDRESS;
2011         Symbol* atype = ss.as_symbol(CHECK_NULL);
2012         const char* at = atype->as_C_string();
2013         if (strlen(at) == 2) {
2014           assert(at[0] == '[', "must be");
2015           switch (at[1]) {
2016             case 'B': in_elem_bt[i]  = T_BYTE; break;
2017             case 'C': in_elem_bt[i]  = T_CHAR; break;
2018             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
2019             case 'F': in_elem_bt[i]  = T_FLOAT; break;
2020             case 'I': in_elem_bt[i]  = T_INT; break;
2021             case 'J': in_elem_bt[i]  = T_LONG; break;
2022             case 'S': in_elem_bt[i]  = T_SHORT; break;
2023             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
2024             default: ShouldNotReachHere();
2025           }
2026         }
2027       } else {
2028         out_sig_bt[argc++] = in_sig_bt[i];
2029         in_elem_bt[i] = T_VOID;
2030       }
2031       if (in_sig_bt[i] != T_VOID) {
2032         assert(in_sig_bt[i] == ss.type(), "must match");
2033         ss.next();
2034       }
2035     }
2036   }
2037 
2038   // Now figure out where the args must be stored and how much stack space
2039   // they require.
2040   int out_arg_slots;
2041   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
2042 
2043   // Compute framesize for the wrapper.  We need to handlize all oops in
2044   // incoming registers
2045 
2046   // Calculate the total number of stack slots we will need.
2047 
2048   // First count the abi requirement plus all of the outgoing args
2049   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
2050 
2051   // Now the space for the inbound oop handle area
2052   int total_save_slots = 6 * VMRegImpl::slots_per_word;  // 6 arguments passed in registers
2053   if (is_critical_native) {
2054     // Critical natives may have to call out so they need a save area
2055     // for register arguments.
2056     int double_slots = 0;
2057     int single_slots = 0;
2058     for ( int i = 0; i < total_in_args; i++) {
2059       if (in_regs[i].first()->is_Register()) {
2060         const Register reg = in_regs[i].first()->as_Register();
2061         switch (in_sig_bt[i]) {
2062           case T_BOOLEAN:
2063           case T_BYTE:
2064           case T_SHORT:
2065           case T_CHAR:
2066           case T_INT:  single_slots++; break;
2067           case T_ARRAY:  // specific to LP64 (7145024)
2068           case T_LONG: double_slots++; break;
2069           default:  ShouldNotReachHere();
2070         }
2071       } else if (in_regs[i].first()->is_XMMRegister()) {
2072         switch (in_sig_bt[i]) {
2073           case T_FLOAT:  single_slots++; break;
2074           case T_DOUBLE: double_slots++; break;
2075           default:  ShouldNotReachHere();
2076         }
2077       } else if (in_regs[i].first()->is_FloatRegister()) {
2078         ShouldNotReachHere();
2079       }
2080     }
2081     total_save_slots = double_slots * 2 + single_slots;
2082     // align the save area
2083     if (double_slots != 0) {
2084       stack_slots = align_up(stack_slots, 2);
2085     }
2086   }
2087 
2088   int oop_handle_offset = stack_slots;
2089   stack_slots += total_save_slots;
2090 
2091   // Now any space we need for handlizing a klass if static method
2092 
2093   int klass_slot_offset = 0;
2094   int klass_offset = -1;
2095   int lock_slot_offset = 0;
2096   bool is_static = false;
2097 
2098   if (method->is_static()) {
2099     klass_slot_offset = stack_slots;
2100     stack_slots += VMRegImpl::slots_per_word;
2101     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
2102     is_static = true;
2103   }
2104 
2105   // Plus a lock if needed
2106 
2107   if (method->is_synchronized()) {
2108     lock_slot_offset = stack_slots;
2109     stack_slots += VMRegImpl::slots_per_word;
2110   }
2111 
2112   // Now a place (+2) to save return values or temp during shuffling
2113   // + 4 for return address (which we own) and saved rbp
2114   stack_slots += 6;
2115 
2116   // Ok The space we have allocated will look like:
2117   //
2118   //
2119   // FP-> |                     |
2120   //      |---------------------|
2121   //      | 2 slots for moves   |
2122   //      |---------------------|
2123   //      | lock box (if sync)  |
2124   //      |---------------------| <- lock_slot_offset
2125   //      | klass (if static)   |
2126   //      |---------------------| <- klass_slot_offset
2127   //      | oopHandle area      |
2128   //      |---------------------| <- oop_handle_offset (6 java arg registers)
2129   //      | outbound memory     |
2130   //      | based arguments     |
2131   //      |                     |
2132   //      |---------------------|
2133   //      |                     |
2134   // SP-> | out_preserved_slots |
2135   //
2136   //
2137 
2138 
2139   // Now compute actual number of stack words we need rounding to make
2140   // stack properly aligned.
2141   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
2142 
2143   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
2144 
2145   // First thing make an ic check to see if we should even be here
2146 
2147   // We are free to use all registers as temps without saving them and
2148   // restoring them except rbp. rbp is the only callee save register
2149   // as far as the interpreter and the compiler(s) are concerned.
2150 
2151 
2152   const Register ic_reg = rax;
2153   const Register receiver = j_rarg0;
2154 
2155   Label hit;
2156   Label exception_pending;
2157 
2158   assert_different_registers(ic_reg, receiver, rscratch1);
2159   __ verify_oop(receiver);
2160   __ load_klass(rscratch1, receiver);
2161   __ cmpq(ic_reg, rscratch1);
2162   __ jcc(Assembler::equal, hit);
2163 
2164   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
2165 
2166   // Verified entry point must be aligned
2167   __ align(8);
2168 
2169   __ bind(hit);
2170 
2171   int vep_offset = ((intptr_t)__ pc()) - start;
2172 
2173 #ifdef COMPILER1
2174   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
2175   if ((InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) || (method->intrinsic_id() == vmIntrinsics::_identityHashCode)) {
2176     inline_check_hashcode_from_object_header(masm, method, j_rarg0 /*obj_reg*/, rax /*result*/);
2177   }
2178 #endif // COMPILER1
2179 
2180   // The instruction at the verified entry point must be 5 bytes or longer
2181   // because it can be patched on the fly by make_non_entrant. The stack bang
2182   // instruction fits that requirement.
2183 
2184   // Generate stack overflow check
2185 
2186   if (UseStackBanging) {
2187     __ bang_stack_with_offset((int)JavaThread::stack_shadow_zone_size());
2188   } else {
2189     // need a 5 byte instruction to allow MT safe patching to non-entrant
2190     __ fat_nop();
2191   }
2192 
2193   // Generate a new frame for the wrapper.
2194   __ enter();
2195   // -2 because return address is already present and so is saved rbp
2196   __ subptr(rsp, stack_size - 2*wordSize);
2197 
2198   // Frame is now completed as far as size and linkage.
2199   int frame_complete = ((intptr_t)__ pc()) - start;
2200 
2201     if (UseRTMLocking) {
2202       // Abort RTM transaction before calling JNI
2203       // because critical section will be large and will be
2204       // aborted anyway. Also nmethod could be deoptimized.
2205       __ xabort(0);
2206     }
2207 
2208 #ifdef ASSERT
2209     {
2210       Label L;
2211       __ mov(rax, rsp);
2212       __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
2213       __ cmpptr(rax, rsp);
2214       __ jcc(Assembler::equal, L);
2215       __ stop("improperly aligned stack");
2216       __ bind(L);
2217     }
2218 #endif /* ASSERT */
2219 
2220 
2221   // We use r14 as the oop handle for the receiver/klass
2222   // It is callee save so it survives the call to native
2223 
2224   const Register oop_handle_reg = r14;
2225 
2226   if (is_critical_native && !Universe::heap()->supports_object_pinning()) {
2227     check_needs_gc_for_critical_native(masm, stack_slots, total_c_args, total_in_args,
2228                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
2229   }
2230 
2231   //
2232   // We immediately shuffle the arguments so that any vm call we have to
2233   // make from here on out (sync slow path, jvmti, etc.) we will have
2234   // captured the oops from our caller and have a valid oopMap for
2235   // them.
2236 
2237   // -----------------
2238   // The Grand Shuffle
2239 
2240   // The Java calling convention is either equal (linux) or denser (win64) than the
2241   // c calling convention. However the because of the jni_env argument the c calling
2242   // convention always has at least one more (and two for static) arguments than Java.
2243   // Therefore if we move the args from java -> c backwards then we will never have
2244   // a register->register conflict and we don't have to build a dependency graph
2245   // and figure out how to break any cycles.
2246   //
2247 
2248   // Record esp-based slot for receiver on stack for non-static methods
2249   int receiver_offset = -1;
2250 
2251   // This is a trick. We double the stack slots so we can claim
2252   // the oops in the caller's frame. Since we are sure to have
2253   // more args than the caller doubling is enough to make
2254   // sure we can capture all the incoming oop args from the
2255   // caller.
2256   //
2257   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
2258 
2259   // Mark location of rbp (someday)
2260   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rbp));
2261 
2262   // Use eax, ebx as temporaries during any memory-memory moves we have to do
2263   // All inbound args are referenced based on rbp and all outbound args via rsp.
2264 
2265 
2266 #ifdef ASSERT
2267   bool reg_destroyed[RegisterImpl::number_of_registers];
2268   bool freg_destroyed[XMMRegisterImpl::number_of_registers];
2269   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
2270     reg_destroyed[r] = false;
2271   }
2272   for ( int f = 0 ; f < XMMRegisterImpl::number_of_registers ; f++ ) {
2273     freg_destroyed[f] = false;
2274   }
2275 
2276 #endif /* ASSERT */
2277 
2278   // This may iterate in two different directions depending on the
2279   // kind of native it is.  The reason is that for regular JNI natives
2280   // the incoming and outgoing registers are offset upwards and for
2281   // critical natives they are offset down.
2282   GrowableArray<int> arg_order(2 * total_in_args);
2283   // Inbound arguments that need to be pinned for critical natives
2284   GrowableArray<int> pinned_args(total_in_args);
2285   // Current stack slot for storing register based array argument
2286   int pinned_slot = oop_handle_offset;
2287 
2288   VMRegPair tmp_vmreg;
2289   tmp_vmreg.set2(rbx->as_VMReg());
2290 
2291   if (!is_critical_native) {
2292     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
2293       arg_order.push(i);
2294       arg_order.push(c_arg);
2295     }
2296   } else {
2297     // Compute a valid move order, using tmp_vmreg to break any cycles
2298     ComputeMoveOrder cmo(total_in_args, in_regs, total_c_args, out_regs, in_sig_bt, arg_order, tmp_vmreg);
2299   }
2300 
2301   int temploc = -1;
2302   for (int ai = 0; ai < arg_order.length(); ai += 2) {
2303     int i = arg_order.at(ai);
2304     int c_arg = arg_order.at(ai + 1);
2305     __ block_comment(err_msg("move %d -> %d", i, c_arg));
2306     if (c_arg == -1) {
2307       assert(is_critical_native, "should only be required for critical natives");
2308       // This arg needs to be moved to a temporary
2309       __ mov(tmp_vmreg.first()->as_Register(), in_regs[i].first()->as_Register());
2310       in_regs[i] = tmp_vmreg;
2311       temploc = i;
2312       continue;
2313     } else if (i == -1) {
2314       assert(is_critical_native, "should only be required for critical natives");
2315       // Read from the temporary location
2316       assert(temploc != -1, "must be valid");
2317       i = temploc;
2318       temploc = -1;
2319     }
2320 #ifdef ASSERT
2321     if (in_regs[i].first()->is_Register()) {
2322       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
2323     } else if (in_regs[i].first()->is_XMMRegister()) {
2324       assert(!freg_destroyed[in_regs[i].first()->as_XMMRegister()->encoding()], "destroyed reg!");
2325     }
2326     if (out_regs[c_arg].first()->is_Register()) {
2327       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2328     } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2329       freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2330     }
2331 #endif /* ASSERT */
2332     switch (in_sig_bt[i]) {
2333       case T_ARRAY:
2334         if (is_critical_native) {
2335           // pin before unpack
2336           if (Universe::heap()->supports_object_pinning()) {
2337             assert(pinned_slot <= stack_slots, "overflow");
2338             pin_critical_native_array(masm, in_regs[i], pinned_slot);
2339             pinned_args.append(i);
2340           }
2341           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
2342           c_arg++;
2343 #ifdef ASSERT
2344           if (out_regs[c_arg].first()->is_Register()) {
2345             reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2346           } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2347             freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2348           }
2349 #endif
2350           break;
2351         }
2352       case T_OBJECT:
2353         assert(!is_critical_native, "no oop arguments");
2354         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
2355                     ((i == 0) && (!is_static)),
2356                     &receiver_offset);
2357         break;
2358       case T_VOID:
2359         break;
2360 
2361       case T_FLOAT:
2362         float_move(masm, in_regs[i], out_regs[c_arg]);
2363           break;
2364 
2365       case T_DOUBLE:
2366         assert( i + 1 < total_in_args &&
2367                 in_sig_bt[i + 1] == T_VOID &&
2368                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
2369         double_move(masm, in_regs[i], out_regs[c_arg]);
2370         break;
2371 
2372       case T_LONG :
2373         long_move(masm, in_regs[i], out_regs[c_arg]);
2374         break;
2375 
2376       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
2377 
2378       default:
2379         move32_64(masm, in_regs[i], out_regs[c_arg]);
2380     }
2381   }
2382 
2383   int c_arg;
2384 
2385   // Pre-load a static method's oop into r14.  Used both by locking code and
2386   // the normal JNI call code.
2387   if (!is_critical_native) {
2388     // point c_arg at the first arg that is already loaded in case we
2389     // need to spill before we call out
2390     c_arg = total_c_args - total_in_args;
2391 
2392     if (method->is_static()) {
2393 
2394       //  load oop into a register
2395       __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
2396 
2397       // Now handlize the static class mirror it's known not-null.
2398       __ movptr(Address(rsp, klass_offset), oop_handle_reg);
2399       map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
2400 
2401       // Now get the handle
2402       __ lea(oop_handle_reg, Address(rsp, klass_offset));
2403       // store the klass handle as second argument
2404       __ movptr(c_rarg1, oop_handle_reg);
2405       // and protect the arg if we must spill
2406       c_arg--;
2407     }
2408   } else {
2409     // For JNI critical methods we need to save all registers in save_args.
2410     c_arg = 0;
2411   }
2412 
2413   // Change state to native (we save the return address in the thread, since it might not
2414   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
2415   // points into the right code segment. It does not have to be the correct return pc.
2416   // We use the same pc/oopMap repeatedly when we call out
2417 
2418   intptr_t the_pc = (intptr_t) __ pc();
2419   oop_maps->add_gc_map(the_pc - start, map);
2420 
2421   __ set_last_Java_frame(rsp, noreg, (address)the_pc);
2422 
2423 
2424   // We have all of the arguments setup at this point. We must not touch any register
2425   // argument registers at this point (what if we save/restore them there are no oop?
2426 
2427   {
2428     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2429     // protect the args we've loaded
2430     save_args(masm, total_c_args, c_arg, out_regs);
2431     __ mov_metadata(c_rarg1, method());
2432     __ call_VM_leaf(
2433       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2434       r15_thread, c_rarg1);
2435     restore_args(masm, total_c_args, c_arg, out_regs);
2436   }
2437 
2438   // RedefineClasses() tracing support for obsolete method entry
2439   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2440     // protect the args we've loaded
2441     save_args(masm, total_c_args, c_arg, out_regs);
2442     __ mov_metadata(c_rarg1, method());
2443     __ call_VM_leaf(
2444       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2445       r15_thread, c_rarg1);
2446     restore_args(masm, total_c_args, c_arg, out_regs);
2447   }
2448 
2449   // Lock a synchronized method
2450 
2451   // Register definitions used by locking and unlocking
2452 
2453   const Register swap_reg = rax;  // Must use rax for cmpxchg instruction
2454   const Register obj_reg  = rbx;  // Will contain the oop
2455   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
2456   const Register old_hdr  = r13;  // value of old header at unlock time
2457 
2458   Label slow_path_lock;
2459   Label lock_done;
2460 
2461   if (method->is_synchronized()) {
2462     assert(!is_critical_native, "unhandled");
2463 
2464 
2465     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2466 
2467     // Get the handle (the 2nd argument)
2468     __ mov(oop_handle_reg, c_rarg1);
2469 
2470     // Get address of the box
2471 
2472     __ lea(lock_reg, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2473 
2474     // Load the oop from the handle
2475     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2476 
2477     if (UseBiasedLocking) {
2478       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, rscratch1, false, lock_done, &slow_path_lock);
2479     }
2480 
2481     // Load immediate 1 into swap_reg %rax
2482     __ movl(swap_reg, 1);
2483 
2484     // Load (object->mark() | 1) into swap_reg %rax
2485     __ orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2486 
2487     // Save (object->mark() | 1) into BasicLock's displaced header
2488     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2489 
2490     if (os::is_MP()) {
2491       __ lock();
2492     }
2493 
2494     // src -> dest iff dest == rax else rax <- dest
2495     __ cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2496     __ jcc(Assembler::equal, lock_done);
2497 
2498     // Hmm should this move to the slow path code area???
2499 
2500     // Test if the oopMark is an obvious stack pointer, i.e.,
2501     //  1) (mark & 3) == 0, and
2502     //  2) rsp <= mark < mark + os::pagesize()
2503     // These 3 tests can be done by evaluating the following
2504     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2505     // assuming both stack pointer and pagesize have their
2506     // least significant 2 bits clear.
2507     // NOTE: the oopMark is in swap_reg %rax as the result of cmpxchg
2508 
2509     __ subptr(swap_reg, rsp);
2510     __ andptr(swap_reg, 3 - os::vm_page_size());
2511 
2512     // Save the test result, for recursive case, the result is zero
2513     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2514     __ jcc(Assembler::notEqual, slow_path_lock);
2515 
2516     // Slow path will re-enter here
2517 
2518     __ bind(lock_done);
2519   }
2520 
2521 
2522   // Finally just about ready to make the JNI call
2523 
2524 
2525   // get JNIEnv* which is first argument to native
2526   if (!is_critical_native) {
2527     __ lea(c_rarg0, Address(r15_thread, in_bytes(JavaThread::jni_environment_offset())));
2528   }
2529 
2530   // Now set thread in native
2531   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native);
2532 
2533   __ call(RuntimeAddress(native_func));
2534 
2535   // Verify or restore cpu control state after JNI call
2536   __ restore_cpu_control_state_after_jni();
2537 
2538   // Unpack native results.
2539   switch (ret_type) {
2540   case T_BOOLEAN: __ c2bool(rax);            break;
2541   case T_CHAR   : __ movzwl(rax, rax);      break;
2542   case T_BYTE   : __ sign_extend_byte (rax); break;
2543   case T_SHORT  : __ sign_extend_short(rax); break;
2544   case T_INT    : /* nothing to do */        break;
2545   case T_DOUBLE :
2546   case T_FLOAT  :
2547     // Result is in xmm0 we'll save as needed
2548     break;
2549   case T_ARRAY:                 // Really a handle
2550   case T_OBJECT:                // Really a handle
2551       break; // can't de-handlize until after safepoint check
2552   case T_VOID: break;
2553   case T_LONG: break;
2554   default       : ShouldNotReachHere();
2555   }
2556 
2557   // unpin pinned arguments
2558   pinned_slot = oop_handle_offset;
2559   if (pinned_args.length() > 0) {
2560     // save return value that may be overwritten otherwise.
2561     save_native_result(masm, ret_type, stack_slots);
2562     for (int index = 0; index < pinned_args.length(); index ++) {
2563       int i = pinned_args.at(index);
2564       assert(pinned_slot <= stack_slots, "overflow");
2565       unpin_critical_native_array(masm, in_regs[i], pinned_slot);
2566     }
2567     restore_native_result(masm, ret_type, stack_slots);
2568   }
2569 
2570   // Switch thread to "native transition" state before reading the synchronization state.
2571   // This additional state is necessary because reading and testing the synchronization
2572   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2573   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2574   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2575   //     Thread A is resumed to finish this native method, but doesn't block here since it
2576   //     didn't see any synchronization is progress, and escapes.
2577   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2578 
2579   if(os::is_MP()) {
2580     if (UseMembar) {
2581       // Force this write out before the read below
2582       __ membar(Assembler::Membar_mask_bits(
2583            Assembler::LoadLoad | Assembler::LoadStore |
2584            Assembler::StoreLoad | Assembler::StoreStore));
2585     } else {
2586       // Write serialization page so VM thread can do a pseudo remote membar.
2587       // We use the current thread pointer to calculate a thread specific
2588       // offset to write to within the page. This minimizes bus traffic
2589       // due to cache line collision.
2590       __ serialize_memory(r15_thread, rcx);
2591     }
2592   }
2593 
2594   Label after_transition;
2595 
2596   // check for safepoint operation in progress and/or pending suspend requests
2597   {
2598     Label Continue;
2599     Label slow_path;
2600 
2601     __ safepoint_poll(slow_path, r15_thread, rscratch1);
2602 
2603     __ cmpl(Address(r15_thread, JavaThread::suspend_flags_offset()), 0);
2604     __ jcc(Assembler::equal, Continue);
2605     __ bind(slow_path);
2606 
2607     // Don't use call_VM as it will see a possible pending exception and forward it
2608     // and never return here preventing us from clearing _last_native_pc down below.
2609     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2610     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2611     // by hand.
2612     //
2613     __ vzeroupper();
2614     save_native_result(masm, ret_type, stack_slots);
2615     __ mov(c_rarg0, r15_thread);
2616     __ mov(r12, rsp); // remember sp
2617     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2618     __ andptr(rsp, -16); // align stack as required by ABI
2619     if (!is_critical_native) {
2620       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2621     } else {
2622       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)));
2623     }
2624     __ mov(rsp, r12); // restore sp
2625     __ reinit_heapbase();
2626     // Restore any method result value
2627     restore_native_result(masm, ret_type, stack_slots);
2628 
2629     if (is_critical_native) {
2630       // The call above performed the transition to thread_in_Java so
2631       // skip the transition logic below.
2632       __ jmpb(after_transition);
2633     }
2634 
2635     __ bind(Continue);
2636   }
2637 
2638   // change thread state
2639   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_Java);
2640   __ bind(after_transition);
2641 
2642   Label reguard;
2643   Label reguard_done;
2644   __ cmpl(Address(r15_thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_reserved_disabled);
2645   __ jcc(Assembler::equal, reguard);
2646   __ bind(reguard_done);
2647 
2648   // native result if any is live
2649 
2650   // Unlock
2651   Label unlock_done;
2652   Label slow_path_unlock;
2653   if (method->is_synchronized()) {
2654 
2655     // Get locked oop from the handle we passed to jni
2656     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2657 
2658     Label done;
2659 
2660     if (UseBiasedLocking) {
2661       __ biased_locking_exit(obj_reg, old_hdr, done);
2662     }
2663 
2664     // Simple recursive lock?
2665 
2666     __ cmpptr(Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size), (int32_t)NULL_WORD);
2667     __ jcc(Assembler::equal, done);
2668 
2669     // Must save rax if if it is live now because cmpxchg must use it
2670     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2671       save_native_result(masm, ret_type, stack_slots);
2672     }
2673 
2674 
2675     // get address of the stack lock
2676     __ lea(rax, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2677     //  get old displaced header
2678     __ movptr(old_hdr, Address(rax, 0));
2679 
2680     // Atomic swap old header if oop still contains the stack lock
2681     if (os::is_MP()) {
2682       __ lock();
2683     }
2684     __ cmpxchgptr(old_hdr, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2685     __ jcc(Assembler::notEqual, slow_path_unlock);
2686 
2687     // slow path re-enters here
2688     __ bind(unlock_done);
2689     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2690       restore_native_result(masm, ret_type, stack_slots);
2691     }
2692 
2693     __ bind(done);
2694 
2695   }
2696   {
2697     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2698     save_native_result(masm, ret_type, stack_slots);
2699     __ mov_metadata(c_rarg1, method());
2700     __ call_VM_leaf(
2701          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2702          r15_thread, c_rarg1);
2703     restore_native_result(masm, ret_type, stack_slots);
2704   }
2705 
2706   __ reset_last_Java_frame(false);
2707 
2708   // Unbox oop result, e.g. JNIHandles::resolve value.
2709   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2710     __ resolve_jobject(rax /* value */,
2711                        r15_thread /* thread */,
2712                        rcx /* tmp */);
2713   }
2714 
2715   if (CheckJNICalls) {
2716     // clear_pending_jni_exception_check
2717     __ movptr(Address(r15_thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
2718   }
2719 
2720   if (!is_critical_native) {
2721     // reset handle block
2722     __ movptr(rcx, Address(r15_thread, JavaThread::active_handles_offset()));
2723     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), (int32_t)NULL_WORD);
2724   }
2725 
2726   // pop our frame
2727 
2728   __ leave();
2729 
2730   if (!is_critical_native) {
2731     // Any exception pending?
2732     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2733     __ jcc(Assembler::notEqual, exception_pending);
2734   }
2735 
2736   // Return
2737 
2738   __ ret(0);
2739 
2740   // Unexpected paths are out of line and go here
2741 
2742   if (!is_critical_native) {
2743     // forward the exception
2744     __ bind(exception_pending);
2745 
2746     // and forward the exception
2747     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2748   }
2749 
2750   // Slow path locking & unlocking
2751   if (method->is_synchronized()) {
2752 
2753     // BEGIN Slow path lock
2754     __ bind(slow_path_lock);
2755 
2756     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2757     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2758 
2759     // protect the args we've loaded
2760     save_args(masm, total_c_args, c_arg, out_regs);
2761 
2762     __ mov(c_rarg0, obj_reg);
2763     __ mov(c_rarg1, lock_reg);
2764     __ mov(c_rarg2, r15_thread);
2765 
2766     // Not a leaf but we have last_Java_frame setup as we want
2767     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2768     restore_args(masm, total_c_args, c_arg, out_regs);
2769 
2770 #ifdef ASSERT
2771     { Label L;
2772     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2773     __ jcc(Assembler::equal, L);
2774     __ stop("no pending exception allowed on exit from monitorenter");
2775     __ bind(L);
2776     }
2777 #endif
2778     __ jmp(lock_done);
2779 
2780     // END Slow path lock
2781 
2782     // BEGIN Slow path unlock
2783     __ bind(slow_path_unlock);
2784 
2785     // If we haven't already saved the native result we must save it now as xmm registers
2786     // are still exposed.
2787     __ vzeroupper();
2788     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2789       save_native_result(masm, ret_type, stack_slots);
2790     }
2791 
2792     __ lea(c_rarg1, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2793 
2794     __ mov(c_rarg0, obj_reg);
2795     __ mov(c_rarg2, r15_thread);
2796     __ mov(r12, rsp); // remember sp
2797     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2798     __ andptr(rsp, -16); // align stack as required by ABI
2799 
2800     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2801     // NOTE that obj_reg == rbx currently
2802     __ movptr(rbx, Address(r15_thread, in_bytes(Thread::pending_exception_offset())));
2803     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2804 
2805     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2806     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2807     __ mov(rsp, r12); // restore sp
2808     __ reinit_heapbase();
2809 #ifdef ASSERT
2810     {
2811       Label L;
2812       __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2813       __ jcc(Assembler::equal, L);
2814       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2815       __ bind(L);
2816     }
2817 #endif /* ASSERT */
2818 
2819     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), rbx);
2820 
2821     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2822       restore_native_result(masm, ret_type, stack_slots);
2823     }
2824     __ jmp(unlock_done);
2825 
2826     // END Slow path unlock
2827 
2828   } // synchronized
2829 
2830   // SLOW PATH Reguard the stack if needed
2831 
2832   __ bind(reguard);
2833   __ vzeroupper();
2834   save_native_result(masm, ret_type, stack_slots);
2835   __ mov(r12, rsp); // remember sp
2836   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2837   __ andptr(rsp, -16); // align stack as required by ABI
2838   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2839   __ mov(rsp, r12); // restore sp
2840   __ reinit_heapbase();
2841   restore_native_result(masm, ret_type, stack_slots);
2842   // and continue
2843   __ jmp(reguard_done);
2844 
2845 
2846 
2847   __ flush();
2848 
2849   nmethod *nm = nmethod::new_native_nmethod(method,
2850                                             compile_id,
2851                                             masm->code(),
2852                                             vep_offset,
2853                                             frame_complete,
2854                                             stack_slots / VMRegImpl::slots_per_word,
2855                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2856                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2857                                             oop_maps);
2858 
2859   if (is_critical_native) {
2860     nm->set_lazy_critical_native(true);
2861   }
2862 
2863   return nm;
2864 
2865 }
2866 
2867 // this function returns the adjust size (in number of words) to a c2i adapter
2868 // activation for use during deoptimization
2869 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2870   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2871 }
2872 
2873 
2874 uint SharedRuntime::out_preserve_stack_slots() {
2875   return 0;
2876 }
2877 
2878 //------------------------------generate_deopt_blob----------------------------
2879 void SharedRuntime::generate_deopt_blob() {
2880   // Allocate space for the code
2881   ResourceMark rm;
2882   // Setup code generation tools
2883   int pad = 0;
2884 #if INCLUDE_JVMCI
2885   if (EnableJVMCI || UseAOT) {
2886     pad += 512; // Increase the buffer size when compiling for JVMCI
2887   }
2888 #endif
2889   CodeBuffer buffer("deopt_blob", 2048+pad, 1024);
2890   MacroAssembler* masm = new MacroAssembler(&buffer);
2891   int frame_size_in_words;
2892   OopMap* map = NULL;
2893   OopMapSet *oop_maps = new OopMapSet();
2894 
2895   // -------------
2896   // This code enters when returning to a de-optimized nmethod.  A return
2897   // address has been pushed on the the stack, and return values are in
2898   // registers.
2899   // If we are doing a normal deopt then we were called from the patched
2900   // nmethod from the point we returned to the nmethod. So the return
2901   // address on the stack is wrong by NativeCall::instruction_size
2902   // We will adjust the value so it looks like we have the original return
2903   // address on the stack (like when we eagerly deoptimized).
2904   // In the case of an exception pending when deoptimizing, we enter
2905   // with a return address on the stack that points after the call we patched
2906   // into the exception handler. We have the following register state from,
2907   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2908   //    rax: exception oop
2909   //    rbx: exception handler
2910   //    rdx: throwing pc
2911   // So in this case we simply jam rdx into the useless return address and
2912   // the stack looks just like we want.
2913   //
2914   // At this point we need to de-opt.  We save the argument return
2915   // registers.  We call the first C routine, fetch_unroll_info().  This
2916   // routine captures the return values and returns a structure which
2917   // describes the current frame size and the sizes of all replacement frames.
2918   // The current frame is compiled code and may contain many inlined
2919   // functions, each with their own JVM state.  We pop the current frame, then
2920   // push all the new frames.  Then we call the C routine unpack_frames() to
2921   // populate these frames.  Finally unpack_frames() returns us the new target
2922   // address.  Notice that callee-save registers are BLOWN here; they have
2923   // already been captured in the vframeArray at the time the return PC was
2924   // patched.
2925   address start = __ pc();
2926   Label cont;
2927 
2928   // Prolog for non exception case!
2929 
2930   // Save everything in sight.
2931   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2932 
2933   // Normal deoptimization.  Save exec mode for unpack_frames.
2934   __ movl(r14, Deoptimization::Unpack_deopt); // callee-saved
2935   __ jmp(cont);
2936 
2937   int reexecute_offset = __ pc() - start;
2938 #if INCLUDE_JVMCI && !defined(COMPILER1)
2939   if (EnableJVMCI && UseJVMCICompiler) {
2940     // JVMCI does not use this kind of deoptimization
2941     __ should_not_reach_here();
2942   }
2943 #endif
2944 
2945   // Reexecute case
2946   // return address is the pc describes what bci to do re-execute at
2947 
2948   // No need to update map as each call to save_live_registers will produce identical oopmap
2949   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2950 
2951   __ movl(r14, Deoptimization::Unpack_reexecute); // callee-saved
2952   __ jmp(cont);
2953 
2954 #if INCLUDE_JVMCI
2955   Label after_fetch_unroll_info_call;
2956   int implicit_exception_uncommon_trap_offset = 0;
2957   int uncommon_trap_offset = 0;
2958 
2959   if (EnableJVMCI || UseAOT) {
2960     implicit_exception_uncommon_trap_offset = __ pc() - start;
2961 
2962     __ pushptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2963     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())), (int32_t)NULL_WORD);
2964 
2965     uncommon_trap_offset = __ pc() - start;
2966 
2967     // Save everything in sight.
2968     RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2969     // fetch_unroll_info needs to call last_java_frame()
2970     __ set_last_Java_frame(noreg, noreg, NULL);
2971 
2972     __ movl(c_rarg1, Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())));
2973     __ movl(Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())), -1);
2974 
2975     __ movl(r14, (int32_t)Deoptimization::Unpack_reexecute);
2976     __ mov(c_rarg0, r15_thread);
2977     __ movl(c_rarg2, r14); // exec mode
2978     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2979     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2980 
2981     __ reset_last_Java_frame(false);
2982 
2983     __ jmp(after_fetch_unroll_info_call);
2984   } // EnableJVMCI
2985 #endif // INCLUDE_JVMCI
2986 
2987   int exception_offset = __ pc() - start;
2988 
2989   // Prolog for exception case
2990 
2991   // all registers are dead at this entry point, except for rax, and
2992   // rdx which contain the exception oop and exception pc
2993   // respectively.  Set them in TLS and fall thru to the
2994   // unpack_with_exception_in_tls entry point.
2995 
2996   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
2997   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), rax);
2998 
2999   int exception_in_tls_offset = __ pc() - start;
3000 
3001   // new implementation because exception oop is now passed in JavaThread
3002 
3003   // Prolog for exception case
3004   // All registers must be preserved because they might be used by LinearScan
3005   // Exceptiop oop and throwing PC are passed in JavaThread
3006   // tos: stack at point of call to method that threw the exception (i.e. only
3007   // args are on the stack, no return address)
3008 
3009   // make room on stack for the return address
3010   // It will be patched later with the throwing pc. The correct value is not
3011   // available now because loading it from memory would destroy registers.
3012   __ push(0);
3013 
3014   // Save everything in sight.
3015   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3016 
3017   // Now it is safe to overwrite any register
3018 
3019   // Deopt during an exception.  Save exec mode for unpack_frames.
3020   __ movl(r14, Deoptimization::Unpack_exception); // callee-saved
3021 
3022   // load throwing pc from JavaThread and patch it as the return address
3023   // of the current frame. Then clear the field in JavaThread
3024 
3025   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3026   __ movptr(Address(rbp, wordSize), rdx);
3027   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
3028 
3029 #ifdef ASSERT
3030   // verify that there is really an exception oop in JavaThread
3031   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3032   __ verify_oop(rax);
3033 
3034   // verify that there is no pending exception
3035   Label no_pending_exception;
3036   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
3037   __ testptr(rax, rax);
3038   __ jcc(Assembler::zero, no_pending_exception);
3039   __ stop("must not have pending exception here");
3040   __ bind(no_pending_exception);
3041 #endif
3042 
3043   __ bind(cont);
3044 
3045   // Call C code.  Need thread and this frame, but NOT official VM entry
3046   // crud.  We cannot block on this call, no GC can happen.
3047   //
3048   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
3049 
3050   // fetch_unroll_info needs to call last_java_frame().
3051 
3052   __ set_last_Java_frame(noreg, noreg, NULL);
3053 #ifdef ASSERT
3054   { Label L;
3055     __ cmpptr(Address(r15_thread,
3056                     JavaThread::last_Java_fp_offset()),
3057             (int32_t)0);
3058     __ jcc(Assembler::equal, L);
3059     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
3060     __ bind(L);
3061   }
3062 #endif // ASSERT
3063   __ mov(c_rarg0, r15_thread);
3064   __ movl(c_rarg1, r14); // exec_mode
3065   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
3066 
3067   // Need to have an oopmap that tells fetch_unroll_info where to
3068   // find any register it might need.
3069   oop_maps->add_gc_map(__ pc() - start, map);
3070 
3071   __ reset_last_Java_frame(false);
3072 
3073 #if INCLUDE_JVMCI
3074   if (EnableJVMCI || UseAOT) {
3075     __ bind(after_fetch_unroll_info_call);
3076   }
3077 #endif
3078 
3079   // Load UnrollBlock* into rdi
3080   __ mov(rdi, rax);
3081 
3082   __ movl(r14, Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
3083    Label noException;
3084   __ cmpl(r14, Deoptimization::Unpack_exception);   // Was exception pending?
3085   __ jcc(Assembler::notEqual, noException);
3086   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3087   // QQQ this is useless it was NULL above
3088   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3089   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int32_t)NULL_WORD);
3090   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
3091 
3092   __ verify_oop(rax);
3093 
3094   // Overwrite the result registers with the exception results.
3095   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3096   // I think this is useless
3097   __ movptr(Address(rsp, RegisterSaver::rdx_offset_in_bytes()), rdx);
3098 
3099   __ bind(noException);
3100 
3101   // Only register save data is on the stack.
3102   // Now restore the result registers.  Everything else is either dead
3103   // or captured in the vframeArray.
3104   RegisterSaver::restore_result_registers(masm);
3105 
3106   // All of the register save area has been popped of the stack. Only the
3107   // return address remains.
3108 
3109   // Pop all the frames we must move/replace.
3110   //
3111   // Frame picture (youngest to oldest)
3112   // 1: self-frame (no frame link)
3113   // 2: deopting frame  (no frame link)
3114   // 3: caller of deopting frame (could be compiled/interpreted).
3115   //
3116   // Note: by leaving the return address of self-frame on the stack
3117   // and using the size of frame 2 to adjust the stack
3118   // when we are done the return to frame 3 will still be on the stack.
3119 
3120   // Pop deoptimized frame
3121   __ movl(rcx, Address(rdi, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
3122   __ addptr(rsp, rcx);
3123 
3124   // rsp should be pointing at the return address to the caller (3)
3125 
3126   // Pick up the initial fp we should save
3127   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
3128   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
3129 
3130 #ifdef ASSERT
3131   // Compilers generate code that bang the stack by as much as the
3132   // interpreter would need. So this stack banging should never
3133   // trigger a fault. Verify that it does not on non product builds.
3134   if (UseStackBanging) {
3135     __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
3136     __ bang_stack_size(rbx, rcx);
3137   }
3138 #endif
3139 
3140   // Load address of array of frame pcs into rcx
3141   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3142 
3143   // Trash the old pc
3144   __ addptr(rsp, wordSize);
3145 
3146   // Load address of array of frame sizes into rsi
3147   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
3148 
3149   // Load counter into rdx
3150   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
3151 
3152   // Now adjust the caller's stack to make up for the extra locals
3153   // but record the original sp so that we can save it in the skeletal interpreter
3154   // frame and the stack walking of interpreter_sender will get the unextended sp
3155   // value and not the "real" sp value.
3156 
3157   const Register sender_sp = r8;
3158 
3159   __ mov(sender_sp, rsp);
3160   __ movl(rbx, Address(rdi,
3161                        Deoptimization::UnrollBlock::
3162                        caller_adjustment_offset_in_bytes()));
3163   __ subptr(rsp, rbx);
3164 
3165   // Push interpreter frames in a loop
3166   Label loop;
3167   __ bind(loop);
3168   __ movptr(rbx, Address(rsi, 0));      // Load frame size
3169   __ subptr(rbx, 2*wordSize);           // We'll push pc and ebp by hand
3170   __ pushptr(Address(rcx, 0));          // Save return address
3171   __ enter();                           // Save old & set new ebp
3172   __ subptr(rsp, rbx);                  // Prolog
3173   // This value is corrected by layout_activation_impl
3174   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3175   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), sender_sp); // Make it walkable
3176   __ mov(sender_sp, rsp);               // Pass sender_sp to next frame
3177   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
3178   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
3179   __ decrementl(rdx);                   // Decrement counter
3180   __ jcc(Assembler::notZero, loop);
3181   __ pushptr(Address(rcx, 0));          // Save final return address
3182 
3183   // Re-push self-frame
3184   __ enter();                           // Save old & set new ebp
3185 
3186   // Allocate a full sized register save area.
3187   // Return address and rbp are in place, so we allocate two less words.
3188   __ subptr(rsp, (frame_size_in_words - 2) * wordSize);
3189 
3190   // Restore frame locals after moving the frame
3191   __ movdbl(Address(rsp, RegisterSaver::xmm0_offset_in_bytes()), xmm0);
3192   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3193 
3194   // Call C code.  Need thread but NOT official VM entry
3195   // crud.  We cannot block on this call, no GC can happen.  Call should
3196   // restore return values to their stack-slots with the new SP.
3197   //
3198   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
3199 
3200   // Use rbp because the frames look interpreted now
3201   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3202   // Don't need the precise return PC here, just precise enough to point into this code blob.
3203   address the_pc = __ pc();
3204   __ set_last_Java_frame(noreg, rbp, the_pc);
3205 
3206   __ andptr(rsp, -(StackAlignmentInBytes));  // Fix stack alignment as required by ABI
3207   __ mov(c_rarg0, r15_thread);
3208   __ movl(c_rarg1, r14); // second arg: exec_mode
3209   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3210   // Revert SP alignment after call since we're going to do some SP relative addressing below
3211   __ movptr(rsp, Address(r15_thread, JavaThread::last_Java_sp_offset()));
3212 
3213   // Set an oopmap for the call site
3214   // Use the same PC we used for the last java frame
3215   oop_maps->add_gc_map(the_pc - start,
3216                        new OopMap( frame_size_in_words, 0 ));
3217 
3218   // Clear fp AND pc
3219   __ reset_last_Java_frame(true);
3220 
3221   // Collect return values
3222   __ movdbl(xmm0, Address(rsp, RegisterSaver::xmm0_offset_in_bytes()));
3223   __ movptr(rax, Address(rsp, RegisterSaver::rax_offset_in_bytes()));
3224   // I think this is useless (throwing pc?)
3225   __ movptr(rdx, Address(rsp, RegisterSaver::rdx_offset_in_bytes()));
3226 
3227   // Pop self-frame.
3228   __ leave();                           // Epilog
3229 
3230   // Jump to interpreter
3231   __ ret(0);
3232 
3233   // Make sure all code is generated
3234   masm->flush();
3235 
3236   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
3237   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
3238 #if INCLUDE_JVMCI
3239   if (EnableJVMCI || UseAOT) {
3240     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
3241     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
3242   }
3243 #endif
3244 }
3245 
3246 #ifdef COMPILER2
3247 //------------------------------generate_uncommon_trap_blob--------------------
3248 void SharedRuntime::generate_uncommon_trap_blob() {
3249   // Allocate space for the code
3250   ResourceMark rm;
3251   // Setup code generation tools
3252   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
3253   MacroAssembler* masm = new MacroAssembler(&buffer);
3254 
3255   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3256 
3257   address start = __ pc();
3258 
3259   if (UseRTMLocking) {
3260     // Abort RTM transaction before possible nmethod deoptimization.
3261     __ xabort(0);
3262   }
3263 
3264   // Push self-frame.  We get here with a return address on the
3265   // stack, so rsp is 8-byte aligned until we allocate our frame.
3266   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
3267 
3268   // No callee saved registers. rbp is assumed implicitly saved
3269   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3270 
3271   // compiler left unloaded_class_index in j_rarg0 move to where the
3272   // runtime expects it.
3273   __ movl(c_rarg1, j_rarg0);
3274 
3275   __ set_last_Java_frame(noreg, noreg, NULL);
3276 
3277   // Call C code.  Need thread but NOT official VM entry
3278   // crud.  We cannot block on this call, no GC can happen.  Call should
3279   // capture callee-saved registers as well as return values.
3280   // Thread is in rdi already.
3281   //
3282   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
3283 
3284   __ mov(c_rarg0, r15_thread);
3285   __ movl(c_rarg2, Deoptimization::Unpack_uncommon_trap);
3286   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
3287 
3288   // Set an oopmap for the call site
3289   OopMapSet* oop_maps = new OopMapSet();
3290   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
3291 
3292   // location of rbp is known implicitly by the frame sender code
3293 
3294   oop_maps->add_gc_map(__ pc() - start, map);
3295 
3296   __ reset_last_Java_frame(false);
3297 
3298   // Load UnrollBlock* into rdi
3299   __ mov(rdi, rax);
3300 
3301 #ifdef ASSERT
3302   { Label L;
3303     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
3304             (int32_t)Deoptimization::Unpack_uncommon_trap);
3305     __ jcc(Assembler::equal, L);
3306     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
3307     __ bind(L);
3308   }
3309 #endif
3310 
3311   // Pop all the frames we must move/replace.
3312   //
3313   // Frame picture (youngest to oldest)
3314   // 1: self-frame (no frame link)
3315   // 2: deopting frame  (no frame link)
3316   // 3: caller of deopting frame (could be compiled/interpreted).
3317 
3318   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
3319   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
3320 
3321   // Pop deoptimized frame (int)
3322   __ movl(rcx, Address(rdi,
3323                        Deoptimization::UnrollBlock::
3324                        size_of_deoptimized_frame_offset_in_bytes()));
3325   __ addptr(rsp, rcx);
3326 
3327   // rsp should be pointing at the return address to the caller (3)
3328 
3329   // Pick up the initial fp we should save
3330   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
3331   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
3332 
3333 #ifdef ASSERT
3334   // Compilers generate code that bang the stack by as much as the
3335   // interpreter would need. So this stack banging should never
3336   // trigger a fault. Verify that it does not on non product builds.
3337   if (UseStackBanging) {
3338     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
3339     __ bang_stack_size(rbx, rcx);
3340   }
3341 #endif
3342 
3343   // Load address of array of frame pcs into rcx (address*)
3344   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3345 
3346   // Trash the return pc
3347   __ addptr(rsp, wordSize);
3348 
3349   // Load address of array of frame sizes into rsi (intptr_t*)
3350   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock:: frame_sizes_offset_in_bytes()));
3351 
3352   // Counter
3353   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock:: number_of_frames_offset_in_bytes())); // (int)
3354 
3355   // Now adjust the caller's stack to make up for the extra locals but
3356   // record the original sp so that we can save it in the skeletal
3357   // interpreter frame and the stack walking of interpreter_sender
3358   // will get the unextended sp value and not the "real" sp value.
3359 
3360   const Register sender_sp = r8;
3361 
3362   __ mov(sender_sp, rsp);
3363   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock:: caller_adjustment_offset_in_bytes())); // (int)
3364   __ subptr(rsp, rbx);
3365 
3366   // Push interpreter frames in a loop
3367   Label loop;
3368   __ bind(loop);
3369   __ movptr(rbx, Address(rsi, 0)); // Load frame size
3370   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
3371   __ pushptr(Address(rcx, 0));     // Save return address
3372   __ enter();                      // Save old & set new rbp
3373   __ subptr(rsp, rbx);             // Prolog
3374   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
3375             sender_sp);            // Make it walkable
3376   // This value is corrected by layout_activation_impl
3377   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3378   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
3379   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
3380   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
3381   __ decrementl(rdx);              // Decrement counter
3382   __ jcc(Assembler::notZero, loop);
3383   __ pushptr(Address(rcx, 0));     // Save final return address
3384 
3385   // Re-push self-frame
3386   __ enter();                 // Save old & set new rbp
3387   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
3388                               // Prolog
3389 
3390   // Use rbp because the frames look interpreted now
3391   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3392   // Don't need the precise return PC here, just precise enough to point into this code blob.
3393   address the_pc = __ pc();
3394   __ set_last_Java_frame(noreg, rbp, the_pc);
3395 
3396   // Call C code.  Need thread but NOT official VM entry
3397   // crud.  We cannot block on this call, no GC can happen.  Call should
3398   // restore return values to their stack-slots with the new SP.
3399   // Thread is in rdi already.
3400   //
3401   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
3402 
3403   __ andptr(rsp, -(StackAlignmentInBytes)); // Align SP as required by ABI
3404   __ mov(c_rarg0, r15_thread);
3405   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
3406   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3407 
3408   // Set an oopmap for the call site
3409   // Use the same PC we used for the last java frame
3410   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3411 
3412   // Clear fp AND pc
3413   __ reset_last_Java_frame(true);
3414 
3415   // Pop self-frame.
3416   __ leave();                 // Epilog
3417 
3418   // Jump to interpreter
3419   __ ret(0);
3420 
3421   // Make sure all code is generated
3422   masm->flush();
3423 
3424   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
3425                                                  SimpleRuntimeFrame::framesize >> 1);
3426 }
3427 #endif // COMPILER2
3428 
3429 
3430 //------------------------------generate_handler_blob------
3431 //
3432 // Generate a special Compile2Runtime blob that saves all registers,
3433 // and setup oopmap.
3434 //
3435 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3436   assert(StubRoutines::forward_exception_entry() != NULL,
3437          "must be generated before");
3438 
3439   ResourceMark rm;
3440   OopMapSet *oop_maps = new OopMapSet();
3441   OopMap* map;
3442 
3443   // Allocate space for the code.  Setup code generation tools.
3444   CodeBuffer buffer("handler_blob", 2048, 1024);
3445   MacroAssembler* masm = new MacroAssembler(&buffer);
3446 
3447   address start   = __ pc();
3448   address call_pc = NULL;
3449   int frame_size_in_words;
3450   bool cause_return = (poll_type == POLL_AT_RETURN);
3451   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
3452 
3453   if (UseRTMLocking) {
3454     // Abort RTM transaction before calling runtime
3455     // because critical section will be large and will be
3456     // aborted anyway. Also nmethod could be deoptimized.
3457     __ xabort(0);
3458   }
3459 
3460   // Make room for return address (or push it again)
3461   if (!cause_return) {
3462     __ push(rbx);
3463   }
3464 
3465   // Save registers, fpu state, and flags
3466   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, save_vectors);
3467 
3468   // The following is basically a call_VM.  However, we need the precise
3469   // address of the call in order to generate an oopmap. Hence, we do all the
3470   // work outselves.
3471 
3472   __ set_last_Java_frame(noreg, noreg, NULL);
3473 
3474   // The return address must always be correct so that frame constructor never
3475   // sees an invalid pc.
3476 
3477   if (!cause_return) {
3478     // Get the return pc saved by the signal handler and stash it in its appropriate place on the stack.
3479     // Additionally, rbx is a callee saved register and we can look at it later to determine
3480     // if someone changed the return address for us!
3481     __ movptr(rbx, Address(r15_thread, JavaThread::saved_exception_pc_offset()));
3482     __ movptr(Address(rbp, wordSize), rbx);
3483   }
3484 
3485   // Do the call
3486   __ mov(c_rarg0, r15_thread);
3487   __ call(RuntimeAddress(call_ptr));
3488 
3489   // Set an oopmap for the call site.  This oopmap will map all
3490   // oop-registers and debug-info registers as callee-saved.  This
3491   // will allow deoptimization at this safepoint to find all possible
3492   // debug-info recordings, as well as let GC find all oops.
3493 
3494   oop_maps->add_gc_map( __ pc() - start, map);
3495 
3496   Label noException;
3497 
3498   __ reset_last_Java_frame(false);
3499 
3500   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3501   __ jcc(Assembler::equal, noException);
3502 
3503   // Exception pending
3504 
3505   RegisterSaver::restore_live_registers(masm, save_vectors);
3506 
3507   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3508 
3509   // No exception case
3510   __ bind(noException);
3511 
3512   Label no_adjust, bail, no_prefix, not_special;
3513   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
3514     // If our stashed return pc was modified by the runtime we avoid touching it
3515     __ cmpptr(rbx, Address(rbp, wordSize));
3516     __ jccb(Assembler::notEqual, no_adjust);
3517 
3518     // Skip over the poll instruction.
3519     // See NativeInstruction::is_safepoint_poll()
3520     // Possible encodings:
3521     //      85 00       test   %eax,(%rax)
3522     //      85 01       test   %eax,(%rcx)
3523     //      85 02       test   %eax,(%rdx)
3524     //      85 03       test   %eax,(%rbx)
3525     //      85 06       test   %eax,(%rsi)
3526     //      85 07       test   %eax,(%rdi)
3527     //
3528     //   41 85 00       test   %eax,(%r8)
3529     //   41 85 01       test   %eax,(%r9)
3530     //   41 85 02       test   %eax,(%r10)
3531     //   41 85 03       test   %eax,(%r11)
3532     //   41 85 06       test   %eax,(%r14)
3533     //   41 85 07       test   %eax,(%r15)
3534     //
3535     //      85 04 24    test   %eax,(%rsp)
3536     //   41 85 04 24    test   %eax,(%r12)
3537     //      85 45 00    test   %eax,0x0(%rbp)
3538     //   41 85 45 00    test   %eax,0x0(%r13)
3539 
3540     __ cmpb(Address(rbx, 0), NativeTstRegMem::instruction_rex_b_prefix);
3541     __ jcc(Assembler::notEqual, no_prefix);
3542     __ addptr(rbx, 1);
3543     __ bind(no_prefix);
3544 #ifdef ASSERT
3545     __ movptr(rax, rbx); // remember where 0x85 should be, for verification below
3546 #endif
3547     // r12/r13/rsp/rbp base encoding takes 3 bytes with the following register values:
3548     // r12/rsp 0x04
3549     // r13/rbp 0x05
3550     __ movzbq(rcx, Address(rbx, 1));
3551     __ andptr(rcx, 0x07); // looking for 0x04 .. 0x05
3552     __ subptr(rcx, 4);    // looking for 0x00 .. 0x01
3553     __ cmpptr(rcx, 1);
3554     __ jcc(Assembler::above, not_special);
3555     __ addptr(rbx, 1);
3556     __ bind(not_special);
3557 #ifdef ASSERT
3558     // Verify the correct encoding of the poll we're about to skip.
3559     __ cmpb(Address(rax, 0), NativeTstRegMem::instruction_code_memXregl);
3560     __ jcc(Assembler::notEqual, bail);
3561     // Mask out the modrm bits
3562     __ testb(Address(rax, 1), NativeTstRegMem::modrm_mask);
3563     // rax encodes to 0, so if the bits are nonzero it's incorrect
3564     __ jcc(Assembler::notZero, bail);
3565 #endif
3566     // Adjust return pc forward to step over the safepoint poll instruction
3567     __ addptr(rbx, 2);
3568     __ movptr(Address(rbp, wordSize), rbx);
3569   }
3570 
3571   __ bind(no_adjust);
3572   // Normal exit, restore registers and exit.
3573   RegisterSaver::restore_live_registers(masm, save_vectors);
3574   __ ret(0);
3575 
3576 #ifdef ASSERT
3577   __ bind(bail);
3578   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
3579 #endif
3580 
3581   // Make sure all code is generated
3582   masm->flush();
3583 
3584   // Fill-out other meta info
3585   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3586 }
3587 
3588 //
3589 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3590 //
3591 // Generate a stub that calls into vm to find out the proper destination
3592 // of a java call. All the argument registers are live at this point
3593 // but since this is generic code we don't know what they are and the caller
3594 // must do any gc of the args.
3595 //
3596 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3597   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3598 
3599   // allocate space for the code
3600   ResourceMark rm;
3601 
3602   CodeBuffer buffer(name, 1000, 512);
3603   MacroAssembler* masm                = new MacroAssembler(&buffer);
3604 
3605   int frame_size_in_words;
3606 
3607   OopMapSet *oop_maps = new OopMapSet();
3608   OopMap* map = NULL;
3609 
3610   int start = __ offset();
3611 
3612   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3613 
3614   int frame_complete = __ offset();
3615 
3616   __ set_last_Java_frame(noreg, noreg, NULL);
3617 
3618   __ mov(c_rarg0, r15_thread);
3619 
3620   __ call(RuntimeAddress(destination));
3621 
3622 
3623   // Set an oopmap for the call site.
3624   // We need this not only for callee-saved registers, but also for volatile
3625   // registers that the compiler might be keeping live across a safepoint.
3626 
3627   oop_maps->add_gc_map( __ offset() - start, map);
3628 
3629   // rax contains the address we are going to jump to assuming no exception got installed
3630 
3631   // clear last_Java_sp
3632   __ reset_last_Java_frame(false);
3633   // check for pending exceptions
3634   Label pending;
3635   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3636   __ jcc(Assembler::notEqual, pending);
3637 
3638   // get the returned Method*
3639   __ get_vm_result_2(rbx, r15_thread);
3640   __ movptr(Address(rsp, RegisterSaver::rbx_offset_in_bytes()), rbx);
3641 
3642   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3643 
3644   RegisterSaver::restore_live_registers(masm);
3645 
3646   // We are back the the original state on entry and ready to go.
3647 
3648   __ jmp(rax);
3649 
3650   // Pending exception after the safepoint
3651 
3652   __ bind(pending);
3653 
3654   RegisterSaver::restore_live_registers(masm);
3655 
3656   // exception pending => remove activation and forward to exception handler
3657 
3658   __ movptr(Address(r15_thread, JavaThread::vm_result_offset()), (int)NULL_WORD);
3659 
3660   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
3661   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3662 
3663   // -------------
3664   // make sure all code is generated
3665   masm->flush();
3666 
3667   // return the  blob
3668   // frame_size_words or bytes??
3669   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3670 }
3671 
3672 
3673 //------------------------------Montgomery multiplication------------------------
3674 //
3675 
3676 #ifndef _WINDOWS
3677 
3678 #define ASM_SUBTRACT
3679 
3680 #ifdef ASM_SUBTRACT
3681 // Subtract 0:b from carry:a.  Return carry.
3682 static unsigned long
3683 sub(unsigned long a[], unsigned long b[], unsigned long carry, long len) {
3684   long i = 0, cnt = len;
3685   unsigned long tmp;
3686   asm volatile("clc; "
3687                "0: ; "
3688                "mov (%[b], %[i], 8), %[tmp]; "
3689                "sbb %[tmp], (%[a], %[i], 8); "
3690                "inc %[i]; dec %[cnt]; "
3691                "jne 0b; "
3692                "mov %[carry], %[tmp]; sbb $0, %[tmp]; "
3693                : [i]"+r"(i), [cnt]"+r"(cnt), [tmp]"=&r"(tmp)
3694                : [a]"r"(a), [b]"r"(b), [carry]"r"(carry)
3695                : "memory");
3696   return tmp;
3697 }
3698 #else // ASM_SUBTRACT
3699 typedef int __attribute__((mode(TI))) int128;
3700 
3701 // Subtract 0:b from carry:a.  Return carry.
3702 static unsigned long
3703 sub(unsigned long a[], unsigned long b[], unsigned long carry, int len) {
3704   int128 tmp = 0;
3705   int i;
3706   for (i = 0; i < len; i++) {
3707     tmp += a[i];
3708     tmp -= b[i];
3709     a[i] = tmp;
3710     tmp >>= 64;
3711     assert(-1 <= tmp && tmp <= 0, "invariant");
3712   }
3713   return tmp + carry;
3714 }
3715 #endif // ! ASM_SUBTRACT
3716 
3717 // Multiply (unsigned) Long A by Long B, accumulating the double-
3718 // length result into the accumulator formed of T0, T1, and T2.
3719 #define MACC(A, B, T0, T1, T2)                                  \
3720 do {                                                            \
3721   unsigned long hi, lo;                                         \
3722   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4"   \
3723            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3724            : "r"(A), "a"(B) : "cc");                            \
3725  } while(0)
3726 
3727 // As above, but add twice the double-length result into the
3728 // accumulator.
3729 #define MACC2(A, B, T0, T1, T2)                                 \
3730 do {                                                            \
3731   unsigned long hi, lo;                                         \
3732   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4; " \
3733            "add %%rax, %2; adc %%rdx, %3; adc $0, %4"           \
3734            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3735            : "r"(A), "a"(B) : "cc");                            \
3736  } while(0)
3737 
3738 // Fast Montgomery multiplication.  The derivation of the algorithm is
3739 // in  A Cryptographic Library for the Motorola DSP56000,
3740 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237.
3741 
3742 static void __attribute__((noinline))
3743 montgomery_multiply(unsigned long a[], unsigned long b[], unsigned long n[],
3744                     unsigned long m[], unsigned long inv, int len) {
3745   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3746   int i;
3747 
3748   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3749 
3750   for (i = 0; i < len; i++) {
3751     int j;
3752     for (j = 0; j < i; j++) {
3753       MACC(a[j], b[i-j], t0, t1, t2);
3754       MACC(m[j], n[i-j], t0, t1, t2);
3755     }
3756     MACC(a[i], b[0], t0, t1, t2);
3757     m[i] = t0 * inv;
3758     MACC(m[i], n[0], t0, t1, t2);
3759 
3760     assert(t0 == 0, "broken Montgomery multiply");
3761 
3762     t0 = t1; t1 = t2; t2 = 0;
3763   }
3764 
3765   for (i = len; i < 2*len; i++) {
3766     int j;
3767     for (j = i-len+1; j < len; j++) {
3768       MACC(a[j], b[i-j], t0, t1, t2);
3769       MACC(m[j], n[i-j], t0, t1, t2);
3770     }
3771     m[i-len] = t0;
3772     t0 = t1; t1 = t2; t2 = 0;
3773   }
3774 
3775   while (t0)
3776     t0 = sub(m, n, t0, len);
3777 }
3778 
3779 // Fast Montgomery squaring.  This uses asymptotically 25% fewer
3780 // multiplies so it should be up to 25% faster than Montgomery
3781 // multiplication.  However, its loop control is more complex and it
3782 // may actually run slower on some machines.
3783 
3784 static void __attribute__((noinline))
3785 montgomery_square(unsigned long a[], unsigned long n[],
3786                   unsigned long m[], unsigned long inv, int len) {
3787   unsigned long t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3788   int i;
3789 
3790   assert(inv * n[0] == -1UL, "broken inverse in Montgomery multiply");
3791 
3792   for (i = 0; i < len; i++) {
3793     int j;
3794     int end = (i+1)/2;
3795     for (j = 0; j < end; j++) {
3796       MACC2(a[j], a[i-j], t0, t1, t2);
3797       MACC(m[j], n[i-j], t0, t1, t2);
3798     }
3799     if ((i & 1) == 0) {
3800       MACC(a[j], a[j], t0, t1, t2);
3801     }
3802     for (; j < i; j++) {
3803       MACC(m[j], n[i-j], t0, t1, t2);
3804     }
3805     m[i] = t0 * inv;
3806     MACC(m[i], n[0], t0, t1, t2);
3807 
3808     assert(t0 == 0, "broken Montgomery square");
3809 
3810     t0 = t1; t1 = t2; t2 = 0;
3811   }
3812 
3813   for (i = len; i < 2*len; i++) {
3814     int start = i-len+1;
3815     int end = start + (len - start)/2;
3816     int j;
3817     for (j = start; j < end; j++) {
3818       MACC2(a[j], a[i-j], t0, t1, t2);
3819       MACC(m[j], n[i-j], t0, t1, t2);
3820     }
3821     if ((i & 1) == 0) {
3822       MACC(a[j], a[j], t0, t1, t2);
3823     }
3824     for (; j < len; j++) {
3825       MACC(m[j], n[i-j], t0, t1, t2);
3826     }
3827     m[i-len] = t0;
3828     t0 = t1; t1 = t2; t2 = 0;
3829   }
3830 
3831   while (t0)
3832     t0 = sub(m, n, t0, len);
3833 }
3834 
3835 // Swap words in a longword.
3836 static unsigned long swap(unsigned long x) {
3837   return (x << 32) | (x >> 32);
3838 }
3839 
3840 // Copy len longwords from s to d, word-swapping as we go.  The
3841 // destination array is reversed.
3842 static void reverse_words(unsigned long *s, unsigned long *d, int len) {
3843   d += len;
3844   while(len-- > 0) {
3845     d--;
3846     *d = swap(*s);
3847     s++;
3848   }
3849 }
3850 
3851 // The threshold at which squaring is advantageous was determined
3852 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3853 #define MONTGOMERY_SQUARING_THRESHOLD 64
3854 
3855 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3856                                         jint len, jlong inv,
3857                                         jint *m_ints) {
3858   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3859   int longwords = len/2;
3860 
3861   // Make very sure we don't use so much space that the stack might
3862   // overflow.  512 jints corresponds to an 16384-bit integer and
3863   // will use here a total of 8k bytes of stack space.
3864   int total_allocation = longwords * sizeof (unsigned long) * 4;
3865   guarantee(total_allocation <= 8192, "must be");
3866   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3867 
3868   // Local scratch arrays
3869   unsigned long
3870     *a = scratch + 0 * longwords,
3871     *b = scratch + 1 * longwords,
3872     *n = scratch + 2 * longwords,
3873     *m = scratch + 3 * longwords;
3874 
3875   reverse_words((unsigned long *)a_ints, a, longwords);
3876   reverse_words((unsigned long *)b_ints, b, longwords);
3877   reverse_words((unsigned long *)n_ints, n, longwords);
3878 
3879   ::montgomery_multiply(a, b, n, m, (unsigned long)inv, longwords);
3880 
3881   reverse_words(m, (unsigned long *)m_ints, longwords);
3882 }
3883 
3884 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3885                                       jint len, jlong inv,
3886                                       jint *m_ints) {
3887   assert(len % 2 == 0, "array length in montgomery_square must be even");
3888   int longwords = len/2;
3889 
3890   // Make very sure we don't use so much space that the stack might
3891   // overflow.  512 jints corresponds to an 16384-bit integer and
3892   // will use here a total of 6k bytes of stack space.
3893   int total_allocation = longwords * sizeof (unsigned long) * 3;
3894   guarantee(total_allocation <= 8192, "must be");
3895   unsigned long *scratch = (unsigned long *)alloca(total_allocation);
3896 
3897   // Local scratch arrays
3898   unsigned long
3899     *a = scratch + 0 * longwords,
3900     *n = scratch + 1 * longwords,
3901     *m = scratch + 2 * longwords;
3902 
3903   reverse_words((unsigned long *)a_ints, a, longwords);
3904   reverse_words((unsigned long *)n_ints, n, longwords);
3905 
3906   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3907     ::montgomery_square(a, n, m, (unsigned long)inv, longwords);
3908   } else {
3909     ::montgomery_multiply(a, a, n, m, (unsigned long)inv, longwords);
3910   }
3911 
3912   reverse_words(m, (unsigned long *)m_ints, longwords);
3913 }
3914 
3915 #endif // WINDOWS
3916 
3917 #ifdef COMPILER2
3918 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
3919 //
3920 //------------------------------generate_exception_blob---------------------------
3921 // creates exception blob at the end
3922 // Using exception blob, this code is jumped from a compiled method.
3923 // (see emit_exception_handler in x86_64.ad file)
3924 //
3925 // Given an exception pc at a call we call into the runtime for the
3926 // handler in this method. This handler might merely restore state
3927 // (i.e. callee save registers) unwind the frame and jump to the
3928 // exception handler for the nmethod if there is no Java level handler
3929 // for the nmethod.
3930 //
3931 // This code is entered with a jmp.
3932 //
3933 // Arguments:
3934 //   rax: exception oop
3935 //   rdx: exception pc
3936 //
3937 // Results:
3938 //   rax: exception oop
3939 //   rdx: exception pc in caller or ???
3940 //   destination: exception handler of caller
3941 //
3942 // Note: the exception pc MUST be at a call (precise debug information)
3943 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
3944 //
3945 
3946 void OptoRuntime::generate_exception_blob() {
3947   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
3948   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
3949   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
3950 
3951   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3952 
3953   // Allocate space for the code
3954   ResourceMark rm;
3955   // Setup code generation tools
3956   CodeBuffer buffer("exception_blob", 2048, 1024);
3957   MacroAssembler* masm = new MacroAssembler(&buffer);
3958 
3959 
3960   address start = __ pc();
3961 
3962   // Exception pc is 'return address' for stack walker
3963   __ push(rdx);
3964   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
3965 
3966   // Save callee-saved registers.  See x86_64.ad.
3967 
3968   // rbp is an implicitly saved callee saved register (i.e., the calling
3969   // convention will save/restore it in the prolog/epilog). Other than that
3970   // there are no callee save registers now that adapter frames are gone.
3971 
3972   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3973 
3974   // Store exception in Thread object. We cannot pass any arguments to the
3975   // handle_exception call, since we do not want to make any assumption
3976   // about the size of the frame where the exception happened in.
3977   // c_rarg0 is either rdi (Linux) or rcx (Windows).
3978   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
3979   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
3980 
3981   // This call does all the hard work.  It checks if an exception handler
3982   // exists in the method.
3983   // If so, it returns the handler address.
3984   // If not, it prepares for stack-unwinding, restoring the callee-save
3985   // registers of the frame being removed.
3986   //
3987   // address OptoRuntime::handle_exception_C(JavaThread* thread)
3988 
3989   // At a method handle call, the stack may not be properly aligned
3990   // when returning with an exception.
3991   address the_pc = __ pc();
3992   __ set_last_Java_frame(noreg, noreg, the_pc);
3993   __ mov(c_rarg0, r15_thread);
3994   __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
3995   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3996 
3997   // Set an oopmap for the call site.  This oopmap will only be used if we
3998   // are unwinding the stack.  Hence, all locations will be dead.
3999   // Callee-saved registers will be the same as the frame above (i.e.,
4000   // handle_exception_stub), since they were restored when we got the
4001   // exception.
4002 
4003   OopMapSet* oop_maps = new OopMapSet();
4004 
4005   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
4006 
4007   __ reset_last_Java_frame(false);
4008 
4009   // Restore callee-saved registers
4010 
4011   // rbp is an implicitly saved callee-saved register (i.e., the calling
4012   // convention will save restore it in prolog/epilog) Other than that
4013   // there are no callee save registers now that adapter frames are gone.
4014 
4015   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
4016 
4017   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
4018   __ pop(rdx);                  // No need for exception pc anymore
4019 
4020   // rax: exception handler
4021 
4022   // We have a handler in rax (could be deopt blob).
4023   __ mov(r8, rax);
4024 
4025   // Get the exception oop
4026   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
4027   // Get the exception pc in case we are deoptimized
4028   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
4029 #ifdef ASSERT
4030   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), (int)NULL_WORD);
4031   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int)NULL_WORD);
4032 #endif
4033   // Clear the exception oop so GC no longer processes it as a root.
4034   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int)NULL_WORD);
4035 
4036   // rax: exception oop
4037   // r8:  exception handler
4038   // rdx: exception pc
4039   // Jump to handler
4040 
4041   __ jmp(r8);
4042 
4043   // Make sure all code is generated
4044   masm->flush();
4045 
4046   // Set exception blob
4047   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
4048 }
4049 #endif // COMPILER2