1 /*
   2  * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/macroAssembler.hpp"
  27 #include "asm/macroAssembler.inline.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "code/icBuffer.hpp"
  30 #include "code/vtableStubs.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "logging/log.hpp"
  33 #include "memory/resourceArea.hpp"
  34 #include "oops/compiledICHolder.hpp"
  35 #include "runtime/sharedRuntime.hpp"
  36 #include "runtime/vframeArray.hpp"
  37 #include "vmreg_x86.inline.hpp"
  38 #ifdef COMPILER1
  39 #include "c1/c1_Runtime1.hpp"
  40 #endif
  41 #ifdef COMPILER2
  42 #include "opto/runtime.hpp"
  43 #endif
  44 #include "vm_version_x86.hpp"
  45 
  46 #define __ masm->
  47 
  48 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  49 
  50 class RegisterSaver {
  51   // Capture info about frame layout
  52 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  53   enum layout {
  54                 fpu_state_off = 0,
  55                 fpu_state_end = fpu_state_off+FPUStateSizeInWords,
  56                 st0_off, st0H_off,
  57                 st1_off, st1H_off,
  58                 st2_off, st2H_off,
  59                 st3_off, st3H_off,
  60                 st4_off, st4H_off,
  61                 st5_off, st5H_off,
  62                 st6_off, st6H_off,
  63                 st7_off, st7H_off,
  64                 xmm_off,
  65                 DEF_XMM_OFFS(0),
  66                 DEF_XMM_OFFS(1),
  67                 DEF_XMM_OFFS(2),
  68                 DEF_XMM_OFFS(3),
  69                 DEF_XMM_OFFS(4),
  70                 DEF_XMM_OFFS(5),
  71                 DEF_XMM_OFFS(6),
  72                 DEF_XMM_OFFS(7),
  73                 flags_off = xmm7_off + 16/BytesPerInt + 1, // 16-byte stack alignment fill word
  74                 rdi_off,
  75                 rsi_off,
  76                 ignore_off,  // extra copy of rbp,
  77                 rsp_off,
  78                 rbx_off,
  79                 rdx_off,
  80                 rcx_off,
  81                 rax_off,
  82                 // The frame sender code expects that rbp will be in the "natural" place and
  83                 // will override any oopMap setting for it. We must therefore force the layout
  84                 // so that it agrees with the frame sender code.
  85                 rbp_off,
  86                 return_off,      // slot for return address
  87                 reg_save_size };
  88   enum { FPU_regs_live = flags_off - fpu_state_end };
  89 
  90   public:
  91 
  92   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words,
  93                                      int* total_frame_words, bool verify_fpu = true, bool save_vectors = false);
  94   static void restore_live_registers(MacroAssembler* masm, bool restore_vectors = false);
  95 
  96   static int rax_offset() { return rax_off; }
  97   static int rbx_offset() { return rbx_off; }
  98 
  99   // Offsets into the register save area
 100   // Used by deoptimization when it is managing result register
 101   // values on its own
 102 
 103   static int raxOffset(void) { return rax_off; }
 104   static int rdxOffset(void) { return rdx_off; }
 105   static int rbxOffset(void) { return rbx_off; }
 106   static int xmm0Offset(void) { return xmm0_off; }
 107   // This really returns a slot in the fp save area, which one is not important
 108   static int fpResultOffset(void) { return st0_off; }
 109 
 110   // During deoptimization only the result register need to be restored
 111   // all the other values have already been extracted.
 112 
 113   static void restore_result_registers(MacroAssembler* masm);
 114 
 115 };
 116 
 117 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words,
 118                                            int* total_frame_words, bool verify_fpu, bool save_vectors) {
 119   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 120   int ymm_bytes = num_xmm_regs * 16;
 121   int zmm_bytes = num_xmm_regs * 32;
 122 #ifdef COMPILER2
 123   if (save_vectors) {
 124     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 125     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 126     // Save upper half of YMM registers
 127     int vect_bytes = ymm_bytes;
 128     if (UseAVX > 2) {
 129       // Save upper half of ZMM registers as well
 130       vect_bytes += zmm_bytes;
 131     }
 132     additional_frame_words += vect_bytes / wordSize;
 133   }
 134 #else
 135   assert(!save_vectors, "vectors are generated only by C2");
 136 #endif
 137   int frame_size_in_bytes = (reg_save_size + additional_frame_words) * wordSize;
 138   int frame_words = frame_size_in_bytes / wordSize;
 139   *total_frame_words = frame_words;
 140 
 141   assert(FPUStateSizeInWords == 27, "update stack layout");
 142 
 143   // save registers, fpu state, and flags
 144   // We assume caller has already has return address slot on the stack
 145   // We push epb twice in this sequence because we want the real rbp,
 146   // to be under the return like a normal enter and we want to use pusha
 147   // We push by hand instead of pusing push
 148   __ enter();
 149   __ pusha();
 150   __ pushf();
 151   __ subptr(rsp,FPU_regs_live*wordSize); // Push FPU registers space
 152   __ push_FPU_state();          // Save FPU state & init
 153 
 154   if (verify_fpu) {
 155     // Some stubs may have non standard FPU control word settings so
 156     // only check and reset the value when it required to be the
 157     // standard value.  The safepoint blob in particular can be used
 158     // in methods which are using the 24 bit control word for
 159     // optimized float math.
 160 
 161 #ifdef ASSERT
 162     // Make sure the control word has the expected value
 163     Label ok;
 164     __ cmpw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 165     __ jccb(Assembler::equal, ok);
 166     __ stop("corrupted control word detected");
 167     __ bind(ok);
 168 #endif
 169 
 170     // Reset the control word to guard against exceptions being unmasked
 171     // since fstp_d can cause FPU stack underflow exceptions.  Write it
 172     // into the on stack copy and then reload that to make sure that the
 173     // current and future values are correct.
 174     __ movw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 175   }
 176 
 177   __ frstor(Address(rsp, 0));
 178   if (!verify_fpu) {
 179     // Set the control word so that exceptions are masked for the
 180     // following code.
 181     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 182   }
 183 
 184   int off = st0_off;
 185   int delta = st1_off - off;
 186 
 187   // Save the FPU registers in de-opt-able form
 188   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 189     __ fstp_d(Address(rsp, off*wordSize));
 190     off += delta;
 191   }
 192 
 193   off = xmm0_off;
 194   delta = xmm1_off - off;
 195   if(UseSSE == 1) {
 196     // Save the XMM state
 197     for (int n = 0; n < num_xmm_regs; n++) {
 198       __ movflt(Address(rsp, off*wordSize), as_XMMRegister(n));
 199       off += delta;
 200     }
 201   } else if(UseSSE >= 2) {
 202     // Save whole 128bit (16 bytes) XMM registers
 203     for (int n = 0; n < num_xmm_regs; n++) {
 204       __ movdqu(Address(rsp, off*wordSize), as_XMMRegister(n));
 205       off += delta;
 206     }
 207   }
 208 
 209   if (save_vectors) {
 210     __ subptr(rsp, ymm_bytes);
 211     // Save upper half of YMM registers
 212     for (int n = 0; n < num_xmm_regs; n++) {
 213       __ vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
 214     }
 215     if (UseAVX > 2) {
 216       __ subptr(rsp, zmm_bytes);
 217       // Save upper half of ZMM registers
 218       for (int n = 0; n < num_xmm_regs; n++) {
 219         __ vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
 220       }
 221     }
 222   }
 223   __ vzeroupper();
 224 
 225   // Set an oopmap for the call site.  This oopmap will map all
 226   // oop-registers and debug-info registers as callee-saved.  This
 227   // will allow deoptimization at this safepoint to find all possible
 228   // debug-info recordings, as well as let GC find all oops.
 229 
 230   OopMapSet *oop_maps = new OopMapSet();
 231   OopMap* map =  new OopMap( frame_words, 0 );
 232 
 233 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x) + additional_frame_words)
 234 #define NEXTREG(x) (x)->as_VMReg()->next()
 235 
 236   map->set_callee_saved(STACK_OFFSET(rax_off), rax->as_VMReg());
 237   map->set_callee_saved(STACK_OFFSET(rcx_off), rcx->as_VMReg());
 238   map->set_callee_saved(STACK_OFFSET(rdx_off), rdx->as_VMReg());
 239   map->set_callee_saved(STACK_OFFSET(rbx_off), rbx->as_VMReg());
 240   // rbp, location is known implicitly, no oopMap
 241   map->set_callee_saved(STACK_OFFSET(rsi_off), rsi->as_VMReg());
 242   map->set_callee_saved(STACK_OFFSET(rdi_off), rdi->as_VMReg());
 243   // %%% This is really a waste but we'll keep things as they were for now for the upper component
 244   off = st0_off;
 245   delta = st1_off - off;
 246   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 247     FloatRegister freg_name = as_FloatRegister(n);
 248     map->set_callee_saved(STACK_OFFSET(off), freg_name->as_VMReg());
 249     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(freg_name));
 250     off += delta;
 251   }
 252   off = xmm0_off;
 253   delta = xmm1_off - off;
 254   for (int n = 0; n < num_xmm_regs; n++) {
 255     XMMRegister xmm_name = as_XMMRegister(n);
 256     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 257     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(xmm_name));
 258     off += delta;
 259   }
 260 #undef NEXTREG
 261 #undef STACK_OFFSET
 262 
 263   return map;
 264 }
 265 
 266 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 267   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 268   int ymm_bytes = num_xmm_regs * 16;
 269   int zmm_bytes = num_xmm_regs * 32;
 270   // Recover XMM & FPU state
 271   int additional_frame_bytes = 0;
 272 #ifdef COMPILER2
 273   if (restore_vectors) {
 274     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 275     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 276     // Save upper half of YMM registers
 277     additional_frame_bytes = ymm_bytes;
 278     if (UseAVX > 2) {
 279       // Save upper half of ZMM registers as well
 280       additional_frame_bytes += zmm_bytes;
 281     }
 282   }
 283 #else
 284   assert(!restore_vectors, "vectors are generated only by C2");
 285 #endif
 286 
 287   int off = xmm0_off;
 288   int delta = xmm1_off - off;
 289 
 290   __ vzeroupper();
 291 
 292   if (UseSSE == 1) {
 293     // Restore XMM registers
 294     assert(additional_frame_bytes == 0, "");
 295     for (int n = 0; n < num_xmm_regs; n++) {
 296       __ movflt(as_XMMRegister(n), Address(rsp, off*wordSize));
 297       off += delta;
 298     }
 299   } else if (UseSSE >= 2) {
 300     // Restore whole 128bit (16 bytes) XMM registers. Do this before restoring YMM and
 301     // ZMM because the movdqu instruction zeros the upper part of the XMM register.
 302     for (int n = 0; n < num_xmm_regs; n++) {
 303       __ movdqu(as_XMMRegister(n), Address(rsp, off*wordSize+additional_frame_bytes));
 304       off += delta;
 305     }
 306   }
 307 
 308   if (restore_vectors) {
 309     if (UseAVX > 2) {
 310       // Restore upper half of ZMM registers.
 311       for (int n = 0; n < num_xmm_regs; n++) {
 312         __ vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
 313       }
 314       __ addptr(rsp, zmm_bytes);
 315     }
 316     // Restore upper half of YMM registers.
 317     for (int n = 0; n < num_xmm_regs; n++) {
 318       __ vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
 319     }
 320     __ addptr(rsp, ymm_bytes);
 321   }
 322 
 323   __ pop_FPU_state();
 324   __ addptr(rsp, FPU_regs_live*wordSize); // Pop FPU registers
 325 
 326   __ popf();
 327   __ popa();
 328   // Get the rbp, described implicitly by the frame sender code (no oopMap)
 329   __ pop(rbp);
 330 }
 331 
 332 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 333 
 334   // Just restore result register. Only used by deoptimization. By
 335   // now any callee save register that needs to be restore to a c2
 336   // caller of the deoptee has been extracted into the vframeArray
 337   // and will be stuffed into the c2i adapter we create for later
 338   // restoration so only result registers need to be restored here.
 339   //
 340 
 341   __ frstor(Address(rsp, 0));      // Restore fpu state
 342 
 343   // Recover XMM & FPU state
 344   if( UseSSE == 1 ) {
 345     __ movflt(xmm0, Address(rsp, xmm0_off*wordSize));
 346   } else if( UseSSE >= 2 ) {
 347     __ movdbl(xmm0, Address(rsp, xmm0_off*wordSize));
 348   }
 349   __ movptr(rax, Address(rsp, rax_off*wordSize));
 350   __ movptr(rdx, Address(rsp, rdx_off*wordSize));
 351   // Pop all of the register save are off the stack except the return address
 352   __ addptr(rsp, return_off * wordSize);
 353 }
 354 
 355 // Is vector's size (in bytes) bigger than a size saved by default?
 356 // 16 bytes XMM registers are saved by default using SSE2 movdqu instructions.
 357 // Note, MaxVectorSize == 0 with UseSSE < 2 and vectors are not generated.
 358 bool SharedRuntime::is_wide_vector(int size) {
 359   return size > 16;
 360 }
 361 
 362 size_t SharedRuntime::trampoline_size() {
 363   return 16;
 364 }
 365 
 366 void SharedRuntime::generate_trampoline(MacroAssembler *masm, address destination) {
 367   __ jump(RuntimeAddress(destination));
 368 }
 369 
 370 // The java_calling_convention describes stack locations as ideal slots on
 371 // a frame with no abi restrictions. Since we must observe abi restrictions
 372 // (like the placement of the register window) the slots must be biased by
 373 // the following value.
 374 static int reg2offset_in(VMReg r) {
 375   // Account for saved rbp, and return address
 376   // This should really be in_preserve_stack_slots
 377   return (r->reg2stack() + 2) * VMRegImpl::stack_slot_size;
 378 }
 379 
 380 static int reg2offset_out(VMReg r) {
 381   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 382 }
 383 
 384 // ---------------------------------------------------------------------------
 385 // Read the array of BasicTypes from a signature, and compute where the
 386 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 387 // quantities.  Values less than SharedInfo::stack0 are registers, those above
 388 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 389 // as framesizes are fixed.
 390 // VMRegImpl::stack0 refers to the first slot 0(sp).
 391 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 392 // up to RegisterImpl::number_of_registers) are the 32-bit
 393 // integer registers.
 394 
 395 // Pass first two oop/int args in registers ECX and EDX.
 396 // Pass first two float/double args in registers XMM0 and XMM1.
 397 // Doubles have precedence, so if you pass a mix of floats and doubles
 398 // the doubles will grab the registers before the floats will.
 399 
 400 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 401 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 402 // units regardless of build. Of course for i486 there is no 64 bit build
 403 
 404 
 405 // ---------------------------------------------------------------------------
 406 // The compiled Java calling convention.
 407 // Pass first two oop/int args in registers ECX and EDX.
 408 // Pass first two float/double args in registers XMM0 and XMM1.
 409 // Doubles have precedence, so if you pass a mix of floats and doubles
 410 // the doubles will grab the registers before the floats will.
 411 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 412                                            VMRegPair *regs,
 413                                            int total_args_passed,
 414                                            int is_outgoing) {
 415   uint    stack = 0;          // Starting stack position for args on stack
 416 
 417 
 418   // Pass first two oop/int args in registers ECX and EDX.
 419   uint reg_arg0 = 9999;
 420   uint reg_arg1 = 9999;
 421 
 422   // Pass first two float/double args in registers XMM0 and XMM1.
 423   // Doubles have precedence, so if you pass a mix of floats and doubles
 424   // the doubles will grab the registers before the floats will.
 425   // CNC - TURNED OFF FOR non-SSE.
 426   //       On Intel we have to round all doubles (and most floats) at
 427   //       call sites by storing to the stack in any case.
 428   // UseSSE=0 ==> Don't Use ==> 9999+0
 429   // UseSSE=1 ==> Floats only ==> 9999+1
 430   // UseSSE>=2 ==> Floats or doubles ==> 9999+2
 431   enum { fltarg_dontuse = 9999+0, fltarg_float_only = 9999+1, fltarg_flt_dbl = 9999+2 };
 432   uint fargs = (UseSSE>=2) ? 2 : UseSSE;
 433   uint freg_arg0 = 9999+fargs;
 434   uint freg_arg1 = 9999+fargs;
 435 
 436   // Pass doubles & longs aligned on the stack.  First count stack slots for doubles
 437   int i;
 438   for( i = 0; i < total_args_passed; i++) {
 439     if( sig_bt[i] == T_DOUBLE ) {
 440       // first 2 doubles go in registers
 441       if( freg_arg0 == fltarg_flt_dbl ) freg_arg0 = i;
 442       else if( freg_arg1 == fltarg_flt_dbl ) freg_arg1 = i;
 443       else // Else double is passed low on the stack to be aligned.
 444         stack += 2;
 445     } else if( sig_bt[i] == T_LONG ) {
 446       stack += 2;
 447     }
 448   }
 449   int dstack = 0;             // Separate counter for placing doubles
 450 
 451   // Now pick where all else goes.
 452   for( i = 0; i < total_args_passed; i++) {
 453     // From the type and the argument number (count) compute the location
 454     switch( sig_bt[i] ) {
 455     case T_SHORT:
 456     case T_CHAR:
 457     case T_BYTE:
 458     case T_BOOLEAN:
 459     case T_INT:
 460     case T_ARRAY:
 461     case T_OBJECT:
 462     case T_ADDRESS:
 463       if( reg_arg0 == 9999 )  {
 464         reg_arg0 = i;
 465         regs[i].set1(rcx->as_VMReg());
 466       } else if( reg_arg1 == 9999 )  {
 467         reg_arg1 = i;
 468         regs[i].set1(rdx->as_VMReg());
 469       } else {
 470         regs[i].set1(VMRegImpl::stack2reg(stack++));
 471       }
 472       break;
 473     case T_FLOAT:
 474       if( freg_arg0 == fltarg_flt_dbl || freg_arg0 == fltarg_float_only ) {
 475         freg_arg0 = i;
 476         regs[i].set1(xmm0->as_VMReg());
 477       } else if( freg_arg1 == fltarg_flt_dbl || freg_arg1 == fltarg_float_only ) {
 478         freg_arg1 = i;
 479         regs[i].set1(xmm1->as_VMReg());
 480       } else {
 481         regs[i].set1(VMRegImpl::stack2reg(stack++));
 482       }
 483       break;
 484     case T_LONG:
 485       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
 486       regs[i].set2(VMRegImpl::stack2reg(dstack));
 487       dstack += 2;
 488       break;
 489     case T_DOUBLE:
 490       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
 491       if( freg_arg0 == (uint)i ) {
 492         regs[i].set2(xmm0->as_VMReg());
 493       } else if( freg_arg1 == (uint)i ) {
 494         regs[i].set2(xmm1->as_VMReg());
 495       } else {
 496         regs[i].set2(VMRegImpl::stack2reg(dstack));
 497         dstack += 2;
 498       }
 499       break;
 500     case T_VOID: regs[i].set_bad(); break;
 501       break;
 502     default:
 503       ShouldNotReachHere();
 504       break;
 505     }
 506   }
 507 
 508   // return value can be odd number of VMRegImpl stack slots make multiple of 2
 509   return align_up(stack, 2);
 510 }
 511 
 512 // Patch the callers callsite with entry to compiled code if it exists.
 513 static void patch_callers_callsite(MacroAssembler *masm) {
 514   Label L;
 515   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 516   __ jcc(Assembler::equal, L);
 517   // Schedule the branch target address early.
 518   // Call into the VM to patch the caller, then jump to compiled callee
 519   // rax, isn't live so capture return address while we easily can
 520   __ movptr(rax, Address(rsp, 0));
 521   __ pusha();
 522   __ pushf();
 523 
 524   if (UseSSE == 1) {
 525     __ subptr(rsp, 2*wordSize);
 526     __ movflt(Address(rsp, 0), xmm0);
 527     __ movflt(Address(rsp, wordSize), xmm1);
 528   }
 529   if (UseSSE >= 2) {
 530     __ subptr(rsp, 4*wordSize);
 531     __ movdbl(Address(rsp, 0), xmm0);
 532     __ movdbl(Address(rsp, 2*wordSize), xmm1);
 533   }
 534 #ifdef COMPILER2
 535   // C2 may leave the stack dirty if not in SSE2+ mode
 536   if (UseSSE >= 2) {
 537     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 538   } else {
 539     __ empty_FPU_stack();
 540   }
 541 #endif /* COMPILER2 */
 542 
 543   // VM needs caller's callsite
 544   __ push(rax);
 545   // VM needs target method
 546   __ push(rbx);
 547   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 548   __ addptr(rsp, 2*wordSize);
 549 
 550   if (UseSSE == 1) {
 551     __ movflt(xmm0, Address(rsp, 0));
 552     __ movflt(xmm1, Address(rsp, wordSize));
 553     __ addptr(rsp, 2*wordSize);
 554   }
 555   if (UseSSE >= 2) {
 556     __ movdbl(xmm0, Address(rsp, 0));
 557     __ movdbl(xmm1, Address(rsp, 2*wordSize));
 558     __ addptr(rsp, 4*wordSize);
 559   }
 560 
 561   __ popf();
 562   __ popa();
 563   __ bind(L);
 564 }
 565 
 566 
 567 static void move_c2i_double(MacroAssembler *masm, XMMRegister r, int st_off) {
 568   int next_off = st_off - Interpreter::stackElementSize;
 569   __ movdbl(Address(rsp, next_off), r);
 570 }
 571 
 572 static void gen_c2i_adapter(MacroAssembler *masm,
 573                             int total_args_passed,
 574                             int comp_args_on_stack,
 575                             const BasicType *sig_bt,
 576                             const VMRegPair *regs,
 577                             Label& skip_fixup) {
 578   // Before we get into the guts of the C2I adapter, see if we should be here
 579   // at all.  We've come from compiled code and are attempting to jump to the
 580   // interpreter, which means the caller made a static call to get here
 581   // (vcalls always get a compiled target if there is one).  Check for a
 582   // compiled target.  If there is one, we need to patch the caller's call.
 583   patch_callers_callsite(masm);
 584 
 585   __ bind(skip_fixup);
 586 
 587 #ifdef COMPILER2
 588   // C2 may leave the stack dirty if not in SSE2+ mode
 589   if (UseSSE >= 2) {
 590     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 591   } else {
 592     __ empty_FPU_stack();
 593   }
 594 #endif /* COMPILER2 */
 595 
 596   // Since all args are passed on the stack, total_args_passed * interpreter_
 597   // stack_element_size  is the
 598   // space we need.
 599   int extraspace = total_args_passed * Interpreter::stackElementSize;
 600 
 601   // Get return address
 602   __ pop(rax);
 603 
 604   // set senderSP value
 605   __ movptr(rsi, rsp);
 606 
 607   __ subptr(rsp, extraspace);
 608 
 609   // Now write the args into the outgoing interpreter space
 610   for (int i = 0; i < total_args_passed; i++) {
 611     if (sig_bt[i] == T_VOID) {
 612       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 613       continue;
 614     }
 615 
 616     // st_off points to lowest address on stack.
 617     int st_off = ((total_args_passed - 1) - i) * Interpreter::stackElementSize;
 618     int next_off = st_off - Interpreter::stackElementSize;
 619 
 620     // Say 4 args:
 621     // i   st_off
 622     // 0   12 T_LONG
 623     // 1    8 T_VOID
 624     // 2    4 T_OBJECT
 625     // 3    0 T_BOOL
 626     VMReg r_1 = regs[i].first();
 627     VMReg r_2 = regs[i].second();
 628     if (!r_1->is_valid()) {
 629       assert(!r_2->is_valid(), "");
 630       continue;
 631     }
 632 
 633     if (r_1->is_stack()) {
 634       // memory to memory use fpu stack top
 635       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 636 
 637       if (!r_2->is_valid()) {
 638         __ movl(rdi, Address(rsp, ld_off));
 639         __ movptr(Address(rsp, st_off), rdi);
 640       } else {
 641 
 642         // ld_off == LSW, ld_off+VMRegImpl::stack_slot_size == MSW
 643         // st_off == MSW, st_off-wordSize == LSW
 644 
 645         __ movptr(rdi, Address(rsp, ld_off));
 646         __ movptr(Address(rsp, next_off), rdi);
 647 #ifndef _LP64
 648         __ movptr(rdi, Address(rsp, ld_off + wordSize));
 649         __ movptr(Address(rsp, st_off), rdi);
 650 #else
 651 #ifdef ASSERT
 652         // Overwrite the unused slot with known junk
 653         __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 654         __ movptr(Address(rsp, st_off), rax);
 655 #endif /* ASSERT */
 656 #endif // _LP64
 657       }
 658     } else if (r_1->is_Register()) {
 659       Register r = r_1->as_Register();
 660       if (!r_2->is_valid()) {
 661         __ movl(Address(rsp, st_off), r);
 662       } else {
 663         // long/double in gpr
 664         NOT_LP64(ShouldNotReachHere());
 665         // Two VMRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 666         // T_DOUBLE and T_LONG use two slots in the interpreter
 667         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 668           // long/double in gpr
 669 #ifdef ASSERT
 670           // Overwrite the unused slot with known junk
 671           LP64_ONLY(__ mov64(rax, CONST64(0xdeadffffdeadaaab)));
 672           __ movptr(Address(rsp, st_off), rax);
 673 #endif /* ASSERT */
 674           __ movptr(Address(rsp, next_off), r);
 675         } else {
 676           __ movptr(Address(rsp, st_off), r);
 677         }
 678       }
 679     } else {
 680       assert(r_1->is_XMMRegister(), "");
 681       if (!r_2->is_valid()) {
 682         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 683       } else {
 684         assert(sig_bt[i] == T_DOUBLE || sig_bt[i] == T_LONG, "wrong type");
 685         move_c2i_double(masm, r_1->as_XMMRegister(), st_off);
 686       }
 687     }
 688   }
 689 
 690   // Schedule the branch target address early.
 691   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 692   // And repush original return address
 693   __ push(rax);
 694   __ jmp(rcx);
 695 }
 696 
 697 
 698 static void move_i2c_double(MacroAssembler *masm, XMMRegister r, Register saved_sp, int ld_off) {
 699   int next_val_off = ld_off - Interpreter::stackElementSize;
 700   __ movdbl(r, Address(saved_sp, next_val_off));
 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   // Note: rsi contains the senderSP on entry. We must preserve it since
 722   // we may do a i2c -> c2i transition if we lose a race where compiled
 723   // code goes non-entrant while we get args ready.
 724 
 725   // Adapters can be frameless because they do not require the caller
 726   // to perform additional cleanup work, such as correcting the stack pointer.
 727   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 728   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 729   // even if a callee has modified the stack pointer.
 730   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 731   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 732   // up via the senderSP register).
 733   // In other words, if *either* the caller or callee is interpreted, we can
 734   // get the stack pointer repaired after a call.
 735   // This is why c2i and i2c adapters cannot be indefinitely composed.
 736   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 737   // both caller and callee would be compiled methods, and neither would
 738   // clean up the stack pointer changes performed by the two adapters.
 739   // If this happens, control eventually transfers back to the compiled
 740   // caller, but with an uncorrected stack, causing delayed havoc.
 741 
 742   // Pick up the return address
 743   __ movptr(rax, Address(rsp, 0));
 744 
 745   if (VerifyAdapterCalls &&
 746       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 747     // So, let's test for cascading c2i/i2c adapters right now.
 748     //  assert(Interpreter::contains($return_addr) ||
 749     //         StubRoutines::contains($return_addr),
 750     //         "i2c adapter must return to an interpreter frame");
 751     __ block_comment("verify_i2c { ");
 752     Label L_ok;
 753     if (Interpreter::code() != NULL)
 754       range_check(masm, rax, rdi,
 755                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 756                   L_ok);
 757     if (StubRoutines::code1() != NULL)
 758       range_check(masm, rax, rdi,
 759                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 760                   L_ok);
 761     if (StubRoutines::code2() != NULL)
 762       range_check(masm, rax, rdi,
 763                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 764                   L_ok);
 765     const char* msg = "i2c adapter must return to an interpreter frame";
 766     __ block_comment(msg);
 767     __ stop(msg);
 768     __ bind(L_ok);
 769     __ block_comment("} verify_i2ce ");
 770   }
 771 
 772   // Must preserve original SP for loading incoming arguments because
 773   // we need to align the outgoing SP for compiled code.
 774   __ movptr(rdi, rsp);
 775 
 776   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 777   // in registers, we will occasionally have no stack args.
 778   int comp_words_on_stack = 0;
 779   if (comp_args_on_stack) {
 780     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 781     // registers are below.  By subtracting stack0, we either get a negative
 782     // number (all values in registers) or the maximum stack slot accessed.
 783     // int comp_args_on_stack = VMRegImpl::reg2stack(max_arg);
 784     // Convert 4-byte stack slots to words.
 785     comp_words_on_stack = align_up(comp_args_on_stack*4, wordSize)>>LogBytesPerWord;
 786     // Round up to miminum stack alignment, in wordSize
 787     comp_words_on_stack = align_up(comp_words_on_stack, 2);
 788     __ subptr(rsp, comp_words_on_stack * wordSize);
 789   }
 790 
 791   // Align the outgoing SP
 792   __ andptr(rsp, -(StackAlignmentInBytes));
 793 
 794   // push the return address on the stack (note that pushing, rather
 795   // than storing it, yields the correct frame alignment for the callee)
 796   __ push(rax);
 797 
 798   // Put saved SP in another register
 799   const Register saved_sp = rax;
 800   __ movptr(saved_sp, rdi);
 801 
 802 
 803   // Will jump to the compiled code just as if compiled code was doing it.
 804   // Pre-load the register-jump target early, to schedule it better.
 805   __ movptr(rdi, Address(rbx, in_bytes(Method::from_compiled_offset())));
 806 
 807   // Now generate the shuffle code.  Pick up all register args and move the
 808   // rest through the floating point stack top.
 809   for (int i = 0; i < total_args_passed; i++) {
 810     if (sig_bt[i] == T_VOID) {
 811       // Longs and doubles are passed in native word order, but misaligned
 812       // in the 32-bit build.
 813       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 814       continue;
 815     }
 816 
 817     // Pick up 0, 1 or 2 words from SP+offset.
 818 
 819     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 820             "scrambled load targets?");
 821     // Load in argument order going down.
 822     int ld_off = (total_args_passed - i) * Interpreter::stackElementSize;
 823     // Point to interpreter value (vs. tag)
 824     int next_off = ld_off - Interpreter::stackElementSize;
 825     //
 826     //
 827     //
 828     VMReg r_1 = regs[i].first();
 829     VMReg r_2 = regs[i].second();
 830     if (!r_1->is_valid()) {
 831       assert(!r_2->is_valid(), "");
 832       continue;
 833     }
 834     if (r_1->is_stack()) {
 835       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 836       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 837 
 838       // We can use rsi as a temp here because compiled code doesn't need rsi as an input
 839       // and if we end up going thru a c2i because of a miss a reasonable value of rsi
 840       // we be generated.
 841       if (!r_2->is_valid()) {
 842         // __ fld_s(Address(saved_sp, ld_off));
 843         // __ fstp_s(Address(rsp, st_off));
 844         __ movl(rsi, Address(saved_sp, ld_off));
 845         __ movptr(Address(rsp, st_off), rsi);
 846       } else {
 847         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 848         // are accessed as negative so LSW is at LOW address
 849 
 850         // ld_off is MSW so get LSW
 851         // st_off is LSW (i.e. reg.first())
 852         // __ fld_d(Address(saved_sp, next_off));
 853         // __ fstp_d(Address(rsp, st_off));
 854         //
 855         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 856         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 857         // So we must adjust where to pick up the data to match the interpreter.
 858         //
 859         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 860         // are accessed as negative so LSW is at LOW address
 861 
 862         // ld_off is MSW so get LSW
 863         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 864                            next_off : ld_off;
 865         __ movptr(rsi, Address(saved_sp, offset));
 866         __ movptr(Address(rsp, st_off), rsi);
 867 #ifndef _LP64
 868         __ movptr(rsi, Address(saved_sp, ld_off));
 869         __ movptr(Address(rsp, st_off + wordSize), rsi);
 870 #endif // _LP64
 871       }
 872     } else if (r_1->is_Register()) {  // Register argument
 873       Register r = r_1->as_Register();
 874       assert(r != rax, "must be different");
 875       if (r_2->is_valid()) {
 876         //
 877         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 878         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 879         // So we must adjust where to pick up the data to match the interpreter.
 880 
 881         const int offset = (NOT_LP64(true ||) sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 882                            next_off : ld_off;
 883 
 884         // this can be a misaligned move
 885         __ movptr(r, Address(saved_sp, offset));
 886 #ifndef _LP64
 887         assert(r_2->as_Register() != rax, "need another temporary register");
 888         // Remember r_1 is low address (and LSB on x86)
 889         // So r_2 gets loaded from high address regardless of the platform
 890         __ movptr(r_2->as_Register(), Address(saved_sp, ld_off));
 891 #endif // _LP64
 892       } else {
 893         __ movl(r, Address(saved_sp, ld_off));
 894       }
 895     } else {
 896       assert(r_1->is_XMMRegister(), "");
 897       if (!r_2->is_valid()) {
 898         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 899       } else {
 900         move_i2c_double(masm, r_1->as_XMMRegister(), saved_sp, ld_off);
 901       }
 902     }
 903   }
 904 
 905   // 6243940 We might end up in handle_wrong_method if
 906   // the callee is deoptimized as we race thru here. If that
 907   // happens we don't want to take a safepoint because the
 908   // caller frame will look interpreted and arguments are now
 909   // "compiled" so it is much better to make this transition
 910   // invisible to the stack walking code. Unfortunately if
 911   // we try and find the callee by normal means a safepoint
 912   // is possible. So we stash the desired callee in the thread
 913   // and the vm will find there should this case occur.
 914 
 915   __ get_thread(rax);
 916   __ movptr(Address(rax, JavaThread::callee_target_offset()), rbx);
 917 
 918   // move Method* to rax, in case we end up in an c2i adapter.
 919   // the c2i adapters expect Method* in rax, (c2) because c2's
 920   // resolve stubs return the result (the method) in rax,.
 921   // I'd love to fix this.
 922   __ mov(rax, rbx);
 923 
 924   __ jmp(rdi);
 925 }
 926 
 927 // ---------------------------------------------------------------
 928 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 929                                                             int total_args_passed,
 930                                                             int comp_args_on_stack,
 931                                                             const BasicType *sig_bt,
 932                                                             const VMRegPair *regs,
 933                                                             AdapterFingerPrint* fingerprint) {
 934   address i2c_entry = __ pc();
 935 
 936   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 937 
 938   // -------------------------------------------------------------------------
 939   // Generate a C2I adapter.  On entry we know rbx, holds the Method* during calls
 940   // to the interpreter.  The args start out packed in the compiled layout.  They
 941   // need to be unpacked into the interpreter layout.  This will almost always
 942   // require some stack space.  We grow the current (compiled) stack, then repack
 943   // the args.  We  finally end in a jump to the generic interpreter entry point.
 944   // On exit from the interpreter, the interpreter will restore our SP (lest the
 945   // compiled code, which relys solely on SP and not EBP, get sick).
 946 
 947   address c2i_unverified_entry = __ pc();
 948   Label skip_fixup;
 949 
 950   Register holder = rax;
 951   Register receiver = rcx;
 952   Register temp = rbx;
 953 
 954   {
 955 
 956     Label missed;
 957     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 958     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 959     __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
 960     __ jcc(Assembler::notEqual, missed);
 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 
 967     __ bind(missed);
 968     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 969   }
 970 
 971   address c2i_entry = __ pc();
 972 
 973   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 974 
 975   __ flush();
 976   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 977 }
 978 
 979 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 980                                          VMRegPair *regs,
 981                                          VMRegPair *regs2,
 982                                          int total_args_passed) {
 983   assert(regs2 == NULL, "not needed on x86");
 984 // We return the amount of VMRegImpl stack slots we need to reserve for all
 985 // the arguments NOT counting out_preserve_stack_slots.
 986 
 987   uint    stack = 0;        // All arguments on stack
 988 
 989   for( int i = 0; i < total_args_passed; i++) {
 990     // From the type and the argument number (count) compute the location
 991     switch( sig_bt[i] ) {
 992     case T_BOOLEAN:
 993     case T_CHAR:
 994     case T_FLOAT:
 995     case T_BYTE:
 996     case T_SHORT:
 997     case T_INT:
 998     case T_OBJECT:
 999     case T_ARRAY:
1000     case T_ADDRESS:
1001     case T_METADATA:
1002       regs[i].set1(VMRegImpl::stack2reg(stack++));
1003       break;
1004     case T_LONG:
1005     case T_DOUBLE: // The stack numbering is reversed from Java
1006       // Since C arguments do not get reversed, the ordering for
1007       // doubles on the stack must be opposite the Java convention
1008       assert((i + 1) < total_args_passed && sig_bt[i+1] == T_VOID, "missing Half" );
1009       regs[i].set2(VMRegImpl::stack2reg(stack));
1010       stack += 2;
1011       break;
1012     case T_VOID: regs[i].set_bad(); break;
1013     default:
1014       ShouldNotReachHere();
1015       break;
1016     }
1017   }
1018   return stack;
1019 }
1020 
1021 // A simple move of integer like type
1022 static void simple_move32(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1023   if (src.first()->is_stack()) {
1024     if (dst.first()->is_stack()) {
1025       // stack to stack
1026       // __ ld(FP, reg2offset(src.first()) + STACK_BIAS, L5);
1027       // __ st(L5, SP, reg2offset(dst.first()) + STACK_BIAS);
1028       __ movl2ptr(rax, Address(rbp, reg2offset_in(src.first())));
1029       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1030     } else {
1031       // stack to reg
1032       __ movl2ptr(dst.first()->as_Register(),  Address(rbp, reg2offset_in(src.first())));
1033     }
1034   } else if (dst.first()->is_stack()) {
1035     // reg to stack
1036     // no need to sign extend on 64bit
1037     __ movptr(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1038   } else {
1039     if (dst.first() != src.first()) {
1040       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1041     }
1042   }
1043 }
1044 
1045 // An oop arg. Must pass a handle not the oop itself
1046 static void object_move(MacroAssembler* masm,
1047                         OopMap* map,
1048                         int oop_handle_offset,
1049                         int framesize_in_slots,
1050                         VMRegPair src,
1051                         VMRegPair dst,
1052                         bool is_receiver,
1053                         int* receiver_offset) {
1054 
1055   // Because of the calling conventions we know that src can be a
1056   // register or a stack location. dst can only be a stack location.
1057 
1058   assert(dst.first()->is_stack(), "must be stack");
1059   // must pass a handle. First figure out the location we use as a handle
1060 
1061   if (src.first()->is_stack()) {
1062     // Oop is already on the stack as an argument
1063     Register rHandle = rax;
1064     Label nil;
1065     __ xorptr(rHandle, rHandle);
1066     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1067     __ jcc(Assembler::equal, nil);
1068     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1069     __ bind(nil);
1070     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1071 
1072     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1073     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1074     if (is_receiver) {
1075       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1076     }
1077   } else {
1078     // Oop is in an a register we must store it to the space we reserve
1079     // on the stack for oop_handles
1080     const Register rOop = src.first()->as_Register();
1081     const Register rHandle = rax;
1082     int oop_slot = (rOop == rcx ? 0 : 1) * VMRegImpl::slots_per_word + oop_handle_offset;
1083     int offset = oop_slot*VMRegImpl::stack_slot_size;
1084     Label skip;
1085     __ movptr(Address(rsp, offset), rOop);
1086     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1087     __ xorptr(rHandle, rHandle);
1088     __ cmpptr(rOop, (int32_t)NULL_WORD);
1089     __ jcc(Assembler::equal, skip);
1090     __ lea(rHandle, Address(rsp, offset));
1091     __ bind(skip);
1092     // Store the handle parameter
1093     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1094     if (is_receiver) {
1095       *receiver_offset = offset;
1096     }
1097   }
1098 }
1099 
1100 // A float arg may have to do float reg int reg conversion
1101 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1102   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1103 
1104   // Because of the calling convention we know that src is either a stack location
1105   // or an xmm register. dst can only be a stack location.
1106 
1107   assert(dst.first()->is_stack() && ( src.first()->is_stack() || src.first()->is_XMMRegister()), "bad parameters");
1108 
1109   if (src.first()->is_stack()) {
1110     __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1111     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1112   } else {
1113     // reg to stack
1114     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1115   }
1116 }
1117 
1118 // A long move
1119 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1120 
1121   // The only legal possibility for a long_move VMRegPair is:
1122   // 1: two stack slots (possibly unaligned)
1123   // as neither the java  or C calling convention will use registers
1124   // for longs.
1125 
1126   if (src.first()->is_stack() && dst.first()->is_stack()) {
1127     assert(src.second()->is_stack() && dst.second()->is_stack(), "must be all stack");
1128     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1129     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1130     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1131     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1132   } else {
1133     ShouldNotReachHere();
1134   }
1135 }
1136 
1137 // A double move
1138 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1139 
1140   // The only legal possibilities for a double_move VMRegPair are:
1141   // The painful thing here is that like long_move a VMRegPair might be
1142 
1143   // Because of the calling convention we know that src is either
1144   //   1: a single physical register (xmm registers only)
1145   //   2: two stack slots (possibly unaligned)
1146   // dst can only be a pair of stack slots.
1147 
1148   assert(dst.first()->is_stack() && (src.first()->is_XMMRegister() || src.first()->is_stack()), "bad args");
1149 
1150   if (src.first()->is_stack()) {
1151     // source is all stack
1152     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1153     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1154     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1155     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1156   } else {
1157     // reg to stack
1158     // No worries about stack alignment
1159     __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1160   }
1161 }
1162 
1163 
1164 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1165   // We always ignore the frame_slots arg and just use the space just below frame pointer
1166   // which by this time is free to use
1167   switch (ret_type) {
1168   case T_FLOAT:
1169     __ fstp_s(Address(rbp, -wordSize));
1170     break;
1171   case T_DOUBLE:
1172     __ fstp_d(Address(rbp, -2*wordSize));
1173     break;
1174   case T_VOID:  break;
1175   case T_LONG:
1176     __ movptr(Address(rbp, -wordSize), rax);
1177     NOT_LP64(__ movptr(Address(rbp, -2*wordSize), rdx));
1178     break;
1179   default: {
1180     __ movptr(Address(rbp, -wordSize), rax);
1181     }
1182   }
1183 }
1184 
1185 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1186   // We always ignore the frame_slots arg and just use the space just below frame pointer
1187   // which by this time is free to use
1188   switch (ret_type) {
1189   case T_FLOAT:
1190     __ fld_s(Address(rbp, -wordSize));
1191     break;
1192   case T_DOUBLE:
1193     __ fld_d(Address(rbp, -2*wordSize));
1194     break;
1195   case T_LONG:
1196     __ movptr(rax, Address(rbp, -wordSize));
1197     NOT_LP64(__ movptr(rdx, Address(rbp, -2*wordSize)));
1198     break;
1199   case T_VOID:  break;
1200   default: {
1201     __ movptr(rax, Address(rbp, -wordSize));
1202     }
1203   }
1204 }
1205 
1206 
1207 static void save_or_restore_arguments(MacroAssembler* masm,
1208                                       const int stack_slots,
1209                                       const int total_in_args,
1210                                       const int arg_save_area,
1211                                       OopMap* map,
1212                                       VMRegPair* in_regs,
1213                                       BasicType* in_sig_bt) {
1214   // if map is non-NULL then the code should store the values,
1215   // otherwise it should load them.
1216   int handle_index = 0;
1217   // Save down double word first
1218   for ( int i = 0; i < total_in_args; i++) {
1219     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1220       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1221       int offset = slot * VMRegImpl::stack_slot_size;
1222       handle_index += 2;
1223       assert(handle_index <= stack_slots, "overflow");
1224       if (map != NULL) {
1225         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1226       } else {
1227         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1228       }
1229     }
1230     if (in_regs[i].first()->is_Register() && in_sig_bt[i] == T_LONG) {
1231       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1232       int offset = slot * VMRegImpl::stack_slot_size;
1233       handle_index += 2;
1234       assert(handle_index <= stack_slots, "overflow");
1235       if (map != NULL) {
1236         __ movl(Address(rsp, offset), in_regs[i].first()->as_Register());
1237         if (in_regs[i].second()->is_Register()) {
1238           __ movl(Address(rsp, offset + 4), in_regs[i].second()->as_Register());
1239         }
1240       } else {
1241         __ movl(in_regs[i].first()->as_Register(), Address(rsp, offset));
1242         if (in_regs[i].second()->is_Register()) {
1243           __ movl(in_regs[i].second()->as_Register(), Address(rsp, offset + 4));
1244         }
1245       }
1246     }
1247   }
1248   // Save or restore single word registers
1249   for ( int i = 0; i < total_in_args; i++) {
1250     if (in_regs[i].first()->is_Register()) {
1251       int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1252       int offset = slot * VMRegImpl::stack_slot_size;
1253       assert(handle_index <= stack_slots, "overflow");
1254       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1255         map->set_oop(VMRegImpl::stack2reg(slot));;
1256       }
1257 
1258       // Value is in an input register pass we must flush it to the stack
1259       const Register reg = in_regs[i].first()->as_Register();
1260       switch (in_sig_bt[i]) {
1261         case T_ARRAY:
1262           if (map != NULL) {
1263             __ movptr(Address(rsp, offset), reg);
1264           } else {
1265             __ movptr(reg, Address(rsp, offset));
1266           }
1267           break;
1268         case T_BOOLEAN:
1269         case T_CHAR:
1270         case T_BYTE:
1271         case T_SHORT:
1272         case T_INT:
1273           if (map != NULL) {
1274             __ movl(Address(rsp, offset), reg);
1275           } else {
1276             __ movl(reg, Address(rsp, offset));
1277           }
1278           break;
1279         case T_OBJECT:
1280         default: ShouldNotReachHere();
1281       }
1282     } else if (in_regs[i].first()->is_XMMRegister()) {
1283       if (in_sig_bt[i] == T_FLOAT) {
1284         int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1285         int offset = slot * VMRegImpl::stack_slot_size;
1286         assert(handle_index <= stack_slots, "overflow");
1287         if (map != NULL) {
1288           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1289         } else {
1290           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1291         }
1292       }
1293     } else if (in_regs[i].first()->is_stack()) {
1294       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1295         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1296         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1297       }
1298     }
1299   }
1300 }
1301 
1302 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1303 // keeps a new JNI critical region from starting until a GC has been
1304 // forced.  Save down any oops in registers and describe them in an
1305 // OopMap.
1306 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1307                                                Register thread,
1308                                                int stack_slots,
1309                                                int total_c_args,
1310                                                int total_in_args,
1311                                                int arg_save_area,
1312                                                OopMapSet* oop_maps,
1313                                                VMRegPair* in_regs,
1314                                                BasicType* in_sig_bt) {
1315   __ block_comment("check GCLocker::needs_gc");
1316   Label cont;
1317   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1318   __ jcc(Assembler::equal, cont);
1319 
1320   // Save down any incoming oops and call into the runtime to halt for a GC
1321 
1322   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1323 
1324   save_or_restore_arguments(masm, stack_slots, total_in_args,
1325                             arg_save_area, map, in_regs, in_sig_bt);
1326 
1327   address the_pc = __ pc();
1328   oop_maps->add_gc_map( __ offset(), map);
1329   __ set_last_Java_frame(thread, rsp, noreg, the_pc);
1330 
1331   __ block_comment("block_for_jni_critical");
1332   __ push(thread);
1333   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1334   __ increment(rsp, wordSize);
1335 
1336   __ get_thread(thread);
1337   __ reset_last_Java_frame(thread, false);
1338 
1339   save_or_restore_arguments(masm, stack_slots, total_in_args,
1340                             arg_save_area, NULL, in_regs, in_sig_bt);
1341 
1342   __ bind(cont);
1343 #ifdef ASSERT
1344   if (StressCriticalJNINatives) {
1345     // Stress register saving
1346     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1347     save_or_restore_arguments(masm, stack_slots, total_in_args,
1348                               arg_save_area, map, in_regs, in_sig_bt);
1349     // Destroy argument registers
1350     for (int i = 0; i < total_in_args - 1; i++) {
1351       if (in_regs[i].first()->is_Register()) {
1352         const Register reg = in_regs[i].first()->as_Register();
1353         __ xorptr(reg, reg);
1354       } else if (in_regs[i].first()->is_XMMRegister()) {
1355         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1356       } else if (in_regs[i].first()->is_FloatRegister()) {
1357         ShouldNotReachHere();
1358       } else if (in_regs[i].first()->is_stack()) {
1359         // Nothing to do
1360       } else {
1361         ShouldNotReachHere();
1362       }
1363       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1364         i++;
1365       }
1366     }
1367 
1368     save_or_restore_arguments(masm, stack_slots, total_in_args,
1369                               arg_save_area, NULL, in_regs, in_sig_bt);
1370   }
1371 #endif
1372 }
1373 
1374 // Unpack an array argument into a pointer to the body and the length
1375 // if the array is non-null, otherwise pass 0 for both.
1376 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1377   Register tmp_reg = rax;
1378   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1379          "possible collision");
1380   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1381          "possible collision");
1382 
1383   // Pass the length, ptr pair
1384   Label is_null, done;
1385   VMRegPair tmp(tmp_reg->as_VMReg());
1386   if (reg.first()->is_stack()) {
1387     // Load the arg up from the stack
1388     simple_move32(masm, reg, tmp);
1389     reg = tmp;
1390   }
1391   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1392   __ jccb(Assembler::equal, is_null);
1393   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1394   simple_move32(masm, tmp, body_arg);
1395   // load the length relative to the body.
1396   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1397                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1398   simple_move32(masm, tmp, length_arg);
1399   __ jmpb(done);
1400   __ bind(is_null);
1401   // Pass zeros
1402   __ xorptr(tmp_reg, tmp_reg);
1403   simple_move32(masm, tmp, body_arg);
1404   simple_move32(masm, tmp, length_arg);
1405   __ bind(done);
1406 }
1407 
1408 static void verify_oop_args(MacroAssembler* masm,
1409                             methodHandle method,
1410                             const BasicType* sig_bt,
1411                             const VMRegPair* regs) {
1412   Register temp_reg = rbx;  // not part of any compiled calling seq
1413   if (VerifyOops) {
1414     for (int i = 0; i < method->size_of_parameters(); i++) {
1415       if (sig_bt[i] == T_OBJECT ||
1416           sig_bt[i] == T_ARRAY) {
1417         VMReg r = regs[i].first();
1418         assert(r->is_valid(), "bad oop arg");
1419         if (r->is_stack()) {
1420           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1421           __ verify_oop(temp_reg);
1422         } else {
1423           __ verify_oop(r->as_Register());
1424         }
1425       }
1426     }
1427   }
1428 }
1429 
1430 static void gen_special_dispatch(MacroAssembler* masm,
1431                                  methodHandle method,
1432                                  const BasicType* sig_bt,
1433                                  const VMRegPair* regs) {
1434   verify_oop_args(masm, method, sig_bt, regs);
1435   vmIntrinsics::ID iid = method->intrinsic_id();
1436 
1437   // Now write the args into the outgoing interpreter space
1438   bool     has_receiver   = false;
1439   Register receiver_reg   = noreg;
1440   int      member_arg_pos = -1;
1441   Register member_reg     = noreg;
1442   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1443   if (ref_kind != 0) {
1444     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1445     member_reg = rbx;  // known to be free at this point
1446     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1447   } else if (iid == vmIntrinsics::_invokeBasic) {
1448     has_receiver = true;
1449   } else {
1450     fatal("unexpected intrinsic id %d", iid);
1451   }
1452 
1453   if (member_reg != noreg) {
1454     // Load the member_arg into register, if necessary.
1455     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1456     VMReg r = regs[member_arg_pos].first();
1457     if (r->is_stack()) {
1458       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1459     } else {
1460       // no data motion is needed
1461       member_reg = r->as_Register();
1462     }
1463   }
1464 
1465   if (has_receiver) {
1466     // Make sure the receiver is loaded into a register.
1467     assert(method->size_of_parameters() > 0, "oob");
1468     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1469     VMReg r = regs[0].first();
1470     assert(r->is_valid(), "bad receiver arg");
1471     if (r->is_stack()) {
1472       // Porting note:  This assumes that compiled calling conventions always
1473       // pass the receiver oop in a register.  If this is not true on some
1474       // platform, pick a temp and load the receiver from stack.
1475       fatal("receiver always in a register");
1476       receiver_reg = rcx;  // known to be free at this point
1477       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1478     } else {
1479       // no data motion is needed
1480       receiver_reg = r->as_Register();
1481     }
1482   }
1483 
1484   // Figure out which address we are really jumping to:
1485   MethodHandles::generate_method_handle_dispatch(masm, iid,
1486                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1487 }
1488 
1489 // ---------------------------------------------------------------------------
1490 // Generate a native wrapper for a given method.  The method takes arguments
1491 // in the Java compiled code convention, marshals them to the native
1492 // convention (handlizes oops, etc), transitions to native, makes the call,
1493 // returns to java state (possibly blocking), unhandlizes any result and
1494 // returns.
1495 //
1496 // Critical native functions are a shorthand for the use of
1497 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1498 // functions.  The wrapper is expected to unpack the arguments before
1499 // passing them to the callee and perform checks before and after the
1500 // native call to ensure that they GCLocker
1501 // lock_critical/unlock_critical semantics are followed.  Some other
1502 // parts of JNI setup are skipped like the tear down of the JNI handle
1503 // block and the check for pending exceptions it's impossible for them
1504 // to be thrown.
1505 //
1506 // They are roughly structured like this:
1507 //    if (GCLocker::needs_gc())
1508 //      SharedRuntime::block_for_jni_critical();
1509 //    tranistion to thread_in_native
1510 //    unpack arrray arguments and call native entry point
1511 //    check for safepoint in progress
1512 //    check if any thread suspend flags are set
1513 //      call into JVM and possible unlock the JNI critical
1514 //      if a GC was suppressed while in the critical native.
1515 //    transition back to thread_in_Java
1516 //    return to caller
1517 //
1518 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1519                                                 const methodHandle& method,
1520                                                 int compile_id,
1521                                                 BasicType* in_sig_bt,
1522                                                 VMRegPair* in_regs,
1523                                                 BasicType ret_type) {
1524   if (method->is_method_handle_intrinsic()) {
1525     vmIntrinsics::ID iid = method->intrinsic_id();
1526     intptr_t start = (intptr_t)__ pc();
1527     int vep_offset = ((intptr_t)__ pc()) - start;
1528     gen_special_dispatch(masm,
1529                          method,
1530                          in_sig_bt,
1531                          in_regs);
1532     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1533     __ flush();
1534     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1535     return nmethod::new_native_nmethod(method,
1536                                        compile_id,
1537                                        masm->code(),
1538                                        vep_offset,
1539                                        frame_complete,
1540                                        stack_slots / VMRegImpl::slots_per_word,
1541                                        in_ByteSize(-1),
1542                                        in_ByteSize(-1),
1543                                        (OopMapSet*)NULL);
1544   }
1545   bool is_critical_native = true;
1546   address native_func = method->critical_native_function();
1547   if (native_func == NULL) {
1548     native_func = method->native_function();
1549     is_critical_native = false;
1550   }
1551   assert(native_func != NULL, "must have function");
1552 
1553   // An OopMap for lock (and class if static)
1554   OopMapSet *oop_maps = new OopMapSet();
1555 
1556   // We have received a description of where all the java arg are located
1557   // on entry to the wrapper. We need to convert these args to where
1558   // the jni function will expect them. To figure out where they go
1559   // we convert the java signature to a C signature by inserting
1560   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1561 
1562   const int total_in_args = method->size_of_parameters();
1563   int total_c_args = total_in_args;
1564   if (!is_critical_native) {
1565     total_c_args += 1;
1566     if (method->is_static()) {
1567       total_c_args++;
1568     }
1569   } else {
1570     for (int i = 0; i < total_in_args; i++) {
1571       if (in_sig_bt[i] == T_ARRAY) {
1572         total_c_args++;
1573       }
1574     }
1575   }
1576 
1577   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1578   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1579   BasicType* in_elem_bt = NULL;
1580 
1581   int argc = 0;
1582   if (!is_critical_native) {
1583     out_sig_bt[argc++] = T_ADDRESS;
1584     if (method->is_static()) {
1585       out_sig_bt[argc++] = T_OBJECT;
1586     }
1587 
1588     for (int i = 0; i < total_in_args ; i++ ) {
1589       out_sig_bt[argc++] = in_sig_bt[i];
1590     }
1591   } else {
1592     Thread* THREAD = Thread::current();
1593     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1594     SignatureStream ss(method->signature());
1595     for (int i = 0; i < total_in_args ; i++ ) {
1596       if (in_sig_bt[i] == T_ARRAY) {
1597         // Arrays are passed as int, elem* pair
1598         out_sig_bt[argc++] = T_INT;
1599         out_sig_bt[argc++] = T_ADDRESS;
1600         Symbol* atype = ss.as_symbol(CHECK_NULL);
1601         const char* at = atype->as_C_string();
1602         if (strlen(at) == 2) {
1603           assert(at[0] == '[', "must be");
1604           switch (at[1]) {
1605             case 'B': in_elem_bt[i]  = T_BYTE; break;
1606             case 'C': in_elem_bt[i]  = T_CHAR; break;
1607             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1608             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1609             case 'I': in_elem_bt[i]  = T_INT; break;
1610             case 'J': in_elem_bt[i]  = T_LONG; break;
1611             case 'S': in_elem_bt[i]  = T_SHORT; break;
1612             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1613             default: ShouldNotReachHere();
1614           }
1615         }
1616       } else {
1617         out_sig_bt[argc++] = in_sig_bt[i];
1618         in_elem_bt[i] = T_VOID;
1619       }
1620       if (in_sig_bt[i] != T_VOID) {
1621         assert(in_sig_bt[i] == ss.type(), "must match");
1622         ss.next();
1623       }
1624     }
1625   }
1626 
1627   // Now figure out where the args must be stored and how much stack space
1628   // they require.
1629   int out_arg_slots;
1630   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1631 
1632   // Compute framesize for the wrapper.  We need to handlize all oops in
1633   // registers a max of 2 on x86.
1634 
1635   // Calculate the total number of stack slots we will need.
1636 
1637   // First count the abi requirement plus all of the outgoing args
1638   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1639 
1640   // Now the space for the inbound oop handle area
1641   int total_save_slots = 2 * VMRegImpl::slots_per_word; // 2 arguments passed in registers
1642   if (is_critical_native) {
1643     // Critical natives may have to call out so they need a save area
1644     // for register arguments.
1645     int double_slots = 0;
1646     int single_slots = 0;
1647     for ( int i = 0; i < total_in_args; i++) {
1648       if (in_regs[i].first()->is_Register()) {
1649         const Register reg = in_regs[i].first()->as_Register();
1650         switch (in_sig_bt[i]) {
1651           case T_ARRAY:  // critical array (uses 2 slots on LP64)
1652           case T_BOOLEAN:
1653           case T_BYTE:
1654           case T_SHORT:
1655           case T_CHAR:
1656           case T_INT:  single_slots++; break;
1657           case T_LONG: double_slots++; break;
1658           default:  ShouldNotReachHere();
1659         }
1660       } else if (in_regs[i].first()->is_XMMRegister()) {
1661         switch (in_sig_bt[i]) {
1662           case T_FLOAT:  single_slots++; break;
1663           case T_DOUBLE: double_slots++; break;
1664           default:  ShouldNotReachHere();
1665         }
1666       } else if (in_regs[i].first()->is_FloatRegister()) {
1667         ShouldNotReachHere();
1668       }
1669     }
1670     total_save_slots = double_slots * 2 + single_slots;
1671     // align the save area
1672     if (double_slots != 0) {
1673       stack_slots = align_up(stack_slots, 2);
1674     }
1675   }
1676 
1677   int oop_handle_offset = stack_slots;
1678   stack_slots += total_save_slots;
1679 
1680   // Now any space we need for handlizing a klass if static method
1681 
1682   int klass_slot_offset = 0;
1683   int klass_offset = -1;
1684   int lock_slot_offset = 0;
1685   bool is_static = false;
1686 
1687   if (method->is_static()) {
1688     klass_slot_offset = stack_slots;
1689     stack_slots += VMRegImpl::slots_per_word;
1690     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1691     is_static = true;
1692   }
1693 
1694   // Plus a lock if needed
1695 
1696   if (method->is_synchronized()) {
1697     lock_slot_offset = stack_slots;
1698     stack_slots += VMRegImpl::slots_per_word;
1699   }
1700 
1701   // Now a place (+2) to save return values or temp during shuffling
1702   // + 2 for return address (which we own) and saved rbp,
1703   stack_slots += 4;
1704 
1705   // Ok The space we have allocated will look like:
1706   //
1707   //
1708   // FP-> |                     |
1709   //      |---------------------|
1710   //      | 2 slots for moves   |
1711   //      |---------------------|
1712   //      | lock box (if sync)  |
1713   //      |---------------------| <- lock_slot_offset  (-lock_slot_rbp_offset)
1714   //      | klass (if static)   |
1715   //      |---------------------| <- klass_slot_offset
1716   //      | oopHandle area      |
1717   //      |---------------------| <- oop_handle_offset (a max of 2 registers)
1718   //      | outbound memory     |
1719   //      | based arguments     |
1720   //      |                     |
1721   //      |---------------------|
1722   //      |                     |
1723   // SP-> | out_preserved_slots |
1724   //
1725   //
1726   // ****************************************************************************
1727   // WARNING - on Windows Java Natives use pascal calling convention and pop the
1728   // arguments off of the stack after the jni call. Before the call we can use
1729   // instructions that are SP relative. After the jni call we switch to FP
1730   // relative instructions instead of re-adjusting the stack on windows.
1731   // ****************************************************************************
1732 
1733 
1734   // Now compute actual number of stack words we need rounding to make
1735   // stack properly aligned.
1736   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
1737 
1738   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1739 
1740   intptr_t start = (intptr_t)__ pc();
1741 
1742   // First thing make an ic check to see if we should even be here
1743 
1744   // We are free to use all registers as temps without saving them and
1745   // restoring them except rbp. rbp is the only callee save register
1746   // as far as the interpreter and the compiler(s) are concerned.
1747 
1748 
1749   const Register ic_reg = rax;
1750   const Register receiver = rcx;
1751   Label hit;
1752   Label exception_pending;
1753 
1754   __ verify_oop(receiver);
1755   __ cmpptr(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
1756   __ jcc(Assembler::equal, hit);
1757 
1758   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1759 
1760   // verified entry must be aligned for code patching.
1761   // and the first 5 bytes must be in the same cache line
1762   // if we align at 8 then we will be sure 5 bytes are in the same line
1763   __ align(8);
1764 
1765   __ bind(hit);
1766 
1767   int vep_offset = ((intptr_t)__ pc()) - start;
1768 
1769 #ifdef COMPILER1
1770   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
1771   if ((InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) || (method->intrinsic_id() == vmIntrinsics::_identityHashCode)) {
1772     inline_check_hashcode_from_object_header(masm, method, rcx /*obj_reg*/, rax /*result*/);
1773    }
1774 #endif // COMPILER1
1775 
1776   // The instruction at the verified entry point must be 5 bytes or longer
1777   // because it can be patched on the fly by make_non_entrant. The stack bang
1778   // instruction fits that requirement.
1779 
1780   // Generate stack overflow check
1781 
1782   if (UseStackBanging) {
1783     __ bang_stack_with_offset((int)JavaThread::stack_shadow_zone_size());
1784   } else {
1785     // need a 5 byte instruction to allow MT safe patching to non-entrant
1786     __ fat_nop();
1787   }
1788 
1789   // Generate a new frame for the wrapper.
1790   __ enter();
1791   // -2 because return address is already present and so is saved rbp
1792   __ subptr(rsp, stack_size - 2*wordSize);
1793 
1794   // Frame is now completed as far as size and linkage.
1795   int frame_complete = ((intptr_t)__ pc()) - start;
1796 
1797   if (UseRTMLocking) {
1798     // Abort RTM transaction before calling JNI
1799     // because critical section will be large and will be
1800     // aborted anyway. Also nmethod could be deoptimized.
1801     __ xabort(0);
1802   }
1803 
1804   // Calculate the difference between rsp and rbp,. We need to know it
1805   // after the native call because on windows Java Natives will pop
1806   // the arguments and it is painful to do rsp relative addressing
1807   // in a platform independent way. So after the call we switch to
1808   // rbp, relative addressing.
1809 
1810   int fp_adjustment = stack_size - 2*wordSize;
1811 
1812 #ifdef COMPILER2
1813   // C2 may leave the stack dirty if not in SSE2+ mode
1814   if (UseSSE >= 2) {
1815     __ verify_FPU(0, "c2i transition should have clean FPU stack");
1816   } else {
1817     __ empty_FPU_stack();
1818   }
1819 #endif /* COMPILER2 */
1820 
1821   // Compute the rbp, offset for any slots used after the jni call
1822 
1823   int lock_slot_rbp_offset = (lock_slot_offset*VMRegImpl::stack_slot_size) - fp_adjustment;
1824 
1825   // We use rdi as a thread pointer because it is callee save and
1826   // if we load it once it is usable thru the entire wrapper
1827   const Register thread = rdi;
1828 
1829   // We use rsi as the oop handle for the receiver/klass
1830   // It is callee save so it survives the call to native
1831 
1832   const Register oop_handle_reg = rsi;
1833 
1834   __ get_thread(thread);
1835 
1836   if (is_critical_native) {
1837     check_needs_gc_for_critical_native(masm, thread, stack_slots, total_c_args, total_in_args,
1838                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
1839   }
1840 
1841   //
1842   // We immediately shuffle the arguments so that any vm call we have to
1843   // make from here on out (sync slow path, jvmti, etc.) we will have
1844   // captured the oops from our caller and have a valid oopMap for
1845   // them.
1846 
1847   // -----------------
1848   // The Grand Shuffle
1849   //
1850   // Natives require 1 or 2 extra arguments over the normal ones: the JNIEnv*
1851   // and, if static, the class mirror instead of a receiver.  This pretty much
1852   // guarantees that register layout will not match (and x86 doesn't use reg
1853   // parms though amd does).  Since the native abi doesn't use register args
1854   // and the java conventions does we don't have to worry about collisions.
1855   // All of our moved are reg->stack or stack->stack.
1856   // We ignore the extra arguments during the shuffle and handle them at the
1857   // last moment. The shuffle is described by the two calling convention
1858   // vectors we have in our possession. We simply walk the java vector to
1859   // get the source locations and the c vector to get the destinations.
1860 
1861   int c_arg = is_critical_native ? 0 : (method->is_static() ? 2 : 1 );
1862 
1863   // Record rsp-based slot for receiver on stack for non-static methods
1864   int receiver_offset = -1;
1865 
1866   // This is a trick. We double the stack slots so we can claim
1867   // the oops in the caller's frame. Since we are sure to have
1868   // more args than the caller doubling is enough to make
1869   // sure we can capture all the incoming oop args from the
1870   // caller.
1871   //
1872   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1873 
1874   // Mark location of rbp,
1875   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, rbp->as_VMReg());
1876 
1877   // We know that we only have args in at most two integer registers (rcx, rdx). So rax, rbx
1878   // Are free to temporaries if we have to do  stack to steck moves.
1879   // All inbound args are referenced based on rbp, and all outbound args via rsp.
1880 
1881   for (int i = 0; i < total_in_args ; i++, c_arg++ ) {
1882     switch (in_sig_bt[i]) {
1883       case T_ARRAY:
1884         if (is_critical_native) {
1885           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
1886           c_arg++;
1887           break;
1888         }
1889       case T_OBJECT:
1890         assert(!is_critical_native, "no oop arguments");
1891         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1892                     ((i == 0) && (!is_static)),
1893                     &receiver_offset);
1894         break;
1895       case T_VOID:
1896         break;
1897 
1898       case T_FLOAT:
1899         float_move(masm, in_regs[i], out_regs[c_arg]);
1900           break;
1901 
1902       case T_DOUBLE:
1903         assert( i + 1 < total_in_args &&
1904                 in_sig_bt[i + 1] == T_VOID &&
1905                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1906         double_move(masm, in_regs[i], out_regs[c_arg]);
1907         break;
1908 
1909       case T_LONG :
1910         long_move(masm, in_regs[i], out_regs[c_arg]);
1911         break;
1912 
1913       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1914 
1915       default:
1916         simple_move32(masm, in_regs[i], out_regs[c_arg]);
1917     }
1918   }
1919 
1920   // Pre-load a static method's oop into rsi.  Used both by locking code and
1921   // the normal JNI call code.
1922   if (method->is_static() && !is_critical_native) {
1923 
1924     //  load opp into a register
1925     __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
1926 
1927     // Now handlize the static class mirror it's known not-null.
1928     __ movptr(Address(rsp, klass_offset), oop_handle_reg);
1929     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1930 
1931     // Now get the handle
1932     __ lea(oop_handle_reg, Address(rsp, klass_offset));
1933     // store the klass handle as second argument
1934     __ movptr(Address(rsp, wordSize), oop_handle_reg);
1935   }
1936 
1937   // Change state to native (we save the return address in the thread, since it might not
1938   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1939   // points into the right code segment. It does not have to be the correct return pc.
1940   // We use the same pc/oopMap repeatedly when we call out
1941 
1942   intptr_t the_pc = (intptr_t) __ pc();
1943   oop_maps->add_gc_map(the_pc - start, map);
1944 
1945   __ set_last_Java_frame(thread, rsp, noreg, (address)the_pc);
1946 
1947 
1948   // We have all of the arguments setup at this point. We must not touch any register
1949   // argument registers at this point (what if we save/restore them there are no oop?
1950 
1951   {
1952     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
1953     __ mov_metadata(rax, method());
1954     __ call_VM_leaf(
1955          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1956          thread, rax);
1957   }
1958 
1959   // RedefineClasses() tracing support for obsolete method entry
1960   if (log_is_enabled(Trace, redefine, class, obsolete)) {
1961     __ mov_metadata(rax, method());
1962     __ call_VM_leaf(
1963          CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1964          thread, rax);
1965   }
1966 
1967   // These are register definitions we need for locking/unlocking
1968   const Register swap_reg = rax;  // Must use rax, for cmpxchg instruction
1969   const Register obj_reg  = rcx;  // Will contain the oop
1970   const Register lock_reg = rdx;  // Address of compiler lock object (BasicLock)
1971 
1972   Label slow_path_lock;
1973   Label lock_done;
1974 
1975   // Lock a synchronized method
1976   if (method->is_synchronized()) {
1977     assert(!is_critical_native, "unhandled");
1978 
1979 
1980     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1981 
1982     // Get the handle (the 2nd argument)
1983     __ movptr(oop_handle_reg, Address(rsp, wordSize));
1984 
1985     // Get address of the box
1986 
1987     __ lea(lock_reg, Address(rbp, lock_slot_rbp_offset));
1988 
1989     // Load the oop from the handle
1990     __ movptr(obj_reg, Address(oop_handle_reg, 0));
1991 
1992     if (UseBiasedLocking) {
1993       // Note that oop_handle_reg is trashed during this call
1994       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, oop_handle_reg, false, lock_done, &slow_path_lock);
1995     }
1996 
1997     // Load immediate 1 into swap_reg %rax,
1998     __ movptr(swap_reg, 1);
1999 
2000     // Load (object->mark() | 1) into swap_reg %rax,
2001     __ orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2002 
2003     // Save (object->mark() | 1) into BasicLock's displaced header
2004     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2005 
2006     if (os::is_MP()) {
2007       __ lock();
2008     }
2009 
2010     // src -> dest iff dest == rax, else rax, <- dest
2011     // *obj_reg = lock_reg iff *obj_reg == rax, else rax, = *(obj_reg)
2012     __ cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2013     __ jcc(Assembler::equal, lock_done);
2014 
2015     // Test if the oopMark is an obvious stack pointer, i.e.,
2016     //  1) (mark & 3) == 0, and
2017     //  2) rsp <= mark < mark + os::pagesize()
2018     // These 3 tests can be done by evaluating the following
2019     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2020     // assuming both stack pointer and pagesize have their
2021     // least significant 2 bits clear.
2022     // NOTE: the oopMark is in swap_reg %rax, as the result of cmpxchg
2023 
2024     __ subptr(swap_reg, rsp);
2025     __ andptr(swap_reg, 3 - os::vm_page_size());
2026 
2027     // Save the test result, for recursive case, the result is zero
2028     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2029     __ jcc(Assembler::notEqual, slow_path_lock);
2030     // Slow path will re-enter here
2031     __ bind(lock_done);
2032 
2033     if (UseBiasedLocking) {
2034       // Re-fetch oop_handle_reg as we trashed it above
2035       __ movptr(oop_handle_reg, Address(rsp, wordSize));
2036     }
2037   }
2038 
2039 
2040   // Finally just about ready to make the JNI call
2041 
2042 
2043   // get JNIEnv* which is first argument to native
2044   if (!is_critical_native) {
2045     __ lea(rdx, Address(thread, in_bytes(JavaThread::jni_environment_offset())));
2046     __ movptr(Address(rsp, 0), rdx);
2047   }
2048 
2049   // Now set thread in native
2050   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native);
2051 
2052   __ call(RuntimeAddress(native_func));
2053 
2054   // Verify or restore cpu control state after JNI call
2055   __ restore_cpu_control_state_after_jni();
2056 
2057   // WARNING - on Windows Java Natives use pascal calling convention and pop the
2058   // arguments off of the stack. We could just re-adjust the stack pointer here
2059   // and continue to do SP relative addressing but we instead switch to FP
2060   // relative addressing.
2061 
2062   // Unpack native results.
2063   switch (ret_type) {
2064   case T_BOOLEAN: __ c2bool(rax);            break;
2065   case T_CHAR   : __ andptr(rax, 0xFFFF);    break;
2066   case T_BYTE   : __ sign_extend_byte (rax); break;
2067   case T_SHORT  : __ sign_extend_short(rax); break;
2068   case T_INT    : /* nothing to do */        break;
2069   case T_DOUBLE :
2070   case T_FLOAT  :
2071     // Result is in st0 we'll save as needed
2072     break;
2073   case T_ARRAY:                 // Really a handle
2074   case T_OBJECT:                // Really a handle
2075       break; // can't de-handlize until after safepoint check
2076   case T_VOID: break;
2077   case T_LONG: break;
2078   default       : ShouldNotReachHere();
2079   }
2080 
2081   // Switch thread to "native transition" state before reading the synchronization state.
2082   // This additional state is necessary because reading and testing the synchronization
2083   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2084   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2085   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2086   //     Thread A is resumed to finish this native method, but doesn't block here since it
2087   //     didn't see any synchronization is progress, and escapes.
2088   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2089 
2090   if(os::is_MP()) {
2091     if (UseMembar) {
2092       // Force this write out before the read below
2093       __ membar(Assembler::Membar_mask_bits(
2094            Assembler::LoadLoad | Assembler::LoadStore |
2095            Assembler::StoreLoad | Assembler::StoreStore));
2096     } else {
2097       // Write serialization page so VM thread can do a pseudo remote membar.
2098       // We use the current thread pointer to calculate a thread specific
2099       // offset to write to within the page. This minimizes bus traffic
2100       // due to cache line collision.
2101       __ serialize_memory(thread, rcx);
2102     }
2103   }
2104 
2105   if (AlwaysRestoreFPU) {
2106     // Make sure the control word is correct.
2107     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2108   }
2109 
2110   Label after_transition;
2111 
2112   // check for safepoint operation in progress and/or pending suspend requests
2113   { Label Continue;
2114 
2115     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
2116              SafepointSynchronize::_not_synchronized);
2117 
2118     Label L;
2119     __ jcc(Assembler::notEqual, L);
2120     __ cmpl(Address(thread, JavaThread::suspend_flags_offset()), 0);
2121     __ jcc(Assembler::equal, Continue);
2122     __ bind(L);
2123 
2124     // Don't use call_VM as it will see a possible pending exception and forward it
2125     // and never return here preventing us from clearing _last_native_pc down below.
2126     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2127     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2128     // by hand.
2129     //
2130     __ vzeroupper();
2131 
2132     save_native_result(masm, ret_type, stack_slots);
2133     __ push(thread);
2134     if (!is_critical_native) {
2135       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2136                                               JavaThread::check_special_condition_for_native_trans)));
2137     } else {
2138       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address,
2139                                               JavaThread::check_special_condition_for_native_trans_and_transition)));
2140     }
2141     __ increment(rsp, wordSize);
2142     // Restore any method result value
2143     restore_native_result(masm, ret_type, stack_slots);
2144 
2145     if (is_critical_native) {
2146       // The call above performed the transition to thread_in_Java so
2147       // skip the transition logic below.
2148       __ jmpb(after_transition);
2149     }
2150 
2151     __ bind(Continue);
2152   }
2153 
2154   // change thread state
2155   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_Java);
2156   __ bind(after_transition);
2157 
2158   Label reguard;
2159   Label reguard_done;
2160   __ cmpl(Address(thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_reserved_disabled);
2161   __ jcc(Assembler::equal, reguard);
2162 
2163   // slow path reguard  re-enters here
2164   __ bind(reguard_done);
2165 
2166   // Handle possible exception (will unlock if necessary)
2167 
2168   // native result if any is live
2169 
2170   // Unlock
2171   Label slow_path_unlock;
2172   Label unlock_done;
2173   if (method->is_synchronized()) {
2174 
2175     Label done;
2176 
2177     // Get locked oop from the handle we passed to jni
2178     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2179 
2180     if (UseBiasedLocking) {
2181       __ biased_locking_exit(obj_reg, rbx, done);
2182     }
2183 
2184     // Simple recursive lock?
2185 
2186     __ cmpptr(Address(rbp, lock_slot_rbp_offset), (int32_t)NULL_WORD);
2187     __ jcc(Assembler::equal, done);
2188 
2189     // Must save rax, if if it is live now because cmpxchg must use it
2190     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2191       save_native_result(masm, ret_type, stack_slots);
2192     }
2193 
2194     //  get old displaced header
2195     __ movptr(rbx, Address(rbp, lock_slot_rbp_offset));
2196 
2197     // get address of the stack lock
2198     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2199 
2200     // Atomic swap old header if oop still contains the stack lock
2201     if (os::is_MP()) {
2202     __ lock();
2203     }
2204 
2205     // src -> dest iff dest == rax, else rax, <- dest
2206     // *obj_reg = rbx, iff *obj_reg == rax, else rax, = *(obj_reg)
2207     __ cmpxchgptr(rbx, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2208     __ jcc(Assembler::notEqual, slow_path_unlock);
2209 
2210     // slow path re-enters here
2211     __ bind(unlock_done);
2212     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2213       restore_native_result(masm, ret_type, stack_slots);
2214     }
2215 
2216     __ bind(done);
2217 
2218   }
2219 
2220   {
2221     SkipIfEqual skip_if(masm, &DTraceMethodProbes, 0);
2222     // Tell dtrace about this method exit
2223     save_native_result(masm, ret_type, stack_slots);
2224     __ mov_metadata(rax, method());
2225     __ call_VM_leaf(
2226          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2227          thread, rax);
2228     restore_native_result(masm, ret_type, stack_slots);
2229   }
2230 
2231   // We can finally stop using that last_Java_frame we setup ages ago
2232 
2233   __ reset_last_Java_frame(thread, false);
2234 
2235   // Unbox oop result, e.g. JNIHandles::resolve value.
2236   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2237     __ resolve_jobject(rax /* value */,
2238                        thread /* thread */,
2239                        rcx /* tmp */);
2240   }
2241 
2242   if (CheckJNICalls) {
2243     // clear_pending_jni_exception_check
2244     __ movptr(Address(thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
2245   }
2246 
2247   if (!is_critical_native) {
2248     // reset handle block
2249     __ movptr(rcx, Address(thread, JavaThread::active_handles_offset()));
2250     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), NULL_WORD);
2251 
2252     // Any exception pending?
2253     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2254     __ jcc(Assembler::notEqual, exception_pending);
2255   }
2256 
2257   // no exception, we're almost done
2258 
2259   // check that only result value is on FPU stack
2260   __ verify_FPU(ret_type == T_FLOAT || ret_type == T_DOUBLE ? 1 : 0, "native_wrapper normal exit");
2261 
2262   // Fixup floating pointer results so that result looks like a return from a compiled method
2263   if (ret_type == T_FLOAT) {
2264     if (UseSSE >= 1) {
2265       // Pop st0 and store as float and reload into xmm register
2266       __ fstp_s(Address(rbp, -4));
2267       __ movflt(xmm0, Address(rbp, -4));
2268     }
2269   } else if (ret_type == T_DOUBLE) {
2270     if (UseSSE >= 2) {
2271       // Pop st0 and store as double and reload into xmm register
2272       __ fstp_d(Address(rbp, -8));
2273       __ movdbl(xmm0, Address(rbp, -8));
2274     }
2275   }
2276 
2277   // Return
2278 
2279   __ leave();
2280   __ ret(0);
2281 
2282   // Unexpected paths are out of line and go here
2283 
2284   // Slow path locking & unlocking
2285   if (method->is_synchronized()) {
2286 
2287     // BEGIN Slow path lock
2288 
2289     __ bind(slow_path_lock);
2290 
2291     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2292     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2293     __ push(thread);
2294     __ push(lock_reg);
2295     __ push(obj_reg);
2296     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C)));
2297     __ addptr(rsp, 3*wordSize);
2298 
2299 #ifdef ASSERT
2300     { Label L;
2301     __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2302     __ jcc(Assembler::equal, L);
2303     __ stop("no pending exception allowed on exit from monitorenter");
2304     __ bind(L);
2305     }
2306 #endif
2307     __ jmp(lock_done);
2308 
2309     // END Slow path lock
2310 
2311     // BEGIN Slow path unlock
2312     __ bind(slow_path_unlock);
2313     __ vzeroupper();
2314     // Slow path unlock
2315 
2316     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2317       save_native_result(masm, ret_type, stack_slots);
2318     }
2319     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2320 
2321     __ pushptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2322     __ movptr(Address(thread, in_bytes(Thread::pending_exception_offset())), NULL_WORD);
2323 
2324 
2325     // should be a peal
2326     // +wordSize because of the push above
2327     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2328     __ push(thread);
2329     __ lea(rax, Address(rbp, lock_slot_rbp_offset));
2330     __ push(rax);
2331 
2332     __ push(obj_reg);
2333     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2334     __ addptr(rsp, 3*wordSize);
2335 #ifdef ASSERT
2336     {
2337       Label L;
2338       __ cmpptr(Address(thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2339       __ jcc(Assembler::equal, L);
2340       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2341       __ bind(L);
2342     }
2343 #endif /* ASSERT */
2344 
2345     __ popptr(Address(thread, in_bytes(Thread::pending_exception_offset())));
2346 
2347     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2348       restore_native_result(masm, ret_type, stack_slots);
2349     }
2350     __ jmp(unlock_done);
2351     // END Slow path unlock
2352 
2353   }
2354 
2355   // SLOW PATH Reguard the stack if needed
2356 
2357   __ bind(reguard);
2358   __ vzeroupper();
2359   save_native_result(masm, ret_type, stack_slots);
2360   {
2361     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2362   }
2363   restore_native_result(masm, ret_type, stack_slots);
2364   __ jmp(reguard_done);
2365 
2366 
2367   // BEGIN EXCEPTION PROCESSING
2368 
2369   if (!is_critical_native) {
2370     // Forward  the exception
2371     __ bind(exception_pending);
2372 
2373     // remove possible return value from FPU register stack
2374     __ empty_FPU_stack();
2375 
2376     // pop our frame
2377     __ leave();
2378     // and forward the exception
2379     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2380   }
2381 
2382   __ flush();
2383 
2384   nmethod *nm = nmethod::new_native_nmethod(method,
2385                                             compile_id,
2386                                             masm->code(),
2387                                             vep_offset,
2388                                             frame_complete,
2389                                             stack_slots / VMRegImpl::slots_per_word,
2390                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2391                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2392                                             oop_maps);
2393 
2394   if (is_critical_native) {
2395     nm->set_lazy_critical_native(true);
2396   }
2397 
2398   return nm;
2399 
2400 }
2401 
2402 // this function returns the adjust size (in number of words) to a c2i adapter
2403 // activation for use during deoptimization
2404 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2405   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2406 }
2407 
2408 
2409 uint SharedRuntime::out_preserve_stack_slots() {
2410   return 0;
2411 }
2412 
2413 //------------------------------generate_deopt_blob----------------------------
2414 void SharedRuntime::generate_deopt_blob() {
2415   // allocate space for the code
2416   ResourceMark rm;
2417   // setup code generation tools
2418   // note: the buffer code size must account for StackShadowPages=50
2419   CodeBuffer   buffer("deopt_blob", 1536, 1024);
2420   MacroAssembler* masm = new MacroAssembler(&buffer);
2421   int frame_size_in_words;
2422   OopMap* map = NULL;
2423   // Account for the extra args we place on the stack
2424   // by the time we call fetch_unroll_info
2425   const int additional_words = 2; // deopt kind, thread
2426 
2427   OopMapSet *oop_maps = new OopMapSet();
2428 
2429   // -------------
2430   // This code enters when returning to a de-optimized nmethod.  A return
2431   // address has been pushed on the the stack, and return values are in
2432   // registers.
2433   // If we are doing a normal deopt then we were called from the patched
2434   // nmethod from the point we returned to the nmethod. So the return
2435   // address on the stack is wrong by NativeCall::instruction_size
2436   // We will adjust the value to it looks like we have the original return
2437   // address on the stack (like when we eagerly deoptimized).
2438   // In the case of an exception pending with deoptimized then we enter
2439   // with a return address on the stack that points after the call we patched
2440   // into the exception handler. We have the following register state:
2441   //    rax,: exception
2442   //    rbx,: exception handler
2443   //    rdx: throwing pc
2444   // So in this case we simply jam rdx into the useless return address and
2445   // the stack looks just like we want.
2446   //
2447   // At this point we need to de-opt.  We save the argument return
2448   // registers.  We call the first C routine, fetch_unroll_info().  This
2449   // routine captures the return values and returns a structure which
2450   // describes the current frame size and the sizes of all replacement frames.
2451   // The current frame is compiled code and may contain many inlined
2452   // functions, each with their own JVM state.  We pop the current frame, then
2453   // push all the new frames.  Then we call the C routine unpack_frames() to
2454   // populate these frames.  Finally unpack_frames() returns us the new target
2455   // address.  Notice that callee-save registers are BLOWN here; they have
2456   // already been captured in the vframeArray at the time the return PC was
2457   // patched.
2458   address start = __ pc();
2459   Label cont;
2460 
2461   // Prolog for non exception case!
2462 
2463   // Save everything in sight.
2464 
2465   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2466   // Normal deoptimization
2467   __ push(Deoptimization::Unpack_deopt);
2468   __ jmp(cont);
2469 
2470   int reexecute_offset = __ pc() - start;
2471 
2472   // Reexecute case
2473   // return address is the pc describes what bci to do re-execute at
2474 
2475   // No need to update map as each call to save_live_registers will produce identical oopmap
2476   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2477 
2478   __ push(Deoptimization::Unpack_reexecute);
2479   __ jmp(cont);
2480 
2481   int exception_offset = __ pc() - start;
2482 
2483   // Prolog for exception case
2484 
2485   // all registers are dead at this entry point, except for rax, and
2486   // rdx which contain the exception oop and exception pc
2487   // respectively.  Set them in TLS and fall thru to the
2488   // unpack_with_exception_in_tls entry point.
2489 
2490   __ get_thread(rdi);
2491   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), rdx);
2492   __ movptr(Address(rdi, JavaThread::exception_oop_offset()), rax);
2493 
2494   int exception_in_tls_offset = __ pc() - start;
2495 
2496   // new implementation because exception oop is now passed in JavaThread
2497 
2498   // Prolog for exception case
2499   // All registers must be preserved because they might be used by LinearScan
2500   // Exceptiop oop and throwing PC are passed in JavaThread
2501   // tos: stack at point of call to method that threw the exception (i.e. only
2502   // args are on the stack, no return address)
2503 
2504   // make room on stack for the return address
2505   // It will be patched later with the throwing pc. The correct value is not
2506   // available now because loading it from memory would destroy registers.
2507   __ push(0);
2508 
2509   // Save everything in sight.
2510 
2511   // No need to update map as each call to save_live_registers will produce identical oopmap
2512   (void) RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false);
2513 
2514   // Now it is safe to overwrite any register
2515 
2516   // store the correct deoptimization type
2517   __ push(Deoptimization::Unpack_exception);
2518 
2519   // load throwing pc from JavaThread and patch it as the return address
2520   // of the current frame. Then clear the field in JavaThread
2521   __ get_thread(rdi);
2522   __ movptr(rdx, Address(rdi, JavaThread::exception_pc_offset()));
2523   __ movptr(Address(rbp, wordSize), rdx);
2524   __ movptr(Address(rdi, JavaThread::exception_pc_offset()), NULL_WORD);
2525 
2526 #ifdef ASSERT
2527   // verify that there is really an exception oop in JavaThread
2528   __ movptr(rax, Address(rdi, JavaThread::exception_oop_offset()));
2529   __ verify_oop(rax);
2530 
2531   // verify that there is no pending exception
2532   Label no_pending_exception;
2533   __ movptr(rax, Address(rdi, Thread::pending_exception_offset()));
2534   __ testptr(rax, rax);
2535   __ jcc(Assembler::zero, no_pending_exception);
2536   __ stop("must not have pending exception here");
2537   __ bind(no_pending_exception);
2538 #endif
2539 
2540   __ bind(cont);
2541 
2542   // Compiled code leaves the floating point stack dirty, empty it.
2543   __ empty_FPU_stack();
2544 
2545 
2546   // Call C code.  Need thread and this frame, but NOT official VM entry
2547   // crud.  We cannot block on this call, no GC can happen.
2548   __ get_thread(rcx);
2549   __ push(rcx);
2550   // fetch_unroll_info needs to call last_java_frame()
2551   __ set_last_Java_frame(rcx, noreg, noreg, NULL);
2552 
2553   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2554 
2555   // Need to have an oopmap that tells fetch_unroll_info where to
2556   // find any register it might need.
2557 
2558   oop_maps->add_gc_map( __ pc()-start, map);
2559 
2560   // Discard args to fetch_unroll_info
2561   __ pop(rcx);
2562   __ pop(rcx);
2563 
2564   __ get_thread(rcx);
2565   __ reset_last_Java_frame(rcx, false);
2566 
2567   // Load UnrollBlock into EDI
2568   __ mov(rdi, rax);
2569 
2570   // Move the unpack kind to a safe place in the UnrollBlock because
2571   // we are very short of registers
2572 
2573   Address unpack_kind(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes());
2574   // retrieve the deopt kind from the UnrollBlock.
2575   __ movl(rax, unpack_kind);
2576 
2577    Label noException;
2578   __ cmpl(rax, Deoptimization::Unpack_exception);   // Was exception pending?
2579   __ jcc(Assembler::notEqual, noException);
2580   __ movptr(rax, Address(rcx, JavaThread::exception_oop_offset()));
2581   __ movptr(rdx, Address(rcx, JavaThread::exception_pc_offset()));
2582   __ movptr(Address(rcx, JavaThread::exception_oop_offset()), NULL_WORD);
2583   __ movptr(Address(rcx, JavaThread::exception_pc_offset()), NULL_WORD);
2584 
2585   __ verify_oop(rax);
2586 
2587   // Overwrite the result registers with the exception results.
2588   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2589   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2590 
2591   __ bind(noException);
2592 
2593   // Stack is back to only having register save data on the stack.
2594   // Now restore the result registers. Everything else is either dead or captured
2595   // in the vframeArray.
2596 
2597   RegisterSaver::restore_result_registers(masm);
2598 
2599   // Non standard control word may be leaked out through a safepoint blob, and we can
2600   // deopt at a poll point with the non standard control word. However, we should make
2601   // sure the control word is correct after restore_result_registers.
2602   __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
2603 
2604   // All of the register save area has been popped of the stack. Only the
2605   // return address remains.
2606 
2607   // Pop all the frames we must move/replace.
2608   //
2609   // Frame picture (youngest to oldest)
2610   // 1: self-frame (no frame link)
2611   // 2: deopting frame  (no frame link)
2612   // 3: caller of deopting frame (could be compiled/interpreted).
2613   //
2614   // Note: by leaving the return address of self-frame on the stack
2615   // and using the size of frame 2 to adjust the stack
2616   // when we are done the return to frame 3 will still be on the stack.
2617 
2618   // Pop deoptimized frame
2619   __ addptr(rsp, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2620 
2621   // sp should be pointing at the return address to the caller (3)
2622 
2623   // Pick up the initial fp we should save
2624   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2625   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2626 
2627 #ifdef ASSERT
2628   // Compilers generate code that bang the stack by as much as the
2629   // interpreter would need. So this stack banging should never
2630   // trigger a fault. Verify that it does not on non product builds.
2631   if (UseStackBanging) {
2632     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2633     __ bang_stack_size(rbx, rcx);
2634   }
2635 #endif
2636 
2637   // Load array of frame pcs into ECX
2638   __ movptr(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2639 
2640   __ pop(rsi); // trash the old pc
2641 
2642   // Load array of frame sizes into ESI
2643   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2644 
2645   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2646 
2647   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2648   __ movl(counter, rbx);
2649 
2650   // Now adjust the caller's stack to make up for the extra locals
2651   // but record the original sp so that we can save it in the skeletal interpreter
2652   // frame and the stack walking of interpreter_sender will get the unextended sp
2653   // value and not the "real" sp value.
2654 
2655   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2656   __ movptr(sp_temp, rsp);
2657   __ movl2ptr(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2658   __ subptr(rsp, rbx);
2659 
2660   // Push interpreter frames in a loop
2661   Label loop;
2662   __ bind(loop);
2663   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2664   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2665   __ pushptr(Address(rcx, 0));          // save return address
2666   __ enter();                           // save old & set new rbp,
2667   __ subptr(rsp, rbx);                  // Prolog!
2668   __ movptr(rbx, sp_temp);              // sender's sp
2669   // This value is corrected by layout_activation_impl
2670   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
2671   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2672   __ movptr(sp_temp, rsp);              // pass to next frame
2673   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2674   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2675   __ decrementl(counter);             // decrement counter
2676   __ jcc(Assembler::notZero, loop);
2677   __ pushptr(Address(rcx, 0));          // save final return address
2678 
2679   // Re-push self-frame
2680   __ enter();                           // save old & set new rbp,
2681 
2682   //  Return address and rbp, are in place
2683   // We'll push additional args later. Just allocate a full sized
2684   // register save area
2685   __ subptr(rsp, (frame_size_in_words-additional_words - 2) * wordSize);
2686 
2687   // Restore frame locals after moving the frame
2688   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2689   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2690   __ fstp_d(Address(rsp, RegisterSaver::fpResultOffset()*wordSize));   // Pop float stack and store in local
2691   if( UseSSE>=2 ) __ movdbl(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2692   if( UseSSE==1 ) __ movflt(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2693 
2694   // Set up the args to unpack_frame
2695 
2696   __ pushl(unpack_kind);                     // get the unpack_kind value
2697   __ get_thread(rcx);
2698   __ push(rcx);
2699 
2700   // set last_Java_sp, last_Java_fp
2701   __ set_last_Java_frame(rcx, noreg, rbp, NULL);
2702 
2703   // Call C code.  Need thread but NOT official VM entry
2704   // crud.  We cannot block on this call, no GC can happen.  Call should
2705   // restore return values to their stack-slots with the new SP.
2706   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2707   // Set an oopmap for the call site
2708   oop_maps->add_gc_map( __ pc()-start, new OopMap( frame_size_in_words, 0 ));
2709 
2710   // rax, contains the return result type
2711   __ push(rax);
2712 
2713   __ get_thread(rcx);
2714   __ reset_last_Java_frame(rcx, false);
2715 
2716   // Collect return values
2717   __ movptr(rax,Address(rsp, (RegisterSaver::raxOffset() + additional_words + 1)*wordSize));
2718   __ movptr(rdx,Address(rsp, (RegisterSaver::rdxOffset() + additional_words + 1)*wordSize));
2719 
2720   // Clear floating point stack before returning to interpreter
2721   __ empty_FPU_stack();
2722 
2723   // Check if we should push the float or double return value.
2724   Label results_done, yes_double_value;
2725   __ cmpl(Address(rsp, 0), T_DOUBLE);
2726   __ jcc (Assembler::zero, yes_double_value);
2727   __ cmpl(Address(rsp, 0), T_FLOAT);
2728   __ jcc (Assembler::notZero, results_done);
2729 
2730   // return float value as expected by interpreter
2731   if( UseSSE>=1 ) __ movflt(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2732   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2733   __ jmp(results_done);
2734 
2735   // return double value as expected by interpreter
2736   __ bind(yes_double_value);
2737   if( UseSSE>=2 ) __ movdbl(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2738   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2739 
2740   __ bind(results_done);
2741 
2742   // Pop self-frame.
2743   __ leave();                              // Epilog!
2744 
2745   // Jump to interpreter
2746   __ ret(0);
2747 
2748   // -------------
2749   // make sure all code is generated
2750   masm->flush();
2751 
2752   _deopt_blob = DeoptimizationBlob::create( &buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2753   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2754 }
2755 
2756 
2757 #ifdef COMPILER2
2758 //------------------------------generate_uncommon_trap_blob--------------------
2759 void SharedRuntime::generate_uncommon_trap_blob() {
2760   // allocate space for the code
2761   ResourceMark rm;
2762   // setup code generation tools
2763   CodeBuffer   buffer("uncommon_trap_blob", 512, 512);
2764   MacroAssembler* masm = new MacroAssembler(&buffer);
2765 
2766   enum frame_layout {
2767     arg0_off,      // thread                     sp + 0 // Arg location for
2768     arg1_off,      // unloaded_class_index       sp + 1 // calling C
2769     arg2_off,      // exec_mode                  sp + 2
2770     // The frame sender code expects that rbp will be in the "natural" place and
2771     // will override any oopMap setting for it. We must therefore force the layout
2772     // so that it agrees with the frame sender code.
2773     rbp_off,       // callee saved register      sp + 3
2774     return_off,    // slot for return address    sp + 4
2775     framesize
2776   };
2777 
2778   address start = __ pc();
2779 
2780   if (UseRTMLocking) {
2781     // Abort RTM transaction before possible nmethod deoptimization.
2782     __ xabort(0);
2783   }
2784 
2785   // Push self-frame.
2786   __ subptr(rsp, return_off*wordSize);     // Epilog!
2787 
2788   // rbp, is an implicitly saved callee saved register (i.e. the calling
2789   // convention will save restore it in prolog/epilog) Other than that
2790   // there are no callee save registers no that adapter frames are gone.
2791   __ movptr(Address(rsp, rbp_off*wordSize), rbp);
2792 
2793   // Clear the floating point exception stack
2794   __ empty_FPU_stack();
2795 
2796   // set last_Java_sp
2797   __ get_thread(rdx);
2798   __ set_last_Java_frame(rdx, noreg, noreg, NULL);
2799 
2800   // Call C code.  Need thread but NOT official VM entry
2801   // crud.  We cannot block on this call, no GC can happen.  Call should
2802   // capture callee-saved registers as well as return values.
2803   __ movptr(Address(rsp, arg0_off*wordSize), rdx);
2804   // argument already in ECX
2805   __ movl(Address(rsp, arg1_off*wordSize),rcx);
2806   __ movl(Address(rsp, arg2_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2807   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2808 
2809   // Set an oopmap for the call site
2810   OopMapSet *oop_maps = new OopMapSet();
2811   OopMap* map =  new OopMap( framesize, 0 );
2812   // No oopMap for rbp, it is known implicitly
2813 
2814   oop_maps->add_gc_map( __ pc()-start, map);
2815 
2816   __ get_thread(rcx);
2817 
2818   __ reset_last_Java_frame(rcx, false);
2819 
2820   // Load UnrollBlock into EDI
2821   __ movptr(rdi, rax);
2822 
2823 #ifdef ASSERT
2824   { Label L;
2825     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
2826             (int32_t)Deoptimization::Unpack_uncommon_trap);
2827     __ jcc(Assembler::equal, L);
2828     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
2829     __ bind(L);
2830   }
2831 #endif
2832 
2833   // Pop all the frames we must move/replace.
2834   //
2835   // Frame picture (youngest to oldest)
2836   // 1: self-frame (no frame link)
2837   // 2: deopting frame  (no frame link)
2838   // 3: caller of deopting frame (could be compiled/interpreted).
2839 
2840   // Pop self-frame.  We have no frame, and must rely only on EAX and ESP.
2841   __ addptr(rsp,(framesize-1)*wordSize);     // Epilog!
2842 
2843   // Pop deoptimized frame
2844   __ movl2ptr(rcx, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2845   __ addptr(rsp, rcx);
2846 
2847   // sp should be pointing at the return address to the caller (3)
2848 
2849   // Pick up the initial fp we should save
2850   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2851   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2852 
2853 #ifdef ASSERT
2854   // Compilers generate code that bang the stack by as much as the
2855   // interpreter would need. So this stack banging should never
2856   // trigger a fault. Verify that it does not on non product builds.
2857   if (UseStackBanging) {
2858     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2859     __ bang_stack_size(rbx, rcx);
2860   }
2861 #endif
2862 
2863   // Load array of frame pcs into ECX
2864   __ movl(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2865 
2866   __ pop(rsi); // trash the pc
2867 
2868   // Load array of frame sizes into ESI
2869   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2870 
2871   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2872 
2873   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2874   __ movl(counter, rbx);
2875 
2876   // Now adjust the caller's stack to make up for the extra locals
2877   // but record the original sp so that we can save it in the skeletal interpreter
2878   // frame and the stack walking of interpreter_sender will get the unextended sp
2879   // value and not the "real" sp value.
2880 
2881   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2882   __ movptr(sp_temp, rsp);
2883   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2884   __ subptr(rsp, rbx);
2885 
2886   // Push interpreter frames in a loop
2887   Label loop;
2888   __ bind(loop);
2889   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2890   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2891   __ pushptr(Address(rcx, 0));          // save return address
2892   __ enter();                           // save old & set new rbp,
2893   __ subptr(rsp, rbx);                  // Prolog!
2894   __ movptr(rbx, sp_temp);              // sender's sp
2895   // This value is corrected by layout_activation_impl
2896   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD );
2897   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2898   __ movptr(sp_temp, rsp);              // pass to next frame
2899   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2900   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2901   __ decrementl(counter);             // decrement counter
2902   __ jcc(Assembler::notZero, loop);
2903   __ pushptr(Address(rcx, 0));            // save final return address
2904 
2905   // Re-push self-frame
2906   __ enter();                           // save old & set new rbp,
2907   __ subptr(rsp, (framesize-2) * wordSize);   // Prolog!
2908 
2909 
2910   // set last_Java_sp, last_Java_fp
2911   __ get_thread(rdi);
2912   __ set_last_Java_frame(rdi, noreg, rbp, NULL);
2913 
2914   // Call C code.  Need thread but NOT official VM entry
2915   // crud.  We cannot block on this call, no GC can happen.  Call should
2916   // restore return values to their stack-slots with the new SP.
2917   __ movptr(Address(rsp,arg0_off*wordSize),rdi);
2918   __ movl(Address(rsp,arg1_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2919   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2920   // Set an oopmap for the call site
2921   oop_maps->add_gc_map( __ pc()-start, new OopMap( framesize, 0 ) );
2922 
2923   __ get_thread(rdi);
2924   __ reset_last_Java_frame(rdi, true);
2925 
2926   // Pop self-frame.
2927   __ leave();     // Epilog!
2928 
2929   // Jump to interpreter
2930   __ ret(0);
2931 
2932   // -------------
2933   // make sure all code is generated
2934   masm->flush();
2935 
2936    _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, framesize);
2937 }
2938 #endif // COMPILER2
2939 
2940 //------------------------------generate_handler_blob------
2941 //
2942 // Generate a special Compile2Runtime blob that saves all registers,
2943 // setup oopmap, and calls safepoint code to stop the compiled code for
2944 // a safepoint.
2945 //
2946 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2947 
2948   // Account for thread arg in our frame
2949   const int additional_words = 1;
2950   int frame_size_in_words;
2951 
2952   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2953 
2954   ResourceMark rm;
2955   OopMapSet *oop_maps = new OopMapSet();
2956   OopMap* map;
2957 
2958   // allocate space for the code
2959   // setup code generation tools
2960   CodeBuffer   buffer("handler_blob", 1024, 512);
2961   MacroAssembler* masm = new MacroAssembler(&buffer);
2962 
2963   const Register java_thread = rdi; // callee-saved for VC++
2964   address start   = __ pc();
2965   address call_pc = NULL;
2966   bool cause_return = (poll_type == POLL_AT_RETURN);
2967   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2968 
2969   if (UseRTMLocking) {
2970     // Abort RTM transaction before calling runtime
2971     // because critical section will be large and will be
2972     // aborted anyway. Also nmethod could be deoptimized.
2973     __ xabort(0);
2974   }
2975 
2976   // If cause_return is true we are at a poll_return and there is
2977   // the return address on the stack to the caller on the nmethod
2978   // that is safepoint. We can leave this return on the stack and
2979   // effectively complete the return and safepoint in the caller.
2980   // Otherwise we push space for a return address that the safepoint
2981   // handler will install later to make the stack walking sensible.
2982   if (!cause_return)
2983     __ push(rbx);  // Make room for return address (or push it again)
2984 
2985   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false, save_vectors);
2986 
2987   // The following is basically a call_VM. However, we need the precise
2988   // address of the call in order to generate an oopmap. Hence, we do all the
2989   // work ourselves.
2990 
2991   // Push thread argument and setup last_Java_sp
2992   __ get_thread(java_thread);
2993   __ push(java_thread);
2994   __ set_last_Java_frame(java_thread, noreg, noreg, NULL);
2995 
2996   // if this was not a poll_return then we need to correct the return address now.
2997   if (!cause_return) {
2998     __ movptr(rax, Address(java_thread, JavaThread::saved_exception_pc_offset()));
2999     __ movptr(Address(rbp, wordSize), rax);
3000   }
3001 
3002   // do the call
3003   __ call(RuntimeAddress(call_ptr));
3004 
3005   // Set an oopmap for the call site.  This oopmap will map all
3006   // oop-registers and debug-info registers as callee-saved.  This
3007   // will allow deoptimization at this safepoint to find all possible
3008   // debug-info recordings, as well as let GC find all oops.
3009 
3010   oop_maps->add_gc_map( __ pc() - start, map);
3011 
3012   // Discard arg
3013   __ pop(rcx);
3014 
3015   Label noException;
3016 
3017   // Clear last_Java_sp again
3018   __ get_thread(java_thread);
3019   __ reset_last_Java_frame(java_thread, false);
3020 
3021   __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3022   __ jcc(Assembler::equal, noException);
3023 
3024   // Exception pending
3025   RegisterSaver::restore_live_registers(masm, save_vectors);
3026 
3027   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3028 
3029   __ bind(noException);
3030 
3031   // Normal exit, register restoring and exit
3032   RegisterSaver::restore_live_registers(masm, save_vectors);
3033 
3034   __ ret(0);
3035 
3036   // make sure all code is generated
3037   masm->flush();
3038 
3039   // Fill-out other meta info
3040   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3041 }
3042 
3043 //
3044 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3045 //
3046 // Generate a stub that calls into vm to find out the proper destination
3047 // of a java call. All the argument registers are live at this point
3048 // but since this is generic code we don't know what they are and the caller
3049 // must do any gc of the args.
3050 //
3051 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3052   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3053 
3054   // allocate space for the code
3055   ResourceMark rm;
3056 
3057   CodeBuffer buffer(name, 1000, 512);
3058   MacroAssembler* masm                = new MacroAssembler(&buffer);
3059 
3060   int frame_size_words;
3061   enum frame_layout {
3062                 thread_off,
3063                 extra_words };
3064 
3065   OopMapSet *oop_maps = new OopMapSet();
3066   OopMap* map = NULL;
3067 
3068   int start = __ offset();
3069 
3070   map = RegisterSaver::save_live_registers(masm, extra_words, &frame_size_words);
3071 
3072   int frame_complete = __ offset();
3073 
3074   const Register thread = rdi;
3075   __ get_thread(rdi);
3076 
3077   __ push(thread);
3078   __ set_last_Java_frame(thread, noreg, rbp, NULL);
3079 
3080   __ call(RuntimeAddress(destination));
3081 
3082 
3083   // Set an oopmap for the call site.
3084   // We need this not only for callee-saved registers, but also for volatile
3085   // registers that the compiler might be keeping live across a safepoint.
3086 
3087   oop_maps->add_gc_map( __ offset() - start, map);
3088 
3089   // rax, contains the address we are going to jump to assuming no exception got installed
3090 
3091   __ addptr(rsp, wordSize);
3092 
3093   // clear last_Java_sp
3094   __ reset_last_Java_frame(thread, true);
3095   // check for pending exceptions
3096   Label pending;
3097   __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3098   __ jcc(Assembler::notEqual, pending);
3099 
3100   // get the returned Method*
3101   __ get_vm_result_2(rbx, thread);
3102   __ movptr(Address(rsp, RegisterSaver::rbx_offset() * wordSize), rbx);
3103 
3104   __ movptr(Address(rsp, RegisterSaver::rax_offset() * wordSize), rax);
3105 
3106   RegisterSaver::restore_live_registers(masm);
3107 
3108   // We are back the the original state on entry and ready to go.
3109 
3110   __ jmp(rax);
3111 
3112   // Pending exception after the safepoint
3113 
3114   __ bind(pending);
3115 
3116   RegisterSaver::restore_live_registers(masm);
3117 
3118   // exception pending => remove activation and forward to exception handler
3119 
3120   __ get_thread(thread);
3121   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
3122   __ movptr(rax, Address(thread, Thread::pending_exception_offset()));
3123   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3124 
3125   // -------------
3126   // make sure all code is generated
3127   masm->flush();
3128 
3129   // return the  blob
3130   // frame_size_words or bytes??
3131   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_words, oop_maps, true);
3132 }