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