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