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