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