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