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