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