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