1 /*
   2  * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #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 num_xmm_regs = XMMRegisterImpl::number_of_registers;
 118   int ymm_bytes = num_xmm_regs * 16;
 119   int zmm_bytes = num_xmm_regs * 32;
 120 #ifdef COMPILER2
 121   if (save_vectors) {
 122     assert(UseAVX > 0, "up to 512bit vectors are supported with EVEX");
 123     assert(MaxVectorSize <= 64, "up to 512bit vectors are supported now");
 124     // Save upper half of YMM registers
 125     int vect_bytes = ymm_bytes;
 126     if (UseAVX > 2) {
 127       // Save upper half of ZMM registers as well
 128       vect_bytes += zmm_bytes;
 129     }
 130     additional_frame_words += vect_bytes / wordSize;
 131   }
 132 #else
 133   assert(!save_vectors, "vectors are generated only by C2");
 134 #endif
 135   int frame_size_in_bytes = (reg_save_size + additional_frame_words) * wordSize;
 136   int frame_words = frame_size_in_bytes / wordSize;
 137   *total_frame_words = frame_words;
 138 
 139   assert(FPUStateSizeInWords == 27, "update stack layout");
 140 
 141   // save registers, fpu state, and flags
 142   // We assume caller has already has return address slot on the stack
 143   // We push epb twice in this sequence because we want the real rbp,
 144   // to be under the return like a normal enter and we want to use pusha
 145   // We push by hand instead of pusing push
 146   __ enter();
 147   __ pusha();
 148   __ pushf();
 149   __ subptr(rsp,FPU_regs_live*wordSize); // Push FPU registers space
 150   __ push_FPU_state();          // Save FPU state & init
 151 
 152   if (verify_fpu) {
 153     // Some stubs may have non standard FPU control word settings so
 154     // only check and reset the value when it required to be the
 155     // standard value.  The safepoint blob in particular can be used
 156     // in methods which are using the 24 bit control word for
 157     // optimized float math.
 158 
 159 #ifdef ASSERT
 160     // Make sure the control word has the expected value
 161     Label ok;
 162     __ cmpw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 163     __ jccb(Assembler::equal, ok);
 164     __ stop("corrupted control word detected");
 165     __ bind(ok);
 166 #endif
 167 
 168     // Reset the control word to guard against exceptions being unmasked
 169     // since fstp_d can cause FPU stack underflow exceptions.  Write it
 170     // into the on stack copy and then reload that to make sure that the
 171     // current and future values are correct.
 172     __ movw(Address(rsp, 0), StubRoutines::fpu_cntrl_wrd_std());
 173   }
 174 
 175   __ frstor(Address(rsp, 0));
 176   if (!verify_fpu) {
 177     // Set the control word so that exceptions are masked for the
 178     // following code.
 179     __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
 180   }
 181 
 182   int off = st0_off;
 183   int delta = st1_off - off;
 184 
 185   // Save the FPU registers in de-opt-able form
 186   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 187     __ fstp_d(Address(rsp, off*wordSize));
 188     off += delta;
 189   }
 190 
 191   off = xmm0_off;
 192   delta = xmm1_off - off;
 193   if(UseSSE == 1) {
 194     // Save the XMM state
 195     for (int n = 0; n < num_xmm_regs; n++) {
 196       __ movflt(Address(rsp, off*wordSize), as_XMMRegister(n));
 197       off += delta;
 198     }
 199   } else if(UseSSE >= 2) {
 200     // Save whole 128bit (16 bytes) XMM registers
 201     for (int n = 0; n < num_xmm_regs; n++) {
 202       __ movdqu(Address(rsp, off*wordSize), as_XMMRegister(n));
 203       off += delta;
 204     }
 205   }
 206 
 207   if (save_vectors) {
 208     __ subptr(rsp, ymm_bytes);
 209     // Save upper half of YMM registers
 210     for (int n = 0; n < num_xmm_regs; n++) {
 211       __ vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
 212     }
 213     if (UseAVX > 2) {
 214       __ subptr(rsp, zmm_bytes);
 215       // Save upper half of ZMM registers
 216       for (int n = 0; n < num_xmm_regs; n++) {
 217         __ vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
 218       }
 219     }
 220   }
 221 
 222   // Set an oopmap for the call site.  This oopmap will map all
 223   // oop-registers and debug-info registers as callee-saved.  This
 224   // will allow deoptimization at this safepoint to find all possible
 225   // debug-info recordings, as well as let GC find all oops.
 226 
 227   OopMapSet *oop_maps = new OopMapSet();
 228   OopMap* map =  new OopMap( frame_words, 0 );
 229 
 230 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x) + additional_frame_words)
 231 #define NEXTREG(x) (x)->as_VMReg()->next()
 232 
 233   map->set_callee_saved(STACK_OFFSET(rax_off), rax->as_VMReg());
 234   map->set_callee_saved(STACK_OFFSET(rcx_off), rcx->as_VMReg());
 235   map->set_callee_saved(STACK_OFFSET(rdx_off), rdx->as_VMReg());
 236   map->set_callee_saved(STACK_OFFSET(rbx_off), rbx->as_VMReg());
 237   // rbp, location is known implicitly, no oopMap
 238   map->set_callee_saved(STACK_OFFSET(rsi_off), rsi->as_VMReg());
 239   map->set_callee_saved(STACK_OFFSET(rdi_off), rdi->as_VMReg());
 240   // %%% This is really a waste but we'll keep things as they were for now for the upper component
 241   off = st0_off;
 242   delta = st1_off - off;
 243   for (int n = 0; n < FloatRegisterImpl::number_of_registers; n++) {
 244     FloatRegister freg_name = as_FloatRegister(n);
 245     map->set_callee_saved(STACK_OFFSET(off), freg_name->as_VMReg());
 246     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(freg_name));
 247     off += delta;
 248   }
 249   off = xmm0_off;
 250   delta = xmm1_off - off;
 251   for (int n = 0; n < num_xmm_regs; n++) {
 252     XMMRegister xmm_name = as_XMMRegister(n);
 253     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 254     map->set_callee_saved(STACK_OFFSET(off+1), NEXTREG(xmm_name));
 255     off += delta;
 256   }
 257 #undef NEXTREG
 258 #undef STACK_OFFSET
 259 
 260   return map;
 261 }
 262 
 263 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 264   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 265   int ymm_bytes = num_xmm_regs * 16;
 266   int zmm_bytes = num_xmm_regs * 32;
 267   // Recover XMM & FPU state
 268   int additional_frame_bytes = 0;
 269 #ifdef COMPILER2
 270   if (restore_vectors) {
 271     assert(UseAVX > 0, "up to 512bit vectors are supported with EVEX");
 272     assert(MaxVectorSize <= 64, "up to 512bit vectors are supported now");
 273     // Save upper half of YMM registers
 274     additional_frame_bytes = ymm_bytes;
 275     if (UseAVX > 2) {
 276       // Save upper half of ZMM registers as well
 277       additional_frame_bytes += zmm_bytes;
 278     }
 279   }
 280 #else
 281   assert(!restore_vectors, "vectors are generated only by C2");
 282 #endif
 283 
 284   int off = xmm0_off;
 285   int delta = xmm1_off - off;
 286 
 287   if (UseSSE == 1) {
 288     // Restore XMM registers
 289     assert(additional_frame_bytes == 0, "");
 290     for (int n = 0; n < num_xmm_regs; n++) {
 291       __ movflt(as_XMMRegister(n), Address(rsp, off*wordSize));
 292       off += delta;
 293     }
 294   } else if (UseSSE >= 2) {
 295     // Restore whole 128bit (16 bytes) XMM registers. Do this before restoring YMM and
 296     // ZMM because the movdqu instruction zeros the upper part of the XMM register.
 297     for (int n = 0; n < num_xmm_regs; n++) {
 298       __ movdqu(as_XMMRegister(n), Address(rsp, off*wordSize+additional_frame_bytes));
 299       off += delta;
 300     }
 301   }
 302 
 303   if (restore_vectors) {
 304     if (UseAVX > 2) {
 305       // Restore upper half of ZMM registers.
 306       for (int n = 0; n < num_xmm_regs; n++) {
 307         __ vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
 308       }
 309       __ addptr(rsp, zmm_bytes);
 310     }
 311     // Restore upper half of YMM registers.
 312     for (int n = 0; n < num_xmm_regs; n++) {
 313       __ vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
 314     }
 315     __ addptr(rsp, ymm_bytes);
 316   }
 317 
 318   __ pop_FPU_state();
 319   __ addptr(rsp, FPU_regs_live*wordSize); // Pop FPU registers
 320 
 321   __ popf();
 322   __ popa();
 323   // Get the rbp, described implicitly by the frame sender code (no oopMap)
 324   __ pop(rbp);
 325 }
 326 
 327 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 328 
 329   // Just restore result register. Only used by deoptimization. By
 330   // now any callee save register that needs to be restore to a c2
 331   // caller of the deoptee has been extracted into the vframeArray
 332   // and will be stuffed into the c2i adapter we create for later
 333   // restoration so only result registers need to be restored here.
 334   //
 335 
 336   __ frstor(Address(rsp, 0));      // Restore fpu state
 337 
 338   // Recover XMM & FPU state
 339   if( UseSSE == 1 ) {
 340     __ movflt(xmm0, Address(rsp, xmm0_off*wordSize));
 341   } else if( UseSSE >= 2 ) {
 342     __ movdbl(xmm0, Address(rsp, xmm0_off*wordSize));
 343   }
 344   __ movptr(rax, Address(rsp, rax_off*wordSize));
 345   __ movptr(rdx, Address(rsp, rdx_off*wordSize));
 346   // Pop all of the register save are off the stack except the return address
 347   __ addptr(rsp, return_off * wordSize);
 348 }
 349 
 350 // Is vector's size (in bytes) bigger than a size saved by default?
 351 // 16 bytes XMM registers are saved by default using SSE2 movdqu instructions.
 352 // Note, MaxVectorSize == 0 with UseSSE < 2 and vectors are not generated.
 353 bool SharedRuntime::is_wide_vector(int size) {
 354   return size > 16;
 355 }
 356 
 357 // The java_calling_convention describes stack locations as ideal slots on
 358 // a frame with no abi restrictions. Since we must observe abi restrictions
 359 // (like the placement of the register window) the slots must be biased by
 360 // the following value.
 361 static int reg2offset_in(VMReg r) {
 362   // Account for saved rbp, and return address
 363   // This should really be in_preserve_stack_slots
 364   return (r->reg2stack() + 2) * VMRegImpl::stack_slot_size;
 365 }
 366 
 367 static int reg2offset_out(VMReg r) {
 368   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 369 }
 370 
 371 // ---------------------------------------------------------------------------
 372 // Read the array of BasicTypes from a signature, and compute where the
 373 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 374 // quantities.  Values less than SharedInfo::stack0 are registers, those above
 375 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 376 // as framesizes are fixed.
 377 // VMRegImpl::stack0 refers to the first slot 0(sp).
 378 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 379 // up to RegisterImpl::number_of_registers) are the 32-bit
 380 // integer registers.
 381 
 382 // Pass first two oop/int args in registers ECX and EDX.
 383 // Pass first two float/double args in registers XMM0 and XMM1.
 384 // Doubles have precedence, so if you pass a mix of floats and doubles
 385 // the doubles will grab the registers before the floats will.
 386 
 387 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 388 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 389 // units regardless of build. Of course for i486 there is no 64 bit build
 390 
 391 
 392 // ---------------------------------------------------------------------------
 393 // The compiled Java calling convention.
 394 // Pass first two oop/int args in registers ECX and EDX.
 395 // Pass first two float/double args in registers XMM0 and XMM1.
 396 // Doubles have precedence, so if you pass a mix of floats and doubles
 397 // the doubles will grab the registers before the floats will.
 398 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 399                                            VMRegPair *regs,
 400                                            int total_args_passed,
 401                                            int is_outgoing) {
 402   uint    stack = 0;          // Starting stack position for args on stack
 403 
 404 
 405   // Pass first two oop/int args in registers ECX and EDX.
 406   uint reg_arg0 = 9999;
 407   uint reg_arg1 = 9999;
 408 
 409   // Pass first two float/double args in registers XMM0 and XMM1.
 410   // Doubles have precedence, so if you pass a mix of floats and doubles
 411   // the doubles will grab the registers before the floats will.
 412   // CNC - TURNED OFF FOR non-SSE.
 413   //       On Intel we have to round all doubles (and most floats) at
 414   //       call sites by storing to the stack in any case.
 415   // UseSSE=0 ==> Don't Use ==> 9999+0
 416   // UseSSE=1 ==> Floats only ==> 9999+1
 417   // UseSSE>=2 ==> Floats or doubles ==> 9999+2
 418   enum { fltarg_dontuse = 9999+0, fltarg_float_only = 9999+1, fltarg_flt_dbl = 9999+2 };
 419   uint fargs = (UseSSE>=2) ? 2 : UseSSE;
 420   uint freg_arg0 = 9999+fargs;
 421   uint freg_arg1 = 9999+fargs;
 422 
 423   // Pass doubles & longs aligned on the stack.  First count stack slots for doubles
 424   int i;
 425   for( i = 0; i < total_args_passed; i++) {
 426     if( sig_bt[i] == T_DOUBLE ) {
 427       // first 2 doubles go in registers
 428       if( freg_arg0 == fltarg_flt_dbl ) freg_arg0 = i;
 429       else if( freg_arg1 == fltarg_flt_dbl ) freg_arg1 = i;
 430       else // Else double is passed low on the stack to be aligned.
 431         stack += 2;
 432     } else if( sig_bt[i] == T_LONG ) {
 433       stack += 2;
 434     }
 435   }
 436   int dstack = 0;             // Separate counter for placing doubles
 437 
 438   // Now pick where all else goes.
 439   for( i = 0; i < total_args_passed; i++) {
 440     // From the type and the argument number (count) compute the location
 441     switch( sig_bt[i] ) {
 442     case T_SHORT:
 443     case T_CHAR:
 444     case T_BYTE:
 445     case T_BOOLEAN:
 446     case T_INT:
 447     case T_ARRAY:
 448     case T_OBJECT:
 449     case T_ADDRESS:
 450       if( reg_arg0 == 9999 )  {
 451         reg_arg0 = i;
 452         regs[i].set1(rcx->as_VMReg());
 453       } else if( reg_arg1 == 9999 )  {
 454         reg_arg1 = i;
 455         regs[i].set1(rdx->as_VMReg());
 456       } else {
 457         regs[i].set1(VMRegImpl::stack2reg(stack++));
 458       }
 459       break;
 460     case T_FLOAT:
 461       if( freg_arg0 == fltarg_flt_dbl || freg_arg0 == fltarg_float_only ) {
 462         freg_arg0 = i;
 463         regs[i].set1(xmm0->as_VMReg());
 464       } else if( freg_arg1 == fltarg_flt_dbl || freg_arg1 == fltarg_float_only ) {
 465         freg_arg1 = i;
 466         regs[i].set1(xmm1->as_VMReg());
 467       } else {
 468         regs[i].set1(VMRegImpl::stack2reg(stack++));
 469       }
 470       break;
 471     case T_LONG:
 472       assert(sig_bt[i+1] == T_VOID, "missing Half" );
 473       regs[i].set2(VMRegImpl::stack2reg(dstack));
 474       dstack += 2;
 475       break;
 476     case T_DOUBLE:
 477       assert(sig_bt[i+1] == T_VOID, "missing Half" );
 478       if( freg_arg0 == (uint)i ) {
 479         regs[i].set2(xmm0->as_VMReg());
 480       } else if( freg_arg1 == (uint)i ) {
 481         regs[i].set2(xmm1->as_VMReg());
 482       } else {
 483         regs[i].set2(VMRegImpl::stack2reg(dstack));
 484         dstack += 2;
 485       }
 486       break;
 487     case T_VOID: regs[i].set_bad(); break;
 488       break;
 489     default:
 490       ShouldNotReachHere();
 491       break;
 492     }
 493   }
 494 
 495   // return value can be odd number of VMRegImpl stack slots make multiple of 2
 496   return round_to(stack, 2);
 497 }
 498 
 499 // Patch the callers callsite with entry to compiled code if it exists.
 500 static void patch_callers_callsite(MacroAssembler *masm) {
 501   Label L;
 502   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 503   __ jcc(Assembler::equal, L);
 504   // Schedule the branch target address early.
 505   // Call into the VM to patch the caller, then jump to compiled callee
 506   // rax, isn't live so capture return address while we easily can
 507   __ movptr(rax, Address(rsp, 0));
 508   __ pusha();
 509   __ pushf();
 510 
 511   if (UseSSE == 1) {
 512     __ subptr(rsp, 2*wordSize);
 513     __ movflt(Address(rsp, 0), xmm0);
 514     __ movflt(Address(rsp, wordSize), xmm1);
 515   }
 516   if (UseSSE >= 2) {
 517     __ subptr(rsp, 4*wordSize);
 518     __ movdbl(Address(rsp, 0), xmm0);
 519     __ movdbl(Address(rsp, 2*wordSize), xmm1);
 520   }
 521 #ifdef COMPILER2
 522   // C2 may leave the stack dirty if not in SSE2+ mode
 523   if (UseSSE >= 2) {
 524     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 525   } else {
 526     __ empty_FPU_stack();
 527   }
 528 #endif /* COMPILER2 */
 529 
 530   // VM needs caller's callsite
 531   __ push(rax);
 532   // VM needs target method
 533   __ push(rbx);
 534   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 535   __ addptr(rsp, 2*wordSize);
 536 
 537   if (UseSSE == 1) {
 538     __ movflt(xmm0, Address(rsp, 0));
 539     __ movflt(xmm1, Address(rsp, wordSize));
 540     __ addptr(rsp, 2*wordSize);
 541   }
 542   if (UseSSE >= 2) {
 543     __ movdbl(xmm0, Address(rsp, 0));
 544     __ movdbl(xmm1, Address(rsp, 2*wordSize));
 545     __ addptr(rsp, 4*wordSize);
 546   }
 547 
 548   __ popf();
 549   __ popa();
 550   __ bind(L);
 551 }
 552 
 553 
 554 static void move_c2i_double(MacroAssembler *masm, XMMRegister r, int st_off) {
 555   int next_off = st_off - Interpreter::stackElementSize;
 556   __ movdbl(Address(rsp, next_off), r);
 557 }
 558 
 559 static void gen_c2i_adapter(MacroAssembler *masm,
 560                             const GrowableArray<SigEntry>& sig_extended,
 561                             const VMRegPair *regs,
 562                             Label& skip_fixup,
 563                             address start,
 564                             OopMapSet*& oop_maps,
 565                             int& frame_complete,
 566                             int& frame_size_in_words) {
 567   // Before we get into the guts of the C2I adapter, see if we should be here
 568   // at all.  We've come from compiled code and are attempting to jump to the
 569   // interpreter, which means the caller made a static call to get here
 570   // (vcalls always get a compiled target if there is one).  Check for a
 571   // compiled target.  If there is one, we need to patch the caller's call.
 572   patch_callers_callsite(masm);
 573 
 574   __ bind(skip_fixup);
 575 
 576 #ifdef COMPILER2
 577   // C2 may leave the stack dirty if not in SSE2+ mode
 578   if (UseSSE >= 2) {
 579     __ verify_FPU(0, "c2i transition should have clean FPU stack");
 580   } else {
 581     __ empty_FPU_stack();
 582   }
 583 #endif /* COMPILER2 */
 584 
 585   // Since all args are passed on the stack, total_args_passed * interpreter_
 586   // stack_element_size  is the
 587   // space we need.
 588   int extraspace = sig_extended.length() * Interpreter::stackElementSize;
 589 
 590   // Get return address
 591   __ pop(rax);
 592 
 593   // set senderSP value
 594   __ movptr(rsi, rsp);
 595 
 596   __ subptr(rsp, extraspace);
 597 
 598   // Now write the args into the outgoing interpreter space
 599   for (int i = 0; i < sig_extended.length(); i++) {
 600     if (sig_extended.at(i)._bt == T_VOID) {
 601       assert(i > 0 && (sig_extended.at(i-1)._bt == T_LONG || sig_extended.at(i-1)._bt == T_DOUBLE), "missing half");
 602       continue;
 603     }
 604 
 605     // st_off points to lowest address on stack.
 606     int st_off = ((sig_extended.length() - 1) - i) * Interpreter::stackElementSize;
 607     int next_off = st_off - Interpreter::stackElementSize;
 608 
 609     // Say 4 args:
 610     // i   st_off
 611     // 0   12 T_LONG
 612     // 1    8 T_VOID
 613     // 2    4 T_OBJECT
 614     // 3    0 T_BOOL
 615     VMReg r_1 = regs[i].first();
 616     VMReg r_2 = regs[i].second();
 617     if (!r_1->is_valid()) {
 618       assert(!r_2->is_valid(), "");
 619       continue;
 620     }
 621 
 622     if (r_1->is_stack()) {
 623       // memory to memory use fpu stack top
 624       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 625 
 626       if (!r_2->is_valid()) {
 627         __ movl(rdi, Address(rsp, ld_off));
 628         __ movptr(Address(rsp, st_off), rdi);
 629       } else {
 630 
 631         // ld_off == LSW, ld_off+VMRegImpl::stack_slot_size == MSW
 632         // st_off == MSW, st_off-wordSize == LSW
 633 
 634         __ movptr(rdi, Address(rsp, ld_off));
 635         __ movptr(Address(rsp, next_off), rdi);
 636 #ifndef _LP64
 637         __ movptr(rdi, Address(rsp, ld_off + wordSize));
 638         __ movptr(Address(rsp, st_off), rdi);
 639 #else
 640 #ifdef ASSERT
 641         // Overwrite the unused slot with known junk
 642         __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 643         __ movptr(Address(rsp, st_off), rax);
 644 #endif /* ASSERT */
 645 #endif // _LP64
 646       }
 647     } else if (r_1->is_Register()) {
 648       Register r = r_1->as_Register();
 649       if (!r_2->is_valid()) {
 650         __ movl(Address(rsp, st_off), r);
 651       } else {
 652         // long/double in gpr
 653         NOT_LP64(ShouldNotReachHere());
 654         // Two VMRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 655         // T_DOUBLE and T_LONG use two slots in the interpreter
 656         if ( sig_extended.at(i)._bt == T_LONG || sig_extended.at(i)._bt == T_DOUBLE) {
 657           // long/double in gpr
 658 #ifdef ASSERT
 659           // Overwrite the unused slot with known junk
 660           LP64_ONLY(__ mov64(rax, CONST64(0xdeadffffdeadaaab)));
 661           __ movptr(Address(rsp, st_off), rax);
 662 #endif /* ASSERT */
 663           __ movptr(Address(rsp, next_off), r);
 664         } else {
 665           __ movptr(Address(rsp, st_off), r);
 666         }
 667       }
 668     } else {
 669       assert(r_1->is_XMMRegister(), "");
 670       if (!r_2->is_valid()) {
 671         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 672       } else {
 673         assert(sig_extended.at(i)._bt == T_DOUBLE || sig_extended.at(i)._bt == T_LONG, "wrong type");
 674         move_c2i_double(masm, r_1->as_XMMRegister(), st_off);
 675       }
 676     }
 677   }
 678 
 679   // Schedule the branch target address early.
 680   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 681   // And repush original return address
 682   __ push(rax);
 683   __ jmp(rcx);
 684 }
 685 
 686 
 687 static void move_i2c_double(MacroAssembler *masm, XMMRegister r, Register saved_sp, int ld_off) {
 688   int next_val_off = ld_off - Interpreter::stackElementSize;
 689   __ movdbl(r, Address(saved_sp, next_val_off));
 690 }
 691 
 692 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 693                         address code_start, address code_end,
 694                         Label& L_ok) {
 695   Label L_fail;
 696   __ lea(temp_reg, ExternalAddress(code_start));
 697   __ cmpptr(pc_reg, temp_reg);
 698   __ jcc(Assembler::belowEqual, L_fail);
 699   __ lea(temp_reg, ExternalAddress(code_end));
 700   __ cmpptr(pc_reg, temp_reg);
 701   __ jcc(Assembler::below, L_ok);
 702   __ bind(L_fail);
 703 }
 704 
 705 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 706                                     int comp_args_on_stack,
 707                                     const GrowableArray<SigEntry>& sig_extended,
 708                                     const VMRegPair *regs) {
 709 
 710   // Note: rsi contains the senderSP on entry. We must preserve it since
 711   // we may do a i2c -> c2i transition if we lose a race where compiled
 712   // code goes non-entrant while we get args ready.
 713 
 714   // Adapters can be frameless because they do not require the caller
 715   // to perform additional cleanup work, such as correcting the stack pointer.
 716   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 717   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 718   // even if a callee has modified the stack pointer.
 719   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 720   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 721   // up via the senderSP register).
 722   // In other words, if *either* the caller or callee is interpreted, we can
 723   // get the stack pointer repaired after a call.
 724   // This is why c2i and i2c adapters cannot be indefinitely composed.
 725   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 726   // both caller and callee would be compiled methods, and neither would
 727   // clean up the stack pointer changes performed by the two adapters.
 728   // If this happens, control eventually transfers back to the compiled
 729   // caller, but with an uncorrected stack, causing delayed havoc.
 730 
 731   // Pick up the return address
 732   __ movptr(rax, Address(rsp, 0));
 733 
 734   if (VerifyAdapterCalls &&
 735       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 736     // So, let's test for cascading c2i/i2c adapters right now.
 737     //  assert(Interpreter::contains($return_addr) ||
 738     //         StubRoutines::contains($return_addr),
 739     //         "i2c adapter must return to an interpreter frame");
 740     __ block_comment("verify_i2c { ");
 741     Label L_ok;
 742     if (Interpreter::code() != NULL)
 743       range_check(masm, rax, rdi,
 744                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 745                   L_ok);
 746     if (StubRoutines::code1() != NULL)
 747       range_check(masm, rax, rdi,
 748                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 749                   L_ok);
 750     if (StubRoutines::code2() != NULL)
 751       range_check(masm, rax, rdi,
 752                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 753                   L_ok);
 754     const char* msg = "i2c adapter must return to an interpreter frame";
 755     __ block_comment(msg);
 756     __ stop(msg);
 757     __ bind(L_ok);
 758     __ block_comment("} verify_i2ce ");
 759   }
 760 
 761   // Must preserve original SP for loading incoming arguments because
 762   // we need to align the outgoing SP for compiled code.
 763   __ movptr(rdi, rsp);
 764 
 765   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 766   // in registers, we will occasionally have no stack args.
 767   int comp_words_on_stack = 0;
 768   if (comp_args_on_stack) {
 769     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 770     // registers are below.  By subtracting stack0, we either get a negative
 771     // number (all values in registers) or the maximum stack slot accessed.
 772     // int comp_args_on_stack = VMRegImpl::reg2stack(max_arg);
 773     // Convert 4-byte stack slots to words.
 774     comp_words_on_stack = round_to(comp_args_on_stack*4, wordSize)>>LogBytesPerWord;
 775     // Round up to miminum stack alignment, in wordSize
 776     comp_words_on_stack = round_to(comp_words_on_stack, 2);
 777     __ subptr(rsp, comp_words_on_stack * wordSize);
 778   }
 779 
 780   // Align the outgoing SP
 781   __ andptr(rsp, -(StackAlignmentInBytes));
 782 
 783   // push the return address on the stack (note that pushing, rather
 784   // than storing it, yields the correct frame alignment for the callee)
 785   __ push(rax);
 786 
 787   // Put saved SP in another register
 788   const Register saved_sp = rax;
 789   __ movptr(saved_sp, rdi);
 790 
 791 
 792   // Will jump to the compiled code just as if compiled code was doing it.
 793   // Pre-load the register-jump target early, to schedule it better.
 794   __ movptr(rdi, Address(rbx, in_bytes(Method::from_compiled_offset())));
 795 
 796   // Now generate the shuffle code.  Pick up all register args and move the
 797   // rest through the floating point stack top.
 798   for (int i = 0; i < sig_extended.length(); i++) {
 799     if (sig_extended.at(i)._bt == T_VOID) {
 800       // Longs and doubles are passed in native word order, but misaligned
 801       // in the 32-bit build.
 802       assert(i > 0 && (sig_extended.at(i-1)._bt == T_LONG || sig_extended.at(i-1)._bt == T_DOUBLE), "missing half");
 803       continue;
 804     }
 805 
 806     // Pick up 0, 1 or 2 words from SP+offset.
 807 
 808     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 809             "scrambled load targets?");
 810     // Load in argument order going down.
 811     int ld_off = (sig_extended.length() - i) * Interpreter::stackElementSize;
 812     // Point to interpreter value (vs. tag)
 813     int next_off = ld_off - Interpreter::stackElementSize;
 814     //
 815     //
 816     //
 817     VMReg r_1 = regs[i].first();
 818     VMReg r_2 = regs[i].second();
 819     if (!r_1->is_valid()) {
 820       assert(!r_2->is_valid(), "");
 821       continue;
 822     }
 823     if (r_1->is_stack()) {
 824       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 825       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 826 
 827       // We can use rsi as a temp here because compiled code doesn't need rsi as an input
 828       // and if we end up going thru a c2i because of a miss a reasonable value of rsi
 829       // we be generated.
 830       if (!r_2->is_valid()) {
 831         // __ fld_s(Address(saved_sp, ld_off));
 832         // __ fstp_s(Address(rsp, st_off));
 833         __ movl(rsi, Address(saved_sp, ld_off));
 834         __ movptr(Address(rsp, st_off), rsi);
 835       } else {
 836         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 837         // are accessed as negative so LSW is at LOW address
 838 
 839         // ld_off is MSW so get LSW
 840         // st_off is LSW (i.e. reg.first())
 841         // __ fld_d(Address(saved_sp, next_off));
 842         // __ fstp_d(Address(rsp, st_off));
 843         //
 844         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 845         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 846         // So we must adjust where to pick up the data to match the interpreter.
 847         //
 848         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 849         // are accessed as negative so LSW is at LOW address
 850 
 851         // ld_off is MSW so get LSW
 852         const int offset = (NOT_LP64(true ||) sig_extended.at(i)._bt==T_LONG||sig_extended.at(i)._bt==T_DOUBLE)?
 853                            next_off : ld_off;
 854         __ movptr(rsi, Address(saved_sp, offset));
 855         __ movptr(Address(rsp, st_off), rsi);
 856 #ifndef _LP64
 857         __ movptr(rsi, Address(saved_sp, ld_off));
 858         __ movptr(Address(rsp, st_off + wordSize), rsi);
 859 #endif // _LP64
 860       }
 861     } else if (r_1->is_Register()) {  // Register argument
 862       Register r = r_1->as_Register();
 863       assert(r != rax, "must be different");
 864       if (r_2->is_valid()) {
 865         //
 866         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 867         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 868         // So we must adjust where to pick up the data to match the interpreter.
 869 
 870         const int offset = (NOT_LP64(true ||) sig_extended.at(i)._bt==T_LONG||sig_extended.at(i)._bt==T_DOUBLE)?
 871                            next_off : ld_off;
 872 
 873         // this can be a misaligned move
 874         __ movptr(r, Address(saved_sp, offset));
 875 #ifndef _LP64
 876         assert(r_2->as_Register() != rax, "need another temporary register");
 877         // Remember r_1 is low address (and LSB on x86)
 878         // So r_2 gets loaded from high address regardless of the platform
 879         __ movptr(r_2->as_Register(), Address(saved_sp, ld_off));
 880 #endif // _LP64
 881       } else {
 882         __ movl(r, Address(saved_sp, ld_off));
 883       }
 884     } else {
 885       assert(r_1->is_XMMRegister(), "");
 886       if (!r_2->is_valid()) {
 887         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 888       } else {
 889         move_i2c_double(masm, r_1->as_XMMRegister(), saved_sp, ld_off);
 890       }
 891     }
 892   }
 893 
 894   // 6243940 We might end up in handle_wrong_method if
 895   // the callee is deoptimized as we race thru here. If that
 896   // happens we don't want to take a safepoint because the
 897   // caller frame will look interpreted and arguments are now
 898   // "compiled" so it is much better to make this transition
 899   // invisible to the stack walking code. Unfortunately if
 900   // we try and find the callee by normal means a safepoint
 901   // is possible. So we stash the desired callee in the thread
 902   // and the vm will find there should this case occur.
 903 
 904   __ get_thread(rax);
 905   __ movptr(Address(rax, JavaThread::callee_target_offset()), rbx);
 906 
 907   // move Method* to rax, in case we end up in an c2i adapter.
 908   // the c2i adapters expect Method* in rax, (c2) because c2's
 909   // resolve stubs return the result (the method) in rax,.
 910   // I'd love to fix this.
 911   __ mov(rax, rbx);
 912 
 913   __ jmp(rdi);
 914 }
 915 
 916 // ---------------------------------------------------------------
 917 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 918                                                             int comp_args_on_stack,
 919                                                             const GrowableArray<SigEntry>& sig_extended,
 920                                                             const VMRegPair *regs,
 921                                                             AdapterFingerPrint* fingerprint,
 922                                                             AdapterBlob*& new_adapter) {
 923   address i2c_entry = __ pc();
 924 
 925   gen_i2c_adapter(masm, comp_args_on_stack, sig_extended, regs);
 926 
 927   // -------------------------------------------------------------------------
 928   // Generate a C2I adapter.  On entry we know rbx, holds the Method* during calls
 929   // to the interpreter.  The args start out packed in the compiled layout.  They
 930   // need to be unpacked into the interpreter layout.  This will almost always
 931   // require some stack space.  We grow the current (compiled) stack, then repack
 932   // the args.  We  finally end in a jump to the generic interpreter entry point.
 933   // On exit from the interpreter, the interpreter will restore our SP (lest the
 934   // compiled code, which relys solely on SP and not EBP, get sick).
 935 
 936   address c2i_unverified_entry = __ pc();
 937   Label skip_fixup;
 938 
 939   Register holder = rax;
 940   Register receiver = rcx;
 941   Register temp = rbx;
 942 
 943   {
 944 
 945     Label missed;
 946     __ movptr(temp, Address(receiver, oopDesc::klass_offset_in_bytes()));
 947     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 948     __ movptr(rbx, Address(holder, CompiledICHolder::holder_method_offset()));
 949     __ jcc(Assembler::notEqual, missed);
 950     // Method might have been compiled since the call site was patched to
 951     // interpreted if that is the case treat it as a miss so we can get
 952     // the call site corrected.
 953     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 954     __ jcc(Assembler::equal, skip_fixup);
 955 
 956     __ bind(missed);
 957     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 958   }
 959 
 960   address c2i_entry = __ pc();
 961 
 962   OopMapSet* oop_maps = NULL;
 963   int frame_complete = CodeOffsets::frame_never_safe;
 964   int frame_size_in_words = 0;
 965   gen_c2i_adapter(masm, sig_extended, regs, skip_fixup, i2c_entry, oop_maps, frame_complete, frame_size_in_words);
 966 
 967   __ flush();
 968   new_adapter = AdapterBlob::create(masm->code(), frame_complete, frame_size_in_words, oop_maps);
 969   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 970 }
 971 
 972 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 973                                          VMRegPair *regs,
 974                                          VMRegPair *regs2,
 975                                          int total_args_passed) {
 976   assert(regs2 == NULL, "not needed on x86");
 977 // We return the amount of VMRegImpl stack slots we need to reserve for all
 978 // the arguments NOT counting out_preserve_stack_slots.
 979 
 980   uint    stack = 0;        // All arguments on stack
 981 
 982   for( int i = 0; i < total_args_passed; i++) {
 983     // From the type and the argument number (count) compute the location
 984     switch( sig_bt[i] ) {
 985     case T_BOOLEAN:
 986     case T_CHAR:
 987     case T_FLOAT:
 988     case T_BYTE:
 989     case T_SHORT:
 990     case T_INT:
 991     case T_OBJECT:
 992     case T_ARRAY:
 993     case T_ADDRESS:
 994     case T_METADATA:
 995       regs[i].set1(VMRegImpl::stack2reg(stack++));
 996       break;
 997     case T_LONG:
 998     case T_DOUBLE: // The stack numbering is reversed from Java
 999       // Since C arguments do not get reversed, the ordering for
1000       // doubles on the stack must be opposite the Java convention
1001       assert(sig_bt[i+1] == T_VOID, "missing Half" );
1002       regs[i].set2(VMRegImpl::stack2reg(stack));
1003       stack += 2;
1004       break;
1005     case T_VOID: regs[i].set_bad(); break;
1006     default:
1007       ShouldNotReachHere();
1008       break;
1009     }
1010   }
1011   return stack;
1012 }
1013 
1014 // A simple move of integer like type
1015 static void simple_move32(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1016   if (src.first()->is_stack()) {
1017     if (dst.first()->is_stack()) {
1018       // stack to stack
1019       // __ ld(FP, reg2offset(src.first()) + STACK_BIAS, L5);
1020       // __ st(L5, SP, reg2offset(dst.first()) + STACK_BIAS);
1021       __ movl2ptr(rax, Address(rbp, reg2offset_in(src.first())));
1022       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1023     } else {
1024       // stack to reg
1025       __ movl2ptr(dst.first()->as_Register(),  Address(rbp, reg2offset_in(src.first())));
1026     }
1027   } else if (dst.first()->is_stack()) {
1028     // reg to stack
1029     // no need to sign extend on 64bit
1030     __ movptr(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1031   } else {
1032     if (dst.first() != src.first()) {
1033       __ mov(dst.first()->as_Register(), src.first()->as_Register());
1034     }
1035   }
1036 }
1037 
1038 // An oop arg. Must pass a handle not the oop itself
1039 static void object_move(MacroAssembler* masm,
1040                         OopMap* map,
1041                         int oop_handle_offset,
1042                         int framesize_in_slots,
1043                         VMRegPair src,
1044                         VMRegPair dst,
1045                         bool is_receiver,
1046                         int* receiver_offset) {
1047 
1048   // Because of the calling conventions we know that src can be a
1049   // register or a stack location. dst can only be a stack location.
1050 
1051   assert(dst.first()->is_stack(), "must be stack");
1052   // must pass a handle. First figure out the location we use as a handle
1053 
1054   if (src.first()->is_stack()) {
1055     // Oop is already on the stack as an argument
1056     Register rHandle = rax;
1057     Label nil;
1058     __ xorptr(rHandle, rHandle);
1059     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1060     __ jcc(Assembler::equal, nil);
1061     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1062     __ bind(nil);
1063     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1064 
1065     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1066     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1067     if (is_receiver) {
1068       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1069     }
1070   } else {
1071     // Oop is in an a register we must store it to the space we reserve
1072     // on the stack for oop_handles
1073     const Register rOop = src.first()->as_Register();
1074     const Register rHandle = rax;
1075     int oop_slot = (rOop == rcx ? 0 : 1) * VMRegImpl::slots_per_word + oop_handle_offset;
1076     int offset = oop_slot*VMRegImpl::stack_slot_size;
1077     Label skip;
1078     __ movptr(Address(rsp, offset), rOop);
1079     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1080     __ xorptr(rHandle, rHandle);
1081     __ cmpptr(rOop, (int32_t)NULL_WORD);
1082     __ jcc(Assembler::equal, skip);
1083     __ lea(rHandle, Address(rsp, offset));
1084     __ bind(skip);
1085     // Store the handle parameter
1086     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1087     if (is_receiver) {
1088       *receiver_offset = offset;
1089     }
1090   }
1091 }
1092 
1093 // A float arg may have to do float reg int reg conversion
1094 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1095   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1096 
1097   // Because of the calling convention we know that src is either a stack location
1098   // or an xmm register. dst can only be a stack location.
1099 
1100   assert(dst.first()->is_stack() && ( src.first()->is_stack() || src.first()->is_XMMRegister()), "bad parameters");
1101 
1102   if (src.first()->is_stack()) {
1103     __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1104     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1105   } else {
1106     // reg to stack
1107     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1108   }
1109 }
1110 
1111 // A long move
1112 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1113 
1114   // The only legal possibility for a long_move VMRegPair is:
1115   // 1: two stack slots (possibly unaligned)
1116   // as neither the java  or C calling convention will use registers
1117   // for longs.
1118 
1119   if (src.first()->is_stack() && dst.first()->is_stack()) {
1120     assert(src.second()->is_stack() && dst.second()->is_stack(), "must be 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     ShouldNotReachHere();
1127   }
1128 }
1129 
1130 // A double move
1131 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1132 
1133   // The only legal possibilities for a double_move VMRegPair are:
1134   // The painful thing here is that like long_move a VMRegPair might be
1135 
1136   // Because of the calling convention we know that src is either
1137   //   1: a single physical register (xmm registers only)
1138   //   2: two stack slots (possibly unaligned)
1139   // dst can only be a pair of stack slots.
1140 
1141   assert(dst.first()->is_stack() && (src.first()->is_XMMRegister() || src.first()->is_stack()), "bad args");
1142 
1143   if (src.first()->is_stack()) {
1144     // source is all stack
1145     __ movptr(rax, Address(rbp, reg2offset_in(src.first())));
1146     NOT_LP64(__ movptr(rbx, Address(rbp, reg2offset_in(src.second()))));
1147     __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1148     NOT_LP64(__ movptr(Address(rsp, reg2offset_out(dst.second())), rbx));
1149   } else {
1150     // reg to stack
1151     // No worries about stack alignment
1152     __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1153   }
1154 }
1155 
1156 
1157 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1158   // We always ignore the frame_slots arg and just use the space just below frame pointer
1159   // which by this time is free to use
1160   switch (ret_type) {
1161   case T_FLOAT:
1162     __ fstp_s(Address(rbp, -wordSize));
1163     break;
1164   case T_DOUBLE:
1165     __ fstp_d(Address(rbp, -2*wordSize));
1166     break;
1167   case T_VOID:  break;
1168   case T_LONG:
1169     __ movptr(Address(rbp, -wordSize), rax);
1170     NOT_LP64(__ movptr(Address(rbp, -2*wordSize), rdx));
1171     break;
1172   default: {
1173     __ movptr(Address(rbp, -wordSize), rax);
1174     }
1175   }
1176 }
1177 
1178 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1179   // We always ignore the frame_slots arg and just use the space just below frame pointer
1180   // which by this time is free to use
1181   switch (ret_type) {
1182   case T_FLOAT:
1183     __ fld_s(Address(rbp, -wordSize));
1184     break;
1185   case T_DOUBLE:
1186     __ fld_d(Address(rbp, -2*wordSize));
1187     break;
1188   case T_LONG:
1189     __ movptr(rax, Address(rbp, -wordSize));
1190     NOT_LP64(__ movptr(rdx, Address(rbp, -2*wordSize)));
1191     break;
1192   case T_VOID:  break;
1193   default: {
1194     __ movptr(rax, Address(rbp, -wordSize));
1195     }
1196   }
1197 }
1198 
1199 
1200 static void save_or_restore_arguments(MacroAssembler* masm,
1201                                       const int stack_slots,
1202                                       const int total_in_args,
1203                                       const int arg_save_area,
1204                                       OopMap* map,
1205                                       VMRegPair* in_regs,
1206                                       BasicType* in_sig_bt) {
1207   // if map is non-NULL then the code should store the values,
1208   // otherwise it should load them.
1209   int handle_index = 0;
1210   // Save down double word first
1211   for ( int i = 0; i < total_in_args; i++) {
1212     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1213       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1214       int offset = slot * VMRegImpl::stack_slot_size;
1215       handle_index += 2;
1216       assert(handle_index <= stack_slots, "overflow");
1217       if (map != NULL) {
1218         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1219       } else {
1220         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1221       }
1222     }
1223     if (in_regs[i].first()->is_Register() && in_sig_bt[i] == T_LONG) {
1224       int slot = handle_index * VMRegImpl::slots_per_word + arg_save_area;
1225       int offset = slot * VMRegImpl::stack_slot_size;
1226       handle_index += 2;
1227       assert(handle_index <= stack_slots, "overflow");
1228       if (map != NULL) {
1229         __ movl(Address(rsp, offset), in_regs[i].first()->as_Register());
1230         if (in_regs[i].second()->is_Register()) {
1231           __ movl(Address(rsp, offset + 4), in_regs[i].second()->as_Register());
1232         }
1233       } else {
1234         __ movl(in_regs[i].first()->as_Register(), Address(rsp, offset));
1235         if (in_regs[i].second()->is_Register()) {
1236           __ movl(in_regs[i].second()->as_Register(), Address(rsp, offset + 4));
1237         }
1238       }
1239     }
1240   }
1241   // Save or restore single word registers
1242   for ( int i = 0; i < total_in_args; i++) {
1243     if (in_regs[i].first()->is_Register()) {
1244       int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1245       int offset = slot * VMRegImpl::stack_slot_size;
1246       assert(handle_index <= stack_slots, "overflow");
1247       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1248         map->set_oop(VMRegImpl::stack2reg(slot));;
1249       }
1250 
1251       // Value is in an input register pass we must flush it to the stack
1252       const Register reg = in_regs[i].first()->as_Register();
1253       switch (in_sig_bt[i]) {
1254         case T_ARRAY:
1255           if (map != NULL) {
1256             __ movptr(Address(rsp, offset), reg);
1257           } else {
1258             __ movptr(reg, Address(rsp, offset));
1259           }
1260           break;
1261         case T_BOOLEAN:
1262         case T_CHAR:
1263         case T_BYTE:
1264         case T_SHORT:
1265         case T_INT:
1266           if (map != NULL) {
1267             __ movl(Address(rsp, offset), reg);
1268           } else {
1269             __ movl(reg, Address(rsp, offset));
1270           }
1271           break;
1272         case T_OBJECT:
1273         default: ShouldNotReachHere();
1274       }
1275     } else if (in_regs[i].first()->is_XMMRegister()) {
1276       if (in_sig_bt[i] == T_FLOAT) {
1277         int slot = handle_index++ * VMRegImpl::slots_per_word + arg_save_area;
1278         int offset = slot * VMRegImpl::stack_slot_size;
1279         assert(handle_index <= stack_slots, "overflow");
1280         if (map != NULL) {
1281           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1282         } else {
1283           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1284         }
1285       }
1286     } else if (in_regs[i].first()->is_stack()) {
1287       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1288         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1289         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1290       }
1291     }
1292   }
1293 }
1294 
1295 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1296 // keeps a new JNI critical region from starting until a GC has been
1297 // forced.  Save down any oops in registers and describe them in an
1298 // OopMap.
1299 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1300                                                Register thread,
1301                                                int stack_slots,
1302                                                int total_c_args,
1303                                                int total_in_args,
1304                                                int arg_save_area,
1305                                                OopMapSet* oop_maps,
1306                                                VMRegPair* in_regs,
1307                                                BasicType* in_sig_bt) {
1308   __ block_comment("check GCLocker::needs_gc");
1309   Label cont;
1310   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1311   __ jcc(Assembler::equal, cont);
1312 
1313   // Save down any incoming oops and call into the runtime to halt for a GC
1314 
1315   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1316 
1317   save_or_restore_arguments(masm, stack_slots, total_in_args,
1318                             arg_save_area, map, in_regs, in_sig_bt);
1319 
1320   address the_pc = __ pc();
1321   oop_maps->add_gc_map( __ offset(), map);
1322   __ set_last_Java_frame(thread, rsp, noreg, the_pc);
1323 
1324   __ block_comment("block_for_jni_critical");
1325   __ push(thread);
1326   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1327   __ increment(rsp, wordSize);
1328 
1329   __ get_thread(thread);
1330   __ reset_last_Java_frame(thread, false, true);
1331 
1332   save_or_restore_arguments(masm, stack_slots, total_in_args,
1333                             arg_save_area, NULL, in_regs, in_sig_bt);
1334 
1335   __ bind(cont);
1336 #ifdef ASSERT
1337   if (StressCriticalJNINatives) {
1338     // Stress register saving
1339     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1340     save_or_restore_arguments(masm, stack_slots, total_in_args,
1341                               arg_save_area, map, in_regs, in_sig_bt);
1342     // Destroy argument registers
1343     for (int i = 0; i < total_in_args - 1; i++) {
1344       if (in_regs[i].first()->is_Register()) {
1345         const Register reg = in_regs[i].first()->as_Register();
1346         __ xorptr(reg, reg);
1347       } else if (in_regs[i].first()->is_XMMRegister()) {
1348         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1349       } else if (in_regs[i].first()->is_FloatRegister()) {
1350         ShouldNotReachHere();
1351       } else if (in_regs[i].first()->is_stack()) {
1352         // Nothing to do
1353       } else {
1354         ShouldNotReachHere();
1355       }
1356       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1357         i++;
1358       }
1359     }
1360 
1361     save_or_restore_arguments(masm, stack_slots, total_in_args,
1362                               arg_save_area, NULL, in_regs, in_sig_bt);
1363   }
1364 #endif
1365 }
1366 
1367 // Unpack an array argument into a pointer to the body and the length
1368 // if the array is non-null, otherwise pass 0 for both.
1369 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1370   Register tmp_reg = rax;
1371   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1372          "possible collision");
1373   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1374          "possible collision");
1375 
1376   // Pass the length, ptr pair
1377   Label is_null, done;
1378   VMRegPair tmp(tmp_reg->as_VMReg());
1379   if (reg.first()->is_stack()) {
1380     // Load the arg up from the stack
1381     simple_move32(masm, reg, tmp);
1382     reg = tmp;
1383   }
1384   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1385   __ jccb(Assembler::equal, is_null);
1386   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1387   simple_move32(masm, tmp, body_arg);
1388   // load the length relative to the body.
1389   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1390                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1391   simple_move32(masm, tmp, length_arg);
1392   __ jmpb(done);
1393   __ bind(is_null);
1394   // Pass zeros
1395   __ xorptr(tmp_reg, tmp_reg);
1396   simple_move32(masm, tmp, body_arg);
1397   simple_move32(masm, tmp, length_arg);
1398   __ bind(done);
1399 }
1400 
1401 static void verify_oop_args(MacroAssembler* masm,
1402                             methodHandle method,
1403                             const BasicType* sig_bt,
1404                             const VMRegPair* regs) {
1405   Register temp_reg = rbx;  // not part of any compiled calling seq
1406   if (VerifyOops) {
1407     for (int i = 0; i < method->size_of_parameters(); i++) {
1408       if (sig_bt[i] == T_OBJECT ||
1409           sig_bt[i] == T_ARRAY) {
1410         VMReg r = regs[i].first();
1411         assert(r->is_valid(), "bad oop arg");
1412         if (r->is_stack()) {
1413           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1414           __ verify_oop(temp_reg);
1415         } else {
1416           __ verify_oop(r->as_Register());
1417         }
1418       }
1419     }
1420   }
1421 }
1422 
1423 static void gen_special_dispatch(MacroAssembler* masm,
1424                                  methodHandle method,
1425                                  const BasicType* sig_bt,
1426                                  const VMRegPair* regs) {
1427   verify_oop_args(masm, method, sig_bt, regs);
1428   vmIntrinsics::ID iid = method->intrinsic_id();
1429 
1430   // Now write the args into the outgoing interpreter space
1431   bool     has_receiver   = false;
1432   Register receiver_reg   = noreg;
1433   int      member_arg_pos = -1;
1434   Register member_reg     = noreg;
1435   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1436   if (ref_kind != 0) {
1437     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1438     member_reg = rbx;  // known to be free at this point
1439     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1440   } else if (iid == vmIntrinsics::_invokeBasic) {
1441     has_receiver = true;
1442   } else {
1443     fatal("unexpected intrinsic id %d", iid);
1444   }
1445 
1446   if (member_reg != noreg) {
1447     // Load the member_arg into register, if necessary.
1448     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1449     VMReg r = regs[member_arg_pos].first();
1450     if (r->is_stack()) {
1451       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1452     } else {
1453       // no data motion is needed
1454       member_reg = r->as_Register();
1455     }
1456   }
1457 
1458   if (has_receiver) {
1459     // Make sure the receiver is loaded into a register.
1460     assert(method->size_of_parameters() > 0, "oob");
1461     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1462     VMReg r = regs[0].first();
1463     assert(r->is_valid(), "bad receiver arg");
1464     if (r->is_stack()) {
1465       // Porting note:  This assumes that compiled calling conventions always
1466       // pass the receiver oop in a register.  If this is not true on some
1467       // platform, pick a temp and load the receiver from stack.
1468       fatal("receiver always in a register");
1469       receiver_reg = rcx;  // known to be free at this point
1470       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1471     } else {
1472       // no data motion is needed
1473       receiver_reg = r->as_Register();
1474     }
1475   }
1476 
1477   // Figure out which address we are really jumping to:
1478   MethodHandles::generate_method_handle_dispatch(masm, iid,
1479                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1480 }
1481 
1482 // ---------------------------------------------------------------------------
1483 // Generate a native wrapper for a given method.  The method takes arguments
1484 // in the Java compiled code convention, marshals them to the native
1485 // convention (handlizes oops, etc), transitions to native, makes the call,
1486 // returns to java state (possibly blocking), unhandlizes any result and
1487 // returns.
1488 //
1489 // Critical native functions are a shorthand for the use of
1490 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1491 // functions.  The wrapper is expected to unpack the arguments before
1492 // passing them to the callee and perform checks before and after the
1493 // native call to ensure that they GCLocker
1494 // lock_critical/unlock_critical semantics are followed.  Some other
1495 // parts of JNI setup are skipped like the tear down of the JNI handle
1496 // block and the check for pending exceptions it's impossible for them
1497 // to be thrown.
1498 //
1499 // They are roughly structured like this:
1500 //    if (GCLocker::needs_gc())
1501 //      SharedRuntime::block_for_jni_critical();
1502 //    tranistion to thread_in_native
1503 //    unpack arrray arguments and call native entry point
1504 //    check for safepoint in progress
1505 //    check if any thread suspend flags are set
1506 //      call into JVM and possible unlock the JNI critical
1507 //      if a GC was suppressed while in the critical native.
1508 //    transition back to thread_in_Java
1509 //    return to caller
1510 //
1511 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1512                                                 const methodHandle& method,
1513                                                 int compile_id,
1514                                                 BasicType* in_sig_bt,
1515                                                 VMRegPair* in_regs,
1516                                                 BasicType ret_type) {
1517   if (method->is_method_handle_intrinsic()) {
1518     vmIntrinsics::ID iid = method->intrinsic_id();
1519     intptr_t start = (intptr_t)__ pc();
1520     int vep_offset = ((intptr_t)__ pc()) - start;
1521     gen_special_dispatch(masm,
1522                          method,
1523                          in_sig_bt,
1524                          in_regs);
1525     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1526     __ flush();
1527     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1528     return nmethod::new_native_nmethod(method,
1529                                        compile_id,
1530                                        masm->code(),
1531                                        vep_offset,
1532                                        frame_complete,
1533                                        stack_slots / VMRegImpl::slots_per_word,
1534                                        in_ByteSize(-1),
1535                                        in_ByteSize(-1),
1536                                        (OopMapSet*)NULL);
1537   }
1538   bool is_critical_native = true;
1539   address native_func = method->critical_native_function();
1540   if (native_func == NULL) {
1541     native_func = method->native_function();
1542     is_critical_native = false;
1543   }
1544   assert(native_func != NULL, "must have function");
1545 
1546   // An OopMap for lock (and class if static)
1547   OopMapSet *oop_maps = new OopMapSet();
1548 
1549   // We have received a description of where all the java arg are located
1550   // on entry to the wrapper. We need to convert these args to where
1551   // the jni function will expect them. To figure out where they go
1552   // we convert the java signature to a C signature by inserting
1553   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1554 
1555   const int total_in_args = method->size_of_parameters();
1556   int total_c_args = total_in_args;
1557   if (!is_critical_native) {
1558     total_c_args += 1;
1559     if (method->is_static()) {
1560       total_c_args++;
1561     }
1562   } else {
1563     for (int i = 0; i < total_in_args; i++) {
1564       if (in_sig_bt[i] == T_ARRAY) {
1565         total_c_args++;
1566       }
1567     }
1568   }
1569 
1570   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1571   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1572   BasicType* in_elem_bt = NULL;
1573 
1574   int argc = 0;
1575   if (!is_critical_native) {
1576     out_sig_bt[argc++] = T_ADDRESS;
1577     if (method->is_static()) {
1578       out_sig_bt[argc++] = T_OBJECT;
1579     }
1580 
1581     for (int i = 0; i < total_in_args ; i++ ) {
1582       out_sig_bt[argc++] = in_sig_bt[i];
1583     }
1584   } else {
1585     Thread* THREAD = Thread::current();
1586     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1587     SignatureStream ss(method->signature());
1588     for (int i = 0; i < total_in_args ; i++ ) {
1589       if (in_sig_bt[i] == T_ARRAY) {
1590         // Arrays are passed as int, elem* pair
1591         out_sig_bt[argc++] = T_INT;
1592         out_sig_bt[argc++] = T_ADDRESS;
1593         Symbol* atype = ss.as_symbol(CHECK_NULL);
1594         const char* at = atype->as_C_string();
1595         if (strlen(at) == 2) {
1596           assert(at[0] == '[', "must be");
1597           switch (at[1]) {
1598             case 'B': in_elem_bt[i]  = T_BYTE; break;
1599             case 'C': in_elem_bt[i]  = T_CHAR; break;
1600             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1601             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1602             case 'I': in_elem_bt[i]  = T_INT; break;
1603             case 'J': in_elem_bt[i]  = T_LONG; break;
1604             case 'S': in_elem_bt[i]  = T_SHORT; break;
1605             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1606             default: ShouldNotReachHere();
1607           }
1608         }
1609       } else {
1610         out_sig_bt[argc++] = in_sig_bt[i];
1611         in_elem_bt[i] = T_VOID;
1612       }
1613       if (in_sig_bt[i] != T_VOID) {
1614         assert(in_sig_bt[i] == ss.type(), "must match");
1615         ss.next();
1616       }
1617     }
1618   }
1619 
1620   // Now figure out where the args must be stored and how much stack space
1621   // they require.
1622   int out_arg_slots;
1623   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1624 
1625   // Compute framesize for the wrapper.  We need to handlize all oops in
1626   // registers a max of 2 on x86.
1627 
1628   // Calculate the total number of stack slots we will need.
1629 
1630   // First count the abi requirement plus all of the outgoing args
1631   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1632 
1633   // Now the space for the inbound oop handle area
1634   int total_save_slots = 2 * VMRegImpl::slots_per_word; // 2 arguments passed in registers
1635   if (is_critical_native) {
1636     // Critical natives may have to call out so they need a save area
1637     // for register arguments.
1638     int double_slots = 0;
1639     int single_slots = 0;
1640     for ( int i = 0; i < total_in_args; i++) {
1641       if (in_regs[i].first()->is_Register()) {
1642         const Register reg = in_regs[i].first()->as_Register();
1643         switch (in_sig_bt[i]) {
1644           case T_ARRAY:  // critical array (uses 2 slots on LP64)
1645           case T_BOOLEAN:
1646           case T_BYTE:
1647           case T_SHORT:
1648           case T_CHAR:
1649           case T_INT:  single_slots++; break;
1650           case T_LONG: double_slots++; break;
1651           default:  ShouldNotReachHere();
1652         }
1653       } else if (in_regs[i].first()->is_XMMRegister()) {
1654         switch (in_sig_bt[i]) {
1655           case T_FLOAT:  single_slots++; break;
1656           case T_DOUBLE: double_slots++; break;
1657           default:  ShouldNotReachHere();
1658         }
1659       } else if (in_regs[i].first()->is_FloatRegister()) {
1660         ShouldNotReachHere();
1661       }
1662     }
1663     total_save_slots = double_slots * 2 + single_slots;
1664     // align the save area
1665     if (double_slots != 0) {
1666       stack_slots = round_to(stack_slots, 2);
1667     }
1668   }
1669 
1670   int oop_handle_offset = stack_slots;
1671   stack_slots += total_save_slots;
1672 
1673   // Now any space we need for handlizing a klass if static method
1674 
1675   int klass_slot_offset = 0;
1676   int klass_offset = -1;
1677   int lock_slot_offset = 0;
1678   bool is_static = false;
1679 
1680   if (method->is_static()) {
1681     klass_slot_offset = stack_slots;
1682     stack_slots += VMRegImpl::slots_per_word;
1683     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1684     is_static = true;
1685   }
1686 
1687   // Plus a lock if needed
1688 
1689   if (method->is_synchronized()) {
1690     lock_slot_offset = stack_slots;
1691     stack_slots += VMRegImpl::slots_per_word;
1692   }
1693 
1694   // Now a place (+2) to save return values or temp during shuffling
1695   // + 2 for return address (which we own) and saved rbp,
1696   stack_slots += 4;
1697 
1698   // Ok The space we have allocated will look like:
1699   //
1700   //
1701   // FP-> |                     |
1702   //      |---------------------|
1703   //      | 2 slots for moves   |
1704   //      |---------------------|
1705   //      | lock box (if sync)  |
1706   //      |---------------------| <- lock_slot_offset  (-lock_slot_rbp_offset)
1707   //      | klass (if static)   |
1708   //      |---------------------| <- klass_slot_offset
1709   //      | oopHandle area      |
1710   //      |---------------------| <- oop_handle_offset (a max of 2 registers)
1711   //      | outbound memory     |
1712   //      | based arguments     |
1713   //      |                     |
1714   //      |---------------------|
1715   //      |                     |
1716   // SP-> | out_preserved_slots |
1717   //
1718   //
1719   // ****************************************************************************
1720   // WARNING - on Windows Java Natives use pascal calling convention and pop the
1721   // arguments off of the stack after the jni call. Before the call we can use
1722   // instructions that are SP relative. After the jni call we switch to FP
1723   // relative instructions instead of re-adjusting the stack on windows.
1724   // ****************************************************************************
1725 
1726 
1727   // Now compute actual number of stack words we need rounding to make
1728   // stack properly aligned.
1729   stack_slots = round_to(stack_slots, StackAlignmentInSlots);
1730 
1731   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1732 
1733   intptr_t start = (intptr_t)__ pc();
1734 
1735   // First thing make an ic check to see if we should even be here
1736 
1737   // We are free to use all registers as temps without saving them and
1738   // restoring them except rbp. rbp is the only callee save register
1739   // as far as the interpreter and the compiler(s) are concerned.
1740 
1741 
1742   const Register ic_reg = rax;
1743   const Register receiver = rcx;
1744   Label hit;
1745   Label exception_pending;
1746 
1747   __ verify_oop(receiver);
1748   __ cmpptr(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
1749   __ jcc(Assembler::equal, hit);
1750 
1751   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1752 
1753   // verified entry must be aligned for code patching.
1754   // and the first 5 bytes must be in the same cache line
1755   // if we align at 8 then we will be sure 5 bytes are in the same line
1756   __ align(8);
1757 
1758   __ bind(hit);
1759 
1760   int vep_offset = ((intptr_t)__ pc()) - start;
1761 
1762 #ifdef COMPILER1
1763   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
1764   if ((InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) || (method->intrinsic_id() == vmIntrinsics::_identityHashCode)) {
1765     inline_check_hashcode_from_object_header(masm, method, rcx /*obj_reg*/, rax /*result*/);
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((int)JavaThread::stack_shadow_zone_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_reserved_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 args to fetch_unroll_info
2549   __ pop(rcx);
2550   __ pop(rcx);
2551 
2552   __ get_thread(rcx);
2553   __ reset_last_Java_frame(rcx, false, false);
2554 
2555   // Load UnrollBlock into EDI
2556   __ mov(rdi, rax);
2557 
2558   // Move the unpack kind to a safe place in the UnrollBlock because
2559   // we are very short of registers
2560 
2561   Address unpack_kind(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes());
2562   // retrieve the deopt kind from the UnrollBlock.
2563   __ movl(rax, unpack_kind);
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   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2653   __ pushptr(Address(rcx, 0));          // save return address
2654   __ enter();                           // save old & set new rbp,
2655   __ subptr(rsp, rbx);                  // Prolog!
2656   __ movptr(rbx, sp_temp);              // sender's sp
2657   // This value is corrected by layout_activation_impl
2658   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD);
2659   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2660   __ movptr(sp_temp, rsp);              // pass to next frame
2661   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2662   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2663   __ decrementl(counter);             // decrement counter
2664   __ jcc(Assembler::notZero, loop);
2665   __ pushptr(Address(rcx, 0));          // save final return address
2666 
2667   // Re-push self-frame
2668   __ enter();                           // save old & set new rbp,
2669 
2670   //  Return address and rbp, are in place
2671   // We'll push additional args later. Just allocate a full sized
2672   // register save area
2673   __ subptr(rsp, (frame_size_in_words-additional_words - 2) * wordSize);
2674 
2675   // Restore frame locals after moving the frame
2676   __ movptr(Address(rsp, RegisterSaver::raxOffset()*wordSize), rax);
2677   __ movptr(Address(rsp, RegisterSaver::rdxOffset()*wordSize), rdx);
2678   __ fstp_d(Address(rsp, RegisterSaver::fpResultOffset()*wordSize));   // Pop float stack and store in local
2679   if( UseSSE>=2 ) __ movdbl(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2680   if( UseSSE==1 ) __ movflt(Address(rsp, RegisterSaver::xmm0Offset()*wordSize), xmm0);
2681 
2682   // Set up the args to unpack_frame
2683 
2684   __ pushl(unpack_kind);                     // get the unpack_kind value
2685   __ get_thread(rcx);
2686   __ push(rcx);
2687 
2688   // set last_Java_sp, last_Java_fp
2689   __ set_last_Java_frame(rcx, noreg, rbp, NULL);
2690 
2691   // Call C code.  Need thread but NOT official VM entry
2692   // crud.  We cannot block on this call, no GC can happen.  Call should
2693   // restore return values to their stack-slots with the new SP.
2694   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2695   // Set an oopmap for the call site
2696   oop_maps->add_gc_map( __ pc()-start, new OopMap( frame_size_in_words, 0 ));
2697 
2698   // rax, contains the return result type
2699   __ push(rax);
2700 
2701   __ get_thread(rcx);
2702   __ reset_last_Java_frame(rcx, false, false);
2703 
2704   // Collect return values
2705   __ movptr(rax,Address(rsp, (RegisterSaver::raxOffset() + additional_words + 1)*wordSize));
2706   __ movptr(rdx,Address(rsp, (RegisterSaver::rdxOffset() + additional_words + 1)*wordSize));
2707 
2708   // Clear floating point stack before returning to interpreter
2709   __ empty_FPU_stack();
2710 
2711   // Check if we should push the float or double return value.
2712   Label results_done, yes_double_value;
2713   __ cmpl(Address(rsp, 0), T_DOUBLE);
2714   __ jcc (Assembler::zero, yes_double_value);
2715   __ cmpl(Address(rsp, 0), T_FLOAT);
2716   __ jcc (Assembler::notZero, results_done);
2717 
2718   // return float value as expected by interpreter
2719   if( UseSSE>=1 ) __ movflt(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2720   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2721   __ jmp(results_done);
2722 
2723   // return double value as expected by interpreter
2724   __ bind(yes_double_value);
2725   if( UseSSE>=2 ) __ movdbl(xmm0, Address(rsp, (RegisterSaver::xmm0Offset() + additional_words + 1)*wordSize));
2726   else            __ fld_d(Address(rsp, (RegisterSaver::fpResultOffset() + additional_words + 1)*wordSize));
2727 
2728   __ bind(results_done);
2729 
2730   // Pop self-frame.
2731   __ leave();                              // Epilog!
2732 
2733   // Jump to interpreter
2734   __ ret(0);
2735 
2736   // -------------
2737   // make sure all code is generated
2738   masm->flush();
2739 
2740   _deopt_blob = DeoptimizationBlob::create( &buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2741   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2742 }
2743 
2744 
2745 #ifdef COMPILER2
2746 //------------------------------generate_uncommon_trap_blob--------------------
2747 void SharedRuntime::generate_uncommon_trap_blob() {
2748   // allocate space for the code
2749   ResourceMark rm;
2750   // setup code generation tools
2751   CodeBuffer   buffer("uncommon_trap_blob", 512, 512);
2752   MacroAssembler* masm = new MacroAssembler(&buffer);
2753 
2754   enum frame_layout {
2755     arg0_off,      // thread                     sp + 0 // Arg location for
2756     arg1_off,      // unloaded_class_index       sp + 1 // calling C
2757     arg2_off,      // exec_mode                  sp + 2
2758     // The frame sender code expects that rbp will be in the "natural" place and
2759     // will override any oopMap setting for it. We must therefore force the layout
2760     // so that it agrees with the frame sender code.
2761     rbp_off,       // callee saved register      sp + 3
2762     return_off,    // slot for return address    sp + 4
2763     framesize
2764   };
2765 
2766   address start = __ pc();
2767 
2768   if (UseRTMLocking) {
2769     // Abort RTM transaction before possible nmethod deoptimization.
2770     __ xabort(0);
2771   }
2772 
2773   // Push self-frame.
2774   __ subptr(rsp, return_off*wordSize);     // Epilog!
2775 
2776   // rbp, is an implicitly saved callee saved register (i.e. the calling
2777   // convention will save restore it in prolog/epilog) Other than that
2778   // there are no callee save registers no that adapter frames are gone.
2779   __ movptr(Address(rsp, rbp_off*wordSize), rbp);
2780 
2781   // Clear the floating point exception stack
2782   __ empty_FPU_stack();
2783 
2784   // set last_Java_sp
2785   __ get_thread(rdx);
2786   __ set_last_Java_frame(rdx, noreg, noreg, NULL);
2787 
2788   // Call C code.  Need thread but NOT official VM entry
2789   // crud.  We cannot block on this call, no GC can happen.  Call should
2790   // capture callee-saved registers as well as return values.
2791   __ movptr(Address(rsp, arg0_off*wordSize), rdx);
2792   // argument already in ECX
2793   __ movl(Address(rsp, arg1_off*wordSize),rcx);
2794   __ movl(Address(rsp, arg2_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2795   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2796 
2797   // Set an oopmap for the call site
2798   OopMapSet *oop_maps = new OopMapSet();
2799   OopMap* map =  new OopMap( framesize, 0 );
2800   // No oopMap for rbp, it is known implicitly
2801 
2802   oop_maps->add_gc_map( __ pc()-start, map);
2803 
2804   __ get_thread(rcx);
2805 
2806   __ reset_last_Java_frame(rcx, false, false);
2807 
2808   // Load UnrollBlock into EDI
2809   __ movptr(rdi, rax);
2810 
2811 #ifdef ASSERT
2812   { Label L;
2813     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
2814             (int32_t)Deoptimization::Unpack_uncommon_trap);
2815     __ jcc(Assembler::equal, L);
2816     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
2817     __ bind(L);
2818   }
2819 #endif
2820 
2821   // Pop all the frames we must move/replace.
2822   //
2823   // Frame picture (youngest to oldest)
2824   // 1: self-frame (no frame link)
2825   // 2: deopting frame  (no frame link)
2826   // 3: caller of deopting frame (could be compiled/interpreted).
2827 
2828   // Pop self-frame.  We have no frame, and must rely only on EAX and ESP.
2829   __ addptr(rsp,(framesize-1)*wordSize);     // Epilog!
2830 
2831   // Pop deoptimized frame
2832   __ movl2ptr(rcx, Address(rdi,Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2833   __ addptr(rsp, rcx);
2834 
2835   // sp should be pointing at the return address to the caller (3)
2836 
2837   // Pick up the initial fp we should save
2838   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
2839   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
2840 
2841 #ifdef ASSERT
2842   // Compilers generate code that bang the stack by as much as the
2843   // interpreter would need. So this stack banging should never
2844   // trigger a fault. Verify that it does not on non product builds.
2845   if (UseStackBanging) {
2846     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2847     __ bang_stack_size(rbx, rcx);
2848   }
2849 #endif
2850 
2851   // Load array of frame pcs into ECX
2852   __ movl(rcx,Address(rdi,Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2853 
2854   __ pop(rsi); // trash the pc
2855 
2856   // Load array of frame sizes into ESI
2857   __ movptr(rsi,Address(rdi,Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2858 
2859   Address counter(rdi, Deoptimization::UnrollBlock::counter_temp_offset_in_bytes());
2860 
2861   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2862   __ movl(counter, rbx);
2863 
2864   // Now adjust the caller's stack to make up for the extra locals
2865   // but record the original sp so that we can save it in the skeletal interpreter
2866   // frame and the stack walking of interpreter_sender will get the unextended sp
2867   // value and not the "real" sp value.
2868 
2869   Address sp_temp(rdi, Deoptimization::UnrollBlock::sender_sp_temp_offset_in_bytes());
2870   __ movptr(sp_temp, rsp);
2871   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::caller_adjustment_offset_in_bytes()));
2872   __ subptr(rsp, rbx);
2873 
2874   // Push interpreter frames in a loop
2875   Label loop;
2876   __ bind(loop);
2877   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2878   __ subptr(rbx, 2*wordSize);           // we'll push pc and rbp, by hand
2879   __ pushptr(Address(rcx, 0));          // save return address
2880   __ enter();                           // save old & set new rbp,
2881   __ subptr(rsp, rbx);                  // Prolog!
2882   __ movptr(rbx, sp_temp);              // sender's sp
2883   // This value is corrected by layout_activation_impl
2884   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), NULL_WORD );
2885   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), rbx); // Make it walkable
2886   __ movptr(sp_temp, rsp);              // pass to next frame
2887   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2888   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2889   __ decrementl(counter);             // decrement counter
2890   __ jcc(Assembler::notZero, loop);
2891   __ pushptr(Address(rcx, 0));            // save final return address
2892 
2893   // Re-push self-frame
2894   __ enter();                           // save old & set new rbp,
2895   __ subptr(rsp, (framesize-2) * wordSize);   // Prolog!
2896 
2897 
2898   // set last_Java_sp, last_Java_fp
2899   __ get_thread(rdi);
2900   __ set_last_Java_frame(rdi, noreg, rbp, NULL);
2901 
2902   // Call C code.  Need thread but NOT official VM entry
2903   // crud.  We cannot block on this call, no GC can happen.  Call should
2904   // restore return values to their stack-slots with the new SP.
2905   __ movptr(Address(rsp,arg0_off*wordSize),rdi);
2906   __ movl(Address(rsp,arg1_off*wordSize), Deoptimization::Unpack_uncommon_trap);
2907   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2908   // Set an oopmap for the call site
2909   oop_maps->add_gc_map( __ pc()-start, new OopMap( framesize, 0 ) );
2910 
2911   __ get_thread(rdi);
2912   __ reset_last_Java_frame(rdi, true, false);
2913 
2914   // Pop self-frame.
2915   __ leave();     // Epilog!
2916 
2917   // Jump to interpreter
2918   __ ret(0);
2919 
2920   // -------------
2921   // make sure all code is generated
2922   masm->flush();
2923 
2924    _uncommon_trap_blob = UncommonTrapBlob::create(&buffer, oop_maps, framesize);
2925 }
2926 #endif // COMPILER2
2927 
2928 //------------------------------generate_handler_blob------
2929 //
2930 // Generate a special Compile2Runtime blob that saves all registers,
2931 // setup oopmap, and calls safepoint code to stop the compiled code for
2932 // a safepoint.
2933 //
2934 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
2935 
2936   // Account for thread arg in our frame
2937   const int additional_words = 1;
2938   int frame_size_in_words;
2939 
2940   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
2941 
2942   ResourceMark rm;
2943   OopMapSet *oop_maps = new OopMapSet();
2944   OopMap* map;
2945 
2946   // allocate space for the code
2947   // setup code generation tools
2948   CodeBuffer   buffer("handler_blob", 1024, 512);
2949   MacroAssembler* masm = new MacroAssembler(&buffer);
2950 
2951   const Register java_thread = rdi; // callee-saved for VC++
2952   address start   = __ pc();
2953   address call_pc = NULL;
2954   bool cause_return = (poll_type == POLL_AT_RETURN);
2955   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
2956 
2957   if (UseRTMLocking) {
2958     // Abort RTM transaction before calling runtime
2959     // because critical section will be large and will be
2960     // aborted anyway. Also nmethod could be deoptimized.
2961     __ xabort(0);
2962   }
2963 
2964   // If cause_return is true we are at a poll_return and there is
2965   // the return address on the stack to the caller on the nmethod
2966   // that is safepoint. We can leave this return on the stack and
2967   // effectively complete the return and safepoint in the caller.
2968   // Otherwise we push space for a return address that the safepoint
2969   // handler will install later to make the stack walking sensible.
2970   if (!cause_return)
2971     __ push(rbx);  // Make room for return address (or push it again)
2972 
2973   map = RegisterSaver::save_live_registers(masm, additional_words, &frame_size_in_words, false, save_vectors);
2974 
2975   // The following is basically a call_VM. However, we need the precise
2976   // address of the call in order to generate an oopmap. Hence, we do all the
2977   // work ourselves.
2978 
2979   // Push thread argument and setup last_Java_sp
2980   __ get_thread(java_thread);
2981   __ push(java_thread);
2982   __ set_last_Java_frame(java_thread, noreg, noreg, NULL);
2983 
2984   // if this was not a poll_return then we need to correct the return address now.
2985   if (!cause_return) {
2986     __ movptr(rax, Address(java_thread, JavaThread::saved_exception_pc_offset()));
2987     __ movptr(Address(rbp, wordSize), rax);
2988   }
2989 
2990   // do the call
2991   __ call(RuntimeAddress(call_ptr));
2992 
2993   // Set an oopmap for the call site.  This oopmap will map all
2994   // oop-registers and debug-info registers as callee-saved.  This
2995   // will allow deoptimization at this safepoint to find all possible
2996   // debug-info recordings, as well as let GC find all oops.
2997 
2998   oop_maps->add_gc_map( __ pc() - start, map);
2999 
3000   // Discard arg
3001   __ pop(rcx);
3002 
3003   Label noException;
3004 
3005   // Clear last_Java_sp again
3006   __ get_thread(java_thread);
3007   __ reset_last_Java_frame(java_thread, false, false);
3008 
3009   __ cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3010   __ jcc(Assembler::equal, noException);
3011 
3012   // Exception pending
3013   RegisterSaver::restore_live_registers(masm, save_vectors);
3014 
3015   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3016 
3017   __ bind(noException);
3018 
3019   // Normal exit, register restoring and exit
3020   RegisterSaver::restore_live_registers(masm, save_vectors);
3021 
3022   __ ret(0);
3023 
3024   // make sure all code is generated
3025   masm->flush();
3026 
3027   // Fill-out other meta info
3028   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3029 }
3030 
3031 //
3032 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3033 //
3034 // Generate a stub that calls into vm to find out the proper destination
3035 // of a java call. All the argument registers are live at this point
3036 // but since this is generic code we don't know what they are and the caller
3037 // must do any gc of the args.
3038 //
3039 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3040   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3041 
3042   // allocate space for the code
3043   ResourceMark rm;
3044 
3045   CodeBuffer buffer(name, 1000, 512);
3046   MacroAssembler* masm                = new MacroAssembler(&buffer);
3047 
3048   int frame_size_words;
3049   enum frame_layout {
3050                 thread_off,
3051                 extra_words };
3052 
3053   OopMapSet *oop_maps = new OopMapSet();
3054   OopMap* map = NULL;
3055 
3056   int start = __ offset();
3057 
3058   map = RegisterSaver::save_live_registers(masm, extra_words, &frame_size_words);
3059 
3060   int frame_complete = __ offset();
3061 
3062   const Register thread = rdi;
3063   __ get_thread(rdi);
3064 
3065   __ push(thread);
3066   __ set_last_Java_frame(thread, noreg, rbp, NULL);
3067 
3068   __ call(RuntimeAddress(destination));
3069 
3070 
3071   // Set an oopmap for the call site.
3072   // We need this not only for callee-saved registers, but also for volatile
3073   // registers that the compiler might be keeping live across a safepoint.
3074 
3075   oop_maps->add_gc_map( __ offset() - start, map);
3076 
3077   // rax, contains the address we are going to jump to assuming no exception got installed
3078 
3079   __ addptr(rsp, wordSize);
3080 
3081   // clear last_Java_sp
3082   __ reset_last_Java_frame(thread, true, false);
3083   // check for pending exceptions
3084   Label pending;
3085   __ cmpptr(Address(thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3086   __ jcc(Assembler::notEqual, pending);
3087 
3088   // get the returned Method*
3089   __ get_vm_result_2(rbx, thread);
3090   __ movptr(Address(rsp, RegisterSaver::rbx_offset() * wordSize), rbx);
3091 
3092   __ movptr(Address(rsp, RegisterSaver::rax_offset() * wordSize), rax);
3093 
3094   RegisterSaver::restore_live_registers(masm);
3095 
3096   // We are back the the original state on entry and ready to go.
3097 
3098   __ jmp(rax);
3099 
3100   // Pending exception after the safepoint
3101 
3102   __ bind(pending);
3103 
3104   RegisterSaver::restore_live_registers(masm);
3105 
3106   // exception pending => remove activation and forward to exception handler
3107 
3108   __ get_thread(thread);
3109   __ movptr(Address(thread, JavaThread::vm_result_offset()), NULL_WORD);
3110   __ movptr(rax, Address(thread, Thread::pending_exception_offset()));
3111   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3112 
3113   // -------------
3114   // make sure all code is generated
3115   masm->flush();
3116 
3117   // return the  blob
3118   // frame_size_words or bytes??
3119   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_words, oop_maps, true);
3120 }