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