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