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