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