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