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