1 /*
   2  * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "asm/assembler.hpp"
  27 #include "asm/assembler.inline.hpp"
  28 #include "compiler/disassembler.hpp"
  29 #include "gc/shared/cardTableModRefBS.hpp"
  30 #include "gc/shared/collectedHeap.inline.hpp"
  31 #include "interpreter/interpreter.hpp"
  32 #include "memory/resourceArea.hpp"
  33 #include "memory/universe.hpp"
  34 #include "oops/klass.inline.hpp"
  35 #include "prims/methodHandles.hpp"
  36 #include "runtime/biasedLocking.hpp"
  37 #include "runtime/interfaceSupport.hpp"
  38 #include "runtime/objectMonitor.hpp"
  39 #include "runtime/os.hpp"
  40 #include "runtime/sharedRuntime.hpp"
  41 #include "runtime/stubRoutines.hpp"
  42 #include "utilities/macros.hpp"
  43 #if INCLUDE_ALL_GCS
  44 #include "gc/g1/g1CollectedHeap.inline.hpp"
  45 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  46 #include "gc/g1/heapRegion.hpp"
  47 #endif // INCLUDE_ALL_GCS
  48 #include "crc32c.h"
  49 
  50 #ifdef PRODUCT
  51 #define BLOCK_COMMENT(str) /* nothing */
  52 #define STOP(error) stop(error)
  53 #else
  54 #define BLOCK_COMMENT(str) block_comment(str)
  55 #define STOP(error) block_comment(error); stop(error)
  56 #endif
  57 
  58 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  59 
  60 #ifdef ASSERT
  61 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  62 #endif
  63 
  64 static Assembler::Condition reverse[] = {
  65     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  66     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  67     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  68     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  69     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  70     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  71     Assembler::above          /* belowEqual    = 0x6 */ ,
  72     Assembler::belowEqual     /* above         = 0x7 */ ,
  73     Assembler::positive       /* negative      = 0x8 */ ,
  74     Assembler::negative       /* positive      = 0x9 */ ,
  75     Assembler::noParity       /* parity        = 0xa */ ,
  76     Assembler::parity         /* noParity      = 0xb */ ,
  77     Assembler::greaterEqual   /* less          = 0xc */ ,
  78     Assembler::less           /* greaterEqual  = 0xd */ ,
  79     Assembler::greater        /* lessEqual     = 0xe */ ,
  80     Assembler::lessEqual      /* greater       = 0xf, */
  81 
  82 };
  83 
  84 
  85 // Implementation of MacroAssembler
  86 
  87 // First all the versions that have distinct versions depending on 32/64 bit
  88 // Unless the difference is trivial (1 line or so).
  89 
  90 #ifndef _LP64
  91 
  92 // 32bit versions
  93 
  94 Address MacroAssembler::as_Address(AddressLiteral adr) {
  95   return Address(adr.target(), adr.rspec());
  96 }
  97 
  98 Address MacroAssembler::as_Address(ArrayAddress adr) {
  99   return Address::make_array(adr);
 100 }
 101 
 102 void MacroAssembler::call_VM_leaf_base(address entry_point,
 103                                        int number_of_arguments) {
 104   call(RuntimeAddress(entry_point));
 105   increment(rsp, number_of_arguments * wordSize);
 106 }
 107 
 108 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 109   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 110 }
 111 
 112 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 113   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 114 }
 115 
 116 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 117   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 118 }
 119 
 120 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 121   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 122 }
 123 
 124 void MacroAssembler::extend_sign(Register hi, Register lo) {
 125   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 126   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 127     cdql();
 128   } else {
 129     movl(hi, lo);
 130     sarl(hi, 31);
 131   }
 132 }
 133 
 134 void MacroAssembler::jC2(Register tmp, Label& L) {
 135   // set parity bit if FPU flag C2 is set (via rax)
 136   save_rax(tmp);
 137   fwait(); fnstsw_ax();
 138   sahf();
 139   restore_rax(tmp);
 140   // branch
 141   jcc(Assembler::parity, L);
 142 }
 143 
 144 void MacroAssembler::jnC2(Register tmp, Label& L) {
 145   // set parity bit if FPU flag C2 is set (via rax)
 146   save_rax(tmp);
 147   fwait(); fnstsw_ax();
 148   sahf();
 149   restore_rax(tmp);
 150   // branch
 151   jcc(Assembler::noParity, L);
 152 }
 153 
 154 // 32bit can do a case table jump in one instruction but we no longer allow the base
 155 // to be installed in the Address class
 156 void MacroAssembler::jump(ArrayAddress entry) {
 157   jmp(as_Address(entry));
 158 }
 159 
 160 // Note: y_lo will be destroyed
 161 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 162   // Long compare for Java (semantics as described in JVM spec.)
 163   Label high, low, done;
 164 
 165   cmpl(x_hi, y_hi);
 166   jcc(Assembler::less, low);
 167   jcc(Assembler::greater, high);
 168   // x_hi is the return register
 169   xorl(x_hi, x_hi);
 170   cmpl(x_lo, y_lo);
 171   jcc(Assembler::below, low);
 172   jcc(Assembler::equal, done);
 173 
 174   bind(high);
 175   xorl(x_hi, x_hi);
 176   increment(x_hi);
 177   jmp(done);
 178 
 179   bind(low);
 180   xorl(x_hi, x_hi);
 181   decrementl(x_hi);
 182 
 183   bind(done);
 184 }
 185 
 186 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 187     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 188 }
 189 
 190 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 191   // leal(dst, as_Address(adr));
 192   // see note in movl as to why we must use a move
 193   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 194 }
 195 
 196 void MacroAssembler::leave() {
 197   mov(rsp, rbp);
 198   pop(rbp);
 199 }
 200 
 201 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 202   // Multiplication of two Java long values stored on the stack
 203   // as illustrated below. Result is in rdx:rax.
 204   //
 205   // rsp ---> [  ??  ] \               \
 206   //            ....    | y_rsp_offset  |
 207   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 208   //          [ y_hi ]                  | (in bytes)
 209   //            ....                    |
 210   //          [ x_lo ]                 /
 211   //          [ x_hi ]
 212   //            ....
 213   //
 214   // Basic idea: lo(result) = lo(x_lo * y_lo)
 215   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 216   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 217   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 218   Label quick;
 219   // load x_hi, y_hi and check if quick
 220   // multiplication is possible
 221   movl(rbx, x_hi);
 222   movl(rcx, y_hi);
 223   movl(rax, rbx);
 224   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 225   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 226   // do full multiplication
 227   // 1st step
 228   mull(y_lo);                                    // x_hi * y_lo
 229   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 230   // 2nd step
 231   movl(rax, x_lo);
 232   mull(rcx);                                     // x_lo * y_hi
 233   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 234   // 3rd step
 235   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 236   movl(rax, x_lo);
 237   mull(y_lo);                                    // x_lo * y_lo
 238   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 239 }
 240 
 241 void MacroAssembler::lneg(Register hi, Register lo) {
 242   negl(lo);
 243   adcl(hi, 0);
 244   negl(hi);
 245 }
 246 
 247 void MacroAssembler::lshl(Register hi, Register lo) {
 248   // Java shift left long support (semantics as described in JVM spec., p.305)
 249   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 250   // shift value is in rcx !
 251   assert(hi != rcx, "must not use rcx");
 252   assert(lo != rcx, "must not use rcx");
 253   const Register s = rcx;                        // shift count
 254   const int      n = BitsPerWord;
 255   Label L;
 256   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 257   cmpl(s, n);                                    // if (s < n)
 258   jcc(Assembler::less, L);                       // else (s >= n)
 259   movl(hi, lo);                                  // x := x << n
 260   xorl(lo, lo);
 261   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 262   bind(L);                                       // s (mod n) < n
 263   shldl(hi, lo);                                 // x := x << s
 264   shll(lo);
 265 }
 266 
 267 
 268 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 269   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 270   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 271   assert(hi != rcx, "must not use rcx");
 272   assert(lo != rcx, "must not use rcx");
 273   const Register s = rcx;                        // shift count
 274   const int      n = BitsPerWord;
 275   Label L;
 276   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 277   cmpl(s, n);                                    // if (s < n)
 278   jcc(Assembler::less, L);                       // else (s >= n)
 279   movl(lo, hi);                                  // x := x >> n
 280   if (sign_extension) sarl(hi, 31);
 281   else                xorl(hi, hi);
 282   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 283   bind(L);                                       // s (mod n) < n
 284   shrdl(lo, hi);                                 // x := x >> s
 285   if (sign_extension) sarl(hi);
 286   else                shrl(hi);
 287 }
 288 
 289 void MacroAssembler::movoop(Register dst, jobject obj) {
 290   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 291 }
 292 
 293 void MacroAssembler::movoop(Address dst, jobject obj) {
 294   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 295 }
 296 
 297 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 298   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 299 }
 300 
 301 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 302   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 303 }
 304 
 305 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 306   // scratch register is not used,
 307   // it is defined to match parameters of 64-bit version of this method.
 308   if (src.is_lval()) {
 309     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 310   } else {
 311     movl(dst, as_Address(src));
 312   }
 313 }
 314 
 315 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 316   movl(as_Address(dst), src);
 317 }
 318 
 319 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 320   movl(dst, as_Address(src));
 321 }
 322 
 323 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 324 void MacroAssembler::movptr(Address dst, intptr_t src) {
 325   movl(dst, src);
 326 }
 327 
 328 
 329 void MacroAssembler::pop_callee_saved_registers() {
 330   pop(rcx);
 331   pop(rdx);
 332   pop(rdi);
 333   pop(rsi);
 334 }
 335 
 336 void MacroAssembler::pop_fTOS() {
 337   fld_d(Address(rsp, 0));
 338   addl(rsp, 2 * wordSize);
 339 }
 340 
 341 void MacroAssembler::push_callee_saved_registers() {
 342   push(rsi);
 343   push(rdi);
 344   push(rdx);
 345   push(rcx);
 346 }
 347 
 348 void MacroAssembler::push_fTOS() {
 349   subl(rsp, 2 * wordSize);
 350   fstp_d(Address(rsp, 0));
 351 }
 352 
 353 
 354 void MacroAssembler::pushoop(jobject obj) {
 355   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 356 }
 357 
 358 void MacroAssembler::pushklass(Metadata* obj) {
 359   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 360 }
 361 
 362 void MacroAssembler::pushptr(AddressLiteral src) {
 363   if (src.is_lval()) {
 364     push_literal32((int32_t)src.target(), src.rspec());
 365   } else {
 366     pushl(as_Address(src));
 367   }
 368 }
 369 
 370 void MacroAssembler::set_word_if_not_zero(Register dst) {
 371   xorl(dst, dst);
 372   set_byte_if_not_zero(dst);
 373 }
 374 
 375 static void pass_arg0(MacroAssembler* masm, Register arg) {
 376   masm->push(arg);
 377 }
 378 
 379 static void pass_arg1(MacroAssembler* masm, Register arg) {
 380   masm->push(arg);
 381 }
 382 
 383 static void pass_arg2(MacroAssembler* masm, Register arg) {
 384   masm->push(arg);
 385 }
 386 
 387 static void pass_arg3(MacroAssembler* masm, Register arg) {
 388   masm->push(arg);
 389 }
 390 
 391 #ifndef PRODUCT
 392 extern "C" void findpc(intptr_t x);
 393 #endif
 394 
 395 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 396   // In order to get locks to work, we need to fake a in_VM state
 397   JavaThread* thread = JavaThread::current();
 398   JavaThreadState saved_state = thread->thread_state();
 399   thread->set_thread_state(_thread_in_vm);
 400   if (ShowMessageBoxOnError) {
 401     JavaThread* thread = JavaThread::current();
 402     JavaThreadState saved_state = thread->thread_state();
 403     thread->set_thread_state(_thread_in_vm);
 404     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 405       ttyLocker ttyl;
 406       BytecodeCounter::print();
 407     }
 408     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 409     // This is the value of eip which points to where verify_oop will return.
 410     if (os::message_box(msg, "Execution stopped, print registers?")) {
 411       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 412       BREAKPOINT;
 413     }
 414   } else {
 415     ttyLocker ttyl;
 416     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 417   }
 418   // Don't assert holding the ttyLock
 419     assert(false, "DEBUG MESSAGE: %s", msg);
 420   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 421 }
 422 
 423 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 424   ttyLocker ttyl;
 425   FlagSetting fs(Debugging, true);
 426   tty->print_cr("eip = 0x%08x", eip);
 427 #ifndef PRODUCT
 428   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 429     tty->cr();
 430     findpc(eip);
 431     tty->cr();
 432   }
 433 #endif
 434 #define PRINT_REG(rax) \
 435   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 436   PRINT_REG(rax);
 437   PRINT_REG(rbx);
 438   PRINT_REG(rcx);
 439   PRINT_REG(rdx);
 440   PRINT_REG(rdi);
 441   PRINT_REG(rsi);
 442   PRINT_REG(rbp);
 443   PRINT_REG(rsp);
 444 #undef PRINT_REG
 445   // Print some words near top of staack.
 446   int* dump_sp = (int*) rsp;
 447   for (int col1 = 0; col1 < 8; col1++) {
 448     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 449     os::print_location(tty, *dump_sp++);
 450   }
 451   for (int row = 0; row < 16; row++) {
 452     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 453     for (int col = 0; col < 8; col++) {
 454       tty->print(" 0x%08x", *dump_sp++);
 455     }
 456     tty->cr();
 457   }
 458   // Print some instructions around pc:
 459   Disassembler::decode((address)eip-64, (address)eip);
 460   tty->print_cr("--------");
 461   Disassembler::decode((address)eip, (address)eip+32);
 462 }
 463 
 464 void MacroAssembler::stop(const char* msg) {
 465   ExternalAddress message((address)msg);
 466   // push address of message
 467   pushptr(message.addr());
 468   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 469   pusha();                                            // push registers
 470   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 471   hlt();
 472 }
 473 
 474 void MacroAssembler::warn(const char* msg) {
 475   push_CPU_state();
 476 
 477   ExternalAddress message((address) msg);
 478   // push address of message
 479   pushptr(message.addr());
 480 
 481   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 482   addl(rsp, wordSize);       // discard argument
 483   pop_CPU_state();
 484 }
 485 
 486 void MacroAssembler::print_state() {
 487   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 488   pusha();                                            // push registers
 489 
 490   push_CPU_state();
 491   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 492   pop_CPU_state();
 493 
 494   popa();
 495   addl(rsp, wordSize);
 496 }
 497 
 498 #else // _LP64
 499 
 500 // 64 bit versions
 501 
 502 Address MacroAssembler::as_Address(AddressLiteral adr) {
 503   // amd64 always does this as a pc-rel
 504   // we can be absolute or disp based on the instruction type
 505   // jmp/call are displacements others are absolute
 506   assert(!adr.is_lval(), "must be rval");
 507   assert(reachable(adr), "must be");
 508   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 509 
 510 }
 511 
 512 Address MacroAssembler::as_Address(ArrayAddress adr) {
 513   AddressLiteral base = adr.base();
 514   lea(rscratch1, base);
 515   Address index = adr.index();
 516   assert(index._disp == 0, "must not have disp"); // maybe it can?
 517   Address array(rscratch1, index._index, index._scale, index._disp);
 518   return array;
 519 }
 520 
 521 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 522   Label L, E;
 523 
 524 #ifdef _WIN64
 525   // Windows always allocates space for it's register args
 526   assert(num_args <= 4, "only register arguments supported");
 527   subq(rsp,  frame::arg_reg_save_area_bytes);
 528 #endif
 529 
 530   // Align stack if necessary
 531   testl(rsp, 15);
 532   jcc(Assembler::zero, L);
 533 
 534   subq(rsp, 8);
 535   {
 536     call(RuntimeAddress(entry_point));
 537   }
 538   addq(rsp, 8);
 539   jmp(E);
 540 
 541   bind(L);
 542   {
 543     call(RuntimeAddress(entry_point));
 544   }
 545 
 546   bind(E);
 547 
 548 #ifdef _WIN64
 549   // restore stack pointer
 550   addq(rsp, frame::arg_reg_save_area_bytes);
 551 #endif
 552 
 553 }
 554 
 555 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 556   assert(!src2.is_lval(), "should use cmpptr");
 557 
 558   if (reachable(src2)) {
 559     cmpq(src1, as_Address(src2));
 560   } else {
 561     lea(rscratch1, src2);
 562     Assembler::cmpq(src1, Address(rscratch1, 0));
 563   }
 564 }
 565 
 566 int MacroAssembler::corrected_idivq(Register reg) {
 567   // Full implementation of Java ldiv and lrem; checks for special
 568   // case as described in JVM spec., p.243 & p.271.  The function
 569   // returns the (pc) offset of the idivl instruction - may be needed
 570   // for implicit exceptions.
 571   //
 572   //         normal case                           special case
 573   //
 574   // input : rax: dividend                         min_long
 575   //         reg: divisor   (may not be eax/edx)   -1
 576   //
 577   // output: rax: quotient  (= rax idiv reg)       min_long
 578   //         rdx: remainder (= rax irem reg)       0
 579   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 580   static const int64_t min_long = 0x8000000000000000;
 581   Label normal_case, special_case;
 582 
 583   // check for special case
 584   cmp64(rax, ExternalAddress((address) &min_long));
 585   jcc(Assembler::notEqual, normal_case);
 586   xorl(rdx, rdx); // prepare rdx for possible special case (where
 587                   // remainder = 0)
 588   cmpq(reg, -1);
 589   jcc(Assembler::equal, special_case);
 590 
 591   // handle normal case
 592   bind(normal_case);
 593   cdqq();
 594   int idivq_offset = offset();
 595   idivq(reg);
 596 
 597   // normal and special case exit
 598   bind(special_case);
 599 
 600   return idivq_offset;
 601 }
 602 
 603 void MacroAssembler::decrementq(Register reg, int value) {
 604   if (value == min_jint) { subq(reg, value); return; }
 605   if (value <  0) { incrementq(reg, -value); return; }
 606   if (value == 0) {                        ; return; }
 607   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 608   /* else */      { subq(reg, value)       ; return; }
 609 }
 610 
 611 void MacroAssembler::decrementq(Address dst, int value) {
 612   if (value == min_jint) { subq(dst, value); return; }
 613   if (value <  0) { incrementq(dst, -value); return; }
 614   if (value == 0) {                        ; return; }
 615   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 616   /* else */      { subq(dst, value)       ; return; }
 617 }
 618 
 619 void MacroAssembler::incrementq(AddressLiteral dst) {
 620   if (reachable(dst)) {
 621     incrementq(as_Address(dst));
 622   } else {
 623     lea(rscratch1, dst);
 624     incrementq(Address(rscratch1, 0));
 625   }
 626 }
 627 
 628 void MacroAssembler::incrementq(Register reg, int value) {
 629   if (value == min_jint) { addq(reg, value); return; }
 630   if (value <  0) { decrementq(reg, -value); return; }
 631   if (value == 0) {                        ; return; }
 632   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 633   /* else */      { addq(reg, value)       ; return; }
 634 }
 635 
 636 void MacroAssembler::incrementq(Address dst, int value) {
 637   if (value == min_jint) { addq(dst, value); return; }
 638   if (value <  0) { decrementq(dst, -value); return; }
 639   if (value == 0) {                        ; return; }
 640   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 641   /* else */      { addq(dst, value)       ; return; }
 642 }
 643 
 644 // 32bit can do a case table jump in one instruction but we no longer allow the base
 645 // to be installed in the Address class
 646 void MacroAssembler::jump(ArrayAddress entry) {
 647   lea(rscratch1, entry.base());
 648   Address dispatch = entry.index();
 649   assert(dispatch._base == noreg, "must be");
 650   dispatch._base = rscratch1;
 651   jmp(dispatch);
 652 }
 653 
 654 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 655   ShouldNotReachHere(); // 64bit doesn't use two regs
 656   cmpq(x_lo, y_lo);
 657 }
 658 
 659 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 660     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 661 }
 662 
 663 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 664   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 665   movptr(dst, rscratch1);
 666 }
 667 
 668 void MacroAssembler::leave() {
 669   // %%% is this really better? Why not on 32bit too?
 670   emit_int8((unsigned char)0xC9); // LEAVE
 671 }
 672 
 673 void MacroAssembler::lneg(Register hi, Register lo) {
 674   ShouldNotReachHere(); // 64bit doesn't use two regs
 675   negq(lo);
 676 }
 677 
 678 void MacroAssembler::movoop(Register dst, jobject obj) {
 679   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 680 }
 681 
 682 void MacroAssembler::movoop(Address dst, jobject obj) {
 683   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 684   movq(dst, rscratch1);
 685 }
 686 
 687 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 688   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 689 }
 690 
 691 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 692   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 693   movq(dst, rscratch1);
 694 }
 695 
 696 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 697   if (src.is_lval()) {
 698     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 699   } else {
 700     if (reachable(src)) {
 701       movq(dst, as_Address(src));
 702     } else {
 703       lea(scratch, src);
 704       movq(dst, Address(scratch, 0));
 705     }
 706   }
 707 }
 708 
 709 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 710   movq(as_Address(dst), src);
 711 }
 712 
 713 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 714   movq(dst, as_Address(src));
 715 }
 716 
 717 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 718 void MacroAssembler::movptr(Address dst, intptr_t src) {
 719   mov64(rscratch1, src);
 720   movq(dst, rscratch1);
 721 }
 722 
 723 // These are mostly for initializing NULL
 724 void MacroAssembler::movptr(Address dst, int32_t src) {
 725   movslq(dst, src);
 726 }
 727 
 728 void MacroAssembler::movptr(Register dst, int32_t src) {
 729   mov64(dst, (intptr_t)src);
 730 }
 731 
 732 void MacroAssembler::pushoop(jobject obj) {
 733   movoop(rscratch1, obj);
 734   push(rscratch1);
 735 }
 736 
 737 void MacroAssembler::pushklass(Metadata* obj) {
 738   mov_metadata(rscratch1, obj);
 739   push(rscratch1);
 740 }
 741 
 742 void MacroAssembler::pushptr(AddressLiteral src) {
 743   lea(rscratch1, src);
 744   if (src.is_lval()) {
 745     push(rscratch1);
 746   } else {
 747     pushq(Address(rscratch1, 0));
 748   }
 749 }
 750 
 751 void MacroAssembler::reset_last_Java_frame(bool clear_fp,
 752                                            bool clear_pc) {
 753   // we must set sp to zero to clear frame
 754   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 755   // must clear fp, so that compiled frames are not confused; it is
 756   // possible that we need it only for debugging
 757   if (clear_fp) {
 758     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 759   }
 760 
 761   if (clear_pc) {
 762     movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 763   }
 764 }
 765 
 766 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 767                                          Register last_java_fp,
 768                                          address  last_java_pc) {
 769   // determine last_java_sp register
 770   if (!last_java_sp->is_valid()) {
 771     last_java_sp = rsp;
 772   }
 773 
 774   // last_java_fp is optional
 775   if (last_java_fp->is_valid()) {
 776     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 777            last_java_fp);
 778   }
 779 
 780   // last_java_pc is optional
 781   if (last_java_pc != NULL) {
 782     Address java_pc(r15_thread,
 783                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 784     lea(rscratch1, InternalAddress(last_java_pc));
 785     movptr(java_pc, rscratch1);
 786   }
 787 
 788   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 789 }
 790 
 791 static void pass_arg0(MacroAssembler* masm, Register arg) {
 792   if (c_rarg0 != arg ) {
 793     masm->mov(c_rarg0, arg);
 794   }
 795 }
 796 
 797 static void pass_arg1(MacroAssembler* masm, Register arg) {
 798   if (c_rarg1 != arg ) {
 799     masm->mov(c_rarg1, arg);
 800   }
 801 }
 802 
 803 static void pass_arg2(MacroAssembler* masm, Register arg) {
 804   if (c_rarg2 != arg ) {
 805     masm->mov(c_rarg2, arg);
 806   }
 807 }
 808 
 809 static void pass_arg3(MacroAssembler* masm, Register arg) {
 810   if (c_rarg3 != arg ) {
 811     masm->mov(c_rarg3, arg);
 812   }
 813 }
 814 
 815 void MacroAssembler::stop(const char* msg) {
 816   address rip = pc();
 817   pusha(); // get regs on stack
 818   lea(c_rarg0, ExternalAddress((address) msg));
 819   lea(c_rarg1, InternalAddress(rip));
 820   movq(c_rarg2, rsp); // pass pointer to regs array
 821   andq(rsp, -16); // align stack as required by ABI
 822   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 823   hlt();
 824 }
 825 
 826 void MacroAssembler::warn(const char* msg) {
 827   push(rbp);
 828   movq(rbp, rsp);
 829   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 830   push_CPU_state();   // keeps alignment at 16 bytes
 831   lea(c_rarg0, ExternalAddress((address) msg));
 832   call_VM_leaf(CAST_FROM_FN_PTR(address, warning), c_rarg0);
 833   pop_CPU_state();
 834   mov(rsp, rbp);
 835   pop(rbp);
 836 }
 837 
 838 void MacroAssembler::print_state() {
 839   address rip = pc();
 840   pusha();            // get regs on stack
 841   push(rbp);
 842   movq(rbp, rsp);
 843   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 844   push_CPU_state();   // keeps alignment at 16 bytes
 845 
 846   lea(c_rarg0, InternalAddress(rip));
 847   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 848   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 849 
 850   pop_CPU_state();
 851   mov(rsp, rbp);
 852   pop(rbp);
 853   popa();
 854 }
 855 
 856 #ifndef PRODUCT
 857 extern "C" void findpc(intptr_t x);
 858 #endif
 859 
 860 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 861   // In order to get locks to work, we need to fake a in_VM state
 862   if (ShowMessageBoxOnError) {
 863     JavaThread* thread = JavaThread::current();
 864     JavaThreadState saved_state = thread->thread_state();
 865     thread->set_thread_state(_thread_in_vm);
 866 #ifndef PRODUCT
 867     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 868       ttyLocker ttyl;
 869       BytecodeCounter::print();
 870     }
 871 #endif
 872     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 873     // XXX correct this offset for amd64
 874     // This is the value of eip which points to where verify_oop will return.
 875     if (os::message_box(msg, "Execution stopped, print registers?")) {
 876       print_state64(pc, regs);
 877       BREAKPOINT;
 878       assert(false, "start up GDB");
 879     }
 880     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 881   } else {
 882     ttyLocker ttyl;
 883     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 884                     msg);
 885     assert(false, "DEBUG MESSAGE: %s", msg);
 886   }
 887 }
 888 
 889 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 890   ttyLocker ttyl;
 891   FlagSetting fs(Debugging, true);
 892   tty->print_cr("rip = 0x%016lx", pc);
 893 #ifndef PRODUCT
 894   tty->cr();
 895   findpc(pc);
 896   tty->cr();
 897 #endif
 898 #define PRINT_REG(rax, value) \
 899   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 900   PRINT_REG(rax, regs[15]);
 901   PRINT_REG(rbx, regs[12]);
 902   PRINT_REG(rcx, regs[14]);
 903   PRINT_REG(rdx, regs[13]);
 904   PRINT_REG(rdi, regs[8]);
 905   PRINT_REG(rsi, regs[9]);
 906   PRINT_REG(rbp, regs[10]);
 907   PRINT_REG(rsp, regs[11]);
 908   PRINT_REG(r8 , regs[7]);
 909   PRINT_REG(r9 , regs[6]);
 910   PRINT_REG(r10, regs[5]);
 911   PRINT_REG(r11, regs[4]);
 912   PRINT_REG(r12, regs[3]);
 913   PRINT_REG(r13, regs[2]);
 914   PRINT_REG(r14, regs[1]);
 915   PRINT_REG(r15, regs[0]);
 916 #undef PRINT_REG
 917   // Print some words near top of staack.
 918   int64_t* rsp = (int64_t*) regs[11];
 919   int64_t* dump_sp = rsp;
 920   for (int col1 = 0; col1 < 8; col1++) {
 921     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 922     os::print_location(tty, *dump_sp++);
 923   }
 924   for (int row = 0; row < 25; row++) {
 925     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (int64_t)dump_sp);
 926     for (int col = 0; col < 4; col++) {
 927       tty->print(" 0x%016lx", *dump_sp++);
 928     }
 929     tty->cr();
 930   }
 931   // Print some instructions around pc:
 932   Disassembler::decode((address)pc-64, (address)pc);
 933   tty->print_cr("--------");
 934   Disassembler::decode((address)pc, (address)pc+32);
 935 }
 936 
 937 #endif // _LP64
 938 
 939 // Now versions that are common to 32/64 bit
 940 
 941 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 942   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 943 }
 944 
 945 void MacroAssembler::addptr(Register dst, Register src) {
 946   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 947 }
 948 
 949 void MacroAssembler::addptr(Address dst, Register src) {
 950   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 951 }
 952 
 953 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 954   if (reachable(src)) {
 955     Assembler::addsd(dst, as_Address(src));
 956   } else {
 957     lea(rscratch1, src);
 958     Assembler::addsd(dst, Address(rscratch1, 0));
 959   }
 960 }
 961 
 962 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 963   if (reachable(src)) {
 964     addss(dst, as_Address(src));
 965   } else {
 966     lea(rscratch1, src);
 967     addss(dst, Address(rscratch1, 0));
 968   }
 969 }
 970 
 971 void MacroAssembler::align(int modulus) {
 972   align(modulus, offset());
 973 }
 974 
 975 void MacroAssembler::align(int modulus, int target) {
 976   if (target % modulus != 0) {
 977     nop(modulus - (target % modulus));
 978   }
 979 }
 980 
 981 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
 982   // Used in sign-masking with aligned address.
 983   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 984   if (reachable(src)) {
 985     Assembler::andpd(dst, as_Address(src));
 986   } else {
 987     lea(rscratch1, src);
 988     Assembler::andpd(dst, Address(rscratch1, 0));
 989   }
 990 }
 991 
 992 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
 993   // Used in sign-masking with aligned address.
 994   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
 995   if (reachable(src)) {
 996     Assembler::andps(dst, as_Address(src));
 997   } else {
 998     lea(rscratch1, src);
 999     Assembler::andps(dst, Address(rscratch1, 0));
1000   }
1001 }
1002 
1003 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1004   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1005 }
1006 
1007 void MacroAssembler::atomic_incl(Address counter_addr) {
1008   if (os::is_MP())
1009     lock();
1010   incrementl(counter_addr);
1011 }
1012 
1013 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1014   if (reachable(counter_addr)) {
1015     atomic_incl(as_Address(counter_addr));
1016   } else {
1017     lea(scr, counter_addr);
1018     atomic_incl(Address(scr, 0));
1019   }
1020 }
1021 
1022 #ifdef _LP64
1023 void MacroAssembler::atomic_incq(Address counter_addr) {
1024   if (os::is_MP())
1025     lock();
1026   incrementq(counter_addr);
1027 }
1028 
1029 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1030   if (reachable(counter_addr)) {
1031     atomic_incq(as_Address(counter_addr));
1032   } else {
1033     lea(scr, counter_addr);
1034     atomic_incq(Address(scr, 0));
1035   }
1036 }
1037 #endif
1038 
1039 // Writes to stack successive pages until offset reached to check for
1040 // stack overflow + shadow pages.  This clobbers tmp.
1041 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1042   movptr(tmp, rsp);
1043   // Bang stack for total size given plus shadow page size.
1044   // Bang one page at a time because large size can bang beyond yellow and
1045   // red zones.
1046   Label loop;
1047   bind(loop);
1048   movl(Address(tmp, (-os::vm_page_size())), size );
1049   subptr(tmp, os::vm_page_size());
1050   subl(size, os::vm_page_size());
1051   jcc(Assembler::greater, loop);
1052 
1053   // Bang down shadow pages too.
1054   // At this point, (tmp-0) is the last address touched, so don't
1055   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1056   // was post-decremented.)  Skip this address by starting at i=1, and
1057   // touch a few more pages below.  N.B.  It is important to touch all
1058   // the way down to and including i=StackShadowPages.
1059   for (int i = 1; i < StackShadowPages; i++) {
1060     // this could be any sized move but this is can be a debugging crumb
1061     // so the bigger the better.
1062     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1063   }
1064 }
1065 
1066 int MacroAssembler::biased_locking_enter(Register lock_reg,
1067                                          Register obj_reg,
1068                                          Register swap_reg,
1069                                          Register tmp_reg,
1070                                          bool swap_reg_contains_mark,
1071                                          Label& done,
1072                                          Label* slow_case,
1073                                          BiasedLockingCounters* counters) {
1074   assert(UseBiasedLocking, "why call this otherwise?");
1075   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1076   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1077   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1078   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1079   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1080   Address saved_mark_addr(lock_reg, 0);
1081 
1082   if (PrintBiasedLockingStatistics && counters == NULL) {
1083     counters = BiasedLocking::counters();
1084   }
1085   // Biased locking
1086   // See whether the lock is currently biased toward our thread and
1087   // whether the epoch is still valid
1088   // Note that the runtime guarantees sufficient alignment of JavaThread
1089   // pointers to allow age to be placed into low bits
1090   // First check to see whether biasing is even enabled for this object
1091   Label cas_label;
1092   int null_check_offset = -1;
1093   if (!swap_reg_contains_mark) {
1094     null_check_offset = offset();
1095     movptr(swap_reg, mark_addr);
1096   }
1097   movptr(tmp_reg, swap_reg);
1098   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1099   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1100   jcc(Assembler::notEqual, cas_label);
1101   // The bias pattern is present in the object's header. Need to check
1102   // whether the bias owner and the epoch are both still current.
1103 #ifndef _LP64
1104   // Note that because there is no current thread register on x86_32 we
1105   // need to store off the mark word we read out of the object to
1106   // avoid reloading it and needing to recheck invariants below. This
1107   // store is unfortunate but it makes the overall code shorter and
1108   // simpler.
1109   movptr(saved_mark_addr, swap_reg);
1110 #endif
1111   if (swap_reg_contains_mark) {
1112     null_check_offset = offset();
1113   }
1114   load_prototype_header(tmp_reg, obj_reg);
1115 #ifdef _LP64
1116   orptr(tmp_reg, r15_thread);
1117   xorptr(tmp_reg, swap_reg);
1118   Register header_reg = tmp_reg;
1119 #else
1120   xorptr(tmp_reg, swap_reg);
1121   get_thread(swap_reg);
1122   xorptr(swap_reg, tmp_reg);
1123   Register header_reg = swap_reg;
1124 #endif
1125   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1126   if (counters != NULL) {
1127     cond_inc32(Assembler::zero,
1128                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1129   }
1130   jcc(Assembler::equal, done);
1131 
1132   Label try_revoke_bias;
1133   Label try_rebias;
1134 
1135   // At this point we know that the header has the bias pattern and
1136   // that we are not the bias owner in the current epoch. We need to
1137   // figure out more details about the state of the header in order to
1138   // know what operations can be legally performed on the object's
1139   // header.
1140 
1141   // If the low three bits in the xor result aren't clear, that means
1142   // the prototype header is no longer biased and we have to revoke
1143   // the bias on this object.
1144   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1145   jccb(Assembler::notZero, try_revoke_bias);
1146 
1147   // Biasing is still enabled for this data type. See whether the
1148   // epoch of the current bias is still valid, meaning that the epoch
1149   // bits of the mark word are equal to the epoch bits of the
1150   // prototype header. (Note that the prototype header's epoch bits
1151   // only change at a safepoint.) If not, attempt to rebias the object
1152   // toward the current thread. Note that we must be absolutely sure
1153   // that the current epoch is invalid in order to do this because
1154   // otherwise the manipulations it performs on the mark word are
1155   // illegal.
1156   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1157   jccb(Assembler::notZero, try_rebias);
1158 
1159   // The epoch of the current bias is still valid but we know nothing
1160   // about the owner; it might be set or it might be clear. Try to
1161   // acquire the bias of the object using an atomic operation. If this
1162   // fails we will go in to the runtime to revoke the object's bias.
1163   // Note that we first construct the presumed unbiased header so we
1164   // don't accidentally blow away another thread's valid bias.
1165   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1166   andptr(swap_reg,
1167          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1168 #ifdef _LP64
1169   movptr(tmp_reg, swap_reg);
1170   orptr(tmp_reg, r15_thread);
1171 #else
1172   get_thread(tmp_reg);
1173   orptr(tmp_reg, swap_reg);
1174 #endif
1175   if (os::is_MP()) {
1176     lock();
1177   }
1178   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1179   // If the biasing toward our thread failed, this means that
1180   // another thread succeeded in biasing it toward itself and we
1181   // need to revoke that bias. The revocation will occur in the
1182   // interpreter runtime in the slow case.
1183   if (counters != NULL) {
1184     cond_inc32(Assembler::zero,
1185                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1186   }
1187   if (slow_case != NULL) {
1188     jcc(Assembler::notZero, *slow_case);
1189   }
1190   jmp(done);
1191 
1192   bind(try_rebias);
1193   // At this point we know the epoch has expired, meaning that the
1194   // current "bias owner", if any, is actually invalid. Under these
1195   // circumstances _only_, we are allowed to use the current header's
1196   // value as the comparison value when doing the cas to acquire the
1197   // bias in the current epoch. In other words, we allow transfer of
1198   // the bias from one thread to another directly in this situation.
1199   //
1200   // FIXME: due to a lack of registers we currently blow away the age
1201   // bits in this situation. Should attempt to preserve them.
1202   load_prototype_header(tmp_reg, obj_reg);
1203 #ifdef _LP64
1204   orptr(tmp_reg, r15_thread);
1205 #else
1206   get_thread(swap_reg);
1207   orptr(tmp_reg, swap_reg);
1208   movptr(swap_reg, saved_mark_addr);
1209 #endif
1210   if (os::is_MP()) {
1211     lock();
1212   }
1213   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1214   // If the biasing toward our thread failed, then another thread
1215   // succeeded in biasing it toward itself and we need to revoke that
1216   // bias. The revocation will occur in the runtime in the slow case.
1217   if (counters != NULL) {
1218     cond_inc32(Assembler::zero,
1219                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1220   }
1221   if (slow_case != NULL) {
1222     jcc(Assembler::notZero, *slow_case);
1223   }
1224   jmp(done);
1225 
1226   bind(try_revoke_bias);
1227   // The prototype mark in the klass doesn't have the bias bit set any
1228   // more, indicating that objects of this data type are not supposed
1229   // to be biased any more. We are going to try to reset the mark of
1230   // this object to the prototype value and fall through to the
1231   // CAS-based locking scheme. Note that if our CAS fails, it means
1232   // that another thread raced us for the privilege of revoking the
1233   // bias of this particular object, so it's okay to continue in the
1234   // normal locking code.
1235   //
1236   // FIXME: due to a lack of registers we currently blow away the age
1237   // bits in this situation. Should attempt to preserve them.
1238   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1239   load_prototype_header(tmp_reg, obj_reg);
1240   if (os::is_MP()) {
1241     lock();
1242   }
1243   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1244   // Fall through to the normal CAS-based lock, because no matter what
1245   // the result of the above CAS, some thread must have succeeded in
1246   // removing the bias bit from the object's header.
1247   if (counters != NULL) {
1248     cond_inc32(Assembler::zero,
1249                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1250   }
1251 
1252   bind(cas_label);
1253 
1254   return null_check_offset;
1255 }
1256 
1257 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1258   assert(UseBiasedLocking, "why call this otherwise?");
1259 
1260   // Check for biased locking unlock case, which is a no-op
1261   // Note: we do not have to check the thread ID for two reasons.
1262   // First, the interpreter checks for IllegalMonitorStateException at
1263   // a higher level. Second, if the bias was revoked while we held the
1264   // lock, the object could not be rebiased toward another thread, so
1265   // the bias bit would be clear.
1266   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1267   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1268   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1269   jcc(Assembler::equal, done);
1270 }
1271 
1272 #ifdef COMPILER2
1273 
1274 #if INCLUDE_RTM_OPT
1275 
1276 // Update rtm_counters based on abort status
1277 // input: abort_status
1278 //        rtm_counters (RTMLockingCounters*)
1279 // flags are killed
1280 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1281 
1282   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1283   if (PrintPreciseRTMLockingStatistics) {
1284     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1285       Label check_abort;
1286       testl(abort_status, (1<<i));
1287       jccb(Assembler::equal, check_abort);
1288       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1289       bind(check_abort);
1290     }
1291   }
1292 }
1293 
1294 // Branch if (random & (count-1) != 0), count is 2^n
1295 // tmp, scr and flags are killed
1296 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1297   assert(tmp == rax, "");
1298   assert(scr == rdx, "");
1299   rdtsc(); // modifies EDX:EAX
1300   andptr(tmp, count-1);
1301   jccb(Assembler::notZero, brLabel);
1302 }
1303 
1304 // Perform abort ratio calculation, set no_rtm bit if high ratio
1305 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1306 // tmpReg, rtm_counters_Reg and flags are killed
1307 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1308                                                  Register rtm_counters_Reg,
1309                                                  RTMLockingCounters* rtm_counters,
1310                                                  Metadata* method_data) {
1311   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1312 
1313   if (RTMLockingCalculationDelay > 0) {
1314     // Delay calculation
1315     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1316     testptr(tmpReg, tmpReg);
1317     jccb(Assembler::equal, L_done);
1318   }
1319   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1320   //   Aborted transactions = abort_count * 100
1321   //   All transactions = total_count *  RTMTotalCountIncrRate
1322   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1323 
1324   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1325   cmpptr(tmpReg, RTMAbortThreshold);
1326   jccb(Assembler::below, L_check_always_rtm2);
1327   imulptr(tmpReg, tmpReg, 100);
1328 
1329   Register scrReg = rtm_counters_Reg;
1330   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1331   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1332   imulptr(scrReg, scrReg, RTMAbortRatio);
1333   cmpptr(tmpReg, scrReg);
1334   jccb(Assembler::below, L_check_always_rtm1);
1335   if (method_data != NULL) {
1336     // set rtm_state to "no rtm" in MDO
1337     mov_metadata(tmpReg, method_data);
1338     if (os::is_MP()) {
1339       lock();
1340     }
1341     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1342   }
1343   jmpb(L_done);
1344   bind(L_check_always_rtm1);
1345   // Reload RTMLockingCounters* address
1346   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1347   bind(L_check_always_rtm2);
1348   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1349   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1350   jccb(Assembler::below, L_done);
1351   if (method_data != NULL) {
1352     // set rtm_state to "always rtm" in MDO
1353     mov_metadata(tmpReg, method_data);
1354     if (os::is_MP()) {
1355       lock();
1356     }
1357     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1358   }
1359   bind(L_done);
1360 }
1361 
1362 // Update counters and perform abort ratio calculation
1363 // input:  abort_status_Reg
1364 // rtm_counters_Reg, flags are killed
1365 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1366                                    Register rtm_counters_Reg,
1367                                    RTMLockingCounters* rtm_counters,
1368                                    Metadata* method_data,
1369                                    bool profile_rtm) {
1370 
1371   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1372   // update rtm counters based on rax value at abort
1373   // reads abort_status_Reg, updates flags
1374   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1375   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1376   if (profile_rtm) {
1377     // Save abort status because abort_status_Reg is used by following code.
1378     if (RTMRetryCount > 0) {
1379       push(abort_status_Reg);
1380     }
1381     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1382     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1383     // restore abort status
1384     if (RTMRetryCount > 0) {
1385       pop(abort_status_Reg);
1386     }
1387   }
1388 }
1389 
1390 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1391 // inputs: retry_count_Reg
1392 //       : abort_status_Reg
1393 // output: retry_count_Reg decremented by 1
1394 // flags are killed
1395 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1396   Label doneRetry;
1397   assert(abort_status_Reg == rax, "");
1398   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1399   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1400   // if reason is in 0x6 and retry count != 0 then retry
1401   andptr(abort_status_Reg, 0x6);
1402   jccb(Assembler::zero, doneRetry);
1403   testl(retry_count_Reg, retry_count_Reg);
1404   jccb(Assembler::zero, doneRetry);
1405   pause();
1406   decrementl(retry_count_Reg);
1407   jmp(retryLabel);
1408   bind(doneRetry);
1409 }
1410 
1411 // Spin and retry if lock is busy,
1412 // inputs: box_Reg (monitor address)
1413 //       : retry_count_Reg
1414 // output: retry_count_Reg decremented by 1
1415 //       : clear z flag if retry count exceeded
1416 // tmp_Reg, scr_Reg, flags are killed
1417 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1418                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1419   Label SpinLoop, SpinExit, doneRetry;
1420   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1421 
1422   testl(retry_count_Reg, retry_count_Reg);
1423   jccb(Assembler::zero, doneRetry);
1424   decrementl(retry_count_Reg);
1425   movptr(scr_Reg, RTMSpinLoopCount);
1426 
1427   bind(SpinLoop);
1428   pause();
1429   decrementl(scr_Reg);
1430   jccb(Assembler::lessEqual, SpinExit);
1431   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1432   testptr(tmp_Reg, tmp_Reg);
1433   jccb(Assembler::notZero, SpinLoop);
1434 
1435   bind(SpinExit);
1436   jmp(retryLabel);
1437   bind(doneRetry);
1438   incrementl(retry_count_Reg); // clear z flag
1439 }
1440 
1441 // Use RTM for normal stack locks
1442 // Input: objReg (object to lock)
1443 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1444                                        Register retry_on_abort_count_Reg,
1445                                        RTMLockingCounters* stack_rtm_counters,
1446                                        Metadata* method_data, bool profile_rtm,
1447                                        Label& DONE_LABEL, Label& IsInflated) {
1448   assert(UseRTMForStackLocks, "why call this otherwise?");
1449   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1450   assert(tmpReg == rax, "");
1451   assert(scrReg == rdx, "");
1452   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1453 
1454   if (RTMRetryCount > 0) {
1455     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1456     bind(L_rtm_retry);
1457   }
1458   movptr(tmpReg, Address(objReg, 0));
1459   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1460   jcc(Assembler::notZero, IsInflated);
1461 
1462   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1463     Label L_noincrement;
1464     if (RTMTotalCountIncrRate > 1) {
1465       // tmpReg, scrReg and flags are killed
1466       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1467     }
1468     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1469     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1470     bind(L_noincrement);
1471   }
1472   xbegin(L_on_abort);
1473   movptr(tmpReg, Address(objReg, 0));       // fetch markword
1474   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1475   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1476   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1477 
1478   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1479   if (UseRTMXendForLockBusy) {
1480     xend();
1481     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1482     jmp(L_decrement_retry);
1483   }
1484   else {
1485     xabort(0);
1486   }
1487   bind(L_on_abort);
1488   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1489     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1490   }
1491   bind(L_decrement_retry);
1492   if (RTMRetryCount > 0) {
1493     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1494     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1495   }
1496 }
1497 
1498 // Use RTM for inflating locks
1499 // inputs: objReg (object to lock)
1500 //         boxReg (on-stack box address (displaced header location) - KILLED)
1501 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1502 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1503                                           Register scrReg, Register retry_on_busy_count_Reg,
1504                                           Register retry_on_abort_count_Reg,
1505                                           RTMLockingCounters* rtm_counters,
1506                                           Metadata* method_data, bool profile_rtm,
1507                                           Label& DONE_LABEL) {
1508   assert(UseRTMLocking, "why call this otherwise?");
1509   assert(tmpReg == rax, "");
1510   assert(scrReg == rdx, "");
1511   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1512   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1513 
1514   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1515   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1516   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1517 
1518   if (RTMRetryCount > 0) {
1519     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1520     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1521     bind(L_rtm_retry);
1522   }
1523   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1524     Label L_noincrement;
1525     if (RTMTotalCountIncrRate > 1) {
1526       // tmpReg, scrReg and flags are killed
1527       branch_on_random_using_rdtsc(tmpReg, scrReg, (int)RTMTotalCountIncrRate, L_noincrement);
1528     }
1529     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1530     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1531     bind(L_noincrement);
1532   }
1533   xbegin(L_on_abort);
1534   movptr(tmpReg, Address(objReg, 0));
1535   movptr(tmpReg, Address(tmpReg, owner_offset));
1536   testptr(tmpReg, tmpReg);
1537   jcc(Assembler::zero, DONE_LABEL);
1538   if (UseRTMXendForLockBusy) {
1539     xend();
1540     jmp(L_decrement_retry);
1541   }
1542   else {
1543     xabort(0);
1544   }
1545   bind(L_on_abort);
1546   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1547   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1548     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1549   }
1550   if (RTMRetryCount > 0) {
1551     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1552     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1553   }
1554 
1555   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1556   testptr(tmpReg, tmpReg) ;
1557   jccb(Assembler::notZero, L_decrement_retry) ;
1558 
1559   // Appears unlocked - try to swing _owner from null to non-null.
1560   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1561 #ifdef _LP64
1562   Register threadReg = r15_thread;
1563 #else
1564   get_thread(scrReg);
1565   Register threadReg = scrReg;
1566 #endif
1567   if (os::is_MP()) {
1568     lock();
1569   }
1570   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1571 
1572   if (RTMRetryCount > 0) {
1573     // success done else retry
1574     jccb(Assembler::equal, DONE_LABEL) ;
1575     bind(L_decrement_retry);
1576     // Spin and retry if lock is busy.
1577     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1578   }
1579   else {
1580     bind(L_decrement_retry);
1581   }
1582 }
1583 
1584 #endif //  INCLUDE_RTM_OPT
1585 
1586 // Fast_Lock and Fast_Unlock used by C2
1587 
1588 // Because the transitions from emitted code to the runtime
1589 // monitorenter/exit helper stubs are so slow it's critical that
1590 // we inline both the stack-locking fast-path and the inflated fast path.
1591 //
1592 // See also: cmpFastLock and cmpFastUnlock.
1593 //
1594 // What follows is a specialized inline transliteration of the code
1595 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1596 // another option would be to emit TrySlowEnter and TrySlowExit methods
1597 // at startup-time.  These methods would accept arguments as
1598 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1599 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1600 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1601 // In practice, however, the # of lock sites is bounded and is usually small.
1602 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1603 // if the processor uses simple bimodal branch predictors keyed by EIP
1604 // Since the helper routines would be called from multiple synchronization
1605 // sites.
1606 //
1607 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1608 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1609 // to those specialized methods.  That'd give us a mostly platform-independent
1610 // implementation that the JITs could optimize and inline at their pleasure.
1611 // Done correctly, the only time we'd need to cross to native could would be
1612 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1613 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1614 // (b) explicit barriers or fence operations.
1615 //
1616 // TODO:
1617 //
1618 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1619 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1620 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1621 //    the lock operators would typically be faster than reifying Self.
1622 //
1623 // *  Ideally I'd define the primitives as:
1624 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1625 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1626 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1627 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1628 //    Furthermore the register assignments are overconstrained, possibly resulting in
1629 //    sub-optimal code near the synchronization site.
1630 //
1631 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1632 //    Alternately, use a better sp-proximity test.
1633 //
1634 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1635 //    Either one is sufficient to uniquely identify a thread.
1636 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1637 //
1638 // *  Intrinsify notify() and notifyAll() for the common cases where the
1639 //    object is locked by the calling thread but the waitlist is empty.
1640 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1641 //
1642 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1643 //    But beware of excessive branch density on AMD Opterons.
1644 //
1645 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1646 //    or failure of the fast-path.  If the fast-path fails then we pass
1647 //    control to the slow-path, typically in C.  In Fast_Lock and
1648 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1649 //    will emit a conditional branch immediately after the node.
1650 //    So we have branches to branches and lots of ICC.ZF games.
1651 //    Instead, it might be better to have C2 pass a "FailureLabel"
1652 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1653 //    will drop through the node.  ICC.ZF is undefined at exit.
1654 //    In the case of failure, the node will branch directly to the
1655 //    FailureLabel
1656 
1657 
1658 // obj: object to lock
1659 // box: on-stack box address (displaced header location) - KILLED
1660 // rax,: tmp -- KILLED
1661 // scr: tmp -- KILLED
1662 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1663                                Register scrReg, Register cx1Reg, Register cx2Reg,
1664                                BiasedLockingCounters* counters,
1665                                RTMLockingCounters* rtm_counters,
1666                                RTMLockingCounters* stack_rtm_counters,
1667                                Metadata* method_data,
1668                                bool use_rtm, bool profile_rtm) {
1669   // Ensure the register assignents are disjoint
1670   assert(tmpReg == rax, "");
1671 
1672   if (use_rtm) {
1673     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1674   } else {
1675     assert(cx1Reg == noreg, "");
1676     assert(cx2Reg == noreg, "");
1677     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1678   }
1679 
1680   if (counters != NULL) {
1681     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1682   }
1683   if (EmitSync & 1) {
1684       // set box->dhw = markOopDesc::unused_mark()
1685       // Force all sync thru slow-path: slow_enter() and slow_exit()
1686       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1687       cmpptr (rsp, (int32_t)NULL_WORD);
1688   } else {
1689     // Possible cases that we'll encounter in fast_lock
1690     // ------------------------------------------------
1691     // * Inflated
1692     //    -- unlocked
1693     //    -- Locked
1694     //       = by self
1695     //       = by other
1696     // * biased
1697     //    -- by Self
1698     //    -- by other
1699     // * neutral
1700     // * stack-locked
1701     //    -- by self
1702     //       = sp-proximity test hits
1703     //       = sp-proximity test generates false-negative
1704     //    -- by other
1705     //
1706 
1707     Label IsInflated, DONE_LABEL;
1708 
1709     // it's stack-locked, biased or neutral
1710     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1711     // order to reduce the number of conditional branches in the most common cases.
1712     // Beware -- there's a subtle invariant that fetch of the markword
1713     // at [FETCH], below, will never observe a biased encoding (*101b).
1714     // If this invariant is not held we risk exclusion (safety) failure.
1715     if (UseBiasedLocking && !UseOptoBiasInlining) {
1716       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1717     }
1718 
1719 #if INCLUDE_RTM_OPT
1720     if (UseRTMForStackLocks && use_rtm) {
1721       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1722                         stack_rtm_counters, method_data, profile_rtm,
1723                         DONE_LABEL, IsInflated);
1724     }
1725 #endif // INCLUDE_RTM_OPT
1726 
1727     movptr(tmpReg, Address(objReg, 0));          // [FETCH]
1728     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1729     jccb(Assembler::notZero, IsInflated);
1730 
1731     // Attempt stack-locking ...
1732     orptr (tmpReg, markOopDesc::unlocked_value);
1733     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1734     if (os::is_MP()) {
1735       lock();
1736     }
1737     cmpxchgptr(boxReg, Address(objReg, 0));      // Updates tmpReg
1738     if (counters != NULL) {
1739       cond_inc32(Assembler::equal,
1740                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1741     }
1742     jcc(Assembler::equal, DONE_LABEL);           // Success
1743 
1744     // Recursive locking.
1745     // The object is stack-locked: markword contains stack pointer to BasicLock.
1746     // Locked by current thread if difference with current SP is less than one page.
1747     subptr(tmpReg, rsp);
1748     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1749     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1750     movptr(Address(boxReg, 0), tmpReg);
1751     if (counters != NULL) {
1752       cond_inc32(Assembler::equal,
1753                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1754     }
1755     jmp(DONE_LABEL);
1756 
1757     bind(IsInflated);
1758     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1759 
1760 #if INCLUDE_RTM_OPT
1761     // Use the same RTM locking code in 32- and 64-bit VM.
1762     if (use_rtm) {
1763       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1764                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1765     } else {
1766 #endif // INCLUDE_RTM_OPT
1767 
1768 #ifndef _LP64
1769     // The object is inflated.
1770 
1771     // boxReg refers to the on-stack BasicLock in the current frame.
1772     // We'd like to write:
1773     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1774     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1775     // additional latency as we have another ST in the store buffer that must drain.
1776 
1777     if (EmitSync & 8192) {
1778        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1779        get_thread (scrReg);
1780        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1781        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1782        if (os::is_MP()) {
1783          lock();
1784        }
1785        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1786     } else
1787     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1788        // register juggle because we need tmpReg for cmpxchgptr below
1789        movptr(scrReg, boxReg);
1790        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1791 
1792        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1793        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1794           // prefetchw [eax + Offset(_owner)-2]
1795           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1796        }
1797 
1798        if ((EmitSync & 64) == 0) {
1799          // Optimistic form: consider XORL tmpReg,tmpReg
1800          movptr(tmpReg, NULL_WORD);
1801        } else {
1802          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1803          // Test-And-CAS instead of CAS
1804          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1805          testptr(tmpReg, tmpReg);                   // Locked ?
1806          jccb  (Assembler::notZero, DONE_LABEL);
1807        }
1808 
1809        // Appears unlocked - try to swing _owner from null to non-null.
1810        // Ideally, I'd manifest "Self" with get_thread and then attempt
1811        // to CAS the register containing Self into m->Owner.
1812        // But we don't have enough registers, so instead we can either try to CAS
1813        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1814        // we later store "Self" into m->Owner.  Transiently storing a stack address
1815        // (rsp or the address of the box) into  m->owner is harmless.
1816        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1817        if (os::is_MP()) {
1818          lock();
1819        }
1820        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1821        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1822        // If we weren't able to swing _owner from NULL to the BasicLock
1823        // then take the slow path.
1824        jccb  (Assembler::notZero, DONE_LABEL);
1825        // update _owner from BasicLock to thread
1826        get_thread (scrReg);                    // beware: clobbers ICCs
1827        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1828        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1829 
1830        // If the CAS fails we can either retry or pass control to the slow-path.
1831        // We use the latter tactic.
1832        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1833        // If the CAS was successful ...
1834        //   Self has acquired the lock
1835        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1836        // Intentional fall-through into DONE_LABEL ...
1837     } else {
1838        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1839        movptr(boxReg, tmpReg);
1840 
1841        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1842        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1843           // prefetchw [eax + Offset(_owner)-2]
1844           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1845        }
1846 
1847        if ((EmitSync & 64) == 0) {
1848          // Optimistic form
1849          xorptr  (tmpReg, tmpReg);
1850        } else {
1851          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1852          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1853          testptr(tmpReg, tmpReg);                   // Locked ?
1854          jccb  (Assembler::notZero, DONE_LABEL);
1855        }
1856 
1857        // Appears unlocked - try to swing _owner from null to non-null.
1858        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1859        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1860        get_thread (scrReg);
1861        if (os::is_MP()) {
1862          lock();
1863        }
1864        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1865 
1866        // If the CAS fails we can either retry or pass control to the slow-path.
1867        // We use the latter tactic.
1868        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1869        // If the CAS was successful ...
1870        //   Self has acquired the lock
1871        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1872        // Intentional fall-through into DONE_LABEL ...
1873     }
1874 #else // _LP64
1875     // It's inflated
1876     movq(scrReg, tmpReg);
1877     xorq(tmpReg, tmpReg);
1878 
1879     if (os::is_MP()) {
1880       lock();
1881     }
1882     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1883     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1884     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1885     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1886     // Intentional fall-through into DONE_LABEL ...
1887     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1888 #endif // _LP64
1889 #if INCLUDE_RTM_OPT
1890     } // use_rtm()
1891 #endif
1892     // DONE_LABEL is a hot target - we'd really like to place it at the
1893     // start of cache line by padding with NOPs.
1894     // See the AMD and Intel software optimization manuals for the
1895     // most efficient "long" NOP encodings.
1896     // Unfortunately none of our alignment mechanisms suffice.
1897     bind(DONE_LABEL);
1898 
1899     // At DONE_LABEL the icc ZFlag is set as follows ...
1900     // Fast_Unlock uses the same protocol.
1901     // ZFlag == 1 -> Success
1902     // ZFlag == 0 -> Failure - force control through the slow-path
1903   }
1904 }
1905 
1906 // obj: object to unlock
1907 // box: box address (displaced header location), killed.  Must be EAX.
1908 // tmp: killed, cannot be obj nor box.
1909 //
1910 // Some commentary on balanced locking:
1911 //
1912 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1913 // Methods that don't have provably balanced locking are forced to run in the
1914 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1915 // The interpreter provides two properties:
1916 // I1:  At return-time the interpreter automatically and quietly unlocks any
1917 //      objects acquired the current activation (frame).  Recall that the
1918 //      interpreter maintains an on-stack list of locks currently held by
1919 //      a frame.
1920 // I2:  If a method attempts to unlock an object that is not held by the
1921 //      the frame the interpreter throws IMSX.
1922 //
1923 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1924 // B() doesn't have provably balanced locking so it runs in the interpreter.
1925 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1926 // is still locked by A().
1927 //
1928 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1929 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1930 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1931 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1932 // Arguably given that the spec legislates the JNI case as undefined our implementation
1933 // could reasonably *avoid* checking owner in Fast_Unlock().
1934 // In the interest of performance we elide m->Owner==Self check in unlock.
1935 // A perfectly viable alternative is to elide the owner check except when
1936 // Xcheck:jni is enabled.
1937 
1938 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1939   assert(boxReg == rax, "");
1940   assert_different_registers(objReg, boxReg, tmpReg);
1941 
1942   if (EmitSync & 4) {
1943     // Disable - inhibit all inlining.  Force control through the slow-path
1944     cmpptr (rsp, 0);
1945   } else {
1946     Label DONE_LABEL, Stacked, CheckSucc;
1947 
1948     // Critically, the biased locking test must have precedence over
1949     // and appear before the (box->dhw == 0) recursive stack-lock test.
1950     if (UseBiasedLocking && !UseOptoBiasInlining) {
1951        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1952     }
1953 
1954 #if INCLUDE_RTM_OPT
1955     if (UseRTMForStackLocks && use_rtm) {
1956       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1957       Label L_regular_unlock;
1958       movptr(tmpReg, Address(objReg, 0));           // fetch markword
1959       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1960       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1961       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1962       xend();                                       // otherwise end...
1963       jmp(DONE_LABEL);                              // ... and we're done
1964       bind(L_regular_unlock);
1965     }
1966 #endif
1967 
1968     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
1969     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
1970     movptr(tmpReg, Address(objReg, 0));             // Examine the object's markword
1971     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
1972     jccb  (Assembler::zero, Stacked);
1973 
1974     // It's inflated.
1975 #if INCLUDE_RTM_OPT
1976     if (use_rtm) {
1977       Label L_regular_inflated_unlock;
1978       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1979       movptr(boxReg, Address(tmpReg, owner_offset));
1980       testptr(boxReg, boxReg);
1981       jccb(Assembler::notZero, L_regular_inflated_unlock);
1982       xend();
1983       jmpb(DONE_LABEL);
1984       bind(L_regular_inflated_unlock);
1985     }
1986 #endif
1987 
1988     // Despite our balanced locking property we still check that m->_owner == Self
1989     // as java routines or native JNI code called by this thread might
1990     // have released the lock.
1991     // Refer to the comments in synchronizer.cpp for how we might encode extra
1992     // state in _succ so we can avoid fetching EntryList|cxq.
1993     //
1994     // I'd like to add more cases in fast_lock() and fast_unlock() --
1995     // such as recursive enter and exit -- but we have to be wary of
1996     // I$ bloat, T$ effects and BP$ effects.
1997     //
1998     // If there's no contention try a 1-0 exit.  That is, exit without
1999     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2000     // we detect and recover from the race that the 1-0 exit admits.
2001     //
2002     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2003     // before it STs null into _owner, releasing the lock.  Updates
2004     // to data protected by the critical section must be visible before
2005     // we drop the lock (and thus before any other thread could acquire
2006     // the lock and observe the fields protected by the lock).
2007     // IA32's memory-model is SPO, so STs are ordered with respect to
2008     // each other and there's no need for an explicit barrier (fence).
2009     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2010 #ifndef _LP64
2011     get_thread (boxReg);
2012     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2013       // prefetchw [ebx + Offset(_owner)-2]
2014       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2015     }
2016 
2017     // Note that we could employ various encoding schemes to reduce
2018     // the number of loads below (currently 4) to just 2 or 3.
2019     // Refer to the comments in synchronizer.cpp.
2020     // In practice the chain of fetches doesn't seem to impact performance, however.
2021     xorptr(boxReg, boxReg);
2022     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2023        // Attempt to reduce branch density - AMD's branch predictor.
2024        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2025        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2026        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2027        jccb  (Assembler::notZero, DONE_LABEL);
2028        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2029        jmpb  (DONE_LABEL);
2030     } else {
2031        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2032        jccb  (Assembler::notZero, DONE_LABEL);
2033        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2034        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2035        jccb  (Assembler::notZero, CheckSucc);
2036        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2037        jmpb  (DONE_LABEL);
2038     }
2039 
2040     // The Following code fragment (EmitSync & 65536) improves the performance of
2041     // contended applications and contended synchronization microbenchmarks.
2042     // Unfortunately the emission of the code - even though not executed - causes regressions
2043     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2044     // with an equal number of never-executed NOPs results in the same regression.
2045     // We leave it off by default.
2046 
2047     if ((EmitSync & 65536) != 0) {
2048        Label LSuccess, LGoSlowPath ;
2049 
2050        bind  (CheckSucc);
2051 
2052        // Optional pre-test ... it's safe to elide this
2053        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2054        jccb(Assembler::zero, LGoSlowPath);
2055 
2056        // We have a classic Dekker-style idiom:
2057        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2058        // There are a number of ways to implement the barrier:
2059        // (1) lock:andl &m->_owner, 0
2060        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2061        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2062        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2063        // (2) If supported, an explicit MFENCE is appealing.
2064        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2065        //     particularly if the write-buffer is full as might be the case if
2066        //     if stores closely precede the fence or fence-equivalent instruction.
2067        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2068        //     as the situation has changed with Nehalem and Shanghai.
2069        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2070        //     The $lines underlying the top-of-stack should be in M-state.
2071        //     The locked add instruction is serializing, of course.
2072        // (4) Use xchg, which is serializing
2073        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2074        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2075        //     The integer condition codes will tell us if succ was 0.
2076        //     Since _succ and _owner should reside in the same $line and
2077        //     we just stored into _owner, it's likely that the $line
2078        //     remains in M-state for the lock:orl.
2079        //
2080        // We currently use (3), although it's likely that switching to (2)
2081        // is correct for the future.
2082 
2083        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2084        if (os::is_MP()) {
2085          lock(); addptr(Address(rsp, 0), 0);
2086        }
2087        // Ratify _succ remains non-null
2088        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2089        jccb  (Assembler::notZero, LSuccess);
2090 
2091        xorptr(boxReg, boxReg);                  // box is really EAX
2092        if (os::is_MP()) { lock(); }
2093        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2094        // There's no successor so we tried to regrab the lock with the
2095        // placeholder value. If that didn't work, then another thread
2096        // grabbed the lock so we're done (and exit was a success).
2097        jccb  (Assembler::notEqual, LSuccess);
2098        // Since we're low on registers we installed rsp as a placeholding in _owner.
2099        // Now install Self over rsp.  This is safe as we're transitioning from
2100        // non-null to non=null
2101        get_thread (boxReg);
2102        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2103        // Intentional fall-through into LGoSlowPath ...
2104 
2105        bind  (LGoSlowPath);
2106        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2107        jmpb  (DONE_LABEL);
2108 
2109        bind  (LSuccess);
2110        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2111        jmpb  (DONE_LABEL);
2112     }
2113 
2114     bind (Stacked);
2115     // It's not inflated and it's not recursively stack-locked and it's not biased.
2116     // It must be stack-locked.
2117     // Try to reset the header to displaced header.
2118     // The "box" value on the stack is stable, so we can reload
2119     // and be assured we observe the same value as above.
2120     movptr(tmpReg, Address(boxReg, 0));
2121     if (os::is_MP()) {
2122       lock();
2123     }
2124     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2125     // Intention fall-thru into DONE_LABEL
2126 
2127     // DONE_LABEL is a hot target - we'd really like to place it at the
2128     // start of cache line by padding with NOPs.
2129     // See the AMD and Intel software optimization manuals for the
2130     // most efficient "long" NOP encodings.
2131     // Unfortunately none of our alignment mechanisms suffice.
2132     if ((EmitSync & 65536) == 0) {
2133        bind (CheckSucc);
2134     }
2135 #else // _LP64
2136     // It's inflated
2137     if (EmitSync & 1024) {
2138       // Emit code to check that _owner == Self
2139       // We could fold the _owner test into subsequent code more efficiently
2140       // than using a stand-alone check, but since _owner checking is off by
2141       // default we don't bother. We also might consider predicating the
2142       // _owner==Self check on Xcheck:jni or running on a debug build.
2143       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2144       xorptr(boxReg, r15_thread);
2145     } else {
2146       xorptr(boxReg, boxReg);
2147     }
2148     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2149     jccb  (Assembler::notZero, DONE_LABEL);
2150     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2151     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2152     jccb  (Assembler::notZero, CheckSucc);
2153     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2154     jmpb  (DONE_LABEL);
2155 
2156     if ((EmitSync & 65536) == 0) {
2157       // Try to avoid passing control into the slow_path ...
2158       Label LSuccess, LGoSlowPath ;
2159       bind  (CheckSucc);
2160 
2161       // The following optional optimization can be elided if necessary
2162       // Effectively: if (succ == null) goto SlowPath
2163       // The code reduces the window for a race, however,
2164       // and thus benefits performance.
2165       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2166       jccb  (Assembler::zero, LGoSlowPath);
2167 
2168       if ((EmitSync & 16) && os::is_MP()) {
2169         orptr(boxReg, boxReg);
2170         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2171       } else {
2172         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2173         if (os::is_MP()) {
2174           // Memory barrier/fence
2175           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2176           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2177           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2178           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2179           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2180           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2181           lock(); addl(Address(rsp, 0), 0);
2182         }
2183       }
2184       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2185       jccb  (Assembler::notZero, LSuccess);
2186 
2187       // Rare inopportune interleaving - race.
2188       // The successor vanished in the small window above.
2189       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2190       // We need to ensure progress and succession.
2191       // Try to reacquire the lock.
2192       // If that fails then the new owner is responsible for succession and this
2193       // thread needs to take no further action and can exit via the fast path (success).
2194       // If the re-acquire succeeds then pass control into the slow path.
2195       // As implemented, this latter mode is horrible because we generated more
2196       // coherence traffic on the lock *and* artifically extended the critical section
2197       // length while by virtue of passing control into the slow path.
2198 
2199       // box is really RAX -- the following CMPXCHG depends on that binding
2200       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2201       movptr(boxReg, (int32_t)NULL_WORD);
2202       if (os::is_MP()) { lock(); }
2203       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2204       // There's no successor so we tried to regrab the lock.
2205       // If that didn't work, then another thread grabbed the
2206       // lock so we're done (and exit was a success).
2207       jccb  (Assembler::notEqual, LSuccess);
2208       // Intentional fall-through into slow-path
2209 
2210       bind  (LGoSlowPath);
2211       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2212       jmpb  (DONE_LABEL);
2213 
2214       bind  (LSuccess);
2215       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2216       jmpb  (DONE_LABEL);
2217     }
2218 
2219     bind  (Stacked);
2220     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2221     if (os::is_MP()) { lock(); }
2222     cmpxchgptr(tmpReg, Address(objReg, 0)); // Uses RAX which is box
2223 
2224     if (EmitSync & 65536) {
2225        bind (CheckSucc);
2226     }
2227 #endif
2228     bind(DONE_LABEL);
2229   }
2230 }
2231 #endif // COMPILER2
2232 
2233 void MacroAssembler::c2bool(Register x) {
2234   // implements x == 0 ? 0 : 1
2235   // note: must only look at least-significant byte of x
2236   //       since C-style booleans are stored in one byte
2237   //       only! (was bug)
2238   andl(x, 0xFF);
2239   setb(Assembler::notZero, x);
2240 }
2241 
2242 // Wouldn't need if AddressLiteral version had new name
2243 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2244   Assembler::call(L, rtype);
2245 }
2246 
2247 void MacroAssembler::call(Register entry) {
2248   Assembler::call(entry);
2249 }
2250 
2251 void MacroAssembler::call(AddressLiteral entry) {
2252   if (reachable(entry)) {
2253     Assembler::call_literal(entry.target(), entry.rspec());
2254   } else {
2255     lea(rscratch1, entry);
2256     Assembler::call(rscratch1);
2257   }
2258 }
2259 
2260 void MacroAssembler::ic_call(address entry) {
2261   RelocationHolder rh = virtual_call_Relocation::spec(pc());
2262   movptr(rax, (intptr_t)Universe::non_oop_word());
2263   call(AddressLiteral(entry, rh));
2264 }
2265 
2266 // Implementation of call_VM versions
2267 
2268 void MacroAssembler::call_VM(Register oop_result,
2269                              address entry_point,
2270                              bool check_exceptions) {
2271   Label C, E;
2272   call(C, relocInfo::none);
2273   jmp(E);
2274 
2275   bind(C);
2276   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2277   ret(0);
2278 
2279   bind(E);
2280 }
2281 
2282 void MacroAssembler::call_VM(Register oop_result,
2283                              address entry_point,
2284                              Register arg_1,
2285                              bool check_exceptions) {
2286   Label C, E;
2287   call(C, relocInfo::none);
2288   jmp(E);
2289 
2290   bind(C);
2291   pass_arg1(this, arg_1);
2292   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2293   ret(0);
2294 
2295   bind(E);
2296 }
2297 
2298 void MacroAssembler::call_VM(Register oop_result,
2299                              address entry_point,
2300                              Register arg_1,
2301                              Register arg_2,
2302                              bool check_exceptions) {
2303   Label C, E;
2304   call(C, relocInfo::none);
2305   jmp(E);
2306 
2307   bind(C);
2308 
2309   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2310 
2311   pass_arg2(this, arg_2);
2312   pass_arg1(this, arg_1);
2313   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2314   ret(0);
2315 
2316   bind(E);
2317 }
2318 
2319 void MacroAssembler::call_VM(Register oop_result,
2320                              address entry_point,
2321                              Register arg_1,
2322                              Register arg_2,
2323                              Register arg_3,
2324                              bool check_exceptions) {
2325   Label C, E;
2326   call(C, relocInfo::none);
2327   jmp(E);
2328 
2329   bind(C);
2330 
2331   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2332   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2333   pass_arg3(this, arg_3);
2334 
2335   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2336   pass_arg2(this, arg_2);
2337 
2338   pass_arg1(this, arg_1);
2339   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2340   ret(0);
2341 
2342   bind(E);
2343 }
2344 
2345 void MacroAssembler::call_VM(Register oop_result,
2346                              Register last_java_sp,
2347                              address entry_point,
2348                              int number_of_arguments,
2349                              bool check_exceptions) {
2350   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2351   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2352 }
2353 
2354 void MacroAssembler::call_VM(Register oop_result,
2355                              Register last_java_sp,
2356                              address entry_point,
2357                              Register arg_1,
2358                              bool check_exceptions) {
2359   pass_arg1(this, arg_1);
2360   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2361 }
2362 
2363 void MacroAssembler::call_VM(Register oop_result,
2364                              Register last_java_sp,
2365                              address entry_point,
2366                              Register arg_1,
2367                              Register arg_2,
2368                              bool check_exceptions) {
2369 
2370   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2371   pass_arg2(this, arg_2);
2372   pass_arg1(this, arg_1);
2373   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2374 }
2375 
2376 void MacroAssembler::call_VM(Register oop_result,
2377                              Register last_java_sp,
2378                              address entry_point,
2379                              Register arg_1,
2380                              Register arg_2,
2381                              Register arg_3,
2382                              bool check_exceptions) {
2383   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2384   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2385   pass_arg3(this, arg_3);
2386   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2387   pass_arg2(this, arg_2);
2388   pass_arg1(this, arg_1);
2389   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2390 }
2391 
2392 void MacroAssembler::super_call_VM(Register oop_result,
2393                                    Register last_java_sp,
2394                                    address entry_point,
2395                                    int number_of_arguments,
2396                                    bool check_exceptions) {
2397   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2398   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2399 }
2400 
2401 void MacroAssembler::super_call_VM(Register oop_result,
2402                                    Register last_java_sp,
2403                                    address entry_point,
2404                                    Register arg_1,
2405                                    bool check_exceptions) {
2406   pass_arg1(this, arg_1);
2407   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2408 }
2409 
2410 void MacroAssembler::super_call_VM(Register oop_result,
2411                                    Register last_java_sp,
2412                                    address entry_point,
2413                                    Register arg_1,
2414                                    Register arg_2,
2415                                    bool check_exceptions) {
2416 
2417   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2418   pass_arg2(this, arg_2);
2419   pass_arg1(this, arg_1);
2420   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2421 }
2422 
2423 void MacroAssembler::super_call_VM(Register oop_result,
2424                                    Register last_java_sp,
2425                                    address entry_point,
2426                                    Register arg_1,
2427                                    Register arg_2,
2428                                    Register arg_3,
2429                                    bool check_exceptions) {
2430   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2431   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2432   pass_arg3(this, arg_3);
2433   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2434   pass_arg2(this, arg_2);
2435   pass_arg1(this, arg_1);
2436   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2437 }
2438 
2439 void MacroAssembler::call_VM_base(Register oop_result,
2440                                   Register java_thread,
2441                                   Register last_java_sp,
2442                                   address  entry_point,
2443                                   int      number_of_arguments,
2444                                   bool     check_exceptions) {
2445   // determine java_thread register
2446   if (!java_thread->is_valid()) {
2447 #ifdef _LP64
2448     java_thread = r15_thread;
2449 #else
2450     java_thread = rdi;
2451     get_thread(java_thread);
2452 #endif // LP64
2453   }
2454   // determine last_java_sp register
2455   if (!last_java_sp->is_valid()) {
2456     last_java_sp = rsp;
2457   }
2458   // debugging support
2459   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2460   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2461 #ifdef ASSERT
2462   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2463   // r12 is the heapbase.
2464   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2465 #endif // ASSERT
2466 
2467   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2468   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2469 
2470   // push java thread (becomes first argument of C function)
2471 
2472   NOT_LP64(push(java_thread); number_of_arguments++);
2473   LP64_ONLY(mov(c_rarg0, r15_thread));
2474 
2475   // set last Java frame before call
2476   assert(last_java_sp != rbp, "can't use ebp/rbp");
2477 
2478   // Only interpreter should have to set fp
2479   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2480 
2481   // do the call, remove parameters
2482   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2483 
2484   // restore the thread (cannot use the pushed argument since arguments
2485   // may be overwritten by C code generated by an optimizing compiler);
2486   // however can use the register value directly if it is callee saved.
2487   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2488     // rdi & rsi (also r15) are callee saved -> nothing to do
2489 #ifdef ASSERT
2490     guarantee(java_thread != rax, "change this code");
2491     push(rax);
2492     { Label L;
2493       get_thread(rax);
2494       cmpptr(java_thread, rax);
2495       jcc(Assembler::equal, L);
2496       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2497       bind(L);
2498     }
2499     pop(rax);
2500 #endif
2501   } else {
2502     get_thread(java_thread);
2503   }
2504   // reset last Java frame
2505   // Only interpreter should have to clear fp
2506   reset_last_Java_frame(java_thread, true, false);
2507 
2508 #ifndef CC_INTERP
2509    // C++ interp handles this in the interpreter
2510   check_and_handle_popframe(java_thread);
2511   check_and_handle_earlyret(java_thread);
2512 #endif /* CC_INTERP */
2513 
2514   if (check_exceptions) {
2515     // check for pending exceptions (java_thread is set upon return)
2516     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2517 #ifndef _LP64
2518     jump_cc(Assembler::notEqual,
2519             RuntimeAddress(StubRoutines::forward_exception_entry()));
2520 #else
2521     // This used to conditionally jump to forward_exception however it is
2522     // possible if we relocate that the branch will not reach. So we must jump
2523     // around so we can always reach
2524 
2525     Label ok;
2526     jcc(Assembler::equal, ok);
2527     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2528     bind(ok);
2529 #endif // LP64
2530   }
2531 
2532   // get oop result if there is one and reset the value in the thread
2533   if (oop_result->is_valid()) {
2534     get_vm_result(oop_result, java_thread);
2535   }
2536 }
2537 
2538 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2539 
2540   // Calculate the value for last_Java_sp
2541   // somewhat subtle. call_VM does an intermediate call
2542   // which places a return address on the stack just under the
2543   // stack pointer as the user finsihed with it. This allows
2544   // use to retrieve last_Java_pc from last_Java_sp[-1].
2545   // On 32bit we then have to push additional args on the stack to accomplish
2546   // the actual requested call. On 64bit call_VM only can use register args
2547   // so the only extra space is the return address that call_VM created.
2548   // This hopefully explains the calculations here.
2549 
2550 #ifdef _LP64
2551   // We've pushed one address, correct last_Java_sp
2552   lea(rax, Address(rsp, wordSize));
2553 #else
2554   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2555 #endif // LP64
2556 
2557   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2558 
2559 }
2560 
2561 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2562   call_VM_leaf_base(entry_point, number_of_arguments);
2563 }
2564 
2565 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2566   pass_arg0(this, arg_0);
2567   call_VM_leaf(entry_point, 1);
2568 }
2569 
2570 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2571 
2572   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2573   pass_arg1(this, arg_1);
2574   pass_arg0(this, arg_0);
2575   call_VM_leaf(entry_point, 2);
2576 }
2577 
2578 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2579   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2580   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2581   pass_arg2(this, arg_2);
2582   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2583   pass_arg1(this, arg_1);
2584   pass_arg0(this, arg_0);
2585   call_VM_leaf(entry_point, 3);
2586 }
2587 
2588 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2589   pass_arg0(this, arg_0);
2590   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2591 }
2592 
2593 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2594 
2595   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2596   pass_arg1(this, arg_1);
2597   pass_arg0(this, arg_0);
2598   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2599 }
2600 
2601 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2602   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2603   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2604   pass_arg2(this, arg_2);
2605   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2606   pass_arg1(this, arg_1);
2607   pass_arg0(this, arg_0);
2608   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2609 }
2610 
2611 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2612   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2613   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2614   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2615   pass_arg3(this, arg_3);
2616   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2617   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2618   pass_arg2(this, arg_2);
2619   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2620   pass_arg1(this, arg_1);
2621   pass_arg0(this, arg_0);
2622   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2623 }
2624 
2625 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2626   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2627   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2628   verify_oop(oop_result, "broken oop in call_VM_base");
2629 }
2630 
2631 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2632   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2633   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2634 }
2635 
2636 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2637 }
2638 
2639 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2640 }
2641 
2642 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2643   if (reachable(src1)) {
2644     cmpl(as_Address(src1), imm);
2645   } else {
2646     lea(rscratch1, src1);
2647     cmpl(Address(rscratch1, 0), imm);
2648   }
2649 }
2650 
2651 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2652   assert(!src2.is_lval(), "use cmpptr");
2653   if (reachable(src2)) {
2654     cmpl(src1, as_Address(src2));
2655   } else {
2656     lea(rscratch1, src2);
2657     cmpl(src1, Address(rscratch1, 0));
2658   }
2659 }
2660 
2661 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2662   Assembler::cmpl(src1, imm);
2663 }
2664 
2665 void MacroAssembler::cmp32(Register src1, Address src2) {
2666   Assembler::cmpl(src1, src2);
2667 }
2668 
2669 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2670   ucomisd(opr1, opr2);
2671 
2672   Label L;
2673   if (unordered_is_less) {
2674     movl(dst, -1);
2675     jcc(Assembler::parity, L);
2676     jcc(Assembler::below , L);
2677     movl(dst, 0);
2678     jcc(Assembler::equal , L);
2679     increment(dst);
2680   } else { // unordered is greater
2681     movl(dst, 1);
2682     jcc(Assembler::parity, L);
2683     jcc(Assembler::above , L);
2684     movl(dst, 0);
2685     jcc(Assembler::equal , L);
2686     decrementl(dst);
2687   }
2688   bind(L);
2689 }
2690 
2691 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2692   ucomiss(opr1, opr2);
2693 
2694   Label L;
2695   if (unordered_is_less) {
2696     movl(dst, -1);
2697     jcc(Assembler::parity, L);
2698     jcc(Assembler::below , L);
2699     movl(dst, 0);
2700     jcc(Assembler::equal , L);
2701     increment(dst);
2702   } else { // unordered is greater
2703     movl(dst, 1);
2704     jcc(Assembler::parity, L);
2705     jcc(Assembler::above , L);
2706     movl(dst, 0);
2707     jcc(Assembler::equal , L);
2708     decrementl(dst);
2709   }
2710   bind(L);
2711 }
2712 
2713 
2714 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2715   if (reachable(src1)) {
2716     cmpb(as_Address(src1), imm);
2717   } else {
2718     lea(rscratch1, src1);
2719     cmpb(Address(rscratch1, 0), imm);
2720   }
2721 }
2722 
2723 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2724 #ifdef _LP64
2725   if (src2.is_lval()) {
2726     movptr(rscratch1, src2);
2727     Assembler::cmpq(src1, rscratch1);
2728   } else if (reachable(src2)) {
2729     cmpq(src1, as_Address(src2));
2730   } else {
2731     lea(rscratch1, src2);
2732     Assembler::cmpq(src1, Address(rscratch1, 0));
2733   }
2734 #else
2735   if (src2.is_lval()) {
2736     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2737   } else {
2738     cmpl(src1, as_Address(src2));
2739   }
2740 #endif // _LP64
2741 }
2742 
2743 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2744   assert(src2.is_lval(), "not a mem-mem compare");
2745 #ifdef _LP64
2746   // moves src2's literal address
2747   movptr(rscratch1, src2);
2748   Assembler::cmpq(src1, rscratch1);
2749 #else
2750   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2751 #endif // _LP64
2752 }
2753 
2754 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2755   if (reachable(adr)) {
2756     if (os::is_MP())
2757       lock();
2758     cmpxchgptr(reg, as_Address(adr));
2759   } else {
2760     lea(rscratch1, adr);
2761     if (os::is_MP())
2762       lock();
2763     cmpxchgptr(reg, Address(rscratch1, 0));
2764   }
2765 }
2766 
2767 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2768   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2769 }
2770 
2771 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2772   if (reachable(src)) {
2773     Assembler::comisd(dst, as_Address(src));
2774   } else {
2775     lea(rscratch1, src);
2776     Assembler::comisd(dst, Address(rscratch1, 0));
2777   }
2778 }
2779 
2780 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2781   if (reachable(src)) {
2782     Assembler::comiss(dst, as_Address(src));
2783   } else {
2784     lea(rscratch1, src);
2785     Assembler::comiss(dst, Address(rscratch1, 0));
2786   }
2787 }
2788 
2789 
2790 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2791   Condition negated_cond = negate_condition(cond);
2792   Label L;
2793   jcc(negated_cond, L);
2794   pushf(); // Preserve flags
2795   atomic_incl(counter_addr);
2796   popf();
2797   bind(L);
2798 }
2799 
2800 int MacroAssembler::corrected_idivl(Register reg) {
2801   // Full implementation of Java idiv and irem; checks for
2802   // special case as described in JVM spec., p.243 & p.271.
2803   // The function returns the (pc) offset of the idivl
2804   // instruction - may be needed for implicit exceptions.
2805   //
2806   //         normal case                           special case
2807   //
2808   // input : rax,: dividend                         min_int
2809   //         reg: divisor   (may not be rax,/rdx)   -1
2810   //
2811   // output: rax,: quotient  (= rax, idiv reg)       min_int
2812   //         rdx: remainder (= rax, irem reg)       0
2813   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2814   const int min_int = 0x80000000;
2815   Label normal_case, special_case;
2816 
2817   // check for special case
2818   cmpl(rax, min_int);
2819   jcc(Assembler::notEqual, normal_case);
2820   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2821   cmpl(reg, -1);
2822   jcc(Assembler::equal, special_case);
2823 
2824   // handle normal case
2825   bind(normal_case);
2826   cdql();
2827   int idivl_offset = offset();
2828   idivl(reg);
2829 
2830   // normal and special case exit
2831   bind(special_case);
2832 
2833   return idivl_offset;
2834 }
2835 
2836 
2837 
2838 void MacroAssembler::decrementl(Register reg, int value) {
2839   if (value == min_jint) {subl(reg, value) ; return; }
2840   if (value <  0) { incrementl(reg, -value); return; }
2841   if (value == 0) {                        ; return; }
2842   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2843   /* else */      { subl(reg, value)       ; return; }
2844 }
2845 
2846 void MacroAssembler::decrementl(Address dst, int value) {
2847   if (value == min_jint) {subl(dst, value) ; return; }
2848   if (value <  0) { incrementl(dst, -value); return; }
2849   if (value == 0) {                        ; return; }
2850   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2851   /* else */      { subl(dst, value)       ; return; }
2852 }
2853 
2854 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2855   assert (shift_value > 0, "illegal shift value");
2856   Label _is_positive;
2857   testl (reg, reg);
2858   jcc (Assembler::positive, _is_positive);
2859   int offset = (1 << shift_value) - 1 ;
2860 
2861   if (offset == 1) {
2862     incrementl(reg);
2863   } else {
2864     addl(reg, offset);
2865   }
2866 
2867   bind (_is_positive);
2868   sarl(reg, shift_value);
2869 }
2870 
2871 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2872   if (reachable(src)) {
2873     Assembler::divsd(dst, as_Address(src));
2874   } else {
2875     lea(rscratch1, src);
2876     Assembler::divsd(dst, Address(rscratch1, 0));
2877   }
2878 }
2879 
2880 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2881   if (reachable(src)) {
2882     Assembler::divss(dst, as_Address(src));
2883   } else {
2884     lea(rscratch1, src);
2885     Assembler::divss(dst, Address(rscratch1, 0));
2886   }
2887 }
2888 
2889 // !defined(COMPILER2) is because of stupid core builds
2890 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2891 void MacroAssembler::empty_FPU_stack() {
2892   if (VM_Version::supports_mmx()) {
2893     emms();
2894   } else {
2895     for (int i = 8; i-- > 0; ) ffree(i);
2896   }
2897 }
2898 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2899 
2900 
2901 // Defines obj, preserves var_size_in_bytes
2902 void MacroAssembler::eden_allocate(Register obj,
2903                                    Register var_size_in_bytes,
2904                                    int con_size_in_bytes,
2905                                    Register t1,
2906                                    Label& slow_case) {
2907   assert(obj == rax, "obj must be in rax, for cmpxchg");
2908   assert_different_registers(obj, var_size_in_bytes, t1);
2909   if (!Universe::heap()->supports_inline_contig_alloc()) {
2910     jmp(slow_case);
2911   } else {
2912     Register end = t1;
2913     Label retry;
2914     bind(retry);
2915     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2916     movptr(obj, heap_top);
2917     if (var_size_in_bytes == noreg) {
2918       lea(end, Address(obj, con_size_in_bytes));
2919     } else {
2920       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2921     }
2922     // if end < obj then we wrapped around => object too long => slow case
2923     cmpptr(end, obj);
2924     jcc(Assembler::below, slow_case);
2925     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2926     jcc(Assembler::above, slow_case);
2927     // Compare obj with the top addr, and if still equal, store the new top addr in
2928     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2929     // it otherwise. Use lock prefix for atomicity on MPs.
2930     locked_cmpxchgptr(end, heap_top);
2931     jcc(Assembler::notEqual, retry);
2932   }
2933 }
2934 
2935 void MacroAssembler::enter() {
2936   push(rbp);
2937   mov(rbp, rsp);
2938 }
2939 
2940 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2941 void MacroAssembler::fat_nop() {
2942   if (UseAddressNop) {
2943     addr_nop_5();
2944   } else {
2945     emit_int8(0x26); // es:
2946     emit_int8(0x2e); // cs:
2947     emit_int8(0x64); // fs:
2948     emit_int8(0x65); // gs:
2949     emit_int8((unsigned char)0x90);
2950   }
2951 }
2952 
2953 void MacroAssembler::fcmp(Register tmp) {
2954   fcmp(tmp, 1, true, true);
2955 }
2956 
2957 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
2958   assert(!pop_right || pop_left, "usage error");
2959   if (VM_Version::supports_cmov()) {
2960     assert(tmp == noreg, "unneeded temp");
2961     if (pop_left) {
2962       fucomip(index);
2963     } else {
2964       fucomi(index);
2965     }
2966     if (pop_right) {
2967       fpop();
2968     }
2969   } else {
2970     assert(tmp != noreg, "need temp");
2971     if (pop_left) {
2972       if (pop_right) {
2973         fcompp();
2974       } else {
2975         fcomp(index);
2976       }
2977     } else {
2978       fcom(index);
2979     }
2980     // convert FPU condition into eflags condition via rax,
2981     save_rax(tmp);
2982     fwait(); fnstsw_ax();
2983     sahf();
2984     restore_rax(tmp);
2985   }
2986   // condition codes set as follows:
2987   //
2988   // CF (corresponds to C0) if x < y
2989   // PF (corresponds to C2) if unordered
2990   // ZF (corresponds to C3) if x = y
2991 }
2992 
2993 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
2994   fcmp2int(dst, unordered_is_less, 1, true, true);
2995 }
2996 
2997 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
2998   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
2999   Label L;
3000   if (unordered_is_less) {
3001     movl(dst, -1);
3002     jcc(Assembler::parity, L);
3003     jcc(Assembler::below , L);
3004     movl(dst, 0);
3005     jcc(Assembler::equal , L);
3006     increment(dst);
3007   } else { // unordered is greater
3008     movl(dst, 1);
3009     jcc(Assembler::parity, L);
3010     jcc(Assembler::above , L);
3011     movl(dst, 0);
3012     jcc(Assembler::equal , L);
3013     decrementl(dst);
3014   }
3015   bind(L);
3016 }
3017 
3018 void MacroAssembler::fld_d(AddressLiteral src) {
3019   fld_d(as_Address(src));
3020 }
3021 
3022 void MacroAssembler::fld_s(AddressLiteral src) {
3023   fld_s(as_Address(src));
3024 }
3025 
3026 void MacroAssembler::fld_x(AddressLiteral src) {
3027   Assembler::fld_x(as_Address(src));
3028 }
3029 
3030 void MacroAssembler::fldcw(AddressLiteral src) {
3031   Assembler::fldcw(as_Address(src));
3032 }
3033 
3034 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3035   if (reachable(src)) {
3036     Assembler::mulpd(dst, as_Address(src));
3037   } else {
3038     lea(rscratch1, src);
3039     Assembler::mulpd(dst, Address(rscratch1, 0));
3040   }
3041 }
3042 
3043 void MacroAssembler::pow_exp_core_encoding() {
3044   // kills rax, rcx, rdx
3045   subptr(rsp,sizeof(jdouble));
3046   // computes 2^X. Stack: X ...
3047   // f2xm1 computes 2^X-1 but only operates on -1<=X<=1. Get int(X) and
3048   // keep it on the thread's stack to compute 2^int(X) later
3049   // then compute 2^(X-int(X)) as (2^(X-int(X)-1+1)
3050   // final result is obtained with: 2^X = 2^int(X) * 2^(X-int(X))
3051   fld_s(0);                 // Stack: X X ...
3052   frndint();                // Stack: int(X) X ...
3053   fsuba(1);                 // Stack: int(X) X-int(X) ...
3054   fistp_s(Address(rsp,0));  // move int(X) as integer to thread's stack. Stack: X-int(X) ...
3055   f2xm1();                  // Stack: 2^(X-int(X))-1 ...
3056   fld1();                   // Stack: 1 2^(X-int(X))-1 ...
3057   faddp(1);                 // Stack: 2^(X-int(X))
3058   // computes 2^(int(X)): add exponent bias (1023) to int(X), then
3059   // shift int(X)+1023 to exponent position.
3060   // Exponent is limited to 11 bits if int(X)+1023 does not fit in 11
3061   // bits, set result to NaN. 0x000 and 0x7FF are reserved exponent
3062   // values so detect them and set result to NaN.
3063   movl(rax,Address(rsp,0));
3064   movl(rcx, -2048); // 11 bit mask and valid NaN binary encoding
3065   addl(rax, 1023);
3066   movl(rdx,rax);
3067   shll(rax,20);
3068   // Check that 0 < int(X)+1023 < 2047. Otherwise set rax to NaN.
3069   addl(rdx,1);
3070   // Check that 1 < int(X)+1023+1 < 2048
3071   // in 3 steps:
3072   // 1- (int(X)+1023+1)&-2048 == 0 => 0 <= int(X)+1023+1 < 2048
3073   // 2- (int(X)+1023+1)&-2048 != 0
3074   // 3- (int(X)+1023+1)&-2048 != 1
3075   // Do 2- first because addl just updated the flags.
3076   cmov32(Assembler::equal,rax,rcx);
3077   cmpl(rdx,1);
3078   cmov32(Assembler::equal,rax,rcx);
3079   testl(rdx,rcx);
3080   cmov32(Assembler::notEqual,rax,rcx);
3081   movl(Address(rsp,4),rax);
3082   movl(Address(rsp,0),0);
3083   fmul_d(Address(rsp,0));   // Stack: 2^X ...
3084   addptr(rsp,sizeof(jdouble));
3085 }
3086 
3087 void MacroAssembler::increase_precision() {
3088   subptr(rsp, BytesPerWord);
3089   fnstcw(Address(rsp, 0));
3090   movl(rax, Address(rsp, 0));
3091   orl(rax, 0x300);
3092   push(rax);
3093   fldcw(Address(rsp, 0));
3094   pop(rax);
3095 }
3096 
3097 void MacroAssembler::restore_precision() {
3098   fldcw(Address(rsp, 0));
3099   addptr(rsp, BytesPerWord);
3100 }
3101 
3102 void MacroAssembler::fast_pow() {
3103   // computes X^Y = 2^(Y * log2(X))
3104   // if fast computation is not possible, result is NaN. Requires
3105   // fallback from user of this macro.
3106   // increase precision for intermediate steps of the computation
3107   BLOCK_COMMENT("fast_pow {");
3108   increase_precision();
3109   fyl2x();                 // Stack: (Y*log2(X)) ...
3110   pow_exp_core_encoding(); // Stack: exp(X) ...
3111   restore_precision();
3112   BLOCK_COMMENT("} fast_pow");
3113 }
3114 
3115 void MacroAssembler::pow_or_exp(int num_fpu_regs_in_use) {
3116   // kills rax, rcx, rdx
3117   // pow and exp needs 2 extra registers on the fpu stack.
3118   Label slow_case, done;
3119   Register tmp = noreg;
3120   if (!VM_Version::supports_cmov()) {
3121     // fcmp needs a temporary so preserve rdx,
3122     tmp = rdx;
3123   }
3124   Register tmp2 = rax;
3125   Register tmp3 = rcx;
3126 
3127   // Stack: X Y
3128   Label x_negative, y_not_2;
3129 
3130   static double two = 2.0;
3131   ExternalAddress two_addr((address)&two);
3132 
3133   // constant maybe too far on 64 bit
3134   lea(tmp2, two_addr);
3135   fld_d(Address(tmp2, 0));    // Stack: 2 X Y
3136   fcmp(tmp, 2, true, false);  // Stack: X Y
3137   jcc(Assembler::parity, y_not_2);
3138   jcc(Assembler::notEqual, y_not_2);
3139 
3140   fxch(); fpop();             // Stack: X
3141   fmul(0);                    // Stack: X*X
3142 
3143   jmp(done);
3144 
3145   bind(y_not_2);
3146 
3147   fldz();                     // Stack: 0 X Y
3148   fcmp(tmp, 1, true, false);  // Stack: X Y
3149   jcc(Assembler::above, x_negative);
3150 
3151   // X >= 0
3152 
3153   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3154   fld_s(1);                   // Stack: X Y X Y
3155   fast_pow();                 // Stack: X^Y X Y
3156   fcmp(tmp, 0, false, false); // Stack: X^Y X Y
3157   // X^Y not equal to itself: X^Y is NaN go to slow case.
3158   jcc(Assembler::parity, slow_case);
3159   // get rid of duplicate arguments. Stack: X^Y
3160   if (num_fpu_regs_in_use > 0) {
3161     fxch(); fpop();
3162     fxch(); fpop();
3163   } else {
3164     ffree(2);
3165     ffree(1);
3166   }
3167   jmp(done);
3168 
3169   // X <= 0
3170   bind(x_negative);
3171 
3172   fld_s(1);                   // Stack: Y X Y
3173   frndint();                  // Stack: int(Y) X Y
3174   fcmp(tmp, 2, false, false); // Stack: int(Y) X Y
3175   jcc(Assembler::notEqual, slow_case);
3176 
3177   subptr(rsp, 8);
3178 
3179   // For X^Y, when X < 0, Y has to be an integer and the final
3180   // result depends on whether it's odd or even. We just checked
3181   // that int(Y) == Y.  We move int(Y) to gp registers as a 64 bit
3182   // integer to test its parity. If int(Y) is huge and doesn't fit
3183   // in the 64 bit integer range, the integer indefinite value will
3184   // end up in the gp registers. Huge numbers are all even, the
3185   // integer indefinite number is even so it's fine.
3186 
3187 #ifdef ASSERT
3188   // Let's check we don't end up with an integer indefinite number
3189   // when not expected. First test for huge numbers: check whether
3190   // int(Y)+1 == int(Y) which is true for very large numbers and
3191   // those are all even. A 64 bit integer is guaranteed to not
3192   // overflow for numbers where y+1 != y (when precision is set to
3193   // double precision).
3194   Label y_not_huge;
3195 
3196   fld1();                     // Stack: 1 int(Y) X Y
3197   fadd(1);                    // Stack: 1+int(Y) int(Y) X Y
3198 
3199 #ifdef _LP64
3200   // trip to memory to force the precision down from double extended
3201   // precision
3202   fstp_d(Address(rsp, 0));
3203   fld_d(Address(rsp, 0));
3204 #endif
3205 
3206   fcmp(tmp, 1, true, false);  // Stack: int(Y) X Y
3207 #endif
3208 
3209   // move int(Y) as 64 bit integer to thread's stack
3210   fistp_d(Address(rsp,0));    // Stack: X Y
3211 
3212 #ifdef ASSERT
3213   jcc(Assembler::notEqual, y_not_huge);
3214 
3215   // Y is huge so we know it's even. It may not fit in a 64 bit
3216   // integer and we don't want the debug code below to see the
3217   // integer indefinite value so overwrite int(Y) on the thread's
3218   // stack with 0.
3219   movl(Address(rsp, 0), 0);
3220   movl(Address(rsp, 4), 0);
3221 
3222   bind(y_not_huge);
3223 #endif
3224 
3225   fld_s(1);                   // duplicate arguments for runtime call. Stack: Y X Y
3226   fld_s(1);                   // Stack: X Y X Y
3227   fabs();                     // Stack: abs(X) Y X Y
3228   fast_pow();                 // Stack: abs(X)^Y X Y
3229   fcmp(tmp, 0, false, false); // Stack: abs(X)^Y X Y
3230   // abs(X)^Y not equal to itself: abs(X)^Y is NaN go to slow case.
3231 
3232   pop(tmp2);
3233   NOT_LP64(pop(tmp3));
3234   jcc(Assembler::parity, slow_case);
3235 
3236 #ifdef ASSERT
3237   // Check that int(Y) is not integer indefinite value (int
3238   // overflow). Shouldn't happen because for values that would
3239   // overflow, 1+int(Y)==Y which was tested earlier.
3240 #ifndef _LP64
3241   {
3242     Label integer;
3243     testl(tmp2, tmp2);
3244     jcc(Assembler::notZero, integer);
3245     cmpl(tmp3, 0x80000000);
3246     jcc(Assembler::notZero, integer);
3247     STOP("integer indefinite value shouldn't be seen here");
3248     bind(integer);
3249   }
3250 #else
3251   {
3252     Label integer;
3253     mov(tmp3, tmp2); // preserve tmp2 for parity check below
3254     shlq(tmp3, 1);
3255     jcc(Assembler::carryClear, integer);
3256     jcc(Assembler::notZero, integer);
3257     STOP("integer indefinite value shouldn't be seen here");
3258     bind(integer);
3259   }
3260 #endif
3261 #endif
3262 
3263   // get rid of duplicate arguments. Stack: X^Y
3264   if (num_fpu_regs_in_use > 0) {
3265     fxch(); fpop();
3266     fxch(); fpop();
3267   } else {
3268     ffree(2);
3269     ffree(1);
3270   }
3271 
3272   testl(tmp2, 1);
3273   jcc(Assembler::zero, done); // X <= 0, Y even: X^Y = abs(X)^Y
3274   // X <= 0, Y even: X^Y = -abs(X)^Y
3275 
3276   fchs();                     // Stack: -abs(X)^Y Y
3277   jmp(done);
3278 
3279   // slow case: runtime call
3280   bind(slow_case);
3281 
3282   fpop();                       // pop incorrect result or int(Y)
3283 
3284   fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dpow), 2, num_fpu_regs_in_use);
3285 
3286   // Come here with result in F-TOS
3287   bind(done);
3288 }
3289 
3290 void MacroAssembler::fpop() {
3291   ffree();
3292   fincstp();
3293 }
3294 
3295 void MacroAssembler::load_float(Address src) {
3296   if (UseSSE >= 1) {
3297     movflt(xmm0, src);
3298   } else {
3299     LP64_ONLY(ShouldNotReachHere());
3300     NOT_LP64(fld_s(src));
3301   }
3302 }
3303 
3304 void MacroAssembler::store_float(Address dst) {
3305   if (UseSSE >= 1) {
3306     movflt(dst, xmm0);
3307   } else {
3308     LP64_ONLY(ShouldNotReachHere());
3309     NOT_LP64(fstp_s(dst));
3310   }
3311 }
3312 
3313 void MacroAssembler::load_double(Address src) {
3314   if (UseSSE >= 2) {
3315     movdbl(xmm0, src);
3316   } else {
3317     LP64_ONLY(ShouldNotReachHere());
3318     NOT_LP64(fld_d(src));
3319   }
3320 }
3321 
3322 void MacroAssembler::store_double(Address dst) {
3323   if (UseSSE >= 2) {
3324     movdbl(dst, xmm0);
3325   } else {
3326     LP64_ONLY(ShouldNotReachHere());
3327     NOT_LP64(fstp_d(dst));
3328   }
3329 }
3330 
3331 void MacroAssembler::fremr(Register tmp) {
3332   save_rax(tmp);
3333   { Label L;
3334     bind(L);
3335     fprem();
3336     fwait(); fnstsw_ax();
3337 #ifdef _LP64
3338     testl(rax, 0x400);
3339     jcc(Assembler::notEqual, L);
3340 #else
3341     sahf();
3342     jcc(Assembler::parity, L);
3343 #endif // _LP64
3344   }
3345   restore_rax(tmp);
3346   // Result is in ST0.
3347   // Note: fxch & fpop to get rid of ST1
3348   // (otherwise FPU stack could overflow eventually)
3349   fxch(1);
3350   fpop();
3351 }
3352 
3353 
3354 void MacroAssembler::incrementl(AddressLiteral dst) {
3355   if (reachable(dst)) {
3356     incrementl(as_Address(dst));
3357   } else {
3358     lea(rscratch1, dst);
3359     incrementl(Address(rscratch1, 0));
3360   }
3361 }
3362 
3363 void MacroAssembler::incrementl(ArrayAddress dst) {
3364   incrementl(as_Address(dst));
3365 }
3366 
3367 void MacroAssembler::incrementl(Register reg, int value) {
3368   if (value == min_jint) {addl(reg, value) ; return; }
3369   if (value <  0) { decrementl(reg, -value); return; }
3370   if (value == 0) {                        ; return; }
3371   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3372   /* else */      { addl(reg, value)       ; return; }
3373 }
3374 
3375 void MacroAssembler::incrementl(Address dst, int value) {
3376   if (value == min_jint) {addl(dst, value) ; return; }
3377   if (value <  0) { decrementl(dst, -value); return; }
3378   if (value == 0) {                        ; return; }
3379   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3380   /* else */      { addl(dst, value)       ; return; }
3381 }
3382 
3383 void MacroAssembler::jump(AddressLiteral dst) {
3384   if (reachable(dst)) {
3385     jmp_literal(dst.target(), dst.rspec());
3386   } else {
3387     lea(rscratch1, dst);
3388     jmp(rscratch1);
3389   }
3390 }
3391 
3392 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3393   if (reachable(dst)) {
3394     InstructionMark im(this);
3395     relocate(dst.reloc());
3396     const int short_size = 2;
3397     const int long_size = 6;
3398     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3399     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3400       // 0111 tttn #8-bit disp
3401       emit_int8(0x70 | cc);
3402       emit_int8((offs - short_size) & 0xFF);
3403     } else {
3404       // 0000 1111 1000 tttn #32-bit disp
3405       emit_int8(0x0F);
3406       emit_int8((unsigned char)(0x80 | cc));
3407       emit_int32(offs - long_size);
3408     }
3409   } else {
3410 #ifdef ASSERT
3411     warning("reversing conditional branch");
3412 #endif /* ASSERT */
3413     Label skip;
3414     jccb(reverse[cc], skip);
3415     lea(rscratch1, dst);
3416     Assembler::jmp(rscratch1);
3417     bind(skip);
3418   }
3419 }
3420 
3421 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3422   if (reachable(src)) {
3423     Assembler::ldmxcsr(as_Address(src));
3424   } else {
3425     lea(rscratch1, src);
3426     Assembler::ldmxcsr(Address(rscratch1, 0));
3427   }
3428 }
3429 
3430 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3431   int off;
3432   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3433     off = offset();
3434     movsbl(dst, src); // movsxb
3435   } else {
3436     off = load_unsigned_byte(dst, src);
3437     shll(dst, 24);
3438     sarl(dst, 24);
3439   }
3440   return off;
3441 }
3442 
3443 // Note: load_signed_short used to be called load_signed_word.
3444 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3445 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3446 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3447 int MacroAssembler::load_signed_short(Register dst, Address src) {
3448   int off;
3449   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3450     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3451     // version but this is what 64bit has always done. This seems to imply
3452     // that users are only using 32bits worth.
3453     off = offset();
3454     movswl(dst, src); // movsxw
3455   } else {
3456     off = load_unsigned_short(dst, src);
3457     shll(dst, 16);
3458     sarl(dst, 16);
3459   }
3460   return off;
3461 }
3462 
3463 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3464   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3465   // and "3.9 Partial Register Penalties", p. 22).
3466   int off;
3467   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3468     off = offset();
3469     movzbl(dst, src); // movzxb
3470   } else {
3471     xorl(dst, dst);
3472     off = offset();
3473     movb(dst, src);
3474   }
3475   return off;
3476 }
3477 
3478 // Note: load_unsigned_short used to be called load_unsigned_word.
3479 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3480   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3481   // and "3.9 Partial Register Penalties", p. 22).
3482   int off;
3483   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3484     off = offset();
3485     movzwl(dst, src); // movzxw
3486   } else {
3487     xorl(dst, dst);
3488     off = offset();
3489     movw(dst, src);
3490   }
3491   return off;
3492 }
3493 
3494 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3495   switch (size_in_bytes) {
3496 #ifndef _LP64
3497   case  8:
3498     assert(dst2 != noreg, "second dest register required");
3499     movl(dst,  src);
3500     movl(dst2, src.plus_disp(BytesPerInt));
3501     break;
3502 #else
3503   case  8:  movq(dst, src); break;
3504 #endif
3505   case  4:  movl(dst, src); break;
3506   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3507   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3508   default:  ShouldNotReachHere();
3509   }
3510 }
3511 
3512 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3513   switch (size_in_bytes) {
3514 #ifndef _LP64
3515   case  8:
3516     assert(src2 != noreg, "second source register required");
3517     movl(dst,                        src);
3518     movl(dst.plus_disp(BytesPerInt), src2);
3519     break;
3520 #else
3521   case  8:  movq(dst, src); break;
3522 #endif
3523   case  4:  movl(dst, src); break;
3524   case  2:  movw(dst, src); break;
3525   case  1:  movb(dst, src); break;
3526   default:  ShouldNotReachHere();
3527   }
3528 }
3529 
3530 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3531   if (reachable(dst)) {
3532     movl(as_Address(dst), src);
3533   } else {
3534     lea(rscratch1, dst);
3535     movl(Address(rscratch1, 0), src);
3536   }
3537 }
3538 
3539 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3540   if (reachable(src)) {
3541     movl(dst, as_Address(src));
3542   } else {
3543     lea(rscratch1, src);
3544     movl(dst, Address(rscratch1, 0));
3545   }
3546 }
3547 
3548 // C++ bool manipulation
3549 
3550 void MacroAssembler::movbool(Register dst, Address src) {
3551   if(sizeof(bool) == 1)
3552     movb(dst, src);
3553   else if(sizeof(bool) == 2)
3554     movw(dst, src);
3555   else if(sizeof(bool) == 4)
3556     movl(dst, src);
3557   else
3558     // unsupported
3559     ShouldNotReachHere();
3560 }
3561 
3562 void MacroAssembler::movbool(Address dst, bool boolconst) {
3563   if(sizeof(bool) == 1)
3564     movb(dst, (int) boolconst);
3565   else if(sizeof(bool) == 2)
3566     movw(dst, (int) boolconst);
3567   else if(sizeof(bool) == 4)
3568     movl(dst, (int) boolconst);
3569   else
3570     // unsupported
3571     ShouldNotReachHere();
3572 }
3573 
3574 void MacroAssembler::movbool(Address dst, Register src) {
3575   if(sizeof(bool) == 1)
3576     movb(dst, src);
3577   else if(sizeof(bool) == 2)
3578     movw(dst, src);
3579   else if(sizeof(bool) == 4)
3580     movl(dst, src);
3581   else
3582     // unsupported
3583     ShouldNotReachHere();
3584 }
3585 
3586 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3587   movb(as_Address(dst), src);
3588 }
3589 
3590 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3591   if (reachable(src)) {
3592     movdl(dst, as_Address(src));
3593   } else {
3594     lea(rscratch1, src);
3595     movdl(dst, Address(rscratch1, 0));
3596   }
3597 }
3598 
3599 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3600   if (reachable(src)) {
3601     movq(dst, as_Address(src));
3602   } else {
3603     lea(rscratch1, src);
3604     movq(dst, Address(rscratch1, 0));
3605   }
3606 }
3607 
3608 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3609   if (reachable(src)) {
3610     if (UseXmmLoadAndClearUpper) {
3611       movsd (dst, as_Address(src));
3612     } else {
3613       movlpd(dst, as_Address(src));
3614     }
3615   } else {
3616     lea(rscratch1, src);
3617     if (UseXmmLoadAndClearUpper) {
3618       movsd (dst, Address(rscratch1, 0));
3619     } else {
3620       movlpd(dst, Address(rscratch1, 0));
3621     }
3622   }
3623 }
3624 
3625 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3626   if (reachable(src)) {
3627     movss(dst, as_Address(src));
3628   } else {
3629     lea(rscratch1, src);
3630     movss(dst, Address(rscratch1, 0));
3631   }
3632 }
3633 
3634 void MacroAssembler::movptr(Register dst, Register src) {
3635   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3636 }
3637 
3638 void MacroAssembler::movptr(Register dst, Address src) {
3639   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3640 }
3641 
3642 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3643 void MacroAssembler::movptr(Register dst, intptr_t src) {
3644   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3645 }
3646 
3647 void MacroAssembler::movptr(Address dst, Register src) {
3648   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3649 }
3650 
3651 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3652   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3653     Assembler::vextractf32x4h(dst, src, 0);
3654   } else {
3655     Assembler::movdqu(dst, src);
3656   }
3657 }
3658 
3659 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3660   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3661     Assembler::vinsertf32x4h(dst, src, 0);
3662   } else {
3663     Assembler::movdqu(dst, src);
3664   }
3665 }
3666 
3667 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3668   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3669     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3670   } else {
3671     Assembler::movdqu(dst, src);
3672   }
3673 }
3674 
3675 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) {
3676   if (reachable(src)) {
3677     movdqu(dst, as_Address(src));
3678   } else {
3679     lea(rscratch1, src);
3680     movdqu(dst, Address(rscratch1, 0));
3681   }
3682 }
3683 
3684 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3685   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3686     Assembler::vextractf64x4h(dst, src, 0);
3687   } else {
3688     Assembler::vmovdqu(dst, src);
3689   }
3690 }
3691 
3692 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3693   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3694     Assembler::vinsertf64x4h(dst, src, 0);
3695   } else {
3696     Assembler::vmovdqu(dst, src);
3697   }
3698 }
3699 
3700 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3701   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3702     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3703   }
3704   else {
3705     Assembler::vmovdqu(dst, src);
3706   }
3707 }
3708 
3709 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3710   if (reachable(src)) {
3711     vmovdqu(dst, as_Address(src));
3712   }
3713   else {
3714     lea(rscratch1, src);
3715     vmovdqu(dst, Address(rscratch1, 0));
3716   }
3717 }
3718 
3719 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3720   if (reachable(src)) {
3721     Assembler::movdqa(dst, as_Address(src));
3722   } else {
3723     lea(rscratch1, src);
3724     Assembler::movdqa(dst, Address(rscratch1, 0));
3725   }
3726 }
3727 
3728 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3729   if (reachable(src)) {
3730     Assembler::movsd(dst, as_Address(src));
3731   } else {
3732     lea(rscratch1, src);
3733     Assembler::movsd(dst, Address(rscratch1, 0));
3734   }
3735 }
3736 
3737 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3738   if (reachable(src)) {
3739     Assembler::movss(dst, as_Address(src));
3740   } else {
3741     lea(rscratch1, src);
3742     Assembler::movss(dst, Address(rscratch1, 0));
3743   }
3744 }
3745 
3746 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3747   if (reachable(src)) {
3748     Assembler::mulsd(dst, as_Address(src));
3749   } else {
3750     lea(rscratch1, src);
3751     Assembler::mulsd(dst, Address(rscratch1, 0));
3752   }
3753 }
3754 
3755 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3756   if (reachable(src)) {
3757     Assembler::mulss(dst, as_Address(src));
3758   } else {
3759     lea(rscratch1, src);
3760     Assembler::mulss(dst, Address(rscratch1, 0));
3761   }
3762 }
3763 
3764 void MacroAssembler::null_check(Register reg, int offset) {
3765   if (needs_explicit_null_check(offset)) {
3766     // provoke OS NULL exception if reg = NULL by
3767     // accessing M[reg] w/o changing any (non-CC) registers
3768     // NOTE: cmpl is plenty here to provoke a segv
3769     cmpptr(rax, Address(reg, 0));
3770     // Note: should probably use testl(rax, Address(reg, 0));
3771     //       may be shorter code (however, this version of
3772     //       testl needs to be implemented first)
3773   } else {
3774     // nothing to do, (later) access of M[reg + offset]
3775     // will provoke OS NULL exception if reg = NULL
3776   }
3777 }
3778 
3779 void MacroAssembler::os_breakpoint() {
3780   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3781   // (e.g., MSVC can't call ps() otherwise)
3782   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3783 }
3784 
3785 #ifdef _LP64
3786 #define XSTATE_BV 0x200
3787 #endif
3788 
3789 void MacroAssembler::pop_CPU_state() {
3790   pop_FPU_state();
3791   pop_IU_state();
3792 }
3793 
3794 void MacroAssembler::pop_FPU_state() {
3795 #ifndef _LP64
3796   frstor(Address(rsp, 0));
3797 #else
3798   fxrstor(Address(rsp, 0));
3799 #endif
3800   addptr(rsp, FPUStateSizeInWords * wordSize);
3801 }
3802 
3803 void MacroAssembler::pop_IU_state() {
3804   popa();
3805   LP64_ONLY(addq(rsp, 8));
3806   popf();
3807 }
3808 
3809 // Save Integer and Float state
3810 // Warning: Stack must be 16 byte aligned (64bit)
3811 void MacroAssembler::push_CPU_state() {
3812   push_IU_state();
3813   push_FPU_state();
3814 }
3815 
3816 void MacroAssembler::push_FPU_state() {
3817   subptr(rsp, FPUStateSizeInWords * wordSize);
3818 #ifndef _LP64
3819   fnsave(Address(rsp, 0));
3820   fwait();
3821 #else
3822   fxsave(Address(rsp, 0));
3823 #endif // LP64
3824 }
3825 
3826 void MacroAssembler::push_IU_state() {
3827   // Push flags first because pusha kills them
3828   pushf();
3829   // Make sure rsp stays 16-byte aligned
3830   LP64_ONLY(subq(rsp, 8));
3831   pusha();
3832 }
3833 
3834 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp, bool clear_pc) {
3835   // determine java_thread register
3836   if (!java_thread->is_valid()) {
3837     java_thread = rdi;
3838     get_thread(java_thread);
3839   }
3840   // we must set sp to zero to clear frame
3841   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3842   if (clear_fp) {
3843     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3844   }
3845 
3846   if (clear_pc)
3847     movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3848 
3849 }
3850 
3851 void MacroAssembler::restore_rax(Register tmp) {
3852   if (tmp == noreg) pop(rax);
3853   else if (tmp != rax) mov(rax, tmp);
3854 }
3855 
3856 void MacroAssembler::round_to(Register reg, int modulus) {
3857   addptr(reg, modulus - 1);
3858   andptr(reg, -modulus);
3859 }
3860 
3861 void MacroAssembler::save_rax(Register tmp) {
3862   if (tmp == noreg) push(rax);
3863   else if (tmp != rax) mov(tmp, rax);
3864 }
3865 
3866 // Write serialization page so VM thread can do a pseudo remote membar.
3867 // We use the current thread pointer to calculate a thread specific
3868 // offset to write to within the page. This minimizes bus traffic
3869 // due to cache line collision.
3870 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3871   movl(tmp, thread);
3872   shrl(tmp, os::get_serialize_page_shift_count());
3873   andl(tmp, (os::vm_page_size() - sizeof(int)));
3874 
3875   Address index(noreg, tmp, Address::times_1);
3876   ExternalAddress page(os::get_memory_serialize_page());
3877 
3878   // Size of store must match masking code above
3879   movl(as_Address(ArrayAddress(page, index)), tmp);
3880 }
3881 
3882 // Calls to C land
3883 //
3884 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3885 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3886 // has to be reset to 0. This is required to allow proper stack traversal.
3887 void MacroAssembler::set_last_Java_frame(Register java_thread,
3888                                          Register last_java_sp,
3889                                          Register last_java_fp,
3890                                          address  last_java_pc) {
3891   // determine java_thread register
3892   if (!java_thread->is_valid()) {
3893     java_thread = rdi;
3894     get_thread(java_thread);
3895   }
3896   // determine last_java_sp register
3897   if (!last_java_sp->is_valid()) {
3898     last_java_sp = rsp;
3899   }
3900 
3901   // last_java_fp is optional
3902 
3903   if (last_java_fp->is_valid()) {
3904     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3905   }
3906 
3907   // last_java_pc is optional
3908 
3909   if (last_java_pc != NULL) {
3910     lea(Address(java_thread,
3911                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3912         InternalAddress(last_java_pc));
3913 
3914   }
3915   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3916 }
3917 
3918 void MacroAssembler::shlptr(Register dst, int imm8) {
3919   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3920 }
3921 
3922 void MacroAssembler::shrptr(Register dst, int imm8) {
3923   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3924 }
3925 
3926 void MacroAssembler::sign_extend_byte(Register reg) {
3927   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3928     movsbl(reg, reg); // movsxb
3929   } else {
3930     shll(reg, 24);
3931     sarl(reg, 24);
3932   }
3933 }
3934 
3935 void MacroAssembler::sign_extend_short(Register reg) {
3936   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3937     movswl(reg, reg); // movsxw
3938   } else {
3939     shll(reg, 16);
3940     sarl(reg, 16);
3941   }
3942 }
3943 
3944 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3945   assert(reachable(src), "Address should be reachable");
3946   testl(dst, as_Address(src));
3947 }
3948 
3949 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
3950   if (reachable(src)) {
3951     Assembler::sqrtsd(dst, as_Address(src));
3952   } else {
3953     lea(rscratch1, src);
3954     Assembler::sqrtsd(dst, Address(rscratch1, 0));
3955   }
3956 }
3957 
3958 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
3959   if (reachable(src)) {
3960     Assembler::sqrtss(dst, as_Address(src));
3961   } else {
3962     lea(rscratch1, src);
3963     Assembler::sqrtss(dst, Address(rscratch1, 0));
3964   }
3965 }
3966 
3967 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
3968   if (reachable(src)) {
3969     Assembler::subsd(dst, as_Address(src));
3970   } else {
3971     lea(rscratch1, src);
3972     Assembler::subsd(dst, Address(rscratch1, 0));
3973   }
3974 }
3975 
3976 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
3977   if (reachable(src)) {
3978     Assembler::subss(dst, as_Address(src));
3979   } else {
3980     lea(rscratch1, src);
3981     Assembler::subss(dst, Address(rscratch1, 0));
3982   }
3983 }
3984 
3985 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
3986   if (reachable(src)) {
3987     Assembler::ucomisd(dst, as_Address(src));
3988   } else {
3989     lea(rscratch1, src);
3990     Assembler::ucomisd(dst, Address(rscratch1, 0));
3991   }
3992 }
3993 
3994 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
3995   if (reachable(src)) {
3996     Assembler::ucomiss(dst, as_Address(src));
3997   } else {
3998     lea(rscratch1, src);
3999     Assembler::ucomiss(dst, Address(rscratch1, 0));
4000   }
4001 }
4002 
4003 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4004   // Used in sign-bit flipping with aligned address.
4005   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4006   if (reachable(src)) {
4007     Assembler::xorpd(dst, as_Address(src));
4008   } else {
4009     lea(rscratch1, src);
4010     Assembler::xorpd(dst, Address(rscratch1, 0));
4011   }
4012 }
4013 
4014 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4015   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4016     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4017   }
4018   else {
4019     Assembler::xorpd(dst, src);
4020   }
4021 }
4022 
4023 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4024   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4025     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4026   } else {
4027     Assembler::xorps(dst, src);
4028   }
4029 }
4030 
4031 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4032   // Used in sign-bit flipping with aligned address.
4033   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4034   if (reachable(src)) {
4035     Assembler::xorps(dst, as_Address(src));
4036   } else {
4037     lea(rscratch1, src);
4038     Assembler::xorps(dst, Address(rscratch1, 0));
4039   }
4040 }
4041 
4042 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4043   // Used in sign-bit flipping with aligned address.
4044   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4045   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4046   if (reachable(src)) {
4047     Assembler::pshufb(dst, as_Address(src));
4048   } else {
4049     lea(rscratch1, src);
4050     Assembler::pshufb(dst, Address(rscratch1, 0));
4051   }
4052 }
4053 
4054 // AVX 3-operands instructions
4055 
4056 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4057   if (reachable(src)) {
4058     vaddsd(dst, nds, as_Address(src));
4059   } else {
4060     lea(rscratch1, src);
4061     vaddsd(dst, nds, Address(rscratch1, 0));
4062   }
4063 }
4064 
4065 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4066   if (reachable(src)) {
4067     vaddss(dst, nds, as_Address(src));
4068   } else {
4069     lea(rscratch1, src);
4070     vaddss(dst, nds, Address(rscratch1, 0));
4071   }
4072 }
4073 
4074 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4075   int dst_enc = dst->encoding();
4076   int nds_enc = nds->encoding();
4077   int src_enc = src->encoding();
4078   if ((dst_enc < 16) && (nds_enc < 16)) {
4079     vandps(dst, nds, negate_field, vector_len);
4080   } else if ((src_enc < 16) && (dst_enc < 16)) {
4081     movss(src, nds);
4082     vandps(dst, src, negate_field, vector_len);
4083   } else if (src_enc < 16) {
4084     movss(src, nds);
4085     vandps(src, src, negate_field, vector_len);
4086     movss(dst, src);
4087   } else if (dst_enc < 16) {
4088     movdqu(src, xmm0);
4089     movss(xmm0, nds);
4090     vandps(dst, xmm0, negate_field, vector_len);
4091     movdqu(xmm0, src);
4092   } else if (nds_enc < 16) {
4093     movdqu(src, xmm0);
4094     vandps(xmm0, nds, negate_field, vector_len);
4095     movss(dst, xmm0);
4096     movdqu(xmm0, src);
4097   } else {
4098     movdqu(src, xmm0);
4099     movss(xmm0, nds);
4100     vandps(xmm0, xmm0, negate_field, vector_len);
4101     movss(dst, xmm0);
4102     movdqu(xmm0, src);
4103   }
4104 }
4105 
4106 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4107   int dst_enc = dst->encoding();
4108   int nds_enc = nds->encoding();
4109   int src_enc = src->encoding();
4110   if ((dst_enc < 16) && (nds_enc < 16)) {
4111     vandpd(dst, nds, negate_field, vector_len);
4112   } else if ((src_enc < 16) && (dst_enc < 16)) {
4113     movsd(src, nds);
4114     vandpd(dst, src, negate_field, vector_len);
4115   } else if (src_enc < 16) {
4116     movsd(src, nds);
4117     vandpd(src, src, negate_field, vector_len);
4118     movsd(dst, src);
4119   } else if (dst_enc < 16) {
4120     movdqu(src, xmm0);
4121     movsd(xmm0, nds);
4122     vandpd(dst, xmm0, negate_field, vector_len);
4123     movdqu(xmm0, src);
4124   } else if (nds_enc < 16) {
4125     movdqu(src, xmm0);
4126     vandpd(xmm0, nds, negate_field, vector_len);
4127     movsd(dst, xmm0);
4128     movdqu(xmm0, src);
4129   } else {
4130     movdqu(src, xmm0);
4131     movsd(xmm0, nds);
4132     vandpd(xmm0, xmm0, negate_field, vector_len);
4133     movsd(dst, xmm0);
4134     movdqu(xmm0, src);
4135   }
4136 }
4137 
4138 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4139   int dst_enc = dst->encoding();
4140   int nds_enc = nds->encoding();
4141   int src_enc = src->encoding();
4142   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4143     Assembler::vpaddb(dst, nds, src, vector_len);
4144   } else if ((dst_enc < 16) && (src_enc < 16)) {
4145     Assembler::vpaddb(dst, dst, src, vector_len);
4146   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4147     // use nds as scratch for src
4148     evmovdqul(nds, src, Assembler::AVX_512bit);
4149     Assembler::vpaddb(dst, dst, nds, vector_len);
4150   } else if ((src_enc < 16) && (nds_enc < 16)) {
4151     // use nds as scratch for dst
4152     evmovdqul(nds, dst, Assembler::AVX_512bit);
4153     Assembler::vpaddb(nds, nds, src, vector_len);
4154     evmovdqul(dst, nds, Assembler::AVX_512bit);
4155   } else if (dst_enc < 16) {
4156     // use nds as scatch for xmm0 to hold src
4157     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4158     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4159     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4160     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4161   } else {
4162     // worse case scenario, all regs are in the upper bank
4163     subptr(rsp, 64);
4164     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4165     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4166     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4167     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4168     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4169     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4170     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4171     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4172     addptr(rsp, 64);
4173   }
4174 }
4175 
4176 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4177   int dst_enc = dst->encoding();
4178   int nds_enc = nds->encoding();
4179   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4180     Assembler::vpaddb(dst, nds, src, vector_len);
4181   } else if (dst_enc < 16) {
4182     Assembler::vpaddb(dst, dst, src, vector_len);
4183   } else if (nds_enc < 16) {
4184     // implies dst_enc in upper bank with src as scratch
4185     evmovdqul(nds, dst, Assembler::AVX_512bit);
4186     Assembler::vpaddb(nds, nds, src, vector_len);
4187     evmovdqul(dst, nds, Assembler::AVX_512bit);
4188   } else {
4189     // worse case scenario, all regs in upper bank
4190     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4191     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4192     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4193     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4194   }
4195 }
4196 
4197 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4198   int dst_enc = dst->encoding();
4199   int nds_enc = nds->encoding();
4200   int src_enc = src->encoding();
4201   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4202     Assembler::vpaddw(dst, nds, src, vector_len);
4203   } else if ((dst_enc < 16) && (src_enc < 16)) {
4204     Assembler::vpaddw(dst, dst, src, vector_len);
4205   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4206     // use nds as scratch for src
4207     evmovdqul(nds, src, Assembler::AVX_512bit);
4208     Assembler::vpaddw(dst, dst, nds, vector_len);
4209   } else if ((src_enc < 16) && (nds_enc < 16)) {
4210     // use nds as scratch for dst
4211     evmovdqul(nds, dst, Assembler::AVX_512bit);
4212     Assembler::vpaddw(nds, nds, src, vector_len);
4213     evmovdqul(dst, nds, Assembler::AVX_512bit);
4214   } else if (dst_enc < 16) {
4215     // use nds as scatch for xmm0 to hold src
4216     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4217     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4218     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4219     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4220   } else {
4221     // worse case scenario, all regs are in the upper bank
4222     subptr(rsp, 64);
4223     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4224     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4225     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4226     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4227     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4228     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4229     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4230     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4231     addptr(rsp, 64);
4232   }
4233 }
4234 
4235 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4236   int dst_enc = dst->encoding();
4237   int nds_enc = nds->encoding();
4238   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4239     Assembler::vpaddw(dst, nds, src, vector_len);
4240   } else if (dst_enc < 16) {
4241     Assembler::vpaddw(dst, dst, src, vector_len);
4242   } else if (nds_enc < 16) {
4243     // implies dst_enc in upper bank with src as scratch
4244     evmovdqul(nds, dst, Assembler::AVX_512bit);
4245     Assembler::vpaddw(nds, nds, src, vector_len);
4246     evmovdqul(dst, nds, Assembler::AVX_512bit);
4247   } else {
4248     // worse case scenario, all regs in upper bank
4249     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4250     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4251     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4252     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4253   }
4254 }
4255 
4256 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4257   int dst_enc = dst->encoding();
4258   int nds_enc = nds->encoding();
4259   int src_enc = src->encoding();
4260   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4261     Assembler::vpsubb(dst, nds, src, vector_len);
4262   } else if ((dst_enc < 16) && (src_enc < 16)) {
4263     Assembler::vpsubb(dst, dst, src, vector_len);
4264   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4265     // use nds as scratch for src
4266     evmovdqul(nds, src, Assembler::AVX_512bit);
4267     Assembler::vpsubb(dst, dst, nds, vector_len);
4268   } else if ((src_enc < 16) && (nds_enc < 16)) {
4269     // use nds as scratch for dst
4270     evmovdqul(nds, dst, Assembler::AVX_512bit);
4271     Assembler::vpsubb(nds, nds, src, vector_len);
4272     evmovdqul(dst, nds, Assembler::AVX_512bit);
4273   } else if (dst_enc < 16) {
4274     // use nds as scatch for xmm0 to hold src
4275     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4276     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4277     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4278     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4279   } else {
4280     // worse case scenario, all regs are in the upper bank
4281     subptr(rsp, 64);
4282     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4283     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4284     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4285     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4286     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4287     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4288     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4289     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4290     addptr(rsp, 64);
4291   }
4292 }
4293 
4294 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4295   int dst_enc = dst->encoding();
4296   int nds_enc = nds->encoding();
4297   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4298     Assembler::vpsubb(dst, nds, src, vector_len);
4299   } else if (dst_enc < 16) {
4300     Assembler::vpsubb(dst, dst, src, vector_len);
4301   } else if (nds_enc < 16) {
4302     // implies dst_enc in upper bank with src as scratch
4303     evmovdqul(nds, dst, Assembler::AVX_512bit);
4304     Assembler::vpsubb(nds, nds, src, vector_len);
4305     evmovdqul(dst, nds, Assembler::AVX_512bit);
4306   } else {
4307     // worse case scenario, all regs in upper bank
4308     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4309     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4310     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4311     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4312   }
4313 }
4314 
4315 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4316   int dst_enc = dst->encoding();
4317   int nds_enc = nds->encoding();
4318   int src_enc = src->encoding();
4319   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4320     Assembler::vpsubw(dst, nds, src, vector_len);
4321   } else if ((dst_enc < 16) && (src_enc < 16)) {
4322     Assembler::vpsubw(dst, dst, src, vector_len);
4323   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4324     // use nds as scratch for src
4325     evmovdqul(nds, src, Assembler::AVX_512bit);
4326     Assembler::vpsubw(dst, dst, nds, vector_len);
4327   } else if ((src_enc < 16) && (nds_enc < 16)) {
4328     // use nds as scratch for dst
4329     evmovdqul(nds, dst, Assembler::AVX_512bit);
4330     Assembler::vpsubw(nds, nds, src, vector_len);
4331     evmovdqul(dst, nds, Assembler::AVX_512bit);
4332   } else if (dst_enc < 16) {
4333     // use nds as scatch for xmm0 to hold src
4334     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4335     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4336     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4337     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4338   } else {
4339     // worse case scenario, all regs are in the upper bank
4340     subptr(rsp, 64);
4341     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4342     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4343     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4344     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4345     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4346     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4347     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4348     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4349     addptr(rsp, 64);
4350   }
4351 }
4352 
4353 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4354   int dst_enc = dst->encoding();
4355   int nds_enc = nds->encoding();
4356   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4357     Assembler::vpsubw(dst, nds, src, vector_len);
4358   } else if (dst_enc < 16) {
4359     Assembler::vpsubw(dst, dst, src, vector_len);
4360   } else if (nds_enc < 16) {
4361     // implies dst_enc in upper bank with src as scratch
4362     evmovdqul(nds, dst, Assembler::AVX_512bit);
4363     Assembler::vpsubw(nds, nds, src, vector_len);
4364     evmovdqul(dst, nds, Assembler::AVX_512bit);
4365   } else {
4366     // worse case scenario, all regs in upper bank
4367     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4368     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4369     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4370     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4371   }
4372 }
4373 
4374 
4375 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4376   int dst_enc = dst->encoding();
4377   int nds_enc = nds->encoding();
4378   int src_enc = src->encoding();
4379   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4380     Assembler::vpmullw(dst, nds, src, vector_len);
4381   } else if ((dst_enc < 16) && (src_enc < 16)) {
4382     Assembler::vpmullw(dst, dst, src, vector_len);
4383   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4384     // use nds as scratch for src
4385     evmovdqul(nds, src, Assembler::AVX_512bit);
4386     Assembler::vpmullw(dst, dst, nds, vector_len);
4387   } else if ((src_enc < 16) && (nds_enc < 16)) {
4388     // use nds as scratch for dst
4389     evmovdqul(nds, dst, Assembler::AVX_512bit);
4390     Assembler::vpmullw(nds, nds, src, vector_len);
4391     evmovdqul(dst, nds, Assembler::AVX_512bit);
4392   } else if (dst_enc < 16) {
4393     // use nds as scatch for xmm0 to hold src
4394     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4395     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4396     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4397     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4398   } else {
4399     // worse case scenario, all regs are in the upper bank
4400     subptr(rsp, 64);
4401     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4402     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4403     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4404     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4405     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4406     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4407     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4408     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4409     addptr(rsp, 64);
4410   }
4411 }
4412 
4413 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4414   int dst_enc = dst->encoding();
4415   int nds_enc = nds->encoding();
4416   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4417     Assembler::vpmullw(dst, nds, src, vector_len);
4418   } else if (dst_enc < 16) {
4419     Assembler::vpmullw(dst, dst, src, vector_len);
4420   } else if (nds_enc < 16) {
4421     // implies dst_enc in upper bank with src as scratch
4422     evmovdqul(nds, dst, Assembler::AVX_512bit);
4423     Assembler::vpmullw(nds, nds, src, vector_len);
4424     evmovdqul(dst, nds, Assembler::AVX_512bit);
4425   } else {
4426     // worse case scenario, all regs in upper bank
4427     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4428     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4429     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4430     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4431   }
4432 }
4433 
4434 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4435   int dst_enc = dst->encoding();
4436   int nds_enc = nds->encoding();
4437   int shift_enc = shift->encoding();
4438   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4439     Assembler::vpsraw(dst, nds, shift, vector_len);
4440   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4441     Assembler::vpsraw(dst, dst, shift, vector_len);
4442   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4443     // use nds_enc as scratch with shift
4444     evmovdqul(nds, shift, Assembler::AVX_512bit);
4445     Assembler::vpsraw(dst, dst, nds, vector_len);
4446   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4447     // use nds as scratch with dst
4448     evmovdqul(nds, dst, Assembler::AVX_512bit);
4449     Assembler::vpsraw(nds, nds, shift, vector_len);
4450     evmovdqul(dst, nds, Assembler::AVX_512bit);
4451   } else if (dst_enc < 16) {
4452     // use nds to save a copy of xmm0 and hold shift
4453     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4454     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4455     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4456     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4457   } else if (nds_enc < 16) {
4458     // use nds as dest as temps
4459     evmovdqul(nds, dst, Assembler::AVX_512bit);
4460     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4461     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4462     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4463     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4464     evmovdqul(dst, nds, Assembler::AVX_512bit);
4465   } else {
4466     // worse case scenario, all regs are in the upper bank
4467     subptr(rsp, 64);
4468     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4469     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4470     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4471     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4472     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4473     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4474     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4475     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4476     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4477     addptr(rsp, 64);
4478   }
4479 }
4480 
4481 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4482   int dst_enc = dst->encoding();
4483   int nds_enc = nds->encoding();
4484   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4485     Assembler::vpsraw(dst, nds, shift, vector_len);
4486   } else if (dst_enc < 16) {
4487     Assembler::vpsraw(dst, dst, shift, vector_len);
4488   } else if (nds_enc < 16) {
4489     // use nds as scratch
4490     evmovdqul(nds, dst, Assembler::AVX_512bit);
4491     Assembler::vpsraw(nds, nds, shift, vector_len);
4492     evmovdqul(dst, nds, Assembler::AVX_512bit);
4493   } else {
4494     // use nds as scratch for xmm0
4495     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4496     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4497     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4498     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4499   }
4500 }
4501 
4502 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4503   int dst_enc = dst->encoding();
4504   int nds_enc = nds->encoding();
4505   int shift_enc = shift->encoding();
4506   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4507     Assembler::vpsrlw(dst, nds, shift, vector_len);
4508   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4509     Assembler::vpsrlw(dst, dst, shift, vector_len);
4510   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4511     // use nds_enc as scratch with shift
4512     evmovdqul(nds, shift, Assembler::AVX_512bit);
4513     Assembler::vpsrlw(dst, dst, nds, vector_len);
4514   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4515     // use nds as scratch with dst
4516     evmovdqul(nds, dst, Assembler::AVX_512bit);
4517     Assembler::vpsrlw(nds, nds, shift, vector_len);
4518     evmovdqul(dst, nds, Assembler::AVX_512bit);
4519   } else if (dst_enc < 16) {
4520     // use nds to save a copy of xmm0 and hold shift
4521     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4522     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4523     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4524     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4525   } else if (nds_enc < 16) {
4526     // use nds as dest as temps
4527     evmovdqul(nds, dst, Assembler::AVX_512bit);
4528     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4529     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4530     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4531     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4532     evmovdqul(dst, nds, Assembler::AVX_512bit);
4533   } else {
4534     // worse case scenario, all regs are in the upper bank
4535     subptr(rsp, 64);
4536     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4537     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4538     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4539     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4540     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4541     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4542     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4543     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4544     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4545     addptr(rsp, 64);
4546   }
4547 }
4548 
4549 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4550   int dst_enc = dst->encoding();
4551   int nds_enc = nds->encoding();
4552   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4553     Assembler::vpsrlw(dst, nds, shift, vector_len);
4554   } else if (dst_enc < 16) {
4555     Assembler::vpsrlw(dst, dst, shift, vector_len);
4556   } else if (nds_enc < 16) {
4557     // use nds as scratch
4558     evmovdqul(nds, dst, Assembler::AVX_512bit);
4559     Assembler::vpsrlw(nds, nds, shift, vector_len);
4560     evmovdqul(dst, nds, Assembler::AVX_512bit);
4561   } else {
4562     // use nds as scratch for xmm0
4563     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4564     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4565     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4566     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4567   }
4568 }
4569 
4570 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4571   int dst_enc = dst->encoding();
4572   int nds_enc = nds->encoding();
4573   int shift_enc = shift->encoding();
4574   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4575     Assembler::vpsllw(dst, nds, shift, vector_len);
4576   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4577     Assembler::vpsllw(dst, dst, shift, vector_len);
4578   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4579     // use nds_enc as scratch with shift
4580     evmovdqul(nds, shift, Assembler::AVX_512bit);
4581     Assembler::vpsllw(dst, dst, nds, vector_len);
4582   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4583     // use nds as scratch with dst
4584     evmovdqul(nds, dst, Assembler::AVX_512bit);
4585     Assembler::vpsllw(nds, nds, shift, vector_len);
4586     evmovdqul(dst, nds, Assembler::AVX_512bit);
4587   } else if (dst_enc < 16) {
4588     // use nds to save a copy of xmm0 and hold shift
4589     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4590     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4591     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4592     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4593   } else if (nds_enc < 16) {
4594     // use nds as dest as temps
4595     evmovdqul(nds, dst, Assembler::AVX_512bit);
4596     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4597     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4598     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4599     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4600     evmovdqul(dst, nds, Assembler::AVX_512bit);
4601   } else {
4602     // worse case scenario, all regs are in the upper bank
4603     subptr(rsp, 64);
4604     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4605     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4606     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4607     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4608     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4609     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4610     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4611     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4612     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4613     addptr(rsp, 64);
4614   }
4615 }
4616 
4617 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4618   int dst_enc = dst->encoding();
4619   int nds_enc = nds->encoding();
4620   if (VM_Version::supports_avx256only() || VM_Version::supports_avx512bw()) {
4621     Assembler::vpsllw(dst, nds, shift, vector_len);
4622   } else if (dst_enc < 16) {
4623     Assembler::vpsllw(dst, dst, shift, vector_len);
4624   } else if (nds_enc < 16) {
4625     // use nds as scratch
4626     evmovdqul(nds, dst, Assembler::AVX_512bit);
4627     Assembler::vpsllw(nds, nds, shift, vector_len);
4628     evmovdqul(dst, nds, Assembler::AVX_512bit);
4629   } else {
4630     // use nds as scratch for xmm0
4631     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4632     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4633     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4634     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4635   }
4636 }
4637 
4638 // This instruction exists within macros, ergo we cannot control its input
4639 // when emitted through those patterns.
4640 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4641   if (VM_Version::supports_avx512nobw()) {
4642     int dst_enc = dst->encoding();
4643     int src_enc = src->encoding();
4644     if (dst_enc == src_enc) {
4645       if (dst_enc < 16) {
4646         Assembler::punpcklbw(dst, src);
4647       } else {
4648         subptr(rsp, 64);
4649         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4650         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4651         Assembler::punpcklbw(xmm0, xmm0);
4652         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4653         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4654         addptr(rsp, 64);
4655       }
4656     } else {
4657       if ((src_enc < 16) && (dst_enc < 16)) {
4658         Assembler::punpcklbw(dst, src);
4659       } else if (src_enc < 16) {
4660         subptr(rsp, 64);
4661         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4662         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663         Assembler::punpcklbw(xmm0, src);
4664         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4665         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4666         addptr(rsp, 64);
4667       } else if (dst_enc < 16) {
4668         subptr(rsp, 64);
4669         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4670         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4671         Assembler::punpcklbw(dst, xmm0);
4672         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4673         addptr(rsp, 64);
4674       } else {
4675         subptr(rsp, 64);
4676         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4677         subptr(rsp, 64);
4678         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4679         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4680         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4681         Assembler::punpcklbw(xmm0, xmm1);
4682         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4683         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4684         addptr(rsp, 64);
4685         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4686         addptr(rsp, 64);
4687       }
4688     }
4689   } else {
4690     Assembler::punpcklbw(dst, src);
4691   }
4692 }
4693 
4694 // This instruction exists within macros, ergo we cannot control its input
4695 // when emitted through those patterns.
4696 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
4697   if (VM_Version::supports_avx512nobw()) {
4698     int dst_enc = dst->encoding();
4699     int src_enc = src->encoding();
4700     if (dst_enc == src_enc) {
4701       if (dst_enc < 16) {
4702         Assembler::pshuflw(dst, src, mode);
4703       } else {
4704         subptr(rsp, 64);
4705         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4706         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4707         Assembler::pshuflw(xmm0, xmm0, mode);
4708         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4709         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4710         addptr(rsp, 64);
4711       }
4712     } else {
4713       if ((src_enc < 16) && (dst_enc < 16)) {
4714         Assembler::pshuflw(dst, src, mode);
4715       } else if (src_enc < 16) {
4716         subptr(rsp, 64);
4717         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4718         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4719         Assembler::pshuflw(xmm0, src, mode);
4720         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4721         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4722         addptr(rsp, 64);
4723       } else if (dst_enc < 16) {
4724         subptr(rsp, 64);
4725         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4726         evmovdqul(xmm0, src, Assembler::AVX_512bit);
4727         Assembler::pshuflw(dst, xmm0, mode);
4728         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4729         addptr(rsp, 64);
4730       } else {
4731         subptr(rsp, 64);
4732         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4733         subptr(rsp, 64);
4734         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4735         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4736         evmovdqul(xmm1, src, Assembler::AVX_512bit);
4737         Assembler::pshuflw(xmm0, xmm1, mode);
4738         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4739         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4740         addptr(rsp, 64);
4741         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4742         addptr(rsp, 64);
4743       }
4744     }
4745   } else {
4746     Assembler::pshuflw(dst, src, mode);
4747   }
4748 }
4749 
4750 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4751   if (reachable(src)) {
4752     vandpd(dst, nds, as_Address(src), vector_len);
4753   } else {
4754     lea(rscratch1, src);
4755     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
4756   }
4757 }
4758 
4759 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4760   if (reachable(src)) {
4761     vandps(dst, nds, as_Address(src), vector_len);
4762   } else {
4763     lea(rscratch1, src);
4764     vandps(dst, nds, Address(rscratch1, 0), vector_len);
4765   }
4766 }
4767 
4768 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4769   if (reachable(src)) {
4770     vdivsd(dst, nds, as_Address(src));
4771   } else {
4772     lea(rscratch1, src);
4773     vdivsd(dst, nds, Address(rscratch1, 0));
4774   }
4775 }
4776 
4777 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4778   if (reachable(src)) {
4779     vdivss(dst, nds, as_Address(src));
4780   } else {
4781     lea(rscratch1, src);
4782     vdivss(dst, nds, Address(rscratch1, 0));
4783   }
4784 }
4785 
4786 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4787   if (reachable(src)) {
4788     vmulsd(dst, nds, as_Address(src));
4789   } else {
4790     lea(rscratch1, src);
4791     vmulsd(dst, nds, Address(rscratch1, 0));
4792   }
4793 }
4794 
4795 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4796   if (reachable(src)) {
4797     vmulss(dst, nds, as_Address(src));
4798   } else {
4799     lea(rscratch1, src);
4800     vmulss(dst, nds, Address(rscratch1, 0));
4801   }
4802 }
4803 
4804 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4805   if (reachable(src)) {
4806     vsubsd(dst, nds, as_Address(src));
4807   } else {
4808     lea(rscratch1, src);
4809     vsubsd(dst, nds, Address(rscratch1, 0));
4810   }
4811 }
4812 
4813 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4814   if (reachable(src)) {
4815     vsubss(dst, nds, as_Address(src));
4816   } else {
4817     lea(rscratch1, src);
4818     vsubss(dst, nds, Address(rscratch1, 0));
4819   }
4820 }
4821 
4822 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4823   int nds_enc = nds->encoding();
4824   int dst_enc = dst->encoding();
4825   bool dst_upper_bank = (dst_enc > 15);
4826   bool nds_upper_bank = (nds_enc > 15);
4827   if (VM_Version::supports_avx512novl() &&
4828       (nds_upper_bank || dst_upper_bank)) {
4829     if (dst_upper_bank) {
4830       subptr(rsp, 64);
4831       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4832       movflt(xmm0, nds);
4833       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
4834       movflt(dst, xmm0);
4835       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4836       addptr(rsp, 64);
4837     } else {
4838       movflt(dst, nds);
4839       vxorps(dst, dst, src, Assembler::AVX_128bit);
4840     }
4841   } else {
4842     vxorps(dst, nds, src, Assembler::AVX_128bit);
4843   }
4844 }
4845 
4846 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4847   int nds_enc = nds->encoding();
4848   int dst_enc = dst->encoding();
4849   bool dst_upper_bank = (dst_enc > 15);
4850   bool nds_upper_bank = (nds_enc > 15);
4851   if (VM_Version::supports_avx512novl() &&
4852       (nds_upper_bank || dst_upper_bank)) {
4853     if (dst_upper_bank) {
4854       subptr(rsp, 64);
4855       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4856       movdbl(xmm0, nds);
4857       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
4858       movdbl(dst, xmm0);
4859       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4860       addptr(rsp, 64);
4861     } else {
4862       movdbl(dst, nds);
4863       vxorpd(dst, dst, src, Assembler::AVX_128bit);
4864     }
4865   } else {
4866     vxorpd(dst, nds, src, Assembler::AVX_128bit);
4867   }
4868 }
4869 
4870 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4871   if (reachable(src)) {
4872     vxorpd(dst, nds, as_Address(src), vector_len);
4873   } else {
4874     lea(rscratch1, src);
4875     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
4876   }
4877 }
4878 
4879 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4880   if (reachable(src)) {
4881     vxorps(dst, nds, as_Address(src), vector_len);
4882   } else {
4883     lea(rscratch1, src);
4884     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
4885   }
4886 }
4887 
4888 
4889 //////////////////////////////////////////////////////////////////////////////////
4890 #if INCLUDE_ALL_GCS
4891 
4892 void MacroAssembler::g1_write_barrier_pre(Register obj,
4893                                           Register pre_val,
4894                                           Register thread,
4895                                           Register tmp,
4896                                           bool tosca_live,
4897                                           bool expand_call) {
4898 
4899   // If expand_call is true then we expand the call_VM_leaf macro
4900   // directly to skip generating the check by
4901   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
4902 
4903 #ifdef _LP64
4904   assert(thread == r15_thread, "must be");
4905 #endif // _LP64
4906 
4907   Label done;
4908   Label runtime;
4909 
4910   assert(pre_val != noreg, "check this code");
4911 
4912   if (obj != noreg) {
4913     assert_different_registers(obj, pre_val, tmp);
4914     assert(pre_val != rax, "check this code");
4915   }
4916 
4917   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4918                                        PtrQueue::byte_offset_of_active()));
4919   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4920                                        PtrQueue::byte_offset_of_index()));
4921   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
4922                                        PtrQueue::byte_offset_of_buf()));
4923 
4924 
4925   // Is marking active?
4926   if (in_bytes(PtrQueue::byte_width_of_active()) == 4) {
4927     cmpl(in_progress, 0);
4928   } else {
4929     assert(in_bytes(PtrQueue::byte_width_of_active()) == 1, "Assumption");
4930     cmpb(in_progress, 0);
4931   }
4932   jcc(Assembler::equal, done);
4933 
4934   // Do we need to load the previous value?
4935   if (obj != noreg) {
4936     load_heap_oop(pre_val, Address(obj, 0));
4937   }
4938 
4939   // Is the previous value null?
4940   cmpptr(pre_val, (int32_t) NULL_WORD);
4941   jcc(Assembler::equal, done);
4942 
4943   // Can we store original value in the thread's buffer?
4944   // Is index == 0?
4945   // (The index field is typed as size_t.)
4946 
4947   movptr(tmp, index);                   // tmp := *index_adr
4948   cmpptr(tmp, 0);                       // tmp == 0?
4949   jcc(Assembler::equal, runtime);       // If yes, goto runtime
4950 
4951   subptr(tmp, wordSize);                // tmp := tmp - wordSize
4952   movptr(index, tmp);                   // *index_adr := tmp
4953   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
4954 
4955   // Record the previous value
4956   movptr(Address(tmp, 0), pre_val);
4957   jmp(done);
4958 
4959   bind(runtime);
4960   // save the live input values
4961   if(tosca_live) push(rax);
4962 
4963   if (obj != noreg && obj != rax)
4964     push(obj);
4965 
4966   if (pre_val != rax)
4967     push(pre_val);
4968 
4969   // Calling the runtime using the regular call_VM_leaf mechanism generates
4970   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
4971   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
4972   //
4973   // If we care generating the pre-barrier without a frame (e.g. in the
4974   // intrinsified Reference.get() routine) then ebp might be pointing to
4975   // the caller frame and so this check will most likely fail at runtime.
4976   //
4977   // Expanding the call directly bypasses the generation of the check.
4978   // So when we do not have have a full interpreter frame on the stack
4979   // expand_call should be passed true.
4980 
4981   NOT_LP64( push(thread); )
4982 
4983   if (expand_call) {
4984     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
4985     pass_arg1(this, thread);
4986     pass_arg0(this, pre_val);
4987     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
4988   } else {
4989     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
4990   }
4991 
4992   NOT_LP64( pop(thread); )
4993 
4994   // save the live input values
4995   if (pre_val != rax)
4996     pop(pre_val);
4997 
4998   if (obj != noreg && obj != rax)
4999     pop(obj);
5000 
5001   if(tosca_live) pop(rax);
5002 
5003   bind(done);
5004 }
5005 
5006 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5007                                            Register new_val,
5008                                            Register thread,
5009                                            Register tmp,
5010                                            Register tmp2) {
5011 #ifdef _LP64
5012   assert(thread == r15_thread, "must be");
5013 #endif // _LP64
5014 
5015   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5016                                        PtrQueue::byte_offset_of_index()));
5017   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5018                                        PtrQueue::byte_offset_of_buf()));
5019 
5020   CardTableModRefBS* ct =
5021     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5022   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5023 
5024   Label done;
5025   Label runtime;
5026 
5027   // Does store cross heap regions?
5028 
5029   movptr(tmp, store_addr);
5030   xorptr(tmp, new_val);
5031   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5032   jcc(Assembler::equal, done);
5033 
5034   // crosses regions, storing NULL?
5035 
5036   cmpptr(new_val, (int32_t) NULL_WORD);
5037   jcc(Assembler::equal, done);
5038 
5039   // storing region crossing non-NULL, is card already dirty?
5040 
5041   const Register card_addr = tmp;
5042   const Register cardtable = tmp2;
5043 
5044   movptr(card_addr, store_addr);
5045   shrptr(card_addr, CardTableModRefBS::card_shift);
5046   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5047   // a valid address and therefore is not properly handled by the relocation code.
5048   movptr(cardtable, (intptr_t)ct->byte_map_base);
5049   addptr(card_addr, cardtable);
5050 
5051   cmpb(Address(card_addr, 0), (int)G1SATBCardTableModRefBS::g1_young_card_val());
5052   jcc(Assembler::equal, done);
5053 
5054   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5055   cmpb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5056   jcc(Assembler::equal, done);
5057 
5058 
5059   // storing a region crossing, non-NULL oop, card is clean.
5060   // dirty card and log.
5061 
5062   movb(Address(card_addr, 0), (int)CardTableModRefBS::dirty_card_val());
5063 
5064   cmpl(queue_index, 0);
5065   jcc(Assembler::equal, runtime);
5066   subl(queue_index, wordSize);
5067   movptr(tmp2, buffer);
5068 #ifdef _LP64
5069   movslq(rscratch1, queue_index);
5070   addq(tmp2, rscratch1);
5071   movq(Address(tmp2, 0), card_addr);
5072 #else
5073   addl(tmp2, queue_index);
5074   movl(Address(tmp2, 0), card_addr);
5075 #endif
5076   jmp(done);
5077 
5078   bind(runtime);
5079   // save the live input values
5080   push(store_addr);
5081   push(new_val);
5082 #ifdef _LP64
5083   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5084 #else
5085   push(thread);
5086   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5087   pop(thread);
5088 #endif
5089   pop(new_val);
5090   pop(store_addr);
5091 
5092   bind(done);
5093 }
5094 
5095 #endif // INCLUDE_ALL_GCS
5096 //////////////////////////////////////////////////////////////////////////////////
5097 
5098 
5099 void MacroAssembler::store_check(Register obj, Address dst) {
5100   store_check(obj);
5101 }
5102 
5103 void MacroAssembler::store_check(Register obj) {
5104   // Does a store check for the oop in register obj. The content of
5105   // register obj is destroyed afterwards.
5106   BarrierSet* bs = Universe::heap()->barrier_set();
5107   assert(bs->kind() == BarrierSet::CardTableForRS ||
5108          bs->kind() == BarrierSet::CardTableExtension,
5109          "Wrong barrier set kind");
5110 
5111   CardTableModRefBS* ct = barrier_set_cast<CardTableModRefBS>(bs);
5112   assert(sizeof(*ct->byte_map_base) == sizeof(jbyte), "adjust this code");
5113 
5114   shrptr(obj, CardTableModRefBS::card_shift);
5115 
5116   Address card_addr;
5117 
5118   // The calculation for byte_map_base is as follows:
5119   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5120   // So this essentially converts an address to a displacement and it will
5121   // never need to be relocated. On 64bit however the value may be too
5122   // large for a 32bit displacement.
5123   intptr_t disp = (intptr_t) ct->byte_map_base;
5124   if (is_simm32(disp)) {
5125     card_addr = Address(noreg, obj, Address::times_1, disp);
5126   } else {
5127     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5128     // displacement and done in a single instruction given favorable mapping and a
5129     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5130     // entry and that entry is not properly handled by the relocation code.
5131     AddressLiteral cardtable((address)ct->byte_map_base, relocInfo::none);
5132     Address index(noreg, obj, Address::times_1);
5133     card_addr = as_Address(ArrayAddress(cardtable, index));
5134   }
5135 
5136   int dirty = CardTableModRefBS::dirty_card_val();
5137   if (UseCondCardMark) {
5138     Label L_already_dirty;
5139     if (UseConcMarkSweepGC) {
5140       membar(Assembler::StoreLoad);
5141     }
5142     cmpb(card_addr, dirty);
5143     jcc(Assembler::equal, L_already_dirty);
5144     movb(card_addr, dirty);
5145     bind(L_already_dirty);
5146   } else {
5147     movb(card_addr, dirty);
5148   }
5149 }
5150 
5151 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5152   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5153 }
5154 
5155 // Force generation of a 4 byte immediate value even if it fits into 8bit
5156 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5157   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5158 }
5159 
5160 void MacroAssembler::subptr(Register dst, Register src) {
5161   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5162 }
5163 
5164 // C++ bool manipulation
5165 void MacroAssembler::testbool(Register dst) {
5166   if(sizeof(bool) == 1)
5167     testb(dst, 0xff);
5168   else if(sizeof(bool) == 2) {
5169     // testw implementation needed for two byte bools
5170     ShouldNotReachHere();
5171   } else if(sizeof(bool) == 4)
5172     testl(dst, dst);
5173   else
5174     // unsupported
5175     ShouldNotReachHere();
5176 }
5177 
5178 void MacroAssembler::testptr(Register dst, Register src) {
5179   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5180 }
5181 
5182 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5183 void MacroAssembler::tlab_allocate(Register obj,
5184                                    Register var_size_in_bytes,
5185                                    int con_size_in_bytes,
5186                                    Register t1,
5187                                    Register t2,
5188                                    Label& slow_case) {
5189   assert_different_registers(obj, t1, t2);
5190   assert_different_registers(obj, var_size_in_bytes, t1);
5191   Register end = t2;
5192   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5193 
5194   verify_tlab();
5195 
5196   NOT_LP64(get_thread(thread));
5197 
5198   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5199   if (var_size_in_bytes == noreg) {
5200     lea(end, Address(obj, con_size_in_bytes));
5201   } else {
5202     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5203   }
5204   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5205   jcc(Assembler::above, slow_case);
5206 
5207   // update the tlab top pointer
5208   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5209 
5210   // recover var_size_in_bytes if necessary
5211   if (var_size_in_bytes == end) {
5212     subptr(var_size_in_bytes, obj);
5213   }
5214   verify_tlab();
5215 }
5216 
5217 // Preserves rbx, and rdx.
5218 Register MacroAssembler::tlab_refill(Label& retry,
5219                                      Label& try_eden,
5220                                      Label& slow_case) {
5221   Register top = rax;
5222   Register t1  = rcx;
5223   Register t2  = rsi;
5224   Register thread_reg = NOT_LP64(rdi) LP64_ONLY(r15_thread);
5225   assert_different_registers(top, thread_reg, t1, t2, /* preserve: */ rbx, rdx);
5226   Label do_refill, discard_tlab;
5227 
5228   if (!Universe::heap()->supports_inline_contig_alloc()) {
5229     // No allocation in the shared eden.
5230     jmp(slow_case);
5231   }
5232 
5233   NOT_LP64(get_thread(thread_reg));
5234 
5235   movptr(top, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5236   movptr(t1,  Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5237 
5238   // calculate amount of free space
5239   subptr(t1, top);
5240   shrptr(t1, LogHeapWordSize);
5241 
5242   // Retain tlab and allocate object in shared space if
5243   // the amount free in the tlab is too large to discard.
5244   cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())));
5245   jcc(Assembler::lessEqual, discard_tlab);
5246 
5247   // Retain
5248   // %%% yuck as movptr...
5249   movptr(t2, (int32_t) ThreadLocalAllocBuffer::refill_waste_limit_increment());
5250   addptr(Address(thread_reg, in_bytes(JavaThread::tlab_refill_waste_limit_offset())), t2);
5251   if (TLABStats) {
5252     // increment number of slow_allocations
5253     addl(Address(thread_reg, in_bytes(JavaThread::tlab_slow_allocations_offset())), 1);
5254   }
5255   jmp(try_eden);
5256 
5257   bind(discard_tlab);
5258   if (TLABStats) {
5259     // increment number of refills
5260     addl(Address(thread_reg, in_bytes(JavaThread::tlab_number_of_refills_offset())), 1);
5261     // accumulate wastage -- t1 is amount free in tlab
5262     addl(Address(thread_reg, in_bytes(JavaThread::tlab_fast_refill_waste_offset())), t1);
5263   }
5264 
5265   // if tlab is currently allocated (top or end != null) then
5266   // fill [top, end + alignment_reserve) with array object
5267   testptr(top, top);
5268   jcc(Assembler::zero, do_refill);
5269 
5270   // set up the mark word
5271   movptr(Address(top, oopDesc::mark_offset_in_bytes()), (intptr_t)markOopDesc::prototype()->copy_set_hash(0x2));
5272   // set the length to the remaining space
5273   subptr(t1, typeArrayOopDesc::header_size(T_INT));
5274   addptr(t1, (int32_t)ThreadLocalAllocBuffer::alignment_reserve());
5275   shlptr(t1, log2_intptr(HeapWordSize/sizeof(jint)));
5276   movl(Address(top, arrayOopDesc::length_offset_in_bytes()), t1);
5277   // set klass to intArrayKlass
5278   // dubious reloc why not an oop reloc?
5279   movptr(t1, ExternalAddress((address)Universe::intArrayKlassObj_addr()));
5280   // store klass last.  concurrent gcs assumes klass length is valid if
5281   // klass field is not null.
5282   store_klass(top, t1);
5283 
5284   movptr(t1, top);
5285   subptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5286   incr_allocated_bytes(thread_reg, t1, 0);
5287 
5288   // refill the tlab with an eden allocation
5289   bind(do_refill);
5290   movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5291   shlptr(t1, LogHeapWordSize);
5292   // allocate new tlab, address returned in top
5293   eden_allocate(top, t1, 0, t2, slow_case);
5294 
5295   // Check that t1 was preserved in eden_allocate.
5296 #ifdef ASSERT
5297   if (UseTLAB) {
5298     Label ok;
5299     Register tsize = rsi;
5300     assert_different_registers(tsize, thread_reg, t1);
5301     push(tsize);
5302     movptr(tsize, Address(thread_reg, in_bytes(JavaThread::tlab_size_offset())));
5303     shlptr(tsize, LogHeapWordSize);
5304     cmpptr(t1, tsize);
5305     jcc(Assembler::equal, ok);
5306     STOP("assert(t1 != tlab size)");
5307     should_not_reach_here();
5308 
5309     bind(ok);
5310     pop(tsize);
5311   }
5312 #endif
5313   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())), top);
5314   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())), top);
5315   addptr(top, t1);
5316   subptr(top, (int32_t)ThreadLocalAllocBuffer::alignment_reserve_in_bytes());
5317   movptr(Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())), top);
5318   verify_tlab();
5319   jmp(retry);
5320 
5321   return thread_reg; // for use by caller
5322 }
5323 
5324 void MacroAssembler::incr_allocated_bytes(Register thread,
5325                                           Register var_size_in_bytes,
5326                                           int con_size_in_bytes,
5327                                           Register t1) {
5328   if (!thread->is_valid()) {
5329 #ifdef _LP64
5330     thread = r15_thread;
5331 #else
5332     assert(t1->is_valid(), "need temp reg");
5333     thread = t1;
5334     get_thread(thread);
5335 #endif
5336   }
5337 
5338 #ifdef _LP64
5339   if (var_size_in_bytes->is_valid()) {
5340     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5341   } else {
5342     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5343   }
5344 #else
5345   if (var_size_in_bytes->is_valid()) {
5346     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5347   } else {
5348     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5349   }
5350   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5351 #endif
5352 }
5353 
5354 void MacroAssembler::fp_runtime_fallback(address runtime_entry, int nb_args, int num_fpu_regs_in_use) {
5355   pusha();
5356 
5357   // if we are coming from c1, xmm registers may be live
5358   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
5359   if (UseAVX > 2) {
5360     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
5361   }
5362 
5363   if (UseSSE == 1)  {
5364     subptr(rsp, sizeof(jdouble)*8);
5365     for (int n = 0; n < 8; n++) {
5366       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
5367     }
5368   } else if (UseSSE >= 2)  {
5369     if (UseAVX > 2) {
5370       push(rbx);
5371       movl(rbx, 0xffff);
5372       kmovwl(k1, rbx);
5373       pop(rbx);
5374     }
5375 #ifdef COMPILER2
5376     if (MaxVectorSize > 16) {
5377       if(UseAVX > 2) {
5378         // Save upper half of ZMM registers
5379         subptr(rsp, 32*num_xmm_regs);
5380         for (int n = 0; n < num_xmm_regs; n++) {
5381           vextractf64x4h(Address(rsp, n*32), as_XMMRegister(n), 1);
5382         }
5383       }
5384       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
5385       // Save upper half of YMM registers
5386       subptr(rsp, 16*num_xmm_regs);
5387       for (int n = 0; n < num_xmm_regs; n++) {
5388         vextractf128h(Address(rsp, n*16), as_XMMRegister(n));
5389       }
5390     }
5391 #endif
5392     // Save whole 128bit (16 bytes) XMM registers
5393     subptr(rsp, 16*num_xmm_regs);
5394 #ifdef _LP64
5395     if (VM_Version::supports_evex()) {
5396       for (int n = 0; n < num_xmm_regs; n++) {
5397         vextractf32x4h(Address(rsp, n*16), as_XMMRegister(n), 0);
5398       }
5399     } else {
5400       for (int n = 0; n < num_xmm_regs; n++) {
5401         movdqu(Address(rsp, n*16), as_XMMRegister(n));
5402       }
5403     }
5404 #else
5405     for (int n = 0; n < num_xmm_regs; n++) {
5406       movdqu(Address(rsp, n*16), as_XMMRegister(n));
5407     }
5408 #endif
5409   }
5410 
5411   // Preserve registers across runtime call
5412   int incoming_argument_and_return_value_offset = -1;
5413   if (num_fpu_regs_in_use > 1) {
5414     // Must preserve all other FPU regs (could alternatively convert
5415     // SharedRuntime::dsin, dcos etc. into assembly routines known not to trash
5416     // FPU state, but can not trust C compiler)
5417     NEEDS_CLEANUP;
5418     // NOTE that in this case we also push the incoming argument(s) to
5419     // the stack and restore it later; we also use this stack slot to
5420     // hold the return value from dsin, dcos etc.
5421     for (int i = 0; i < num_fpu_regs_in_use; i++) {
5422       subptr(rsp, sizeof(jdouble));
5423       fstp_d(Address(rsp, 0));
5424     }
5425     incoming_argument_and_return_value_offset = sizeof(jdouble)*(num_fpu_regs_in_use-1);
5426     for (int i = nb_args-1; i >= 0; i--) {
5427       fld_d(Address(rsp, incoming_argument_and_return_value_offset-i*sizeof(jdouble)));
5428     }
5429   }
5430 
5431   subptr(rsp, nb_args*sizeof(jdouble));
5432   for (int i = 0; i < nb_args; i++) {
5433     fstp_d(Address(rsp, i*sizeof(jdouble)));
5434   }
5435 
5436 #ifdef _LP64
5437   if (nb_args > 0) {
5438     movdbl(xmm0, Address(rsp, 0));
5439   }
5440   if (nb_args > 1) {
5441     movdbl(xmm1, Address(rsp, sizeof(jdouble)));
5442   }
5443   assert(nb_args <= 2, "unsupported number of args");
5444 #endif // _LP64
5445 
5446   // NOTE: we must not use call_VM_leaf here because that requires a
5447   // complete interpreter frame in debug mode -- same bug as 4387334
5448   // MacroAssembler::call_VM_leaf_base is perfectly safe and will
5449   // do proper 64bit abi
5450 
5451   NEEDS_CLEANUP;
5452   // Need to add stack banging before this runtime call if it needs to
5453   // be taken; however, there is no generic stack banging routine at
5454   // the MacroAssembler level
5455 
5456   MacroAssembler::call_VM_leaf_base(runtime_entry, 0);
5457 
5458 #ifdef _LP64
5459   movsd(Address(rsp, 0), xmm0);
5460   fld_d(Address(rsp, 0));
5461 #endif // _LP64
5462   addptr(rsp, sizeof(jdouble)*nb_args);
5463   if (num_fpu_regs_in_use > 1) {
5464     // Must save return value to stack and then restore entire FPU
5465     // stack except incoming arguments
5466     fstp_d(Address(rsp, incoming_argument_and_return_value_offset));
5467     for (int i = 0; i < num_fpu_regs_in_use - nb_args; i++) {
5468       fld_d(Address(rsp, 0));
5469       addptr(rsp, sizeof(jdouble));
5470     }
5471     fld_d(Address(rsp, (nb_args-1)*sizeof(jdouble)));
5472     addptr(rsp, sizeof(jdouble)*nb_args);
5473   }
5474 
5475   if (UseSSE == 1)  {
5476     for (int n = 0; n < 8; n++) {
5477       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
5478     }
5479     addptr(rsp, sizeof(jdouble)*8);
5480   } else if (UseSSE >= 2)  {
5481     // Restore whole 128bit (16 bytes) XMM registers
5482 #ifdef _LP64
5483   if (VM_Version::supports_evex()) {
5484     for (int n = 0; n < num_xmm_regs; n++) {
5485       vinsertf32x4h(as_XMMRegister(n), Address(rsp, n*16), 0);
5486     }
5487   } else {
5488     for (int n = 0; n < num_xmm_regs; n++) {
5489       movdqu(as_XMMRegister(n), Address(rsp, n*16));
5490     }
5491   }
5492 #else
5493   for (int n = 0; n < num_xmm_regs; n++) {
5494     movdqu(as_XMMRegister(n), Address(rsp, n*16));
5495   }
5496 #endif
5497     addptr(rsp, 16*num_xmm_regs);
5498 
5499 #ifdef COMPILER2
5500     if (MaxVectorSize > 16) {
5501       // Restore upper half of YMM registers.
5502       for (int n = 0; n < num_xmm_regs; n++) {
5503         vinsertf128h(as_XMMRegister(n), Address(rsp, n*16));
5504       }
5505       addptr(rsp, 16*num_xmm_regs);
5506       if(UseAVX > 2) {
5507         for (int n = 0; n < num_xmm_regs; n++) {
5508           vinsertf64x4h(as_XMMRegister(n), Address(rsp, n*32), 1);
5509         }
5510         addptr(rsp, 32*num_xmm_regs);
5511       }
5512     }
5513 #endif
5514   }
5515   popa();
5516 }
5517 
5518 static const double     pi_4 =  0.7853981633974483;
5519 
5520 void MacroAssembler::trigfunc(char trig, int num_fpu_regs_in_use) {
5521   // A hand-coded argument reduction for values in fabs(pi/4, pi/2)
5522   // was attempted in this code; unfortunately it appears that the
5523   // switch to 80-bit precision and back causes this to be
5524   // unprofitable compared with simply performing a runtime call if
5525   // the argument is out of the (-pi/4, pi/4) range.
5526 
5527   Register tmp = noreg;
5528   if (!VM_Version::supports_cmov()) {
5529     // fcmp needs a temporary so preserve rbx,
5530     tmp = rbx;
5531     push(tmp);
5532   }
5533 
5534   Label slow_case, done;
5535 
5536   ExternalAddress pi4_adr = (address)&pi_4;
5537   if (reachable(pi4_adr)) {
5538     // x ?<= pi/4
5539     fld_d(pi4_adr);
5540     fld_s(1);                // Stack:  X  PI/4  X
5541     fabs();                  // Stack: |X| PI/4  X
5542     fcmp(tmp);
5543     jcc(Assembler::above, slow_case);
5544 
5545     // fastest case: -pi/4 <= x <= pi/4
5546     switch(trig) {
5547     case 's':
5548       fsin();
5549       break;
5550     case 'c':
5551       fcos();
5552       break;
5553     case 't':
5554       ftan();
5555       break;
5556     default:
5557       assert(false, "bad intrinsic");
5558       break;
5559     }
5560     jmp(done);
5561   }
5562 
5563   // slow case: runtime call
5564   bind(slow_case);
5565 
5566   switch(trig) {
5567   case 's':
5568     {
5569       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dsin), 1, num_fpu_regs_in_use);
5570     }
5571     break;
5572   case 'c':
5573     {
5574       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dcos), 1, num_fpu_regs_in_use);
5575     }
5576     break;
5577   case 't':
5578     {
5579       fp_runtime_fallback(CAST_FROM_FN_PTR(address, SharedRuntime::dtan), 1, num_fpu_regs_in_use);
5580     }
5581     break;
5582   default:
5583     assert(false, "bad intrinsic");
5584     break;
5585   }
5586 
5587   // Come here with result in F-TOS
5588   bind(done);
5589 
5590   if (tmp != noreg) {
5591     pop(tmp);
5592   }
5593 }
5594 
5595 
5596 // Look up the method for a megamorphic invokeinterface call.
5597 // The target method is determined by <intf_klass, itable_index>.
5598 // The receiver klass is in recv_klass.
5599 // On success, the result will be in method_result, and execution falls through.
5600 // On failure, execution transfers to the given label.
5601 void MacroAssembler::lookup_interface_method(Register recv_klass,
5602                                              Register intf_klass,
5603                                              RegisterOrConstant itable_index,
5604                                              Register method_result,
5605                                              Register scan_temp,
5606                                              Label& L_no_such_interface) {
5607   assert_different_registers(recv_klass, intf_klass, method_result, scan_temp);
5608   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5609          "caller must use same register for non-constant itable index as for method");
5610 
5611   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5612   int vtable_base = InstanceKlass::vtable_start_offset() * wordSize;
5613   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5614   int scan_step   = itableOffsetEntry::size() * wordSize;
5615   int vte_size    = vtableEntry::size() * wordSize;
5616   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5617   assert(vte_size == wordSize, "else adjust times_vte_scale");
5618 
5619   movl(scan_temp, Address(recv_klass, InstanceKlass::vtable_length_offset() * wordSize));
5620 
5621   // %%% Could store the aligned, prescaled offset in the klassoop.
5622   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5623   if (HeapWordsPerLong > 1) {
5624     // Round up to align_object_offset boundary
5625     // see code for InstanceKlass::start_of_itable!
5626     round_to(scan_temp, BytesPerLong);
5627   }
5628 
5629   // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5630   assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5631   lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5632 
5633   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5634   //   if (scan->interface() == intf) {
5635   //     result = (klass + scan->offset() + itable_index);
5636   //   }
5637   // }
5638   Label search, found_method;
5639 
5640   for (int peel = 1; peel >= 0; peel--) {
5641     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5642     cmpptr(intf_klass, method_result);
5643 
5644     if (peel) {
5645       jccb(Assembler::equal, found_method);
5646     } else {
5647       jccb(Assembler::notEqual, search);
5648       // (invert the test to fall through to found_method...)
5649     }
5650 
5651     if (!peel)  break;
5652 
5653     bind(search);
5654 
5655     // Check that the previous entry is non-null.  A null entry means that
5656     // the receiver class doesn't implement the interface, and wasn't the
5657     // same as when the caller was compiled.
5658     testptr(method_result, method_result);
5659     jcc(Assembler::zero, L_no_such_interface);
5660     addptr(scan_temp, scan_step);
5661   }
5662 
5663   bind(found_method);
5664 
5665   // Got a hit.
5666   movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5667   movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5668 }
5669 
5670 
5671 // virtual method calling
5672 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5673                                            RegisterOrConstant vtable_index,
5674                                            Register method_result) {
5675   const int base = InstanceKlass::vtable_start_offset() * wordSize;
5676   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5677   Address vtable_entry_addr(recv_klass,
5678                             vtable_index, Address::times_ptr,
5679                             base + vtableEntry::method_offset_in_bytes());
5680   movptr(method_result, vtable_entry_addr);
5681 }
5682 
5683 
5684 void MacroAssembler::check_klass_subtype(Register sub_klass,
5685                            Register super_klass,
5686                            Register temp_reg,
5687                            Label& L_success) {
5688   Label L_failure;
5689   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5690   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5691   bind(L_failure);
5692 }
5693 
5694 
5695 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5696                                                    Register super_klass,
5697                                                    Register temp_reg,
5698                                                    Label* L_success,
5699                                                    Label* L_failure,
5700                                                    Label* L_slow_path,
5701                                         RegisterOrConstant super_check_offset) {
5702   assert_different_registers(sub_klass, super_klass, temp_reg);
5703   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5704   if (super_check_offset.is_register()) {
5705     assert_different_registers(sub_klass, super_klass,
5706                                super_check_offset.as_register());
5707   } else if (must_load_sco) {
5708     assert(temp_reg != noreg, "supply either a temp or a register offset");
5709   }
5710 
5711   Label L_fallthrough;
5712   int label_nulls = 0;
5713   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5714   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5715   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5716   assert(label_nulls <= 1, "at most one NULL in the batch");
5717 
5718   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5719   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5720   Address super_check_offset_addr(super_klass, sco_offset);
5721 
5722   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5723   // range of a jccb.  If this routine grows larger, reconsider at
5724   // least some of these.
5725 #define local_jcc(assembler_cond, label)                                \
5726   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5727   else                             jcc( assembler_cond, label) /*omit semi*/
5728 
5729   // Hacked jmp, which may only be used just before L_fallthrough.
5730 #define final_jmp(label)                                                \
5731   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5732   else                            jmp(label)                /*omit semi*/
5733 
5734   // If the pointers are equal, we are done (e.g., String[] elements).
5735   // This self-check enables sharing of secondary supertype arrays among
5736   // non-primary types such as array-of-interface.  Otherwise, each such
5737   // type would need its own customized SSA.
5738   // We move this check to the front of the fast path because many
5739   // type checks are in fact trivially successful in this manner,
5740   // so we get a nicely predicted branch right at the start of the check.
5741   cmpptr(sub_klass, super_klass);
5742   local_jcc(Assembler::equal, *L_success);
5743 
5744   // Check the supertype display:
5745   if (must_load_sco) {
5746     // Positive movl does right thing on LP64.
5747     movl(temp_reg, super_check_offset_addr);
5748     super_check_offset = RegisterOrConstant(temp_reg);
5749   }
5750   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5751   cmpptr(super_klass, super_check_addr); // load displayed supertype
5752 
5753   // This check has worked decisively for primary supers.
5754   // Secondary supers are sought in the super_cache ('super_cache_addr').
5755   // (Secondary supers are interfaces and very deeply nested subtypes.)
5756   // This works in the same check above because of a tricky aliasing
5757   // between the super_cache and the primary super display elements.
5758   // (The 'super_check_addr' can address either, as the case requires.)
5759   // Note that the cache is updated below if it does not help us find
5760   // what we need immediately.
5761   // So if it was a primary super, we can just fail immediately.
5762   // Otherwise, it's the slow path for us (no success at this point).
5763 
5764   if (super_check_offset.is_register()) {
5765     local_jcc(Assembler::equal, *L_success);
5766     cmpl(super_check_offset.as_register(), sc_offset);
5767     if (L_failure == &L_fallthrough) {
5768       local_jcc(Assembler::equal, *L_slow_path);
5769     } else {
5770       local_jcc(Assembler::notEqual, *L_failure);
5771       final_jmp(*L_slow_path);
5772     }
5773   } else if (super_check_offset.as_constant() == sc_offset) {
5774     // Need a slow path; fast failure is impossible.
5775     if (L_slow_path == &L_fallthrough) {
5776       local_jcc(Assembler::equal, *L_success);
5777     } else {
5778       local_jcc(Assembler::notEqual, *L_slow_path);
5779       final_jmp(*L_success);
5780     }
5781   } else {
5782     // No slow path; it's a fast decision.
5783     if (L_failure == &L_fallthrough) {
5784       local_jcc(Assembler::equal, *L_success);
5785     } else {
5786       local_jcc(Assembler::notEqual, *L_failure);
5787       final_jmp(*L_success);
5788     }
5789   }
5790 
5791   bind(L_fallthrough);
5792 
5793 #undef local_jcc
5794 #undef final_jmp
5795 }
5796 
5797 
5798 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5799                                                    Register super_klass,
5800                                                    Register temp_reg,
5801                                                    Register temp2_reg,
5802                                                    Label* L_success,
5803                                                    Label* L_failure,
5804                                                    bool set_cond_codes) {
5805   assert_different_registers(sub_klass, super_klass, temp_reg);
5806   if (temp2_reg != noreg)
5807     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5808 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5809 
5810   Label L_fallthrough;
5811   int label_nulls = 0;
5812   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5813   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5814   assert(label_nulls <= 1, "at most one NULL in the batch");
5815 
5816   // a couple of useful fields in sub_klass:
5817   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5818   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5819   Address secondary_supers_addr(sub_klass, ss_offset);
5820   Address super_cache_addr(     sub_klass, sc_offset);
5821 
5822   // Do a linear scan of the secondary super-klass chain.
5823   // This code is rarely used, so simplicity is a virtue here.
5824   // The repne_scan instruction uses fixed registers, which we must spill.
5825   // Don't worry too much about pre-existing connections with the input regs.
5826 
5827   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5828   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5829 
5830   // Get super_klass value into rax (even if it was in rdi or rcx).
5831   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5832   if (super_klass != rax || UseCompressedOops) {
5833     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5834     mov(rax, super_klass);
5835   }
5836   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5837   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5838 
5839 #ifndef PRODUCT
5840   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5841   ExternalAddress pst_counter_addr((address) pst_counter);
5842   NOT_LP64(  incrementl(pst_counter_addr) );
5843   LP64_ONLY( lea(rcx, pst_counter_addr) );
5844   LP64_ONLY( incrementl(Address(rcx, 0)) );
5845 #endif //PRODUCT
5846 
5847   // We will consult the secondary-super array.
5848   movptr(rdi, secondary_supers_addr);
5849   // Load the array length.  (Positive movl does right thing on LP64.)
5850   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5851   // Skip to start of data.
5852   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5853 
5854   // Scan RCX words at [RDI] for an occurrence of RAX.
5855   // Set NZ/Z based on last compare.
5856   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5857   // not change flags (only scas instruction which is repeated sets flags).
5858   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5859 
5860     testptr(rax,rax); // Set Z = 0
5861     repne_scan();
5862 
5863   // Unspill the temp. registers:
5864   if (pushed_rdi)  pop(rdi);
5865   if (pushed_rcx)  pop(rcx);
5866   if (pushed_rax)  pop(rax);
5867 
5868   if (set_cond_codes) {
5869     // Special hack for the AD files:  rdi is guaranteed non-zero.
5870     assert(!pushed_rdi, "rdi must be left non-NULL");
5871     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5872   }
5873 
5874   if (L_failure == &L_fallthrough)
5875         jccb(Assembler::notEqual, *L_failure);
5876   else  jcc(Assembler::notEqual, *L_failure);
5877 
5878   // Success.  Cache the super we found and proceed in triumph.
5879   movptr(super_cache_addr, super_klass);
5880 
5881   if (L_success != &L_fallthrough) {
5882     jmp(*L_success);
5883   }
5884 
5885 #undef IS_A_TEMP
5886 
5887   bind(L_fallthrough);
5888 }
5889 
5890 
5891 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5892   if (VM_Version::supports_cmov()) {
5893     cmovl(cc, dst, src);
5894   } else {
5895     Label L;
5896     jccb(negate_condition(cc), L);
5897     movl(dst, src);
5898     bind(L);
5899   }
5900 }
5901 
5902 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5903   if (VM_Version::supports_cmov()) {
5904     cmovl(cc, dst, src);
5905   } else {
5906     Label L;
5907     jccb(negate_condition(cc), L);
5908     movl(dst, src);
5909     bind(L);
5910   }
5911 }
5912 
5913 void MacroAssembler::verify_oop(Register reg, const char* s) {
5914   if (!VerifyOops) return;
5915 
5916   // Pass register number to verify_oop_subroutine
5917   const char* b = NULL;
5918   {
5919     ResourceMark rm;
5920     stringStream ss;
5921     ss.print("verify_oop: %s: %s", reg->name(), s);
5922     b = code_string(ss.as_string());
5923   }
5924   BLOCK_COMMENT("verify_oop {");
5925 #ifdef _LP64
5926   push(rscratch1);                    // save r10, trashed by movptr()
5927 #endif
5928   push(rax);                          // save rax,
5929   push(reg);                          // pass register argument
5930   ExternalAddress buffer((address) b);
5931   // avoid using pushptr, as it modifies scratch registers
5932   // and our contract is not to modify anything
5933   movptr(rax, buffer.addr());
5934   push(rax);
5935   // call indirectly to solve generation ordering problem
5936   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5937   call(rax);
5938   // Caller pops the arguments (oop, message) and restores rax, r10
5939   BLOCK_COMMENT("} verify_oop");
5940 }
5941 
5942 
5943 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5944                                                       Register tmp,
5945                                                       int offset) {
5946   intptr_t value = *delayed_value_addr;
5947   if (value != 0)
5948     return RegisterOrConstant(value + offset);
5949 
5950   // load indirectly to solve generation ordering problem
5951   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5952 
5953 #ifdef ASSERT
5954   { Label L;
5955     testptr(tmp, tmp);
5956     if (WizardMode) {
5957       const char* buf = NULL;
5958       {
5959         ResourceMark rm;
5960         stringStream ss;
5961         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5962         buf = code_string(ss.as_string());
5963       }
5964       jcc(Assembler::notZero, L);
5965       STOP(buf);
5966     } else {
5967       jccb(Assembler::notZero, L);
5968       hlt();
5969     }
5970     bind(L);
5971   }
5972 #endif
5973 
5974   if (offset != 0)
5975     addptr(tmp, offset);
5976 
5977   return RegisterOrConstant(tmp);
5978 }
5979 
5980 
5981 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5982                                          int extra_slot_offset) {
5983   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5984   int stackElementSize = Interpreter::stackElementSize;
5985   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5986 #ifdef ASSERT
5987   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5988   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5989 #endif
5990   Register             scale_reg    = noreg;
5991   Address::ScaleFactor scale_factor = Address::no_scale;
5992   if (arg_slot.is_constant()) {
5993     offset += arg_slot.as_constant() * stackElementSize;
5994   } else {
5995     scale_reg    = arg_slot.as_register();
5996     scale_factor = Address::times(stackElementSize);
5997   }
5998   offset += wordSize;           // return PC is on stack
5999   return Address(rsp, scale_reg, scale_factor, offset);
6000 }
6001 
6002 
6003 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6004   if (!VerifyOops) return;
6005 
6006   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6007   // Pass register number to verify_oop_subroutine
6008   const char* b = NULL;
6009   {
6010     ResourceMark rm;
6011     stringStream ss;
6012     ss.print("verify_oop_addr: %s", s);
6013     b = code_string(ss.as_string());
6014   }
6015 #ifdef _LP64
6016   push(rscratch1);                    // save r10, trashed by movptr()
6017 #endif
6018   push(rax);                          // save rax,
6019   // addr may contain rsp so we will have to adjust it based on the push
6020   // we just did (and on 64 bit we do two pushes)
6021   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6022   // stores rax into addr which is backwards of what was intended.
6023   if (addr.uses(rsp)) {
6024     lea(rax, addr);
6025     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6026   } else {
6027     pushptr(addr);
6028   }
6029 
6030   ExternalAddress buffer((address) b);
6031   // pass msg argument
6032   // avoid using pushptr, as it modifies scratch registers
6033   // and our contract is not to modify anything
6034   movptr(rax, buffer.addr());
6035   push(rax);
6036 
6037   // call indirectly to solve generation ordering problem
6038   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6039   call(rax);
6040   // Caller pops the arguments (addr, message) and restores rax, r10.
6041 }
6042 
6043 void MacroAssembler::verify_tlab() {
6044 #ifdef ASSERT
6045   if (UseTLAB && VerifyOops) {
6046     Label next, ok;
6047     Register t1 = rsi;
6048     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6049 
6050     push(t1);
6051     NOT_LP64(push(thread_reg));
6052     NOT_LP64(get_thread(thread_reg));
6053 
6054     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6055     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6056     jcc(Assembler::aboveEqual, next);
6057     STOP("assert(top >= start)");
6058     should_not_reach_here();
6059 
6060     bind(next);
6061     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6062     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6063     jcc(Assembler::aboveEqual, ok);
6064     STOP("assert(top <= end)");
6065     should_not_reach_here();
6066 
6067     bind(ok);
6068     NOT_LP64(pop(thread_reg));
6069     pop(t1);
6070   }
6071 #endif
6072 }
6073 
6074 class ControlWord {
6075  public:
6076   int32_t _value;
6077 
6078   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6079   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6080   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6081   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6082   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6083   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6084   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6085   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6086 
6087   void print() const {
6088     // rounding control
6089     const char* rc;
6090     switch (rounding_control()) {
6091       case 0: rc = "round near"; break;
6092       case 1: rc = "round down"; break;
6093       case 2: rc = "round up  "; break;
6094       case 3: rc = "chop      "; break;
6095     };
6096     // precision control
6097     const char* pc;
6098     switch (precision_control()) {
6099       case 0: pc = "24 bits "; break;
6100       case 1: pc = "reserved"; break;
6101       case 2: pc = "53 bits "; break;
6102       case 3: pc = "64 bits "; break;
6103     };
6104     // flags
6105     char f[9];
6106     f[0] = ' ';
6107     f[1] = ' ';
6108     f[2] = (precision   ()) ? 'P' : 'p';
6109     f[3] = (underflow   ()) ? 'U' : 'u';
6110     f[4] = (overflow    ()) ? 'O' : 'o';
6111     f[5] = (zero_divide ()) ? 'Z' : 'z';
6112     f[6] = (denormalized()) ? 'D' : 'd';
6113     f[7] = (invalid     ()) ? 'I' : 'i';
6114     f[8] = '\x0';
6115     // output
6116     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6117   }
6118 
6119 };
6120 
6121 class StatusWord {
6122  public:
6123   int32_t _value;
6124 
6125   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6126   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6127   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6128   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6129   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6130   int  top() const                     { return  (_value >> 11) & 7      ; }
6131   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6132   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6133   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6134   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6135   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6136   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6137   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6138   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6139 
6140   void print() const {
6141     // condition codes
6142     char c[5];
6143     c[0] = (C3()) ? '3' : '-';
6144     c[1] = (C2()) ? '2' : '-';
6145     c[2] = (C1()) ? '1' : '-';
6146     c[3] = (C0()) ? '0' : '-';
6147     c[4] = '\x0';
6148     // flags
6149     char f[9];
6150     f[0] = (error_status()) ? 'E' : '-';
6151     f[1] = (stack_fault ()) ? 'S' : '-';
6152     f[2] = (precision   ()) ? 'P' : '-';
6153     f[3] = (underflow   ()) ? 'U' : '-';
6154     f[4] = (overflow    ()) ? 'O' : '-';
6155     f[5] = (zero_divide ()) ? 'Z' : '-';
6156     f[6] = (denormalized()) ? 'D' : '-';
6157     f[7] = (invalid     ()) ? 'I' : '-';
6158     f[8] = '\x0';
6159     // output
6160     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6161   }
6162 
6163 };
6164 
6165 class TagWord {
6166  public:
6167   int32_t _value;
6168 
6169   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6170 
6171   void print() const {
6172     printf("%04x", _value & 0xFFFF);
6173   }
6174 
6175 };
6176 
6177 class FPU_Register {
6178  public:
6179   int32_t _m0;
6180   int32_t _m1;
6181   int16_t _ex;
6182 
6183   bool is_indefinite() const           {
6184     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6185   }
6186 
6187   void print() const {
6188     char  sign = (_ex < 0) ? '-' : '+';
6189     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6190     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6191   };
6192 
6193 };
6194 
6195 class FPU_State {
6196  public:
6197   enum {
6198     register_size       = 10,
6199     number_of_registers =  8,
6200     register_mask       =  7
6201   };
6202 
6203   ControlWord  _control_word;
6204   StatusWord   _status_word;
6205   TagWord      _tag_word;
6206   int32_t      _error_offset;
6207   int32_t      _error_selector;
6208   int32_t      _data_offset;
6209   int32_t      _data_selector;
6210   int8_t       _register[register_size * number_of_registers];
6211 
6212   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6213   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6214 
6215   const char* tag_as_string(int tag) const {
6216     switch (tag) {
6217       case 0: return "valid";
6218       case 1: return "zero";
6219       case 2: return "special";
6220       case 3: return "empty";
6221     }
6222     ShouldNotReachHere();
6223     return NULL;
6224   }
6225 
6226   void print() const {
6227     // print computation registers
6228     { int t = _status_word.top();
6229       for (int i = 0; i < number_of_registers; i++) {
6230         int j = (i - t) & register_mask;
6231         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6232         st(j)->print();
6233         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6234       }
6235     }
6236     printf("\n");
6237     // print control registers
6238     printf("ctrl = "); _control_word.print(); printf("\n");
6239     printf("stat = "); _status_word .print(); printf("\n");
6240     printf("tags = "); _tag_word    .print(); printf("\n");
6241   }
6242 
6243 };
6244 
6245 class Flag_Register {
6246  public:
6247   int32_t _value;
6248 
6249   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6250   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6251   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6252   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6253   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6254   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6255   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6256 
6257   void print() const {
6258     // flags
6259     char f[8];
6260     f[0] = (overflow       ()) ? 'O' : '-';
6261     f[1] = (direction      ()) ? 'D' : '-';
6262     f[2] = (sign           ()) ? 'S' : '-';
6263     f[3] = (zero           ()) ? 'Z' : '-';
6264     f[4] = (auxiliary_carry()) ? 'A' : '-';
6265     f[5] = (parity         ()) ? 'P' : '-';
6266     f[6] = (carry          ()) ? 'C' : '-';
6267     f[7] = '\x0';
6268     // output
6269     printf("%08x  flags = %s", _value, f);
6270   }
6271 
6272 };
6273 
6274 class IU_Register {
6275  public:
6276   int32_t _value;
6277 
6278   void print() const {
6279     printf("%08x  %11d", _value, _value);
6280   }
6281 
6282 };
6283 
6284 class IU_State {
6285  public:
6286   Flag_Register _eflags;
6287   IU_Register   _rdi;
6288   IU_Register   _rsi;
6289   IU_Register   _rbp;
6290   IU_Register   _rsp;
6291   IU_Register   _rbx;
6292   IU_Register   _rdx;
6293   IU_Register   _rcx;
6294   IU_Register   _rax;
6295 
6296   void print() const {
6297     // computation registers
6298     printf("rax,  = "); _rax.print(); printf("\n");
6299     printf("rbx,  = "); _rbx.print(); printf("\n");
6300     printf("rcx  = "); _rcx.print(); printf("\n");
6301     printf("rdx  = "); _rdx.print(); printf("\n");
6302     printf("rdi  = "); _rdi.print(); printf("\n");
6303     printf("rsi  = "); _rsi.print(); printf("\n");
6304     printf("rbp,  = "); _rbp.print(); printf("\n");
6305     printf("rsp  = "); _rsp.print(); printf("\n");
6306     printf("\n");
6307     // control registers
6308     printf("flgs = "); _eflags.print(); printf("\n");
6309   }
6310 };
6311 
6312 
6313 class CPU_State {
6314  public:
6315   FPU_State _fpu_state;
6316   IU_State  _iu_state;
6317 
6318   void print() const {
6319     printf("--------------------------------------------------\n");
6320     _iu_state .print();
6321     printf("\n");
6322     _fpu_state.print();
6323     printf("--------------------------------------------------\n");
6324   }
6325 
6326 };
6327 
6328 
6329 static void _print_CPU_state(CPU_State* state) {
6330   state->print();
6331 };
6332 
6333 
6334 void MacroAssembler::print_CPU_state() {
6335   push_CPU_state();
6336   push(rsp);                // pass CPU state
6337   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6338   addptr(rsp, wordSize);       // discard argument
6339   pop_CPU_state();
6340 }
6341 
6342 
6343 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6344   static int counter = 0;
6345   FPU_State* fs = &state->_fpu_state;
6346   counter++;
6347   // For leaf calls, only verify that the top few elements remain empty.
6348   // We only need 1 empty at the top for C2 code.
6349   if( stack_depth < 0 ) {
6350     if( fs->tag_for_st(7) != 3 ) {
6351       printf("FPR7 not empty\n");
6352       state->print();
6353       assert(false, "error");
6354       return false;
6355     }
6356     return true;                // All other stack states do not matter
6357   }
6358 
6359   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6360          "bad FPU control word");
6361 
6362   // compute stack depth
6363   int i = 0;
6364   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6365   int d = i;
6366   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6367   // verify findings
6368   if (i != FPU_State::number_of_registers) {
6369     // stack not contiguous
6370     printf("%s: stack not contiguous at ST%d\n", s, i);
6371     state->print();
6372     assert(false, "error");
6373     return false;
6374   }
6375   // check if computed stack depth corresponds to expected stack depth
6376   if (stack_depth < 0) {
6377     // expected stack depth is -stack_depth or less
6378     if (d > -stack_depth) {
6379       // too many elements on the stack
6380       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6381       state->print();
6382       assert(false, "error");
6383       return false;
6384     }
6385   } else {
6386     // expected stack depth is stack_depth
6387     if (d != stack_depth) {
6388       // wrong stack depth
6389       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6390       state->print();
6391       assert(false, "error");
6392       return false;
6393     }
6394   }
6395   // everything is cool
6396   return true;
6397 }
6398 
6399 
6400 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6401   if (!VerifyFPU) return;
6402   push_CPU_state();
6403   push(rsp);                // pass CPU state
6404   ExternalAddress msg((address) s);
6405   // pass message string s
6406   pushptr(msg.addr());
6407   push(stack_depth);        // pass stack depth
6408   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6409   addptr(rsp, 3 * wordSize);   // discard arguments
6410   // check for error
6411   { Label L;
6412     testl(rax, rax);
6413     jcc(Assembler::notZero, L);
6414     int3();                  // break if error condition
6415     bind(L);
6416   }
6417   pop_CPU_state();
6418 }
6419 
6420 void MacroAssembler::restore_cpu_control_state_after_jni() {
6421   // Either restore the MXCSR register after returning from the JNI Call
6422   // or verify that it wasn't changed (with -Xcheck:jni flag).
6423   if (VM_Version::supports_sse()) {
6424     if (RestoreMXCSROnJNICalls) {
6425       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6426     } else if (CheckJNICalls) {
6427       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6428     }
6429   }
6430   if (VM_Version::supports_avx()) {
6431     // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6432     vzeroupper();
6433   }
6434 
6435 #ifndef _LP64
6436   // Either restore the x87 floating pointer control word after returning
6437   // from the JNI call or verify that it wasn't changed.
6438   if (CheckJNICalls) {
6439     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6440   }
6441 #endif // _LP64
6442 }
6443 
6444 
6445 void MacroAssembler::load_klass(Register dst, Register src) {
6446 #ifdef _LP64
6447   if (UseCompressedClassPointers) {
6448     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6449     decode_klass_not_null(dst);
6450   } else
6451 #endif
6452     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6453 }
6454 
6455 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6456   load_klass(dst, src);
6457   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6458 }
6459 
6460 void MacroAssembler::store_klass(Register dst, Register src) {
6461 #ifdef _LP64
6462   if (UseCompressedClassPointers) {
6463     encode_klass_not_null(src);
6464     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6465   } else
6466 #endif
6467     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6468 }
6469 
6470 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6471 #ifdef _LP64
6472   // FIXME: Must change all places where we try to load the klass.
6473   if (UseCompressedOops) {
6474     movl(dst, src);
6475     decode_heap_oop(dst);
6476   } else
6477 #endif
6478     movptr(dst, src);
6479 }
6480 
6481 // Doesn't do verfication, generates fixed size code
6482 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6483 #ifdef _LP64
6484   if (UseCompressedOops) {
6485     movl(dst, src);
6486     decode_heap_oop_not_null(dst);
6487   } else
6488 #endif
6489     movptr(dst, src);
6490 }
6491 
6492 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6493 #ifdef _LP64
6494   if (UseCompressedOops) {
6495     assert(!dst.uses(src), "not enough registers");
6496     encode_heap_oop(src);
6497     movl(dst, src);
6498   } else
6499 #endif
6500     movptr(dst, src);
6501 }
6502 
6503 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6504   assert_different_registers(src1, tmp);
6505 #ifdef _LP64
6506   if (UseCompressedOops) {
6507     bool did_push = false;
6508     if (tmp == noreg) {
6509       tmp = rax;
6510       push(tmp);
6511       did_push = true;
6512       assert(!src2.uses(rsp), "can't push");
6513     }
6514     load_heap_oop(tmp, src2);
6515     cmpptr(src1, tmp);
6516     if (did_push)  pop(tmp);
6517   } else
6518 #endif
6519     cmpptr(src1, src2);
6520 }
6521 
6522 // Used for storing NULLs.
6523 void MacroAssembler::store_heap_oop_null(Address dst) {
6524 #ifdef _LP64
6525   if (UseCompressedOops) {
6526     movl(dst, (int32_t)NULL_WORD);
6527   } else {
6528     movslq(dst, (int32_t)NULL_WORD);
6529   }
6530 #else
6531   movl(dst, (int32_t)NULL_WORD);
6532 #endif
6533 }
6534 
6535 #ifdef _LP64
6536 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6537   if (UseCompressedClassPointers) {
6538     // Store to klass gap in destination
6539     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6540   }
6541 }
6542 
6543 #ifdef ASSERT
6544 void MacroAssembler::verify_heapbase(const char* msg) {
6545   assert (UseCompressedOops, "should be compressed");
6546   assert (Universe::heap() != NULL, "java heap should be initialized");
6547   if (CheckCompressedOops) {
6548     Label ok;
6549     push(rscratch1); // cmpptr trashes rscratch1
6550     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6551     jcc(Assembler::equal, ok);
6552     STOP(msg);
6553     bind(ok);
6554     pop(rscratch1);
6555   }
6556 }
6557 #endif
6558 
6559 // Algorithm must match oop.inline.hpp encode_heap_oop.
6560 void MacroAssembler::encode_heap_oop(Register r) {
6561 #ifdef ASSERT
6562   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6563 #endif
6564   verify_oop(r, "broken oop in encode_heap_oop");
6565   if (Universe::narrow_oop_base() == NULL) {
6566     if (Universe::narrow_oop_shift() != 0) {
6567       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6568       shrq(r, LogMinObjAlignmentInBytes);
6569     }
6570     return;
6571   }
6572   testq(r, r);
6573   cmovq(Assembler::equal, r, r12_heapbase);
6574   subq(r, r12_heapbase);
6575   shrq(r, LogMinObjAlignmentInBytes);
6576 }
6577 
6578 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6579 #ifdef ASSERT
6580   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6581   if (CheckCompressedOops) {
6582     Label ok;
6583     testq(r, r);
6584     jcc(Assembler::notEqual, ok);
6585     STOP("null oop passed to encode_heap_oop_not_null");
6586     bind(ok);
6587   }
6588 #endif
6589   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6590   if (Universe::narrow_oop_base() != NULL) {
6591     subq(r, r12_heapbase);
6592   }
6593   if (Universe::narrow_oop_shift() != 0) {
6594     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6595     shrq(r, LogMinObjAlignmentInBytes);
6596   }
6597 }
6598 
6599 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6600 #ifdef ASSERT
6601   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6602   if (CheckCompressedOops) {
6603     Label ok;
6604     testq(src, src);
6605     jcc(Assembler::notEqual, ok);
6606     STOP("null oop passed to encode_heap_oop_not_null2");
6607     bind(ok);
6608   }
6609 #endif
6610   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6611   if (dst != src) {
6612     movq(dst, src);
6613   }
6614   if (Universe::narrow_oop_base() != NULL) {
6615     subq(dst, r12_heapbase);
6616   }
6617   if (Universe::narrow_oop_shift() != 0) {
6618     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6619     shrq(dst, LogMinObjAlignmentInBytes);
6620   }
6621 }
6622 
6623 void  MacroAssembler::decode_heap_oop(Register r) {
6624 #ifdef ASSERT
6625   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6626 #endif
6627   if (Universe::narrow_oop_base() == NULL) {
6628     if (Universe::narrow_oop_shift() != 0) {
6629       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6630       shlq(r, LogMinObjAlignmentInBytes);
6631     }
6632   } else {
6633     Label done;
6634     shlq(r, LogMinObjAlignmentInBytes);
6635     jccb(Assembler::equal, done);
6636     addq(r, r12_heapbase);
6637     bind(done);
6638   }
6639   verify_oop(r, "broken oop in decode_heap_oop");
6640 }
6641 
6642 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6643   // Note: it will change flags
6644   assert (UseCompressedOops, "should only be used for compressed headers");
6645   assert (Universe::heap() != NULL, "java heap should be initialized");
6646   // Cannot assert, unverified entry point counts instructions (see .ad file)
6647   // vtableStubs also counts instructions in pd_code_size_limit.
6648   // Also do not verify_oop as this is called by verify_oop.
6649   if (Universe::narrow_oop_shift() != 0) {
6650     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6651     shlq(r, LogMinObjAlignmentInBytes);
6652     if (Universe::narrow_oop_base() != NULL) {
6653       addq(r, r12_heapbase);
6654     }
6655   } else {
6656     assert (Universe::narrow_oop_base() == NULL, "sanity");
6657   }
6658 }
6659 
6660 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6661   // Note: it will change flags
6662   assert (UseCompressedOops, "should only be used for compressed headers");
6663   assert (Universe::heap() != NULL, "java heap should be initialized");
6664   // Cannot assert, unverified entry point counts instructions (see .ad file)
6665   // vtableStubs also counts instructions in pd_code_size_limit.
6666   // Also do not verify_oop as this is called by verify_oop.
6667   if (Universe::narrow_oop_shift() != 0) {
6668     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6669     if (LogMinObjAlignmentInBytes == Address::times_8) {
6670       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6671     } else {
6672       if (dst != src) {
6673         movq(dst, src);
6674       }
6675       shlq(dst, LogMinObjAlignmentInBytes);
6676       if (Universe::narrow_oop_base() != NULL) {
6677         addq(dst, r12_heapbase);
6678       }
6679     }
6680   } else {
6681     assert (Universe::narrow_oop_base() == NULL, "sanity");
6682     if (dst != src) {
6683       movq(dst, src);
6684     }
6685   }
6686 }
6687 
6688 void MacroAssembler::encode_klass_not_null(Register r) {
6689   if (Universe::narrow_klass_base() != NULL) {
6690     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6691     assert(r != r12_heapbase, "Encoding a klass in r12");
6692     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6693     subq(r, r12_heapbase);
6694   }
6695   if (Universe::narrow_klass_shift() != 0) {
6696     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6697     shrq(r, LogKlassAlignmentInBytes);
6698   }
6699   if (Universe::narrow_klass_base() != NULL) {
6700     reinit_heapbase();
6701   }
6702 }
6703 
6704 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6705   if (dst == src) {
6706     encode_klass_not_null(src);
6707   } else {
6708     if (Universe::narrow_klass_base() != NULL) {
6709       mov64(dst, (int64_t)Universe::narrow_klass_base());
6710       negq(dst);
6711       addq(dst, src);
6712     } else {
6713       movptr(dst, src);
6714     }
6715     if (Universe::narrow_klass_shift() != 0) {
6716       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6717       shrq(dst, LogKlassAlignmentInBytes);
6718     }
6719   }
6720 }
6721 
6722 // Function instr_size_for_decode_klass_not_null() counts the instructions
6723 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6724 // when (Universe::heap() != NULL).  Hence, if the instructions they
6725 // generate change, then this method needs to be updated.
6726 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6727   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6728   if (Universe::narrow_klass_base() != NULL) {
6729     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6730     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6731   } else {
6732     // longest load decode klass function, mov64, leaq
6733     return 16;
6734   }
6735 }
6736 
6737 // !!! If the instructions that get generated here change then function
6738 // instr_size_for_decode_klass_not_null() needs to get updated.
6739 void  MacroAssembler::decode_klass_not_null(Register r) {
6740   // Note: it will change flags
6741   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6742   assert(r != r12_heapbase, "Decoding a klass in r12");
6743   // Cannot assert, unverified entry point counts instructions (see .ad file)
6744   // vtableStubs also counts instructions in pd_code_size_limit.
6745   // Also do not verify_oop as this is called by verify_oop.
6746   if (Universe::narrow_klass_shift() != 0) {
6747     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6748     shlq(r, LogKlassAlignmentInBytes);
6749   }
6750   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6751   if (Universe::narrow_klass_base() != NULL) {
6752     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6753     addq(r, r12_heapbase);
6754     reinit_heapbase();
6755   }
6756 }
6757 
6758 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6759   // Note: it will change flags
6760   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6761   if (dst == src) {
6762     decode_klass_not_null(dst);
6763   } else {
6764     // Cannot assert, unverified entry point counts instructions (see .ad file)
6765     // vtableStubs also counts instructions in pd_code_size_limit.
6766     // Also do not verify_oop as this is called by verify_oop.
6767     mov64(dst, (int64_t)Universe::narrow_klass_base());
6768     if (Universe::narrow_klass_shift() != 0) {
6769       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6770       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6771       leaq(dst, Address(dst, src, Address::times_8, 0));
6772     } else {
6773       addq(dst, src);
6774     }
6775   }
6776 }
6777 
6778 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6779   assert (UseCompressedOops, "should only be used for compressed headers");
6780   assert (Universe::heap() != NULL, "java heap should be initialized");
6781   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6782   int oop_index = oop_recorder()->find_index(obj);
6783   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6784   mov_narrow_oop(dst, oop_index, rspec);
6785 }
6786 
6787 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6788   assert (UseCompressedOops, "should only be used for compressed headers");
6789   assert (Universe::heap() != NULL, "java heap should be initialized");
6790   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6791   int oop_index = oop_recorder()->find_index(obj);
6792   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6793   mov_narrow_oop(dst, oop_index, rspec);
6794 }
6795 
6796 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6797   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6798   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6799   int klass_index = oop_recorder()->find_index(k);
6800   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6801   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6802 }
6803 
6804 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6805   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6806   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6807   int klass_index = oop_recorder()->find_index(k);
6808   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6809   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6810 }
6811 
6812 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6813   assert (UseCompressedOops, "should only be used for compressed headers");
6814   assert (Universe::heap() != NULL, "java heap should be initialized");
6815   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6816   int oop_index = oop_recorder()->find_index(obj);
6817   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6818   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6819 }
6820 
6821 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6822   assert (UseCompressedOops, "should only be used for compressed headers");
6823   assert (Universe::heap() != NULL, "java heap should be initialized");
6824   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6825   int oop_index = oop_recorder()->find_index(obj);
6826   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6827   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6828 }
6829 
6830 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6831   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6832   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6833   int klass_index = oop_recorder()->find_index(k);
6834   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6835   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6836 }
6837 
6838 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6839   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6840   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6841   int klass_index = oop_recorder()->find_index(k);
6842   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6843   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6844 }
6845 
6846 void MacroAssembler::reinit_heapbase() {
6847   if (UseCompressedOops || UseCompressedClassPointers) {
6848     if (Universe::heap() != NULL) {
6849       if (Universe::narrow_oop_base() == NULL) {
6850         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6851       } else {
6852         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6853       }
6854     } else {
6855       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6856     }
6857   }
6858 }
6859 
6860 #endif // _LP64
6861 
6862 
6863 // C2 compiled method's prolog code.
6864 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6865 
6866   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6867   // NativeJump::patch_verified_entry will be able to patch out the entry
6868   // code safely. The push to verify stack depth is ok at 5 bytes,
6869   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6870   // stack bang then we must use the 6 byte frame allocation even if
6871   // we have no frame. :-(
6872   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6873 
6874   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6875   // Remove word for return addr
6876   framesize -= wordSize;
6877   stack_bang_size -= wordSize;
6878 
6879   // Calls to C2R adapters often do not accept exceptional returns.
6880   // We require that their callers must bang for them.  But be careful, because
6881   // some VM calls (such as call site linkage) can use several kilobytes of
6882   // stack.  But the stack safety zone should account for that.
6883   // See bugs 4446381, 4468289, 4497237.
6884   if (stack_bang_size > 0) {
6885     generate_stack_overflow_check(stack_bang_size);
6886 
6887     // We always push rbp, so that on return to interpreter rbp, will be
6888     // restored correctly and we can correct the stack.
6889     push(rbp);
6890     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6891     if (PreserveFramePointer) {
6892       mov(rbp, rsp);
6893     }
6894     // Remove word for ebp
6895     framesize -= wordSize;
6896 
6897     // Create frame
6898     if (framesize) {
6899       subptr(rsp, framesize);
6900     }
6901   } else {
6902     // Create frame (force generation of a 4 byte immediate value)
6903     subptr_imm32(rsp, framesize);
6904 
6905     // Save RBP register now.
6906     framesize -= wordSize;
6907     movptr(Address(rsp, framesize), rbp);
6908     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6909     if (PreserveFramePointer) {
6910       movptr(rbp, rsp);
6911       if (framesize > 0) {
6912         addptr(rbp, framesize);
6913       }
6914     }
6915   }
6916 
6917   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6918     framesize -= wordSize;
6919     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6920   }
6921 
6922 #ifndef _LP64
6923   // If method sets FPU control word do it now
6924   if (fp_mode_24b) {
6925     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6926   }
6927   if (UseSSE >= 2 && VerifyFPU) {
6928     verify_FPU(0, "FPU stack must be clean on entry");
6929   }
6930 #endif
6931 
6932 #ifdef ASSERT
6933   if (VerifyStackAtCalls) {
6934     Label L;
6935     push(rax);
6936     mov(rax, rsp);
6937     andptr(rax, StackAlignmentInBytes-1);
6938     cmpptr(rax, StackAlignmentInBytes-wordSize);
6939     pop(rax);
6940     jcc(Assembler::equal, L);
6941     STOP("Stack is not properly aligned!");
6942     bind(L);
6943   }
6944 #endif
6945 
6946 }
6947 
6948 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp) {
6949   // cnt - number of qwords (8-byte words).
6950   // base - start address, qword aligned.
6951   assert(base==rdi, "base register must be edi for rep stos");
6952   assert(tmp==rax,   "tmp register must be eax for rep stos");
6953   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6954 
6955   xorptr(tmp, tmp);
6956   if (UseFastStosb) {
6957     shlptr(cnt,3); // convert to number of bytes
6958     rep_stosb();
6959   } else {
6960     NOT_LP64(shlptr(cnt,1);) // convert to number of dwords for 32-bit VM
6961     rep_stos();
6962   }
6963 }
6964 
6965 // IndexOf for constant substrings with size >= 8 chars
6966 // which don't need to be loaded through stack.
6967 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6968                                       Register cnt1, Register cnt2,
6969                                       int int_cnt2,  Register result,
6970                                       XMMRegister vec, Register tmp) {
6971   ShortBranchVerifier sbv(this);
6972   assert(UseSSE42Intrinsics, "SSE4.2 is required");
6973 
6974   // This method uses pcmpestri instruction with bound registers
6975   //   inputs:
6976   //     xmm - substring
6977   //     rax - substring length (elements count)
6978   //     mem - scanned string
6979   //     rdx - string length (elements count)
6980   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6981   //   outputs:
6982   //     rcx - matched index in string
6983   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6984 
6985   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6986         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6987         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6988 
6989   // Note, inline_string_indexOf() generates checks:
6990   // if (substr.count > string.count) return -1;
6991   // if (substr.count == 0) return 0;
6992   assert(int_cnt2 >= 8, "this code isused only for cnt2 >= 8 chars");
6993 
6994   // Load substring.
6995   movdqu(vec, Address(str2, 0));
6996   movl(cnt2, int_cnt2);
6997   movptr(result, str1); // string addr
6998 
6999   if (int_cnt2 > 8) {
7000     jmpb(SCAN_TO_SUBSTR);
7001 
7002     // Reload substr for rescan, this code
7003     // is executed only for large substrings (> 8 chars)
7004     bind(RELOAD_SUBSTR);
7005     movdqu(vec, Address(str2, 0));
7006     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7007 
7008     bind(RELOAD_STR);
7009     // We came here after the beginning of the substring was
7010     // matched but the rest of it was not so we need to search
7011     // again. Start from the next element after the previous match.
7012 
7013     // cnt2 is number of substring reminding elements and
7014     // cnt1 is number of string reminding elements when cmp failed.
7015     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7016     subl(cnt1, cnt2);
7017     addl(cnt1, int_cnt2);
7018     movl(cnt2, int_cnt2); // Now restore cnt2
7019 
7020     decrementl(cnt1);     // Shift to next element
7021     cmpl(cnt1, cnt2);
7022     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7023 
7024     addptr(result, 2);
7025 
7026   } // (int_cnt2 > 8)
7027 
7028   // Scan string for start of substr in 16-byte vectors
7029   bind(SCAN_TO_SUBSTR);
7030   pcmpestri(vec, Address(result, 0), 0x0d);
7031   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7032   subl(cnt1, 8);
7033   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7034   cmpl(cnt1, cnt2);
7035   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7036   addptr(result, 16);
7037   jmpb(SCAN_TO_SUBSTR);
7038 
7039   // Found a potential substr
7040   bind(FOUND_CANDIDATE);
7041   // Matched whole vector if first element matched (tmp(rcx) == 0).
7042   if (int_cnt2 == 8) {
7043     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7044   } else { // int_cnt2 > 8
7045     jccb(Assembler::overflow, FOUND_SUBSTR);
7046   }
7047   // After pcmpestri tmp(rcx) contains matched element index
7048   // Compute start addr of substr
7049   lea(result, Address(result, tmp, Address::times_2));
7050 
7051   // Make sure string is still long enough
7052   subl(cnt1, tmp);
7053   cmpl(cnt1, cnt2);
7054   if (int_cnt2 == 8) {
7055     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7056   } else { // int_cnt2 > 8
7057     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7058   }
7059   // Left less then substring.
7060 
7061   bind(RET_NOT_FOUND);
7062   movl(result, -1);
7063   jmpb(EXIT);
7064 
7065   if (int_cnt2 > 8) {
7066     // This code is optimized for the case when whole substring
7067     // is matched if its head is matched.
7068     bind(MATCH_SUBSTR_HEAD);
7069     pcmpestri(vec, Address(result, 0), 0x0d);
7070     // Reload only string if does not match
7071     jccb(Assembler::noOverflow, RELOAD_STR); // OF == 0
7072 
7073     Label CONT_SCAN_SUBSTR;
7074     // Compare the rest of substring (> 8 chars).
7075     bind(FOUND_SUBSTR);
7076     // First 8 chars are already matched.
7077     negptr(cnt2);
7078     addptr(cnt2, 8);
7079 
7080     bind(SCAN_SUBSTR);
7081     subl(cnt1, 8);
7082     cmpl(cnt2, -8); // Do not read beyond substring
7083     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7084     // Back-up strings to avoid reading beyond substring:
7085     // cnt1 = cnt1 - cnt2 + 8
7086     addl(cnt1, cnt2); // cnt2 is negative
7087     addl(cnt1, 8);
7088     movl(cnt2, 8); negptr(cnt2);
7089     bind(CONT_SCAN_SUBSTR);
7090     if (int_cnt2 < (int)G) {
7091       movdqu(vec, Address(str2, cnt2, Address::times_2, int_cnt2*2));
7092       pcmpestri(vec, Address(result, cnt2, Address::times_2, int_cnt2*2), 0x0d);
7093     } else {
7094       // calculate index in register to avoid integer overflow (int_cnt2*2)
7095       movl(tmp, int_cnt2);
7096       addptr(tmp, cnt2);
7097       movdqu(vec, Address(str2, tmp, Address::times_2, 0));
7098       pcmpestri(vec, Address(result, tmp, Address::times_2, 0), 0x0d);
7099     }
7100     // Need to reload strings pointers if not matched whole vector
7101     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7102     addptr(cnt2, 8);
7103     jcc(Assembler::negative, SCAN_SUBSTR);
7104     // Fall through if found full substring
7105 
7106   } // (int_cnt2 > 8)
7107 
7108   bind(RET_FOUND);
7109   // Found result if we matched full small substring.
7110   // Compute substr offset
7111   subptr(result, str1);
7112   shrl(result, 1); // index
7113   bind(EXIT);
7114 
7115 } // string_indexofC8
7116 
7117 // Small strings are loaded through stack if they cross page boundary.
7118 void MacroAssembler::string_indexof(Register str1, Register str2,
7119                                     Register cnt1, Register cnt2,
7120                                     int int_cnt2,  Register result,
7121                                     XMMRegister vec, Register tmp) {
7122   ShortBranchVerifier sbv(this);
7123   assert(UseSSE42Intrinsics, "SSE4.2 is required");
7124   //
7125   // int_cnt2 is length of small (< 8 chars) constant substring
7126   // or (-1) for non constant substring in which case its length
7127   // is in cnt2 register.
7128   //
7129   // Note, inline_string_indexOf() generates checks:
7130   // if (substr.count > string.count) return -1;
7131   // if (substr.count == 0) return 0;
7132   //
7133   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < 8), "should be != 0");
7134 
7135   // This method uses pcmpestri instruction with bound registers
7136   //   inputs:
7137   //     xmm - substring
7138   //     rax - substring length (elements count)
7139   //     mem - scanned string
7140   //     rdx - string length (elements count)
7141   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7142   //   outputs:
7143   //     rcx - matched index in string
7144   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7145 
7146   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7147         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7148         FOUND_CANDIDATE;
7149 
7150   { //========================================================
7151     // We don't know where these strings are located
7152     // and we can't read beyond them. Load them through stack.
7153     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7154 
7155     movptr(tmp, rsp); // save old SP
7156 
7157     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7158       if (int_cnt2 == 1) {  // One char
7159         load_unsigned_short(result, Address(str2, 0));
7160         movdl(vec, result); // move 32 bits
7161       } else if (int_cnt2 == 2) { // Two chars
7162         movdl(vec, Address(str2, 0)); // move 32 bits
7163       } else if (int_cnt2 == 4) { // Four chars
7164         movq(vec, Address(str2, 0));  // move 64 bits
7165       } else { // cnt2 = { 3, 5, 6, 7 }
7166         // Array header size is 12 bytes in 32-bit VM
7167         // + 6 bytes for 3 chars == 18 bytes,
7168         // enough space to load vec and shift.
7169         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7170         movdqu(vec, Address(str2, (int_cnt2*2)-16));
7171         psrldq(vec, 16-(int_cnt2*2));
7172       }
7173     } else { // not constant substring
7174       cmpl(cnt2, 8);
7175       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7176 
7177       // We can read beyond string if srt+16 does not cross page boundary
7178       // since heaps are aligned and mapped by pages.
7179       assert(os::vm_page_size() < (int)G, "default page should be small");
7180       movl(result, str2); // We need only low 32 bits
7181       andl(result, (os::vm_page_size()-1));
7182       cmpl(result, (os::vm_page_size()-16));
7183       jccb(Assembler::belowEqual, CHECK_STR);
7184 
7185       // Move small strings to stack to allow load 16 bytes into vec.
7186       subptr(rsp, 16);
7187       int stk_offset = wordSize-2;
7188       push(cnt2);
7189 
7190       bind(COPY_SUBSTR);
7191       load_unsigned_short(result, Address(str2, cnt2, Address::times_2, -2));
7192       movw(Address(rsp, cnt2, Address::times_2, stk_offset), result);
7193       decrement(cnt2);
7194       jccb(Assembler::notZero, COPY_SUBSTR);
7195 
7196       pop(cnt2);
7197       movptr(str2, rsp);  // New substring address
7198     } // non constant
7199 
7200     bind(CHECK_STR);
7201     cmpl(cnt1, 8);
7202     jccb(Assembler::aboveEqual, BIG_STRINGS);
7203 
7204     // Check cross page boundary.
7205     movl(result, str1); // We need only low 32 bits
7206     andl(result, (os::vm_page_size()-1));
7207     cmpl(result, (os::vm_page_size()-16));
7208     jccb(Assembler::belowEqual, BIG_STRINGS);
7209 
7210     subptr(rsp, 16);
7211     int stk_offset = -2;
7212     if (int_cnt2 < 0) { // not constant
7213       push(cnt2);
7214       stk_offset += wordSize;
7215     }
7216     movl(cnt2, cnt1);
7217 
7218     bind(COPY_STR);
7219     load_unsigned_short(result, Address(str1, cnt2, Address::times_2, -2));
7220     movw(Address(rsp, cnt2, Address::times_2, stk_offset), result);
7221     decrement(cnt2);
7222     jccb(Assembler::notZero, COPY_STR);
7223 
7224     if (int_cnt2 < 0) { // not constant
7225       pop(cnt2);
7226     }
7227     movptr(str1, rsp);  // New string address
7228 
7229     bind(BIG_STRINGS);
7230     // Load substring.
7231     if (int_cnt2 < 0) { // -1
7232       movdqu(vec, Address(str2, 0));
7233       push(cnt2);       // substr count
7234       push(str2);       // substr addr
7235       push(str1);       // string addr
7236     } else {
7237       // Small (< 8 chars) constant substrings are loaded already.
7238       movl(cnt2, int_cnt2);
7239     }
7240     push(tmp);  // original SP
7241 
7242   } // Finished loading
7243 
7244   //========================================================
7245   // Start search
7246   //
7247 
7248   movptr(result, str1); // string addr
7249 
7250   if (int_cnt2  < 0) {  // Only for non constant substring
7251     jmpb(SCAN_TO_SUBSTR);
7252 
7253     // SP saved at sp+0
7254     // String saved at sp+1*wordSize
7255     // Substr saved at sp+2*wordSize
7256     // Substr count saved at sp+3*wordSize
7257 
7258     // Reload substr for rescan, this code
7259     // is executed only for large substrings (> 8 chars)
7260     bind(RELOAD_SUBSTR);
7261     movptr(str2, Address(rsp, 2*wordSize));
7262     movl(cnt2, Address(rsp, 3*wordSize));
7263     movdqu(vec, Address(str2, 0));
7264     // We came here after the beginning of the substring was
7265     // matched but the rest of it was not so we need to search
7266     // again. Start from the next element after the previous match.
7267     subptr(str1, result); // Restore counter
7268     shrl(str1, 1);
7269     addl(cnt1, str1);
7270     decrementl(cnt1);   // Shift to next element
7271     cmpl(cnt1, cnt2);
7272     jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7273 
7274     addptr(result, 2);
7275   } // non constant
7276 
7277   // Scan string for start of substr in 16-byte vectors
7278   bind(SCAN_TO_SUBSTR);
7279   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7280   pcmpestri(vec, Address(result, 0), 0x0d);
7281   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7282   subl(cnt1, 8);
7283   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7284   cmpl(cnt1, cnt2);
7285   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7286   addptr(result, 16);
7287 
7288   bind(ADJUST_STR);
7289   cmpl(cnt1, 8); // Do not read beyond string
7290   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7291   // Back-up string to avoid reading beyond string.
7292   lea(result, Address(result, cnt1, Address::times_2, -16));
7293   movl(cnt1, 8);
7294   jmpb(SCAN_TO_SUBSTR);
7295 
7296   // Found a potential substr
7297   bind(FOUND_CANDIDATE);
7298   // After pcmpestri tmp(rcx) contains matched element index
7299 
7300   // Make sure string is still long enough
7301   subl(cnt1, tmp);
7302   cmpl(cnt1, cnt2);
7303   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7304   // Left less then substring.
7305 
7306   bind(RET_NOT_FOUND);
7307   movl(result, -1);
7308   jmpb(CLEANUP);
7309 
7310   bind(FOUND_SUBSTR);
7311   // Compute start addr of substr
7312   lea(result, Address(result, tmp, Address::times_2));
7313 
7314   if (int_cnt2 > 0) { // Constant substring
7315     // Repeat search for small substring (< 8 chars)
7316     // from new point without reloading substring.
7317     // Have to check that we don't read beyond string.
7318     cmpl(tmp, 8-int_cnt2);
7319     jccb(Assembler::greater, ADJUST_STR);
7320     // Fall through if matched whole substring.
7321   } else { // non constant
7322     assert(int_cnt2 == -1, "should be != 0");
7323 
7324     addl(tmp, cnt2);
7325     // Found result if we matched whole substring.
7326     cmpl(tmp, 8);
7327     jccb(Assembler::lessEqual, RET_FOUND);
7328 
7329     // Repeat search for small substring (<= 8 chars)
7330     // from new point 'str1' without reloading substring.
7331     cmpl(cnt2, 8);
7332     // Have to check that we don't read beyond string.
7333     jccb(Assembler::lessEqual, ADJUST_STR);
7334 
7335     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7336     // Compare the rest of substring (> 8 chars).
7337     movptr(str1, result);
7338 
7339     cmpl(tmp, cnt2);
7340     // First 8 chars are already matched.
7341     jccb(Assembler::equal, CHECK_NEXT);
7342 
7343     bind(SCAN_SUBSTR);
7344     pcmpestri(vec, Address(str1, 0), 0x0d);
7345     // Need to reload strings pointers if not matched whole vector
7346     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7347 
7348     bind(CHECK_NEXT);
7349     subl(cnt2, 8);
7350     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7351     addptr(str1, 16);
7352     addptr(str2, 16);
7353     subl(cnt1, 8);
7354     cmpl(cnt2, 8); // Do not read beyond substring
7355     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7356     // Back-up strings to avoid reading beyond substring.
7357     lea(str2, Address(str2, cnt2, Address::times_2, -16));
7358     lea(str1, Address(str1, cnt2, Address::times_2, -16));
7359     subl(cnt1, cnt2);
7360     movl(cnt2, 8);
7361     addl(cnt1, 8);
7362     bind(CONT_SCAN_SUBSTR);
7363     movdqu(vec, Address(str2, 0));
7364     jmpb(SCAN_SUBSTR);
7365 
7366     bind(RET_FOUND_LONG);
7367     movptr(str1, Address(rsp, wordSize));
7368   } // non constant
7369 
7370   bind(RET_FOUND);
7371   // Compute substr offset
7372   subptr(result, str1);
7373   shrl(result, 1); // index
7374 
7375   bind(CLEANUP);
7376   pop(rsp); // restore SP
7377 
7378 } // string_indexof
7379 
7380 // Compare strings.
7381 void MacroAssembler::string_compare(Register str1, Register str2,
7382                                     Register cnt1, Register cnt2, Register result,
7383                                     XMMRegister vec1) {
7384   ShortBranchVerifier sbv(this);
7385   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7386 
7387   // Compute the minimum of the string lengths and the
7388   // difference of the string lengths (stack).
7389   // Do the conditional move stuff
7390   movl(result, cnt1);
7391   subl(cnt1, cnt2);
7392   push(cnt1);
7393   cmov32(Assembler::lessEqual, cnt2, result);
7394 
7395   // Is the minimum length zero?
7396   testl(cnt2, cnt2);
7397   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7398 
7399   // Compare first characters
7400   load_unsigned_short(result, Address(str1, 0));
7401   load_unsigned_short(cnt1, Address(str2, 0));
7402   subl(result, cnt1);
7403   jcc(Assembler::notZero,  POP_LABEL);
7404   cmpl(cnt2, 1);
7405   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7406 
7407   // Check if the strings start at the same location.
7408   cmpptr(str1, str2);
7409   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7410 
7411   Address::ScaleFactor scale = Address::times_2;
7412   int stride = 8;
7413 
7414   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7415     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7416     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7417     Label COMPARE_TAIL_LONG;
7418     int pcmpmask = 0x19;
7419 
7420     // Setup to compare 16-chars (32-bytes) vectors,
7421     // start from first character again because it has aligned address.
7422     int stride2 = 16;
7423     int adr_stride  = stride  << scale;
7424 
7425     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7426     // rax and rdx are used by pcmpestri as elements counters
7427     movl(result, cnt2);
7428     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7429     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7430 
7431     // fast path : compare first 2 8-char vectors.
7432     bind(COMPARE_16_CHARS);
7433     movdqu(vec1, Address(str1, 0));
7434     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7435     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7436 
7437     movdqu(vec1, Address(str1, adr_stride));
7438     pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7439     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7440     addl(cnt1, stride);
7441 
7442     // Compare the characters at index in cnt1
7443     bind(COMPARE_INDEX_CHAR); //cnt1 has the offset of the mismatching character
7444     load_unsigned_short(result, Address(str1, cnt1, scale));
7445     load_unsigned_short(cnt2, Address(str2, cnt1, scale));
7446     subl(result, cnt2);
7447     jmp(POP_LABEL);
7448 
7449     // Setup the registers to start vector comparison loop
7450     bind(COMPARE_WIDE_VECTORS);
7451     lea(str1, Address(str1, result, scale));
7452     lea(str2, Address(str2, result, scale));
7453     subl(result, stride2);
7454     subl(cnt2, stride2);
7455     jccb(Assembler::zero, COMPARE_WIDE_TAIL);
7456     negptr(result);
7457 
7458     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7459     bind(COMPARE_WIDE_VECTORS_LOOP);
7460     vmovdqu(vec1, Address(str1, result, scale));
7461     vpxor(vec1, Address(str2, result, scale));
7462     vptest(vec1, vec1);
7463     jccb(Assembler::notZero, VECTOR_NOT_EQUAL);
7464     addptr(result, stride2);
7465     subl(cnt2, stride2);
7466     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7467     // clean upper bits of YMM registers
7468     vpxor(vec1, vec1);
7469 
7470     // compare wide vectors tail
7471     bind(COMPARE_WIDE_TAIL);
7472     testptr(result, result);
7473     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7474 
7475     movl(result, stride2);
7476     movl(cnt2, result);
7477     negptr(result);
7478     jmpb(COMPARE_WIDE_VECTORS_LOOP);
7479 
7480     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7481     bind(VECTOR_NOT_EQUAL);
7482     // clean upper bits of YMM registers
7483     vpxor(vec1, vec1);
7484     lea(str1, Address(str1, result, scale));
7485     lea(str2, Address(str2, result, scale));
7486     jmp(COMPARE_16_CHARS);
7487 
7488     // Compare tail chars, length between 1 to 15 chars
7489     bind(COMPARE_TAIL_LONG);
7490     movl(cnt2, result);
7491     cmpl(cnt2, stride);
7492     jccb(Assembler::less, COMPARE_SMALL_STR);
7493 
7494     movdqu(vec1, Address(str1, 0));
7495     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7496     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7497     subptr(cnt2, stride);
7498     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7499     lea(str1, Address(str1, result, scale));
7500     lea(str2, Address(str2, result, scale));
7501     negptr(cnt2);
7502     jmpb(WHILE_HEAD_LABEL);
7503 
7504     bind(COMPARE_SMALL_STR);
7505   } else if (UseSSE42Intrinsics) {
7506     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7507     int pcmpmask = 0x19;
7508     // Setup to compare 8-char (16-byte) vectors,
7509     // start from first character again because it has aligned address.
7510     movl(result, cnt2);
7511     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7512     jccb(Assembler::zero, COMPARE_TAIL);
7513 
7514     lea(str1, Address(str1, result, scale));
7515     lea(str2, Address(str2, result, scale));
7516     negptr(result);
7517 
7518     // pcmpestri
7519     //   inputs:
7520     //     vec1- substring
7521     //     rax - negative string length (elements count)
7522     //     mem - scanned string
7523     //     rdx - string length (elements count)
7524     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7525     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7526     //   outputs:
7527     //     rcx - first mismatched element index
7528     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7529 
7530     bind(COMPARE_WIDE_VECTORS);
7531     movdqu(vec1, Address(str1, result, scale));
7532     pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7533     // After pcmpestri cnt1(rcx) contains mismatched element index
7534 
7535     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7536     addptr(result, stride);
7537     subptr(cnt2, stride);
7538     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7539 
7540     // compare wide vectors tail
7541     testptr(result, result);
7542     jccb(Assembler::zero, LENGTH_DIFF_LABEL);
7543 
7544     movl(cnt2, stride);
7545     movl(result, stride);
7546     negptr(result);
7547     movdqu(vec1, Address(str1, result, scale));
7548     pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7549     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7550 
7551     // Mismatched characters in the vectors
7552     bind(VECTOR_NOT_EQUAL);
7553     addptr(cnt1, result);
7554     load_unsigned_short(result, Address(str1, cnt1, scale));
7555     load_unsigned_short(cnt2, Address(str2, cnt1, scale));
7556     subl(result, cnt2);
7557     jmpb(POP_LABEL);
7558 
7559     bind(COMPARE_TAIL); // limit is zero
7560     movl(cnt2, result);
7561     // Fallthru to tail compare
7562   }
7563   // Shift str2 and str1 to the end of the arrays, negate min
7564   lea(str1, Address(str1, cnt2, scale));
7565   lea(str2, Address(str2, cnt2, scale));
7566   decrementl(cnt2);  // first character was compared already
7567   negptr(cnt2);
7568 
7569   // Compare the rest of the elements
7570   bind(WHILE_HEAD_LABEL);
7571   load_unsigned_short(result, Address(str1, cnt2, scale, 0));
7572   load_unsigned_short(cnt1, Address(str2, cnt2, scale, 0));
7573   subl(result, cnt1);
7574   jccb(Assembler::notZero, POP_LABEL);
7575   increment(cnt2);
7576   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7577 
7578   // Strings are equal up to min length.  Return the length difference.
7579   bind(LENGTH_DIFF_LABEL);
7580   pop(result);
7581   jmpb(DONE_LABEL);
7582 
7583   // Discard the stored length difference
7584   bind(POP_LABEL);
7585   pop(cnt1);
7586 
7587   // That's it
7588   bind(DONE_LABEL);
7589 }
7590 
7591 // Compare char[] arrays aligned to 4 bytes or substrings.
7592 void MacroAssembler::char_arrays_equals(bool is_array_equ, Register ary1, Register ary2,
7593                                         Register limit, Register result, Register chr,
7594                                         XMMRegister vec1, XMMRegister vec2) {
7595   ShortBranchVerifier sbv(this);
7596   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR;
7597 
7598   int length_offset  = arrayOopDesc::length_offset_in_bytes();
7599   int base_offset    = arrayOopDesc::base_offset_in_bytes(T_CHAR);
7600 
7601   // Check the input args
7602   cmpptr(ary1, ary2);
7603   jcc(Assembler::equal, TRUE_LABEL);
7604 
7605   if (is_array_equ) {
7606     // Need additional checks for arrays_equals.
7607     testptr(ary1, ary1);
7608     jcc(Assembler::zero, FALSE_LABEL);
7609     testptr(ary2, ary2);
7610     jcc(Assembler::zero, FALSE_LABEL);
7611 
7612     // Check the lengths
7613     movl(limit, Address(ary1, length_offset));
7614     cmpl(limit, Address(ary2, length_offset));
7615     jcc(Assembler::notEqual, FALSE_LABEL);
7616   }
7617 
7618   // count == 0
7619   testl(limit, limit);
7620   jcc(Assembler::zero, TRUE_LABEL);
7621 
7622   if (is_array_equ) {
7623     // Load array address
7624     lea(ary1, Address(ary1, base_offset));
7625     lea(ary2, Address(ary2, base_offset));
7626   }
7627 
7628   shll(limit, 1);      // byte count != 0
7629   movl(result, limit); // copy
7630 
7631   if (UseAVX >= 2) {
7632     // With AVX2, use 32-byte vector compare
7633     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7634 
7635     // Compare 32-byte vectors
7636     andl(result, 0x0000001e);  //   tail count (in bytes)
7637     andl(limit, 0xffffffe0);   // vector count (in bytes)
7638     jccb(Assembler::zero, COMPARE_TAIL);
7639 
7640     lea(ary1, Address(ary1, limit, Address::times_1));
7641     lea(ary2, Address(ary2, limit, Address::times_1));
7642     negptr(limit);
7643 
7644     bind(COMPARE_WIDE_VECTORS);
7645     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
7646     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
7647     vpxor(vec1, vec2);
7648 
7649     vptest(vec1, vec1);
7650     jccb(Assembler::notZero, FALSE_LABEL);
7651     addptr(limit, 32);
7652     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7653 
7654     testl(result, result);
7655     jccb(Assembler::zero, TRUE_LABEL);
7656 
7657     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
7658     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
7659     vpxor(vec1, vec2);
7660 
7661     vptest(vec1, vec1);
7662     jccb(Assembler::notZero, FALSE_LABEL);
7663     jmpb(TRUE_LABEL);
7664 
7665     bind(COMPARE_TAIL); // limit is zero
7666     movl(limit, result);
7667     // Fallthru to tail compare
7668   } else if (UseSSE42Intrinsics) {
7669     // With SSE4.2, use double quad vector compare
7670     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
7671 
7672     // Compare 16-byte vectors
7673     andl(result, 0x0000000e);  //   tail count (in bytes)
7674     andl(limit, 0xfffffff0);   // vector count (in bytes)
7675     jccb(Assembler::zero, COMPARE_TAIL);
7676 
7677     lea(ary1, Address(ary1, limit, Address::times_1));
7678     lea(ary2, Address(ary2, limit, Address::times_1));
7679     negptr(limit);
7680 
7681     bind(COMPARE_WIDE_VECTORS);
7682     movdqu(vec1, Address(ary1, limit, Address::times_1));
7683     movdqu(vec2, Address(ary2, limit, Address::times_1));
7684     pxor(vec1, vec2);
7685 
7686     ptest(vec1, vec1);
7687     jccb(Assembler::notZero, FALSE_LABEL);
7688     addptr(limit, 16);
7689     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
7690 
7691     testl(result, result);
7692     jccb(Assembler::zero, TRUE_LABEL);
7693 
7694     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
7695     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
7696     pxor(vec1, vec2);
7697 
7698     ptest(vec1, vec1);
7699     jccb(Assembler::notZero, FALSE_LABEL);
7700     jmpb(TRUE_LABEL);
7701 
7702     bind(COMPARE_TAIL); // limit is zero
7703     movl(limit, result);
7704     // Fallthru to tail compare
7705   }
7706 
7707   // Compare 4-byte vectors
7708   andl(limit, 0xfffffffc); // vector count (in bytes)
7709   jccb(Assembler::zero, COMPARE_CHAR);
7710 
7711   lea(ary1, Address(ary1, limit, Address::times_1));
7712   lea(ary2, Address(ary2, limit, Address::times_1));
7713   negptr(limit);
7714 
7715   bind(COMPARE_VECTORS);
7716   movl(chr, Address(ary1, limit, Address::times_1));
7717   cmpl(chr, Address(ary2, limit, Address::times_1));
7718   jccb(Assembler::notEqual, FALSE_LABEL);
7719   addptr(limit, 4);
7720   jcc(Assembler::notZero, COMPARE_VECTORS);
7721 
7722   // Compare trailing char (final 2 bytes), if any
7723   bind(COMPARE_CHAR);
7724   testl(result, 0x2);   // tail  char
7725   jccb(Assembler::zero, TRUE_LABEL);
7726   load_unsigned_short(chr, Address(ary1, 0));
7727   load_unsigned_short(limit, Address(ary2, 0));
7728   cmpl(chr, limit);
7729   jccb(Assembler::notEqual, FALSE_LABEL);
7730 
7731   bind(TRUE_LABEL);
7732   movl(result, 1);   // return true
7733   jmpb(DONE);
7734 
7735   bind(FALSE_LABEL);
7736   xorl(result, result); // return false
7737 
7738   // That's it
7739   bind(DONE);
7740   if (UseAVX >= 2) {
7741     // clean upper bits of YMM registers
7742     vpxor(vec1, vec1);
7743     vpxor(vec2, vec2);
7744   }
7745 }
7746 
7747 void MacroAssembler::generate_fill(BasicType t, bool aligned,
7748                                    Register to, Register value, Register count,
7749                                    Register rtmp, XMMRegister xtmp) {
7750   ShortBranchVerifier sbv(this);
7751   assert_different_registers(to, value, count, rtmp);
7752   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
7753   Label L_fill_2_bytes, L_fill_4_bytes;
7754 
7755   int shift = -1;
7756   switch (t) {
7757     case T_BYTE:
7758       shift = 2;
7759       break;
7760     case T_SHORT:
7761       shift = 1;
7762       break;
7763     case T_INT:
7764       shift = 0;
7765       break;
7766     default: ShouldNotReachHere();
7767   }
7768 
7769   if (t == T_BYTE) {
7770     andl(value, 0xff);
7771     movl(rtmp, value);
7772     shll(rtmp, 8);
7773     orl(value, rtmp);
7774   }
7775   if (t == T_SHORT) {
7776     andl(value, 0xffff);
7777   }
7778   if (t == T_BYTE || t == T_SHORT) {
7779     movl(rtmp, value);
7780     shll(rtmp, 16);
7781     orl(value, rtmp);
7782   }
7783 
7784   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
7785   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
7786   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
7787     // align source address at 4 bytes address boundary
7788     if (t == T_BYTE) {
7789       // One byte misalignment happens only for byte arrays
7790       testptr(to, 1);
7791       jccb(Assembler::zero, L_skip_align1);
7792       movb(Address(to, 0), value);
7793       increment(to);
7794       decrement(count);
7795       BIND(L_skip_align1);
7796     }
7797     // Two bytes misalignment happens only for byte and short (char) arrays
7798     testptr(to, 2);
7799     jccb(Assembler::zero, L_skip_align2);
7800     movw(Address(to, 0), value);
7801     addptr(to, 2);
7802     subl(count, 1<<(shift-1));
7803     BIND(L_skip_align2);
7804   }
7805   if (UseSSE < 2) {
7806     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7807     // Fill 32-byte chunks
7808     subl(count, 8 << shift);
7809     jcc(Assembler::less, L_check_fill_8_bytes);
7810     align(16);
7811 
7812     BIND(L_fill_32_bytes_loop);
7813 
7814     for (int i = 0; i < 32; i += 4) {
7815       movl(Address(to, i), value);
7816     }
7817 
7818     addptr(to, 32);
7819     subl(count, 8 << shift);
7820     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7821     BIND(L_check_fill_8_bytes);
7822     addl(count, 8 << shift);
7823     jccb(Assembler::zero, L_exit);
7824     jmpb(L_fill_8_bytes);
7825 
7826     //
7827     // length is too short, just fill qwords
7828     //
7829     BIND(L_fill_8_bytes_loop);
7830     movl(Address(to, 0), value);
7831     movl(Address(to, 4), value);
7832     addptr(to, 8);
7833     BIND(L_fill_8_bytes);
7834     subl(count, 1 << (shift + 1));
7835     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7836     // fall through to fill 4 bytes
7837   } else {
7838     Label L_fill_32_bytes;
7839     if (!UseUnalignedLoadStores) {
7840       // align to 8 bytes, we know we are 4 byte aligned to start
7841       testptr(to, 4);
7842       jccb(Assembler::zero, L_fill_32_bytes);
7843       movl(Address(to, 0), value);
7844       addptr(to, 4);
7845       subl(count, 1<<shift);
7846     }
7847     BIND(L_fill_32_bytes);
7848     {
7849       assert( UseSSE >= 2, "supported cpu only" );
7850       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
7851       if (UseAVX > 2) {
7852         movl(rtmp, 0xffff);
7853         kmovwl(k1, rtmp);
7854       }
7855       movdl(xtmp, value);
7856       if (UseAVX > 2 && UseUnalignedLoadStores) {
7857         // Fill 64-byte chunks
7858         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7859         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
7860 
7861         subl(count, 16 << shift);
7862         jcc(Assembler::less, L_check_fill_32_bytes);
7863         align(16);
7864 
7865         BIND(L_fill_64_bytes_loop);
7866         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
7867         addptr(to, 64);
7868         subl(count, 16 << shift);
7869         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7870 
7871         BIND(L_check_fill_32_bytes);
7872         addl(count, 8 << shift);
7873         jccb(Assembler::less, L_check_fill_8_bytes);
7874         vmovdqu(Address(to, 0), xtmp);
7875         addptr(to, 32);
7876         subl(count, 8 << shift);
7877 
7878         BIND(L_check_fill_8_bytes);
7879       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
7880         // Fill 64-byte chunks
7881         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
7882         vpbroadcastd(xtmp, xtmp);
7883 
7884         subl(count, 16 << shift);
7885         jcc(Assembler::less, L_check_fill_32_bytes);
7886         align(16);
7887 
7888         BIND(L_fill_64_bytes_loop);
7889         vmovdqu(Address(to, 0), xtmp);
7890         vmovdqu(Address(to, 32), xtmp);
7891         addptr(to, 64);
7892         subl(count, 16 << shift);
7893         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
7894 
7895         BIND(L_check_fill_32_bytes);
7896         addl(count, 8 << shift);
7897         jccb(Assembler::less, L_check_fill_8_bytes);
7898         vmovdqu(Address(to, 0), xtmp);
7899         addptr(to, 32);
7900         subl(count, 8 << shift);
7901 
7902         BIND(L_check_fill_8_bytes);
7903         // clean upper bits of YMM registers
7904         movdl(xtmp, value);
7905         pshufd(xtmp, xtmp, 0);
7906       } else {
7907         // Fill 32-byte chunks
7908         pshufd(xtmp, xtmp, 0);
7909 
7910         subl(count, 8 << shift);
7911         jcc(Assembler::less, L_check_fill_8_bytes);
7912         align(16);
7913 
7914         BIND(L_fill_32_bytes_loop);
7915 
7916         if (UseUnalignedLoadStores) {
7917           movdqu(Address(to, 0), xtmp);
7918           movdqu(Address(to, 16), xtmp);
7919         } else {
7920           movq(Address(to, 0), xtmp);
7921           movq(Address(to, 8), xtmp);
7922           movq(Address(to, 16), xtmp);
7923           movq(Address(to, 24), xtmp);
7924         }
7925 
7926         addptr(to, 32);
7927         subl(count, 8 << shift);
7928         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
7929 
7930         BIND(L_check_fill_8_bytes);
7931       }
7932       addl(count, 8 << shift);
7933       jccb(Assembler::zero, L_exit);
7934       jmpb(L_fill_8_bytes);
7935 
7936       //
7937       // length is too short, just fill qwords
7938       //
7939       BIND(L_fill_8_bytes_loop);
7940       movq(Address(to, 0), xtmp);
7941       addptr(to, 8);
7942       BIND(L_fill_8_bytes);
7943       subl(count, 1 << (shift + 1));
7944       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
7945     }
7946   }
7947   // fill trailing 4 bytes
7948   BIND(L_fill_4_bytes);
7949   testl(count, 1<<shift);
7950   jccb(Assembler::zero, L_fill_2_bytes);
7951   movl(Address(to, 0), value);
7952   if (t == T_BYTE || t == T_SHORT) {
7953     addptr(to, 4);
7954     BIND(L_fill_2_bytes);
7955     // fill trailing 2 bytes
7956     testl(count, 1<<(shift-1));
7957     jccb(Assembler::zero, L_fill_byte);
7958     movw(Address(to, 0), value);
7959     if (t == T_BYTE) {
7960       addptr(to, 2);
7961       BIND(L_fill_byte);
7962       // fill trailing byte
7963       testl(count, 1);
7964       jccb(Assembler::zero, L_exit);
7965       movb(Address(to, 0), value);
7966     } else {
7967       BIND(L_fill_byte);
7968     }
7969   } else {
7970     BIND(L_fill_2_bytes);
7971   }
7972   BIND(L_exit);
7973 }
7974 
7975 // encode char[] to byte[] in ISO_8859_1
7976 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
7977                                       XMMRegister tmp1Reg, XMMRegister tmp2Reg,
7978                                       XMMRegister tmp3Reg, XMMRegister tmp4Reg,
7979                                       Register tmp5, Register result) {
7980   // rsi: src
7981   // rdi: dst
7982   // rdx: len
7983   // rcx: tmp5
7984   // rax: result
7985   ShortBranchVerifier sbv(this);
7986   assert_different_registers(src, dst, len, tmp5, result);
7987   Label L_done, L_copy_1_char, L_copy_1_char_exit;
7988 
7989   // set result
7990   xorl(result, result);
7991   // check for zero length
7992   testl(len, len);
7993   jcc(Assembler::zero, L_done);
7994   movl(result, len);
7995 
7996   // Setup pointers
7997   lea(src, Address(src, len, Address::times_2)); // char[]
7998   lea(dst, Address(dst, len, Address::times_1)); // byte[]
7999   negptr(len);
8000 
8001   if (UseSSE42Intrinsics || UseAVX >= 2) {
8002     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8003     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8004 
8005     if (UseAVX >= 2) {
8006       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8007       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8008       movdl(tmp1Reg, tmp5);
8009       vpbroadcastd(tmp1Reg, tmp1Reg);
8010       jmpb(L_chars_32_check);
8011 
8012       bind(L_copy_32_chars);
8013       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8014       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8015       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8016       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8017       jccb(Assembler::notZero, L_copy_32_chars_exit);
8018       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8019       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8020       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8021 
8022       bind(L_chars_32_check);
8023       addptr(len, 32);
8024       jccb(Assembler::lessEqual, L_copy_32_chars);
8025 
8026       bind(L_copy_32_chars_exit);
8027       subptr(len, 16);
8028       jccb(Assembler::greater, L_copy_16_chars_exit);
8029 
8030     } else if (UseSSE42Intrinsics) {
8031       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8032       movdl(tmp1Reg, tmp5);
8033       pshufd(tmp1Reg, tmp1Reg, 0);
8034       jmpb(L_chars_16_check);
8035     }
8036 
8037     bind(L_copy_16_chars);
8038     if (UseAVX >= 2) {
8039       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8040       vptest(tmp2Reg, tmp1Reg);
8041       jccb(Assembler::notZero, L_copy_16_chars_exit);
8042       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8043       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8044     } else {
8045       if (UseAVX > 0) {
8046         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8047         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8048         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8049       } else {
8050         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8051         por(tmp2Reg, tmp3Reg);
8052         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8053         por(tmp2Reg, tmp4Reg);
8054       }
8055       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8056       jccb(Assembler::notZero, L_copy_16_chars_exit);
8057       packuswb(tmp3Reg, tmp4Reg);
8058     }
8059     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8060 
8061     bind(L_chars_16_check);
8062     addptr(len, 16);
8063     jccb(Assembler::lessEqual, L_copy_16_chars);
8064 
8065     bind(L_copy_16_chars_exit);
8066     if (UseAVX >= 2) {
8067       // clean upper bits of YMM registers
8068       vpxor(tmp2Reg, tmp2Reg);
8069       vpxor(tmp3Reg, tmp3Reg);
8070       vpxor(tmp4Reg, tmp4Reg);
8071       movdl(tmp1Reg, tmp5);
8072       pshufd(tmp1Reg, tmp1Reg, 0);
8073     }
8074     subptr(len, 8);
8075     jccb(Assembler::greater, L_copy_8_chars_exit);
8076 
8077     bind(L_copy_8_chars);
8078     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8079     ptest(tmp3Reg, tmp1Reg);
8080     jccb(Assembler::notZero, L_copy_8_chars_exit);
8081     packuswb(tmp3Reg, tmp1Reg);
8082     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8083     addptr(len, 8);
8084     jccb(Assembler::lessEqual, L_copy_8_chars);
8085 
8086     bind(L_copy_8_chars_exit);
8087     subptr(len, 8);
8088     jccb(Assembler::zero, L_done);
8089   }
8090 
8091   bind(L_copy_1_char);
8092   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8093   testl(tmp5, 0xff00);      // check if Unicode char
8094   jccb(Assembler::notZero, L_copy_1_char_exit);
8095   movb(Address(dst, len, Address::times_1, 0), tmp5);
8096   addptr(len, 1);
8097   jccb(Assembler::less, L_copy_1_char);
8098 
8099   bind(L_copy_1_char_exit);
8100   addptr(result, len); // len is negative count of not processed elements
8101   bind(L_done);
8102 }
8103 
8104 #ifdef _LP64
8105 /**
8106  * Helper for multiply_to_len().
8107  */
8108 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8109   addq(dest_lo, src1);
8110   adcq(dest_hi, 0);
8111   addq(dest_lo, src2);
8112   adcq(dest_hi, 0);
8113 }
8114 
8115 /**
8116  * Multiply 64 bit by 64 bit first loop.
8117  */
8118 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8119                                            Register y, Register y_idx, Register z,
8120                                            Register carry, Register product,
8121                                            Register idx, Register kdx) {
8122   //
8123   //  jlong carry, x[], y[], z[];
8124   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8125   //    huge_128 product = y[idx] * x[xstart] + carry;
8126   //    z[kdx] = (jlong)product;
8127   //    carry  = (jlong)(product >>> 64);
8128   //  }
8129   //  z[xstart] = carry;
8130   //
8131 
8132   Label L_first_loop, L_first_loop_exit;
8133   Label L_one_x, L_one_y, L_multiply;
8134 
8135   decrementl(xstart);
8136   jcc(Assembler::negative, L_one_x);
8137 
8138   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8139   rorq(x_xstart, 32); // convert big-endian to little-endian
8140 
8141   bind(L_first_loop);
8142   decrementl(idx);
8143   jcc(Assembler::negative, L_first_loop_exit);
8144   decrementl(idx);
8145   jcc(Assembler::negative, L_one_y);
8146   movq(y_idx, Address(y, idx, Address::times_4,  0));
8147   rorq(y_idx, 32); // convert big-endian to little-endian
8148   bind(L_multiply);
8149   movq(product, x_xstart);
8150   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8151   addq(product, carry);
8152   adcq(rdx, 0);
8153   subl(kdx, 2);
8154   movl(Address(z, kdx, Address::times_4,  4), product);
8155   shrq(product, 32);
8156   movl(Address(z, kdx, Address::times_4,  0), product);
8157   movq(carry, rdx);
8158   jmp(L_first_loop);
8159 
8160   bind(L_one_y);
8161   movl(y_idx, Address(y,  0));
8162   jmp(L_multiply);
8163 
8164   bind(L_one_x);
8165   movl(x_xstart, Address(x,  0));
8166   jmp(L_first_loop);
8167 
8168   bind(L_first_loop_exit);
8169 }
8170 
8171 /**
8172  * Multiply 64 bit by 64 bit and add 128 bit.
8173  */
8174 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8175                                             Register yz_idx, Register idx,
8176                                             Register carry, Register product, int offset) {
8177   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8178   //     z[kdx] = (jlong)product;
8179 
8180   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8181   rorq(yz_idx, 32); // convert big-endian to little-endian
8182   movq(product, x_xstart);
8183   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8184   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8185   rorq(yz_idx, 32); // convert big-endian to little-endian
8186 
8187   add2_with_carry(rdx, product, carry, yz_idx);
8188 
8189   movl(Address(z, idx, Address::times_4,  offset+4), product);
8190   shrq(product, 32);
8191   movl(Address(z, idx, Address::times_4,  offset), product);
8192 
8193 }
8194 
8195 /**
8196  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8197  */
8198 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8199                                              Register yz_idx, Register idx, Register jdx,
8200                                              Register carry, Register product,
8201                                              Register carry2) {
8202   //   jlong carry, x[], y[], z[];
8203   //   int kdx = ystart+1;
8204   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8205   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8206   //     z[kdx+idx+1] = (jlong)product;
8207   //     jlong carry2  = (jlong)(product >>> 64);
8208   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8209   //     z[kdx+idx] = (jlong)product;
8210   //     carry  = (jlong)(product >>> 64);
8211   //   }
8212   //   idx += 2;
8213   //   if (idx > 0) {
8214   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8215   //     z[kdx+idx] = (jlong)product;
8216   //     carry  = (jlong)(product >>> 64);
8217   //   }
8218   //
8219 
8220   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8221 
8222   movl(jdx, idx);
8223   andl(jdx, 0xFFFFFFFC);
8224   shrl(jdx, 2);
8225 
8226   bind(L_third_loop);
8227   subl(jdx, 1);
8228   jcc(Assembler::negative, L_third_loop_exit);
8229   subl(idx, 4);
8230 
8231   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8232   movq(carry2, rdx);
8233 
8234   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8235   movq(carry, rdx);
8236   jmp(L_third_loop);
8237 
8238   bind (L_third_loop_exit);
8239 
8240   andl (idx, 0x3);
8241   jcc(Assembler::zero, L_post_third_loop_done);
8242 
8243   Label L_check_1;
8244   subl(idx, 2);
8245   jcc(Assembler::negative, L_check_1);
8246 
8247   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8248   movq(carry, rdx);
8249 
8250   bind (L_check_1);
8251   addl (idx, 0x2);
8252   andl (idx, 0x1);
8253   subl(idx, 1);
8254   jcc(Assembler::negative, L_post_third_loop_done);
8255 
8256   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8257   movq(product, x_xstart);
8258   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8259   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8260 
8261   add2_with_carry(rdx, product, yz_idx, carry);
8262 
8263   movl(Address(z, idx, Address::times_4,  0), product);
8264   shrq(product, 32);
8265 
8266   shlq(rdx, 32);
8267   orq(product, rdx);
8268   movq(carry, product);
8269 
8270   bind(L_post_third_loop_done);
8271 }
8272 
8273 /**
8274  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8275  *
8276  */
8277 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8278                                                   Register carry, Register carry2,
8279                                                   Register idx, Register jdx,
8280                                                   Register yz_idx1, Register yz_idx2,
8281                                                   Register tmp, Register tmp3, Register tmp4) {
8282   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8283 
8284   //   jlong carry, x[], y[], z[];
8285   //   int kdx = ystart+1;
8286   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8287   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8288   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8289   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8290   //     carry  = (jlong)(tmp4 >>> 64);
8291   //     z[kdx+idx+1] = (jlong)tmp3;
8292   //     z[kdx+idx] = (jlong)tmp4;
8293   //   }
8294   //   idx += 2;
8295   //   if (idx > 0) {
8296   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8297   //     z[kdx+idx] = (jlong)yz_idx1;
8298   //     carry  = (jlong)(yz_idx1 >>> 64);
8299   //   }
8300   //
8301 
8302   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8303 
8304   movl(jdx, idx);
8305   andl(jdx, 0xFFFFFFFC);
8306   shrl(jdx, 2);
8307 
8308   bind(L_third_loop);
8309   subl(jdx, 1);
8310   jcc(Assembler::negative, L_third_loop_exit);
8311   subl(idx, 4);
8312 
8313   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8314   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8315   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8316   rorxq(yz_idx2, yz_idx2, 32);
8317 
8318   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8319   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8320 
8321   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8322   rorxq(yz_idx1, yz_idx1, 32);
8323   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8324   rorxq(yz_idx2, yz_idx2, 32);
8325 
8326   if (VM_Version::supports_adx()) {
8327     adcxq(tmp3, carry);
8328     adoxq(tmp3, yz_idx1);
8329 
8330     adcxq(tmp4, tmp);
8331     adoxq(tmp4, yz_idx2);
8332 
8333     movl(carry, 0); // does not affect flags
8334     adcxq(carry2, carry);
8335     adoxq(carry2, carry);
8336   } else {
8337     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8338     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8339   }
8340   movq(carry, carry2);
8341 
8342   movl(Address(z, idx, Address::times_4, 12), tmp3);
8343   shrq(tmp3, 32);
8344   movl(Address(z, idx, Address::times_4,  8), tmp3);
8345 
8346   movl(Address(z, idx, Address::times_4,  4), tmp4);
8347   shrq(tmp4, 32);
8348   movl(Address(z, idx, Address::times_4,  0), tmp4);
8349 
8350   jmp(L_third_loop);
8351 
8352   bind (L_third_loop_exit);
8353 
8354   andl (idx, 0x3);
8355   jcc(Assembler::zero, L_post_third_loop_done);
8356 
8357   Label L_check_1;
8358   subl(idx, 2);
8359   jcc(Assembler::negative, L_check_1);
8360 
8361   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8362   rorxq(yz_idx1, yz_idx1, 32);
8363   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8364   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8365   rorxq(yz_idx2, yz_idx2, 32);
8366 
8367   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8368 
8369   movl(Address(z, idx, Address::times_4,  4), tmp3);
8370   shrq(tmp3, 32);
8371   movl(Address(z, idx, Address::times_4,  0), tmp3);
8372   movq(carry, tmp4);
8373 
8374   bind (L_check_1);
8375   addl (idx, 0x2);
8376   andl (idx, 0x1);
8377   subl(idx, 1);
8378   jcc(Assembler::negative, L_post_third_loop_done);
8379   movl(tmp4, Address(y, idx, Address::times_4,  0));
8380   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8381   movl(tmp4, Address(z, idx, Address::times_4,  0));
8382 
8383   add2_with_carry(carry2, tmp3, tmp4, carry);
8384 
8385   movl(Address(z, idx, Address::times_4,  0), tmp3);
8386   shrq(tmp3, 32);
8387 
8388   shlq(carry2, 32);
8389   orq(tmp3, carry2);
8390   movq(carry, tmp3);
8391 
8392   bind(L_post_third_loop_done);
8393 }
8394 
8395 /**
8396  * Code for BigInteger::multiplyToLen() instrinsic.
8397  *
8398  * rdi: x
8399  * rax: xlen
8400  * rsi: y
8401  * rcx: ylen
8402  * r8:  z
8403  * r11: zlen
8404  * r12: tmp1
8405  * r13: tmp2
8406  * r14: tmp3
8407  * r15: tmp4
8408  * rbx: tmp5
8409  *
8410  */
8411 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
8412                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
8413   ShortBranchVerifier sbv(this);
8414   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
8415 
8416   push(tmp1);
8417   push(tmp2);
8418   push(tmp3);
8419   push(tmp4);
8420   push(tmp5);
8421 
8422   push(xlen);
8423   push(zlen);
8424 
8425   const Register idx = tmp1;
8426   const Register kdx = tmp2;
8427   const Register xstart = tmp3;
8428 
8429   const Register y_idx = tmp4;
8430   const Register carry = tmp5;
8431   const Register product  = xlen;
8432   const Register x_xstart = zlen;  // reuse register
8433 
8434   // First Loop.
8435   //
8436   //  final static long LONG_MASK = 0xffffffffL;
8437   //  int xstart = xlen - 1;
8438   //  int ystart = ylen - 1;
8439   //  long carry = 0;
8440   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8441   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
8442   //    z[kdx] = (int)product;
8443   //    carry = product >>> 32;
8444   //  }
8445   //  z[xstart] = (int)carry;
8446   //
8447 
8448   movl(idx, ylen);      // idx = ylen;
8449   movl(kdx, zlen);      // kdx = xlen+ylen;
8450   xorq(carry, carry);   // carry = 0;
8451 
8452   Label L_done;
8453 
8454   movl(xstart, xlen);
8455   decrementl(xstart);
8456   jcc(Assembler::negative, L_done);
8457 
8458   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
8459 
8460   Label L_second_loop;
8461   testl(kdx, kdx);
8462   jcc(Assembler::zero, L_second_loop);
8463 
8464   Label L_carry;
8465   subl(kdx, 1);
8466   jcc(Assembler::zero, L_carry);
8467 
8468   movl(Address(z, kdx, Address::times_4,  0), carry);
8469   shrq(carry, 32);
8470   subl(kdx, 1);
8471 
8472   bind(L_carry);
8473   movl(Address(z, kdx, Address::times_4,  0), carry);
8474 
8475   // Second and third (nested) loops.
8476   //
8477   // for (int i = xstart-1; i >= 0; i--) { // Second loop
8478   //   carry = 0;
8479   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
8480   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
8481   //                    (z[k] & LONG_MASK) + carry;
8482   //     z[k] = (int)product;
8483   //     carry = product >>> 32;
8484   //   }
8485   //   z[i] = (int)carry;
8486   // }
8487   //
8488   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
8489 
8490   const Register jdx = tmp1;
8491 
8492   bind(L_second_loop);
8493   xorl(carry, carry);    // carry = 0;
8494   movl(jdx, ylen);       // j = ystart+1
8495 
8496   subl(xstart, 1);       // i = xstart-1;
8497   jcc(Assembler::negative, L_done);
8498 
8499   push (z);
8500 
8501   Label L_last_x;
8502   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
8503   subl(xstart, 1);       // i = xstart-1;
8504   jcc(Assembler::negative, L_last_x);
8505 
8506   if (UseBMI2Instructions) {
8507     movq(rdx,  Address(x, xstart, Address::times_4,  0));
8508     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
8509   } else {
8510     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8511     rorq(x_xstart, 32);  // convert big-endian to little-endian
8512   }
8513 
8514   Label L_third_loop_prologue;
8515   bind(L_third_loop_prologue);
8516 
8517   push (x);
8518   push (xstart);
8519   push (ylen);
8520 
8521 
8522   if (UseBMI2Instructions) {
8523     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
8524   } else { // !UseBMI2Instructions
8525     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
8526   }
8527 
8528   pop(ylen);
8529   pop(xlen);
8530   pop(x);
8531   pop(z);
8532 
8533   movl(tmp3, xlen);
8534   addl(tmp3, 1);
8535   movl(Address(z, tmp3, Address::times_4,  0), carry);
8536   subl(tmp3, 1);
8537   jccb(Assembler::negative, L_done);
8538 
8539   shrq(carry, 32);
8540   movl(Address(z, tmp3, Address::times_4,  0), carry);
8541   jmp(L_second_loop);
8542 
8543   // Next infrequent code is moved outside loops.
8544   bind(L_last_x);
8545   if (UseBMI2Instructions) {
8546     movl(rdx, Address(x,  0));
8547   } else {
8548     movl(x_xstart, Address(x,  0));
8549   }
8550   jmp(L_third_loop_prologue);
8551 
8552   bind(L_done);
8553 
8554   pop(zlen);
8555   pop(xlen);
8556 
8557   pop(tmp5);
8558   pop(tmp4);
8559   pop(tmp3);
8560   pop(tmp2);
8561   pop(tmp1);
8562 }
8563 
8564 //Helper functions for square_to_len()
8565 
8566 /**
8567  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
8568  * Preserves x and z and modifies rest of the registers.
8569  */
8570 
8571 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8572   // Perform square and right shift by 1
8573   // Handle odd xlen case first, then for even xlen do the following
8574   // jlong carry = 0;
8575   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
8576   //     huge_128 product = x[j:j+1] * x[j:j+1];
8577   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
8578   //     z[i+2:i+3] = (jlong)(product >>> 1);
8579   //     carry = (jlong)product;
8580   // }
8581 
8582   xorq(tmp5, tmp5);     // carry
8583   xorq(rdxReg, rdxReg);
8584   xorl(tmp1, tmp1);     // index for x
8585   xorl(tmp4, tmp4);     // index for z
8586 
8587   Label L_first_loop, L_first_loop_exit;
8588 
8589   testl(xlen, 1);
8590   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
8591 
8592   // Square and right shift by 1 the odd element using 32 bit multiply
8593   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
8594   imulq(raxReg, raxReg);
8595   shrq(raxReg, 1);
8596   adcq(tmp5, 0);
8597   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
8598   incrementl(tmp1);
8599   addl(tmp4, 2);
8600 
8601   // Square and  right shift by 1 the rest using 64 bit multiply
8602   bind(L_first_loop);
8603   cmpptr(tmp1, xlen);
8604   jccb(Assembler::equal, L_first_loop_exit);
8605 
8606   // Square
8607   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
8608   rorq(raxReg, 32);    // convert big-endian to little-endian
8609   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
8610 
8611   // Right shift by 1 and save carry
8612   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
8613   rcrq(rdxReg, 1);
8614   rcrq(raxReg, 1);
8615   adcq(tmp5, 0);
8616 
8617   // Store result in z
8618   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
8619   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
8620 
8621   // Update indices for x and z
8622   addl(tmp1, 2);
8623   addl(tmp4, 4);
8624   jmp(L_first_loop);
8625 
8626   bind(L_first_loop_exit);
8627 }
8628 
8629 
8630 /**
8631  * Perform the following multiply add operation using BMI2 instructions
8632  * carry:sum = sum + op1*op2 + carry
8633  * op2 should be in rdx
8634  * op2 is preserved, all other registers are modified
8635  */
8636 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
8637   // assert op2 is rdx
8638   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
8639   addq(sum, carry);
8640   adcq(tmp2, 0);
8641   addq(sum, op1);
8642   adcq(tmp2, 0);
8643   movq(carry, tmp2);
8644 }
8645 
8646 /**
8647  * Perform the following multiply add operation:
8648  * carry:sum = sum + op1*op2 + carry
8649  * Preserves op1, op2 and modifies rest of registers
8650  */
8651 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
8652   // rdx:rax = op1 * op2
8653   movq(raxReg, op2);
8654   mulq(op1);
8655 
8656   //  rdx:rax = sum + carry + rdx:rax
8657   addq(sum, carry);
8658   adcq(rdxReg, 0);
8659   addq(sum, raxReg);
8660   adcq(rdxReg, 0);
8661 
8662   // carry:sum = rdx:sum
8663   movq(carry, rdxReg);
8664 }
8665 
8666 /**
8667  * Add 64 bit long carry into z[] with carry propogation.
8668  * Preserves z and carry register values and modifies rest of registers.
8669  *
8670  */
8671 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
8672   Label L_fourth_loop, L_fourth_loop_exit;
8673 
8674   movl(tmp1, 1);
8675   subl(zlen, 2);
8676   addq(Address(z, zlen, Address::times_4, 0), carry);
8677 
8678   bind(L_fourth_loop);
8679   jccb(Assembler::carryClear, L_fourth_loop_exit);
8680   subl(zlen, 2);
8681   jccb(Assembler::negative, L_fourth_loop_exit);
8682   addq(Address(z, zlen, Address::times_4, 0), tmp1);
8683   jmp(L_fourth_loop);
8684   bind(L_fourth_loop_exit);
8685 }
8686 
8687 /**
8688  * Shift z[] left by 1 bit.
8689  * Preserves x, len, z and zlen registers and modifies rest of the registers.
8690  *
8691  */
8692 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
8693 
8694   Label L_fifth_loop, L_fifth_loop_exit;
8695 
8696   // Fifth loop
8697   // Perform primitiveLeftShift(z, zlen, 1)
8698 
8699   const Register prev_carry = tmp1;
8700   const Register new_carry = tmp4;
8701   const Register value = tmp2;
8702   const Register zidx = tmp3;
8703 
8704   // int zidx, carry;
8705   // long value;
8706   // carry = 0;
8707   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
8708   //    (carry:value)  = (z[i] << 1) | carry ;
8709   //    z[i] = value;
8710   // }
8711 
8712   movl(zidx, zlen);
8713   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
8714 
8715   bind(L_fifth_loop);
8716   decl(zidx);  // Use decl to preserve carry flag
8717   decl(zidx);
8718   jccb(Assembler::negative, L_fifth_loop_exit);
8719 
8720   if (UseBMI2Instructions) {
8721      movq(value, Address(z, zidx, Address::times_4, 0));
8722      rclq(value, 1);
8723      rorxq(value, value, 32);
8724      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8725   }
8726   else {
8727     // clear new_carry
8728     xorl(new_carry, new_carry);
8729 
8730     // Shift z[i] by 1, or in previous carry and save new carry
8731     movq(value, Address(z, zidx, Address::times_4, 0));
8732     shlq(value, 1);
8733     adcl(new_carry, 0);
8734 
8735     orq(value, prev_carry);
8736     rorq(value, 0x20);
8737     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
8738 
8739     // Set previous carry = new carry
8740     movl(prev_carry, new_carry);
8741   }
8742   jmp(L_fifth_loop);
8743 
8744   bind(L_fifth_loop_exit);
8745 }
8746 
8747 
8748 /**
8749  * Code for BigInteger::squareToLen() intrinsic
8750  *
8751  * rdi: x
8752  * rsi: len
8753  * r8:  z
8754  * rcx: zlen
8755  * r12: tmp1
8756  * r13: tmp2
8757  * r14: tmp3
8758  * r15: tmp4
8759  * rbx: tmp5
8760  *
8761  */
8762 void MacroAssembler::square_to_len(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8763 
8764   Label L_second_loop, L_second_loop_exit, L_third_loop, L_third_loop_exit, fifth_loop, fifth_loop_exit, L_last_x, L_multiply;
8765   push(tmp1);
8766   push(tmp2);
8767   push(tmp3);
8768   push(tmp4);
8769   push(tmp5);
8770 
8771   // First loop
8772   // Store the squares, right shifted one bit (i.e., divided by 2).
8773   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
8774 
8775   // Add in off-diagonal sums.
8776   //
8777   // Second, third (nested) and fourth loops.
8778   // zlen +=2;
8779   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
8780   //    carry = 0;
8781   //    long op2 = x[xidx:xidx+1];
8782   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
8783   //       k -= 2;
8784   //       long op1 = x[j:j+1];
8785   //       long sum = z[k:k+1];
8786   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
8787   //       z[k:k+1] = sum;
8788   //    }
8789   //    add_one_64(z, k, carry, tmp_regs);
8790   // }
8791 
8792   const Register carry = tmp5;
8793   const Register sum = tmp3;
8794   const Register op1 = tmp4;
8795   Register op2 = tmp2;
8796 
8797   push(zlen);
8798   push(len);
8799   addl(zlen,2);
8800   bind(L_second_loop);
8801   xorq(carry, carry);
8802   subl(zlen, 4);
8803   subl(len, 2);
8804   push(zlen);
8805   push(len);
8806   cmpl(len, 0);
8807   jccb(Assembler::lessEqual, L_second_loop_exit);
8808 
8809   // Multiply an array by one 64 bit long.
8810   if (UseBMI2Instructions) {
8811     op2 = rdxReg;
8812     movq(op2, Address(x, len, Address::times_4,  0));
8813     rorxq(op2, op2, 32);
8814   }
8815   else {
8816     movq(op2, Address(x, len, Address::times_4,  0));
8817     rorq(op2, 32);
8818   }
8819 
8820   bind(L_third_loop);
8821   decrementl(len);
8822   jccb(Assembler::negative, L_third_loop_exit);
8823   decrementl(len);
8824   jccb(Assembler::negative, L_last_x);
8825 
8826   movq(op1, Address(x, len, Address::times_4,  0));
8827   rorq(op1, 32);
8828 
8829   bind(L_multiply);
8830   subl(zlen, 2);
8831   movq(sum, Address(z, zlen, Address::times_4,  0));
8832 
8833   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
8834   if (UseBMI2Instructions) {
8835     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
8836   }
8837   else {
8838     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8839   }
8840 
8841   movq(Address(z, zlen, Address::times_4, 0), sum);
8842 
8843   jmp(L_third_loop);
8844   bind(L_third_loop_exit);
8845 
8846   // Fourth loop
8847   // Add 64 bit long carry into z with carry propogation.
8848   // Uses offsetted zlen.
8849   add_one_64(z, zlen, carry, tmp1);
8850 
8851   pop(len);
8852   pop(zlen);
8853   jmp(L_second_loop);
8854 
8855   // Next infrequent code is moved outside loops.
8856   bind(L_last_x);
8857   movl(op1, Address(x, 0));
8858   jmp(L_multiply);
8859 
8860   bind(L_second_loop_exit);
8861   pop(len);
8862   pop(zlen);
8863   pop(len);
8864   pop(zlen);
8865 
8866   // Fifth loop
8867   // Shift z left 1 bit.
8868   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
8869 
8870   // z[zlen-1] |= x[len-1] & 1;
8871   movl(tmp3, Address(x, len, Address::times_4, -4));
8872   andl(tmp3, 1);
8873   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
8874 
8875   pop(tmp5);
8876   pop(tmp4);
8877   pop(tmp3);
8878   pop(tmp2);
8879   pop(tmp1);
8880 }
8881 
8882 /**
8883  * Helper function for mul_add()
8884  * Multiply the in[] by int k and add to out[] starting at offset offs using
8885  * 128 bit by 32 bit multiply and return the carry in tmp5.
8886  * Only quad int aligned length of in[] is operated on in this function.
8887  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
8888  * This function preserves out, in and k registers.
8889  * len and offset point to the appropriate index in "in" & "out" correspondingly
8890  * tmp5 has the carry.
8891  * other registers are temporary and are modified.
8892  *
8893  */
8894 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
8895   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
8896   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8897 
8898   Label L_first_loop, L_first_loop_exit;
8899 
8900   movl(tmp1, len);
8901   shrl(tmp1, 2);
8902 
8903   bind(L_first_loop);
8904   subl(tmp1, 1);
8905   jccb(Assembler::negative, L_first_loop_exit);
8906 
8907   subl(len, 4);
8908   subl(offset, 4);
8909 
8910   Register op2 = tmp2;
8911   const Register sum = tmp3;
8912   const Register op1 = tmp4;
8913   const Register carry = tmp5;
8914 
8915   if (UseBMI2Instructions) {
8916     op2 = rdxReg;
8917   }
8918 
8919   movq(op1, Address(in, len, Address::times_4,  8));
8920   rorq(op1, 32);
8921   movq(sum, Address(out, offset, Address::times_4,  8));
8922   rorq(sum, 32);
8923   if (UseBMI2Instructions) {
8924     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8925   }
8926   else {
8927     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8928   }
8929   // Store back in big endian from little endian
8930   rorq(sum, 0x20);
8931   movq(Address(out, offset, Address::times_4,  8), sum);
8932 
8933   movq(op1, Address(in, len, Address::times_4,  0));
8934   rorq(op1, 32);
8935   movq(sum, Address(out, offset, Address::times_4,  0));
8936   rorq(sum, 32);
8937   if (UseBMI2Instructions) {
8938     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
8939   }
8940   else {
8941     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
8942   }
8943   // Store back in big endian from little endian
8944   rorq(sum, 0x20);
8945   movq(Address(out, offset, Address::times_4,  0), sum);
8946 
8947   jmp(L_first_loop);
8948   bind(L_first_loop_exit);
8949 }
8950 
8951 /**
8952  * Code for BigInteger::mulAdd() intrinsic
8953  *
8954  * rdi: out
8955  * rsi: in
8956  * r11: offs (out.length - offset)
8957  * rcx: len
8958  * r8:  k
8959  * r12: tmp1
8960  * r13: tmp2
8961  * r14: tmp3
8962  * r15: tmp4
8963  * rbx: tmp5
8964  * Multiply the in[] by word k and add to out[], return the carry in rax
8965  */
8966 void MacroAssembler::mul_add(Register out, Register in, Register offs,
8967    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
8968    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
8969 
8970   Label L_carry, L_last_in, L_done;
8971 
8972 // carry = 0;
8973 // for (int j=len-1; j >= 0; j--) {
8974 //    long product = (in[j] & LONG_MASK) * kLong +
8975 //                   (out[offs] & LONG_MASK) + carry;
8976 //    out[offs--] = (int)product;
8977 //    carry = product >>> 32;
8978 // }
8979 //
8980   push(tmp1);
8981   push(tmp2);
8982   push(tmp3);
8983   push(tmp4);
8984   push(tmp5);
8985 
8986   Register op2 = tmp2;
8987   const Register sum = tmp3;
8988   const Register op1 = tmp4;
8989   const Register carry =  tmp5;
8990 
8991   if (UseBMI2Instructions) {
8992     op2 = rdxReg;
8993     movl(op2, k);
8994   }
8995   else {
8996     movl(op2, k);
8997   }
8998 
8999   xorq(carry, carry);
9000 
9001   //First loop
9002 
9003   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9004   //The carry is in tmp5
9005   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9006 
9007   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9008   decrementl(len);
9009   jccb(Assembler::negative, L_carry);
9010   decrementl(len);
9011   jccb(Assembler::negative, L_last_in);
9012 
9013   movq(op1, Address(in, len, Address::times_4,  0));
9014   rorq(op1, 32);
9015 
9016   subl(offs, 2);
9017   movq(sum, Address(out, offs, Address::times_4,  0));
9018   rorq(sum, 32);
9019 
9020   if (UseBMI2Instructions) {
9021     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9022   }
9023   else {
9024     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9025   }
9026 
9027   // Store back in big endian from little endian
9028   rorq(sum, 0x20);
9029   movq(Address(out, offs, Address::times_4,  0), sum);
9030 
9031   testl(len, len);
9032   jccb(Assembler::zero, L_carry);
9033 
9034   //Multiply the last in[] entry, if any
9035   bind(L_last_in);
9036   movl(op1, Address(in, 0));
9037   movl(sum, Address(out, offs, Address::times_4,  -4));
9038 
9039   movl(raxReg, k);
9040   mull(op1); //tmp4 * eax -> edx:eax
9041   addl(sum, carry);
9042   adcl(rdxReg, 0);
9043   addl(sum, raxReg);
9044   adcl(rdxReg, 0);
9045   movl(carry, rdxReg);
9046 
9047   movl(Address(out, offs, Address::times_4,  -4), sum);
9048 
9049   bind(L_carry);
9050   //return tmp5/carry as carry in rax
9051   movl(rax, carry);
9052 
9053   bind(L_done);
9054   pop(tmp5);
9055   pop(tmp4);
9056   pop(tmp3);
9057   pop(tmp2);
9058   pop(tmp1);
9059 }
9060 #endif
9061 
9062 /**
9063  * Emits code to update CRC-32 with a byte value according to constants in table
9064  *
9065  * @param [in,out]crc   Register containing the crc.
9066  * @param [in]val       Register containing the byte to fold into the CRC.
9067  * @param [in]table     Register containing the table of crc constants.
9068  *
9069  * uint32_t crc;
9070  * val = crc_table[(val ^ crc) & 0xFF];
9071  * crc = val ^ (crc >> 8);
9072  *
9073  */
9074 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9075   xorl(val, crc);
9076   andl(val, 0xFF);
9077   shrl(crc, 8); // unsigned shift
9078   xorl(crc, Address(table, val, Address::times_4, 0));
9079 }
9080 
9081 /**
9082  * Fold 128-bit data chunk
9083  */
9084 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9085   if (UseAVX > 0) {
9086     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9087     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9088     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9089     pxor(xcrc, xtmp);
9090   } else {
9091     movdqa(xtmp, xcrc);
9092     pclmulhdq(xtmp, xK);   // [123:64]
9093     pclmulldq(xcrc, xK);   // [63:0]
9094     pxor(xcrc, xtmp);
9095     movdqu(xtmp, Address(buf, offset));
9096     pxor(xcrc, xtmp);
9097   }
9098 }
9099 
9100 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9101   if (UseAVX > 0) {
9102     vpclmulhdq(xtmp, xK, xcrc);
9103     vpclmulldq(xcrc, xK, xcrc);
9104     pxor(xcrc, xbuf);
9105     pxor(xcrc, xtmp);
9106   } else {
9107     movdqa(xtmp, xcrc);
9108     pclmulhdq(xtmp, xK);
9109     pclmulldq(xcrc, xK);
9110     pxor(xcrc, xbuf);
9111     pxor(xcrc, xtmp);
9112   }
9113 }
9114 
9115 /**
9116  * 8-bit folds to compute 32-bit CRC
9117  *
9118  * uint64_t xcrc;
9119  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9120  */
9121 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9122   movdl(tmp, xcrc);
9123   andl(tmp, 0xFF);
9124   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9125   psrldq(xcrc, 1); // unsigned shift one byte
9126   pxor(xcrc, xtmp);
9127 }
9128 
9129 /**
9130  * uint32_t crc;
9131  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9132  */
9133 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9134   movl(tmp, crc);
9135   andl(tmp, 0xFF);
9136   shrl(crc, 8);
9137   xorl(crc, Address(table, tmp, Address::times_4, 0));
9138 }
9139 
9140 /**
9141  * @param crc   register containing existing CRC (32-bit)
9142  * @param buf   register pointing to input byte buffer (byte*)
9143  * @param len   register containing number of bytes
9144  * @param table register that will contain address of CRC table
9145  * @param tmp   scratch register
9146  */
9147 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9148   assert_different_registers(crc, buf, len, table, tmp, rax);
9149 
9150   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9151   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9152 
9153   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9154   // context for the registers used, where all instructions below are using 128-bit mode
9155   // On EVEX without VL and BW, these instructions will all be AVX.
9156   if (VM_Version::supports_avx512vlbw()) {
9157     movl(tmp, 0xffff);
9158     kmovwl(k1, tmp);
9159   }
9160 
9161   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
9162   notl(crc); // ~crc
9163   cmpl(len, 16);
9164   jcc(Assembler::less, L_tail);
9165 
9166   // Align buffer to 16 bytes
9167   movl(tmp, buf);
9168   andl(tmp, 0xF);
9169   jccb(Assembler::zero, L_aligned);
9170   subl(tmp,  16);
9171   addl(len, tmp);
9172 
9173   align(4);
9174   BIND(L_align_loop);
9175   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9176   update_byte_crc32(crc, rax, table);
9177   increment(buf);
9178   incrementl(tmp);
9179   jccb(Assembler::less, L_align_loop);
9180 
9181   BIND(L_aligned);
9182   movl(tmp, len); // save
9183   shrl(len, 4);
9184   jcc(Assembler::zero, L_tail_restore);
9185 
9186   // Fold crc into first bytes of vector
9187   movdqa(xmm1, Address(buf, 0));
9188   movdl(rax, xmm1);
9189   xorl(crc, rax);
9190   pinsrd(xmm1, crc, 0);
9191   addptr(buf, 16);
9192   subl(len, 4); // len > 0
9193   jcc(Assembler::less, L_fold_tail);
9194 
9195   movdqa(xmm2, Address(buf,  0));
9196   movdqa(xmm3, Address(buf, 16));
9197   movdqa(xmm4, Address(buf, 32));
9198   addptr(buf, 48);
9199   subl(len, 3);
9200   jcc(Assembler::lessEqual, L_fold_512b);
9201 
9202   // Fold total 512 bits of polynomial on each iteration,
9203   // 128 bits per each of 4 parallel streams.
9204   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
9205 
9206   align(32);
9207   BIND(L_fold_512b_loop);
9208   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9209   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
9210   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
9211   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
9212   addptr(buf, 64);
9213   subl(len, 4);
9214   jcc(Assembler::greater, L_fold_512b_loop);
9215 
9216   // Fold 512 bits to 128 bits.
9217   BIND(L_fold_512b);
9218   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9219   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
9220   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
9221   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
9222 
9223   // Fold the rest of 128 bits data chunks
9224   BIND(L_fold_tail);
9225   addl(len, 3);
9226   jccb(Assembler::lessEqual, L_fold_128b);
9227   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
9228 
9229   BIND(L_fold_tail_loop);
9230   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
9231   addptr(buf, 16);
9232   decrementl(len);
9233   jccb(Assembler::greater, L_fold_tail_loop);
9234 
9235   // Fold 128 bits in xmm1 down into 32 bits in crc register.
9236   BIND(L_fold_128b);
9237   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
9238   if (UseAVX > 0) {
9239     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
9240     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
9241     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
9242   } else {
9243     movdqa(xmm2, xmm0);
9244     pclmulqdq(xmm2, xmm1, 0x1);
9245     movdqa(xmm3, xmm0);
9246     pand(xmm3, xmm2);
9247     pclmulqdq(xmm0, xmm3, 0x1);
9248   }
9249   psrldq(xmm1, 8);
9250   psrldq(xmm2, 4);
9251   pxor(xmm0, xmm1);
9252   pxor(xmm0, xmm2);
9253 
9254   // 8 8-bit folds to compute 32-bit CRC.
9255   for (int j = 0; j < 4; j++) {
9256     fold_8bit_crc32(xmm0, table, xmm1, rax);
9257   }
9258   movdl(crc, xmm0); // mov 32 bits to general register
9259   for (int j = 0; j < 4; j++) {
9260     fold_8bit_crc32(crc, table, rax);
9261   }
9262 
9263   BIND(L_tail_restore);
9264   movl(len, tmp); // restore
9265   BIND(L_tail);
9266   andl(len, 0xf);
9267   jccb(Assembler::zero, L_exit);
9268 
9269   // Fold the rest of bytes
9270   align(4);
9271   BIND(L_tail_loop);
9272   movsbl(rax, Address(buf, 0)); // load byte with sign extension
9273   update_byte_crc32(crc, rax, table);
9274   increment(buf);
9275   decrementl(len);
9276   jccb(Assembler::greater, L_tail_loop);
9277 
9278   BIND(L_exit);
9279   notl(crc); // ~c
9280 }
9281 
9282 #ifdef _LP64
9283 // S. Gueron / Information Processing Letters 112 (2012) 184
9284 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
9285 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
9286 // Output: the 64-bit carry-less product of B * CONST
9287 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
9288                                      Register tmp1, Register tmp2, Register tmp3) {
9289   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9290   if (n > 0) {
9291     addq(tmp3, n * 256 * 8);
9292   }
9293   //    Q1 = TABLEExt[n][B & 0xFF];
9294   movl(tmp1, in);
9295   andl(tmp1, 0x000000FF);
9296   shll(tmp1, 3);
9297   addq(tmp1, tmp3);
9298   movq(tmp1, Address(tmp1, 0));
9299 
9300   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9301   movl(tmp2, in);
9302   shrl(tmp2, 8);
9303   andl(tmp2, 0x000000FF);
9304   shll(tmp2, 3);
9305   addq(tmp2, tmp3);
9306   movq(tmp2, Address(tmp2, 0));
9307 
9308   shlq(tmp2, 8);
9309   xorq(tmp1, tmp2);
9310 
9311   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9312   movl(tmp2, in);
9313   shrl(tmp2, 16);
9314   andl(tmp2, 0x000000FF);
9315   shll(tmp2, 3);
9316   addq(tmp2, tmp3);
9317   movq(tmp2, Address(tmp2, 0));
9318 
9319   shlq(tmp2, 16);
9320   xorq(tmp1, tmp2);
9321 
9322   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9323   shrl(in, 24);
9324   andl(in, 0x000000FF);
9325   shll(in, 3);
9326   addq(in, tmp3);
9327   movq(in, Address(in, 0));
9328 
9329   shlq(in, 24);
9330   xorq(in, tmp1);
9331   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9332 }
9333 
9334 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9335                                       Register in_out,
9336                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9337                                       XMMRegister w_xtmp2,
9338                                       Register tmp1,
9339                                       Register n_tmp2, Register n_tmp3) {
9340   if (is_pclmulqdq_supported) {
9341     movdl(w_xtmp1, in_out); // modified blindly
9342 
9343     movl(tmp1, const_or_pre_comp_const_index);
9344     movdl(w_xtmp2, tmp1);
9345     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9346 
9347     movdq(in_out, w_xtmp1);
9348   } else {
9349     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
9350   }
9351 }
9352 
9353 // Recombination Alternative 2: No bit-reflections
9354 // T1 = (CRC_A * U1) << 1
9355 // T2 = (CRC_B * U2) << 1
9356 // C1 = T1 >> 32
9357 // C2 = T2 >> 32
9358 // T1 = T1 & 0xFFFFFFFF
9359 // T2 = T2 & 0xFFFFFFFF
9360 // T1 = CRC32(0, T1)
9361 // T2 = CRC32(0, T2)
9362 // C1 = C1 ^ T1
9363 // C2 = C2 ^ T2
9364 // CRC = C1 ^ C2 ^ CRC_C
9365 void MacroAssembler::crc32c_rec_alt2(uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported, Register in_out, Register in1, Register in2,
9366                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9367                                      Register tmp1, Register tmp2,
9368                                      Register n_tmp3) {
9369   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9370   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9371   shlq(in_out, 1);
9372   movl(tmp1, in_out);
9373   shrq(in_out, 32);
9374   xorl(tmp2, tmp2);
9375   crc32(tmp2, tmp1, 4);
9376   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
9377   shlq(in1, 1);
9378   movl(tmp1, in1);
9379   shrq(in1, 32);
9380   xorl(tmp2, tmp2);
9381   crc32(tmp2, tmp1, 4);
9382   xorl(in1, tmp2);
9383   xorl(in_out, in1);
9384   xorl(in_out, in2);
9385 }
9386 
9387 // Set N to predefined value
9388 // Subtract from a lenght of a buffer
9389 // execute in a loop:
9390 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
9391 // for i = 1 to N do
9392 //  CRC_A = CRC32(CRC_A, A[i])
9393 //  CRC_B = CRC32(CRC_B, B[i])
9394 //  CRC_C = CRC32(CRC_C, C[i])
9395 // end for
9396 // Recombine
9397 void MacroAssembler::crc32c_proc_chunk(uint32_t size, uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported,
9398                                        Register in_out1, Register in_out2, Register in_out3,
9399                                        Register tmp1, Register tmp2, Register tmp3,
9400                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9401                                        Register tmp4, Register tmp5,
9402                                        Register n_tmp6) {
9403   Label L_processPartitions;
9404   Label L_processPartition;
9405   Label L_exit;
9406 
9407   bind(L_processPartitions);
9408   cmpl(in_out1, 3 * size);
9409   jcc(Assembler::less, L_exit);
9410     xorl(tmp1, tmp1);
9411     xorl(tmp2, tmp2);
9412     movq(tmp3, in_out2);
9413     addq(tmp3, size);
9414 
9415     bind(L_processPartition);
9416       crc32(in_out3, Address(in_out2, 0), 8);
9417       crc32(tmp1, Address(in_out2, size), 8);
9418       crc32(tmp2, Address(in_out2, size * 2), 8);
9419       addq(in_out2, 8);
9420       cmpq(in_out2, tmp3);
9421       jcc(Assembler::less, L_processPartition);
9422     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9423             w_xtmp1, w_xtmp2, w_xtmp3,
9424             tmp4, tmp5,
9425             n_tmp6);
9426     addq(in_out2, 2 * size);
9427     subl(in_out1, 3 * size);
9428     jmp(L_processPartitions);
9429 
9430   bind(L_exit);
9431 }
9432 #else
9433 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
9434                                      Register tmp1, Register tmp2, Register tmp3,
9435                                      XMMRegister xtmp1, XMMRegister xtmp2) {
9436   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
9437   if (n > 0) {
9438     addl(tmp3, n * 256 * 8);
9439   }
9440   //    Q1 = TABLEExt[n][B & 0xFF];
9441   movl(tmp1, in_out);
9442   andl(tmp1, 0x000000FF);
9443   shll(tmp1, 3);
9444   addl(tmp1, tmp3);
9445   movq(xtmp1, Address(tmp1, 0));
9446 
9447   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
9448   movl(tmp2, in_out);
9449   shrl(tmp2, 8);
9450   andl(tmp2, 0x000000FF);
9451   shll(tmp2, 3);
9452   addl(tmp2, tmp3);
9453   movq(xtmp2, Address(tmp2, 0));
9454 
9455   psllq(xtmp2, 8);
9456   pxor(xtmp1, xtmp2);
9457 
9458   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
9459   movl(tmp2, in_out);
9460   shrl(tmp2, 16);
9461   andl(tmp2, 0x000000FF);
9462   shll(tmp2, 3);
9463   addl(tmp2, tmp3);
9464   movq(xtmp2, Address(tmp2, 0));
9465 
9466   psllq(xtmp2, 16);
9467   pxor(xtmp1, xtmp2);
9468 
9469   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
9470   shrl(in_out, 24);
9471   andl(in_out, 0x000000FF);
9472   shll(in_out, 3);
9473   addl(in_out, tmp3);
9474   movq(xtmp2, Address(in_out, 0));
9475 
9476   psllq(xtmp2, 24);
9477   pxor(xtmp1, xtmp2); // Result in CXMM
9478   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
9479 }
9480 
9481 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
9482                                       Register in_out,
9483                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
9484                                       XMMRegister w_xtmp2,
9485                                       Register tmp1,
9486                                       Register n_tmp2, Register n_tmp3) {
9487   if (is_pclmulqdq_supported) {
9488     movdl(w_xtmp1, in_out);
9489 
9490     movl(tmp1, const_or_pre_comp_const_index);
9491     movdl(w_xtmp2, tmp1);
9492     pclmulqdq(w_xtmp1, w_xtmp2, 0);
9493     // Keep result in XMM since GPR is 32 bit in length
9494   } else {
9495     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
9496   }
9497 }
9498 
9499 void MacroAssembler::crc32c_rec_alt2(uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported, Register in_out, Register in1, Register in2,
9500                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9501                                      Register tmp1, Register tmp2,
9502                                      Register n_tmp3) {
9503   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9504   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
9505 
9506   psllq(w_xtmp1, 1);
9507   movdl(tmp1, w_xtmp1);
9508   psrlq(w_xtmp1, 32);
9509   movdl(in_out, w_xtmp1);
9510 
9511   xorl(tmp2, tmp2);
9512   crc32(tmp2, tmp1, 4);
9513   xorl(in_out, tmp2);
9514 
9515   psllq(w_xtmp2, 1);
9516   movdl(tmp1, w_xtmp2);
9517   psrlq(w_xtmp2, 32);
9518   movdl(in1, w_xtmp2);
9519 
9520   xorl(tmp2, tmp2);
9521   crc32(tmp2, tmp1, 4);
9522   xorl(in1, tmp2);
9523   xorl(in_out, in1);
9524   xorl(in_out, in2);
9525 }
9526 
9527 void MacroAssembler::crc32c_proc_chunk(uint32_t size, uint32_t const_or_pre_comp_const_index_u1, uint32_t const_or_pre_comp_const_index_u2, bool is_pclmulqdq_supported,
9528                                        Register in_out1, Register in_out2, Register in_out3,
9529                                        Register tmp1, Register tmp2, Register tmp3,
9530                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9531                                        Register tmp4, Register tmp5,
9532                                        Register n_tmp6) {
9533   Label L_processPartitions;
9534   Label L_processPartition;
9535   Label L_exit;
9536 
9537   bind(L_processPartitions);
9538   cmpl(in_out1, 3 * size);
9539   jcc(Assembler::less, L_exit);
9540     xorl(tmp1, tmp1);
9541     xorl(tmp2, tmp2);
9542     movl(tmp3, in_out2);
9543     addl(tmp3, size);
9544 
9545     bind(L_processPartition);
9546       crc32(in_out3, Address(in_out2, 0), 4);
9547       crc32(tmp1, Address(in_out2, size), 4);
9548       crc32(tmp2, Address(in_out2, size*2), 4);
9549       crc32(in_out3, Address(in_out2, 0+4), 4);
9550       crc32(tmp1, Address(in_out2, size+4), 4);
9551       crc32(tmp2, Address(in_out2, size*2+4), 4);
9552       addl(in_out2, 8);
9553       cmpl(in_out2, tmp3);
9554       jcc(Assembler::less, L_processPartition);
9555 
9556         push(tmp3);
9557         push(in_out1);
9558         push(in_out2);
9559         tmp4 = tmp3;
9560         tmp5 = in_out1;
9561         n_tmp6 = in_out2;
9562 
9563       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
9564             w_xtmp1, w_xtmp2, w_xtmp3,
9565             tmp4, tmp5,
9566             n_tmp6);
9567 
9568         pop(in_out2);
9569         pop(in_out1);
9570         pop(tmp3);
9571 
9572     addl(in_out2, 2 * size);
9573     subl(in_out1, 3 * size);
9574     jmp(L_processPartitions);
9575 
9576   bind(L_exit);
9577 }
9578 #endif //LP64
9579 
9580 #ifdef _LP64
9581 // Algorithm 2: Pipelined usage of the CRC32 instruction.
9582 // Input: A buffer I of L bytes.
9583 // Output: the CRC32C value of the buffer.
9584 // Notations:
9585 // Write L = 24N + r, with N = floor (L/24).
9586 // r = L mod 24 (0 <= r < 24).
9587 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
9588 // N quadwords, and R consists of r bytes.
9589 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
9590 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
9591 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
9592 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
9593 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9594                                           Register tmp1, Register tmp2, Register tmp3,
9595                                           Register tmp4, Register tmp5, Register tmp6,
9596                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9597                                           bool is_pclmulqdq_supported) {
9598   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9599   Label L_wordByWord;
9600   Label L_byteByByteProlog;
9601   Label L_byteByByte;
9602   Label L_exit;
9603 
9604   if (is_pclmulqdq_supported ) {
9605     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9606     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
9607 
9608     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9609     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9610 
9611     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9612     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9613     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
9614   } else {
9615     const_or_pre_comp_const_index[0] = 1;
9616     const_or_pre_comp_const_index[1] = 0;
9617 
9618     const_or_pre_comp_const_index[2] = 3;
9619     const_or_pre_comp_const_index[3] = 2;
9620 
9621     const_or_pre_comp_const_index[4] = 5;
9622     const_or_pre_comp_const_index[5] = 4;
9623    }
9624   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9625                     in2, in1, in_out,
9626                     tmp1, tmp2, tmp3,
9627                     w_xtmp1, w_xtmp2, w_xtmp3,
9628                     tmp4, tmp5,
9629                     tmp6);
9630   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9631                     in2, in1, in_out,
9632                     tmp1, tmp2, tmp3,
9633                     w_xtmp1, w_xtmp2, w_xtmp3,
9634                     tmp4, tmp5,
9635                     tmp6);
9636   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9637                     in2, in1, in_out,
9638                     tmp1, tmp2, tmp3,
9639                     w_xtmp1, w_xtmp2, w_xtmp3,
9640                     tmp4, tmp5,
9641                     tmp6);
9642   movl(tmp1, in2);
9643   andl(tmp1, 0x00000007);
9644   negl(tmp1);
9645   addl(tmp1, in2);
9646   addq(tmp1, in1);
9647 
9648   BIND(L_wordByWord);
9649   cmpq(in1, tmp1);
9650   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9651     crc32(in_out, Address(in1, 0), 4);
9652     addq(in1, 4);
9653     jmp(L_wordByWord);
9654 
9655   BIND(L_byteByByteProlog);
9656   andl(in2, 0x00000007);
9657   movl(tmp2, 1);
9658 
9659   BIND(L_byteByByte);
9660   cmpl(tmp2, in2);
9661   jccb(Assembler::greater, L_exit);
9662     crc32(in_out, Address(in1, 0), 1);
9663     incq(in1);
9664     incl(tmp2);
9665     jmp(L_byteByByte);
9666 
9667   BIND(L_exit);
9668 }
9669 #else
9670 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
9671                                           Register tmp1, Register  tmp2, Register tmp3,
9672                                           Register tmp4, Register  tmp5, Register tmp6,
9673                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
9674                                           bool is_pclmulqdq_supported) {
9675   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
9676   Label L_wordByWord;
9677   Label L_byteByByteProlog;
9678   Label L_byteByByte;
9679   Label L_exit;
9680 
9681   if (is_pclmulqdq_supported) {
9682     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
9683     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
9684 
9685     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
9686     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
9687 
9688     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
9689     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
9690   } else {
9691     const_or_pre_comp_const_index[0] = 1;
9692     const_or_pre_comp_const_index[1] = 0;
9693 
9694     const_or_pre_comp_const_index[2] = 3;
9695     const_or_pre_comp_const_index[3] = 2;
9696 
9697     const_or_pre_comp_const_index[4] = 5;
9698     const_or_pre_comp_const_index[5] = 4;
9699   }
9700   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
9701                     in2, in1, in_out,
9702                     tmp1, tmp2, tmp3,
9703                     w_xtmp1, w_xtmp2, w_xtmp3,
9704                     tmp4, tmp5,
9705                     tmp6);
9706   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
9707                     in2, in1, in_out,
9708                     tmp1, tmp2, tmp3,
9709                     w_xtmp1, w_xtmp2, w_xtmp3,
9710                     tmp4, tmp5,
9711                     tmp6);
9712   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
9713                     in2, in1, in_out,
9714                     tmp1, tmp2, tmp3,
9715                     w_xtmp1, w_xtmp2, w_xtmp3,
9716                     tmp4, tmp5,
9717                     tmp6);
9718   movl(tmp1, in2);
9719   andl(tmp1, 0x00000007);
9720   negl(tmp1);
9721   addl(tmp1, in2);
9722   addl(tmp1, in1);
9723 
9724   BIND(L_wordByWord);
9725   cmpl(in1, tmp1);
9726   jcc(Assembler::greaterEqual, L_byteByByteProlog);
9727     crc32(in_out, Address(in1,0), 4);
9728     addl(in1, 4);
9729     jmp(L_wordByWord);
9730 
9731   BIND(L_byteByByteProlog);
9732   andl(in2, 0x00000007);
9733   movl(tmp2, 1);
9734 
9735   BIND(L_byteByByte);
9736   cmpl(tmp2, in2);
9737   jccb(Assembler::greater, L_exit);
9738     movb(tmp1, Address(in1, 0));
9739     crc32(in_out, tmp1, 1);
9740     incl(in1);
9741     incl(tmp2);
9742     jmp(L_byteByByte);
9743 
9744   BIND(L_exit);
9745 }
9746 #endif // LP64
9747 #undef BIND
9748 #undef BLOCK_COMMENT
9749 
9750 
9751 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
9752   switch (cond) {
9753     // Note some conditions are synonyms for others
9754     case Assembler::zero:         return Assembler::notZero;
9755     case Assembler::notZero:      return Assembler::zero;
9756     case Assembler::less:         return Assembler::greaterEqual;
9757     case Assembler::lessEqual:    return Assembler::greater;
9758     case Assembler::greater:      return Assembler::lessEqual;
9759     case Assembler::greaterEqual: return Assembler::less;
9760     case Assembler::below:        return Assembler::aboveEqual;
9761     case Assembler::belowEqual:   return Assembler::above;
9762     case Assembler::above:        return Assembler::belowEqual;
9763     case Assembler::aboveEqual:   return Assembler::below;
9764     case Assembler::overflow:     return Assembler::noOverflow;
9765     case Assembler::noOverflow:   return Assembler::overflow;
9766     case Assembler::negative:     return Assembler::positive;
9767     case Assembler::positive:     return Assembler::negative;
9768     case Assembler::parity:       return Assembler::noParity;
9769     case Assembler::noParity:     return Assembler::parity;
9770   }
9771   ShouldNotReachHere(); return Assembler::overflow;
9772 }
9773 
9774 SkipIfEqual::SkipIfEqual(
9775     MacroAssembler* masm, const bool* flag_addr, bool value) {
9776   _masm = masm;
9777   _masm->cmp8(ExternalAddress((address)flag_addr), value);
9778   _masm->jcc(Assembler::equal, _label);
9779 }
9780 
9781 SkipIfEqual::~SkipIfEqual() {
9782   _masm->bind(_label);
9783 }