1 /*
   2  * Copyright 2003-2010 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 #include "incls/_precompiled.incl"
  26 #include "incls/_sharedRuntime_x86_64.cpp.incl"
  27 
  28 DeoptimizationBlob *SharedRuntime::_deopt_blob;
  29 #ifdef COMPILER2
  30 UncommonTrapBlob   *SharedRuntime::_uncommon_trap_blob;
  31 ExceptionBlob      *OptoRuntime::_exception_blob;
  32 #endif // COMPILER2
  33 
  34 SafepointBlob      *SharedRuntime::_polling_page_safepoint_handler_blob;
  35 SafepointBlob      *SharedRuntime::_polling_page_return_handler_blob;
  36 RuntimeStub*       SharedRuntime::_wrong_method_blob;
  37 RuntimeStub*       SharedRuntime::_ic_miss_blob;
  38 RuntimeStub*       SharedRuntime::_resolve_opt_virtual_call_blob;
  39 RuntimeStub*       SharedRuntime::_resolve_virtual_call_blob;
  40 RuntimeStub*       SharedRuntime::_resolve_static_call_blob;
  41 
  42 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  43 
  44 #define __ masm->
  45 
  46 class SimpleRuntimeFrame {
  47 
  48   public:
  49 
  50   // Most of the runtime stubs have this simple frame layout.
  51   // This class exists to make the layout shared in one place.
  52   // Offsets are for compiler stack slots, which are jints.
  53   enum layout {
  54     // The frame sender code expects that rbp will be in the "natural" place and
  55     // will override any oopMap setting for it. We must therefore force the layout
  56     // so that it agrees with the frame sender code.
  57     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
  58     rbp_off2,
  59     return_off, return_off2,
  60     framesize
  61   };
  62 };
  63 
  64 class RegisterSaver {
  65   // Capture info about frame layout.  Layout offsets are in jint
  66   // units because compiler frame slots are jints.
  67 #define DEF_XMM_OFFS(regnum) xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  68   enum layout {
  69     fpu_state_off = frame::arg_reg_save_area_bytes/BytesPerInt, // fxsave save area
  70     xmm_off       = fpu_state_off + 160/BytesPerInt,            // offset in fxsave save area
  71     DEF_XMM_OFFS(0),
  72     DEF_XMM_OFFS(1),
  73     DEF_XMM_OFFS(2),
  74     DEF_XMM_OFFS(3),
  75     DEF_XMM_OFFS(4),
  76     DEF_XMM_OFFS(5),
  77     DEF_XMM_OFFS(6),
  78     DEF_XMM_OFFS(7),
  79     DEF_XMM_OFFS(8),
  80     DEF_XMM_OFFS(9),
  81     DEF_XMM_OFFS(10),
  82     DEF_XMM_OFFS(11),
  83     DEF_XMM_OFFS(12),
  84     DEF_XMM_OFFS(13),
  85     DEF_XMM_OFFS(14),
  86     DEF_XMM_OFFS(15),
  87     fpu_state_end = fpu_state_off + ((FPUStateSizeInWords-1)*wordSize / BytesPerInt),
  88     fpu_stateH_end,
  89     r15_off, r15H_off,
  90     r14_off, r14H_off,
  91     r13_off, r13H_off,
  92     r12_off, r12H_off,
  93     r11_off, r11H_off,
  94     r10_off, r10H_off,
  95     r9_off,  r9H_off,
  96     r8_off,  r8H_off,
  97     rdi_off, rdiH_off,
  98     rsi_off, rsiH_off,
  99     ignore_off, ignoreH_off,  // extra copy of rbp
 100     rsp_off, rspH_off,
 101     rbx_off, rbxH_off,
 102     rdx_off, rdxH_off,
 103     rcx_off, rcxH_off,
 104     rax_off, raxH_off,
 105     // 16-byte stack alignment fill word: see MacroAssembler::push/pop_IU_state
 106     align_off, alignH_off,
 107     flags_off, flagsH_off,
 108     // The frame sender code expects that rbp will be in the "natural" place and
 109     // will override any oopMap setting for it. We must therefore force the layout
 110     // so that it agrees with the frame sender code.
 111     rbp_off, rbpH_off,        // copy of rbp we will restore
 112     return_off, returnH_off,  // slot for return address
 113     reg_save_size             // size in compiler stack slots
 114   };
 115 
 116  public:
 117   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words);
 118   static void restore_live_registers(MacroAssembler* masm);
 119 
 120   // Offsets into the register save area
 121   // Used by deoptimization when it is managing result register
 122   // values on its own
 123 
 124   static int rax_offset_in_bytes(void)    { return BytesPerInt * rax_off; }
 125   static int rdx_offset_in_bytes(void)    { return BytesPerInt * rdx_off; }
 126   static int rbx_offset_in_bytes(void)    { return BytesPerInt * rbx_off; }
 127   static int xmm0_offset_in_bytes(void)   { return BytesPerInt * xmm0_off; }
 128   static int return_offset_in_bytes(void) { return BytesPerInt * return_off; }
 129 
 130   // During deoptimization only the result registers need to be restored,
 131   // all the other values have already been extracted.
 132   static void restore_result_registers(MacroAssembler* masm);
 133 };
 134 
 135 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words) {
 136 
 137   // Always make the frame size 16-byte aligned
 138   int frame_size_in_bytes = round_to(additional_frame_words*wordSize +
 139                                      reg_save_size*BytesPerInt, 16);
 140   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 141   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 142   // The caller will allocate additional_frame_words
 143   int additional_frame_slots = additional_frame_words*wordSize / BytesPerInt;
 144   // CodeBlob frame size is in words.
 145   int frame_size_in_words = frame_size_in_bytes / wordSize;
 146   *total_frame_words = frame_size_in_words;
 147 
 148   // Save registers, fpu state, and flags.
 149   // We assume caller has already pushed the return address onto the
 150   // stack, so rsp is 8-byte aligned here.
 151   // We push rpb twice in this sequence because we want the real rbp
 152   // to be under the return like a normal enter.
 153 
 154   __ enter();          // rsp becomes 16-byte aligned here
 155   __ push_CPU_state(); // Push a multiple of 16 bytes
 156   if (frame::arg_reg_save_area_bytes != 0) {
 157     // Allocate argument register save area
 158     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 159   }
 160 
 161   // Set an oopmap for the call site.  This oopmap will map all
 162   // oop-registers and debug-info registers as callee-saved.  This
 163   // will allow deoptimization at this safepoint to find all possible
 164   // debug-info recordings, as well as let GC find all oops.
 165 
 166   OopMapSet *oop_maps = new OopMapSet();
 167   OopMap* map = new OopMap(frame_size_in_slots, 0);
 168   map->set_callee_saved(VMRegImpl::stack2reg( rax_off  + additional_frame_slots), rax->as_VMReg());
 169   map->set_callee_saved(VMRegImpl::stack2reg( rcx_off  + additional_frame_slots), rcx->as_VMReg());
 170   map->set_callee_saved(VMRegImpl::stack2reg( rdx_off  + additional_frame_slots), rdx->as_VMReg());
 171   map->set_callee_saved(VMRegImpl::stack2reg( rbx_off  + additional_frame_slots), rbx->as_VMReg());
 172   // rbp location is known implicitly by the frame sender code, needs no oopmap
 173   // and the location where rbp was saved by is ignored
 174   map->set_callee_saved(VMRegImpl::stack2reg( rsi_off  + additional_frame_slots), rsi->as_VMReg());
 175   map->set_callee_saved(VMRegImpl::stack2reg( rdi_off  + additional_frame_slots), rdi->as_VMReg());
 176   map->set_callee_saved(VMRegImpl::stack2reg( r8_off   + additional_frame_slots), r8->as_VMReg());
 177   map->set_callee_saved(VMRegImpl::stack2reg( r9_off   + additional_frame_slots), r9->as_VMReg());
 178   map->set_callee_saved(VMRegImpl::stack2reg( r10_off  + additional_frame_slots), r10->as_VMReg());
 179   map->set_callee_saved(VMRegImpl::stack2reg( r11_off  + additional_frame_slots), r11->as_VMReg());
 180   map->set_callee_saved(VMRegImpl::stack2reg( r12_off  + additional_frame_slots), r12->as_VMReg());
 181   map->set_callee_saved(VMRegImpl::stack2reg( r13_off  + additional_frame_slots), r13->as_VMReg());
 182   map->set_callee_saved(VMRegImpl::stack2reg( r14_off  + additional_frame_slots), r14->as_VMReg());
 183   map->set_callee_saved(VMRegImpl::stack2reg( r15_off  + additional_frame_slots), r15->as_VMReg());
 184   map->set_callee_saved(VMRegImpl::stack2reg(xmm0_off  + additional_frame_slots), xmm0->as_VMReg());
 185   map->set_callee_saved(VMRegImpl::stack2reg(xmm1_off  + additional_frame_slots), xmm1->as_VMReg());
 186   map->set_callee_saved(VMRegImpl::stack2reg(xmm2_off  + additional_frame_slots), xmm2->as_VMReg());
 187   map->set_callee_saved(VMRegImpl::stack2reg(xmm3_off  + additional_frame_slots), xmm3->as_VMReg());
 188   map->set_callee_saved(VMRegImpl::stack2reg(xmm4_off  + additional_frame_slots), xmm4->as_VMReg());
 189   map->set_callee_saved(VMRegImpl::stack2reg(xmm5_off  + additional_frame_slots), xmm5->as_VMReg());
 190   map->set_callee_saved(VMRegImpl::stack2reg(xmm6_off  + additional_frame_slots), xmm6->as_VMReg());
 191   map->set_callee_saved(VMRegImpl::stack2reg(xmm7_off  + additional_frame_slots), xmm7->as_VMReg());
 192   map->set_callee_saved(VMRegImpl::stack2reg(xmm8_off  + additional_frame_slots), xmm8->as_VMReg());
 193   map->set_callee_saved(VMRegImpl::stack2reg(xmm9_off  + additional_frame_slots), xmm9->as_VMReg());
 194   map->set_callee_saved(VMRegImpl::stack2reg(xmm10_off + additional_frame_slots), xmm10->as_VMReg());
 195   map->set_callee_saved(VMRegImpl::stack2reg(xmm11_off + additional_frame_slots), xmm11->as_VMReg());
 196   map->set_callee_saved(VMRegImpl::stack2reg(xmm12_off + additional_frame_slots), xmm12->as_VMReg());
 197   map->set_callee_saved(VMRegImpl::stack2reg(xmm13_off + additional_frame_slots), xmm13->as_VMReg());
 198   map->set_callee_saved(VMRegImpl::stack2reg(xmm14_off + additional_frame_slots), xmm14->as_VMReg());
 199   map->set_callee_saved(VMRegImpl::stack2reg(xmm15_off + additional_frame_slots), xmm15->as_VMReg());
 200 
 201   // %%% These should all be a waste but we'll keep things as they were for now
 202   if (true) {
 203     map->set_callee_saved(VMRegImpl::stack2reg( raxH_off  + additional_frame_slots),
 204                           rax->as_VMReg()->next());
 205     map->set_callee_saved(VMRegImpl::stack2reg( rcxH_off  + additional_frame_slots),
 206                           rcx->as_VMReg()->next());
 207     map->set_callee_saved(VMRegImpl::stack2reg( rdxH_off  + additional_frame_slots),
 208                           rdx->as_VMReg()->next());
 209     map->set_callee_saved(VMRegImpl::stack2reg( rbxH_off  + additional_frame_slots),
 210                           rbx->as_VMReg()->next());
 211     // rbp location is known implicitly by the frame sender code, needs no oopmap
 212     map->set_callee_saved(VMRegImpl::stack2reg( rsiH_off  + additional_frame_slots),
 213                           rsi->as_VMReg()->next());
 214     map->set_callee_saved(VMRegImpl::stack2reg( rdiH_off  + additional_frame_slots),
 215                           rdi->as_VMReg()->next());
 216     map->set_callee_saved(VMRegImpl::stack2reg( r8H_off   + additional_frame_slots),
 217                           r8->as_VMReg()->next());
 218     map->set_callee_saved(VMRegImpl::stack2reg( r9H_off   + additional_frame_slots),
 219                           r9->as_VMReg()->next());
 220     map->set_callee_saved(VMRegImpl::stack2reg( r10H_off  + additional_frame_slots),
 221                           r10->as_VMReg()->next());
 222     map->set_callee_saved(VMRegImpl::stack2reg( r11H_off  + additional_frame_slots),
 223                           r11->as_VMReg()->next());
 224     map->set_callee_saved(VMRegImpl::stack2reg( r12H_off  + additional_frame_slots),
 225                           r12->as_VMReg()->next());
 226     map->set_callee_saved(VMRegImpl::stack2reg( r13H_off  + additional_frame_slots),
 227                           r13->as_VMReg()->next());
 228     map->set_callee_saved(VMRegImpl::stack2reg( r14H_off  + additional_frame_slots),
 229                           r14->as_VMReg()->next());
 230     map->set_callee_saved(VMRegImpl::stack2reg( r15H_off  + additional_frame_slots),
 231                           r15->as_VMReg()->next());
 232     map->set_callee_saved(VMRegImpl::stack2reg(xmm0H_off  + additional_frame_slots),
 233                           xmm0->as_VMReg()->next());
 234     map->set_callee_saved(VMRegImpl::stack2reg(xmm1H_off  + additional_frame_slots),
 235                           xmm1->as_VMReg()->next());
 236     map->set_callee_saved(VMRegImpl::stack2reg(xmm2H_off  + additional_frame_slots),
 237                           xmm2->as_VMReg()->next());
 238     map->set_callee_saved(VMRegImpl::stack2reg(xmm3H_off  + additional_frame_slots),
 239                           xmm3->as_VMReg()->next());
 240     map->set_callee_saved(VMRegImpl::stack2reg(xmm4H_off  + additional_frame_slots),
 241                           xmm4->as_VMReg()->next());
 242     map->set_callee_saved(VMRegImpl::stack2reg(xmm5H_off  + additional_frame_slots),
 243                           xmm5->as_VMReg()->next());
 244     map->set_callee_saved(VMRegImpl::stack2reg(xmm6H_off  + additional_frame_slots),
 245                           xmm6->as_VMReg()->next());
 246     map->set_callee_saved(VMRegImpl::stack2reg(xmm7H_off  + additional_frame_slots),
 247                           xmm7->as_VMReg()->next());
 248     map->set_callee_saved(VMRegImpl::stack2reg(xmm8H_off  + additional_frame_slots),
 249                           xmm8->as_VMReg()->next());
 250     map->set_callee_saved(VMRegImpl::stack2reg(xmm9H_off  + additional_frame_slots),
 251                           xmm9->as_VMReg()->next());
 252     map->set_callee_saved(VMRegImpl::stack2reg(xmm10H_off + additional_frame_slots),
 253                           xmm10->as_VMReg()->next());
 254     map->set_callee_saved(VMRegImpl::stack2reg(xmm11H_off + additional_frame_slots),
 255                           xmm11->as_VMReg()->next());
 256     map->set_callee_saved(VMRegImpl::stack2reg(xmm12H_off + additional_frame_slots),
 257                           xmm12->as_VMReg()->next());
 258     map->set_callee_saved(VMRegImpl::stack2reg(xmm13H_off + additional_frame_slots),
 259                           xmm13->as_VMReg()->next());
 260     map->set_callee_saved(VMRegImpl::stack2reg(xmm14H_off + additional_frame_slots),
 261                           xmm14->as_VMReg()->next());
 262     map->set_callee_saved(VMRegImpl::stack2reg(xmm15H_off + additional_frame_slots),
 263                           xmm15->as_VMReg()->next());
 264   }
 265 
 266   return map;
 267 }
 268 
 269 void RegisterSaver::restore_live_registers(MacroAssembler* masm) {
 270   if (frame::arg_reg_save_area_bytes != 0) {
 271     // Pop arg register save area
 272     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 273   }
 274   // Recover CPU state
 275   __ pop_CPU_state();
 276   // Get the rbp described implicitly by the calling convention (no oopMap)
 277   __ pop(rbp);
 278 }
 279 
 280 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 281 
 282   // Just restore result register. Only used by deoptimization. By
 283   // now any callee save register that needs to be restored to a c2
 284   // caller of the deoptee has been extracted into the vframeArray
 285   // and will be stuffed into the c2i adapter we create for later
 286   // restoration so only result registers need to be restored here.
 287 
 288   // Restore fp result register
 289   __ movdbl(xmm0, Address(rsp, xmm0_offset_in_bytes()));
 290   // Restore integer result register
 291   __ movptr(rax, Address(rsp, rax_offset_in_bytes()));
 292   __ movptr(rdx, Address(rsp, rdx_offset_in_bytes()));
 293 
 294   // Pop all of the register save are off the stack except the return address
 295   __ addptr(rsp, return_offset_in_bytes());
 296 }
 297 
 298 // The java_calling_convention describes stack locations as ideal slots on
 299 // a frame with no abi restrictions. Since we must observe abi restrictions
 300 // (like the placement of the register window) the slots must be biased by
 301 // the following value.
 302 static int reg2offset_in(VMReg r) {
 303   // Account for saved rbp and return address
 304   // This should really be in_preserve_stack_slots
 305   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 306 }
 307 
 308 static int reg2offset_out(VMReg r) {
 309   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 310 }
 311 
 312 // ---------------------------------------------------------------------------
 313 // This method is used to read a float value which is saved on stack as double
 314 // (see RegisterSaver::save_live_registers() above).
 315 StackValue* StackValue::create_float_stack_value(address value_addr) {
 316   union { intptr_t p; jfloat jf; } value;
 317   value.p = (intptr_t) CONST64(0xDEADDEAFDEADDEAF);
 318   // XMM registers are used for float values and they are saved as double
 319   // without conversion. Read lowest 32 bit to get float value.
 320   value.jf = *(jfloat*) value_addr;
 321   return new StackValue(value.p); // 64-bit high half is stack junk
 322 }
 323 
 324 // ---------------------------------------------------------------------------
 325 // Read the array of BasicTypes from a signature, and compute where the
 326 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 327 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 328 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 329 // as framesizes are fixed.
 330 // VMRegImpl::stack0 refers to the first slot 0(sp).
 331 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 332 // up to RegisterImpl::number_of_registers) are the 64-bit
 333 // integer registers.
 334 
 335 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 336 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 337 // units regardless of build. Of course for i486 there is no 64 bit build
 338 
 339 // The Java calling convention is a "shifted" version of the C ABI.
 340 // By skipping the first C ABI register we can call non-static jni methods
 341 // with small numbers of arguments without having to shuffle the arguments
 342 // at all. Since we control the java ABI we ought to at least get some
 343 // advantage out of it.
 344 
 345 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 346                                            VMRegPair *regs,
 347                                            int total_args_passed,
 348                                            int is_outgoing) {
 349 
 350   // Create the mapping between argument positions and
 351   // registers.
 352   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 353     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5
 354   };
 355   static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 356     j_farg0, j_farg1, j_farg2, j_farg3,
 357     j_farg4, j_farg5, j_farg6, j_farg7
 358   };
 359 
 360 
 361   uint int_args = 0;
 362   uint fp_args = 0;
 363   uint stk_args = 0; // inc by 2 each time
 364 
 365   for (int i = 0; i < total_args_passed; i++) {
 366     switch (sig_bt[i]) {
 367     case T_BOOLEAN:
 368     case T_CHAR:
 369     case T_BYTE:
 370     case T_SHORT:
 371     case T_INT:
 372       if (int_args < Argument::n_int_register_parameters_j) {
 373         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 374       } else {
 375         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 376         stk_args += 2;
 377       }
 378       break;
 379     case T_VOID:
 380       // halves of T_LONG or T_DOUBLE
 381       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 382       regs[i].set_bad();
 383       break;
 384     case T_LONG:
 385       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 386       // fall through
 387     case T_OBJECT:
 388     case T_ARRAY:
 389     case T_ADDRESS:
 390       if (int_args < Argument::n_int_register_parameters_j) {
 391         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 392       } else {
 393         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 394         stk_args += 2;
 395       }
 396       break;
 397     case T_FLOAT:
 398       if (fp_args < Argument::n_float_register_parameters_j) {
 399         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 400       } else {
 401         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 402         stk_args += 2;
 403       }
 404       break;
 405     case T_DOUBLE:
 406       assert(sig_bt[i + 1] == T_VOID, "expecting half");
 407       if (fp_args < Argument::n_float_register_parameters_j) {
 408         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 409       } else {
 410         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 411         stk_args += 2;
 412       }
 413       break;
 414     default:
 415       ShouldNotReachHere();
 416       break;
 417     }
 418   }
 419 
 420   return round_to(stk_args, 2);
 421 }
 422 
 423 // Patch the callers callsite with entry to compiled code if it exists.
 424 static void patch_callers_callsite(MacroAssembler *masm) {
 425   Label L;
 426   __ verify_oop(rbx);
 427   __ cmpptr(Address(rbx, in_bytes(methodOopDesc::code_offset())), (int32_t)NULL_WORD);
 428   __ jcc(Assembler::equal, L);
 429 
 430   // Save the current stack pointer
 431   __ mov(r13, rsp);
 432   // Schedule the branch target address early.
 433   // Call into the VM to patch the caller, then jump to compiled callee
 434   // rax isn't live so capture return address while we easily can
 435   __ movptr(rax, Address(rsp, 0));
 436 
 437   // align stack so push_CPU_state doesn't fault
 438   __ andptr(rsp, -(StackAlignmentInBytes));
 439   __ push_CPU_state();
 440 
 441 
 442   __ verify_oop(rbx);
 443   // VM needs caller's callsite
 444   // VM needs target method
 445   // This needs to be a long call since we will relocate this adapter to
 446   // the codeBuffer and it may not reach
 447 
 448   // Allocate argument register save area
 449   if (frame::arg_reg_save_area_bytes != 0) {
 450     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 451   }
 452   __ mov(c_rarg0, rbx);
 453   __ mov(c_rarg1, rax);
 454   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 455 
 456   // De-allocate argument register save area
 457   if (frame::arg_reg_save_area_bytes != 0) {
 458     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 459   }
 460 
 461   __ pop_CPU_state();
 462   // restore sp
 463   __ mov(rsp, r13);
 464   __ bind(L);
 465 }
 466 
 467 // Helper function to put tags in interpreter stack.
 468 static void  tag_stack(MacroAssembler *masm, const BasicType sig, int st_off) {
 469   if (TaggedStackInterpreter) {
 470     int tag_offset = st_off + Interpreter::expr_tag_offset_in_bytes(0);
 471     if (sig == T_OBJECT || sig == T_ARRAY) {
 472       __ movptr(Address(rsp, tag_offset), (int32_t) frame::TagReference);
 473     } else if (sig == T_LONG || sig == T_DOUBLE) {
 474       int next_tag_offset = st_off + Interpreter::expr_tag_offset_in_bytes(1);
 475       __ movptr(Address(rsp, next_tag_offset), (int32_t) frame::TagValue);
 476       __ movptr(Address(rsp, tag_offset), (int32_t) frame::TagValue);
 477     } else {
 478       __ movptr(Address(rsp, tag_offset), (int32_t) frame::TagValue);
 479     }
 480   }
 481 }
 482 
 483 
 484 static void gen_c2i_adapter(MacroAssembler *masm,
 485                             int total_args_passed,
 486                             int comp_args_on_stack,
 487                             const BasicType *sig_bt,
 488                             const VMRegPair *regs,
 489                             Label& skip_fixup) {
 490   // Before we get into the guts of the C2I adapter, see if we should be here
 491   // at all.  We've come from compiled code and are attempting to jump to the
 492   // interpreter, which means the caller made a static call to get here
 493   // (vcalls always get a compiled target if there is one).  Check for a
 494   // compiled target.  If there is one, we need to patch the caller's call.
 495   patch_callers_callsite(masm);
 496 
 497   __ bind(skip_fixup);
 498 
 499   // Since all args are passed on the stack, total_args_passed *
 500   // Interpreter::stackElementSize is the space we need. Plus 1 because
 501   // we also account for the return address location since
 502   // we store it first rather than hold it in rax across all the shuffling
 503 
 504   int extraspace = (total_args_passed * Interpreter::stackElementSize()) + wordSize;
 505 
 506   // stack is aligned, keep it that way
 507   extraspace = round_to(extraspace, 2*wordSize);
 508 
 509   // Get return address
 510   __ pop(rax);
 511 
 512   // set senderSP value
 513   __ mov(r13, rsp);
 514 
 515   __ subptr(rsp, extraspace);
 516 
 517   // Store the return address in the expected location
 518   __ movptr(Address(rsp, 0), rax);
 519 
 520   // Now write the args into the outgoing interpreter space
 521   for (int i = 0; i < total_args_passed; i++) {
 522     if (sig_bt[i] == T_VOID) {
 523       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 524       continue;
 525     }
 526 
 527     // offset to start parameters
 528     int st_off   = (total_args_passed - i) * Interpreter::stackElementSize() +
 529                    Interpreter::value_offset_in_bytes();
 530     int next_off = st_off - Interpreter::stackElementSize();
 531 
 532     // Say 4 args:
 533     // i   st_off
 534     // 0   32 T_LONG
 535     // 1   24 T_VOID
 536     // 2   16 T_OBJECT
 537     // 3    8 T_BOOL
 538     // -    0 return address
 539     //
 540     // However to make thing extra confusing. Because we can fit a long/double in
 541     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 542     // leaves one slot empty and only stores to a single slot. In this case the
 543     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 544 
 545     VMReg r_1 = regs[i].first();
 546     VMReg r_2 = regs[i].second();
 547     if (!r_1->is_valid()) {
 548       assert(!r_2->is_valid(), "");
 549       continue;
 550     }
 551     if (r_1->is_stack()) {
 552       // memory to memory use rax
 553       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 554       if (!r_2->is_valid()) {
 555         // sign extend??
 556         __ movl(rax, Address(rsp, ld_off));
 557         __ movptr(Address(rsp, st_off), rax);
 558         tag_stack(masm, sig_bt[i], st_off);
 559 
 560       } else {
 561 
 562         __ movq(rax, Address(rsp, ld_off));
 563 
 564         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 565         // T_DOUBLE and T_LONG use two slots in the interpreter
 566         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 567           // ld_off == LSW, ld_off+wordSize == MSW
 568           // st_off == MSW, next_off == LSW
 569           __ movq(Address(rsp, next_off), rax);
 570 #ifdef ASSERT
 571           // Overwrite the unused slot with known junk
 572           __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 573           __ movptr(Address(rsp, st_off), rax);
 574 #endif /* ASSERT */
 575           tag_stack(masm, sig_bt[i], next_off);
 576         } else {
 577           __ movq(Address(rsp, st_off), rax);
 578           tag_stack(masm, sig_bt[i], st_off);
 579         }
 580       }
 581     } else if (r_1->is_Register()) {
 582       Register r = r_1->as_Register();
 583       if (!r_2->is_valid()) {
 584         // must be only an int (or less ) so move only 32bits to slot
 585         // why not sign extend??
 586         __ movl(Address(rsp, st_off), r);
 587         tag_stack(masm, sig_bt[i], st_off);
 588       } else {
 589         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 590         // T_DOUBLE and T_LONG use two slots in the interpreter
 591         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 592           // long/double in gpr
 593 #ifdef ASSERT
 594           // Overwrite the unused slot with known junk
 595           __ mov64(rax, CONST64(0xdeadffffdeadaaab));
 596           __ movptr(Address(rsp, st_off), rax);
 597 #endif /* ASSERT */
 598           __ movq(Address(rsp, next_off), r);
 599           tag_stack(masm, sig_bt[i], next_off);
 600         } else {
 601           __ movptr(Address(rsp, st_off), r);
 602           tag_stack(masm, sig_bt[i], st_off);
 603         }
 604       }
 605     } else {
 606       assert(r_1->is_XMMRegister(), "");
 607       if (!r_2->is_valid()) {
 608         // only a float use just part of the slot
 609         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 610         tag_stack(masm, sig_bt[i], st_off);
 611       } else {
 612 #ifdef ASSERT
 613         // Overwrite the unused slot with known junk
 614         __ mov64(rax, CONST64(0xdeadffffdeadaaac));
 615         __ movptr(Address(rsp, st_off), rax);
 616 #endif /* ASSERT */
 617         __ movdbl(Address(rsp, next_off), r_1->as_XMMRegister());
 618         tag_stack(masm, sig_bt[i], next_off);
 619       }
 620     }
 621   }
 622 
 623   // Schedule the branch target address early.
 624   __ movptr(rcx, Address(rbx, in_bytes(methodOopDesc::interpreter_entry_offset())));
 625   __ jmp(rcx);
 626 }
 627 
 628 static void gen_i2c_adapter(MacroAssembler *masm,
 629                             int total_args_passed,
 630                             int comp_args_on_stack,
 631                             const BasicType *sig_bt,
 632                             const VMRegPair *regs) {
 633 
 634   //
 635   // We will only enter here from an interpreted frame and never from after
 636   // passing thru a c2i. Azul allowed this but we do not. If we lose the
 637   // race and use a c2i we will remain interpreted for the race loser(s).
 638   // This removes all sorts of headaches on the x86 side and also eliminates
 639   // the possibility of having c2i -> i2c -> c2i -> ... endless transitions.
 640 
 641 
 642   // Note: r13 contains the senderSP on entry. We must preserve it since
 643   // we may do a i2c -> c2i transition if we lose a race where compiled
 644   // code goes non-entrant while we get args ready.
 645   // In addition we use r13 to locate all the interpreter args as
 646   // we must align the stack to 16 bytes on an i2c entry else we
 647   // lose alignment we expect in all compiled code and register
 648   // save code can segv when fxsave instructions find improperly
 649   // aligned stack pointer.
 650 
 651   __ movptr(rax, Address(rsp, 0));
 652 
 653   // Must preserve original SP for loading incoming arguments because
 654   // we need to align the outgoing SP for compiled code.
 655   __ movptr(r11, rsp);
 656 
 657   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 658   // in registers, we will occasionally have no stack args.
 659   int comp_words_on_stack = 0;
 660   if (comp_args_on_stack) {
 661     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 662     // registers are below.  By subtracting stack0, we either get a negative
 663     // number (all values in registers) or the maximum stack slot accessed.
 664 
 665     // Convert 4-byte c2 stack slots to words.
 666     comp_words_on_stack = round_to(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 667     // Round up to miminum stack alignment, in wordSize
 668     comp_words_on_stack = round_to(comp_words_on_stack, 2);
 669     __ subptr(rsp, comp_words_on_stack * wordSize);
 670   }
 671 
 672 
 673   // Ensure compiled code always sees stack at proper alignment
 674   __ andptr(rsp, -16);
 675 
 676   // push the return address and misalign the stack that youngest frame always sees
 677   // as far as the placement of the call instruction
 678   __ push(rax);
 679 
 680   // Put saved SP in another register
 681   const Register saved_sp = rax;
 682   __ movptr(saved_sp, r11);
 683 
 684   // Will jump to the compiled code just as if compiled code was doing it.
 685   // Pre-load the register-jump target early, to schedule it better.
 686   __ movptr(r11, Address(rbx, in_bytes(methodOopDesc::from_compiled_offset())));
 687 
 688   // Now generate the shuffle code.  Pick up all register args and move the
 689   // rest through the floating point stack top.
 690   for (int i = 0; i < total_args_passed; i++) {
 691     if (sig_bt[i] == T_VOID) {
 692       // Longs and doubles are passed in native word order, but misaligned
 693       // in the 32-bit build.
 694       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 695       continue;
 696     }
 697 
 698     // Pick up 0, 1 or 2 words from SP+offset.
 699 
 700     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 701             "scrambled load targets?");
 702     // Load in argument order going down.
 703     int ld_off = (total_args_passed - i)*Interpreter::stackElementSize() + Interpreter::value_offset_in_bytes();
 704     // Point to interpreter value (vs. tag)
 705     int next_off = ld_off - Interpreter::stackElementSize();
 706     //
 707     //
 708     //
 709     VMReg r_1 = regs[i].first();
 710     VMReg r_2 = regs[i].second();
 711     if (!r_1->is_valid()) {
 712       assert(!r_2->is_valid(), "");
 713       continue;
 714     }
 715     if (r_1->is_stack()) {
 716       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 717       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 718 
 719       // We can use r13 as a temp here because compiled code doesn't need r13 as an input
 720       // and if we end up going thru a c2i because of a miss a reasonable value of r13
 721       // will be generated.
 722       if (!r_2->is_valid()) {
 723         // sign extend???
 724         __ movl(r13, Address(saved_sp, ld_off));
 725         __ movptr(Address(rsp, st_off), r13);
 726       } else {
 727         //
 728         // We are using two optoregs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 729         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 730         // So we must adjust where to pick up the data to match the interpreter.
 731         //
 732         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 733         // are accessed as negative so LSW is at LOW address
 734 
 735         // ld_off is MSW so get LSW
 736         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 737                            next_off : ld_off;
 738         __ movq(r13, Address(saved_sp, offset));
 739         // st_off is LSW (i.e. reg.first())
 740         __ movq(Address(rsp, st_off), r13);
 741       }
 742     } else if (r_1->is_Register()) {  // Register argument
 743       Register r = r_1->as_Register();
 744       assert(r != rax, "must be different");
 745       if (r_2->is_valid()) {
 746         //
 747         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 748         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 749         // So we must adjust where to pick up the data to match the interpreter.
 750 
 751         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 752                            next_off : ld_off;
 753 
 754         // this can be a misaligned move
 755         __ movq(r, Address(saved_sp, offset));
 756       } else {
 757         // sign extend and use a full word?
 758         __ movl(r, Address(saved_sp, ld_off));
 759       }
 760     } else {
 761       if (!r_2->is_valid()) {
 762         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 763       } else {
 764         __ movdbl(r_1->as_XMMRegister(), Address(saved_sp, next_off));
 765       }
 766     }
 767   }
 768 
 769   // 6243940 We might end up in handle_wrong_method if
 770   // the callee is deoptimized as we race thru here. If that
 771   // happens we don't want to take a safepoint because the
 772   // caller frame will look interpreted and arguments are now
 773   // "compiled" so it is much better to make this transition
 774   // invisible to the stack walking code. Unfortunately if
 775   // we try and find the callee by normal means a safepoint
 776   // is possible. So we stash the desired callee in the thread
 777   // and the vm will find there should this case occur.
 778 
 779   __ movptr(Address(r15_thread, JavaThread::callee_target_offset()), rbx);
 780 
 781   // put methodOop where a c2i would expect should we end up there
 782   // only needed becaus eof c2 resolve stubs return methodOop as a result in
 783   // rax
 784   __ mov(rax, rbx);
 785   __ jmp(r11);
 786 }
 787 
 788 // ---------------------------------------------------------------
 789 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 790                                                             int total_args_passed,
 791                                                             int comp_args_on_stack,
 792                                                             const BasicType *sig_bt,
 793                                                             const VMRegPair *regs,
 794                                                             AdapterFingerPrint* fingerprint) {
 795   address i2c_entry = __ pc();
 796 
 797   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 798 
 799   // -------------------------------------------------------------------------
 800   // Generate a C2I adapter.  On entry we know rbx holds the methodOop during calls
 801   // to the interpreter.  The args start out packed in the compiled layout.  They
 802   // need to be unpacked into the interpreter layout.  This will almost always
 803   // require some stack space.  We grow the current (compiled) stack, then repack
 804   // the args.  We  finally end in a jump to the generic interpreter entry point.
 805   // On exit from the interpreter, the interpreter will restore our SP (lest the
 806   // compiled code, which relys solely on SP and not RBP, get sick).
 807 
 808   address c2i_unverified_entry = __ pc();
 809   Label skip_fixup;
 810   Label ok;
 811 
 812   Register holder = rax;
 813   Register receiver = j_rarg0;
 814   Register temp = rbx;
 815 
 816   {
 817     __ verify_oop(holder);
 818     __ load_klass(temp, receiver);
 819     __ verify_oop(temp);
 820 
 821     __ cmpptr(temp, Address(holder, compiledICHolderOopDesc::holder_klass_offset()));
 822     __ movptr(rbx, Address(holder, compiledICHolderOopDesc::holder_method_offset()));
 823     __ jcc(Assembler::equal, ok);
 824     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 825 
 826     __ bind(ok);
 827     // Method might have been compiled since the call site was patched to
 828     // interpreted if that is the case treat it as a miss so we can get
 829     // the call site corrected.
 830     __ cmpptr(Address(rbx, in_bytes(methodOopDesc::code_offset())), (int32_t)NULL_WORD);
 831     __ jcc(Assembler::equal, skip_fixup);
 832     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 833   }
 834 
 835   address c2i_entry = __ pc();
 836 
 837   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 838 
 839   __ flush();
 840   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 841 }
 842 
 843 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 844                                          VMRegPair *regs,
 845                                          int total_args_passed) {
 846 // We return the amount of VMRegImpl stack slots we need to reserve for all
 847 // the arguments NOT counting out_preserve_stack_slots.
 848 
 849 // NOTE: These arrays will have to change when c1 is ported
 850 #ifdef _WIN64
 851     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 852       c_rarg0, c_rarg1, c_rarg2, c_rarg3
 853     };
 854     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 855       c_farg0, c_farg1, c_farg2, c_farg3
 856     };
 857 #else
 858     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
 859       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5
 860     };
 861     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
 862       c_farg0, c_farg1, c_farg2, c_farg3,
 863       c_farg4, c_farg5, c_farg6, c_farg7
 864     };
 865 #endif // _WIN64
 866 
 867 
 868     uint int_args = 0;
 869     uint fp_args = 0;
 870     uint stk_args = 0; // inc by 2 each time
 871 
 872     for (int i = 0; i < total_args_passed; i++) {
 873       switch (sig_bt[i]) {
 874       case T_BOOLEAN:
 875       case T_CHAR:
 876       case T_BYTE:
 877       case T_SHORT:
 878       case T_INT:
 879         if (int_args < Argument::n_int_register_parameters_c) {
 880           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 881 #ifdef _WIN64
 882           fp_args++;
 883           // Allocate slots for callee to stuff register args the stack.
 884           stk_args += 2;
 885 #endif
 886         } else {
 887           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 888           stk_args += 2;
 889         }
 890         break;
 891       case T_LONG:
 892         assert(sig_bt[i + 1] == T_VOID, "expecting half");
 893         // fall through
 894       case T_OBJECT:
 895       case T_ARRAY:
 896       case T_ADDRESS:
 897         if (int_args < Argument::n_int_register_parameters_c) {
 898           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 899 #ifdef _WIN64
 900           fp_args++;
 901           stk_args += 2;
 902 #endif
 903         } else {
 904           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 905           stk_args += 2;
 906         }
 907         break;
 908       case T_FLOAT:
 909         if (fp_args < Argument::n_float_register_parameters_c) {
 910           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 911 #ifdef _WIN64
 912           int_args++;
 913           // Allocate slots for callee to stuff register args the stack.
 914           stk_args += 2;
 915 #endif
 916         } else {
 917           regs[i].set1(VMRegImpl::stack2reg(stk_args));
 918           stk_args += 2;
 919         }
 920         break;
 921       case T_DOUBLE:
 922         assert(sig_bt[i + 1] == T_VOID, "expecting half");
 923         if (fp_args < Argument::n_float_register_parameters_c) {
 924           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 925 #ifdef _WIN64
 926           int_args++;
 927           // Allocate slots for callee to stuff register args the stack.
 928           stk_args += 2;
 929 #endif
 930         } else {
 931           regs[i].set2(VMRegImpl::stack2reg(stk_args));
 932           stk_args += 2;
 933         }
 934         break;
 935       case T_VOID: // Halves of longs and doubles
 936         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 937         regs[i].set_bad();
 938         break;
 939       default:
 940         ShouldNotReachHere();
 941         break;
 942       }
 943     }
 944 #ifdef _WIN64
 945   // windows abi requires that we always allocate enough stack space
 946   // for 4 64bit registers to be stored down.
 947   if (stk_args < 8) {
 948     stk_args = 8;
 949   }
 950 #endif // _WIN64
 951 
 952   return stk_args;
 953 }
 954 
 955 // On 64 bit we will store integer like items to the stack as
 956 // 64 bits items (sparc abi) even though java would only store
 957 // 32bits for a parameter. On 32bit it will simply be 32 bits
 958 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
 959 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
 960   if (src.first()->is_stack()) {
 961     if (dst.first()->is_stack()) {
 962       // stack to stack
 963       __ movslq(rax, Address(rbp, reg2offset_in(src.first())));
 964       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
 965     } else {
 966       // stack to reg
 967       __ movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
 968     }
 969   } else if (dst.first()->is_stack()) {
 970     // reg to stack
 971     // Do we really have to sign extend???
 972     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
 973     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
 974   } else {
 975     // Do we really have to sign extend???
 976     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
 977     if (dst.first() != src.first()) {
 978       __ movq(dst.first()->as_Register(), src.first()->as_Register());
 979     }
 980   }
 981 }
 982 
 983 
 984 // An oop arg. Must pass a handle not the oop itself
 985 static void object_move(MacroAssembler* masm,
 986                         OopMap* map,
 987                         int oop_handle_offset,
 988                         int framesize_in_slots,
 989                         VMRegPair src,
 990                         VMRegPair dst,
 991                         bool is_receiver,
 992                         int* receiver_offset) {
 993 
 994   // must pass a handle. First figure out the location we use as a handle
 995 
 996   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
 997 
 998   // See if oop is NULL if it is we need no handle
 999 
1000   if (src.first()->is_stack()) {
1001 
1002     // Oop is already on the stack as an argument
1003     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1004     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1005     if (is_receiver) {
1006       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1007     }
1008 
1009     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1010     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1011     // conditionally move a NULL
1012     __ cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
1013   } else {
1014 
1015     // Oop is in an a register we must store it to the space we reserve
1016     // on the stack for oop_handles and pass a handle if oop is non-NULL
1017 
1018     const Register rOop = src.first()->as_Register();
1019     int oop_slot;
1020     if (rOop == j_rarg0)
1021       oop_slot = 0;
1022     else if (rOop == j_rarg1)
1023       oop_slot = 1;
1024     else if (rOop == j_rarg2)
1025       oop_slot = 2;
1026     else if (rOop == j_rarg3)
1027       oop_slot = 3;
1028     else if (rOop == j_rarg4)
1029       oop_slot = 4;
1030     else {
1031       assert(rOop == j_rarg5, "wrong register");
1032       oop_slot = 5;
1033     }
1034 
1035     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1036     int offset = oop_slot*VMRegImpl::stack_slot_size;
1037 
1038     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1039     // Store oop in handle area, may be NULL
1040     __ movptr(Address(rsp, offset), rOop);
1041     if (is_receiver) {
1042       *receiver_offset = offset;
1043     }
1044 
1045     __ cmpptr(rOop, (int32_t)NULL_WORD);
1046     __ lea(rHandle, Address(rsp, offset));
1047     // conditionally move a NULL from the handle area where it was just stored
1048     __ cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
1049   }
1050 
1051   // If arg is on the stack then place it otherwise it is already in correct reg.
1052   if (dst.first()->is_stack()) {
1053     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1054   }
1055 }
1056 
1057 // A float arg may have to do float reg int reg conversion
1058 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1059   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1060 
1061   // The calling conventions assures us that each VMregpair is either
1062   // all really one physical register or adjacent stack slots.
1063   // This greatly simplifies the cases here compared to sparc.
1064 
1065   if (src.first()->is_stack()) {
1066     if (dst.first()->is_stack()) {
1067       __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1068       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1069     } else {
1070       // stack to reg
1071       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1072       __ movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
1073     }
1074   } else if (dst.first()->is_stack()) {
1075     // reg to stack
1076     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1077     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1078   } else {
1079     // reg to reg
1080     // In theory these overlap but the ordering is such that this is likely a nop
1081     if ( src.first() != dst.first()) {
1082       __ movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1083     }
1084   }
1085 }
1086 
1087 // A long move
1088 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1089 
1090   // The calling conventions assures us that each VMregpair is either
1091   // all really one physical register or adjacent stack slots.
1092   // This greatly simplifies the cases here compared to sparc.
1093 
1094   if (src.is_single_phys_reg() ) {
1095     if (dst.is_single_phys_reg()) {
1096       if (dst.first() != src.first()) {
1097         __ mov(dst.first()->as_Register(), src.first()->as_Register());
1098       }
1099     } else {
1100       assert(dst.is_single_reg(), "not a stack pair");
1101       __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1102     }
1103   } else if (dst.is_single_phys_reg()) {
1104     assert(src.is_single_reg(),  "not a stack pair");
1105     __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
1106   } else {
1107     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1108     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1109     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1110   }
1111 }
1112 
1113 // A double move
1114 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1115 
1116   // The calling conventions assures us that each VMregpair is either
1117   // all really one physical register or adjacent stack slots.
1118   // This greatly simplifies the cases here compared to sparc.
1119 
1120   if (src.is_single_phys_reg() ) {
1121     if (dst.is_single_phys_reg()) {
1122       // In theory these overlap but the ordering is such that this is likely a nop
1123       if ( src.first() != dst.first()) {
1124         __ movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
1125       }
1126     } else {
1127       assert(dst.is_single_reg(), "not a stack pair");
1128       __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1129     }
1130   } else if (dst.is_single_phys_reg()) {
1131     assert(src.is_single_reg(),  "not a stack pair");
1132     __ movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
1133   } else {
1134     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1135     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1136     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1137   }
1138 }
1139 
1140 
1141 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1142   // We always ignore the frame_slots arg and just use the space just below frame pointer
1143   // which by this time is free to use
1144   switch (ret_type) {
1145   case T_FLOAT:
1146     __ movflt(Address(rbp, -wordSize), xmm0);
1147     break;
1148   case T_DOUBLE:
1149     __ movdbl(Address(rbp, -wordSize), xmm0);
1150     break;
1151   case T_VOID:  break;
1152   default: {
1153     __ movptr(Address(rbp, -wordSize), rax);
1154     }
1155   }
1156 }
1157 
1158 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1159   // We always ignore the frame_slots arg and just use the space just below frame pointer
1160   // which by this time is free to use
1161   switch (ret_type) {
1162   case T_FLOAT:
1163     __ movflt(xmm0, Address(rbp, -wordSize));
1164     break;
1165   case T_DOUBLE:
1166     __ movdbl(xmm0, Address(rbp, -wordSize));
1167     break;
1168   case T_VOID:  break;
1169   default: {
1170     __ movptr(rax, Address(rbp, -wordSize));
1171     }
1172   }
1173 }
1174 
1175 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1176     for ( int i = first_arg ; i < arg_count ; i++ ) {
1177       if (args[i].first()->is_Register()) {
1178         __ push(args[i].first()->as_Register());
1179       } else if (args[i].first()->is_XMMRegister()) {
1180         __ subptr(rsp, 2*wordSize);
1181         __ movdbl(Address(rsp, 0), args[i].first()->as_XMMRegister());
1182       }
1183     }
1184 }
1185 
1186 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1187     for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1188       if (args[i].first()->is_Register()) {
1189         __ pop(args[i].first()->as_Register());
1190       } else if (args[i].first()->is_XMMRegister()) {
1191         __ movdbl(args[i].first()->as_XMMRegister(), Address(rsp, 0));
1192         __ addptr(rsp, 2*wordSize);
1193       }
1194     }
1195 }
1196 
1197 // ---------------------------------------------------------------------------
1198 // Generate a native wrapper for a given method.  The method takes arguments
1199 // in the Java compiled code convention, marshals them to the native
1200 // convention (handlizes oops, etc), transitions to native, makes the call,
1201 // returns to java state (possibly blocking), unhandlizes any result and
1202 // returns.
1203 nmethod *SharedRuntime::generate_native_wrapper(MacroAssembler *masm,
1204                                                 methodHandle method,
1205                                                 int total_in_args,
1206                                                 int comp_args_on_stack,
1207                                                 BasicType *in_sig_bt,
1208                                                 VMRegPair *in_regs,
1209                                                 BasicType ret_type) {
1210   // Native nmethod wrappers never take possesion of the oop arguments.
1211   // So the caller will gc the arguments. The only thing we need an
1212   // oopMap for is if the call is static
1213   //
1214   // An OopMap for lock (and class if static)
1215   OopMapSet *oop_maps = new OopMapSet();
1216   intptr_t start = (intptr_t)__ pc();
1217 
1218   // We have received a description of where all the java arg are located
1219   // on entry to the wrapper. We need to convert these args to where
1220   // the jni function will expect them. To figure out where they go
1221   // we convert the java signature to a C signature by inserting
1222   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1223 
1224   int total_c_args = total_in_args + 1;
1225   if (method->is_static()) {
1226     total_c_args++;
1227   }
1228 
1229   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1230   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair,   total_c_args);
1231 
1232   int argc = 0;
1233   out_sig_bt[argc++] = T_ADDRESS;
1234   if (method->is_static()) {
1235     out_sig_bt[argc++] = T_OBJECT;
1236   }
1237 
1238   for (int i = 0; i < total_in_args ; i++ ) {
1239     out_sig_bt[argc++] = in_sig_bt[i];
1240   }
1241 
1242   // Now figure out where the args must be stored and how much stack space
1243   // they require.
1244   //
1245   int out_arg_slots;
1246   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, total_c_args);
1247 
1248   // Compute framesize for the wrapper.  We need to handlize all oops in
1249   // incoming registers
1250 
1251   // Calculate the total number of stack slots we will need.
1252 
1253   // First count the abi requirement plus all of the outgoing args
1254   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1255 
1256   // Now the space for the inbound oop handle area
1257 
1258   int oop_handle_offset = stack_slots;
1259   stack_slots += 6*VMRegImpl::slots_per_word;
1260 
1261   // Now any space we need for handlizing a klass if static method
1262 
1263   int oop_temp_slot_offset = 0;
1264   int klass_slot_offset = 0;
1265   int klass_offset = -1;
1266   int lock_slot_offset = 0;
1267   bool is_static = false;
1268 
1269   if (method->is_static()) {
1270     klass_slot_offset = stack_slots;
1271     stack_slots += VMRegImpl::slots_per_word;
1272     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
1273     is_static = true;
1274   }
1275 
1276   // Plus a lock if needed
1277 
1278   if (method->is_synchronized()) {
1279     lock_slot_offset = stack_slots;
1280     stack_slots += VMRegImpl::slots_per_word;
1281   }
1282 
1283   // Now a place (+2) to save return values or temp during shuffling
1284   // + 4 for return address (which we own) and saved rbp
1285   stack_slots += 6;
1286 
1287   // Ok The space we have allocated will look like:
1288   //
1289   //
1290   // FP-> |                     |
1291   //      |---------------------|
1292   //      | 2 slots for moves   |
1293   //      |---------------------|
1294   //      | lock box (if sync)  |
1295   //      |---------------------| <- lock_slot_offset
1296   //      | klass (if static)   |
1297   //      |---------------------| <- klass_slot_offset
1298   //      | oopHandle area      |
1299   //      |---------------------| <- oop_handle_offset (6 java arg registers)
1300   //      | outbound memory     |
1301   //      | based arguments     |
1302   //      |                     |
1303   //      |---------------------|
1304   //      |                     |
1305   // SP-> | out_preserved_slots |
1306   //
1307   //
1308 
1309 
1310   // Now compute actual number of stack words we need rounding to make
1311   // stack properly aligned.
1312   stack_slots = round_to(stack_slots, StackAlignmentInSlots);
1313 
1314   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
1315 
1316 
1317   // First thing make an ic check to see if we should even be here
1318 
1319   // We are free to use all registers as temps without saving them and
1320   // restoring them except rbp. rbp is the only callee save register
1321   // as far as the interpreter and the compiler(s) are concerned.
1322 
1323 
1324   const Register ic_reg = rax;
1325   const Register receiver = j_rarg0;
1326 
1327   Label ok;
1328   Label exception_pending;
1329 
1330   assert_different_registers(ic_reg, receiver, rscratch1);
1331   __ verify_oop(receiver);
1332   __ load_klass(rscratch1, receiver);
1333   __ cmpq(ic_reg, rscratch1);
1334   __ jcc(Assembler::equal, ok);
1335 
1336   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
1337 
1338   __ bind(ok);
1339 
1340   // Verified entry point must be aligned
1341   __ align(8);
1342 
1343   int vep_offset = ((intptr_t)__ pc()) - start;
1344 
1345   // The instruction at the verified entry point must be 5 bytes or longer
1346   // because it can be patched on the fly by make_non_entrant. The stack bang
1347   // instruction fits that requirement.
1348 
1349   // Generate stack overflow check
1350 
1351   if (UseStackBanging) {
1352     __ bang_stack_with_offset(StackShadowPages*os::vm_page_size());
1353   } else {
1354     // need a 5 byte instruction to allow MT safe patching to non-entrant
1355     __ fat_nop();
1356   }
1357 
1358   // Generate a new frame for the wrapper.
1359   __ enter();
1360   // -2 because return address is already present and so is saved rbp
1361   __ subptr(rsp, stack_size - 2*wordSize);
1362 
1363     // Frame is now completed as far as size and linkage.
1364 
1365     int frame_complete = ((intptr_t)__ pc()) - start;
1366 
1367 #ifdef ASSERT
1368     {
1369       Label L;
1370       __ mov(rax, rsp);
1371       __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
1372       __ cmpptr(rax, rsp);
1373       __ jcc(Assembler::equal, L);
1374       __ stop("improperly aligned stack");
1375       __ bind(L);
1376     }
1377 #endif /* ASSERT */
1378 
1379 
1380   // We use r14 as the oop handle for the receiver/klass
1381   // It is callee save so it survives the call to native
1382 
1383   const Register oop_handle_reg = r14;
1384 
1385 
1386 
1387   //
1388   // We immediately shuffle the arguments so that any vm call we have to
1389   // make from here on out (sync slow path, jvmti, etc.) we will have
1390   // captured the oops from our caller and have a valid oopMap for
1391   // them.
1392 
1393   // -----------------
1394   // The Grand Shuffle
1395 
1396   // The Java calling convention is either equal (linux) or denser (win64) than the
1397   // c calling convention. However the because of the jni_env argument the c calling
1398   // convention always has at least one more (and two for static) arguments than Java.
1399   // Therefore if we move the args from java -> c backwards then we will never have
1400   // a register->register conflict and we don't have to build a dependency graph
1401   // and figure out how to break any cycles.
1402   //
1403 
1404   // Record esp-based slot for receiver on stack for non-static methods
1405   int receiver_offset = -1;
1406 
1407   // This is a trick. We double the stack slots so we can claim
1408   // the oops in the caller's frame. Since we are sure to have
1409   // more args than the caller doubling is enough to make
1410   // sure we can capture all the incoming oop args from the
1411   // caller.
1412   //
1413   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1414 
1415   // Mark location of rbp (someday)
1416   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rbp));
1417 
1418   // Use eax, ebx as temporaries during any memory-memory moves we have to do
1419   // All inbound args are referenced based on rbp and all outbound args via rsp.
1420 
1421 
1422 #ifdef ASSERT
1423   bool reg_destroyed[RegisterImpl::number_of_registers];
1424   bool freg_destroyed[XMMRegisterImpl::number_of_registers];
1425   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
1426     reg_destroyed[r] = false;
1427   }
1428   for ( int f = 0 ; f < XMMRegisterImpl::number_of_registers ; f++ ) {
1429     freg_destroyed[f] = false;
1430   }
1431 
1432 #endif /* ASSERT */
1433 
1434 
1435   int c_arg = total_c_args - 1;
1436   for ( int i = total_in_args - 1; i >= 0 ; i--, c_arg-- ) {
1437 #ifdef ASSERT
1438     if (in_regs[i].first()->is_Register()) {
1439       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
1440     } else if (in_regs[i].first()->is_XMMRegister()) {
1441       assert(!freg_destroyed[in_regs[i].first()->as_XMMRegister()->encoding()], "destroyed reg!");
1442     }
1443     if (out_regs[c_arg].first()->is_Register()) {
1444       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
1445     } else if (out_regs[c_arg].first()->is_XMMRegister()) {
1446       freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
1447     }
1448 #endif /* ASSERT */
1449     switch (in_sig_bt[i]) {
1450       case T_ARRAY:
1451       case T_OBJECT:
1452         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
1453                     ((i == 0) && (!is_static)),
1454                     &receiver_offset);
1455         break;
1456       case T_VOID:
1457         break;
1458 
1459       case T_FLOAT:
1460         float_move(masm, in_regs[i], out_regs[c_arg]);
1461           break;
1462 
1463       case T_DOUBLE:
1464         assert( i + 1 < total_in_args &&
1465                 in_sig_bt[i + 1] == T_VOID &&
1466                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
1467         double_move(masm, in_regs[i], out_regs[c_arg]);
1468         break;
1469 
1470       case T_LONG :
1471         long_move(masm, in_regs[i], out_regs[c_arg]);
1472         break;
1473 
1474       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
1475 
1476       default:
1477         move32_64(masm, in_regs[i], out_regs[c_arg]);
1478     }
1479   }
1480 
1481   // point c_arg at the first arg that is already loaded in case we
1482   // need to spill before we call out
1483   c_arg++;
1484 
1485   // Pre-load a static method's oop into r14.  Used both by locking code and
1486   // the normal JNI call code.
1487   if (method->is_static()) {
1488 
1489     //  load oop into a register
1490     __ movoop(oop_handle_reg, JNIHandles::make_local(Klass::cast(method->method_holder())->java_mirror()));
1491 
1492     // Now handlize the static class mirror it's known not-null.
1493     __ movptr(Address(rsp, klass_offset), oop_handle_reg);
1494     map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
1495 
1496     // Now get the handle
1497     __ lea(oop_handle_reg, Address(rsp, klass_offset));
1498     // store the klass handle as second argument
1499     __ movptr(c_rarg1, oop_handle_reg);
1500     // and protect the arg if we must spill
1501     c_arg--;
1502   }
1503 
1504   // Change state to native (we save the return address in the thread, since it might not
1505   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
1506   // points into the right code segment. It does not have to be the correct return pc.
1507   // We use the same pc/oopMap repeatedly when we call out
1508 
1509   intptr_t the_pc = (intptr_t) __ pc();
1510   oop_maps->add_gc_map(the_pc - start, map);
1511 
1512   __ set_last_Java_frame(rsp, noreg, (address)the_pc);
1513 
1514 
1515   // We have all of the arguments setup at this point. We must not touch any register
1516   // argument registers at this point (what if we save/restore them there are no oop?
1517 
1518   {
1519     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
1520     // protect the args we've loaded
1521     save_args(masm, total_c_args, c_arg, out_regs);
1522     __ movoop(c_rarg1, JNIHandles::make_local(method()));
1523     __ call_VM_leaf(
1524       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
1525       r15_thread, c_rarg1);
1526     restore_args(masm, total_c_args, c_arg, out_regs);
1527   }
1528 
1529   // RedefineClasses() tracing support for obsolete method entry
1530   if (RC_TRACE_IN_RANGE(0x00001000, 0x00002000)) {
1531     // protect the args we've loaded
1532     save_args(masm, total_c_args, c_arg, out_regs);
1533     __ movoop(c_rarg1, JNIHandles::make_local(method()));
1534     __ call_VM_leaf(
1535       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
1536       r15_thread, c_rarg1);
1537     restore_args(masm, total_c_args, c_arg, out_regs);
1538   }
1539 
1540   // Lock a synchronized method
1541 
1542   // Register definitions used by locking and unlocking
1543 
1544   const Register swap_reg = rax;  // Must use rax for cmpxchg instruction
1545   const Register obj_reg  = rbx;  // Will contain the oop
1546   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
1547   const Register old_hdr  = r13;  // value of old header at unlock time
1548 
1549   Label slow_path_lock;
1550   Label lock_done;
1551 
1552   if (method->is_synchronized()) {
1553 
1554 
1555     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
1556 
1557     // Get the handle (the 2nd argument)
1558     __ mov(oop_handle_reg, c_rarg1);
1559 
1560     // Get address of the box
1561 
1562     __ lea(lock_reg, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1563 
1564     // Load the oop from the handle
1565     __ movptr(obj_reg, Address(oop_handle_reg, 0));
1566 
1567     if (UseBiasedLocking) {
1568       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, rscratch1, false, lock_done, &slow_path_lock);
1569     }
1570 
1571     // Load immediate 1 into swap_reg %rax
1572     __ movl(swap_reg, 1);
1573 
1574     // Load (object->mark() | 1) into swap_reg %rax
1575     __ orptr(swap_reg, Address(obj_reg, 0));
1576 
1577     // Save (object->mark() | 1) into BasicLock's displaced header
1578     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
1579 
1580     if (os::is_MP()) {
1581       __ lock();
1582     }
1583 
1584     // src -> dest iff dest == rax else rax <- dest
1585     __ cmpxchgptr(lock_reg, Address(obj_reg, 0));
1586     __ jcc(Assembler::equal, lock_done);
1587 
1588     // Hmm should this move to the slow path code area???
1589 
1590     // Test if the oopMark is an obvious stack pointer, i.e.,
1591     //  1) (mark & 3) == 0, and
1592     //  2) rsp <= mark < mark + os::pagesize()
1593     // These 3 tests can be done by evaluating the following
1594     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
1595     // assuming both stack pointer and pagesize have their
1596     // least significant 2 bits clear.
1597     // NOTE: the oopMark is in swap_reg %rax as the result of cmpxchg
1598 
1599     __ subptr(swap_reg, rsp);
1600     __ andptr(swap_reg, 3 - os::vm_page_size());
1601 
1602     // Save the test result, for recursive case, the result is zero
1603     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
1604     __ jcc(Assembler::notEqual, slow_path_lock);
1605 
1606     // Slow path will re-enter here
1607 
1608     __ bind(lock_done);
1609   }
1610 
1611 
1612   // Finally just about ready to make the JNI call
1613 
1614 
1615   // get JNIEnv* which is first argument to native
1616 
1617   __ lea(c_rarg0, Address(r15_thread, in_bytes(JavaThread::jni_environment_offset())));
1618 
1619   // Now set thread in native
1620   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native);
1621 
1622   __ call(RuntimeAddress(method->native_function()));
1623 
1624     // Either restore the MXCSR register after returning from the JNI Call
1625     // or verify that it wasn't changed.
1626     if (RestoreMXCSROnJNICalls) {
1627       __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std()));
1628 
1629     }
1630     else if (CheckJNICalls ) {
1631       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::verify_mxcsr_entry())));
1632     }
1633 
1634 
1635   // Unpack native results.
1636   switch (ret_type) {
1637   case T_BOOLEAN: __ c2bool(rax);            break;
1638   case T_CHAR   : __ movzwl(rax, rax);      break;
1639   case T_BYTE   : __ sign_extend_byte (rax); break;
1640   case T_SHORT  : __ sign_extend_short(rax); break;
1641   case T_INT    : /* nothing to do */        break;
1642   case T_DOUBLE :
1643   case T_FLOAT  :
1644     // Result is in xmm0 we'll save as needed
1645     break;
1646   case T_ARRAY:                 // Really a handle
1647   case T_OBJECT:                // Really a handle
1648       break; // can't de-handlize until after safepoint check
1649   case T_VOID: break;
1650   case T_LONG: break;
1651   default       : ShouldNotReachHere();
1652   }
1653 
1654   // Switch thread to "native transition" state before reading the synchronization state.
1655   // This additional state is necessary because reading and testing the synchronization
1656   // state is not atomic w.r.t. GC, as this scenario demonstrates:
1657   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
1658   //     VM thread changes sync state to synchronizing and suspends threads for GC.
1659   //     Thread A is resumed to finish this native method, but doesn't block here since it
1660   //     didn't see any synchronization is progress, and escapes.
1661   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
1662 
1663   if(os::is_MP()) {
1664     if (UseMembar) {
1665       // Force this write out before the read below
1666       __ membar(Assembler::Membar_mask_bits(
1667            Assembler::LoadLoad | Assembler::LoadStore |
1668            Assembler::StoreLoad | Assembler::StoreStore));
1669     } else {
1670       // Write serialization page so VM thread can do a pseudo remote membar.
1671       // We use the current thread pointer to calculate a thread specific
1672       // offset to write to within the page. This minimizes bus traffic
1673       // due to cache line collision.
1674       __ serialize_memory(r15_thread, rcx);
1675     }
1676   }
1677 
1678 
1679   // check for safepoint operation in progress and/or pending suspend requests
1680   {
1681     Label Continue;
1682 
1683     __ cmp32(ExternalAddress((address)SafepointSynchronize::address_of_state()),
1684              SafepointSynchronize::_not_synchronized);
1685 
1686     Label L;
1687     __ jcc(Assembler::notEqual, L);
1688     __ cmpl(Address(r15_thread, JavaThread::suspend_flags_offset()), 0);
1689     __ jcc(Assembler::equal, Continue);
1690     __ bind(L);
1691 
1692     // Don't use call_VM as it will see a possible pending exception and forward it
1693     // and never return here preventing us from clearing _last_native_pc down below.
1694     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
1695     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
1696     // by hand.
1697     //
1698     save_native_result(masm, ret_type, stack_slots);
1699     __ mov(c_rarg0, r15_thread);
1700     __ mov(r12, rsp); // remember sp
1701     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1702     __ andptr(rsp, -16); // align stack as required by ABI
1703     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
1704     __ mov(rsp, r12); // restore sp
1705     __ reinit_heapbase();
1706     // Restore any method result value
1707     restore_native_result(masm, ret_type, stack_slots);
1708     __ bind(Continue);
1709   }
1710 
1711   // change thread state
1712   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_Java);
1713 
1714   Label reguard;
1715   Label reguard_done;
1716   __ cmpl(Address(r15_thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_disabled);
1717   __ jcc(Assembler::equal, reguard);
1718   __ bind(reguard_done);
1719 
1720   // native result if any is live
1721 
1722   // Unlock
1723   Label unlock_done;
1724   Label slow_path_unlock;
1725   if (method->is_synchronized()) {
1726 
1727     // Get locked oop from the handle we passed to jni
1728     __ movptr(obj_reg, Address(oop_handle_reg, 0));
1729 
1730     Label done;
1731 
1732     if (UseBiasedLocking) {
1733       __ biased_locking_exit(obj_reg, old_hdr, done);
1734     }
1735 
1736     // Simple recursive lock?
1737 
1738     __ cmpptr(Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size), (int32_t)NULL_WORD);
1739     __ jcc(Assembler::equal, done);
1740 
1741     // Must save rax if if it is live now because cmpxchg must use it
1742     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1743       save_native_result(masm, ret_type, stack_slots);
1744     }
1745 
1746 
1747     // get address of the stack lock
1748     __ lea(rax, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1749     //  get old displaced header
1750     __ movptr(old_hdr, Address(rax, 0));
1751 
1752     // Atomic swap old header if oop still contains the stack lock
1753     if (os::is_MP()) {
1754       __ lock();
1755     }
1756     __ cmpxchgptr(old_hdr, Address(obj_reg, 0));
1757     __ jcc(Assembler::notEqual, slow_path_unlock);
1758 
1759     // slow path re-enters here
1760     __ bind(unlock_done);
1761     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
1762       restore_native_result(masm, ret_type, stack_slots);
1763     }
1764 
1765     __ bind(done);
1766 
1767   }
1768   {
1769     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
1770     save_native_result(masm, ret_type, stack_slots);
1771     __ movoop(c_rarg1, JNIHandles::make_local(method()));
1772     __ call_VM_leaf(
1773          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
1774          r15_thread, c_rarg1);
1775     restore_native_result(masm, ret_type, stack_slots);
1776   }
1777 
1778   __ reset_last_Java_frame(false, true);
1779 
1780   // Unpack oop result
1781   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
1782       Label L;
1783       __ testptr(rax, rax);
1784       __ jcc(Assembler::zero, L);
1785       __ movptr(rax, Address(rax, 0));
1786       __ bind(L);
1787       __ verify_oop(rax);
1788   }
1789 
1790   // reset handle block
1791   __ movptr(rcx, Address(r15_thread, JavaThread::active_handles_offset()));
1792   __ movptr(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), (int32_t)NULL_WORD);
1793 
1794   // pop our frame
1795 
1796   __ leave();
1797 
1798   // Any exception pending?
1799   __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
1800   __ jcc(Assembler::notEqual, exception_pending);
1801 
1802   // Return
1803 
1804   __ ret(0);
1805 
1806   // Unexpected paths are out of line and go here
1807 
1808   // forward the exception
1809   __ bind(exception_pending);
1810 
1811   // and forward the exception
1812   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
1813 
1814 
1815   // Slow path locking & unlocking
1816   if (method->is_synchronized()) {
1817 
1818     // BEGIN Slow path lock
1819     __ bind(slow_path_lock);
1820 
1821     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
1822     // args are (oop obj, BasicLock* lock, JavaThread* thread)
1823 
1824     // protect the args we've loaded
1825     save_args(masm, total_c_args, c_arg, out_regs);
1826 
1827     __ mov(c_rarg0, obj_reg);
1828     __ mov(c_rarg1, lock_reg);
1829     __ mov(c_rarg2, r15_thread);
1830 
1831     // Not a leaf but we have last_Java_frame setup as we want
1832     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
1833     restore_args(masm, total_c_args, c_arg, out_regs);
1834 
1835 #ifdef ASSERT
1836     { Label L;
1837     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
1838     __ jcc(Assembler::equal, L);
1839     __ stop("no pending exception allowed on exit from monitorenter");
1840     __ bind(L);
1841     }
1842 #endif
1843     __ jmp(lock_done);
1844 
1845     // END Slow path lock
1846 
1847     // BEGIN Slow path unlock
1848     __ bind(slow_path_unlock);
1849 
1850     // If we haven't already saved the native result we must save it now as xmm registers
1851     // are still exposed.
1852 
1853     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1854       save_native_result(masm, ret_type, stack_slots);
1855     }
1856 
1857     __ lea(c_rarg1, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
1858 
1859     __ mov(c_rarg0, obj_reg);
1860     __ mov(r12, rsp); // remember sp
1861     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1862     __ andptr(rsp, -16); // align stack as required by ABI
1863 
1864     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
1865     // NOTE that obj_reg == rbx currently
1866     __ movptr(rbx, Address(r15_thread, in_bytes(Thread::pending_exception_offset())));
1867     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
1868 
1869     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
1870     __ mov(rsp, r12); // restore sp
1871     __ reinit_heapbase();
1872 #ifdef ASSERT
1873     {
1874       Label L;
1875       __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
1876       __ jcc(Assembler::equal, L);
1877       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
1878       __ bind(L);
1879     }
1880 #endif /* ASSERT */
1881 
1882     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), rbx);
1883 
1884     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
1885       restore_native_result(masm, ret_type, stack_slots);
1886     }
1887     __ jmp(unlock_done);
1888 
1889     // END Slow path unlock
1890 
1891   } // synchronized
1892 
1893   // SLOW PATH Reguard the stack if needed
1894 
1895   __ bind(reguard);
1896   save_native_result(masm, ret_type, stack_slots);
1897   __ mov(r12, rsp); // remember sp
1898   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1899   __ andptr(rsp, -16); // align stack as required by ABI
1900   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
1901   __ mov(rsp, r12); // restore sp
1902   __ reinit_heapbase();
1903   restore_native_result(masm, ret_type, stack_slots);
1904   // and continue
1905   __ jmp(reguard_done);
1906 
1907 
1908 
1909   __ flush();
1910 
1911   nmethod *nm = nmethod::new_native_nmethod(method,
1912                                             masm->code(),
1913                                             vep_offset,
1914                                             frame_complete,
1915                                             stack_slots / VMRegImpl::slots_per_word,
1916                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
1917                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
1918                                             oop_maps);
1919   return nm;
1920 
1921 }
1922 
1923 #ifdef HAVE_DTRACE_H
1924 // ---------------------------------------------------------------------------
1925 // Generate a dtrace nmethod for a given signature.  The method takes arguments
1926 // in the Java compiled code convention, marshals them to the native
1927 // abi and then leaves nops at the position you would expect to call a native
1928 // function. When the probe is enabled the nops are replaced with a trap
1929 // instruction that dtrace inserts and the trace will cause a notification
1930 // to dtrace.
1931 //
1932 // The probes are only able to take primitive types and java/lang/String as
1933 // arguments.  No other java types are allowed. Strings are converted to utf8
1934 // strings so that from dtrace point of view java strings are converted to C
1935 // strings. There is an arbitrary fixed limit on the total space that a method
1936 // can use for converting the strings. (256 chars per string in the signature).
1937 // So any java string larger then this is truncated.
1938 
1939 static int  fp_offset[ConcreteRegisterImpl::number_of_registers] = { 0 };
1940 static bool offsets_initialized = false;
1941 
1942 
1943 nmethod *SharedRuntime::generate_dtrace_nmethod(MacroAssembler *masm,
1944                                                 methodHandle method) {
1945 
1946 
1947   // generate_dtrace_nmethod is guarded by a mutex so we are sure to
1948   // be single threaded in this method.
1949   assert(AdapterHandlerLibrary_lock->owned_by_self(), "must be");
1950 
1951   if (!offsets_initialized) {
1952     fp_offset[c_rarg0->as_VMReg()->value()] = -1 * wordSize;
1953     fp_offset[c_rarg1->as_VMReg()->value()] = -2 * wordSize;
1954     fp_offset[c_rarg2->as_VMReg()->value()] = -3 * wordSize;
1955     fp_offset[c_rarg3->as_VMReg()->value()] = -4 * wordSize;
1956     fp_offset[c_rarg4->as_VMReg()->value()] = -5 * wordSize;
1957     fp_offset[c_rarg5->as_VMReg()->value()] = -6 * wordSize;
1958 
1959     fp_offset[c_farg0->as_VMReg()->value()] = -7 * wordSize;
1960     fp_offset[c_farg1->as_VMReg()->value()] = -8 * wordSize;
1961     fp_offset[c_farg2->as_VMReg()->value()] = -9 * wordSize;
1962     fp_offset[c_farg3->as_VMReg()->value()] = -10 * wordSize;
1963     fp_offset[c_farg4->as_VMReg()->value()] = -11 * wordSize;
1964     fp_offset[c_farg5->as_VMReg()->value()] = -12 * wordSize;
1965     fp_offset[c_farg6->as_VMReg()->value()] = -13 * wordSize;
1966     fp_offset[c_farg7->as_VMReg()->value()] = -14 * wordSize;
1967 
1968     offsets_initialized = true;
1969   }
1970   // Fill in the signature array, for the calling-convention call.
1971   int total_args_passed = method->size_of_parameters();
1972 
1973   BasicType* in_sig_bt  = NEW_RESOURCE_ARRAY(BasicType, total_args_passed);
1974   VMRegPair  *in_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed);
1975 
1976   // The signature we are going to use for the trap that dtrace will see
1977   // java/lang/String is converted. We drop "this" and any other object
1978   // is converted to NULL.  (A one-slot java/lang/Long object reference
1979   // is converted to a two-slot long, which is why we double the allocation).
1980   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_args_passed * 2);
1981   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_args_passed * 2);
1982 
1983   int i=0;
1984   int total_strings = 0;
1985   int first_arg_to_pass = 0;
1986   int total_c_args = 0;
1987 
1988   // Skip the receiver as dtrace doesn't want to see it
1989   if( !method->is_static() ) {
1990     in_sig_bt[i++] = T_OBJECT;
1991     first_arg_to_pass = 1;
1992   }
1993 
1994   // We need to convert the java args to where a native (non-jni) function
1995   // would expect them. To figure out where they go we convert the java
1996   // signature to a C signature.
1997 
1998   SignatureStream ss(method->signature());
1999   for ( ; !ss.at_return_type(); ss.next()) {
2000     BasicType bt = ss.type();
2001     in_sig_bt[i++] = bt;  // Collect remaining bits of signature
2002     out_sig_bt[total_c_args++] = bt;
2003     if( bt == T_OBJECT) {
2004       symbolOop s = ss.as_symbol_or_null();
2005       if (s == vmSymbols::java_lang_String()) {
2006         total_strings++;
2007         out_sig_bt[total_c_args-1] = T_ADDRESS;
2008       } else if (s == vmSymbols::java_lang_Boolean() ||
2009                  s == vmSymbols::java_lang_Character() ||
2010                  s == vmSymbols::java_lang_Byte() ||
2011                  s == vmSymbols::java_lang_Short() ||
2012                  s == vmSymbols::java_lang_Integer() ||
2013                  s == vmSymbols::java_lang_Float()) {
2014         out_sig_bt[total_c_args-1] = T_INT;
2015       } else if (s == vmSymbols::java_lang_Long() ||
2016                  s == vmSymbols::java_lang_Double()) {
2017         out_sig_bt[total_c_args-1] = T_LONG;
2018         out_sig_bt[total_c_args++] = T_VOID;
2019       }
2020     } else if ( bt == T_LONG || bt == T_DOUBLE ) {
2021       in_sig_bt[i++] = T_VOID;   // Longs & doubles take 2 Java slots
2022       // We convert double to long
2023       out_sig_bt[total_c_args-1] = T_LONG;
2024       out_sig_bt[total_c_args++] = T_VOID;
2025     } else if ( bt == T_FLOAT) {
2026       // We convert float to int
2027       out_sig_bt[total_c_args-1] = T_INT;
2028     }
2029   }
2030 
2031   assert(i==total_args_passed, "validly parsed signature");
2032 
2033   // Now get the compiled-Java layout as input arguments
2034   int comp_args_on_stack;
2035   comp_args_on_stack = SharedRuntime::java_calling_convention(
2036       in_sig_bt, in_regs, total_args_passed, false);
2037 
2038   // Now figure out where the args must be stored and how much stack space
2039   // they require (neglecting out_preserve_stack_slots but space for storing
2040   // the 1st six register arguments). It's weird see int_stk_helper.
2041 
2042   int out_arg_slots;
2043   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, total_c_args);
2044 
2045   // Calculate the total number of stack slots we will need.
2046 
2047   // First count the abi requirement plus all of the outgoing args
2048   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
2049 
2050   // Now space for the string(s) we must convert
2051   int* string_locs   = NEW_RESOURCE_ARRAY(int, total_strings + 1);
2052   for (i = 0; i < total_strings ; i++) {
2053     string_locs[i] = stack_slots;
2054     stack_slots += max_dtrace_string_size / VMRegImpl::stack_slot_size;
2055   }
2056 
2057   // Plus the temps we might need to juggle register args
2058   // regs take two slots each
2059   stack_slots += (Argument::n_int_register_parameters_c +
2060                   Argument::n_float_register_parameters_c) * 2;
2061 
2062 
2063   // + 4 for return address (which we own) and saved rbp,
2064 
2065   stack_slots += 4;
2066 
2067   // Ok The space we have allocated will look like:
2068   //
2069   //
2070   // FP-> |                     |
2071   //      |---------------------|
2072   //      | string[n]           |
2073   //      |---------------------| <- string_locs[n]
2074   //      | string[n-1]         |
2075   //      |---------------------| <- string_locs[n-1]
2076   //      | ...                 |
2077   //      | ...                 |
2078   //      |---------------------| <- string_locs[1]
2079   //      | string[0]           |
2080   //      |---------------------| <- string_locs[0]
2081   //      | outbound memory     |
2082   //      | based arguments     |
2083   //      |                     |
2084   //      |---------------------|
2085   //      |                     |
2086   // SP-> | out_preserved_slots |
2087   //
2088   //
2089 
2090   // Now compute actual number of stack words we need rounding to make
2091   // stack properly aligned.
2092   stack_slots = round_to(stack_slots, 4 * VMRegImpl::slots_per_word);
2093 
2094   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
2095 
2096   intptr_t start = (intptr_t)__ pc();
2097 
2098   // First thing make an ic check to see if we should even be here
2099 
2100   // We are free to use all registers as temps without saving them and
2101   // restoring them except rbp. rbp, is the only callee save register
2102   // as far as the interpreter and the compiler(s) are concerned.
2103 
2104   const Register ic_reg = rax;
2105   const Register receiver = rcx;
2106   Label hit;
2107   Label exception_pending;
2108 
2109 
2110   __ verify_oop(receiver);
2111   __ cmpl(ic_reg, Address(receiver, oopDesc::klass_offset_in_bytes()));
2112   __ jcc(Assembler::equal, hit);
2113 
2114   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
2115 
2116   // verified entry must be aligned for code patching.
2117   // and the first 5 bytes must be in the same cache line
2118   // if we align at 8 then we will be sure 5 bytes are in the same line
2119   __ align(8);
2120 
2121   __ bind(hit);
2122 
2123   int vep_offset = ((intptr_t)__ pc()) - start;
2124 
2125 
2126   // The instruction at the verified entry point must be 5 bytes or longer
2127   // because it can be patched on the fly by make_non_entrant. The stack bang
2128   // instruction fits that requirement.
2129 
2130   // Generate stack overflow check
2131 
2132   if (UseStackBanging) {
2133     if (stack_size <= StackShadowPages*os::vm_page_size()) {
2134       __ bang_stack_with_offset(StackShadowPages*os::vm_page_size());
2135     } else {
2136       __ movl(rax, stack_size);
2137       __ bang_stack_size(rax, rbx);
2138     }
2139   } else {
2140     // need a 5 byte instruction to allow MT safe patching to non-entrant
2141     __ fat_nop();
2142   }
2143 
2144   assert(((uintptr_t)__ pc() - start - vep_offset) >= 5,
2145          "valid size for make_non_entrant");
2146 
2147   // Generate a new frame for the wrapper.
2148   __ enter();
2149 
2150   // -4 because return address is already present and so is saved rbp,
2151   if (stack_size - 2*wordSize != 0) {
2152     __ subq(rsp, stack_size - 2*wordSize);
2153   }
2154 
2155   // Frame is now completed as far a size and linkage.
2156 
2157   int frame_complete = ((intptr_t)__ pc()) - start;
2158 
2159   int c_arg, j_arg;
2160 
2161   // State of input register args
2162 
2163   bool  live[ConcreteRegisterImpl::number_of_registers];
2164 
2165   live[j_rarg0->as_VMReg()->value()] = false;
2166   live[j_rarg1->as_VMReg()->value()] = false;
2167   live[j_rarg2->as_VMReg()->value()] = false;
2168   live[j_rarg3->as_VMReg()->value()] = false;
2169   live[j_rarg4->as_VMReg()->value()] = false;
2170   live[j_rarg5->as_VMReg()->value()] = false;
2171 
2172   live[j_farg0->as_VMReg()->value()] = false;
2173   live[j_farg1->as_VMReg()->value()] = false;
2174   live[j_farg2->as_VMReg()->value()] = false;
2175   live[j_farg3->as_VMReg()->value()] = false;
2176   live[j_farg4->as_VMReg()->value()] = false;
2177   live[j_farg5->as_VMReg()->value()] = false;
2178   live[j_farg6->as_VMReg()->value()] = false;
2179   live[j_farg7->as_VMReg()->value()] = false;
2180 
2181 
2182   bool rax_is_zero = false;
2183 
2184   // All args (except strings) destined for the stack are moved first
2185   for (j_arg = first_arg_to_pass, c_arg = 0 ;
2186        j_arg < total_args_passed ; j_arg++, c_arg++ ) {
2187     VMRegPair src = in_regs[j_arg];
2188     VMRegPair dst = out_regs[c_arg];
2189 
2190     // Get the real reg value or a dummy (rsp)
2191 
2192     int src_reg = src.first()->is_reg() ?
2193                   src.first()->value() :
2194                   rsp->as_VMReg()->value();
2195 
2196     bool useless =  in_sig_bt[j_arg] == T_ARRAY ||
2197                     (in_sig_bt[j_arg] == T_OBJECT &&
2198                      out_sig_bt[c_arg] != T_INT &&
2199                      out_sig_bt[c_arg] != T_ADDRESS &&
2200                      out_sig_bt[c_arg] != T_LONG);
2201 
2202     live[src_reg] = !useless;
2203 
2204     if (dst.first()->is_stack()) {
2205 
2206       // Even though a string arg in a register is still live after this loop
2207       // after the string conversion loop (next) it will be dead so we take
2208       // advantage of that now for simpler code to manage live.
2209 
2210       live[src_reg] = false;
2211       switch (in_sig_bt[j_arg]) {
2212 
2213         case T_ARRAY:
2214         case T_OBJECT:
2215           {
2216             Address stack_dst(rsp, reg2offset_out(dst.first()));
2217 
2218             if (out_sig_bt[c_arg] == T_INT || out_sig_bt[c_arg] == T_LONG) {
2219               // need to unbox a one-word value
2220               Register in_reg = rax;
2221               if ( src.first()->is_reg() ) {
2222                 in_reg = src.first()->as_Register();
2223               } else {
2224                 __ movq(rax, Address(rbp, reg2offset_in(src.first())));
2225                 rax_is_zero = false;
2226               }
2227               Label skipUnbox;
2228               __ movptr(Address(rsp, reg2offset_out(dst.first())),
2229                         (int32_t)NULL_WORD);
2230               __ testq(in_reg, in_reg);
2231               __ jcc(Assembler::zero, skipUnbox);
2232 
2233               BasicType bt = out_sig_bt[c_arg];
2234               int box_offset = java_lang_boxing_object::value_offset_in_bytes(bt);
2235               Address src1(in_reg, box_offset);
2236               if ( bt == T_LONG ) {
2237                 __ movq(in_reg,  src1);
2238                 __ movq(stack_dst, in_reg);
2239                 assert(out_sig_bt[c_arg+1] == T_VOID, "must be");
2240                 ++c_arg; // skip over T_VOID to keep the loop indices in sync
2241               } else {
2242                 __ movl(in_reg,  src1);
2243                 __ movl(stack_dst, in_reg);
2244               }
2245 
2246               __ bind(skipUnbox);
2247             } else if (out_sig_bt[c_arg] != T_ADDRESS) {
2248               // Convert the arg to NULL
2249               if (!rax_is_zero) {
2250                 __ xorq(rax, rax);
2251                 rax_is_zero = true;
2252               }
2253               __ movq(stack_dst, rax);
2254             }
2255           }
2256           break;
2257 
2258         case T_VOID:
2259           break;
2260 
2261         case T_FLOAT:
2262           // This does the right thing since we know it is destined for the
2263           // stack
2264           float_move(masm, src, dst);
2265           break;
2266 
2267         case T_DOUBLE:
2268           // This does the right thing since we know it is destined for the
2269           // stack
2270           double_move(masm, src, dst);
2271           break;
2272 
2273         case T_LONG :
2274           long_move(masm, src, dst);
2275           break;
2276 
2277         case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
2278 
2279         default:
2280           move32_64(masm, src, dst);
2281       }
2282     }
2283 
2284   }
2285 
2286   // If we have any strings we must store any register based arg to the stack
2287   // This includes any still live xmm registers too.
2288 
2289   int sid = 0;
2290 
2291   if (total_strings > 0 ) {
2292     for (j_arg = first_arg_to_pass, c_arg = 0 ;
2293          j_arg < total_args_passed ; j_arg++, c_arg++ ) {
2294       VMRegPair src = in_regs[j_arg];
2295       VMRegPair dst = out_regs[c_arg];
2296 
2297       if (src.first()->is_reg()) {
2298         Address src_tmp(rbp, fp_offset[src.first()->value()]);
2299 
2300         // string oops were left untouched by the previous loop even if the
2301         // eventual (converted) arg is destined for the stack so park them
2302         // away now (except for first)
2303 
2304         if (out_sig_bt[c_arg] == T_ADDRESS) {
2305           Address utf8_addr = Address(
2306               rsp, string_locs[sid++] * VMRegImpl::stack_slot_size);
2307           if (sid != 1) {
2308             // The first string arg won't be killed until after the utf8
2309             // conversion
2310             __ movq(utf8_addr, src.first()->as_Register());
2311           }
2312         } else if (dst.first()->is_reg()) {
2313           if (in_sig_bt[j_arg] == T_FLOAT || in_sig_bt[j_arg] == T_DOUBLE) {
2314 
2315             // Convert the xmm register to an int and store it in the reserved
2316             // location for the eventual c register arg
2317             XMMRegister f = src.first()->as_XMMRegister();
2318             if (in_sig_bt[j_arg] == T_FLOAT) {
2319               __ movflt(src_tmp, f);
2320             } else {
2321               __ movdbl(src_tmp, f);
2322             }
2323           } else {
2324             // If the arg is an oop type we don't support don't bother to store
2325             // it remember string was handled above.
2326             bool useless =  in_sig_bt[j_arg] == T_ARRAY ||
2327                             (in_sig_bt[j_arg] == T_OBJECT &&
2328                              out_sig_bt[c_arg] != T_INT &&
2329                              out_sig_bt[c_arg] != T_LONG);
2330 
2331             if (!useless) {
2332               __ movq(src_tmp, src.first()->as_Register());
2333             }
2334           }
2335         }
2336       }
2337       if (in_sig_bt[j_arg] == T_OBJECT && out_sig_bt[c_arg] == T_LONG) {
2338         assert(out_sig_bt[c_arg+1] == T_VOID, "must be");
2339         ++c_arg; // skip over T_VOID to keep the loop indices in sync
2340       }
2341     }
2342 
2343     // Now that the volatile registers are safe, convert all the strings
2344     sid = 0;
2345 
2346     for (j_arg = first_arg_to_pass, c_arg = 0 ;
2347          j_arg < total_args_passed ; j_arg++, c_arg++ ) {
2348       if (out_sig_bt[c_arg] == T_ADDRESS) {
2349         // It's a string
2350         Address utf8_addr = Address(
2351             rsp, string_locs[sid++] * VMRegImpl::stack_slot_size);
2352         // The first string we find might still be in the original java arg
2353         // register
2354 
2355         VMReg src = in_regs[j_arg].first();
2356 
2357         // We will need to eventually save the final argument to the trap
2358         // in the von-volatile location dedicated to src. This is the offset
2359         // from fp we will use.
2360         int src_off = src->is_reg() ?
2361             fp_offset[src->value()] : reg2offset_in(src);
2362 
2363         // This is where the argument will eventually reside
2364         VMRegPair dst = out_regs[c_arg];
2365 
2366         if (src->is_reg()) {
2367           if (sid == 1) {
2368             __ movq(c_rarg0, src->as_Register());
2369           } else {
2370             __ movq(c_rarg0, utf8_addr);
2371           }
2372         } else {
2373           // arg is still in the original location
2374           __ movq(c_rarg0, Address(rbp, reg2offset_in(src)));
2375         }
2376         Label done, convert;
2377 
2378         // see if the oop is NULL
2379         __ testq(c_rarg0, c_rarg0);
2380         __ jcc(Assembler::notEqual, convert);
2381 
2382         if (dst.first()->is_reg()) {
2383           // Save the ptr to utf string in the origina src loc or the tmp
2384           // dedicated to it
2385           __ movq(Address(rbp, src_off), c_rarg0);
2386         } else {
2387           __ movq(Address(rsp, reg2offset_out(dst.first())), c_rarg0);
2388         }
2389         __ jmp(done);
2390 
2391         __ bind(convert);
2392 
2393         __ lea(c_rarg1, utf8_addr);
2394         if (dst.first()->is_reg()) {
2395           __ movq(Address(rbp, src_off), c_rarg1);
2396         } else {
2397           __ movq(Address(rsp, reg2offset_out(dst.first())), c_rarg1);
2398         }
2399         // And do the conversion
2400         __ call(RuntimeAddress(
2401                 CAST_FROM_FN_PTR(address, SharedRuntime::get_utf)));
2402 
2403         __ bind(done);
2404       }
2405       if (in_sig_bt[j_arg] == T_OBJECT && out_sig_bt[c_arg] == T_LONG) {
2406         assert(out_sig_bt[c_arg+1] == T_VOID, "must be");
2407         ++c_arg; // skip over T_VOID to keep the loop indices in sync
2408       }
2409     }
2410     // The get_utf call killed all the c_arg registers
2411     live[c_rarg0->as_VMReg()->value()] = false;
2412     live[c_rarg1->as_VMReg()->value()] = false;
2413     live[c_rarg2->as_VMReg()->value()] = false;
2414     live[c_rarg3->as_VMReg()->value()] = false;
2415     live[c_rarg4->as_VMReg()->value()] = false;
2416     live[c_rarg5->as_VMReg()->value()] = false;
2417 
2418     live[c_farg0->as_VMReg()->value()] = false;
2419     live[c_farg1->as_VMReg()->value()] = false;
2420     live[c_farg2->as_VMReg()->value()] = false;
2421     live[c_farg3->as_VMReg()->value()] = false;
2422     live[c_farg4->as_VMReg()->value()] = false;
2423     live[c_farg5->as_VMReg()->value()] = false;
2424     live[c_farg6->as_VMReg()->value()] = false;
2425     live[c_farg7->as_VMReg()->value()] = false;
2426   }
2427 
2428   // Now we can finally move the register args to their desired locations
2429 
2430   rax_is_zero = false;
2431 
2432   for (j_arg = first_arg_to_pass, c_arg = 0 ;
2433        j_arg < total_args_passed ; j_arg++, c_arg++ ) {
2434 
2435     VMRegPair src = in_regs[j_arg];
2436     VMRegPair dst = out_regs[c_arg];
2437 
2438     // Only need to look for args destined for the interger registers (since we
2439     // convert float/double args to look like int/long outbound)
2440     if (dst.first()->is_reg()) {
2441       Register r =  dst.first()->as_Register();
2442 
2443       // Check if the java arg is unsupported and thereofre useless
2444       bool useless =  in_sig_bt[j_arg] == T_ARRAY ||
2445                       (in_sig_bt[j_arg] == T_OBJECT &&
2446                        out_sig_bt[c_arg] != T_INT &&
2447                        out_sig_bt[c_arg] != T_ADDRESS &&
2448                        out_sig_bt[c_arg] != T_LONG);
2449 
2450 
2451       // If we're going to kill an existing arg save it first
2452       if (live[dst.first()->value()]) {
2453         // you can't kill yourself
2454         if (src.first() != dst.first()) {
2455           __ movq(Address(rbp, fp_offset[dst.first()->value()]), r);
2456         }
2457       }
2458       if (src.first()->is_reg()) {
2459         if (live[src.first()->value()] ) {
2460           if (in_sig_bt[j_arg] == T_FLOAT) {
2461             __ movdl(r, src.first()->as_XMMRegister());
2462           } else if (in_sig_bt[j_arg] == T_DOUBLE) {
2463             __ movdq(r, src.first()->as_XMMRegister());
2464           } else if (r != src.first()->as_Register()) {
2465             if (!useless) {
2466               __ movq(r, src.first()->as_Register());
2467             }
2468           }
2469         } else {
2470           // If the arg is an oop type we don't support don't bother to store
2471           // it
2472           if (!useless) {
2473             if (in_sig_bt[j_arg] == T_DOUBLE ||
2474                 in_sig_bt[j_arg] == T_LONG  ||
2475                 in_sig_bt[j_arg] == T_OBJECT ) {
2476               __ movq(r, Address(rbp, fp_offset[src.first()->value()]));
2477             } else {
2478               __ movl(r, Address(rbp, fp_offset[src.first()->value()]));
2479             }
2480           }
2481         }
2482         live[src.first()->value()] = false;
2483       } else if (!useless) {
2484         // full sized move even for int should be ok
2485         __ movq(r, Address(rbp, reg2offset_in(src.first())));
2486       }
2487 
2488       // At this point r has the original java arg in the final location
2489       // (assuming it wasn't useless). If the java arg was an oop
2490       // we have a bit more to do
2491 
2492       if (in_sig_bt[j_arg] == T_ARRAY || in_sig_bt[j_arg] == T_OBJECT ) {
2493         if (out_sig_bt[c_arg] == T_INT || out_sig_bt[c_arg] == T_LONG) {
2494           // need to unbox a one-word value
2495           Label skip;
2496           __ testq(r, r);
2497           __ jcc(Assembler::equal, skip);
2498           BasicType bt = out_sig_bt[c_arg];
2499           int box_offset = java_lang_boxing_object::value_offset_in_bytes(bt);
2500           Address src1(r, box_offset);
2501           if ( bt == T_LONG ) {
2502             __ movq(r, src1);
2503           } else {
2504             __ movl(r, src1);
2505           }
2506           __ bind(skip);
2507 
2508         } else if (out_sig_bt[c_arg] != T_ADDRESS) {
2509           // Convert the arg to NULL
2510           __ xorq(r, r);
2511         }
2512       }
2513 
2514       // dst can longer be holding an input value
2515       live[dst.first()->value()] = false;
2516     }
2517     if (in_sig_bt[j_arg] == T_OBJECT && out_sig_bt[c_arg] == T_LONG) {
2518       assert(out_sig_bt[c_arg+1] == T_VOID, "must be");
2519       ++c_arg; // skip over T_VOID to keep the loop indices in sync
2520     }
2521   }
2522 
2523 
2524   // Ok now we are done. Need to place the nop that dtrace wants in order to
2525   // patch in the trap
2526   int patch_offset = ((intptr_t)__ pc()) - start;
2527 
2528   __ nop();
2529 
2530 
2531   // Return
2532 
2533   __ leave();
2534   __ ret(0);
2535 
2536   __ flush();
2537 
2538   nmethod *nm = nmethod::new_dtrace_nmethod(
2539       method, masm->code(), vep_offset, patch_offset, frame_complete,
2540       stack_slots / VMRegImpl::slots_per_word);
2541   return nm;
2542 
2543 }
2544 
2545 #endif // HAVE_DTRACE_H
2546 
2547 // this function returns the adjust size (in number of words) to a c2i adapter
2548 // activation for use during deoptimization
2549 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2550   return (callee_locals - callee_parameters) * Interpreter::stackElementWords();
2551 }
2552 
2553 
2554 uint SharedRuntime::out_preserve_stack_slots() {
2555   return 0;
2556 }
2557 
2558 
2559 //------------------------------generate_deopt_blob----------------------------
2560 void SharedRuntime::generate_deopt_blob() {
2561   // Allocate space for the code
2562   ResourceMark rm;
2563   // Setup code generation tools
2564   CodeBuffer buffer("deopt_blob", 2048, 1024);
2565   MacroAssembler* masm = new MacroAssembler(&buffer);
2566   int frame_size_in_words;
2567   OopMap* map = NULL;
2568   OopMapSet *oop_maps = new OopMapSet();
2569 
2570   // -------------
2571   // This code enters when returning to a de-optimized nmethod.  A return
2572   // address has been pushed on the the stack, and return values are in
2573   // registers.
2574   // If we are doing a normal deopt then we were called from the patched
2575   // nmethod from the point we returned to the nmethod. So the return
2576   // address on the stack is wrong by NativeCall::instruction_size
2577   // We will adjust the value so it looks like we have the original return
2578   // address on the stack (like when we eagerly deoptimized).
2579   // In the case of an exception pending when deoptimizing, we enter
2580   // with a return address on the stack that points after the call we patched
2581   // into the exception handler. We have the following register state from,
2582   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2583   //    rax: exception oop
2584   //    rbx: exception handler
2585   //    rdx: throwing pc
2586   // So in this case we simply jam rdx into the useless return address and
2587   // the stack looks just like we want.
2588   //
2589   // At this point we need to de-opt.  We save the argument return
2590   // registers.  We call the first C routine, fetch_unroll_info().  This
2591   // routine captures the return values and returns a structure which
2592   // describes the current frame size and the sizes of all replacement frames.
2593   // The current frame is compiled code and may contain many inlined
2594   // functions, each with their own JVM state.  We pop the current frame, then
2595   // push all the new frames.  Then we call the C routine unpack_frames() to
2596   // populate these frames.  Finally unpack_frames() returns us the new target
2597   // address.  Notice that callee-save registers are BLOWN here; they have
2598   // already been captured in the vframeArray at the time the return PC was
2599   // patched.
2600   address start = __ pc();
2601   Label cont;
2602 
2603   // Prolog for non exception case!
2604 
2605   // Save everything in sight.
2606   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2607 
2608   // Normal deoptimization.  Save exec mode for unpack_frames.
2609   __ movl(r14, Deoptimization::Unpack_deopt); // callee-saved
2610   __ jmp(cont);
2611 
2612   int reexecute_offset = __ pc() - start;
2613 
2614   // Reexecute case
2615   // return address is the pc describes what bci to do re-execute at
2616 
2617   // No need to update map as each call to save_live_registers will produce identical oopmap
2618   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2619 
2620   __ movl(r14, Deoptimization::Unpack_reexecute); // callee-saved
2621   __ jmp(cont);
2622 
2623   int exception_offset = __ pc() - start;
2624 
2625   // Prolog for exception case
2626 
2627   // all registers are dead at this entry point, except for rax, and
2628   // rdx which contain the exception oop and exception pc
2629   // respectively.  Set them in TLS and fall thru to the
2630   // unpack_with_exception_in_tls entry point.
2631 
2632   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
2633   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), rax);
2634 
2635   int exception_in_tls_offset = __ pc() - start;
2636 
2637   // new implementation because exception oop is now passed in JavaThread
2638 
2639   // Prolog for exception case
2640   // All registers must be preserved because they might be used by LinearScan
2641   // Exceptiop oop and throwing PC are passed in JavaThread
2642   // tos: stack at point of call to method that threw the exception (i.e. only
2643   // args are on the stack, no return address)
2644 
2645   // make room on stack for the return address
2646   // It will be patched later with the throwing pc. The correct value is not
2647   // available now because loading it from memory would destroy registers.
2648   __ push(0);
2649 
2650   // Save everything in sight.
2651   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
2652 
2653   // Now it is safe to overwrite any register
2654 
2655   // Deopt during an exception.  Save exec mode for unpack_frames.
2656   __ movl(r14, Deoptimization::Unpack_exception); // callee-saved
2657 
2658   // load throwing pc from JavaThread and patch it as the return address
2659   // of the current frame. Then clear the field in JavaThread
2660 
2661   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2662   __ movptr(Address(rbp, wordSize), rdx);
2663   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
2664 
2665 #ifdef ASSERT
2666   // verify that there is really an exception oop in JavaThread
2667   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2668   __ verify_oop(rax);
2669 
2670   // verify that there is no pending exception
2671   Label no_pending_exception;
2672   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
2673   __ testptr(rax, rax);
2674   __ jcc(Assembler::zero, no_pending_exception);
2675   __ stop("must not have pending exception here");
2676   __ bind(no_pending_exception);
2677 #endif
2678 
2679   __ bind(cont);
2680 
2681   // Call C code.  Need thread and this frame, but NOT official VM entry
2682   // crud.  We cannot block on this call, no GC can happen.
2683   //
2684   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2685 
2686   // fetch_unroll_info needs to call last_java_frame().
2687 
2688   __ set_last_Java_frame(noreg, noreg, NULL);
2689 #ifdef ASSERT
2690   { Label L;
2691     __ cmpptr(Address(r15_thread,
2692                     JavaThread::last_Java_fp_offset()),
2693             (int32_t)0);
2694     __ jcc(Assembler::equal, L);
2695     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2696     __ bind(L);
2697   }
2698 #endif // ASSERT
2699   __ mov(c_rarg0, r15_thread);
2700   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
2701 
2702   // Need to have an oopmap that tells fetch_unroll_info where to
2703   // find any register it might need.
2704   oop_maps->add_gc_map(__ pc() - start, map);
2705 
2706   __ reset_last_Java_frame(false, false);
2707 
2708   // Load UnrollBlock* into rdi
2709   __ mov(rdi, rax);
2710 
2711    Label noException;
2712   __ cmpl(r14, Deoptimization::Unpack_exception);   // Was exception pending?
2713   __ jcc(Assembler::notEqual, noException);
2714   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2715   // QQQ this is useless it was NULL above
2716   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2717   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int32_t)NULL_WORD);
2718   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
2719 
2720   __ verify_oop(rax);
2721 
2722   // Overwrite the result registers with the exception results.
2723   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
2724   // I think this is useless
2725   __ movptr(Address(rsp, RegisterSaver::rdx_offset_in_bytes()), rdx);
2726 
2727   __ bind(noException);
2728 
2729   // Only register save data is on the stack.
2730   // Now restore the result registers.  Everything else is either dead
2731   // or captured in the vframeArray.
2732   RegisterSaver::restore_result_registers(masm);
2733 
2734   // All of the register save area has been popped of the stack. Only the
2735   // return address remains.
2736 
2737   // Pop all the frames we must move/replace.
2738   //
2739   // Frame picture (youngest to oldest)
2740   // 1: self-frame (no frame link)
2741   // 2: deopting frame  (no frame link)
2742   // 3: caller of deopting frame (could be compiled/interpreted).
2743   //
2744   // Note: by leaving the return address of self-frame on the stack
2745   // and using the size of frame 2 to adjust the stack
2746   // when we are done the return to frame 3 will still be on the stack.
2747 
2748   // Pop deoptimized frame
2749   __ movl(rcx, Address(rdi, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
2750   __ addptr(rsp, rcx);
2751 
2752   // rsp should be pointing at the return address to the caller (3)
2753 
2754   // Stack bang to make sure there's enough room for these interpreter frames.
2755   if (UseStackBanging) {
2756     __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2757     __ bang_stack_size(rbx, rcx);
2758   }
2759 
2760   // Load address of array of frame pcs into rcx
2761   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2762 
2763   // Trash the old pc
2764   __ addptr(rsp, wordSize);
2765 
2766   // Load address of array of frame sizes into rsi
2767   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
2768 
2769   // Load counter into rdx
2770   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
2771 
2772   // Pick up the initial fp we should save
2773   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_fp_offset_in_bytes()));
2774 
2775   // Now adjust the caller's stack to make up for the extra locals
2776   // but record the original sp so that we can save it in the skeletal interpreter
2777   // frame and the stack walking of interpreter_sender will get the unextended sp
2778   // value and not the "real" sp value.
2779 
2780   const Register sender_sp = r8;
2781 
2782   __ mov(sender_sp, rsp);
2783   __ movl(rbx, Address(rdi,
2784                        Deoptimization::UnrollBlock::
2785                        caller_adjustment_offset_in_bytes()));
2786   __ subptr(rsp, rbx);
2787 
2788   // Push interpreter frames in a loop
2789   Label loop;
2790   __ bind(loop);
2791   __ movptr(rbx, Address(rsi, 0));      // Load frame size
2792 #ifdef CC_INTERP
2793   __ subptr(rbx, 4*wordSize);           // we'll push pc and ebp by hand and
2794 #ifdef ASSERT
2795   __ push(0xDEADDEAD);                  // Make a recognizable pattern
2796   __ push(0xDEADDEAD);
2797 #else /* ASSERT */
2798   __ subptr(rsp, 2*wordSize);           // skip the "static long no_param"
2799 #endif /* ASSERT */
2800 #else
2801   __ subptr(rbx, 2*wordSize);           // We'll push pc and ebp by hand
2802 #endif // CC_INTERP
2803   __ pushptr(Address(rcx, 0));          // Save return address
2804   __ enter();                           // Save old & set new ebp
2805   __ subptr(rsp, rbx);                  // Prolog
2806 #ifdef CC_INTERP
2807   __ movptr(Address(rbp,
2808                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2809             sender_sp); // Make it walkable
2810 #else /* CC_INTERP */
2811   // This value is corrected by layout_activation_impl
2812   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
2813   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), sender_sp); // Make it walkable
2814 #endif /* CC_INTERP */
2815   __ mov(sender_sp, rsp);               // Pass sender_sp to next frame
2816   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
2817   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
2818   __ decrementl(rdx);                   // Decrement counter
2819   __ jcc(Assembler::notZero, loop);
2820   __ pushptr(Address(rcx, 0));          // Save final return address
2821 
2822   // Re-push self-frame
2823   __ enter();                           // Save old & set new ebp
2824 
2825   // Allocate a full sized register save area.
2826   // Return address and rbp are in place, so we allocate two less words.
2827   __ subptr(rsp, (frame_size_in_words - 2) * wordSize);
2828 
2829   // Restore frame locals after moving the frame
2830   __ movdbl(Address(rsp, RegisterSaver::xmm0_offset_in_bytes()), xmm0);
2831   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
2832 
2833   // Call C code.  Need thread but NOT official VM entry
2834   // crud.  We cannot block on this call, no GC can happen.  Call should
2835   // restore return values to their stack-slots with the new SP.
2836   //
2837   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
2838 
2839   // Use rbp because the frames look interpreted now
2840   __ set_last_Java_frame(noreg, rbp, NULL);
2841 
2842   __ mov(c_rarg0, r15_thread);
2843   __ movl(c_rarg1, r14); // second arg: exec_mode
2844   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
2845 
2846   // Set an oopmap for the call site
2847   oop_maps->add_gc_map(__ pc() - start,
2848                        new OopMap( frame_size_in_words, 0 ));
2849 
2850   __ reset_last_Java_frame(true, false);
2851 
2852   // Collect return values
2853   __ movdbl(xmm0, Address(rsp, RegisterSaver::xmm0_offset_in_bytes()));
2854   __ movptr(rax, Address(rsp, RegisterSaver::rax_offset_in_bytes()));
2855   // I think this is useless (throwing pc?)
2856   __ movptr(rdx, Address(rsp, RegisterSaver::rdx_offset_in_bytes()));
2857 
2858   // Pop self-frame.
2859   __ leave();                           // Epilog
2860 
2861   // Jump to interpreter
2862   __ ret(0);
2863 
2864   // Make sure all code is generated
2865   masm->flush();
2866 
2867   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
2868   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
2869 }
2870 
2871 #ifdef COMPILER2
2872 //------------------------------generate_uncommon_trap_blob--------------------
2873 void SharedRuntime::generate_uncommon_trap_blob() {
2874   // Allocate space for the code
2875   ResourceMark rm;
2876   // Setup code generation tools
2877   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
2878   MacroAssembler* masm = new MacroAssembler(&buffer);
2879 
2880   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
2881 
2882   address start = __ pc();
2883 
2884   // Push self-frame.  We get here with a return address on the
2885   // stack, so rsp is 8-byte aligned until we allocate our frame.
2886   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
2887 
2888   // No callee saved registers. rbp is assumed implicitly saved
2889   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
2890 
2891   // compiler left unloaded_class_index in j_rarg0 move to where the
2892   // runtime expects it.
2893   __ movl(c_rarg1, j_rarg0);
2894 
2895   __ set_last_Java_frame(noreg, noreg, NULL);
2896 
2897   // Call C code.  Need thread but NOT official VM entry
2898   // crud.  We cannot block on this call, no GC can happen.  Call should
2899   // capture callee-saved registers as well as return values.
2900   // Thread is in rdi already.
2901   //
2902   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
2903 
2904   __ mov(c_rarg0, r15_thread);
2905   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2906 
2907   // Set an oopmap for the call site
2908   OopMapSet* oop_maps = new OopMapSet();
2909   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
2910 
2911   // location of rbp is known implicitly by the frame sender code
2912 
2913   oop_maps->add_gc_map(__ pc() - start, map);
2914 
2915   __ reset_last_Java_frame(false, false);
2916 
2917   // Load UnrollBlock* into rdi
2918   __ mov(rdi, rax);
2919 
2920   // Pop all the frames we must move/replace.
2921   //
2922   // Frame picture (youngest to oldest)
2923   // 1: self-frame (no frame link)
2924   // 2: deopting frame  (no frame link)
2925   // 3: caller of deopting frame (could be compiled/interpreted).
2926 
2927   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
2928   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
2929 
2930   // Pop deoptimized frame (int)
2931   __ movl(rcx, Address(rdi,
2932                        Deoptimization::UnrollBlock::
2933                        size_of_deoptimized_frame_offset_in_bytes()));
2934   __ addptr(rsp, rcx);
2935 
2936   // rsp should be pointing at the return address to the caller (3)
2937 
2938   // Stack bang to make sure there's enough room for these interpreter frames.
2939   if (UseStackBanging) {
2940     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
2941     __ bang_stack_size(rbx, rcx);
2942   }
2943 
2944   // Load address of array of frame pcs into rcx (address*)
2945   __ movptr(rcx,
2946             Address(rdi,
2947                     Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
2948 
2949   // Trash the return pc
2950   __ addptr(rsp, wordSize);
2951 
2952   // Load address of array of frame sizes into rsi (intptr_t*)
2953   __ movptr(rsi, Address(rdi,
2954                          Deoptimization::UnrollBlock::
2955                          frame_sizes_offset_in_bytes()));
2956 
2957   // Counter
2958   __ movl(rdx, Address(rdi,
2959                        Deoptimization::UnrollBlock::
2960                        number_of_frames_offset_in_bytes())); // (int)
2961 
2962   // Pick up the initial fp we should save
2963   __ movptr(rbp,
2964             Address(rdi,
2965                     Deoptimization::UnrollBlock::initial_fp_offset_in_bytes()));
2966 
2967   // Now adjust the caller's stack to make up for the extra locals but
2968   // record the original sp so that we can save it in the skeletal
2969   // interpreter frame and the stack walking of interpreter_sender
2970   // will get the unextended sp value and not the "real" sp value.
2971 
2972   const Register sender_sp = r8;
2973 
2974   __ mov(sender_sp, rsp);
2975   __ movl(rbx, Address(rdi,
2976                        Deoptimization::UnrollBlock::
2977                        caller_adjustment_offset_in_bytes())); // (int)
2978   __ subptr(rsp, rbx);
2979 
2980   // Push interpreter frames in a loop
2981   Label loop;
2982   __ bind(loop);
2983   __ movptr(rbx, Address(rsi, 0)); // Load frame size
2984   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
2985   __ pushptr(Address(rcx, 0));     // Save return address
2986   __ enter();                      // Save old & set new rbp
2987   __ subptr(rsp, rbx);             // Prolog
2988 #ifdef CC_INTERP
2989   __ movptr(Address(rbp,
2990                   -(sizeof(BytecodeInterpreter)) + in_bytes(byte_offset_of(BytecodeInterpreter, _sender_sp))),
2991             sender_sp); // Make it walkable
2992 #else // CC_INTERP
2993   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
2994             sender_sp);            // Make it walkable
2995   // This value is corrected by layout_activation_impl
2996   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
2997 #endif // CC_INTERP
2998   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
2999   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
3000   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
3001   __ decrementl(rdx);              // Decrement counter
3002   __ jcc(Assembler::notZero, loop);
3003   __ pushptr(Address(rcx, 0));     // Save final return address
3004 
3005   // Re-push self-frame
3006   __ enter();                 // Save old & set new rbp
3007   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
3008                               // Prolog
3009 
3010   // Use rbp because the frames look interpreted now
3011   __ set_last_Java_frame(noreg, rbp, NULL);
3012 
3013   // Call C code.  Need thread but NOT official VM entry
3014   // crud.  We cannot block on this call, no GC can happen.  Call should
3015   // restore return values to their stack-slots with the new SP.
3016   // Thread is in rdi already.
3017   //
3018   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
3019 
3020   __ mov(c_rarg0, r15_thread);
3021   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
3022   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3023 
3024   // Set an oopmap for the call site
3025   oop_maps->add_gc_map(__ pc() - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3026 
3027   __ reset_last_Java_frame(true, false);
3028 
3029   // Pop self-frame.
3030   __ leave();                 // Epilog
3031 
3032   // Jump to interpreter
3033   __ ret(0);
3034 
3035   // Make sure all code is generated
3036   masm->flush();
3037 
3038   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
3039                                                  SimpleRuntimeFrame::framesize >> 1);
3040 }
3041 #endif // COMPILER2
3042 
3043 
3044 //------------------------------generate_handler_blob------
3045 //
3046 // Generate a special Compile2Runtime blob that saves all registers,
3047 // and setup oopmap.
3048 //
3049 static SafepointBlob* generate_handler_blob(address call_ptr, bool cause_return) {
3050   assert(StubRoutines::forward_exception_entry() != NULL,
3051          "must be generated before");
3052 
3053   ResourceMark rm;
3054   OopMapSet *oop_maps = new OopMapSet();
3055   OopMap* map;
3056 
3057   // Allocate space for the code.  Setup code generation tools.
3058   CodeBuffer buffer("handler_blob", 2048, 1024);
3059   MacroAssembler* masm = new MacroAssembler(&buffer);
3060 
3061   address start   = __ pc();
3062   address call_pc = NULL;
3063   int frame_size_in_words;
3064 
3065   // Make room for return address (or push it again)
3066   if (!cause_return) {
3067     __ push(rbx);
3068   }
3069 
3070   // Save registers, fpu state, and flags
3071   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3072 
3073   // The following is basically a call_VM.  However, we need the precise
3074   // address of the call in order to generate an oopmap. Hence, we do all the
3075   // work outselves.
3076 
3077   __ set_last_Java_frame(noreg, noreg, NULL);
3078 
3079   // The return address must always be correct so that frame constructor never
3080   // sees an invalid pc.
3081 
3082   if (!cause_return) {
3083     // overwrite the dummy value we pushed on entry
3084     __ movptr(c_rarg0, Address(r15_thread, JavaThread::saved_exception_pc_offset()));
3085     __ movptr(Address(rbp, wordSize), c_rarg0);
3086   }
3087 
3088   // Do the call
3089   __ mov(c_rarg0, r15_thread);
3090   __ call(RuntimeAddress(call_ptr));
3091 
3092   // Set an oopmap for the call site.  This oopmap will map all
3093   // oop-registers and debug-info registers as callee-saved.  This
3094   // will allow deoptimization at this safepoint to find all possible
3095   // debug-info recordings, as well as let GC find all oops.
3096 
3097   oop_maps->add_gc_map( __ pc() - start, map);
3098 
3099   Label noException;
3100 
3101   __ reset_last_Java_frame(false, false);
3102 
3103   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3104   __ jcc(Assembler::equal, noException);
3105 
3106   // Exception pending
3107 
3108   RegisterSaver::restore_live_registers(masm);
3109 
3110   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3111 
3112   // No exception case
3113   __ bind(noException);
3114 
3115   // Normal exit, restore registers and exit.
3116   RegisterSaver::restore_live_registers(masm);
3117 
3118   __ ret(0);
3119 
3120   // Make sure all code is generated
3121   masm->flush();
3122 
3123   // Fill-out other meta info
3124   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3125 }
3126 
3127 //
3128 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3129 //
3130 // Generate a stub that calls into vm to find out the proper destination
3131 // of a java call. All the argument registers are live at this point
3132 // but since this is generic code we don't know what they are and the caller
3133 // must do any gc of the args.
3134 //
3135 static RuntimeStub* generate_resolve_blob(address destination, const char* name) {
3136   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3137 
3138   // allocate space for the code
3139   ResourceMark rm;
3140 
3141   CodeBuffer buffer(name, 1000, 512);
3142   MacroAssembler* masm                = new MacroAssembler(&buffer);
3143 
3144   int frame_size_in_words;
3145 
3146   OopMapSet *oop_maps = new OopMapSet();
3147   OopMap* map = NULL;
3148 
3149   int start = __ offset();
3150 
3151   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words);
3152 
3153   int frame_complete = __ offset();
3154 
3155   __ set_last_Java_frame(noreg, noreg, NULL);
3156 
3157   __ mov(c_rarg0, r15_thread);
3158 
3159   __ call(RuntimeAddress(destination));
3160 
3161 
3162   // Set an oopmap for the call site.
3163   // We need this not only for callee-saved registers, but also for volatile
3164   // registers that the compiler might be keeping live across a safepoint.
3165 
3166   oop_maps->add_gc_map( __ offset() - start, map);
3167 
3168   // rax contains the address we are going to jump to assuming no exception got installed
3169 
3170   // clear last_Java_sp
3171   __ reset_last_Java_frame(false, false);
3172   // check for pending exceptions
3173   Label pending;
3174   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3175   __ jcc(Assembler::notEqual, pending);
3176 
3177   // get the returned methodOop
3178   __ movptr(rbx, Address(r15_thread, JavaThread::vm_result_offset()));
3179   __ movptr(Address(rsp, RegisterSaver::rbx_offset_in_bytes()), rbx);
3180 
3181   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3182 
3183   RegisterSaver::restore_live_registers(masm);
3184 
3185   // We are back the the original state on entry and ready to go.
3186 
3187   __ jmp(rax);
3188 
3189   // Pending exception after the safepoint
3190 
3191   __ bind(pending);
3192 
3193   RegisterSaver::restore_live_registers(masm);
3194 
3195   // exception pending => remove activation and forward to exception handler
3196 
3197   __ movptr(Address(r15_thread, JavaThread::vm_result_offset()), (int)NULL_WORD);
3198 
3199   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
3200   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3201 
3202   // -------------
3203   // make sure all code is generated
3204   masm->flush();
3205 
3206   // return the  blob
3207   // frame_size_words or bytes??
3208   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3209 }
3210 
3211 
3212 void SharedRuntime::generate_stubs() {
3213 
3214   _wrong_method_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method),
3215                                         "wrong_method_stub");
3216   _ic_miss_blob =      generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::handle_wrong_method_ic_miss),
3217                                         "ic_miss_stub");
3218   _resolve_opt_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_opt_virtual_call_C),
3219                                         "resolve_opt_virtual_call");
3220 
3221   _resolve_virtual_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_virtual_call_C),
3222                                         "resolve_virtual_call");
3223 
3224   _resolve_static_call_blob = generate_resolve_blob(CAST_FROM_FN_PTR(address, SharedRuntime::resolve_static_call_C),
3225                                         "resolve_static_call");
3226   _polling_page_safepoint_handler_blob =
3227     generate_handler_blob(CAST_FROM_FN_PTR(address,
3228                    SafepointSynchronize::handle_polling_page_exception), false);
3229 
3230   _polling_page_return_handler_blob =
3231     generate_handler_blob(CAST_FROM_FN_PTR(address,
3232                    SafepointSynchronize::handle_polling_page_exception), true);
3233 
3234   generate_deopt_blob();
3235 
3236 #ifdef COMPILER2
3237   generate_uncommon_trap_blob();
3238 #endif // COMPILER2
3239 }
3240 
3241 
3242 #ifdef COMPILER2
3243 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
3244 //
3245 //------------------------------generate_exception_blob---------------------------
3246 // creates exception blob at the end
3247 // Using exception blob, this code is jumped from a compiled method.
3248 // (see emit_exception_handler in x86_64.ad file)
3249 //
3250 // Given an exception pc at a call we call into the runtime for the
3251 // handler in this method. This handler might merely restore state
3252 // (i.e. callee save registers) unwind the frame and jump to the
3253 // exception handler for the nmethod if there is no Java level handler
3254 // for the nmethod.
3255 //
3256 // This code is entered with a jmp.
3257 //
3258 // Arguments:
3259 //   rax: exception oop
3260 //   rdx: exception pc
3261 //
3262 // Results:
3263 //   rax: exception oop
3264 //   rdx: exception pc in caller or ???
3265 //   destination: exception handler of caller
3266 //
3267 // Note: the exception pc MUST be at a call (precise debug information)
3268 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
3269 //
3270 
3271 void OptoRuntime::generate_exception_blob() {
3272   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
3273   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
3274   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
3275 
3276   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3277 
3278   // Allocate space for the code
3279   ResourceMark rm;
3280   // Setup code generation tools
3281   CodeBuffer buffer("exception_blob", 2048, 1024);
3282   MacroAssembler* masm = new MacroAssembler(&buffer);
3283 
3284 
3285   address start = __ pc();
3286 
3287   // Exception pc is 'return address' for stack walker
3288   __ push(rdx);
3289   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
3290 
3291   // Save callee-saved registers.  See x86_64.ad.
3292 
3293   // rbp is an implicitly saved callee saved register (i.e. the calling
3294   // convention will save restore it in prolog/epilog) Other than that
3295   // there are no callee save registers now that adapter frames are gone.
3296 
3297   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3298 
3299   // Store exception in Thread object. We cannot pass any arguments to the
3300   // handle_exception call, since we do not want to make any assumption
3301   // about the size of the frame where the exception happened in.
3302   // c_rarg0 is either rdi (Linux) or rcx (Windows).
3303   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
3304   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
3305 
3306   // This call does all the hard work.  It checks if an exception handler
3307   // exists in the method.
3308   // If so, it returns the handler address.
3309   // If not, it prepares for stack-unwinding, restoring the callee-save
3310   // registers of the frame being removed.
3311   //
3312   // address OptoRuntime::handle_exception_C(JavaThread* thread)
3313 
3314   __ set_last_Java_frame(noreg, noreg, NULL);
3315   __ mov(c_rarg0, r15_thread);
3316   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3317 
3318   // Set an oopmap for the call site.  This oopmap will only be used if we
3319   // are unwinding the stack.  Hence, all locations will be dead.
3320   // Callee-saved registers will be the same as the frame above (i.e.,
3321   // handle_exception_stub), since they were restored when we got the
3322   // exception.
3323 
3324   OopMapSet* oop_maps = new OopMapSet();
3325 
3326   oop_maps->add_gc_map( __ pc()-start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3327 
3328   __ reset_last_Java_frame(false, false);
3329 
3330   // Restore callee-saved registers
3331 
3332   // rbp is an implicitly saved callee saved register (i.e. the calling
3333   // convention will save restore it in prolog/epilog) Other than that
3334   // there are no callee save registers no that adapter frames are gone.
3335 
3336   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
3337 
3338   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
3339   __ pop(rdx);                  // No need for exception pc anymore
3340 
3341   // rax: exception handler
3342 
3343   // Restore SP from BP if the exception PC is a MethodHandle call.
3344   __ cmpl(Address(r15_thread, JavaThread::is_method_handle_exception_offset()), 0);
3345   __ cmovptr(Assembler::notEqual, rsp, rbp);
3346 
3347   // We have a handler in rax (could be deopt blob).
3348   __ mov(r8, rax);
3349 
3350   // Get the exception oop
3351   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3352   // Get the exception pc in case we are deoptimized
3353   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3354 #ifdef ASSERT
3355   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), (int)NULL_WORD);
3356   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int)NULL_WORD);
3357 #endif
3358   // Clear the exception oop so GC no longer processes it as a root.
3359   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int)NULL_WORD);
3360 
3361   // rax: exception oop
3362   // r8:  exception handler
3363   // rdx: exception pc
3364   // Jump to handler
3365 
3366   __ jmp(r8);
3367 
3368   // Make sure all code is generated
3369   masm->flush();
3370 
3371   // Set exception blob
3372   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
3373 }
3374 #endif // COMPILER2