1 /*
   2  * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #ifndef _WINDOWS
  27 #include "alloca.h"
  28 #endif
  29 #include "asm/macroAssembler.hpp"
  30 #include "asm/macroAssembler.inline.hpp"
  31 #include "code/debugInfoRec.hpp"
  32 #include "code/icBuffer.hpp"
  33 #include "code/nativeInst.hpp"
  34 #include "code/vtableStubs.hpp"
  35 #include "gc/shared/gcLocker.hpp"
  36 #include "interpreter/interpreter.hpp"
  37 #include "logging/log.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/compiledICHolder.hpp"
  40 #include "runtime/safepointMechanism.hpp"
  41 #include "runtime/sharedRuntime.hpp"
  42 #include "runtime/vframeArray.hpp"
  43 #include "runtime/vm_version.hpp"
  44 #include "utilities/align.hpp"
  45 #include "utilities/formatBuffer.hpp"
  46 #include "utilities/macros.hpp"
  47 #include "vmreg_x86.inline.hpp"
  48 #ifdef COMPILER1
  49 #include "c1/c1_Runtime1.hpp"
  50 #endif
  51 #ifdef COMPILER2
  52 #include "opto/runtime.hpp"
  53 #endif
  54 #if INCLUDE_JVMCI
  55 #include "jvmci/jvmciJavaClasses.hpp"
  56 #endif
  57 #if INCLUDE_SHENANDOAHGC
  58 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  59 #include "gc/shenandoah/shenandoahBarrierSetAssembler.hpp"
  60 #endif
  61 
  62 #define __ masm->
  63 
  64 const int StackAlignmentInSlots = StackAlignmentInBytes / VMRegImpl::stack_slot_size;
  65 
  66 class SimpleRuntimeFrame {
  67 
  68   public:
  69 
  70   // Most of the runtime stubs have this simple frame layout.
  71   // This class exists to make the layout shared in one place.
  72   // Offsets are for compiler stack slots, which are jints.
  73   enum layout {
  74     // The frame sender code expects that rbp will be in the "natural" place and
  75     // will override any oopMap setting for it. We must therefore force the layout
  76     // so that it agrees with the frame sender code.
  77     rbp_off = frame::arg_reg_save_area_bytes/BytesPerInt,
  78     rbp_off2,
  79     return_off, return_off2,
  80     framesize
  81   };
  82 };
  83 
  84 class RegisterSaver {
  85   // Capture info about frame layout.  Layout offsets are in jint
  86   // units because compiler frame slots are jints.
  87 #define XSAVE_AREA_BEGIN 160
  88 #define XSAVE_AREA_YMM_BEGIN 576
  89 #define XSAVE_AREA_ZMM_BEGIN 1152
  90 #define XSAVE_AREA_UPPERBANK 1664
  91 #define DEF_XMM_OFFS(regnum)       xmm ## regnum ## _off = xmm_off + (regnum)*16/BytesPerInt, xmm ## regnum ## H_off
  92 #define DEF_YMM_OFFS(regnum)       ymm ## regnum ## _off = ymm_off + (regnum)*16/BytesPerInt, ymm ## regnum ## H_off
  93 #define DEF_ZMM_OFFS(regnum)       zmm ## regnum ## _off = zmm_off + (regnum)*32/BytesPerInt, zmm ## regnum ## H_off
  94 #define DEF_ZMM_UPPER_OFFS(regnum) zmm ## regnum ## _off = zmm_upper_off + (regnum-16)*64/BytesPerInt, zmm ## regnum ## H_off
  95   enum layout {
  96     fpu_state_off = frame::arg_reg_save_area_bytes/BytesPerInt, // fxsave save area
  97     xmm_off       = fpu_state_off + XSAVE_AREA_BEGIN/BytesPerInt,            // offset in fxsave save area
  98     DEF_XMM_OFFS(0),
  99     DEF_XMM_OFFS(1),
 100     // 2..15 are implied in range usage
 101     ymm_off = xmm_off + (XSAVE_AREA_YMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
 102     DEF_YMM_OFFS(0),
 103     DEF_YMM_OFFS(1),
 104     // 2..15 are implied in range usage
 105     zmm_off = xmm_off + (XSAVE_AREA_ZMM_BEGIN - XSAVE_AREA_BEGIN)/BytesPerInt,
 106     DEF_ZMM_OFFS(0),
 107     DEF_ZMM_OFFS(1),
 108     zmm_upper_off = xmm_off + (XSAVE_AREA_UPPERBANK - XSAVE_AREA_BEGIN)/BytesPerInt,
 109     DEF_ZMM_UPPER_OFFS(16),
 110     DEF_ZMM_UPPER_OFFS(17),
 111     // 18..31 are implied in range usage
 112     fpu_state_end = fpu_state_off + ((FPUStateSizeInWords-1)*wordSize / BytesPerInt),
 113     fpu_stateH_end,
 114     r15_off, r15H_off,
 115     r14_off, r14H_off,
 116     r13_off, r13H_off,
 117     r12_off, r12H_off,
 118     r11_off, r11H_off,
 119     r10_off, r10H_off,
 120     r9_off,  r9H_off,
 121     r8_off,  r8H_off,
 122     rdi_off, rdiH_off,
 123     rsi_off, rsiH_off,
 124     ignore_off, ignoreH_off,  // extra copy of rbp
 125     rsp_off, rspH_off,
 126     rbx_off, rbxH_off,
 127     rdx_off, rdxH_off,
 128     rcx_off, rcxH_off,
 129     rax_off, raxH_off,
 130     // 16-byte stack alignment fill word: see MacroAssembler::push/pop_IU_state
 131     align_off, alignH_off,
 132     flags_off, flagsH_off,
 133     // The frame sender code expects that rbp will be in the "natural" place and
 134     // will override any oopMap setting for it. We must therefore force the layout
 135     // so that it agrees with the frame sender code.
 136     rbp_off, rbpH_off,        // copy of rbp we will restore
 137     return_off, returnH_off,  // slot for return address
 138     reg_save_size             // size in compiler stack slots
 139   };
 140 
 141  public:
 142   static OopMap* save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors);
 143   static void restore_live_registers(MacroAssembler* masm, bool restore_vectors = false);
 144 
 145   // Offsets into the register save area
 146   // Used by deoptimization when it is managing result register
 147   // values on its own
 148 
 149   static int rax_offset_in_bytes(void)    { return BytesPerInt * rax_off; }
 150   static int rdx_offset_in_bytes(void)    { return BytesPerInt * rdx_off; }
 151   static int rbx_offset_in_bytes(void)    { return BytesPerInt * rbx_off; }
 152   static int xmm0_offset_in_bytes(void)   { return BytesPerInt * xmm0_off; }
 153   static int return_offset_in_bytes(void) { return BytesPerInt * return_off; }
 154 
 155   // During deoptimization only the result registers need to be restored,
 156   // all the other values have already been extracted.
 157   static void restore_result_registers(MacroAssembler* masm);
 158 };
 159 
 160 OopMap* RegisterSaver::save_live_registers(MacroAssembler* masm, int additional_frame_words, int* total_frame_words, bool save_vectors) {
 161   int off = 0;
 162   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 163   if (UseAVX < 3) {
 164     num_xmm_regs = num_xmm_regs/2;
 165   }
 166 #if COMPILER2_OR_JVMCI
 167   if (save_vectors && UseAVX == 0) {
 168     save_vectors = false; // vectors larger than 16 byte long are supported only with AVX
 169   }
 170   assert(!save_vectors || MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 171 #else
 172   save_vectors = false; // vectors are generated only by C2 and JVMCI
 173 #endif
 174 
 175   // Always make the frame size 16-byte aligned, both vector and non vector stacks are always allocated
 176   int frame_size_in_bytes = align_up(reg_save_size*BytesPerInt, num_xmm_regs);
 177   // OopMap frame size is in compiler stack slots (jint's) not bytes or words
 178   int frame_size_in_slots = frame_size_in_bytes / BytesPerInt;
 179   // CodeBlob frame size is in words.
 180   int frame_size_in_words = frame_size_in_bytes / wordSize;
 181   *total_frame_words = frame_size_in_words;
 182 
 183   // Save registers, fpu state, and flags.
 184   // We assume caller has already pushed the return address onto the
 185   // stack, so rsp is 8-byte aligned here.
 186   // We push rpb twice in this sequence because we want the real rbp
 187   // to be under the return like a normal enter.
 188 
 189   __ enter();          // rsp becomes 16-byte aligned here
 190   __ push_CPU_state(); // Push a multiple of 16 bytes
 191 
 192   // push cpu state handles this on EVEX enabled targets
 193   if (save_vectors) {
 194     // Save upper half of YMM registers(0..15)
 195     int base_addr = XSAVE_AREA_YMM_BEGIN;
 196     for (int n = 0; n < 16; n++) {
 197       __ vextractf128_high(Address(rsp, base_addr+n*16), as_XMMRegister(n));
 198     }
 199     if (VM_Version::supports_evex()) {
 200       // Save upper half of ZMM registers(0..15)
 201       base_addr = XSAVE_AREA_ZMM_BEGIN;
 202       for (int n = 0; n < 16; n++) {
 203         __ vextractf64x4_high(Address(rsp, base_addr+n*32), as_XMMRegister(n));
 204       }
 205       // Save full ZMM registers(16..num_xmm_regs)
 206       base_addr = XSAVE_AREA_UPPERBANK;
 207       off = 0;
 208       int vector_len = Assembler::AVX_512bit;
 209       for (int n = 16; n < num_xmm_regs; n++) {
 210         __ evmovdqul(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n), vector_len);
 211       }
 212     }
 213   } else {
 214     if (VM_Version::supports_evex()) {
 215       // Save upper bank of ZMM registers(16..31) for double/float usage
 216       int base_addr = XSAVE_AREA_UPPERBANK;
 217       off = 0;
 218       for (int n = 16; n < num_xmm_regs; n++) {
 219         __ movsd(Address(rsp, base_addr+(off++*64)), as_XMMRegister(n));
 220       }
 221     }
 222   }
 223   __ vzeroupper();
 224   if (frame::arg_reg_save_area_bytes != 0) {
 225     // Allocate argument register save area
 226     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 227   }
 228 
 229   // Set an oopmap for the call site.  This oopmap will map all
 230   // oop-registers and debug-info registers as callee-saved.  This
 231   // will allow deoptimization at this safepoint to find all possible
 232   // debug-info recordings, as well as let GC find all oops.
 233 
 234   OopMapSet *oop_maps = new OopMapSet();
 235   OopMap* map = new OopMap(frame_size_in_slots, 0);
 236 
 237 #define STACK_OFFSET(x) VMRegImpl::stack2reg((x))
 238 
 239   map->set_callee_saved(STACK_OFFSET( rax_off ), rax->as_VMReg());
 240   map->set_callee_saved(STACK_OFFSET( rcx_off ), rcx->as_VMReg());
 241   map->set_callee_saved(STACK_OFFSET( rdx_off ), rdx->as_VMReg());
 242   map->set_callee_saved(STACK_OFFSET( rbx_off ), rbx->as_VMReg());
 243   // rbp location is known implicitly by the frame sender code, needs no oopmap
 244   // and the location where rbp was saved by is ignored
 245   map->set_callee_saved(STACK_OFFSET( rsi_off ), rsi->as_VMReg());
 246   map->set_callee_saved(STACK_OFFSET( rdi_off ), rdi->as_VMReg());
 247   map->set_callee_saved(STACK_OFFSET( r8_off  ), r8->as_VMReg());
 248   map->set_callee_saved(STACK_OFFSET( r9_off  ), r9->as_VMReg());
 249   map->set_callee_saved(STACK_OFFSET( r10_off ), r10->as_VMReg());
 250   map->set_callee_saved(STACK_OFFSET( r11_off ), r11->as_VMReg());
 251   map->set_callee_saved(STACK_OFFSET( r12_off ), r12->as_VMReg());
 252   map->set_callee_saved(STACK_OFFSET( r13_off ), r13->as_VMReg());
 253   map->set_callee_saved(STACK_OFFSET( r14_off ), r14->as_VMReg());
 254   map->set_callee_saved(STACK_OFFSET( r15_off ), r15->as_VMReg());
 255   // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 256   // on EVEX enabled targets, we get it included in the xsave area
 257   off = xmm0_off;
 258   int delta = xmm1_off - off;
 259   for (int n = 0; n < 16; n++) {
 260     XMMRegister xmm_name = as_XMMRegister(n);
 261     map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg());
 262     off += delta;
 263   }
 264   if (UseAVX > 2) {
 265     // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 266     off = zmm16_off;
 267     delta = zmm17_off - off;
 268     for (int n = 16; n < num_xmm_regs; n++) {
 269       XMMRegister zmm_name = as_XMMRegister(n);
 270       map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg());
 271       off += delta;
 272     }
 273   }
 274 
 275 #if COMPILER2_OR_JVMCI
 276   if (save_vectors) {
 277     // Save upper half of YMM registers(0..15)
 278     off = ymm0_off;
 279     delta = ymm1_off - ymm0_off;
 280     for (int n = 0; n < 16; n++) {
 281       XMMRegister ymm_name = as_XMMRegister(n);
 282       map->set_callee_saved(STACK_OFFSET(off), ymm_name->as_VMReg()->next(4));
 283       off += delta;
 284     }
 285     if (VM_Version::supports_evex()) {
 286       // Save upper half of ZMM registers(0..15)
 287       off = zmm0_off;
 288       delta = zmm1_off - zmm0_off;
 289       for (int n = 0; n < 16; n++) {
 290         XMMRegister zmm_name = as_XMMRegister(n);
 291         map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg()->next(8));
 292         off += delta;
 293       }
 294     }
 295   }
 296 #endif // COMPILER2_OR_JVMCI
 297 
 298   // %%% These should all be a waste but we'll keep things as they were for now
 299   if (true) {
 300     map->set_callee_saved(STACK_OFFSET( raxH_off ), rax->as_VMReg()->next());
 301     map->set_callee_saved(STACK_OFFSET( rcxH_off ), rcx->as_VMReg()->next());
 302     map->set_callee_saved(STACK_OFFSET( rdxH_off ), rdx->as_VMReg()->next());
 303     map->set_callee_saved(STACK_OFFSET( rbxH_off ), rbx->as_VMReg()->next());
 304     // rbp location is known implicitly by the frame sender code, needs no oopmap
 305     map->set_callee_saved(STACK_OFFSET( rsiH_off ), rsi->as_VMReg()->next());
 306     map->set_callee_saved(STACK_OFFSET( rdiH_off ), rdi->as_VMReg()->next());
 307     map->set_callee_saved(STACK_OFFSET( r8H_off  ), r8->as_VMReg()->next());
 308     map->set_callee_saved(STACK_OFFSET( r9H_off  ), r9->as_VMReg()->next());
 309     map->set_callee_saved(STACK_OFFSET( r10H_off ), r10->as_VMReg()->next());
 310     map->set_callee_saved(STACK_OFFSET( r11H_off ), r11->as_VMReg()->next());
 311     map->set_callee_saved(STACK_OFFSET( r12H_off ), r12->as_VMReg()->next());
 312     map->set_callee_saved(STACK_OFFSET( r13H_off ), r13->as_VMReg()->next());
 313     map->set_callee_saved(STACK_OFFSET( r14H_off ), r14->as_VMReg()->next());
 314     map->set_callee_saved(STACK_OFFSET( r15H_off ), r15->as_VMReg()->next());
 315     // For both AVX and EVEX we will use the legacy FXSAVE area for xmm0..xmm15,
 316     // on EVEX enabled targets, we get it included in the xsave area
 317     off = xmm0H_off;
 318     delta = xmm1H_off - off;
 319     for (int n = 0; n < 16; n++) {
 320       XMMRegister xmm_name = as_XMMRegister(n);
 321       map->set_callee_saved(STACK_OFFSET(off), xmm_name->as_VMReg()->next());
 322       off += delta;
 323     }
 324     if (UseAVX > 2) {
 325       // Obtain xmm16..xmm31 from the XSAVE area on EVEX enabled targets
 326       off = zmm16H_off;
 327       delta = zmm17H_off - off;
 328       for (int n = 16; n < num_xmm_regs; n++) {
 329         XMMRegister zmm_name = as_XMMRegister(n);
 330         map->set_callee_saved(STACK_OFFSET(off), zmm_name->as_VMReg()->next());
 331         off += delta;
 332       }
 333     }
 334   }
 335 
 336   return map;
 337 }
 338 
 339 void RegisterSaver::restore_live_registers(MacroAssembler* masm, bool restore_vectors) {
 340   int num_xmm_regs = XMMRegisterImpl::number_of_registers;
 341   if (UseAVX < 3) {
 342     num_xmm_regs = num_xmm_regs/2;
 343   }
 344   if (frame::arg_reg_save_area_bytes != 0) {
 345     // Pop arg register save area
 346     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 347   }
 348 
 349 #if COMPILER2_OR_JVMCI
 350   if (restore_vectors) {
 351     assert(UseAVX > 0, "Vectors larger than 16 byte long are supported only with AVX");
 352     assert(MaxVectorSize <= 64, "Only up to 64 byte long vectors are supported");
 353   }
 354 #else
 355   assert(!restore_vectors, "vectors are generated only by C2");
 356 #endif
 357 
 358   __ vzeroupper();
 359 
 360   // On EVEX enabled targets everything is handled in pop fpu state
 361   if (restore_vectors) {
 362     // Restore upper half of YMM registers (0..15)
 363     int base_addr = XSAVE_AREA_YMM_BEGIN;
 364     for (int n = 0; n < 16; n++) {
 365       __ vinsertf128_high(as_XMMRegister(n), Address(rsp, base_addr+n*16));
 366     }
 367     if (VM_Version::supports_evex()) {
 368       // Restore upper half of ZMM registers (0..15)
 369       base_addr = XSAVE_AREA_ZMM_BEGIN;
 370       for (int n = 0; n < 16; n++) {
 371         __ vinsertf64x4_high(as_XMMRegister(n), Address(rsp, base_addr+n*32));
 372       }
 373       // Restore full ZMM registers(16..num_xmm_regs)
 374       base_addr = XSAVE_AREA_UPPERBANK;
 375       int vector_len = Assembler::AVX_512bit;
 376       int off = 0;
 377       for (int n = 16; n < num_xmm_regs; n++) {
 378         __ evmovdqul(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)), vector_len);
 379       }
 380     }
 381   } else {
 382     if (VM_Version::supports_evex()) {
 383       // Restore upper bank of ZMM registers(16..31) for double/float usage
 384       int base_addr = XSAVE_AREA_UPPERBANK;
 385       int off = 0;
 386       for (int n = 16; n < num_xmm_regs; n++) {
 387         __ movsd(as_XMMRegister(n), Address(rsp, base_addr+(off++*64)));
 388       }
 389     }
 390   }
 391 
 392   // Recover CPU state
 393   __ pop_CPU_state();
 394   // Get the rbp described implicitly by the calling convention (no oopMap)
 395   __ pop(rbp);
 396 }
 397 
 398 void RegisterSaver::restore_result_registers(MacroAssembler* masm) {
 399 
 400   // Just restore result register. Only used by deoptimization. By
 401   // now any callee save register that needs to be restored to a c2
 402   // caller of the deoptee has been extracted into the vframeArray
 403   // and will be stuffed into the c2i adapter we create for later
 404   // restoration so only result registers need to be restored here.
 405 
 406   // Restore fp result register
 407   __ movdbl(xmm0, Address(rsp, xmm0_offset_in_bytes()));
 408   // Restore integer result register
 409   __ movptr(rax, Address(rsp, rax_offset_in_bytes()));
 410   __ movptr(rdx, Address(rsp, rdx_offset_in_bytes()));
 411 
 412   // Pop all of the register save are off the stack except the return address
 413   __ addptr(rsp, return_offset_in_bytes());
 414 }
 415 
 416 // Is vector's size (in bytes) bigger than a size saved by default?
 417 // 16 bytes XMM registers are saved by default using fxsave/fxrstor instructions.
 418 bool SharedRuntime::is_wide_vector(int size) {
 419   return size > 16;
 420 }
 421 
 422 size_t SharedRuntime::trampoline_size() {
 423   return 16;
 424 }
 425 
 426 void SharedRuntime::generate_trampoline(MacroAssembler *masm, address destination) {
 427   __ jump(RuntimeAddress(destination));
 428 }
 429 
 430 // The java_calling_convention describes stack locations as ideal slots on
 431 // a frame with no abi restrictions. Since we must observe abi restrictions
 432 // (like the placement of the register window) the slots must be biased by
 433 // the following value.
 434 static int reg2offset_in(VMReg r) {
 435   // Account for saved rbp and return address
 436   // This should really be in_preserve_stack_slots
 437   return (r->reg2stack() + 4) * VMRegImpl::stack_slot_size;
 438 }
 439 
 440 static int reg2offset_out(VMReg r) {
 441   return (r->reg2stack() + SharedRuntime::out_preserve_stack_slots()) * VMRegImpl::stack_slot_size;
 442 }
 443 
 444 // ---------------------------------------------------------------------------
 445 // Read the array of BasicTypes from a signature, and compute where the
 446 // arguments should go.  Values in the VMRegPair regs array refer to 4-byte
 447 // quantities.  Values less than VMRegImpl::stack0 are registers, those above
 448 // refer to 4-byte stack slots.  All stack slots are based off of the stack pointer
 449 // as framesizes are fixed.
 450 // VMRegImpl::stack0 refers to the first slot 0(sp).
 451 // and VMRegImpl::stack0+1 refers to the memory word 4-byes higher.  Register
 452 // up to RegisterImpl::number_of_registers) are the 64-bit
 453 // integer registers.
 454 
 455 // Note: the INPUTS in sig_bt are in units of Java argument words, which are
 456 // either 32-bit or 64-bit depending on the build.  The OUTPUTS are in 32-bit
 457 // units regardless of build. Of course for i486 there is no 64 bit build
 458 
 459 // The Java calling convention is a "shifted" version of the C ABI.
 460 // By skipping the first C ABI register we can call non-static jni methods
 461 // with small numbers of arguments without having to shuffle the arguments
 462 // at all. Since we control the java ABI we ought to at least get some
 463 // advantage out of it.
 464 
 465 int SharedRuntime::java_calling_convention(const BasicType *sig_bt,
 466                                            VMRegPair *regs,
 467                                            int total_args_passed,
 468                                            int is_outgoing) {
 469 
 470   // Create the mapping between argument positions and
 471   // registers.
 472   static const Register INT_ArgReg[Argument::n_int_register_parameters_j] = {
 473     j_rarg0, j_rarg1, j_rarg2, j_rarg3, j_rarg4, j_rarg5
 474   };
 475   static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_j] = {
 476     j_farg0, j_farg1, j_farg2, j_farg3,
 477     j_farg4, j_farg5, j_farg6, j_farg7
 478   };
 479 
 480 
 481   uint int_args = 0;
 482   uint fp_args = 0;
 483   uint stk_args = 0; // inc by 2 each time
 484 
 485   for (int i = 0; i < total_args_passed; i++) {
 486     switch (sig_bt[i]) {
 487     case T_BOOLEAN:
 488     case T_CHAR:
 489     case T_BYTE:
 490     case T_SHORT:
 491     case T_INT:
 492       if (int_args < Argument::n_int_register_parameters_j) {
 493         regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
 494       } else {
 495         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 496         stk_args += 2;
 497       }
 498       break;
 499     case T_VOID:
 500       // halves of T_LONG or T_DOUBLE
 501       assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
 502       regs[i].set_bad();
 503       break;
 504     case T_LONG:
 505       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 506       // fall through
 507     case T_OBJECT:
 508     case T_ARRAY:
 509     case T_ADDRESS:
 510       if (int_args < Argument::n_int_register_parameters_j) {
 511         regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
 512       } else {
 513         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 514         stk_args += 2;
 515       }
 516       break;
 517     case T_FLOAT:
 518       if (fp_args < Argument::n_float_register_parameters_j) {
 519         regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
 520       } else {
 521         regs[i].set1(VMRegImpl::stack2reg(stk_args));
 522         stk_args += 2;
 523       }
 524       break;
 525     case T_DOUBLE:
 526       assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
 527       if (fp_args < Argument::n_float_register_parameters_j) {
 528         regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
 529       } else {
 530         regs[i].set2(VMRegImpl::stack2reg(stk_args));
 531         stk_args += 2;
 532       }
 533       break;
 534     default:
 535       ShouldNotReachHere();
 536       break;
 537     }
 538   }
 539 
 540   return align_up(stk_args, 2);
 541 }
 542 
 543 // Patch the callers callsite with entry to compiled code if it exists.
 544 static void patch_callers_callsite(MacroAssembler *masm) {
 545   Label L;
 546   __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 547   __ jcc(Assembler::equal, L);
 548 
 549   // Save the current stack pointer
 550   __ mov(r13, rsp);
 551   // Schedule the branch target address early.
 552   // Call into the VM to patch the caller, then jump to compiled callee
 553   // rax isn't live so capture return address while we easily can
 554   __ movptr(rax, Address(rsp, 0));
 555 
 556   // align stack so push_CPU_state doesn't fault
 557   __ andptr(rsp, -(StackAlignmentInBytes));
 558   __ push_CPU_state();
 559   __ vzeroupper();
 560   // VM needs caller's callsite
 561   // VM needs target method
 562   // This needs to be a long call since we will relocate this adapter to
 563   // the codeBuffer and it may not reach
 564 
 565   // Allocate argument register save area
 566   if (frame::arg_reg_save_area_bytes != 0) {
 567     __ subptr(rsp, frame::arg_reg_save_area_bytes);
 568   }
 569   __ mov(c_rarg0, rbx);
 570   __ mov(c_rarg1, rax);
 571   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::fixup_callers_callsite)));
 572 
 573   // De-allocate argument register save area
 574   if (frame::arg_reg_save_area_bytes != 0) {
 575     __ addptr(rsp, frame::arg_reg_save_area_bytes);
 576   }
 577 
 578   __ vzeroupper();
 579   __ pop_CPU_state();
 580   // restore sp
 581   __ mov(rsp, r13);
 582   __ bind(L);
 583 }
 584 
 585 
 586 static void gen_c2i_adapter(MacroAssembler *masm,
 587                             int total_args_passed,
 588                             int comp_args_on_stack,
 589                             const BasicType *sig_bt,
 590                             const VMRegPair *regs,
 591                             Label& skip_fixup) {
 592   // Before we get into the guts of the C2I adapter, see if we should be here
 593   // at all.  We've come from compiled code and are attempting to jump to the
 594   // interpreter, which means the caller made a static call to get here
 595   // (vcalls always get a compiled target if there is one).  Check for a
 596   // compiled target.  If there is one, we need to patch the caller's call.
 597   patch_callers_callsite(masm);
 598 
 599   __ bind(skip_fixup);
 600 
 601   // Since all args are passed on the stack, total_args_passed *
 602   // Interpreter::stackElementSize is the space we need. Plus 1 because
 603   // we also account for the return address location since
 604   // we store it first rather than hold it in rax across all the shuffling
 605 
 606   int extraspace = (total_args_passed * Interpreter::stackElementSize) + wordSize;
 607 
 608   // stack is aligned, keep it that way
 609   extraspace = align_up(extraspace, 2*wordSize);
 610 
 611   // Get return address
 612   __ pop(rax);
 613 
 614   // set senderSP value
 615   __ mov(r13, rsp);
 616 
 617   __ subptr(rsp, extraspace);
 618 
 619   // Store the return address in the expected location
 620   __ movptr(Address(rsp, 0), rax);
 621 
 622   // Now write the args into the outgoing interpreter space
 623   for (int i = 0; i < total_args_passed; i++) {
 624     if (sig_bt[i] == T_VOID) {
 625       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 626       continue;
 627     }
 628 
 629     // offset to start parameters
 630     int st_off   = (total_args_passed - i) * Interpreter::stackElementSize;
 631     int next_off = st_off - Interpreter::stackElementSize;
 632 
 633     // Say 4 args:
 634     // i   st_off
 635     // 0   32 T_LONG
 636     // 1   24 T_VOID
 637     // 2   16 T_OBJECT
 638     // 3    8 T_BOOL
 639     // -    0 return address
 640     //
 641     // However to make thing extra confusing. Because we can fit a long/double in
 642     // a single slot on a 64 bt vm and it would be silly to break them up, the interpreter
 643     // leaves one slot empty and only stores to a single slot. In this case the
 644     // slot that is occupied is the T_VOID slot. See I said it was confusing.
 645 
 646     VMReg r_1 = regs[i].first();
 647     VMReg r_2 = regs[i].second();
 648     if (!r_1->is_valid()) {
 649       assert(!r_2->is_valid(), "");
 650       continue;
 651     }
 652     if (r_1->is_stack()) {
 653       // memory to memory use rax
 654       int ld_off = r_1->reg2stack() * VMRegImpl::stack_slot_size + extraspace;
 655       if (!r_2->is_valid()) {
 656         // sign extend??
 657         __ movl(rax, Address(rsp, ld_off));
 658         __ movptr(Address(rsp, st_off), rax);
 659 
 660       } else {
 661 
 662         __ movq(rax, Address(rsp, ld_off));
 663 
 664         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 665         // T_DOUBLE and T_LONG use two slots in the interpreter
 666         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 667           // ld_off == LSW, ld_off+wordSize == MSW
 668           // st_off == MSW, next_off == LSW
 669           __ movq(Address(rsp, next_off), rax);
 670 #ifdef ASSERT
 671           // Overwrite the unused slot with known junk
 672           __ mov64(rax, CONST64(0xdeadffffdeadaaaa));
 673           __ movptr(Address(rsp, st_off), rax);
 674 #endif /* ASSERT */
 675         } else {
 676           __ movq(Address(rsp, st_off), rax);
 677         }
 678       }
 679     } else if (r_1->is_Register()) {
 680       Register r = r_1->as_Register();
 681       if (!r_2->is_valid()) {
 682         // must be only an int (or less ) so move only 32bits to slot
 683         // why not sign extend??
 684         __ movl(Address(rsp, st_off), r);
 685       } else {
 686         // Two VMREgs|OptoRegs can be T_OBJECT, T_ADDRESS, T_DOUBLE, T_LONG
 687         // T_DOUBLE and T_LONG use two slots in the interpreter
 688         if ( sig_bt[i] == T_LONG || sig_bt[i] == T_DOUBLE) {
 689           // long/double in gpr
 690 #ifdef ASSERT
 691           // Overwrite the unused slot with known junk
 692           __ mov64(rax, CONST64(0xdeadffffdeadaaab));
 693           __ movptr(Address(rsp, st_off), rax);
 694 #endif /* ASSERT */
 695           __ movq(Address(rsp, next_off), r);
 696         } else {
 697           __ movptr(Address(rsp, st_off), r);
 698         }
 699       }
 700     } else {
 701       assert(r_1->is_XMMRegister(), "");
 702       if (!r_2->is_valid()) {
 703         // only a float use just part of the slot
 704         __ movflt(Address(rsp, st_off), r_1->as_XMMRegister());
 705       } else {
 706 #ifdef ASSERT
 707         // Overwrite the unused slot with known junk
 708         __ mov64(rax, CONST64(0xdeadffffdeadaaac));
 709         __ movptr(Address(rsp, st_off), rax);
 710 #endif /* ASSERT */
 711         __ movdbl(Address(rsp, next_off), r_1->as_XMMRegister());
 712       }
 713     }
 714   }
 715 
 716   // Schedule the branch target address early.
 717   __ movptr(rcx, Address(rbx, in_bytes(Method::interpreter_entry_offset())));
 718   __ jmp(rcx);
 719 }
 720 
 721 static void range_check(MacroAssembler* masm, Register pc_reg, Register temp_reg,
 722                         address code_start, address code_end,
 723                         Label& L_ok) {
 724   Label L_fail;
 725   __ lea(temp_reg, ExternalAddress(code_start));
 726   __ cmpptr(pc_reg, temp_reg);
 727   __ jcc(Assembler::belowEqual, L_fail);
 728   __ lea(temp_reg, ExternalAddress(code_end));
 729   __ cmpptr(pc_reg, temp_reg);
 730   __ jcc(Assembler::below, L_ok);
 731   __ bind(L_fail);
 732 }
 733 
 734 void SharedRuntime::gen_i2c_adapter(MacroAssembler *masm,
 735                                     int total_args_passed,
 736                                     int comp_args_on_stack,
 737                                     const BasicType *sig_bt,
 738                                     const VMRegPair *regs) {
 739 
 740   // Note: r13 contains the senderSP on entry. We must preserve it since
 741   // we may do a i2c -> c2i transition if we lose a race where compiled
 742   // code goes non-entrant while we get args ready.
 743   // In addition we use r13 to locate all the interpreter args as
 744   // we must align the stack to 16 bytes on an i2c entry else we
 745   // lose alignment we expect in all compiled code and register
 746   // save code can segv when fxsave instructions find improperly
 747   // aligned stack pointer.
 748 
 749   // Adapters can be frameless because they do not require the caller
 750   // to perform additional cleanup work, such as correcting the stack pointer.
 751   // An i2c adapter is frameless because the *caller* frame, which is interpreted,
 752   // routinely repairs its own stack pointer (from interpreter_frame_last_sp),
 753   // even if a callee has modified the stack pointer.
 754   // A c2i adapter is frameless because the *callee* frame, which is interpreted,
 755   // routinely repairs its caller's stack pointer (from sender_sp, which is set
 756   // up via the senderSP register).
 757   // In other words, if *either* the caller or callee is interpreted, we can
 758   // get the stack pointer repaired after a call.
 759   // This is why c2i and i2c adapters cannot be indefinitely composed.
 760   // In particular, if a c2i adapter were to somehow call an i2c adapter,
 761   // both caller and callee would be compiled methods, and neither would
 762   // clean up the stack pointer changes performed by the two adapters.
 763   // If this happens, control eventually transfers back to the compiled
 764   // caller, but with an uncorrected stack, causing delayed havoc.
 765 
 766   // Pick up the return address
 767   __ movptr(rax, Address(rsp, 0));
 768 
 769   if (VerifyAdapterCalls &&
 770       (Interpreter::code() != NULL || StubRoutines::code1() != NULL)) {
 771     // So, let's test for cascading c2i/i2c adapters right now.
 772     //  assert(Interpreter::contains($return_addr) ||
 773     //         StubRoutines::contains($return_addr),
 774     //         "i2c adapter must return to an interpreter frame");
 775     __ block_comment("verify_i2c { ");
 776     Label L_ok;
 777     if (Interpreter::code() != NULL)
 778       range_check(masm, rax, r11,
 779                   Interpreter::code()->code_start(), Interpreter::code()->code_end(),
 780                   L_ok);
 781     if (StubRoutines::code1() != NULL)
 782       range_check(masm, rax, r11,
 783                   StubRoutines::code1()->code_begin(), StubRoutines::code1()->code_end(),
 784                   L_ok);
 785     if (StubRoutines::code2() != NULL)
 786       range_check(masm, rax, r11,
 787                   StubRoutines::code2()->code_begin(), StubRoutines::code2()->code_end(),
 788                   L_ok);
 789     const char* msg = "i2c adapter must return to an interpreter frame";
 790     __ block_comment(msg);
 791     __ stop(msg);
 792     __ bind(L_ok);
 793     __ block_comment("} verify_i2ce ");
 794   }
 795 
 796   // Must preserve original SP for loading incoming arguments because
 797   // we need to align the outgoing SP for compiled code.
 798   __ movptr(r11, rsp);
 799 
 800   // Cut-out for having no stack args.  Since up to 2 int/oop args are passed
 801   // in registers, we will occasionally have no stack args.
 802   int comp_words_on_stack = 0;
 803   if (comp_args_on_stack) {
 804     // Sig words on the stack are greater-than VMRegImpl::stack0.  Those in
 805     // registers are below.  By subtracting stack0, we either get a negative
 806     // number (all values in registers) or the maximum stack slot accessed.
 807 
 808     // Convert 4-byte c2 stack slots to words.
 809     comp_words_on_stack = align_up(comp_args_on_stack*VMRegImpl::stack_slot_size, wordSize)>>LogBytesPerWord;
 810     // Round up to miminum stack alignment, in wordSize
 811     comp_words_on_stack = align_up(comp_words_on_stack, 2);
 812     __ subptr(rsp, comp_words_on_stack * wordSize);
 813   }
 814 
 815 
 816   // Ensure compiled code always sees stack at proper alignment
 817   __ andptr(rsp, -16);
 818 
 819   // push the return address and misalign the stack that youngest frame always sees
 820   // as far as the placement of the call instruction
 821   __ push(rax);
 822 
 823   // Put saved SP in another register
 824   const Register saved_sp = rax;
 825   __ movptr(saved_sp, r11);
 826 
 827   // Will jump to the compiled code just as if compiled code was doing it.
 828   // Pre-load the register-jump target early, to schedule it better.
 829   __ movptr(r11, Address(rbx, in_bytes(Method::from_compiled_offset())));
 830 
 831 #if INCLUDE_JVMCI
 832   if (EnableJVMCI || UseAOT) {
 833     // check if this call should be routed towards a specific entry point
 834     __ cmpptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 835     Label no_alternative_target;
 836     __ jcc(Assembler::equal, no_alternative_target);
 837     __ movptr(r11, Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())));
 838     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_alternate_call_target_offset())), 0);
 839     __ bind(no_alternative_target);
 840   }
 841 #endif // INCLUDE_JVMCI
 842 
 843   // Now generate the shuffle code.  Pick up all register args and move the
 844   // rest through the floating point stack top.
 845   for (int i = 0; i < total_args_passed; i++) {
 846     if (sig_bt[i] == T_VOID) {
 847       // Longs and doubles are passed in native word order, but misaligned
 848       // in the 32-bit build.
 849       assert(i > 0 && (sig_bt[i-1] == T_LONG || sig_bt[i-1] == T_DOUBLE), "missing half");
 850       continue;
 851     }
 852 
 853     // Pick up 0, 1 or 2 words from SP+offset.
 854 
 855     assert(!regs[i].second()->is_valid() || regs[i].first()->next() == regs[i].second(),
 856             "scrambled load targets?");
 857     // Load in argument order going down.
 858     int ld_off = (total_args_passed - i)*Interpreter::stackElementSize;
 859     // Point to interpreter value (vs. tag)
 860     int next_off = ld_off - Interpreter::stackElementSize;
 861     //
 862     //
 863     //
 864     VMReg r_1 = regs[i].first();
 865     VMReg r_2 = regs[i].second();
 866     if (!r_1->is_valid()) {
 867       assert(!r_2->is_valid(), "");
 868       continue;
 869     }
 870     if (r_1->is_stack()) {
 871       // Convert stack slot to an SP offset (+ wordSize to account for return address )
 872       int st_off = regs[i].first()->reg2stack()*VMRegImpl::stack_slot_size + wordSize;
 873 
 874       // We can use r13 as a temp here because compiled code doesn't need r13 as an input
 875       // and if we end up going thru a c2i because of a miss a reasonable value of r13
 876       // will be generated.
 877       if (!r_2->is_valid()) {
 878         // sign extend???
 879         __ movl(r13, Address(saved_sp, ld_off));
 880         __ movptr(Address(rsp, st_off), r13);
 881       } else {
 882         //
 883         // We are using two optoregs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 884         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 885         // So we must adjust where to pick up the data to match the interpreter.
 886         //
 887         // Interpreter local[n] == MSW, local[n+1] == LSW however locals
 888         // are accessed as negative so LSW is at LOW address
 889 
 890         // ld_off is MSW so get LSW
 891         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 892                            next_off : ld_off;
 893         __ movq(r13, Address(saved_sp, offset));
 894         // st_off is LSW (i.e. reg.first())
 895         __ movq(Address(rsp, st_off), r13);
 896       }
 897     } else if (r_1->is_Register()) {  // Register argument
 898       Register r = r_1->as_Register();
 899       assert(r != rax, "must be different");
 900       if (r_2->is_valid()) {
 901         //
 902         // We are using two VMRegs. This can be either T_OBJECT, T_ADDRESS, T_LONG, or T_DOUBLE
 903         // the interpreter allocates two slots but only uses one for thr T_LONG or T_DOUBLE case
 904         // So we must adjust where to pick up the data to match the interpreter.
 905 
 906         const int offset = (sig_bt[i]==T_LONG||sig_bt[i]==T_DOUBLE)?
 907                            next_off : ld_off;
 908 
 909         // this can be a misaligned move
 910         __ movq(r, Address(saved_sp, offset));
 911       } else {
 912         // sign extend and use a full word?
 913         __ movl(r, Address(saved_sp, ld_off));
 914       }
 915     } else {
 916       if (!r_2->is_valid()) {
 917         __ movflt(r_1->as_XMMRegister(), Address(saved_sp, ld_off));
 918       } else {
 919         __ movdbl(r_1->as_XMMRegister(), Address(saved_sp, next_off));
 920       }
 921     }
 922   }
 923 
 924   // 6243940 We might end up in handle_wrong_method if
 925   // the callee is deoptimized as we race thru here. If that
 926   // happens we don't want to take a safepoint because the
 927   // caller frame will look interpreted and arguments are now
 928   // "compiled" so it is much better to make this transition
 929   // invisible to the stack walking code. Unfortunately if
 930   // we try and find the callee by normal means a safepoint
 931   // is possible. So we stash the desired callee in the thread
 932   // and the vm will find there should this case occur.
 933 
 934   __ movptr(Address(r15_thread, JavaThread::callee_target_offset()), rbx);
 935 
 936   // put Method* where a c2i would expect should we end up there
 937   // only needed becaus eof c2 resolve stubs return Method* as a result in
 938   // rax
 939   __ mov(rax, rbx);
 940   __ jmp(r11);
 941 }
 942 
 943 // ---------------------------------------------------------------
 944 AdapterHandlerEntry* SharedRuntime::generate_i2c2i_adapters(MacroAssembler *masm,
 945                                                             int total_args_passed,
 946                                                             int comp_args_on_stack,
 947                                                             const BasicType *sig_bt,
 948                                                             const VMRegPair *regs,
 949                                                             AdapterFingerPrint* fingerprint) {
 950   address i2c_entry = __ pc();
 951 
 952   gen_i2c_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs);
 953 
 954   // -------------------------------------------------------------------------
 955   // Generate a C2I adapter.  On entry we know rbx holds the Method* during calls
 956   // to the interpreter.  The args start out packed in the compiled layout.  They
 957   // need to be unpacked into the interpreter layout.  This will almost always
 958   // require some stack space.  We grow the current (compiled) stack, then repack
 959   // the args.  We  finally end in a jump to the generic interpreter entry point.
 960   // On exit from the interpreter, the interpreter will restore our SP (lest the
 961   // compiled code, which relys solely on SP and not RBP, get sick).
 962 
 963   address c2i_unverified_entry = __ pc();
 964   Label skip_fixup;
 965   Label ok;
 966 
 967   Register holder = rax;
 968   Register receiver = j_rarg0;
 969   Register temp = rbx;
 970 
 971   {
 972     __ load_klass(temp, receiver);
 973     __ cmpptr(temp, Address(holder, CompiledICHolder::holder_klass_offset()));
 974     __ movptr(rbx, Address(holder, CompiledICHolder::holder_metadata_offset()));
 975     __ jcc(Assembler::equal, ok);
 976     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 977 
 978     __ bind(ok);
 979     // Method might have been compiled since the call site was patched to
 980     // interpreted if that is the case treat it as a miss so we can get
 981     // the call site corrected.
 982     __ cmpptr(Address(rbx, in_bytes(Method::code_offset())), (int32_t)NULL_WORD);
 983     __ jcc(Assembler::equal, skip_fixup);
 984     __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
 985   }
 986 
 987   address c2i_entry = __ pc();
 988 
 989   gen_c2i_adapter(masm, total_args_passed, comp_args_on_stack, sig_bt, regs, skip_fixup);
 990 
 991   __ flush();
 992   return AdapterHandlerLibrary::new_entry(fingerprint, i2c_entry, c2i_entry, c2i_unverified_entry);
 993 }
 994 
 995 int SharedRuntime::c_calling_convention(const BasicType *sig_bt,
 996                                          VMRegPair *regs,
 997                                          VMRegPair *regs2,
 998                                          int total_args_passed) {
 999   assert(regs2 == NULL, "not needed on x86");
1000 // We return the amount of VMRegImpl stack slots we need to reserve for all
1001 // the arguments NOT counting out_preserve_stack_slots.
1002 
1003 // NOTE: These arrays will have to change when c1 is ported
1004 #ifdef _WIN64
1005     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
1006       c_rarg0, c_rarg1, c_rarg2, c_rarg3
1007     };
1008     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
1009       c_farg0, c_farg1, c_farg2, c_farg3
1010     };
1011 #else
1012     static const Register INT_ArgReg[Argument::n_int_register_parameters_c] = {
1013       c_rarg0, c_rarg1, c_rarg2, c_rarg3, c_rarg4, c_rarg5
1014     };
1015     static const XMMRegister FP_ArgReg[Argument::n_float_register_parameters_c] = {
1016       c_farg0, c_farg1, c_farg2, c_farg3,
1017       c_farg4, c_farg5, c_farg6, c_farg7
1018     };
1019 #endif // _WIN64
1020 
1021 
1022     uint int_args = 0;
1023     uint fp_args = 0;
1024     uint stk_args = 0; // inc by 2 each time
1025 
1026     for (int i = 0; i < total_args_passed; i++) {
1027       switch (sig_bt[i]) {
1028       case T_BOOLEAN:
1029       case T_CHAR:
1030       case T_BYTE:
1031       case T_SHORT:
1032       case T_INT:
1033         if (int_args < Argument::n_int_register_parameters_c) {
1034           regs[i].set1(INT_ArgReg[int_args++]->as_VMReg());
1035 #ifdef _WIN64
1036           fp_args++;
1037           // Allocate slots for callee to stuff register args the stack.
1038           stk_args += 2;
1039 #endif
1040         } else {
1041           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1042           stk_args += 2;
1043         }
1044         break;
1045       case T_LONG:
1046         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1047         // fall through
1048       case T_OBJECT:
1049       case T_ARRAY:
1050       case T_ADDRESS:
1051       case T_METADATA:
1052         if (int_args < Argument::n_int_register_parameters_c) {
1053           regs[i].set2(INT_ArgReg[int_args++]->as_VMReg());
1054 #ifdef _WIN64
1055           fp_args++;
1056           stk_args += 2;
1057 #endif
1058         } else {
1059           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1060           stk_args += 2;
1061         }
1062         break;
1063       case T_FLOAT:
1064         if (fp_args < Argument::n_float_register_parameters_c) {
1065           regs[i].set1(FP_ArgReg[fp_args++]->as_VMReg());
1066 #ifdef _WIN64
1067           int_args++;
1068           // Allocate slots for callee to stuff register args the stack.
1069           stk_args += 2;
1070 #endif
1071         } else {
1072           regs[i].set1(VMRegImpl::stack2reg(stk_args));
1073           stk_args += 2;
1074         }
1075         break;
1076       case T_DOUBLE:
1077         assert((i + 1) < total_args_passed && sig_bt[i + 1] == T_VOID, "expecting half");
1078         if (fp_args < Argument::n_float_register_parameters_c) {
1079           regs[i].set2(FP_ArgReg[fp_args++]->as_VMReg());
1080 #ifdef _WIN64
1081           int_args++;
1082           // Allocate slots for callee to stuff register args the stack.
1083           stk_args += 2;
1084 #endif
1085         } else {
1086           regs[i].set2(VMRegImpl::stack2reg(stk_args));
1087           stk_args += 2;
1088         }
1089         break;
1090       case T_VOID: // Halves of longs and doubles
1091         assert(i != 0 && (sig_bt[i - 1] == T_LONG || sig_bt[i - 1] == T_DOUBLE), "expecting half");
1092         regs[i].set_bad();
1093         break;
1094       default:
1095         ShouldNotReachHere();
1096         break;
1097       }
1098     }
1099 #ifdef _WIN64
1100   // windows abi requires that we always allocate enough stack space
1101   // for 4 64bit registers to be stored down.
1102   if (stk_args < 8) {
1103     stk_args = 8;
1104   }
1105 #endif // _WIN64
1106 
1107   return stk_args;
1108 }
1109 
1110 // On 64 bit we will store integer like items to the stack as
1111 // 64 bits items (sparc abi) even though java would only store
1112 // 32bits for a parameter. On 32bit it will simply be 32 bits
1113 // So this routine will do 32->32 on 32bit and 32->64 on 64bit
1114 static void move32_64(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1115   if (src.first()->is_stack()) {
1116     if (dst.first()->is_stack()) {
1117       // stack to stack
1118       __ movslq(rax, Address(rbp, reg2offset_in(src.first())));
1119       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1120     } else {
1121       // stack to reg
1122       __ movslq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1123     }
1124   } else if (dst.first()->is_stack()) {
1125     // reg to stack
1126     // Do we really have to sign extend???
1127     // __ movslq(src.first()->as_Register(), src.first()->as_Register());
1128     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1129   } else {
1130     // Do we really have to sign extend???
1131     // __ movslq(dst.first()->as_Register(), src.first()->as_Register());
1132     if (dst.first() != src.first()) {
1133       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1134     }
1135   }
1136 }
1137 
1138 static void move_ptr(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1139   if (src.first()->is_stack()) {
1140     if (dst.first()->is_stack()) {
1141       // stack to stack
1142       __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1143       __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1144     } else {
1145       // stack to reg
1146       __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_in(src.first())));
1147     }
1148   } else if (dst.first()->is_stack()) {
1149     // reg to stack
1150     __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1151   } else {
1152     if (dst.first() != src.first()) {
1153       __ movq(dst.first()->as_Register(), src.first()->as_Register());
1154     }
1155   }
1156 }
1157 
1158 // An oop arg. Must pass a handle not the oop itself
1159 static void object_move(MacroAssembler* masm,
1160                         OopMap* map,
1161                         int oop_handle_offset,
1162                         int framesize_in_slots,
1163                         VMRegPair src,
1164                         VMRegPair dst,
1165                         bool is_receiver,
1166                         int* receiver_offset) {
1167 
1168   // must pass a handle. First figure out the location we use as a handle
1169 
1170   Register rHandle = dst.first()->is_stack() ? rax : dst.first()->as_Register();
1171 
1172   // See if oop is NULL if it is we need no handle
1173 
1174   if (src.first()->is_stack()) {
1175 
1176     // Oop is already on the stack as an argument
1177     int offset_in_older_frame = src.first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1178     map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + framesize_in_slots));
1179     if (is_receiver) {
1180       *receiver_offset = (offset_in_older_frame + framesize_in_slots) * VMRegImpl::stack_slot_size;
1181     }
1182 
1183     __ cmpptr(Address(rbp, reg2offset_in(src.first())), (int32_t)NULL_WORD);
1184     __ lea(rHandle, Address(rbp, reg2offset_in(src.first())));
1185     // conditionally move a NULL
1186     __ cmovptr(Assembler::equal, rHandle, Address(rbp, reg2offset_in(src.first())));
1187   } else {
1188 
1189     // Oop is in an a register we must store it to the space we reserve
1190     // on the stack for oop_handles and pass a handle if oop is non-NULL
1191 
1192     const Register rOop = src.first()->as_Register();
1193     int oop_slot;
1194     if (rOop == j_rarg0)
1195       oop_slot = 0;
1196     else if (rOop == j_rarg1)
1197       oop_slot = 1;
1198     else if (rOop == j_rarg2)
1199       oop_slot = 2;
1200     else if (rOop == j_rarg3)
1201       oop_slot = 3;
1202     else if (rOop == j_rarg4)
1203       oop_slot = 4;
1204     else {
1205       assert(rOop == j_rarg5, "wrong register");
1206       oop_slot = 5;
1207     }
1208 
1209     oop_slot = oop_slot * VMRegImpl::slots_per_word + oop_handle_offset;
1210     int offset = oop_slot*VMRegImpl::stack_slot_size;
1211 
1212     map->set_oop(VMRegImpl::stack2reg(oop_slot));
1213     // Store oop in handle area, may be NULL
1214     __ movptr(Address(rsp, offset), rOop);
1215     if (is_receiver) {
1216       *receiver_offset = offset;
1217     }
1218 
1219     __ cmpptr(rOop, (int32_t)NULL_WORD);
1220     __ lea(rHandle, Address(rsp, offset));
1221     // conditionally move a NULL from the handle area where it was just stored
1222     __ cmovptr(Assembler::equal, rHandle, Address(rsp, offset));
1223   }
1224 
1225   // If arg is on the stack then place it otherwise it is already in correct reg.
1226   if (dst.first()->is_stack()) {
1227     __ movptr(Address(rsp, reg2offset_out(dst.first())), rHandle);
1228   }
1229 }
1230 
1231 // A float arg may have to do float reg int reg conversion
1232 static void float_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1233   assert(!src.second()->is_valid() && !dst.second()->is_valid(), "bad float_move");
1234 
1235   // The calling conventions assures us that each VMregpair is either
1236   // all really one physical register or adjacent stack slots.
1237   // This greatly simplifies the cases here compared to sparc.
1238 
1239   if (src.first()->is_stack()) {
1240     if (dst.first()->is_stack()) {
1241       __ movl(rax, Address(rbp, reg2offset_in(src.first())));
1242       __ movptr(Address(rsp, reg2offset_out(dst.first())), rax);
1243     } else {
1244       // stack to reg
1245       assert(dst.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1246       __ movflt(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_in(src.first())));
1247     }
1248   } else if (dst.first()->is_stack()) {
1249     // reg to stack
1250     assert(src.first()->is_XMMRegister(), "only expect xmm registers as parameters");
1251     __ movflt(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1252   } else {
1253     // reg to reg
1254     // In theory these overlap but the ordering is such that this is likely a nop
1255     if ( src.first() != dst.first()) {
1256       __ movdbl(dst.first()->as_XMMRegister(),  src.first()->as_XMMRegister());
1257     }
1258   }
1259 }
1260 
1261 // A long move
1262 static void long_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1263 
1264   // The calling conventions assures us that each VMregpair is either
1265   // all really one physical register or adjacent stack slots.
1266   // This greatly simplifies the cases here compared to sparc.
1267 
1268   if (src.is_single_phys_reg() ) {
1269     if (dst.is_single_phys_reg()) {
1270       if (dst.first() != src.first()) {
1271         __ mov(dst.first()->as_Register(), src.first()->as_Register());
1272       }
1273     } else {
1274       assert(dst.is_single_reg(), "not a stack pair");
1275       __ movq(Address(rsp, reg2offset_out(dst.first())), src.first()->as_Register());
1276     }
1277   } else if (dst.is_single_phys_reg()) {
1278     assert(src.is_single_reg(),  "not a stack pair");
1279     __ movq(dst.first()->as_Register(), Address(rbp, reg2offset_out(src.first())));
1280   } else {
1281     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1282     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1283     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1284   }
1285 }
1286 
1287 // A double move
1288 static void double_move(MacroAssembler* masm, VMRegPair src, VMRegPair dst) {
1289 
1290   // The calling conventions assures us that each VMregpair is either
1291   // all really one physical register or adjacent stack slots.
1292   // This greatly simplifies the cases here compared to sparc.
1293 
1294   if (src.is_single_phys_reg() ) {
1295     if (dst.is_single_phys_reg()) {
1296       // In theory these overlap but the ordering is such that this is likely a nop
1297       if ( src.first() != dst.first()) {
1298         __ movdbl(dst.first()->as_XMMRegister(), src.first()->as_XMMRegister());
1299       }
1300     } else {
1301       assert(dst.is_single_reg(), "not a stack pair");
1302       __ movdbl(Address(rsp, reg2offset_out(dst.first())), src.first()->as_XMMRegister());
1303     }
1304   } else if (dst.is_single_phys_reg()) {
1305     assert(src.is_single_reg(),  "not a stack pair");
1306     __ movdbl(dst.first()->as_XMMRegister(), Address(rbp, reg2offset_out(src.first())));
1307   } else {
1308     assert(src.is_single_reg() && dst.is_single_reg(), "not stack pairs");
1309     __ movq(rax, Address(rbp, reg2offset_in(src.first())));
1310     __ movq(Address(rsp, reg2offset_out(dst.first())), rax);
1311   }
1312 }
1313 
1314 
1315 void SharedRuntime::save_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1316   // We always ignore the frame_slots arg and just use the space just below frame pointer
1317   // which by this time is free to use
1318   switch (ret_type) {
1319   case T_FLOAT:
1320     __ movflt(Address(rbp, -wordSize), xmm0);
1321     break;
1322   case T_DOUBLE:
1323     __ movdbl(Address(rbp, -wordSize), xmm0);
1324     break;
1325   case T_VOID:  break;
1326   default: {
1327     __ movptr(Address(rbp, -wordSize), rax);
1328     }
1329   }
1330 }
1331 
1332 void SharedRuntime::restore_native_result(MacroAssembler *masm, BasicType ret_type, int frame_slots) {
1333   // We always ignore the frame_slots arg and just use the space just below frame pointer
1334   // which by this time is free to use
1335   switch (ret_type) {
1336   case T_FLOAT:
1337     __ movflt(xmm0, Address(rbp, -wordSize));
1338     break;
1339   case T_DOUBLE:
1340     __ movdbl(xmm0, Address(rbp, -wordSize));
1341     break;
1342   case T_VOID:  break;
1343   default: {
1344     __ movptr(rax, Address(rbp, -wordSize));
1345     }
1346   }
1347 }
1348 
1349 static void save_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1350     for ( int i = first_arg ; i < arg_count ; i++ ) {
1351       if (args[i].first()->is_Register()) {
1352         __ push(args[i].first()->as_Register());
1353       } else if (args[i].first()->is_XMMRegister()) {
1354         __ subptr(rsp, 2*wordSize);
1355         __ movdbl(Address(rsp, 0), args[i].first()->as_XMMRegister());
1356       }
1357     }
1358 }
1359 
1360 static void restore_args(MacroAssembler *masm, int arg_count, int first_arg, VMRegPair *args) {
1361     for ( int i = arg_count - 1 ; i >= first_arg ; i-- ) {
1362       if (args[i].first()->is_Register()) {
1363         __ pop(args[i].first()->as_Register());
1364       } else if (args[i].first()->is_XMMRegister()) {
1365         __ movdbl(args[i].first()->as_XMMRegister(), Address(rsp, 0));
1366         __ addptr(rsp, 2*wordSize);
1367       }
1368     }
1369 }
1370 
1371 
1372 static void save_or_restore_arguments(MacroAssembler* masm,
1373                                       const int stack_slots,
1374                                       const int total_in_args,
1375                                       const int arg_save_area,
1376                                       OopMap* map,
1377                                       VMRegPair* in_regs,
1378                                       BasicType* in_sig_bt) {
1379   // if map is non-NULL then the code should store the values,
1380   // otherwise it should load them.
1381   int slot = arg_save_area;
1382   // Save down double word first
1383   for ( int i = 0; i < total_in_args; i++) {
1384     if (in_regs[i].first()->is_XMMRegister() && in_sig_bt[i] == T_DOUBLE) {
1385       int offset = slot * VMRegImpl::stack_slot_size;
1386       slot += VMRegImpl::slots_per_word;
1387       assert(slot <= stack_slots, "overflow");
1388       if (map != NULL) {
1389         __ movdbl(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1390       } else {
1391         __ movdbl(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1392       }
1393     }
1394     if (in_regs[i].first()->is_Register() &&
1395         (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_ARRAY)) {
1396       int offset = slot * VMRegImpl::stack_slot_size;
1397       if (map != NULL) {
1398         __ movq(Address(rsp, offset), in_regs[i].first()->as_Register());
1399         if (in_sig_bt[i] == T_ARRAY) {
1400           map->set_oop(VMRegImpl::stack2reg(slot));;
1401         }
1402       } else {
1403         __ movq(in_regs[i].first()->as_Register(), Address(rsp, offset));
1404       }
1405       slot += VMRegImpl::slots_per_word;
1406     }
1407   }
1408   // Save or restore single word registers
1409   for ( int i = 0; i < total_in_args; i++) {
1410     if (in_regs[i].first()->is_Register()) {
1411       int offset = slot * VMRegImpl::stack_slot_size;
1412       slot++;
1413       assert(slot <= stack_slots, "overflow");
1414 
1415       // Value is in an input register pass we must flush it to the stack
1416       const Register reg = in_regs[i].first()->as_Register();
1417       switch (in_sig_bt[i]) {
1418         case T_BOOLEAN:
1419         case T_CHAR:
1420         case T_BYTE:
1421         case T_SHORT:
1422         case T_INT:
1423           if (map != NULL) {
1424             __ movl(Address(rsp, offset), reg);
1425           } else {
1426             __ movl(reg, Address(rsp, offset));
1427           }
1428           break;
1429         case T_ARRAY:
1430         case T_LONG:
1431           // handled above
1432           break;
1433         case T_OBJECT:
1434         default: ShouldNotReachHere();
1435       }
1436     } else if (in_regs[i].first()->is_XMMRegister()) {
1437       if (in_sig_bt[i] == T_FLOAT) {
1438         int offset = slot * VMRegImpl::stack_slot_size;
1439         slot++;
1440         assert(slot <= stack_slots, "overflow");
1441         if (map != NULL) {
1442           __ movflt(Address(rsp, offset), in_regs[i].first()->as_XMMRegister());
1443         } else {
1444           __ movflt(in_regs[i].first()->as_XMMRegister(), Address(rsp, offset));
1445         }
1446       }
1447     } else if (in_regs[i].first()->is_stack()) {
1448       if (in_sig_bt[i] == T_ARRAY && map != NULL) {
1449         int offset_in_older_frame = in_regs[i].first()->reg2stack() + SharedRuntime::out_preserve_stack_slots();
1450         map->set_oop(VMRegImpl::stack2reg(offset_in_older_frame + stack_slots));
1451       }
1452     }
1453   }
1454 }
1455 
1456 
1457 // Check GCLocker::needs_gc and enter the runtime if it's true.  This
1458 // keeps a new JNI critical region from starting until a GC has been
1459 // forced.  Save down any oops in registers and describe them in an
1460 // OopMap.
1461 static void check_needs_gc_for_critical_native(MacroAssembler* masm,
1462                                                int stack_slots,
1463                                                int total_c_args,
1464                                                int total_in_args,
1465                                                int arg_save_area,
1466                                                OopMapSet* oop_maps,
1467                                                VMRegPair* in_regs,
1468                                                BasicType* in_sig_bt) {
1469   __ block_comment("check GCLocker::needs_gc");
1470   Label cont;
1471   __ cmp8(ExternalAddress((address)GCLocker::needs_gc_address()), false);
1472   __ jcc(Assembler::equal, cont);
1473 
1474   // Save down any incoming oops and call into the runtime to halt for a GC
1475 
1476   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1477   save_or_restore_arguments(masm, stack_slots, total_in_args,
1478                             arg_save_area, map, in_regs, in_sig_bt);
1479 
1480   address the_pc = __ pc();
1481   oop_maps->add_gc_map( __ offset(), map);
1482   __ set_last_Java_frame(rsp, noreg, the_pc);
1483 
1484   __ block_comment("block_for_jni_critical");
1485   __ movptr(c_rarg0, r15_thread);
1486   __ mov(r12, rsp); // remember sp
1487   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
1488   __ andptr(rsp, -16); // align stack as required by ABI
1489   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::block_for_jni_critical)));
1490   __ mov(rsp, r12); // restore sp
1491   __ reinit_heapbase();
1492 
1493   __ reset_last_Java_frame(false);
1494 
1495   save_or_restore_arguments(masm, stack_slots, total_in_args,
1496                             arg_save_area, NULL, in_regs, in_sig_bt);
1497   __ bind(cont);
1498 #ifdef ASSERT
1499   if (StressCriticalJNINatives) {
1500     // Stress register saving
1501     OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
1502     save_or_restore_arguments(masm, stack_slots, total_in_args,
1503                               arg_save_area, map, in_regs, in_sig_bt);
1504     // Destroy argument registers
1505     for (int i = 0; i < total_in_args - 1; i++) {
1506       if (in_regs[i].first()->is_Register()) {
1507         const Register reg = in_regs[i].first()->as_Register();
1508         __ xorptr(reg, reg);
1509       } else if (in_regs[i].first()->is_XMMRegister()) {
1510         __ xorpd(in_regs[i].first()->as_XMMRegister(), in_regs[i].first()->as_XMMRegister());
1511       } else if (in_regs[i].first()->is_FloatRegister()) {
1512         ShouldNotReachHere();
1513       } else if (in_regs[i].first()->is_stack()) {
1514         // Nothing to do
1515       } else {
1516         ShouldNotReachHere();
1517       }
1518       if (in_sig_bt[i] == T_LONG || in_sig_bt[i] == T_DOUBLE) {
1519         i++;
1520       }
1521     }
1522 
1523     save_or_restore_arguments(masm, stack_slots, total_in_args,
1524                               arg_save_area, NULL, in_regs, in_sig_bt);
1525   }
1526 #endif
1527 }
1528 
1529 // Unpack an array argument into a pointer to the body and the length
1530 // if the array is non-null, otherwise pass 0 for both.
1531 static void unpack_array_argument(MacroAssembler* masm, VMRegPair reg, BasicType in_elem_type, VMRegPair body_arg, VMRegPair length_arg) {
1532   Register tmp_reg = rax;
1533   assert(!body_arg.first()->is_Register() || body_arg.first()->as_Register() != tmp_reg,
1534          "possible collision");
1535   assert(!length_arg.first()->is_Register() || length_arg.first()->as_Register() != tmp_reg,
1536          "possible collision");
1537 
1538   __ block_comment("unpack_array_argument {");
1539 
1540   // Pass the length, ptr pair
1541   Label is_null, done;
1542   VMRegPair tmp;
1543   tmp.set_ptr(tmp_reg->as_VMReg());
1544   if (reg.first()->is_stack()) {
1545     // Load the arg up from the stack
1546     move_ptr(masm, reg, tmp);
1547     reg = tmp;
1548   }
1549   __ testptr(reg.first()->as_Register(), reg.first()->as_Register());
1550   __ jccb(Assembler::equal, is_null);
1551   __ lea(tmp_reg, Address(reg.first()->as_Register(), arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1552   move_ptr(masm, tmp, body_arg);
1553   // load the length relative to the body.
1554   __ movl(tmp_reg, Address(tmp_reg, arrayOopDesc::length_offset_in_bytes() -
1555                            arrayOopDesc::base_offset_in_bytes(in_elem_type)));
1556   move32_64(masm, tmp, length_arg);
1557   __ jmpb(done);
1558   __ bind(is_null);
1559   // Pass zeros
1560   __ xorptr(tmp_reg, tmp_reg);
1561   move_ptr(masm, tmp, body_arg);
1562   move32_64(masm, tmp, length_arg);
1563   __ bind(done);
1564 
1565   __ block_comment("} unpack_array_argument");
1566 }
1567 
1568 
1569 // Different signatures may require very different orders for the move
1570 // to avoid clobbering other arguments.  There's no simple way to
1571 // order them safely.  Compute a safe order for issuing stores and
1572 // break any cycles in those stores.  This code is fairly general but
1573 // it's not necessary on the other platforms so we keep it in the
1574 // platform dependent code instead of moving it into a shared file.
1575 // (See bugs 7013347 & 7145024.)
1576 // Note that this code is specific to LP64.
1577 class ComputeMoveOrder: public StackObj {
1578   class MoveOperation: public ResourceObj {
1579     friend class ComputeMoveOrder;
1580    private:
1581     VMRegPair        _src;
1582     VMRegPair        _dst;
1583     int              _src_index;
1584     int              _dst_index;
1585     bool             _processed;
1586     MoveOperation*  _next;
1587     MoveOperation*  _prev;
1588 
1589     static int get_id(VMRegPair r) {
1590       return r.first()->value();
1591     }
1592 
1593    public:
1594     MoveOperation(int src_index, VMRegPair src, int dst_index, VMRegPair dst):
1595       _src(src)
1596     , _src_index(src_index)
1597     , _dst(dst)
1598     , _dst_index(dst_index)
1599     , _next(NULL)
1600     , _prev(NULL)
1601     , _processed(false) {
1602     }
1603 
1604     VMRegPair src() const              { return _src; }
1605     int src_id() const                 { return get_id(src()); }
1606     int src_index() const              { return _src_index; }
1607     VMRegPair dst() const              { return _dst; }
1608     void set_dst(int i, VMRegPair dst) { _dst_index = i, _dst = dst; }
1609     int dst_index() const              { return _dst_index; }
1610     int dst_id() const                 { return get_id(dst()); }
1611     MoveOperation* next() const       { return _next; }
1612     MoveOperation* prev() const       { return _prev; }
1613     void set_processed()               { _processed = true; }
1614     bool is_processed() const          { return _processed; }
1615 
1616     // insert
1617     void break_cycle(VMRegPair temp_register) {
1618       // create a new store following the last store
1619       // to move from the temp_register to the original
1620       MoveOperation* new_store = new MoveOperation(-1, temp_register, dst_index(), dst());
1621 
1622       // break the cycle of links and insert new_store at the end
1623       // break the reverse link.
1624       MoveOperation* p = prev();
1625       assert(p->next() == this, "must be");
1626       _prev = NULL;
1627       p->_next = new_store;
1628       new_store->_prev = p;
1629 
1630       // change the original store to save it's value in the temp.
1631       set_dst(-1, temp_register);
1632     }
1633 
1634     void link(GrowableArray<MoveOperation*>& killer) {
1635       // link this store in front the store that it depends on
1636       MoveOperation* n = killer.at_grow(src_id(), NULL);
1637       if (n != NULL) {
1638         assert(_next == NULL && n->_prev == NULL, "shouldn't have been set yet");
1639         _next = n;
1640         n->_prev = this;
1641       }
1642     }
1643   };
1644 
1645  private:
1646   GrowableArray<MoveOperation*> edges;
1647 
1648  public:
1649   ComputeMoveOrder(int total_in_args, VMRegPair* in_regs, int total_c_args, VMRegPair* out_regs,
1650                     BasicType* in_sig_bt, GrowableArray<int>& arg_order, VMRegPair tmp_vmreg) {
1651     // Move operations where the dest is the stack can all be
1652     // scheduled first since they can't interfere with the other moves.
1653     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
1654       if (in_sig_bt[i] == T_ARRAY) {
1655         c_arg--;
1656         if (out_regs[c_arg].first()->is_stack() &&
1657             out_regs[c_arg + 1].first()->is_stack()) {
1658           arg_order.push(i);
1659           arg_order.push(c_arg);
1660         } else {
1661           if (out_regs[c_arg].first()->is_stack() ||
1662               in_regs[i].first() == out_regs[c_arg].first()) {
1663             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg + 1]);
1664           } else {
1665             add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1666           }
1667         }
1668       } else if (in_sig_bt[i] == T_VOID) {
1669         arg_order.push(i);
1670         arg_order.push(c_arg);
1671       } else {
1672         if (out_regs[c_arg].first()->is_stack() ||
1673             in_regs[i].first() == out_regs[c_arg].first()) {
1674           arg_order.push(i);
1675           arg_order.push(c_arg);
1676         } else {
1677           add_edge(i, in_regs[i].first(), c_arg, out_regs[c_arg]);
1678         }
1679       }
1680     }
1681     // Break any cycles in the register moves and emit the in the
1682     // proper order.
1683     GrowableArray<MoveOperation*>* stores = get_store_order(tmp_vmreg);
1684     for (int i = 0; i < stores->length(); i++) {
1685       arg_order.push(stores->at(i)->src_index());
1686       arg_order.push(stores->at(i)->dst_index());
1687     }
1688  }
1689 
1690   // Collected all the move operations
1691   void add_edge(int src_index, VMRegPair src, int dst_index, VMRegPair dst) {
1692     if (src.first() == dst.first()) return;
1693     edges.append(new MoveOperation(src_index, src, dst_index, dst));
1694   }
1695 
1696   // Walk the edges breaking cycles between moves.  The result list
1697   // can be walked in order to produce the proper set of loads
1698   GrowableArray<MoveOperation*>* get_store_order(VMRegPair temp_register) {
1699     // Record which moves kill which values
1700     GrowableArray<MoveOperation*> killer;
1701     for (int i = 0; i < edges.length(); i++) {
1702       MoveOperation* s = edges.at(i);
1703       assert(killer.at_grow(s->dst_id(), NULL) == NULL, "only one killer");
1704       killer.at_put_grow(s->dst_id(), s, NULL);
1705     }
1706     assert(killer.at_grow(MoveOperation::get_id(temp_register), NULL) == NULL,
1707            "make sure temp isn't in the registers that are killed");
1708 
1709     // create links between loads and stores
1710     for (int i = 0; i < edges.length(); i++) {
1711       edges.at(i)->link(killer);
1712     }
1713 
1714     // at this point, all the move operations are chained together
1715     // in a doubly linked list.  Processing it backwards finds
1716     // the beginning of the chain, forwards finds the end.  If there's
1717     // a cycle it can be broken at any point,  so pick an edge and walk
1718     // backward until the list ends or we end where we started.
1719     GrowableArray<MoveOperation*>* stores = new GrowableArray<MoveOperation*>();
1720     for (int e = 0; e < edges.length(); e++) {
1721       MoveOperation* s = edges.at(e);
1722       if (!s->is_processed()) {
1723         MoveOperation* start = s;
1724         // search for the beginning of the chain or cycle
1725         while (start->prev() != NULL && start->prev() != s) {
1726           start = start->prev();
1727         }
1728         if (start->prev() == s) {
1729           start->break_cycle(temp_register);
1730         }
1731         // walk the chain forward inserting to store list
1732         while (start != NULL) {
1733           stores->append(start);
1734           start->set_processed();
1735           start = start->next();
1736         }
1737       }
1738     }
1739     return stores;
1740   }
1741 };
1742 
1743 static void verify_oop_args(MacroAssembler* masm,
1744                             const methodHandle& method,
1745                             const BasicType* sig_bt,
1746                             const VMRegPair* regs) {
1747   Register temp_reg = rbx;  // not part of any compiled calling seq
1748   if (VerifyOops) {
1749     for (int i = 0; i < method->size_of_parameters(); i++) {
1750       if (sig_bt[i] == T_OBJECT ||
1751           sig_bt[i] == T_ARRAY) {
1752         VMReg r = regs[i].first();
1753         assert(r->is_valid(), "bad oop arg");
1754         if (r->is_stack()) {
1755           __ movptr(temp_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1756           __ verify_oop(temp_reg);
1757         } else {
1758           __ verify_oop(r->as_Register());
1759         }
1760       }
1761     }
1762   }
1763 }
1764 
1765 static void gen_special_dispatch(MacroAssembler* masm,
1766                                  const methodHandle& method,
1767                                  const BasicType* sig_bt,
1768                                  const VMRegPair* regs) {
1769   verify_oop_args(masm, method, sig_bt, regs);
1770   vmIntrinsics::ID iid = method->intrinsic_id();
1771 
1772   // Now write the args into the outgoing interpreter space
1773   bool     has_receiver   = false;
1774   Register receiver_reg   = noreg;
1775   int      member_arg_pos = -1;
1776   Register member_reg     = noreg;
1777   int      ref_kind       = MethodHandles::signature_polymorphic_intrinsic_ref_kind(iid);
1778   if (ref_kind != 0) {
1779     member_arg_pos = method->size_of_parameters() - 1;  // trailing MemberName argument
1780     member_reg = rbx;  // known to be free at this point
1781     has_receiver = MethodHandles::ref_kind_has_receiver(ref_kind);
1782   } else if (iid == vmIntrinsics::_invokeBasic) {
1783     has_receiver = true;
1784   } else {
1785     fatal("unexpected intrinsic id %d", iid);
1786   }
1787 
1788   if (member_reg != noreg) {
1789     // Load the member_arg into register, if necessary.
1790     SharedRuntime::check_member_name_argument_is_last_argument(method, sig_bt, regs);
1791     VMReg r = regs[member_arg_pos].first();
1792     if (r->is_stack()) {
1793       __ movptr(member_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1794     } else {
1795       // no data motion is needed
1796       member_reg = r->as_Register();
1797     }
1798   }
1799 
1800   if (has_receiver) {
1801     // Make sure the receiver is loaded into a register.
1802     assert(method->size_of_parameters() > 0, "oob");
1803     assert(sig_bt[0] == T_OBJECT, "receiver argument must be an object");
1804     VMReg r = regs[0].first();
1805     assert(r->is_valid(), "bad receiver arg");
1806     if (r->is_stack()) {
1807       // Porting note:  This assumes that compiled calling conventions always
1808       // pass the receiver oop in a register.  If this is not true on some
1809       // platform, pick a temp and load the receiver from stack.
1810       fatal("receiver always in a register");
1811       receiver_reg = j_rarg0;  // known to be free at this point
1812       __ movptr(receiver_reg, Address(rsp, r->reg2stack() * VMRegImpl::stack_slot_size + wordSize));
1813     } else {
1814       // no data motion is needed
1815       receiver_reg = r->as_Register();
1816     }
1817   }
1818 
1819   // Figure out which address we are really jumping to:
1820   MethodHandles::generate_method_handle_dispatch(masm, iid,
1821                                                  receiver_reg, member_reg, /*for_compiler_entry:*/ true);
1822 }
1823 
1824 // ---------------------------------------------------------------------------
1825 // Generate a native wrapper for a given method.  The method takes arguments
1826 // in the Java compiled code convention, marshals them to the native
1827 // convention (handlizes oops, etc), transitions to native, makes the call,
1828 // returns to java state (possibly blocking), unhandlizes any result and
1829 // returns.
1830 //
1831 // Critical native functions are a shorthand for the use of
1832 // GetPrimtiveArrayCritical and disallow the use of any other JNI
1833 // functions.  The wrapper is expected to unpack the arguments before
1834 // passing them to the callee and perform checks before and after the
1835 // native call to ensure that they GCLocker
1836 // lock_critical/unlock_critical semantics are followed.  Some other
1837 // parts of JNI setup are skipped like the tear down of the JNI handle
1838 // block and the check for pending exceptions it's impossible for them
1839 // to be thrown.
1840 //
1841 // They are roughly structured like this:
1842 //    if (GCLocker::needs_gc())
1843 //      SharedRuntime::block_for_jni_critical();
1844 //    tranistion to thread_in_native
1845 //    unpack arrray arguments and call native entry point
1846 //    check for safepoint in progress
1847 //    check if any thread suspend flags are set
1848 //      call into JVM and possible unlock the JNI critical
1849 //      if a GC was suppressed while in the critical native.
1850 //    transition back to thread_in_Java
1851 //    return to caller
1852 //
1853 nmethod* SharedRuntime::generate_native_wrapper(MacroAssembler* masm,
1854                                                 const methodHandle& method,
1855                                                 int compile_id,
1856                                                 BasicType* in_sig_bt,
1857                                                 VMRegPair* in_regs,
1858                                                 BasicType ret_type,
1859                                                 address critical_entry) {
1860   if (method->is_method_handle_intrinsic()) {
1861     vmIntrinsics::ID iid = method->intrinsic_id();
1862     intptr_t start = (intptr_t)__ pc();
1863     int vep_offset = ((intptr_t)__ pc()) - start;
1864     gen_special_dispatch(masm,
1865                          method,
1866                          in_sig_bt,
1867                          in_regs);
1868     int frame_complete = ((intptr_t)__ pc()) - start;  // not complete, period
1869     __ flush();
1870     int stack_slots = SharedRuntime::out_preserve_stack_slots();  // no out slots at all, actually
1871     return nmethod::new_native_nmethod(method,
1872                                        compile_id,
1873                                        masm->code(),
1874                                        vep_offset,
1875                                        frame_complete,
1876                                        stack_slots / VMRegImpl::slots_per_word,
1877                                        in_ByteSize(-1),
1878                                        in_ByteSize(-1),
1879                                        (OopMapSet*)NULL);
1880   }
1881   bool is_critical_native = true;
1882   address native_func = critical_entry;
1883   if (native_func == NULL) {
1884     native_func = method->native_function();
1885     is_critical_native = false;
1886   }
1887   assert(native_func != NULL, "must have function");
1888 
1889   // An OopMap for lock (and class if static)
1890   OopMapSet *oop_maps = new OopMapSet();
1891   intptr_t start = (intptr_t)__ pc();
1892 
1893   // We have received a description of where all the java arg are located
1894   // on entry to the wrapper. We need to convert these args to where
1895   // the jni function will expect them. To figure out where they go
1896   // we convert the java signature to a C signature by inserting
1897   // the hidden arguments as arg[0] and possibly arg[1] (static method)
1898 
1899   const int total_in_args = method->size_of_parameters();
1900   int total_c_args = total_in_args;
1901   if (!is_critical_native) {
1902     total_c_args += 1;
1903     if (method->is_static()) {
1904       total_c_args++;
1905     }
1906   } else {
1907     for (int i = 0; i < total_in_args; i++) {
1908       if (in_sig_bt[i] == T_ARRAY) {
1909         total_c_args++;
1910       }
1911     }
1912   }
1913 
1914   BasicType* out_sig_bt = NEW_RESOURCE_ARRAY(BasicType, total_c_args);
1915   VMRegPair* out_regs   = NEW_RESOURCE_ARRAY(VMRegPair, total_c_args);
1916   BasicType* in_elem_bt = NULL;
1917 
1918   int argc = 0;
1919   if (!is_critical_native) {
1920     out_sig_bt[argc++] = T_ADDRESS;
1921     if (method->is_static()) {
1922       out_sig_bt[argc++] = T_OBJECT;
1923     }
1924 
1925     for (int i = 0; i < total_in_args ; i++ ) {
1926       out_sig_bt[argc++] = in_sig_bt[i];
1927     }
1928   } else {
1929     Thread* THREAD = Thread::current();
1930     in_elem_bt = NEW_RESOURCE_ARRAY(BasicType, total_in_args);
1931     SignatureStream ss(method->signature());
1932     for (int i = 0; i < total_in_args ; i++ ) {
1933       if (in_sig_bt[i] == T_ARRAY) {
1934         // Arrays are passed as int, elem* pair
1935         out_sig_bt[argc++] = T_INT;
1936         out_sig_bt[argc++] = T_ADDRESS;
1937         Symbol* atype = ss.as_symbol(CHECK_NULL);
1938         const char* at = atype->as_C_string();
1939         if (strlen(at) == 2) {
1940           assert(at[0] == '[', "must be");
1941           switch (at[1]) {
1942             case 'B': in_elem_bt[i]  = T_BYTE; break;
1943             case 'C': in_elem_bt[i]  = T_CHAR; break;
1944             case 'D': in_elem_bt[i]  = T_DOUBLE; break;
1945             case 'F': in_elem_bt[i]  = T_FLOAT; break;
1946             case 'I': in_elem_bt[i]  = T_INT; break;
1947             case 'J': in_elem_bt[i]  = T_LONG; break;
1948             case 'S': in_elem_bt[i]  = T_SHORT; break;
1949             case 'Z': in_elem_bt[i]  = T_BOOLEAN; break;
1950             default: ShouldNotReachHere();
1951           }
1952         }
1953       } else {
1954         out_sig_bt[argc++] = in_sig_bt[i];
1955         in_elem_bt[i] = T_VOID;
1956       }
1957       if (in_sig_bt[i] != T_VOID) {
1958         assert(in_sig_bt[i] == ss.type(), "must match");
1959         ss.next();
1960       }
1961     }
1962   }
1963 
1964   // Now figure out where the args must be stored and how much stack space
1965   // they require.
1966   int out_arg_slots;
1967   out_arg_slots = c_calling_convention(out_sig_bt, out_regs, NULL, total_c_args);
1968 
1969   // Compute framesize for the wrapper.  We need to handlize all oops in
1970   // incoming registers
1971 
1972   // Calculate the total number of stack slots we will need.
1973 
1974   // First count the abi requirement plus all of the outgoing args
1975   int stack_slots = SharedRuntime::out_preserve_stack_slots() + out_arg_slots;
1976 
1977   // Now the space for the inbound oop handle area
1978   int total_save_slots = 6 * VMRegImpl::slots_per_word;  // 6 arguments passed in registers
1979   if (is_critical_native) {
1980     // Critical natives may have to call out so they need a save area
1981     // for register arguments.
1982     int double_slots = 0;
1983     int single_slots = 0;
1984     for ( int i = 0; i < total_in_args; i++) {
1985       if (in_regs[i].first()->is_Register()) {
1986         const Register reg = in_regs[i].first()->as_Register();
1987         switch (in_sig_bt[i]) {
1988           case T_BOOLEAN:
1989           case T_BYTE:
1990           case T_SHORT:
1991           case T_CHAR:
1992           case T_INT:  single_slots++; break;
1993           case T_ARRAY:  // specific to LP64 (7145024)
1994           case T_LONG: double_slots++; break;
1995           default:  ShouldNotReachHere();
1996         }
1997       } else if (in_regs[i].first()->is_XMMRegister()) {
1998         switch (in_sig_bt[i]) {
1999           case T_FLOAT:  single_slots++; break;
2000           case T_DOUBLE: double_slots++; break;
2001           default:  ShouldNotReachHere();
2002         }
2003       } else if (in_regs[i].first()->is_FloatRegister()) {
2004         ShouldNotReachHere();
2005       }
2006     }
2007     total_save_slots = double_slots * 2 + single_slots;
2008     // align the save area
2009     if (double_slots != 0) {
2010       stack_slots = align_up(stack_slots, 2);
2011     }
2012   }
2013 
2014   int oop_handle_offset = stack_slots;
2015   stack_slots += total_save_slots;
2016 
2017   // Now any space we need for handlizing a klass if static method
2018 
2019   int klass_slot_offset = 0;
2020   int klass_offset = -1;
2021   int lock_slot_offset = 0;
2022   bool is_static = false;
2023 
2024   if (method->is_static()) {
2025     klass_slot_offset = stack_slots;
2026     stack_slots += VMRegImpl::slots_per_word;
2027     klass_offset = klass_slot_offset * VMRegImpl::stack_slot_size;
2028     is_static = true;
2029   }
2030 
2031   // Plus a lock if needed
2032 
2033   if (method->is_synchronized()) {
2034     lock_slot_offset = stack_slots;
2035     stack_slots += VMRegImpl::slots_per_word;
2036   }
2037 
2038   // Now a place (+2) to save return values or temp during shuffling
2039   // + 4 for return address (which we own) and saved rbp
2040   stack_slots += 6;
2041 
2042   // Ok The space we have allocated will look like:
2043   //
2044   //
2045   // FP-> |                     |
2046   //      |---------------------|
2047   //      | 2 slots for moves   |
2048   //      |---------------------|
2049   //      | lock box (if sync)  |
2050   //      |---------------------| <- lock_slot_offset
2051   //      | klass (if static)   |
2052   //      |---------------------| <- klass_slot_offset
2053   //      | oopHandle area      |
2054   //      |---------------------| <- oop_handle_offset (6 java arg registers)
2055   //      | outbound memory     |
2056   //      | based arguments     |
2057   //      |                     |
2058   //      |---------------------|
2059   //      |                     |
2060   // SP-> | out_preserved_slots |
2061   //
2062   //
2063 
2064 
2065   // Now compute actual number of stack words we need rounding to make
2066   // stack properly aligned.
2067   stack_slots = align_up(stack_slots, StackAlignmentInSlots);
2068 
2069   int stack_size = stack_slots * VMRegImpl::stack_slot_size;
2070 
2071   // First thing make an ic check to see if we should even be here
2072 
2073   // We are free to use all registers as temps without saving them and
2074   // restoring them except rbp. rbp is the only callee save register
2075   // as far as the interpreter and the compiler(s) are concerned.
2076 
2077 
2078   const Register ic_reg = rax;
2079   const Register receiver = j_rarg0;
2080 
2081   Label hit;
2082   Label exception_pending;
2083 
2084   assert_different_registers(ic_reg, receiver, rscratch1);
2085   __ verify_oop(receiver);
2086   __ load_klass(rscratch1, receiver);
2087   __ cmpq(ic_reg, rscratch1);
2088   __ jcc(Assembler::equal, hit);
2089 
2090   __ jump(RuntimeAddress(SharedRuntime::get_ic_miss_stub()));
2091 
2092   // Verified entry point must be aligned
2093   __ align(8);
2094 
2095   __ bind(hit);
2096 
2097   int vep_offset = ((intptr_t)__ pc()) - start;
2098 
2099 #ifdef COMPILER1
2100   // For Object.hashCode, System.identityHashCode try to pull hashCode from object header if available.
2101   if ((InlineObjectHash && method->intrinsic_id() == vmIntrinsics::_hashCode) || (method->intrinsic_id() == vmIntrinsics::_identityHashCode)) {
2102     inline_check_hashcode_from_object_header(masm, method, j_rarg0 /*obj_reg*/, rax /*result*/);
2103   }
2104 #endif // COMPILER1
2105 
2106   // The instruction at the verified entry point must be 5 bytes or longer
2107   // because it can be patched on the fly by make_non_entrant. The stack bang
2108   // instruction fits that requirement.
2109 
2110   // Generate stack overflow check
2111 
2112   if (UseStackBanging) {
2113     __ bang_stack_with_offset((int)JavaThread::stack_shadow_zone_size());
2114   } else {
2115     // need a 5 byte instruction to allow MT safe patching to non-entrant
2116     __ fat_nop();
2117   }
2118 
2119   // Generate a new frame for the wrapper.
2120   __ enter();
2121   // -2 because return address is already present and so is saved rbp
2122   __ subptr(rsp, stack_size - 2*wordSize);
2123 
2124   // Frame is now completed as far as size and linkage.
2125   int frame_complete = ((intptr_t)__ pc()) - start;
2126 
2127     if (UseRTMLocking) {
2128       // Abort RTM transaction before calling JNI
2129       // because critical section will be large and will be
2130       // aborted anyway. Also nmethod could be deoptimized.
2131       __ xabort(0);
2132     }
2133 
2134 #ifdef ASSERT
2135     {
2136       Label L;
2137       __ mov(rax, rsp);
2138       __ andptr(rax, -16); // must be 16 byte boundary (see amd64 ABI)
2139       __ cmpptr(rax, rsp);
2140       __ jcc(Assembler::equal, L);
2141       __ stop("improperly aligned stack");
2142       __ bind(L);
2143     }
2144 #endif /* ASSERT */
2145 
2146 
2147   // We use r14 as the oop handle for the receiver/klass
2148   // It is callee save so it survives the call to native
2149 
2150   const Register oop_handle_reg = r14;
2151 
2152   if (is_critical_native SHENANDOAHGC_ONLY(&& !UseShenandoahGC)) {
2153     check_needs_gc_for_critical_native(masm, stack_slots, total_c_args, total_in_args,
2154                                        oop_handle_offset, oop_maps, in_regs, in_sig_bt);
2155   }
2156 
2157   //
2158   // We immediately shuffle the arguments so that any vm call we have to
2159   // make from here on out (sync slow path, jvmti, etc.) we will have
2160   // captured the oops from our caller and have a valid oopMap for
2161   // them.
2162 
2163   // -----------------
2164   // The Grand Shuffle
2165 
2166   // The Java calling convention is either equal (linux) or denser (win64) than the
2167   // c calling convention. However the because of the jni_env argument the c calling
2168   // convention always has at least one more (and two for static) arguments than Java.
2169   // Therefore if we move the args from java -> c backwards then we will never have
2170   // a register->register conflict and we don't have to build a dependency graph
2171   // and figure out how to break any cycles.
2172   //
2173 
2174   // Record esp-based slot for receiver on stack for non-static methods
2175   int receiver_offset = -1;
2176 
2177   // This is a trick. We double the stack slots so we can claim
2178   // the oops in the caller's frame. Since we are sure to have
2179   // more args than the caller doubling is enough to make
2180   // sure we can capture all the incoming oop args from the
2181   // caller.
2182   //
2183   OopMap* map = new OopMap(stack_slots * 2, 0 /* arg_slots*/);
2184 
2185   // Mark location of rbp (someday)
2186   // map->set_callee_saved(VMRegImpl::stack2reg( stack_slots - 2), stack_slots * 2, 0, vmreg(rbp));
2187 
2188   // Use eax, ebx as temporaries during any memory-memory moves we have to do
2189   // All inbound args are referenced based on rbp and all outbound args via rsp.
2190 
2191 
2192 #ifdef ASSERT
2193   bool reg_destroyed[RegisterImpl::number_of_registers];
2194   bool freg_destroyed[XMMRegisterImpl::number_of_registers];
2195   for ( int r = 0 ; r < RegisterImpl::number_of_registers ; r++ ) {
2196     reg_destroyed[r] = false;
2197   }
2198   for ( int f = 0 ; f < XMMRegisterImpl::number_of_registers ; f++ ) {
2199     freg_destroyed[f] = false;
2200   }
2201 
2202 #endif /* ASSERT */
2203 
2204   // This may iterate in two different directions depending on the
2205   // kind of native it is.  The reason is that for regular JNI natives
2206   // the incoming and outgoing registers are offset upwards and for
2207   // critical natives they are offset down.
2208   GrowableArray<int> arg_order(2 * total_in_args);
2209 #if INCLUDE_SHENANDOAHGC
2210   // Inbound arguments that need to be pinned for critical natives
2211   GrowableArray<int> pinned_args(total_in_args);
2212   // Current stack slot for storing register based array argument
2213   int pinned_slot = oop_handle_offset;
2214 #endif
2215   VMRegPair tmp_vmreg;
2216   tmp_vmreg.set2(rbx->as_VMReg());
2217 
2218   if (!is_critical_native) {
2219     for (int i = total_in_args - 1, c_arg = total_c_args - 1; i >= 0; i--, c_arg--) {
2220       arg_order.push(i);
2221       arg_order.push(c_arg);
2222     }
2223   } else {
2224     // Compute a valid move order, using tmp_vmreg to break any cycles
2225     ComputeMoveOrder cmo(total_in_args, in_regs, total_c_args, out_regs, in_sig_bt, arg_order, tmp_vmreg);
2226   }
2227 
2228   int temploc = -1;
2229   for (int ai = 0; ai < arg_order.length(); ai += 2) {
2230     int i = arg_order.at(ai);
2231     int c_arg = arg_order.at(ai + 1);
2232     __ block_comment(err_msg("move %d -> %d", i, c_arg));
2233     if (c_arg == -1) {
2234       assert(is_critical_native, "should only be required for critical natives");
2235       // This arg needs to be moved to a temporary
2236       __ mov(tmp_vmreg.first()->as_Register(), in_regs[i].first()->as_Register());
2237       in_regs[i] = tmp_vmreg;
2238       temploc = i;
2239       continue;
2240     } else if (i == -1) {
2241       assert(is_critical_native, "should only be required for critical natives");
2242       // Read from the temporary location
2243       assert(temploc != -1, "must be valid");
2244       i = temploc;
2245       temploc = -1;
2246     }
2247 #ifdef ASSERT
2248     if (in_regs[i].first()->is_Register()) {
2249       assert(!reg_destroyed[in_regs[i].first()->as_Register()->encoding()], "destroyed reg!");
2250     } else if (in_regs[i].first()->is_XMMRegister()) {
2251       assert(!freg_destroyed[in_regs[i].first()->as_XMMRegister()->encoding()], "destroyed reg!");
2252     }
2253     if (out_regs[c_arg].first()->is_Register()) {
2254       reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2255     } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2256       freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2257     }
2258 #endif /* ASSERT */
2259     switch (in_sig_bt[i]) {
2260       case T_ARRAY:
2261         if (is_critical_native) {
2262 #if INCLUDE_SHENANDOAHGC
2263           // pin before unpack
2264           if (UseShenandoahGC) {
2265             assert(pinned_slot <= stack_slots, "overflow");
2266             ShenandoahBarrierSet::assembler()->pin_critical_native_array(masm, in_regs[i], pinned_slot);
2267             pinned_args.append(i);
2268           }
2269 #endif
2270           unpack_array_argument(masm, in_regs[i], in_elem_bt[i], out_regs[c_arg + 1], out_regs[c_arg]);
2271           c_arg++;
2272 #ifdef ASSERT
2273           if (out_regs[c_arg].first()->is_Register()) {
2274             reg_destroyed[out_regs[c_arg].first()->as_Register()->encoding()] = true;
2275           } else if (out_regs[c_arg].first()->is_XMMRegister()) {
2276             freg_destroyed[out_regs[c_arg].first()->as_XMMRegister()->encoding()] = true;
2277           }
2278 #endif
2279           break;
2280         }
2281       case T_OBJECT:
2282         assert(!is_critical_native, "no oop arguments");
2283         object_move(masm, map, oop_handle_offset, stack_slots, in_regs[i], out_regs[c_arg],
2284                     ((i == 0) && (!is_static)),
2285                     &receiver_offset);
2286         break;
2287       case T_VOID:
2288         break;
2289 
2290       case T_FLOAT:
2291         float_move(masm, in_regs[i], out_regs[c_arg]);
2292           break;
2293 
2294       case T_DOUBLE:
2295         assert( i + 1 < total_in_args &&
2296                 in_sig_bt[i + 1] == T_VOID &&
2297                 out_sig_bt[c_arg+1] == T_VOID, "bad arg list");
2298         double_move(masm, in_regs[i], out_regs[c_arg]);
2299         break;
2300 
2301       case T_LONG :
2302         long_move(masm, in_regs[i], out_regs[c_arg]);
2303         break;
2304 
2305       case T_ADDRESS: assert(false, "found T_ADDRESS in java args");
2306 
2307       default:
2308         move32_64(masm, in_regs[i], out_regs[c_arg]);
2309     }
2310   }
2311 
2312   int c_arg;
2313 
2314   // Pre-load a static method's oop into r14.  Used both by locking code and
2315   // the normal JNI call code.
2316   if (!is_critical_native) {
2317     // point c_arg at the first arg that is already loaded in case we
2318     // need to spill before we call out
2319     c_arg = total_c_args - total_in_args;
2320 
2321     if (method->is_static()) {
2322 
2323       //  load oop into a register
2324       __ movoop(oop_handle_reg, JNIHandles::make_local(method->method_holder()->java_mirror()));
2325 
2326       // Now handlize the static class mirror it's known not-null.
2327       __ movptr(Address(rsp, klass_offset), oop_handle_reg);
2328       map->set_oop(VMRegImpl::stack2reg(klass_slot_offset));
2329 
2330       // Now get the handle
2331       __ lea(oop_handle_reg, Address(rsp, klass_offset));
2332       // store the klass handle as second argument
2333       __ movptr(c_rarg1, oop_handle_reg);
2334       // and protect the arg if we must spill
2335       c_arg--;
2336     }
2337   } else {
2338     // For JNI critical methods we need to save all registers in save_args.
2339     c_arg = 0;
2340   }
2341 
2342   // Change state to native (we save the return address in the thread, since it might not
2343   // be pushed on the stack when we do a a stack traversal). It is enough that the pc()
2344   // points into the right code segment. It does not have to be the correct return pc.
2345   // We use the same pc/oopMap repeatedly when we call out
2346 
2347   intptr_t the_pc = (intptr_t) __ pc();
2348   oop_maps->add_gc_map(the_pc - start, map);
2349 
2350   __ set_last_Java_frame(rsp, noreg, (address)the_pc);
2351 
2352 
2353   // We have all of the arguments setup at this point. We must not touch any register
2354   // argument registers at this point (what if we save/restore them there are no oop?
2355 
2356   {
2357     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2358     // protect the args we've loaded
2359     save_args(masm, total_c_args, c_arg, out_regs);
2360     __ mov_metadata(c_rarg1, method());
2361     __ call_VM_leaf(
2362       CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_entry),
2363       r15_thread, c_rarg1);
2364     restore_args(masm, total_c_args, c_arg, out_regs);
2365   }
2366 
2367   // RedefineClasses() tracing support for obsolete method entry
2368   if (log_is_enabled(Trace, redefine, class, obsolete)) {
2369     // protect the args we've loaded
2370     save_args(masm, total_c_args, c_arg, out_regs);
2371     __ mov_metadata(c_rarg1, method());
2372     __ call_VM_leaf(
2373       CAST_FROM_FN_PTR(address, SharedRuntime::rc_trace_method_entry),
2374       r15_thread, c_rarg1);
2375     restore_args(masm, total_c_args, c_arg, out_regs);
2376   }
2377 
2378   // Lock a synchronized method
2379 
2380   // Register definitions used by locking and unlocking
2381 
2382   const Register swap_reg = rax;  // Must use rax for cmpxchg instruction
2383   const Register obj_reg  = rbx;  // Will contain the oop
2384   const Register lock_reg = r13;  // Address of compiler lock object (BasicLock)
2385   const Register old_hdr  = r13;  // value of old header at unlock time
2386 
2387   Label slow_path_lock;
2388   Label lock_done;
2389 
2390   if (method->is_synchronized()) {
2391     assert(!is_critical_native, "unhandled");
2392 
2393 
2394     const int mark_word_offset = BasicLock::displaced_header_offset_in_bytes();
2395 
2396     // Get the handle (the 2nd argument)
2397     __ mov(oop_handle_reg, c_rarg1);
2398 
2399     // Get address of the box
2400 
2401     __ lea(lock_reg, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2402 
2403     // Load the oop from the handle
2404     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2405 
2406     if (UseBiasedLocking) {
2407       __ biased_locking_enter(lock_reg, obj_reg, swap_reg, rscratch1, false, lock_done, &slow_path_lock);
2408     }
2409 
2410     // Load immediate 1 into swap_reg %rax
2411     __ movl(swap_reg, 1);
2412 
2413     // Load (object->mark() | 1) into swap_reg %rax
2414     __ orptr(swap_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2415 
2416     // Save (object->mark() | 1) into BasicLock's displaced header
2417     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2418 
2419     if (os::is_MP()) {
2420       __ lock();
2421     }
2422 
2423     // src -> dest iff dest == rax else rax <- dest
2424     __ cmpxchgptr(lock_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2425     __ jcc(Assembler::equal, lock_done);
2426 
2427     // Hmm should this move to the slow path code area???
2428 
2429     // Test if the oopMark is an obvious stack pointer, i.e.,
2430     //  1) (mark & 3) == 0, and
2431     //  2) rsp <= mark < mark + os::pagesize()
2432     // These 3 tests can be done by evaluating the following
2433     // expression: ((mark - rsp) & (3 - os::vm_page_size())),
2434     // assuming both stack pointer and pagesize have their
2435     // least significant 2 bits clear.
2436     // NOTE: the oopMark is in swap_reg %rax as the result of cmpxchg
2437 
2438     __ subptr(swap_reg, rsp);
2439     __ andptr(swap_reg, 3 - os::vm_page_size());
2440 
2441     // Save the test result, for recursive case, the result is zero
2442     __ movptr(Address(lock_reg, mark_word_offset), swap_reg);
2443     __ jcc(Assembler::notEqual, slow_path_lock);
2444 
2445     // Slow path will re-enter here
2446 
2447     __ bind(lock_done);
2448   }
2449 
2450 
2451   // Finally just about ready to make the JNI call
2452 
2453 
2454   // get JNIEnv* which is first argument to native
2455   if (!is_critical_native) {
2456     __ lea(c_rarg0, Address(r15_thread, in_bytes(JavaThread::jni_environment_offset())));
2457   }
2458 
2459   // Now set thread in native
2460   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native);
2461 
2462   __ call(RuntimeAddress(native_func));
2463 
2464   // Verify or restore cpu control state after JNI call
2465   __ restore_cpu_control_state_after_jni();
2466 
2467   // Unpack native results.
2468   switch (ret_type) {
2469   case T_BOOLEAN: __ c2bool(rax);            break;
2470   case T_CHAR   : __ movzwl(rax, rax);      break;
2471   case T_BYTE   : __ sign_extend_byte (rax); break;
2472   case T_SHORT  : __ sign_extend_short(rax); break;
2473   case T_INT    : /* nothing to do */        break;
2474   case T_DOUBLE :
2475   case T_FLOAT  :
2476     // Result is in xmm0 we'll save as needed
2477     break;
2478   case T_ARRAY:                 // Really a handle
2479   case T_OBJECT:                // Really a handle
2480       break; // can't de-handlize until after safepoint check
2481   case T_VOID: break;
2482   case T_LONG: break;
2483   default       : ShouldNotReachHere();
2484   }
2485 
2486 #if INCLUDE_SHENANDOAHGC
2487   if (UseShenandoahGC) {
2488     // unpin pinned arguments
2489     pinned_slot = oop_handle_offset;
2490     if (pinned_args.length() > 0) {
2491       // save return value that may be overwritten otherwise.
2492       save_native_result(masm, ret_type, stack_slots);
2493       for (int index = 0; index < pinned_args.length(); index ++) {
2494         int i = pinned_args.at(index);
2495         assert(pinned_slot <= stack_slots, "overflow");
2496         ShenandoahBarrierSet::assembler()->unpin_critical_native_array(masm, in_regs[i], pinned_slot);
2497       }
2498       restore_native_result(masm, ret_type, stack_slots);
2499     }
2500   }
2501 #endif
2502   // Switch thread to "native transition" state before reading the synchronization state.
2503   // This additional state is necessary because reading and testing the synchronization
2504   // state is not atomic w.r.t. GC, as this scenario demonstrates:
2505   //     Java thread A, in _thread_in_native state, loads _not_synchronized and is preempted.
2506   //     VM thread changes sync state to synchronizing and suspends threads for GC.
2507   //     Thread A is resumed to finish this native method, but doesn't block here since it
2508   //     didn't see any synchronization is progress, and escapes.
2509   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
2510 
2511   if(os::is_MP()) {
2512     if (UseMembar) {
2513       // Force this write out before the read below
2514       __ membar(Assembler::Membar_mask_bits(
2515            Assembler::LoadLoad | Assembler::LoadStore |
2516            Assembler::StoreLoad | Assembler::StoreStore));
2517     } else {
2518       // Write serialization page so VM thread can do a pseudo remote membar.
2519       // We use the current thread pointer to calculate a thread specific
2520       // offset to write to within the page. This minimizes bus traffic
2521       // due to cache line collision.
2522       __ serialize_memory(r15_thread, rcx);
2523     }
2524   }
2525 
2526   Label after_transition;
2527 
2528   // check for safepoint operation in progress and/or pending suspend requests
2529   {
2530     Label Continue;
2531     Label slow_path;
2532 
2533     __ safepoint_poll(slow_path, r15_thread, rscratch1);
2534 
2535     __ cmpl(Address(r15_thread, JavaThread::suspend_flags_offset()), 0);
2536     __ jcc(Assembler::equal, Continue);
2537     __ bind(slow_path);
2538 
2539     // Don't use call_VM as it will see a possible pending exception and forward it
2540     // and never return here preventing us from clearing _last_native_pc down below.
2541     // Also can't use call_VM_leaf either as it will check to see if rsi & rdi are
2542     // preserved and correspond to the bcp/locals pointers. So we do a runtime call
2543     // by hand.
2544     //
2545     __ vzeroupper();
2546     save_native_result(masm, ret_type, stack_slots);
2547     __ mov(c_rarg0, r15_thread);
2548     __ mov(r12, rsp); // remember sp
2549     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2550     __ andptr(rsp, -16); // align stack as required by ABI
2551     if (!is_critical_native) {
2552       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans)));
2553     } else {
2554       __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, JavaThread::check_special_condition_for_native_trans_and_transition)));
2555     }
2556     __ mov(rsp, r12); // restore sp
2557     __ reinit_heapbase();
2558     // Restore any method result value
2559     restore_native_result(masm, ret_type, stack_slots);
2560 
2561     if (is_critical_native) {
2562       // The call above performed the transition to thread_in_Java so
2563       // skip the transition logic below.
2564       __ jmpb(after_transition);
2565     }
2566 
2567     __ bind(Continue);
2568   }
2569 
2570   // change thread state
2571   __ movl(Address(r15_thread, JavaThread::thread_state_offset()), _thread_in_Java);
2572   __ bind(after_transition);
2573 
2574   Label reguard;
2575   Label reguard_done;
2576   __ cmpl(Address(r15_thread, JavaThread::stack_guard_state_offset()), JavaThread::stack_guard_yellow_reserved_disabled);
2577   __ jcc(Assembler::equal, reguard);
2578   __ bind(reguard_done);
2579 
2580   // native result if any is live
2581 
2582   // Unlock
2583   Label unlock_done;
2584   Label slow_path_unlock;
2585   if (method->is_synchronized()) {
2586 
2587     // Get locked oop from the handle we passed to jni
2588     __ movptr(obj_reg, Address(oop_handle_reg, 0));
2589 
2590     Label done;
2591 
2592     if (UseBiasedLocking) {
2593       __ biased_locking_exit(obj_reg, old_hdr, done);
2594     }
2595 
2596     // Simple recursive lock?
2597 
2598     __ cmpptr(Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size), (int32_t)NULL_WORD);
2599     __ jcc(Assembler::equal, done);
2600 
2601     // Must save rax if if it is live now because cmpxchg must use it
2602     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2603       save_native_result(masm, ret_type, stack_slots);
2604     }
2605 
2606 
2607     // get address of the stack lock
2608     __ lea(rax, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2609     //  get old displaced header
2610     __ movptr(old_hdr, Address(rax, 0));
2611 
2612     // Atomic swap old header if oop still contains the stack lock
2613     if (os::is_MP()) {
2614       __ lock();
2615     }
2616     __ cmpxchgptr(old_hdr, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
2617     __ jcc(Assembler::notEqual, slow_path_unlock);
2618 
2619     // slow path re-enters here
2620     __ bind(unlock_done);
2621     if (ret_type != T_FLOAT && ret_type != T_DOUBLE && ret_type != T_VOID) {
2622       restore_native_result(masm, ret_type, stack_slots);
2623     }
2624 
2625     __ bind(done);
2626 
2627   }
2628   {
2629     SkipIfEqual skip(masm, &DTraceMethodProbes, false);
2630     save_native_result(masm, ret_type, stack_slots);
2631     __ mov_metadata(c_rarg1, method());
2632     __ call_VM_leaf(
2633          CAST_FROM_FN_PTR(address, SharedRuntime::dtrace_method_exit),
2634          r15_thread, c_rarg1);
2635     restore_native_result(masm, ret_type, stack_slots);
2636   }
2637 
2638   __ reset_last_Java_frame(false);
2639 
2640   // Unbox oop result, e.g. JNIHandles::resolve value.
2641   if (ret_type == T_OBJECT || ret_type == T_ARRAY) {
2642     __ resolve_jobject(rax /* value */,
2643                        r15_thread /* thread */,
2644                        rcx /* tmp */);
2645   }
2646 
2647   if (CheckJNICalls) {
2648     // clear_pending_jni_exception_check
2649     __ movptr(Address(r15_thread, JavaThread::pending_jni_exception_check_fn_offset()), NULL_WORD);
2650   }
2651 
2652   if (!is_critical_native) {
2653     // reset handle block
2654     __ movptr(rcx, Address(r15_thread, JavaThread::active_handles_offset()));
2655     __ movl(Address(rcx, JNIHandleBlock::top_offset_in_bytes()), (int32_t)NULL_WORD);
2656   }
2657 
2658   // pop our frame
2659 
2660   __ leave();
2661 
2662   if (!is_critical_native) {
2663     // Any exception pending?
2664     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2665     __ jcc(Assembler::notEqual, exception_pending);
2666   }
2667 
2668   // Return
2669 
2670   __ ret(0);
2671 
2672   // Unexpected paths are out of line and go here
2673 
2674   if (!is_critical_native) {
2675     // forward the exception
2676     __ bind(exception_pending);
2677 
2678     // and forward the exception
2679     __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2680   }
2681 
2682   // Slow path locking & unlocking
2683   if (method->is_synchronized()) {
2684 
2685     // BEGIN Slow path lock
2686     __ bind(slow_path_lock);
2687 
2688     // has last_Java_frame setup. No exceptions so do vanilla call not call_VM
2689     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2690 
2691     // protect the args we've loaded
2692     save_args(masm, total_c_args, c_arg, out_regs);
2693 
2694     __ mov(c_rarg0, obj_reg);
2695     __ mov(c_rarg1, lock_reg);
2696     __ mov(c_rarg2, r15_thread);
2697 
2698     // Not a leaf but we have last_Java_frame setup as we want
2699     __ call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_locking_C), 3);
2700     restore_args(masm, total_c_args, c_arg, out_regs);
2701 
2702 #ifdef ASSERT
2703     { Label L;
2704     __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2705     __ jcc(Assembler::equal, L);
2706     __ stop("no pending exception allowed on exit from monitorenter");
2707     __ bind(L);
2708     }
2709 #endif
2710     __ jmp(lock_done);
2711 
2712     // END Slow path lock
2713 
2714     // BEGIN Slow path unlock
2715     __ bind(slow_path_unlock);
2716 
2717     // If we haven't already saved the native result we must save it now as xmm registers
2718     // are still exposed.
2719     __ vzeroupper();
2720     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2721       save_native_result(masm, ret_type, stack_slots);
2722     }
2723 
2724     __ lea(c_rarg1, Address(rsp, lock_slot_offset * VMRegImpl::stack_slot_size));
2725 
2726     __ mov(c_rarg0, obj_reg);
2727     __ mov(c_rarg2, r15_thread);
2728     __ mov(r12, rsp); // remember sp
2729     __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2730     __ andptr(rsp, -16); // align stack as required by ABI
2731 
2732     // Save pending exception around call to VM (which contains an EXCEPTION_MARK)
2733     // NOTE that obj_reg == rbx currently
2734     __ movptr(rbx, Address(r15_thread, in_bytes(Thread::pending_exception_offset())));
2735     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int32_t)NULL_WORD);
2736 
2737     // args are (oop obj, BasicLock* lock, JavaThread* thread)
2738     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::complete_monitor_unlocking_C)));
2739     __ mov(rsp, r12); // restore sp
2740     __ reinit_heapbase();
2741 #ifdef ASSERT
2742     {
2743       Label L;
2744       __ cmpptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), (int)NULL_WORD);
2745       __ jcc(Assembler::equal, L);
2746       __ stop("no pending exception allowed on exit complete_monitor_unlocking_C");
2747       __ bind(L);
2748     }
2749 #endif /* ASSERT */
2750 
2751     __ movptr(Address(r15_thread, in_bytes(Thread::pending_exception_offset())), rbx);
2752 
2753     if (ret_type == T_FLOAT || ret_type == T_DOUBLE ) {
2754       restore_native_result(masm, ret_type, stack_slots);
2755     }
2756     __ jmp(unlock_done);
2757 
2758     // END Slow path unlock
2759 
2760   } // synchronized
2761 
2762   // SLOW PATH Reguard the stack if needed
2763 
2764   __ bind(reguard);
2765   __ vzeroupper();
2766   save_native_result(masm, ret_type, stack_slots);
2767   __ mov(r12, rsp); // remember sp
2768   __ subptr(rsp, frame::arg_reg_save_area_bytes); // windows
2769   __ andptr(rsp, -16); // align stack as required by ABI
2770   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, SharedRuntime::reguard_yellow_pages)));
2771   __ mov(rsp, r12); // restore sp
2772   __ reinit_heapbase();
2773   restore_native_result(masm, ret_type, stack_slots);
2774   // and continue
2775   __ jmp(reguard_done);
2776 
2777 
2778 
2779   __ flush();
2780 
2781   nmethod *nm = nmethod::new_native_nmethod(method,
2782                                             compile_id,
2783                                             masm->code(),
2784                                             vep_offset,
2785                                             frame_complete,
2786                                             stack_slots / VMRegImpl::slots_per_word,
2787                                             (is_static ? in_ByteSize(klass_offset) : in_ByteSize(receiver_offset)),
2788                                             in_ByteSize(lock_slot_offset*VMRegImpl::stack_slot_size),
2789                                             oop_maps);
2790 
2791   if (is_critical_native) {
2792     nm->set_lazy_critical_native(true);
2793   }
2794 
2795   return nm;
2796 
2797 }
2798 
2799 // this function returns the adjust size (in number of words) to a c2i adapter
2800 // activation for use during deoptimization
2801 int Deoptimization::last_frame_adjust(int callee_parameters, int callee_locals ) {
2802   return (callee_locals - callee_parameters) * Interpreter::stackElementWords;
2803 }
2804 
2805 
2806 uint SharedRuntime::out_preserve_stack_slots() {
2807   return 0;
2808 }
2809 
2810 //------------------------------generate_deopt_blob----------------------------
2811 void SharedRuntime::generate_deopt_blob() {
2812   // Allocate space for the code
2813   ResourceMark rm;
2814   // Setup code generation tools
2815   int pad = 0;
2816   if (UseAVX > 2) {
2817     pad += 1024;
2818   }
2819 #if INCLUDE_JVMCI
2820   if (EnableJVMCI || UseAOT) {
2821     pad += 512; // Increase the buffer size when compiling for JVMCI
2822   }
2823 #endif
2824   CodeBuffer buffer("deopt_blob", 2560+pad, 1024);
2825   MacroAssembler* masm = new MacroAssembler(&buffer);
2826   int frame_size_in_words;
2827   OopMap* map = NULL;
2828   OopMapSet *oop_maps = new OopMapSet();
2829 
2830   // -------------
2831   // This code enters when returning to a de-optimized nmethod.  A return
2832   // address has been pushed on the the stack, and return values are in
2833   // registers.
2834   // If we are doing a normal deopt then we were called from the patched
2835   // nmethod from the point we returned to the nmethod. So the return
2836   // address on the stack is wrong by NativeCall::instruction_size
2837   // We will adjust the value so it looks like we have the original return
2838   // address on the stack (like when we eagerly deoptimized).
2839   // In the case of an exception pending when deoptimizing, we enter
2840   // with a return address on the stack that points after the call we patched
2841   // into the exception handler. We have the following register state from,
2842   // e.g., the forward exception stub (see stubGenerator_x86_64.cpp).
2843   //    rax: exception oop
2844   //    rbx: exception handler
2845   //    rdx: throwing pc
2846   // So in this case we simply jam rdx into the useless return address and
2847   // the stack looks just like we want.
2848   //
2849   // At this point we need to de-opt.  We save the argument return
2850   // registers.  We call the first C routine, fetch_unroll_info().  This
2851   // routine captures the return values and returns a structure which
2852   // describes the current frame size and the sizes of all replacement frames.
2853   // The current frame is compiled code and may contain many inlined
2854   // functions, each with their own JVM state.  We pop the current frame, then
2855   // push all the new frames.  Then we call the C routine unpack_frames() to
2856   // populate these frames.  Finally unpack_frames() returns us the new target
2857   // address.  Notice that callee-save registers are BLOWN here; they have
2858   // already been captured in the vframeArray at the time the return PC was
2859   // patched.
2860   address start = __ pc();
2861   Label cont;
2862 
2863   // Prolog for non exception case!
2864 
2865   // Save everything in sight.
2866   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, /*save_vectors*/ true);
2867 
2868   // Normal deoptimization.  Save exec mode for unpack_frames.
2869   __ movl(r14, Deoptimization::Unpack_deopt); // callee-saved
2870   __ jmp(cont);
2871 
2872   int reexecute_offset = __ pc() - start;
2873 #if INCLUDE_JVMCI && !defined(COMPILER1)
2874   if (EnableJVMCI && UseJVMCICompiler) {
2875     // JVMCI does not use this kind of deoptimization
2876     __ should_not_reach_here();
2877   }
2878 #endif
2879 
2880   // Reexecute case
2881   // return address is the pc describes what bci to do re-execute at
2882 
2883   // No need to update map as each call to save_live_registers will produce identical oopmap
2884   (void) RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, /*save_vectors*/ true);
2885 
2886   __ movl(r14, Deoptimization::Unpack_reexecute); // callee-saved
2887   __ jmp(cont);
2888 
2889 #if INCLUDE_JVMCI
2890   Label after_fetch_unroll_info_call;
2891   int implicit_exception_uncommon_trap_offset = 0;
2892   int uncommon_trap_offset = 0;
2893 
2894   if (EnableJVMCI || UseAOT) {
2895     implicit_exception_uncommon_trap_offset = __ pc() - start;
2896 
2897     __ pushptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())));
2898     __ movptr(Address(r15_thread, in_bytes(JavaThread::jvmci_implicit_exception_pc_offset())), (int32_t)NULL_WORD);
2899 
2900     uncommon_trap_offset = __ pc() - start;
2901 
2902     // Save everything in sight.
2903     RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, /*save_vectors*/ true);
2904     // fetch_unroll_info needs to call last_java_frame()
2905     __ set_last_Java_frame(noreg, noreg, NULL);
2906 
2907     __ movl(c_rarg1, Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())));
2908     __ movl(Address(r15_thread, in_bytes(JavaThread::pending_deoptimization_offset())), -1);
2909 
2910     __ movl(r14, (int32_t)Deoptimization::Unpack_reexecute);
2911     __ mov(c_rarg0, r15_thread);
2912     __ movl(c_rarg2, r14); // exec mode
2913     __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
2914     oop_maps->add_gc_map( __ pc()-start, map->deep_copy());
2915 
2916     __ reset_last_Java_frame(false);
2917 
2918     __ jmp(after_fetch_unroll_info_call);
2919   } // EnableJVMCI
2920 #endif // INCLUDE_JVMCI
2921 
2922   int exception_offset = __ pc() - start;
2923 
2924   // Prolog for exception case
2925 
2926   // all registers are dead at this entry point, except for rax, and
2927   // rdx which contain the exception oop and exception pc
2928   // respectively.  Set them in TLS and fall thru to the
2929   // unpack_with_exception_in_tls entry point.
2930 
2931   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
2932   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), rax);
2933 
2934   int exception_in_tls_offset = __ pc() - start;
2935 
2936   // new implementation because exception oop is now passed in JavaThread
2937 
2938   // Prolog for exception case
2939   // All registers must be preserved because they might be used by LinearScan
2940   // Exceptiop oop and throwing PC are passed in JavaThread
2941   // tos: stack at point of call to method that threw the exception (i.e. only
2942   // args are on the stack, no return address)
2943 
2944   // make room on stack for the return address
2945   // It will be patched later with the throwing pc. The correct value is not
2946   // available now because loading it from memory would destroy registers.
2947   __ push(0);
2948 
2949   // Save everything in sight.
2950   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, /*save_vectors*/ true);
2951 
2952   // Now it is safe to overwrite any register
2953 
2954   // Deopt during an exception.  Save exec mode for unpack_frames.
2955   __ movl(r14, Deoptimization::Unpack_exception); // callee-saved
2956 
2957   // load throwing pc from JavaThread and patch it as the return address
2958   // of the current frame. Then clear the field in JavaThread
2959 
2960   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
2961   __ movptr(Address(rbp, wordSize), rdx);
2962   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
2963 
2964 #ifdef ASSERT
2965   // verify that there is really an exception oop in JavaThread
2966   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
2967   __ verify_oop(rax);
2968 
2969   // verify that there is no pending exception
2970   Label no_pending_exception;
2971   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
2972   __ testptr(rax, rax);
2973   __ jcc(Assembler::zero, no_pending_exception);
2974   __ stop("must not have pending exception here");
2975   __ bind(no_pending_exception);
2976 #endif
2977 
2978   __ bind(cont);
2979 
2980   // Call C code.  Need thread and this frame, but NOT official VM entry
2981   // crud.  We cannot block on this call, no GC can happen.
2982   //
2983   // UnrollBlock* fetch_unroll_info(JavaThread* thread)
2984 
2985   // fetch_unroll_info needs to call last_java_frame().
2986 
2987   __ set_last_Java_frame(noreg, noreg, NULL);
2988 #ifdef ASSERT
2989   { Label L;
2990     __ cmpptr(Address(r15_thread,
2991                     JavaThread::last_Java_fp_offset()),
2992             (int32_t)0);
2993     __ jcc(Assembler::equal, L);
2994     __ stop("SharedRuntime::generate_deopt_blob: last_Java_fp not cleared");
2995     __ bind(L);
2996   }
2997 #endif // ASSERT
2998   __ mov(c_rarg0, r15_thread);
2999   __ movl(c_rarg1, r14); // exec_mode
3000   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::fetch_unroll_info)));
3001 
3002   // Need to have an oopmap that tells fetch_unroll_info where to
3003   // find any register it might need.
3004   oop_maps->add_gc_map(__ pc() - start, map);
3005 
3006   __ reset_last_Java_frame(false);
3007 
3008 #if INCLUDE_JVMCI
3009   if (EnableJVMCI || UseAOT) {
3010     __ bind(after_fetch_unroll_info_call);
3011   }
3012 #endif
3013 
3014   // Load UnrollBlock* into rdi
3015   __ mov(rdi, rax);
3016 
3017   __ movl(r14, Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()));
3018    Label noException;
3019   __ cmpl(r14, Deoptimization::Unpack_exception);   // Was exception pending?
3020   __ jcc(Assembler::notEqual, noException);
3021   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3022   // QQQ this is useless it was NULL above
3023   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3024   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int32_t)NULL_WORD);
3025   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int32_t)NULL_WORD);
3026 
3027   __ verify_oop(rax);
3028 
3029   // Overwrite the result registers with the exception results.
3030   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3031   // I think this is useless
3032   __ movptr(Address(rsp, RegisterSaver::rdx_offset_in_bytes()), rdx);
3033 
3034   __ bind(noException);
3035 
3036   // Only register save data is on the stack.
3037   // Now restore the result registers.  Everything else is either dead
3038   // or captured in the vframeArray.
3039   RegisterSaver::restore_result_registers(masm);
3040 
3041   // All of the register save area has been popped of the stack. Only the
3042   // return address remains.
3043 
3044   // Pop all the frames we must move/replace.
3045   //
3046   // Frame picture (youngest to oldest)
3047   // 1: self-frame (no frame link)
3048   // 2: deopting frame  (no frame link)
3049   // 3: caller of deopting frame (could be compiled/interpreted).
3050   //
3051   // Note: by leaving the return address of self-frame on the stack
3052   // and using the size of frame 2 to adjust the stack
3053   // when we are done the return to frame 3 will still be on the stack.
3054 
3055   // Pop deoptimized frame
3056   __ movl(rcx, Address(rdi, Deoptimization::UnrollBlock::size_of_deoptimized_frame_offset_in_bytes()));
3057   __ addptr(rsp, rcx);
3058 
3059   // rsp should be pointing at the return address to the caller (3)
3060 
3061   // Pick up the initial fp we should save
3062   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
3063   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
3064 
3065 #ifdef ASSERT
3066   // Compilers generate code that bang the stack by as much as the
3067   // interpreter would need. So this stack banging should never
3068   // trigger a fault. Verify that it does not on non product builds.
3069   if (UseStackBanging) {
3070     __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
3071     __ bang_stack_size(rbx, rcx);
3072   }
3073 #endif
3074 
3075   // Load address of array of frame pcs into rcx
3076   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3077 
3078   // Trash the old pc
3079   __ addptr(rsp, wordSize);
3080 
3081   // Load address of array of frame sizes into rsi
3082   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock::frame_sizes_offset_in_bytes()));
3083 
3084   // Load counter into rdx
3085   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock::number_of_frames_offset_in_bytes()));
3086 
3087   // Now adjust the caller's stack to make up for the extra locals
3088   // but record the original sp so that we can save it in the skeletal interpreter
3089   // frame and the stack walking of interpreter_sender will get the unextended sp
3090   // value and not the "real" sp value.
3091 
3092   const Register sender_sp = r8;
3093 
3094   __ mov(sender_sp, rsp);
3095   __ movl(rbx, Address(rdi,
3096                        Deoptimization::UnrollBlock::
3097                        caller_adjustment_offset_in_bytes()));
3098   __ subptr(rsp, rbx);
3099 
3100   // Push interpreter frames in a loop
3101   Label loop;
3102   __ bind(loop);
3103   __ movptr(rbx, Address(rsi, 0));      // Load frame size
3104   __ subptr(rbx, 2*wordSize);           // We'll push pc and ebp by hand
3105   __ pushptr(Address(rcx, 0));          // Save return address
3106   __ enter();                           // Save old & set new ebp
3107   __ subptr(rsp, rbx);                  // Prolog
3108   // This value is corrected by layout_activation_impl
3109   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3110   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize), sender_sp); // Make it walkable
3111   __ mov(sender_sp, rsp);               // Pass sender_sp to next frame
3112   __ addptr(rsi, wordSize);             // Bump array pointer (sizes)
3113   __ addptr(rcx, wordSize);             // Bump array pointer (pcs)
3114   __ decrementl(rdx);                   // Decrement counter
3115   __ jcc(Assembler::notZero, loop);
3116   __ pushptr(Address(rcx, 0));          // Save final return address
3117 
3118   // Re-push self-frame
3119   __ enter();                           // Save old & set new ebp
3120 
3121   // Allocate a full sized register save area.
3122   // Return address and rbp are in place, so we allocate two less words.
3123   __ subptr(rsp, (frame_size_in_words - 2) * wordSize);
3124 
3125   // Restore frame locals after moving the frame
3126   __ movdbl(Address(rsp, RegisterSaver::xmm0_offset_in_bytes()), xmm0);
3127   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3128 
3129   // Call C code.  Need thread but NOT official VM entry
3130   // crud.  We cannot block on this call, no GC can happen.  Call should
3131   // restore return values to their stack-slots with the new SP.
3132   //
3133   // void Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)
3134 
3135   // Use rbp because the frames look interpreted now
3136   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3137   // Don't need the precise return PC here, just precise enough to point into this code blob.
3138   address the_pc = __ pc();
3139   __ set_last_Java_frame(noreg, rbp, the_pc);
3140 
3141   __ andptr(rsp, -(StackAlignmentInBytes));  // Fix stack alignment as required by ABI
3142   __ mov(c_rarg0, r15_thread);
3143   __ movl(c_rarg1, r14); // second arg: exec_mode
3144   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3145   // Revert SP alignment after call since we're going to do some SP relative addressing below
3146   __ movptr(rsp, Address(r15_thread, JavaThread::last_Java_sp_offset()));
3147 
3148   // Set an oopmap for the call site
3149   // Use the same PC we used for the last java frame
3150   oop_maps->add_gc_map(the_pc - start,
3151                        new OopMap( frame_size_in_words, 0 ));
3152 
3153   // Clear fp AND pc
3154   __ reset_last_Java_frame(true);
3155 
3156   // Collect return values
3157   __ movdbl(xmm0, Address(rsp, RegisterSaver::xmm0_offset_in_bytes()));
3158   __ movptr(rax, Address(rsp, RegisterSaver::rax_offset_in_bytes()));
3159   // I think this is useless (throwing pc?)
3160   __ movptr(rdx, Address(rsp, RegisterSaver::rdx_offset_in_bytes()));
3161 
3162   // Pop self-frame.
3163   __ leave();                           // Epilog
3164 
3165   // Jump to interpreter
3166   __ ret(0);
3167 
3168   // Make sure all code is generated
3169   masm->flush();
3170 
3171   _deopt_blob = DeoptimizationBlob::create(&buffer, oop_maps, 0, exception_offset, reexecute_offset, frame_size_in_words);
3172   _deopt_blob->set_unpack_with_exception_in_tls_offset(exception_in_tls_offset);
3173 #if INCLUDE_JVMCI
3174   if (EnableJVMCI || UseAOT) {
3175     _deopt_blob->set_uncommon_trap_offset(uncommon_trap_offset);
3176     _deopt_blob->set_implicit_exception_uncommon_trap_offset(implicit_exception_uncommon_trap_offset);
3177   }
3178 #endif
3179 }
3180 
3181 #ifdef COMPILER2
3182 //------------------------------generate_uncommon_trap_blob--------------------
3183 void SharedRuntime::generate_uncommon_trap_blob() {
3184   // Allocate space for the code
3185   ResourceMark rm;
3186   // Setup code generation tools
3187   CodeBuffer buffer("uncommon_trap_blob", 2048, 1024);
3188   MacroAssembler* masm = new MacroAssembler(&buffer);
3189 
3190   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3191 
3192   address start = __ pc();
3193 
3194   if (UseRTMLocking) {
3195     // Abort RTM transaction before possible nmethod deoptimization.
3196     __ xabort(0);
3197   }
3198 
3199   // Push self-frame.  We get here with a return address on the
3200   // stack, so rsp is 8-byte aligned until we allocate our frame.
3201   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog!
3202 
3203   // No callee saved registers. rbp is assumed implicitly saved
3204   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3205 
3206   // compiler left unloaded_class_index in j_rarg0 move to where the
3207   // runtime expects it.
3208   __ movl(c_rarg1, j_rarg0);
3209 
3210   __ set_last_Java_frame(noreg, noreg, NULL);
3211 
3212   // Call C code.  Need thread but NOT official VM entry
3213   // crud.  We cannot block on this call, no GC can happen.  Call should
3214   // capture callee-saved registers as well as return values.
3215   // Thread is in rdi already.
3216   //
3217   // UnrollBlock* uncommon_trap(JavaThread* thread, jint unloaded_class_index);
3218 
3219   __ mov(c_rarg0, r15_thread);
3220   __ movl(c_rarg2, Deoptimization::Unpack_uncommon_trap);
3221   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::uncommon_trap)));
3222 
3223   // Set an oopmap for the call site
3224   OopMapSet* oop_maps = new OopMapSet();
3225   OopMap* map = new OopMap(SimpleRuntimeFrame::framesize, 0);
3226 
3227   // location of rbp is known implicitly by the frame sender code
3228 
3229   oop_maps->add_gc_map(__ pc() - start, map);
3230 
3231   __ reset_last_Java_frame(false);
3232 
3233   // Load UnrollBlock* into rdi
3234   __ mov(rdi, rax);
3235 
3236 #ifdef ASSERT
3237   { Label L;
3238     __ cmpptr(Address(rdi, Deoptimization::UnrollBlock::unpack_kind_offset_in_bytes()),
3239             (int32_t)Deoptimization::Unpack_uncommon_trap);
3240     __ jcc(Assembler::equal, L);
3241     __ stop("SharedRuntime::generate_deopt_blob: expected Unpack_uncommon_trap");
3242     __ bind(L);
3243   }
3244 #endif
3245 
3246   // Pop all the frames we must move/replace.
3247   //
3248   // Frame picture (youngest to oldest)
3249   // 1: self-frame (no frame link)
3250   // 2: deopting frame  (no frame link)
3251   // 3: caller of deopting frame (could be compiled/interpreted).
3252 
3253   // Pop self-frame.  We have no frame, and must rely only on rax and rsp.
3254   __ addptr(rsp, (SimpleRuntimeFrame::framesize - 2) << LogBytesPerInt); // Epilog!
3255 
3256   // Pop deoptimized frame (int)
3257   __ movl(rcx, Address(rdi,
3258                        Deoptimization::UnrollBlock::
3259                        size_of_deoptimized_frame_offset_in_bytes()));
3260   __ addptr(rsp, rcx);
3261 
3262   // rsp should be pointing at the return address to the caller (3)
3263 
3264   // Pick up the initial fp we should save
3265   // restore rbp before stack bang because if stack overflow is thrown it needs to be pushed (and preserved)
3266   __ movptr(rbp, Address(rdi, Deoptimization::UnrollBlock::initial_info_offset_in_bytes()));
3267 
3268 #ifdef ASSERT
3269   // Compilers generate code that bang the stack by as much as the
3270   // interpreter would need. So this stack banging should never
3271   // trigger a fault. Verify that it does not on non product builds.
3272   if (UseStackBanging) {
3273     __ movl(rbx, Address(rdi ,Deoptimization::UnrollBlock::total_frame_sizes_offset_in_bytes()));
3274     __ bang_stack_size(rbx, rcx);
3275   }
3276 #endif
3277 
3278   // Load address of array of frame pcs into rcx (address*)
3279   __ movptr(rcx, Address(rdi, Deoptimization::UnrollBlock::frame_pcs_offset_in_bytes()));
3280 
3281   // Trash the return pc
3282   __ addptr(rsp, wordSize);
3283 
3284   // Load address of array of frame sizes into rsi (intptr_t*)
3285   __ movptr(rsi, Address(rdi, Deoptimization::UnrollBlock:: frame_sizes_offset_in_bytes()));
3286 
3287   // Counter
3288   __ movl(rdx, Address(rdi, Deoptimization::UnrollBlock:: number_of_frames_offset_in_bytes())); // (int)
3289 
3290   // Now adjust the caller's stack to make up for the extra locals but
3291   // record the original sp so that we can save it in the skeletal
3292   // interpreter frame and the stack walking of interpreter_sender
3293   // will get the unextended sp value and not the "real" sp value.
3294 
3295   const Register sender_sp = r8;
3296 
3297   __ mov(sender_sp, rsp);
3298   __ movl(rbx, Address(rdi, Deoptimization::UnrollBlock:: caller_adjustment_offset_in_bytes())); // (int)
3299   __ subptr(rsp, rbx);
3300 
3301   // Push interpreter frames in a loop
3302   Label loop;
3303   __ bind(loop);
3304   __ movptr(rbx, Address(rsi, 0)); // Load frame size
3305   __ subptr(rbx, 2 * wordSize);    // We'll push pc and rbp by hand
3306   __ pushptr(Address(rcx, 0));     // Save return address
3307   __ enter();                      // Save old & set new rbp
3308   __ subptr(rsp, rbx);             // Prolog
3309   __ movptr(Address(rbp, frame::interpreter_frame_sender_sp_offset * wordSize),
3310             sender_sp);            // Make it walkable
3311   // This value is corrected by layout_activation_impl
3312   __ movptr(Address(rbp, frame::interpreter_frame_last_sp_offset * wordSize), (int32_t)NULL_WORD );
3313   __ mov(sender_sp, rsp);          // Pass sender_sp to next frame
3314   __ addptr(rsi, wordSize);        // Bump array pointer (sizes)
3315   __ addptr(rcx, wordSize);        // Bump array pointer (pcs)
3316   __ decrementl(rdx);              // Decrement counter
3317   __ jcc(Assembler::notZero, loop);
3318   __ pushptr(Address(rcx, 0));     // Save final return address
3319 
3320   // Re-push self-frame
3321   __ enter();                 // Save old & set new rbp
3322   __ subptr(rsp, (SimpleRuntimeFrame::framesize - 4) << LogBytesPerInt);
3323                               // Prolog
3324 
3325   // Use rbp because the frames look interpreted now
3326   // Save "the_pc" since it cannot easily be retrieved using the last_java_SP after we aligned SP.
3327   // Don't need the precise return PC here, just precise enough to point into this code blob.
3328   address the_pc = __ pc();
3329   __ set_last_Java_frame(noreg, rbp, the_pc);
3330 
3331   // Call C code.  Need thread but NOT official VM entry
3332   // crud.  We cannot block on this call, no GC can happen.  Call should
3333   // restore return values to their stack-slots with the new SP.
3334   // Thread is in rdi already.
3335   //
3336   // BasicType unpack_frames(JavaThread* thread, int exec_mode);
3337 
3338   __ andptr(rsp, -(StackAlignmentInBytes)); // Align SP as required by ABI
3339   __ mov(c_rarg0, r15_thread);
3340   __ movl(c_rarg1, Deoptimization::Unpack_uncommon_trap);
3341   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, Deoptimization::unpack_frames)));
3342 
3343   // Set an oopmap for the call site
3344   // Use the same PC we used for the last java frame
3345   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3346 
3347   // Clear fp AND pc
3348   __ reset_last_Java_frame(true);
3349 
3350   // Pop self-frame.
3351   __ leave();                 // Epilog
3352 
3353   // Jump to interpreter
3354   __ ret(0);
3355 
3356   // Make sure all code is generated
3357   masm->flush();
3358 
3359   _uncommon_trap_blob =  UncommonTrapBlob::create(&buffer, oop_maps,
3360                                                  SimpleRuntimeFrame::framesize >> 1);
3361 }
3362 #endif // COMPILER2
3363 
3364 
3365 //------------------------------generate_handler_blob------
3366 //
3367 // Generate a special Compile2Runtime blob that saves all registers,
3368 // and setup oopmap.
3369 //
3370 SafepointBlob* SharedRuntime::generate_handler_blob(address call_ptr, int poll_type) {
3371   assert(StubRoutines::forward_exception_entry() != NULL,
3372          "must be generated before");
3373 
3374   ResourceMark rm;
3375   OopMapSet *oop_maps = new OopMapSet();
3376   OopMap* map;
3377 
3378   // Allocate space for the code.  Setup code generation tools.
3379   CodeBuffer buffer("handler_blob", 2048, 1024);
3380   MacroAssembler* masm = new MacroAssembler(&buffer);
3381 
3382   address start   = __ pc();
3383   address call_pc = NULL;
3384   int frame_size_in_words;
3385   bool cause_return = (poll_type == POLL_AT_RETURN);
3386   bool save_vectors = (poll_type == POLL_AT_VECTOR_LOOP);
3387 
3388   if (UseRTMLocking) {
3389     // Abort RTM transaction before calling runtime
3390     // because critical section will be large and will be
3391     // aborted anyway. Also nmethod could be deoptimized.
3392     __ xabort(0);
3393   }
3394 
3395   // Make room for return address (or push it again)
3396   if (!cause_return) {
3397     __ push(rbx);
3398   }
3399 
3400   // Save registers, fpu state, and flags
3401   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, save_vectors);
3402 
3403   // The following is basically a call_VM.  However, we need the precise
3404   // address of the call in order to generate an oopmap. Hence, we do all the
3405   // work outselves.
3406 
3407   __ set_last_Java_frame(noreg, noreg, NULL);
3408 
3409   // The return address must always be correct so that frame constructor never
3410   // sees an invalid pc.
3411 
3412   if (!cause_return) {
3413     // Get the return pc saved by the signal handler and stash it in its appropriate place on the stack.
3414     // Additionally, rbx is a callee saved register and we can look at it later to determine
3415     // if someone changed the return address for us!
3416     __ movptr(rbx, Address(r15_thread, JavaThread::saved_exception_pc_offset()));
3417     __ movptr(Address(rbp, wordSize), rbx);
3418   }
3419 
3420   // Do the call
3421   __ mov(c_rarg0, r15_thread);
3422   __ call(RuntimeAddress(call_ptr));
3423 
3424   // Set an oopmap for the call site.  This oopmap will map all
3425   // oop-registers and debug-info registers as callee-saved.  This
3426   // will allow deoptimization at this safepoint to find all possible
3427   // debug-info recordings, as well as let GC find all oops.
3428 
3429   oop_maps->add_gc_map( __ pc() - start, map);
3430 
3431   Label noException;
3432 
3433   __ reset_last_Java_frame(false);
3434 
3435   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3436   __ jcc(Assembler::equal, noException);
3437 
3438   // Exception pending
3439 
3440   RegisterSaver::restore_live_registers(masm, save_vectors);
3441 
3442   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3443 
3444   // No exception case
3445   __ bind(noException);
3446 
3447   Label no_adjust, bail, no_prefix, not_special;
3448   if (SafepointMechanism::uses_thread_local_poll() && !cause_return) {
3449     // If our stashed return pc was modified by the runtime we avoid touching it
3450     __ cmpptr(rbx, Address(rbp, wordSize));
3451     __ jccb(Assembler::notEqual, no_adjust);
3452 
3453     // Skip over the poll instruction.
3454     // See NativeInstruction::is_safepoint_poll()
3455     // Possible encodings:
3456     //      85 00       test   %eax,(%rax)
3457     //      85 01       test   %eax,(%rcx)
3458     //      85 02       test   %eax,(%rdx)
3459     //      85 03       test   %eax,(%rbx)
3460     //      85 06       test   %eax,(%rsi)
3461     //      85 07       test   %eax,(%rdi)
3462     //
3463     //   41 85 00       test   %eax,(%r8)
3464     //   41 85 01       test   %eax,(%r9)
3465     //   41 85 02       test   %eax,(%r10)
3466     //   41 85 03       test   %eax,(%r11)
3467     //   41 85 06       test   %eax,(%r14)
3468     //   41 85 07       test   %eax,(%r15)
3469     //
3470     //      85 04 24    test   %eax,(%rsp)
3471     //   41 85 04 24    test   %eax,(%r12)
3472     //      85 45 00    test   %eax,0x0(%rbp)
3473     //   41 85 45 00    test   %eax,0x0(%r13)
3474 
3475     __ cmpb(Address(rbx, 0), NativeTstRegMem::instruction_rex_b_prefix);
3476     __ jcc(Assembler::notEqual, no_prefix);
3477     __ addptr(rbx, 1);
3478     __ bind(no_prefix);
3479 #ifdef ASSERT
3480     __ movptr(rax, rbx); // remember where 0x85 should be, for verification below
3481 #endif
3482     // r12/r13/rsp/rbp base encoding takes 3 bytes with the following register values:
3483     // r12/rsp 0x04
3484     // r13/rbp 0x05
3485     __ movzbq(rcx, Address(rbx, 1));
3486     __ andptr(rcx, 0x07); // looking for 0x04 .. 0x05
3487     __ subptr(rcx, 4);    // looking for 0x00 .. 0x01
3488     __ cmpptr(rcx, 1);
3489     __ jcc(Assembler::above, not_special);
3490     __ addptr(rbx, 1);
3491     __ bind(not_special);
3492 #ifdef ASSERT
3493     // Verify the correct encoding of the poll we're about to skip.
3494     __ cmpb(Address(rax, 0), NativeTstRegMem::instruction_code_memXregl);
3495     __ jcc(Assembler::notEqual, bail);
3496     // Mask out the modrm bits
3497     __ testb(Address(rax, 1), NativeTstRegMem::modrm_mask);
3498     // rax encodes to 0, so if the bits are nonzero it's incorrect
3499     __ jcc(Assembler::notZero, bail);
3500 #endif
3501     // Adjust return pc forward to step over the safepoint poll instruction
3502     __ addptr(rbx, 2);
3503     __ movptr(Address(rbp, wordSize), rbx);
3504   }
3505 
3506   __ bind(no_adjust);
3507   // Normal exit, restore registers and exit.
3508   RegisterSaver::restore_live_registers(masm, save_vectors);
3509   __ ret(0);
3510 
3511 #ifdef ASSERT
3512   __ bind(bail);
3513   __ stop("Attempting to adjust pc to skip safepoint poll but the return point is not what we expected");
3514 #endif
3515 
3516   // Make sure all code is generated
3517   masm->flush();
3518 
3519   // Fill-out other meta info
3520   return SafepointBlob::create(&buffer, oop_maps, frame_size_in_words);
3521 }
3522 
3523 //
3524 // generate_resolve_blob - call resolution (static/virtual/opt-virtual/ic-miss
3525 //
3526 // Generate a stub that calls into vm to find out the proper destination
3527 // of a java call. All the argument registers are live at this point
3528 // but since this is generic code we don't know what they are and the caller
3529 // must do any gc of the args.
3530 //
3531 RuntimeStub* SharedRuntime::generate_resolve_blob(address destination, const char* name) {
3532   assert (StubRoutines::forward_exception_entry() != NULL, "must be generated before");
3533 
3534   // allocate space for the code
3535   ResourceMark rm;
3536 
3537   CodeBuffer buffer(name, 1000, 512);
3538   MacroAssembler* masm                = new MacroAssembler(&buffer);
3539 
3540   int frame_size_in_words;
3541 
3542   OopMapSet *oop_maps = new OopMapSet();
3543   OopMap* map = NULL;
3544 
3545   int start = __ offset();
3546 
3547   // No need to save vector registers since they are caller-saved anyway.
3548   map = RegisterSaver::save_live_registers(masm, 0, &frame_size_in_words, /*save_vectors*/ false);
3549 
3550   int frame_complete = __ offset();
3551 
3552   __ set_last_Java_frame(noreg, noreg, NULL);
3553 
3554   __ mov(c_rarg0, r15_thread);
3555 
3556   __ call(RuntimeAddress(destination));
3557 
3558 
3559   // Set an oopmap for the call site.
3560   // We need this not only for callee-saved registers, but also for volatile
3561   // registers that the compiler might be keeping live across a safepoint.
3562 
3563   oop_maps->add_gc_map( __ offset() - start, map);
3564 
3565   // rax contains the address we are going to jump to assuming no exception got installed
3566 
3567   // clear last_Java_sp
3568   __ reset_last_Java_frame(false);
3569   // check for pending exceptions
3570   Label pending;
3571   __ cmpptr(Address(r15_thread, Thread::pending_exception_offset()), (int32_t)NULL_WORD);
3572   __ jcc(Assembler::notEqual, pending);
3573 
3574   // get the returned Method*
3575   __ get_vm_result_2(rbx, r15_thread);
3576   __ movptr(Address(rsp, RegisterSaver::rbx_offset_in_bytes()), rbx);
3577 
3578   __ movptr(Address(rsp, RegisterSaver::rax_offset_in_bytes()), rax);
3579 
3580   RegisterSaver::restore_live_registers(masm);
3581 
3582   // We are back the the original state on entry and ready to go.
3583 
3584   __ jmp(rax);
3585 
3586   // Pending exception after the safepoint
3587 
3588   __ bind(pending);
3589 
3590   RegisterSaver::restore_live_registers(masm);
3591 
3592   // exception pending => remove activation and forward to exception handler
3593 
3594   __ movptr(Address(r15_thread, JavaThread::vm_result_offset()), (int)NULL_WORD);
3595 
3596   __ movptr(rax, Address(r15_thread, Thread::pending_exception_offset()));
3597   __ jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
3598 
3599   // -------------
3600   // make sure all code is generated
3601   masm->flush();
3602 
3603   // return the  blob
3604   // frame_size_words or bytes??
3605   return RuntimeStub::new_runtime_stub(name, &buffer, frame_complete, frame_size_in_words, oop_maps, true);
3606 }
3607 
3608 
3609 //------------------------------Montgomery multiplication------------------------
3610 //
3611 
3612 #ifndef _WINDOWS
3613 
3614 // Subtract 0:b from carry:a.  Return carry.
3615 static julong
3616 sub(julong a[], julong b[], julong carry, long len) {
3617   long long i = 0, cnt = len;
3618   julong tmp;
3619   asm volatile("clc; "
3620                "0: ; "
3621                "mov (%[b], %[i], 8), %[tmp]; "
3622                "sbb %[tmp], (%[a], %[i], 8); "
3623                "inc %[i]; dec %[cnt]; "
3624                "jne 0b; "
3625                "mov %[carry], %[tmp]; sbb $0, %[tmp]; "
3626                : [i]"+r"(i), [cnt]"+r"(cnt), [tmp]"=&r"(tmp)
3627                : [a]"r"(a), [b]"r"(b), [carry]"r"(carry)
3628                : "memory");
3629   return tmp;
3630 }
3631 
3632 // Multiply (unsigned) Long A by Long B, accumulating the double-
3633 // length result into the accumulator formed of T0, T1, and T2.
3634 #define MACC(A, B, T0, T1, T2)                                  \
3635 do {                                                            \
3636   unsigned long hi, lo;                                         \
3637   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4"   \
3638            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3639            : "r"(A), "a"(B) : "cc");                            \
3640  } while(0)
3641 
3642 // As above, but add twice the double-length result into the
3643 // accumulator.
3644 #define MACC2(A, B, T0, T1, T2)                                 \
3645 do {                                                            \
3646   unsigned long hi, lo;                                         \
3647   __asm__ ("mul %5; add %%rax, %2; adc %%rdx, %3; adc $0, %4; " \
3648            "add %%rax, %2; adc %%rdx, %3; adc $0, %4"           \
3649            : "=&d"(hi), "=a"(lo), "+r"(T0), "+r"(T1), "+g"(T2)  \
3650            : "r"(A), "a"(B) : "cc");                            \
3651  } while(0)
3652 
3653 #else //_WINDOWS
3654 
3655 static julong
3656 sub(julong a[], julong b[], julong carry, long len) {
3657   long i;
3658   julong tmp;
3659   unsigned char c = 1;
3660   for (i = 0; i < len; i++) {
3661     c = _addcarry_u64(c, a[i], ~b[i], &tmp);
3662     a[i] = tmp;
3663   }
3664   c = _addcarry_u64(c, carry, ~0, &tmp);
3665   return tmp;
3666 }
3667 
3668 // Multiply (unsigned) Long A by Long B, accumulating the double-
3669 // length result into the accumulator formed of T0, T1, and T2.
3670 #define MACC(A, B, T0, T1, T2)                          \
3671 do {                                                    \
3672   julong hi, lo;                            \
3673   lo = _umul128(A, B, &hi);                             \
3674   unsigned char c = _addcarry_u64(0, lo, T0, &T0);      \
3675   c = _addcarry_u64(c, hi, T1, &T1);                    \
3676   _addcarry_u64(c, T2, 0, &T2);                         \
3677  } while(0)
3678 
3679 // As above, but add twice the double-length result into the
3680 // accumulator.
3681 #define MACC2(A, B, T0, T1, T2)                         \
3682 do {                                                    \
3683   julong hi, lo;                            \
3684   lo = _umul128(A, B, &hi);                             \
3685   unsigned char c = _addcarry_u64(0, lo, T0, &T0);      \
3686   c = _addcarry_u64(c, hi, T1, &T1);                    \
3687   _addcarry_u64(c, T2, 0, &T2);                         \
3688   c = _addcarry_u64(0, lo, T0, &T0);                    \
3689   c = _addcarry_u64(c, hi, T1, &T1);                    \
3690   _addcarry_u64(c, T2, 0, &T2);                         \
3691  } while(0)
3692 
3693 #endif //_WINDOWS
3694 
3695 // Fast Montgomery multiplication.  The derivation of the algorithm is
3696 // in  A Cryptographic Library for the Motorola DSP56000,
3697 // Dusse and Kaliski, Proc. EUROCRYPT 90, pp. 230-237.
3698 
3699 static void NOINLINE
3700 montgomery_multiply(julong a[], julong b[], julong n[],
3701                     julong m[], julong inv, int len) {
3702   julong t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3703   int i;
3704 
3705   assert(inv * n[0] == ULLONG_MAX, "broken inverse in Montgomery multiply");
3706 
3707   for (i = 0; i < len; i++) {
3708     int j;
3709     for (j = 0; j < i; j++) {
3710       MACC(a[j], b[i-j], t0, t1, t2);
3711       MACC(m[j], n[i-j], t0, t1, t2);
3712     }
3713     MACC(a[i], b[0], t0, t1, t2);
3714     m[i] = t0 * inv;
3715     MACC(m[i], n[0], t0, t1, t2);
3716 
3717     assert(t0 == 0, "broken Montgomery multiply");
3718 
3719     t0 = t1; t1 = t2; t2 = 0;
3720   }
3721 
3722   for (i = len; i < 2*len; i++) {
3723     int j;
3724     for (j = i-len+1; j < len; j++) {
3725       MACC(a[j], b[i-j], t0, t1, t2);
3726       MACC(m[j], n[i-j], t0, t1, t2);
3727     }
3728     m[i-len] = t0;
3729     t0 = t1; t1 = t2; t2 = 0;
3730   }
3731 
3732   while (t0)
3733     t0 = sub(m, n, t0, len);
3734 }
3735 
3736 // Fast Montgomery squaring.  This uses asymptotically 25% fewer
3737 // multiplies so it should be up to 25% faster than Montgomery
3738 // multiplication.  However, its loop control is more complex and it
3739 // may actually run slower on some machines.
3740 
3741 static void NOINLINE
3742 montgomery_square(julong a[], julong n[],
3743                   julong m[], julong inv, int len) {
3744   julong t0 = 0, t1 = 0, t2 = 0; // Triple-precision accumulator
3745   int i;
3746 
3747   assert(inv * n[0] == ULLONG_MAX, "broken inverse in Montgomery square");
3748 
3749   for (i = 0; i < len; i++) {
3750     int j;
3751     int end = (i+1)/2;
3752     for (j = 0; j < end; j++) {
3753       MACC2(a[j], a[i-j], t0, t1, t2);
3754       MACC(m[j], n[i-j], t0, t1, t2);
3755     }
3756     if ((i & 1) == 0) {
3757       MACC(a[j], a[j], t0, t1, t2);
3758     }
3759     for (; j < i; j++) {
3760       MACC(m[j], n[i-j], t0, t1, t2);
3761     }
3762     m[i] = t0 * inv;
3763     MACC(m[i], n[0], t0, t1, t2);
3764 
3765     assert(t0 == 0, "broken Montgomery square");
3766 
3767     t0 = t1; t1 = t2; t2 = 0;
3768   }
3769 
3770   for (i = len; i < 2*len; i++) {
3771     int start = i-len+1;
3772     int end = start + (len - start)/2;
3773     int j;
3774     for (j = start; j < end; j++) {
3775       MACC2(a[j], a[i-j], t0, t1, t2);
3776       MACC(m[j], n[i-j], t0, t1, t2);
3777     }
3778     if ((i & 1) == 0) {
3779       MACC(a[j], a[j], t0, t1, t2);
3780     }
3781     for (; j < len; j++) {
3782       MACC(m[j], n[i-j], t0, t1, t2);
3783     }
3784     m[i-len] = t0;
3785     t0 = t1; t1 = t2; t2 = 0;
3786   }
3787 
3788   while (t0)
3789     t0 = sub(m, n, t0, len);
3790 }
3791 
3792 // Swap words in a longword.
3793 static julong swap(julong x) {
3794   return (x << 32) | (x >> 32);
3795 }
3796 
3797 // Copy len longwords from s to d, word-swapping as we go.  The
3798 // destination array is reversed.
3799 static void reverse_words(julong *s, julong *d, int len) {
3800   d += len;
3801   while(len-- > 0) {
3802     d--;
3803     *d = swap(*s);
3804     s++;
3805   }
3806 }
3807 
3808 // The threshold at which squaring is advantageous was determined
3809 // experimentally on an i7-3930K (Ivy Bridge) CPU @ 3.5GHz.
3810 #define MONTGOMERY_SQUARING_THRESHOLD 64
3811 
3812 void SharedRuntime::montgomery_multiply(jint *a_ints, jint *b_ints, jint *n_ints,
3813                                         jint len, jlong inv,
3814                                         jint *m_ints) {
3815   assert(len % 2 == 0, "array length in montgomery_multiply must be even");
3816   int longwords = len/2;
3817 
3818   // Make very sure we don't use so much space that the stack might
3819   // overflow.  512 jints corresponds to an 16384-bit integer and
3820   // will use here a total of 8k bytes of stack space.
3821   int total_allocation = longwords * sizeof (julong) * 4;
3822   guarantee(total_allocation <= 8192, "must be");
3823   julong *scratch = (julong *)alloca(total_allocation);
3824 
3825   // Local scratch arrays
3826   julong
3827     *a = scratch + 0 * longwords,
3828     *b = scratch + 1 * longwords,
3829     *n = scratch + 2 * longwords,
3830     *m = scratch + 3 * longwords;
3831 
3832   reverse_words((julong *)a_ints, a, longwords);
3833   reverse_words((julong *)b_ints, b, longwords);
3834   reverse_words((julong *)n_ints, n, longwords);
3835 
3836   ::montgomery_multiply(a, b, n, m, (julong)inv, longwords);
3837 
3838   reverse_words(m, (julong *)m_ints, longwords);
3839 }
3840 
3841 void SharedRuntime::montgomery_square(jint *a_ints, jint *n_ints,
3842                                       jint len, jlong inv,
3843                                       jint *m_ints) {
3844   assert(len % 2 == 0, "array length in montgomery_square must be even");
3845   int longwords = len/2;
3846 
3847   // Make very sure we don't use so much space that the stack might
3848   // overflow.  512 jints corresponds to an 16384-bit integer and
3849   // will use here a total of 6k bytes of stack space.
3850   int total_allocation = longwords * sizeof (julong) * 3;
3851   guarantee(total_allocation <= 8192, "must be");
3852   julong *scratch = (julong *)alloca(total_allocation);
3853 
3854   // Local scratch arrays
3855   julong
3856     *a = scratch + 0 * longwords,
3857     *n = scratch + 1 * longwords,
3858     *m = scratch + 2 * longwords;
3859 
3860   reverse_words((julong *)a_ints, a, longwords);
3861   reverse_words((julong *)n_ints, n, longwords);
3862 
3863   if (len >= MONTGOMERY_SQUARING_THRESHOLD) {
3864     ::montgomery_square(a, n, m, (julong)inv, longwords);
3865   } else {
3866     ::montgomery_multiply(a, a, n, m, (julong)inv, longwords);
3867   }
3868 
3869   reverse_words(m, (julong *)m_ints, longwords);
3870 }
3871 
3872 #ifdef COMPILER2
3873 // This is here instead of runtime_x86_64.cpp because it uses SimpleRuntimeFrame
3874 //
3875 //------------------------------generate_exception_blob---------------------------
3876 // creates exception blob at the end
3877 // Using exception blob, this code is jumped from a compiled method.
3878 // (see emit_exception_handler in x86_64.ad file)
3879 //
3880 // Given an exception pc at a call we call into the runtime for the
3881 // handler in this method. This handler might merely restore state
3882 // (i.e. callee save registers) unwind the frame and jump to the
3883 // exception handler for the nmethod if there is no Java level handler
3884 // for the nmethod.
3885 //
3886 // This code is entered with a jmp.
3887 //
3888 // Arguments:
3889 //   rax: exception oop
3890 //   rdx: exception pc
3891 //
3892 // Results:
3893 //   rax: exception oop
3894 //   rdx: exception pc in caller or ???
3895 //   destination: exception handler of caller
3896 //
3897 // Note: the exception pc MUST be at a call (precise debug information)
3898 //       Registers rax, rdx, rcx, rsi, rdi, r8-r11 are not callee saved.
3899 //
3900 
3901 void OptoRuntime::generate_exception_blob() {
3902   assert(!OptoRuntime::is_callee_saved_register(RDX_num), "");
3903   assert(!OptoRuntime::is_callee_saved_register(RAX_num), "");
3904   assert(!OptoRuntime::is_callee_saved_register(RCX_num), "");
3905 
3906   assert(SimpleRuntimeFrame::framesize % 4 == 0, "sp not 16-byte aligned");
3907 
3908   // Allocate space for the code
3909   ResourceMark rm;
3910   // Setup code generation tools
3911   CodeBuffer buffer("exception_blob", 2048, 1024);
3912   MacroAssembler* masm = new MacroAssembler(&buffer);
3913 
3914 
3915   address start = __ pc();
3916 
3917   // Exception pc is 'return address' for stack walker
3918   __ push(rdx);
3919   __ subptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Prolog
3920 
3921   // Save callee-saved registers.  See x86_64.ad.
3922 
3923   // rbp is an implicitly saved callee saved register (i.e., the calling
3924   // convention will save/restore it in the prolog/epilog). Other than that
3925   // there are no callee save registers now that adapter frames are gone.
3926 
3927   __ movptr(Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt), rbp);
3928 
3929   // Store exception in Thread object. We cannot pass any arguments to the
3930   // handle_exception call, since we do not want to make any assumption
3931   // about the size of the frame where the exception happened in.
3932   // c_rarg0 is either rdi (Linux) or rcx (Windows).
3933   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()),rax);
3934   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), rdx);
3935 
3936   // This call does all the hard work.  It checks if an exception handler
3937   // exists in the method.
3938   // If so, it returns the handler address.
3939   // If not, it prepares for stack-unwinding, restoring the callee-save
3940   // registers of the frame being removed.
3941   //
3942   // address OptoRuntime::handle_exception_C(JavaThread* thread)
3943 
3944   // At a method handle call, the stack may not be properly aligned
3945   // when returning with an exception.
3946   address the_pc = __ pc();
3947   __ set_last_Java_frame(noreg, noreg, the_pc);
3948   __ mov(c_rarg0, r15_thread);
3949   __ andptr(rsp, -(StackAlignmentInBytes));    // Align stack
3950   __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, OptoRuntime::handle_exception_C)));
3951 
3952   // Set an oopmap for the call site.  This oopmap will only be used if we
3953   // are unwinding the stack.  Hence, all locations will be dead.
3954   // Callee-saved registers will be the same as the frame above (i.e.,
3955   // handle_exception_stub), since they were restored when we got the
3956   // exception.
3957 
3958   OopMapSet* oop_maps = new OopMapSet();
3959 
3960   oop_maps->add_gc_map(the_pc - start, new OopMap(SimpleRuntimeFrame::framesize, 0));
3961 
3962   __ reset_last_Java_frame(false);
3963 
3964   // Restore callee-saved registers
3965 
3966   // rbp is an implicitly saved callee-saved register (i.e., the calling
3967   // convention will save restore it in prolog/epilog) Other than that
3968   // there are no callee save registers now that adapter frames are gone.
3969 
3970   __ movptr(rbp, Address(rsp, SimpleRuntimeFrame::rbp_off << LogBytesPerInt));
3971 
3972   __ addptr(rsp, SimpleRuntimeFrame::return_off << LogBytesPerInt); // Epilog
3973   __ pop(rdx);                  // No need for exception pc anymore
3974 
3975   // rax: exception handler
3976 
3977   // We have a handler in rax (could be deopt blob).
3978   __ mov(r8, rax);
3979 
3980   // Get the exception oop
3981   __ movptr(rax, Address(r15_thread, JavaThread::exception_oop_offset()));
3982   // Get the exception pc in case we are deoptimized
3983   __ movptr(rdx, Address(r15_thread, JavaThread::exception_pc_offset()));
3984 #ifdef ASSERT
3985   __ movptr(Address(r15_thread, JavaThread::exception_handler_pc_offset()), (int)NULL_WORD);
3986   __ movptr(Address(r15_thread, JavaThread::exception_pc_offset()), (int)NULL_WORD);
3987 #endif
3988   // Clear the exception oop so GC no longer processes it as a root.
3989   __ movptr(Address(r15_thread, JavaThread::exception_oop_offset()), (int)NULL_WORD);
3990 
3991   // rax: exception oop
3992   // r8:  exception handler
3993   // rdx: exception pc
3994   // Jump to handler
3995 
3996   __ jmp(r8);
3997 
3998   // Make sure all code is generated
3999   masm->flush();
4000 
4001   // Set exception blob
4002   _exception_blob =  ExceptionBlob::create(&buffer, oop_maps, SimpleRuntimeFrame::framesize >> 1);
4003 }
4004 #endif // COMPILER2