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