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