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