1 /*
   2  * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "jvm.h"
  27 #include "asm/assembler.hpp"
  28 #include "asm/assembler.inline.hpp"
  29 #include "compiler/disassembler.hpp"
  30 #include "gc/shared/cardTable.hpp"
  31 #include "gc/shared/cardTableModRefBS.hpp"
  32 #include "gc/shared/collectedHeap.inline.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "memory/resourceArea.hpp"
  35 #include "memory/universe.hpp"
  36 #include "oops/klass.inline.hpp"
  37 #include "prims/methodHandles.hpp"
  38 #include "runtime/biasedLocking.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/objectMonitor.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/safepoint.hpp"
  43 #include "runtime/safepointMechanism.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/stubRoutines.hpp"
  46 #include "runtime/thread.hpp"
  47 #include "utilities/macros.hpp"
  48 #if INCLUDE_ALL_GCS
  49 #include "gc/g1/g1BarrierSet.hpp"
  50 #include "gc/g1/g1CardTable.hpp"
  51 #include "gc/g1/g1CollectedHeap.inline.hpp"
  52 #include "gc/g1/heapRegion.hpp"
  53 #include "gc/z/zGlobals.hpp"
  54 #endif // INCLUDE_ALL_GCS
  55 #include "crc32c.h"
  56 #ifdef COMPILER2
  57 #include "opto/intrinsicnode.hpp"
  58 #endif
  59 
  60 #ifdef PRODUCT
  61 #define BLOCK_COMMENT(str) /* nothing */
  62 #define STOP(error) stop(error)
  63 #else
  64 #define BLOCK_COMMENT(str) block_comment(str)
  65 #define STOP(error) block_comment(error); stop(error)
  66 #endif
  67 
  68 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  69 
  70 #ifdef ASSERT
  71 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  72 #endif
  73 
  74 static Assembler::Condition reverse[] = {
  75     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  76     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  77     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  78     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  79     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  80     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  81     Assembler::above          /* belowEqual    = 0x6 */ ,
  82     Assembler::belowEqual     /* above         = 0x7 */ ,
  83     Assembler::positive       /* negative      = 0x8 */ ,
  84     Assembler::negative       /* positive      = 0x9 */ ,
  85     Assembler::noParity       /* parity        = 0xa */ ,
  86     Assembler::parity         /* noParity      = 0xb */ ,
  87     Assembler::greaterEqual   /* less          = 0xc */ ,
  88     Assembler::less           /* greaterEqual  = 0xd */ ,
  89     Assembler::greater        /* lessEqual     = 0xe */ ,
  90     Assembler::lessEqual      /* greater       = 0xf, */
  91 
  92 };
  93 
  94 
  95 // Implementation of MacroAssembler
  96 
  97 // First all the versions that have distinct versions depending on 32/64 bit
  98 // Unless the difference is trivial (1 line or so).
  99 
 100 #ifndef _LP64
 101 
 102 // 32bit versions
 103 
 104 Address MacroAssembler::as_Address(AddressLiteral adr) {
 105   return Address(adr.target(), adr.rspec());
 106 }
 107 
 108 Address MacroAssembler::as_Address(ArrayAddress adr) {
 109   return Address::make_array(adr);
 110 }
 111 
 112 void MacroAssembler::call_VM_leaf_base(address entry_point,
 113                                        int number_of_arguments) {
 114   call(RuntimeAddress(entry_point));
 115   increment(rsp, number_of_arguments * wordSize);
 116 }
 117 
 118 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 119   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 120 }
 121 
 122 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 123   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 124 }
 125 
 126 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 127   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 128 }
 129 
 130 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 131   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 132 }
 133 
 134 void MacroAssembler::extend_sign(Register hi, Register lo) {
 135   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 136   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 137     cdql();
 138   } else {
 139     movl(hi, lo);
 140     sarl(hi, 31);
 141   }
 142 }
 143 
 144 void MacroAssembler::jC2(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::parity, L);
 152 }
 153 
 154 void MacroAssembler::jnC2(Register tmp, Label& L) {
 155   // set parity bit if FPU flag C2 is set (via rax)
 156   save_rax(tmp);
 157   fwait(); fnstsw_ax();
 158   sahf();
 159   restore_rax(tmp);
 160   // branch
 161   jcc(Assembler::noParity, L);
 162 }
 163 
 164 // 32bit can do a case table jump in one instruction but we no longer allow the base
 165 // to be installed in the Address class
 166 void MacroAssembler::jump(ArrayAddress entry) {
 167   jmp(as_Address(entry));
 168 }
 169 
 170 // Note: y_lo will be destroyed
 171 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 172   // Long compare for Java (semantics as described in JVM spec.)
 173   Label high, low, done;
 174 
 175   cmpl(x_hi, y_hi);
 176   jcc(Assembler::less, low);
 177   jcc(Assembler::greater, high);
 178   // x_hi is the return register
 179   xorl(x_hi, x_hi);
 180   cmpl(x_lo, y_lo);
 181   jcc(Assembler::below, low);
 182   jcc(Assembler::equal, done);
 183 
 184   bind(high);
 185   xorl(x_hi, x_hi);
 186   increment(x_hi);
 187   jmp(done);
 188 
 189   bind(low);
 190   xorl(x_hi, x_hi);
 191   decrementl(x_hi);
 192 
 193   bind(done);
 194 }
 195 
 196 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 197     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 198 }
 199 
 200 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 201   // leal(dst, as_Address(adr));
 202   // see note in movl as to why we must use a move
 203   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 204 }
 205 
 206 void MacroAssembler::leave() {
 207   mov(rsp, rbp);
 208   pop(rbp);
 209 }
 210 
 211 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 212   // Multiplication of two Java long values stored on the stack
 213   // as illustrated below. Result is in rdx:rax.
 214   //
 215   // rsp ---> [  ??  ] \               \
 216   //            ....    | y_rsp_offset  |
 217   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 218   //          [ y_hi ]                  | (in bytes)
 219   //            ....                    |
 220   //          [ x_lo ]                 /
 221   //          [ x_hi ]
 222   //            ....
 223   //
 224   // Basic idea: lo(result) = lo(x_lo * y_lo)
 225   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 226   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 227   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 228   Label quick;
 229   // load x_hi, y_hi and check if quick
 230   // multiplication is possible
 231   movl(rbx, x_hi);
 232   movl(rcx, y_hi);
 233   movl(rax, rbx);
 234   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 235   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 236   // do full multiplication
 237   // 1st step
 238   mull(y_lo);                                    // x_hi * y_lo
 239   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 240   // 2nd step
 241   movl(rax, x_lo);
 242   mull(rcx);                                     // x_lo * y_hi
 243   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 244   // 3rd step
 245   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 246   movl(rax, x_lo);
 247   mull(y_lo);                                    // x_lo * y_lo
 248   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 249 }
 250 
 251 void MacroAssembler::lneg(Register hi, Register lo) {
 252   negl(lo);
 253   adcl(hi, 0);
 254   negl(hi);
 255 }
 256 
 257 void MacroAssembler::lshl(Register hi, Register lo) {
 258   // Java shift left long support (semantics as described in JVM spec., p.305)
 259   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 260   // shift value is in rcx !
 261   assert(hi != rcx, "must not use rcx");
 262   assert(lo != rcx, "must not use rcx");
 263   const Register s = rcx;                        // shift count
 264   const int      n = BitsPerWord;
 265   Label L;
 266   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 267   cmpl(s, n);                                    // if (s < n)
 268   jcc(Assembler::less, L);                       // else (s >= n)
 269   movl(hi, lo);                                  // x := x << n
 270   xorl(lo, lo);
 271   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 272   bind(L);                                       // s (mod n) < n
 273   shldl(hi, lo);                                 // x := x << s
 274   shll(lo);
 275 }
 276 
 277 
 278 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 279   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 280   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 281   assert(hi != rcx, "must not use rcx");
 282   assert(lo != rcx, "must not use rcx");
 283   const Register s = rcx;                        // shift count
 284   const int      n = BitsPerWord;
 285   Label L;
 286   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 287   cmpl(s, n);                                    // if (s < n)
 288   jcc(Assembler::less, L);                       // else (s >= n)
 289   movl(lo, hi);                                  // x := x >> n
 290   if (sign_extension) sarl(hi, 31);
 291   else                xorl(hi, hi);
 292   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 293   bind(L);                                       // s (mod n) < n
 294   shrdl(lo, hi);                                 // x := x >> s
 295   if (sign_extension) sarl(hi);
 296   else                shrl(hi);
 297 }
 298 
 299 void MacroAssembler::movoop(Register dst, jobject obj) {
 300   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 301 }
 302 
 303 void MacroAssembler::movoop(Address dst, jobject obj) {
 304   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 305 }
 306 
 307 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 308   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 309 }
 310 
 311 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 312   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 313 }
 314 
 315 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 316   // scratch register is not used,
 317   // it is defined to match parameters of 64-bit version of this method.
 318   if (src.is_lval()) {
 319     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 320   } else {
 321     movl(dst, as_Address(src));
 322   }
 323 }
 324 
 325 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 326   movl(as_Address(dst), src);
 327 }
 328 
 329 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 330   movl(dst, as_Address(src));
 331 }
 332 
 333 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 334 void MacroAssembler::movptr(Address dst, intptr_t src) {
 335   movl(dst, src);
 336 }
 337 
 338 
 339 void MacroAssembler::pop_callee_saved_registers() {
 340   pop(rcx);
 341   pop(rdx);
 342   pop(rdi);
 343   pop(rsi);
 344 }
 345 
 346 void MacroAssembler::pop_fTOS() {
 347   fld_d(Address(rsp, 0));
 348   addl(rsp, 2 * wordSize);
 349 }
 350 
 351 void MacroAssembler::push_callee_saved_registers() {
 352   push(rsi);
 353   push(rdi);
 354   push(rdx);
 355   push(rcx);
 356 }
 357 
 358 void MacroAssembler::push_fTOS() {
 359   subl(rsp, 2 * wordSize);
 360   fstp_d(Address(rsp, 0));
 361 }
 362 
 363 
 364 void MacroAssembler::pushoop(jobject obj) {
 365   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 366 }
 367 
 368 void MacroAssembler::pushklass(Metadata* obj) {
 369   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 370 }
 371 
 372 void MacroAssembler::pushptr(AddressLiteral src) {
 373   if (src.is_lval()) {
 374     push_literal32((int32_t)src.target(), src.rspec());
 375   } else {
 376     pushl(as_Address(src));
 377   }
 378 }
 379 
 380 void MacroAssembler::set_word_if_not_zero(Register dst) {
 381   xorl(dst, dst);
 382   set_byte_if_not_zero(dst);
 383 }
 384 
 385 static void pass_arg0(MacroAssembler* masm, Register arg) {
 386   masm->push(arg);
 387 }
 388 
 389 static void pass_arg1(MacroAssembler* masm, Register arg) {
 390   masm->push(arg);
 391 }
 392 
 393 static void pass_arg2(MacroAssembler* masm, Register arg) {
 394   masm->push(arg);
 395 }
 396 
 397 static void pass_arg3(MacroAssembler* masm, Register arg) {
 398   masm->push(arg);
 399 }
 400 
 401 #ifndef PRODUCT
 402 extern "C" void findpc(intptr_t x);
 403 #endif
 404 
 405 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 406   // In order to get locks to work, we need to fake a in_VM state
 407   JavaThread* thread = JavaThread::current();
 408   JavaThreadState saved_state = thread->thread_state();
 409   thread->set_thread_state(_thread_in_vm);
 410   if (ShowMessageBoxOnError) {
 411     JavaThread* thread = JavaThread::current();
 412     JavaThreadState saved_state = thread->thread_state();
 413     thread->set_thread_state(_thread_in_vm);
 414     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 415       ttyLocker ttyl;
 416       BytecodeCounter::print();
 417     }
 418     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 419     // This is the value of eip which points to where verify_oop will return.
 420     if (os::message_box(msg, "Execution stopped, print registers?")) {
 421       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 422       BREAKPOINT;
 423     }
 424   } else {
 425     ttyLocker ttyl;
 426     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 427   }
 428   // Don't assert holding the ttyLock
 429     assert(false, "DEBUG MESSAGE: %s", msg);
 430   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 431 }
 432 
 433 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 434   ttyLocker ttyl;
 435   FlagSetting fs(Debugging, true);
 436   tty->print_cr("eip = 0x%08x", eip);
 437 #ifndef PRODUCT
 438   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 439     tty->cr();
 440     findpc(eip);
 441     tty->cr();
 442   }
 443 #endif
 444 #define PRINT_REG(rax) \
 445   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 446   PRINT_REG(rax);
 447   PRINT_REG(rbx);
 448   PRINT_REG(rcx);
 449   PRINT_REG(rdx);
 450   PRINT_REG(rdi);
 451   PRINT_REG(rsi);
 452   PRINT_REG(rbp);
 453   PRINT_REG(rsp);
 454 #undef PRINT_REG
 455   // Print some words near top of staack.
 456   int* dump_sp = (int*) rsp;
 457   for (int col1 = 0; col1 < 8; col1++) {
 458     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 459     os::print_location(tty, *dump_sp++);
 460   }
 461   for (int row = 0; row < 16; row++) {
 462     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 463     for (int col = 0; col < 8; col++) {
 464       tty->print(" 0x%08x", *dump_sp++);
 465     }
 466     tty->cr();
 467   }
 468   // Print some instructions around pc:
 469   Disassembler::decode((address)eip-64, (address)eip);
 470   tty->print_cr("--------");
 471   Disassembler::decode((address)eip, (address)eip+32);
 472 }
 473 
 474 void MacroAssembler::stop(const char* msg) {
 475   ExternalAddress message((address)msg);
 476   // push address of message
 477   pushptr(message.addr());
 478   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 479   pusha();                                            // push registers
 480   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 481   hlt();
 482 }
 483 
 484 void MacroAssembler::warn(const char* msg) {
 485   push_CPU_state();
 486 
 487   ExternalAddress message((address) msg);
 488   // push address of message
 489   pushptr(message.addr());
 490 
 491   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 492   addl(rsp, wordSize);       // discard argument
 493   pop_CPU_state();
 494 }
 495 
 496 void MacroAssembler::print_state() {
 497   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 498   pusha();                                            // push registers
 499 
 500   push_CPU_state();
 501   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 502   pop_CPU_state();
 503 
 504   popa();
 505   addl(rsp, wordSize);
 506 }
 507 
 508 #else // _LP64
 509 
 510 // 64 bit versions
 511 
 512 Address MacroAssembler::as_Address(AddressLiteral adr) {
 513   // amd64 always does this as a pc-rel
 514   // we can be absolute or disp based on the instruction type
 515   // jmp/call are displacements others are absolute
 516   assert(!adr.is_lval(), "must be rval");
 517   assert(reachable(adr), "must be");
 518   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 519 
 520 }
 521 
 522 Address MacroAssembler::as_Address(ArrayAddress adr) {
 523   AddressLiteral base = adr.base();
 524   lea(rscratch1, base);
 525   Address index = adr.index();
 526   assert(index._disp == 0, "must not have disp"); // maybe it can?
 527   Address array(rscratch1, index._index, index._scale, index._disp);
 528   return array;
 529 }
 530 
 531 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 532   Label L, E;
 533 
 534 #ifdef _WIN64
 535   // Windows always allocates space for it's register args
 536   assert(num_args <= 4, "only register arguments supported");
 537   subq(rsp,  frame::arg_reg_save_area_bytes);
 538 #endif
 539 
 540   // Align stack if necessary
 541   testl(rsp, 15);
 542   jcc(Assembler::zero, L);
 543 
 544   subq(rsp, 8);
 545   {
 546     call(RuntimeAddress(entry_point));
 547   }
 548   addq(rsp, 8);
 549   jmp(E);
 550 
 551   bind(L);
 552   {
 553     call(RuntimeAddress(entry_point));
 554   }
 555 
 556   bind(E);
 557 
 558 #ifdef _WIN64
 559   // restore stack pointer
 560   addq(rsp, frame::arg_reg_save_area_bytes);
 561 #endif
 562 
 563 }
 564 
 565 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 566   assert(!src2.is_lval(), "should use cmpptr");
 567 
 568   if (reachable(src2)) {
 569     cmpq(src1, as_Address(src2));
 570   } else {
 571     lea(rscratch1, src2);
 572     Assembler::cmpq(src1, Address(rscratch1, 0));
 573   }
 574 }
 575 
 576 int MacroAssembler::corrected_idivq(Register reg) {
 577   // Full implementation of Java ldiv and lrem; checks for special
 578   // case as described in JVM spec., p.243 & p.271.  The function
 579   // returns the (pc) offset of the idivl instruction - may be needed
 580   // for implicit exceptions.
 581   //
 582   //         normal case                           special case
 583   //
 584   // input : rax: dividend                         min_long
 585   //         reg: divisor   (may not be eax/edx)   -1
 586   //
 587   // output: rax: quotient  (= rax idiv reg)       min_long
 588   //         rdx: remainder (= rax irem reg)       0
 589   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 590   static const int64_t min_long = 0x8000000000000000;
 591   Label normal_case, special_case;
 592 
 593   // check for special case
 594   cmp64(rax, ExternalAddress((address) &min_long));
 595   jcc(Assembler::notEqual, normal_case);
 596   xorl(rdx, rdx); // prepare rdx for possible special case (where
 597                   // remainder = 0)
 598   cmpq(reg, -1);
 599   jcc(Assembler::equal, special_case);
 600 
 601   // handle normal case
 602   bind(normal_case);
 603   cdqq();
 604   int idivq_offset = offset();
 605   idivq(reg);
 606 
 607   // normal and special case exit
 608   bind(special_case);
 609 
 610   return idivq_offset;
 611 }
 612 
 613 void MacroAssembler::decrementq(Register reg, int value) {
 614   if (value == min_jint) { subq(reg, value); return; }
 615   if (value <  0) { incrementq(reg, -value); return; }
 616   if (value == 0) {                        ; return; }
 617   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 618   /* else */      { subq(reg, value)       ; return; }
 619 }
 620 
 621 void MacroAssembler::decrementq(Address dst, int value) {
 622   if (value == min_jint) { subq(dst, value); return; }
 623   if (value <  0) { incrementq(dst, -value); return; }
 624   if (value == 0) {                        ; return; }
 625   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 626   /* else */      { subq(dst, value)       ; return; }
 627 }
 628 
 629 void MacroAssembler::incrementq(AddressLiteral dst) {
 630   if (reachable(dst)) {
 631     incrementq(as_Address(dst));
 632   } else {
 633     lea(rscratch1, dst);
 634     incrementq(Address(rscratch1, 0));
 635   }
 636 }
 637 
 638 void MacroAssembler::incrementq(Register reg, int value) {
 639   if (value == min_jint) { addq(reg, value); return; }
 640   if (value <  0) { decrementq(reg, -value); return; }
 641   if (value == 0) {                        ; return; }
 642   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 643   /* else */      { addq(reg, value)       ; return; }
 644 }
 645 
 646 void MacroAssembler::incrementq(Address dst, int value) {
 647   if (value == min_jint) { addq(dst, value); return; }
 648   if (value <  0) { decrementq(dst, -value); return; }
 649   if (value == 0) {                        ; return; }
 650   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 651   /* else */      { addq(dst, value)       ; return; }
 652 }
 653 
 654 // 32bit can do a case table jump in one instruction but we no longer allow the base
 655 // to be installed in the Address class
 656 void MacroAssembler::jump(ArrayAddress entry) {
 657   lea(rscratch1, entry.base());
 658   Address dispatch = entry.index();
 659   assert(dispatch._base == noreg, "must be");
 660   dispatch._base = rscratch1;
 661   jmp(dispatch);
 662 }
 663 
 664 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 665   ShouldNotReachHere(); // 64bit doesn't use two regs
 666   cmpq(x_lo, y_lo);
 667 }
 668 
 669 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 670     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 671 }
 672 
 673 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 674   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 675   movptr(dst, rscratch1);
 676 }
 677 
 678 void MacroAssembler::leave() {
 679   // %%% is this really better? Why not on 32bit too?
 680   emit_int8((unsigned char)0xC9); // LEAVE
 681 }
 682 
 683 void MacroAssembler::lneg(Register hi, Register lo) {
 684   ShouldNotReachHere(); // 64bit doesn't use two regs
 685   negq(lo);
 686 }
 687 
 688 void MacroAssembler::movoop(Register dst, jobject obj) {
 689   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 690 }
 691 
 692 void MacroAssembler::movoop(Address dst, jobject obj) {
 693   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 694   movq(dst, rscratch1);
 695 }
 696 
 697 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 698   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 699 }
 700 
 701 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 702   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 703   movq(dst, rscratch1);
 704 }
 705 
 706 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 707   if (src.is_lval()) {
 708     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 709   } else {
 710     if (reachable(src)) {
 711       movq(dst, as_Address(src));
 712     } else {
 713       lea(scratch, src);
 714       movq(dst, Address(scratch, 0));
 715     }
 716   }
 717 }
 718 
 719 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 720   movq(as_Address(dst), src);
 721 }
 722 
 723 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 724   movq(dst, as_Address(src));
 725 }
 726 
 727 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 728 void MacroAssembler::movptr(Address dst, intptr_t src) {
 729   mov64(rscratch1, src);
 730   movq(dst, rscratch1);
 731 }
 732 
 733 // These are mostly for initializing NULL
 734 void MacroAssembler::movptr(Address dst, int32_t src) {
 735   movslq(dst, src);
 736 }
 737 
 738 void MacroAssembler::movptr(Register dst, int32_t src) {
 739   mov64(dst, (intptr_t)src);
 740 }
 741 
 742 void MacroAssembler::pushoop(jobject obj) {
 743   movoop(rscratch1, obj);
 744   push(rscratch1);
 745 }
 746 
 747 void MacroAssembler::pushklass(Metadata* obj) {
 748   mov_metadata(rscratch1, obj);
 749   push(rscratch1);
 750 }
 751 
 752 void MacroAssembler::pushptr(AddressLiteral src) {
 753   lea(rscratch1, src);
 754   if (src.is_lval()) {
 755     push(rscratch1);
 756   } else {
 757     pushq(Address(rscratch1, 0));
 758   }
 759 }
 760 
 761 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 762   // we must set sp to zero to clear frame
 763   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 764   // must clear fp, so that compiled frames are not confused; it is
 765   // possible that we need it only for debugging
 766   if (clear_fp) {
 767     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 768   }
 769 
 770   // Always clear the pc because it could have been set by make_walkable()
 771   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 772   vzeroupper();
 773 }
 774 
 775 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 776                                          Register last_java_fp,
 777                                          address  last_java_pc) {
 778   vzeroupper();
 779   // determine last_java_sp register
 780   if (!last_java_sp->is_valid()) {
 781     last_java_sp = rsp;
 782   }
 783 
 784   // last_java_fp is optional
 785   if (last_java_fp->is_valid()) {
 786     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 787            last_java_fp);
 788   }
 789 
 790   // last_java_pc is optional
 791   if (last_java_pc != NULL) {
 792     Address java_pc(r15_thread,
 793                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 794     lea(rscratch1, InternalAddress(last_java_pc));
 795     movptr(java_pc, rscratch1);
 796   }
 797 
 798   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 799 }
 800 
 801 static void pass_arg0(MacroAssembler* masm, Register arg) {
 802   if (c_rarg0 != arg ) {
 803     masm->mov(c_rarg0, arg);
 804   }
 805 }
 806 
 807 static void pass_arg1(MacroAssembler* masm, Register arg) {
 808   if (c_rarg1 != arg ) {
 809     masm->mov(c_rarg1, arg);
 810   }
 811 }
 812 
 813 static void pass_arg2(MacroAssembler* masm, Register arg) {
 814   if (c_rarg2 != arg ) {
 815     masm->mov(c_rarg2, arg);
 816   }
 817 }
 818 
 819 static void pass_arg3(MacroAssembler* masm, Register arg) {
 820   if (c_rarg3 != arg ) {
 821     masm->mov(c_rarg3, arg);
 822   }
 823 }
 824 
 825 void MacroAssembler::stop(const char* msg) {
 826   address rip = pc();
 827   pusha(); // get regs on stack
 828   lea(c_rarg0, ExternalAddress((address) msg));
 829   lea(c_rarg1, InternalAddress(rip));
 830   movq(c_rarg2, rsp); // pass pointer to regs array
 831   andq(rsp, -16); // align stack as required by ABI
 832   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 833   hlt();
 834 }
 835 
 836 void MacroAssembler::warn(const char* msg) {
 837   push(rbp);
 838   movq(rbp, rsp);
 839   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 840   push_CPU_state();   // keeps alignment at 16 bytes
 841   lea(c_rarg0, ExternalAddress((address) msg));
 842   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 843   call(rax);
 844   pop_CPU_state();
 845   mov(rsp, rbp);
 846   pop(rbp);
 847 }
 848 
 849 void MacroAssembler::print_state() {
 850   address rip = pc();
 851   pusha();            // get regs on stack
 852   push(rbp);
 853   movq(rbp, rsp);
 854   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 855   push_CPU_state();   // keeps alignment at 16 bytes
 856 
 857   lea(c_rarg0, InternalAddress(rip));
 858   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 859   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 860 
 861   pop_CPU_state();
 862   mov(rsp, rbp);
 863   pop(rbp);
 864   popa();
 865 }
 866 
 867 #ifndef PRODUCT
 868 extern "C" void findpc(intptr_t x);
 869 #endif
 870 
 871 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 872   // In order to get locks to work, we need to fake a in_VM state
 873   if (ShowMessageBoxOnError) {
 874     JavaThread* thread = JavaThread::current();
 875     JavaThreadState saved_state = thread->thread_state();
 876     thread->set_thread_state(_thread_in_vm);
 877 #ifndef PRODUCT
 878     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 879       ttyLocker ttyl;
 880       BytecodeCounter::print();
 881     }
 882 #endif
 883     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 884     // XXX correct this offset for amd64
 885     // This is the value of eip which points to where verify_oop will return.
 886     if (os::message_box(msg, "Execution stopped, print registers?")) {
 887       print_state64(pc, regs);
 888       BREAKPOINT;
 889       assert(false, "start up GDB");
 890     }
 891     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 892   } else {
 893     ttyLocker ttyl;
 894     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 895                     msg);
 896     assert(false, "DEBUG MESSAGE: %s", msg);
 897   }
 898 }
 899 
 900 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 901   ttyLocker ttyl;
 902   FlagSetting fs(Debugging, true);
 903   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 904 #ifndef PRODUCT
 905   tty->cr();
 906   findpc(pc);
 907   tty->cr();
 908 #endif
 909 #define PRINT_REG(rax, value) \
 910   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 911   PRINT_REG(rax, regs[15]);
 912   PRINT_REG(rbx, regs[12]);
 913   PRINT_REG(rcx, regs[14]);
 914   PRINT_REG(rdx, regs[13]);
 915   PRINT_REG(rdi, regs[8]);
 916   PRINT_REG(rsi, regs[9]);
 917   PRINT_REG(rbp, regs[10]);
 918   PRINT_REG(rsp, regs[11]);
 919   PRINT_REG(r8 , regs[7]);
 920   PRINT_REG(r9 , regs[6]);
 921   PRINT_REG(r10, regs[5]);
 922   PRINT_REG(r11, regs[4]);
 923   PRINT_REG(r12, regs[3]);
 924   PRINT_REG(r13, regs[2]);
 925   PRINT_REG(r14, regs[1]);
 926   PRINT_REG(r15, regs[0]);
 927 #undef PRINT_REG
 928   // Print some words near top of staack.
 929   int64_t* rsp = (int64_t*) regs[11];
 930   int64_t* dump_sp = rsp;
 931   for (int col1 = 0; col1 < 8; col1++) {
 932     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 933     os::print_location(tty, *dump_sp++);
 934   }
 935   for (int row = 0; row < 25; row++) {
 936     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 937     for (int col = 0; col < 4; col++) {
 938       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 939     }
 940     tty->cr();
 941   }
 942   // Print some instructions around pc:
 943   Disassembler::decode((address)pc-64, (address)pc);
 944   tty->print_cr("--------");
 945   Disassembler::decode((address)pc, (address)pc+32);
 946 }
 947 
 948 #endif // _LP64
 949 
 950 // Now versions that are common to 32/64 bit
 951 
 952 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 953   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 954 }
 955 
 956 void MacroAssembler::addptr(Register dst, Register src) {
 957   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 958 }
 959 
 960 void MacroAssembler::addptr(Address dst, Register src) {
 961   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 962 }
 963 
 964 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 965   if (reachable(src)) {
 966     Assembler::addsd(dst, as_Address(src));
 967   } else {
 968     lea(rscratch1, src);
 969     Assembler::addsd(dst, Address(rscratch1, 0));
 970   }
 971 }
 972 
 973 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 974   if (reachable(src)) {
 975     addss(dst, as_Address(src));
 976   } else {
 977     lea(rscratch1, src);
 978     addss(dst, Address(rscratch1, 0));
 979   }
 980 }
 981 
 982 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 983   if (reachable(src)) {
 984     Assembler::addpd(dst, as_Address(src));
 985   } else {
 986     lea(rscratch1, src);
 987     Assembler::addpd(dst, Address(rscratch1, 0));
 988   }
 989 }
 990 
 991 void MacroAssembler::align(int modulus) {
 992   align(modulus, offset());
 993 }
 994 
 995 void MacroAssembler::align(int modulus, int target) {
 996   if (target % modulus != 0) {
 997     nop(modulus - (target % modulus));
 998   }
 999 }
1000 
1001 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1002   // Used in sign-masking with aligned address.
1003   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1004   if (reachable(src)) {
1005     Assembler::andpd(dst, as_Address(src));
1006   } else {
1007     lea(rscratch1, src);
1008     Assembler::andpd(dst, Address(rscratch1, 0));
1009   }
1010 }
1011 
1012 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1013   // Used in sign-masking with aligned address.
1014   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1015   if (reachable(src)) {
1016     Assembler::andps(dst, as_Address(src));
1017   } else {
1018     lea(rscratch1, src);
1019     Assembler::andps(dst, Address(rscratch1, 0));
1020   }
1021 }
1022 
1023 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1024   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1025 }
1026 
1027 void MacroAssembler::atomic_incl(Address counter_addr) {
1028   if (os::is_MP())
1029     lock();
1030   incrementl(counter_addr);
1031 }
1032 
1033 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1034   if (reachable(counter_addr)) {
1035     atomic_incl(as_Address(counter_addr));
1036   } else {
1037     lea(scr, counter_addr);
1038     atomic_incl(Address(scr, 0));
1039   }
1040 }
1041 
1042 #ifdef _LP64
1043 void MacroAssembler::atomic_incq(Address counter_addr) {
1044   if (os::is_MP())
1045     lock();
1046   incrementq(counter_addr);
1047 }
1048 
1049 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1050   if (reachable(counter_addr)) {
1051     atomic_incq(as_Address(counter_addr));
1052   } else {
1053     lea(scr, counter_addr);
1054     atomic_incq(Address(scr, 0));
1055   }
1056 }
1057 #endif
1058 
1059 // Writes to stack successive pages until offset reached to check for
1060 // stack overflow + shadow pages.  This clobbers tmp.
1061 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1062   movptr(tmp, rsp);
1063   // Bang stack for total size given plus shadow page size.
1064   // Bang one page at a time because large size can bang beyond yellow and
1065   // red zones.
1066   Label loop;
1067   bind(loop);
1068   movl(Address(tmp, (-os::vm_page_size())), size );
1069   subptr(tmp, os::vm_page_size());
1070   subl(size, os::vm_page_size());
1071   jcc(Assembler::greater, loop);
1072 
1073   // Bang down shadow pages too.
1074   // At this point, (tmp-0) is the last address touched, so don't
1075   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1076   // was post-decremented.)  Skip this address by starting at i=1, and
1077   // touch a few more pages below.  N.B.  It is important to touch all
1078   // the way down including all pages in the shadow zone.
1079   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1080     // this could be any sized move but this is can be a debugging crumb
1081     // so the bigger the better.
1082     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1083   }
1084 }
1085 
1086 void MacroAssembler::reserved_stack_check() {
1087     // testing if reserved zone needs to be enabled
1088     Label no_reserved_zone_enabling;
1089     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1090     NOT_LP64(get_thread(rsi);)
1091 
1092     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1093     jcc(Assembler::below, no_reserved_zone_enabling);
1094 
1095     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1096     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1097     should_not_reach_here();
1098 
1099     bind(no_reserved_zone_enabling);
1100 }
1101 
1102 int MacroAssembler::biased_locking_enter(Register lock_reg,
1103                                          Register obj_reg,
1104                                          Register swap_reg,
1105                                          Register tmp_reg,
1106                                          bool swap_reg_contains_mark,
1107                                          Label& done,
1108                                          Label* slow_case,
1109                                          BiasedLockingCounters* counters) {
1110   assert(UseBiasedLocking, "why call this otherwise?");
1111   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1112   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1113   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1114   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1115   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1116   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1117 
1118   if (PrintBiasedLockingStatistics && counters == NULL) {
1119     counters = BiasedLocking::counters();
1120   }
1121   // Biased locking
1122   // See whether the lock is currently biased toward our thread and
1123   // whether the epoch is still valid
1124   // Note that the runtime guarantees sufficient alignment of JavaThread
1125   // pointers to allow age to be placed into low bits
1126   // First check to see whether biasing is even enabled for this object
1127   Label cas_label;
1128   int null_check_offset = -1;
1129   if (!swap_reg_contains_mark) {
1130     null_check_offset = offset();
1131     movptr(swap_reg, mark_addr);
1132   }
1133   movptr(tmp_reg, swap_reg);
1134   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1135   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1136   jcc(Assembler::notEqual, cas_label);
1137   // The bias pattern is present in the object's header. Need to check
1138   // whether the bias owner and the epoch are both still current.
1139 #ifndef _LP64
1140   // Note that because there is no current thread register on x86_32 we
1141   // need to store off the mark word we read out of the object to
1142   // avoid reloading it and needing to recheck invariants below. This
1143   // store is unfortunate but it makes the overall code shorter and
1144   // simpler.
1145   movptr(saved_mark_addr, swap_reg);
1146 #endif
1147   if (swap_reg_contains_mark) {
1148     null_check_offset = offset();
1149   }
1150   load_prototype_header(tmp_reg, obj_reg);
1151 #ifdef _LP64
1152   orptr(tmp_reg, r15_thread);
1153   xorptr(tmp_reg, swap_reg);
1154   Register header_reg = tmp_reg;
1155 #else
1156   xorptr(tmp_reg, swap_reg);
1157   get_thread(swap_reg);
1158   xorptr(swap_reg, tmp_reg);
1159   Register header_reg = swap_reg;
1160 #endif
1161   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1162   if (counters != NULL) {
1163     cond_inc32(Assembler::zero,
1164                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1165   }
1166   jcc(Assembler::equal, done);
1167 
1168   Label try_revoke_bias;
1169   Label try_rebias;
1170 
1171   // At this point we know that the header has the bias pattern and
1172   // that we are not the bias owner in the current epoch. We need to
1173   // figure out more details about the state of the header in order to
1174   // know what operations can be legally performed on the object's
1175   // header.
1176 
1177   // If the low three bits in the xor result aren't clear, that means
1178   // the prototype header is no longer biased and we have to revoke
1179   // the bias on this object.
1180   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1181   jccb(Assembler::notZero, try_revoke_bias);
1182 
1183   // Biasing is still enabled for this data type. See whether the
1184   // epoch of the current bias is still valid, meaning that the epoch
1185   // bits of the mark word are equal to the epoch bits of the
1186   // prototype header. (Note that the prototype header's epoch bits
1187   // only change at a safepoint.) If not, attempt to rebias the object
1188   // toward the current thread. Note that we must be absolutely sure
1189   // that the current epoch is invalid in order to do this because
1190   // otherwise the manipulations it performs on the mark word are
1191   // illegal.
1192   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1193   jccb(Assembler::notZero, try_rebias);
1194 
1195   // The epoch of the current bias is still valid but we know nothing
1196   // about the owner; it might be set or it might be clear. Try to
1197   // acquire the bias of the object using an atomic operation. If this
1198   // fails we will go in to the runtime to revoke the object's bias.
1199   // Note that we first construct the presumed unbiased header so we
1200   // don't accidentally blow away another thread's valid bias.
1201   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1202   andptr(swap_reg,
1203          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1204 #ifdef _LP64
1205   movptr(tmp_reg, swap_reg);
1206   orptr(tmp_reg, r15_thread);
1207 #else
1208   get_thread(tmp_reg);
1209   orptr(tmp_reg, swap_reg);
1210 #endif
1211   if (os::is_MP()) {
1212     lock();
1213   }
1214   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1215   // If the biasing toward our thread failed, this means that
1216   // another thread succeeded in biasing it toward itself and we
1217   // need to revoke that bias. The revocation will occur in the
1218   // interpreter runtime in the slow case.
1219   if (counters != NULL) {
1220     cond_inc32(Assembler::zero,
1221                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1222   }
1223   if (slow_case != NULL) {
1224     jcc(Assembler::notZero, *slow_case);
1225   }
1226   jmp(done);
1227 
1228   bind(try_rebias);
1229   // At this point we know the epoch has expired, meaning that the
1230   // current "bias owner", if any, is actually invalid. Under these
1231   // circumstances _only_, we are allowed to use the current header's
1232   // value as the comparison value when doing the cas to acquire the
1233   // bias in the current epoch. In other words, we allow transfer of
1234   // the bias from one thread to another directly in this situation.
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   load_prototype_header(tmp_reg, obj_reg);
1239 #ifdef _LP64
1240   orptr(tmp_reg, r15_thread);
1241 #else
1242   get_thread(swap_reg);
1243   orptr(tmp_reg, swap_reg);
1244   movptr(swap_reg, saved_mark_addr);
1245 #endif
1246   if (os::is_MP()) {
1247     lock();
1248   }
1249   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1250   // If the biasing toward our thread failed, then another thread
1251   // succeeded in biasing it toward itself and we need to revoke that
1252   // bias. The revocation will occur in the runtime in the slow case.
1253   if (counters != NULL) {
1254     cond_inc32(Assembler::zero,
1255                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1256   }
1257   if (slow_case != NULL) {
1258     jcc(Assembler::notZero, *slow_case);
1259   }
1260   jmp(done);
1261 
1262   bind(try_revoke_bias);
1263   // The prototype mark in the klass doesn't have the bias bit set any
1264   // more, indicating that objects of this data type are not supposed
1265   // to be biased any more. We are going to try to reset the mark of
1266   // this object to the prototype value and fall through to the
1267   // CAS-based locking scheme. Note that if our CAS fails, it means
1268   // that another thread raced us for the privilege of revoking the
1269   // bias of this particular object, so it's okay to continue in the
1270   // normal locking code.
1271   //
1272   // FIXME: due to a lack of registers we currently blow away the age
1273   // bits in this situation. Should attempt to preserve them.
1274   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1275   load_prototype_header(tmp_reg, obj_reg);
1276   if (os::is_MP()) {
1277     lock();
1278   }
1279   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1280   // Fall through to the normal CAS-based lock, because no matter what
1281   // the result of the above CAS, some thread must have succeeded in
1282   // removing the bias bit from the object's header.
1283   if (counters != NULL) {
1284     cond_inc32(Assembler::zero,
1285                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1286   }
1287 
1288   bind(cas_label);
1289 
1290   return null_check_offset;
1291 }
1292 
1293 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1294   assert(UseBiasedLocking, "why call this otherwise?");
1295 
1296   // Check for biased locking unlock case, which is a no-op
1297   // Note: we do not have to check the thread ID for two reasons.
1298   // First, the interpreter checks for IllegalMonitorStateException at
1299   // a higher level. Second, if the bias was revoked while we held the
1300   // lock, the object could not be rebiased toward another thread, so
1301   // the bias bit would be clear.
1302   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1303   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1304   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1305   jcc(Assembler::equal, done);
1306 }
1307 
1308 #ifdef COMPILER2
1309 
1310 #if INCLUDE_RTM_OPT
1311 
1312 // Update rtm_counters based on abort status
1313 // input: abort_status
1314 //        rtm_counters (RTMLockingCounters*)
1315 // flags are killed
1316 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1317 
1318   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1319   if (PrintPreciseRTMLockingStatistics) {
1320     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1321       Label check_abort;
1322       testl(abort_status, (1<<i));
1323       jccb(Assembler::equal, check_abort);
1324       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1325       bind(check_abort);
1326     }
1327   }
1328 }
1329 
1330 // Branch if (random & (count-1) != 0), count is 2^n
1331 // tmp, scr and flags are killed
1332 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1333   assert(tmp == rax, "");
1334   assert(scr == rdx, "");
1335   rdtsc(); // modifies EDX:EAX
1336   andptr(tmp, count-1);
1337   jccb(Assembler::notZero, brLabel);
1338 }
1339 
1340 // Perform abort ratio calculation, set no_rtm bit if high ratio
1341 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1342 // tmpReg, rtm_counters_Reg and flags are killed
1343 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1344                                                  Register rtm_counters_Reg,
1345                                                  RTMLockingCounters* rtm_counters,
1346                                                  Metadata* method_data) {
1347   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1348 
1349   if (RTMLockingCalculationDelay > 0) {
1350     // Delay calculation
1351     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1352     testptr(tmpReg, tmpReg);
1353     jccb(Assembler::equal, L_done);
1354   }
1355   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1356   //   Aborted transactions = abort_count * 100
1357   //   All transactions = total_count *  RTMTotalCountIncrRate
1358   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1359 
1360   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1361   cmpptr(tmpReg, RTMAbortThreshold);
1362   jccb(Assembler::below, L_check_always_rtm2);
1363   imulptr(tmpReg, tmpReg, 100);
1364 
1365   Register scrReg = rtm_counters_Reg;
1366   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1367   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1368   imulptr(scrReg, scrReg, RTMAbortRatio);
1369   cmpptr(tmpReg, scrReg);
1370   jccb(Assembler::below, L_check_always_rtm1);
1371   if (method_data != NULL) {
1372     // set rtm_state to "no rtm" in MDO
1373     mov_metadata(tmpReg, method_data);
1374     if (os::is_MP()) {
1375       lock();
1376     }
1377     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1378   }
1379   jmpb(L_done);
1380   bind(L_check_always_rtm1);
1381   // Reload RTMLockingCounters* address
1382   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1383   bind(L_check_always_rtm2);
1384   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1385   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1386   jccb(Assembler::below, L_done);
1387   if (method_data != NULL) {
1388     // set rtm_state to "always rtm" in MDO
1389     mov_metadata(tmpReg, method_data);
1390     if (os::is_MP()) {
1391       lock();
1392     }
1393     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1394   }
1395   bind(L_done);
1396 }
1397 
1398 // Update counters and perform abort ratio calculation
1399 // input:  abort_status_Reg
1400 // rtm_counters_Reg, flags are killed
1401 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1402                                    Register rtm_counters_Reg,
1403                                    RTMLockingCounters* rtm_counters,
1404                                    Metadata* method_data,
1405                                    bool profile_rtm) {
1406 
1407   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1408   // update rtm counters based on rax value at abort
1409   // reads abort_status_Reg, updates flags
1410   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1411   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1412   if (profile_rtm) {
1413     // Save abort status because abort_status_Reg is used by following code.
1414     if (RTMRetryCount > 0) {
1415       push(abort_status_Reg);
1416     }
1417     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1418     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1419     // restore abort status
1420     if (RTMRetryCount > 0) {
1421       pop(abort_status_Reg);
1422     }
1423   }
1424 }
1425 
1426 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1427 // inputs: retry_count_Reg
1428 //       : abort_status_Reg
1429 // output: retry_count_Reg decremented by 1
1430 // flags are killed
1431 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1432   Label doneRetry;
1433   assert(abort_status_Reg == rax, "");
1434   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1435   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1436   // if reason is in 0x6 and retry count != 0 then retry
1437   andptr(abort_status_Reg, 0x6);
1438   jccb(Assembler::zero, doneRetry);
1439   testl(retry_count_Reg, retry_count_Reg);
1440   jccb(Assembler::zero, doneRetry);
1441   pause();
1442   decrementl(retry_count_Reg);
1443   jmp(retryLabel);
1444   bind(doneRetry);
1445 }
1446 
1447 // Spin and retry if lock is busy,
1448 // inputs: box_Reg (monitor address)
1449 //       : retry_count_Reg
1450 // output: retry_count_Reg decremented by 1
1451 //       : clear z flag if retry count exceeded
1452 // tmp_Reg, scr_Reg, flags are killed
1453 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1454                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1455   Label SpinLoop, SpinExit, doneRetry;
1456   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1457 
1458   testl(retry_count_Reg, retry_count_Reg);
1459   jccb(Assembler::zero, doneRetry);
1460   decrementl(retry_count_Reg);
1461   movptr(scr_Reg, RTMSpinLoopCount);
1462 
1463   bind(SpinLoop);
1464   pause();
1465   decrementl(scr_Reg);
1466   jccb(Assembler::lessEqual, SpinExit);
1467   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1468   testptr(tmp_Reg, tmp_Reg);
1469   jccb(Assembler::notZero, SpinLoop);
1470 
1471   bind(SpinExit);
1472   jmp(retryLabel);
1473   bind(doneRetry);
1474   incrementl(retry_count_Reg); // clear z flag
1475 }
1476 
1477 // Use RTM for normal stack locks
1478 // Input: objReg (object to lock)
1479 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1480                                        Register retry_on_abort_count_Reg,
1481                                        RTMLockingCounters* stack_rtm_counters,
1482                                        Metadata* method_data, bool profile_rtm,
1483                                        Label& DONE_LABEL, Label& IsInflated) {
1484   assert(UseRTMForStackLocks, "why call this otherwise?");
1485   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1486   assert(tmpReg == rax, "");
1487   assert(scrReg == rdx, "");
1488   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1489 
1490   if (RTMRetryCount > 0) {
1491     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1492     bind(L_rtm_retry);
1493   }
1494   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1495   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1496   jcc(Assembler::notZero, IsInflated);
1497 
1498   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1499     Label L_noincrement;
1500     if (RTMTotalCountIncrRate > 1) {
1501       // tmpReg, scrReg and flags are killed
1502       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1503     }
1504     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1505     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1506     bind(L_noincrement);
1507   }
1508   xbegin(L_on_abort);
1509   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1510   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1511   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1512   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1513 
1514   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1515   if (UseRTMXendForLockBusy) {
1516     xend();
1517     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1518     jmp(L_decrement_retry);
1519   }
1520   else {
1521     xabort(0);
1522   }
1523   bind(L_on_abort);
1524   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1525     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1526   }
1527   bind(L_decrement_retry);
1528   if (RTMRetryCount > 0) {
1529     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1530     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1531   }
1532 }
1533 
1534 // Use RTM for inflating locks
1535 // inputs: objReg (object to lock)
1536 //         boxReg (on-stack box address (displaced header location) - KILLED)
1537 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1538 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1539                                           Register scrReg, Register retry_on_busy_count_Reg,
1540                                           Register retry_on_abort_count_Reg,
1541                                           RTMLockingCounters* rtm_counters,
1542                                           Metadata* method_data, bool profile_rtm,
1543                                           Label& DONE_LABEL) {
1544   assert(UseRTMLocking, "why call this otherwise?");
1545   assert(tmpReg == rax, "");
1546   assert(scrReg == rdx, "");
1547   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1548   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1549 
1550   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1551   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1552   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1553 
1554   if (RTMRetryCount > 0) {
1555     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1556     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1557     bind(L_rtm_retry);
1558   }
1559   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1560     Label L_noincrement;
1561     if (RTMTotalCountIncrRate > 1) {
1562       // tmpReg, scrReg and flags are killed
1563       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1564     }
1565     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1566     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1567     bind(L_noincrement);
1568   }
1569   xbegin(L_on_abort);
1570   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1571   movptr(tmpReg, Address(tmpReg, owner_offset));
1572   testptr(tmpReg, tmpReg);
1573   jcc(Assembler::zero, DONE_LABEL);
1574   if (UseRTMXendForLockBusy) {
1575     xend();
1576     jmp(L_decrement_retry);
1577   }
1578   else {
1579     xabort(0);
1580   }
1581   bind(L_on_abort);
1582   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1583   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1584     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1585   }
1586   if (RTMRetryCount > 0) {
1587     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1588     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1589   }
1590 
1591   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1592   testptr(tmpReg, tmpReg) ;
1593   jccb(Assembler::notZero, L_decrement_retry) ;
1594 
1595   // Appears unlocked - try to swing _owner from null to non-null.
1596   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1597 #ifdef _LP64
1598   Register threadReg = r15_thread;
1599 #else
1600   get_thread(scrReg);
1601   Register threadReg = scrReg;
1602 #endif
1603   if (os::is_MP()) {
1604     lock();
1605   }
1606   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1607 
1608   if (RTMRetryCount > 0) {
1609     // success done else retry
1610     jccb(Assembler::equal, DONE_LABEL) ;
1611     bind(L_decrement_retry);
1612     // Spin and retry if lock is busy.
1613     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1614   }
1615   else {
1616     bind(L_decrement_retry);
1617   }
1618 }
1619 
1620 #endif //  INCLUDE_RTM_OPT
1621 
1622 // Fast_Lock and Fast_Unlock used by C2
1623 
1624 // Because the transitions from emitted code to the runtime
1625 // monitorenter/exit helper stubs are so slow it's critical that
1626 // we inline both the stack-locking fast-path and the inflated fast path.
1627 //
1628 // See also: cmpFastLock and cmpFastUnlock.
1629 //
1630 // What follows is a specialized inline transliteration of the code
1631 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1632 // another option would be to emit TrySlowEnter and TrySlowExit methods
1633 // at startup-time.  These methods would accept arguments as
1634 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1635 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1636 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1637 // In practice, however, the # of lock sites is bounded and is usually small.
1638 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1639 // if the processor uses simple bimodal branch predictors keyed by EIP
1640 // Since the helper routines would be called from multiple synchronization
1641 // sites.
1642 //
1643 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1644 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1645 // to those specialized methods.  That'd give us a mostly platform-independent
1646 // implementation that the JITs could optimize and inline at their pleasure.
1647 // Done correctly, the only time we'd need to cross to native could would be
1648 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1649 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1650 // (b) explicit barriers or fence operations.
1651 //
1652 // TODO:
1653 //
1654 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1655 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1656 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1657 //    the lock operators would typically be faster than reifying Self.
1658 //
1659 // *  Ideally I'd define the primitives as:
1660 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1661 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1662 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1663 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1664 //    Furthermore the register assignments are overconstrained, possibly resulting in
1665 //    sub-optimal code near the synchronization site.
1666 //
1667 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1668 //    Alternately, use a better sp-proximity test.
1669 //
1670 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1671 //    Either one is sufficient to uniquely identify a thread.
1672 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1673 //
1674 // *  Intrinsify notify() and notifyAll() for the common cases where the
1675 //    object is locked by the calling thread but the waitlist is empty.
1676 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1677 //
1678 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1679 //    But beware of excessive branch density on AMD Opterons.
1680 //
1681 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1682 //    or failure of the fast-path.  If the fast-path fails then we pass
1683 //    control to the slow-path, typically in C.  In Fast_Lock and
1684 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1685 //    will emit a conditional branch immediately after the node.
1686 //    So we have branches to branches and lots of ICC.ZF games.
1687 //    Instead, it might be better to have C2 pass a "FailureLabel"
1688 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1689 //    will drop through the node.  ICC.ZF is undefined at exit.
1690 //    In the case of failure, the node will branch directly to the
1691 //    FailureLabel
1692 
1693 
1694 // obj: object to lock
1695 // box: on-stack box address (displaced header location) - KILLED
1696 // rax,: tmp -- KILLED
1697 // scr: tmp -- KILLED
1698 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1699                                Register scrReg, Register cx1Reg, Register cx2Reg,
1700                                BiasedLockingCounters* counters,
1701                                RTMLockingCounters* rtm_counters,
1702                                RTMLockingCounters* stack_rtm_counters,
1703                                Metadata* method_data,
1704                                bool use_rtm, bool profile_rtm) {
1705   // Ensure the register assignments are disjoint
1706   assert(tmpReg == rax, "");
1707 
1708   if (use_rtm) {
1709     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1710   } else {
1711     assert(cx1Reg == noreg, "");
1712     assert(cx2Reg == noreg, "");
1713     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1714   }
1715 
1716   if (counters != NULL) {
1717     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1718   }
1719   if (EmitSync & 1) {
1720       // set box->dhw = markOopDesc::unused_mark()
1721       // Force all sync thru slow-path: slow_enter() and slow_exit()
1722       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1723       cmpptr (rsp, (int32_t)NULL_WORD);
1724   } else {
1725     // Possible cases that we'll encounter in fast_lock
1726     // ------------------------------------------------
1727     // * Inflated
1728     //    -- unlocked
1729     //    -- Locked
1730     //       = by self
1731     //       = by other
1732     // * biased
1733     //    -- by Self
1734     //    -- by other
1735     // * neutral
1736     // * stack-locked
1737     //    -- by self
1738     //       = sp-proximity test hits
1739     //       = sp-proximity test generates false-negative
1740     //    -- by other
1741     //
1742 
1743     Label IsInflated, DONE_LABEL;
1744 
1745     // it's stack-locked, biased or neutral
1746     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1747     // order to reduce the number of conditional branches in the most common cases.
1748     // Beware -- there's a subtle invariant that fetch of the markword
1749     // at [FETCH], below, will never observe a biased encoding (*101b).
1750     // If this invariant is not held we risk exclusion (safety) failure.
1751     if (UseBiasedLocking && !UseOptoBiasInlining) {
1752       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1753     }
1754 
1755 #if INCLUDE_RTM_OPT
1756     if (UseRTMForStackLocks && use_rtm) {
1757       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1758                         stack_rtm_counters, method_data, profile_rtm,
1759                         DONE_LABEL, IsInflated);
1760     }
1761 #endif // INCLUDE_RTM_OPT
1762 
1763     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1764     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1765     jccb(Assembler::notZero, IsInflated);
1766 
1767     // Attempt stack-locking ...
1768     orptr (tmpReg, markOopDesc::unlocked_value);
1769     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1770     if (os::is_MP()) {
1771       lock();
1772     }
1773     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1774     if (counters != NULL) {
1775       cond_inc32(Assembler::equal,
1776                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1777     }
1778     jcc(Assembler::equal, DONE_LABEL);           // Success
1779 
1780     // Recursive locking.
1781     // The object is stack-locked: markword contains stack pointer to BasicLock.
1782     // Locked by current thread if difference with current SP is less than one page.
1783     subptr(tmpReg, rsp);
1784     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1785     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1786     movptr(Address(boxReg, 0), tmpReg);
1787     if (counters != NULL) {
1788       cond_inc32(Assembler::equal,
1789                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1790     }
1791     jmp(DONE_LABEL);
1792 
1793     bind(IsInflated);
1794     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1795 
1796 #if INCLUDE_RTM_OPT
1797     // Use the same RTM locking code in 32- and 64-bit VM.
1798     if (use_rtm) {
1799       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1800                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1801     } else {
1802 #endif // INCLUDE_RTM_OPT
1803 
1804 #ifndef _LP64
1805     // The object is inflated.
1806 
1807     // boxReg refers to the on-stack BasicLock in the current frame.
1808     // We'd like to write:
1809     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1810     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1811     // additional latency as we have another ST in the store buffer that must drain.
1812 
1813     if (EmitSync & 8192) {
1814        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1815        get_thread (scrReg);
1816        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1817        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1818        if (os::is_MP()) {
1819          lock();
1820        }
1821        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1822     } else
1823     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1824        // register juggle because we need tmpReg for cmpxchgptr below
1825        movptr(scrReg, boxReg);
1826        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1827 
1828        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1829        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1830           // prefetchw [eax + Offset(_owner)-2]
1831           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1832        }
1833 
1834        if ((EmitSync & 64) == 0) {
1835          // Optimistic form: consider XORL tmpReg,tmpReg
1836          movptr(tmpReg, NULL_WORD);
1837        } else {
1838          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1839          // Test-And-CAS instead of CAS
1840          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1841          testptr(tmpReg, tmpReg);                   // Locked ?
1842          jccb  (Assembler::notZero, DONE_LABEL);
1843        }
1844 
1845        // Appears unlocked - try to swing _owner from null to non-null.
1846        // Ideally, I'd manifest "Self" with get_thread and then attempt
1847        // to CAS the register containing Self into m->Owner.
1848        // But we don't have enough registers, so instead we can either try to CAS
1849        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1850        // we later store "Self" into m->Owner.  Transiently storing a stack address
1851        // (rsp or the address of the box) into  m->owner is harmless.
1852        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1853        if (os::is_MP()) {
1854          lock();
1855        }
1856        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1857        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1858        // If we weren't able to swing _owner from NULL to the BasicLock
1859        // then take the slow path.
1860        jccb  (Assembler::notZero, DONE_LABEL);
1861        // update _owner from BasicLock to thread
1862        get_thread (scrReg);                    // beware: clobbers ICCs
1863        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1864        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
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     } else {
1874        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1875        movptr(boxReg, tmpReg);
1876 
1877        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1878        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1879           // prefetchw [eax + Offset(_owner)-2]
1880           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1881        }
1882 
1883        if ((EmitSync & 64) == 0) {
1884          // Optimistic form
1885          xorptr  (tmpReg, tmpReg);
1886        } else {
1887          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1888          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1889          testptr(tmpReg, tmpReg);                   // Locked ?
1890          jccb  (Assembler::notZero, DONE_LABEL);
1891        }
1892 
1893        // Appears unlocked - try to swing _owner from null to non-null.
1894        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1895        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1896        get_thread (scrReg);
1897        if (os::is_MP()) {
1898          lock();
1899        }
1900        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1901 
1902        // If the CAS fails we can either retry or pass control to the slow-path.
1903        // We use the latter tactic.
1904        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1905        // If the CAS was successful ...
1906        //   Self has acquired the lock
1907        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1908        // Intentional fall-through into DONE_LABEL ...
1909     }
1910 #else // _LP64
1911     // It's inflated
1912     movq(scrReg, tmpReg);
1913     xorq(tmpReg, tmpReg);
1914 
1915     if (os::is_MP()) {
1916       lock();
1917     }
1918     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1919     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1920     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1921     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1922     // Intentional fall-through into DONE_LABEL ...
1923     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1924 #endif // _LP64
1925 #if INCLUDE_RTM_OPT
1926     } // use_rtm()
1927 #endif
1928     // DONE_LABEL is a hot target - we'd really like to place it at the
1929     // start of cache line by padding with NOPs.
1930     // See the AMD and Intel software optimization manuals for the
1931     // most efficient "long" NOP encodings.
1932     // Unfortunately none of our alignment mechanisms suffice.
1933     bind(DONE_LABEL);
1934 
1935     // At DONE_LABEL the icc ZFlag is set as follows ...
1936     // Fast_Unlock uses the same protocol.
1937     // ZFlag == 1 -> Success
1938     // ZFlag == 0 -> Failure - force control through the slow-path
1939   }
1940 }
1941 
1942 // obj: object to unlock
1943 // box: box address (displaced header location), killed.  Must be EAX.
1944 // tmp: killed, cannot be obj nor box.
1945 //
1946 // Some commentary on balanced locking:
1947 //
1948 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1949 // Methods that don't have provably balanced locking are forced to run in the
1950 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1951 // The interpreter provides two properties:
1952 // I1:  At return-time the interpreter automatically and quietly unlocks any
1953 //      objects acquired the current activation (frame).  Recall that the
1954 //      interpreter maintains an on-stack list of locks currently held by
1955 //      a frame.
1956 // I2:  If a method attempts to unlock an object that is not held by the
1957 //      the frame the interpreter throws IMSX.
1958 //
1959 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1960 // B() doesn't have provably balanced locking so it runs in the interpreter.
1961 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1962 // is still locked by A().
1963 //
1964 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1965 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1966 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1967 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1968 // Arguably given that the spec legislates the JNI case as undefined our implementation
1969 // could reasonably *avoid* checking owner in Fast_Unlock().
1970 // In the interest of performance we elide m->Owner==Self check in unlock.
1971 // A perfectly viable alternative is to elide the owner check except when
1972 // Xcheck:jni is enabled.
1973 
1974 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1975   assert(boxReg == rax, "");
1976   assert_different_registers(objReg, boxReg, tmpReg);
1977 
1978   if (EmitSync & 4) {
1979     // Disable - inhibit all inlining.  Force control through the slow-path
1980     cmpptr (rsp, 0);
1981   } else {
1982     Label DONE_LABEL, Stacked, CheckSucc;
1983 
1984     // Critically, the biased locking test must have precedence over
1985     // and appear before the (box->dhw == 0) recursive stack-lock test.
1986     if (UseBiasedLocking && !UseOptoBiasInlining) {
1987        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1988     }
1989 
1990 #if INCLUDE_RTM_OPT
1991     if (UseRTMForStackLocks && use_rtm) {
1992       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1993       Label L_regular_unlock;
1994       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1995       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1996       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1997       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1998       xend();                                       // otherwise end...
1999       jmp(DONE_LABEL);                              // ... and we're done
2000       bind(L_regular_unlock);
2001     }
2002 #endif
2003 
2004     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2005     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2006     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2007     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2008     jccb  (Assembler::zero, Stacked);
2009 
2010     // It's inflated.
2011 #if INCLUDE_RTM_OPT
2012     if (use_rtm) {
2013       Label L_regular_inflated_unlock;
2014       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2015       movptr(boxReg, Address(tmpReg, owner_offset));
2016       testptr(boxReg, boxReg);
2017       jccb(Assembler::notZero, L_regular_inflated_unlock);
2018       xend();
2019       jmpb(DONE_LABEL);
2020       bind(L_regular_inflated_unlock);
2021     }
2022 #endif
2023 
2024     // Despite our balanced locking property we still check that m->_owner == Self
2025     // as java routines or native JNI code called by this thread might
2026     // have released the lock.
2027     // Refer to the comments in synchronizer.cpp for how we might encode extra
2028     // state in _succ so we can avoid fetching EntryList|cxq.
2029     //
2030     // I'd like to add more cases in fast_lock() and fast_unlock() --
2031     // such as recursive enter and exit -- but we have to be wary of
2032     // I$ bloat, T$ effects and BP$ effects.
2033     //
2034     // If there's no contention try a 1-0 exit.  That is, exit without
2035     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2036     // we detect and recover from the race that the 1-0 exit admits.
2037     //
2038     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2039     // before it STs null into _owner, releasing the lock.  Updates
2040     // to data protected by the critical section must be visible before
2041     // we drop the lock (and thus before any other thread could acquire
2042     // the lock and observe the fields protected by the lock).
2043     // IA32's memory-model is SPO, so STs are ordered with respect to
2044     // each other and there's no need for an explicit barrier (fence).
2045     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2046 #ifndef _LP64
2047     get_thread (boxReg);
2048     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2049       // prefetchw [ebx + Offset(_owner)-2]
2050       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2051     }
2052 
2053     // Note that we could employ various encoding schemes to reduce
2054     // the number of loads below (currently 4) to just 2 or 3.
2055     // Refer to the comments in synchronizer.cpp.
2056     // In practice the chain of fetches doesn't seem to impact performance, however.
2057     xorptr(boxReg, boxReg);
2058     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2059        // Attempt to reduce branch density - AMD's branch predictor.
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2061        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2062        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2063        jccb  (Assembler::notZero, DONE_LABEL);
2064        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2065        jmpb  (DONE_LABEL);
2066     } else {
2067        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2068        jccb  (Assembler::notZero, DONE_LABEL);
2069        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2070        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2071        jccb  (Assembler::notZero, CheckSucc);
2072        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2073        jmpb  (DONE_LABEL);
2074     }
2075 
2076     // The Following code fragment (EmitSync & 65536) improves the performance of
2077     // contended applications and contended synchronization microbenchmarks.
2078     // Unfortunately the emission of the code - even though not executed - causes regressions
2079     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2080     // with an equal number of never-executed NOPs results in the same regression.
2081     // We leave it off by default.
2082 
2083     if ((EmitSync & 65536) != 0) {
2084        Label LSuccess, LGoSlowPath ;
2085 
2086        bind  (CheckSucc);
2087 
2088        // Optional pre-test ... it's safe to elide this
2089        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2090        jccb(Assembler::zero, LGoSlowPath);
2091 
2092        // We have a classic Dekker-style idiom:
2093        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2094        // There are a number of ways to implement the barrier:
2095        // (1) lock:andl &m->_owner, 0
2096        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2097        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2098        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2099        // (2) If supported, an explicit MFENCE is appealing.
2100        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2101        //     particularly if the write-buffer is full as might be the case if
2102        //     if stores closely precede the fence or fence-equivalent instruction.
2103        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2104        //     as the situation has changed with Nehalem and Shanghai.
2105        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2106        //     The $lines underlying the top-of-stack should be in M-state.
2107        //     The locked add instruction is serializing, of course.
2108        // (4) Use xchg, which is serializing
2109        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2110        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2111        //     The integer condition codes will tell us if succ was 0.
2112        //     Since _succ and _owner should reside in the same $line and
2113        //     we just stored into _owner, it's likely that the $line
2114        //     remains in M-state for the lock:orl.
2115        //
2116        // We currently use (3), although it's likely that switching to (2)
2117        // is correct for the future.
2118 
2119        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2120        if (os::is_MP()) {
2121          lock(); addptr(Address(rsp, 0), 0);
2122        }
2123        // Ratify _succ remains non-null
2124        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2125        jccb  (Assembler::notZero, LSuccess);
2126 
2127        xorptr(boxReg, boxReg);                  // box is really EAX
2128        if (os::is_MP()) { lock(); }
2129        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2130        // There's no successor so we tried to regrab the lock with the
2131        // placeholder value. If that didn't work, then another thread
2132        // grabbed the lock so we're done (and exit was a success).
2133        jccb  (Assembler::notEqual, LSuccess);
2134        // Since we're low on registers we installed rsp as a placeholding in _owner.
2135        // Now install Self over rsp.  This is safe as we're transitioning from
2136        // non-null to non=null
2137        get_thread (boxReg);
2138        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2139        // Intentional fall-through into LGoSlowPath ...
2140 
2141        bind  (LGoSlowPath);
2142        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2143        jmpb  (DONE_LABEL);
2144 
2145        bind  (LSuccess);
2146        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2147        jmpb  (DONE_LABEL);
2148     }
2149 
2150     bind (Stacked);
2151     // It's not inflated and it's not recursively stack-locked and it's not biased.
2152     // It must be stack-locked.
2153     // Try to reset the header to displaced header.
2154     // The "box" value on the stack is stable, so we can reload
2155     // and be assured we observe the same value as above.
2156     movptr(tmpReg, Address(boxReg, 0));
2157     if (os::is_MP()) {
2158       lock();
2159     }
2160     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2161     // Intention fall-thru into DONE_LABEL
2162 
2163     // DONE_LABEL is a hot target - we'd really like to place it at the
2164     // start of cache line by padding with NOPs.
2165     // See the AMD and Intel software optimization manuals for the
2166     // most efficient "long" NOP encodings.
2167     // Unfortunately none of our alignment mechanisms suffice.
2168     if ((EmitSync & 65536) == 0) {
2169        bind (CheckSucc);
2170     }
2171 #else // _LP64
2172     // It's inflated
2173     if (EmitSync & 1024) {
2174       // Emit code to check that _owner == Self
2175       // We could fold the _owner test into subsequent code more efficiently
2176       // than using a stand-alone check, but since _owner checking is off by
2177       // default we don't bother. We also might consider predicating the
2178       // _owner==Self check on Xcheck:jni or running on a debug build.
2179       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2180       xorptr(boxReg, r15_thread);
2181     } else {
2182       xorptr(boxReg, boxReg);
2183     }
2184     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2185     jccb  (Assembler::notZero, DONE_LABEL);
2186     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2187     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2188     jccb  (Assembler::notZero, CheckSucc);
2189     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2190     jmpb  (DONE_LABEL);
2191 
2192     if ((EmitSync & 65536) == 0) {
2193       // Try to avoid passing control into the slow_path ...
2194       Label LSuccess, LGoSlowPath ;
2195       bind  (CheckSucc);
2196 
2197       // The following optional optimization can be elided if necessary
2198       // Effectively: if (succ == null) goto SlowPath
2199       // The code reduces the window for a race, however,
2200       // and thus benefits performance.
2201       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2202       jccb  (Assembler::zero, LGoSlowPath);
2203 
2204       xorptr(boxReg, boxReg);
2205       if ((EmitSync & 16) && os::is_MP()) {
2206         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2207       } else {
2208         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2209         if (os::is_MP()) {
2210           // Memory barrier/fence
2211           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2212           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2213           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2214           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2215           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2216           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2217           lock(); addl(Address(rsp, 0), 0);
2218         }
2219       }
2220       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2221       jccb  (Assembler::notZero, LSuccess);
2222 
2223       // Rare inopportune interleaving - race.
2224       // The successor vanished in the small window above.
2225       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2226       // We need to ensure progress and succession.
2227       // Try to reacquire the lock.
2228       // If that fails then the new owner is responsible for succession and this
2229       // thread needs to take no further action and can exit via the fast path (success).
2230       // If the re-acquire succeeds then pass control into the slow path.
2231       // As implemented, this latter mode is horrible because we generated more
2232       // coherence traffic on the lock *and* artifically extended the critical section
2233       // length while by virtue of passing control into the slow path.
2234 
2235       // box is really RAX -- the following CMPXCHG depends on that binding
2236       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2237       if (os::is_MP()) { lock(); }
2238       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2239       // There's no successor so we tried to regrab the lock.
2240       // If that didn't work, then another thread grabbed the
2241       // lock so we're done (and exit was a success).
2242       jccb  (Assembler::notEqual, LSuccess);
2243       // Intentional fall-through into slow-path
2244 
2245       bind  (LGoSlowPath);
2246       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2247       jmpb  (DONE_LABEL);
2248 
2249       bind  (LSuccess);
2250       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2251       jmpb  (DONE_LABEL);
2252     }
2253 
2254     bind  (Stacked);
2255     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2256     if (os::is_MP()) { lock(); }
2257     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2258 
2259     if (EmitSync & 65536) {
2260        bind (CheckSucc);
2261     }
2262 #endif
2263     bind(DONE_LABEL);
2264   }
2265 }
2266 #endif // COMPILER2
2267 
2268 void MacroAssembler::c2bool(Register x) {
2269   // implements x == 0 ? 0 : 1
2270   // note: must only look at least-significant byte of x
2271   //       since C-style booleans are stored in one byte
2272   //       only! (was bug)
2273   andl(x, 0xFF);
2274   setb(Assembler::notZero, x);
2275 }
2276 
2277 // Wouldn't need if AddressLiteral version had new name
2278 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2279   Assembler::call(L, rtype);
2280 }
2281 
2282 void MacroAssembler::call(Register entry) {
2283   Assembler::call(entry);
2284 }
2285 
2286 void MacroAssembler::call(AddressLiteral entry) {
2287   if (reachable(entry)) {
2288     Assembler::call_literal(entry.target(), entry.rspec());
2289   } else {
2290     lea(rscratch1, entry);
2291     Assembler::call(rscratch1);
2292   }
2293 }
2294 
2295 void MacroAssembler::ic_call(address entry, jint method_index) {
2296   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2297   movptr(rax, (intptr_t)Universe::non_oop_word());
2298   call(AddressLiteral(entry, rh));
2299 }
2300 
2301 // Implementation of call_VM versions
2302 
2303 void MacroAssembler::call_VM(Register oop_result,
2304                              address entry_point,
2305                              bool check_exceptions) {
2306   Label C, E;
2307   call(C, relocInfo::none);
2308   jmp(E);
2309 
2310   bind(C);
2311   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2312   ret(0);
2313 
2314   bind(E);
2315 }
2316 
2317 void MacroAssembler::call_VM(Register oop_result,
2318                              address entry_point,
2319                              Register arg_1,
2320                              bool check_exceptions) {
2321   Label C, E;
2322   call(C, relocInfo::none);
2323   jmp(E);
2324 
2325   bind(C);
2326   pass_arg1(this, arg_1);
2327   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2328   ret(0);
2329 
2330   bind(E);
2331 }
2332 
2333 void MacroAssembler::call_VM(Register oop_result,
2334                              address entry_point,
2335                              Register arg_1,
2336                              Register arg_2,
2337                              bool check_exceptions) {
2338   Label C, E;
2339   call(C, relocInfo::none);
2340   jmp(E);
2341 
2342   bind(C);
2343 
2344   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2345 
2346   pass_arg2(this, arg_2);
2347   pass_arg1(this, arg_1);
2348   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2349   ret(0);
2350 
2351   bind(E);
2352 }
2353 
2354 void MacroAssembler::call_VM(Register oop_result,
2355                              address entry_point,
2356                              Register arg_1,
2357                              Register arg_2,
2358                              Register arg_3,
2359                              bool check_exceptions) {
2360   Label C, E;
2361   call(C, relocInfo::none);
2362   jmp(E);
2363 
2364   bind(C);
2365 
2366   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2367   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2368   pass_arg3(this, arg_3);
2369 
2370   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2371   pass_arg2(this, arg_2);
2372 
2373   pass_arg1(this, arg_1);
2374   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2375   ret(0);
2376 
2377   bind(E);
2378 }
2379 
2380 void MacroAssembler::call_VM(Register oop_result,
2381                              Register last_java_sp,
2382                              address entry_point,
2383                              int number_of_arguments,
2384                              bool check_exceptions) {
2385   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2386   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2387 }
2388 
2389 void MacroAssembler::call_VM(Register oop_result,
2390                              Register last_java_sp,
2391                              address entry_point,
2392                              Register arg_1,
2393                              bool check_exceptions) {
2394   pass_arg1(this, arg_1);
2395   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2396 }
2397 
2398 void MacroAssembler::call_VM(Register oop_result,
2399                              Register last_java_sp,
2400                              address entry_point,
2401                              Register arg_1,
2402                              Register arg_2,
2403                              bool check_exceptions) {
2404 
2405   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2406   pass_arg2(this, arg_2);
2407   pass_arg1(this, arg_1);
2408   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2409 }
2410 
2411 void MacroAssembler::call_VM(Register oop_result,
2412                              Register last_java_sp,
2413                              address entry_point,
2414                              Register arg_1,
2415                              Register arg_2,
2416                              Register arg_3,
2417                              bool check_exceptions) {
2418   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2419   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2420   pass_arg3(this, arg_3);
2421   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2422   pass_arg2(this, arg_2);
2423   pass_arg1(this, arg_1);
2424   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2425 }
2426 
2427 void MacroAssembler::super_call_VM(Register oop_result,
2428                                    Register last_java_sp,
2429                                    address entry_point,
2430                                    int number_of_arguments,
2431                                    bool check_exceptions) {
2432   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2433   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2434 }
2435 
2436 void MacroAssembler::super_call_VM(Register oop_result,
2437                                    Register last_java_sp,
2438                                    address entry_point,
2439                                    Register arg_1,
2440                                    bool check_exceptions) {
2441   pass_arg1(this, arg_1);
2442   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2443 }
2444 
2445 void MacroAssembler::super_call_VM(Register oop_result,
2446                                    Register last_java_sp,
2447                                    address entry_point,
2448                                    Register arg_1,
2449                                    Register arg_2,
2450                                    bool check_exceptions) {
2451 
2452   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2453   pass_arg2(this, arg_2);
2454   pass_arg1(this, arg_1);
2455   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2456 }
2457 
2458 void MacroAssembler::super_call_VM(Register oop_result,
2459                                    Register last_java_sp,
2460                                    address entry_point,
2461                                    Register arg_1,
2462                                    Register arg_2,
2463                                    Register arg_3,
2464                                    bool check_exceptions) {
2465   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2466   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2467   pass_arg3(this, arg_3);
2468   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2469   pass_arg2(this, arg_2);
2470   pass_arg1(this, arg_1);
2471   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2472 }
2473 
2474 void MacroAssembler::call_VM_base(Register oop_result,
2475                                   Register java_thread,
2476                                   Register last_java_sp,
2477                                   address  entry_point,
2478                                   int      number_of_arguments,
2479                                   bool     check_exceptions) {
2480   // determine java_thread register
2481   if (!java_thread->is_valid()) {
2482 #ifdef _LP64
2483     java_thread = r15_thread;
2484 #else
2485     java_thread = rdi;
2486     get_thread(java_thread);
2487 #endif // LP64
2488   }
2489   // determine last_java_sp register
2490   if (!last_java_sp->is_valid()) {
2491     last_java_sp = rsp;
2492   }
2493   // debugging support
2494   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2495   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2496 #ifdef ASSERT
2497   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2498   // r12 is the heapbase.
2499   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2500 #endif // ASSERT
2501 
2502   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2503   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2504 
2505   // push java thread (becomes first argument of C function)
2506 
2507   NOT_LP64(push(java_thread); number_of_arguments++);
2508   LP64_ONLY(mov(c_rarg0, r15_thread));
2509 
2510   // set last Java frame before call
2511   assert(last_java_sp != rbp, "can't use ebp/rbp");
2512 
2513   // Only interpreter should have to set fp
2514   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2515 
2516   // do the call, remove parameters
2517   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2518 
2519   // restore the thread (cannot use the pushed argument since arguments
2520   // may be overwritten by C code generated by an optimizing compiler);
2521   // however can use the register value directly if it is callee saved.
2522   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2523     // rdi & rsi (also r15) are callee saved -> nothing to do
2524 #ifdef ASSERT
2525     guarantee(java_thread != rax, "change this code");
2526     push(rax);
2527     { Label L;
2528       get_thread(rax);
2529       cmpptr(java_thread, rax);
2530       jcc(Assembler::equal, L);
2531       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2532       bind(L);
2533     }
2534     pop(rax);
2535 #endif
2536   } else {
2537     get_thread(java_thread);
2538   }
2539   // reset last Java frame
2540   // Only interpreter should have to clear fp
2541   reset_last_Java_frame(java_thread, true);
2542 
2543    // C++ interp handles this in the interpreter
2544   check_and_handle_popframe(java_thread);
2545   check_and_handle_earlyret(java_thread);
2546 
2547   if (check_exceptions) {
2548     // check for pending exceptions (java_thread is set upon return)
2549     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2550 #ifndef _LP64
2551     jump_cc(Assembler::notEqual,
2552             RuntimeAddress(StubRoutines::forward_exception_entry()));
2553 #else
2554     // This used to conditionally jump to forward_exception however it is
2555     // possible if we relocate that the branch will not reach. So we must jump
2556     // around so we can always reach
2557 
2558     Label ok;
2559     jcc(Assembler::equal, ok);
2560     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2561     bind(ok);
2562 #endif // LP64
2563   }
2564 
2565   // get oop result if there is one and reset the value in the thread
2566   if (oop_result->is_valid()) {
2567     get_vm_result(oop_result, java_thread);
2568   }
2569 }
2570 
2571 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2572 
2573   // Calculate the value for last_Java_sp
2574   // somewhat subtle. call_VM does an intermediate call
2575   // which places a return address on the stack just under the
2576   // stack pointer as the user finsihed with it. This allows
2577   // use to retrieve last_Java_pc from last_Java_sp[-1].
2578   // On 32bit we then have to push additional args on the stack to accomplish
2579   // the actual requested call. On 64bit call_VM only can use register args
2580   // so the only extra space is the return address that call_VM created.
2581   // This hopefully explains the calculations here.
2582 
2583 #ifdef _LP64
2584   // We've pushed one address, correct last_Java_sp
2585   lea(rax, Address(rsp, wordSize));
2586 #else
2587   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2588 #endif // LP64
2589 
2590   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2591 
2592 }
2593 
2594 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2595 void MacroAssembler::call_VM_leaf0(address entry_point) {
2596   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2597 }
2598 
2599 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2600   call_VM_leaf_base(entry_point, number_of_arguments);
2601 }
2602 
2603 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2604   pass_arg0(this, arg_0);
2605   call_VM_leaf(entry_point, 1);
2606 }
2607 
2608 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2609 
2610   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2611   pass_arg1(this, arg_1);
2612   pass_arg0(this, arg_0);
2613   call_VM_leaf(entry_point, 2);
2614 }
2615 
2616 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2617   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2618   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2619   pass_arg2(this, arg_2);
2620   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2621   pass_arg1(this, arg_1);
2622   pass_arg0(this, arg_0);
2623   call_VM_leaf(entry_point, 3);
2624 }
2625 
2626 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2627   pass_arg0(this, arg_0);
2628   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2629 }
2630 
2631 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2632 
2633   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2634   pass_arg1(this, arg_1);
2635   pass_arg0(this, arg_0);
2636   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2637 }
2638 
2639 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2640   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2641   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2642   pass_arg2(this, arg_2);
2643   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2644   pass_arg1(this, arg_1);
2645   pass_arg0(this, arg_0);
2646   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2647 }
2648 
2649 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2650   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2651   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2652   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2653   pass_arg3(this, arg_3);
2654   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2655   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2656   pass_arg2(this, arg_2);
2657   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2658   pass_arg1(this, arg_1);
2659   pass_arg0(this, arg_0);
2660   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2661 }
2662 
2663 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2664   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2665   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2666   verify_oop(oop_result, "broken oop in call_VM_base");
2667 }
2668 
2669 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2670   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2671   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2672 }
2673 
2674 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2675 }
2676 
2677 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2678 }
2679 
2680 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2681   if (reachable(src1)) {
2682     cmpl(as_Address(src1), imm);
2683   } else {
2684     lea(rscratch1, src1);
2685     cmpl(Address(rscratch1, 0), imm);
2686   }
2687 }
2688 
2689 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2690   assert(!src2.is_lval(), "use cmpptr");
2691   if (reachable(src2)) {
2692     cmpl(src1, as_Address(src2));
2693   } else {
2694     lea(rscratch1, src2);
2695     cmpl(src1, Address(rscratch1, 0));
2696   }
2697 }
2698 
2699 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2700   Assembler::cmpl(src1, imm);
2701 }
2702 
2703 void MacroAssembler::cmp32(Register src1, Address src2) {
2704   Assembler::cmpl(src1, src2);
2705 }
2706 
2707 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2708   ucomisd(opr1, opr2);
2709 
2710   Label L;
2711   if (unordered_is_less) {
2712     movl(dst, -1);
2713     jcc(Assembler::parity, L);
2714     jcc(Assembler::below , L);
2715     movl(dst, 0);
2716     jcc(Assembler::equal , L);
2717     increment(dst);
2718   } else { // unordered is greater
2719     movl(dst, 1);
2720     jcc(Assembler::parity, L);
2721     jcc(Assembler::above , L);
2722     movl(dst, 0);
2723     jcc(Assembler::equal , L);
2724     decrementl(dst);
2725   }
2726   bind(L);
2727 }
2728 
2729 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2730   ucomiss(opr1, opr2);
2731 
2732   Label L;
2733   if (unordered_is_less) {
2734     movl(dst, -1);
2735     jcc(Assembler::parity, L);
2736     jcc(Assembler::below , L);
2737     movl(dst, 0);
2738     jcc(Assembler::equal , L);
2739     increment(dst);
2740   } else { // unordered is greater
2741     movl(dst, 1);
2742     jcc(Assembler::parity, L);
2743     jcc(Assembler::above , L);
2744     movl(dst, 0);
2745     jcc(Assembler::equal , L);
2746     decrementl(dst);
2747   }
2748   bind(L);
2749 }
2750 
2751 
2752 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2753   if (reachable(src1)) {
2754     cmpb(as_Address(src1), imm);
2755   } else {
2756     lea(rscratch1, src1);
2757     cmpb(Address(rscratch1, 0), imm);
2758   }
2759 }
2760 
2761 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2762 #ifdef _LP64
2763   if (src2.is_lval()) {
2764     movptr(rscratch1, src2);
2765     Assembler::cmpq(src1, rscratch1);
2766   } else if (reachable(src2)) {
2767     cmpq(src1, as_Address(src2));
2768   } else {
2769     lea(rscratch1, src2);
2770     Assembler::cmpq(src1, Address(rscratch1, 0));
2771   }
2772 #else
2773   if (src2.is_lval()) {
2774     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2775   } else {
2776     cmpl(src1, as_Address(src2));
2777   }
2778 #endif // _LP64
2779 }
2780 
2781 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2782   assert(src2.is_lval(), "not a mem-mem compare");
2783 #ifdef _LP64
2784   // moves src2's literal address
2785   movptr(rscratch1, src2);
2786   Assembler::cmpq(src1, rscratch1);
2787 #else
2788   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2789 #endif // _LP64
2790 }
2791 
2792 void MacroAssembler::cmpoop(Register src1, Register src2) {
2793   cmpptr(src1, src2);
2794 }
2795 
2796 void MacroAssembler::cmpoop(Register src1, Address src2) {
2797   cmpptr(src1, src2);
2798 }
2799 
2800 #ifdef _LP64
2801 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2802   movoop(rscratch1, src2);
2803   cmpptr(src1, rscratch1);
2804 }
2805 #endif
2806 
2807 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2808   if (reachable(adr)) {
2809     if (os::is_MP())
2810       lock();
2811     cmpxchgptr(reg, as_Address(adr));
2812   } else {
2813     lea(rscratch1, adr);
2814     if (os::is_MP())
2815       lock();
2816     cmpxchgptr(reg, Address(rscratch1, 0));
2817   }
2818 }
2819 
2820 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2821   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2822 }
2823 
2824 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2825   if (reachable(src)) {
2826     Assembler::comisd(dst, as_Address(src));
2827   } else {
2828     lea(rscratch1, src);
2829     Assembler::comisd(dst, Address(rscratch1, 0));
2830   }
2831 }
2832 
2833 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2834   if (reachable(src)) {
2835     Assembler::comiss(dst, as_Address(src));
2836   } else {
2837     lea(rscratch1, src);
2838     Assembler::comiss(dst, Address(rscratch1, 0));
2839   }
2840 }
2841 
2842 
2843 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2844   Condition negated_cond = negate_condition(cond);
2845   Label L;
2846   jcc(negated_cond, L);
2847   pushf(); // Preserve flags
2848   atomic_incl(counter_addr);
2849   popf();
2850   bind(L);
2851 }
2852 
2853 int MacroAssembler::corrected_idivl(Register reg) {
2854   // Full implementation of Java idiv and irem; checks for
2855   // special case as described in JVM spec., p.243 & p.271.
2856   // The function returns the (pc) offset of the idivl
2857   // instruction - may be needed for implicit exceptions.
2858   //
2859   //         normal case                           special case
2860   //
2861   // input : rax,: dividend                         min_int
2862   //         reg: divisor   (may not be rax,/rdx)   -1
2863   //
2864   // output: rax,: quotient  (= rax, idiv reg)       min_int
2865   //         rdx: remainder (= rax, irem reg)       0
2866   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2867   const int min_int = 0x80000000;
2868   Label normal_case, special_case;
2869 
2870   // check for special case
2871   cmpl(rax, min_int);
2872   jcc(Assembler::notEqual, normal_case);
2873   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2874   cmpl(reg, -1);
2875   jcc(Assembler::equal, special_case);
2876 
2877   // handle normal case
2878   bind(normal_case);
2879   cdql();
2880   int idivl_offset = offset();
2881   idivl(reg);
2882 
2883   // normal and special case exit
2884   bind(special_case);
2885 
2886   return idivl_offset;
2887 }
2888 
2889 
2890 
2891 void MacroAssembler::decrementl(Register reg, int value) {
2892   if (value == min_jint) {subl(reg, value) ; return; }
2893   if (value <  0) { incrementl(reg, -value); return; }
2894   if (value == 0) {                        ; return; }
2895   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2896   /* else */      { subl(reg, value)       ; return; }
2897 }
2898 
2899 void MacroAssembler::decrementl(Address dst, int value) {
2900   if (value == min_jint) {subl(dst, value) ; return; }
2901   if (value <  0) { incrementl(dst, -value); return; }
2902   if (value == 0) {                        ; return; }
2903   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2904   /* else */      { subl(dst, value)       ; return; }
2905 }
2906 
2907 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2908   assert (shift_value > 0, "illegal shift value");
2909   Label _is_positive;
2910   testl (reg, reg);
2911   jcc (Assembler::positive, _is_positive);
2912   int offset = (1 << shift_value) - 1 ;
2913 
2914   if (offset == 1) {
2915     incrementl(reg);
2916   } else {
2917     addl(reg, offset);
2918   }
2919 
2920   bind (_is_positive);
2921   sarl(reg, shift_value);
2922 }
2923 
2924 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2925   if (reachable(src)) {
2926     Assembler::divsd(dst, as_Address(src));
2927   } else {
2928     lea(rscratch1, src);
2929     Assembler::divsd(dst, Address(rscratch1, 0));
2930   }
2931 }
2932 
2933 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2934   if (reachable(src)) {
2935     Assembler::divss(dst, as_Address(src));
2936   } else {
2937     lea(rscratch1, src);
2938     Assembler::divss(dst, Address(rscratch1, 0));
2939   }
2940 }
2941 
2942 // !defined(COMPILER2) is because of stupid core builds
2943 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2944 void MacroAssembler::empty_FPU_stack() {
2945   if (VM_Version::supports_mmx()) {
2946     emms();
2947   } else {
2948     for (int i = 8; i-- > 0; ) ffree(i);
2949   }
2950 }
2951 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2952 
2953 
2954 // Defines obj, preserves var_size_in_bytes
2955 void MacroAssembler::eden_allocate(Register obj,
2956                                    Register var_size_in_bytes,
2957                                    int con_size_in_bytes,
2958                                    Register t1,
2959                                    Label& slow_case) {
2960   assert(obj == rax, "obj must be in rax, for cmpxchg");
2961   assert_different_registers(obj, var_size_in_bytes, t1);
2962   if (!Universe::heap()->supports_inline_contig_alloc()) {
2963     jmp(slow_case);
2964   } else {
2965     Register end = t1;
2966     Label retry;
2967     bind(retry);
2968     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2969     movptr(obj, heap_top);
2970     if (var_size_in_bytes == noreg) {
2971       lea(end, Address(obj, con_size_in_bytes));
2972     } else {
2973       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2974     }
2975     // if end < obj then we wrapped around => object too long => slow case
2976     cmpptr(end, obj);
2977     jcc(Assembler::below, slow_case);
2978     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2979     jcc(Assembler::above, slow_case);
2980     // Compare obj with the top addr, and if still equal, store the new top addr in
2981     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2982     // it otherwise. Use lock prefix for atomicity on MPs.
2983     locked_cmpxchgptr(end, heap_top);
2984     jcc(Assembler::notEqual, retry);
2985   }
2986 }
2987 
2988 void MacroAssembler::enter() {
2989   push(rbp);
2990   mov(rbp, rsp);
2991 }
2992 
2993 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2994 void MacroAssembler::fat_nop() {
2995   if (UseAddressNop) {
2996     addr_nop_5();
2997   } else {
2998     emit_int8(0x26); // es:
2999     emit_int8(0x2e); // cs:
3000     emit_int8(0x64); // fs:
3001     emit_int8(0x65); // gs:
3002     emit_int8((unsigned char)0x90);
3003   }
3004 }
3005 
3006 void MacroAssembler::fcmp(Register tmp) {
3007   fcmp(tmp, 1, true, true);
3008 }
3009 
3010 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3011   assert(!pop_right || pop_left, "usage error");
3012   if (VM_Version::supports_cmov()) {
3013     assert(tmp == noreg, "unneeded temp");
3014     if (pop_left) {
3015       fucomip(index);
3016     } else {
3017       fucomi(index);
3018     }
3019     if (pop_right) {
3020       fpop();
3021     }
3022   } else {
3023     assert(tmp != noreg, "need temp");
3024     if (pop_left) {
3025       if (pop_right) {
3026         fcompp();
3027       } else {
3028         fcomp(index);
3029       }
3030     } else {
3031       fcom(index);
3032     }
3033     // convert FPU condition into eflags condition via rax,
3034     save_rax(tmp);
3035     fwait(); fnstsw_ax();
3036     sahf();
3037     restore_rax(tmp);
3038   }
3039   // condition codes set as follows:
3040   //
3041   // CF (corresponds to C0) if x < y
3042   // PF (corresponds to C2) if unordered
3043   // ZF (corresponds to C3) if x = y
3044 }
3045 
3046 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3047   fcmp2int(dst, unordered_is_less, 1, true, true);
3048 }
3049 
3050 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3051   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3052   Label L;
3053   if (unordered_is_less) {
3054     movl(dst, -1);
3055     jcc(Assembler::parity, L);
3056     jcc(Assembler::below , L);
3057     movl(dst, 0);
3058     jcc(Assembler::equal , L);
3059     increment(dst);
3060   } else { // unordered is greater
3061     movl(dst, 1);
3062     jcc(Assembler::parity, L);
3063     jcc(Assembler::above , L);
3064     movl(dst, 0);
3065     jcc(Assembler::equal , L);
3066     decrementl(dst);
3067   }
3068   bind(L);
3069 }
3070 
3071 void MacroAssembler::fld_d(AddressLiteral src) {
3072   fld_d(as_Address(src));
3073 }
3074 
3075 void MacroAssembler::fld_s(AddressLiteral src) {
3076   fld_s(as_Address(src));
3077 }
3078 
3079 void MacroAssembler::fld_x(AddressLiteral src) {
3080   Assembler::fld_x(as_Address(src));
3081 }
3082 
3083 void MacroAssembler::fldcw(AddressLiteral src) {
3084   Assembler::fldcw(as_Address(src));
3085 }
3086 
3087 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3088   if (reachable(src)) {
3089     Assembler::mulpd(dst, as_Address(src));
3090   } else {
3091     lea(rscratch1, src);
3092     Assembler::mulpd(dst, Address(rscratch1, 0));
3093   }
3094 }
3095 
3096 void MacroAssembler::increase_precision() {
3097   subptr(rsp, BytesPerWord);
3098   fnstcw(Address(rsp, 0));
3099   movl(rax, Address(rsp, 0));
3100   orl(rax, 0x300);
3101   push(rax);
3102   fldcw(Address(rsp, 0));
3103   pop(rax);
3104 }
3105 
3106 void MacroAssembler::restore_precision() {
3107   fldcw(Address(rsp, 0));
3108   addptr(rsp, BytesPerWord);
3109 }
3110 
3111 void MacroAssembler::fpop() {
3112   ffree();
3113   fincstp();
3114 }
3115 
3116 void MacroAssembler::load_float(Address src) {
3117   if (UseSSE >= 1) {
3118     movflt(xmm0, src);
3119   } else {
3120     LP64_ONLY(ShouldNotReachHere());
3121     NOT_LP64(fld_s(src));
3122   }
3123 }
3124 
3125 void MacroAssembler::store_float(Address dst) {
3126   if (UseSSE >= 1) {
3127     movflt(dst, xmm0);
3128   } else {
3129     LP64_ONLY(ShouldNotReachHere());
3130     NOT_LP64(fstp_s(dst));
3131   }
3132 }
3133 
3134 void MacroAssembler::load_double(Address src) {
3135   if (UseSSE >= 2) {
3136     movdbl(xmm0, src);
3137   } else {
3138     LP64_ONLY(ShouldNotReachHere());
3139     NOT_LP64(fld_d(src));
3140   }
3141 }
3142 
3143 void MacroAssembler::store_double(Address dst) {
3144   if (UseSSE >= 2) {
3145     movdbl(dst, xmm0);
3146   } else {
3147     LP64_ONLY(ShouldNotReachHere());
3148     NOT_LP64(fstp_d(dst));
3149   }
3150 }
3151 
3152 void MacroAssembler::fremr(Register tmp) {
3153   save_rax(tmp);
3154   { Label L;
3155     bind(L);
3156     fprem();
3157     fwait(); fnstsw_ax();
3158 #ifdef _LP64
3159     testl(rax, 0x400);
3160     jcc(Assembler::notEqual, L);
3161 #else
3162     sahf();
3163     jcc(Assembler::parity, L);
3164 #endif // _LP64
3165   }
3166   restore_rax(tmp);
3167   // Result is in ST0.
3168   // Note: fxch & fpop to get rid of ST1
3169   // (otherwise FPU stack could overflow eventually)
3170   fxch(1);
3171   fpop();
3172 }
3173 
3174 // dst = c = a * b + c
3175 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3176   Assembler::vfmadd231sd(c, a, b);
3177   if (dst != c) {
3178     movdbl(dst, c);
3179   }
3180 }
3181 
3182 // dst = c = a * b + c
3183 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3184   Assembler::vfmadd231ss(c, a, b);
3185   if (dst != c) {
3186     movflt(dst, c);
3187   }
3188 }
3189 
3190 // dst = c = a * b + c
3191 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3192   Assembler::vfmadd231pd(c, a, b, vector_len);
3193   if (dst != c) {
3194     vmovdqu(dst, c);
3195   }
3196 }
3197 
3198 // dst = c = a * b + c
3199 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3200   Assembler::vfmadd231ps(c, a, b, vector_len);
3201   if (dst != c) {
3202     vmovdqu(dst, c);
3203   }
3204 }
3205 
3206 // dst = c = a * b + c
3207 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3208   Assembler::vfmadd231pd(c, a, b, vector_len);
3209   if (dst != c) {
3210     vmovdqu(dst, c);
3211   }
3212 }
3213 
3214 // dst = c = a * b + c
3215 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3216   Assembler::vfmadd231ps(c, a, b, vector_len);
3217   if (dst != c) {
3218     vmovdqu(dst, c);
3219   }
3220 }
3221 
3222 void MacroAssembler::incrementl(AddressLiteral dst) {
3223   if (reachable(dst)) {
3224     incrementl(as_Address(dst));
3225   } else {
3226     lea(rscratch1, dst);
3227     incrementl(Address(rscratch1, 0));
3228   }
3229 }
3230 
3231 void MacroAssembler::incrementl(ArrayAddress dst) {
3232   incrementl(as_Address(dst));
3233 }
3234 
3235 void MacroAssembler::incrementl(Register reg, int value) {
3236   if (value == min_jint) {addl(reg, value) ; return; }
3237   if (value <  0) { decrementl(reg, -value); return; }
3238   if (value == 0) {                        ; return; }
3239   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3240   /* else */      { addl(reg, value)       ; return; }
3241 }
3242 
3243 void MacroAssembler::incrementl(Address dst, int value) {
3244   if (value == min_jint) {addl(dst, value) ; return; }
3245   if (value <  0) { decrementl(dst, -value); return; }
3246   if (value == 0) {                        ; return; }
3247   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3248   /* else */      { addl(dst, value)       ; return; }
3249 }
3250 
3251 void MacroAssembler::jump(AddressLiteral dst) {
3252   if (reachable(dst)) {
3253     jmp_literal(dst.target(), dst.rspec());
3254   } else {
3255     lea(rscratch1, dst);
3256     jmp(rscratch1);
3257   }
3258 }
3259 
3260 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3261   if (reachable(dst)) {
3262     InstructionMark im(this);
3263     relocate(dst.reloc());
3264     const int short_size = 2;
3265     const int long_size = 6;
3266     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3267     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3268       // 0111 tttn #8-bit disp
3269       emit_int8(0x70 | cc);
3270       emit_int8((offs - short_size) & 0xFF);
3271     } else {
3272       // 0000 1111 1000 tttn #32-bit disp
3273       emit_int8(0x0F);
3274       emit_int8((unsigned char)(0x80 | cc));
3275       emit_int32(offs - long_size);
3276     }
3277   } else {
3278 #ifdef ASSERT
3279     warning("reversing conditional branch");
3280 #endif /* ASSERT */
3281     Label skip;
3282     jccb(reverse[cc], skip);
3283     lea(rscratch1, dst);
3284     Assembler::jmp(rscratch1);
3285     bind(skip);
3286   }
3287 }
3288 
3289 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3290   if (reachable(src)) {
3291     Assembler::ldmxcsr(as_Address(src));
3292   } else {
3293     lea(rscratch1, src);
3294     Assembler::ldmxcsr(Address(rscratch1, 0));
3295   }
3296 }
3297 
3298 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3299   int off;
3300   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3301     off = offset();
3302     movsbl(dst, src); // movsxb
3303   } else {
3304     off = load_unsigned_byte(dst, src);
3305     shll(dst, 24);
3306     sarl(dst, 24);
3307   }
3308   return off;
3309 }
3310 
3311 // Note: load_signed_short used to be called load_signed_word.
3312 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3313 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3314 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3315 int MacroAssembler::load_signed_short(Register dst, Address src) {
3316   int off;
3317   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3318     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3319     // version but this is what 64bit has always done. This seems to imply
3320     // that users are only using 32bits worth.
3321     off = offset();
3322     movswl(dst, src); // movsxw
3323   } else {
3324     off = load_unsigned_short(dst, src);
3325     shll(dst, 16);
3326     sarl(dst, 16);
3327   }
3328   return off;
3329 }
3330 
3331 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3332   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3333   // and "3.9 Partial Register Penalties", p. 22).
3334   int off;
3335   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3336     off = offset();
3337     movzbl(dst, src); // movzxb
3338   } else {
3339     xorl(dst, dst);
3340     off = offset();
3341     movb(dst, src);
3342   }
3343   return off;
3344 }
3345 
3346 // Note: load_unsigned_short used to be called load_unsigned_word.
3347 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3348   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3349   // and "3.9 Partial Register Penalties", p. 22).
3350   int off;
3351   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3352     off = offset();
3353     movzwl(dst, src); // movzxw
3354   } else {
3355     xorl(dst, dst);
3356     off = offset();
3357     movw(dst, src);
3358   }
3359   return off;
3360 }
3361 
3362 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3363   switch (size_in_bytes) {
3364 #ifndef _LP64
3365   case  8:
3366     assert(dst2 != noreg, "second dest register required");
3367     movl(dst,  src);
3368     movl(dst2, src.plus_disp(BytesPerInt));
3369     break;
3370 #else
3371   case  8:  movq(dst, src); break;
3372 #endif
3373   case  4:  movl(dst, src); break;
3374   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3375   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3376   default:  ShouldNotReachHere();
3377   }
3378 }
3379 
3380 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3381   switch (size_in_bytes) {
3382 #ifndef _LP64
3383   case  8:
3384     assert(src2 != noreg, "second source register required");
3385     movl(dst,                        src);
3386     movl(dst.plus_disp(BytesPerInt), src2);
3387     break;
3388 #else
3389   case  8:  movq(dst, src); break;
3390 #endif
3391   case  4:  movl(dst, src); break;
3392   case  2:  movw(dst, src); break;
3393   case  1:  movb(dst, src); break;
3394   default:  ShouldNotReachHere();
3395   }
3396 }
3397 
3398 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3399   if (reachable(dst)) {
3400     movl(as_Address(dst), src);
3401   } else {
3402     lea(rscratch1, dst);
3403     movl(Address(rscratch1, 0), src);
3404   }
3405 }
3406 
3407 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3408   if (reachable(src)) {
3409     movl(dst, as_Address(src));
3410   } else {
3411     lea(rscratch1, src);
3412     movl(dst, Address(rscratch1, 0));
3413   }
3414 }
3415 
3416 // C++ bool manipulation
3417 
3418 void MacroAssembler::movbool(Register dst, Address src) {
3419   if(sizeof(bool) == 1)
3420     movb(dst, src);
3421   else if(sizeof(bool) == 2)
3422     movw(dst, src);
3423   else if(sizeof(bool) == 4)
3424     movl(dst, src);
3425   else
3426     // unsupported
3427     ShouldNotReachHere();
3428 }
3429 
3430 void MacroAssembler::movbool(Address dst, bool boolconst) {
3431   if(sizeof(bool) == 1)
3432     movb(dst, (int) boolconst);
3433   else if(sizeof(bool) == 2)
3434     movw(dst, (int) boolconst);
3435   else if(sizeof(bool) == 4)
3436     movl(dst, (int) boolconst);
3437   else
3438     // unsupported
3439     ShouldNotReachHere();
3440 }
3441 
3442 void MacroAssembler::movbool(Address dst, Register src) {
3443   if(sizeof(bool) == 1)
3444     movb(dst, src);
3445   else if(sizeof(bool) == 2)
3446     movw(dst, src);
3447   else if(sizeof(bool) == 4)
3448     movl(dst, src);
3449   else
3450     // unsupported
3451     ShouldNotReachHere();
3452 }
3453 
3454 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3455   movb(as_Address(dst), src);
3456 }
3457 
3458 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3459   if (reachable(src)) {
3460     movdl(dst, as_Address(src));
3461   } else {
3462     lea(rscratch1, src);
3463     movdl(dst, Address(rscratch1, 0));
3464   }
3465 }
3466 
3467 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3468   if (reachable(src)) {
3469     movq(dst, as_Address(src));
3470   } else {
3471     lea(rscratch1, src);
3472     movq(dst, Address(rscratch1, 0));
3473   }
3474 }
3475 
3476 void MacroAssembler::setvectmask(Register dst, Register src) {
3477   Assembler::movl(dst, 1);
3478   Assembler::shlxl(dst, dst, src);
3479   Assembler::decl(dst);
3480   Assembler::kmovdl(k1, dst);
3481   Assembler::movl(dst, src);
3482 }
3483 
3484 void MacroAssembler::restorevectmask() {
3485   Assembler::knotwl(k1, k0);
3486 }
3487 
3488 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3489   if (reachable(src)) {
3490     if (UseXmmLoadAndClearUpper) {
3491       movsd (dst, as_Address(src));
3492     } else {
3493       movlpd(dst, as_Address(src));
3494     }
3495   } else {
3496     lea(rscratch1, src);
3497     if (UseXmmLoadAndClearUpper) {
3498       movsd (dst, Address(rscratch1, 0));
3499     } else {
3500       movlpd(dst, Address(rscratch1, 0));
3501     }
3502   }
3503 }
3504 
3505 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3506   if (reachable(src)) {
3507     movss(dst, as_Address(src));
3508   } else {
3509     lea(rscratch1, src);
3510     movss(dst, Address(rscratch1, 0));
3511   }
3512 }
3513 
3514 void MacroAssembler::movptr(Register dst, Register src) {
3515   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3516 }
3517 
3518 void MacroAssembler::movptr(Register dst, Address src) {
3519   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3520 }
3521 
3522 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3523 void MacroAssembler::movptr(Register dst, intptr_t src) {
3524   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3525 }
3526 
3527 void MacroAssembler::movptr(Address dst, Register src) {
3528   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3529 }
3530 
3531 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3532   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3533     Assembler::vextractf32x4(dst, src, 0);
3534   } else {
3535     Assembler::movdqu(dst, src);
3536   }
3537 }
3538 
3539 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3540   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3541     Assembler::vinsertf32x4(dst, dst, src, 0);
3542   } else {
3543     Assembler::movdqu(dst, src);
3544   }
3545 }
3546 
3547 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3548   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3549     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3550   } else {
3551     Assembler::movdqu(dst, src);
3552   }
3553 }
3554 
3555 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3556   if (reachable(src)) {
3557     movdqu(dst, as_Address(src));
3558   } else {
3559     lea(scratchReg, src);
3560     movdqu(dst, Address(scratchReg, 0));
3561   }
3562 }
3563 
3564 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3565   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3566     vextractf64x4_low(dst, src);
3567   } else {
3568     Assembler::vmovdqu(dst, src);
3569   }
3570 }
3571 
3572 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3573   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3574     vinsertf64x4_low(dst, src);
3575   } else {
3576     Assembler::vmovdqu(dst, src);
3577   }
3578 }
3579 
3580 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3581   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3582     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3583   }
3584   else {
3585     Assembler::vmovdqu(dst, src);
3586   }
3587 }
3588 
3589 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3590   if (reachable(src)) {
3591     vmovdqu(dst, as_Address(src));
3592   }
3593   else {
3594     lea(rscratch1, src);
3595     vmovdqu(dst, Address(rscratch1, 0));
3596   }
3597 }
3598 
3599 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3600   if (reachable(src)) {
3601     Assembler::movdqa(dst, as_Address(src));
3602   } else {
3603     lea(rscratch1, src);
3604     Assembler::movdqa(dst, Address(rscratch1, 0));
3605   }
3606 }
3607 
3608 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3609   if (reachable(src)) {
3610     Assembler::movsd(dst, as_Address(src));
3611   } else {
3612     lea(rscratch1, src);
3613     Assembler::movsd(dst, Address(rscratch1, 0));
3614   }
3615 }
3616 
3617 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3618   if (reachable(src)) {
3619     Assembler::movss(dst, as_Address(src));
3620   } else {
3621     lea(rscratch1, src);
3622     Assembler::movss(dst, Address(rscratch1, 0));
3623   }
3624 }
3625 
3626 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3627   if (reachable(src)) {
3628     Assembler::mulsd(dst, as_Address(src));
3629   } else {
3630     lea(rscratch1, src);
3631     Assembler::mulsd(dst, Address(rscratch1, 0));
3632   }
3633 }
3634 
3635 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3636   if (reachable(src)) {
3637     Assembler::mulss(dst, as_Address(src));
3638   } else {
3639     lea(rscratch1, src);
3640     Assembler::mulss(dst, Address(rscratch1, 0));
3641   }
3642 }
3643 
3644 void MacroAssembler::null_check(Register reg, int offset) {
3645   if (needs_explicit_null_check(offset)) {
3646     // provoke OS NULL exception if reg = NULL by
3647     // accessing M[reg] w/o changing any (non-CC) registers
3648     // NOTE: cmpl is plenty here to provoke a segv
3649     cmpptr(rax, Address(reg, 0));
3650     // Note: should probably use testl(rax, Address(reg, 0));
3651     //       may be shorter code (however, this version of
3652     //       testl needs to be implemented first)
3653   } else {
3654     // nothing to do, (later) access of M[reg + offset]
3655     // will provoke OS NULL exception if reg = NULL
3656   }
3657 }
3658 
3659 void MacroAssembler::os_breakpoint() {
3660   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3661   // (e.g., MSVC can't call ps() otherwise)
3662   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3663 }
3664 
3665 void MacroAssembler::unimplemented(const char* what) {
3666   const char* buf = NULL;
3667   {
3668     ResourceMark rm;
3669     stringStream ss;
3670     ss.print("unimplemented: %s", what);
3671     buf = code_string(ss.as_string());
3672   }
3673   stop(buf);
3674 }
3675 
3676 #ifdef _LP64
3677 #define XSTATE_BV 0x200
3678 #endif
3679 
3680 void MacroAssembler::pop_CPU_state() {
3681   pop_FPU_state();
3682   pop_IU_state();
3683 }
3684 
3685 void MacroAssembler::pop_FPU_state() {
3686 #ifndef _LP64
3687   frstor(Address(rsp, 0));
3688 #else
3689   fxrstor(Address(rsp, 0));
3690 #endif
3691   addptr(rsp, FPUStateSizeInWords * wordSize);
3692 }
3693 
3694 void MacroAssembler::pop_IU_state() {
3695   popa();
3696   LP64_ONLY(addq(rsp, 8));
3697   popf();
3698 }
3699 
3700 // Save Integer and Float state
3701 // Warning: Stack must be 16 byte aligned (64bit)
3702 void MacroAssembler::push_CPU_state() {
3703   push_IU_state();
3704   push_FPU_state();
3705 }
3706 
3707 void MacroAssembler::push_FPU_state() {
3708   subptr(rsp, FPUStateSizeInWords * wordSize);
3709 #ifndef _LP64
3710   fnsave(Address(rsp, 0));
3711   fwait();
3712 #else
3713   fxsave(Address(rsp, 0));
3714 #endif // LP64
3715 }
3716 
3717 void MacroAssembler::push_IU_state() {
3718   // Push flags first because pusha kills them
3719   pushf();
3720   // Make sure rsp stays 16-byte aligned
3721   LP64_ONLY(subq(rsp, 8));
3722   pusha();
3723 }
3724 
3725 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3726   if (!java_thread->is_valid()) {
3727     java_thread = rdi;
3728     get_thread(java_thread);
3729   }
3730   // we must set sp to zero to clear frame
3731   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3732   if (clear_fp) {
3733     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3734   }
3735 
3736   // Always clear the pc because it could have been set by make_walkable()
3737   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3738 
3739   vzeroupper();
3740 }
3741 
3742 void MacroAssembler::restore_rax(Register tmp) {
3743   if (tmp == noreg) pop(rax);
3744   else if (tmp != rax) mov(rax, tmp);
3745 }
3746 
3747 void MacroAssembler::round_to(Register reg, int modulus) {
3748   addptr(reg, modulus - 1);
3749   andptr(reg, -modulus);
3750 }
3751 
3752 void MacroAssembler::save_rax(Register tmp) {
3753   if (tmp == noreg) push(rax);
3754   else if (tmp != rax) mov(tmp, rax);
3755 }
3756 
3757 // Write serialization page so VM thread can do a pseudo remote membar.
3758 // We use the current thread pointer to calculate a thread specific
3759 // offset to write to within the page. This minimizes bus traffic
3760 // due to cache line collision.
3761 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3762   movl(tmp, thread);
3763   shrl(tmp, os::get_serialize_page_shift_count());
3764   andl(tmp, (os::vm_page_size() - sizeof(int)));
3765 
3766   Address index(noreg, tmp, Address::times_1);
3767   ExternalAddress page(os::get_memory_serialize_page());
3768 
3769   // Size of store must match masking code above
3770   movl(as_Address(ArrayAddress(page, index)), tmp);
3771 }
3772 
3773 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3774   if (SafepointMechanism::uses_thread_local_poll()) {
3775 #ifdef _LP64
3776     assert(thread_reg == r15_thread, "should be");
3777 #else
3778     if (thread_reg == noreg) {
3779       thread_reg = temp_reg;
3780       get_thread(thread_reg);
3781     }
3782 #endif
3783     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3784     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3785   } else {
3786     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3787         SafepointSynchronize::_not_synchronized);
3788     jcc(Assembler::notEqual, slow_path);
3789   }
3790 }
3791 
3792 // Calls to C land
3793 //
3794 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3795 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3796 // has to be reset to 0. This is required to allow proper stack traversal.
3797 void MacroAssembler::set_last_Java_frame(Register java_thread,
3798                                          Register last_java_sp,
3799                                          Register last_java_fp,
3800                                          address  last_java_pc) {
3801   vzeroupper();
3802   // determine java_thread register
3803   if (!java_thread->is_valid()) {
3804     java_thread = rdi;
3805     get_thread(java_thread);
3806   }
3807   // determine last_java_sp register
3808   if (!last_java_sp->is_valid()) {
3809     last_java_sp = rsp;
3810   }
3811 
3812   // last_java_fp is optional
3813 
3814   if (last_java_fp->is_valid()) {
3815     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3816   }
3817 
3818   // last_java_pc is optional
3819 
3820   if (last_java_pc != NULL) {
3821     lea(Address(java_thread,
3822                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3823         InternalAddress(last_java_pc));
3824 
3825   }
3826   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3827 }
3828 
3829 void MacroAssembler::shlptr(Register dst, int imm8) {
3830   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3831 }
3832 
3833 void MacroAssembler::shrptr(Register dst, int imm8) {
3834   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3835 }
3836 
3837 void MacroAssembler::sign_extend_byte(Register reg) {
3838   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3839     movsbl(reg, reg); // movsxb
3840   } else {
3841     shll(reg, 24);
3842     sarl(reg, 24);
3843   }
3844 }
3845 
3846 void MacroAssembler::sign_extend_short(Register reg) {
3847   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3848     movswl(reg, reg); // movsxw
3849   } else {
3850     shll(reg, 16);
3851     sarl(reg, 16);
3852   }
3853 }
3854 
3855 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3856   assert(reachable(src), "Address should be reachable");
3857   testl(dst, as_Address(src));
3858 }
3859 
3860 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3861   int dst_enc = dst->encoding();
3862   int src_enc = src->encoding();
3863   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3864     Assembler::pcmpeqb(dst, src);
3865   } else if ((dst_enc < 16) && (src_enc < 16)) {
3866     Assembler::pcmpeqb(dst, src);
3867   } else if (src_enc < 16) {
3868     subptr(rsp, 64);
3869     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3870     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3871     Assembler::pcmpeqb(xmm0, src);
3872     movdqu(dst, xmm0);
3873     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3874     addptr(rsp, 64);
3875   } else if (dst_enc < 16) {
3876     subptr(rsp, 64);
3877     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3878     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3879     Assembler::pcmpeqb(dst, xmm0);
3880     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3881     addptr(rsp, 64);
3882   } else {
3883     subptr(rsp, 64);
3884     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3885     subptr(rsp, 64);
3886     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3887     movdqu(xmm0, src);
3888     movdqu(xmm1, dst);
3889     Assembler::pcmpeqb(xmm1, xmm0);
3890     movdqu(dst, xmm1);
3891     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3892     addptr(rsp, 64);
3893     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3894     addptr(rsp, 64);
3895   }
3896 }
3897 
3898 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3899   int dst_enc = dst->encoding();
3900   int src_enc = src->encoding();
3901   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3902     Assembler::pcmpeqw(dst, src);
3903   } else if ((dst_enc < 16) && (src_enc < 16)) {
3904     Assembler::pcmpeqw(dst, src);
3905   } else if (src_enc < 16) {
3906     subptr(rsp, 64);
3907     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3908     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3909     Assembler::pcmpeqw(xmm0, src);
3910     movdqu(dst, xmm0);
3911     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3912     addptr(rsp, 64);
3913   } else if (dst_enc < 16) {
3914     subptr(rsp, 64);
3915     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3916     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3917     Assembler::pcmpeqw(dst, xmm0);
3918     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3919     addptr(rsp, 64);
3920   } else {
3921     subptr(rsp, 64);
3922     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3923     subptr(rsp, 64);
3924     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3925     movdqu(xmm0, src);
3926     movdqu(xmm1, dst);
3927     Assembler::pcmpeqw(xmm1, xmm0);
3928     movdqu(dst, xmm1);
3929     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3930     addptr(rsp, 64);
3931     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3932     addptr(rsp, 64);
3933   }
3934 }
3935 
3936 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3937   int dst_enc = dst->encoding();
3938   if (dst_enc < 16) {
3939     Assembler::pcmpestri(dst, src, imm8);
3940   } else {
3941     subptr(rsp, 64);
3942     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3943     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3944     Assembler::pcmpestri(xmm0, src, imm8);
3945     movdqu(dst, xmm0);
3946     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3947     addptr(rsp, 64);
3948   }
3949 }
3950 
3951 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3952   int dst_enc = dst->encoding();
3953   int src_enc = src->encoding();
3954   if ((dst_enc < 16) && (src_enc < 16)) {
3955     Assembler::pcmpestri(dst, src, imm8);
3956   } else if (src_enc < 16) {
3957     subptr(rsp, 64);
3958     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3959     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3960     Assembler::pcmpestri(xmm0, src, imm8);
3961     movdqu(dst, xmm0);
3962     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3963     addptr(rsp, 64);
3964   } else if (dst_enc < 16) {
3965     subptr(rsp, 64);
3966     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3967     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3968     Assembler::pcmpestri(dst, xmm0, imm8);
3969     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3970     addptr(rsp, 64);
3971   } else {
3972     subptr(rsp, 64);
3973     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3974     subptr(rsp, 64);
3975     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3976     movdqu(xmm0, src);
3977     movdqu(xmm1, dst);
3978     Assembler::pcmpestri(xmm1, xmm0, imm8);
3979     movdqu(dst, xmm1);
3980     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3981     addptr(rsp, 64);
3982     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3983     addptr(rsp, 64);
3984   }
3985 }
3986 
3987 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
3988   int dst_enc = dst->encoding();
3989   int src_enc = src->encoding();
3990   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3991     Assembler::pmovzxbw(dst, src);
3992   } else if ((dst_enc < 16) && (src_enc < 16)) {
3993     Assembler::pmovzxbw(dst, src);
3994   } else if (src_enc < 16) {
3995     subptr(rsp, 64);
3996     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3997     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3998     Assembler::pmovzxbw(xmm0, src);
3999     movdqu(dst, xmm0);
4000     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4001     addptr(rsp, 64);
4002   } else if (dst_enc < 16) {
4003     subptr(rsp, 64);
4004     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4005     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4006     Assembler::pmovzxbw(dst, xmm0);
4007     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4008     addptr(rsp, 64);
4009   } else {
4010     subptr(rsp, 64);
4011     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4012     subptr(rsp, 64);
4013     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4014     movdqu(xmm0, src);
4015     movdqu(xmm1, dst);
4016     Assembler::pmovzxbw(xmm1, xmm0);
4017     movdqu(dst, xmm1);
4018     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4019     addptr(rsp, 64);
4020     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4021     addptr(rsp, 64);
4022   }
4023 }
4024 
4025 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4026   int dst_enc = dst->encoding();
4027   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4028     Assembler::pmovzxbw(dst, src);
4029   } else if (dst_enc < 16) {
4030     Assembler::pmovzxbw(dst, src);
4031   } else {
4032     subptr(rsp, 64);
4033     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4034     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4035     Assembler::pmovzxbw(xmm0, src);
4036     movdqu(dst, xmm0);
4037     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4038     addptr(rsp, 64);
4039   }
4040 }
4041 
4042 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4043   int src_enc = src->encoding();
4044   if (src_enc < 16) {
4045     Assembler::pmovmskb(dst, src);
4046   } else {
4047     subptr(rsp, 64);
4048     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4049     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4050     Assembler::pmovmskb(dst, xmm0);
4051     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4052     addptr(rsp, 64);
4053   }
4054 }
4055 
4056 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4057   int dst_enc = dst->encoding();
4058   int src_enc = src->encoding();
4059   if ((dst_enc < 16) && (src_enc < 16)) {
4060     Assembler::ptest(dst, src);
4061   } else if (src_enc < 16) {
4062     subptr(rsp, 64);
4063     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4064     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4065     Assembler::ptest(xmm0, src);
4066     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4067     addptr(rsp, 64);
4068   } else if (dst_enc < 16) {
4069     subptr(rsp, 64);
4070     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4071     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4072     Assembler::ptest(dst, xmm0);
4073     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4074     addptr(rsp, 64);
4075   } else {
4076     subptr(rsp, 64);
4077     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4078     subptr(rsp, 64);
4079     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4080     movdqu(xmm0, src);
4081     movdqu(xmm1, dst);
4082     Assembler::ptest(xmm1, xmm0);
4083     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4084     addptr(rsp, 64);
4085     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4086     addptr(rsp, 64);
4087   }
4088 }
4089 
4090 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4091   if (reachable(src)) {
4092     Assembler::sqrtsd(dst, as_Address(src));
4093   } else {
4094     lea(rscratch1, src);
4095     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4096   }
4097 }
4098 
4099 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4100   if (reachable(src)) {
4101     Assembler::sqrtss(dst, as_Address(src));
4102   } else {
4103     lea(rscratch1, src);
4104     Assembler::sqrtss(dst, Address(rscratch1, 0));
4105   }
4106 }
4107 
4108 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4109   if (reachable(src)) {
4110     Assembler::subsd(dst, as_Address(src));
4111   } else {
4112     lea(rscratch1, src);
4113     Assembler::subsd(dst, Address(rscratch1, 0));
4114   }
4115 }
4116 
4117 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4118   if (reachable(src)) {
4119     Assembler::subss(dst, as_Address(src));
4120   } else {
4121     lea(rscratch1, src);
4122     Assembler::subss(dst, Address(rscratch1, 0));
4123   }
4124 }
4125 
4126 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4127   if (reachable(src)) {
4128     Assembler::ucomisd(dst, as_Address(src));
4129   } else {
4130     lea(rscratch1, src);
4131     Assembler::ucomisd(dst, Address(rscratch1, 0));
4132   }
4133 }
4134 
4135 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4136   if (reachable(src)) {
4137     Assembler::ucomiss(dst, as_Address(src));
4138   } else {
4139     lea(rscratch1, src);
4140     Assembler::ucomiss(dst, Address(rscratch1, 0));
4141   }
4142 }
4143 
4144 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4145   // Used in sign-bit flipping with aligned address.
4146   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4147   if (reachable(src)) {
4148     Assembler::xorpd(dst, as_Address(src));
4149   } else {
4150     lea(rscratch1, src);
4151     Assembler::xorpd(dst, Address(rscratch1, 0));
4152   }
4153 }
4154 
4155 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4156   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4157     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4158   }
4159   else {
4160     Assembler::xorpd(dst, src);
4161   }
4162 }
4163 
4164 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4165   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4166     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4167   } else {
4168     Assembler::xorps(dst, src);
4169   }
4170 }
4171 
4172 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4173   // Used in sign-bit flipping with aligned address.
4174   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4175   if (reachable(src)) {
4176     Assembler::xorps(dst, as_Address(src));
4177   } else {
4178     lea(rscratch1, src);
4179     Assembler::xorps(dst, Address(rscratch1, 0));
4180   }
4181 }
4182 
4183 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4184   // Used in sign-bit flipping with aligned address.
4185   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4186   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4187   if (reachable(src)) {
4188     Assembler::pshufb(dst, as_Address(src));
4189   } else {
4190     lea(rscratch1, src);
4191     Assembler::pshufb(dst, Address(rscratch1, 0));
4192   }
4193 }
4194 
4195 // AVX 3-operands instructions
4196 
4197 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4198   if (reachable(src)) {
4199     vaddsd(dst, nds, as_Address(src));
4200   } else {
4201     lea(rscratch1, src);
4202     vaddsd(dst, nds, Address(rscratch1, 0));
4203   }
4204 }
4205 
4206 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4207   if (reachable(src)) {
4208     vaddss(dst, nds, as_Address(src));
4209   } else {
4210     lea(rscratch1, src);
4211     vaddss(dst, nds, Address(rscratch1, 0));
4212   }
4213 }
4214 
4215 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4216   int dst_enc = dst->encoding();
4217   int nds_enc = nds->encoding();
4218   int src_enc = src->encoding();
4219   if ((dst_enc < 16) && (nds_enc < 16)) {
4220     vandps(dst, nds, negate_field, vector_len);
4221   } else if ((src_enc < 16) && (dst_enc < 16)) {
4222     evmovdqul(src, nds, Assembler::AVX_512bit);
4223     vandps(dst, src, negate_field, vector_len);
4224   } else if (src_enc < 16) {
4225     evmovdqul(src, nds, Assembler::AVX_512bit);
4226     vandps(src, src, negate_field, vector_len);
4227     evmovdqul(dst, src, Assembler::AVX_512bit);
4228   } else if (dst_enc < 16) {
4229     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4230     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4231     vandps(dst, xmm0, negate_field, vector_len);
4232     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4233   } else {
4234     if (src_enc != dst_enc) {
4235       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4236       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4237       vandps(xmm0, xmm0, negate_field, vector_len);
4238       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4239       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4240     } else {
4241       subptr(rsp, 64);
4242       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4243       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4244       vandps(xmm0, xmm0, negate_field, vector_len);
4245       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4246       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4247       addptr(rsp, 64);
4248     }
4249   }
4250 }
4251 
4252 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4253   int dst_enc = dst->encoding();
4254   int nds_enc = nds->encoding();
4255   int src_enc = src->encoding();
4256   if ((dst_enc < 16) && (nds_enc < 16)) {
4257     vandpd(dst, nds, negate_field, vector_len);
4258   } else if ((src_enc < 16) && (dst_enc < 16)) {
4259     evmovdqul(src, nds, Assembler::AVX_512bit);
4260     vandpd(dst, src, negate_field, vector_len);
4261   } else if (src_enc < 16) {
4262     evmovdqul(src, nds, Assembler::AVX_512bit);
4263     vandpd(src, src, negate_field, vector_len);
4264     evmovdqul(dst, src, Assembler::AVX_512bit);
4265   } else if (dst_enc < 16) {
4266     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4267     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4268     vandpd(dst, xmm0, negate_field, vector_len);
4269     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4270   } else {
4271     if (src_enc != dst_enc) {
4272       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4273       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4274       vandpd(xmm0, xmm0, negate_field, vector_len);
4275       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4276       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4277     } else {
4278       subptr(rsp, 64);
4279       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4280       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4281       vandpd(xmm0, xmm0, negate_field, vector_len);
4282       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4283       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4284       addptr(rsp, 64);
4285     }
4286   }
4287 }
4288 
4289 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4290   int dst_enc = dst->encoding();
4291   int nds_enc = nds->encoding();
4292   int src_enc = src->encoding();
4293   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4294     Assembler::vpaddb(dst, nds, src, vector_len);
4295   } else if ((dst_enc < 16) && (src_enc < 16)) {
4296     Assembler::vpaddb(dst, dst, src, vector_len);
4297   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4298     // use nds as scratch for src
4299     evmovdqul(nds, src, Assembler::AVX_512bit);
4300     Assembler::vpaddb(dst, dst, nds, vector_len);
4301   } else if ((src_enc < 16) && (nds_enc < 16)) {
4302     // use nds as scratch for dst
4303     evmovdqul(nds, dst, Assembler::AVX_512bit);
4304     Assembler::vpaddb(nds, nds, src, vector_len);
4305     evmovdqul(dst, nds, Assembler::AVX_512bit);
4306   } else if (dst_enc < 16) {
4307     // use nds as scatch for xmm0 to hold src
4308     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4309     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4310     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4311     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4312   } else {
4313     // worse case scenario, all regs are in the upper bank
4314     subptr(rsp, 64);
4315     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4316     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4317     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4318     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4319     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4320     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4321     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4322     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4323     addptr(rsp, 64);
4324   }
4325 }
4326 
4327 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4328   int dst_enc = dst->encoding();
4329   int nds_enc = nds->encoding();
4330   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4331     Assembler::vpaddb(dst, nds, src, vector_len);
4332   } else if (dst_enc < 16) {
4333     Assembler::vpaddb(dst, dst, src, vector_len);
4334   } else if (nds_enc < 16) {
4335     // implies dst_enc in upper bank with src as scratch
4336     evmovdqul(nds, dst, Assembler::AVX_512bit);
4337     Assembler::vpaddb(nds, nds, src, vector_len);
4338     evmovdqul(dst, nds, Assembler::AVX_512bit);
4339   } else {
4340     // worse case scenario, all regs in upper bank
4341     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4342     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4343     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4344     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4345   }
4346 }
4347 
4348 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4349   int dst_enc = dst->encoding();
4350   int nds_enc = nds->encoding();
4351   int src_enc = src->encoding();
4352   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4353     Assembler::vpaddw(dst, nds, src, vector_len);
4354   } else if ((dst_enc < 16) && (src_enc < 16)) {
4355     Assembler::vpaddw(dst, dst, src, vector_len);
4356   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4357     // use nds as scratch for src
4358     evmovdqul(nds, src, Assembler::AVX_512bit);
4359     Assembler::vpaddw(dst, dst, nds, vector_len);
4360   } else if ((src_enc < 16) && (nds_enc < 16)) {
4361     // use nds as scratch for dst
4362     evmovdqul(nds, dst, Assembler::AVX_512bit);
4363     Assembler::vpaddw(nds, nds, src, vector_len);
4364     evmovdqul(dst, nds, Assembler::AVX_512bit);
4365   } else if (dst_enc < 16) {
4366     // use nds as scatch for xmm0 to hold src
4367     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4368     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4369     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4370     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4371   } else {
4372     // worse case scenario, all regs are in the upper bank
4373     subptr(rsp, 64);
4374     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4375     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4376     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4377     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4378     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4379     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4380     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4381     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4382     addptr(rsp, 64);
4383   }
4384 }
4385 
4386 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4387   int dst_enc = dst->encoding();
4388   int nds_enc = nds->encoding();
4389   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4390     Assembler::vpaddw(dst, nds, src, vector_len);
4391   } else if (dst_enc < 16) {
4392     Assembler::vpaddw(dst, dst, src, vector_len);
4393   } else if (nds_enc < 16) {
4394     // implies dst_enc in upper bank with src as scratch
4395     evmovdqul(nds, dst, Assembler::AVX_512bit);
4396     Assembler::vpaddw(nds, nds, src, vector_len);
4397     evmovdqul(dst, nds, Assembler::AVX_512bit);
4398   } else {
4399     // worse case scenario, all regs in upper bank
4400     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4401     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4402     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4403     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4404   }
4405 }
4406 
4407 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4408   if (reachable(src)) {
4409     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4410   } else {
4411     lea(rscratch1, src);
4412     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4413   }
4414 }
4415 
4416 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4417   int dst_enc = dst->encoding();
4418   int src_enc = src->encoding();
4419   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4420     Assembler::vpbroadcastw(dst, src);
4421   } else if ((dst_enc < 16) && (src_enc < 16)) {
4422     Assembler::vpbroadcastw(dst, src);
4423   } else if (src_enc < 16) {
4424     subptr(rsp, 64);
4425     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4426     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4427     Assembler::vpbroadcastw(xmm0, src);
4428     movdqu(dst, xmm0);
4429     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4430     addptr(rsp, 64);
4431   } else if (dst_enc < 16) {
4432     subptr(rsp, 64);
4433     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4434     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4435     Assembler::vpbroadcastw(dst, xmm0);
4436     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4437     addptr(rsp, 64);
4438   } else {
4439     subptr(rsp, 64);
4440     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4441     subptr(rsp, 64);
4442     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4443     movdqu(xmm0, src);
4444     movdqu(xmm1, dst);
4445     Assembler::vpbroadcastw(xmm1, xmm0);
4446     movdqu(dst, xmm1);
4447     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4448     addptr(rsp, 64);
4449     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4450     addptr(rsp, 64);
4451   }
4452 }
4453 
4454 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4455   int dst_enc = dst->encoding();
4456   int nds_enc = nds->encoding();
4457   int src_enc = src->encoding();
4458   assert(dst_enc == nds_enc, "");
4459   if ((dst_enc < 16) && (src_enc < 16)) {
4460     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4461   } else if (src_enc < 16) {
4462     subptr(rsp, 64);
4463     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4464     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4465     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4466     movdqu(dst, xmm0);
4467     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4468     addptr(rsp, 64);
4469   } else if (dst_enc < 16) {
4470     subptr(rsp, 64);
4471     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4472     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4473     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4474     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4475     addptr(rsp, 64);
4476   } else {
4477     subptr(rsp, 64);
4478     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4479     subptr(rsp, 64);
4480     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4481     movdqu(xmm0, src);
4482     movdqu(xmm1, dst);
4483     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4484     movdqu(dst, xmm1);
4485     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4486     addptr(rsp, 64);
4487     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4488     addptr(rsp, 64);
4489   }
4490 }
4491 
4492 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4493   int dst_enc = dst->encoding();
4494   int nds_enc = nds->encoding();
4495   int src_enc = src->encoding();
4496   assert(dst_enc == nds_enc, "");
4497   if ((dst_enc < 16) && (src_enc < 16)) {
4498     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4499   } else if (src_enc < 16) {
4500     subptr(rsp, 64);
4501     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4502     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4503     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4504     movdqu(dst, xmm0);
4505     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4506     addptr(rsp, 64);
4507   } else if (dst_enc < 16) {
4508     subptr(rsp, 64);
4509     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4510     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4511     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4512     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4513     addptr(rsp, 64);
4514   } else {
4515     subptr(rsp, 64);
4516     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4517     subptr(rsp, 64);
4518     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4519     movdqu(xmm0, src);
4520     movdqu(xmm1, dst);
4521     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4522     movdqu(dst, xmm1);
4523     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4524     addptr(rsp, 64);
4525     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4526     addptr(rsp, 64);
4527   }
4528 }
4529 
4530 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4531   int dst_enc = dst->encoding();
4532   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4533     Assembler::vpmovzxbw(dst, src, vector_len);
4534   } else if (dst_enc < 16) {
4535     Assembler::vpmovzxbw(dst, src, vector_len);
4536   } else {
4537     subptr(rsp, 64);
4538     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4539     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4540     Assembler::vpmovzxbw(xmm0, src, vector_len);
4541     movdqu(dst, xmm0);
4542     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4543     addptr(rsp, 64);
4544   }
4545 }
4546 
4547 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4548   int src_enc = src->encoding();
4549   if (src_enc < 16) {
4550     Assembler::vpmovmskb(dst, src);
4551   } else {
4552     subptr(rsp, 64);
4553     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4554     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4555     Assembler::vpmovmskb(dst, xmm0);
4556     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4557     addptr(rsp, 64);
4558   }
4559 }
4560 
4561 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4562   int dst_enc = dst->encoding();
4563   int nds_enc = nds->encoding();
4564   int src_enc = src->encoding();
4565   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4566     Assembler::vpmullw(dst, nds, src, vector_len);
4567   } else if ((dst_enc < 16) && (src_enc < 16)) {
4568     Assembler::vpmullw(dst, dst, src, vector_len);
4569   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4570     // use nds as scratch for src
4571     evmovdqul(nds, src, Assembler::AVX_512bit);
4572     Assembler::vpmullw(dst, dst, nds, vector_len);
4573   } else if ((src_enc < 16) && (nds_enc < 16)) {
4574     // use nds as scratch for dst
4575     evmovdqul(nds, dst, Assembler::AVX_512bit);
4576     Assembler::vpmullw(nds, nds, src, vector_len);
4577     evmovdqul(dst, nds, Assembler::AVX_512bit);
4578   } else if (dst_enc < 16) {
4579     // use nds as scatch for xmm0 to hold src
4580     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4581     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4582     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4583     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4584   } else {
4585     // worse case scenario, all regs are in the upper bank
4586     subptr(rsp, 64);
4587     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4588     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4589     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4590     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4591     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4592     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4593     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4594     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4595     addptr(rsp, 64);
4596   }
4597 }
4598 
4599 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4600   int dst_enc = dst->encoding();
4601   int nds_enc = nds->encoding();
4602   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4603     Assembler::vpmullw(dst, nds, src, vector_len);
4604   } else if (dst_enc < 16) {
4605     Assembler::vpmullw(dst, dst, src, vector_len);
4606   } else if (nds_enc < 16) {
4607     // implies dst_enc in upper bank with src as scratch
4608     evmovdqul(nds, dst, Assembler::AVX_512bit);
4609     Assembler::vpmullw(nds, nds, src, vector_len);
4610     evmovdqul(dst, nds, Assembler::AVX_512bit);
4611   } else {
4612     // worse case scenario, all regs in upper bank
4613     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4614     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4615     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4616     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4617   }
4618 }
4619 
4620 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4621   int dst_enc = dst->encoding();
4622   int nds_enc = nds->encoding();
4623   int src_enc = src->encoding();
4624   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4625     Assembler::vpsubb(dst, nds, src, vector_len);
4626   } else if ((dst_enc < 16) && (src_enc < 16)) {
4627     Assembler::vpsubb(dst, dst, src, vector_len);
4628   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4629     // use nds as scratch for src
4630     evmovdqul(nds, src, Assembler::AVX_512bit);
4631     Assembler::vpsubb(dst, dst, nds, vector_len);
4632   } else if ((src_enc < 16) && (nds_enc < 16)) {
4633     // use nds as scratch for dst
4634     evmovdqul(nds, dst, Assembler::AVX_512bit);
4635     Assembler::vpsubb(nds, nds, src, vector_len);
4636     evmovdqul(dst, nds, Assembler::AVX_512bit);
4637   } else if (dst_enc < 16) {
4638     // use nds as scatch for xmm0 to hold src
4639     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4640     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4641     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4642     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4643   } else {
4644     // worse case scenario, all regs are in the upper bank
4645     subptr(rsp, 64);
4646     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4647     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4648     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4649     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4650     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4651     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4652     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4653     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4654     addptr(rsp, 64);
4655   }
4656 }
4657 
4658 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4659   int dst_enc = dst->encoding();
4660   int nds_enc = nds->encoding();
4661   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4662     Assembler::vpsubb(dst, nds, src, vector_len);
4663   } else if (dst_enc < 16) {
4664     Assembler::vpsubb(dst, dst, src, vector_len);
4665   } else if (nds_enc < 16) {
4666     // implies dst_enc in upper bank with src as scratch
4667     evmovdqul(nds, dst, Assembler::AVX_512bit);
4668     Assembler::vpsubb(nds, nds, src, vector_len);
4669     evmovdqul(dst, nds, Assembler::AVX_512bit);
4670   } else {
4671     // worse case scenario, all regs in upper bank
4672     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4673     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4674     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4675     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4676   }
4677 }
4678 
4679 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4680   int dst_enc = dst->encoding();
4681   int nds_enc = nds->encoding();
4682   int src_enc = src->encoding();
4683   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4684     Assembler::vpsubw(dst, nds, src, vector_len);
4685   } else if ((dst_enc < 16) && (src_enc < 16)) {
4686     Assembler::vpsubw(dst, dst, src, vector_len);
4687   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4688     // use nds as scratch for src
4689     evmovdqul(nds, src, Assembler::AVX_512bit);
4690     Assembler::vpsubw(dst, dst, nds, vector_len);
4691   } else if ((src_enc < 16) && (nds_enc < 16)) {
4692     // use nds as scratch for dst
4693     evmovdqul(nds, dst, Assembler::AVX_512bit);
4694     Assembler::vpsubw(nds, nds, src, vector_len);
4695     evmovdqul(dst, nds, Assembler::AVX_512bit);
4696   } else if (dst_enc < 16) {
4697     // use nds as scatch for xmm0 to hold src
4698     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4699     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4700     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4701     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4702   } else {
4703     // worse case scenario, all regs are in the upper bank
4704     subptr(rsp, 64);
4705     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4706     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4707     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4708     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4709     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4710     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4711     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4712     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4713     addptr(rsp, 64);
4714   }
4715 }
4716 
4717 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4718   int dst_enc = dst->encoding();
4719   int nds_enc = nds->encoding();
4720   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4721     Assembler::vpsubw(dst, nds, src, vector_len);
4722   } else if (dst_enc < 16) {
4723     Assembler::vpsubw(dst, dst, src, vector_len);
4724   } else if (nds_enc < 16) {
4725     // implies dst_enc in upper bank with src as scratch
4726     evmovdqul(nds, dst, Assembler::AVX_512bit);
4727     Assembler::vpsubw(nds, nds, src, vector_len);
4728     evmovdqul(dst, nds, Assembler::AVX_512bit);
4729   } else {
4730     // worse case scenario, all regs in upper bank
4731     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4732     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4733     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4734     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4735   }
4736 }
4737 
4738 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4739   int dst_enc = dst->encoding();
4740   int nds_enc = nds->encoding();
4741   int shift_enc = shift->encoding();
4742   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4743     Assembler::vpsraw(dst, nds, shift, vector_len);
4744   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4745     Assembler::vpsraw(dst, dst, shift, vector_len);
4746   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4747     // use nds_enc as scratch with shift
4748     evmovdqul(nds, shift, Assembler::AVX_512bit);
4749     Assembler::vpsraw(dst, dst, nds, vector_len);
4750   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4751     // use nds as scratch with dst
4752     evmovdqul(nds, dst, Assembler::AVX_512bit);
4753     Assembler::vpsraw(nds, nds, shift, vector_len);
4754     evmovdqul(dst, nds, Assembler::AVX_512bit);
4755   } else if (dst_enc < 16) {
4756     // use nds to save a copy of xmm0 and hold shift
4757     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4758     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4759     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4760     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4761   } else if (nds_enc < 16) {
4762     // use nds as dest as temps
4763     evmovdqul(nds, dst, Assembler::AVX_512bit);
4764     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4765     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4766     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4767     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4768     evmovdqul(dst, nds, Assembler::AVX_512bit);
4769   } else {
4770     // worse case scenario, all regs are in the upper bank
4771     subptr(rsp, 64);
4772     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4773     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4774     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4775     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4776     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4777     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4778     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4779     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4780     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4781     addptr(rsp, 64);
4782   }
4783 }
4784 
4785 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4786   int dst_enc = dst->encoding();
4787   int nds_enc = nds->encoding();
4788   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4789     Assembler::vpsraw(dst, nds, shift, vector_len);
4790   } else if (dst_enc < 16) {
4791     Assembler::vpsraw(dst, dst, shift, vector_len);
4792   } else if (nds_enc < 16) {
4793     // use nds as scratch
4794     evmovdqul(nds, dst, Assembler::AVX_512bit);
4795     Assembler::vpsraw(nds, nds, shift, vector_len);
4796     evmovdqul(dst, nds, Assembler::AVX_512bit);
4797   } else {
4798     // use nds as scratch for xmm0
4799     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4800     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4801     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4802     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4803   }
4804 }
4805 
4806 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4807   int dst_enc = dst->encoding();
4808   int nds_enc = nds->encoding();
4809   int shift_enc = shift->encoding();
4810   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4811     Assembler::vpsrlw(dst, nds, shift, vector_len);
4812   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4813     Assembler::vpsrlw(dst, dst, shift, vector_len);
4814   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4815     // use nds_enc as scratch with shift
4816     evmovdqul(nds, shift, Assembler::AVX_512bit);
4817     Assembler::vpsrlw(dst, dst, nds, vector_len);
4818   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4819     // use nds as scratch with dst
4820     evmovdqul(nds, dst, Assembler::AVX_512bit);
4821     Assembler::vpsrlw(nds, nds, shift, vector_len);
4822     evmovdqul(dst, nds, Assembler::AVX_512bit);
4823   } else if (dst_enc < 16) {
4824     // use nds to save a copy of xmm0 and hold shift
4825     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4826     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4827     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4828     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4829   } else if (nds_enc < 16) {
4830     // use nds as dest as temps
4831     evmovdqul(nds, dst, Assembler::AVX_512bit);
4832     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4833     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4834     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4835     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4836     evmovdqul(dst, nds, Assembler::AVX_512bit);
4837   } else {
4838     // worse case scenario, all regs are in the upper bank
4839     subptr(rsp, 64);
4840     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4841     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4842     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4843     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4844     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4845     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4846     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4847     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4848     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4849     addptr(rsp, 64);
4850   }
4851 }
4852 
4853 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4854   int dst_enc = dst->encoding();
4855   int nds_enc = nds->encoding();
4856   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4857     Assembler::vpsrlw(dst, nds, shift, vector_len);
4858   } else if (dst_enc < 16) {
4859     Assembler::vpsrlw(dst, dst, shift, vector_len);
4860   } else if (nds_enc < 16) {
4861     // use nds as scratch
4862     evmovdqul(nds, dst, Assembler::AVX_512bit);
4863     Assembler::vpsrlw(nds, nds, shift, vector_len);
4864     evmovdqul(dst, nds, Assembler::AVX_512bit);
4865   } else {
4866     // use nds as scratch for xmm0
4867     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4868     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4869     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4870     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4871   }
4872 }
4873 
4874 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4875   int dst_enc = dst->encoding();
4876   int nds_enc = nds->encoding();
4877   int shift_enc = shift->encoding();
4878   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4879     Assembler::vpsllw(dst, nds, shift, vector_len);
4880   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4881     Assembler::vpsllw(dst, dst, shift, vector_len);
4882   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4883     // use nds_enc as scratch with shift
4884     evmovdqul(nds, shift, Assembler::AVX_512bit);
4885     Assembler::vpsllw(dst, dst, nds, vector_len);
4886   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4887     // use nds as scratch with dst
4888     evmovdqul(nds, dst, Assembler::AVX_512bit);
4889     Assembler::vpsllw(nds, nds, shift, vector_len);
4890     evmovdqul(dst, nds, Assembler::AVX_512bit);
4891   } else if (dst_enc < 16) {
4892     // use nds to save a copy of xmm0 and hold shift
4893     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4894     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4895     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4896     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4897   } else if (nds_enc < 16) {
4898     // use nds as dest as temps
4899     evmovdqul(nds, dst, Assembler::AVX_512bit);
4900     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4901     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4902     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4903     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4904     evmovdqul(dst, nds, Assembler::AVX_512bit);
4905   } else {
4906     // worse case scenario, all regs are in the upper bank
4907     subptr(rsp, 64);
4908     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4909     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4910     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4911     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4912     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4913     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4914     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4915     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4916     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4917     addptr(rsp, 64);
4918   }
4919 }
4920 
4921 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4922   int dst_enc = dst->encoding();
4923   int nds_enc = nds->encoding();
4924   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4925     Assembler::vpsllw(dst, nds, shift, vector_len);
4926   } else if (dst_enc < 16) {
4927     Assembler::vpsllw(dst, dst, shift, vector_len);
4928   } else if (nds_enc < 16) {
4929     // use nds as scratch
4930     evmovdqul(nds, dst, Assembler::AVX_512bit);
4931     Assembler::vpsllw(nds, nds, shift, vector_len);
4932     evmovdqul(dst, nds, Assembler::AVX_512bit);
4933   } else {
4934     // use nds as scratch for xmm0
4935     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4936     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4937     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4938     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4939   }
4940 }
4941 
4942 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4943   int dst_enc = dst->encoding();
4944   int src_enc = src->encoding();
4945   if ((dst_enc < 16) && (src_enc < 16)) {
4946     Assembler::vptest(dst, src);
4947   } else if (src_enc < 16) {
4948     subptr(rsp, 64);
4949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4950     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4951     Assembler::vptest(xmm0, src);
4952     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4953     addptr(rsp, 64);
4954   } else if (dst_enc < 16) {
4955     subptr(rsp, 64);
4956     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4957     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4958     Assembler::vptest(dst, xmm0);
4959     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4960     addptr(rsp, 64);
4961   } else {
4962     subptr(rsp, 64);
4963     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4964     subptr(rsp, 64);
4965     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4966     movdqu(xmm0, src);
4967     movdqu(xmm1, dst);
4968     Assembler::vptest(xmm1, xmm0);
4969     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4970     addptr(rsp, 64);
4971     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4972     addptr(rsp, 64);
4973   }
4974 }
4975 
4976 // This instruction exists within macros, ergo we cannot control its input
4977 // when emitted through those patterns.
4978 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4979   if (VM_Version::supports_avx512nobw()) {
4980     int dst_enc = dst->encoding();
4981     int src_enc = src->encoding();
4982     if (dst_enc == src_enc) {
4983       if (dst_enc < 16) {
4984         Assembler::punpcklbw(dst, src);
4985       } else {
4986         subptr(rsp, 64);
4987         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4988         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4989         Assembler::punpcklbw(xmm0, xmm0);
4990         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4991         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4992         addptr(rsp, 64);
4993       }
4994     } else {
4995       if ((src_enc < 16) && (dst_enc < 16)) {
4996         Assembler::punpcklbw(dst, src);
4997       } else if (src_enc < 16) {
4998         subptr(rsp, 64);
4999         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5000         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5001         Assembler::punpcklbw(xmm0, src);
5002         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5003         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5004         addptr(rsp, 64);
5005       } else if (dst_enc < 16) {
5006         subptr(rsp, 64);
5007         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5008         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5009         Assembler::punpcklbw(dst, xmm0);
5010         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5011         addptr(rsp, 64);
5012       } else {
5013         subptr(rsp, 64);
5014         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5015         subptr(rsp, 64);
5016         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5017         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5018         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5019         Assembler::punpcklbw(xmm0, xmm1);
5020         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5021         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5022         addptr(rsp, 64);
5023         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5024         addptr(rsp, 64);
5025       }
5026     }
5027   } else {
5028     Assembler::punpcklbw(dst, src);
5029   }
5030 }
5031 
5032 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5033   if (VM_Version::supports_avx512vl()) {
5034     Assembler::pshufd(dst, src, mode);
5035   } else {
5036     int dst_enc = dst->encoding();
5037     if (dst_enc < 16) {
5038       Assembler::pshufd(dst, src, mode);
5039     } else {
5040       subptr(rsp, 64);
5041       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5042       Assembler::pshufd(xmm0, src, mode);
5043       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5044       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5045       addptr(rsp, 64);
5046     }
5047   }
5048 }
5049 
5050 // This instruction exists within macros, ergo we cannot control its input
5051 // when emitted through those patterns.
5052 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5053   if (VM_Version::supports_avx512nobw()) {
5054     int dst_enc = dst->encoding();
5055     int src_enc = src->encoding();
5056     if (dst_enc == src_enc) {
5057       if (dst_enc < 16) {
5058         Assembler::pshuflw(dst, src, mode);
5059       } else {
5060         subptr(rsp, 64);
5061         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5062         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5063         Assembler::pshuflw(xmm0, xmm0, mode);
5064         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5065         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5066         addptr(rsp, 64);
5067       }
5068     } else {
5069       if ((src_enc < 16) && (dst_enc < 16)) {
5070         Assembler::pshuflw(dst, src, mode);
5071       } else if (src_enc < 16) {
5072         subptr(rsp, 64);
5073         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5074         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5075         Assembler::pshuflw(xmm0, src, mode);
5076         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5077         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5078         addptr(rsp, 64);
5079       } else if (dst_enc < 16) {
5080         subptr(rsp, 64);
5081         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5082         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5083         Assembler::pshuflw(dst, xmm0, mode);
5084         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5085         addptr(rsp, 64);
5086       } else {
5087         subptr(rsp, 64);
5088         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5089         subptr(rsp, 64);
5090         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5091         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5092         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5093         Assembler::pshuflw(xmm0, xmm1, mode);
5094         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5095         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5096         addptr(rsp, 64);
5097         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5098         addptr(rsp, 64);
5099       }
5100     }
5101   } else {
5102     Assembler::pshuflw(dst, src, mode);
5103   }
5104 }
5105 
5106 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5107   if (reachable(src)) {
5108     vandpd(dst, nds, as_Address(src), vector_len);
5109   } else {
5110     lea(rscratch1, src);
5111     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5112   }
5113 }
5114 
5115 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5116   if (reachable(src)) {
5117     vandps(dst, nds, as_Address(src), vector_len);
5118   } else {
5119     lea(rscratch1, src);
5120     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5121   }
5122 }
5123 
5124 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5125   if (reachable(src)) {
5126     vdivsd(dst, nds, as_Address(src));
5127   } else {
5128     lea(rscratch1, src);
5129     vdivsd(dst, nds, Address(rscratch1, 0));
5130   }
5131 }
5132 
5133 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5134   if (reachable(src)) {
5135     vdivss(dst, nds, as_Address(src));
5136   } else {
5137     lea(rscratch1, src);
5138     vdivss(dst, nds, Address(rscratch1, 0));
5139   }
5140 }
5141 
5142 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5143   if (reachable(src)) {
5144     vmulsd(dst, nds, as_Address(src));
5145   } else {
5146     lea(rscratch1, src);
5147     vmulsd(dst, nds, Address(rscratch1, 0));
5148   }
5149 }
5150 
5151 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5152   if (reachable(src)) {
5153     vmulss(dst, nds, as_Address(src));
5154   } else {
5155     lea(rscratch1, src);
5156     vmulss(dst, nds, Address(rscratch1, 0));
5157   }
5158 }
5159 
5160 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5161   if (reachable(src)) {
5162     vsubsd(dst, nds, as_Address(src));
5163   } else {
5164     lea(rscratch1, src);
5165     vsubsd(dst, nds, Address(rscratch1, 0));
5166   }
5167 }
5168 
5169 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5170   if (reachable(src)) {
5171     vsubss(dst, nds, as_Address(src));
5172   } else {
5173     lea(rscratch1, src);
5174     vsubss(dst, nds, Address(rscratch1, 0));
5175   }
5176 }
5177 
5178 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5179   int nds_enc = nds->encoding();
5180   int dst_enc = dst->encoding();
5181   bool dst_upper_bank = (dst_enc > 15);
5182   bool nds_upper_bank = (nds_enc > 15);
5183   if (VM_Version::supports_avx512novl() &&
5184       (nds_upper_bank || dst_upper_bank)) {
5185     if (dst_upper_bank) {
5186       subptr(rsp, 64);
5187       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5188       movflt(xmm0, nds);
5189       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5190       movflt(dst, xmm0);
5191       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5192       addptr(rsp, 64);
5193     } else {
5194       movflt(dst, nds);
5195       vxorps(dst, dst, src, Assembler::AVX_128bit);
5196     }
5197   } else {
5198     vxorps(dst, nds, src, Assembler::AVX_128bit);
5199   }
5200 }
5201 
5202 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5203   int nds_enc = nds->encoding();
5204   int dst_enc = dst->encoding();
5205   bool dst_upper_bank = (dst_enc > 15);
5206   bool nds_upper_bank = (nds_enc > 15);
5207   if (VM_Version::supports_avx512novl() &&
5208       (nds_upper_bank || dst_upper_bank)) {
5209     if (dst_upper_bank) {
5210       subptr(rsp, 64);
5211       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5212       movdbl(xmm0, nds);
5213       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5214       movdbl(dst, xmm0);
5215       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5216       addptr(rsp, 64);
5217     } else {
5218       movdbl(dst, nds);
5219       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5220     }
5221   } else {
5222     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5223   }
5224 }
5225 
5226 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5227   if (reachable(src)) {
5228     vxorpd(dst, nds, as_Address(src), vector_len);
5229   } else {
5230     lea(rscratch1, src);
5231     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5232   }
5233 }
5234 
5235 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5236   if (reachable(src)) {
5237     vxorps(dst, nds, as_Address(src), vector_len);
5238   } else {
5239     lea(rscratch1, src);
5240     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5241   }
5242 }
5243 
5244 
5245 void MacroAssembler::resolve_jobject(Register value,
5246                                      Register thread,
5247                                      Register tmp) {
5248   assert_different_registers(value, thread, tmp);
5249   Label done, not_weak;
5250   testptr(value, value);
5251   jcc(Assembler::zero, done);                // Use NULL as-is.
5252   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5253   jcc(Assembler::zero, not_weak);
5254   // Resolve jweak.
5255 #if INCLUDE_ALL_GCS
5256   if (UseLoadBarrier) {
5257     load_barrier(value, Address(value, -JNIHandles::weak_tag_value), false /* expand call */, LoadBarrierOnPhantomOopRef);
5258   } else
5259 #endif
5260   {
5261     movptr(value, Address(value, -JNIHandles::weak_tag_value));
5262   }
5263   verify_oop(value);
5264 #if INCLUDE_ALL_GCS
5265   if (UseG1GC) {
5266     g1_write_barrier_pre(noreg /* obj */,
5267                          value /* pre_val */,
5268                          thread /* thread */,
5269                          tmp /* tmp */,
5270                          true /* tosca_live */,
5271                          true /* expand_call */);
5272   }
5273 #endif // INCLUDE_ALL_GCS
5274   jmp(done);
5275   bind(not_weak);
5276   // Resolve (untagged) jobject.
5277   movptr(value, Address(value, 0));
5278   verify_oop(value);
5279   bind(done);
5280 }
5281 
5282 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5283   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5284   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5285   // The inverted mask is sign-extended
5286   andptr(possibly_jweak, inverted_jweak_mask);
5287 }
5288 
5289 //////////////////////////////////////////////////////////////////////////////////
5290 #if INCLUDE_ALL_GCS
5291 
5292 void MacroAssembler::g1_write_barrier_pre(Register obj,
5293                                           Register pre_val,
5294                                           Register thread,
5295                                           Register tmp,
5296                                           bool tosca_live,
5297                                           bool expand_call) {
5298 
5299   // If expand_call is true then we expand the call_VM_leaf macro
5300   // directly to skip generating the check by
5301   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5302 
5303 #ifdef _LP64
5304   assert(thread == r15_thread, "must be");
5305 #endif // _LP64
5306 
5307   Label done;
5308   Label runtime;
5309 
5310   assert(pre_val != noreg, "check this code");
5311 
5312   if (obj != noreg) {
5313     assert_different_registers(obj, pre_val, tmp);
5314     assert(pre_val != rax, "check this code");
5315   }
5316 
5317   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5318                                        SATBMarkQueue::byte_offset_of_active()));
5319   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5320                                        SATBMarkQueue::byte_offset_of_index()));
5321   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5322                                        SATBMarkQueue::byte_offset_of_buf()));
5323 
5324 
5325   // Is marking active?
5326   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5327     cmpl(in_progress, 0);
5328   } else {
5329     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5330     cmpb(in_progress, 0);
5331   }
5332   jcc(Assembler::equal, done);
5333 
5334   // Do we need to load the previous value?
5335   if (obj != noreg) {
5336     load_heap_oop(pre_val, Address(obj, 0));
5337   }
5338 
5339   // Is the previous value null?
5340   cmpptr(pre_val, (int32_t) NULL_WORD);
5341   jcc(Assembler::equal, done);
5342 
5343   // Can we store original value in the thread's buffer?
5344   // Is index == 0?
5345   // (The index field is typed as size_t.)
5346 
5347   movptr(tmp, index);                   // tmp := *index_adr
5348   cmpptr(tmp, 0);                       // tmp == 0?
5349   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5350 
5351   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5352   movptr(index, tmp);                   // *index_adr := tmp
5353   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5354 
5355   // Record the previous value
5356   movptr(Address(tmp, 0), pre_val);
5357   jmp(done);
5358 
5359   bind(runtime);
5360   // save the live input values
5361   if(tosca_live) push(rax);
5362 
5363   if (obj != noreg && obj != rax)
5364     push(obj);
5365 
5366   if (pre_val != rax)
5367     push(pre_val);
5368 
5369   // Calling the runtime using the regular call_VM_leaf mechanism generates
5370   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5371   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5372   //
5373   // If we care generating the pre-barrier without a frame (e.g. in the
5374   // intrinsified Reference.get() routine) then ebp might be pointing to
5375   // the caller frame and so this check will most likely fail at runtime.
5376   //
5377   // Expanding the call directly bypasses the generation of the check.
5378   // So when we do not have have a full interpreter frame on the stack
5379   // expand_call should be passed true.
5380 
5381   NOT_LP64( push(thread); )
5382 
5383   if (expand_call) {
5384     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5385     pass_arg1(this, thread);
5386     pass_arg0(this, pre_val);
5387     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5388   } else {
5389     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5390   }
5391 
5392   NOT_LP64( pop(thread); )
5393 
5394   // save the live input values
5395   if (pre_val != rax)
5396     pop(pre_val);
5397 
5398   if (obj != noreg && obj != rax)
5399     pop(obj);
5400 
5401   if(tosca_live) pop(rax);
5402 
5403   bind(done);
5404 }
5405 
5406 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5407                                            Register new_val,
5408                                            Register thread,
5409                                            Register tmp,
5410                                            Register tmp2) {
5411 #ifdef _LP64
5412   assert(thread == r15_thread, "must be");
5413 #endif // _LP64
5414 
5415   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5416                                        DirtyCardQueue::byte_offset_of_index()));
5417   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5418                                        DirtyCardQueue::byte_offset_of_buf()));
5419 
5420   CardTableModRefBS* ctbs =
5421     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5422   CardTable* ct = ctbs->card_table();
5423   assert(sizeof(*ct->byte_map_base()) == sizeof(jbyte), "adjust this code");
5424 
5425   Label done;
5426   Label runtime;
5427 
5428   // Does store cross heap regions?
5429 
5430   movptr(tmp, store_addr);
5431   xorptr(tmp, new_val);
5432   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5433   jcc(Assembler::equal, done);
5434 
5435   // crosses regions, storing NULL?
5436 
5437   cmpptr(new_val, (int32_t) NULL_WORD);
5438   jcc(Assembler::equal, done);
5439 
5440   // storing region crossing non-NULL, is card already dirty?
5441 
5442   const Register card_addr = tmp;
5443   const Register cardtable = tmp2;
5444 
5445   movptr(card_addr, store_addr);
5446   shrptr(card_addr, CardTable::card_shift);
5447   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5448   // a valid address and therefore is not properly handled by the relocation code.
5449   movptr(cardtable, (intptr_t)ct->byte_map_base());
5450   addptr(card_addr, cardtable);
5451 
5452   cmpb(Address(card_addr, 0), (int)G1CardTable::g1_young_card_val());
5453   jcc(Assembler::equal, done);
5454 
5455   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5456   cmpb(Address(card_addr, 0), (int)CardTable::dirty_card_val());
5457   jcc(Assembler::equal, done);
5458 
5459 
5460   // storing a region crossing, non-NULL oop, card is clean.
5461   // dirty card and log.
5462 
5463   movb(Address(card_addr, 0), (int)CardTable::dirty_card_val());
5464 
5465   cmpl(queue_index, 0);
5466   jcc(Assembler::equal, runtime);
5467   subl(queue_index, wordSize);
5468   movptr(tmp2, buffer);
5469 #ifdef _LP64
5470   movslq(rscratch1, queue_index);
5471   addq(tmp2, rscratch1);
5472   movq(Address(tmp2, 0), card_addr);
5473 #else
5474   addl(tmp2, queue_index);
5475   movl(Address(tmp2, 0), card_addr);
5476 #endif
5477   jmp(done);
5478 
5479   bind(runtime);
5480   // save the live input values
5481   push(store_addr);
5482   push(new_val);
5483 #ifdef _LP64
5484   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5485 #else
5486   push(thread);
5487   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5488   pop(thread);
5489 #endif
5490   pop(new_val);
5491   pop(store_addr);
5492 
5493   bind(done);
5494 }
5495 
5496 #endif // INCLUDE_ALL_GCS
5497 //////////////////////////////////////////////////////////////////////////////////
5498 
5499 
5500 void MacroAssembler::store_check(Register obj, Address dst) {
5501   store_check(obj);
5502 }
5503 
5504 void MacroAssembler::store_check(Register obj) {
5505   // Does a store check for the oop in register obj. The content of
5506   // register obj is destroyed afterwards.
5507   BarrierSet* bs = Universe::heap()->barrier_set();
5508   assert(bs->kind() == BarrierSet::CardTableModRef,
5509          "Wrong barrier set kind");
5510 
5511   CardTableModRefBS* ctbs = barrier_set_cast<CardTableModRefBS>(bs);
5512   CardTable* ct = ctbs->card_table();
5513   assert(sizeof(*ct->byte_map_base()) == sizeof(jbyte), "adjust this code");
5514 
5515   shrptr(obj, CardTable::card_shift);
5516 
5517   Address card_addr;
5518 
5519   // The calculation for byte_map_base is as follows:
5520   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5521   // So this essentially converts an address to a displacement and it will
5522   // never need to be relocated. On 64bit however the value may be too
5523   // large for a 32bit displacement.
5524   intptr_t disp = (intptr_t) ct->byte_map_base();
5525   if (is_simm32(disp)) {
5526     card_addr = Address(noreg, obj, Address::times_1, disp);
5527   } else {
5528     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5529     // displacement and done in a single instruction given favorable mapping and a
5530     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5531     // entry and that entry is not properly handled by the relocation code.
5532     AddressLiteral cardtable((address)ct->byte_map_base(), relocInfo::none);
5533     Address index(noreg, obj, Address::times_1);
5534     card_addr = as_Address(ArrayAddress(cardtable, index));
5535   }
5536 
5537   int dirty = CardTable::dirty_card_val();
5538   if (UseCondCardMark) {
5539     Label L_already_dirty;
5540     if (UseConcMarkSweepGC) {
5541       membar(Assembler::StoreLoad);
5542     }
5543     cmpb(card_addr, dirty);
5544     jcc(Assembler::equal, L_already_dirty);
5545     movb(card_addr, dirty);
5546     bind(L_already_dirty);
5547   } else {
5548     movb(card_addr, dirty);
5549   }
5550 }
5551 
5552 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5553   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5554 }
5555 
5556 // Force generation of a 4 byte immediate value even if it fits into 8bit
5557 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5558   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5559 }
5560 
5561 void MacroAssembler::subptr(Register dst, Register src) {
5562   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5563 }
5564 
5565 // C++ bool manipulation
5566 void MacroAssembler::testbool(Register dst) {
5567   if(sizeof(bool) == 1)
5568     testb(dst, 0xff);
5569   else if(sizeof(bool) == 2) {
5570     // testw implementation needed for two byte bools
5571     ShouldNotReachHere();
5572   } else if(sizeof(bool) == 4)
5573     testl(dst, dst);
5574   else
5575     // unsupported
5576     ShouldNotReachHere();
5577 }
5578 
5579 void MacroAssembler::testptr(Register dst, Register src) {
5580   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5581 }
5582 
5583 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5584 void MacroAssembler::tlab_allocate(Register obj,
5585                                    Register var_size_in_bytes,
5586                                    int con_size_in_bytes,
5587                                    Register t1,
5588                                    Register t2,
5589                                    Label& slow_case) {
5590   assert_different_registers(obj, t1, t2);
5591   assert_different_registers(obj, var_size_in_bytes, t1);
5592   Register end = t2;
5593   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5594 
5595   verify_tlab();
5596 
5597   NOT_LP64(get_thread(thread));
5598 
5599   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5600   if (var_size_in_bytes == noreg) {
5601     lea(end, Address(obj, con_size_in_bytes));
5602   } else {
5603     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5604   }
5605   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5606   jcc(Assembler::above, slow_case);
5607 
5608   // update the tlab top pointer
5609   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5610 
5611   // recover var_size_in_bytes if necessary
5612   if (var_size_in_bytes == end) {
5613     subptr(var_size_in_bytes, obj);
5614   }
5615   verify_tlab();
5616 }
5617 
5618 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5619 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5620   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5621   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5622   Label done;
5623 
5624   testptr(length_in_bytes, length_in_bytes);
5625   jcc(Assembler::zero, done);
5626 
5627   // initialize topmost word, divide index by 2, check if odd and test if zero
5628   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5629 #ifdef ASSERT
5630   {
5631     Label L;
5632     testptr(length_in_bytes, BytesPerWord - 1);
5633     jcc(Assembler::zero, L);
5634     stop("length must be a multiple of BytesPerWord");
5635     bind(L);
5636   }
5637 #endif
5638   Register index = length_in_bytes;
5639   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5640   if (UseIncDec) {
5641     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5642   } else {
5643     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5644     shrptr(index, 1);
5645   }
5646 #ifndef _LP64
5647   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5648   {
5649     Label even;
5650     // note: if index was a multiple of 8, then it cannot
5651     //       be 0 now otherwise it must have been 0 before
5652     //       => if it is even, we don't need to check for 0 again
5653     jcc(Assembler::carryClear, even);
5654     // clear topmost word (no jump would be needed if conditional assignment worked here)
5655     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5656     // index could be 0 now, must check again
5657     jcc(Assembler::zero, done);
5658     bind(even);
5659   }
5660 #endif // !_LP64
5661   // initialize remaining object fields: index is a multiple of 2 now
5662   {
5663     Label loop;
5664     bind(loop);
5665     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5666     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5667     decrement(index);
5668     jcc(Assembler::notZero, loop);
5669   }
5670 
5671   bind(done);
5672 }
5673 
5674 void MacroAssembler::incr_allocated_bytes(Register thread,
5675                                           Register var_size_in_bytes,
5676                                           int con_size_in_bytes,
5677                                           Register t1) {
5678   if (!thread->is_valid()) {
5679 #ifdef _LP64
5680     thread = r15_thread;
5681 #else
5682     assert(t1->is_valid(), "need temp reg");
5683     thread = t1;
5684     get_thread(thread);
5685 #endif
5686   }
5687 
5688 #ifdef _LP64
5689   if (var_size_in_bytes->is_valid()) {
5690     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5691   } else {
5692     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5693   }
5694 #else
5695   if (var_size_in_bytes->is_valid()) {
5696     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5697   } else {
5698     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5699   }
5700   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5701 #endif
5702 }
5703 
5704 // Look up the method for a megamorphic invokeinterface call.
5705 // The target method is determined by <intf_klass, itable_index>.
5706 // The receiver klass is in recv_klass.
5707 // On success, the result will be in method_result, and execution falls through.
5708 // On failure, execution transfers to the given label.
5709 void MacroAssembler::lookup_interface_method(Register recv_klass,
5710                                              Register intf_klass,
5711                                              RegisterOrConstant itable_index,
5712                                              Register method_result,
5713                                              Register scan_temp,
5714                                              Label& L_no_such_interface,
5715                                              bool return_method) {
5716   assert_different_registers(recv_klass, intf_klass, scan_temp);
5717   assert_different_registers(method_result, intf_klass, scan_temp);
5718   assert(recv_klass != method_result || !return_method,
5719          "recv_klass can be destroyed when method isn't needed");
5720 
5721   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5722          "caller must use same register for non-constant itable index as for method");
5723 
5724   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5725   int vtable_base = in_bytes(Klass::vtable_start_offset());
5726   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5727   int scan_step   = itableOffsetEntry::size() * wordSize;
5728   int vte_size    = vtableEntry::size_in_bytes();
5729   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5730   assert(vte_size == wordSize, "else adjust times_vte_scale");
5731 
5732   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5733 
5734   // %%% Could store the aligned, prescaled offset in the klassoop.
5735   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5736 
5737   if (return_method) {
5738     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5739     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5740     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5741   }
5742 
5743   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5744   //   if (scan->interface() == intf) {
5745   //     result = (klass + scan->offset() + itable_index);
5746   //   }
5747   // }
5748   Label search, found_method;
5749 
5750   for (int peel = 1; peel >= 0; peel--) {
5751     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5752     cmpptr(intf_klass, method_result);
5753 
5754     if (peel) {
5755       jccb(Assembler::equal, found_method);
5756     } else {
5757       jccb(Assembler::notEqual, search);
5758       // (invert the test to fall through to found_method...)
5759     }
5760 
5761     if (!peel)  break;
5762 
5763     bind(search);
5764 
5765     // Check that the previous entry is non-null.  A null entry means that
5766     // the receiver class doesn't implement the interface, and wasn't the
5767     // same as when the caller was compiled.
5768     testptr(method_result, method_result);
5769     jcc(Assembler::zero, L_no_such_interface);
5770     addptr(scan_temp, scan_step);
5771   }
5772 
5773   bind(found_method);
5774 
5775   if (return_method) {
5776     // Got a hit.
5777     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5778     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5779   }
5780 }
5781 
5782 
5783 // virtual method calling
5784 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5785                                            RegisterOrConstant vtable_index,
5786                                            Register method_result) {
5787   const int base = in_bytes(Klass::vtable_start_offset());
5788   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5789   Address vtable_entry_addr(recv_klass,
5790                             vtable_index, Address::times_ptr,
5791                             base + vtableEntry::method_offset_in_bytes());
5792   movptr(method_result, vtable_entry_addr);
5793 }
5794 
5795 
5796 void MacroAssembler::check_klass_subtype(Register sub_klass,
5797                            Register super_klass,
5798                            Register temp_reg,
5799                            Label& L_success) {
5800   Label L_failure;
5801   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5802   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5803   bind(L_failure);
5804 }
5805 
5806 
5807 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5808                                                    Register super_klass,
5809                                                    Register temp_reg,
5810                                                    Label* L_success,
5811                                                    Label* L_failure,
5812                                                    Label* L_slow_path,
5813                                         RegisterOrConstant super_check_offset) {
5814   assert_different_registers(sub_klass, super_klass, temp_reg);
5815   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5816   if (super_check_offset.is_register()) {
5817     assert_different_registers(sub_klass, super_klass,
5818                                super_check_offset.as_register());
5819   } else if (must_load_sco) {
5820     assert(temp_reg != noreg, "supply either a temp or a register offset");
5821   }
5822 
5823   Label L_fallthrough;
5824   int label_nulls = 0;
5825   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5826   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5827   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5828   assert(label_nulls <= 1, "at most one NULL in the batch");
5829 
5830   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5831   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5832   Address super_check_offset_addr(super_klass, sco_offset);
5833 
5834   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5835   // range of a jccb.  If this routine grows larger, reconsider at
5836   // least some of these.
5837 #define local_jcc(assembler_cond, label)                                \
5838   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5839   else                             jcc( assembler_cond, label) /*omit semi*/
5840 
5841   // Hacked jmp, which may only be used just before L_fallthrough.
5842 #define final_jmp(label)                                                \
5843   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5844   else                            jmp(label)                /*omit semi*/
5845 
5846   // If the pointers are equal, we are done (e.g., String[] elements).
5847   // This self-check enables sharing of secondary supertype arrays among
5848   // non-primary types such as array-of-interface.  Otherwise, each such
5849   // type would need its own customized SSA.
5850   // We move this check to the front of the fast path because many
5851   // type checks are in fact trivially successful in this manner,
5852   // so we get a nicely predicted branch right at the start of the check.
5853   cmpptr(sub_klass, super_klass);
5854   local_jcc(Assembler::equal, *L_success);
5855 
5856   // Check the supertype display:
5857   if (must_load_sco) {
5858     // Positive movl does right thing on LP64.
5859     movl(temp_reg, super_check_offset_addr);
5860     super_check_offset = RegisterOrConstant(temp_reg);
5861   }
5862   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5863   cmpptr(super_klass, super_check_addr); // load displayed supertype
5864 
5865   // This check has worked decisively for primary supers.
5866   // Secondary supers are sought in the super_cache ('super_cache_addr').
5867   // (Secondary supers are interfaces and very deeply nested subtypes.)
5868   // This works in the same check above because of a tricky aliasing
5869   // between the super_cache and the primary super display elements.
5870   // (The 'super_check_addr' can address either, as the case requires.)
5871   // Note that the cache is updated below if it does not help us find
5872   // what we need immediately.
5873   // So if it was a primary super, we can just fail immediately.
5874   // Otherwise, it's the slow path for us (no success at this point).
5875 
5876   if (super_check_offset.is_register()) {
5877     local_jcc(Assembler::equal, *L_success);
5878     cmpl(super_check_offset.as_register(), sc_offset);
5879     if (L_failure == &L_fallthrough) {
5880       local_jcc(Assembler::equal, *L_slow_path);
5881     } else {
5882       local_jcc(Assembler::notEqual, *L_failure);
5883       final_jmp(*L_slow_path);
5884     }
5885   } else if (super_check_offset.as_constant() == sc_offset) {
5886     // Need a slow path; fast failure is impossible.
5887     if (L_slow_path == &L_fallthrough) {
5888       local_jcc(Assembler::equal, *L_success);
5889     } else {
5890       local_jcc(Assembler::notEqual, *L_slow_path);
5891       final_jmp(*L_success);
5892     }
5893   } else {
5894     // No slow path; it's a fast decision.
5895     if (L_failure == &L_fallthrough) {
5896       local_jcc(Assembler::equal, *L_success);
5897     } else {
5898       local_jcc(Assembler::notEqual, *L_failure);
5899       final_jmp(*L_success);
5900     }
5901   }
5902 
5903   bind(L_fallthrough);
5904 
5905 #undef local_jcc
5906 #undef final_jmp
5907 }
5908 
5909 
5910 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5911                                                    Register super_klass,
5912                                                    Register temp_reg,
5913                                                    Register temp2_reg,
5914                                                    Label* L_success,
5915                                                    Label* L_failure,
5916                                                    bool set_cond_codes) {
5917   assert_different_registers(sub_klass, super_klass, temp_reg);
5918   if (temp2_reg != noreg)
5919     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5920 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5921 
5922   Label L_fallthrough;
5923   int label_nulls = 0;
5924   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5925   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5926   assert(label_nulls <= 1, "at most one NULL in the batch");
5927 
5928   // a couple of useful fields in sub_klass:
5929   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5930   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5931   Address secondary_supers_addr(sub_klass, ss_offset);
5932   Address super_cache_addr(     sub_klass, sc_offset);
5933 
5934   // Do a linear scan of the secondary super-klass chain.
5935   // This code is rarely used, so simplicity is a virtue here.
5936   // The repne_scan instruction uses fixed registers, which we must spill.
5937   // Don't worry too much about pre-existing connections with the input regs.
5938 
5939   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5940   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5941 
5942   // Get super_klass value into rax (even if it was in rdi or rcx).
5943   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5944   if (super_klass != rax || UseCompressedOops) {
5945     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5946     mov(rax, super_klass);
5947   }
5948   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5949   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5950 
5951 #ifndef PRODUCT
5952   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5953   ExternalAddress pst_counter_addr((address) pst_counter);
5954   NOT_LP64(  incrementl(pst_counter_addr) );
5955   LP64_ONLY( lea(rcx, pst_counter_addr) );
5956   LP64_ONLY( incrementl(Address(rcx, 0)) );
5957 #endif //PRODUCT
5958 
5959   // We will consult the secondary-super array.
5960   movptr(rdi, secondary_supers_addr);
5961   // Load the array length.  (Positive movl does right thing on LP64.)
5962   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5963   // Skip to start of data.
5964   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5965 
5966   // Scan RCX words at [RDI] for an occurrence of RAX.
5967   // Set NZ/Z based on last compare.
5968   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5969   // not change flags (only scas instruction which is repeated sets flags).
5970   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5971 
5972     testptr(rax,rax); // Set Z = 0
5973     repne_scan();
5974 
5975   // Unspill the temp. registers:
5976   if (pushed_rdi)  pop(rdi);
5977   if (pushed_rcx)  pop(rcx);
5978   if (pushed_rax)  pop(rax);
5979 
5980   if (set_cond_codes) {
5981     // Special hack for the AD files:  rdi is guaranteed non-zero.
5982     assert(!pushed_rdi, "rdi must be left non-NULL");
5983     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5984   }
5985 
5986   if (L_failure == &L_fallthrough)
5987         jccb(Assembler::notEqual, *L_failure);
5988   else  jcc(Assembler::notEqual, *L_failure);
5989 
5990   // Success.  Cache the super we found and proceed in triumph.
5991   movptr(super_cache_addr, super_klass);
5992 
5993   if (L_success != &L_fallthrough) {
5994     jmp(*L_success);
5995   }
5996 
5997 #undef IS_A_TEMP
5998 
5999   bind(L_fallthrough);
6000 }
6001 
6002 
6003 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6004   if (VM_Version::supports_cmov()) {
6005     cmovl(cc, dst, src);
6006   } else {
6007     Label L;
6008     jccb(negate_condition(cc), L);
6009     movl(dst, src);
6010     bind(L);
6011   }
6012 }
6013 
6014 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6015   if (VM_Version::supports_cmov()) {
6016     cmovl(cc, dst, src);
6017   } else {
6018     Label L;
6019     jccb(negate_condition(cc), L);
6020     movl(dst, src);
6021     bind(L);
6022   }
6023 }
6024 
6025 void MacroAssembler::verify_oop(Register reg, const char* s) {
6026   if (!VerifyOops) return;
6027 
6028   // Pass register number to verify_oop_subroutine
6029   const char* b = NULL;
6030   {
6031     ResourceMark rm;
6032     stringStream ss;
6033     ss.print("verify_oop: %s: %s", reg->name(), s);
6034     b = code_string(ss.as_string());
6035   }
6036   BLOCK_COMMENT("verify_oop {");
6037 #ifdef _LP64
6038   push(rscratch1);                    // save r10, trashed by movptr()
6039 #endif
6040   push(rax);                          // save rax,
6041   push(reg);                          // pass register argument
6042   ExternalAddress buffer((address) b);
6043   // avoid using pushptr, as it modifies scratch registers
6044   // and our contract is not to modify anything
6045   movptr(rax, buffer.addr());
6046   push(rax);
6047   // call indirectly to solve generation ordering problem
6048   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6049   call(rax);
6050   // Caller pops the arguments (oop, message) and restores rax, r10
6051   BLOCK_COMMENT("} verify_oop");
6052 }
6053 
6054 
6055 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6056                                                       Register tmp,
6057                                                       int offset) {
6058   intptr_t value = *delayed_value_addr;
6059   if (value != 0)
6060     return RegisterOrConstant(value + offset);
6061 
6062   // load indirectly to solve generation ordering problem
6063   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6064 
6065 #ifdef ASSERT
6066   { Label L;
6067     testptr(tmp, tmp);
6068     if (WizardMode) {
6069       const char* buf = NULL;
6070       {
6071         ResourceMark rm;
6072         stringStream ss;
6073         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6074         buf = code_string(ss.as_string());
6075       }
6076       jcc(Assembler::notZero, L);
6077       STOP(buf);
6078     } else {
6079       jccb(Assembler::notZero, L);
6080       hlt();
6081     }
6082     bind(L);
6083   }
6084 #endif
6085 
6086   if (offset != 0)
6087     addptr(tmp, offset);
6088 
6089   return RegisterOrConstant(tmp);
6090 }
6091 
6092 
6093 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6094                                          int extra_slot_offset) {
6095   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6096   int stackElementSize = Interpreter::stackElementSize;
6097   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6098 #ifdef ASSERT
6099   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6100   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6101 #endif
6102   Register             scale_reg    = noreg;
6103   Address::ScaleFactor scale_factor = Address::no_scale;
6104   if (arg_slot.is_constant()) {
6105     offset += arg_slot.as_constant() * stackElementSize;
6106   } else {
6107     scale_reg    = arg_slot.as_register();
6108     scale_factor = Address::times(stackElementSize);
6109   }
6110   offset += wordSize;           // return PC is on stack
6111   return Address(rsp, scale_reg, scale_factor, offset);
6112 }
6113 
6114 
6115 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6116   if (!VerifyOops) return;
6117 
6118   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6119   // Pass register number to verify_oop_subroutine
6120   const char* b = NULL;
6121   {
6122     ResourceMark rm;
6123     stringStream ss;
6124     ss.print("verify_oop_addr: %s", s);
6125     b = code_string(ss.as_string());
6126   }
6127 #ifdef _LP64
6128   push(rscratch1);                    // save r10, trashed by movptr()
6129 #endif
6130   push(rax);                          // save rax,
6131   // addr may contain rsp so we will have to adjust it based on the push
6132   // we just did (and on 64 bit we do two pushes)
6133   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6134   // stores rax into addr which is backwards of what was intended.
6135   if (addr.uses(rsp)) {
6136     lea(rax, addr);
6137     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6138   } else {
6139     pushptr(addr);
6140   }
6141 
6142   ExternalAddress buffer((address) b);
6143   // pass msg argument
6144   // avoid using pushptr, as it modifies scratch registers
6145   // and our contract is not to modify anything
6146   movptr(rax, buffer.addr());
6147   push(rax);
6148 
6149   // call indirectly to solve generation ordering problem
6150   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6151   call(rax);
6152   // Caller pops the arguments (addr, message) and restores rax, r10.
6153 }
6154 
6155 void MacroAssembler::verify_tlab() {
6156 #ifdef ASSERT
6157   if (UseTLAB && VerifyOops) {
6158     Label next, ok;
6159     Register t1 = rsi;
6160     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6161 
6162     push(t1);
6163     NOT_LP64(push(thread_reg));
6164     NOT_LP64(get_thread(thread_reg));
6165 
6166     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6167     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6168     jcc(Assembler::aboveEqual, next);
6169     STOP("assert(top >= start)");
6170     should_not_reach_here();
6171 
6172     bind(next);
6173     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6174     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6175     jcc(Assembler::aboveEqual, ok);
6176     STOP("assert(top <= end)");
6177     should_not_reach_here();
6178 
6179     bind(ok);
6180     NOT_LP64(pop(thread_reg));
6181     pop(t1);
6182   }
6183 #endif
6184 }
6185 
6186 class ControlWord {
6187  public:
6188   int32_t _value;
6189 
6190   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6191   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6192   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6193   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6194   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6195   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6196   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6197   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6198 
6199   void print() const {
6200     // rounding control
6201     const char* rc;
6202     switch (rounding_control()) {
6203       case 0: rc = "round near"; break;
6204       case 1: rc = "round down"; break;
6205       case 2: rc = "round up  "; break;
6206       case 3: rc = "chop      "; break;
6207     };
6208     // precision control
6209     const char* pc;
6210     switch (precision_control()) {
6211       case 0: pc = "24 bits "; break;
6212       case 1: pc = "reserved"; break;
6213       case 2: pc = "53 bits "; break;
6214       case 3: pc = "64 bits "; break;
6215     };
6216     // flags
6217     char f[9];
6218     f[0] = ' ';
6219     f[1] = ' ';
6220     f[2] = (precision   ()) ? 'P' : 'p';
6221     f[3] = (underflow   ()) ? 'U' : 'u';
6222     f[4] = (overflow    ()) ? 'O' : 'o';
6223     f[5] = (zero_divide ()) ? 'Z' : 'z';
6224     f[6] = (denormalized()) ? 'D' : 'd';
6225     f[7] = (invalid     ()) ? 'I' : 'i';
6226     f[8] = '\x0';
6227     // output
6228     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6229   }
6230 
6231 };
6232 
6233 class StatusWord {
6234  public:
6235   int32_t _value;
6236 
6237   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6238   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6239   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6240   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6241   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6242   int  top() const                     { return  (_value >> 11) & 7      ; }
6243   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6244   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6245   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6246   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6247   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6248   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6249   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6250   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6251 
6252   void print() const {
6253     // condition codes
6254     char c[5];
6255     c[0] = (C3()) ? '3' : '-';
6256     c[1] = (C2()) ? '2' : '-';
6257     c[2] = (C1()) ? '1' : '-';
6258     c[3] = (C0()) ? '0' : '-';
6259     c[4] = '\x0';
6260     // flags
6261     char f[9];
6262     f[0] = (error_status()) ? 'E' : '-';
6263     f[1] = (stack_fault ()) ? 'S' : '-';
6264     f[2] = (precision   ()) ? 'P' : '-';
6265     f[3] = (underflow   ()) ? 'U' : '-';
6266     f[4] = (overflow    ()) ? 'O' : '-';
6267     f[5] = (zero_divide ()) ? 'Z' : '-';
6268     f[6] = (denormalized()) ? 'D' : '-';
6269     f[7] = (invalid     ()) ? 'I' : '-';
6270     f[8] = '\x0';
6271     // output
6272     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6273   }
6274 
6275 };
6276 
6277 class TagWord {
6278  public:
6279   int32_t _value;
6280 
6281   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6282 
6283   void print() const {
6284     printf("%04x", _value & 0xFFFF);
6285   }
6286 
6287 };
6288 
6289 class FPU_Register {
6290  public:
6291   int32_t _m0;
6292   int32_t _m1;
6293   int16_t _ex;
6294 
6295   bool is_indefinite() const           {
6296     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6297   }
6298 
6299   void print() const {
6300     char  sign = (_ex < 0) ? '-' : '+';
6301     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6302     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6303   };
6304 
6305 };
6306 
6307 class FPU_State {
6308  public:
6309   enum {
6310     register_size       = 10,
6311     number_of_registers =  8,
6312     register_mask       =  7
6313   };
6314 
6315   ControlWord  _control_word;
6316   StatusWord   _status_word;
6317   TagWord      _tag_word;
6318   int32_t      _error_offset;
6319   int32_t      _error_selector;
6320   int32_t      _data_offset;
6321   int32_t      _data_selector;
6322   int8_t       _register[register_size * number_of_registers];
6323 
6324   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6325   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6326 
6327   const char* tag_as_string(int tag) const {
6328     switch (tag) {
6329       case 0: return "valid";
6330       case 1: return "zero";
6331       case 2: return "special";
6332       case 3: return "empty";
6333     }
6334     ShouldNotReachHere();
6335     return NULL;
6336   }
6337 
6338   void print() const {
6339     // print computation registers
6340     { int t = _status_word.top();
6341       for (int i = 0; i < number_of_registers; i++) {
6342         int j = (i - t) & register_mask;
6343         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6344         st(j)->print();
6345         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6346       }
6347     }
6348     printf("\n");
6349     // print control registers
6350     printf("ctrl = "); _control_word.print(); printf("\n");
6351     printf("stat = "); _status_word .print(); printf("\n");
6352     printf("tags = "); _tag_word    .print(); printf("\n");
6353   }
6354 
6355 };
6356 
6357 class Flag_Register {
6358  public:
6359   int32_t _value;
6360 
6361   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6362   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6363   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6364   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6365   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6366   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6367   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6368 
6369   void print() const {
6370     // flags
6371     char f[8];
6372     f[0] = (overflow       ()) ? 'O' : '-';
6373     f[1] = (direction      ()) ? 'D' : '-';
6374     f[2] = (sign           ()) ? 'S' : '-';
6375     f[3] = (zero           ()) ? 'Z' : '-';
6376     f[4] = (auxiliary_carry()) ? 'A' : '-';
6377     f[5] = (parity         ()) ? 'P' : '-';
6378     f[6] = (carry          ()) ? 'C' : '-';
6379     f[7] = '\x0';
6380     // output
6381     printf("%08x  flags = %s", _value, f);
6382   }
6383 
6384 };
6385 
6386 class IU_Register {
6387  public:
6388   int32_t _value;
6389 
6390   void print() const {
6391     printf("%08x  %11d", _value, _value);
6392   }
6393 
6394 };
6395 
6396 class IU_State {
6397  public:
6398   Flag_Register _eflags;
6399   IU_Register   _rdi;
6400   IU_Register   _rsi;
6401   IU_Register   _rbp;
6402   IU_Register   _rsp;
6403   IU_Register   _rbx;
6404   IU_Register   _rdx;
6405   IU_Register   _rcx;
6406   IU_Register   _rax;
6407 
6408   void print() const {
6409     // computation registers
6410     printf("rax,  = "); _rax.print(); printf("\n");
6411     printf("rbx,  = "); _rbx.print(); printf("\n");
6412     printf("rcx  = "); _rcx.print(); printf("\n");
6413     printf("rdx  = "); _rdx.print(); printf("\n");
6414     printf("rdi  = "); _rdi.print(); printf("\n");
6415     printf("rsi  = "); _rsi.print(); printf("\n");
6416     printf("rbp,  = "); _rbp.print(); printf("\n");
6417     printf("rsp  = "); _rsp.print(); printf("\n");
6418     printf("\n");
6419     // control registers
6420     printf("flgs = "); _eflags.print(); printf("\n");
6421   }
6422 };
6423 
6424 
6425 class CPU_State {
6426  public:
6427   FPU_State _fpu_state;
6428   IU_State  _iu_state;
6429 
6430   void print() const {
6431     printf("--------------------------------------------------\n");
6432     _iu_state .print();
6433     printf("\n");
6434     _fpu_state.print();
6435     printf("--------------------------------------------------\n");
6436   }
6437 
6438 };
6439 
6440 
6441 static void _print_CPU_state(CPU_State* state) {
6442   state->print();
6443 };
6444 
6445 
6446 void MacroAssembler::print_CPU_state() {
6447   push_CPU_state();
6448   push(rsp);                // pass CPU state
6449   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6450   addptr(rsp, wordSize);       // discard argument
6451   pop_CPU_state();
6452 }
6453 
6454 
6455 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6456   static int counter = 0;
6457   FPU_State* fs = &state->_fpu_state;
6458   counter++;
6459   // For leaf calls, only verify that the top few elements remain empty.
6460   // We only need 1 empty at the top for C2 code.
6461   if( stack_depth < 0 ) {
6462     if( fs->tag_for_st(7) != 3 ) {
6463       printf("FPR7 not empty\n");
6464       state->print();
6465       assert(false, "error");
6466       return false;
6467     }
6468     return true;                // All other stack states do not matter
6469   }
6470 
6471   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6472          "bad FPU control word");
6473 
6474   // compute stack depth
6475   int i = 0;
6476   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6477   int d = i;
6478   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6479   // verify findings
6480   if (i != FPU_State::number_of_registers) {
6481     // stack not contiguous
6482     printf("%s: stack not contiguous at ST%d\n", s, i);
6483     state->print();
6484     assert(false, "error");
6485     return false;
6486   }
6487   // check if computed stack depth corresponds to expected stack depth
6488   if (stack_depth < 0) {
6489     // expected stack depth is -stack_depth or less
6490     if (d > -stack_depth) {
6491       // too many elements on the stack
6492       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6493       state->print();
6494       assert(false, "error");
6495       return false;
6496     }
6497   } else {
6498     // expected stack depth is stack_depth
6499     if (d != stack_depth) {
6500       // wrong stack depth
6501       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6502       state->print();
6503       assert(false, "error");
6504       return false;
6505     }
6506   }
6507   // everything is cool
6508   return true;
6509 }
6510 
6511 
6512 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6513   if (!VerifyFPU) return;
6514   push_CPU_state();
6515   push(rsp);                // pass CPU state
6516   ExternalAddress msg((address) s);
6517   // pass message string s
6518   pushptr(msg.addr());
6519   push(stack_depth);        // pass stack depth
6520   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6521   addptr(rsp, 3 * wordSize);   // discard arguments
6522   // check for error
6523   { Label L;
6524     testl(rax, rax);
6525     jcc(Assembler::notZero, L);
6526     int3();                  // break if error condition
6527     bind(L);
6528   }
6529   pop_CPU_state();
6530 }
6531 
6532 void MacroAssembler::restore_cpu_control_state_after_jni() {
6533   // Either restore the MXCSR register after returning from the JNI Call
6534   // or verify that it wasn't changed (with -Xcheck:jni flag).
6535   if (VM_Version::supports_sse()) {
6536     if (RestoreMXCSROnJNICalls) {
6537       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6538     } else if (CheckJNICalls) {
6539       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6540     }
6541   }
6542   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6543   vzeroupper();
6544   // Reset k1 to 0xffff.
6545   if (VM_Version::supports_evex()) {
6546     push(rcx);
6547     movl(rcx, 0xffff);
6548     kmovwl(k1, rcx);
6549     pop(rcx);
6550   }
6551 
6552 #ifndef _LP64
6553   // Either restore the x87 floating pointer control word after returning
6554   // from the JNI call or verify that it wasn't changed.
6555   if (CheckJNICalls) {
6556     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6557   }
6558 #endif // _LP64
6559 }
6560 
6561 // ((OopHandle)result).resolve();
6562 void MacroAssembler::resolve_oop_handle(Register result) {
6563   // OopHandle::resolve is an indirection.
6564   movptr(result, Address(result, 0));
6565 }
6566 
6567 void MacroAssembler::load_mirror(Register mirror, Register method) {
6568   // get mirror
6569   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6570   movptr(mirror, Address(method, Method::const_offset()));
6571   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6572   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6573   movptr(mirror, Address(mirror, mirror_offset));
6574   resolve_oop_handle(mirror);
6575 }
6576 
6577 void MacroAssembler::load_klass(Register dst, Register src) {
6578 #ifdef _LP64
6579   if (UseCompressedClassPointers) {
6580     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6581     decode_klass_not_null(dst);
6582   } else
6583 #endif
6584     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6585 }
6586 
6587 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6588   load_klass(dst, src);
6589   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6590 }
6591 
6592 void MacroAssembler::store_klass(Register dst, Register src) {
6593 #ifdef _LP64
6594   if (UseCompressedClassPointers) {
6595     encode_klass_not_null(src);
6596     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6597   } else
6598 #endif
6599     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6600 }
6601 
6602 #if INCLUDE_ALL_GCS && defined(_LP64)
6603 
6604 void MacroAssembler::load_barrier(Register ref, Address ref_addr, bool expand_call, LoadBarrierOn on) {
6605   Label done;
6606   const Register resolved_ref_addr = rsi;
6607   assert_different_registers(ref, resolved_ref_addr);
6608 
6609   BLOCK_COMMENT("load_barrier {");
6610 
6611   // Save temp register
6612   push(resolved_ref_addr);
6613 
6614   // Resolve reference address now, ref_addr might use the same register as ref,
6615   // which means it gets killed when we write to ref.
6616   lea(resolved_ref_addr, ref_addr);
6617 
6618   // Load reference
6619   movptr(ref, Address(resolved_ref_addr, 0));
6620 
6621   // Check if mask is not bad, which includes an implicit null check.
6622   testptr(ref, Address(r15_thread, JavaThread::zaddress_bad_mask_offset()));
6623   jcc(Assembler::zero, done);
6624 
6625   // Save live registers
6626   push(rax);
6627   push(rcx);
6628   push(rdx);
6629   push(rdi);
6630   push(r8);
6631   push(r9);
6632   push(r10);
6633   push(r11);
6634 
6635   // We may end up here from generate_native_wrapper, then the method may have
6636   // floats as arguments, and we must spill them before calling the VM runtime
6637   // leaf. From the interpreter all floats are passed on the stack.
6638   assert(Argument::n_float_register_parameters_j == 8, "Found %d float regs", Argument::n_float_register_parameters_j);
6639   int f_spill_size = Argument::n_float_register_parameters_j * wordSize * 2;
6640   subptr(rsp, f_spill_size);
6641   movdqu(Address(rsp, 14 * wordSize), xmm7);
6642   movdqu(Address(rsp, 12 * wordSize), xmm6);
6643   movdqu(Address(rsp, 10 * wordSize), xmm5);
6644   movdqu(Address(rsp, 8 * wordSize), xmm4);
6645   movdqu(Address(rsp, 6 * wordSize), xmm3);
6646   movdqu(Address(rsp, 4 * wordSize), xmm2);
6647   movdqu(Address(rsp, 2 * wordSize), xmm1);
6648   movdqu(Address(rsp, 0 * wordSize), xmm0);
6649 
6650   // Call into VM to handle the slow path
6651   if (expand_call) {
6652     assert(ref != c_rarg1, "smashed arg");
6653     pass_arg1(this, resolved_ref_addr);
6654     pass_arg0(this, ref);
6655     switch (on) {
6656     case LoadBarrierOnStrongOopRef:
6657       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_oop_field_preloaded), 2);
6658       break;
6659     case LoadBarrierOnWeakOopRef:
6660       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_weak_oop_field_preloaded), 2);
6661       break;
6662     case LoadBarrierOnPhantomOopRef:
6663       MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_phantom_oop_field_preloaded), 2);
6664       break;
6665     default:
6666       fatal("Unknown strength: %d", on);
6667       break;
6668     }
6669   } else {
6670     switch (on) {
6671     case LoadBarrierOnStrongOopRef:
6672       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_oop_field_preloaded), ref, resolved_ref_addr);
6673       break;
6674     case LoadBarrierOnWeakOopRef:
6675       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_weak_oop_field_preloaded), ref, resolved_ref_addr);
6676       break;
6677     case LoadBarrierOnPhantomOopRef:
6678       call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::z_load_barrier_on_phantom_oop_field_preloaded), ref, resolved_ref_addr);
6679       break;
6680     default: fatal("Unknown strength: %d", on);
6681       break;
6682     }
6683   }
6684 
6685   // Restore live registers
6686   movdqu(xmm0, Address(rsp, 0 * wordSize));
6687   movdqu(xmm1, Address(rsp, 2 * wordSize));
6688   movdqu(xmm2, Address(rsp, 4 * wordSize));
6689   movdqu(xmm3, Address(rsp, 6 * wordSize));
6690   movdqu(xmm4, Address(rsp, 8 * wordSize));
6691   movdqu(xmm5, Address(rsp, 10 * wordSize));
6692   movdqu(xmm6, Address(rsp, 12 * wordSize));
6693   movdqu(xmm7, Address(rsp, 14 * wordSize));
6694   addptr(rsp, f_spill_size);
6695 
6696   pop(r11);
6697   pop(r10);
6698   pop(r9);
6699   pop(r8);
6700   pop(rdi);
6701   pop(rdx);
6702   pop(rcx);
6703 
6704   if (ref == rax) {
6705     addptr(rsp, wordSize);
6706   } else {
6707     movptr(ref, rax);
6708     pop(rax);
6709   }
6710 
6711   bind(done);
6712 
6713   // Restore temp register
6714   pop(resolved_ref_addr);
6715 
6716   BLOCK_COMMENT("} load_barrier");
6717 }
6718 
6719 #endif
6720 
6721 void MacroAssembler::load_heap_oop(Register dst, Address src, bool expand_call, LoadBarrierOn on) {
6722 #ifdef _LP64
6723 #if INCLUDE_ALL_GCS
6724   if (UseLoadBarrier) {
6725     load_barrier(dst, src, expand_call, on);
6726   } else
6727 #endif
6728   if (UseCompressedOops) {
6729     movl(dst, src);
6730     decode_heap_oop(dst);
6731   } else
6732 #endif
6733     movptr(dst, src);
6734 }
6735 
6736 // Doesn't do verfication, generates fixed size code
6737 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6738 #ifdef _LP64
6739   if (UseCompressedOops) {
6740     movl(dst, src);
6741     decode_heap_oop_not_null(dst);
6742   } else
6743 #endif
6744     movptr(dst, src);
6745 }
6746 
6747 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6748 #ifdef ASSERT
6749   if (VerifyOops && UseLoadBarrier) {
6750     // Check if mask is good
6751     Label done;
6752     testptr(src, Address(r15_thread, JavaThread::zaddress_bad_mask_offset()));
6753     jcc(Assembler::zero, done);
6754     STOP("Writing broken oop");
6755     should_not_reach_here();
6756     bind(done);
6757   }
6758 #endif
6759 
6760 #ifdef _LP64
6761   if (UseCompressedOops) {
6762     assert(!dst.uses(src), "not enough registers");
6763     encode_heap_oop(src);
6764     movl(dst, src);
6765   } else
6766 #endif
6767     movptr(dst, src);
6768 }
6769 
6770 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6771   assert_different_registers(src1, tmp);
6772 #ifdef _LP64
6773   if (UseCompressedOops) {
6774     bool did_push = false;
6775     if (tmp == noreg) {
6776       tmp = rax;
6777       push(tmp);
6778       did_push = true;
6779       assert(!src2.uses(rsp), "can't push");
6780     }
6781     load_heap_oop(tmp, src2);
6782     cmpptr(src1, tmp);
6783     if (did_push)  pop(tmp);
6784   } else
6785 #endif
6786     cmpptr(src1, src2);
6787 }
6788 
6789 // Used for storing NULLs.
6790 void MacroAssembler::store_heap_oop_null(Address dst) {
6791 #ifdef _LP64
6792   if (UseCompressedOops) {
6793     movl(dst, (int32_t)NULL_WORD);
6794   } else {
6795     movslq(dst, (int32_t)NULL_WORD);
6796   }
6797 #else
6798   movl(dst, (int32_t)NULL_WORD);
6799 #endif
6800 }
6801 
6802 #ifdef _LP64
6803 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6804   if (UseCompressedClassPointers) {
6805     // Store to klass gap in destination
6806     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6807   }
6808 }
6809 
6810 #ifdef ASSERT
6811 void MacroAssembler::verify_heapbase(const char* msg) {
6812   assert (UseCompressedOops, "should be compressed");
6813   assert (Universe::heap() != NULL, "java heap should be initialized");
6814   if (CheckCompressedOops) {
6815     Label ok;
6816     push(rscratch1); // cmpptr trashes rscratch1
6817     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6818     jcc(Assembler::equal, ok);
6819     STOP(msg);
6820     bind(ok);
6821     pop(rscratch1);
6822   }
6823 }
6824 #endif
6825 
6826 // Algorithm must match oop.inline.hpp encode_heap_oop.
6827 void MacroAssembler::encode_heap_oop(Register r) {
6828 #ifdef ASSERT
6829   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6830 #endif
6831   verify_oop(r, "broken oop in encode_heap_oop");
6832   if (Universe::narrow_oop_base() == NULL) {
6833     if (Universe::narrow_oop_shift() != 0) {
6834       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6835       shrq(r, LogMinObjAlignmentInBytes);
6836     }
6837     return;
6838   }
6839   testq(r, r);
6840   cmovq(Assembler::equal, r, r12_heapbase);
6841   subq(r, r12_heapbase);
6842   shrq(r, LogMinObjAlignmentInBytes);
6843 }
6844 
6845 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6846 #ifdef ASSERT
6847   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6848   if (CheckCompressedOops) {
6849     Label ok;
6850     testq(r, r);
6851     jcc(Assembler::notEqual, ok);
6852     STOP("null oop passed to encode_heap_oop_not_null");
6853     bind(ok);
6854   }
6855 #endif
6856   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6857   if (Universe::narrow_oop_base() != NULL) {
6858     subq(r, r12_heapbase);
6859   }
6860   if (Universe::narrow_oop_shift() != 0) {
6861     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6862     shrq(r, LogMinObjAlignmentInBytes);
6863   }
6864 }
6865 
6866 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6867 #ifdef ASSERT
6868   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6869   if (CheckCompressedOops) {
6870     Label ok;
6871     testq(src, src);
6872     jcc(Assembler::notEqual, ok);
6873     STOP("null oop passed to encode_heap_oop_not_null2");
6874     bind(ok);
6875   }
6876 #endif
6877   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6878   if (dst != src) {
6879     movq(dst, src);
6880   }
6881   if (Universe::narrow_oop_base() != NULL) {
6882     subq(dst, r12_heapbase);
6883   }
6884   if (Universe::narrow_oop_shift() != 0) {
6885     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6886     shrq(dst, LogMinObjAlignmentInBytes);
6887   }
6888 }
6889 
6890 void  MacroAssembler::decode_heap_oop(Register r) {
6891 #ifdef ASSERT
6892   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6893 #endif
6894   if (Universe::narrow_oop_base() == NULL) {
6895     if (Universe::narrow_oop_shift() != 0) {
6896       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6897       shlq(r, LogMinObjAlignmentInBytes);
6898     }
6899   } else {
6900     Label done;
6901     shlq(r, LogMinObjAlignmentInBytes);
6902     jccb(Assembler::equal, done);
6903     addq(r, r12_heapbase);
6904     bind(done);
6905   }
6906   verify_oop(r, "broken oop in decode_heap_oop");
6907 }
6908 
6909 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6910   // Note: it will change flags
6911   assert (UseCompressedOops, "should only be used for compressed headers");
6912   assert (Universe::heap() != NULL, "java heap should be initialized");
6913   // Cannot assert, unverified entry point counts instructions (see .ad file)
6914   // vtableStubs also counts instructions in pd_code_size_limit.
6915   // Also do not verify_oop as this is called by verify_oop.
6916   if (Universe::narrow_oop_shift() != 0) {
6917     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6918     shlq(r, LogMinObjAlignmentInBytes);
6919     if (Universe::narrow_oop_base() != NULL) {
6920       addq(r, r12_heapbase);
6921     }
6922   } else {
6923     assert (Universe::narrow_oop_base() == NULL, "sanity");
6924   }
6925 }
6926 
6927 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6928   // Note: it will change flags
6929   assert (UseCompressedOops, "should only be used for compressed headers");
6930   assert (Universe::heap() != NULL, "java heap should be initialized");
6931   // Cannot assert, unverified entry point counts instructions (see .ad file)
6932   // vtableStubs also counts instructions in pd_code_size_limit.
6933   // Also do not verify_oop as this is called by verify_oop.
6934   if (Universe::narrow_oop_shift() != 0) {
6935     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6936     if (LogMinObjAlignmentInBytes == Address::times_8) {
6937       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6938     } else {
6939       if (dst != src) {
6940         movq(dst, src);
6941       }
6942       shlq(dst, LogMinObjAlignmentInBytes);
6943       if (Universe::narrow_oop_base() != NULL) {
6944         addq(dst, r12_heapbase);
6945       }
6946     }
6947   } else {
6948     assert (Universe::narrow_oop_base() == NULL, "sanity");
6949     if (dst != src) {
6950       movq(dst, src);
6951     }
6952   }
6953 }
6954 
6955 void MacroAssembler::encode_klass_not_null(Register r) {
6956   if (Universe::narrow_klass_base() != NULL) {
6957     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6958     assert(r != r12_heapbase, "Encoding a klass in r12");
6959     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6960     subq(r, r12_heapbase);
6961   }
6962   if (Universe::narrow_klass_shift() != 0) {
6963     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6964     shrq(r, LogKlassAlignmentInBytes);
6965   }
6966   if (Universe::narrow_klass_base() != NULL) {
6967     reinit_heapbase();
6968   }
6969 }
6970 
6971 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6972   if (dst == src) {
6973     encode_klass_not_null(src);
6974   } else {
6975     if (Universe::narrow_klass_base() != NULL) {
6976       mov64(dst, (int64_t)Universe::narrow_klass_base());
6977       negq(dst);
6978       addq(dst, src);
6979     } else {
6980       movptr(dst, src);
6981     }
6982     if (Universe::narrow_klass_shift() != 0) {
6983       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6984       shrq(dst, LogKlassAlignmentInBytes);
6985     }
6986   }
6987 }
6988 
6989 // Function instr_size_for_decode_klass_not_null() counts the instructions
6990 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6991 // when (Universe::heap() != NULL).  Hence, if the instructions they
6992 // generate change, then this method needs to be updated.
6993 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6994   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6995   if (Universe::narrow_klass_base() != NULL) {
6996     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6997     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6998   } else {
6999     // longest load decode klass function, mov64, leaq
7000     return 16;
7001   }
7002 }
7003 
7004 // !!! If the instructions that get generated here change then function
7005 // instr_size_for_decode_klass_not_null() needs to get updated.
7006 void  MacroAssembler::decode_klass_not_null(Register r) {
7007   // Note: it will change flags
7008   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7009   assert(r != r12_heapbase, "Decoding a klass in r12");
7010   // Cannot assert, unverified entry point counts instructions (see .ad file)
7011   // vtableStubs also counts instructions in pd_code_size_limit.
7012   // Also do not verify_oop as this is called by verify_oop.
7013   if (Universe::narrow_klass_shift() != 0) {
7014     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7015     shlq(r, LogKlassAlignmentInBytes);
7016   }
7017   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
7018   if (Universe::narrow_klass_base() != NULL) {
7019     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
7020     addq(r, r12_heapbase);
7021     reinit_heapbase();
7022   }
7023 }
7024 
7025 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
7026   // Note: it will change flags
7027   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7028   if (dst == src) {
7029     decode_klass_not_null(dst);
7030   } else {
7031     // Cannot assert, unverified entry point counts instructions (see .ad file)
7032     // vtableStubs also counts instructions in pd_code_size_limit.
7033     // Also do not verify_oop as this is called by verify_oop.
7034     mov64(dst, (int64_t)Universe::narrow_klass_base());
7035     if (Universe::narrow_klass_shift() != 0) {
7036       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
7037       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
7038       leaq(dst, Address(dst, src, Address::times_8, 0));
7039     } else {
7040       addq(dst, src);
7041     }
7042   }
7043 }
7044 
7045 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
7046   assert (UseCompressedOops, "should only be used for compressed headers");
7047   assert (Universe::heap() != NULL, "java heap should be initialized");
7048   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7049   int oop_index = oop_recorder()->find_index(obj);
7050   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7051   mov_narrow_oop(dst, oop_index, rspec);
7052 }
7053 
7054 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
7055   assert (UseCompressedOops, "should only be used for compressed headers");
7056   assert (Universe::heap() != NULL, "java heap should be initialized");
7057   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7058   int oop_index = oop_recorder()->find_index(obj);
7059   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7060   mov_narrow_oop(dst, oop_index, rspec);
7061 }
7062 
7063 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7064   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7065   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7066   int klass_index = oop_recorder()->find_index(k);
7067   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7068   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7069 }
7070 
7071 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7072   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7073   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7074   int klass_index = oop_recorder()->find_index(k);
7075   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7076   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7077 }
7078 
7079 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7080   assert (UseCompressedOops, "should only be used for compressed headers");
7081   assert (Universe::heap() != NULL, "java heap should be initialized");
7082   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7083   int oop_index = oop_recorder()->find_index(obj);
7084   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7085   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7086 }
7087 
7088 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7089   assert (UseCompressedOops, "should only be used for compressed headers");
7090   assert (Universe::heap() != NULL, "java heap should be initialized");
7091   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7092   int oop_index = oop_recorder()->find_index(obj);
7093   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7094   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7095 }
7096 
7097 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7098   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7099   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7100   int klass_index = oop_recorder()->find_index(k);
7101   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7102   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7103 }
7104 
7105 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7106   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7107   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7108   int klass_index = oop_recorder()->find_index(k);
7109   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7110   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7111 }
7112 
7113 void MacroAssembler::reinit_heapbase() {
7114   if (UseCompressedOops || UseCompressedClassPointers) {
7115     if (Universe::heap() != NULL) {
7116       if (Universe::narrow_oop_base() == NULL) {
7117         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7118       } else {
7119         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7120       }
7121     } else {
7122       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7123     }
7124   } else {
7125     mov64(r12, -1);
7126   }
7127 }
7128 
7129 #endif // _LP64
7130 
7131 // C2 compiled method's prolog code.
7132 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7133 
7134   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7135   // NativeJump::patch_verified_entry will be able to patch out the entry
7136   // code safely. The push to verify stack depth is ok at 5 bytes,
7137   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7138   // stack bang then we must use the 6 byte frame allocation even if
7139   // we have no frame. :-(
7140   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7141 
7142   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7143   // Remove word for return addr
7144   framesize -= wordSize;
7145   stack_bang_size -= wordSize;
7146 
7147   // Calls to C2R adapters often do not accept exceptional returns.
7148   // We require that their callers must bang for them.  But be careful, because
7149   // some VM calls (such as call site linkage) can use several kilobytes of
7150   // stack.  But the stack safety zone should account for that.
7151   // See bugs 4446381, 4468289, 4497237.
7152   if (stack_bang_size > 0) {
7153     generate_stack_overflow_check(stack_bang_size);
7154 
7155     // We always push rbp, so that on return to interpreter rbp, will be
7156     // restored correctly and we can correct the stack.
7157     push(rbp);
7158     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7159     if (PreserveFramePointer) {
7160       mov(rbp, rsp);
7161     }
7162     // Remove word for ebp
7163     framesize -= wordSize;
7164 
7165     // Create frame
7166     if (framesize) {
7167       subptr(rsp, framesize);
7168     }
7169   } else {
7170     // Create frame (force generation of a 4 byte immediate value)
7171     subptr_imm32(rsp, framesize);
7172 
7173     // Save RBP register now.
7174     framesize -= wordSize;
7175     movptr(Address(rsp, framesize), rbp);
7176     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7177     if (PreserveFramePointer) {
7178       movptr(rbp, rsp);
7179       if (framesize > 0) {
7180         addptr(rbp, framesize);
7181       }
7182     }
7183   }
7184 
7185   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7186     framesize -= wordSize;
7187     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7188   }
7189 
7190 #ifndef _LP64
7191   // If method sets FPU control word do it now
7192   if (fp_mode_24b) {
7193     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7194   }
7195   if (UseSSE >= 2 && VerifyFPU) {
7196     verify_FPU(0, "FPU stack must be clean on entry");
7197   }
7198 #endif
7199 
7200 #ifdef ASSERT
7201   if (VerifyStackAtCalls) {
7202     Label L;
7203     push(rax);
7204     mov(rax, rsp);
7205     andptr(rax, StackAlignmentInBytes-1);
7206     cmpptr(rax, StackAlignmentInBytes-wordSize);
7207     pop(rax);
7208     jcc(Assembler::equal, L);
7209     STOP("Stack is not properly aligned!");
7210     bind(L);
7211   }
7212 #endif
7213 
7214 }
7215 
7216 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7217   // cnt - number of qwords (8-byte words).
7218   // base - start address, qword aligned.
7219   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7220   assert(base==rdi, "base register must be edi for rep stos");
7221   assert(tmp==rax,   "tmp register must be eax for rep stos");
7222   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7223   assert(InitArrayShortSize % BytesPerLong == 0,
7224     "InitArrayShortSize should be the multiple of BytesPerLong");
7225 
7226   Label DONE;
7227 
7228   xorptr(tmp, tmp);
7229 
7230   if (!is_large) {
7231     Label LOOP, LONG;
7232     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7233     jccb(Assembler::greater, LONG);
7234 
7235     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7236 
7237     decrement(cnt);
7238     jccb(Assembler::negative, DONE); // Zero length
7239 
7240     // Use individual pointer-sized stores for small counts:
7241     BIND(LOOP);
7242     movptr(Address(base, cnt, Address::times_ptr), tmp);
7243     decrement(cnt);
7244     jccb(Assembler::greaterEqual, LOOP);
7245     jmpb(DONE);
7246 
7247     BIND(LONG);
7248   }
7249 
7250   // Use longer rep-prefixed ops for non-small counts:
7251   if (UseFastStosb) {
7252     shlptr(cnt, 3); // convert to number of bytes
7253     rep_stosb();
7254   } else {
7255     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7256     rep_stos();
7257   }
7258 
7259   BIND(DONE);
7260 }
7261 
7262 #ifdef COMPILER2
7263 
7264 // IndexOf for constant substrings with size >= 8 chars
7265 // which don't need to be loaded through stack.
7266 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7267                                       Register cnt1, Register cnt2,
7268                                       int int_cnt2,  Register result,
7269                                       XMMRegister vec, Register tmp,
7270                                       int ae) {
7271   ShortBranchVerifier sbv(this);
7272   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7273   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7274 
7275   // This method uses the pcmpestri instruction with bound registers
7276   //   inputs:
7277   //     xmm - substring
7278   //     rax - substring length (elements count)
7279   //     mem - scanned string
7280   //     rdx - string length (elements count)
7281   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7282   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7283   //   outputs:
7284   //     rcx - matched index in string
7285   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7286   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7287   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7288   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7289   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7290 
7291   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7292         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7293         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7294 
7295   // Note, inline_string_indexOf() generates checks:
7296   // if (substr.count > string.count) return -1;
7297   // if (substr.count == 0) return 0;
7298   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7299 
7300   // Load substring.
7301   if (ae == StrIntrinsicNode::UL) {
7302     pmovzxbw(vec, Address(str2, 0));
7303   } else {
7304     movdqu(vec, Address(str2, 0));
7305   }
7306   movl(cnt2, int_cnt2);
7307   movptr(result, str1); // string addr
7308 
7309   if (int_cnt2 > stride) {
7310     jmpb(SCAN_TO_SUBSTR);
7311 
7312     // Reload substr for rescan, this code
7313     // is executed only for large substrings (> 8 chars)
7314     bind(RELOAD_SUBSTR);
7315     if (ae == StrIntrinsicNode::UL) {
7316       pmovzxbw(vec, Address(str2, 0));
7317     } else {
7318       movdqu(vec, Address(str2, 0));
7319     }
7320     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7321 
7322     bind(RELOAD_STR);
7323     // We came here after the beginning of the substring was
7324     // matched but the rest of it was not so we need to search
7325     // again. Start from the next element after the previous match.
7326 
7327     // cnt2 is number of substring reminding elements and
7328     // cnt1 is number of string reminding elements when cmp failed.
7329     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7330     subl(cnt1, cnt2);
7331     addl(cnt1, int_cnt2);
7332     movl(cnt2, int_cnt2); // Now restore cnt2
7333 
7334     decrementl(cnt1);     // Shift to next element
7335     cmpl(cnt1, cnt2);
7336     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7337 
7338     addptr(result, (1<<scale1));
7339 
7340   } // (int_cnt2 > 8)
7341 
7342   // Scan string for start of substr in 16-byte vectors
7343   bind(SCAN_TO_SUBSTR);
7344   pcmpestri(vec, Address(result, 0), mode);
7345   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7346   subl(cnt1, stride);
7347   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7348   cmpl(cnt1, cnt2);
7349   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7350   addptr(result, 16);
7351   jmpb(SCAN_TO_SUBSTR);
7352 
7353   // Found a potential substr
7354   bind(FOUND_CANDIDATE);
7355   // Matched whole vector if first element matched (tmp(rcx) == 0).
7356   if (int_cnt2 == stride) {
7357     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7358   } else { // int_cnt2 > 8
7359     jccb(Assembler::overflow, FOUND_SUBSTR);
7360   }
7361   // After pcmpestri tmp(rcx) contains matched element index
7362   // Compute start addr of substr
7363   lea(result, Address(result, tmp, scale1));
7364 
7365   // Make sure string is still long enough
7366   subl(cnt1, tmp);
7367   cmpl(cnt1, cnt2);
7368   if (int_cnt2 == stride) {
7369     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7370   } else { // int_cnt2 > 8
7371     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7372   }
7373   // Left less then substring.
7374 
7375   bind(RET_NOT_FOUND);
7376   movl(result, -1);
7377   jmp(EXIT);
7378 
7379   if (int_cnt2 > stride) {
7380     // This code is optimized for the case when whole substring
7381     // is matched if its head is matched.
7382     bind(MATCH_SUBSTR_HEAD);
7383     pcmpestri(vec, Address(result, 0), mode);
7384     // Reload only string if does not match
7385     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7386 
7387     Label CONT_SCAN_SUBSTR;
7388     // Compare the rest of substring (> 8 chars).
7389     bind(FOUND_SUBSTR);
7390     // First 8 chars are already matched.
7391     negptr(cnt2);
7392     addptr(cnt2, stride);
7393 
7394     bind(SCAN_SUBSTR);
7395     subl(cnt1, stride);
7396     cmpl(cnt2, -stride); // Do not read beyond substring
7397     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7398     // Back-up strings to avoid reading beyond substring:
7399     // cnt1 = cnt1 - cnt2 + 8
7400     addl(cnt1, cnt2); // cnt2 is negative
7401     addl(cnt1, stride);
7402     movl(cnt2, stride); negptr(cnt2);
7403     bind(CONT_SCAN_SUBSTR);
7404     if (int_cnt2 < (int)G) {
7405       int tail_off1 = int_cnt2<<scale1;
7406       int tail_off2 = int_cnt2<<scale2;
7407       if (ae == StrIntrinsicNode::UL) {
7408         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7409       } else {
7410         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7411       }
7412       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7413     } else {
7414       // calculate index in register to avoid integer overflow (int_cnt2*2)
7415       movl(tmp, int_cnt2);
7416       addptr(tmp, cnt2);
7417       if (ae == StrIntrinsicNode::UL) {
7418         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7419       } else {
7420         movdqu(vec, Address(str2, tmp, scale2, 0));
7421       }
7422       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7423     }
7424     // Need to reload strings pointers if not matched whole vector
7425     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7426     addptr(cnt2, stride);
7427     jcc(Assembler::negative, SCAN_SUBSTR);
7428     // Fall through if found full substring
7429 
7430   } // (int_cnt2 > 8)
7431 
7432   bind(RET_FOUND);
7433   // Found result if we matched full small substring.
7434   // Compute substr offset
7435   subptr(result, str1);
7436   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7437     shrl(result, 1); // index
7438   }
7439   bind(EXIT);
7440 
7441 } // string_indexofC8
7442 
7443 // Small strings are loaded through stack if they cross page boundary.
7444 void MacroAssembler::string_indexof(Register str1, Register str2,
7445                                     Register cnt1, Register cnt2,
7446                                     int int_cnt2,  Register result,
7447                                     XMMRegister vec, Register tmp,
7448                                     int ae) {
7449   ShortBranchVerifier sbv(this);
7450   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7451   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7452 
7453   //
7454   // int_cnt2 is length of small (< 8 chars) constant substring
7455   // or (-1) for non constant substring in which case its length
7456   // is in cnt2 register.
7457   //
7458   // Note, inline_string_indexOf() generates checks:
7459   // if (substr.count > string.count) return -1;
7460   // if (substr.count == 0) return 0;
7461   //
7462   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7463   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7464   // This method uses the pcmpestri instruction with bound registers
7465   //   inputs:
7466   //     xmm - substring
7467   //     rax - substring length (elements count)
7468   //     mem - scanned string
7469   //     rdx - string length (elements count)
7470   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7471   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7472   //   outputs:
7473   //     rcx - matched index in string
7474   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7475   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7476   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7477   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7478 
7479   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7480         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7481         FOUND_CANDIDATE;
7482 
7483   { //========================================================
7484     // We don't know where these strings are located
7485     // and we can't read beyond them. Load them through stack.
7486     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7487 
7488     movptr(tmp, rsp); // save old SP
7489 
7490     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7491       if (int_cnt2 == (1>>scale2)) { // One byte
7492         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7493         load_unsigned_byte(result, Address(str2, 0));
7494         movdl(vec, result); // move 32 bits
7495       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7496         // Not enough header space in 32-bit VM: 12+3 = 15.
7497         movl(result, Address(str2, -1));
7498         shrl(result, 8);
7499         movdl(vec, result); // move 32 bits
7500       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7501         load_unsigned_short(result, Address(str2, 0));
7502         movdl(vec, result); // move 32 bits
7503       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7504         movdl(vec, Address(str2, 0)); // move 32 bits
7505       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7506         movq(vec, Address(str2, 0));  // move 64 bits
7507       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7508         // Array header size is 12 bytes in 32-bit VM
7509         // + 6 bytes for 3 chars == 18 bytes,
7510         // enough space to load vec and shift.
7511         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7512         if (ae == StrIntrinsicNode::UL) {
7513           int tail_off = int_cnt2-8;
7514           pmovzxbw(vec, Address(str2, tail_off));
7515           psrldq(vec, -2*tail_off);
7516         }
7517         else {
7518           int tail_off = int_cnt2*(1<<scale2);
7519           movdqu(vec, Address(str2, tail_off-16));
7520           psrldq(vec, 16-tail_off);
7521         }
7522       }
7523     } else { // not constant substring
7524       cmpl(cnt2, stride);
7525       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7526 
7527       // We can read beyond string if srt+16 does not cross page boundary
7528       // since heaps are aligned and mapped by pages.
7529       assert(os::vm_page_size() < (int)G, "default page should be small");
7530       movl(result, str2); // We need only low 32 bits
7531       andl(result, (os::vm_page_size()-1));
7532       cmpl(result, (os::vm_page_size()-16));
7533       jccb(Assembler::belowEqual, CHECK_STR);
7534 
7535       // Move small strings to stack to allow load 16 bytes into vec.
7536       subptr(rsp, 16);
7537       int stk_offset = wordSize-(1<<scale2);
7538       push(cnt2);
7539 
7540       bind(COPY_SUBSTR);
7541       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7542         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7543         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7544       } else if (ae == StrIntrinsicNode::UU) {
7545         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7546         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7547       }
7548       decrement(cnt2);
7549       jccb(Assembler::notZero, COPY_SUBSTR);
7550 
7551       pop(cnt2);
7552       movptr(str2, rsp);  // New substring address
7553     } // non constant
7554 
7555     bind(CHECK_STR);
7556     cmpl(cnt1, stride);
7557     jccb(Assembler::aboveEqual, BIG_STRINGS);
7558 
7559     // Check cross page boundary.
7560     movl(result, str1); // We need only low 32 bits
7561     andl(result, (os::vm_page_size()-1));
7562     cmpl(result, (os::vm_page_size()-16));
7563     jccb(Assembler::belowEqual, BIG_STRINGS);
7564 
7565     subptr(rsp, 16);
7566     int stk_offset = -(1<<scale1);
7567     if (int_cnt2 < 0) { // not constant
7568       push(cnt2);
7569       stk_offset += wordSize;
7570     }
7571     movl(cnt2, cnt1);
7572 
7573     bind(COPY_STR);
7574     if (ae == StrIntrinsicNode::LL) {
7575       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7576       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7577     } else {
7578       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7579       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7580     }
7581     decrement(cnt2);
7582     jccb(Assembler::notZero, COPY_STR);
7583 
7584     if (int_cnt2 < 0) { // not constant
7585       pop(cnt2);
7586     }
7587     movptr(str1, rsp);  // New string address
7588 
7589     bind(BIG_STRINGS);
7590     // Load substring.
7591     if (int_cnt2 < 0) { // -1
7592       if (ae == StrIntrinsicNode::UL) {
7593         pmovzxbw(vec, Address(str2, 0));
7594       } else {
7595         movdqu(vec, Address(str2, 0));
7596       }
7597       push(cnt2);       // substr count
7598       push(str2);       // substr addr
7599       push(str1);       // string addr
7600     } else {
7601       // Small (< 8 chars) constant substrings are loaded already.
7602       movl(cnt2, int_cnt2);
7603     }
7604     push(tmp);  // original SP
7605 
7606   } // Finished loading
7607 
7608   //========================================================
7609   // Start search
7610   //
7611 
7612   movptr(result, str1); // string addr
7613 
7614   if (int_cnt2  < 0) {  // Only for non constant substring
7615     jmpb(SCAN_TO_SUBSTR);
7616 
7617     // SP saved at sp+0
7618     // String saved at sp+1*wordSize
7619     // Substr saved at sp+2*wordSize
7620     // Substr count saved at sp+3*wordSize
7621 
7622     // Reload substr for rescan, this code
7623     // is executed only for large substrings (> 8 chars)
7624     bind(RELOAD_SUBSTR);
7625     movptr(str2, Address(rsp, 2*wordSize));
7626     movl(cnt2, Address(rsp, 3*wordSize));
7627     if (ae == StrIntrinsicNode::UL) {
7628       pmovzxbw(vec, Address(str2, 0));
7629     } else {
7630       movdqu(vec, Address(str2, 0));
7631     }
7632     // We came here after the beginning of the substring was
7633     // matched but the rest of it was not so we need to search
7634     // again. Start from the next element after the previous match.
7635     subptr(str1, result); // Restore counter
7636     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7637       shrl(str1, 1);
7638     }
7639     addl(cnt1, str1);
7640     decrementl(cnt1);   // Shift to next element
7641     cmpl(cnt1, cnt2);
7642     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7643 
7644     addptr(result, (1<<scale1));
7645   } // non constant
7646 
7647   // Scan string for start of substr in 16-byte vectors
7648   bind(SCAN_TO_SUBSTR);
7649   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7650   pcmpestri(vec, Address(result, 0), mode);
7651   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7652   subl(cnt1, stride);
7653   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7654   cmpl(cnt1, cnt2);
7655   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7656   addptr(result, 16);
7657 
7658   bind(ADJUST_STR);
7659   cmpl(cnt1, stride); // Do not read beyond string
7660   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7661   // Back-up string to avoid reading beyond string.
7662   lea(result, Address(result, cnt1, scale1, -16));
7663   movl(cnt1, stride);
7664   jmpb(SCAN_TO_SUBSTR);
7665 
7666   // Found a potential substr
7667   bind(FOUND_CANDIDATE);
7668   // After pcmpestri tmp(rcx) contains matched element index
7669 
7670   // Make sure string is still long enough
7671   subl(cnt1, tmp);
7672   cmpl(cnt1, cnt2);
7673   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7674   // Left less then substring.
7675 
7676   bind(RET_NOT_FOUND);
7677   movl(result, -1);
7678   jmpb(CLEANUP);
7679 
7680   bind(FOUND_SUBSTR);
7681   // Compute start addr of substr
7682   lea(result, Address(result, tmp, scale1));
7683   if (int_cnt2 > 0) { // Constant substring
7684     // Repeat search for small substring (< 8 chars)
7685     // from new point without reloading substring.
7686     // Have to check that we don't read beyond string.
7687     cmpl(tmp, stride-int_cnt2);
7688     jccb(Assembler::greater, ADJUST_STR);
7689     // Fall through if matched whole substring.
7690   } else { // non constant
7691     assert(int_cnt2 == -1, "should be != 0");
7692 
7693     addl(tmp, cnt2);
7694     // Found result if we matched whole substring.
7695     cmpl(tmp, stride);
7696     jccb(Assembler::lessEqual, RET_FOUND);
7697 
7698     // Repeat search for small substring (<= 8 chars)
7699     // from new point 'str1' without reloading substring.
7700     cmpl(cnt2, stride);
7701     // Have to check that we don't read beyond string.
7702     jccb(Assembler::lessEqual, ADJUST_STR);
7703 
7704     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7705     // Compare the rest of substring (> 8 chars).
7706     movptr(str1, result);
7707 
7708     cmpl(tmp, cnt2);
7709     // First 8 chars are already matched.
7710     jccb(Assembler::equal, CHECK_NEXT);
7711 
7712     bind(SCAN_SUBSTR);
7713     pcmpestri(vec, Address(str1, 0), mode);
7714     // Need to reload strings pointers if not matched whole vector
7715     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7716 
7717     bind(CHECK_NEXT);
7718     subl(cnt2, stride);
7719     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7720     addptr(str1, 16);
7721     if (ae == StrIntrinsicNode::UL) {
7722       addptr(str2, 8);
7723     } else {
7724       addptr(str2, 16);
7725     }
7726     subl(cnt1, stride);
7727     cmpl(cnt2, stride); // Do not read beyond substring
7728     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7729     // Back-up strings to avoid reading beyond substring.
7730 
7731     if (ae == StrIntrinsicNode::UL) {
7732       lea(str2, Address(str2, cnt2, scale2, -8));
7733       lea(str1, Address(str1, cnt2, scale1, -16));
7734     } else {
7735       lea(str2, Address(str2, cnt2, scale2, -16));
7736       lea(str1, Address(str1, cnt2, scale1, -16));
7737     }
7738     subl(cnt1, cnt2);
7739     movl(cnt2, stride);
7740     addl(cnt1, stride);
7741     bind(CONT_SCAN_SUBSTR);
7742     if (ae == StrIntrinsicNode::UL) {
7743       pmovzxbw(vec, Address(str2, 0));
7744     } else {
7745       movdqu(vec, Address(str2, 0));
7746     }
7747     jmp(SCAN_SUBSTR);
7748 
7749     bind(RET_FOUND_LONG);
7750     movptr(str1, Address(rsp, wordSize));
7751   } // non constant
7752 
7753   bind(RET_FOUND);
7754   // Compute substr offset
7755   subptr(result, str1);
7756   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7757     shrl(result, 1); // index
7758   }
7759   bind(CLEANUP);
7760   pop(rsp); // restore SP
7761 
7762 } // string_indexof
7763 
7764 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7765                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7766   ShortBranchVerifier sbv(this);
7767   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7768 
7769   int stride = 8;
7770 
7771   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7772         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7773         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7774         FOUND_SEQ_CHAR, DONE_LABEL;
7775 
7776   movptr(result, str1);
7777   if (UseAVX >= 2) {
7778     cmpl(cnt1, stride);
7779     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7780     cmpl(cnt1, 2*stride);
7781     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7782     movdl(vec1, ch);
7783     vpbroadcastw(vec1, vec1);
7784     vpxor(vec2, vec2);
7785     movl(tmp, cnt1);
7786     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7787     andl(cnt1,0x0000000F);  //tail count (in chars)
7788 
7789     bind(SCAN_TO_16_CHAR_LOOP);
7790     vmovdqu(vec3, Address(result, 0));
7791     vpcmpeqw(vec3, vec3, vec1, 1);
7792     vptest(vec2, vec3);
7793     jcc(Assembler::carryClear, FOUND_CHAR);
7794     addptr(result, 32);
7795     subl(tmp, 2*stride);
7796     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7797     jmp(SCAN_TO_8_CHAR);
7798     bind(SCAN_TO_8_CHAR_INIT);
7799     movdl(vec1, ch);
7800     pshuflw(vec1, vec1, 0x00);
7801     pshufd(vec1, vec1, 0);
7802     pxor(vec2, vec2);
7803   }
7804   bind(SCAN_TO_8_CHAR);
7805   cmpl(cnt1, stride);
7806   if (UseAVX >= 2) {
7807     jcc(Assembler::less, SCAN_TO_CHAR);
7808   } else {
7809     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7810     movdl(vec1, ch);
7811     pshuflw(vec1, vec1, 0x00);
7812     pshufd(vec1, vec1, 0);
7813     pxor(vec2, vec2);
7814   }
7815   movl(tmp, cnt1);
7816   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7817   andl(cnt1,0x00000007);  //tail count (in chars)
7818 
7819   bind(SCAN_TO_8_CHAR_LOOP);
7820   movdqu(vec3, Address(result, 0));
7821   pcmpeqw(vec3, vec1);
7822   ptest(vec2, vec3);
7823   jcc(Assembler::carryClear, FOUND_CHAR);
7824   addptr(result, 16);
7825   subl(tmp, stride);
7826   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7827   bind(SCAN_TO_CHAR);
7828   testl(cnt1, cnt1);
7829   jcc(Assembler::zero, RET_NOT_FOUND);
7830   bind(SCAN_TO_CHAR_LOOP);
7831   load_unsigned_short(tmp, Address(result, 0));
7832   cmpl(ch, tmp);
7833   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7834   addptr(result, 2);
7835   subl(cnt1, 1);
7836   jccb(Assembler::zero, RET_NOT_FOUND);
7837   jmp(SCAN_TO_CHAR_LOOP);
7838 
7839   bind(RET_NOT_FOUND);
7840   movl(result, -1);
7841   jmpb(DONE_LABEL);
7842 
7843   bind(FOUND_CHAR);
7844   if (UseAVX >= 2) {
7845     vpmovmskb(tmp, vec3);
7846   } else {
7847     pmovmskb(tmp, vec3);
7848   }
7849   bsfl(ch, tmp);
7850   addl(result, ch);
7851 
7852   bind(FOUND_SEQ_CHAR);
7853   subptr(result, str1);
7854   shrl(result, 1);
7855 
7856   bind(DONE_LABEL);
7857 } // string_indexof_char
7858 
7859 // helper function for string_compare
7860 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7861                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7862                                         Address::ScaleFactor scale2, Register index, int ae) {
7863   if (ae == StrIntrinsicNode::LL) {
7864     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7865     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7866   } else if (ae == StrIntrinsicNode::UU) {
7867     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7868     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7869   } else {
7870     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7871     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7872   }
7873 }
7874 
7875 // Compare strings, used for char[] and byte[].
7876 void MacroAssembler::string_compare(Register str1, Register str2,
7877                                     Register cnt1, Register cnt2, Register result,
7878                                     XMMRegister vec1, int ae) {
7879   ShortBranchVerifier sbv(this);
7880   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7881   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7882   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7883   int stride2x2 = 0x40;
7884   Address::ScaleFactor scale = Address::no_scale;
7885   Address::ScaleFactor scale1 = Address::no_scale;
7886   Address::ScaleFactor scale2 = Address::no_scale;
7887 
7888   if (ae != StrIntrinsicNode::LL) {
7889     stride2x2 = 0x20;
7890   }
7891 
7892   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7893     shrl(cnt2, 1);
7894   }
7895   // Compute the minimum of the string lengths and the
7896   // difference of the string lengths (stack).
7897   // Do the conditional move stuff
7898   movl(result, cnt1);
7899   subl(cnt1, cnt2);
7900   push(cnt1);
7901   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7902 
7903   // Is the minimum length zero?
7904   testl(cnt2, cnt2);
7905   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7906   if (ae == StrIntrinsicNode::LL) {
7907     // Load first bytes
7908     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7909     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7910   } else if (ae == StrIntrinsicNode::UU) {
7911     // Load first characters
7912     load_unsigned_short(result, Address(str1, 0));
7913     load_unsigned_short(cnt1, Address(str2, 0));
7914   } else {
7915     load_unsigned_byte(result, Address(str1, 0));
7916     load_unsigned_short(cnt1, Address(str2, 0));
7917   }
7918   subl(result, cnt1);
7919   jcc(Assembler::notZero,  POP_LABEL);
7920 
7921   if (ae == StrIntrinsicNode::UU) {
7922     // Divide length by 2 to get number of chars
7923     shrl(cnt2, 1);
7924   }
7925   cmpl(cnt2, 1);
7926   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7927 
7928   // Check if the strings start at the same location and setup scale and stride
7929   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7930     cmpptr(str1, str2);
7931     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7932     if (ae == StrIntrinsicNode::LL) {
7933       scale = Address::times_1;
7934       stride = 16;
7935     } else {
7936       scale = Address::times_2;
7937       stride = 8;
7938     }
7939   } else {
7940     scale1 = Address::times_1;
7941     scale2 = Address::times_2;
7942     // scale not used
7943     stride = 8;
7944   }
7945 
7946   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7947     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7948     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7949     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7950     Label COMPARE_TAIL_LONG;
7951     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7952 
7953     int pcmpmask = 0x19;
7954     if (ae == StrIntrinsicNode::LL) {
7955       pcmpmask &= ~0x01;
7956     }
7957 
7958     // Setup to compare 16-chars (32-bytes) vectors,
7959     // start from first character again because it has aligned address.
7960     if (ae == StrIntrinsicNode::LL) {
7961       stride2 = 32;
7962     } else {
7963       stride2 = 16;
7964     }
7965     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7966       adr_stride = stride << scale;
7967     } else {
7968       adr_stride1 = 8;  //stride << scale1;
7969       adr_stride2 = 16; //stride << scale2;
7970     }
7971 
7972     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7973     // rax and rdx are used by pcmpestri as elements counters
7974     movl(result, cnt2);
7975     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7976     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7977 
7978     // fast path : compare first 2 8-char vectors.
7979     bind(COMPARE_16_CHARS);
7980     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7981       movdqu(vec1, Address(str1, 0));
7982     } else {
7983       pmovzxbw(vec1, Address(str1, 0));
7984     }
7985     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7986     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7987 
7988     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7989       movdqu(vec1, Address(str1, adr_stride));
7990       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7991     } else {
7992       pmovzxbw(vec1, Address(str1, adr_stride1));
7993       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7994     }
7995     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7996     addl(cnt1, stride);
7997 
7998     // Compare the characters at index in cnt1
7999     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
8000     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8001     subl(result, cnt2);
8002     jmp(POP_LABEL);
8003 
8004     // Setup the registers to start vector comparison loop
8005     bind(COMPARE_WIDE_VECTORS);
8006     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8007       lea(str1, Address(str1, result, scale));
8008       lea(str2, Address(str2, result, scale));
8009     } else {
8010       lea(str1, Address(str1, result, scale1));
8011       lea(str2, Address(str2, result, scale2));
8012     }
8013     subl(result, stride2);
8014     subl(cnt2, stride2);
8015     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
8016     negptr(result);
8017 
8018     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
8019     bind(COMPARE_WIDE_VECTORS_LOOP);
8020 
8021 #ifdef _LP64
8022     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8023       cmpl(cnt2, stride2x2);
8024       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8025       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
8026       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
8027 
8028       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8029       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8030         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
8031         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8032       } else {
8033         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
8034         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
8035       }
8036       kortestql(k7, k7);
8037       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
8038       addptr(result, stride2x2);  // update since we already compared at this addr
8039       subl(cnt2, stride2x2);      // and sub the size too
8040       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8041 
8042       vpxor(vec1, vec1);
8043       jmpb(COMPARE_WIDE_TAIL);
8044     }//if (VM_Version::supports_avx512vlbw())
8045 #endif // _LP64
8046 
8047 
8048     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8049     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8050       vmovdqu(vec1, Address(str1, result, scale));
8051       vpxor(vec1, Address(str2, result, scale));
8052     } else {
8053       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
8054       vpxor(vec1, Address(str2, result, scale2));
8055     }
8056     vptest(vec1, vec1);
8057     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
8058     addptr(result, stride2);
8059     subl(cnt2, stride2);
8060     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
8061     // clean upper bits of YMM registers
8062     vpxor(vec1, vec1);
8063 
8064     // compare wide vectors tail
8065     bind(COMPARE_WIDE_TAIL);
8066     testptr(result, result);
8067     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8068 
8069     movl(result, stride2);
8070     movl(cnt2, result);
8071     negptr(result);
8072     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8073 
8074     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8075     bind(VECTOR_NOT_EQUAL);
8076     // clean upper bits of YMM registers
8077     vpxor(vec1, vec1);
8078     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8079       lea(str1, Address(str1, result, scale));
8080       lea(str2, Address(str2, result, scale));
8081     } else {
8082       lea(str1, Address(str1, result, scale1));
8083       lea(str2, Address(str2, result, scale2));
8084     }
8085     jmp(COMPARE_16_CHARS);
8086 
8087     // Compare tail chars, length between 1 to 15 chars
8088     bind(COMPARE_TAIL_LONG);
8089     movl(cnt2, result);
8090     cmpl(cnt2, stride);
8091     jcc(Assembler::less, COMPARE_SMALL_STR);
8092 
8093     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8094       movdqu(vec1, Address(str1, 0));
8095     } else {
8096       pmovzxbw(vec1, Address(str1, 0));
8097     }
8098     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8099     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8100     subptr(cnt2, stride);
8101     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8102     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8103       lea(str1, Address(str1, result, scale));
8104       lea(str2, Address(str2, result, scale));
8105     } else {
8106       lea(str1, Address(str1, result, scale1));
8107       lea(str2, Address(str2, result, scale2));
8108     }
8109     negptr(cnt2);
8110     jmpb(WHILE_HEAD_LABEL);
8111 
8112     bind(COMPARE_SMALL_STR);
8113   } else if (UseSSE42Intrinsics) {
8114     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8115     int pcmpmask = 0x19;
8116     // Setup to compare 8-char (16-byte) vectors,
8117     // start from first character again because it has aligned address.
8118     movl(result, cnt2);
8119     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8120     if (ae == StrIntrinsicNode::LL) {
8121       pcmpmask &= ~0x01;
8122     }
8123     jcc(Assembler::zero, COMPARE_TAIL);
8124     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8125       lea(str1, Address(str1, result, scale));
8126       lea(str2, Address(str2, result, scale));
8127     } else {
8128       lea(str1, Address(str1, result, scale1));
8129       lea(str2, Address(str2, result, scale2));
8130     }
8131     negptr(result);
8132 
8133     // pcmpestri
8134     //   inputs:
8135     //     vec1- substring
8136     //     rax - negative string length (elements count)
8137     //     mem - scanned string
8138     //     rdx - string length (elements count)
8139     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8140     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8141     //   outputs:
8142     //     rcx - first mismatched element index
8143     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8144 
8145     bind(COMPARE_WIDE_VECTORS);
8146     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8147       movdqu(vec1, Address(str1, result, scale));
8148       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8149     } else {
8150       pmovzxbw(vec1, Address(str1, result, scale1));
8151       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8152     }
8153     // After pcmpestri cnt1(rcx) contains mismatched element index
8154 
8155     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8156     addptr(result, stride);
8157     subptr(cnt2, stride);
8158     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8159 
8160     // compare wide vectors tail
8161     testptr(result, result);
8162     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8163 
8164     movl(cnt2, stride);
8165     movl(result, stride);
8166     negptr(result);
8167     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8168       movdqu(vec1, Address(str1, result, scale));
8169       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8170     } else {
8171       pmovzxbw(vec1, Address(str1, result, scale1));
8172       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8173     }
8174     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8175 
8176     // Mismatched characters in the vectors
8177     bind(VECTOR_NOT_EQUAL);
8178     addptr(cnt1, result);
8179     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8180     subl(result, cnt2);
8181     jmpb(POP_LABEL);
8182 
8183     bind(COMPARE_TAIL); // limit is zero
8184     movl(cnt2, result);
8185     // Fallthru to tail compare
8186   }
8187   // Shift str2 and str1 to the end of the arrays, negate min
8188   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8189     lea(str1, Address(str1, cnt2, scale));
8190     lea(str2, Address(str2, cnt2, scale));
8191   } else {
8192     lea(str1, Address(str1, cnt2, scale1));
8193     lea(str2, Address(str2, cnt2, scale2));
8194   }
8195   decrementl(cnt2);  // first character was compared already
8196   negptr(cnt2);
8197 
8198   // Compare the rest of the elements
8199   bind(WHILE_HEAD_LABEL);
8200   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8201   subl(result, cnt1);
8202   jccb(Assembler::notZero, POP_LABEL);
8203   increment(cnt2);
8204   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8205 
8206   // Strings are equal up to min length.  Return the length difference.
8207   bind(LENGTH_DIFF_LABEL);
8208   pop(result);
8209   if (ae == StrIntrinsicNode::UU) {
8210     // Divide diff by 2 to get number of chars
8211     sarl(result, 1);
8212   }
8213   jmpb(DONE_LABEL);
8214 
8215 #ifdef _LP64
8216   if (VM_Version::supports_avx512vlbw()) {
8217 
8218     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8219 
8220     kmovql(cnt1, k7);
8221     notq(cnt1);
8222     bsfq(cnt2, cnt1);
8223     if (ae != StrIntrinsicNode::LL) {
8224       // Divide diff by 2 to get number of chars
8225       sarl(cnt2, 1);
8226     }
8227     addq(result, cnt2);
8228     if (ae == StrIntrinsicNode::LL) {
8229       load_unsigned_byte(cnt1, Address(str2, result));
8230       load_unsigned_byte(result, Address(str1, result));
8231     } else if (ae == StrIntrinsicNode::UU) {
8232       load_unsigned_short(cnt1, Address(str2, result, scale));
8233       load_unsigned_short(result, Address(str1, result, scale));
8234     } else {
8235       load_unsigned_short(cnt1, Address(str2, result, scale2));
8236       load_unsigned_byte(result, Address(str1, result, scale1));
8237     }
8238     subl(result, cnt1);
8239     jmpb(POP_LABEL);
8240   }//if (VM_Version::supports_avx512vlbw())
8241 #endif // _LP64
8242 
8243   // Discard the stored length difference
8244   bind(POP_LABEL);
8245   pop(cnt1);
8246 
8247   // That's it
8248   bind(DONE_LABEL);
8249   if(ae == StrIntrinsicNode::UL) {
8250     negl(result);
8251   }
8252 
8253 }
8254 
8255 // Search for Non-ASCII character (Negative byte value) in a byte array,
8256 // return true if it has any and false otherwise.
8257 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8258 //   @HotSpotIntrinsicCandidate
8259 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8260 //     for (int i = off; i < off + len; i++) {
8261 //       if (ba[i] < 0) {
8262 //         return true;
8263 //       }
8264 //     }
8265 //     return false;
8266 //   }
8267 void MacroAssembler::has_negatives(Register ary1, Register len,
8268   Register result, Register tmp1,
8269   XMMRegister vec1, XMMRegister vec2) {
8270   // rsi: byte array
8271   // rcx: len
8272   // rax: result
8273   ShortBranchVerifier sbv(this);
8274   assert_different_registers(ary1, len, result, tmp1);
8275   assert_different_registers(vec1, vec2);
8276   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8277 
8278   // len == 0
8279   testl(len, len);
8280   jcc(Assembler::zero, FALSE_LABEL);
8281 
8282   if ((UseAVX > 2) && // AVX512
8283     VM_Version::supports_avx512vlbw() &&
8284     VM_Version::supports_bmi2()) {
8285 
8286     set_vector_masking();  // opening of the stub context for programming mask registers
8287 
8288     Label test_64_loop, test_tail;
8289     Register tmp3_aliased = len;
8290 
8291     movl(tmp1, len);
8292     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8293 
8294     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8295     andl(len, ~(64 - 1));    // vector count (in chars)
8296     jccb(Assembler::zero, test_tail);
8297 
8298     lea(ary1, Address(ary1, len, Address::times_1));
8299     negptr(len);
8300 
8301     bind(test_64_loop);
8302     // Check whether our 64 elements of size byte contain negatives
8303     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8304     kortestql(k2, k2);
8305     jcc(Assembler::notZero, TRUE_LABEL);
8306 
8307     addptr(len, 64);
8308     jccb(Assembler::notZero, test_64_loop);
8309 
8310 
8311     bind(test_tail);
8312     // bail out when there is nothing to be done
8313     testl(tmp1, -1);
8314     jcc(Assembler::zero, FALSE_LABEL);
8315 
8316     // Save k1
8317     kmovql(k3, k1);
8318 
8319     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8320 #ifdef _LP64
8321     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8322     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8323     notq(tmp3_aliased);
8324     kmovql(k1, tmp3_aliased);
8325 #else
8326     Label k_init;
8327     jmp(k_init);
8328 
8329     // We could not read 64-bits from a general purpose register thus we move
8330     // data required to compose 64 1's to the instruction stream
8331     // We emit 64 byte wide series of elements from 0..63 which later on would
8332     // be used as a compare targets with tail count contained in tmp1 register.
8333     // Result would be a k1 register having tmp1 consecutive number or 1
8334     // counting from least significant bit.
8335     address tmp = pc();
8336     emit_int64(0x0706050403020100);
8337     emit_int64(0x0F0E0D0C0B0A0908);
8338     emit_int64(0x1716151413121110);
8339     emit_int64(0x1F1E1D1C1B1A1918);
8340     emit_int64(0x2726252423222120);
8341     emit_int64(0x2F2E2D2C2B2A2928);
8342     emit_int64(0x3736353433323130);
8343     emit_int64(0x3F3E3D3C3B3A3938);
8344 
8345     bind(k_init);
8346     lea(len, InternalAddress(tmp));
8347     // create mask to test for negative byte inside a vector
8348     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8349     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8350 
8351 #endif
8352     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8353     ktestq(k2, k1);
8354     // Restore k1
8355     kmovql(k1, k3);
8356     jcc(Assembler::notZero, TRUE_LABEL);
8357 
8358     jmp(FALSE_LABEL);
8359 
8360     clear_vector_masking();   // closing of the stub context for programming mask registers
8361   } else {
8362     movl(result, len); // copy
8363 
8364     if (UseAVX == 2 && UseSSE >= 2) {
8365       // With AVX2, use 32-byte vector compare
8366       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8367 
8368       // Compare 32-byte vectors
8369       andl(result, 0x0000001f);  //   tail count (in bytes)
8370       andl(len, 0xffffffe0);   // vector count (in bytes)
8371       jccb(Assembler::zero, COMPARE_TAIL);
8372 
8373       lea(ary1, Address(ary1, len, Address::times_1));
8374       negptr(len);
8375 
8376       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8377       movdl(vec2, tmp1);
8378       vpbroadcastd(vec2, vec2);
8379 
8380       bind(COMPARE_WIDE_VECTORS);
8381       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8382       vptest(vec1, vec2);
8383       jccb(Assembler::notZero, TRUE_LABEL);
8384       addptr(len, 32);
8385       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8386 
8387       testl(result, result);
8388       jccb(Assembler::zero, FALSE_LABEL);
8389 
8390       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8391       vptest(vec1, vec2);
8392       jccb(Assembler::notZero, TRUE_LABEL);
8393       jmpb(FALSE_LABEL);
8394 
8395       bind(COMPARE_TAIL); // len is zero
8396       movl(len, result);
8397       // Fallthru to tail compare
8398     } else if (UseSSE42Intrinsics) {
8399       // With SSE4.2, use double quad vector compare
8400       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8401 
8402       // Compare 16-byte vectors
8403       andl(result, 0x0000000f);  //   tail count (in bytes)
8404       andl(len, 0xfffffff0);   // vector count (in bytes)
8405       jccb(Assembler::zero, COMPARE_TAIL);
8406 
8407       lea(ary1, Address(ary1, len, Address::times_1));
8408       negptr(len);
8409 
8410       movl(tmp1, 0x80808080);
8411       movdl(vec2, tmp1);
8412       pshufd(vec2, vec2, 0);
8413 
8414       bind(COMPARE_WIDE_VECTORS);
8415       movdqu(vec1, Address(ary1, len, Address::times_1));
8416       ptest(vec1, vec2);
8417       jccb(Assembler::notZero, TRUE_LABEL);
8418       addptr(len, 16);
8419       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8420 
8421       testl(result, result);
8422       jccb(Assembler::zero, FALSE_LABEL);
8423 
8424       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8425       ptest(vec1, vec2);
8426       jccb(Assembler::notZero, TRUE_LABEL);
8427       jmpb(FALSE_LABEL);
8428 
8429       bind(COMPARE_TAIL); // len is zero
8430       movl(len, result);
8431       // Fallthru to tail compare
8432     }
8433   }
8434   // Compare 4-byte vectors
8435   andl(len, 0xfffffffc); // vector count (in bytes)
8436   jccb(Assembler::zero, COMPARE_CHAR);
8437 
8438   lea(ary1, Address(ary1, len, Address::times_1));
8439   negptr(len);
8440 
8441   bind(COMPARE_VECTORS);
8442   movl(tmp1, Address(ary1, len, Address::times_1));
8443   andl(tmp1, 0x80808080);
8444   jccb(Assembler::notZero, TRUE_LABEL);
8445   addptr(len, 4);
8446   jcc(Assembler::notZero, COMPARE_VECTORS);
8447 
8448   // Compare trailing char (final 2 bytes), if any
8449   bind(COMPARE_CHAR);
8450   testl(result, 0x2);   // tail  char
8451   jccb(Assembler::zero, COMPARE_BYTE);
8452   load_unsigned_short(tmp1, Address(ary1, 0));
8453   andl(tmp1, 0x00008080);
8454   jccb(Assembler::notZero, TRUE_LABEL);
8455   subptr(result, 2);
8456   lea(ary1, Address(ary1, 2));
8457 
8458   bind(COMPARE_BYTE);
8459   testl(result, 0x1);   // tail  byte
8460   jccb(Assembler::zero, FALSE_LABEL);
8461   load_unsigned_byte(tmp1, Address(ary1, 0));
8462   andl(tmp1, 0x00000080);
8463   jccb(Assembler::notEqual, TRUE_LABEL);
8464   jmpb(FALSE_LABEL);
8465 
8466   bind(TRUE_LABEL);
8467   movl(result, 1);   // return true
8468   jmpb(DONE);
8469 
8470   bind(FALSE_LABEL);
8471   xorl(result, result); // return false
8472 
8473   // That's it
8474   bind(DONE);
8475   if (UseAVX >= 2 && UseSSE >= 2) {
8476     // clean upper bits of YMM registers
8477     vpxor(vec1, vec1);
8478     vpxor(vec2, vec2);
8479   }
8480 }
8481 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8482 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8483                                    Register limit, Register result, Register chr,
8484                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8485   ShortBranchVerifier sbv(this);
8486   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8487 
8488   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8489   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8490 
8491   if (is_array_equ) {
8492     // Check the input args
8493     cmpoop(ary1, ary2);
8494     jcc(Assembler::equal, TRUE_LABEL);
8495 
8496     // Need additional checks for arrays_equals.
8497     testptr(ary1, ary1);
8498     jcc(Assembler::zero, FALSE_LABEL);
8499     testptr(ary2, ary2);
8500     jcc(Assembler::zero, FALSE_LABEL);
8501 
8502     // Check the lengths
8503     movl(limit, Address(ary1, length_offset));
8504     cmpl(limit, Address(ary2, length_offset));
8505     jcc(Assembler::notEqual, FALSE_LABEL);
8506   }
8507 
8508   // count == 0
8509   testl(limit, limit);
8510   jcc(Assembler::zero, TRUE_LABEL);
8511 
8512   if (is_array_equ) {
8513     // Load array address
8514     lea(ary1, Address(ary1, base_offset));
8515     lea(ary2, Address(ary2, base_offset));
8516   }
8517 
8518   if (is_array_equ && is_char) {
8519     // arrays_equals when used for char[].
8520     shll(limit, 1);      // byte count != 0
8521   }
8522   movl(result, limit); // copy
8523 
8524   if (UseAVX >= 2) {
8525     // With AVX2, use 32-byte vector compare
8526     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8527 
8528     // Compare 32-byte vectors
8529     andl(result, 0x0000001f);  //   tail count (in bytes)
8530     andl(limit, 0xffffffe0);   // vector count (in bytes)
8531     jcc(Assembler::zero, COMPARE_TAIL);
8532 
8533     lea(ary1, Address(ary1, limit, Address::times_1));
8534     lea(ary2, Address(ary2, limit, Address::times_1));
8535     negptr(limit);
8536 
8537     bind(COMPARE_WIDE_VECTORS);
8538 
8539 #ifdef _LP64
8540     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8541       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8542 
8543       cmpl(limit, -64);
8544       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8545 
8546       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8547 
8548       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8549       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8550       kortestql(k7, k7);
8551       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8552       addptr(limit, 64);  // update since we already compared at this addr
8553       cmpl(limit, -64);
8554       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8555 
8556       // At this point we may still need to compare -limit+result bytes.
8557       // We could execute the next two instruction and just continue via non-wide path:
8558       //  cmpl(limit, 0);
8559       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8560       // But since we stopped at the points ary{1,2}+limit which are
8561       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8562       // (|limit| <= 32 and result < 32),
8563       // we may just compare the last 64 bytes.
8564       //
8565       addptr(result, -64);   // it is safe, bc we just came from this area
8566       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8567       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8568       kortestql(k7, k7);
8569       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8570 
8571       jmp(TRUE_LABEL);
8572 
8573       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8574 
8575     }//if (VM_Version::supports_avx512vlbw())
8576 #endif //_LP64
8577 
8578     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8579     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8580     vpxor(vec1, vec2);
8581 
8582     vptest(vec1, vec1);
8583     jcc(Assembler::notZero, FALSE_LABEL);
8584     addptr(limit, 32);
8585     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8586 
8587     testl(result, result);
8588     jcc(Assembler::zero, TRUE_LABEL);
8589 
8590     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8591     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8592     vpxor(vec1, vec2);
8593 
8594     vptest(vec1, vec1);
8595     jccb(Assembler::notZero, FALSE_LABEL);
8596     jmpb(TRUE_LABEL);
8597 
8598     bind(COMPARE_TAIL); // limit is zero
8599     movl(limit, result);
8600     // Fallthru to tail compare
8601   } else if (UseSSE42Intrinsics) {
8602     // With SSE4.2, use double quad vector compare
8603     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8604 
8605     // Compare 16-byte vectors
8606     andl(result, 0x0000000f);  //   tail count (in bytes)
8607     andl(limit, 0xfffffff0);   // vector count (in bytes)
8608     jcc(Assembler::zero, COMPARE_TAIL);
8609 
8610     lea(ary1, Address(ary1, limit, Address::times_1));
8611     lea(ary2, Address(ary2, limit, Address::times_1));
8612     negptr(limit);
8613 
8614     bind(COMPARE_WIDE_VECTORS);
8615     movdqu(vec1, Address(ary1, limit, Address::times_1));
8616     movdqu(vec2, Address(ary2, limit, Address::times_1));
8617     pxor(vec1, vec2);
8618 
8619     ptest(vec1, vec1);
8620     jcc(Assembler::notZero, FALSE_LABEL);
8621     addptr(limit, 16);
8622     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8623 
8624     testl(result, result);
8625     jcc(Assembler::zero, TRUE_LABEL);
8626 
8627     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8628     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8629     pxor(vec1, vec2);
8630 
8631     ptest(vec1, vec1);
8632     jccb(Assembler::notZero, FALSE_LABEL);
8633     jmpb(TRUE_LABEL);
8634 
8635     bind(COMPARE_TAIL); // limit is zero
8636     movl(limit, result);
8637     // Fallthru to tail compare
8638   }
8639 
8640   // Compare 4-byte vectors
8641   andl(limit, 0xfffffffc); // vector count (in bytes)
8642   jccb(Assembler::zero, COMPARE_CHAR);
8643 
8644   lea(ary1, Address(ary1, limit, Address::times_1));
8645   lea(ary2, Address(ary2, limit, Address::times_1));
8646   negptr(limit);
8647 
8648   bind(COMPARE_VECTORS);
8649   movl(chr, Address(ary1, limit, Address::times_1));
8650   cmpl(chr, Address(ary2, limit, Address::times_1));
8651   jccb(Assembler::notEqual, FALSE_LABEL);
8652   addptr(limit, 4);
8653   jcc(Assembler::notZero, COMPARE_VECTORS);
8654 
8655   // Compare trailing char (final 2 bytes), if any
8656   bind(COMPARE_CHAR);
8657   testl(result, 0x2);   // tail  char
8658   jccb(Assembler::zero, COMPARE_BYTE);
8659   load_unsigned_short(chr, Address(ary1, 0));
8660   load_unsigned_short(limit, Address(ary2, 0));
8661   cmpl(chr, limit);
8662   jccb(Assembler::notEqual, FALSE_LABEL);
8663 
8664   if (is_array_equ && is_char) {
8665     bind(COMPARE_BYTE);
8666   } else {
8667     lea(ary1, Address(ary1, 2));
8668     lea(ary2, Address(ary2, 2));
8669 
8670     bind(COMPARE_BYTE);
8671     testl(result, 0x1);   // tail  byte
8672     jccb(Assembler::zero, TRUE_LABEL);
8673     load_unsigned_byte(chr, Address(ary1, 0));
8674     load_unsigned_byte(limit, Address(ary2, 0));
8675     cmpl(chr, limit);
8676     jccb(Assembler::notEqual, FALSE_LABEL);
8677   }
8678   bind(TRUE_LABEL);
8679   movl(result, 1);   // return true
8680   jmpb(DONE);
8681 
8682   bind(FALSE_LABEL);
8683   xorl(result, result); // return false
8684 
8685   // That's it
8686   bind(DONE);
8687   if (UseAVX >= 2) {
8688     // clean upper bits of YMM registers
8689     vpxor(vec1, vec1);
8690     vpxor(vec2, vec2);
8691   }
8692 }
8693 
8694 #endif
8695 
8696 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8697                                    Register to, Register value, Register count,
8698                                    Register rtmp, XMMRegister xtmp) {
8699   ShortBranchVerifier sbv(this);
8700   assert_different_registers(to, value, count, rtmp);
8701   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8702   Label L_fill_2_bytes, L_fill_4_bytes;
8703 
8704   int shift = -1;
8705   switch (t) {
8706     case T_BYTE:
8707       shift = 2;
8708       break;
8709     case T_SHORT:
8710       shift = 1;
8711       break;
8712     case T_INT:
8713       shift = 0;
8714       break;
8715     default: ShouldNotReachHere();
8716   }
8717 
8718   if (t == T_BYTE) {
8719     andl(value, 0xff);
8720     movl(rtmp, value);
8721     shll(rtmp, 8);
8722     orl(value, rtmp);
8723   }
8724   if (t == T_SHORT) {
8725     andl(value, 0xffff);
8726   }
8727   if (t == T_BYTE || t == T_SHORT) {
8728     movl(rtmp, value);
8729     shll(rtmp, 16);
8730     orl(value, rtmp);
8731   }
8732 
8733   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8734   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8735   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8736     // align source address at 4 bytes address boundary
8737     if (t == T_BYTE) {
8738       // One byte misalignment happens only for byte arrays
8739       testptr(to, 1);
8740       jccb(Assembler::zero, L_skip_align1);
8741       movb(Address(to, 0), value);
8742       increment(to);
8743       decrement(count);
8744       BIND(L_skip_align1);
8745     }
8746     // Two bytes misalignment happens only for byte and short (char) arrays
8747     testptr(to, 2);
8748     jccb(Assembler::zero, L_skip_align2);
8749     movw(Address(to, 0), value);
8750     addptr(to, 2);
8751     subl(count, 1<<(shift-1));
8752     BIND(L_skip_align2);
8753   }
8754   if (UseSSE < 2) {
8755     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8756     // Fill 32-byte chunks
8757     subl(count, 8 << shift);
8758     jcc(Assembler::less, L_check_fill_8_bytes);
8759     align(16);
8760 
8761     BIND(L_fill_32_bytes_loop);
8762 
8763     for (int i = 0; i < 32; i += 4) {
8764       movl(Address(to, i), value);
8765     }
8766 
8767     addptr(to, 32);
8768     subl(count, 8 << shift);
8769     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8770     BIND(L_check_fill_8_bytes);
8771     addl(count, 8 << shift);
8772     jccb(Assembler::zero, L_exit);
8773     jmpb(L_fill_8_bytes);
8774 
8775     //
8776     // length is too short, just fill qwords
8777     //
8778     BIND(L_fill_8_bytes_loop);
8779     movl(Address(to, 0), value);
8780     movl(Address(to, 4), value);
8781     addptr(to, 8);
8782     BIND(L_fill_8_bytes);
8783     subl(count, 1 << (shift + 1));
8784     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8785     // fall through to fill 4 bytes
8786   } else {
8787     Label L_fill_32_bytes;
8788     if (!UseUnalignedLoadStores) {
8789       // align to 8 bytes, we know we are 4 byte aligned to start
8790       testptr(to, 4);
8791       jccb(Assembler::zero, L_fill_32_bytes);
8792       movl(Address(to, 0), value);
8793       addptr(to, 4);
8794       subl(count, 1<<shift);
8795     }
8796     BIND(L_fill_32_bytes);
8797     {
8798       assert( UseSSE >= 2, "supported cpu only" );
8799       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8800       if (UseAVX > 2) {
8801         movl(rtmp, 0xffff);
8802         kmovwl(k1, rtmp);
8803       }
8804       movdl(xtmp, value);
8805       if (UseAVX > 2 && UseUnalignedLoadStores) {
8806         // Fill 64-byte chunks
8807         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8808         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8809 
8810         subl(count, 16 << shift);
8811         jcc(Assembler::less, L_check_fill_32_bytes);
8812         align(16);
8813 
8814         BIND(L_fill_64_bytes_loop);
8815         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8816         addptr(to, 64);
8817         subl(count, 16 << shift);
8818         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8819 
8820         BIND(L_check_fill_32_bytes);
8821         addl(count, 8 << shift);
8822         jccb(Assembler::less, L_check_fill_8_bytes);
8823         vmovdqu(Address(to, 0), xtmp);
8824         addptr(to, 32);
8825         subl(count, 8 << shift);
8826 
8827         BIND(L_check_fill_8_bytes);
8828       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8829         // Fill 64-byte chunks
8830         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8831         vpbroadcastd(xtmp, xtmp);
8832 
8833         subl(count, 16 << shift);
8834         jcc(Assembler::less, L_check_fill_32_bytes);
8835         align(16);
8836 
8837         BIND(L_fill_64_bytes_loop);
8838         vmovdqu(Address(to, 0), xtmp);
8839         vmovdqu(Address(to, 32), xtmp);
8840         addptr(to, 64);
8841         subl(count, 16 << shift);
8842         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8843 
8844         BIND(L_check_fill_32_bytes);
8845         addl(count, 8 << shift);
8846         jccb(Assembler::less, L_check_fill_8_bytes);
8847         vmovdqu(Address(to, 0), xtmp);
8848         addptr(to, 32);
8849         subl(count, 8 << shift);
8850 
8851         BIND(L_check_fill_8_bytes);
8852         // clean upper bits of YMM registers
8853         movdl(xtmp, value);
8854         pshufd(xtmp, xtmp, 0);
8855       } else {
8856         // Fill 32-byte chunks
8857         pshufd(xtmp, xtmp, 0);
8858 
8859         subl(count, 8 << shift);
8860         jcc(Assembler::less, L_check_fill_8_bytes);
8861         align(16);
8862 
8863         BIND(L_fill_32_bytes_loop);
8864 
8865         if (UseUnalignedLoadStores) {
8866           movdqu(Address(to, 0), xtmp);
8867           movdqu(Address(to, 16), xtmp);
8868         } else {
8869           movq(Address(to, 0), xtmp);
8870           movq(Address(to, 8), xtmp);
8871           movq(Address(to, 16), xtmp);
8872           movq(Address(to, 24), xtmp);
8873         }
8874 
8875         addptr(to, 32);
8876         subl(count, 8 << shift);
8877         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8878 
8879         BIND(L_check_fill_8_bytes);
8880       }
8881       addl(count, 8 << shift);
8882       jccb(Assembler::zero, L_exit);
8883       jmpb(L_fill_8_bytes);
8884 
8885       //
8886       // length is too short, just fill qwords
8887       //
8888       BIND(L_fill_8_bytes_loop);
8889       movq(Address(to, 0), xtmp);
8890       addptr(to, 8);
8891       BIND(L_fill_8_bytes);
8892       subl(count, 1 << (shift + 1));
8893       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8894     }
8895   }
8896   // fill trailing 4 bytes
8897   BIND(L_fill_4_bytes);
8898   testl(count, 1<<shift);
8899   jccb(Assembler::zero, L_fill_2_bytes);
8900   movl(Address(to, 0), value);
8901   if (t == T_BYTE || t == T_SHORT) {
8902     addptr(to, 4);
8903     BIND(L_fill_2_bytes);
8904     // fill trailing 2 bytes
8905     testl(count, 1<<(shift-1));
8906     jccb(Assembler::zero, L_fill_byte);
8907     movw(Address(to, 0), value);
8908     if (t == T_BYTE) {
8909       addptr(to, 2);
8910       BIND(L_fill_byte);
8911       // fill trailing byte
8912       testl(count, 1);
8913       jccb(Assembler::zero, L_exit);
8914       movb(Address(to, 0), value);
8915     } else {
8916       BIND(L_fill_byte);
8917     }
8918   } else {
8919     BIND(L_fill_2_bytes);
8920   }
8921   BIND(L_exit);
8922 }
8923 
8924 // encode char[] to byte[] in ISO_8859_1
8925    //@HotSpotIntrinsicCandidate
8926    //private static int implEncodeISOArray(byte[] sa, int sp,
8927    //byte[] da, int dp, int len) {
8928    //  int i = 0;
8929    //  for (; i < len; i++) {
8930    //    char c = StringUTF16.getChar(sa, sp++);
8931    //    if (c > '\u00FF')
8932    //      break;
8933    //    da[dp++] = (byte)c;
8934    //  }
8935    //  return i;
8936    //}
8937 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8938   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8939   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8940   Register tmp5, Register result) {
8941 
8942   // rsi: src
8943   // rdi: dst
8944   // rdx: len
8945   // rcx: tmp5
8946   // rax: result
8947   ShortBranchVerifier sbv(this);
8948   assert_different_registers(src, dst, len, tmp5, result);
8949   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8950 
8951   // set result
8952   xorl(result, result);
8953   // check for zero length
8954   testl(len, len);
8955   jcc(Assembler::zero, L_done);
8956 
8957   movl(result, len);
8958 
8959   // Setup pointers
8960   lea(src, Address(src, len, Address::times_2)); // char[]
8961   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8962   negptr(len);
8963 
8964   if (UseSSE42Intrinsics || UseAVX >= 2) {
8965     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8966     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8967 
8968     if (UseAVX >= 2) {
8969       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8970       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8971       movdl(tmp1Reg, tmp5);
8972       vpbroadcastd(tmp1Reg, tmp1Reg);
8973       jmp(L_chars_32_check);
8974 
8975       bind(L_copy_32_chars);
8976       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8977       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8978       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8979       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8980       jccb(Assembler::notZero, L_copy_32_chars_exit);
8981       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8982       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8983       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8984 
8985       bind(L_chars_32_check);
8986       addptr(len, 32);
8987       jcc(Assembler::lessEqual, L_copy_32_chars);
8988 
8989       bind(L_copy_32_chars_exit);
8990       subptr(len, 16);
8991       jccb(Assembler::greater, L_copy_16_chars_exit);
8992 
8993     } else if (UseSSE42Intrinsics) {
8994       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8995       movdl(tmp1Reg, tmp5);
8996       pshufd(tmp1Reg, tmp1Reg, 0);
8997       jmpb(L_chars_16_check);
8998     }
8999 
9000     bind(L_copy_16_chars);
9001     if (UseAVX >= 2) {
9002       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
9003       vptest(tmp2Reg, tmp1Reg);
9004       jcc(Assembler::notZero, L_copy_16_chars_exit);
9005       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
9006       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
9007     } else {
9008       if (UseAVX > 0) {
9009         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9010         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9011         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
9012       } else {
9013         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
9014         por(tmp2Reg, tmp3Reg);
9015         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
9016         por(tmp2Reg, tmp4Reg);
9017       }
9018       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
9019       jccb(Assembler::notZero, L_copy_16_chars_exit);
9020       packuswb(tmp3Reg, tmp4Reg);
9021     }
9022     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
9023 
9024     bind(L_chars_16_check);
9025     addptr(len, 16);
9026     jcc(Assembler::lessEqual, L_copy_16_chars);
9027 
9028     bind(L_copy_16_chars_exit);
9029     if (UseAVX >= 2) {
9030       // clean upper bits of YMM registers
9031       vpxor(tmp2Reg, tmp2Reg);
9032       vpxor(tmp3Reg, tmp3Reg);
9033       vpxor(tmp4Reg, tmp4Reg);
9034       movdl(tmp1Reg, tmp5);
9035       pshufd(tmp1Reg, tmp1Reg, 0);
9036     }
9037     subptr(len, 8);
9038     jccb(Assembler::greater, L_copy_8_chars_exit);
9039 
9040     bind(L_copy_8_chars);
9041     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
9042     ptest(tmp3Reg, tmp1Reg);
9043     jccb(Assembler::notZero, L_copy_8_chars_exit);
9044     packuswb(tmp3Reg, tmp1Reg);
9045     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
9046     addptr(len, 8);
9047     jccb(Assembler::lessEqual, L_copy_8_chars);
9048 
9049     bind(L_copy_8_chars_exit);
9050     subptr(len, 8);
9051     jccb(Assembler::zero, L_done);
9052   }
9053 
9054   bind(L_copy_1_char);
9055   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
9056   testl(tmp5, 0xff00);      // check if Unicode char
9057   jccb(Assembler::notZero, L_copy_1_char_exit);
9058   movb(Address(dst, len, Address::times_1, 0), tmp5);
9059   addptr(len, 1);
9060   jccb(Assembler::less, L_copy_1_char);
9061 
9062   bind(L_copy_1_char_exit);
9063   addptr(result, len); // len is negative count of not processed elements
9064 
9065   bind(L_done);
9066 }
9067 
9068 #ifdef _LP64
9069 /**
9070  * Helper for multiply_to_len().
9071  */
9072 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9073   addq(dest_lo, src1);
9074   adcq(dest_hi, 0);
9075   addq(dest_lo, src2);
9076   adcq(dest_hi, 0);
9077 }
9078 
9079 /**
9080  * Multiply 64 bit by 64 bit first loop.
9081  */
9082 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9083                                            Register y, Register y_idx, Register z,
9084                                            Register carry, Register product,
9085                                            Register idx, Register kdx) {
9086   //
9087   //  jlong carry, x[], y[], z[];
9088   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9089   //    huge_128 product = y[idx] * x[xstart] + carry;
9090   //    z[kdx] = (jlong)product;
9091   //    carry  = (jlong)(product >>> 64);
9092   //  }
9093   //  z[xstart] = carry;
9094   //
9095 
9096   Label L_first_loop, L_first_loop_exit;
9097   Label L_one_x, L_one_y, L_multiply;
9098 
9099   decrementl(xstart);
9100   jcc(Assembler::negative, L_one_x);
9101 
9102   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9103   rorq(x_xstart, 32); // convert big-endian to little-endian
9104 
9105   bind(L_first_loop);
9106   decrementl(idx);
9107   jcc(Assembler::negative, L_first_loop_exit);
9108   decrementl(idx);
9109   jcc(Assembler::negative, L_one_y);
9110   movq(y_idx, Address(y, idx, Address::times_4,  0));
9111   rorq(y_idx, 32); // convert big-endian to little-endian
9112   bind(L_multiply);
9113   movq(product, x_xstart);
9114   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9115   addq(product, carry);
9116   adcq(rdx, 0);
9117   subl(kdx, 2);
9118   movl(Address(z, kdx, Address::times_4,  4), product);
9119   shrq(product, 32);
9120   movl(Address(z, kdx, Address::times_4,  0), product);
9121   movq(carry, rdx);
9122   jmp(L_first_loop);
9123 
9124   bind(L_one_y);
9125   movl(y_idx, Address(y,  0));
9126   jmp(L_multiply);
9127 
9128   bind(L_one_x);
9129   movl(x_xstart, Address(x,  0));
9130   jmp(L_first_loop);
9131 
9132   bind(L_first_loop_exit);
9133 }
9134 
9135 /**
9136  * Multiply 64 bit by 64 bit and add 128 bit.
9137  */
9138 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9139                                             Register yz_idx, Register idx,
9140                                             Register carry, Register product, int offset) {
9141   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9142   //     z[kdx] = (jlong)product;
9143 
9144   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9145   rorq(yz_idx, 32); // convert big-endian to little-endian
9146   movq(product, x_xstart);
9147   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9148   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9149   rorq(yz_idx, 32); // convert big-endian to little-endian
9150 
9151   add2_with_carry(rdx, product, carry, yz_idx);
9152 
9153   movl(Address(z, idx, Address::times_4,  offset+4), product);
9154   shrq(product, 32);
9155   movl(Address(z, idx, Address::times_4,  offset), product);
9156 
9157 }
9158 
9159 /**
9160  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9161  */
9162 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9163                                              Register yz_idx, Register idx, Register jdx,
9164                                              Register carry, Register product,
9165                                              Register carry2) {
9166   //   jlong carry, x[], y[], z[];
9167   //   int kdx = ystart+1;
9168   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9169   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9170   //     z[kdx+idx+1] = (jlong)product;
9171   //     jlong carry2  = (jlong)(product >>> 64);
9172   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9173   //     z[kdx+idx] = (jlong)product;
9174   //     carry  = (jlong)(product >>> 64);
9175   //   }
9176   //   idx += 2;
9177   //   if (idx > 0) {
9178   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9179   //     z[kdx+idx] = (jlong)product;
9180   //     carry  = (jlong)(product >>> 64);
9181   //   }
9182   //
9183 
9184   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9185 
9186   movl(jdx, idx);
9187   andl(jdx, 0xFFFFFFFC);
9188   shrl(jdx, 2);
9189 
9190   bind(L_third_loop);
9191   subl(jdx, 1);
9192   jcc(Assembler::negative, L_third_loop_exit);
9193   subl(idx, 4);
9194 
9195   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9196   movq(carry2, rdx);
9197 
9198   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9199   movq(carry, rdx);
9200   jmp(L_third_loop);
9201 
9202   bind (L_third_loop_exit);
9203 
9204   andl (idx, 0x3);
9205   jcc(Assembler::zero, L_post_third_loop_done);
9206 
9207   Label L_check_1;
9208   subl(idx, 2);
9209   jcc(Assembler::negative, L_check_1);
9210 
9211   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9212   movq(carry, rdx);
9213 
9214   bind (L_check_1);
9215   addl (idx, 0x2);
9216   andl (idx, 0x1);
9217   subl(idx, 1);
9218   jcc(Assembler::negative, L_post_third_loop_done);
9219 
9220   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9221   movq(product, x_xstart);
9222   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9223   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9224 
9225   add2_with_carry(rdx, product, yz_idx, carry);
9226 
9227   movl(Address(z, idx, Address::times_4,  0), product);
9228   shrq(product, 32);
9229 
9230   shlq(rdx, 32);
9231   orq(product, rdx);
9232   movq(carry, product);
9233 
9234   bind(L_post_third_loop_done);
9235 }
9236 
9237 /**
9238  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9239  *
9240  */
9241 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9242                                                   Register carry, Register carry2,
9243                                                   Register idx, Register jdx,
9244                                                   Register yz_idx1, Register yz_idx2,
9245                                                   Register tmp, Register tmp3, Register tmp4) {
9246   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9247 
9248   //   jlong carry, x[], y[], z[];
9249   //   int kdx = ystart+1;
9250   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9251   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9252   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9253   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9254   //     carry  = (jlong)(tmp4 >>> 64);
9255   //     z[kdx+idx+1] = (jlong)tmp3;
9256   //     z[kdx+idx] = (jlong)tmp4;
9257   //   }
9258   //   idx += 2;
9259   //   if (idx > 0) {
9260   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9261   //     z[kdx+idx] = (jlong)yz_idx1;
9262   //     carry  = (jlong)(yz_idx1 >>> 64);
9263   //   }
9264   //
9265 
9266   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9267 
9268   movl(jdx, idx);
9269   andl(jdx, 0xFFFFFFFC);
9270   shrl(jdx, 2);
9271 
9272   bind(L_third_loop);
9273   subl(jdx, 1);
9274   jcc(Assembler::negative, L_third_loop_exit);
9275   subl(idx, 4);
9276 
9277   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9278   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9279   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9280   rorxq(yz_idx2, yz_idx2, 32);
9281 
9282   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9283   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9284 
9285   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9286   rorxq(yz_idx1, yz_idx1, 32);
9287   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9288   rorxq(yz_idx2, yz_idx2, 32);
9289 
9290   if (VM_Version::supports_adx()) {
9291     adcxq(tmp3, carry);
9292     adoxq(tmp3, yz_idx1);
9293 
9294     adcxq(tmp4, tmp);
9295     adoxq(tmp4, yz_idx2);
9296 
9297     movl(carry, 0); // does not affect flags
9298     adcxq(carry2, carry);
9299     adoxq(carry2, carry);
9300   } else {
9301     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9302     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9303   }
9304   movq(carry, carry2);
9305 
9306   movl(Address(z, idx, Address::times_4, 12), tmp3);
9307   shrq(tmp3, 32);
9308   movl(Address(z, idx, Address::times_4,  8), tmp3);
9309 
9310   movl(Address(z, idx, Address::times_4,  4), tmp4);
9311   shrq(tmp4, 32);
9312   movl(Address(z, idx, Address::times_4,  0), tmp4);
9313 
9314   jmp(L_third_loop);
9315 
9316   bind (L_third_loop_exit);
9317 
9318   andl (idx, 0x3);
9319   jcc(Assembler::zero, L_post_third_loop_done);
9320 
9321   Label L_check_1;
9322   subl(idx, 2);
9323   jcc(Assembler::negative, L_check_1);
9324 
9325   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9326   rorxq(yz_idx1, yz_idx1, 32);
9327   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9328   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9329   rorxq(yz_idx2, yz_idx2, 32);
9330 
9331   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9332 
9333   movl(Address(z, idx, Address::times_4,  4), tmp3);
9334   shrq(tmp3, 32);
9335   movl(Address(z, idx, Address::times_4,  0), tmp3);
9336   movq(carry, tmp4);
9337 
9338   bind (L_check_1);
9339   addl (idx, 0x2);
9340   andl (idx, 0x1);
9341   subl(idx, 1);
9342   jcc(Assembler::negative, L_post_third_loop_done);
9343   movl(tmp4, Address(y, idx, Address::times_4,  0));
9344   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9345   movl(tmp4, Address(z, idx, Address::times_4,  0));
9346 
9347   add2_with_carry(carry2, tmp3, tmp4, carry);
9348 
9349   movl(Address(z, idx, Address::times_4,  0), tmp3);
9350   shrq(tmp3, 32);
9351 
9352   shlq(carry2, 32);
9353   orq(tmp3, carry2);
9354   movq(carry, tmp3);
9355 
9356   bind(L_post_third_loop_done);
9357 }
9358 
9359 /**
9360  * Code for BigInteger::multiplyToLen() instrinsic.
9361  *
9362  * rdi: x
9363  * rax: xlen
9364  * rsi: y
9365  * rcx: ylen
9366  * r8:  z
9367  * r11: zlen
9368  * r12: tmp1
9369  * r13: tmp2
9370  * r14: tmp3
9371  * r15: tmp4
9372  * rbx: tmp5
9373  *
9374  */
9375 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9376                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9377   ShortBranchVerifier sbv(this);
9378   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9379 
9380   push(tmp1);
9381   push(tmp2);
9382   push(tmp3);
9383   push(tmp4);
9384   push(tmp5);
9385 
9386   push(xlen);
9387   push(zlen);
9388 
9389   const Register idx = tmp1;
9390   const Register kdx = tmp2;
9391   const Register xstart = tmp3;
9392 
9393   const Register y_idx = tmp4;
9394   const Register carry = tmp5;
9395   const Register product  = xlen;
9396   const Register x_xstart = zlen;  // reuse register
9397 
9398   // First Loop.
9399   //
9400   //  final static long LONG_MASK = 0xffffffffL;
9401   //  int xstart = xlen - 1;
9402   //  int ystart = ylen - 1;
9403   //  long carry = 0;
9404   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9405   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9406   //    z[kdx] = (int)product;
9407   //    carry = product >>> 32;
9408   //  }
9409   //  z[xstart] = (int)carry;
9410   //
9411 
9412   movl(idx, ylen);      // idx = ylen;
9413   movl(kdx, zlen);      // kdx = xlen+ylen;
9414   xorq(carry, carry);   // carry = 0;
9415 
9416   Label L_done;
9417 
9418   movl(xstart, xlen);
9419   decrementl(xstart);
9420   jcc(Assembler::negative, L_done);
9421 
9422   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9423 
9424   Label L_second_loop;
9425   testl(kdx, kdx);
9426   jcc(Assembler::zero, L_second_loop);
9427 
9428   Label L_carry;
9429   subl(kdx, 1);
9430   jcc(Assembler::zero, L_carry);
9431 
9432   movl(Address(z, kdx, Address::times_4,  0), carry);
9433   shrq(carry, 32);
9434   subl(kdx, 1);
9435 
9436   bind(L_carry);
9437   movl(Address(z, kdx, Address::times_4,  0), carry);
9438 
9439   // Second and third (nested) loops.
9440   //
9441   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9442   //   carry = 0;
9443   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9444   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9445   //                    (z[k] & LONG_MASK) + carry;
9446   //     z[k] = (int)product;
9447   //     carry = product >>> 32;
9448   //   }
9449   //   z[i] = (int)carry;
9450   // }
9451   //
9452   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9453 
9454   const Register jdx = tmp1;
9455 
9456   bind(L_second_loop);
9457   xorl(carry, carry);    // carry = 0;
9458   movl(jdx, ylen);       // j = ystart+1
9459 
9460   subl(xstart, 1);       // i = xstart-1;
9461   jcc(Assembler::negative, L_done);
9462 
9463   push (z);
9464 
9465   Label L_last_x;
9466   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9467   subl(xstart, 1);       // i = xstart-1;
9468   jcc(Assembler::negative, L_last_x);
9469 
9470   if (UseBMI2Instructions) {
9471     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9472     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9473   } else {
9474     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9475     rorq(x_xstart, 32);  // convert big-endian to little-endian
9476   }
9477 
9478   Label L_third_loop_prologue;
9479   bind(L_third_loop_prologue);
9480 
9481   push (x);
9482   push (xstart);
9483   push (ylen);
9484 
9485 
9486   if (UseBMI2Instructions) {
9487     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9488   } else { // !UseBMI2Instructions
9489     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9490   }
9491 
9492   pop(ylen);
9493   pop(xlen);
9494   pop(x);
9495   pop(z);
9496 
9497   movl(tmp3, xlen);
9498   addl(tmp3, 1);
9499   movl(Address(z, tmp3, Address::times_4,  0), carry);
9500   subl(tmp3, 1);
9501   jccb(Assembler::negative, L_done);
9502 
9503   shrq(carry, 32);
9504   movl(Address(z, tmp3, Address::times_4,  0), carry);
9505   jmp(L_second_loop);
9506 
9507   // Next infrequent code is moved outside loops.
9508   bind(L_last_x);
9509   if (UseBMI2Instructions) {
9510     movl(rdx, Address(x,  0));
9511   } else {
9512     movl(x_xstart, Address(x,  0));
9513   }
9514   jmp(L_third_loop_prologue);
9515 
9516   bind(L_done);
9517 
9518   pop(zlen);
9519   pop(xlen);
9520 
9521   pop(tmp5);
9522   pop(tmp4);
9523   pop(tmp3);
9524   pop(tmp2);
9525   pop(tmp1);
9526 }
9527 
9528 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9529   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9530   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9531   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9532   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9533   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9534   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9535   Label SAME_TILL_END, DONE;
9536   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9537 
9538   //scale is in rcx in both Win64 and Unix
9539   ShortBranchVerifier sbv(this);
9540 
9541   shlq(length);
9542   xorq(result, result);
9543 
9544   if ((UseAVX > 2) &&
9545       VM_Version::supports_avx512vlbw()) {
9546     set_vector_masking();  // opening of the stub context for programming mask registers
9547     cmpq(length, 64);
9548     jcc(Assembler::less, VECTOR32_TAIL);
9549     movq(tmp1, length);
9550     andq(tmp1, 0x3F);      // tail count
9551     andq(length, ~(0x3F)); //vector count
9552 
9553     bind(VECTOR64_LOOP);
9554     // AVX512 code to compare 64 byte vectors.
9555     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9556     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9557     kortestql(k7, k7);
9558     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9559     addq(result, 64);
9560     subq(length, 64);
9561     jccb(Assembler::notZero, VECTOR64_LOOP);
9562 
9563     //bind(VECTOR64_TAIL);
9564     testq(tmp1, tmp1);
9565     jcc(Assembler::zero, SAME_TILL_END);
9566 
9567     bind(VECTOR64_TAIL);
9568     // AVX512 code to compare upto 63 byte vectors.
9569     // Save k1
9570     kmovql(k3, k1);
9571     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9572     shlxq(tmp2, tmp2, tmp1);
9573     notq(tmp2);
9574     kmovql(k1, tmp2);
9575 
9576     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9577     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9578 
9579     ktestql(k7, k1);
9580     // Restore k1
9581     kmovql(k1, k3);
9582     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9583 
9584     bind(VECTOR64_NOT_EQUAL);
9585     kmovql(tmp1, k7);
9586     notq(tmp1);
9587     tzcntq(tmp1, tmp1);
9588     addq(result, tmp1);
9589     shrq(result);
9590     jmp(DONE);
9591     bind(VECTOR32_TAIL);
9592     clear_vector_masking();   // closing of the stub context for programming mask registers
9593   }
9594 
9595   cmpq(length, 8);
9596   jcc(Assembler::equal, VECTOR8_LOOP);
9597   jcc(Assembler::less, VECTOR4_TAIL);
9598 
9599   if (UseAVX >= 2) {
9600 
9601     cmpq(length, 16);
9602     jcc(Assembler::equal, VECTOR16_LOOP);
9603     jcc(Assembler::less, VECTOR8_LOOP);
9604 
9605     cmpq(length, 32);
9606     jccb(Assembler::less, VECTOR16_TAIL);
9607 
9608     subq(length, 32);
9609     bind(VECTOR32_LOOP);
9610     vmovdqu(rymm0, Address(obja, result));
9611     vmovdqu(rymm1, Address(objb, result));
9612     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9613     vptest(rymm2, rymm2);
9614     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9615     addq(result, 32);
9616     subq(length, 32);
9617     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9618     addq(length, 32);
9619     jcc(Assembler::equal, SAME_TILL_END);
9620     //falling through if less than 32 bytes left //close the branch here.
9621 
9622     bind(VECTOR16_TAIL);
9623     cmpq(length, 16);
9624     jccb(Assembler::less, VECTOR8_TAIL);
9625     bind(VECTOR16_LOOP);
9626     movdqu(rymm0, Address(obja, result));
9627     movdqu(rymm1, Address(objb, result));
9628     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9629     ptest(rymm2, rymm2);
9630     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9631     addq(result, 16);
9632     subq(length, 16);
9633     jcc(Assembler::equal, SAME_TILL_END);
9634     //falling through if less than 16 bytes left
9635   } else {//regular intrinsics
9636 
9637     cmpq(length, 16);
9638     jccb(Assembler::less, VECTOR8_TAIL);
9639 
9640     subq(length, 16);
9641     bind(VECTOR16_LOOP);
9642     movdqu(rymm0, Address(obja, result));
9643     movdqu(rymm1, Address(objb, result));
9644     pxor(rymm0, rymm1);
9645     ptest(rymm0, rymm0);
9646     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9647     addq(result, 16);
9648     subq(length, 16);
9649     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9650     addq(length, 16);
9651     jcc(Assembler::equal, SAME_TILL_END);
9652     //falling through if less than 16 bytes left
9653   }
9654 
9655   bind(VECTOR8_TAIL);
9656   cmpq(length, 8);
9657   jccb(Assembler::less, VECTOR4_TAIL);
9658   bind(VECTOR8_LOOP);
9659   movq(tmp1, Address(obja, result));
9660   movq(tmp2, Address(objb, result));
9661   xorq(tmp1, tmp2);
9662   testq(tmp1, tmp1);
9663   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9664   addq(result, 8);
9665   subq(length, 8);
9666   jcc(Assembler::equal, SAME_TILL_END);
9667   //falling through if less than 8 bytes left
9668 
9669   bind(VECTOR4_TAIL);
9670   cmpq(length, 4);
9671   jccb(Assembler::less, BYTES_TAIL);
9672   bind(VECTOR4_LOOP);
9673   movl(tmp1, Address(obja, result));
9674   xorl(tmp1, Address(objb, result));
9675   testl(tmp1, tmp1);
9676   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9677   addq(result, 4);
9678   subq(length, 4);
9679   jcc(Assembler::equal, SAME_TILL_END);
9680   //falling through if less than 4 bytes left
9681 
9682   bind(BYTES_TAIL);
9683   bind(BYTES_LOOP);
9684   load_unsigned_byte(tmp1, Address(obja, result));
9685   load_unsigned_byte(tmp2, Address(objb, result));
9686   xorl(tmp1, tmp2);
9687   testl(tmp1, tmp1);
9688   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9689   decq(length);
9690   jccb(Assembler::zero, SAME_TILL_END);
9691   incq(result);
9692   load_unsigned_byte(tmp1, Address(obja, result));
9693   load_unsigned_byte(tmp2, Address(objb, result));
9694   xorl(tmp1, tmp2);
9695   testl(tmp1, tmp1);
9696   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9697   decq(length);
9698   jccb(Assembler::zero, SAME_TILL_END);
9699   incq(result);
9700   load_unsigned_byte(tmp1, Address(obja, result));
9701   load_unsigned_byte(tmp2, Address(objb, result));
9702   xorl(tmp1, tmp2);
9703   testl(tmp1, tmp1);
9704   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9705   jmpb(SAME_TILL_END);
9706 
9707   if (UseAVX >= 2) {
9708     bind(VECTOR32_NOT_EQUAL);
9709     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9710     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9711     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9712     vpmovmskb(tmp1, rymm0);
9713     bsfq(tmp1, tmp1);
9714     addq(result, tmp1);
9715     shrq(result);
9716     jmpb(DONE);
9717   }
9718 
9719   bind(VECTOR16_NOT_EQUAL);
9720   if (UseAVX >= 2) {
9721     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9722     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9723     pxor(rymm0, rymm2);
9724   } else {
9725     pcmpeqb(rymm2, rymm2);
9726     pxor(rymm0, rymm1);
9727     pcmpeqb(rymm0, rymm1);
9728     pxor(rymm0, rymm2);
9729   }
9730   pmovmskb(tmp1, rymm0);
9731   bsfq(tmp1, tmp1);
9732   addq(result, tmp1);
9733   shrq(result);
9734   jmpb(DONE);
9735 
9736   bind(VECTOR8_NOT_EQUAL);
9737   bind(VECTOR4_NOT_EQUAL);
9738   bsfq(tmp1, tmp1);
9739   shrq(tmp1, 3);
9740   addq(result, tmp1);
9741   bind(BYTES_NOT_EQUAL);
9742   shrq(result);
9743   jmpb(DONE);
9744 
9745   bind(SAME_TILL_END);
9746   mov64(result, -1);
9747 
9748   bind(DONE);
9749 }
9750 
9751 //Helper functions for square_to_len()
9752 
9753 /**
9754  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9755  * Preserves x and z and modifies rest of the registers.
9756  */
9757 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9758   // Perform square and right shift by 1
9759   // Handle odd xlen case first, then for even xlen do the following
9760   // jlong carry = 0;
9761   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9762   //     huge_128 product = x[j:j+1] * x[j:j+1];
9763   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9764   //     z[i+2:i+3] = (jlong)(product >>> 1);
9765   //     carry = (jlong)product;
9766   // }
9767 
9768   xorq(tmp5, tmp5);     // carry
9769   xorq(rdxReg, rdxReg);
9770   xorl(tmp1, tmp1);     // index for x
9771   xorl(tmp4, tmp4);     // index for z
9772 
9773   Label L_first_loop, L_first_loop_exit;
9774 
9775   testl(xlen, 1);
9776   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9777 
9778   // Square and right shift by 1 the odd element using 32 bit multiply
9779   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9780   imulq(raxReg, raxReg);
9781   shrq(raxReg, 1);
9782   adcq(tmp5, 0);
9783   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9784   incrementl(tmp1);
9785   addl(tmp4, 2);
9786 
9787   // Square and  right shift by 1 the rest using 64 bit multiply
9788   bind(L_first_loop);
9789   cmpptr(tmp1, xlen);
9790   jccb(Assembler::equal, L_first_loop_exit);
9791 
9792   // Square
9793   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9794   rorq(raxReg, 32);    // convert big-endian to little-endian
9795   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9796 
9797   // Right shift by 1 and save carry
9798   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9799   rcrq(rdxReg, 1);
9800   rcrq(raxReg, 1);
9801   adcq(tmp5, 0);
9802 
9803   // Store result in z
9804   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9805   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9806 
9807   // Update indices for x and z
9808   addl(tmp1, 2);
9809   addl(tmp4, 4);
9810   jmp(L_first_loop);
9811 
9812   bind(L_first_loop_exit);
9813 }
9814 
9815 
9816 /**
9817  * Perform the following multiply add operation using BMI2 instructions
9818  * carry:sum = sum + op1*op2 + carry
9819  * op2 should be in rdx
9820  * op2 is preserved, all other registers are modified
9821  */
9822 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9823   // assert op2 is rdx
9824   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9825   addq(sum, carry);
9826   adcq(tmp2, 0);
9827   addq(sum, op1);
9828   adcq(tmp2, 0);
9829   movq(carry, tmp2);
9830 }
9831 
9832 /**
9833  * Perform the following multiply add operation:
9834  * carry:sum = sum + op1*op2 + carry
9835  * Preserves op1, op2 and modifies rest of registers
9836  */
9837 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9838   // rdx:rax = op1 * op2
9839   movq(raxReg, op2);
9840   mulq(op1);
9841 
9842   //  rdx:rax = sum + carry + rdx:rax
9843   addq(sum, carry);
9844   adcq(rdxReg, 0);
9845   addq(sum, raxReg);
9846   adcq(rdxReg, 0);
9847 
9848   // carry:sum = rdx:sum
9849   movq(carry, rdxReg);
9850 }
9851 
9852 /**
9853  * Add 64 bit long carry into z[] with carry propogation.
9854  * Preserves z and carry register values and modifies rest of registers.
9855  *
9856  */
9857 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9858   Label L_fourth_loop, L_fourth_loop_exit;
9859 
9860   movl(tmp1, 1);
9861   subl(zlen, 2);
9862   addq(Address(z, zlen, Address::times_4, 0), carry);
9863 
9864   bind(L_fourth_loop);
9865   jccb(Assembler::carryClear, L_fourth_loop_exit);
9866   subl(zlen, 2);
9867   jccb(Assembler::negative, L_fourth_loop_exit);
9868   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9869   jmp(L_fourth_loop);
9870   bind(L_fourth_loop_exit);
9871 }
9872 
9873 /**
9874  * Shift z[] left by 1 bit.
9875  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9876  *
9877  */
9878 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9879 
9880   Label L_fifth_loop, L_fifth_loop_exit;
9881 
9882   // Fifth loop
9883   // Perform primitiveLeftShift(z, zlen, 1)
9884 
9885   const Register prev_carry = tmp1;
9886   const Register new_carry = tmp4;
9887   const Register value = tmp2;
9888   const Register zidx = tmp3;
9889 
9890   // int zidx, carry;
9891   // long value;
9892   // carry = 0;
9893   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9894   //    (carry:value)  = (z[i] << 1) | carry ;
9895   //    z[i] = value;
9896   // }
9897 
9898   movl(zidx, zlen);
9899   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9900 
9901   bind(L_fifth_loop);
9902   decl(zidx);  // Use decl to preserve carry flag
9903   decl(zidx);
9904   jccb(Assembler::negative, L_fifth_loop_exit);
9905 
9906   if (UseBMI2Instructions) {
9907      movq(value, Address(z, zidx, Address::times_4, 0));
9908      rclq(value, 1);
9909      rorxq(value, value, 32);
9910      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9911   }
9912   else {
9913     // clear new_carry
9914     xorl(new_carry, new_carry);
9915 
9916     // Shift z[i] by 1, or in previous carry and save new carry
9917     movq(value, Address(z, zidx, Address::times_4, 0));
9918     shlq(value, 1);
9919     adcl(new_carry, 0);
9920 
9921     orq(value, prev_carry);
9922     rorq(value, 0x20);
9923     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9924 
9925     // Set previous carry = new carry
9926     movl(prev_carry, new_carry);
9927   }
9928   jmp(L_fifth_loop);
9929 
9930   bind(L_fifth_loop_exit);
9931 }
9932 
9933 
9934 /**
9935  * Code for BigInteger::squareToLen() intrinsic
9936  *
9937  * rdi: x
9938  * rsi: len
9939  * r8:  z
9940  * rcx: zlen
9941  * r12: tmp1
9942  * r13: tmp2
9943  * r14: tmp3
9944  * r15: tmp4
9945  * rbx: tmp5
9946  *
9947  */
9948 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) {
9949 
9950   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;
9951   push(tmp1);
9952   push(tmp2);
9953   push(tmp3);
9954   push(tmp4);
9955   push(tmp5);
9956 
9957   // First loop
9958   // Store the squares, right shifted one bit (i.e., divided by 2).
9959   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9960 
9961   // Add in off-diagonal sums.
9962   //
9963   // Second, third (nested) and fourth loops.
9964   // zlen +=2;
9965   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9966   //    carry = 0;
9967   //    long op2 = x[xidx:xidx+1];
9968   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9969   //       k -= 2;
9970   //       long op1 = x[j:j+1];
9971   //       long sum = z[k:k+1];
9972   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9973   //       z[k:k+1] = sum;
9974   //    }
9975   //    add_one_64(z, k, carry, tmp_regs);
9976   // }
9977 
9978   const Register carry = tmp5;
9979   const Register sum = tmp3;
9980   const Register op1 = tmp4;
9981   Register op2 = tmp2;
9982 
9983   push(zlen);
9984   push(len);
9985   addl(zlen,2);
9986   bind(L_second_loop);
9987   xorq(carry, carry);
9988   subl(zlen, 4);
9989   subl(len, 2);
9990   push(zlen);
9991   push(len);
9992   cmpl(len, 0);
9993   jccb(Assembler::lessEqual, L_second_loop_exit);
9994 
9995   // Multiply an array by one 64 bit long.
9996   if (UseBMI2Instructions) {
9997     op2 = rdxReg;
9998     movq(op2, Address(x, len, Address::times_4,  0));
9999     rorxq(op2, op2, 32);
10000   }
10001   else {
10002     movq(op2, Address(x, len, Address::times_4,  0));
10003     rorq(op2, 32);
10004   }
10005 
10006   bind(L_third_loop);
10007   decrementl(len);
10008   jccb(Assembler::negative, L_third_loop_exit);
10009   decrementl(len);
10010   jccb(Assembler::negative, L_last_x);
10011 
10012   movq(op1, Address(x, len, Address::times_4,  0));
10013   rorq(op1, 32);
10014 
10015   bind(L_multiply);
10016   subl(zlen, 2);
10017   movq(sum, Address(z, zlen, Address::times_4,  0));
10018 
10019   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
10020   if (UseBMI2Instructions) {
10021     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
10022   }
10023   else {
10024     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10025   }
10026 
10027   movq(Address(z, zlen, Address::times_4, 0), sum);
10028 
10029   jmp(L_third_loop);
10030   bind(L_third_loop_exit);
10031 
10032   // Fourth loop
10033   // Add 64 bit long carry into z with carry propogation.
10034   // Uses offsetted zlen.
10035   add_one_64(z, zlen, carry, tmp1);
10036 
10037   pop(len);
10038   pop(zlen);
10039   jmp(L_second_loop);
10040 
10041   // Next infrequent code is moved outside loops.
10042   bind(L_last_x);
10043   movl(op1, Address(x, 0));
10044   jmp(L_multiply);
10045 
10046   bind(L_second_loop_exit);
10047   pop(len);
10048   pop(zlen);
10049   pop(len);
10050   pop(zlen);
10051 
10052   // Fifth loop
10053   // Shift z left 1 bit.
10054   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
10055 
10056   // z[zlen-1] |= x[len-1] & 1;
10057   movl(tmp3, Address(x, len, Address::times_4, -4));
10058   andl(tmp3, 1);
10059   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
10060 
10061   pop(tmp5);
10062   pop(tmp4);
10063   pop(tmp3);
10064   pop(tmp2);
10065   pop(tmp1);
10066 }
10067 
10068 /**
10069  * Helper function for mul_add()
10070  * Multiply the in[] by int k and add to out[] starting at offset offs using
10071  * 128 bit by 32 bit multiply and return the carry in tmp5.
10072  * Only quad int aligned length of in[] is operated on in this function.
10073  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10074  * This function preserves out, in and k registers.
10075  * len and offset point to the appropriate index in "in" & "out" correspondingly
10076  * tmp5 has the carry.
10077  * other registers are temporary and are modified.
10078  *
10079  */
10080 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10081   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10082   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10083 
10084   Label L_first_loop, L_first_loop_exit;
10085 
10086   movl(tmp1, len);
10087   shrl(tmp1, 2);
10088 
10089   bind(L_first_loop);
10090   subl(tmp1, 1);
10091   jccb(Assembler::negative, L_first_loop_exit);
10092 
10093   subl(len, 4);
10094   subl(offset, 4);
10095 
10096   Register op2 = tmp2;
10097   const Register sum = tmp3;
10098   const Register op1 = tmp4;
10099   const Register carry = tmp5;
10100 
10101   if (UseBMI2Instructions) {
10102     op2 = rdxReg;
10103   }
10104 
10105   movq(op1, Address(in, len, Address::times_4,  8));
10106   rorq(op1, 32);
10107   movq(sum, Address(out, offset, Address::times_4,  8));
10108   rorq(sum, 32);
10109   if (UseBMI2Instructions) {
10110     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10111   }
10112   else {
10113     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10114   }
10115   // Store back in big endian from little endian
10116   rorq(sum, 0x20);
10117   movq(Address(out, offset, Address::times_4,  8), sum);
10118 
10119   movq(op1, Address(in, len, Address::times_4,  0));
10120   rorq(op1, 32);
10121   movq(sum, Address(out, offset, Address::times_4,  0));
10122   rorq(sum, 32);
10123   if (UseBMI2Instructions) {
10124     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10125   }
10126   else {
10127     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10128   }
10129   // Store back in big endian from little endian
10130   rorq(sum, 0x20);
10131   movq(Address(out, offset, Address::times_4,  0), sum);
10132 
10133   jmp(L_first_loop);
10134   bind(L_first_loop_exit);
10135 }
10136 
10137 /**
10138  * Code for BigInteger::mulAdd() intrinsic
10139  *
10140  * rdi: out
10141  * rsi: in
10142  * r11: offs (out.length - offset)
10143  * rcx: len
10144  * r8:  k
10145  * r12: tmp1
10146  * r13: tmp2
10147  * r14: tmp3
10148  * r15: tmp4
10149  * rbx: tmp5
10150  * Multiply the in[] by word k and add to out[], return the carry in rax
10151  */
10152 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10153    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10154    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10155 
10156   Label L_carry, L_last_in, L_done;
10157 
10158 // carry = 0;
10159 // for (int j=len-1; j >= 0; j--) {
10160 //    long product = (in[j] & LONG_MASK) * kLong +
10161 //                   (out[offs] & LONG_MASK) + carry;
10162 //    out[offs--] = (int)product;
10163 //    carry = product >>> 32;
10164 // }
10165 //
10166   push(tmp1);
10167   push(tmp2);
10168   push(tmp3);
10169   push(tmp4);
10170   push(tmp5);
10171 
10172   Register op2 = tmp2;
10173   const Register sum = tmp3;
10174   const Register op1 = tmp4;
10175   const Register carry =  tmp5;
10176 
10177   if (UseBMI2Instructions) {
10178     op2 = rdxReg;
10179     movl(op2, k);
10180   }
10181   else {
10182     movl(op2, k);
10183   }
10184 
10185   xorq(carry, carry);
10186 
10187   //First loop
10188 
10189   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10190   //The carry is in tmp5
10191   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10192 
10193   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10194   decrementl(len);
10195   jccb(Assembler::negative, L_carry);
10196   decrementl(len);
10197   jccb(Assembler::negative, L_last_in);
10198 
10199   movq(op1, Address(in, len, Address::times_4,  0));
10200   rorq(op1, 32);
10201 
10202   subl(offs, 2);
10203   movq(sum, Address(out, offs, Address::times_4,  0));
10204   rorq(sum, 32);
10205 
10206   if (UseBMI2Instructions) {
10207     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10208   }
10209   else {
10210     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10211   }
10212 
10213   // Store back in big endian from little endian
10214   rorq(sum, 0x20);
10215   movq(Address(out, offs, Address::times_4,  0), sum);
10216 
10217   testl(len, len);
10218   jccb(Assembler::zero, L_carry);
10219 
10220   //Multiply the last in[] entry, if any
10221   bind(L_last_in);
10222   movl(op1, Address(in, 0));
10223   movl(sum, Address(out, offs, Address::times_4,  -4));
10224 
10225   movl(raxReg, k);
10226   mull(op1); //tmp4 * eax -> edx:eax
10227   addl(sum, carry);
10228   adcl(rdxReg, 0);
10229   addl(sum, raxReg);
10230   adcl(rdxReg, 0);
10231   movl(carry, rdxReg);
10232 
10233   movl(Address(out, offs, Address::times_4,  -4), sum);
10234 
10235   bind(L_carry);
10236   //return tmp5/carry as carry in rax
10237   movl(rax, carry);
10238 
10239   bind(L_done);
10240   pop(tmp5);
10241   pop(tmp4);
10242   pop(tmp3);
10243   pop(tmp2);
10244   pop(tmp1);
10245 }
10246 #endif
10247 
10248 /**
10249  * Emits code to update CRC-32 with a byte value according to constants in table
10250  *
10251  * @param [in,out]crc   Register containing the crc.
10252  * @param [in]val       Register containing the byte to fold into the CRC.
10253  * @param [in]table     Register containing the table of crc constants.
10254  *
10255  * uint32_t crc;
10256  * val = crc_table[(val ^ crc) & 0xFF];
10257  * crc = val ^ (crc >> 8);
10258  *
10259  */
10260 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10261   xorl(val, crc);
10262   andl(val, 0xFF);
10263   shrl(crc, 8); // unsigned shift
10264   xorl(crc, Address(table, val, Address::times_4, 0));
10265 }
10266 
10267 /**
10268  * Fold 128-bit data chunk
10269  */
10270 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10271   if (UseAVX > 0) {
10272     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10273     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10274     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10275     pxor(xcrc, xtmp);
10276   } else {
10277     movdqa(xtmp, xcrc);
10278     pclmulhdq(xtmp, xK);   // [123:64]
10279     pclmulldq(xcrc, xK);   // [63:0]
10280     pxor(xcrc, xtmp);
10281     movdqu(xtmp, Address(buf, offset));
10282     pxor(xcrc, xtmp);
10283   }
10284 }
10285 
10286 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10287   if (UseAVX > 0) {
10288     vpclmulhdq(xtmp, xK, xcrc);
10289     vpclmulldq(xcrc, xK, xcrc);
10290     pxor(xcrc, xbuf);
10291     pxor(xcrc, xtmp);
10292   } else {
10293     movdqa(xtmp, xcrc);
10294     pclmulhdq(xtmp, xK);
10295     pclmulldq(xcrc, xK);
10296     pxor(xcrc, xbuf);
10297     pxor(xcrc, xtmp);
10298   }
10299 }
10300 
10301 /**
10302  * 8-bit folds to compute 32-bit CRC
10303  *
10304  * uint64_t xcrc;
10305  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10306  */
10307 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10308   movdl(tmp, xcrc);
10309   andl(tmp, 0xFF);
10310   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10311   psrldq(xcrc, 1); // unsigned shift one byte
10312   pxor(xcrc, xtmp);
10313 }
10314 
10315 /**
10316  * uint32_t crc;
10317  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10318  */
10319 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10320   movl(tmp, crc);
10321   andl(tmp, 0xFF);
10322   shrl(crc, 8);
10323   xorl(crc, Address(table, tmp, Address::times_4, 0));
10324 }
10325 
10326 /**
10327  * @param crc   register containing existing CRC (32-bit)
10328  * @param buf   register pointing to input byte buffer (byte*)
10329  * @param len   register containing number of bytes
10330  * @param table register that will contain address of CRC table
10331  * @param tmp   scratch register
10332  */
10333 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10334   assert_different_registers(crc, buf, len, table, tmp, rax);
10335 
10336   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10337   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10338 
10339   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10340   // context for the registers used, where all instructions below are using 128-bit mode
10341   // On EVEX without VL and BW, these instructions will all be AVX.
10342   if (VM_Version::supports_avx512vlbw()) {
10343     movl(tmp, 0xffff);
10344     kmovwl(k1, tmp);
10345   }
10346 
10347   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10348   notl(crc); // ~crc
10349   cmpl(len, 16);
10350   jcc(Assembler::less, L_tail);
10351 
10352   // Align buffer to 16 bytes
10353   movl(tmp, buf);
10354   andl(tmp, 0xF);
10355   jccb(Assembler::zero, L_aligned);
10356   subl(tmp,  16);
10357   addl(len, tmp);
10358 
10359   align(4);
10360   BIND(L_align_loop);
10361   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10362   update_byte_crc32(crc, rax, table);
10363   increment(buf);
10364   incrementl(tmp);
10365   jccb(Assembler::less, L_align_loop);
10366 
10367   BIND(L_aligned);
10368   movl(tmp, len); // save
10369   shrl(len, 4);
10370   jcc(Assembler::zero, L_tail_restore);
10371 
10372   // Fold crc into first bytes of vector
10373   movdqa(xmm1, Address(buf, 0));
10374   movdl(rax, xmm1);
10375   xorl(crc, rax);
10376   if (VM_Version::supports_sse4_1()) {
10377     pinsrd(xmm1, crc, 0);
10378   } else {
10379     pinsrw(xmm1, crc, 0);
10380     shrl(crc, 16);
10381     pinsrw(xmm1, crc, 1);
10382   }
10383   addptr(buf, 16);
10384   subl(len, 4); // len > 0
10385   jcc(Assembler::less, L_fold_tail);
10386 
10387   movdqa(xmm2, Address(buf,  0));
10388   movdqa(xmm3, Address(buf, 16));
10389   movdqa(xmm4, Address(buf, 32));
10390   addptr(buf, 48);
10391   subl(len, 3);
10392   jcc(Assembler::lessEqual, L_fold_512b);
10393 
10394   // Fold total 512 bits of polynomial on each iteration,
10395   // 128 bits per each of 4 parallel streams.
10396   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10397 
10398   align(32);
10399   BIND(L_fold_512b_loop);
10400   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10401   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10402   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10403   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10404   addptr(buf, 64);
10405   subl(len, 4);
10406   jcc(Assembler::greater, L_fold_512b_loop);
10407 
10408   // Fold 512 bits to 128 bits.
10409   BIND(L_fold_512b);
10410   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10411   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10412   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10413   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10414 
10415   // Fold the rest of 128 bits data chunks
10416   BIND(L_fold_tail);
10417   addl(len, 3);
10418   jccb(Assembler::lessEqual, L_fold_128b);
10419   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10420 
10421   BIND(L_fold_tail_loop);
10422   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10423   addptr(buf, 16);
10424   decrementl(len);
10425   jccb(Assembler::greater, L_fold_tail_loop);
10426 
10427   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10428   BIND(L_fold_128b);
10429   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10430   if (UseAVX > 0) {
10431     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10432     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10433     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10434   } else {
10435     movdqa(xmm2, xmm0);
10436     pclmulqdq(xmm2, xmm1, 0x1);
10437     movdqa(xmm3, xmm0);
10438     pand(xmm3, xmm2);
10439     pclmulqdq(xmm0, xmm3, 0x1);
10440   }
10441   psrldq(xmm1, 8);
10442   psrldq(xmm2, 4);
10443   pxor(xmm0, xmm1);
10444   pxor(xmm0, xmm2);
10445 
10446   // 8 8-bit folds to compute 32-bit CRC.
10447   for (int j = 0; j < 4; j++) {
10448     fold_8bit_crc32(xmm0, table, xmm1, rax);
10449   }
10450   movdl(crc, xmm0); // mov 32 bits to general register
10451   for (int j = 0; j < 4; j++) {
10452     fold_8bit_crc32(crc, table, rax);
10453   }
10454 
10455   BIND(L_tail_restore);
10456   movl(len, tmp); // restore
10457   BIND(L_tail);
10458   andl(len, 0xf);
10459   jccb(Assembler::zero, L_exit);
10460 
10461   // Fold the rest of bytes
10462   align(4);
10463   BIND(L_tail_loop);
10464   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10465   update_byte_crc32(crc, rax, table);
10466   increment(buf);
10467   decrementl(len);
10468   jccb(Assembler::greater, L_tail_loop);
10469 
10470   BIND(L_exit);
10471   notl(crc); // ~c
10472 }
10473 
10474 #ifdef _LP64
10475 // S. Gueron / Information Processing Letters 112 (2012) 184
10476 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10477 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10478 // Output: the 64-bit carry-less product of B * CONST
10479 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10480                                      Register tmp1, Register tmp2, Register tmp3) {
10481   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10482   if (n > 0) {
10483     addq(tmp3, n * 256 * 8);
10484   }
10485   //    Q1 = TABLEExt[n][B & 0xFF];
10486   movl(tmp1, in);
10487   andl(tmp1, 0x000000FF);
10488   shll(tmp1, 3);
10489   addq(tmp1, tmp3);
10490   movq(tmp1, Address(tmp1, 0));
10491 
10492   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10493   movl(tmp2, in);
10494   shrl(tmp2, 8);
10495   andl(tmp2, 0x000000FF);
10496   shll(tmp2, 3);
10497   addq(tmp2, tmp3);
10498   movq(tmp2, Address(tmp2, 0));
10499 
10500   shlq(tmp2, 8);
10501   xorq(tmp1, tmp2);
10502 
10503   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10504   movl(tmp2, in);
10505   shrl(tmp2, 16);
10506   andl(tmp2, 0x000000FF);
10507   shll(tmp2, 3);
10508   addq(tmp2, tmp3);
10509   movq(tmp2, Address(tmp2, 0));
10510 
10511   shlq(tmp2, 16);
10512   xorq(tmp1, tmp2);
10513 
10514   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10515   shrl(in, 24);
10516   andl(in, 0x000000FF);
10517   shll(in, 3);
10518   addq(in, tmp3);
10519   movq(in, Address(in, 0));
10520 
10521   shlq(in, 24);
10522   xorq(in, tmp1);
10523   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10524 }
10525 
10526 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10527                                       Register in_out,
10528                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10529                                       XMMRegister w_xtmp2,
10530                                       Register tmp1,
10531                                       Register n_tmp2, Register n_tmp3) {
10532   if (is_pclmulqdq_supported) {
10533     movdl(w_xtmp1, in_out); // modified blindly
10534 
10535     movl(tmp1, const_or_pre_comp_const_index);
10536     movdl(w_xtmp2, tmp1);
10537     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10538 
10539     movdq(in_out, w_xtmp1);
10540   } else {
10541     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10542   }
10543 }
10544 
10545 // Recombination Alternative 2: No bit-reflections
10546 // T1 = (CRC_A * U1) << 1
10547 // T2 = (CRC_B * U2) << 1
10548 // C1 = T1 >> 32
10549 // C2 = T2 >> 32
10550 // T1 = T1 & 0xFFFFFFFF
10551 // T2 = T2 & 0xFFFFFFFF
10552 // T1 = CRC32(0, T1)
10553 // T2 = CRC32(0, T2)
10554 // C1 = C1 ^ T1
10555 // C2 = C2 ^ T2
10556 // CRC = C1 ^ C2 ^ CRC_C
10557 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,
10558                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10559                                      Register tmp1, Register tmp2,
10560                                      Register n_tmp3) {
10561   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10562   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10563   shlq(in_out, 1);
10564   movl(tmp1, in_out);
10565   shrq(in_out, 32);
10566   xorl(tmp2, tmp2);
10567   crc32(tmp2, tmp1, 4);
10568   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10569   shlq(in1, 1);
10570   movl(tmp1, in1);
10571   shrq(in1, 32);
10572   xorl(tmp2, tmp2);
10573   crc32(tmp2, tmp1, 4);
10574   xorl(in1, tmp2);
10575   xorl(in_out, in1);
10576   xorl(in_out, in2);
10577 }
10578 
10579 // Set N to predefined value
10580 // Subtract from a lenght of a buffer
10581 // execute in a loop:
10582 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10583 // for i = 1 to N do
10584 //  CRC_A = CRC32(CRC_A, A[i])
10585 //  CRC_B = CRC32(CRC_B, B[i])
10586 //  CRC_C = CRC32(CRC_C, C[i])
10587 // end for
10588 // Recombine
10589 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,
10590                                        Register in_out1, Register in_out2, Register in_out3,
10591                                        Register tmp1, Register tmp2, Register tmp3,
10592                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10593                                        Register tmp4, Register tmp5,
10594                                        Register n_tmp6) {
10595   Label L_processPartitions;
10596   Label L_processPartition;
10597   Label L_exit;
10598 
10599   bind(L_processPartitions);
10600   cmpl(in_out1, 3 * size);
10601   jcc(Assembler::less, L_exit);
10602     xorl(tmp1, tmp1);
10603     xorl(tmp2, tmp2);
10604     movq(tmp3, in_out2);
10605     addq(tmp3, size);
10606 
10607     bind(L_processPartition);
10608       crc32(in_out3, Address(in_out2, 0), 8);
10609       crc32(tmp1, Address(in_out2, size), 8);
10610       crc32(tmp2, Address(in_out2, size * 2), 8);
10611       addq(in_out2, 8);
10612       cmpq(in_out2, tmp3);
10613       jcc(Assembler::less, L_processPartition);
10614     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10615             w_xtmp1, w_xtmp2, w_xtmp3,
10616             tmp4, tmp5,
10617             n_tmp6);
10618     addq(in_out2, 2 * size);
10619     subl(in_out1, 3 * size);
10620     jmp(L_processPartitions);
10621 
10622   bind(L_exit);
10623 }
10624 #else
10625 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10626                                      Register tmp1, Register tmp2, Register tmp3,
10627                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10628   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10629   if (n > 0) {
10630     addl(tmp3, n * 256 * 8);
10631   }
10632   //    Q1 = TABLEExt[n][B & 0xFF];
10633   movl(tmp1, in_out);
10634   andl(tmp1, 0x000000FF);
10635   shll(tmp1, 3);
10636   addl(tmp1, tmp3);
10637   movq(xtmp1, Address(tmp1, 0));
10638 
10639   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10640   movl(tmp2, in_out);
10641   shrl(tmp2, 8);
10642   andl(tmp2, 0x000000FF);
10643   shll(tmp2, 3);
10644   addl(tmp2, tmp3);
10645   movq(xtmp2, Address(tmp2, 0));
10646 
10647   psllq(xtmp2, 8);
10648   pxor(xtmp1, xtmp2);
10649 
10650   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10651   movl(tmp2, in_out);
10652   shrl(tmp2, 16);
10653   andl(tmp2, 0x000000FF);
10654   shll(tmp2, 3);
10655   addl(tmp2, tmp3);
10656   movq(xtmp2, Address(tmp2, 0));
10657 
10658   psllq(xtmp2, 16);
10659   pxor(xtmp1, xtmp2);
10660 
10661   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10662   shrl(in_out, 24);
10663   andl(in_out, 0x000000FF);
10664   shll(in_out, 3);
10665   addl(in_out, tmp3);
10666   movq(xtmp2, Address(in_out, 0));
10667 
10668   psllq(xtmp2, 24);
10669   pxor(xtmp1, xtmp2); // Result in CXMM
10670   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10671 }
10672 
10673 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10674                                       Register in_out,
10675                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10676                                       XMMRegister w_xtmp2,
10677                                       Register tmp1,
10678                                       Register n_tmp2, Register n_tmp3) {
10679   if (is_pclmulqdq_supported) {
10680     movdl(w_xtmp1, in_out);
10681 
10682     movl(tmp1, const_or_pre_comp_const_index);
10683     movdl(w_xtmp2, tmp1);
10684     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10685     // Keep result in XMM since GPR is 32 bit in length
10686   } else {
10687     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10688   }
10689 }
10690 
10691 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,
10692                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10693                                      Register tmp1, Register tmp2,
10694                                      Register n_tmp3) {
10695   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10696   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10697 
10698   psllq(w_xtmp1, 1);
10699   movdl(tmp1, w_xtmp1);
10700   psrlq(w_xtmp1, 32);
10701   movdl(in_out, w_xtmp1);
10702 
10703   xorl(tmp2, tmp2);
10704   crc32(tmp2, tmp1, 4);
10705   xorl(in_out, tmp2);
10706 
10707   psllq(w_xtmp2, 1);
10708   movdl(tmp1, w_xtmp2);
10709   psrlq(w_xtmp2, 32);
10710   movdl(in1, w_xtmp2);
10711 
10712   xorl(tmp2, tmp2);
10713   crc32(tmp2, tmp1, 4);
10714   xorl(in1, tmp2);
10715   xorl(in_out, in1);
10716   xorl(in_out, in2);
10717 }
10718 
10719 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,
10720                                        Register in_out1, Register in_out2, Register in_out3,
10721                                        Register tmp1, Register tmp2, Register tmp3,
10722                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10723                                        Register tmp4, Register tmp5,
10724                                        Register n_tmp6) {
10725   Label L_processPartitions;
10726   Label L_processPartition;
10727   Label L_exit;
10728 
10729   bind(L_processPartitions);
10730   cmpl(in_out1, 3 * size);
10731   jcc(Assembler::less, L_exit);
10732     xorl(tmp1, tmp1);
10733     xorl(tmp2, tmp2);
10734     movl(tmp3, in_out2);
10735     addl(tmp3, size);
10736 
10737     bind(L_processPartition);
10738       crc32(in_out3, Address(in_out2, 0), 4);
10739       crc32(tmp1, Address(in_out2, size), 4);
10740       crc32(tmp2, Address(in_out2, size*2), 4);
10741       crc32(in_out3, Address(in_out2, 0+4), 4);
10742       crc32(tmp1, Address(in_out2, size+4), 4);
10743       crc32(tmp2, Address(in_out2, size*2+4), 4);
10744       addl(in_out2, 8);
10745       cmpl(in_out2, tmp3);
10746       jcc(Assembler::less, L_processPartition);
10747 
10748         push(tmp3);
10749         push(in_out1);
10750         push(in_out2);
10751         tmp4 = tmp3;
10752         tmp5 = in_out1;
10753         n_tmp6 = in_out2;
10754 
10755       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10756             w_xtmp1, w_xtmp2, w_xtmp3,
10757             tmp4, tmp5,
10758             n_tmp6);
10759 
10760         pop(in_out2);
10761         pop(in_out1);
10762         pop(tmp3);
10763 
10764     addl(in_out2, 2 * size);
10765     subl(in_out1, 3 * size);
10766     jmp(L_processPartitions);
10767 
10768   bind(L_exit);
10769 }
10770 #endif //LP64
10771 
10772 #ifdef _LP64
10773 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10774 // Input: A buffer I of L bytes.
10775 // Output: the CRC32C value of the buffer.
10776 // Notations:
10777 // Write L = 24N + r, with N = floor (L/24).
10778 // r = L mod 24 (0 <= r < 24).
10779 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10780 // N quadwords, and R consists of r bytes.
10781 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10782 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10783 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10784 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10785 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10786                                           Register tmp1, Register tmp2, Register tmp3,
10787                                           Register tmp4, Register tmp5, Register tmp6,
10788                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10789                                           bool is_pclmulqdq_supported) {
10790   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10791   Label L_wordByWord;
10792   Label L_byteByByteProlog;
10793   Label L_byteByByte;
10794   Label L_exit;
10795 
10796   if (is_pclmulqdq_supported ) {
10797     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10798     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10799 
10800     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10801     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10802 
10803     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10804     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10805     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10806   } else {
10807     const_or_pre_comp_const_index[0] = 1;
10808     const_or_pre_comp_const_index[1] = 0;
10809 
10810     const_or_pre_comp_const_index[2] = 3;
10811     const_or_pre_comp_const_index[3] = 2;
10812 
10813     const_or_pre_comp_const_index[4] = 5;
10814     const_or_pre_comp_const_index[5] = 4;
10815    }
10816   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10817                     in2, in1, in_out,
10818                     tmp1, tmp2, tmp3,
10819                     w_xtmp1, w_xtmp2, w_xtmp3,
10820                     tmp4, tmp5,
10821                     tmp6);
10822   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10823                     in2, in1, in_out,
10824                     tmp1, tmp2, tmp3,
10825                     w_xtmp1, w_xtmp2, w_xtmp3,
10826                     tmp4, tmp5,
10827                     tmp6);
10828   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10829                     in2, in1, in_out,
10830                     tmp1, tmp2, tmp3,
10831                     w_xtmp1, w_xtmp2, w_xtmp3,
10832                     tmp4, tmp5,
10833                     tmp6);
10834   movl(tmp1, in2);
10835   andl(tmp1, 0x00000007);
10836   negl(tmp1);
10837   addl(tmp1, in2);
10838   addq(tmp1, in1);
10839 
10840   BIND(L_wordByWord);
10841   cmpq(in1, tmp1);
10842   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10843     crc32(in_out, Address(in1, 0), 4);
10844     addq(in1, 4);
10845     jmp(L_wordByWord);
10846 
10847   BIND(L_byteByByteProlog);
10848   andl(in2, 0x00000007);
10849   movl(tmp2, 1);
10850 
10851   BIND(L_byteByByte);
10852   cmpl(tmp2, in2);
10853   jccb(Assembler::greater, L_exit);
10854     crc32(in_out, Address(in1, 0), 1);
10855     incq(in1);
10856     incl(tmp2);
10857     jmp(L_byteByByte);
10858 
10859   BIND(L_exit);
10860 }
10861 #else
10862 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10863                                           Register tmp1, Register  tmp2, Register tmp3,
10864                                           Register tmp4, Register  tmp5, Register tmp6,
10865                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10866                                           bool is_pclmulqdq_supported) {
10867   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10868   Label L_wordByWord;
10869   Label L_byteByByteProlog;
10870   Label L_byteByByte;
10871   Label L_exit;
10872 
10873   if (is_pclmulqdq_supported) {
10874     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10875     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10876 
10877     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10878     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10879 
10880     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10881     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10882   } else {
10883     const_or_pre_comp_const_index[0] = 1;
10884     const_or_pre_comp_const_index[1] = 0;
10885 
10886     const_or_pre_comp_const_index[2] = 3;
10887     const_or_pre_comp_const_index[3] = 2;
10888 
10889     const_or_pre_comp_const_index[4] = 5;
10890     const_or_pre_comp_const_index[5] = 4;
10891   }
10892   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10893                     in2, in1, in_out,
10894                     tmp1, tmp2, tmp3,
10895                     w_xtmp1, w_xtmp2, w_xtmp3,
10896                     tmp4, tmp5,
10897                     tmp6);
10898   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10899                     in2, in1, in_out,
10900                     tmp1, tmp2, tmp3,
10901                     w_xtmp1, w_xtmp2, w_xtmp3,
10902                     tmp4, tmp5,
10903                     tmp6);
10904   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10905                     in2, in1, in_out,
10906                     tmp1, tmp2, tmp3,
10907                     w_xtmp1, w_xtmp2, w_xtmp3,
10908                     tmp4, tmp5,
10909                     tmp6);
10910   movl(tmp1, in2);
10911   andl(tmp1, 0x00000007);
10912   negl(tmp1);
10913   addl(tmp1, in2);
10914   addl(tmp1, in1);
10915 
10916   BIND(L_wordByWord);
10917   cmpl(in1, tmp1);
10918   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10919     crc32(in_out, Address(in1,0), 4);
10920     addl(in1, 4);
10921     jmp(L_wordByWord);
10922 
10923   BIND(L_byteByByteProlog);
10924   andl(in2, 0x00000007);
10925   movl(tmp2, 1);
10926 
10927   BIND(L_byteByByte);
10928   cmpl(tmp2, in2);
10929   jccb(Assembler::greater, L_exit);
10930     movb(tmp1, Address(in1, 0));
10931     crc32(in_out, tmp1, 1);
10932     incl(in1);
10933     incl(tmp2);
10934     jmp(L_byteByByte);
10935 
10936   BIND(L_exit);
10937 }
10938 #endif // LP64
10939 #undef BIND
10940 #undef BLOCK_COMMENT
10941 
10942 // Compress char[] array to byte[].
10943 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10944 //   @HotSpotIntrinsicCandidate
10945 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10946 //     for (int i = 0; i < len; i++) {
10947 //       int c = src[srcOff++];
10948 //       if (c >>> 8 != 0) {
10949 //         return 0;
10950 //       }
10951 //       dst[dstOff++] = (byte)c;
10952 //     }
10953 //     return len;
10954 //   }
10955 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10956   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10957   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10958   Register tmp5, Register result) {
10959   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10960 
10961   // rsi: src
10962   // rdi: dst
10963   // rdx: len
10964   // rcx: tmp5
10965   // rax: result
10966 
10967   // rsi holds start addr of source char[] to be compressed
10968   // rdi holds start addr of destination byte[]
10969   // rdx holds length
10970 
10971   assert(len != result, "");
10972 
10973   // save length for return
10974   push(len);
10975 
10976   if ((UseAVX > 2) && // AVX512
10977     VM_Version::supports_avx512vlbw() &&
10978     VM_Version::supports_bmi2()) {
10979 
10980     set_vector_masking();  // opening of the stub context for programming mask registers
10981 
10982     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10983 
10984     // alignement
10985     Label post_alignement;
10986 
10987     // if length of the string is less than 16, handle it in an old fashioned
10988     // way
10989     testl(len, -32);
10990     jcc(Assembler::zero, below_threshold);
10991 
10992     // First check whether a character is compressable ( <= 0xFF).
10993     // Create mask to test for Unicode chars inside zmm vector
10994     movl(result, 0x00FF);
10995     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10996 
10997     // Save k1
10998     kmovql(k3, k1);
10999 
11000     testl(len, -64);
11001     jcc(Assembler::zero, post_alignement);
11002 
11003     movl(tmp5, dst);
11004     andl(tmp5, (32 - 1));
11005     negl(tmp5);
11006     andl(tmp5, (32 - 1));
11007 
11008     // bail out when there is nothing to be done
11009     testl(tmp5, 0xFFFFFFFF);
11010     jcc(Assembler::zero, post_alignement);
11011 
11012     // ~(~0 << len), where len is the # of remaining elements to process
11013     movl(result, 0xFFFFFFFF);
11014     shlxl(result, result, tmp5);
11015     notl(result);
11016     kmovdl(k1, result);
11017 
11018     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11019     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11020     ktestd(k2, k1);
11021     jcc(Assembler::carryClear, restore_k1_return_zero);
11022 
11023     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11024 
11025     addptr(src, tmp5);
11026     addptr(src, tmp5);
11027     addptr(dst, tmp5);
11028     subl(len, tmp5);
11029 
11030     bind(post_alignement);
11031     // end of alignement
11032 
11033     movl(tmp5, len);
11034     andl(tmp5, (32 - 1));    // tail count (in chars)
11035     andl(len, ~(32 - 1));    // vector count (in chars)
11036     jcc(Assembler::zero, copy_loop_tail);
11037 
11038     lea(src, Address(src, len, Address::times_2));
11039     lea(dst, Address(dst, len, Address::times_1));
11040     negptr(len);
11041 
11042     bind(copy_32_loop);
11043     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
11044     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11045     kortestdl(k2, k2);
11046     jcc(Assembler::carryClear, restore_k1_return_zero);
11047 
11048     // All elements in current processed chunk are valid candidates for
11049     // compression. Write a truncated byte elements to the memory.
11050     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
11051     addptr(len, 32);
11052     jcc(Assembler::notZero, copy_32_loop);
11053 
11054     bind(copy_loop_tail);
11055     // bail out when there is nothing to be done
11056     testl(tmp5, 0xFFFFFFFF);
11057     // Restore k1
11058     kmovql(k1, k3);
11059     jcc(Assembler::zero, return_length);
11060 
11061     movl(len, tmp5);
11062 
11063     // ~(~0 << len), where len is the # of remaining elements to process
11064     movl(result, 0xFFFFFFFF);
11065     shlxl(result, result, len);
11066     notl(result);
11067 
11068     kmovdl(k1, result);
11069 
11070     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11071     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11072     ktestd(k2, k1);
11073     jcc(Assembler::carryClear, restore_k1_return_zero);
11074 
11075     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11076     // Restore k1
11077     kmovql(k1, k3);
11078     jmp(return_length);
11079 
11080     bind(restore_k1_return_zero);
11081     // Restore k1
11082     kmovql(k1, k3);
11083     jmp(return_zero);
11084 
11085     clear_vector_masking();   // closing of the stub context for programming mask registers
11086   }
11087   if (UseSSE42Intrinsics) {
11088     Label copy_32_loop, copy_16, copy_tail;
11089 
11090     bind(below_threshold);
11091 
11092     movl(result, len);
11093 
11094     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11095 
11096     // vectored compression
11097     andl(len, 0xfffffff0);    // vector count (in chars)
11098     andl(result, 0x0000000f);    // tail count (in chars)
11099     testl(len, len);
11100     jccb(Assembler::zero, copy_16);
11101 
11102     // compress 16 chars per iter
11103     movdl(tmp1Reg, tmp5);
11104     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11105     pxor(tmp4Reg, tmp4Reg);
11106 
11107     lea(src, Address(src, len, Address::times_2));
11108     lea(dst, Address(dst, len, Address::times_1));
11109     negptr(len);
11110 
11111     bind(copy_32_loop);
11112     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11113     por(tmp4Reg, tmp2Reg);
11114     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11115     por(tmp4Reg, tmp3Reg);
11116     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11117     jcc(Assembler::notZero, return_zero);
11118     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11119     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11120     addptr(len, 16);
11121     jcc(Assembler::notZero, copy_32_loop);
11122 
11123     // compress next vector of 8 chars (if any)
11124     bind(copy_16);
11125     movl(len, result);
11126     andl(len, 0xfffffff8);    // vector count (in chars)
11127     andl(result, 0x00000007);    // tail count (in chars)
11128     testl(len, len);
11129     jccb(Assembler::zero, copy_tail);
11130 
11131     movdl(tmp1Reg, tmp5);
11132     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11133     pxor(tmp3Reg, tmp3Reg);
11134 
11135     movdqu(tmp2Reg, Address(src, 0));
11136     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11137     jccb(Assembler::notZero, return_zero);
11138     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11139     movq(Address(dst, 0), tmp2Reg);
11140     addptr(src, 16);
11141     addptr(dst, 8);
11142 
11143     bind(copy_tail);
11144     movl(len, result);
11145   }
11146   // compress 1 char per iter
11147   testl(len, len);
11148   jccb(Assembler::zero, return_length);
11149   lea(src, Address(src, len, Address::times_2));
11150   lea(dst, Address(dst, len, Address::times_1));
11151   negptr(len);
11152 
11153   bind(copy_chars_loop);
11154   load_unsigned_short(result, Address(src, len, Address::times_2));
11155   testl(result, 0xff00);      // check if Unicode char
11156   jccb(Assembler::notZero, return_zero);
11157   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11158   increment(len);
11159   jcc(Assembler::notZero, copy_chars_loop);
11160 
11161   // if compression succeeded, return length
11162   bind(return_length);
11163   pop(result);
11164   jmpb(done);
11165 
11166   // if compression failed, return 0
11167   bind(return_zero);
11168   xorl(result, result);
11169   addptr(rsp, wordSize);
11170 
11171   bind(done);
11172 }
11173 
11174 // Inflate byte[] array to char[].
11175 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11176 //   @HotSpotIntrinsicCandidate
11177 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11178 //     for (int i = 0; i < len; i++) {
11179 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11180 //     }
11181 //   }
11182 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11183   XMMRegister tmp1, Register tmp2) {
11184   Label copy_chars_loop, done, below_threshold;
11185   // rsi: src
11186   // rdi: dst
11187   // rdx: len
11188   // rcx: tmp2
11189 
11190   // rsi holds start addr of source byte[] to be inflated
11191   // rdi holds start addr of destination char[]
11192   // rdx holds length
11193   assert_different_registers(src, dst, len, tmp2);
11194 
11195   if ((UseAVX > 2) && // AVX512
11196     VM_Version::supports_avx512vlbw() &&
11197     VM_Version::supports_bmi2()) {
11198 
11199     set_vector_masking();  // opening of the stub context for programming mask registers
11200 
11201     Label copy_32_loop, copy_tail;
11202     Register tmp3_aliased = len;
11203 
11204     // if length of the string is less than 16, handle it in an old fashioned
11205     // way
11206     testl(len, -16);
11207     jcc(Assembler::zero, below_threshold);
11208 
11209     // In order to use only one arithmetic operation for the main loop we use
11210     // this pre-calculation
11211     movl(tmp2, len);
11212     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11213     andl(len, -32);     // vector count
11214     jccb(Assembler::zero, copy_tail);
11215 
11216     lea(src, Address(src, len, Address::times_1));
11217     lea(dst, Address(dst, len, Address::times_2));
11218     negptr(len);
11219 
11220 
11221     // inflate 32 chars per iter
11222     bind(copy_32_loop);
11223     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11224     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11225     addptr(len, 32);
11226     jcc(Assembler::notZero, copy_32_loop);
11227 
11228     bind(copy_tail);
11229     // bail out when there is nothing to be done
11230     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11231     jcc(Assembler::zero, done);
11232 
11233     // Save k1
11234     kmovql(k2, k1);
11235 
11236     // ~(~0 << length), where length is the # of remaining elements to process
11237     movl(tmp3_aliased, -1);
11238     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11239     notl(tmp3_aliased);
11240     kmovdl(k1, tmp3_aliased);
11241     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11242     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11243 
11244     // Restore k1
11245     kmovql(k1, k2);
11246     jmp(done);
11247 
11248     clear_vector_masking();   // closing of the stub context for programming mask registers
11249   }
11250   if (UseSSE42Intrinsics) {
11251     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11252 
11253     movl(tmp2, len);
11254 
11255     if (UseAVX > 1) {
11256       andl(tmp2, (16 - 1));
11257       andl(len, -16);
11258       jccb(Assembler::zero, copy_new_tail);
11259     } else {
11260       andl(tmp2, 0x00000007);   // tail count (in chars)
11261       andl(len, 0xfffffff8);    // vector count (in chars)
11262       jccb(Assembler::zero, copy_tail);
11263     }
11264 
11265     // vectored inflation
11266     lea(src, Address(src, len, Address::times_1));
11267     lea(dst, Address(dst, len, Address::times_2));
11268     negptr(len);
11269 
11270     if (UseAVX > 1) {
11271       bind(copy_16_loop);
11272       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11273       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11274       addptr(len, 16);
11275       jcc(Assembler::notZero, copy_16_loop);
11276 
11277       bind(below_threshold);
11278       bind(copy_new_tail);
11279       if ((UseAVX > 2) &&
11280         VM_Version::supports_avx512vlbw() &&
11281         VM_Version::supports_bmi2()) {
11282         movl(tmp2, len);
11283       } else {
11284         movl(len, tmp2);
11285       }
11286       andl(tmp2, 0x00000007);
11287       andl(len, 0xFFFFFFF8);
11288       jccb(Assembler::zero, copy_tail);
11289 
11290       pmovzxbw(tmp1, Address(src, 0));
11291       movdqu(Address(dst, 0), tmp1);
11292       addptr(src, 8);
11293       addptr(dst, 2 * 8);
11294 
11295       jmp(copy_tail, true);
11296     }
11297 
11298     // inflate 8 chars per iter
11299     bind(copy_8_loop);
11300     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11301     movdqu(Address(dst, len, Address::times_2), tmp1);
11302     addptr(len, 8);
11303     jcc(Assembler::notZero, copy_8_loop);
11304 
11305     bind(copy_tail);
11306     movl(len, tmp2);
11307 
11308     cmpl(len, 4);
11309     jccb(Assembler::less, copy_bytes);
11310 
11311     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11312     pmovzxbw(tmp1, tmp1);
11313     movq(Address(dst, 0), tmp1);
11314     subptr(len, 4);
11315     addptr(src, 4);
11316     addptr(dst, 8);
11317 
11318     bind(copy_bytes);
11319   }
11320   testl(len, len);
11321   jccb(Assembler::zero, done);
11322   lea(src, Address(src, len, Address::times_1));
11323   lea(dst, Address(dst, len, Address::times_2));
11324   negptr(len);
11325 
11326   // inflate 1 char per iter
11327   bind(copy_chars_loop);
11328   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11329   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11330   increment(len);
11331   jcc(Assembler::notZero, copy_chars_loop);
11332 
11333   bind(done);
11334 }
11335 
11336 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11337   switch (cond) {
11338     // Note some conditions are synonyms for others
11339     case Assembler::zero:         return Assembler::notZero;
11340     case Assembler::notZero:      return Assembler::zero;
11341     case Assembler::less:         return Assembler::greaterEqual;
11342     case Assembler::lessEqual:    return Assembler::greater;
11343     case Assembler::greater:      return Assembler::lessEqual;
11344     case Assembler::greaterEqual: return Assembler::less;
11345     case Assembler::below:        return Assembler::aboveEqual;
11346     case Assembler::belowEqual:   return Assembler::above;
11347     case Assembler::above:        return Assembler::belowEqual;
11348     case Assembler::aboveEqual:   return Assembler::below;
11349     case Assembler::overflow:     return Assembler::noOverflow;
11350     case Assembler::noOverflow:   return Assembler::overflow;
11351     case Assembler::negative:     return Assembler::positive;
11352     case Assembler::positive:     return Assembler::negative;
11353     case Assembler::parity:       return Assembler::noParity;
11354     case Assembler::noParity:     return Assembler::parity;
11355   }
11356   ShouldNotReachHere(); return Assembler::overflow;
11357 }
11358 
11359 SkipIfEqual::SkipIfEqual(
11360     MacroAssembler* masm, const bool* flag_addr, bool value) {
11361   _masm = masm;
11362   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11363   _masm->jcc(Assembler::equal, _label);
11364 }
11365 
11366 SkipIfEqual::~SkipIfEqual() {
11367   _masm->bind(_label);
11368 }
11369 
11370 // 32-bit Windows has its own fast-path implementation
11371 // of get_thread
11372 #if !defined(WIN32) || defined(_LP64)
11373 
11374 // This is simply a call to Thread::current()
11375 void MacroAssembler::get_thread(Register thread) {
11376   if (thread != rax) {
11377     push(rax);
11378   }
11379   LP64_ONLY(push(rdi);)
11380   LP64_ONLY(push(rsi);)
11381   push(rdx);
11382   push(rcx);
11383 #ifdef _LP64
11384   push(r8);
11385   push(r9);
11386   push(r10);
11387   push(r11);
11388 #endif
11389 
11390   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11391 
11392 #ifdef _LP64
11393   pop(r11);
11394   pop(r10);
11395   pop(r9);
11396   pop(r8);
11397 #endif
11398   pop(rcx);
11399   pop(rdx);
11400   LP64_ONLY(pop(rsi);)
11401   LP64_ONLY(pop(rdi);)
11402   if (thread != rax) {
11403     mov(thread, rax);
11404     pop(rax);
11405   }
11406 }
11407 
11408 #endif