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/g1CardTable.hpp"
  50 #include "gc/g1/g1CollectedHeap.inline.hpp"
  51 #include "gc/g1/g1SATBCardTableModRefBS.hpp"
  52 #include "gc/g1/heapRegion.hpp"
  53 #endif // INCLUDE_ALL_GCS
  54 #include "crc32c.h"
  55 #ifdef COMPILER2
  56 #include "opto/intrinsicnode.hpp"
  57 #endif
  58 
  59 #ifdef PRODUCT
  60 #define BLOCK_COMMENT(str) /* nothing */
  61 #define STOP(error) stop(error)
  62 #else
  63 #define BLOCK_COMMENT(str) block_comment(str)
  64 #define STOP(error) block_comment(error); stop(error)
  65 #endif
  66 
  67 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
  68 
  69 #ifdef ASSERT
  70 bool AbstractAssembler::pd_check_instruction_mark() { return true; }
  71 #endif
  72 
  73 static Assembler::Condition reverse[] = {
  74     Assembler::noOverflow     /* overflow      = 0x0 */ ,
  75     Assembler::overflow       /* noOverflow    = 0x1 */ ,
  76     Assembler::aboveEqual     /* carrySet      = 0x2, below         = 0x2 */ ,
  77     Assembler::below          /* aboveEqual    = 0x3, carryClear    = 0x3 */ ,
  78     Assembler::notZero        /* zero          = 0x4, equal         = 0x4 */ ,
  79     Assembler::zero           /* notZero       = 0x5, notEqual      = 0x5 */ ,
  80     Assembler::above          /* belowEqual    = 0x6 */ ,
  81     Assembler::belowEqual     /* above         = 0x7 */ ,
  82     Assembler::positive       /* negative      = 0x8 */ ,
  83     Assembler::negative       /* positive      = 0x9 */ ,
  84     Assembler::noParity       /* parity        = 0xa */ ,
  85     Assembler::parity         /* noParity      = 0xb */ ,
  86     Assembler::greaterEqual   /* less          = 0xc */ ,
  87     Assembler::less           /* greaterEqual  = 0xd */ ,
  88     Assembler::greater        /* lessEqual     = 0xe */ ,
  89     Assembler::lessEqual      /* greater       = 0xf, */
  90 
  91 };
  92 
  93 
  94 // Implementation of MacroAssembler
  95 
  96 // First all the versions that have distinct versions depending on 32/64 bit
  97 // Unless the difference is trivial (1 line or so).
  98 
  99 #ifndef _LP64
 100 
 101 // 32bit versions
 102 
 103 Address MacroAssembler::as_Address(AddressLiteral adr) {
 104   return Address(adr.target(), adr.rspec());
 105 }
 106 
 107 Address MacroAssembler::as_Address(ArrayAddress adr) {
 108   return Address::make_array(adr);
 109 }
 110 
 111 void MacroAssembler::call_VM_leaf_base(address entry_point,
 112                                        int number_of_arguments) {
 113   call(RuntimeAddress(entry_point));
 114   increment(rsp, number_of_arguments * wordSize);
 115 }
 116 
 117 void MacroAssembler::cmpklass(Address src1, Metadata* obj) {
 118   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 119 }
 120 
 121 void MacroAssembler::cmpklass(Register src1, Metadata* obj) {
 122   cmp_literal32(src1, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 123 }
 124 
 125 void MacroAssembler::cmpoop(Address src1, jobject obj) {
 126   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 127 }
 128 
 129 void MacroAssembler::cmpoop(Register src1, jobject obj) {
 130   cmp_literal32(src1, (int32_t)obj, oop_Relocation::spec_for_immediate());
 131 }
 132 
 133 void MacroAssembler::extend_sign(Register hi, Register lo) {
 134   // According to Intel Doc. AP-526, "Integer Divide", p.18.
 135   if (VM_Version::is_P6() && hi == rdx && lo == rax) {
 136     cdql();
 137   } else {
 138     movl(hi, lo);
 139     sarl(hi, 31);
 140   }
 141 }
 142 
 143 void MacroAssembler::jC2(Register tmp, Label& L) {
 144   // set parity bit if FPU flag C2 is set (via rax)
 145   save_rax(tmp);
 146   fwait(); fnstsw_ax();
 147   sahf();
 148   restore_rax(tmp);
 149   // branch
 150   jcc(Assembler::parity, L);
 151 }
 152 
 153 void MacroAssembler::jnC2(Register tmp, Label& L) {
 154   // set parity bit if FPU flag C2 is set (via rax)
 155   save_rax(tmp);
 156   fwait(); fnstsw_ax();
 157   sahf();
 158   restore_rax(tmp);
 159   // branch
 160   jcc(Assembler::noParity, L);
 161 }
 162 
 163 // 32bit can do a case table jump in one instruction but we no longer allow the base
 164 // to be installed in the Address class
 165 void MacroAssembler::jump(ArrayAddress entry) {
 166   jmp(as_Address(entry));
 167 }
 168 
 169 // Note: y_lo will be destroyed
 170 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 171   // Long compare for Java (semantics as described in JVM spec.)
 172   Label high, low, done;
 173 
 174   cmpl(x_hi, y_hi);
 175   jcc(Assembler::less, low);
 176   jcc(Assembler::greater, high);
 177   // x_hi is the return register
 178   xorl(x_hi, x_hi);
 179   cmpl(x_lo, y_lo);
 180   jcc(Assembler::below, low);
 181   jcc(Assembler::equal, done);
 182 
 183   bind(high);
 184   xorl(x_hi, x_hi);
 185   increment(x_hi);
 186   jmp(done);
 187 
 188   bind(low);
 189   xorl(x_hi, x_hi);
 190   decrementl(x_hi);
 191 
 192   bind(done);
 193 }
 194 
 195 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 196     mov_literal32(dst, (int32_t)src.target(), src.rspec());
 197 }
 198 
 199 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 200   // leal(dst, as_Address(adr));
 201   // see note in movl as to why we must use a move
 202   mov_literal32(dst, (int32_t) adr.target(), adr.rspec());
 203 }
 204 
 205 void MacroAssembler::leave() {
 206   mov(rsp, rbp);
 207   pop(rbp);
 208 }
 209 
 210 void MacroAssembler::lmul(int x_rsp_offset, int y_rsp_offset) {
 211   // Multiplication of two Java long values stored on the stack
 212   // as illustrated below. Result is in rdx:rax.
 213   //
 214   // rsp ---> [  ??  ] \               \
 215   //            ....    | y_rsp_offset  |
 216   //          [ y_lo ] /  (in bytes)    | x_rsp_offset
 217   //          [ y_hi ]                  | (in bytes)
 218   //            ....                    |
 219   //          [ x_lo ]                 /
 220   //          [ x_hi ]
 221   //            ....
 222   //
 223   // Basic idea: lo(result) = lo(x_lo * y_lo)
 224   //             hi(result) = hi(x_lo * y_lo) + lo(x_hi * y_lo) + lo(x_lo * y_hi)
 225   Address x_hi(rsp, x_rsp_offset + wordSize); Address x_lo(rsp, x_rsp_offset);
 226   Address y_hi(rsp, y_rsp_offset + wordSize); Address y_lo(rsp, y_rsp_offset);
 227   Label quick;
 228   // load x_hi, y_hi and check if quick
 229   // multiplication is possible
 230   movl(rbx, x_hi);
 231   movl(rcx, y_hi);
 232   movl(rax, rbx);
 233   orl(rbx, rcx);                                 // rbx, = 0 <=> x_hi = 0 and y_hi = 0
 234   jcc(Assembler::zero, quick);                   // if rbx, = 0 do quick multiply
 235   // do full multiplication
 236   // 1st step
 237   mull(y_lo);                                    // x_hi * y_lo
 238   movl(rbx, rax);                                // save lo(x_hi * y_lo) in rbx,
 239   // 2nd step
 240   movl(rax, x_lo);
 241   mull(rcx);                                     // x_lo * y_hi
 242   addl(rbx, rax);                                // add lo(x_lo * y_hi) to rbx,
 243   // 3rd step
 244   bind(quick);                                   // note: rbx, = 0 if quick multiply!
 245   movl(rax, x_lo);
 246   mull(y_lo);                                    // x_lo * y_lo
 247   addl(rdx, rbx);                                // correct hi(x_lo * y_lo)
 248 }
 249 
 250 void MacroAssembler::lneg(Register hi, Register lo) {
 251   negl(lo);
 252   adcl(hi, 0);
 253   negl(hi);
 254 }
 255 
 256 void MacroAssembler::lshl(Register hi, Register lo) {
 257   // Java shift left long support (semantics as described in JVM spec., p.305)
 258   // (basic idea for shift counts s >= n: x << s == (x << n) << (s - n))
 259   // shift value is in rcx !
 260   assert(hi != rcx, "must not use rcx");
 261   assert(lo != rcx, "must not use rcx");
 262   const Register s = rcx;                        // shift count
 263   const int      n = BitsPerWord;
 264   Label L;
 265   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 266   cmpl(s, n);                                    // if (s < n)
 267   jcc(Assembler::less, L);                       // else (s >= n)
 268   movl(hi, lo);                                  // x := x << n
 269   xorl(lo, lo);
 270   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 271   bind(L);                                       // s (mod n) < n
 272   shldl(hi, lo);                                 // x := x << s
 273   shll(lo);
 274 }
 275 
 276 
 277 void MacroAssembler::lshr(Register hi, Register lo, bool sign_extension) {
 278   // Java shift right long support (semantics as described in JVM spec., p.306 & p.310)
 279   // (basic idea for shift counts s >= n: x >> s == (x >> n) >> (s - n))
 280   assert(hi != rcx, "must not use rcx");
 281   assert(lo != rcx, "must not use rcx");
 282   const Register s = rcx;                        // shift count
 283   const int      n = BitsPerWord;
 284   Label L;
 285   andl(s, 0x3f);                                 // s := s & 0x3f (s < 0x40)
 286   cmpl(s, n);                                    // if (s < n)
 287   jcc(Assembler::less, L);                       // else (s >= n)
 288   movl(lo, hi);                                  // x := x >> n
 289   if (sign_extension) sarl(hi, 31);
 290   else                xorl(hi, hi);
 291   // Note: subl(s, n) is not needed since the Intel shift instructions work rcx mod n!
 292   bind(L);                                       // s (mod n) < n
 293   shrdl(lo, hi);                                 // x := x >> s
 294   if (sign_extension) sarl(hi);
 295   else                shrl(hi);
 296 }
 297 
 298 void MacroAssembler::movoop(Register dst, jobject obj) {
 299   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 300 }
 301 
 302 void MacroAssembler::movoop(Address dst, jobject obj) {
 303   mov_literal32(dst, (int32_t)obj, oop_Relocation::spec_for_immediate());
 304 }
 305 
 306 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 307   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 308 }
 309 
 310 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 311   mov_literal32(dst, (int32_t)obj, metadata_Relocation::spec_for_immediate());
 312 }
 313 
 314 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 315   // scratch register is not used,
 316   // it is defined to match parameters of 64-bit version of this method.
 317   if (src.is_lval()) {
 318     mov_literal32(dst, (intptr_t)src.target(), src.rspec());
 319   } else {
 320     movl(dst, as_Address(src));
 321   }
 322 }
 323 
 324 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 325   movl(as_Address(dst), src);
 326 }
 327 
 328 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 329   movl(dst, as_Address(src));
 330 }
 331 
 332 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 333 void MacroAssembler::movptr(Address dst, intptr_t src) {
 334   movl(dst, src);
 335 }
 336 
 337 
 338 void MacroAssembler::pop_callee_saved_registers() {
 339   pop(rcx);
 340   pop(rdx);
 341   pop(rdi);
 342   pop(rsi);
 343 }
 344 
 345 void MacroAssembler::pop_fTOS() {
 346   fld_d(Address(rsp, 0));
 347   addl(rsp, 2 * wordSize);
 348 }
 349 
 350 void MacroAssembler::push_callee_saved_registers() {
 351   push(rsi);
 352   push(rdi);
 353   push(rdx);
 354   push(rcx);
 355 }
 356 
 357 void MacroAssembler::push_fTOS() {
 358   subl(rsp, 2 * wordSize);
 359   fstp_d(Address(rsp, 0));
 360 }
 361 
 362 
 363 void MacroAssembler::pushoop(jobject obj) {
 364   push_literal32((int32_t)obj, oop_Relocation::spec_for_immediate());
 365 }
 366 
 367 void MacroAssembler::pushklass(Metadata* obj) {
 368   push_literal32((int32_t)obj, metadata_Relocation::spec_for_immediate());
 369 }
 370 
 371 void MacroAssembler::pushptr(AddressLiteral src) {
 372   if (src.is_lval()) {
 373     push_literal32((int32_t)src.target(), src.rspec());
 374   } else {
 375     pushl(as_Address(src));
 376   }
 377 }
 378 
 379 void MacroAssembler::set_word_if_not_zero(Register dst) {
 380   xorl(dst, dst);
 381   set_byte_if_not_zero(dst);
 382 }
 383 
 384 static void pass_arg0(MacroAssembler* masm, Register arg) {
 385   masm->push(arg);
 386 }
 387 
 388 static void pass_arg1(MacroAssembler* masm, Register arg) {
 389   masm->push(arg);
 390 }
 391 
 392 static void pass_arg2(MacroAssembler* masm, Register arg) {
 393   masm->push(arg);
 394 }
 395 
 396 static void pass_arg3(MacroAssembler* masm, Register arg) {
 397   masm->push(arg);
 398 }
 399 
 400 #ifndef PRODUCT
 401 extern "C" void findpc(intptr_t x);
 402 #endif
 403 
 404 void MacroAssembler::debug32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip, char* msg) {
 405   // In order to get locks to work, we need to fake a in_VM state
 406   JavaThread* thread = JavaThread::current();
 407   JavaThreadState saved_state = thread->thread_state();
 408   thread->set_thread_state(_thread_in_vm);
 409   if (ShowMessageBoxOnError) {
 410     JavaThread* thread = JavaThread::current();
 411     JavaThreadState saved_state = thread->thread_state();
 412     thread->set_thread_state(_thread_in_vm);
 413     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 414       ttyLocker ttyl;
 415       BytecodeCounter::print();
 416     }
 417     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 418     // This is the value of eip which points to where verify_oop will return.
 419     if (os::message_box(msg, "Execution stopped, print registers?")) {
 420       print_state32(rdi, rsi, rbp, rsp, rbx, rdx, rcx, rax, eip);
 421       BREAKPOINT;
 422     }
 423   } else {
 424     ttyLocker ttyl;
 425     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n", msg);
 426   }
 427   // Don't assert holding the ttyLock
 428     assert(false, "DEBUG MESSAGE: %s", msg);
 429   ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 430 }
 431 
 432 void MacroAssembler::print_state32(int rdi, int rsi, int rbp, int rsp, int rbx, int rdx, int rcx, int rax, int eip) {
 433   ttyLocker ttyl;
 434   FlagSetting fs(Debugging, true);
 435   tty->print_cr("eip = 0x%08x", eip);
 436 #ifndef PRODUCT
 437   if ((WizardMode || Verbose) && PrintMiscellaneous) {
 438     tty->cr();
 439     findpc(eip);
 440     tty->cr();
 441   }
 442 #endif
 443 #define PRINT_REG(rax) \
 444   { tty->print("%s = ", #rax); os::print_location(tty, rax); }
 445   PRINT_REG(rax);
 446   PRINT_REG(rbx);
 447   PRINT_REG(rcx);
 448   PRINT_REG(rdx);
 449   PRINT_REG(rdi);
 450   PRINT_REG(rsi);
 451   PRINT_REG(rbp);
 452   PRINT_REG(rsp);
 453 #undef PRINT_REG
 454   // Print some words near top of staack.
 455   int* dump_sp = (int*) rsp;
 456   for (int col1 = 0; col1 < 8; col1++) {
 457     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 458     os::print_location(tty, *dump_sp++);
 459   }
 460   for (int row = 0; row < 16; row++) {
 461     tty->print("(rsp+0x%03x) 0x%08x: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 462     for (int col = 0; col < 8; col++) {
 463       tty->print(" 0x%08x", *dump_sp++);
 464     }
 465     tty->cr();
 466   }
 467   // Print some instructions around pc:
 468   Disassembler::decode((address)eip-64, (address)eip);
 469   tty->print_cr("--------");
 470   Disassembler::decode((address)eip, (address)eip+32);
 471 }
 472 
 473 void MacroAssembler::stop(const char* msg) {
 474   ExternalAddress message((address)msg);
 475   // push address of message
 476   pushptr(message.addr());
 477   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 478   pusha();                                            // push registers
 479   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug32)));
 480   hlt();
 481 }
 482 
 483 void MacroAssembler::warn(const char* msg) {
 484   push_CPU_state();
 485 
 486   ExternalAddress message((address) msg);
 487   // push address of message
 488   pushptr(message.addr());
 489 
 490   call(RuntimeAddress(CAST_FROM_FN_PTR(address, warning)));
 491   addl(rsp, wordSize);       // discard argument
 492   pop_CPU_state();
 493 }
 494 
 495 void MacroAssembler::print_state() {
 496   { Label L; call(L, relocInfo::none); bind(L); }     // push eip
 497   pusha();                                            // push registers
 498 
 499   push_CPU_state();
 500   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::print_state32)));
 501   pop_CPU_state();
 502 
 503   popa();
 504   addl(rsp, wordSize);
 505 }
 506 
 507 #else // _LP64
 508 
 509 // 64 bit versions
 510 
 511 Address MacroAssembler::as_Address(AddressLiteral adr) {
 512   // amd64 always does this as a pc-rel
 513   // we can be absolute or disp based on the instruction type
 514   // jmp/call are displacements others are absolute
 515   assert(!adr.is_lval(), "must be rval");
 516   assert(reachable(adr), "must be");
 517   return Address((int32_t)(intptr_t)(adr.target() - pc()), adr.target(), adr.reloc());
 518 
 519 }
 520 
 521 Address MacroAssembler::as_Address(ArrayAddress adr) {
 522   AddressLiteral base = adr.base();
 523   lea(rscratch1, base);
 524   Address index = adr.index();
 525   assert(index._disp == 0, "must not have disp"); // maybe it can?
 526   Address array(rscratch1, index._index, index._scale, index._disp);
 527   return array;
 528 }
 529 
 530 void MacroAssembler::call_VM_leaf_base(address entry_point, int num_args) {
 531   Label L, E;
 532 
 533 #ifdef _WIN64
 534   // Windows always allocates space for it's register args
 535   assert(num_args <= 4, "only register arguments supported");
 536   subq(rsp,  frame::arg_reg_save_area_bytes);
 537 #endif
 538 
 539   // Align stack if necessary
 540   testl(rsp, 15);
 541   jcc(Assembler::zero, L);
 542 
 543   subq(rsp, 8);
 544   {
 545     call(RuntimeAddress(entry_point));
 546   }
 547   addq(rsp, 8);
 548   jmp(E);
 549 
 550   bind(L);
 551   {
 552     call(RuntimeAddress(entry_point));
 553   }
 554 
 555   bind(E);
 556 
 557 #ifdef _WIN64
 558   // restore stack pointer
 559   addq(rsp, frame::arg_reg_save_area_bytes);
 560 #endif
 561 
 562 }
 563 
 564 void MacroAssembler::cmp64(Register src1, AddressLiteral src2) {
 565   assert(!src2.is_lval(), "should use cmpptr");
 566 
 567   if (reachable(src2)) {
 568     cmpq(src1, as_Address(src2));
 569   } else {
 570     lea(rscratch1, src2);
 571     Assembler::cmpq(src1, Address(rscratch1, 0));
 572   }
 573 }
 574 
 575 int MacroAssembler::corrected_idivq(Register reg) {
 576   // Full implementation of Java ldiv and lrem; checks for special
 577   // case as described in JVM spec., p.243 & p.271.  The function
 578   // returns the (pc) offset of the idivl instruction - may be needed
 579   // for implicit exceptions.
 580   //
 581   //         normal case                           special case
 582   //
 583   // input : rax: dividend                         min_long
 584   //         reg: divisor   (may not be eax/edx)   -1
 585   //
 586   // output: rax: quotient  (= rax idiv reg)       min_long
 587   //         rdx: remainder (= rax irem reg)       0
 588   assert(reg != rax && reg != rdx, "reg cannot be rax or rdx register");
 589   static const int64_t min_long = 0x8000000000000000;
 590   Label normal_case, special_case;
 591 
 592   // check for special case
 593   cmp64(rax, ExternalAddress((address) &min_long));
 594   jcc(Assembler::notEqual, normal_case);
 595   xorl(rdx, rdx); // prepare rdx for possible special case (where
 596                   // remainder = 0)
 597   cmpq(reg, -1);
 598   jcc(Assembler::equal, special_case);
 599 
 600   // handle normal case
 601   bind(normal_case);
 602   cdqq();
 603   int idivq_offset = offset();
 604   idivq(reg);
 605 
 606   // normal and special case exit
 607   bind(special_case);
 608 
 609   return idivq_offset;
 610 }
 611 
 612 void MacroAssembler::decrementq(Register reg, int value) {
 613   if (value == min_jint) { subq(reg, value); return; }
 614   if (value <  0) { incrementq(reg, -value); return; }
 615   if (value == 0) {                        ; return; }
 616   if (value == 1 && UseIncDec) { decq(reg) ; return; }
 617   /* else */      { subq(reg, value)       ; return; }
 618 }
 619 
 620 void MacroAssembler::decrementq(Address dst, int value) {
 621   if (value == min_jint) { subq(dst, value); return; }
 622   if (value <  0) { incrementq(dst, -value); return; }
 623   if (value == 0) {                        ; return; }
 624   if (value == 1 && UseIncDec) { decq(dst) ; return; }
 625   /* else */      { subq(dst, value)       ; return; }
 626 }
 627 
 628 void MacroAssembler::incrementq(AddressLiteral dst) {
 629   if (reachable(dst)) {
 630     incrementq(as_Address(dst));
 631   } else {
 632     lea(rscratch1, dst);
 633     incrementq(Address(rscratch1, 0));
 634   }
 635 }
 636 
 637 void MacroAssembler::incrementq(Register reg, int value) {
 638   if (value == min_jint) { addq(reg, value); return; }
 639   if (value <  0) { decrementq(reg, -value); return; }
 640   if (value == 0) {                        ; return; }
 641   if (value == 1 && UseIncDec) { incq(reg) ; return; }
 642   /* else */      { addq(reg, value)       ; return; }
 643 }
 644 
 645 void MacroAssembler::incrementq(Address dst, int value) {
 646   if (value == min_jint) { addq(dst, value); return; }
 647   if (value <  0) { decrementq(dst, -value); return; }
 648   if (value == 0) {                        ; return; }
 649   if (value == 1 && UseIncDec) { incq(dst) ; return; }
 650   /* else */      { addq(dst, value)       ; return; }
 651 }
 652 
 653 // 32bit can do a case table jump in one instruction but we no longer allow the base
 654 // to be installed in the Address class
 655 void MacroAssembler::jump(ArrayAddress entry) {
 656   lea(rscratch1, entry.base());
 657   Address dispatch = entry.index();
 658   assert(dispatch._base == noreg, "must be");
 659   dispatch._base = rscratch1;
 660   jmp(dispatch);
 661 }
 662 
 663 void MacroAssembler::lcmp2int(Register x_hi, Register x_lo, Register y_hi, Register y_lo) {
 664   ShouldNotReachHere(); // 64bit doesn't use two regs
 665   cmpq(x_lo, y_lo);
 666 }
 667 
 668 void MacroAssembler::lea(Register dst, AddressLiteral src) {
 669     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 670 }
 671 
 672 void MacroAssembler::lea(Address dst, AddressLiteral adr) {
 673   mov_literal64(rscratch1, (intptr_t)adr.target(), adr.rspec());
 674   movptr(dst, rscratch1);
 675 }
 676 
 677 void MacroAssembler::leave() {
 678   // %%% is this really better? Why not on 32bit too?
 679   emit_int8((unsigned char)0xC9); // LEAVE
 680 }
 681 
 682 void MacroAssembler::lneg(Register hi, Register lo) {
 683   ShouldNotReachHere(); // 64bit doesn't use two regs
 684   negq(lo);
 685 }
 686 
 687 void MacroAssembler::movoop(Register dst, jobject obj) {
 688   mov_literal64(dst, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 689 }
 690 
 691 void MacroAssembler::movoop(Address dst, jobject obj) {
 692   mov_literal64(rscratch1, (intptr_t)obj, oop_Relocation::spec_for_immediate());
 693   movq(dst, rscratch1);
 694 }
 695 
 696 void MacroAssembler::mov_metadata(Register dst, Metadata* obj) {
 697   mov_literal64(dst, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 698 }
 699 
 700 void MacroAssembler::mov_metadata(Address dst, Metadata* obj) {
 701   mov_literal64(rscratch1, (intptr_t)obj, metadata_Relocation::spec_for_immediate());
 702   movq(dst, rscratch1);
 703 }
 704 
 705 void MacroAssembler::movptr(Register dst, AddressLiteral src, Register scratch) {
 706   if (src.is_lval()) {
 707     mov_literal64(dst, (intptr_t)src.target(), src.rspec());
 708   } else {
 709     if (reachable(src)) {
 710       movq(dst, as_Address(src));
 711     } else {
 712       lea(scratch, src);
 713       movq(dst, Address(scratch, 0));
 714     }
 715   }
 716 }
 717 
 718 void MacroAssembler::movptr(ArrayAddress dst, Register src) {
 719   movq(as_Address(dst), src);
 720 }
 721 
 722 void MacroAssembler::movptr(Register dst, ArrayAddress src) {
 723   movq(dst, as_Address(src));
 724 }
 725 
 726 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
 727 void MacroAssembler::movptr(Address dst, intptr_t src) {
 728   mov64(rscratch1, src);
 729   movq(dst, rscratch1);
 730 }
 731 
 732 // These are mostly for initializing NULL
 733 void MacroAssembler::movptr(Address dst, int32_t src) {
 734   movslq(dst, src);
 735 }
 736 
 737 void MacroAssembler::movptr(Register dst, int32_t src) {
 738   mov64(dst, (intptr_t)src);
 739 }
 740 
 741 void MacroAssembler::pushoop(jobject obj) {
 742   movoop(rscratch1, obj);
 743   push(rscratch1);
 744 }
 745 
 746 void MacroAssembler::pushklass(Metadata* obj) {
 747   mov_metadata(rscratch1, obj);
 748   push(rscratch1);
 749 }
 750 
 751 void MacroAssembler::pushptr(AddressLiteral src) {
 752   lea(rscratch1, src);
 753   if (src.is_lval()) {
 754     push(rscratch1);
 755   } else {
 756     pushq(Address(rscratch1, 0));
 757   }
 758 }
 759 
 760 void MacroAssembler::reset_last_Java_frame(bool clear_fp) {
 761   // we must set sp to zero to clear frame
 762   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
 763   // must clear fp, so that compiled frames are not confused; it is
 764   // possible that we need it only for debugging
 765   if (clear_fp) {
 766     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
 767   }
 768 
 769   // Always clear the pc because it could have been set by make_walkable()
 770   movptr(Address(r15_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
 771   vzeroupper();
 772 }
 773 
 774 void MacroAssembler::set_last_Java_frame(Register last_java_sp,
 775                                          Register last_java_fp,
 776                                          address  last_java_pc) {
 777   vzeroupper();
 778   // determine last_java_sp register
 779   if (!last_java_sp->is_valid()) {
 780     last_java_sp = rsp;
 781   }
 782 
 783   // last_java_fp is optional
 784   if (last_java_fp->is_valid()) {
 785     movptr(Address(r15_thread, JavaThread::last_Java_fp_offset()),
 786            last_java_fp);
 787   }
 788 
 789   // last_java_pc is optional
 790   if (last_java_pc != NULL) {
 791     Address java_pc(r15_thread,
 792                     JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset());
 793     lea(rscratch1, InternalAddress(last_java_pc));
 794     movptr(java_pc, rscratch1);
 795   }
 796 
 797   movptr(Address(r15_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
 798 }
 799 
 800 static void pass_arg0(MacroAssembler* masm, Register arg) {
 801   if (c_rarg0 != arg ) {
 802     masm->mov(c_rarg0, arg);
 803   }
 804 }
 805 
 806 static void pass_arg1(MacroAssembler* masm, Register arg) {
 807   if (c_rarg1 != arg ) {
 808     masm->mov(c_rarg1, arg);
 809   }
 810 }
 811 
 812 static void pass_arg2(MacroAssembler* masm, Register arg) {
 813   if (c_rarg2 != arg ) {
 814     masm->mov(c_rarg2, arg);
 815   }
 816 }
 817 
 818 static void pass_arg3(MacroAssembler* masm, Register arg) {
 819   if (c_rarg3 != arg ) {
 820     masm->mov(c_rarg3, arg);
 821   }
 822 }
 823 
 824 void MacroAssembler::stop(const char* msg) {
 825   address rip = pc();
 826   pusha(); // get regs on stack
 827   lea(c_rarg0, ExternalAddress((address) msg));
 828   lea(c_rarg1, InternalAddress(rip));
 829   movq(c_rarg2, rsp); // pass pointer to regs array
 830   andq(rsp, -16); // align stack as required by ABI
 831   call(RuntimeAddress(CAST_FROM_FN_PTR(address, MacroAssembler::debug64)));
 832   hlt();
 833 }
 834 
 835 void MacroAssembler::warn(const char* msg) {
 836   push(rbp);
 837   movq(rbp, rsp);
 838   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 839   push_CPU_state();   // keeps alignment at 16 bytes
 840   lea(c_rarg0, ExternalAddress((address) msg));
 841   lea(rax, ExternalAddress(CAST_FROM_FN_PTR(address, warning)));
 842   call(rax);
 843   pop_CPU_state();
 844   mov(rsp, rbp);
 845   pop(rbp);
 846 }
 847 
 848 void MacroAssembler::print_state() {
 849   address rip = pc();
 850   pusha();            // get regs on stack
 851   push(rbp);
 852   movq(rbp, rsp);
 853   andq(rsp, -16);     // align stack as required by push_CPU_state and call
 854   push_CPU_state();   // keeps alignment at 16 bytes
 855 
 856   lea(c_rarg0, InternalAddress(rip));
 857   lea(c_rarg1, Address(rbp, wordSize)); // pass pointer to regs array
 858   call_VM_leaf(CAST_FROM_FN_PTR(address, MacroAssembler::print_state64), c_rarg0, c_rarg1);
 859 
 860   pop_CPU_state();
 861   mov(rsp, rbp);
 862   pop(rbp);
 863   popa();
 864 }
 865 
 866 #ifndef PRODUCT
 867 extern "C" void findpc(intptr_t x);
 868 #endif
 869 
 870 void MacroAssembler::debug64(char* msg, int64_t pc, int64_t regs[]) {
 871   // In order to get locks to work, we need to fake a in_VM state
 872   if (ShowMessageBoxOnError) {
 873     JavaThread* thread = JavaThread::current();
 874     JavaThreadState saved_state = thread->thread_state();
 875     thread->set_thread_state(_thread_in_vm);
 876 #ifndef PRODUCT
 877     if (CountBytecodes || TraceBytecodes || StopInterpreterAt) {
 878       ttyLocker ttyl;
 879       BytecodeCounter::print();
 880     }
 881 #endif
 882     // To see where a verify_oop failed, get $ebx+40/X for this frame.
 883     // XXX correct this offset for amd64
 884     // This is the value of eip which points to where verify_oop will return.
 885     if (os::message_box(msg, "Execution stopped, print registers?")) {
 886       print_state64(pc, regs);
 887       BREAKPOINT;
 888       assert(false, "start up GDB");
 889     }
 890     ThreadStateTransition::transition(thread, _thread_in_vm, saved_state);
 891   } else {
 892     ttyLocker ttyl;
 893     ::tty->print_cr("=============== DEBUG MESSAGE: %s ================\n",
 894                     msg);
 895     assert(false, "DEBUG MESSAGE: %s", msg);
 896   }
 897 }
 898 
 899 void MacroAssembler::print_state64(int64_t pc, int64_t regs[]) {
 900   ttyLocker ttyl;
 901   FlagSetting fs(Debugging, true);
 902   tty->print_cr("rip = 0x%016lx", (intptr_t)pc);
 903 #ifndef PRODUCT
 904   tty->cr();
 905   findpc(pc);
 906   tty->cr();
 907 #endif
 908 #define PRINT_REG(rax, value) \
 909   { tty->print("%s = ", #rax); os::print_location(tty, value); }
 910   PRINT_REG(rax, regs[15]);
 911   PRINT_REG(rbx, regs[12]);
 912   PRINT_REG(rcx, regs[14]);
 913   PRINT_REG(rdx, regs[13]);
 914   PRINT_REG(rdi, regs[8]);
 915   PRINT_REG(rsi, regs[9]);
 916   PRINT_REG(rbp, regs[10]);
 917   PRINT_REG(rsp, regs[11]);
 918   PRINT_REG(r8 , regs[7]);
 919   PRINT_REG(r9 , regs[6]);
 920   PRINT_REG(r10, regs[5]);
 921   PRINT_REG(r11, regs[4]);
 922   PRINT_REG(r12, regs[3]);
 923   PRINT_REG(r13, regs[2]);
 924   PRINT_REG(r14, regs[1]);
 925   PRINT_REG(r15, regs[0]);
 926 #undef PRINT_REG
 927   // Print some words near top of staack.
 928   int64_t* rsp = (int64_t*) regs[11];
 929   int64_t* dump_sp = rsp;
 930   for (int col1 = 0; col1 < 8; col1++) {
 931     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 932     os::print_location(tty, *dump_sp++);
 933   }
 934   for (int row = 0; row < 25; row++) {
 935     tty->print("(rsp+0x%03x) 0x%016lx: ", (int)((intptr_t)dump_sp - (intptr_t)rsp), (intptr_t)dump_sp);
 936     for (int col = 0; col < 4; col++) {
 937       tty->print(" 0x%016lx", (intptr_t)*dump_sp++);
 938     }
 939     tty->cr();
 940   }
 941   // Print some instructions around pc:
 942   Disassembler::decode((address)pc-64, (address)pc);
 943   tty->print_cr("--------");
 944   Disassembler::decode((address)pc, (address)pc+32);
 945 }
 946 
 947 #endif // _LP64
 948 
 949 // Now versions that are common to 32/64 bit
 950 
 951 void MacroAssembler::addptr(Register dst, int32_t imm32) {
 952   LP64_ONLY(addq(dst, imm32)) NOT_LP64(addl(dst, imm32));
 953 }
 954 
 955 void MacroAssembler::addptr(Register dst, Register src) {
 956   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 957 }
 958 
 959 void MacroAssembler::addptr(Address dst, Register src) {
 960   LP64_ONLY(addq(dst, src)) NOT_LP64(addl(dst, src));
 961 }
 962 
 963 void MacroAssembler::addsd(XMMRegister dst, AddressLiteral src) {
 964   if (reachable(src)) {
 965     Assembler::addsd(dst, as_Address(src));
 966   } else {
 967     lea(rscratch1, src);
 968     Assembler::addsd(dst, Address(rscratch1, 0));
 969   }
 970 }
 971 
 972 void MacroAssembler::addss(XMMRegister dst, AddressLiteral src) {
 973   if (reachable(src)) {
 974     addss(dst, as_Address(src));
 975   } else {
 976     lea(rscratch1, src);
 977     addss(dst, Address(rscratch1, 0));
 978   }
 979 }
 980 
 981 void MacroAssembler::addpd(XMMRegister dst, AddressLiteral src) {
 982   if (reachable(src)) {
 983     Assembler::addpd(dst, as_Address(src));
 984   } else {
 985     lea(rscratch1, src);
 986     Assembler::addpd(dst, Address(rscratch1, 0));
 987   }
 988 }
 989 
 990 void MacroAssembler::align(int modulus) {
 991   align(modulus, offset());
 992 }
 993 
 994 void MacroAssembler::align(int modulus, int target) {
 995   if (target % modulus != 0) {
 996     nop(modulus - (target % modulus));
 997   }
 998 }
 999 
1000 void MacroAssembler::andpd(XMMRegister dst, AddressLiteral src) {
1001   // Used in sign-masking with aligned address.
1002   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1003   if (reachable(src)) {
1004     Assembler::andpd(dst, as_Address(src));
1005   } else {
1006     lea(rscratch1, src);
1007     Assembler::andpd(dst, Address(rscratch1, 0));
1008   }
1009 }
1010 
1011 void MacroAssembler::andps(XMMRegister dst, AddressLiteral src) {
1012   // Used in sign-masking with aligned address.
1013   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
1014   if (reachable(src)) {
1015     Assembler::andps(dst, as_Address(src));
1016   } else {
1017     lea(rscratch1, src);
1018     Assembler::andps(dst, Address(rscratch1, 0));
1019   }
1020 }
1021 
1022 void MacroAssembler::andptr(Register dst, int32_t imm32) {
1023   LP64_ONLY(andq(dst, imm32)) NOT_LP64(andl(dst, imm32));
1024 }
1025 
1026 void MacroAssembler::atomic_incl(Address counter_addr) {
1027   if (os::is_MP())
1028     lock();
1029   incrementl(counter_addr);
1030 }
1031 
1032 void MacroAssembler::atomic_incl(AddressLiteral counter_addr, Register scr) {
1033   if (reachable(counter_addr)) {
1034     atomic_incl(as_Address(counter_addr));
1035   } else {
1036     lea(scr, counter_addr);
1037     atomic_incl(Address(scr, 0));
1038   }
1039 }
1040 
1041 #ifdef _LP64
1042 void MacroAssembler::atomic_incq(Address counter_addr) {
1043   if (os::is_MP())
1044     lock();
1045   incrementq(counter_addr);
1046 }
1047 
1048 void MacroAssembler::atomic_incq(AddressLiteral counter_addr, Register scr) {
1049   if (reachable(counter_addr)) {
1050     atomic_incq(as_Address(counter_addr));
1051   } else {
1052     lea(scr, counter_addr);
1053     atomic_incq(Address(scr, 0));
1054   }
1055 }
1056 #endif
1057 
1058 // Writes to stack successive pages until offset reached to check for
1059 // stack overflow + shadow pages.  This clobbers tmp.
1060 void MacroAssembler::bang_stack_size(Register size, Register tmp) {
1061   movptr(tmp, rsp);
1062   // Bang stack for total size given plus shadow page size.
1063   // Bang one page at a time because large size can bang beyond yellow and
1064   // red zones.
1065   Label loop;
1066   bind(loop);
1067   movl(Address(tmp, (-os::vm_page_size())), size );
1068   subptr(tmp, os::vm_page_size());
1069   subl(size, os::vm_page_size());
1070   jcc(Assembler::greater, loop);
1071 
1072   // Bang down shadow pages too.
1073   // At this point, (tmp-0) is the last address touched, so don't
1074   // touch it again.  (It was touched as (tmp-pagesize) but then tmp
1075   // was post-decremented.)  Skip this address by starting at i=1, and
1076   // touch a few more pages below.  N.B.  It is important to touch all
1077   // the way down including all pages in the shadow zone.
1078   for (int i = 1; i < ((int)JavaThread::stack_shadow_zone_size() / os::vm_page_size()); i++) {
1079     // this could be any sized move but this is can be a debugging crumb
1080     // so the bigger the better.
1081     movptr(Address(tmp, (-i*os::vm_page_size())), size );
1082   }
1083 }
1084 
1085 void MacroAssembler::reserved_stack_check() {
1086     // testing if reserved zone needs to be enabled
1087     Label no_reserved_zone_enabling;
1088     Register thread = NOT_LP64(rsi) LP64_ONLY(r15_thread);
1089     NOT_LP64(get_thread(rsi);)
1090 
1091     cmpptr(rsp, Address(thread, JavaThread::reserved_stack_activation_offset()));
1092     jcc(Assembler::below, no_reserved_zone_enabling);
1093 
1094     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::enable_stack_reserved_zone), thread);
1095     jump(RuntimeAddress(StubRoutines::throw_delayed_StackOverflowError_entry()));
1096     should_not_reach_here();
1097 
1098     bind(no_reserved_zone_enabling);
1099 }
1100 
1101 int MacroAssembler::biased_locking_enter(Register lock_reg,
1102                                          Register obj_reg,
1103                                          Register swap_reg,
1104                                          Register tmp_reg,
1105                                          bool swap_reg_contains_mark,
1106                                          Label& done,
1107                                          Label* slow_case,
1108                                          BiasedLockingCounters* counters) {
1109   assert(UseBiasedLocking, "why call this otherwise?");
1110   assert(swap_reg == rax, "swap_reg must be rax for cmpxchgq");
1111   assert(tmp_reg != noreg, "tmp_reg must be supplied");
1112   assert_different_registers(lock_reg, obj_reg, swap_reg, tmp_reg);
1113   assert(markOopDesc::age_shift == markOopDesc::lock_bits + markOopDesc::biased_lock_bits, "biased locking makes assumptions about bit layout");
1114   Address mark_addr      (obj_reg, oopDesc::mark_offset_in_bytes());
1115   NOT_LP64( Address saved_mark_addr(lock_reg, 0); )
1116 
1117   if (PrintBiasedLockingStatistics && counters == NULL) {
1118     counters = BiasedLocking::counters();
1119   }
1120   // Biased locking
1121   // See whether the lock is currently biased toward our thread and
1122   // whether the epoch is still valid
1123   // Note that the runtime guarantees sufficient alignment of JavaThread
1124   // pointers to allow age to be placed into low bits
1125   // First check to see whether biasing is even enabled for this object
1126   Label cas_label;
1127   int null_check_offset = -1;
1128   if (!swap_reg_contains_mark) {
1129     null_check_offset = offset();
1130     movptr(swap_reg, mark_addr);
1131   }
1132   movptr(tmp_reg, swap_reg);
1133   andptr(tmp_reg, markOopDesc::biased_lock_mask_in_place);
1134   cmpptr(tmp_reg, markOopDesc::biased_lock_pattern);
1135   jcc(Assembler::notEqual, cas_label);
1136   // The bias pattern is present in the object's header. Need to check
1137   // whether the bias owner and the epoch are both still current.
1138 #ifndef _LP64
1139   // Note that because there is no current thread register on x86_32 we
1140   // need to store off the mark word we read out of the object to
1141   // avoid reloading it and needing to recheck invariants below. This
1142   // store is unfortunate but it makes the overall code shorter and
1143   // simpler.
1144   movptr(saved_mark_addr, swap_reg);
1145 #endif
1146   if (swap_reg_contains_mark) {
1147     null_check_offset = offset();
1148   }
1149   load_prototype_header(tmp_reg, obj_reg);
1150 #ifdef _LP64
1151   orptr(tmp_reg, r15_thread);
1152   xorptr(tmp_reg, swap_reg);
1153   Register header_reg = tmp_reg;
1154 #else
1155   xorptr(tmp_reg, swap_reg);
1156   get_thread(swap_reg);
1157   xorptr(swap_reg, tmp_reg);
1158   Register header_reg = swap_reg;
1159 #endif
1160   andptr(header_reg, ~((int) markOopDesc::age_mask_in_place));
1161   if (counters != NULL) {
1162     cond_inc32(Assembler::zero,
1163                ExternalAddress((address) counters->biased_lock_entry_count_addr()));
1164   }
1165   jcc(Assembler::equal, done);
1166 
1167   Label try_revoke_bias;
1168   Label try_rebias;
1169 
1170   // At this point we know that the header has the bias pattern and
1171   // that we are not the bias owner in the current epoch. We need to
1172   // figure out more details about the state of the header in order to
1173   // know what operations can be legally performed on the object's
1174   // header.
1175 
1176   // If the low three bits in the xor result aren't clear, that means
1177   // the prototype header is no longer biased and we have to revoke
1178   // the bias on this object.
1179   testptr(header_reg, markOopDesc::biased_lock_mask_in_place);
1180   jccb(Assembler::notZero, try_revoke_bias);
1181 
1182   // Biasing is still enabled for this data type. See whether the
1183   // epoch of the current bias is still valid, meaning that the epoch
1184   // bits of the mark word are equal to the epoch bits of the
1185   // prototype header. (Note that the prototype header's epoch bits
1186   // only change at a safepoint.) If not, attempt to rebias the object
1187   // toward the current thread. Note that we must be absolutely sure
1188   // that the current epoch is invalid in order to do this because
1189   // otherwise the manipulations it performs on the mark word are
1190   // illegal.
1191   testptr(header_reg, markOopDesc::epoch_mask_in_place);
1192   jccb(Assembler::notZero, try_rebias);
1193 
1194   // The epoch of the current bias is still valid but we know nothing
1195   // about the owner; it might be set or it might be clear. Try to
1196   // acquire the bias of the object using an atomic operation. If this
1197   // fails we will go in to the runtime to revoke the object's bias.
1198   // Note that we first construct the presumed unbiased header so we
1199   // don't accidentally blow away another thread's valid bias.
1200   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1201   andptr(swap_reg,
1202          markOopDesc::biased_lock_mask_in_place | markOopDesc::age_mask_in_place | markOopDesc::epoch_mask_in_place);
1203 #ifdef _LP64
1204   movptr(tmp_reg, swap_reg);
1205   orptr(tmp_reg, r15_thread);
1206 #else
1207   get_thread(tmp_reg);
1208   orptr(tmp_reg, swap_reg);
1209 #endif
1210   if (os::is_MP()) {
1211     lock();
1212   }
1213   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1214   // If the biasing toward our thread failed, this means that
1215   // another thread succeeded in biasing it toward itself and we
1216   // need to revoke that bias. The revocation will occur in the
1217   // interpreter runtime in the slow case.
1218   if (counters != NULL) {
1219     cond_inc32(Assembler::zero,
1220                ExternalAddress((address) counters->anonymously_biased_lock_entry_count_addr()));
1221   }
1222   if (slow_case != NULL) {
1223     jcc(Assembler::notZero, *slow_case);
1224   }
1225   jmp(done);
1226 
1227   bind(try_rebias);
1228   // At this point we know the epoch has expired, meaning that the
1229   // current "bias owner", if any, is actually invalid. Under these
1230   // circumstances _only_, we are allowed to use the current header's
1231   // value as the comparison value when doing the cas to acquire the
1232   // bias in the current epoch. In other words, we allow transfer of
1233   // the bias from one thread to another directly in this situation.
1234   //
1235   // FIXME: due to a lack of registers we currently blow away the age
1236   // bits in this situation. Should attempt to preserve them.
1237   load_prototype_header(tmp_reg, obj_reg);
1238 #ifdef _LP64
1239   orptr(tmp_reg, r15_thread);
1240 #else
1241   get_thread(swap_reg);
1242   orptr(tmp_reg, swap_reg);
1243   movptr(swap_reg, saved_mark_addr);
1244 #endif
1245   if (os::is_MP()) {
1246     lock();
1247   }
1248   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1249   // If the biasing toward our thread failed, then another thread
1250   // succeeded in biasing it toward itself and we need to revoke that
1251   // bias. The revocation will occur in the runtime in the slow case.
1252   if (counters != NULL) {
1253     cond_inc32(Assembler::zero,
1254                ExternalAddress((address) counters->rebiased_lock_entry_count_addr()));
1255   }
1256   if (slow_case != NULL) {
1257     jcc(Assembler::notZero, *slow_case);
1258   }
1259   jmp(done);
1260 
1261   bind(try_revoke_bias);
1262   // The prototype mark in the klass doesn't have the bias bit set any
1263   // more, indicating that objects of this data type are not supposed
1264   // to be biased any more. We are going to try to reset the mark of
1265   // this object to the prototype value and fall through to the
1266   // CAS-based locking scheme. Note that if our CAS fails, it means
1267   // that another thread raced us for the privilege of revoking the
1268   // bias of this particular object, so it's okay to continue in the
1269   // normal locking code.
1270   //
1271   // FIXME: due to a lack of registers we currently blow away the age
1272   // bits in this situation. Should attempt to preserve them.
1273   NOT_LP64( movptr(swap_reg, saved_mark_addr); )
1274   load_prototype_header(tmp_reg, obj_reg);
1275   if (os::is_MP()) {
1276     lock();
1277   }
1278   cmpxchgptr(tmp_reg, mark_addr); // compare tmp_reg and swap_reg
1279   // Fall through to the normal CAS-based lock, because no matter what
1280   // the result of the above CAS, some thread must have succeeded in
1281   // removing the bias bit from the object's header.
1282   if (counters != NULL) {
1283     cond_inc32(Assembler::zero,
1284                ExternalAddress((address) counters->revoked_lock_entry_count_addr()));
1285   }
1286 
1287   bind(cas_label);
1288 
1289   return null_check_offset;
1290 }
1291 
1292 void MacroAssembler::biased_locking_exit(Register obj_reg, Register temp_reg, Label& done) {
1293   assert(UseBiasedLocking, "why call this otherwise?");
1294 
1295   // Check for biased locking unlock case, which is a no-op
1296   // Note: we do not have to check the thread ID for two reasons.
1297   // First, the interpreter checks for IllegalMonitorStateException at
1298   // a higher level. Second, if the bias was revoked while we held the
1299   // lock, the object could not be rebiased toward another thread, so
1300   // the bias bit would be clear.
1301   movptr(temp_reg, Address(obj_reg, oopDesc::mark_offset_in_bytes()));
1302   andptr(temp_reg, markOopDesc::biased_lock_mask_in_place);
1303   cmpptr(temp_reg, markOopDesc::biased_lock_pattern);
1304   jcc(Assembler::equal, done);
1305 }
1306 
1307 #ifdef COMPILER2
1308 
1309 #if INCLUDE_RTM_OPT
1310 
1311 // Update rtm_counters based on abort status
1312 // input: abort_status
1313 //        rtm_counters (RTMLockingCounters*)
1314 // flags are killed
1315 void MacroAssembler::rtm_counters_update(Register abort_status, Register rtm_counters) {
1316 
1317   atomic_incptr(Address(rtm_counters, RTMLockingCounters::abort_count_offset()));
1318   if (PrintPreciseRTMLockingStatistics) {
1319     for (int i = 0; i < RTMLockingCounters::ABORT_STATUS_LIMIT; i++) {
1320       Label check_abort;
1321       testl(abort_status, (1<<i));
1322       jccb(Assembler::equal, check_abort);
1323       atomic_incptr(Address(rtm_counters, RTMLockingCounters::abortX_count_offset() + (i * sizeof(uintx))));
1324       bind(check_abort);
1325     }
1326   }
1327 }
1328 
1329 // Branch if (random & (count-1) != 0), count is 2^n
1330 // tmp, scr and flags are killed
1331 void MacroAssembler::branch_on_random_using_rdtsc(Register tmp, Register scr, int count, Label& brLabel) {
1332   assert(tmp == rax, "");
1333   assert(scr == rdx, "");
1334   rdtsc(); // modifies EDX:EAX
1335   andptr(tmp, count-1);
1336   jccb(Assembler::notZero, brLabel);
1337 }
1338 
1339 // Perform abort ratio calculation, set no_rtm bit if high ratio
1340 // input:  rtm_counters_Reg (RTMLockingCounters* address)
1341 // tmpReg, rtm_counters_Reg and flags are killed
1342 void MacroAssembler::rtm_abort_ratio_calculation(Register tmpReg,
1343                                                  Register rtm_counters_Reg,
1344                                                  RTMLockingCounters* rtm_counters,
1345                                                  Metadata* method_data) {
1346   Label L_done, L_check_always_rtm1, L_check_always_rtm2;
1347 
1348   if (RTMLockingCalculationDelay > 0) {
1349     // Delay calculation
1350     movptr(tmpReg, ExternalAddress((address) RTMLockingCounters::rtm_calculation_flag_addr()), tmpReg);
1351     testptr(tmpReg, tmpReg);
1352     jccb(Assembler::equal, L_done);
1353   }
1354   // Abort ratio calculation only if abort_count > RTMAbortThreshold
1355   //   Aborted transactions = abort_count * 100
1356   //   All transactions = total_count *  RTMTotalCountIncrRate
1357   //   Set no_rtm bit if (Aborted transactions >= All transactions * RTMAbortRatio)
1358 
1359   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::abort_count_offset()));
1360   cmpptr(tmpReg, RTMAbortThreshold);
1361   jccb(Assembler::below, L_check_always_rtm2);
1362   imulptr(tmpReg, tmpReg, 100);
1363 
1364   Register scrReg = rtm_counters_Reg;
1365   movptr(scrReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1366   imulptr(scrReg, scrReg, RTMTotalCountIncrRate);
1367   imulptr(scrReg, scrReg, RTMAbortRatio);
1368   cmpptr(tmpReg, scrReg);
1369   jccb(Assembler::below, L_check_always_rtm1);
1370   if (method_data != NULL) {
1371     // set rtm_state to "no rtm" in MDO
1372     mov_metadata(tmpReg, method_data);
1373     if (os::is_MP()) {
1374       lock();
1375     }
1376     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), NoRTM);
1377   }
1378   jmpb(L_done);
1379   bind(L_check_always_rtm1);
1380   // Reload RTMLockingCounters* address
1381   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1382   bind(L_check_always_rtm2);
1383   movptr(tmpReg, Address(rtm_counters_Reg, RTMLockingCounters::total_count_offset()));
1384   cmpptr(tmpReg, RTMLockingThreshold / RTMTotalCountIncrRate);
1385   jccb(Assembler::below, L_done);
1386   if (method_data != NULL) {
1387     // set rtm_state to "always rtm" in MDO
1388     mov_metadata(tmpReg, method_data);
1389     if (os::is_MP()) {
1390       lock();
1391     }
1392     orl(Address(tmpReg, MethodData::rtm_state_offset_in_bytes()), UseRTM);
1393   }
1394   bind(L_done);
1395 }
1396 
1397 // Update counters and perform abort ratio calculation
1398 // input:  abort_status_Reg
1399 // rtm_counters_Reg, flags are killed
1400 void MacroAssembler::rtm_profiling(Register abort_status_Reg,
1401                                    Register rtm_counters_Reg,
1402                                    RTMLockingCounters* rtm_counters,
1403                                    Metadata* method_data,
1404                                    bool profile_rtm) {
1405 
1406   assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1407   // update rtm counters based on rax value at abort
1408   // reads abort_status_Reg, updates flags
1409   lea(rtm_counters_Reg, ExternalAddress((address)rtm_counters));
1410   rtm_counters_update(abort_status_Reg, rtm_counters_Reg);
1411   if (profile_rtm) {
1412     // Save abort status because abort_status_Reg is used by following code.
1413     if (RTMRetryCount > 0) {
1414       push(abort_status_Reg);
1415     }
1416     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1417     rtm_abort_ratio_calculation(abort_status_Reg, rtm_counters_Reg, rtm_counters, method_data);
1418     // restore abort status
1419     if (RTMRetryCount > 0) {
1420       pop(abort_status_Reg);
1421     }
1422   }
1423 }
1424 
1425 // Retry on abort if abort's status is 0x6: can retry (0x2) | memory conflict (0x4)
1426 // inputs: retry_count_Reg
1427 //       : abort_status_Reg
1428 // output: retry_count_Reg decremented by 1
1429 // flags are killed
1430 void MacroAssembler::rtm_retry_lock_on_abort(Register retry_count_Reg, Register abort_status_Reg, Label& retryLabel) {
1431   Label doneRetry;
1432   assert(abort_status_Reg == rax, "");
1433   // The abort reason bits are in eax (see all states in rtmLocking.hpp)
1434   // 0x6 = conflict on which we can retry (0x2) | memory conflict (0x4)
1435   // if reason is in 0x6 and retry count != 0 then retry
1436   andptr(abort_status_Reg, 0x6);
1437   jccb(Assembler::zero, doneRetry);
1438   testl(retry_count_Reg, retry_count_Reg);
1439   jccb(Assembler::zero, doneRetry);
1440   pause();
1441   decrementl(retry_count_Reg);
1442   jmp(retryLabel);
1443   bind(doneRetry);
1444 }
1445 
1446 // Spin and retry if lock is busy,
1447 // inputs: box_Reg (monitor address)
1448 //       : retry_count_Reg
1449 // output: retry_count_Reg decremented by 1
1450 //       : clear z flag if retry count exceeded
1451 // tmp_Reg, scr_Reg, flags are killed
1452 void MacroAssembler::rtm_retry_lock_on_busy(Register retry_count_Reg, Register box_Reg,
1453                                             Register tmp_Reg, Register scr_Reg, Label& retryLabel) {
1454   Label SpinLoop, SpinExit, doneRetry;
1455   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1456 
1457   testl(retry_count_Reg, retry_count_Reg);
1458   jccb(Assembler::zero, doneRetry);
1459   decrementl(retry_count_Reg);
1460   movptr(scr_Reg, RTMSpinLoopCount);
1461 
1462   bind(SpinLoop);
1463   pause();
1464   decrementl(scr_Reg);
1465   jccb(Assembler::lessEqual, SpinExit);
1466   movptr(tmp_Reg, Address(box_Reg, owner_offset));
1467   testptr(tmp_Reg, tmp_Reg);
1468   jccb(Assembler::notZero, SpinLoop);
1469 
1470   bind(SpinExit);
1471   jmp(retryLabel);
1472   bind(doneRetry);
1473   incrementl(retry_count_Reg); // clear z flag
1474 }
1475 
1476 // Use RTM for normal stack locks
1477 // Input: objReg (object to lock)
1478 void MacroAssembler::rtm_stack_locking(Register objReg, Register tmpReg, Register scrReg,
1479                                        Register retry_on_abort_count_Reg,
1480                                        RTMLockingCounters* stack_rtm_counters,
1481                                        Metadata* method_data, bool profile_rtm,
1482                                        Label& DONE_LABEL, Label& IsInflated) {
1483   assert(UseRTMForStackLocks, "why call this otherwise?");
1484   assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1485   assert(tmpReg == rax, "");
1486   assert(scrReg == rdx, "");
1487   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1488 
1489   if (RTMRetryCount > 0) {
1490     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1491     bind(L_rtm_retry);
1492   }
1493   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1494   testptr(tmpReg, markOopDesc::monitor_value);  // inflated vs stack-locked|neutral|biased
1495   jcc(Assembler::notZero, IsInflated);
1496 
1497   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1498     Label L_noincrement;
1499     if (RTMTotalCountIncrRate > 1) {
1500       // tmpReg, scrReg and flags are killed
1501       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1502     }
1503     assert(stack_rtm_counters != NULL, "should not be NULL when profiling RTM");
1504     atomic_incptr(ExternalAddress((address)stack_rtm_counters->total_count_addr()), scrReg);
1505     bind(L_noincrement);
1506   }
1507   xbegin(L_on_abort);
1508   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));       // fetch markword
1509   andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1510   cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1511   jcc(Assembler::equal, DONE_LABEL);        // all done if unlocked
1512 
1513   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1514   if (UseRTMXendForLockBusy) {
1515     xend();
1516     movptr(abort_status_Reg, 0x2);   // Set the abort status to 2 (so we can retry)
1517     jmp(L_decrement_retry);
1518   }
1519   else {
1520     xabort(0);
1521   }
1522   bind(L_on_abort);
1523   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1524     rtm_profiling(abort_status_Reg, scrReg, stack_rtm_counters, method_data, profile_rtm);
1525   }
1526   bind(L_decrement_retry);
1527   if (RTMRetryCount > 0) {
1528     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1529     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1530   }
1531 }
1532 
1533 // Use RTM for inflating locks
1534 // inputs: objReg (object to lock)
1535 //         boxReg (on-stack box address (displaced header location) - KILLED)
1536 //         tmpReg (ObjectMonitor address + markOopDesc::monitor_value)
1537 void MacroAssembler::rtm_inflated_locking(Register objReg, Register boxReg, Register tmpReg,
1538                                           Register scrReg, Register retry_on_busy_count_Reg,
1539                                           Register retry_on_abort_count_Reg,
1540                                           RTMLockingCounters* rtm_counters,
1541                                           Metadata* method_data, bool profile_rtm,
1542                                           Label& DONE_LABEL) {
1543   assert(UseRTMLocking, "why call this otherwise?");
1544   assert(tmpReg == rax, "");
1545   assert(scrReg == rdx, "");
1546   Label L_rtm_retry, L_decrement_retry, L_on_abort;
1547   int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
1548 
1549   // Without cast to int32_t a movptr will destroy r10 which is typically obj
1550   movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1551   movptr(boxReg, tmpReg); // Save ObjectMonitor address
1552 
1553   if (RTMRetryCount > 0) {
1554     movl(retry_on_busy_count_Reg, RTMRetryCount);  // Retry on lock busy
1555     movl(retry_on_abort_count_Reg, RTMRetryCount); // Retry on abort
1556     bind(L_rtm_retry);
1557   }
1558   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1559     Label L_noincrement;
1560     if (RTMTotalCountIncrRate > 1) {
1561       // tmpReg, scrReg and flags are killed
1562       branch_on_random_using_rdtsc(tmpReg, scrReg, RTMTotalCountIncrRate, L_noincrement);
1563     }
1564     assert(rtm_counters != NULL, "should not be NULL when profiling RTM");
1565     atomic_incptr(ExternalAddress((address)rtm_counters->total_count_addr()), scrReg);
1566     bind(L_noincrement);
1567   }
1568   xbegin(L_on_abort);
1569   movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));
1570   movptr(tmpReg, Address(tmpReg, owner_offset));
1571   testptr(tmpReg, tmpReg);
1572   jcc(Assembler::zero, DONE_LABEL);
1573   if (UseRTMXendForLockBusy) {
1574     xend();
1575     jmp(L_decrement_retry);
1576   }
1577   else {
1578     xabort(0);
1579   }
1580   bind(L_on_abort);
1581   Register abort_status_Reg = tmpReg; // status of abort is stored in RAX
1582   if (PrintPreciseRTMLockingStatistics || profile_rtm) {
1583     rtm_profiling(abort_status_Reg, scrReg, rtm_counters, method_data, profile_rtm);
1584   }
1585   if (RTMRetryCount > 0) {
1586     // retry on lock abort if abort status is 'can retry' (0x2) or 'memory conflict' (0x4)
1587     rtm_retry_lock_on_abort(retry_on_abort_count_Reg, abort_status_Reg, L_rtm_retry);
1588   }
1589 
1590   movptr(tmpReg, Address(boxReg, owner_offset)) ;
1591   testptr(tmpReg, tmpReg) ;
1592   jccb(Assembler::notZero, L_decrement_retry) ;
1593 
1594   // Appears unlocked - try to swing _owner from null to non-null.
1595   // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1596 #ifdef _LP64
1597   Register threadReg = r15_thread;
1598 #else
1599   get_thread(scrReg);
1600   Register threadReg = scrReg;
1601 #endif
1602   if (os::is_MP()) {
1603     lock();
1604   }
1605   cmpxchgptr(threadReg, Address(boxReg, owner_offset)); // Updates tmpReg
1606 
1607   if (RTMRetryCount > 0) {
1608     // success done else retry
1609     jccb(Assembler::equal, DONE_LABEL) ;
1610     bind(L_decrement_retry);
1611     // Spin and retry if lock is busy.
1612     rtm_retry_lock_on_busy(retry_on_busy_count_Reg, boxReg, tmpReg, scrReg, L_rtm_retry);
1613   }
1614   else {
1615     bind(L_decrement_retry);
1616   }
1617 }
1618 
1619 #endif //  INCLUDE_RTM_OPT
1620 
1621 // Fast_Lock and Fast_Unlock used by C2
1622 
1623 // Because the transitions from emitted code to the runtime
1624 // monitorenter/exit helper stubs are so slow it's critical that
1625 // we inline both the stack-locking fast-path and the inflated fast path.
1626 //
1627 // See also: cmpFastLock and cmpFastUnlock.
1628 //
1629 // What follows is a specialized inline transliteration of the code
1630 // in slow_enter() and slow_exit().  If we're concerned about I$ bloat
1631 // another option would be to emit TrySlowEnter and TrySlowExit methods
1632 // at startup-time.  These methods would accept arguments as
1633 // (rax,=Obj, rbx=Self, rcx=box, rdx=Scratch) and return success-failure
1634 // indications in the icc.ZFlag.  Fast_Lock and Fast_Unlock would simply
1635 // marshal the arguments and emit calls to TrySlowEnter and TrySlowExit.
1636 // In practice, however, the # of lock sites is bounded and is usually small.
1637 // Besides the call overhead, TrySlowEnter and TrySlowExit might suffer
1638 // if the processor uses simple bimodal branch predictors keyed by EIP
1639 // Since the helper routines would be called from multiple synchronization
1640 // sites.
1641 //
1642 // An even better approach would be write "MonitorEnter()" and "MonitorExit()"
1643 // in java - using j.u.c and unsafe - and just bind the lock and unlock sites
1644 // to those specialized methods.  That'd give us a mostly platform-independent
1645 // implementation that the JITs could optimize and inline at their pleasure.
1646 // Done correctly, the only time we'd need to cross to native could would be
1647 // to park() or unpark() threads.  We'd also need a few more unsafe operators
1648 // to (a) prevent compiler-JIT reordering of non-volatile accesses, and
1649 // (b) explicit barriers or fence operations.
1650 //
1651 // TODO:
1652 //
1653 // *  Arrange for C2 to pass "Self" into Fast_Lock and Fast_Unlock in one of the registers (scr).
1654 //    This avoids manifesting the Self pointer in the Fast_Lock and Fast_Unlock terminals.
1655 //    Given TLAB allocation, Self is usually manifested in a register, so passing it into
1656 //    the lock operators would typically be faster than reifying Self.
1657 //
1658 // *  Ideally I'd define the primitives as:
1659 //       fast_lock   (nax Obj, nax box, EAX tmp, nax scr) where box, tmp and scr are KILLED.
1660 //       fast_unlock (nax Obj, EAX box, nax tmp) where box and tmp are KILLED
1661 //    Unfortunately ADLC bugs prevent us from expressing the ideal form.
1662 //    Instead, we're stuck with a rather awkward and brittle register assignments below.
1663 //    Furthermore the register assignments are overconstrained, possibly resulting in
1664 //    sub-optimal code near the synchronization site.
1665 //
1666 // *  Eliminate the sp-proximity tests and just use "== Self" tests instead.
1667 //    Alternately, use a better sp-proximity test.
1668 //
1669 // *  Currently ObjectMonitor._Owner can hold either an sp value or a (THREAD *) value.
1670 //    Either one is sufficient to uniquely identify a thread.
1671 //    TODO: eliminate use of sp in _owner and use get_thread(tr) instead.
1672 //
1673 // *  Intrinsify notify() and notifyAll() for the common cases where the
1674 //    object is locked by the calling thread but the waitlist is empty.
1675 //    avoid the expensive JNI call to JVM_Notify() and JVM_NotifyAll().
1676 //
1677 // *  use jccb and jmpb instead of jcc and jmp to improve code density.
1678 //    But beware of excessive branch density on AMD Opterons.
1679 //
1680 // *  Both Fast_Lock and Fast_Unlock set the ICC.ZF to indicate success
1681 //    or failure of the fast-path.  If the fast-path fails then we pass
1682 //    control to the slow-path, typically in C.  In Fast_Lock and
1683 //    Fast_Unlock we often branch to DONE_LABEL, just to find that C2
1684 //    will emit a conditional branch immediately after the node.
1685 //    So we have branches to branches and lots of ICC.ZF games.
1686 //    Instead, it might be better to have C2 pass a "FailureLabel"
1687 //    into Fast_Lock and Fast_Unlock.  In the case of success, control
1688 //    will drop through the node.  ICC.ZF is undefined at exit.
1689 //    In the case of failure, the node will branch directly to the
1690 //    FailureLabel
1691 
1692 
1693 // obj: object to lock
1694 // box: on-stack box address (displaced header location) - KILLED
1695 // rax,: tmp -- KILLED
1696 // scr: tmp -- KILLED
1697 void MacroAssembler::fast_lock(Register objReg, Register boxReg, Register tmpReg,
1698                                Register scrReg, Register cx1Reg, Register cx2Reg,
1699                                BiasedLockingCounters* counters,
1700                                RTMLockingCounters* rtm_counters,
1701                                RTMLockingCounters* stack_rtm_counters,
1702                                Metadata* method_data,
1703                                bool use_rtm, bool profile_rtm) {
1704   // Ensure the register assignments are disjoint
1705   assert(tmpReg == rax, "");
1706 
1707   if (use_rtm) {
1708     assert_different_registers(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg);
1709   } else {
1710     assert(cx1Reg == noreg, "");
1711     assert(cx2Reg == noreg, "");
1712     assert_different_registers(objReg, boxReg, tmpReg, scrReg);
1713   }
1714 
1715   if (counters != NULL) {
1716     atomic_incl(ExternalAddress((address)counters->total_entry_count_addr()), scrReg);
1717   }
1718   if (EmitSync & 1) {
1719       // set box->dhw = markOopDesc::unused_mark()
1720       // Force all sync thru slow-path: slow_enter() and slow_exit()
1721       movptr (Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1722       cmpptr (rsp, (int32_t)NULL_WORD);
1723   } else {
1724     // Possible cases that we'll encounter in fast_lock
1725     // ------------------------------------------------
1726     // * Inflated
1727     //    -- unlocked
1728     //    -- Locked
1729     //       = by self
1730     //       = by other
1731     // * biased
1732     //    -- by Self
1733     //    -- by other
1734     // * neutral
1735     // * stack-locked
1736     //    -- by self
1737     //       = sp-proximity test hits
1738     //       = sp-proximity test generates false-negative
1739     //    -- by other
1740     //
1741 
1742     Label IsInflated, DONE_LABEL;
1743 
1744     // it's stack-locked, biased or neutral
1745     // TODO: optimize away redundant LDs of obj->mark and improve the markword triage
1746     // order to reduce the number of conditional branches in the most common cases.
1747     // Beware -- there's a subtle invariant that fetch of the markword
1748     // at [FETCH], below, will never observe a biased encoding (*101b).
1749     // If this invariant is not held we risk exclusion (safety) failure.
1750     if (UseBiasedLocking && !UseOptoBiasInlining) {
1751       biased_locking_enter(boxReg, objReg, tmpReg, scrReg, false, DONE_LABEL, NULL, counters);
1752     }
1753 
1754 #if INCLUDE_RTM_OPT
1755     if (UseRTMForStackLocks && use_rtm) {
1756       rtm_stack_locking(objReg, tmpReg, scrReg, cx2Reg,
1757                         stack_rtm_counters, method_data, profile_rtm,
1758                         DONE_LABEL, IsInflated);
1759     }
1760 #endif // INCLUDE_RTM_OPT
1761 
1762     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));          // [FETCH]
1763     testptr(tmpReg, markOopDesc::monitor_value); // inflated vs stack-locked|neutral|biased
1764     jccb(Assembler::notZero, IsInflated);
1765 
1766     // Attempt stack-locking ...
1767     orptr (tmpReg, markOopDesc::unlocked_value);
1768     movptr(Address(boxReg, 0), tmpReg);          // Anticipate successful CAS
1769     if (os::is_MP()) {
1770       lock();
1771     }
1772     cmpxchgptr(boxReg, Address(objReg, oopDesc::mark_offset_in_bytes()));      // Updates tmpReg
1773     if (counters != NULL) {
1774       cond_inc32(Assembler::equal,
1775                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1776     }
1777     jcc(Assembler::equal, DONE_LABEL);           // Success
1778 
1779     // Recursive locking.
1780     // The object is stack-locked: markword contains stack pointer to BasicLock.
1781     // Locked by current thread if difference with current SP is less than one page.
1782     subptr(tmpReg, rsp);
1783     // Next instruction set ZFlag == 1 (Success) if difference is less then one page.
1784     andptr(tmpReg, (int32_t) (NOT_LP64(0xFFFFF003) LP64_ONLY(7 - os::vm_page_size())) );
1785     movptr(Address(boxReg, 0), tmpReg);
1786     if (counters != NULL) {
1787       cond_inc32(Assembler::equal,
1788                  ExternalAddress((address)counters->fast_path_entry_count_addr()));
1789     }
1790     jmp(DONE_LABEL);
1791 
1792     bind(IsInflated);
1793     // The object is inflated. tmpReg contains pointer to ObjectMonitor* + markOopDesc::monitor_value
1794 
1795 #if INCLUDE_RTM_OPT
1796     // Use the same RTM locking code in 32- and 64-bit VM.
1797     if (use_rtm) {
1798       rtm_inflated_locking(objReg, boxReg, tmpReg, scrReg, cx1Reg, cx2Reg,
1799                            rtm_counters, method_data, profile_rtm, DONE_LABEL);
1800     } else {
1801 #endif // INCLUDE_RTM_OPT
1802 
1803 #ifndef _LP64
1804     // The object is inflated.
1805 
1806     // boxReg refers to the on-stack BasicLock in the current frame.
1807     // We'd like to write:
1808     //   set box->_displaced_header = markOopDesc::unused_mark().  Any non-0 value suffices.
1809     // This is convenient but results a ST-before-CAS penalty.  The following CAS suffers
1810     // additional latency as we have another ST in the store buffer that must drain.
1811 
1812     if (EmitSync & 8192) {
1813        movptr(Address(boxReg, 0), 3);            // results in ST-before-CAS penalty
1814        get_thread (scrReg);
1815        movptr(boxReg, tmpReg);                    // consider: LEA box, [tmp-2]
1816        movptr(tmpReg, NULL_WORD);                 // consider: xor vs mov
1817        if (os::is_MP()) {
1818          lock();
1819        }
1820        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1821     } else
1822     if ((EmitSync & 128) == 0) {                      // avoid ST-before-CAS
1823        // register juggle because we need tmpReg for cmpxchgptr below
1824        movptr(scrReg, boxReg);
1825        movptr(boxReg, tmpReg);                   // consider: LEA box, [tmp-2]
1826 
1827        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1828        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1829           // prefetchw [eax + Offset(_owner)-2]
1830           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1831        }
1832 
1833        if ((EmitSync & 64) == 0) {
1834          // Optimistic form: consider XORL tmpReg,tmpReg
1835          movptr(tmpReg, NULL_WORD);
1836        } else {
1837          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1838          // Test-And-CAS instead of CAS
1839          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1840          testptr(tmpReg, tmpReg);                   // Locked ?
1841          jccb  (Assembler::notZero, DONE_LABEL);
1842        }
1843 
1844        // Appears unlocked - try to swing _owner from null to non-null.
1845        // Ideally, I'd manifest "Self" with get_thread and then attempt
1846        // to CAS the register containing Self into m->Owner.
1847        // But we don't have enough registers, so instead we can either try to CAS
1848        // rsp or the address of the box (in scr) into &m->owner.  If the CAS succeeds
1849        // we later store "Self" into m->Owner.  Transiently storing a stack address
1850        // (rsp or the address of the box) into  m->owner is harmless.
1851        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1852        if (os::is_MP()) {
1853          lock();
1854        }
1855        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1856        movptr(Address(scrReg, 0), 3);          // box->_displaced_header = 3
1857        // If we weren't able to swing _owner from NULL to the BasicLock
1858        // then take the slow path.
1859        jccb  (Assembler::notZero, DONE_LABEL);
1860        // update _owner from BasicLock to thread
1861        get_thread (scrReg);                    // beware: clobbers ICCs
1862        movptr(Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), scrReg);
1863        xorptr(boxReg, boxReg);                 // set icc.ZFlag = 1 to indicate success
1864 
1865        // If the CAS fails we can either retry or pass control to the slow-path.
1866        // We use the latter tactic.
1867        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1868        // If the CAS was successful ...
1869        //   Self has acquired the lock
1870        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1871        // Intentional fall-through into DONE_LABEL ...
1872     } else {
1873        movptr(Address(boxReg, 0), intptr_t(markOopDesc::unused_mark()));  // results in ST-before-CAS penalty
1874        movptr(boxReg, tmpReg);
1875 
1876        // Using a prefetchw helps avoid later RTS->RTO upgrades and cache probes
1877        if ((EmitSync & 2048) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
1878           // prefetchw [eax + Offset(_owner)-2]
1879           prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1880        }
1881 
1882        if ((EmitSync & 64) == 0) {
1883          // Optimistic form
1884          xorptr  (tmpReg, tmpReg);
1885        } else {
1886          // Can suffer RTS->RTO upgrades on shared or cold $ lines
1887          movptr(tmpReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));   // rax, = m->_owner
1888          testptr(tmpReg, tmpReg);                   // Locked ?
1889          jccb  (Assembler::notZero, DONE_LABEL);
1890        }
1891 
1892        // Appears unlocked - try to swing _owner from null to non-null.
1893        // Use either "Self" (in scr) or rsp as thread identity in _owner.
1894        // Invariant: tmpReg == 0.  tmpReg is EAX which is the implicit cmpxchg comparand.
1895        get_thread (scrReg);
1896        if (os::is_MP()) {
1897          lock();
1898        }
1899        cmpxchgptr(scrReg, Address(boxReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1900 
1901        // If the CAS fails we can either retry or pass control to the slow-path.
1902        // We use the latter tactic.
1903        // Pass the CAS result in the icc.ZFlag into DONE_LABEL
1904        // If the CAS was successful ...
1905        //   Self has acquired the lock
1906        //   Invariant: m->_recursions should already be 0, so we don't need to explicitly set it.
1907        // Intentional fall-through into DONE_LABEL ...
1908     }
1909 #else // _LP64
1910     // It's inflated
1911     movq(scrReg, tmpReg);
1912     xorq(tmpReg, tmpReg);
1913 
1914     if (os::is_MP()) {
1915       lock();
1916     }
1917     cmpxchgptr(r15_thread, Address(scrReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
1918     // Unconditionally set box->_displaced_header = markOopDesc::unused_mark().
1919     // Without cast to int32_t movptr will destroy r10 which is typically obj.
1920     movptr(Address(boxReg, 0), (int32_t)intptr_t(markOopDesc::unused_mark()));
1921     // Intentional fall-through into DONE_LABEL ...
1922     // Propagate ICC.ZF from CAS above into DONE_LABEL.
1923 #endif // _LP64
1924 #if INCLUDE_RTM_OPT
1925     } // use_rtm()
1926 #endif
1927     // DONE_LABEL is a hot target - we'd really like to place it at the
1928     // start of cache line by padding with NOPs.
1929     // See the AMD and Intel software optimization manuals for the
1930     // most efficient "long" NOP encodings.
1931     // Unfortunately none of our alignment mechanisms suffice.
1932     bind(DONE_LABEL);
1933 
1934     // At DONE_LABEL the icc ZFlag is set as follows ...
1935     // Fast_Unlock uses the same protocol.
1936     // ZFlag == 1 -> Success
1937     // ZFlag == 0 -> Failure - force control through the slow-path
1938   }
1939 }
1940 
1941 // obj: object to unlock
1942 // box: box address (displaced header location), killed.  Must be EAX.
1943 // tmp: killed, cannot be obj nor box.
1944 //
1945 // Some commentary on balanced locking:
1946 //
1947 // Fast_Lock and Fast_Unlock are emitted only for provably balanced lock sites.
1948 // Methods that don't have provably balanced locking are forced to run in the
1949 // interpreter - such methods won't be compiled to use fast_lock and fast_unlock.
1950 // The interpreter provides two properties:
1951 // I1:  At return-time the interpreter automatically and quietly unlocks any
1952 //      objects acquired the current activation (frame).  Recall that the
1953 //      interpreter maintains an on-stack list of locks currently held by
1954 //      a frame.
1955 // I2:  If a method attempts to unlock an object that is not held by the
1956 //      the frame the interpreter throws IMSX.
1957 //
1958 // Lets say A(), which has provably balanced locking, acquires O and then calls B().
1959 // B() doesn't have provably balanced locking so it runs in the interpreter.
1960 // Control returns to A() and A() unlocks O.  By I1 and I2, above, we know that O
1961 // is still locked by A().
1962 //
1963 // The only other source of unbalanced locking would be JNI.  The "Java Native Interface:
1964 // Programmer's Guide and Specification" claims that an object locked by jni_monitorenter
1965 // should not be unlocked by "normal" java-level locking and vice-versa.  The specification
1966 // doesn't specify what will occur if a program engages in such mixed-mode locking, however.
1967 // Arguably given that the spec legislates the JNI case as undefined our implementation
1968 // could reasonably *avoid* checking owner in Fast_Unlock().
1969 // In the interest of performance we elide m->Owner==Self check in unlock.
1970 // A perfectly viable alternative is to elide the owner check except when
1971 // Xcheck:jni is enabled.
1972 
1973 void MacroAssembler::fast_unlock(Register objReg, Register boxReg, Register tmpReg, bool use_rtm) {
1974   assert(boxReg == rax, "");
1975   assert_different_registers(objReg, boxReg, tmpReg);
1976 
1977   if (EmitSync & 4) {
1978     // Disable - inhibit all inlining.  Force control through the slow-path
1979     cmpptr (rsp, 0);
1980   } else {
1981     Label DONE_LABEL, Stacked, CheckSucc;
1982 
1983     // Critically, the biased locking test must have precedence over
1984     // and appear before the (box->dhw == 0) recursive stack-lock test.
1985     if (UseBiasedLocking && !UseOptoBiasInlining) {
1986        biased_locking_exit(objReg, tmpReg, DONE_LABEL);
1987     }
1988 
1989 #if INCLUDE_RTM_OPT
1990     if (UseRTMForStackLocks && use_rtm) {
1991       assert(!UseBiasedLocking, "Biased locking is not supported with RTM locking");
1992       Label L_regular_unlock;
1993       movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));           // fetch markword
1994       andptr(tmpReg, markOopDesc::biased_lock_mask_in_place); // look at 3 lock bits
1995       cmpptr(tmpReg, markOopDesc::unlocked_value);            // bits = 001 unlocked
1996       jccb(Assembler::notEqual, L_regular_unlock);  // if !HLE RegularLock
1997       xend();                                       // otherwise end...
1998       jmp(DONE_LABEL);                              // ... and we're done
1999       bind(L_regular_unlock);
2000     }
2001 #endif
2002 
2003     cmpptr(Address(boxReg, 0), (int32_t)NULL_WORD); // Examine the displaced header
2004     jcc   (Assembler::zero, DONE_LABEL);            // 0 indicates recursive stack-lock
2005     movptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes()));             // Examine the object's markword
2006     testptr(tmpReg, markOopDesc::monitor_value);    // Inflated?
2007     jccb  (Assembler::zero, Stacked);
2008 
2009     // It's inflated.
2010 #if INCLUDE_RTM_OPT
2011     if (use_rtm) {
2012       Label L_regular_inflated_unlock;
2013       int owner_offset = OM_OFFSET_NO_MONITOR_VALUE_TAG(owner);
2014       movptr(boxReg, Address(tmpReg, owner_offset));
2015       testptr(boxReg, boxReg);
2016       jccb(Assembler::notZero, L_regular_inflated_unlock);
2017       xend();
2018       jmpb(DONE_LABEL);
2019       bind(L_regular_inflated_unlock);
2020     }
2021 #endif
2022 
2023     // Despite our balanced locking property we still check that m->_owner == Self
2024     // as java routines or native JNI code called by this thread might
2025     // have released the lock.
2026     // Refer to the comments in synchronizer.cpp for how we might encode extra
2027     // state in _succ so we can avoid fetching EntryList|cxq.
2028     //
2029     // I'd like to add more cases in fast_lock() and fast_unlock() --
2030     // such as recursive enter and exit -- but we have to be wary of
2031     // I$ bloat, T$ effects and BP$ effects.
2032     //
2033     // If there's no contention try a 1-0 exit.  That is, exit without
2034     // a costly MEMBAR or CAS.  See synchronizer.cpp for details on how
2035     // we detect and recover from the race that the 1-0 exit admits.
2036     //
2037     // Conceptually Fast_Unlock() must execute a STST|LDST "release" barrier
2038     // before it STs null into _owner, releasing the lock.  Updates
2039     // to data protected by the critical section must be visible before
2040     // we drop the lock (and thus before any other thread could acquire
2041     // the lock and observe the fields protected by the lock).
2042     // IA32's memory-model is SPO, so STs are ordered with respect to
2043     // each other and there's no need for an explicit barrier (fence).
2044     // See also http://gee.cs.oswego.edu/dl/jmm/cookbook.html.
2045 #ifndef _LP64
2046     get_thread (boxReg);
2047     if ((EmitSync & 4096) && VM_Version::supports_3dnow_prefetch() && os::is_MP()) {
2048       // prefetchw [ebx + Offset(_owner)-2]
2049       prefetchw(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2050     }
2051 
2052     // Note that we could employ various encoding schemes to reduce
2053     // the number of loads below (currently 4) to just 2 or 3.
2054     // Refer to the comments in synchronizer.cpp.
2055     // In practice the chain of fetches doesn't seem to impact performance, however.
2056     xorptr(boxReg, boxReg);
2057     if ((EmitSync & 65536) == 0 && (EmitSync & 256)) {
2058        // Attempt to reduce branch density - AMD's branch predictor.
2059        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2060        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2061        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2062        jccb  (Assembler::notZero, DONE_LABEL);
2063        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2064        jmpb  (DONE_LABEL);
2065     } else {
2066        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2067        jccb  (Assembler::notZero, DONE_LABEL);
2068        movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2069        orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2070        jccb  (Assembler::notZero, CheckSucc);
2071        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2072        jmpb  (DONE_LABEL);
2073     }
2074 
2075     // The Following code fragment (EmitSync & 65536) improves the performance of
2076     // contended applications and contended synchronization microbenchmarks.
2077     // Unfortunately the emission of the code - even though not executed - causes regressions
2078     // in scimark and jetstream, evidently because of $ effects.  Replacing the code
2079     // with an equal number of never-executed NOPs results in the same regression.
2080     // We leave it off by default.
2081 
2082     if ((EmitSync & 65536) != 0) {
2083        Label LSuccess, LGoSlowPath ;
2084 
2085        bind  (CheckSucc);
2086 
2087        // Optional pre-test ... it's safe to elide this
2088        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2089        jccb(Assembler::zero, LGoSlowPath);
2090 
2091        // We have a classic Dekker-style idiom:
2092        //    ST m->_owner = 0 ; MEMBAR; LD m->_succ
2093        // There are a number of ways to implement the barrier:
2094        // (1) lock:andl &m->_owner, 0
2095        //     is fast, but mask doesn't currently support the "ANDL M,IMM32" form.
2096        //     LOCK: ANDL [ebx+Offset(_Owner)-2], 0
2097        //     Encodes as 81 31 OFF32 IMM32 or 83 63 OFF8 IMM8
2098        // (2) If supported, an explicit MFENCE is appealing.
2099        //     In older IA32 processors MFENCE is slower than lock:add or xchg
2100        //     particularly if the write-buffer is full as might be the case if
2101        //     if stores closely precede the fence or fence-equivalent instruction.
2102        //     See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2103        //     as the situation has changed with Nehalem and Shanghai.
2104        // (3) In lieu of an explicit fence, use lock:addl to the top-of-stack
2105        //     The $lines underlying the top-of-stack should be in M-state.
2106        //     The locked add instruction is serializing, of course.
2107        // (4) Use xchg, which is serializing
2108        //     mov boxReg, 0; xchgl boxReg, [tmpReg + Offset(_owner)-2] also works
2109        // (5) ST m->_owner = 0 and then execute lock:orl &m->_succ, 0.
2110        //     The integer condition codes will tell us if succ was 0.
2111        //     Since _succ and _owner should reside in the same $line and
2112        //     we just stored into _owner, it's likely that the $line
2113        //     remains in M-state for the lock:orl.
2114        //
2115        // We currently use (3), although it's likely that switching to (2)
2116        // is correct for the future.
2117 
2118        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), NULL_WORD);
2119        if (os::is_MP()) {
2120          lock(); addptr(Address(rsp, 0), 0);
2121        }
2122        // Ratify _succ remains non-null
2123        cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), 0);
2124        jccb  (Assembler::notZero, LSuccess);
2125 
2126        xorptr(boxReg, boxReg);                  // box is really EAX
2127        if (os::is_MP()) { lock(); }
2128        cmpxchgptr(rsp, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2129        // There's no successor so we tried to regrab the lock with the
2130        // placeholder value. If that didn't work, then another thread
2131        // grabbed the lock so we're done (and exit was a success).
2132        jccb  (Assembler::notEqual, LSuccess);
2133        // Since we're low on registers we installed rsp as a placeholding in _owner.
2134        // Now install Self over rsp.  This is safe as we're transitioning from
2135        // non-null to non=null
2136        get_thread (boxReg);
2137        movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), boxReg);
2138        // Intentional fall-through into LGoSlowPath ...
2139 
2140        bind  (LGoSlowPath);
2141        orptr(boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2142        jmpb  (DONE_LABEL);
2143 
2144        bind  (LSuccess);
2145        xorptr(boxReg, boxReg);                 // set ICC.ZF=1 to indicate success
2146        jmpb  (DONE_LABEL);
2147     }
2148 
2149     bind (Stacked);
2150     // It's not inflated and it's not recursively stack-locked and it's not biased.
2151     // It must be stack-locked.
2152     // Try to reset the header to displaced header.
2153     // The "box" value on the stack is stable, so we can reload
2154     // and be assured we observe the same value as above.
2155     movptr(tmpReg, Address(boxReg, 0));
2156     if (os::is_MP()) {
2157       lock();
2158     }
2159     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2160     // Intention fall-thru into DONE_LABEL
2161 
2162     // DONE_LABEL is a hot target - we'd really like to place it at the
2163     // start of cache line by padding with NOPs.
2164     // See the AMD and Intel software optimization manuals for the
2165     // most efficient "long" NOP encodings.
2166     // Unfortunately none of our alignment mechanisms suffice.
2167     if ((EmitSync & 65536) == 0) {
2168        bind (CheckSucc);
2169     }
2170 #else // _LP64
2171     // It's inflated
2172     if (EmitSync & 1024) {
2173       // Emit code to check that _owner == Self
2174       // We could fold the _owner test into subsequent code more efficiently
2175       // than using a stand-alone check, but since _owner checking is off by
2176       // default we don't bother. We also might consider predicating the
2177       // _owner==Self check on Xcheck:jni or running on a debug build.
2178       movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2179       xorptr(boxReg, r15_thread);
2180     } else {
2181       xorptr(boxReg, boxReg);
2182     }
2183     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(recursions)));
2184     jccb  (Assembler::notZero, DONE_LABEL);
2185     movptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(cxq)));
2186     orptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(EntryList)));
2187     jccb  (Assembler::notZero, CheckSucc);
2188     movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2189     jmpb  (DONE_LABEL);
2190 
2191     if ((EmitSync & 65536) == 0) {
2192       // Try to avoid passing control into the slow_path ...
2193       Label LSuccess, LGoSlowPath ;
2194       bind  (CheckSucc);
2195 
2196       // The following optional optimization can be elided if necessary
2197       // Effectively: if (succ == null) goto SlowPath
2198       // The code reduces the window for a race, however,
2199       // and thus benefits performance.
2200       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2201       jccb  (Assembler::zero, LGoSlowPath);
2202 
2203       xorptr(boxReg, boxReg);
2204       if ((EmitSync & 16) && os::is_MP()) {
2205         xchgptr(boxReg, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2206       } else {
2207         movptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)), (int32_t)NULL_WORD);
2208         if (os::is_MP()) {
2209           // Memory barrier/fence
2210           // Dekker pivot point -- fulcrum : ST Owner; MEMBAR; LD Succ
2211           // Instead of MFENCE we use a dummy locked add of 0 to the top-of-stack.
2212           // This is faster on Nehalem and AMD Shanghai/Barcelona.
2213           // See https://blogs.oracle.com/dave/entry/instruction_selection_for_volatile_fences
2214           // We might also restructure (ST Owner=0;barrier;LD _Succ) to
2215           // (mov box,0; xchgq box, &m->Owner; LD _succ) .
2216           lock(); addl(Address(rsp, 0), 0);
2217         }
2218       }
2219       cmpptr(Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(succ)), (int32_t)NULL_WORD);
2220       jccb  (Assembler::notZero, LSuccess);
2221 
2222       // Rare inopportune interleaving - race.
2223       // The successor vanished in the small window above.
2224       // The lock is contended -- (cxq|EntryList) != null -- and there's no apparent successor.
2225       // We need to ensure progress and succession.
2226       // Try to reacquire the lock.
2227       // If that fails then the new owner is responsible for succession and this
2228       // thread needs to take no further action and can exit via the fast path (success).
2229       // If the re-acquire succeeds then pass control into the slow path.
2230       // As implemented, this latter mode is horrible because we generated more
2231       // coherence traffic on the lock *and* artifically extended the critical section
2232       // length while by virtue of passing control into the slow path.
2233 
2234       // box is really RAX -- the following CMPXCHG depends on that binding
2235       // cmpxchg R,[M] is equivalent to rax = CAS(M,rax,R)
2236       if (os::is_MP()) { lock(); }
2237       cmpxchgptr(r15_thread, Address(tmpReg, OM_OFFSET_NO_MONITOR_VALUE_TAG(owner)));
2238       // There's no successor so we tried to regrab the lock.
2239       // If that didn't work, then another thread grabbed the
2240       // lock so we're done (and exit was a success).
2241       jccb  (Assembler::notEqual, LSuccess);
2242       // Intentional fall-through into slow-path
2243 
2244       bind  (LGoSlowPath);
2245       orl   (boxReg, 1);                      // set ICC.ZF=0 to indicate failure
2246       jmpb  (DONE_LABEL);
2247 
2248       bind  (LSuccess);
2249       testl (boxReg, 0);                      // set ICC.ZF=1 to indicate success
2250       jmpb  (DONE_LABEL);
2251     }
2252 
2253     bind  (Stacked);
2254     movptr(tmpReg, Address (boxReg, 0));      // re-fetch
2255     if (os::is_MP()) { lock(); }
2256     cmpxchgptr(tmpReg, Address(objReg, oopDesc::mark_offset_in_bytes())); // Uses RAX which is box
2257 
2258     if (EmitSync & 65536) {
2259        bind (CheckSucc);
2260     }
2261 #endif
2262     bind(DONE_LABEL);
2263   }
2264 }
2265 #endif // COMPILER2
2266 
2267 void MacroAssembler::c2bool(Register x) {
2268   // implements x == 0 ? 0 : 1
2269   // note: must only look at least-significant byte of x
2270   //       since C-style booleans are stored in one byte
2271   //       only! (was bug)
2272   andl(x, 0xFF);
2273   setb(Assembler::notZero, x);
2274 }
2275 
2276 // Wouldn't need if AddressLiteral version had new name
2277 void MacroAssembler::call(Label& L, relocInfo::relocType rtype) {
2278   Assembler::call(L, rtype);
2279 }
2280 
2281 void MacroAssembler::call(Register entry) {
2282   Assembler::call(entry);
2283 }
2284 
2285 void MacroAssembler::call(AddressLiteral entry) {
2286   if (reachable(entry)) {
2287     Assembler::call_literal(entry.target(), entry.rspec());
2288   } else {
2289     lea(rscratch1, entry);
2290     Assembler::call(rscratch1);
2291   }
2292 }
2293 
2294 void MacroAssembler::ic_call(address entry, jint method_index) {
2295   RelocationHolder rh = virtual_call_Relocation::spec(pc(), method_index);
2296   movptr(rax, (intptr_t)Universe::non_oop_word());
2297   call(AddressLiteral(entry, rh));
2298 }
2299 
2300 // Implementation of call_VM versions
2301 
2302 void MacroAssembler::call_VM(Register oop_result,
2303                              address entry_point,
2304                              bool check_exceptions) {
2305   Label C, E;
2306   call(C, relocInfo::none);
2307   jmp(E);
2308 
2309   bind(C);
2310   call_VM_helper(oop_result, entry_point, 0, check_exceptions);
2311   ret(0);
2312 
2313   bind(E);
2314 }
2315 
2316 void MacroAssembler::call_VM(Register oop_result,
2317                              address entry_point,
2318                              Register arg_1,
2319                              bool check_exceptions) {
2320   Label C, E;
2321   call(C, relocInfo::none);
2322   jmp(E);
2323 
2324   bind(C);
2325   pass_arg1(this, arg_1);
2326   call_VM_helper(oop_result, entry_point, 1, check_exceptions);
2327   ret(0);
2328 
2329   bind(E);
2330 }
2331 
2332 void MacroAssembler::call_VM(Register oop_result,
2333                              address entry_point,
2334                              Register arg_1,
2335                              Register arg_2,
2336                              bool check_exceptions) {
2337   Label C, E;
2338   call(C, relocInfo::none);
2339   jmp(E);
2340 
2341   bind(C);
2342 
2343   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2344 
2345   pass_arg2(this, arg_2);
2346   pass_arg1(this, arg_1);
2347   call_VM_helper(oop_result, entry_point, 2, check_exceptions);
2348   ret(0);
2349 
2350   bind(E);
2351 }
2352 
2353 void MacroAssembler::call_VM(Register oop_result,
2354                              address entry_point,
2355                              Register arg_1,
2356                              Register arg_2,
2357                              Register arg_3,
2358                              bool check_exceptions) {
2359   Label C, E;
2360   call(C, relocInfo::none);
2361   jmp(E);
2362 
2363   bind(C);
2364 
2365   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2366   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2367   pass_arg3(this, arg_3);
2368 
2369   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2370   pass_arg2(this, arg_2);
2371 
2372   pass_arg1(this, arg_1);
2373   call_VM_helper(oop_result, entry_point, 3, check_exceptions);
2374   ret(0);
2375 
2376   bind(E);
2377 }
2378 
2379 void MacroAssembler::call_VM(Register oop_result,
2380                              Register last_java_sp,
2381                              address entry_point,
2382                              int number_of_arguments,
2383                              bool check_exceptions) {
2384   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2385   call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2386 }
2387 
2388 void MacroAssembler::call_VM(Register oop_result,
2389                              Register last_java_sp,
2390                              address entry_point,
2391                              Register arg_1,
2392                              bool check_exceptions) {
2393   pass_arg1(this, arg_1);
2394   call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2395 }
2396 
2397 void MacroAssembler::call_VM(Register oop_result,
2398                              Register last_java_sp,
2399                              address entry_point,
2400                              Register arg_1,
2401                              Register arg_2,
2402                              bool check_exceptions) {
2403 
2404   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2405   pass_arg2(this, arg_2);
2406   pass_arg1(this, arg_1);
2407   call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2408 }
2409 
2410 void MacroAssembler::call_VM(Register oop_result,
2411                              Register last_java_sp,
2412                              address entry_point,
2413                              Register arg_1,
2414                              Register arg_2,
2415                              Register arg_3,
2416                              bool check_exceptions) {
2417   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2418   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2419   pass_arg3(this, arg_3);
2420   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2421   pass_arg2(this, arg_2);
2422   pass_arg1(this, arg_1);
2423   call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2424 }
2425 
2426 void MacroAssembler::super_call_VM(Register oop_result,
2427                                    Register last_java_sp,
2428                                    address entry_point,
2429                                    int number_of_arguments,
2430                                    bool check_exceptions) {
2431   Register thread = LP64_ONLY(r15_thread) NOT_LP64(noreg);
2432   MacroAssembler::call_VM_base(oop_result, thread, last_java_sp, entry_point, number_of_arguments, check_exceptions);
2433 }
2434 
2435 void MacroAssembler::super_call_VM(Register oop_result,
2436                                    Register last_java_sp,
2437                                    address entry_point,
2438                                    Register arg_1,
2439                                    bool check_exceptions) {
2440   pass_arg1(this, arg_1);
2441   super_call_VM(oop_result, last_java_sp, entry_point, 1, check_exceptions);
2442 }
2443 
2444 void MacroAssembler::super_call_VM(Register oop_result,
2445                                    Register last_java_sp,
2446                                    address entry_point,
2447                                    Register arg_1,
2448                                    Register arg_2,
2449                                    bool check_exceptions) {
2450 
2451   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2452   pass_arg2(this, arg_2);
2453   pass_arg1(this, arg_1);
2454   super_call_VM(oop_result, last_java_sp, entry_point, 2, check_exceptions);
2455 }
2456 
2457 void MacroAssembler::super_call_VM(Register oop_result,
2458                                    Register last_java_sp,
2459                                    address entry_point,
2460                                    Register arg_1,
2461                                    Register arg_2,
2462                                    Register arg_3,
2463                                    bool check_exceptions) {
2464   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2465   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2466   pass_arg3(this, arg_3);
2467   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2468   pass_arg2(this, arg_2);
2469   pass_arg1(this, arg_1);
2470   super_call_VM(oop_result, last_java_sp, entry_point, 3, check_exceptions);
2471 }
2472 
2473 void MacroAssembler::call_VM_base(Register oop_result,
2474                                   Register java_thread,
2475                                   Register last_java_sp,
2476                                   address  entry_point,
2477                                   int      number_of_arguments,
2478                                   bool     check_exceptions) {
2479   // determine java_thread register
2480   if (!java_thread->is_valid()) {
2481 #ifdef _LP64
2482     java_thread = r15_thread;
2483 #else
2484     java_thread = rdi;
2485     get_thread(java_thread);
2486 #endif // LP64
2487   }
2488   // determine last_java_sp register
2489   if (!last_java_sp->is_valid()) {
2490     last_java_sp = rsp;
2491   }
2492   // debugging support
2493   assert(number_of_arguments >= 0   , "cannot have negative number of arguments");
2494   LP64_ONLY(assert(java_thread == r15_thread, "unexpected register"));
2495 #ifdef ASSERT
2496   // TraceBytecodes does not use r12 but saves it over the call, so don't verify
2497   // r12 is the heapbase.
2498   LP64_ONLY(if ((UseCompressedOops || UseCompressedClassPointers) && !TraceBytecodes) verify_heapbase("call_VM_base: heap base corrupted?");)
2499 #endif // ASSERT
2500 
2501   assert(java_thread != oop_result  , "cannot use the same register for java_thread & oop_result");
2502   assert(java_thread != last_java_sp, "cannot use the same register for java_thread & last_java_sp");
2503 
2504   // push java thread (becomes first argument of C function)
2505 
2506   NOT_LP64(push(java_thread); number_of_arguments++);
2507   LP64_ONLY(mov(c_rarg0, r15_thread));
2508 
2509   // set last Java frame before call
2510   assert(last_java_sp != rbp, "can't use ebp/rbp");
2511 
2512   // Only interpreter should have to set fp
2513   set_last_Java_frame(java_thread, last_java_sp, rbp, NULL);
2514 
2515   // do the call, remove parameters
2516   MacroAssembler::call_VM_leaf_base(entry_point, number_of_arguments);
2517 
2518   // restore the thread (cannot use the pushed argument since arguments
2519   // may be overwritten by C code generated by an optimizing compiler);
2520   // however can use the register value directly if it is callee saved.
2521   if (LP64_ONLY(true ||) java_thread == rdi || java_thread == rsi) {
2522     // rdi & rsi (also r15) are callee saved -> nothing to do
2523 #ifdef ASSERT
2524     guarantee(java_thread != rax, "change this code");
2525     push(rax);
2526     { Label L;
2527       get_thread(rax);
2528       cmpptr(java_thread, rax);
2529       jcc(Assembler::equal, L);
2530       STOP("MacroAssembler::call_VM_base: rdi not callee saved?");
2531       bind(L);
2532     }
2533     pop(rax);
2534 #endif
2535   } else {
2536     get_thread(java_thread);
2537   }
2538   // reset last Java frame
2539   // Only interpreter should have to clear fp
2540   reset_last_Java_frame(java_thread, true);
2541 
2542    // C++ interp handles this in the interpreter
2543   check_and_handle_popframe(java_thread);
2544   check_and_handle_earlyret(java_thread);
2545 
2546   if (check_exceptions) {
2547     // check for pending exceptions (java_thread is set upon return)
2548     cmpptr(Address(java_thread, Thread::pending_exception_offset()), (int32_t) NULL_WORD);
2549 #ifndef _LP64
2550     jump_cc(Assembler::notEqual,
2551             RuntimeAddress(StubRoutines::forward_exception_entry()));
2552 #else
2553     // This used to conditionally jump to forward_exception however it is
2554     // possible if we relocate that the branch will not reach. So we must jump
2555     // around so we can always reach
2556 
2557     Label ok;
2558     jcc(Assembler::equal, ok);
2559     jump(RuntimeAddress(StubRoutines::forward_exception_entry()));
2560     bind(ok);
2561 #endif // LP64
2562   }
2563 
2564   // get oop result if there is one and reset the value in the thread
2565   if (oop_result->is_valid()) {
2566     get_vm_result(oop_result, java_thread);
2567   }
2568 }
2569 
2570 void MacroAssembler::call_VM_helper(Register oop_result, address entry_point, int number_of_arguments, bool check_exceptions) {
2571 
2572   // Calculate the value for last_Java_sp
2573   // somewhat subtle. call_VM does an intermediate call
2574   // which places a return address on the stack just under the
2575   // stack pointer as the user finsihed with it. This allows
2576   // use to retrieve last_Java_pc from last_Java_sp[-1].
2577   // On 32bit we then have to push additional args on the stack to accomplish
2578   // the actual requested call. On 64bit call_VM only can use register args
2579   // so the only extra space is the return address that call_VM created.
2580   // This hopefully explains the calculations here.
2581 
2582 #ifdef _LP64
2583   // We've pushed one address, correct last_Java_sp
2584   lea(rax, Address(rsp, wordSize));
2585 #else
2586   lea(rax, Address(rsp, (1 + number_of_arguments) * wordSize));
2587 #endif // LP64
2588 
2589   call_VM_base(oop_result, noreg, rax, entry_point, number_of_arguments, check_exceptions);
2590 
2591 }
2592 
2593 // Use this method when MacroAssembler version of call_VM_leaf_base() should be called from Interpreter.
2594 void MacroAssembler::call_VM_leaf0(address entry_point) {
2595   MacroAssembler::call_VM_leaf_base(entry_point, 0);
2596 }
2597 
2598 void MacroAssembler::call_VM_leaf(address entry_point, int number_of_arguments) {
2599   call_VM_leaf_base(entry_point, number_of_arguments);
2600 }
2601 
2602 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0) {
2603   pass_arg0(this, arg_0);
2604   call_VM_leaf(entry_point, 1);
2605 }
2606 
2607 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2608 
2609   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2610   pass_arg1(this, arg_1);
2611   pass_arg0(this, arg_0);
2612   call_VM_leaf(entry_point, 2);
2613 }
2614 
2615 void MacroAssembler::call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2616   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2617   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2618   pass_arg2(this, arg_2);
2619   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2620   pass_arg1(this, arg_1);
2621   pass_arg0(this, arg_0);
2622   call_VM_leaf(entry_point, 3);
2623 }
2624 
2625 void MacroAssembler::super_call_VM_leaf(address entry_point) {
2626   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2627 }
2628 
2629 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0) {
2630   pass_arg0(this, arg_0);
2631   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2632 }
2633 
2634 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2635 
2636   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2637   pass_arg1(this, arg_1);
2638   pass_arg0(this, arg_0);
2639   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2640 }
2641 
2642 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2643   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2644   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2645   pass_arg2(this, arg_2);
2646   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2647   pass_arg1(this, arg_1);
2648   pass_arg0(this, arg_0);
2649   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2650 }
2651 
2652 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2653   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2654   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2655   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2656   pass_arg3(this, arg_3);
2657   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2658   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2659   pass_arg2(this, arg_2);
2660   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2661   pass_arg1(this, arg_1);
2662   pass_arg0(this, arg_0);
2663   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2664 }
2665 
2666 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2667   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2668   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2669   verify_oop(oop_result, "broken oop in call_VM_base");
2670 }
2671 
2672 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2673   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2674   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2675 }
2676 
2677 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2678 }
2679 
2680 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2681 }
2682 
2683 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2684   if (reachable(src1)) {
2685     cmpl(as_Address(src1), imm);
2686   } else {
2687     lea(rscratch1, src1);
2688     cmpl(Address(rscratch1, 0), imm);
2689   }
2690 }
2691 
2692 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2693   assert(!src2.is_lval(), "use cmpptr");
2694   if (reachable(src2)) {
2695     cmpl(src1, as_Address(src2));
2696   } else {
2697     lea(rscratch1, src2);
2698     cmpl(src1, Address(rscratch1, 0));
2699   }
2700 }
2701 
2702 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2703   Assembler::cmpl(src1, imm);
2704 }
2705 
2706 void MacroAssembler::cmp32(Register src1, Address src2) {
2707   Assembler::cmpl(src1, src2);
2708 }
2709 
2710 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2711   ucomisd(opr1, opr2);
2712 
2713   Label L;
2714   if (unordered_is_less) {
2715     movl(dst, -1);
2716     jcc(Assembler::parity, L);
2717     jcc(Assembler::below , L);
2718     movl(dst, 0);
2719     jcc(Assembler::equal , L);
2720     increment(dst);
2721   } else { // unordered is greater
2722     movl(dst, 1);
2723     jcc(Assembler::parity, L);
2724     jcc(Assembler::above , L);
2725     movl(dst, 0);
2726     jcc(Assembler::equal , L);
2727     decrementl(dst);
2728   }
2729   bind(L);
2730 }
2731 
2732 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2733   ucomiss(opr1, opr2);
2734 
2735   Label L;
2736   if (unordered_is_less) {
2737     movl(dst, -1);
2738     jcc(Assembler::parity, L);
2739     jcc(Assembler::below , L);
2740     movl(dst, 0);
2741     jcc(Assembler::equal , L);
2742     increment(dst);
2743   } else { // unordered is greater
2744     movl(dst, 1);
2745     jcc(Assembler::parity, L);
2746     jcc(Assembler::above , L);
2747     movl(dst, 0);
2748     jcc(Assembler::equal , L);
2749     decrementl(dst);
2750   }
2751   bind(L);
2752 }
2753 
2754 
2755 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2756   if (reachable(src1)) {
2757     cmpb(as_Address(src1), imm);
2758   } else {
2759     lea(rscratch1, src1);
2760     cmpb(Address(rscratch1, 0), imm);
2761   }
2762 }
2763 
2764 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2765 #ifdef _LP64
2766   if (src2.is_lval()) {
2767     movptr(rscratch1, src2);
2768     Assembler::cmpq(src1, rscratch1);
2769   } else if (reachable(src2)) {
2770     cmpq(src1, as_Address(src2));
2771   } else {
2772     lea(rscratch1, src2);
2773     Assembler::cmpq(src1, Address(rscratch1, 0));
2774   }
2775 #else
2776   if (src2.is_lval()) {
2777     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2778   } else {
2779     cmpl(src1, as_Address(src2));
2780   }
2781 #endif // _LP64
2782 }
2783 
2784 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2785   assert(src2.is_lval(), "not a mem-mem compare");
2786 #ifdef _LP64
2787   // moves src2's literal address
2788   movptr(rscratch1, src2);
2789   Assembler::cmpq(src1, rscratch1);
2790 #else
2791   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2792 #endif // _LP64
2793 }
2794 
2795 void MacroAssembler::cmpoop(Register src1, Register src2) {
2796   cmpptr(src1, src2);
2797 }
2798 
2799 void MacroAssembler::cmpoop(Register src1, Address src2) {
2800   cmpptr(src1, src2);
2801 }
2802 
2803 #ifdef _LP64
2804 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2805   movoop(rscratch1, src2);
2806   cmpptr(src1, rscratch1);
2807 }
2808 #endif
2809 
2810 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2811   if (reachable(adr)) {
2812     if (os::is_MP())
2813       lock();
2814     cmpxchgptr(reg, as_Address(adr));
2815   } else {
2816     lea(rscratch1, adr);
2817     if (os::is_MP())
2818       lock();
2819     cmpxchgptr(reg, Address(rscratch1, 0));
2820   }
2821 }
2822 
2823 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2824   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2825 }
2826 
2827 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2828   if (reachable(src)) {
2829     Assembler::comisd(dst, as_Address(src));
2830   } else {
2831     lea(rscratch1, src);
2832     Assembler::comisd(dst, Address(rscratch1, 0));
2833   }
2834 }
2835 
2836 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2837   if (reachable(src)) {
2838     Assembler::comiss(dst, as_Address(src));
2839   } else {
2840     lea(rscratch1, src);
2841     Assembler::comiss(dst, Address(rscratch1, 0));
2842   }
2843 }
2844 
2845 
2846 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2847   Condition negated_cond = negate_condition(cond);
2848   Label L;
2849   jcc(negated_cond, L);
2850   pushf(); // Preserve flags
2851   atomic_incl(counter_addr);
2852   popf();
2853   bind(L);
2854 }
2855 
2856 int MacroAssembler::corrected_idivl(Register reg) {
2857   // Full implementation of Java idiv and irem; checks for
2858   // special case as described in JVM spec., p.243 & p.271.
2859   // The function returns the (pc) offset of the idivl
2860   // instruction - may be needed for implicit exceptions.
2861   //
2862   //         normal case                           special case
2863   //
2864   // input : rax,: dividend                         min_int
2865   //         reg: divisor   (may not be rax,/rdx)   -1
2866   //
2867   // output: rax,: quotient  (= rax, idiv reg)       min_int
2868   //         rdx: remainder (= rax, irem reg)       0
2869   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2870   const int min_int = 0x80000000;
2871   Label normal_case, special_case;
2872 
2873   // check for special case
2874   cmpl(rax, min_int);
2875   jcc(Assembler::notEqual, normal_case);
2876   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2877   cmpl(reg, -1);
2878   jcc(Assembler::equal, special_case);
2879 
2880   // handle normal case
2881   bind(normal_case);
2882   cdql();
2883   int idivl_offset = offset();
2884   idivl(reg);
2885 
2886   // normal and special case exit
2887   bind(special_case);
2888 
2889   return idivl_offset;
2890 }
2891 
2892 
2893 
2894 void MacroAssembler::decrementl(Register reg, int value) {
2895   if (value == min_jint) {subl(reg, value) ; return; }
2896   if (value <  0) { incrementl(reg, -value); return; }
2897   if (value == 0) {                        ; return; }
2898   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2899   /* else */      { subl(reg, value)       ; return; }
2900 }
2901 
2902 void MacroAssembler::decrementl(Address dst, int value) {
2903   if (value == min_jint) {subl(dst, value) ; return; }
2904   if (value <  0) { incrementl(dst, -value); return; }
2905   if (value == 0) {                        ; return; }
2906   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2907   /* else */      { subl(dst, value)       ; return; }
2908 }
2909 
2910 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2911   assert (shift_value > 0, "illegal shift value");
2912   Label _is_positive;
2913   testl (reg, reg);
2914   jcc (Assembler::positive, _is_positive);
2915   int offset = (1 << shift_value) - 1 ;
2916 
2917   if (offset == 1) {
2918     incrementl(reg);
2919   } else {
2920     addl(reg, offset);
2921   }
2922 
2923   bind (_is_positive);
2924   sarl(reg, shift_value);
2925 }
2926 
2927 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2928   if (reachable(src)) {
2929     Assembler::divsd(dst, as_Address(src));
2930   } else {
2931     lea(rscratch1, src);
2932     Assembler::divsd(dst, Address(rscratch1, 0));
2933   }
2934 }
2935 
2936 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2937   if (reachable(src)) {
2938     Assembler::divss(dst, as_Address(src));
2939   } else {
2940     lea(rscratch1, src);
2941     Assembler::divss(dst, Address(rscratch1, 0));
2942   }
2943 }
2944 
2945 // !defined(COMPILER2) is because of stupid core builds
2946 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2947 void MacroAssembler::empty_FPU_stack() {
2948   if (VM_Version::supports_mmx()) {
2949     emms();
2950   } else {
2951     for (int i = 8; i-- > 0; ) ffree(i);
2952   }
2953 }
2954 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2955 
2956 
2957 // Defines obj, preserves var_size_in_bytes
2958 void MacroAssembler::eden_allocate(Register obj,
2959                                    Register var_size_in_bytes,
2960                                    int con_size_in_bytes,
2961                                    Register t1,
2962                                    Label& slow_case) {
2963   assert(obj == rax, "obj must be in rax, for cmpxchg");
2964   assert_different_registers(obj, var_size_in_bytes, t1);
2965   if (!Universe::heap()->supports_inline_contig_alloc()) {
2966     jmp(slow_case);
2967   } else {
2968     Register end = t1;
2969     Label retry;
2970     bind(retry);
2971     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2972     movptr(obj, heap_top);
2973     if (var_size_in_bytes == noreg) {
2974       lea(end, Address(obj, con_size_in_bytes));
2975     } else {
2976       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2977     }
2978     // if end < obj then we wrapped around => object too long => slow case
2979     cmpptr(end, obj);
2980     jcc(Assembler::below, slow_case);
2981     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2982     jcc(Assembler::above, slow_case);
2983     // Compare obj with the top addr, and if still equal, store the new top addr in
2984     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2985     // it otherwise. Use lock prefix for atomicity on MPs.
2986     locked_cmpxchgptr(end, heap_top);
2987     jcc(Assembler::notEqual, retry);
2988   }
2989 }
2990 
2991 void MacroAssembler::enter() {
2992   push(rbp);
2993   mov(rbp, rsp);
2994 }
2995 
2996 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2997 void MacroAssembler::fat_nop() {
2998   if (UseAddressNop) {
2999     addr_nop_5();
3000   } else {
3001     emit_int8(0x26); // es:
3002     emit_int8(0x2e); // cs:
3003     emit_int8(0x64); // fs:
3004     emit_int8(0x65); // gs:
3005     emit_int8((unsigned char)0x90);
3006   }
3007 }
3008 
3009 void MacroAssembler::fcmp(Register tmp) {
3010   fcmp(tmp, 1, true, true);
3011 }
3012 
3013 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3014   assert(!pop_right || pop_left, "usage error");
3015   if (VM_Version::supports_cmov()) {
3016     assert(tmp == noreg, "unneeded temp");
3017     if (pop_left) {
3018       fucomip(index);
3019     } else {
3020       fucomi(index);
3021     }
3022     if (pop_right) {
3023       fpop();
3024     }
3025   } else {
3026     assert(tmp != noreg, "need temp");
3027     if (pop_left) {
3028       if (pop_right) {
3029         fcompp();
3030       } else {
3031         fcomp(index);
3032       }
3033     } else {
3034       fcom(index);
3035     }
3036     // convert FPU condition into eflags condition via rax,
3037     save_rax(tmp);
3038     fwait(); fnstsw_ax();
3039     sahf();
3040     restore_rax(tmp);
3041   }
3042   // condition codes set as follows:
3043   //
3044   // CF (corresponds to C0) if x < y
3045   // PF (corresponds to C2) if unordered
3046   // ZF (corresponds to C3) if x = y
3047 }
3048 
3049 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3050   fcmp2int(dst, unordered_is_less, 1, true, true);
3051 }
3052 
3053 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3054   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3055   Label L;
3056   if (unordered_is_less) {
3057     movl(dst, -1);
3058     jcc(Assembler::parity, L);
3059     jcc(Assembler::below , L);
3060     movl(dst, 0);
3061     jcc(Assembler::equal , L);
3062     increment(dst);
3063   } else { // unordered is greater
3064     movl(dst, 1);
3065     jcc(Assembler::parity, L);
3066     jcc(Assembler::above , L);
3067     movl(dst, 0);
3068     jcc(Assembler::equal , L);
3069     decrementl(dst);
3070   }
3071   bind(L);
3072 }
3073 
3074 void MacroAssembler::fld_d(AddressLiteral src) {
3075   fld_d(as_Address(src));
3076 }
3077 
3078 void MacroAssembler::fld_s(AddressLiteral src) {
3079   fld_s(as_Address(src));
3080 }
3081 
3082 void MacroAssembler::fld_x(AddressLiteral src) {
3083   Assembler::fld_x(as_Address(src));
3084 }
3085 
3086 void MacroAssembler::fldcw(AddressLiteral src) {
3087   Assembler::fldcw(as_Address(src));
3088 }
3089 
3090 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3091   if (reachable(src)) {
3092     Assembler::mulpd(dst, as_Address(src));
3093   } else {
3094     lea(rscratch1, src);
3095     Assembler::mulpd(dst, Address(rscratch1, 0));
3096   }
3097 }
3098 
3099 void MacroAssembler::increase_precision() {
3100   subptr(rsp, BytesPerWord);
3101   fnstcw(Address(rsp, 0));
3102   movl(rax, Address(rsp, 0));
3103   orl(rax, 0x300);
3104   push(rax);
3105   fldcw(Address(rsp, 0));
3106   pop(rax);
3107 }
3108 
3109 void MacroAssembler::restore_precision() {
3110   fldcw(Address(rsp, 0));
3111   addptr(rsp, BytesPerWord);
3112 }
3113 
3114 void MacroAssembler::fpop() {
3115   ffree();
3116   fincstp();
3117 }
3118 
3119 void MacroAssembler::load_float(Address src) {
3120   if (UseSSE >= 1) {
3121     movflt(xmm0, src);
3122   } else {
3123     LP64_ONLY(ShouldNotReachHere());
3124     NOT_LP64(fld_s(src));
3125   }
3126 }
3127 
3128 void MacroAssembler::store_float(Address dst) {
3129   if (UseSSE >= 1) {
3130     movflt(dst, xmm0);
3131   } else {
3132     LP64_ONLY(ShouldNotReachHere());
3133     NOT_LP64(fstp_s(dst));
3134   }
3135 }
3136 
3137 void MacroAssembler::load_double(Address src) {
3138   if (UseSSE >= 2) {
3139     movdbl(xmm0, src);
3140   } else {
3141     LP64_ONLY(ShouldNotReachHere());
3142     NOT_LP64(fld_d(src));
3143   }
3144 }
3145 
3146 void MacroAssembler::store_double(Address dst) {
3147   if (UseSSE >= 2) {
3148     movdbl(dst, xmm0);
3149   } else {
3150     LP64_ONLY(ShouldNotReachHere());
3151     NOT_LP64(fstp_d(dst));
3152   }
3153 }
3154 
3155 void MacroAssembler::fremr(Register tmp) {
3156   save_rax(tmp);
3157   { Label L;
3158     bind(L);
3159     fprem();
3160     fwait(); fnstsw_ax();
3161 #ifdef _LP64
3162     testl(rax, 0x400);
3163     jcc(Assembler::notEqual, L);
3164 #else
3165     sahf();
3166     jcc(Assembler::parity, L);
3167 #endif // _LP64
3168   }
3169   restore_rax(tmp);
3170   // Result is in ST0.
3171   // Note: fxch & fpop to get rid of ST1
3172   // (otherwise FPU stack could overflow eventually)
3173   fxch(1);
3174   fpop();
3175 }
3176 
3177 // dst = c = a * b + c
3178 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3179   Assembler::vfmadd231sd(c, a, b);
3180   if (dst != c) {
3181     movdbl(dst, c);
3182   }
3183 }
3184 
3185 // dst = c = a * b + c
3186 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3187   Assembler::vfmadd231ss(c, a, b);
3188   if (dst != c) {
3189     movflt(dst, c);
3190   }
3191 }
3192 
3193 // dst = c = a * b + c
3194 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3195   Assembler::vfmadd231pd(c, a, b, vector_len);
3196   if (dst != c) {
3197     vmovdqu(dst, c);
3198   }
3199 }
3200 
3201 // dst = c = a * b + c
3202 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3203   Assembler::vfmadd231ps(c, a, b, vector_len);
3204   if (dst != c) {
3205     vmovdqu(dst, c);
3206   }
3207 }
3208 
3209 // dst = c = a * b + c
3210 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3211   Assembler::vfmadd231pd(c, a, b, vector_len);
3212   if (dst != c) {
3213     vmovdqu(dst, c);
3214   }
3215 }
3216 
3217 // dst = c = a * b + c
3218 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3219   Assembler::vfmadd231ps(c, a, b, vector_len);
3220   if (dst != c) {
3221     vmovdqu(dst, c);
3222   }
3223 }
3224 
3225 void MacroAssembler::incrementl(AddressLiteral dst) {
3226   if (reachable(dst)) {
3227     incrementl(as_Address(dst));
3228   } else {
3229     lea(rscratch1, dst);
3230     incrementl(Address(rscratch1, 0));
3231   }
3232 }
3233 
3234 void MacroAssembler::incrementl(ArrayAddress dst) {
3235   incrementl(as_Address(dst));
3236 }
3237 
3238 void MacroAssembler::incrementl(Register reg, int value) {
3239   if (value == min_jint) {addl(reg, value) ; return; }
3240   if (value <  0) { decrementl(reg, -value); return; }
3241   if (value == 0) {                        ; return; }
3242   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3243   /* else */      { addl(reg, value)       ; return; }
3244 }
3245 
3246 void MacroAssembler::incrementl(Address dst, int value) {
3247   if (value == min_jint) {addl(dst, value) ; return; }
3248   if (value <  0) { decrementl(dst, -value); return; }
3249   if (value == 0) {                        ; return; }
3250   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3251   /* else */      { addl(dst, value)       ; return; }
3252 }
3253 
3254 void MacroAssembler::jump(AddressLiteral dst) {
3255   if (reachable(dst)) {
3256     jmp_literal(dst.target(), dst.rspec());
3257   } else {
3258     lea(rscratch1, dst);
3259     jmp(rscratch1);
3260   }
3261 }
3262 
3263 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3264   if (reachable(dst)) {
3265     InstructionMark im(this);
3266     relocate(dst.reloc());
3267     const int short_size = 2;
3268     const int long_size = 6;
3269     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3270     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3271       // 0111 tttn #8-bit disp
3272       emit_int8(0x70 | cc);
3273       emit_int8((offs - short_size) & 0xFF);
3274     } else {
3275       // 0000 1111 1000 tttn #32-bit disp
3276       emit_int8(0x0F);
3277       emit_int8((unsigned char)(0x80 | cc));
3278       emit_int32(offs - long_size);
3279     }
3280   } else {
3281 #ifdef ASSERT
3282     warning("reversing conditional branch");
3283 #endif /* ASSERT */
3284     Label skip;
3285     jccb(reverse[cc], skip);
3286     lea(rscratch1, dst);
3287     Assembler::jmp(rscratch1);
3288     bind(skip);
3289   }
3290 }
3291 
3292 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3293   if (reachable(src)) {
3294     Assembler::ldmxcsr(as_Address(src));
3295   } else {
3296     lea(rscratch1, src);
3297     Assembler::ldmxcsr(Address(rscratch1, 0));
3298   }
3299 }
3300 
3301 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3302   int off;
3303   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3304     off = offset();
3305     movsbl(dst, src); // movsxb
3306   } else {
3307     off = load_unsigned_byte(dst, src);
3308     shll(dst, 24);
3309     sarl(dst, 24);
3310   }
3311   return off;
3312 }
3313 
3314 // Note: load_signed_short used to be called load_signed_word.
3315 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3316 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3317 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3318 int MacroAssembler::load_signed_short(Register dst, Address src) {
3319   int off;
3320   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3321     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3322     // version but this is what 64bit has always done. This seems to imply
3323     // that users are only using 32bits worth.
3324     off = offset();
3325     movswl(dst, src); // movsxw
3326   } else {
3327     off = load_unsigned_short(dst, src);
3328     shll(dst, 16);
3329     sarl(dst, 16);
3330   }
3331   return off;
3332 }
3333 
3334 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3335   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3336   // and "3.9 Partial Register Penalties", p. 22).
3337   int off;
3338   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3339     off = offset();
3340     movzbl(dst, src); // movzxb
3341   } else {
3342     xorl(dst, dst);
3343     off = offset();
3344     movb(dst, src);
3345   }
3346   return off;
3347 }
3348 
3349 // Note: load_unsigned_short used to be called load_unsigned_word.
3350 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3351   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3352   // and "3.9 Partial Register Penalties", p. 22).
3353   int off;
3354   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3355     off = offset();
3356     movzwl(dst, src); // movzxw
3357   } else {
3358     xorl(dst, dst);
3359     off = offset();
3360     movw(dst, src);
3361   }
3362   return off;
3363 }
3364 
3365 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3366   switch (size_in_bytes) {
3367 #ifndef _LP64
3368   case  8:
3369     assert(dst2 != noreg, "second dest register required");
3370     movl(dst,  src);
3371     movl(dst2, src.plus_disp(BytesPerInt));
3372     break;
3373 #else
3374   case  8:  movq(dst, src); break;
3375 #endif
3376   case  4:  movl(dst, src); break;
3377   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3378   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3379   default:  ShouldNotReachHere();
3380   }
3381 }
3382 
3383 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3384   switch (size_in_bytes) {
3385 #ifndef _LP64
3386   case  8:
3387     assert(src2 != noreg, "second source register required");
3388     movl(dst,                        src);
3389     movl(dst.plus_disp(BytesPerInt), src2);
3390     break;
3391 #else
3392   case  8:  movq(dst, src); break;
3393 #endif
3394   case  4:  movl(dst, src); break;
3395   case  2:  movw(dst, src); break;
3396   case  1:  movb(dst, src); break;
3397   default:  ShouldNotReachHere();
3398   }
3399 }
3400 
3401 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3402   if (reachable(dst)) {
3403     movl(as_Address(dst), src);
3404   } else {
3405     lea(rscratch1, dst);
3406     movl(Address(rscratch1, 0), src);
3407   }
3408 }
3409 
3410 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3411   if (reachable(src)) {
3412     movl(dst, as_Address(src));
3413   } else {
3414     lea(rscratch1, src);
3415     movl(dst, Address(rscratch1, 0));
3416   }
3417 }
3418 
3419 // C++ bool manipulation
3420 
3421 void MacroAssembler::movbool(Register dst, Address src) {
3422   if(sizeof(bool) == 1)
3423     movb(dst, src);
3424   else if(sizeof(bool) == 2)
3425     movw(dst, src);
3426   else if(sizeof(bool) == 4)
3427     movl(dst, src);
3428   else
3429     // unsupported
3430     ShouldNotReachHere();
3431 }
3432 
3433 void MacroAssembler::movbool(Address dst, bool boolconst) {
3434   if(sizeof(bool) == 1)
3435     movb(dst, (int) boolconst);
3436   else if(sizeof(bool) == 2)
3437     movw(dst, (int) boolconst);
3438   else if(sizeof(bool) == 4)
3439     movl(dst, (int) boolconst);
3440   else
3441     // unsupported
3442     ShouldNotReachHere();
3443 }
3444 
3445 void MacroAssembler::movbool(Address dst, Register src) {
3446   if(sizeof(bool) == 1)
3447     movb(dst, src);
3448   else if(sizeof(bool) == 2)
3449     movw(dst, src);
3450   else if(sizeof(bool) == 4)
3451     movl(dst, src);
3452   else
3453     // unsupported
3454     ShouldNotReachHere();
3455 }
3456 
3457 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3458   movb(as_Address(dst), src);
3459 }
3460 
3461 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3462   if (reachable(src)) {
3463     movdl(dst, as_Address(src));
3464   } else {
3465     lea(rscratch1, src);
3466     movdl(dst, Address(rscratch1, 0));
3467   }
3468 }
3469 
3470 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3471   if (reachable(src)) {
3472     movq(dst, as_Address(src));
3473   } else {
3474     lea(rscratch1, src);
3475     movq(dst, Address(rscratch1, 0));
3476   }
3477 }
3478 
3479 void MacroAssembler::setvectmask(Register dst, Register src) {
3480   Assembler::movl(dst, 1);
3481   Assembler::shlxl(dst, dst, src);
3482   Assembler::decl(dst);
3483   Assembler::kmovdl(k1, dst);
3484   Assembler::movl(dst, src);
3485 }
3486 
3487 void MacroAssembler::restorevectmask() {
3488   Assembler::knotwl(k1, k0);
3489 }
3490 
3491 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3492   if (reachable(src)) {
3493     if (UseXmmLoadAndClearUpper) {
3494       movsd (dst, as_Address(src));
3495     } else {
3496       movlpd(dst, as_Address(src));
3497     }
3498   } else {
3499     lea(rscratch1, src);
3500     if (UseXmmLoadAndClearUpper) {
3501       movsd (dst, Address(rscratch1, 0));
3502     } else {
3503       movlpd(dst, Address(rscratch1, 0));
3504     }
3505   }
3506 }
3507 
3508 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3509   if (reachable(src)) {
3510     movss(dst, as_Address(src));
3511   } else {
3512     lea(rscratch1, src);
3513     movss(dst, Address(rscratch1, 0));
3514   }
3515 }
3516 
3517 void MacroAssembler::movptr(Register dst, Register src) {
3518   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3519 }
3520 
3521 void MacroAssembler::movptr(Register dst, Address src) {
3522   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3523 }
3524 
3525 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3526 void MacroAssembler::movptr(Register dst, intptr_t src) {
3527   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3528 }
3529 
3530 void MacroAssembler::movptr(Address dst, Register src) {
3531   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3532 }
3533 
3534 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3535   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3536     Assembler::vextractf32x4(dst, src, 0);
3537   } else {
3538     Assembler::movdqu(dst, src);
3539   }
3540 }
3541 
3542 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3543   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3544     Assembler::vinsertf32x4(dst, dst, src, 0);
3545   } else {
3546     Assembler::movdqu(dst, src);
3547   }
3548 }
3549 
3550 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3551   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3552     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3553   } else {
3554     Assembler::movdqu(dst, src);
3555   }
3556 }
3557 
3558 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3559   if (reachable(src)) {
3560     movdqu(dst, as_Address(src));
3561   } else {
3562     lea(scratchReg, src);
3563     movdqu(dst, Address(scratchReg, 0));
3564   }
3565 }
3566 
3567 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3568   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3569     vextractf64x4_low(dst, src);
3570   } else {
3571     Assembler::vmovdqu(dst, src);
3572   }
3573 }
3574 
3575 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3576   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3577     vinsertf64x4_low(dst, src);
3578   } else {
3579     Assembler::vmovdqu(dst, src);
3580   }
3581 }
3582 
3583 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3584   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3585     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3586   }
3587   else {
3588     Assembler::vmovdqu(dst, src);
3589   }
3590 }
3591 
3592 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3593   if (reachable(src)) {
3594     vmovdqu(dst, as_Address(src));
3595   }
3596   else {
3597     lea(rscratch1, src);
3598     vmovdqu(dst, Address(rscratch1, 0));
3599   }
3600 }
3601 
3602 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3603   if (reachable(src)) {
3604     Assembler::movdqa(dst, as_Address(src));
3605   } else {
3606     lea(rscratch1, src);
3607     Assembler::movdqa(dst, Address(rscratch1, 0));
3608   }
3609 }
3610 
3611 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3612   if (reachable(src)) {
3613     Assembler::movsd(dst, as_Address(src));
3614   } else {
3615     lea(rscratch1, src);
3616     Assembler::movsd(dst, Address(rscratch1, 0));
3617   }
3618 }
3619 
3620 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3621   if (reachable(src)) {
3622     Assembler::movss(dst, as_Address(src));
3623   } else {
3624     lea(rscratch1, src);
3625     Assembler::movss(dst, Address(rscratch1, 0));
3626   }
3627 }
3628 
3629 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3630   if (reachable(src)) {
3631     Assembler::mulsd(dst, as_Address(src));
3632   } else {
3633     lea(rscratch1, src);
3634     Assembler::mulsd(dst, Address(rscratch1, 0));
3635   }
3636 }
3637 
3638 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3639   if (reachable(src)) {
3640     Assembler::mulss(dst, as_Address(src));
3641   } else {
3642     lea(rscratch1, src);
3643     Assembler::mulss(dst, Address(rscratch1, 0));
3644   }
3645 }
3646 
3647 void MacroAssembler::null_check(Register reg, int offset) {
3648   if (needs_explicit_null_check(offset)) {
3649     // provoke OS NULL exception if reg = NULL by
3650     // accessing M[reg] w/o changing any (non-CC) registers
3651     // NOTE: cmpl is plenty here to provoke a segv
3652     cmpptr(rax, Address(reg, 0));
3653     // Note: should probably use testl(rax, Address(reg, 0));
3654     //       may be shorter code (however, this version of
3655     //       testl needs to be implemented first)
3656   } else {
3657     // nothing to do, (later) access of M[reg + offset]
3658     // will provoke OS NULL exception if reg = NULL
3659   }
3660 }
3661 
3662 void MacroAssembler::test_klass_is_value(Register klass, Register temp_reg, Label& is_value) {
3663   movl(temp_reg, Address(klass, Klass::access_flags_offset()));
3664   testl(temp_reg, JVM_ACC_VALUE);
3665   jcc(Assembler::notZero, is_value);
3666 }
3667 
3668 void MacroAssembler::test_field_is_flattenable(Register flags, Register temp_reg, Label& is_flattenable) {
3669   movl(temp_reg, flags);
3670   shrl(temp_reg, ConstantPoolCacheEntry::is_flattenable_field_shift);
3671   andl(temp_reg, 0x1);
3672   testl(temp_reg, temp_reg);
3673   jcc(Assembler::notZero, is_flattenable);
3674 }
3675 
3676 void MacroAssembler::test_field_is_not_flattenable(Register flags, Register temp_reg, Label& notFlattenable) {
3677   movl(temp_reg, flags);
3678   shrl(temp_reg, ConstantPoolCacheEntry::is_flattenable_field_shift);
3679   andl(temp_reg, 0x1);
3680   testl(temp_reg, temp_reg);
3681   jcc(Assembler::zero, notFlattenable);
3682 }
3683 
3684 void MacroAssembler::test_field_is_flattened(Register flags, Register temp_reg, Label& is_flattened) {
3685   movl(temp_reg, flags);
3686   shrl(temp_reg, ConstantPoolCacheEntry::is_flattened_field_shift);
3687   andl(temp_reg, 0x1);
3688   testl(temp_reg, temp_reg);
3689   jcc(Assembler::notZero, is_flattened);
3690 }
3691 
3692 void MacroAssembler::test_flat_array_klass(Register klass, Register temp_reg,
3693                                            Label& is_flat_array) {
3694   movl(temp_reg, Address(klass, Klass::layout_helper_offset()));
3695   sarl(temp_reg, Klass::_lh_array_tag_shift);
3696   cmpl(temp_reg, Klass::_lh_array_tag_vt_value);
3697   jcc(Assembler::equal, is_flat_array);
3698 }
3699 
3700 
3701 void MacroAssembler::test_flat_array_oop(Register oop, Register temp_reg,
3702                                          Label& is_flat_array) {
3703   load_klass(temp_reg, oop);
3704   test_flat_array_klass(temp_reg, temp_reg, is_flat_array);
3705 }
3706 
3707 void MacroAssembler::test_value_is_not_buffered(Register value, Register temp_reg, Label& not_buffered) {
3708   ExternalAddress VTBuffer_top(VTBuffer::top_addr());
3709   ExternalAddress VTBuffer_end(VTBuffer::end_addr());
3710 
3711   // Test below is ordered based on the relative positions of
3712   // the Java heap and the VTBuffer to execute a single test for heap-allocated values
3713 
3714   if (VTBuffer::base() < Universe::heap()->base()) {
3715     lea(temp_reg, VTBuffer_end);
3716     cmpptr(value, temp_reg);
3717     jcc(Assembler::greaterEqual, not_buffered);
3718     lea(temp_reg, VTBuffer_top);
3719     cmpptr(value, temp_reg);
3720     jcc(Assembler::less, not_buffered);
3721   } else {
3722     lea(temp_reg, VTBuffer_top);
3723     cmpptr(value, temp_reg);
3724     jcc(Assembler::less, not_buffered);
3725     lea(temp_reg, VTBuffer_end);
3726     cmpptr(value, temp_reg);
3727     jcc(Assembler::greaterEqual, not_buffered);
3728   }
3729 }
3730 
3731 void MacroAssembler::os_breakpoint() {
3732   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3733   // (e.g., MSVC can't call ps() otherwise)
3734   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3735 }
3736 
3737 void MacroAssembler::unimplemented(const char* what) {
3738   const char* buf = NULL;
3739   {
3740     ResourceMark rm;
3741     stringStream ss;
3742     ss.print("unimplemented: %s", what);
3743     buf = code_string(ss.as_string());
3744   }
3745   stop(buf);
3746 }
3747 
3748 #ifdef _LP64
3749 #define XSTATE_BV 0x200
3750 #endif
3751 
3752 void MacroAssembler::pop_CPU_state() {
3753   pop_FPU_state();
3754   pop_IU_state();
3755 }
3756 
3757 void MacroAssembler::pop_FPU_state() {
3758 #ifndef _LP64
3759   frstor(Address(rsp, 0));
3760 #else
3761   fxrstor(Address(rsp, 0));
3762 #endif
3763   addptr(rsp, FPUStateSizeInWords * wordSize);
3764 }
3765 
3766 void MacroAssembler::pop_IU_state() {
3767   popa();
3768   LP64_ONLY(addq(rsp, 8));
3769   popf();
3770 }
3771 
3772 // Save Integer and Float state
3773 // Warning: Stack must be 16 byte aligned (64bit)
3774 void MacroAssembler::push_CPU_state() {
3775   push_IU_state();
3776   push_FPU_state();
3777 }
3778 
3779 void MacroAssembler::push_FPU_state() {
3780   subptr(rsp, FPUStateSizeInWords * wordSize);
3781 #ifndef _LP64
3782   fnsave(Address(rsp, 0));
3783   fwait();
3784 #else
3785   fxsave(Address(rsp, 0));
3786 #endif // LP64
3787 }
3788 
3789 void MacroAssembler::push_IU_state() {
3790   // Push flags first because pusha kills them
3791   pushf();
3792   // Make sure rsp stays 16-byte aligned
3793   LP64_ONLY(subq(rsp, 8));
3794   pusha();
3795 }
3796 
3797 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3798   if (!java_thread->is_valid()) {
3799     java_thread = rdi;
3800     get_thread(java_thread);
3801   }
3802   // we must set sp to zero to clear frame
3803   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3804   if (clear_fp) {
3805     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3806   }
3807 
3808   // Always clear the pc because it could have been set by make_walkable()
3809   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3810 
3811   vzeroupper();
3812 }
3813 
3814 void MacroAssembler::restore_rax(Register tmp) {
3815   if (tmp == noreg) pop(rax);
3816   else if (tmp != rax) mov(rax, tmp);
3817 }
3818 
3819 void MacroAssembler::round_to(Register reg, int modulus) {
3820   addptr(reg, modulus - 1);
3821   andptr(reg, -modulus);
3822 }
3823 
3824 void MacroAssembler::save_rax(Register tmp) {
3825   if (tmp == noreg) push(rax);
3826   else if (tmp != rax) mov(tmp, rax);
3827 }
3828 
3829 // Write serialization page so VM thread can do a pseudo remote membar.
3830 // We use the current thread pointer to calculate a thread specific
3831 // offset to write to within the page. This minimizes bus traffic
3832 // due to cache line collision.
3833 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3834   movl(tmp, thread);
3835   shrl(tmp, os::get_serialize_page_shift_count());
3836   andl(tmp, (os::vm_page_size() - sizeof(int)));
3837 
3838   Address index(noreg, tmp, Address::times_1);
3839   ExternalAddress page(os::get_memory_serialize_page());
3840 
3841   // Size of store must match masking code above
3842   movl(as_Address(ArrayAddress(page, index)), tmp);
3843 }
3844 
3845 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3846   if (SafepointMechanism::uses_thread_local_poll()) {
3847 #ifdef _LP64
3848     assert(thread_reg == r15_thread, "should be");
3849 #else
3850     if (thread_reg == noreg) {
3851       thread_reg = temp_reg;
3852       get_thread(thread_reg);
3853     }
3854 #endif
3855     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3856     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3857   } else {
3858     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3859         SafepointSynchronize::_not_synchronized);
3860     jcc(Assembler::notEqual, slow_path);
3861   }
3862 }
3863 
3864 // Calls to C land
3865 //
3866 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3867 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3868 // has to be reset to 0. This is required to allow proper stack traversal.
3869 void MacroAssembler::set_last_Java_frame(Register java_thread,
3870                                          Register last_java_sp,
3871                                          Register last_java_fp,
3872                                          address  last_java_pc) {
3873   vzeroupper();
3874   // determine java_thread register
3875   if (!java_thread->is_valid()) {
3876     java_thread = rdi;
3877     get_thread(java_thread);
3878   }
3879   // determine last_java_sp register
3880   if (!last_java_sp->is_valid()) {
3881     last_java_sp = rsp;
3882   }
3883 
3884   // last_java_fp is optional
3885 
3886   if (last_java_fp->is_valid()) {
3887     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3888   }
3889 
3890   // last_java_pc is optional
3891 
3892   if (last_java_pc != NULL) {
3893     lea(Address(java_thread,
3894                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3895         InternalAddress(last_java_pc));
3896 
3897   }
3898   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3899 }
3900 
3901 void MacroAssembler::shlptr(Register dst, int imm8) {
3902   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3903 }
3904 
3905 void MacroAssembler::shrptr(Register dst, int imm8) {
3906   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3907 }
3908 
3909 void MacroAssembler::sign_extend_byte(Register reg) {
3910   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3911     movsbl(reg, reg); // movsxb
3912   } else {
3913     shll(reg, 24);
3914     sarl(reg, 24);
3915   }
3916 }
3917 
3918 void MacroAssembler::sign_extend_short(Register reg) {
3919   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3920     movswl(reg, reg); // movsxw
3921   } else {
3922     shll(reg, 16);
3923     sarl(reg, 16);
3924   }
3925 }
3926 
3927 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3928   assert(reachable(src), "Address should be reachable");
3929   testl(dst, as_Address(src));
3930 }
3931 
3932 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3933   int dst_enc = dst->encoding();
3934   int src_enc = src->encoding();
3935   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3936     Assembler::pcmpeqb(dst, src);
3937   } else if ((dst_enc < 16) && (src_enc < 16)) {
3938     Assembler::pcmpeqb(dst, src);
3939   } else if (src_enc < 16) {
3940     subptr(rsp, 64);
3941     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3942     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3943     Assembler::pcmpeqb(xmm0, src);
3944     movdqu(dst, xmm0);
3945     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3946     addptr(rsp, 64);
3947   } else if (dst_enc < 16) {
3948     subptr(rsp, 64);
3949     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3950     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3951     Assembler::pcmpeqb(dst, xmm0);
3952     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3953     addptr(rsp, 64);
3954   } else {
3955     subptr(rsp, 64);
3956     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3957     subptr(rsp, 64);
3958     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3959     movdqu(xmm0, src);
3960     movdqu(xmm1, dst);
3961     Assembler::pcmpeqb(xmm1, xmm0);
3962     movdqu(dst, xmm1);
3963     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3964     addptr(rsp, 64);
3965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3966     addptr(rsp, 64);
3967   }
3968 }
3969 
3970 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3971   int dst_enc = dst->encoding();
3972   int src_enc = src->encoding();
3973   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3974     Assembler::pcmpeqw(dst, src);
3975   } else if ((dst_enc < 16) && (src_enc < 16)) {
3976     Assembler::pcmpeqw(dst, src);
3977   } else if (src_enc < 16) {
3978     subptr(rsp, 64);
3979     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3980     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3981     Assembler::pcmpeqw(xmm0, src);
3982     movdqu(dst, xmm0);
3983     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3984     addptr(rsp, 64);
3985   } else if (dst_enc < 16) {
3986     subptr(rsp, 64);
3987     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3988     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3989     Assembler::pcmpeqw(dst, xmm0);
3990     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3991     addptr(rsp, 64);
3992   } else {
3993     subptr(rsp, 64);
3994     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3995     subptr(rsp, 64);
3996     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3997     movdqu(xmm0, src);
3998     movdqu(xmm1, dst);
3999     Assembler::pcmpeqw(xmm1, xmm0);
4000     movdqu(dst, xmm1);
4001     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4002     addptr(rsp, 64);
4003     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4004     addptr(rsp, 64);
4005   }
4006 }
4007 
4008 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
4009   int dst_enc = dst->encoding();
4010   if (dst_enc < 16) {
4011     Assembler::pcmpestri(dst, src, imm8);
4012   } else {
4013     subptr(rsp, 64);
4014     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4015     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4016     Assembler::pcmpestri(xmm0, src, imm8);
4017     movdqu(dst, xmm0);
4018     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4019     addptr(rsp, 64);
4020   }
4021 }
4022 
4023 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
4024   int dst_enc = dst->encoding();
4025   int src_enc = src->encoding();
4026   if ((dst_enc < 16) && (src_enc < 16)) {
4027     Assembler::pcmpestri(dst, src, imm8);
4028   } else if (src_enc < 16) {
4029     subptr(rsp, 64);
4030     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4031     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4032     Assembler::pcmpestri(xmm0, src, imm8);
4033     movdqu(dst, xmm0);
4034     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4035     addptr(rsp, 64);
4036   } else if (dst_enc < 16) {
4037     subptr(rsp, 64);
4038     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4039     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4040     Assembler::pcmpestri(dst, xmm0, imm8);
4041     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4042     addptr(rsp, 64);
4043   } else {
4044     subptr(rsp, 64);
4045     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4046     subptr(rsp, 64);
4047     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4048     movdqu(xmm0, src);
4049     movdqu(xmm1, dst);
4050     Assembler::pcmpestri(xmm1, xmm0, imm8);
4051     movdqu(dst, xmm1);
4052     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4053     addptr(rsp, 64);
4054     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4055     addptr(rsp, 64);
4056   }
4057 }
4058 
4059 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4060   int dst_enc = dst->encoding();
4061   int src_enc = src->encoding();
4062   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4063     Assembler::pmovzxbw(dst, src);
4064   } else if ((dst_enc < 16) && (src_enc < 16)) {
4065     Assembler::pmovzxbw(dst, src);
4066   } else if (src_enc < 16) {
4067     subptr(rsp, 64);
4068     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4069     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4070     Assembler::pmovzxbw(xmm0, src);
4071     movdqu(dst, xmm0);
4072     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4073     addptr(rsp, 64);
4074   } else if (dst_enc < 16) {
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4077     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4078     Assembler::pmovzxbw(dst, xmm0);
4079     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4080     addptr(rsp, 64);
4081   } else {
4082     subptr(rsp, 64);
4083     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4084     subptr(rsp, 64);
4085     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4086     movdqu(xmm0, src);
4087     movdqu(xmm1, dst);
4088     Assembler::pmovzxbw(xmm1, xmm0);
4089     movdqu(dst, xmm1);
4090     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4091     addptr(rsp, 64);
4092     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4093     addptr(rsp, 64);
4094   }
4095 }
4096 
4097 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4098   int dst_enc = dst->encoding();
4099   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4100     Assembler::pmovzxbw(dst, src);
4101   } else if (dst_enc < 16) {
4102     Assembler::pmovzxbw(dst, src);
4103   } else {
4104     subptr(rsp, 64);
4105     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4106     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4107     Assembler::pmovzxbw(xmm0, src);
4108     movdqu(dst, xmm0);
4109     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4110     addptr(rsp, 64);
4111   }
4112 }
4113 
4114 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4115   int src_enc = src->encoding();
4116   if (src_enc < 16) {
4117     Assembler::pmovmskb(dst, src);
4118   } else {
4119     subptr(rsp, 64);
4120     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4121     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4122     Assembler::pmovmskb(dst, xmm0);
4123     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4124     addptr(rsp, 64);
4125   }
4126 }
4127 
4128 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4129   int dst_enc = dst->encoding();
4130   int src_enc = src->encoding();
4131   if ((dst_enc < 16) && (src_enc < 16)) {
4132     Assembler::ptest(dst, src);
4133   } else if (src_enc < 16) {
4134     subptr(rsp, 64);
4135     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4136     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4137     Assembler::ptest(xmm0, src);
4138     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4139     addptr(rsp, 64);
4140   } else if (dst_enc < 16) {
4141     subptr(rsp, 64);
4142     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4143     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4144     Assembler::ptest(dst, xmm0);
4145     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4146     addptr(rsp, 64);
4147   } else {
4148     subptr(rsp, 64);
4149     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4150     subptr(rsp, 64);
4151     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4152     movdqu(xmm0, src);
4153     movdqu(xmm1, dst);
4154     Assembler::ptest(xmm1, xmm0);
4155     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4156     addptr(rsp, 64);
4157     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4158     addptr(rsp, 64);
4159   }
4160 }
4161 
4162 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4163   if (reachable(src)) {
4164     Assembler::sqrtsd(dst, as_Address(src));
4165   } else {
4166     lea(rscratch1, src);
4167     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4168   }
4169 }
4170 
4171 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4172   if (reachable(src)) {
4173     Assembler::sqrtss(dst, as_Address(src));
4174   } else {
4175     lea(rscratch1, src);
4176     Assembler::sqrtss(dst, Address(rscratch1, 0));
4177   }
4178 }
4179 
4180 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4181   if (reachable(src)) {
4182     Assembler::subsd(dst, as_Address(src));
4183   } else {
4184     lea(rscratch1, src);
4185     Assembler::subsd(dst, Address(rscratch1, 0));
4186   }
4187 }
4188 
4189 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4190   if (reachable(src)) {
4191     Assembler::subss(dst, as_Address(src));
4192   } else {
4193     lea(rscratch1, src);
4194     Assembler::subss(dst, Address(rscratch1, 0));
4195   }
4196 }
4197 
4198 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4199   if (reachable(src)) {
4200     Assembler::ucomisd(dst, as_Address(src));
4201   } else {
4202     lea(rscratch1, src);
4203     Assembler::ucomisd(dst, Address(rscratch1, 0));
4204   }
4205 }
4206 
4207 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4208   if (reachable(src)) {
4209     Assembler::ucomiss(dst, as_Address(src));
4210   } else {
4211     lea(rscratch1, src);
4212     Assembler::ucomiss(dst, Address(rscratch1, 0));
4213   }
4214 }
4215 
4216 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4217   // Used in sign-bit flipping with aligned address.
4218   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4219   if (reachable(src)) {
4220     Assembler::xorpd(dst, as_Address(src));
4221   } else {
4222     lea(rscratch1, src);
4223     Assembler::xorpd(dst, Address(rscratch1, 0));
4224   }
4225 }
4226 
4227 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4228   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4229     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4230   }
4231   else {
4232     Assembler::xorpd(dst, src);
4233   }
4234 }
4235 
4236 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4237   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4238     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4239   } else {
4240     Assembler::xorps(dst, src);
4241   }
4242 }
4243 
4244 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4245   // Used in sign-bit flipping with aligned address.
4246   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4247   if (reachable(src)) {
4248     Assembler::xorps(dst, as_Address(src));
4249   } else {
4250     lea(rscratch1, src);
4251     Assembler::xorps(dst, Address(rscratch1, 0));
4252   }
4253 }
4254 
4255 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4256   // Used in sign-bit flipping with aligned address.
4257   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4258   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4259   if (reachable(src)) {
4260     Assembler::pshufb(dst, as_Address(src));
4261   } else {
4262     lea(rscratch1, src);
4263     Assembler::pshufb(dst, Address(rscratch1, 0));
4264   }
4265 }
4266 
4267 // AVX 3-operands instructions
4268 
4269 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4270   if (reachable(src)) {
4271     vaddsd(dst, nds, as_Address(src));
4272   } else {
4273     lea(rscratch1, src);
4274     vaddsd(dst, nds, Address(rscratch1, 0));
4275   }
4276 }
4277 
4278 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4279   if (reachable(src)) {
4280     vaddss(dst, nds, as_Address(src));
4281   } else {
4282     lea(rscratch1, src);
4283     vaddss(dst, nds, Address(rscratch1, 0));
4284   }
4285 }
4286 
4287 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4288   int dst_enc = dst->encoding();
4289   int nds_enc = nds->encoding();
4290   int src_enc = src->encoding();
4291   if ((dst_enc < 16) && (nds_enc < 16)) {
4292     vandps(dst, nds, negate_field, vector_len);
4293   } else if ((src_enc < 16) && (dst_enc < 16)) {
4294     evmovdqul(src, nds, Assembler::AVX_512bit);
4295     vandps(dst, src, negate_field, vector_len);
4296   } else if (src_enc < 16) {
4297     evmovdqul(src, nds, Assembler::AVX_512bit);
4298     vandps(src, src, negate_field, vector_len);
4299     evmovdqul(dst, src, Assembler::AVX_512bit);
4300   } else if (dst_enc < 16) {
4301     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4302     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4303     vandps(dst, xmm0, negate_field, vector_len);
4304     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4305   } else {
4306     if (src_enc != dst_enc) {
4307       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4308       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4309       vandps(xmm0, xmm0, negate_field, vector_len);
4310       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4311       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4312     } else {
4313       subptr(rsp, 64);
4314       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4315       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4316       vandps(xmm0, xmm0, negate_field, vector_len);
4317       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4318       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4319       addptr(rsp, 64);
4320     }
4321   }
4322 }
4323 
4324 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4325   int dst_enc = dst->encoding();
4326   int nds_enc = nds->encoding();
4327   int src_enc = src->encoding();
4328   if ((dst_enc < 16) && (nds_enc < 16)) {
4329     vandpd(dst, nds, negate_field, vector_len);
4330   } else if ((src_enc < 16) && (dst_enc < 16)) {
4331     evmovdqul(src, nds, Assembler::AVX_512bit);
4332     vandpd(dst, src, negate_field, vector_len);
4333   } else if (src_enc < 16) {
4334     evmovdqul(src, nds, Assembler::AVX_512bit);
4335     vandpd(src, src, negate_field, vector_len);
4336     evmovdqul(dst, src, Assembler::AVX_512bit);
4337   } else if (dst_enc < 16) {
4338     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4339     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4340     vandpd(dst, xmm0, negate_field, vector_len);
4341     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4342   } else {
4343     if (src_enc != dst_enc) {
4344       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4345       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4346       vandpd(xmm0, xmm0, negate_field, vector_len);
4347       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4348       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4349     } else {
4350       subptr(rsp, 64);
4351       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4352       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4353       vandpd(xmm0, xmm0, negate_field, vector_len);
4354       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4355       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4356       addptr(rsp, 64);
4357     }
4358   }
4359 }
4360 
4361 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4362   int dst_enc = dst->encoding();
4363   int nds_enc = nds->encoding();
4364   int src_enc = src->encoding();
4365   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4366     Assembler::vpaddb(dst, nds, src, vector_len);
4367   } else if ((dst_enc < 16) && (src_enc < 16)) {
4368     Assembler::vpaddb(dst, dst, src, vector_len);
4369   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4370     // use nds as scratch for src
4371     evmovdqul(nds, src, Assembler::AVX_512bit);
4372     Assembler::vpaddb(dst, dst, nds, vector_len);
4373   } else if ((src_enc < 16) && (nds_enc < 16)) {
4374     // use nds as scratch for dst
4375     evmovdqul(nds, dst, Assembler::AVX_512bit);
4376     Assembler::vpaddb(nds, nds, src, vector_len);
4377     evmovdqul(dst, nds, Assembler::AVX_512bit);
4378   } else if (dst_enc < 16) {
4379     // use nds as scatch for xmm0 to hold src
4380     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4381     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4382     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4383     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4384   } else {
4385     // worse case scenario, all regs are in the upper bank
4386     subptr(rsp, 64);
4387     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4388     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4389     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4390     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4391     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4392     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4393     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4394     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4395     addptr(rsp, 64);
4396   }
4397 }
4398 
4399 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4400   int dst_enc = dst->encoding();
4401   int nds_enc = nds->encoding();
4402   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4403     Assembler::vpaddb(dst, nds, src, vector_len);
4404   } else if (dst_enc < 16) {
4405     Assembler::vpaddb(dst, dst, src, vector_len);
4406   } else if (nds_enc < 16) {
4407     // implies dst_enc in upper bank with src as scratch
4408     evmovdqul(nds, dst, Assembler::AVX_512bit);
4409     Assembler::vpaddb(nds, nds, src, vector_len);
4410     evmovdqul(dst, nds, Assembler::AVX_512bit);
4411   } else {
4412     // worse case scenario, all regs in upper bank
4413     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4414     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4415     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4416     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4417   }
4418 }
4419 
4420 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4421   int dst_enc = dst->encoding();
4422   int nds_enc = nds->encoding();
4423   int src_enc = src->encoding();
4424   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4425     Assembler::vpaddw(dst, nds, src, vector_len);
4426   } else if ((dst_enc < 16) && (src_enc < 16)) {
4427     Assembler::vpaddw(dst, dst, src, vector_len);
4428   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4429     // use nds as scratch for src
4430     evmovdqul(nds, src, Assembler::AVX_512bit);
4431     Assembler::vpaddw(dst, dst, nds, vector_len);
4432   } else if ((src_enc < 16) && (nds_enc < 16)) {
4433     // use nds as scratch for dst
4434     evmovdqul(nds, dst, Assembler::AVX_512bit);
4435     Assembler::vpaddw(nds, nds, src, vector_len);
4436     evmovdqul(dst, nds, Assembler::AVX_512bit);
4437   } else if (dst_enc < 16) {
4438     // use nds as scatch for xmm0 to hold src
4439     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4440     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4441     Assembler::vpaddw(dst, dst, xmm0, vector_len);
4442     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4443   } else {
4444     // worse case scenario, all regs are in the upper bank
4445     subptr(rsp, 64);
4446     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4447     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4448     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4449     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4450     Assembler::vpaddw(xmm0, xmm0, xmm1, vector_len);
4451     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4452     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4453     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4454     addptr(rsp, 64);
4455   }
4456 }
4457 
4458 void MacroAssembler::vpaddw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4459   int dst_enc = dst->encoding();
4460   int nds_enc = nds->encoding();
4461   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4462     Assembler::vpaddw(dst, nds, src, vector_len);
4463   } else if (dst_enc < 16) {
4464     Assembler::vpaddw(dst, dst, src, vector_len);
4465   } else if (nds_enc < 16) {
4466     // implies dst_enc in upper bank with src as scratch
4467     evmovdqul(nds, dst, Assembler::AVX_512bit);
4468     Assembler::vpaddw(nds, nds, src, vector_len);
4469     evmovdqul(dst, nds, Assembler::AVX_512bit);
4470   } else {
4471     // worse case scenario, all regs in upper bank
4472     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4473     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4474     Assembler::vpaddw(xmm0, xmm0, src, vector_len);
4475     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4476   }
4477 }
4478 
4479 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4480   if (reachable(src)) {
4481     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4482   } else {
4483     lea(rscratch1, src);
4484     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4485   }
4486 }
4487 
4488 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4489   int dst_enc = dst->encoding();
4490   int src_enc = src->encoding();
4491   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4492     Assembler::vpbroadcastw(dst, src);
4493   } else if ((dst_enc < 16) && (src_enc < 16)) {
4494     Assembler::vpbroadcastw(dst, src);
4495   } else if (src_enc < 16) {
4496     subptr(rsp, 64);
4497     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4498     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4499     Assembler::vpbroadcastw(xmm0, src);
4500     movdqu(dst, xmm0);
4501     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4502     addptr(rsp, 64);
4503   } else if (dst_enc < 16) {
4504     subptr(rsp, 64);
4505     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4506     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4507     Assembler::vpbroadcastw(dst, xmm0);
4508     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4509     addptr(rsp, 64);
4510   } else {
4511     subptr(rsp, 64);
4512     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4513     subptr(rsp, 64);
4514     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4515     movdqu(xmm0, src);
4516     movdqu(xmm1, dst);
4517     Assembler::vpbroadcastw(xmm1, xmm0);
4518     movdqu(dst, xmm1);
4519     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4520     addptr(rsp, 64);
4521     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4522     addptr(rsp, 64);
4523   }
4524 }
4525 
4526 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4527   int dst_enc = dst->encoding();
4528   int nds_enc = nds->encoding();
4529   int src_enc = src->encoding();
4530   assert(dst_enc == nds_enc, "");
4531   if ((dst_enc < 16) && (src_enc < 16)) {
4532     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4533   } else if (src_enc < 16) {
4534     subptr(rsp, 64);
4535     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4536     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4537     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4538     movdqu(dst, xmm0);
4539     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4540     addptr(rsp, 64);
4541   } else if (dst_enc < 16) {
4542     subptr(rsp, 64);
4543     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4544     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4545     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4546     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4547     addptr(rsp, 64);
4548   } else {
4549     subptr(rsp, 64);
4550     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4551     subptr(rsp, 64);
4552     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4553     movdqu(xmm0, src);
4554     movdqu(xmm1, dst);
4555     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4556     movdqu(dst, xmm1);
4557     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4558     addptr(rsp, 64);
4559     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4560     addptr(rsp, 64);
4561   }
4562 }
4563 
4564 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4565   int dst_enc = dst->encoding();
4566   int nds_enc = nds->encoding();
4567   int src_enc = src->encoding();
4568   assert(dst_enc == nds_enc, "");
4569   if ((dst_enc < 16) && (src_enc < 16)) {
4570     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4571   } else if (src_enc < 16) {
4572     subptr(rsp, 64);
4573     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4574     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4575     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4576     movdqu(dst, xmm0);
4577     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4578     addptr(rsp, 64);
4579   } else if (dst_enc < 16) {
4580     subptr(rsp, 64);
4581     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4582     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4583     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4584     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4585     addptr(rsp, 64);
4586   } else {
4587     subptr(rsp, 64);
4588     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4589     subptr(rsp, 64);
4590     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4591     movdqu(xmm0, src);
4592     movdqu(xmm1, dst);
4593     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4594     movdqu(dst, xmm1);
4595     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4596     addptr(rsp, 64);
4597     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4598     addptr(rsp, 64);
4599   }
4600 }
4601 
4602 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4603   int dst_enc = dst->encoding();
4604   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4605     Assembler::vpmovzxbw(dst, src, vector_len);
4606   } else if (dst_enc < 16) {
4607     Assembler::vpmovzxbw(dst, src, vector_len);
4608   } else {
4609     subptr(rsp, 64);
4610     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4611     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4612     Assembler::vpmovzxbw(xmm0, src, vector_len);
4613     movdqu(dst, xmm0);
4614     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4615     addptr(rsp, 64);
4616   }
4617 }
4618 
4619 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4620   int src_enc = src->encoding();
4621   if (src_enc < 16) {
4622     Assembler::vpmovmskb(dst, src);
4623   } else {
4624     subptr(rsp, 64);
4625     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4626     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4627     Assembler::vpmovmskb(dst, xmm0);
4628     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4629     addptr(rsp, 64);
4630   }
4631 }
4632 
4633 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4634   int dst_enc = dst->encoding();
4635   int nds_enc = nds->encoding();
4636   int src_enc = src->encoding();
4637   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4638     Assembler::vpmullw(dst, nds, src, vector_len);
4639   } else if ((dst_enc < 16) && (src_enc < 16)) {
4640     Assembler::vpmullw(dst, dst, src, vector_len);
4641   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4642     // use nds as scratch for src
4643     evmovdqul(nds, src, Assembler::AVX_512bit);
4644     Assembler::vpmullw(dst, dst, nds, vector_len);
4645   } else if ((src_enc < 16) && (nds_enc < 16)) {
4646     // use nds as scratch for dst
4647     evmovdqul(nds, dst, Assembler::AVX_512bit);
4648     Assembler::vpmullw(nds, nds, src, vector_len);
4649     evmovdqul(dst, nds, Assembler::AVX_512bit);
4650   } else if (dst_enc < 16) {
4651     // use nds as scatch for xmm0 to hold src
4652     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4653     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4654     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4655     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4656   } else {
4657     // worse case scenario, all regs are in the upper bank
4658     subptr(rsp, 64);
4659     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4660     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4661     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4662     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4663     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4664     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4665     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4666     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4667     addptr(rsp, 64);
4668   }
4669 }
4670 
4671 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4672   int dst_enc = dst->encoding();
4673   int nds_enc = nds->encoding();
4674   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4675     Assembler::vpmullw(dst, nds, src, vector_len);
4676   } else if (dst_enc < 16) {
4677     Assembler::vpmullw(dst, dst, src, vector_len);
4678   } else if (nds_enc < 16) {
4679     // implies dst_enc in upper bank with src as scratch
4680     evmovdqul(nds, dst, Assembler::AVX_512bit);
4681     Assembler::vpmullw(nds, nds, src, vector_len);
4682     evmovdqul(dst, nds, Assembler::AVX_512bit);
4683   } else {
4684     // worse case scenario, all regs in upper bank
4685     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4686     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4687     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4688     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4689   }
4690 }
4691 
4692 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4693   int dst_enc = dst->encoding();
4694   int nds_enc = nds->encoding();
4695   int src_enc = src->encoding();
4696   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4697     Assembler::vpsubb(dst, nds, src, vector_len);
4698   } else if ((dst_enc < 16) && (src_enc < 16)) {
4699     Assembler::vpsubb(dst, dst, src, vector_len);
4700   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4701     // use nds as scratch for src
4702     evmovdqul(nds, src, Assembler::AVX_512bit);
4703     Assembler::vpsubb(dst, dst, nds, vector_len);
4704   } else if ((src_enc < 16) && (nds_enc < 16)) {
4705     // use nds as scratch for dst
4706     evmovdqul(nds, dst, Assembler::AVX_512bit);
4707     Assembler::vpsubb(nds, nds, src, vector_len);
4708     evmovdqul(dst, nds, Assembler::AVX_512bit);
4709   } else if (dst_enc < 16) {
4710     // use nds as scatch for xmm0 to hold src
4711     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4712     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4713     Assembler::vpsubb(dst, dst, xmm0, vector_len);
4714     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4715   } else {
4716     // worse case scenario, all regs are in the upper bank
4717     subptr(rsp, 64);
4718     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4719     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4720     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4721     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4722     Assembler::vpsubb(xmm0, xmm0, xmm1, vector_len);
4723     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4724     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4725     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4726     addptr(rsp, 64);
4727   }
4728 }
4729 
4730 void MacroAssembler::vpsubb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4731   int dst_enc = dst->encoding();
4732   int nds_enc = nds->encoding();
4733   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4734     Assembler::vpsubb(dst, nds, src, vector_len);
4735   } else if (dst_enc < 16) {
4736     Assembler::vpsubb(dst, dst, src, vector_len);
4737   } else if (nds_enc < 16) {
4738     // implies dst_enc in upper bank with src as scratch
4739     evmovdqul(nds, dst, Assembler::AVX_512bit);
4740     Assembler::vpsubb(nds, nds, src, vector_len);
4741     evmovdqul(dst, nds, Assembler::AVX_512bit);
4742   } else {
4743     // worse case scenario, all regs in upper bank
4744     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4745     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4746     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4747     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4748   }
4749 }
4750 
4751 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4752   int dst_enc = dst->encoding();
4753   int nds_enc = nds->encoding();
4754   int src_enc = src->encoding();
4755   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4756     Assembler::vpsubw(dst, nds, src, vector_len);
4757   } else if ((dst_enc < 16) && (src_enc < 16)) {
4758     Assembler::vpsubw(dst, dst, src, vector_len);
4759   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4760     // use nds as scratch for src
4761     evmovdqul(nds, src, Assembler::AVX_512bit);
4762     Assembler::vpsubw(dst, dst, nds, vector_len);
4763   } else if ((src_enc < 16) && (nds_enc < 16)) {
4764     // use nds as scratch for dst
4765     evmovdqul(nds, dst, Assembler::AVX_512bit);
4766     Assembler::vpsubw(nds, nds, src, vector_len);
4767     evmovdqul(dst, nds, Assembler::AVX_512bit);
4768   } else if (dst_enc < 16) {
4769     // use nds as scatch for xmm0 to hold src
4770     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4771     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4772     Assembler::vpsubw(dst, dst, xmm0, vector_len);
4773     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4774   } else {
4775     // worse case scenario, all regs are in the upper bank
4776     subptr(rsp, 64);
4777     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4778     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4779     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4780     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4781     Assembler::vpsubw(xmm0, xmm0, xmm1, vector_len);
4782     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4783     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4784     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4785     addptr(rsp, 64);
4786   }
4787 }
4788 
4789 void MacroAssembler::vpsubw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4790   int dst_enc = dst->encoding();
4791   int nds_enc = nds->encoding();
4792   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4793     Assembler::vpsubw(dst, nds, src, vector_len);
4794   } else if (dst_enc < 16) {
4795     Assembler::vpsubw(dst, dst, src, vector_len);
4796   } else if (nds_enc < 16) {
4797     // implies dst_enc in upper bank with src as scratch
4798     evmovdqul(nds, dst, Assembler::AVX_512bit);
4799     Assembler::vpsubw(nds, nds, src, vector_len);
4800     evmovdqul(dst, nds, Assembler::AVX_512bit);
4801   } else {
4802     // worse case scenario, all regs in upper bank
4803     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4804     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4805     Assembler::vpsubw(xmm0, xmm0, src, vector_len);
4806     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4807   }
4808 }
4809 
4810 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4811   int dst_enc = dst->encoding();
4812   int nds_enc = nds->encoding();
4813   int shift_enc = shift->encoding();
4814   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4815     Assembler::vpsraw(dst, nds, shift, vector_len);
4816   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4817     Assembler::vpsraw(dst, dst, shift, vector_len);
4818   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4819     // use nds_enc as scratch with shift
4820     evmovdqul(nds, shift, Assembler::AVX_512bit);
4821     Assembler::vpsraw(dst, dst, nds, vector_len);
4822   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4823     // use nds as scratch with dst
4824     evmovdqul(nds, dst, Assembler::AVX_512bit);
4825     Assembler::vpsraw(nds, nds, shift, vector_len);
4826     evmovdqul(dst, nds, Assembler::AVX_512bit);
4827   } else if (dst_enc < 16) {
4828     // use nds to save a copy of xmm0 and hold shift
4829     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4830     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4831     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4832     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4833   } else if (nds_enc < 16) {
4834     // use nds as dest as temps
4835     evmovdqul(nds, dst, Assembler::AVX_512bit);
4836     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4837     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4838     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4839     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4840     evmovdqul(dst, nds, Assembler::AVX_512bit);
4841   } else {
4842     // worse case scenario, all regs are in the upper bank
4843     subptr(rsp, 64);
4844     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4845     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4846     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4847     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4848     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4849     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4850     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4851     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4852     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4853     addptr(rsp, 64);
4854   }
4855 }
4856 
4857 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4858   int dst_enc = dst->encoding();
4859   int nds_enc = nds->encoding();
4860   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4861     Assembler::vpsraw(dst, nds, shift, vector_len);
4862   } else if (dst_enc < 16) {
4863     Assembler::vpsraw(dst, dst, shift, vector_len);
4864   } else if (nds_enc < 16) {
4865     // use nds as scratch
4866     evmovdqul(nds, dst, Assembler::AVX_512bit);
4867     Assembler::vpsraw(nds, nds, shift, vector_len);
4868     evmovdqul(dst, nds, Assembler::AVX_512bit);
4869   } else {
4870     // use nds as scratch for xmm0
4871     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4872     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4873     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4874     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4875   }
4876 }
4877 
4878 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4879   int dst_enc = dst->encoding();
4880   int nds_enc = nds->encoding();
4881   int shift_enc = shift->encoding();
4882   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4883     Assembler::vpsrlw(dst, nds, shift, vector_len);
4884   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4885     Assembler::vpsrlw(dst, dst, shift, vector_len);
4886   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4887     // use nds_enc as scratch with shift
4888     evmovdqul(nds, shift, Assembler::AVX_512bit);
4889     Assembler::vpsrlw(dst, dst, nds, vector_len);
4890   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4891     // use nds as scratch with dst
4892     evmovdqul(nds, dst, Assembler::AVX_512bit);
4893     Assembler::vpsrlw(nds, nds, shift, vector_len);
4894     evmovdqul(dst, nds, Assembler::AVX_512bit);
4895   } else if (dst_enc < 16) {
4896     // use nds to save a copy of xmm0 and hold shift
4897     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4898     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4899     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4900     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4901   } else if (nds_enc < 16) {
4902     // use nds as dest as temps
4903     evmovdqul(nds, dst, Assembler::AVX_512bit);
4904     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4905     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4906     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4907     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4908     evmovdqul(dst, nds, Assembler::AVX_512bit);
4909   } else {
4910     // worse case scenario, all regs are in the upper bank
4911     subptr(rsp, 64);
4912     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4913     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4914     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4915     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4916     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4917     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4918     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4919     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4920     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4921     addptr(rsp, 64);
4922   }
4923 }
4924 
4925 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4926   int dst_enc = dst->encoding();
4927   int nds_enc = nds->encoding();
4928   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4929     Assembler::vpsrlw(dst, nds, shift, vector_len);
4930   } else if (dst_enc < 16) {
4931     Assembler::vpsrlw(dst, dst, shift, vector_len);
4932   } else if (nds_enc < 16) {
4933     // use nds as scratch
4934     evmovdqul(nds, dst, Assembler::AVX_512bit);
4935     Assembler::vpsrlw(nds, nds, shift, vector_len);
4936     evmovdqul(dst, nds, Assembler::AVX_512bit);
4937   } else {
4938     // use nds as scratch for xmm0
4939     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4940     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4941     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4942     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4943   }
4944 }
4945 
4946 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4947   int dst_enc = dst->encoding();
4948   int nds_enc = nds->encoding();
4949   int shift_enc = shift->encoding();
4950   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4951     Assembler::vpsllw(dst, nds, shift, vector_len);
4952   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4953     Assembler::vpsllw(dst, dst, shift, vector_len);
4954   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4955     // use nds_enc as scratch with shift
4956     evmovdqul(nds, shift, Assembler::AVX_512bit);
4957     Assembler::vpsllw(dst, dst, nds, vector_len);
4958   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4959     // use nds as scratch with dst
4960     evmovdqul(nds, dst, Assembler::AVX_512bit);
4961     Assembler::vpsllw(nds, nds, shift, vector_len);
4962     evmovdqul(dst, nds, Assembler::AVX_512bit);
4963   } else if (dst_enc < 16) {
4964     // use nds to save a copy of xmm0 and hold shift
4965     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4966     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4967     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4968     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4969   } else if (nds_enc < 16) {
4970     // use nds as dest as temps
4971     evmovdqul(nds, dst, Assembler::AVX_512bit);
4972     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4973     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4974     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4975     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4976     evmovdqul(dst, nds, Assembler::AVX_512bit);
4977   } else {
4978     // worse case scenario, all regs are in the upper bank
4979     subptr(rsp, 64);
4980     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4981     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4982     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4983     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4984     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4985     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4986     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4987     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4988     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4989     addptr(rsp, 64);
4990   }
4991 }
4992 
4993 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4994   int dst_enc = dst->encoding();
4995   int nds_enc = nds->encoding();
4996   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4997     Assembler::vpsllw(dst, nds, shift, vector_len);
4998   } else if (dst_enc < 16) {
4999     Assembler::vpsllw(dst, dst, shift, vector_len);
5000   } else if (nds_enc < 16) {
5001     // use nds as scratch
5002     evmovdqul(nds, dst, Assembler::AVX_512bit);
5003     Assembler::vpsllw(nds, nds, shift, vector_len);
5004     evmovdqul(dst, nds, Assembler::AVX_512bit);
5005   } else {
5006     // use nds as scratch for xmm0
5007     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
5008     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5009     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
5010     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
5011   }
5012 }
5013 
5014 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
5015   int dst_enc = dst->encoding();
5016   int src_enc = src->encoding();
5017   if ((dst_enc < 16) && (src_enc < 16)) {
5018     Assembler::vptest(dst, src);
5019   } else if (src_enc < 16) {
5020     subptr(rsp, 64);
5021     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5022     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5023     Assembler::vptest(xmm0, src);
5024     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5025     addptr(rsp, 64);
5026   } else if (dst_enc < 16) {
5027     subptr(rsp, 64);
5028     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5029     evmovdqul(xmm0, src, Assembler::AVX_512bit);
5030     Assembler::vptest(dst, xmm0);
5031     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5032     addptr(rsp, 64);
5033   } else {
5034     subptr(rsp, 64);
5035     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5036     subptr(rsp, 64);
5037     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5038     movdqu(xmm0, src);
5039     movdqu(xmm1, dst);
5040     Assembler::vptest(xmm1, xmm0);
5041     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5042     addptr(rsp, 64);
5043     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5044     addptr(rsp, 64);
5045   }
5046 }
5047 
5048 // This instruction exists within macros, ergo we cannot control its input
5049 // when emitted through those patterns.
5050 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
5051   if (VM_Version::supports_avx512nobw()) {
5052     int dst_enc = dst->encoding();
5053     int src_enc = src->encoding();
5054     if (dst_enc == src_enc) {
5055       if (dst_enc < 16) {
5056         Assembler::punpcklbw(dst, src);
5057       } else {
5058         subptr(rsp, 64);
5059         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5060         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5061         Assembler::punpcklbw(xmm0, xmm0);
5062         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5063         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5064         addptr(rsp, 64);
5065       }
5066     } else {
5067       if ((src_enc < 16) && (dst_enc < 16)) {
5068         Assembler::punpcklbw(dst, src);
5069       } else if (src_enc < 16) {
5070         subptr(rsp, 64);
5071         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5072         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5073         Assembler::punpcklbw(xmm0, src);
5074         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5075         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5076         addptr(rsp, 64);
5077       } else if (dst_enc < 16) {
5078         subptr(rsp, 64);
5079         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5080         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5081         Assembler::punpcklbw(dst, xmm0);
5082         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5083         addptr(rsp, 64);
5084       } else {
5085         subptr(rsp, 64);
5086         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5087         subptr(rsp, 64);
5088         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5089         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5090         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5091         Assembler::punpcklbw(xmm0, xmm1);
5092         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5093         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5094         addptr(rsp, 64);
5095         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5096         addptr(rsp, 64);
5097       }
5098     }
5099   } else {
5100     Assembler::punpcklbw(dst, src);
5101   }
5102 }
5103 
5104 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5105   if (VM_Version::supports_avx512vl()) {
5106     Assembler::pshufd(dst, src, mode);
5107   } else {
5108     int dst_enc = dst->encoding();
5109     if (dst_enc < 16) {
5110       Assembler::pshufd(dst, src, mode);
5111     } else {
5112       subptr(rsp, 64);
5113       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5114       Assembler::pshufd(xmm0, src, mode);
5115       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5116       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5117       addptr(rsp, 64);
5118     }
5119   }
5120 }
5121 
5122 // This instruction exists within macros, ergo we cannot control its input
5123 // when emitted through those patterns.
5124 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5125   if (VM_Version::supports_avx512nobw()) {
5126     int dst_enc = dst->encoding();
5127     int src_enc = src->encoding();
5128     if (dst_enc == src_enc) {
5129       if (dst_enc < 16) {
5130         Assembler::pshuflw(dst, src, mode);
5131       } else {
5132         subptr(rsp, 64);
5133         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5134         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5135         Assembler::pshuflw(xmm0, xmm0, mode);
5136         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5137         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5138         addptr(rsp, 64);
5139       }
5140     } else {
5141       if ((src_enc < 16) && (dst_enc < 16)) {
5142         Assembler::pshuflw(dst, src, mode);
5143       } else if (src_enc < 16) {
5144         subptr(rsp, 64);
5145         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5146         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5147         Assembler::pshuflw(xmm0, src, mode);
5148         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5149         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5150         addptr(rsp, 64);
5151       } else if (dst_enc < 16) {
5152         subptr(rsp, 64);
5153         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5154         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5155         Assembler::pshuflw(dst, xmm0, mode);
5156         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5157         addptr(rsp, 64);
5158       } else {
5159         subptr(rsp, 64);
5160         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5161         subptr(rsp, 64);
5162         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5163         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5164         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5165         Assembler::pshuflw(xmm0, xmm1, mode);
5166         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5167         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5168         addptr(rsp, 64);
5169         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5170         addptr(rsp, 64);
5171       }
5172     }
5173   } else {
5174     Assembler::pshuflw(dst, src, mode);
5175   }
5176 }
5177 
5178 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5179   if (reachable(src)) {
5180     vandpd(dst, nds, as_Address(src), vector_len);
5181   } else {
5182     lea(rscratch1, src);
5183     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5184   }
5185 }
5186 
5187 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5188   if (reachable(src)) {
5189     vandps(dst, nds, as_Address(src), vector_len);
5190   } else {
5191     lea(rscratch1, src);
5192     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5193   }
5194 }
5195 
5196 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5197   if (reachable(src)) {
5198     vdivsd(dst, nds, as_Address(src));
5199   } else {
5200     lea(rscratch1, src);
5201     vdivsd(dst, nds, Address(rscratch1, 0));
5202   }
5203 }
5204 
5205 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5206   if (reachable(src)) {
5207     vdivss(dst, nds, as_Address(src));
5208   } else {
5209     lea(rscratch1, src);
5210     vdivss(dst, nds, Address(rscratch1, 0));
5211   }
5212 }
5213 
5214 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5215   if (reachable(src)) {
5216     vmulsd(dst, nds, as_Address(src));
5217   } else {
5218     lea(rscratch1, src);
5219     vmulsd(dst, nds, Address(rscratch1, 0));
5220   }
5221 }
5222 
5223 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5224   if (reachable(src)) {
5225     vmulss(dst, nds, as_Address(src));
5226   } else {
5227     lea(rscratch1, src);
5228     vmulss(dst, nds, Address(rscratch1, 0));
5229   }
5230 }
5231 
5232 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5233   if (reachable(src)) {
5234     vsubsd(dst, nds, as_Address(src));
5235   } else {
5236     lea(rscratch1, src);
5237     vsubsd(dst, nds, Address(rscratch1, 0));
5238   }
5239 }
5240 
5241 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5242   if (reachable(src)) {
5243     vsubss(dst, nds, as_Address(src));
5244   } else {
5245     lea(rscratch1, src);
5246     vsubss(dst, nds, Address(rscratch1, 0));
5247   }
5248 }
5249 
5250 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5251   int nds_enc = nds->encoding();
5252   int dst_enc = dst->encoding();
5253   bool dst_upper_bank = (dst_enc > 15);
5254   bool nds_upper_bank = (nds_enc > 15);
5255   if (VM_Version::supports_avx512novl() &&
5256       (nds_upper_bank || dst_upper_bank)) {
5257     if (dst_upper_bank) {
5258       subptr(rsp, 64);
5259       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5260       movflt(xmm0, nds);
5261       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5262       movflt(dst, xmm0);
5263       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5264       addptr(rsp, 64);
5265     } else {
5266       movflt(dst, nds);
5267       vxorps(dst, dst, src, Assembler::AVX_128bit);
5268     }
5269   } else {
5270     vxorps(dst, nds, src, Assembler::AVX_128bit);
5271   }
5272 }
5273 
5274 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5275   int nds_enc = nds->encoding();
5276   int dst_enc = dst->encoding();
5277   bool dst_upper_bank = (dst_enc > 15);
5278   bool nds_upper_bank = (nds_enc > 15);
5279   if (VM_Version::supports_avx512novl() &&
5280       (nds_upper_bank || dst_upper_bank)) {
5281     if (dst_upper_bank) {
5282       subptr(rsp, 64);
5283       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5284       movdbl(xmm0, nds);
5285       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5286       movdbl(dst, xmm0);
5287       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5288       addptr(rsp, 64);
5289     } else {
5290       movdbl(dst, nds);
5291       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5292     }
5293   } else {
5294     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5295   }
5296 }
5297 
5298 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5299   if (reachable(src)) {
5300     vxorpd(dst, nds, as_Address(src), vector_len);
5301   } else {
5302     lea(rscratch1, src);
5303     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5304   }
5305 }
5306 
5307 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5308   if (reachable(src)) {
5309     vxorps(dst, nds, as_Address(src), vector_len);
5310   } else {
5311     lea(rscratch1, src);
5312     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5313   }
5314 }
5315 
5316 
5317 void MacroAssembler::resolve_jobject(Register value,
5318                                      Register thread,
5319                                      Register tmp) {
5320   assert_different_registers(value, thread, tmp);
5321   Label done, not_weak;
5322   testptr(value, value);
5323   jcc(Assembler::zero, done);                // Use NULL as-is.
5324   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5325   jcc(Assembler::zero, not_weak);
5326   // Resolve jweak.
5327   movptr(value, Address(value, -JNIHandles::weak_tag_value));
5328   verify_oop(value);
5329 #if INCLUDE_ALL_GCS
5330   if (UseG1GC) {
5331     g1_write_barrier_pre(noreg /* obj */,
5332                          value /* pre_val */,
5333                          thread /* thread */,
5334                          tmp /* tmp */,
5335                          true /* tosca_live */,
5336                          true /* expand_call */);
5337   }
5338 #endif // INCLUDE_ALL_GCS
5339   jmp(done);
5340   bind(not_weak);
5341   // Resolve (untagged) jobject.
5342   movptr(value, Address(value, 0));
5343   verify_oop(value);
5344   bind(done);
5345 }
5346 
5347 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5348   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5349   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5350   // The inverted mask is sign-extended
5351   andptr(possibly_jweak, inverted_jweak_mask);
5352 }
5353 
5354 //////////////////////////////////////////////////////////////////////////////////
5355 #if INCLUDE_ALL_GCS
5356 
5357 void MacroAssembler::g1_write_barrier_pre(Register obj,
5358                                           Register pre_val,
5359                                           Register thread,
5360                                           Register tmp,
5361                                           bool tosca_live,
5362                                           bool expand_call) {
5363 
5364   // If expand_call is true then we expand the call_VM_leaf macro
5365   // directly to skip generating the check by
5366   // InterpreterMacroAssembler::call_VM_leaf_base that checks _last_sp.
5367 
5368 #ifdef _LP64
5369   assert(thread == r15_thread, "must be");
5370 #endif // _LP64
5371 
5372   Label done;
5373   Label runtime;
5374 
5375   assert(pre_val != noreg, "check this code");
5376 
5377   if (obj != noreg) {
5378     assert_different_registers(obj, pre_val, tmp);
5379     assert(pre_val != rax, "check this code");
5380   }
5381 
5382   Address in_progress(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5383                                        SATBMarkQueue::byte_offset_of_active()));
5384   Address index(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5385                                        SATBMarkQueue::byte_offset_of_index()));
5386   Address buffer(thread, in_bytes(JavaThread::satb_mark_queue_offset() +
5387                                        SATBMarkQueue::byte_offset_of_buf()));
5388 
5389 
5390   // Is marking active?
5391   if (in_bytes(SATBMarkQueue::byte_width_of_active()) == 4) {
5392     cmpl(in_progress, 0);
5393   } else {
5394     assert(in_bytes(SATBMarkQueue::byte_width_of_active()) == 1, "Assumption");
5395     cmpb(in_progress, 0);
5396   }
5397   jcc(Assembler::equal, done);
5398 
5399   // Do we need to load the previous value?
5400   if (obj != noreg) {
5401     load_heap_oop(pre_val, Address(obj, 0));
5402   }
5403 
5404   // Is the previous value null?
5405   cmpptr(pre_val, (int32_t) NULL_WORD);
5406   jcc(Assembler::equal, done);
5407 
5408   // Can we store original value in the thread's buffer?
5409   // Is index == 0?
5410   // (The index field is typed as size_t.)
5411 
5412   movptr(tmp, index);                   // tmp := *index_adr
5413   cmpptr(tmp, 0);                       // tmp == 0?
5414   jcc(Assembler::equal, runtime);       // If yes, goto runtime
5415 
5416   subptr(tmp, wordSize);                // tmp := tmp - wordSize
5417   movptr(index, tmp);                   // *index_adr := tmp
5418   addptr(tmp, buffer);                  // tmp := tmp + *buffer_adr
5419 
5420   // Record the previous value
5421   movptr(Address(tmp, 0), pre_val);
5422   jmp(done);
5423 
5424   bind(runtime);
5425   // save the live input values
5426   if(tosca_live) push(rax);
5427 
5428   if (obj != noreg && obj != rax)
5429     push(obj);
5430 
5431   if (pre_val != rax)
5432     push(pre_val);
5433 
5434   // Calling the runtime using the regular call_VM_leaf mechanism generates
5435   // code (generated by InterpreterMacroAssember::call_VM_leaf_base)
5436   // that checks that the *(ebp+frame::interpreter_frame_last_sp) == NULL.
5437   //
5438   // If we care generating the pre-barrier without a frame (e.g. in the
5439   // intrinsified Reference.get() routine) then ebp might be pointing to
5440   // the caller frame and so this check will most likely fail at runtime.
5441   //
5442   // Expanding the call directly bypasses the generation of the check.
5443   // So when we do not have have a full interpreter frame on the stack
5444   // expand_call should be passed true.
5445 
5446   NOT_LP64( push(thread); )
5447 
5448   if (expand_call) {
5449     LP64_ONLY( assert(pre_val != c_rarg1, "smashed arg"); )
5450     pass_arg1(this, thread);
5451     pass_arg0(this, pre_val);
5452     MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), 2);
5453   } else {
5454     call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_pre), pre_val, thread);
5455   }
5456 
5457   NOT_LP64( pop(thread); )
5458 
5459   // save the live input values
5460   if (pre_val != rax)
5461     pop(pre_val);
5462 
5463   if (obj != noreg && obj != rax)
5464     pop(obj);
5465 
5466   if(tosca_live) pop(rax);
5467 
5468   bind(done);
5469 }
5470 
5471 void MacroAssembler::g1_write_barrier_post(Register store_addr,
5472                                            Register new_val,
5473                                            Register thread,
5474                                            Register tmp,
5475                                            Register tmp2) {
5476 #ifdef _LP64
5477   assert(thread == r15_thread, "must be");
5478 #endif // _LP64
5479 
5480   Address queue_index(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5481                                        DirtyCardQueue::byte_offset_of_index()));
5482   Address buffer(thread, in_bytes(JavaThread::dirty_card_queue_offset() +
5483                                        DirtyCardQueue::byte_offset_of_buf()));
5484 
5485   CardTableModRefBS* ctbs =
5486     barrier_set_cast<CardTableModRefBS>(Universe::heap()->barrier_set());
5487   CardTable* ct = ctbs->card_table();
5488   assert(sizeof(*ct->byte_map_base()) == sizeof(jbyte), "adjust this code");
5489 
5490   Label done;
5491   Label runtime;
5492 
5493   // Does store cross heap regions?
5494 
5495   movptr(tmp, store_addr);
5496   xorptr(tmp, new_val);
5497   shrptr(tmp, HeapRegion::LogOfHRGrainBytes);
5498   jcc(Assembler::equal, done);
5499 
5500   // crosses regions, storing NULL?
5501 
5502   cmpptr(new_val, (int32_t) NULL_WORD);
5503   jcc(Assembler::equal, done);
5504 
5505   // storing region crossing non-NULL, is card already dirty?
5506 
5507   const Register card_addr = tmp;
5508   const Register cardtable = tmp2;
5509 
5510   movptr(card_addr, store_addr);
5511   shrptr(card_addr, CardTable::card_shift);
5512   // Do not use ExternalAddress to load 'byte_map_base', since 'byte_map_base' is NOT
5513   // a valid address and therefore is not properly handled by the relocation code.
5514   movptr(cardtable, (intptr_t)ct->byte_map_base());
5515   addptr(card_addr, cardtable);
5516 
5517   cmpb(Address(card_addr, 0), (int)G1CardTable::g1_young_card_val());
5518   jcc(Assembler::equal, done);
5519 
5520   membar(Assembler::Membar_mask_bits(Assembler::StoreLoad));
5521   cmpb(Address(card_addr, 0), (int)CardTable::dirty_card_val());
5522   jcc(Assembler::equal, done);
5523 
5524 
5525   // storing a region crossing, non-NULL oop, card is clean.
5526   // dirty card and log.
5527 
5528   movb(Address(card_addr, 0), (int)CardTable::dirty_card_val());
5529 
5530   cmpl(queue_index, 0);
5531   jcc(Assembler::equal, runtime);
5532   subl(queue_index, wordSize);
5533   movptr(tmp2, buffer);
5534 #ifdef _LP64
5535   movslq(rscratch1, queue_index);
5536   addq(tmp2, rscratch1);
5537   movq(Address(tmp2, 0), card_addr);
5538 #else
5539   addl(tmp2, queue_index);
5540   movl(Address(tmp2, 0), card_addr);
5541 #endif
5542   jmp(done);
5543 
5544   bind(runtime);
5545   // save the live input values
5546   push(store_addr);
5547   push(new_val);
5548 #ifdef _LP64
5549   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, r15_thread);
5550 #else
5551   push(thread);
5552   call_VM_leaf(CAST_FROM_FN_PTR(address, SharedRuntime::g1_wb_post), card_addr, thread);
5553   pop(thread);
5554 #endif
5555   pop(new_val);
5556   pop(store_addr);
5557 
5558   bind(done);
5559 }
5560 
5561 #endif // INCLUDE_ALL_GCS
5562 //////////////////////////////////////////////////////////////////////////////////
5563 
5564 
5565 void MacroAssembler::store_check(Register obj, Address dst) {
5566   store_check(obj);
5567 }
5568 
5569 void MacroAssembler::store_check(Register obj) {
5570   // Does a store check for the oop in register obj. The content of
5571   // register obj is destroyed afterwards.
5572   BarrierSet* bs = Universe::heap()->barrier_set();
5573   assert(bs->kind() == BarrierSet::CardTableModRef,
5574          "Wrong barrier set kind");
5575 
5576   CardTableModRefBS* ctbs = barrier_set_cast<CardTableModRefBS>(bs);
5577   CardTable* ct = ctbs->card_table();
5578   assert(sizeof(*ct->byte_map_base()) == sizeof(jbyte), "adjust this code");
5579 
5580   shrptr(obj, CardTable::card_shift);
5581 
5582   Address card_addr;
5583 
5584   // The calculation for byte_map_base is as follows:
5585   // byte_map_base = _byte_map - (uintptr_t(low_bound) >> card_shift);
5586   // So this essentially converts an address to a displacement and it will
5587   // never need to be relocated. On 64bit however the value may be too
5588   // large for a 32bit displacement.
5589   intptr_t disp = (intptr_t) ct->byte_map_base();
5590   if (is_simm32(disp)) {
5591     card_addr = Address(noreg, obj, Address::times_1, disp);
5592   } else {
5593     // By doing it as an ExternalAddress 'disp' could be converted to a rip-relative
5594     // displacement and done in a single instruction given favorable mapping and a
5595     // smarter version of as_Address. However, 'ExternalAddress' generates a relocation
5596     // entry and that entry is not properly handled by the relocation code.
5597     AddressLiteral cardtable((address)ct->byte_map_base(), relocInfo::none);
5598     Address index(noreg, obj, Address::times_1);
5599     card_addr = as_Address(ArrayAddress(cardtable, index));
5600   }
5601 
5602   int dirty = CardTable::dirty_card_val();
5603   if (UseCondCardMark) {
5604     Label L_already_dirty;
5605     if (UseConcMarkSweepGC) {
5606       membar(Assembler::StoreLoad);
5607     }
5608     cmpb(card_addr, dirty);
5609     jcc(Assembler::equal, L_already_dirty);
5610     movb(card_addr, dirty);
5611     bind(L_already_dirty);
5612   } else {
5613     movb(card_addr, dirty);
5614   }
5615 }
5616 
5617 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5618   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5619 }
5620 
5621 // Force generation of a 4 byte immediate value even if it fits into 8bit
5622 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5623   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5624 }
5625 
5626 void MacroAssembler::subptr(Register dst, Register src) {
5627   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5628 }
5629 
5630 // C++ bool manipulation
5631 void MacroAssembler::testbool(Register dst) {
5632   if(sizeof(bool) == 1)
5633     testb(dst, 0xff);
5634   else if(sizeof(bool) == 2) {
5635     // testw implementation needed for two byte bools
5636     ShouldNotReachHere();
5637   } else if(sizeof(bool) == 4)
5638     testl(dst, dst);
5639   else
5640     // unsupported
5641     ShouldNotReachHere();
5642 }
5643 
5644 void MacroAssembler::testptr(Register dst, Register src) {
5645   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5646 }
5647 
5648 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5649 void MacroAssembler::tlab_allocate(Register obj,
5650                                    Register var_size_in_bytes,
5651                                    int con_size_in_bytes,
5652                                    Register t1,
5653                                    Register t2,
5654                                    Label& slow_case) {
5655   assert_different_registers(obj, t1, t2);
5656   assert_different_registers(obj, var_size_in_bytes, t1);
5657   Register end = t2;
5658   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5659 
5660   verify_tlab();
5661 
5662   NOT_LP64(get_thread(thread));
5663 
5664   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5665   if (var_size_in_bytes == noreg) {
5666     lea(end, Address(obj, con_size_in_bytes));
5667   } else {
5668     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5669   }
5670   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5671   jcc(Assembler::above, slow_case);
5672 
5673   // update the tlab top pointer
5674   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5675 
5676   // recover var_size_in_bytes if necessary
5677   if (var_size_in_bytes == end) {
5678     subptr(var_size_in_bytes, obj);
5679   }
5680   verify_tlab();
5681 }
5682 
5683 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5684 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5685   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5686   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5687   Label done;
5688 
5689   testptr(length_in_bytes, length_in_bytes);
5690   jcc(Assembler::zero, done);
5691 
5692   // initialize topmost word, divide index by 2, check if odd and test if zero
5693   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5694 #ifdef ASSERT
5695   {
5696     Label L;
5697     testptr(length_in_bytes, BytesPerWord - 1);
5698     jcc(Assembler::zero, L);
5699     stop("length must be a multiple of BytesPerWord");
5700     bind(L);
5701   }
5702 #endif
5703   Register index = length_in_bytes;
5704   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5705   if (UseIncDec) {
5706     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5707   } else {
5708     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5709     shrptr(index, 1);
5710   }
5711 #ifndef _LP64
5712   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5713   {
5714     Label even;
5715     // note: if index was a multiple of 8, then it cannot
5716     //       be 0 now otherwise it must have been 0 before
5717     //       => if it is even, we don't need to check for 0 again
5718     jcc(Assembler::carryClear, even);
5719     // clear topmost word (no jump would be needed if conditional assignment worked here)
5720     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5721     // index could be 0 now, must check again
5722     jcc(Assembler::zero, done);
5723     bind(even);
5724   }
5725 #endif // !_LP64
5726   // initialize remaining object fields: index is a multiple of 2 now
5727   {
5728     Label loop;
5729     bind(loop);
5730     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5731     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5732     decrement(index);
5733     jcc(Assembler::notZero, loop);
5734   }
5735 
5736   bind(done);
5737 }
5738 
5739 void MacroAssembler::incr_allocated_bytes(Register thread,
5740                                           Register var_size_in_bytes,
5741                                           int con_size_in_bytes,
5742                                           Register t1) {
5743   if (!thread->is_valid()) {
5744 #ifdef _LP64
5745     thread = r15_thread;
5746 #else
5747     assert(t1->is_valid(), "need temp reg");
5748     thread = t1;
5749     get_thread(thread);
5750 #endif
5751   }
5752 
5753 #ifdef _LP64
5754   if (var_size_in_bytes->is_valid()) {
5755     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5756   } else {
5757     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5758   }
5759 #else
5760   if (var_size_in_bytes->is_valid()) {
5761     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5762   } else {
5763     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5764   }
5765   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5766 #endif
5767 }
5768 
5769 // Look up the method for a megamorphic invokeinterface call.
5770 // The target method is determined by <intf_klass, itable_index>.
5771 // The receiver klass is in recv_klass.
5772 // On success, the result will be in method_result, and execution falls through.
5773 // On failure, execution transfers to the given label.
5774 void MacroAssembler::lookup_interface_method(Register recv_klass,
5775                                              Register intf_klass,
5776                                              RegisterOrConstant itable_index,
5777                                              Register method_result,
5778                                              Register scan_temp,
5779                                              Label& L_no_such_interface,
5780                                              bool return_method) {
5781   assert_different_registers(recv_klass, intf_klass, scan_temp);
5782   assert_different_registers(method_result, intf_klass, scan_temp);
5783   assert(recv_klass != method_result || !return_method,
5784          "recv_klass can be destroyed when method isn't needed");
5785 
5786   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5787          "caller must use same register for non-constant itable index as for method");
5788 
5789   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5790   int vtable_base = in_bytes(Klass::vtable_start_offset());
5791   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5792   int scan_step   = itableOffsetEntry::size() * wordSize;
5793   int vte_size    = vtableEntry::size_in_bytes();
5794   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5795   assert(vte_size == wordSize, "else adjust times_vte_scale");
5796 
5797   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5798 
5799   // %%% Could store the aligned, prescaled offset in the klassoop.
5800   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5801 
5802   if (return_method) {
5803     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5804     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5805     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5806   }
5807 
5808   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5809   //   if (scan->interface() == intf) {
5810   //     result = (klass + scan->offset() + itable_index);
5811   //   }
5812   // }
5813   Label search, found_method;
5814 
5815   for (int peel = 1; peel >= 0; peel--) {
5816     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5817     cmpptr(intf_klass, method_result);
5818 
5819     if (peel) {
5820       jccb(Assembler::equal, found_method);
5821     } else {
5822       jccb(Assembler::notEqual, search);
5823       // (invert the test to fall through to found_method...)
5824     }
5825 
5826     if (!peel)  break;
5827 
5828     bind(search);
5829 
5830     // Check that the previous entry is non-null.  A null entry means that
5831     // the receiver class doesn't implement the interface, and wasn't the
5832     // same as when the caller was compiled.
5833     testptr(method_result, method_result);
5834     jcc(Assembler::zero, L_no_such_interface);
5835     addptr(scan_temp, scan_step);
5836   }
5837 
5838   bind(found_method);
5839 
5840   if (return_method) {
5841     // Got a hit.
5842     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5843     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5844   }
5845 }
5846 
5847 
5848 // virtual method calling
5849 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5850                                            RegisterOrConstant vtable_index,
5851                                            Register method_result) {
5852   const int base = in_bytes(Klass::vtable_start_offset());
5853   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5854   Address vtable_entry_addr(recv_klass,
5855                             vtable_index, Address::times_ptr,
5856                             base + vtableEntry::method_offset_in_bytes());
5857   movptr(method_result, vtable_entry_addr);
5858 }
5859 
5860 
5861 void MacroAssembler::check_klass_subtype(Register sub_klass,
5862                            Register super_klass,
5863                            Register temp_reg,
5864                            Label& L_success) {
5865   Label L_failure;
5866   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5867   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5868   bind(L_failure);
5869 }
5870 
5871 
5872 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5873                                                    Register super_klass,
5874                                                    Register temp_reg,
5875                                                    Label* L_success,
5876                                                    Label* L_failure,
5877                                                    Label* L_slow_path,
5878                                         RegisterOrConstant super_check_offset) {
5879   assert_different_registers(sub_klass, super_klass, temp_reg);
5880   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5881   if (super_check_offset.is_register()) {
5882     assert_different_registers(sub_klass, super_klass,
5883                                super_check_offset.as_register());
5884   } else if (must_load_sco) {
5885     assert(temp_reg != noreg, "supply either a temp or a register offset");
5886   }
5887 
5888   Label L_fallthrough;
5889   int label_nulls = 0;
5890   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5891   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5892   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5893   assert(label_nulls <= 1, "at most one NULL in the batch");
5894 
5895   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5896   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5897   Address super_check_offset_addr(super_klass, sco_offset);
5898 
5899   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5900   // range of a jccb.  If this routine grows larger, reconsider at
5901   // least some of these.
5902 #define local_jcc(assembler_cond, label)                                \
5903   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5904   else                             jcc( assembler_cond, label) /*omit semi*/
5905 
5906   // Hacked jmp, which may only be used just before L_fallthrough.
5907 #define final_jmp(label)                                                \
5908   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5909   else                            jmp(label)                /*omit semi*/
5910 
5911   // If the pointers are equal, we are done (e.g., String[] elements).
5912   // This self-check enables sharing of secondary supertype arrays among
5913   // non-primary types such as array-of-interface.  Otherwise, each such
5914   // type would need its own customized SSA.
5915   // We move this check to the front of the fast path because many
5916   // type checks are in fact trivially successful in this manner,
5917   // so we get a nicely predicted branch right at the start of the check.
5918   cmpptr(sub_klass, super_klass);
5919   local_jcc(Assembler::equal, *L_success);
5920 
5921   // Check the supertype display:
5922   if (must_load_sco) {
5923     // Positive movl does right thing on LP64.
5924     movl(temp_reg, super_check_offset_addr);
5925     super_check_offset = RegisterOrConstant(temp_reg);
5926   }
5927   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5928   cmpptr(super_klass, super_check_addr); // load displayed supertype
5929 
5930   // This check has worked decisively for primary supers.
5931   // Secondary supers are sought in the super_cache ('super_cache_addr').
5932   // (Secondary supers are interfaces and very deeply nested subtypes.)
5933   // This works in the same check above because of a tricky aliasing
5934   // between the super_cache and the primary super display elements.
5935   // (The 'super_check_addr' can address either, as the case requires.)
5936   // Note that the cache is updated below if it does not help us find
5937   // what we need immediately.
5938   // So if it was a primary super, we can just fail immediately.
5939   // Otherwise, it's the slow path for us (no success at this point).
5940 
5941   if (super_check_offset.is_register()) {
5942     local_jcc(Assembler::equal, *L_success);
5943     cmpl(super_check_offset.as_register(), sc_offset);
5944     if (L_failure == &L_fallthrough) {
5945       local_jcc(Assembler::equal, *L_slow_path);
5946     } else {
5947       local_jcc(Assembler::notEqual, *L_failure);
5948       final_jmp(*L_slow_path);
5949     }
5950   } else if (super_check_offset.as_constant() == sc_offset) {
5951     // Need a slow path; fast failure is impossible.
5952     if (L_slow_path == &L_fallthrough) {
5953       local_jcc(Assembler::equal, *L_success);
5954     } else {
5955       local_jcc(Assembler::notEqual, *L_slow_path);
5956       final_jmp(*L_success);
5957     }
5958   } else {
5959     // No slow path; it's a fast decision.
5960     if (L_failure == &L_fallthrough) {
5961       local_jcc(Assembler::equal, *L_success);
5962     } else {
5963       local_jcc(Assembler::notEqual, *L_failure);
5964       final_jmp(*L_success);
5965     }
5966   }
5967 
5968   bind(L_fallthrough);
5969 
5970 #undef local_jcc
5971 #undef final_jmp
5972 }
5973 
5974 
5975 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5976                                                    Register super_klass,
5977                                                    Register temp_reg,
5978                                                    Register temp2_reg,
5979                                                    Label* L_success,
5980                                                    Label* L_failure,
5981                                                    bool set_cond_codes) {
5982   assert_different_registers(sub_klass, super_klass, temp_reg);
5983   if (temp2_reg != noreg)
5984     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5985 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5986 
5987   Label L_fallthrough;
5988   int label_nulls = 0;
5989   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5990   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5991   assert(label_nulls <= 1, "at most one NULL in the batch");
5992 
5993   // a couple of useful fields in sub_klass:
5994   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5995   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5996   Address secondary_supers_addr(sub_klass, ss_offset);
5997   Address super_cache_addr(     sub_klass, sc_offset);
5998 
5999   // Do a linear scan of the secondary super-klass chain.
6000   // This code is rarely used, so simplicity is a virtue here.
6001   // The repne_scan instruction uses fixed registers, which we must spill.
6002   // Don't worry too much about pre-existing connections with the input regs.
6003 
6004   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
6005   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
6006 
6007   // Get super_klass value into rax (even if it was in rdi or rcx).
6008   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
6009   if (super_klass != rax || UseCompressedOops) {
6010     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
6011     mov(rax, super_klass);
6012   }
6013   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
6014   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
6015 
6016 #ifndef PRODUCT
6017   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
6018   ExternalAddress pst_counter_addr((address) pst_counter);
6019   NOT_LP64(  incrementl(pst_counter_addr) );
6020   LP64_ONLY( lea(rcx, pst_counter_addr) );
6021   LP64_ONLY( incrementl(Address(rcx, 0)) );
6022 #endif //PRODUCT
6023 
6024   // We will consult the secondary-super array.
6025   movptr(rdi, secondary_supers_addr);
6026   // Load the array length.  (Positive movl does right thing on LP64.)
6027   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
6028   // Skip to start of data.
6029   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
6030 
6031   // Scan RCX words at [RDI] for an occurrence of RAX.
6032   // Set NZ/Z based on last compare.
6033   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
6034   // not change flags (only scas instruction which is repeated sets flags).
6035   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
6036 
6037     testptr(rax,rax); // Set Z = 0
6038     repne_scan();
6039 
6040   // Unspill the temp. registers:
6041   if (pushed_rdi)  pop(rdi);
6042   if (pushed_rcx)  pop(rcx);
6043   if (pushed_rax)  pop(rax);
6044 
6045   if (set_cond_codes) {
6046     // Special hack for the AD files:  rdi is guaranteed non-zero.
6047     assert(!pushed_rdi, "rdi must be left non-NULL");
6048     // Also, the condition codes are properly set Z/NZ on succeed/failure.
6049   }
6050 
6051   if (L_failure == &L_fallthrough)
6052         jccb(Assembler::notEqual, *L_failure);
6053   else  jcc(Assembler::notEqual, *L_failure);
6054 
6055   // Success.  Cache the super we found and proceed in triumph.
6056   movptr(super_cache_addr, super_klass);
6057 
6058   if (L_success != &L_fallthrough) {
6059     jmp(*L_success);
6060   }
6061 
6062 #undef IS_A_TEMP
6063 
6064   bind(L_fallthrough);
6065 }
6066 
6067 
6068 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
6069   if (VM_Version::supports_cmov()) {
6070     cmovl(cc, dst, src);
6071   } else {
6072     Label L;
6073     jccb(negate_condition(cc), L);
6074     movl(dst, src);
6075     bind(L);
6076   }
6077 }
6078 
6079 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
6080   if (VM_Version::supports_cmov()) {
6081     cmovl(cc, dst, src);
6082   } else {
6083     Label L;
6084     jccb(negate_condition(cc), L);
6085     movl(dst, src);
6086     bind(L);
6087   }
6088 }
6089 
6090 void MacroAssembler::verify_oop(Register reg, const char* s) {
6091   if (!VerifyOops || VerifyAdapterSharing) {
6092     // Below address of the code string confuses VerifyAdapterSharing
6093     // because it may differ between otherwise equivalent adapters.
6094     return;
6095   }
6096 
6097   // Pass register number to verify_oop_subroutine
6098   const char* b = NULL;
6099   {
6100     ResourceMark rm;
6101     stringStream ss;
6102     ss.print("verify_oop: %s: %s", reg->name(), s);
6103     b = code_string(ss.as_string());
6104   }
6105   BLOCK_COMMENT("verify_oop {");
6106 #ifdef _LP64
6107   push(rscratch1);                    // save r10, trashed by movptr()
6108 #endif
6109   push(rax);                          // save rax,
6110   push(reg);                          // pass register argument
6111   ExternalAddress buffer((address) b);
6112   // avoid using pushptr, as it modifies scratch registers
6113   // and our contract is not to modify anything
6114   movptr(rax, buffer.addr());
6115   push(rax);
6116   // call indirectly to solve generation ordering problem
6117   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6118   call(rax);
6119   // Caller pops the arguments (oop, message) and restores rax, r10
6120   BLOCK_COMMENT("} verify_oop");
6121 }
6122 
6123 
6124 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
6125                                                       Register tmp,
6126                                                       int offset) {
6127   intptr_t value = *delayed_value_addr;
6128   if (value != 0)
6129     return RegisterOrConstant(value + offset);
6130 
6131   // load indirectly to solve generation ordering problem
6132   movptr(tmp, ExternalAddress((address) delayed_value_addr));
6133 
6134 #ifdef ASSERT
6135   { Label L;
6136     testptr(tmp, tmp);
6137     if (WizardMode) {
6138       const char* buf = NULL;
6139       {
6140         ResourceMark rm;
6141         stringStream ss;
6142         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
6143         buf = code_string(ss.as_string());
6144       }
6145       jcc(Assembler::notZero, L);
6146       STOP(buf);
6147     } else {
6148       jccb(Assembler::notZero, L);
6149       hlt();
6150     }
6151     bind(L);
6152   }
6153 #endif
6154 
6155   if (offset != 0)
6156     addptr(tmp, offset);
6157 
6158   return RegisterOrConstant(tmp);
6159 }
6160 
6161 
6162 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
6163                                          int extra_slot_offset) {
6164   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
6165   int stackElementSize = Interpreter::stackElementSize;
6166   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
6167 #ifdef ASSERT
6168   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
6169   assert(offset1 - offset == stackElementSize, "correct arithmetic");
6170 #endif
6171   Register             scale_reg    = noreg;
6172   Address::ScaleFactor scale_factor = Address::no_scale;
6173   if (arg_slot.is_constant()) {
6174     offset += arg_slot.as_constant() * stackElementSize;
6175   } else {
6176     scale_reg    = arg_slot.as_register();
6177     scale_factor = Address::times(stackElementSize);
6178   }
6179   offset += wordSize;           // return PC is on stack
6180   return Address(rsp, scale_reg, scale_factor, offset);
6181 }
6182 
6183 
6184 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
6185   if (!VerifyOops || VerifyAdapterSharing) {
6186     // Below address of the code string confuses VerifyAdapterSharing
6187     // because it may differ between otherwise equivalent adapters.
6188     return;
6189   }
6190 
6191   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
6192   // Pass register number to verify_oop_subroutine
6193   const char* b = NULL;
6194   {
6195     ResourceMark rm;
6196     stringStream ss;
6197     ss.print("verify_oop_addr: %s", s);
6198     b = code_string(ss.as_string());
6199   }
6200 #ifdef _LP64
6201   push(rscratch1);                    // save r10, trashed by movptr()
6202 #endif
6203   push(rax);                          // save rax,
6204   // addr may contain rsp so we will have to adjust it based on the push
6205   // we just did (and on 64 bit we do two pushes)
6206   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
6207   // stores rax into addr which is backwards of what was intended.
6208   if (addr.uses(rsp)) {
6209     lea(rax, addr);
6210     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
6211   } else {
6212     pushptr(addr);
6213   }
6214 
6215   ExternalAddress buffer((address) b);
6216   // pass msg argument
6217   // avoid using pushptr, as it modifies scratch registers
6218   // and our contract is not to modify anything
6219   movptr(rax, buffer.addr());
6220   push(rax);
6221 
6222   // call indirectly to solve generation ordering problem
6223   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
6224   call(rax);
6225   // Caller pops the arguments (addr, message) and restores rax, r10.
6226 }
6227 
6228 void MacroAssembler::verify_tlab() {
6229 #ifdef ASSERT
6230   if (UseTLAB && VerifyOops) {
6231     Label next, ok;
6232     Register t1 = rsi;
6233     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
6234 
6235     push(t1);
6236     NOT_LP64(push(thread_reg));
6237     NOT_LP64(get_thread(thread_reg));
6238 
6239     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6240     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
6241     jcc(Assembler::aboveEqual, next);
6242     STOP("assert(top >= start)");
6243     should_not_reach_here();
6244 
6245     bind(next);
6246     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
6247     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
6248     jcc(Assembler::aboveEqual, ok);
6249     STOP("assert(top <= end)");
6250     should_not_reach_here();
6251 
6252     bind(ok);
6253     NOT_LP64(pop(thread_reg));
6254     pop(t1);
6255   }
6256 #endif
6257 }
6258 
6259 class ControlWord {
6260  public:
6261   int32_t _value;
6262 
6263   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
6264   int  precision_control() const       { return  (_value >>  8) & 3      ; }
6265   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6266   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6267   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6268   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6269   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6270   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6271 
6272   void print() const {
6273     // rounding control
6274     const char* rc;
6275     switch (rounding_control()) {
6276       case 0: rc = "round near"; break;
6277       case 1: rc = "round down"; break;
6278       case 2: rc = "round up  "; break;
6279       case 3: rc = "chop      "; break;
6280     };
6281     // precision control
6282     const char* pc;
6283     switch (precision_control()) {
6284       case 0: pc = "24 bits "; break;
6285       case 1: pc = "reserved"; break;
6286       case 2: pc = "53 bits "; break;
6287       case 3: pc = "64 bits "; break;
6288     };
6289     // flags
6290     char f[9];
6291     f[0] = ' ';
6292     f[1] = ' ';
6293     f[2] = (precision   ()) ? 'P' : 'p';
6294     f[3] = (underflow   ()) ? 'U' : 'u';
6295     f[4] = (overflow    ()) ? 'O' : 'o';
6296     f[5] = (zero_divide ()) ? 'Z' : 'z';
6297     f[6] = (denormalized()) ? 'D' : 'd';
6298     f[7] = (invalid     ()) ? 'I' : 'i';
6299     f[8] = '\x0';
6300     // output
6301     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6302   }
6303 
6304 };
6305 
6306 class StatusWord {
6307  public:
6308   int32_t _value;
6309 
6310   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6311   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6312   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6313   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6314   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6315   int  top() const                     { return  (_value >> 11) & 7      ; }
6316   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6317   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6318   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6319   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6320   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6321   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6322   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6323   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6324 
6325   void print() const {
6326     // condition codes
6327     char c[5];
6328     c[0] = (C3()) ? '3' : '-';
6329     c[1] = (C2()) ? '2' : '-';
6330     c[2] = (C1()) ? '1' : '-';
6331     c[3] = (C0()) ? '0' : '-';
6332     c[4] = '\x0';
6333     // flags
6334     char f[9];
6335     f[0] = (error_status()) ? 'E' : '-';
6336     f[1] = (stack_fault ()) ? 'S' : '-';
6337     f[2] = (precision   ()) ? 'P' : '-';
6338     f[3] = (underflow   ()) ? 'U' : '-';
6339     f[4] = (overflow    ()) ? 'O' : '-';
6340     f[5] = (zero_divide ()) ? 'Z' : '-';
6341     f[6] = (denormalized()) ? 'D' : '-';
6342     f[7] = (invalid     ()) ? 'I' : '-';
6343     f[8] = '\x0';
6344     // output
6345     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6346   }
6347 
6348 };
6349 
6350 class TagWord {
6351  public:
6352   int32_t _value;
6353 
6354   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6355 
6356   void print() const {
6357     printf("%04x", _value & 0xFFFF);
6358   }
6359 
6360 };
6361 
6362 class FPU_Register {
6363  public:
6364   int32_t _m0;
6365   int32_t _m1;
6366   int16_t _ex;
6367 
6368   bool is_indefinite() const           {
6369     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6370   }
6371 
6372   void print() const {
6373     char  sign = (_ex < 0) ? '-' : '+';
6374     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6375     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6376   };
6377 
6378 };
6379 
6380 class FPU_State {
6381  public:
6382   enum {
6383     register_size       = 10,
6384     number_of_registers =  8,
6385     register_mask       =  7
6386   };
6387 
6388   ControlWord  _control_word;
6389   StatusWord   _status_word;
6390   TagWord      _tag_word;
6391   int32_t      _error_offset;
6392   int32_t      _error_selector;
6393   int32_t      _data_offset;
6394   int32_t      _data_selector;
6395   int8_t       _register[register_size * number_of_registers];
6396 
6397   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6398   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6399 
6400   const char* tag_as_string(int tag) const {
6401     switch (tag) {
6402       case 0: return "valid";
6403       case 1: return "zero";
6404       case 2: return "special";
6405       case 3: return "empty";
6406     }
6407     ShouldNotReachHere();
6408     return NULL;
6409   }
6410 
6411   void print() const {
6412     // print computation registers
6413     { int t = _status_word.top();
6414       for (int i = 0; i < number_of_registers; i++) {
6415         int j = (i - t) & register_mask;
6416         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6417         st(j)->print();
6418         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6419       }
6420     }
6421     printf("\n");
6422     // print control registers
6423     printf("ctrl = "); _control_word.print(); printf("\n");
6424     printf("stat = "); _status_word .print(); printf("\n");
6425     printf("tags = "); _tag_word    .print(); printf("\n");
6426   }
6427 
6428 };
6429 
6430 class Flag_Register {
6431  public:
6432   int32_t _value;
6433 
6434   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6435   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6436   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6437   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6438   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6439   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6440   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6441 
6442   void print() const {
6443     // flags
6444     char f[8];
6445     f[0] = (overflow       ()) ? 'O' : '-';
6446     f[1] = (direction      ()) ? 'D' : '-';
6447     f[2] = (sign           ()) ? 'S' : '-';
6448     f[3] = (zero           ()) ? 'Z' : '-';
6449     f[4] = (auxiliary_carry()) ? 'A' : '-';
6450     f[5] = (parity         ()) ? 'P' : '-';
6451     f[6] = (carry          ()) ? 'C' : '-';
6452     f[7] = '\x0';
6453     // output
6454     printf("%08x  flags = %s", _value, f);
6455   }
6456 
6457 };
6458 
6459 class IU_Register {
6460  public:
6461   int32_t _value;
6462 
6463   void print() const {
6464     printf("%08x  %11d", _value, _value);
6465   }
6466 
6467 };
6468 
6469 class IU_State {
6470  public:
6471   Flag_Register _eflags;
6472   IU_Register   _rdi;
6473   IU_Register   _rsi;
6474   IU_Register   _rbp;
6475   IU_Register   _rsp;
6476   IU_Register   _rbx;
6477   IU_Register   _rdx;
6478   IU_Register   _rcx;
6479   IU_Register   _rax;
6480 
6481   void print() const {
6482     // computation registers
6483     printf("rax,  = "); _rax.print(); printf("\n");
6484     printf("rbx,  = "); _rbx.print(); printf("\n");
6485     printf("rcx  = "); _rcx.print(); printf("\n");
6486     printf("rdx  = "); _rdx.print(); printf("\n");
6487     printf("rdi  = "); _rdi.print(); printf("\n");
6488     printf("rsi  = "); _rsi.print(); printf("\n");
6489     printf("rbp,  = "); _rbp.print(); printf("\n");
6490     printf("rsp  = "); _rsp.print(); printf("\n");
6491     printf("\n");
6492     // control registers
6493     printf("flgs = "); _eflags.print(); printf("\n");
6494   }
6495 };
6496 
6497 
6498 class CPU_State {
6499  public:
6500   FPU_State _fpu_state;
6501   IU_State  _iu_state;
6502 
6503   void print() const {
6504     printf("--------------------------------------------------\n");
6505     _iu_state .print();
6506     printf("\n");
6507     _fpu_state.print();
6508     printf("--------------------------------------------------\n");
6509   }
6510 
6511 };
6512 
6513 
6514 static void _print_CPU_state(CPU_State* state) {
6515   state->print();
6516 };
6517 
6518 
6519 void MacroAssembler::print_CPU_state() {
6520   push_CPU_state();
6521   push(rsp);                // pass CPU state
6522   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6523   addptr(rsp, wordSize);       // discard argument
6524   pop_CPU_state();
6525 }
6526 
6527 
6528 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6529   static int counter = 0;
6530   FPU_State* fs = &state->_fpu_state;
6531   counter++;
6532   // For leaf calls, only verify that the top few elements remain empty.
6533   // We only need 1 empty at the top for C2 code.
6534   if( stack_depth < 0 ) {
6535     if( fs->tag_for_st(7) != 3 ) {
6536       printf("FPR7 not empty\n");
6537       state->print();
6538       assert(false, "error");
6539       return false;
6540     }
6541     return true;                // All other stack states do not matter
6542   }
6543 
6544   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6545          "bad FPU control word");
6546 
6547   // compute stack depth
6548   int i = 0;
6549   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6550   int d = i;
6551   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6552   // verify findings
6553   if (i != FPU_State::number_of_registers) {
6554     // stack not contiguous
6555     printf("%s: stack not contiguous at ST%d\n", s, i);
6556     state->print();
6557     assert(false, "error");
6558     return false;
6559   }
6560   // check if computed stack depth corresponds to expected stack depth
6561   if (stack_depth < 0) {
6562     // expected stack depth is -stack_depth or less
6563     if (d > -stack_depth) {
6564       // too many elements on the stack
6565       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6566       state->print();
6567       assert(false, "error");
6568       return false;
6569     }
6570   } else {
6571     // expected stack depth is stack_depth
6572     if (d != stack_depth) {
6573       // wrong stack depth
6574       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6575       state->print();
6576       assert(false, "error");
6577       return false;
6578     }
6579   }
6580   // everything is cool
6581   return true;
6582 }
6583 
6584 
6585 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6586   if (!VerifyFPU) return;
6587   push_CPU_state();
6588   push(rsp);                // pass CPU state
6589   ExternalAddress msg((address) s);
6590   // pass message string s
6591   pushptr(msg.addr());
6592   push(stack_depth);        // pass stack depth
6593   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6594   addptr(rsp, 3 * wordSize);   // discard arguments
6595   // check for error
6596   { Label L;
6597     testl(rax, rax);
6598     jcc(Assembler::notZero, L);
6599     int3();                  // break if error condition
6600     bind(L);
6601   }
6602   pop_CPU_state();
6603 }
6604 
6605 void MacroAssembler::restore_cpu_control_state_after_jni() {
6606   // Either restore the MXCSR register after returning from the JNI Call
6607   // or verify that it wasn't changed (with -Xcheck:jni flag).
6608   if (VM_Version::supports_sse()) {
6609     if (RestoreMXCSROnJNICalls) {
6610       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6611     } else if (CheckJNICalls) {
6612       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6613     }
6614   }
6615   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6616   vzeroupper();
6617   // Reset k1 to 0xffff.
6618   if (VM_Version::supports_evex()) {
6619     push(rcx);
6620     movl(rcx, 0xffff);
6621     kmovwl(k1, rcx);
6622     pop(rcx);
6623   }
6624 
6625 #ifndef _LP64
6626   // Either restore the x87 floating pointer control word after returning
6627   // from the JNI call or verify that it wasn't changed.
6628   if (CheckJNICalls) {
6629     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6630   }
6631 #endif // _LP64
6632 }
6633 
6634 // ((OopHandle)result).resolve();
6635 void MacroAssembler::resolve_oop_handle(Register result) {
6636   // OopHandle::resolve is an indirection.
6637   movptr(result, Address(result, 0));
6638 }
6639 
6640 void MacroAssembler::load_mirror(Register mirror, Register method) {
6641   // get mirror
6642   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6643   movptr(mirror, Address(method, Method::const_offset()));
6644   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6645   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6646   movptr(mirror, Address(mirror, mirror_offset));
6647   resolve_oop_handle(mirror);
6648 }
6649 
6650 void MacroAssembler::load_klass(Register dst, Register src) {
6651 #ifdef _LP64
6652   if (UseCompressedClassPointers) {
6653     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6654     decode_klass_not_null(dst);
6655   } else
6656 #endif
6657     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6658 }
6659 
6660 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6661   load_klass(dst, src);
6662   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6663 }
6664 
6665 void MacroAssembler::store_klass(Register dst, Register src) {
6666 #ifdef _LP64
6667   if (UseCompressedClassPointers) {
6668     encode_klass_not_null(src);
6669     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6670   } else
6671 #endif
6672     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6673 }
6674 
6675 void MacroAssembler::load_heap_oop(Register dst, Address src) {
6676 #ifdef _LP64
6677   // FIXME: Must change all places where we try to load the klass.
6678   if (UseCompressedOops) {
6679     movl(dst, src);
6680     decode_heap_oop(dst);
6681   } else
6682 #endif
6683     movptr(dst, src);
6684 }
6685 
6686 // Doesn't do verfication, generates fixed size code
6687 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src) {
6688 #ifdef _LP64
6689   if (UseCompressedOops) {
6690     movl(dst, src);
6691     decode_heap_oop_not_null(dst);
6692   } else
6693 #endif
6694     movptr(dst, src);
6695 }
6696 
6697 void MacroAssembler::store_heap_oop(Address dst, Register src) {
6698 #ifdef _LP64
6699   if (UseCompressedOops) {
6700     assert(!dst.uses(src), "not enough registers");
6701     encode_heap_oop(src);
6702     movl(dst, src);
6703   } else
6704 #endif
6705     movptr(dst, src);
6706 }
6707 
6708 void MacroAssembler::cmp_heap_oop(Register src1, Address src2, Register tmp) {
6709   assert_different_registers(src1, tmp);
6710 #ifdef _LP64
6711   if (UseCompressedOops) {
6712     bool did_push = false;
6713     if (tmp == noreg) {
6714       tmp = rax;
6715       push(tmp);
6716       did_push = true;
6717       assert(!src2.uses(rsp), "can't push");
6718     }
6719     load_heap_oop(tmp, src2);
6720     cmpptr(src1, tmp);
6721     if (did_push)  pop(tmp);
6722   } else
6723 #endif
6724     cmpptr(src1, src2);
6725 }
6726 
6727 // Used for storing NULLs.
6728 void MacroAssembler::store_heap_oop_null(Address dst) {
6729 #ifdef _LP64
6730   if (UseCompressedOops) {
6731     movl(dst, (int32_t)NULL_WORD);
6732   } else {
6733     movslq(dst, (int32_t)NULL_WORD);
6734   }
6735 #else
6736   movl(dst, (int32_t)NULL_WORD);
6737 #endif
6738 }
6739 
6740 #ifdef _LP64
6741 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6742   if (UseCompressedClassPointers) {
6743     // Store to klass gap in destination
6744     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6745   }
6746 }
6747 
6748 #ifdef ASSERT
6749 void MacroAssembler::verify_heapbase(const char* msg) {
6750   assert (UseCompressedOops, "should be compressed");
6751   assert (Universe::heap() != NULL, "java heap should be initialized");
6752   if (CheckCompressedOops) {
6753     Label ok;
6754     push(rscratch1); // cmpptr trashes rscratch1
6755     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6756     jcc(Assembler::equal, ok);
6757     STOP(msg);
6758     bind(ok);
6759     pop(rscratch1);
6760   }
6761 }
6762 #endif
6763 
6764 // Algorithm must match oop.inline.hpp encode_heap_oop.
6765 void MacroAssembler::encode_heap_oop(Register r) {
6766 #ifdef ASSERT
6767   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6768 #endif
6769   verify_oop(r, "broken oop in encode_heap_oop");
6770   if (Universe::narrow_oop_base() == NULL) {
6771     if (Universe::narrow_oop_shift() != 0) {
6772       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6773       shrq(r, LogMinObjAlignmentInBytes);
6774     }
6775     return;
6776   }
6777   testq(r, r);
6778   cmovq(Assembler::equal, r, r12_heapbase);
6779   subq(r, r12_heapbase);
6780   shrq(r, LogMinObjAlignmentInBytes);
6781 }
6782 
6783 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6784 #ifdef ASSERT
6785   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6786   if (CheckCompressedOops) {
6787     Label ok;
6788     testq(r, r);
6789     jcc(Assembler::notEqual, ok);
6790     STOP("null oop passed to encode_heap_oop_not_null");
6791     bind(ok);
6792   }
6793 #endif
6794   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6795   if (Universe::narrow_oop_base() != NULL) {
6796     subq(r, r12_heapbase);
6797   }
6798   if (Universe::narrow_oop_shift() != 0) {
6799     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6800     shrq(r, LogMinObjAlignmentInBytes);
6801   }
6802 }
6803 
6804 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6805 #ifdef ASSERT
6806   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6807   if (CheckCompressedOops) {
6808     Label ok;
6809     testq(src, src);
6810     jcc(Assembler::notEqual, ok);
6811     STOP("null oop passed to encode_heap_oop_not_null2");
6812     bind(ok);
6813   }
6814 #endif
6815   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6816   if (dst != src) {
6817     movq(dst, src);
6818   }
6819   if (Universe::narrow_oop_base() != NULL) {
6820     subq(dst, r12_heapbase);
6821   }
6822   if (Universe::narrow_oop_shift() != 0) {
6823     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6824     shrq(dst, LogMinObjAlignmentInBytes);
6825   }
6826 }
6827 
6828 void  MacroAssembler::decode_heap_oop(Register r) {
6829 #ifdef ASSERT
6830   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6831 #endif
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       shlq(r, LogMinObjAlignmentInBytes);
6836     }
6837   } else {
6838     Label done;
6839     shlq(r, LogMinObjAlignmentInBytes);
6840     jccb(Assembler::equal, done);
6841     addq(r, r12_heapbase);
6842     bind(done);
6843   }
6844   verify_oop(r, "broken oop in decode_heap_oop");
6845 }
6846 
6847 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6848   // Note: it will change flags
6849   assert (UseCompressedOops, "should only be used for compressed headers");
6850   assert (Universe::heap() != NULL, "java heap should be initialized");
6851   // Cannot assert, unverified entry point counts instructions (see .ad file)
6852   // vtableStubs also counts instructions in pd_code_size_limit.
6853   // Also do not verify_oop as this is called by verify_oop.
6854   if (Universe::narrow_oop_shift() != 0) {
6855     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6856     shlq(r, LogMinObjAlignmentInBytes);
6857     if (Universe::narrow_oop_base() != NULL) {
6858       addq(r, r12_heapbase);
6859     }
6860   } else {
6861     assert (Universe::narrow_oop_base() == NULL, "sanity");
6862   }
6863 }
6864 
6865 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6866   // Note: it will change flags
6867   assert (UseCompressedOops, "should only be used for compressed headers");
6868   assert (Universe::heap() != NULL, "java heap should be initialized");
6869   // Cannot assert, unverified entry point counts instructions (see .ad file)
6870   // vtableStubs also counts instructions in pd_code_size_limit.
6871   // Also do not verify_oop as this is called by verify_oop.
6872   if (Universe::narrow_oop_shift() != 0) {
6873     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6874     if (LogMinObjAlignmentInBytes == Address::times_8) {
6875       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6876     } else {
6877       if (dst != src) {
6878         movq(dst, src);
6879       }
6880       shlq(dst, LogMinObjAlignmentInBytes);
6881       if (Universe::narrow_oop_base() != NULL) {
6882         addq(dst, r12_heapbase);
6883       }
6884     }
6885   } else {
6886     assert (Universe::narrow_oop_base() == NULL, "sanity");
6887     if (dst != src) {
6888       movq(dst, src);
6889     }
6890   }
6891 }
6892 
6893 void MacroAssembler::encode_klass_not_null(Register r) {
6894   if (Universe::narrow_klass_base() != NULL) {
6895     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6896     assert(r != r12_heapbase, "Encoding a klass in r12");
6897     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6898     subq(r, r12_heapbase);
6899   }
6900   if (Universe::narrow_klass_shift() != 0) {
6901     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6902     shrq(r, LogKlassAlignmentInBytes);
6903   }
6904   if (Universe::narrow_klass_base() != NULL) {
6905     reinit_heapbase();
6906   }
6907 }
6908 
6909 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6910   if (dst == src) {
6911     encode_klass_not_null(src);
6912   } else {
6913     if (Universe::narrow_klass_base() != NULL) {
6914       mov64(dst, (int64_t)Universe::narrow_klass_base());
6915       negq(dst);
6916       addq(dst, src);
6917     } else {
6918       movptr(dst, src);
6919     }
6920     if (Universe::narrow_klass_shift() != 0) {
6921       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6922       shrq(dst, LogKlassAlignmentInBytes);
6923     }
6924   }
6925 }
6926 
6927 // Function instr_size_for_decode_klass_not_null() counts the instructions
6928 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6929 // when (Universe::heap() != NULL).  Hence, if the instructions they
6930 // generate change, then this method needs to be updated.
6931 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6932   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6933   if (Universe::narrow_klass_base() != NULL) {
6934     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6935     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6936   } else {
6937     // longest load decode klass function, mov64, leaq
6938     return 16;
6939   }
6940 }
6941 
6942 // !!! If the instructions that get generated here change then function
6943 // instr_size_for_decode_klass_not_null() needs to get updated.
6944 void  MacroAssembler::decode_klass_not_null(Register r) {
6945   // Note: it will change flags
6946   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6947   assert(r != r12_heapbase, "Decoding a klass in r12");
6948   // Cannot assert, unverified entry point counts instructions (see .ad file)
6949   // vtableStubs also counts instructions in pd_code_size_limit.
6950   // Also do not verify_oop as this is called by verify_oop.
6951   if (Universe::narrow_klass_shift() != 0) {
6952     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6953     shlq(r, LogKlassAlignmentInBytes);
6954   }
6955   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6956   if (Universe::narrow_klass_base() != NULL) {
6957     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6958     addq(r, r12_heapbase);
6959     reinit_heapbase();
6960   }
6961 }
6962 
6963 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6964   // Note: it will change flags
6965   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6966   if (dst == src) {
6967     decode_klass_not_null(dst);
6968   } else {
6969     // Cannot assert, unverified entry point counts instructions (see .ad file)
6970     // vtableStubs also counts instructions in pd_code_size_limit.
6971     // Also do not verify_oop as this is called by verify_oop.
6972     mov64(dst, (int64_t)Universe::narrow_klass_base());
6973     if (Universe::narrow_klass_shift() != 0) {
6974       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6975       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6976       leaq(dst, Address(dst, src, Address::times_8, 0));
6977     } else {
6978       addq(dst, src);
6979     }
6980   }
6981 }
6982 
6983 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6984   assert (UseCompressedOops, "should only be used for compressed headers");
6985   assert (Universe::heap() != NULL, "java heap should be initialized");
6986   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6987   int oop_index = oop_recorder()->find_index(obj);
6988   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6989   mov_narrow_oop(dst, oop_index, rspec);
6990 }
6991 
6992 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6993   assert (UseCompressedOops, "should only be used for compressed headers");
6994   assert (Universe::heap() != NULL, "java heap should be initialized");
6995   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6996   int oop_index = oop_recorder()->find_index(obj);
6997   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6998   mov_narrow_oop(dst, oop_index, rspec);
6999 }
7000 
7001 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
7002   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7003   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7004   int klass_index = oop_recorder()->find_index(k);
7005   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7006   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7007 }
7008 
7009 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
7010   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7011   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7012   int klass_index = oop_recorder()->find_index(k);
7013   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7014   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
7015 }
7016 
7017 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
7018   assert (UseCompressedOops, "should only be used for compressed headers");
7019   assert (Universe::heap() != NULL, "java heap should be initialized");
7020   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7021   int oop_index = oop_recorder()->find_index(obj);
7022   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7023   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7024 }
7025 
7026 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
7027   assert (UseCompressedOops, "should only be used for compressed headers");
7028   assert (Universe::heap() != NULL, "java heap should be initialized");
7029   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7030   int oop_index = oop_recorder()->find_index(obj);
7031   RelocationHolder rspec = oop_Relocation::spec(oop_index);
7032   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
7033 }
7034 
7035 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
7036   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7037   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7038   int klass_index = oop_recorder()->find_index(k);
7039   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7040   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7041 }
7042 
7043 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
7044   assert (UseCompressedClassPointers, "should only be used for compressed headers");
7045   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
7046   int klass_index = oop_recorder()->find_index(k);
7047   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
7048   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
7049 }
7050 
7051 void MacroAssembler::reinit_heapbase() {
7052   if (UseCompressedOops || UseCompressedClassPointers) {
7053     if (Universe::heap() != NULL) {
7054       if (Universe::narrow_oop_base() == NULL) {
7055         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
7056       } else {
7057         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
7058       }
7059     } else {
7060       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
7061     }
7062   }
7063 }
7064 
7065 #endif // _LP64
7066 
7067 // C2 compiled method's prolog code.
7068 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
7069 
7070   // WARNING: Initial instruction MUST be 5 bytes or longer so that
7071   // NativeJump::patch_verified_entry will be able to patch out the entry
7072   // code safely. The push to verify stack depth is ok at 5 bytes,
7073   // the frame allocation can be either 3 or 6 bytes. So if we don't do
7074   // stack bang then we must use the 6 byte frame allocation even if
7075   // we have no frame. :-(
7076   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
7077 
7078   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
7079   // Remove word for return addr
7080   framesize -= wordSize;
7081   stack_bang_size -= wordSize;
7082 
7083   // Calls to C2R adapters often do not accept exceptional returns.
7084   // We require that their callers must bang for them.  But be careful, because
7085   // some VM calls (such as call site linkage) can use several kilobytes of
7086   // stack.  But the stack safety zone should account for that.
7087   // See bugs 4446381, 4468289, 4497237.
7088   if (stack_bang_size > 0) {
7089     generate_stack_overflow_check(stack_bang_size);
7090 
7091     // We always push rbp, so that on return to interpreter rbp, will be
7092     // restored correctly and we can correct the stack.
7093     push(rbp);
7094     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7095     if (PreserveFramePointer) {
7096       mov(rbp, rsp);
7097     }
7098     // Remove word for ebp
7099     framesize -= wordSize;
7100 
7101     // Create frame
7102     if (framesize) {
7103       subptr(rsp, framesize);
7104     }
7105   } else {
7106     // Create frame (force generation of a 4 byte immediate value)
7107     subptr_imm32(rsp, framesize);
7108 
7109     // Save RBP register now.
7110     framesize -= wordSize;
7111     movptr(Address(rsp, framesize), rbp);
7112     // Save caller's stack pointer into RBP if the frame pointer is preserved.
7113     if (PreserveFramePointer) {
7114       movptr(rbp, rsp);
7115       if (framesize > 0) {
7116         addptr(rbp, framesize);
7117       }
7118     }
7119   }
7120 
7121   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
7122     framesize -= wordSize;
7123     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
7124   }
7125 
7126 #ifndef _LP64
7127   // If method sets FPU control word do it now
7128   if (fp_mode_24b) {
7129     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
7130   }
7131   if (UseSSE >= 2 && VerifyFPU) {
7132     verify_FPU(0, "FPU stack must be clean on entry");
7133   }
7134 #endif
7135 
7136 #ifdef ASSERT
7137   if (VerifyStackAtCalls) {
7138     Label L;
7139     push(rax);
7140     mov(rax, rsp);
7141     andptr(rax, StackAlignmentInBytes-1);
7142     cmpptr(rax, StackAlignmentInBytes-wordSize);
7143     pop(rax);
7144     jcc(Assembler::equal, L);
7145     STOP("Stack is not properly aligned!");
7146     bind(L);
7147   }
7148 #endif
7149 
7150 }
7151 
7152 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
7153   // cnt - number of qwords (8-byte words).
7154   // base - start address, qword aligned.
7155   // is_large - if optimizers know cnt is larger than InitArrayShortSize
7156   assert(base==rdi, "base register must be edi for rep stos");
7157   assert(tmp==rax,   "tmp register must be eax for rep stos");
7158   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
7159   assert(InitArrayShortSize % BytesPerLong == 0,
7160     "InitArrayShortSize should be the multiple of BytesPerLong");
7161 
7162   Label DONE;
7163 
7164   xorptr(tmp, tmp);
7165 
7166   if (!is_large) {
7167     Label LOOP, LONG;
7168     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
7169     jccb(Assembler::greater, LONG);
7170 
7171     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7172 
7173     decrement(cnt);
7174     jccb(Assembler::negative, DONE); // Zero length
7175 
7176     // Use individual pointer-sized stores for small counts:
7177     BIND(LOOP);
7178     movptr(Address(base, cnt, Address::times_ptr), tmp);
7179     decrement(cnt);
7180     jccb(Assembler::greaterEqual, LOOP);
7181     jmpb(DONE);
7182 
7183     BIND(LONG);
7184   }
7185 
7186   // Use longer rep-prefixed ops for non-small counts:
7187   if (UseFastStosb) {
7188     shlptr(cnt, 3); // convert to number of bytes
7189     rep_stosb();
7190   } else {
7191     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
7192     rep_stos();
7193   }
7194 
7195   BIND(DONE);
7196 }
7197 
7198 #ifdef COMPILER2
7199 
7200 // IndexOf for constant substrings with size >= 8 chars
7201 // which don't need to be loaded through stack.
7202 void MacroAssembler::string_indexofC8(Register str1, Register str2,
7203                                       Register cnt1, Register cnt2,
7204                                       int int_cnt2,  Register result,
7205                                       XMMRegister vec, Register tmp,
7206                                       int ae) {
7207   ShortBranchVerifier sbv(this);
7208   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7209   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7210 
7211   // This method uses the pcmpestri instruction with bound registers
7212   //   inputs:
7213   //     xmm - substring
7214   //     rax - substring length (elements count)
7215   //     mem - scanned string
7216   //     rdx - string length (elements count)
7217   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7218   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7219   //   outputs:
7220   //     rcx - matched index in string
7221   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7222   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7223   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7224   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7225   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7226 
7227   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
7228         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
7229         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
7230 
7231   // Note, inline_string_indexOf() generates checks:
7232   // if (substr.count > string.count) return -1;
7233   // if (substr.count == 0) return 0;
7234   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
7235 
7236   // Load substring.
7237   if (ae == StrIntrinsicNode::UL) {
7238     pmovzxbw(vec, Address(str2, 0));
7239   } else {
7240     movdqu(vec, Address(str2, 0));
7241   }
7242   movl(cnt2, int_cnt2);
7243   movptr(result, str1); // string addr
7244 
7245   if (int_cnt2 > stride) {
7246     jmpb(SCAN_TO_SUBSTR);
7247 
7248     // Reload substr for rescan, this code
7249     // is executed only for large substrings (> 8 chars)
7250     bind(RELOAD_SUBSTR);
7251     if (ae == StrIntrinsicNode::UL) {
7252       pmovzxbw(vec, Address(str2, 0));
7253     } else {
7254       movdqu(vec, Address(str2, 0));
7255     }
7256     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
7257 
7258     bind(RELOAD_STR);
7259     // We came here after the beginning of the substring was
7260     // matched but the rest of it was not so we need to search
7261     // again. Start from the next element after the previous match.
7262 
7263     // cnt2 is number of substring reminding elements and
7264     // cnt1 is number of string reminding elements when cmp failed.
7265     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
7266     subl(cnt1, cnt2);
7267     addl(cnt1, int_cnt2);
7268     movl(cnt2, int_cnt2); // Now restore cnt2
7269 
7270     decrementl(cnt1);     // Shift to next element
7271     cmpl(cnt1, cnt2);
7272     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7273 
7274     addptr(result, (1<<scale1));
7275 
7276   } // (int_cnt2 > 8)
7277 
7278   // Scan string for start of substr in 16-byte vectors
7279   bind(SCAN_TO_SUBSTR);
7280   pcmpestri(vec, Address(result, 0), mode);
7281   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7282   subl(cnt1, stride);
7283   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7284   cmpl(cnt1, cnt2);
7285   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7286   addptr(result, 16);
7287   jmpb(SCAN_TO_SUBSTR);
7288 
7289   // Found a potential substr
7290   bind(FOUND_CANDIDATE);
7291   // Matched whole vector if first element matched (tmp(rcx) == 0).
7292   if (int_cnt2 == stride) {
7293     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7294   } else { // int_cnt2 > 8
7295     jccb(Assembler::overflow, FOUND_SUBSTR);
7296   }
7297   // After pcmpestri tmp(rcx) contains matched element index
7298   // Compute start addr of substr
7299   lea(result, Address(result, tmp, scale1));
7300 
7301   // Make sure string is still long enough
7302   subl(cnt1, tmp);
7303   cmpl(cnt1, cnt2);
7304   if (int_cnt2 == stride) {
7305     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7306   } else { // int_cnt2 > 8
7307     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7308   }
7309   // Left less then substring.
7310 
7311   bind(RET_NOT_FOUND);
7312   movl(result, -1);
7313   jmp(EXIT);
7314 
7315   if (int_cnt2 > stride) {
7316     // This code is optimized for the case when whole substring
7317     // is matched if its head is matched.
7318     bind(MATCH_SUBSTR_HEAD);
7319     pcmpestri(vec, Address(result, 0), mode);
7320     // Reload only string if does not match
7321     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7322 
7323     Label CONT_SCAN_SUBSTR;
7324     // Compare the rest of substring (> 8 chars).
7325     bind(FOUND_SUBSTR);
7326     // First 8 chars are already matched.
7327     negptr(cnt2);
7328     addptr(cnt2, stride);
7329 
7330     bind(SCAN_SUBSTR);
7331     subl(cnt1, stride);
7332     cmpl(cnt2, -stride); // Do not read beyond substring
7333     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7334     // Back-up strings to avoid reading beyond substring:
7335     // cnt1 = cnt1 - cnt2 + 8
7336     addl(cnt1, cnt2); // cnt2 is negative
7337     addl(cnt1, stride);
7338     movl(cnt2, stride); negptr(cnt2);
7339     bind(CONT_SCAN_SUBSTR);
7340     if (int_cnt2 < (int)G) {
7341       int tail_off1 = int_cnt2<<scale1;
7342       int tail_off2 = int_cnt2<<scale2;
7343       if (ae == StrIntrinsicNode::UL) {
7344         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7345       } else {
7346         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7347       }
7348       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7349     } else {
7350       // calculate index in register to avoid integer overflow (int_cnt2*2)
7351       movl(tmp, int_cnt2);
7352       addptr(tmp, cnt2);
7353       if (ae == StrIntrinsicNode::UL) {
7354         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7355       } else {
7356         movdqu(vec, Address(str2, tmp, scale2, 0));
7357       }
7358       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7359     }
7360     // Need to reload strings pointers if not matched whole vector
7361     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7362     addptr(cnt2, stride);
7363     jcc(Assembler::negative, SCAN_SUBSTR);
7364     // Fall through if found full substring
7365 
7366   } // (int_cnt2 > 8)
7367 
7368   bind(RET_FOUND);
7369   // Found result if we matched full small substring.
7370   // Compute substr offset
7371   subptr(result, str1);
7372   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7373     shrl(result, 1); // index
7374   }
7375   bind(EXIT);
7376 
7377 } // string_indexofC8
7378 
7379 // Small strings are loaded through stack if they cross page boundary.
7380 void MacroAssembler::string_indexof(Register str1, Register str2,
7381                                     Register cnt1, Register cnt2,
7382                                     int int_cnt2,  Register result,
7383                                     XMMRegister vec, Register tmp,
7384                                     int ae) {
7385   ShortBranchVerifier sbv(this);
7386   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7387   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7388 
7389   //
7390   // int_cnt2 is length of small (< 8 chars) constant substring
7391   // or (-1) for non constant substring in which case its length
7392   // is in cnt2 register.
7393   //
7394   // Note, inline_string_indexOf() generates checks:
7395   // if (substr.count > string.count) return -1;
7396   // if (substr.count == 0) return 0;
7397   //
7398   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7399   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7400   // This method uses the pcmpestri instruction with bound registers
7401   //   inputs:
7402   //     xmm - substring
7403   //     rax - substring length (elements count)
7404   //     mem - scanned string
7405   //     rdx - string length (elements count)
7406   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7407   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7408   //   outputs:
7409   //     rcx - matched index in string
7410   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7411   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7412   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7413   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7414 
7415   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7416         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7417         FOUND_CANDIDATE;
7418 
7419   { //========================================================
7420     // We don't know where these strings are located
7421     // and we can't read beyond them. Load them through stack.
7422     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7423 
7424     movptr(tmp, rsp); // save old SP
7425 
7426     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7427       if (int_cnt2 == (1>>scale2)) { // One byte
7428         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7429         load_unsigned_byte(result, Address(str2, 0));
7430         movdl(vec, result); // move 32 bits
7431       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7432         // Not enough header space in 32-bit VM: 12+3 = 15.
7433         movl(result, Address(str2, -1));
7434         shrl(result, 8);
7435         movdl(vec, result); // move 32 bits
7436       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7437         load_unsigned_short(result, Address(str2, 0));
7438         movdl(vec, result); // move 32 bits
7439       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7440         movdl(vec, Address(str2, 0)); // move 32 bits
7441       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7442         movq(vec, Address(str2, 0));  // move 64 bits
7443       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7444         // Array header size is 12 bytes in 32-bit VM
7445         // + 6 bytes for 3 chars == 18 bytes,
7446         // enough space to load vec and shift.
7447         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7448         if (ae == StrIntrinsicNode::UL) {
7449           int tail_off = int_cnt2-8;
7450           pmovzxbw(vec, Address(str2, tail_off));
7451           psrldq(vec, -2*tail_off);
7452         }
7453         else {
7454           int tail_off = int_cnt2*(1<<scale2);
7455           movdqu(vec, Address(str2, tail_off-16));
7456           psrldq(vec, 16-tail_off);
7457         }
7458       }
7459     } else { // not constant substring
7460       cmpl(cnt2, stride);
7461       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7462 
7463       // We can read beyond string if srt+16 does not cross page boundary
7464       // since heaps are aligned and mapped by pages.
7465       assert(os::vm_page_size() < (int)G, "default page should be small");
7466       movl(result, str2); // We need only low 32 bits
7467       andl(result, (os::vm_page_size()-1));
7468       cmpl(result, (os::vm_page_size()-16));
7469       jccb(Assembler::belowEqual, CHECK_STR);
7470 
7471       // Move small strings to stack to allow load 16 bytes into vec.
7472       subptr(rsp, 16);
7473       int stk_offset = wordSize-(1<<scale2);
7474       push(cnt2);
7475 
7476       bind(COPY_SUBSTR);
7477       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7478         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7479         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7480       } else if (ae == StrIntrinsicNode::UU) {
7481         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7482         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7483       }
7484       decrement(cnt2);
7485       jccb(Assembler::notZero, COPY_SUBSTR);
7486 
7487       pop(cnt2);
7488       movptr(str2, rsp);  // New substring address
7489     } // non constant
7490 
7491     bind(CHECK_STR);
7492     cmpl(cnt1, stride);
7493     jccb(Assembler::aboveEqual, BIG_STRINGS);
7494 
7495     // Check cross page boundary.
7496     movl(result, str1); // We need only low 32 bits
7497     andl(result, (os::vm_page_size()-1));
7498     cmpl(result, (os::vm_page_size()-16));
7499     jccb(Assembler::belowEqual, BIG_STRINGS);
7500 
7501     subptr(rsp, 16);
7502     int stk_offset = -(1<<scale1);
7503     if (int_cnt2 < 0) { // not constant
7504       push(cnt2);
7505       stk_offset += wordSize;
7506     }
7507     movl(cnt2, cnt1);
7508 
7509     bind(COPY_STR);
7510     if (ae == StrIntrinsicNode::LL) {
7511       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7512       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7513     } else {
7514       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7515       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7516     }
7517     decrement(cnt2);
7518     jccb(Assembler::notZero, COPY_STR);
7519 
7520     if (int_cnt2 < 0) { // not constant
7521       pop(cnt2);
7522     }
7523     movptr(str1, rsp);  // New string address
7524 
7525     bind(BIG_STRINGS);
7526     // Load substring.
7527     if (int_cnt2 < 0) { // -1
7528       if (ae == StrIntrinsicNode::UL) {
7529         pmovzxbw(vec, Address(str2, 0));
7530       } else {
7531         movdqu(vec, Address(str2, 0));
7532       }
7533       push(cnt2);       // substr count
7534       push(str2);       // substr addr
7535       push(str1);       // string addr
7536     } else {
7537       // Small (< 8 chars) constant substrings are loaded already.
7538       movl(cnt2, int_cnt2);
7539     }
7540     push(tmp);  // original SP
7541 
7542   } // Finished loading
7543 
7544   //========================================================
7545   // Start search
7546   //
7547 
7548   movptr(result, str1); // string addr
7549 
7550   if (int_cnt2  < 0) {  // Only for non constant substring
7551     jmpb(SCAN_TO_SUBSTR);
7552 
7553     // SP saved at sp+0
7554     // String saved at sp+1*wordSize
7555     // Substr saved at sp+2*wordSize
7556     // Substr count saved at sp+3*wordSize
7557 
7558     // Reload substr for rescan, this code
7559     // is executed only for large substrings (> 8 chars)
7560     bind(RELOAD_SUBSTR);
7561     movptr(str2, Address(rsp, 2*wordSize));
7562     movl(cnt2, Address(rsp, 3*wordSize));
7563     if (ae == StrIntrinsicNode::UL) {
7564       pmovzxbw(vec, Address(str2, 0));
7565     } else {
7566       movdqu(vec, Address(str2, 0));
7567     }
7568     // We came here after the beginning of the substring was
7569     // matched but the rest of it was not so we need to search
7570     // again. Start from the next element after the previous match.
7571     subptr(str1, result); // Restore counter
7572     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7573       shrl(str1, 1);
7574     }
7575     addl(cnt1, str1);
7576     decrementl(cnt1);   // Shift to next element
7577     cmpl(cnt1, cnt2);
7578     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7579 
7580     addptr(result, (1<<scale1));
7581   } // non constant
7582 
7583   // Scan string for start of substr in 16-byte vectors
7584   bind(SCAN_TO_SUBSTR);
7585   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7586   pcmpestri(vec, Address(result, 0), mode);
7587   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7588   subl(cnt1, stride);
7589   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7590   cmpl(cnt1, cnt2);
7591   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7592   addptr(result, 16);
7593 
7594   bind(ADJUST_STR);
7595   cmpl(cnt1, stride); // Do not read beyond string
7596   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7597   // Back-up string to avoid reading beyond string.
7598   lea(result, Address(result, cnt1, scale1, -16));
7599   movl(cnt1, stride);
7600   jmpb(SCAN_TO_SUBSTR);
7601 
7602   // Found a potential substr
7603   bind(FOUND_CANDIDATE);
7604   // After pcmpestri tmp(rcx) contains matched element index
7605 
7606   // Make sure string is still long enough
7607   subl(cnt1, tmp);
7608   cmpl(cnt1, cnt2);
7609   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7610   // Left less then substring.
7611 
7612   bind(RET_NOT_FOUND);
7613   movl(result, -1);
7614   jmpb(CLEANUP);
7615 
7616   bind(FOUND_SUBSTR);
7617   // Compute start addr of substr
7618   lea(result, Address(result, tmp, scale1));
7619   if (int_cnt2 > 0) { // Constant substring
7620     // Repeat search for small substring (< 8 chars)
7621     // from new point without reloading substring.
7622     // Have to check that we don't read beyond string.
7623     cmpl(tmp, stride-int_cnt2);
7624     jccb(Assembler::greater, ADJUST_STR);
7625     // Fall through if matched whole substring.
7626   } else { // non constant
7627     assert(int_cnt2 == -1, "should be != 0");
7628 
7629     addl(tmp, cnt2);
7630     // Found result if we matched whole substring.
7631     cmpl(tmp, stride);
7632     jccb(Assembler::lessEqual, RET_FOUND);
7633 
7634     // Repeat search for small substring (<= 8 chars)
7635     // from new point 'str1' without reloading substring.
7636     cmpl(cnt2, stride);
7637     // Have to check that we don't read beyond string.
7638     jccb(Assembler::lessEqual, ADJUST_STR);
7639 
7640     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7641     // Compare the rest of substring (> 8 chars).
7642     movptr(str1, result);
7643 
7644     cmpl(tmp, cnt2);
7645     // First 8 chars are already matched.
7646     jccb(Assembler::equal, CHECK_NEXT);
7647 
7648     bind(SCAN_SUBSTR);
7649     pcmpestri(vec, Address(str1, 0), mode);
7650     // Need to reload strings pointers if not matched whole vector
7651     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7652 
7653     bind(CHECK_NEXT);
7654     subl(cnt2, stride);
7655     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7656     addptr(str1, 16);
7657     if (ae == StrIntrinsicNode::UL) {
7658       addptr(str2, 8);
7659     } else {
7660       addptr(str2, 16);
7661     }
7662     subl(cnt1, stride);
7663     cmpl(cnt2, stride); // Do not read beyond substring
7664     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7665     // Back-up strings to avoid reading beyond substring.
7666 
7667     if (ae == StrIntrinsicNode::UL) {
7668       lea(str2, Address(str2, cnt2, scale2, -8));
7669       lea(str1, Address(str1, cnt2, scale1, -16));
7670     } else {
7671       lea(str2, Address(str2, cnt2, scale2, -16));
7672       lea(str1, Address(str1, cnt2, scale1, -16));
7673     }
7674     subl(cnt1, cnt2);
7675     movl(cnt2, stride);
7676     addl(cnt1, stride);
7677     bind(CONT_SCAN_SUBSTR);
7678     if (ae == StrIntrinsicNode::UL) {
7679       pmovzxbw(vec, Address(str2, 0));
7680     } else {
7681       movdqu(vec, Address(str2, 0));
7682     }
7683     jmp(SCAN_SUBSTR);
7684 
7685     bind(RET_FOUND_LONG);
7686     movptr(str1, Address(rsp, wordSize));
7687   } // non constant
7688 
7689   bind(RET_FOUND);
7690   // Compute substr offset
7691   subptr(result, str1);
7692   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7693     shrl(result, 1); // index
7694   }
7695   bind(CLEANUP);
7696   pop(rsp); // restore SP
7697 
7698 } // string_indexof
7699 
7700 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7701                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7702   ShortBranchVerifier sbv(this);
7703   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7704 
7705   int stride = 8;
7706 
7707   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7708         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7709         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7710         FOUND_SEQ_CHAR, DONE_LABEL;
7711 
7712   movptr(result, str1);
7713   if (UseAVX >= 2) {
7714     cmpl(cnt1, stride);
7715     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7716     cmpl(cnt1, 2*stride);
7717     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7718     movdl(vec1, ch);
7719     vpbroadcastw(vec1, vec1);
7720     vpxor(vec2, vec2);
7721     movl(tmp, cnt1);
7722     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7723     andl(cnt1,0x0000000F);  //tail count (in chars)
7724 
7725     bind(SCAN_TO_16_CHAR_LOOP);
7726     vmovdqu(vec3, Address(result, 0));
7727     vpcmpeqw(vec3, vec3, vec1, 1);
7728     vptest(vec2, vec3);
7729     jcc(Assembler::carryClear, FOUND_CHAR);
7730     addptr(result, 32);
7731     subl(tmp, 2*stride);
7732     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7733     jmp(SCAN_TO_8_CHAR);
7734     bind(SCAN_TO_8_CHAR_INIT);
7735     movdl(vec1, ch);
7736     pshuflw(vec1, vec1, 0x00);
7737     pshufd(vec1, vec1, 0);
7738     pxor(vec2, vec2);
7739   }
7740   bind(SCAN_TO_8_CHAR);
7741   cmpl(cnt1, stride);
7742   if (UseAVX >= 2) {
7743     jcc(Assembler::less, SCAN_TO_CHAR);
7744   } else {
7745     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7746     movdl(vec1, ch);
7747     pshuflw(vec1, vec1, 0x00);
7748     pshufd(vec1, vec1, 0);
7749     pxor(vec2, vec2);
7750   }
7751   movl(tmp, cnt1);
7752   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7753   andl(cnt1,0x00000007);  //tail count (in chars)
7754 
7755   bind(SCAN_TO_8_CHAR_LOOP);
7756   movdqu(vec3, Address(result, 0));
7757   pcmpeqw(vec3, vec1);
7758   ptest(vec2, vec3);
7759   jcc(Assembler::carryClear, FOUND_CHAR);
7760   addptr(result, 16);
7761   subl(tmp, stride);
7762   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7763   bind(SCAN_TO_CHAR);
7764   testl(cnt1, cnt1);
7765   jcc(Assembler::zero, RET_NOT_FOUND);
7766   bind(SCAN_TO_CHAR_LOOP);
7767   load_unsigned_short(tmp, Address(result, 0));
7768   cmpl(ch, tmp);
7769   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7770   addptr(result, 2);
7771   subl(cnt1, 1);
7772   jccb(Assembler::zero, RET_NOT_FOUND);
7773   jmp(SCAN_TO_CHAR_LOOP);
7774 
7775   bind(RET_NOT_FOUND);
7776   movl(result, -1);
7777   jmpb(DONE_LABEL);
7778 
7779   bind(FOUND_CHAR);
7780   if (UseAVX >= 2) {
7781     vpmovmskb(tmp, vec3);
7782   } else {
7783     pmovmskb(tmp, vec3);
7784   }
7785   bsfl(ch, tmp);
7786   addl(result, ch);
7787 
7788   bind(FOUND_SEQ_CHAR);
7789   subptr(result, str1);
7790   shrl(result, 1);
7791 
7792   bind(DONE_LABEL);
7793 } // string_indexof_char
7794 
7795 // helper function for string_compare
7796 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7797                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7798                                         Address::ScaleFactor scale2, Register index, int ae) {
7799   if (ae == StrIntrinsicNode::LL) {
7800     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7801     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7802   } else if (ae == StrIntrinsicNode::UU) {
7803     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7804     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7805   } else {
7806     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7807     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7808   }
7809 }
7810 
7811 // Compare strings, used for char[] and byte[].
7812 void MacroAssembler::string_compare(Register str1, Register str2,
7813                                     Register cnt1, Register cnt2, Register result,
7814                                     XMMRegister vec1, int ae) {
7815   ShortBranchVerifier sbv(this);
7816   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7817   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7818   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7819   int stride2x2 = 0x40;
7820   Address::ScaleFactor scale = Address::no_scale;
7821   Address::ScaleFactor scale1 = Address::no_scale;
7822   Address::ScaleFactor scale2 = Address::no_scale;
7823 
7824   if (ae != StrIntrinsicNode::LL) {
7825     stride2x2 = 0x20;
7826   }
7827 
7828   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7829     shrl(cnt2, 1);
7830   }
7831   // Compute the minimum of the string lengths and the
7832   // difference of the string lengths (stack).
7833   // Do the conditional move stuff
7834   movl(result, cnt1);
7835   subl(cnt1, cnt2);
7836   push(cnt1);
7837   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7838 
7839   // Is the minimum length zero?
7840   testl(cnt2, cnt2);
7841   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7842   if (ae == StrIntrinsicNode::LL) {
7843     // Load first bytes
7844     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7845     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7846   } else if (ae == StrIntrinsicNode::UU) {
7847     // Load first characters
7848     load_unsigned_short(result, Address(str1, 0));
7849     load_unsigned_short(cnt1, Address(str2, 0));
7850   } else {
7851     load_unsigned_byte(result, Address(str1, 0));
7852     load_unsigned_short(cnt1, Address(str2, 0));
7853   }
7854   subl(result, cnt1);
7855   jcc(Assembler::notZero,  POP_LABEL);
7856 
7857   if (ae == StrIntrinsicNode::UU) {
7858     // Divide length by 2 to get number of chars
7859     shrl(cnt2, 1);
7860   }
7861   cmpl(cnt2, 1);
7862   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7863 
7864   // Check if the strings start at the same location and setup scale and stride
7865   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7866     cmpptr(str1, str2);
7867     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7868     if (ae == StrIntrinsicNode::LL) {
7869       scale = Address::times_1;
7870       stride = 16;
7871     } else {
7872       scale = Address::times_2;
7873       stride = 8;
7874     }
7875   } else {
7876     scale1 = Address::times_1;
7877     scale2 = Address::times_2;
7878     // scale not used
7879     stride = 8;
7880   }
7881 
7882   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7883     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7884     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7885     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7886     Label COMPARE_TAIL_LONG;
7887     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7888 
7889     int pcmpmask = 0x19;
7890     if (ae == StrIntrinsicNode::LL) {
7891       pcmpmask &= ~0x01;
7892     }
7893 
7894     // Setup to compare 16-chars (32-bytes) vectors,
7895     // start from first character again because it has aligned address.
7896     if (ae == StrIntrinsicNode::LL) {
7897       stride2 = 32;
7898     } else {
7899       stride2 = 16;
7900     }
7901     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7902       adr_stride = stride << scale;
7903     } else {
7904       adr_stride1 = 8;  //stride << scale1;
7905       adr_stride2 = 16; //stride << scale2;
7906     }
7907 
7908     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7909     // rax and rdx are used by pcmpestri as elements counters
7910     movl(result, cnt2);
7911     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7912     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7913 
7914     // fast path : compare first 2 8-char vectors.
7915     bind(COMPARE_16_CHARS);
7916     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7917       movdqu(vec1, Address(str1, 0));
7918     } else {
7919       pmovzxbw(vec1, Address(str1, 0));
7920     }
7921     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7922     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7923 
7924     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7925       movdqu(vec1, Address(str1, adr_stride));
7926       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7927     } else {
7928       pmovzxbw(vec1, Address(str1, adr_stride1));
7929       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7930     }
7931     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7932     addl(cnt1, stride);
7933 
7934     // Compare the characters at index in cnt1
7935     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7936     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7937     subl(result, cnt2);
7938     jmp(POP_LABEL);
7939 
7940     // Setup the registers to start vector comparison loop
7941     bind(COMPARE_WIDE_VECTORS);
7942     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7943       lea(str1, Address(str1, result, scale));
7944       lea(str2, Address(str2, result, scale));
7945     } else {
7946       lea(str1, Address(str1, result, scale1));
7947       lea(str2, Address(str2, result, scale2));
7948     }
7949     subl(result, stride2);
7950     subl(cnt2, stride2);
7951     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7952     negptr(result);
7953 
7954     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7955     bind(COMPARE_WIDE_VECTORS_LOOP);
7956 
7957 #ifdef _LP64
7958     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7959       cmpl(cnt2, stride2x2);
7960       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7961       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7962       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7963 
7964       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7965       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7966         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7967         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7968       } else {
7969         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7970         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7971       }
7972       kortestql(k7, k7);
7973       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7974       addptr(result, stride2x2);  // update since we already compared at this addr
7975       subl(cnt2, stride2x2);      // and sub the size too
7976       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7977 
7978       vpxor(vec1, vec1);
7979       jmpb(COMPARE_WIDE_TAIL);
7980     }//if (VM_Version::supports_avx512vlbw())
7981 #endif // _LP64
7982 
7983 
7984     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7985     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7986       vmovdqu(vec1, Address(str1, result, scale));
7987       vpxor(vec1, Address(str2, result, scale));
7988     } else {
7989       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7990       vpxor(vec1, Address(str2, result, scale2));
7991     }
7992     vptest(vec1, vec1);
7993     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7994     addptr(result, stride2);
7995     subl(cnt2, stride2);
7996     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7997     // clean upper bits of YMM registers
7998     vpxor(vec1, vec1);
7999 
8000     // compare wide vectors tail
8001     bind(COMPARE_WIDE_TAIL);
8002     testptr(result, result);
8003     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8004 
8005     movl(result, stride2);
8006     movl(cnt2, result);
8007     negptr(result);
8008     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8009 
8010     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
8011     bind(VECTOR_NOT_EQUAL);
8012     // clean upper bits of YMM registers
8013     vpxor(vec1, vec1);
8014     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8015       lea(str1, Address(str1, result, scale));
8016       lea(str2, Address(str2, result, scale));
8017     } else {
8018       lea(str1, Address(str1, result, scale1));
8019       lea(str2, Address(str2, result, scale2));
8020     }
8021     jmp(COMPARE_16_CHARS);
8022 
8023     // Compare tail chars, length between 1 to 15 chars
8024     bind(COMPARE_TAIL_LONG);
8025     movl(cnt2, result);
8026     cmpl(cnt2, stride);
8027     jcc(Assembler::less, COMPARE_SMALL_STR);
8028 
8029     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8030       movdqu(vec1, Address(str1, 0));
8031     } else {
8032       pmovzxbw(vec1, Address(str1, 0));
8033     }
8034     pcmpestri(vec1, Address(str2, 0), pcmpmask);
8035     jcc(Assembler::below, COMPARE_INDEX_CHAR);
8036     subptr(cnt2, stride);
8037     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8038     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8039       lea(str1, Address(str1, result, scale));
8040       lea(str2, Address(str2, result, scale));
8041     } else {
8042       lea(str1, Address(str1, result, scale1));
8043       lea(str2, Address(str2, result, scale2));
8044     }
8045     negptr(cnt2);
8046     jmpb(WHILE_HEAD_LABEL);
8047 
8048     bind(COMPARE_SMALL_STR);
8049   } else if (UseSSE42Intrinsics) {
8050     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
8051     int pcmpmask = 0x19;
8052     // Setup to compare 8-char (16-byte) vectors,
8053     // start from first character again because it has aligned address.
8054     movl(result, cnt2);
8055     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
8056     if (ae == StrIntrinsicNode::LL) {
8057       pcmpmask &= ~0x01;
8058     }
8059     jcc(Assembler::zero, COMPARE_TAIL);
8060     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8061       lea(str1, Address(str1, result, scale));
8062       lea(str2, Address(str2, result, scale));
8063     } else {
8064       lea(str1, Address(str1, result, scale1));
8065       lea(str2, Address(str2, result, scale2));
8066     }
8067     negptr(result);
8068 
8069     // pcmpestri
8070     //   inputs:
8071     //     vec1- substring
8072     //     rax - negative string length (elements count)
8073     //     mem - scanned string
8074     //     rdx - string length (elements count)
8075     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
8076     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
8077     //   outputs:
8078     //     rcx - first mismatched element index
8079     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
8080 
8081     bind(COMPARE_WIDE_VECTORS);
8082     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8083       movdqu(vec1, Address(str1, result, scale));
8084       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8085     } else {
8086       pmovzxbw(vec1, Address(str1, result, scale1));
8087       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8088     }
8089     // After pcmpestri cnt1(rcx) contains mismatched element index
8090 
8091     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
8092     addptr(result, stride);
8093     subptr(cnt2, stride);
8094     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
8095 
8096     // compare wide vectors tail
8097     testptr(result, result);
8098     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
8099 
8100     movl(cnt2, stride);
8101     movl(result, stride);
8102     negptr(result);
8103     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8104       movdqu(vec1, Address(str1, result, scale));
8105       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
8106     } else {
8107       pmovzxbw(vec1, Address(str1, result, scale1));
8108       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
8109     }
8110     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
8111 
8112     // Mismatched characters in the vectors
8113     bind(VECTOR_NOT_EQUAL);
8114     addptr(cnt1, result);
8115     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
8116     subl(result, cnt2);
8117     jmpb(POP_LABEL);
8118 
8119     bind(COMPARE_TAIL); // limit is zero
8120     movl(cnt2, result);
8121     // Fallthru to tail compare
8122   }
8123   // Shift str2 and str1 to the end of the arrays, negate min
8124   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
8125     lea(str1, Address(str1, cnt2, scale));
8126     lea(str2, Address(str2, cnt2, scale));
8127   } else {
8128     lea(str1, Address(str1, cnt2, scale1));
8129     lea(str2, Address(str2, cnt2, scale2));
8130   }
8131   decrementl(cnt2);  // first character was compared already
8132   negptr(cnt2);
8133 
8134   // Compare the rest of the elements
8135   bind(WHILE_HEAD_LABEL);
8136   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
8137   subl(result, cnt1);
8138   jccb(Assembler::notZero, POP_LABEL);
8139   increment(cnt2);
8140   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
8141 
8142   // Strings are equal up to min length.  Return the length difference.
8143   bind(LENGTH_DIFF_LABEL);
8144   pop(result);
8145   if (ae == StrIntrinsicNode::UU) {
8146     // Divide diff by 2 to get number of chars
8147     sarl(result, 1);
8148   }
8149   jmpb(DONE_LABEL);
8150 
8151 #ifdef _LP64
8152   if (VM_Version::supports_avx512vlbw()) {
8153 
8154     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
8155 
8156     kmovql(cnt1, k7);
8157     notq(cnt1);
8158     bsfq(cnt2, cnt1);
8159     if (ae != StrIntrinsicNode::LL) {
8160       // Divide diff by 2 to get number of chars
8161       sarl(cnt2, 1);
8162     }
8163     addq(result, cnt2);
8164     if (ae == StrIntrinsicNode::LL) {
8165       load_unsigned_byte(cnt1, Address(str2, result));
8166       load_unsigned_byte(result, Address(str1, result));
8167     } else if (ae == StrIntrinsicNode::UU) {
8168       load_unsigned_short(cnt1, Address(str2, result, scale));
8169       load_unsigned_short(result, Address(str1, result, scale));
8170     } else {
8171       load_unsigned_short(cnt1, Address(str2, result, scale2));
8172       load_unsigned_byte(result, Address(str1, result, scale1));
8173     }
8174     subl(result, cnt1);
8175     jmpb(POP_LABEL);
8176   }//if (VM_Version::supports_avx512vlbw())
8177 #endif // _LP64
8178 
8179   // Discard the stored length difference
8180   bind(POP_LABEL);
8181   pop(cnt1);
8182 
8183   // That's it
8184   bind(DONE_LABEL);
8185   if(ae == StrIntrinsicNode::UL) {
8186     negl(result);
8187   }
8188 
8189 }
8190 
8191 // Search for Non-ASCII character (Negative byte value) in a byte array,
8192 // return true if it has any and false otherwise.
8193 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
8194 //   @HotSpotIntrinsicCandidate
8195 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
8196 //     for (int i = off; i < off + len; i++) {
8197 //       if (ba[i] < 0) {
8198 //         return true;
8199 //       }
8200 //     }
8201 //     return false;
8202 //   }
8203 void MacroAssembler::has_negatives(Register ary1, Register len,
8204   Register result, Register tmp1,
8205   XMMRegister vec1, XMMRegister vec2) {
8206   // rsi: byte array
8207   // rcx: len
8208   // rax: result
8209   ShortBranchVerifier sbv(this);
8210   assert_different_registers(ary1, len, result, tmp1);
8211   assert_different_registers(vec1, vec2);
8212   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
8213 
8214   // len == 0
8215   testl(len, len);
8216   jcc(Assembler::zero, FALSE_LABEL);
8217 
8218   if ((UseAVX > 2) && // AVX512
8219     VM_Version::supports_avx512vlbw() &&
8220     VM_Version::supports_bmi2()) {
8221 
8222     set_vector_masking();  // opening of the stub context for programming mask registers
8223 
8224     Label test_64_loop, test_tail;
8225     Register tmp3_aliased = len;
8226 
8227     movl(tmp1, len);
8228     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
8229 
8230     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
8231     andl(len, ~(64 - 1));    // vector count (in chars)
8232     jccb(Assembler::zero, test_tail);
8233 
8234     lea(ary1, Address(ary1, len, Address::times_1));
8235     negptr(len);
8236 
8237     bind(test_64_loop);
8238     // Check whether our 64 elements of size byte contain negatives
8239     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
8240     kortestql(k2, k2);
8241     jcc(Assembler::notZero, TRUE_LABEL);
8242 
8243     addptr(len, 64);
8244     jccb(Assembler::notZero, test_64_loop);
8245 
8246 
8247     bind(test_tail);
8248     // bail out when there is nothing to be done
8249     testl(tmp1, -1);
8250     jcc(Assembler::zero, FALSE_LABEL);
8251 
8252     // Save k1
8253     kmovql(k3, k1);
8254 
8255     // ~(~0 << len) applied up to two times (for 32-bit scenario)
8256 #ifdef _LP64
8257     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
8258     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
8259     notq(tmp3_aliased);
8260     kmovql(k1, tmp3_aliased);
8261 #else
8262     Label k_init;
8263     jmp(k_init);
8264 
8265     // We could not read 64-bits from a general purpose register thus we move
8266     // data required to compose 64 1's to the instruction stream
8267     // We emit 64 byte wide series of elements from 0..63 which later on would
8268     // be used as a compare targets with tail count contained in tmp1 register.
8269     // Result would be a k1 register having tmp1 consecutive number or 1
8270     // counting from least significant bit.
8271     address tmp = pc();
8272     emit_int64(0x0706050403020100);
8273     emit_int64(0x0F0E0D0C0B0A0908);
8274     emit_int64(0x1716151413121110);
8275     emit_int64(0x1F1E1D1C1B1A1918);
8276     emit_int64(0x2726252423222120);
8277     emit_int64(0x2F2E2D2C2B2A2928);
8278     emit_int64(0x3736353433323130);
8279     emit_int64(0x3F3E3D3C3B3A3938);
8280 
8281     bind(k_init);
8282     lea(len, InternalAddress(tmp));
8283     // create mask to test for negative byte inside a vector
8284     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
8285     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
8286 
8287 #endif
8288     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
8289     ktestq(k2, k1);
8290     // Restore k1
8291     kmovql(k1, k3);
8292     jcc(Assembler::notZero, TRUE_LABEL);
8293 
8294     jmp(FALSE_LABEL);
8295 
8296     clear_vector_masking();   // closing of the stub context for programming mask registers
8297   } else {
8298     movl(result, len); // copy
8299 
8300     if (UseAVX == 2 && UseSSE >= 2) {
8301       // With AVX2, use 32-byte vector compare
8302       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8303 
8304       // Compare 32-byte vectors
8305       andl(result, 0x0000001f);  //   tail count (in bytes)
8306       andl(len, 0xffffffe0);   // vector count (in bytes)
8307       jccb(Assembler::zero, COMPARE_TAIL);
8308 
8309       lea(ary1, Address(ary1, len, Address::times_1));
8310       negptr(len);
8311 
8312       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8313       movdl(vec2, tmp1);
8314       vpbroadcastd(vec2, vec2);
8315 
8316       bind(COMPARE_WIDE_VECTORS);
8317       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8318       vptest(vec1, vec2);
8319       jccb(Assembler::notZero, TRUE_LABEL);
8320       addptr(len, 32);
8321       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8322 
8323       testl(result, result);
8324       jccb(Assembler::zero, FALSE_LABEL);
8325 
8326       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8327       vptest(vec1, vec2);
8328       jccb(Assembler::notZero, TRUE_LABEL);
8329       jmpb(FALSE_LABEL);
8330 
8331       bind(COMPARE_TAIL); // len is zero
8332       movl(len, result);
8333       // Fallthru to tail compare
8334     } else if (UseSSE42Intrinsics) {
8335       // With SSE4.2, use double quad vector compare
8336       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8337 
8338       // Compare 16-byte vectors
8339       andl(result, 0x0000000f);  //   tail count (in bytes)
8340       andl(len, 0xfffffff0);   // vector count (in bytes)
8341       jccb(Assembler::zero, COMPARE_TAIL);
8342 
8343       lea(ary1, Address(ary1, len, Address::times_1));
8344       negptr(len);
8345 
8346       movl(tmp1, 0x80808080);
8347       movdl(vec2, tmp1);
8348       pshufd(vec2, vec2, 0);
8349 
8350       bind(COMPARE_WIDE_VECTORS);
8351       movdqu(vec1, Address(ary1, len, Address::times_1));
8352       ptest(vec1, vec2);
8353       jccb(Assembler::notZero, TRUE_LABEL);
8354       addptr(len, 16);
8355       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8356 
8357       testl(result, result);
8358       jccb(Assembler::zero, FALSE_LABEL);
8359 
8360       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8361       ptest(vec1, vec2);
8362       jccb(Assembler::notZero, TRUE_LABEL);
8363       jmpb(FALSE_LABEL);
8364 
8365       bind(COMPARE_TAIL); // len is zero
8366       movl(len, result);
8367       // Fallthru to tail compare
8368     }
8369   }
8370   // Compare 4-byte vectors
8371   andl(len, 0xfffffffc); // vector count (in bytes)
8372   jccb(Assembler::zero, COMPARE_CHAR);
8373 
8374   lea(ary1, Address(ary1, len, Address::times_1));
8375   negptr(len);
8376 
8377   bind(COMPARE_VECTORS);
8378   movl(tmp1, Address(ary1, len, Address::times_1));
8379   andl(tmp1, 0x80808080);
8380   jccb(Assembler::notZero, TRUE_LABEL);
8381   addptr(len, 4);
8382   jcc(Assembler::notZero, COMPARE_VECTORS);
8383 
8384   // Compare trailing char (final 2 bytes), if any
8385   bind(COMPARE_CHAR);
8386   testl(result, 0x2);   // tail  char
8387   jccb(Assembler::zero, COMPARE_BYTE);
8388   load_unsigned_short(tmp1, Address(ary1, 0));
8389   andl(tmp1, 0x00008080);
8390   jccb(Assembler::notZero, TRUE_LABEL);
8391   subptr(result, 2);
8392   lea(ary1, Address(ary1, 2));
8393 
8394   bind(COMPARE_BYTE);
8395   testl(result, 0x1);   // tail  byte
8396   jccb(Assembler::zero, FALSE_LABEL);
8397   load_unsigned_byte(tmp1, Address(ary1, 0));
8398   andl(tmp1, 0x00000080);
8399   jccb(Assembler::notEqual, TRUE_LABEL);
8400   jmpb(FALSE_LABEL);
8401 
8402   bind(TRUE_LABEL);
8403   movl(result, 1);   // return true
8404   jmpb(DONE);
8405 
8406   bind(FALSE_LABEL);
8407   xorl(result, result); // return false
8408 
8409   // That's it
8410   bind(DONE);
8411   if (UseAVX >= 2 && UseSSE >= 2) {
8412     // clean upper bits of YMM registers
8413     vpxor(vec1, vec1);
8414     vpxor(vec2, vec2);
8415   }
8416 }
8417 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8418 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8419                                    Register limit, Register result, Register chr,
8420                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8421   ShortBranchVerifier sbv(this);
8422   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8423 
8424   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8425   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8426 
8427   if (is_array_equ) {
8428     // Check the input args
8429     cmpoop(ary1, ary2);
8430     jcc(Assembler::equal, TRUE_LABEL);
8431 
8432     // Need additional checks for arrays_equals.
8433     testptr(ary1, ary1);
8434     jcc(Assembler::zero, FALSE_LABEL);
8435     testptr(ary2, ary2);
8436     jcc(Assembler::zero, FALSE_LABEL);
8437 
8438     // Check the lengths
8439     movl(limit, Address(ary1, length_offset));
8440     cmpl(limit, Address(ary2, length_offset));
8441     jcc(Assembler::notEqual, FALSE_LABEL);
8442   }
8443 
8444   // count == 0
8445   testl(limit, limit);
8446   jcc(Assembler::zero, TRUE_LABEL);
8447 
8448   if (is_array_equ) {
8449     // Load array address
8450     lea(ary1, Address(ary1, base_offset));
8451     lea(ary2, Address(ary2, base_offset));
8452   }
8453 
8454   if (is_array_equ && is_char) {
8455     // arrays_equals when used for char[].
8456     shll(limit, 1);      // byte count != 0
8457   }
8458   movl(result, limit); // copy
8459 
8460   if (UseAVX >= 2) {
8461     // With AVX2, use 32-byte vector compare
8462     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8463 
8464     // Compare 32-byte vectors
8465     andl(result, 0x0000001f);  //   tail count (in bytes)
8466     andl(limit, 0xffffffe0);   // vector count (in bytes)
8467     jcc(Assembler::zero, COMPARE_TAIL);
8468 
8469     lea(ary1, Address(ary1, limit, Address::times_1));
8470     lea(ary2, Address(ary2, limit, Address::times_1));
8471     negptr(limit);
8472 
8473     bind(COMPARE_WIDE_VECTORS);
8474 
8475 #ifdef _LP64
8476     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8477       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8478 
8479       cmpl(limit, -64);
8480       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8481 
8482       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8483 
8484       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8485       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8486       kortestql(k7, k7);
8487       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8488       addptr(limit, 64);  // update since we already compared at this addr
8489       cmpl(limit, -64);
8490       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8491 
8492       // At this point we may still need to compare -limit+result bytes.
8493       // We could execute the next two instruction and just continue via non-wide path:
8494       //  cmpl(limit, 0);
8495       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8496       // But since we stopped at the points ary{1,2}+limit which are
8497       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8498       // (|limit| <= 32 and result < 32),
8499       // we may just compare the last 64 bytes.
8500       //
8501       addptr(result, -64);   // it is safe, bc we just came from this area
8502       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8503       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8504       kortestql(k7, k7);
8505       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8506 
8507       jmp(TRUE_LABEL);
8508 
8509       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8510 
8511     }//if (VM_Version::supports_avx512vlbw())
8512 #endif //_LP64
8513 
8514     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8515     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8516     vpxor(vec1, vec2);
8517 
8518     vptest(vec1, vec1);
8519     jcc(Assembler::notZero, FALSE_LABEL);
8520     addptr(limit, 32);
8521     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8522 
8523     testl(result, result);
8524     jcc(Assembler::zero, TRUE_LABEL);
8525 
8526     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8527     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8528     vpxor(vec1, vec2);
8529 
8530     vptest(vec1, vec1);
8531     jccb(Assembler::notZero, FALSE_LABEL);
8532     jmpb(TRUE_LABEL);
8533 
8534     bind(COMPARE_TAIL); // limit is zero
8535     movl(limit, result);
8536     // Fallthru to tail compare
8537   } else if (UseSSE42Intrinsics) {
8538     // With SSE4.2, use double quad vector compare
8539     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8540 
8541     // Compare 16-byte vectors
8542     andl(result, 0x0000000f);  //   tail count (in bytes)
8543     andl(limit, 0xfffffff0);   // vector count (in bytes)
8544     jcc(Assembler::zero, COMPARE_TAIL);
8545 
8546     lea(ary1, Address(ary1, limit, Address::times_1));
8547     lea(ary2, Address(ary2, limit, Address::times_1));
8548     negptr(limit);
8549 
8550     bind(COMPARE_WIDE_VECTORS);
8551     movdqu(vec1, Address(ary1, limit, Address::times_1));
8552     movdqu(vec2, Address(ary2, limit, Address::times_1));
8553     pxor(vec1, vec2);
8554 
8555     ptest(vec1, vec1);
8556     jcc(Assembler::notZero, FALSE_LABEL);
8557     addptr(limit, 16);
8558     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8559 
8560     testl(result, result);
8561     jcc(Assembler::zero, TRUE_LABEL);
8562 
8563     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8564     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8565     pxor(vec1, vec2);
8566 
8567     ptest(vec1, vec1);
8568     jccb(Assembler::notZero, FALSE_LABEL);
8569     jmpb(TRUE_LABEL);
8570 
8571     bind(COMPARE_TAIL); // limit is zero
8572     movl(limit, result);
8573     // Fallthru to tail compare
8574   }
8575 
8576   // Compare 4-byte vectors
8577   andl(limit, 0xfffffffc); // vector count (in bytes)
8578   jccb(Assembler::zero, COMPARE_CHAR);
8579 
8580   lea(ary1, Address(ary1, limit, Address::times_1));
8581   lea(ary2, Address(ary2, limit, Address::times_1));
8582   negptr(limit);
8583 
8584   bind(COMPARE_VECTORS);
8585   movl(chr, Address(ary1, limit, Address::times_1));
8586   cmpl(chr, Address(ary2, limit, Address::times_1));
8587   jccb(Assembler::notEqual, FALSE_LABEL);
8588   addptr(limit, 4);
8589   jcc(Assembler::notZero, COMPARE_VECTORS);
8590 
8591   // Compare trailing char (final 2 bytes), if any
8592   bind(COMPARE_CHAR);
8593   testl(result, 0x2);   // tail  char
8594   jccb(Assembler::zero, COMPARE_BYTE);
8595   load_unsigned_short(chr, Address(ary1, 0));
8596   load_unsigned_short(limit, Address(ary2, 0));
8597   cmpl(chr, limit);
8598   jccb(Assembler::notEqual, FALSE_LABEL);
8599 
8600   if (is_array_equ && is_char) {
8601     bind(COMPARE_BYTE);
8602   } else {
8603     lea(ary1, Address(ary1, 2));
8604     lea(ary2, Address(ary2, 2));
8605 
8606     bind(COMPARE_BYTE);
8607     testl(result, 0x1);   // tail  byte
8608     jccb(Assembler::zero, TRUE_LABEL);
8609     load_unsigned_byte(chr, Address(ary1, 0));
8610     load_unsigned_byte(limit, Address(ary2, 0));
8611     cmpl(chr, limit);
8612     jccb(Assembler::notEqual, FALSE_LABEL);
8613   }
8614   bind(TRUE_LABEL);
8615   movl(result, 1);   // return true
8616   jmpb(DONE);
8617 
8618   bind(FALSE_LABEL);
8619   xorl(result, result); // return false
8620 
8621   // That's it
8622   bind(DONE);
8623   if (UseAVX >= 2) {
8624     // clean upper bits of YMM registers
8625     vpxor(vec1, vec1);
8626     vpxor(vec2, vec2);
8627   }
8628 }
8629 
8630 #endif
8631 
8632 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8633                                    Register to, Register value, Register count,
8634                                    Register rtmp, XMMRegister xtmp) {
8635   ShortBranchVerifier sbv(this);
8636   assert_different_registers(to, value, count, rtmp);
8637   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8638   Label L_fill_2_bytes, L_fill_4_bytes;
8639 
8640   int shift = -1;
8641   switch (t) {
8642     case T_BYTE:
8643       shift = 2;
8644       break;
8645     case T_SHORT:
8646       shift = 1;
8647       break;
8648     case T_INT:
8649       shift = 0;
8650       break;
8651     default: ShouldNotReachHere();
8652   }
8653 
8654   if (t == T_BYTE) {
8655     andl(value, 0xff);
8656     movl(rtmp, value);
8657     shll(rtmp, 8);
8658     orl(value, rtmp);
8659   }
8660   if (t == T_SHORT) {
8661     andl(value, 0xffff);
8662   }
8663   if (t == T_BYTE || t == T_SHORT) {
8664     movl(rtmp, value);
8665     shll(rtmp, 16);
8666     orl(value, rtmp);
8667   }
8668 
8669   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8670   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8671   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8672     // align source address at 4 bytes address boundary
8673     if (t == T_BYTE) {
8674       // One byte misalignment happens only for byte arrays
8675       testptr(to, 1);
8676       jccb(Assembler::zero, L_skip_align1);
8677       movb(Address(to, 0), value);
8678       increment(to);
8679       decrement(count);
8680       BIND(L_skip_align1);
8681     }
8682     // Two bytes misalignment happens only for byte and short (char) arrays
8683     testptr(to, 2);
8684     jccb(Assembler::zero, L_skip_align2);
8685     movw(Address(to, 0), value);
8686     addptr(to, 2);
8687     subl(count, 1<<(shift-1));
8688     BIND(L_skip_align2);
8689   }
8690   if (UseSSE < 2) {
8691     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8692     // Fill 32-byte chunks
8693     subl(count, 8 << shift);
8694     jcc(Assembler::less, L_check_fill_8_bytes);
8695     align(16);
8696 
8697     BIND(L_fill_32_bytes_loop);
8698 
8699     for (int i = 0; i < 32; i += 4) {
8700       movl(Address(to, i), value);
8701     }
8702 
8703     addptr(to, 32);
8704     subl(count, 8 << shift);
8705     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8706     BIND(L_check_fill_8_bytes);
8707     addl(count, 8 << shift);
8708     jccb(Assembler::zero, L_exit);
8709     jmpb(L_fill_8_bytes);
8710 
8711     //
8712     // length is too short, just fill qwords
8713     //
8714     BIND(L_fill_8_bytes_loop);
8715     movl(Address(to, 0), value);
8716     movl(Address(to, 4), value);
8717     addptr(to, 8);
8718     BIND(L_fill_8_bytes);
8719     subl(count, 1 << (shift + 1));
8720     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8721     // fall through to fill 4 bytes
8722   } else {
8723     Label L_fill_32_bytes;
8724     if (!UseUnalignedLoadStores) {
8725       // align to 8 bytes, we know we are 4 byte aligned to start
8726       testptr(to, 4);
8727       jccb(Assembler::zero, L_fill_32_bytes);
8728       movl(Address(to, 0), value);
8729       addptr(to, 4);
8730       subl(count, 1<<shift);
8731     }
8732     BIND(L_fill_32_bytes);
8733     {
8734       assert( UseSSE >= 2, "supported cpu only" );
8735       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8736       if (UseAVX > 2) {
8737         movl(rtmp, 0xffff);
8738         kmovwl(k1, rtmp);
8739       }
8740       movdl(xtmp, value);
8741       if (UseAVX > 2 && UseUnalignedLoadStores) {
8742         // Fill 64-byte chunks
8743         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8744         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8745 
8746         subl(count, 16 << shift);
8747         jcc(Assembler::less, L_check_fill_32_bytes);
8748         align(16);
8749 
8750         BIND(L_fill_64_bytes_loop);
8751         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8752         addptr(to, 64);
8753         subl(count, 16 << shift);
8754         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8755 
8756         BIND(L_check_fill_32_bytes);
8757         addl(count, 8 << shift);
8758         jccb(Assembler::less, L_check_fill_8_bytes);
8759         vmovdqu(Address(to, 0), xtmp);
8760         addptr(to, 32);
8761         subl(count, 8 << shift);
8762 
8763         BIND(L_check_fill_8_bytes);
8764       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8765         // Fill 64-byte chunks
8766         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8767         vpbroadcastd(xtmp, xtmp);
8768 
8769         subl(count, 16 << shift);
8770         jcc(Assembler::less, L_check_fill_32_bytes);
8771         align(16);
8772 
8773         BIND(L_fill_64_bytes_loop);
8774         vmovdqu(Address(to, 0), xtmp);
8775         vmovdqu(Address(to, 32), xtmp);
8776         addptr(to, 64);
8777         subl(count, 16 << shift);
8778         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8779 
8780         BIND(L_check_fill_32_bytes);
8781         addl(count, 8 << shift);
8782         jccb(Assembler::less, L_check_fill_8_bytes);
8783         vmovdqu(Address(to, 0), xtmp);
8784         addptr(to, 32);
8785         subl(count, 8 << shift);
8786 
8787         BIND(L_check_fill_8_bytes);
8788         // clean upper bits of YMM registers
8789         movdl(xtmp, value);
8790         pshufd(xtmp, xtmp, 0);
8791       } else {
8792         // Fill 32-byte chunks
8793         pshufd(xtmp, xtmp, 0);
8794 
8795         subl(count, 8 << shift);
8796         jcc(Assembler::less, L_check_fill_8_bytes);
8797         align(16);
8798 
8799         BIND(L_fill_32_bytes_loop);
8800 
8801         if (UseUnalignedLoadStores) {
8802           movdqu(Address(to, 0), xtmp);
8803           movdqu(Address(to, 16), xtmp);
8804         } else {
8805           movq(Address(to, 0), xtmp);
8806           movq(Address(to, 8), xtmp);
8807           movq(Address(to, 16), xtmp);
8808           movq(Address(to, 24), xtmp);
8809         }
8810 
8811         addptr(to, 32);
8812         subl(count, 8 << shift);
8813         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8814 
8815         BIND(L_check_fill_8_bytes);
8816       }
8817       addl(count, 8 << shift);
8818       jccb(Assembler::zero, L_exit);
8819       jmpb(L_fill_8_bytes);
8820 
8821       //
8822       // length is too short, just fill qwords
8823       //
8824       BIND(L_fill_8_bytes_loop);
8825       movq(Address(to, 0), xtmp);
8826       addptr(to, 8);
8827       BIND(L_fill_8_bytes);
8828       subl(count, 1 << (shift + 1));
8829       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8830     }
8831   }
8832   // fill trailing 4 bytes
8833   BIND(L_fill_4_bytes);
8834   testl(count, 1<<shift);
8835   jccb(Assembler::zero, L_fill_2_bytes);
8836   movl(Address(to, 0), value);
8837   if (t == T_BYTE || t == T_SHORT) {
8838     addptr(to, 4);
8839     BIND(L_fill_2_bytes);
8840     // fill trailing 2 bytes
8841     testl(count, 1<<(shift-1));
8842     jccb(Assembler::zero, L_fill_byte);
8843     movw(Address(to, 0), value);
8844     if (t == T_BYTE) {
8845       addptr(to, 2);
8846       BIND(L_fill_byte);
8847       // fill trailing byte
8848       testl(count, 1);
8849       jccb(Assembler::zero, L_exit);
8850       movb(Address(to, 0), value);
8851     } else {
8852       BIND(L_fill_byte);
8853     }
8854   } else {
8855     BIND(L_fill_2_bytes);
8856   }
8857   BIND(L_exit);
8858 }
8859 
8860 // encode char[] to byte[] in ISO_8859_1
8861    //@HotSpotIntrinsicCandidate
8862    //private static int implEncodeISOArray(byte[] sa, int sp,
8863    //byte[] da, int dp, int len) {
8864    //  int i = 0;
8865    //  for (; i < len; i++) {
8866    //    char c = StringUTF16.getChar(sa, sp++);
8867    //    if (c > '\u00FF')
8868    //      break;
8869    //    da[dp++] = (byte)c;
8870    //  }
8871    //  return i;
8872    //}
8873 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8874   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8875   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8876   Register tmp5, Register result) {
8877 
8878   // rsi: src
8879   // rdi: dst
8880   // rdx: len
8881   // rcx: tmp5
8882   // rax: result
8883   ShortBranchVerifier sbv(this);
8884   assert_different_registers(src, dst, len, tmp5, result);
8885   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8886 
8887   // set result
8888   xorl(result, result);
8889   // check for zero length
8890   testl(len, len);
8891   jcc(Assembler::zero, L_done);
8892 
8893   movl(result, len);
8894 
8895   // Setup pointers
8896   lea(src, Address(src, len, Address::times_2)); // char[]
8897   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8898   negptr(len);
8899 
8900   if (UseSSE42Intrinsics || UseAVX >= 2) {
8901     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8902     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8903 
8904     if (UseAVX >= 2) {
8905       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8906       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8907       movdl(tmp1Reg, tmp5);
8908       vpbroadcastd(tmp1Reg, tmp1Reg);
8909       jmp(L_chars_32_check);
8910 
8911       bind(L_copy_32_chars);
8912       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8913       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8914       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8915       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8916       jccb(Assembler::notZero, L_copy_32_chars_exit);
8917       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8918       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8919       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8920 
8921       bind(L_chars_32_check);
8922       addptr(len, 32);
8923       jcc(Assembler::lessEqual, L_copy_32_chars);
8924 
8925       bind(L_copy_32_chars_exit);
8926       subptr(len, 16);
8927       jccb(Assembler::greater, L_copy_16_chars_exit);
8928 
8929     } else if (UseSSE42Intrinsics) {
8930       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8931       movdl(tmp1Reg, tmp5);
8932       pshufd(tmp1Reg, tmp1Reg, 0);
8933       jmpb(L_chars_16_check);
8934     }
8935 
8936     bind(L_copy_16_chars);
8937     if (UseAVX >= 2) {
8938       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8939       vptest(tmp2Reg, tmp1Reg);
8940       jcc(Assembler::notZero, L_copy_16_chars_exit);
8941       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8942       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8943     } else {
8944       if (UseAVX > 0) {
8945         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8946         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8947         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8948       } else {
8949         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8950         por(tmp2Reg, tmp3Reg);
8951         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8952         por(tmp2Reg, tmp4Reg);
8953       }
8954       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8955       jccb(Assembler::notZero, L_copy_16_chars_exit);
8956       packuswb(tmp3Reg, tmp4Reg);
8957     }
8958     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8959 
8960     bind(L_chars_16_check);
8961     addptr(len, 16);
8962     jcc(Assembler::lessEqual, L_copy_16_chars);
8963 
8964     bind(L_copy_16_chars_exit);
8965     if (UseAVX >= 2) {
8966       // clean upper bits of YMM registers
8967       vpxor(tmp2Reg, tmp2Reg);
8968       vpxor(tmp3Reg, tmp3Reg);
8969       vpxor(tmp4Reg, tmp4Reg);
8970       movdl(tmp1Reg, tmp5);
8971       pshufd(tmp1Reg, tmp1Reg, 0);
8972     }
8973     subptr(len, 8);
8974     jccb(Assembler::greater, L_copy_8_chars_exit);
8975 
8976     bind(L_copy_8_chars);
8977     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8978     ptest(tmp3Reg, tmp1Reg);
8979     jccb(Assembler::notZero, L_copy_8_chars_exit);
8980     packuswb(tmp3Reg, tmp1Reg);
8981     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8982     addptr(len, 8);
8983     jccb(Assembler::lessEqual, L_copy_8_chars);
8984 
8985     bind(L_copy_8_chars_exit);
8986     subptr(len, 8);
8987     jccb(Assembler::zero, L_done);
8988   }
8989 
8990   bind(L_copy_1_char);
8991   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8992   testl(tmp5, 0xff00);      // check if Unicode char
8993   jccb(Assembler::notZero, L_copy_1_char_exit);
8994   movb(Address(dst, len, Address::times_1, 0), tmp5);
8995   addptr(len, 1);
8996   jccb(Assembler::less, L_copy_1_char);
8997 
8998   bind(L_copy_1_char_exit);
8999   addptr(result, len); // len is negative count of not processed elements
9000 
9001   bind(L_done);
9002 }
9003 
9004 #ifdef _LP64
9005 /**
9006  * Helper for multiply_to_len().
9007  */
9008 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
9009   addq(dest_lo, src1);
9010   adcq(dest_hi, 0);
9011   addq(dest_lo, src2);
9012   adcq(dest_hi, 0);
9013 }
9014 
9015 /**
9016  * Multiply 64 bit by 64 bit first loop.
9017  */
9018 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
9019                                            Register y, Register y_idx, Register z,
9020                                            Register carry, Register product,
9021                                            Register idx, Register kdx) {
9022   //
9023   //  jlong carry, x[], y[], z[];
9024   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9025   //    huge_128 product = y[idx] * x[xstart] + carry;
9026   //    z[kdx] = (jlong)product;
9027   //    carry  = (jlong)(product >>> 64);
9028   //  }
9029   //  z[xstart] = carry;
9030   //
9031 
9032   Label L_first_loop, L_first_loop_exit;
9033   Label L_one_x, L_one_y, L_multiply;
9034 
9035   decrementl(xstart);
9036   jcc(Assembler::negative, L_one_x);
9037 
9038   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9039   rorq(x_xstart, 32); // convert big-endian to little-endian
9040 
9041   bind(L_first_loop);
9042   decrementl(idx);
9043   jcc(Assembler::negative, L_first_loop_exit);
9044   decrementl(idx);
9045   jcc(Assembler::negative, L_one_y);
9046   movq(y_idx, Address(y, idx, Address::times_4,  0));
9047   rorq(y_idx, 32); // convert big-endian to little-endian
9048   bind(L_multiply);
9049   movq(product, x_xstart);
9050   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
9051   addq(product, carry);
9052   adcq(rdx, 0);
9053   subl(kdx, 2);
9054   movl(Address(z, kdx, Address::times_4,  4), product);
9055   shrq(product, 32);
9056   movl(Address(z, kdx, Address::times_4,  0), product);
9057   movq(carry, rdx);
9058   jmp(L_first_loop);
9059 
9060   bind(L_one_y);
9061   movl(y_idx, Address(y,  0));
9062   jmp(L_multiply);
9063 
9064   bind(L_one_x);
9065   movl(x_xstart, Address(x,  0));
9066   jmp(L_first_loop);
9067 
9068   bind(L_first_loop_exit);
9069 }
9070 
9071 /**
9072  * Multiply 64 bit by 64 bit and add 128 bit.
9073  */
9074 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
9075                                             Register yz_idx, Register idx,
9076                                             Register carry, Register product, int offset) {
9077   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
9078   //     z[kdx] = (jlong)product;
9079 
9080   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
9081   rorq(yz_idx, 32); // convert big-endian to little-endian
9082   movq(product, x_xstart);
9083   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
9084   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
9085   rorq(yz_idx, 32); // convert big-endian to little-endian
9086 
9087   add2_with_carry(rdx, product, carry, yz_idx);
9088 
9089   movl(Address(z, idx, Address::times_4,  offset+4), product);
9090   shrq(product, 32);
9091   movl(Address(z, idx, Address::times_4,  offset), product);
9092 
9093 }
9094 
9095 /**
9096  * Multiply 128 bit by 128 bit. Unrolled inner loop.
9097  */
9098 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
9099                                              Register yz_idx, Register idx, Register jdx,
9100                                              Register carry, Register product,
9101                                              Register carry2) {
9102   //   jlong carry, x[], y[], z[];
9103   //   int kdx = ystart+1;
9104   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9105   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
9106   //     z[kdx+idx+1] = (jlong)product;
9107   //     jlong carry2  = (jlong)(product >>> 64);
9108   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
9109   //     z[kdx+idx] = (jlong)product;
9110   //     carry  = (jlong)(product >>> 64);
9111   //   }
9112   //   idx += 2;
9113   //   if (idx > 0) {
9114   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
9115   //     z[kdx+idx] = (jlong)product;
9116   //     carry  = (jlong)(product >>> 64);
9117   //   }
9118   //
9119 
9120   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9121 
9122   movl(jdx, idx);
9123   andl(jdx, 0xFFFFFFFC);
9124   shrl(jdx, 2);
9125 
9126   bind(L_third_loop);
9127   subl(jdx, 1);
9128   jcc(Assembler::negative, L_third_loop_exit);
9129   subl(idx, 4);
9130 
9131   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
9132   movq(carry2, rdx);
9133 
9134   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
9135   movq(carry, rdx);
9136   jmp(L_third_loop);
9137 
9138   bind (L_third_loop_exit);
9139 
9140   andl (idx, 0x3);
9141   jcc(Assembler::zero, L_post_third_loop_done);
9142 
9143   Label L_check_1;
9144   subl(idx, 2);
9145   jcc(Assembler::negative, L_check_1);
9146 
9147   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
9148   movq(carry, rdx);
9149 
9150   bind (L_check_1);
9151   addl (idx, 0x2);
9152   andl (idx, 0x1);
9153   subl(idx, 1);
9154   jcc(Assembler::negative, L_post_third_loop_done);
9155 
9156   movl(yz_idx, Address(y, idx, Address::times_4,  0));
9157   movq(product, x_xstart);
9158   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
9159   movl(yz_idx, Address(z, idx, Address::times_4,  0));
9160 
9161   add2_with_carry(rdx, product, yz_idx, carry);
9162 
9163   movl(Address(z, idx, Address::times_4,  0), product);
9164   shrq(product, 32);
9165 
9166   shlq(rdx, 32);
9167   orq(product, rdx);
9168   movq(carry, product);
9169 
9170   bind(L_post_third_loop_done);
9171 }
9172 
9173 /**
9174  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
9175  *
9176  */
9177 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
9178                                                   Register carry, Register carry2,
9179                                                   Register idx, Register jdx,
9180                                                   Register yz_idx1, Register yz_idx2,
9181                                                   Register tmp, Register tmp3, Register tmp4) {
9182   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
9183 
9184   //   jlong carry, x[], y[], z[];
9185   //   int kdx = ystart+1;
9186   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
9187   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
9188   //     jlong carry2  = (jlong)(tmp3 >>> 64);
9189   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
9190   //     carry  = (jlong)(tmp4 >>> 64);
9191   //     z[kdx+idx+1] = (jlong)tmp3;
9192   //     z[kdx+idx] = (jlong)tmp4;
9193   //   }
9194   //   idx += 2;
9195   //   if (idx > 0) {
9196   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
9197   //     z[kdx+idx] = (jlong)yz_idx1;
9198   //     carry  = (jlong)(yz_idx1 >>> 64);
9199   //   }
9200   //
9201 
9202   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
9203 
9204   movl(jdx, idx);
9205   andl(jdx, 0xFFFFFFFC);
9206   shrl(jdx, 2);
9207 
9208   bind(L_third_loop);
9209   subl(jdx, 1);
9210   jcc(Assembler::negative, L_third_loop_exit);
9211   subl(idx, 4);
9212 
9213   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
9214   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
9215   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
9216   rorxq(yz_idx2, yz_idx2, 32);
9217 
9218   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
9219   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
9220 
9221   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
9222   rorxq(yz_idx1, yz_idx1, 32);
9223   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9224   rorxq(yz_idx2, yz_idx2, 32);
9225 
9226   if (VM_Version::supports_adx()) {
9227     adcxq(tmp3, carry);
9228     adoxq(tmp3, yz_idx1);
9229 
9230     adcxq(tmp4, tmp);
9231     adoxq(tmp4, yz_idx2);
9232 
9233     movl(carry, 0); // does not affect flags
9234     adcxq(carry2, carry);
9235     adoxq(carry2, carry);
9236   } else {
9237     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
9238     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
9239   }
9240   movq(carry, carry2);
9241 
9242   movl(Address(z, idx, Address::times_4, 12), tmp3);
9243   shrq(tmp3, 32);
9244   movl(Address(z, idx, Address::times_4,  8), tmp3);
9245 
9246   movl(Address(z, idx, Address::times_4,  4), tmp4);
9247   shrq(tmp4, 32);
9248   movl(Address(z, idx, Address::times_4,  0), tmp4);
9249 
9250   jmp(L_third_loop);
9251 
9252   bind (L_third_loop_exit);
9253 
9254   andl (idx, 0x3);
9255   jcc(Assembler::zero, L_post_third_loop_done);
9256 
9257   Label L_check_1;
9258   subl(idx, 2);
9259   jcc(Assembler::negative, L_check_1);
9260 
9261   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
9262   rorxq(yz_idx1, yz_idx1, 32);
9263   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
9264   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
9265   rorxq(yz_idx2, yz_idx2, 32);
9266 
9267   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
9268 
9269   movl(Address(z, idx, Address::times_4,  4), tmp3);
9270   shrq(tmp3, 32);
9271   movl(Address(z, idx, Address::times_4,  0), tmp3);
9272   movq(carry, tmp4);
9273 
9274   bind (L_check_1);
9275   addl (idx, 0x2);
9276   andl (idx, 0x1);
9277   subl(idx, 1);
9278   jcc(Assembler::negative, L_post_third_loop_done);
9279   movl(tmp4, Address(y, idx, Address::times_4,  0));
9280   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
9281   movl(tmp4, Address(z, idx, Address::times_4,  0));
9282 
9283   add2_with_carry(carry2, tmp3, tmp4, carry);
9284 
9285   movl(Address(z, idx, Address::times_4,  0), tmp3);
9286   shrq(tmp3, 32);
9287 
9288   shlq(carry2, 32);
9289   orq(tmp3, carry2);
9290   movq(carry, tmp3);
9291 
9292   bind(L_post_third_loop_done);
9293 }
9294 
9295 /**
9296  * Code for BigInteger::multiplyToLen() instrinsic.
9297  *
9298  * rdi: x
9299  * rax: xlen
9300  * rsi: y
9301  * rcx: ylen
9302  * r8:  z
9303  * r11: zlen
9304  * r12: tmp1
9305  * r13: tmp2
9306  * r14: tmp3
9307  * r15: tmp4
9308  * rbx: tmp5
9309  *
9310  */
9311 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9312                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9313   ShortBranchVerifier sbv(this);
9314   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9315 
9316   push(tmp1);
9317   push(tmp2);
9318   push(tmp3);
9319   push(tmp4);
9320   push(tmp5);
9321 
9322   push(xlen);
9323   push(zlen);
9324 
9325   const Register idx = tmp1;
9326   const Register kdx = tmp2;
9327   const Register xstart = tmp3;
9328 
9329   const Register y_idx = tmp4;
9330   const Register carry = tmp5;
9331   const Register product  = xlen;
9332   const Register x_xstart = zlen;  // reuse register
9333 
9334   // First Loop.
9335   //
9336   //  final static long LONG_MASK = 0xffffffffL;
9337   //  int xstart = xlen - 1;
9338   //  int ystart = ylen - 1;
9339   //  long carry = 0;
9340   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9341   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9342   //    z[kdx] = (int)product;
9343   //    carry = product >>> 32;
9344   //  }
9345   //  z[xstart] = (int)carry;
9346   //
9347 
9348   movl(idx, ylen);      // idx = ylen;
9349   movl(kdx, zlen);      // kdx = xlen+ylen;
9350   xorq(carry, carry);   // carry = 0;
9351 
9352   Label L_done;
9353 
9354   movl(xstart, xlen);
9355   decrementl(xstart);
9356   jcc(Assembler::negative, L_done);
9357 
9358   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9359 
9360   Label L_second_loop;
9361   testl(kdx, kdx);
9362   jcc(Assembler::zero, L_second_loop);
9363 
9364   Label L_carry;
9365   subl(kdx, 1);
9366   jcc(Assembler::zero, L_carry);
9367 
9368   movl(Address(z, kdx, Address::times_4,  0), carry);
9369   shrq(carry, 32);
9370   subl(kdx, 1);
9371 
9372   bind(L_carry);
9373   movl(Address(z, kdx, Address::times_4,  0), carry);
9374 
9375   // Second and third (nested) loops.
9376   //
9377   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9378   //   carry = 0;
9379   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9380   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9381   //                    (z[k] & LONG_MASK) + carry;
9382   //     z[k] = (int)product;
9383   //     carry = product >>> 32;
9384   //   }
9385   //   z[i] = (int)carry;
9386   // }
9387   //
9388   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9389 
9390   const Register jdx = tmp1;
9391 
9392   bind(L_second_loop);
9393   xorl(carry, carry);    // carry = 0;
9394   movl(jdx, ylen);       // j = ystart+1
9395 
9396   subl(xstart, 1);       // i = xstart-1;
9397   jcc(Assembler::negative, L_done);
9398 
9399   push (z);
9400 
9401   Label L_last_x;
9402   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9403   subl(xstart, 1);       // i = xstart-1;
9404   jcc(Assembler::negative, L_last_x);
9405 
9406   if (UseBMI2Instructions) {
9407     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9408     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9409   } else {
9410     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9411     rorq(x_xstart, 32);  // convert big-endian to little-endian
9412   }
9413 
9414   Label L_third_loop_prologue;
9415   bind(L_third_loop_prologue);
9416 
9417   push (x);
9418   push (xstart);
9419   push (ylen);
9420 
9421 
9422   if (UseBMI2Instructions) {
9423     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9424   } else { // !UseBMI2Instructions
9425     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9426   }
9427 
9428   pop(ylen);
9429   pop(xlen);
9430   pop(x);
9431   pop(z);
9432 
9433   movl(tmp3, xlen);
9434   addl(tmp3, 1);
9435   movl(Address(z, tmp3, Address::times_4,  0), carry);
9436   subl(tmp3, 1);
9437   jccb(Assembler::negative, L_done);
9438 
9439   shrq(carry, 32);
9440   movl(Address(z, tmp3, Address::times_4,  0), carry);
9441   jmp(L_second_loop);
9442 
9443   // Next infrequent code is moved outside loops.
9444   bind(L_last_x);
9445   if (UseBMI2Instructions) {
9446     movl(rdx, Address(x,  0));
9447   } else {
9448     movl(x_xstart, Address(x,  0));
9449   }
9450   jmp(L_third_loop_prologue);
9451 
9452   bind(L_done);
9453 
9454   pop(zlen);
9455   pop(xlen);
9456 
9457   pop(tmp5);
9458   pop(tmp4);
9459   pop(tmp3);
9460   pop(tmp2);
9461   pop(tmp1);
9462 }
9463 
9464 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9465   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9466   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9467   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9468   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9469   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9470   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9471   Label SAME_TILL_END, DONE;
9472   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9473 
9474   //scale is in rcx in both Win64 and Unix
9475   ShortBranchVerifier sbv(this);
9476 
9477   shlq(length);
9478   xorq(result, result);
9479 
9480   if ((UseAVX > 2) &&
9481       VM_Version::supports_avx512vlbw()) {
9482     set_vector_masking();  // opening of the stub context for programming mask registers
9483     cmpq(length, 64);
9484     jcc(Assembler::less, VECTOR32_TAIL);
9485     movq(tmp1, length);
9486     andq(tmp1, 0x3F);      // tail count
9487     andq(length, ~(0x3F)); //vector count
9488 
9489     bind(VECTOR64_LOOP);
9490     // AVX512 code to compare 64 byte vectors.
9491     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9492     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9493     kortestql(k7, k7);
9494     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9495     addq(result, 64);
9496     subq(length, 64);
9497     jccb(Assembler::notZero, VECTOR64_LOOP);
9498 
9499     //bind(VECTOR64_TAIL);
9500     testq(tmp1, tmp1);
9501     jcc(Assembler::zero, SAME_TILL_END);
9502 
9503     bind(VECTOR64_TAIL);
9504     // AVX512 code to compare upto 63 byte vectors.
9505     // Save k1
9506     kmovql(k3, k1);
9507     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9508     shlxq(tmp2, tmp2, tmp1);
9509     notq(tmp2);
9510     kmovql(k1, tmp2);
9511 
9512     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9513     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9514 
9515     ktestql(k7, k1);
9516     // Restore k1
9517     kmovql(k1, k3);
9518     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9519 
9520     bind(VECTOR64_NOT_EQUAL);
9521     kmovql(tmp1, k7);
9522     notq(tmp1);
9523     tzcntq(tmp1, tmp1);
9524     addq(result, tmp1);
9525     shrq(result);
9526     jmp(DONE);
9527     bind(VECTOR32_TAIL);
9528     clear_vector_masking();   // closing of the stub context for programming mask registers
9529   }
9530 
9531   cmpq(length, 8);
9532   jcc(Assembler::equal, VECTOR8_LOOP);
9533   jcc(Assembler::less, VECTOR4_TAIL);
9534 
9535   if (UseAVX >= 2) {
9536 
9537     cmpq(length, 16);
9538     jcc(Assembler::equal, VECTOR16_LOOP);
9539     jcc(Assembler::less, VECTOR8_LOOP);
9540 
9541     cmpq(length, 32);
9542     jccb(Assembler::less, VECTOR16_TAIL);
9543 
9544     subq(length, 32);
9545     bind(VECTOR32_LOOP);
9546     vmovdqu(rymm0, Address(obja, result));
9547     vmovdqu(rymm1, Address(objb, result));
9548     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9549     vptest(rymm2, rymm2);
9550     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9551     addq(result, 32);
9552     subq(length, 32);
9553     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9554     addq(length, 32);
9555     jcc(Assembler::equal, SAME_TILL_END);
9556     //falling through if less than 32 bytes left //close the branch here.
9557 
9558     bind(VECTOR16_TAIL);
9559     cmpq(length, 16);
9560     jccb(Assembler::less, VECTOR8_TAIL);
9561     bind(VECTOR16_LOOP);
9562     movdqu(rymm0, Address(obja, result));
9563     movdqu(rymm1, Address(objb, result));
9564     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9565     ptest(rymm2, rymm2);
9566     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9567     addq(result, 16);
9568     subq(length, 16);
9569     jcc(Assembler::equal, SAME_TILL_END);
9570     //falling through if less than 16 bytes left
9571   } else {//regular intrinsics
9572 
9573     cmpq(length, 16);
9574     jccb(Assembler::less, VECTOR8_TAIL);
9575 
9576     subq(length, 16);
9577     bind(VECTOR16_LOOP);
9578     movdqu(rymm0, Address(obja, result));
9579     movdqu(rymm1, Address(objb, result));
9580     pxor(rymm0, rymm1);
9581     ptest(rymm0, rymm0);
9582     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9583     addq(result, 16);
9584     subq(length, 16);
9585     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9586     addq(length, 16);
9587     jcc(Assembler::equal, SAME_TILL_END);
9588     //falling through if less than 16 bytes left
9589   }
9590 
9591   bind(VECTOR8_TAIL);
9592   cmpq(length, 8);
9593   jccb(Assembler::less, VECTOR4_TAIL);
9594   bind(VECTOR8_LOOP);
9595   movq(tmp1, Address(obja, result));
9596   movq(tmp2, Address(objb, result));
9597   xorq(tmp1, tmp2);
9598   testq(tmp1, tmp1);
9599   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9600   addq(result, 8);
9601   subq(length, 8);
9602   jcc(Assembler::equal, SAME_TILL_END);
9603   //falling through if less than 8 bytes left
9604 
9605   bind(VECTOR4_TAIL);
9606   cmpq(length, 4);
9607   jccb(Assembler::less, BYTES_TAIL);
9608   bind(VECTOR4_LOOP);
9609   movl(tmp1, Address(obja, result));
9610   xorl(tmp1, Address(objb, result));
9611   testl(tmp1, tmp1);
9612   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9613   addq(result, 4);
9614   subq(length, 4);
9615   jcc(Assembler::equal, SAME_TILL_END);
9616   //falling through if less than 4 bytes left
9617 
9618   bind(BYTES_TAIL);
9619   bind(BYTES_LOOP);
9620   load_unsigned_byte(tmp1, Address(obja, result));
9621   load_unsigned_byte(tmp2, Address(objb, result));
9622   xorl(tmp1, tmp2);
9623   testl(tmp1, tmp1);
9624   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9625   decq(length);
9626   jccb(Assembler::zero, SAME_TILL_END);
9627   incq(result);
9628   load_unsigned_byte(tmp1, Address(obja, result));
9629   load_unsigned_byte(tmp2, Address(objb, result));
9630   xorl(tmp1, tmp2);
9631   testl(tmp1, tmp1);
9632   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9633   decq(length);
9634   jccb(Assembler::zero, SAME_TILL_END);
9635   incq(result);
9636   load_unsigned_byte(tmp1, Address(obja, result));
9637   load_unsigned_byte(tmp2, Address(objb, result));
9638   xorl(tmp1, tmp2);
9639   testl(tmp1, tmp1);
9640   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9641   jmpb(SAME_TILL_END);
9642 
9643   if (UseAVX >= 2) {
9644     bind(VECTOR32_NOT_EQUAL);
9645     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9646     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9647     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9648     vpmovmskb(tmp1, rymm0);
9649     bsfq(tmp1, tmp1);
9650     addq(result, tmp1);
9651     shrq(result);
9652     jmpb(DONE);
9653   }
9654 
9655   bind(VECTOR16_NOT_EQUAL);
9656   if (UseAVX >= 2) {
9657     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9658     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9659     pxor(rymm0, rymm2);
9660   } else {
9661     pcmpeqb(rymm2, rymm2);
9662     pxor(rymm0, rymm1);
9663     pcmpeqb(rymm0, rymm1);
9664     pxor(rymm0, rymm2);
9665   }
9666   pmovmskb(tmp1, rymm0);
9667   bsfq(tmp1, tmp1);
9668   addq(result, tmp1);
9669   shrq(result);
9670   jmpb(DONE);
9671 
9672   bind(VECTOR8_NOT_EQUAL);
9673   bind(VECTOR4_NOT_EQUAL);
9674   bsfq(tmp1, tmp1);
9675   shrq(tmp1, 3);
9676   addq(result, tmp1);
9677   bind(BYTES_NOT_EQUAL);
9678   shrq(result);
9679   jmpb(DONE);
9680 
9681   bind(SAME_TILL_END);
9682   mov64(result, -1);
9683 
9684   bind(DONE);
9685 }
9686 
9687 //Helper functions for square_to_len()
9688 
9689 /**
9690  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9691  * Preserves x and z and modifies rest of the registers.
9692  */
9693 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9694   // Perform square and right shift by 1
9695   // Handle odd xlen case first, then for even xlen do the following
9696   // jlong carry = 0;
9697   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9698   //     huge_128 product = x[j:j+1] * x[j:j+1];
9699   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9700   //     z[i+2:i+3] = (jlong)(product >>> 1);
9701   //     carry = (jlong)product;
9702   // }
9703 
9704   xorq(tmp5, tmp5);     // carry
9705   xorq(rdxReg, rdxReg);
9706   xorl(tmp1, tmp1);     // index for x
9707   xorl(tmp4, tmp4);     // index for z
9708 
9709   Label L_first_loop, L_first_loop_exit;
9710 
9711   testl(xlen, 1);
9712   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9713 
9714   // Square and right shift by 1 the odd element using 32 bit multiply
9715   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9716   imulq(raxReg, raxReg);
9717   shrq(raxReg, 1);
9718   adcq(tmp5, 0);
9719   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9720   incrementl(tmp1);
9721   addl(tmp4, 2);
9722 
9723   // Square and  right shift by 1 the rest using 64 bit multiply
9724   bind(L_first_loop);
9725   cmpptr(tmp1, xlen);
9726   jccb(Assembler::equal, L_first_loop_exit);
9727 
9728   // Square
9729   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9730   rorq(raxReg, 32);    // convert big-endian to little-endian
9731   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9732 
9733   // Right shift by 1 and save carry
9734   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9735   rcrq(rdxReg, 1);
9736   rcrq(raxReg, 1);
9737   adcq(tmp5, 0);
9738 
9739   // Store result in z
9740   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9741   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9742 
9743   // Update indices for x and z
9744   addl(tmp1, 2);
9745   addl(tmp4, 4);
9746   jmp(L_first_loop);
9747 
9748   bind(L_first_loop_exit);
9749 }
9750 
9751 
9752 /**
9753  * Perform the following multiply add operation using BMI2 instructions
9754  * carry:sum = sum + op1*op2 + carry
9755  * op2 should be in rdx
9756  * op2 is preserved, all other registers are modified
9757  */
9758 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9759   // assert op2 is rdx
9760   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9761   addq(sum, carry);
9762   adcq(tmp2, 0);
9763   addq(sum, op1);
9764   adcq(tmp2, 0);
9765   movq(carry, tmp2);
9766 }
9767 
9768 /**
9769  * Perform the following multiply add operation:
9770  * carry:sum = sum + op1*op2 + carry
9771  * Preserves op1, op2 and modifies rest of registers
9772  */
9773 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9774   // rdx:rax = op1 * op2
9775   movq(raxReg, op2);
9776   mulq(op1);
9777 
9778   //  rdx:rax = sum + carry + rdx:rax
9779   addq(sum, carry);
9780   adcq(rdxReg, 0);
9781   addq(sum, raxReg);
9782   adcq(rdxReg, 0);
9783 
9784   // carry:sum = rdx:sum
9785   movq(carry, rdxReg);
9786 }
9787 
9788 /**
9789  * Add 64 bit long carry into z[] with carry propogation.
9790  * Preserves z and carry register values and modifies rest of registers.
9791  *
9792  */
9793 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9794   Label L_fourth_loop, L_fourth_loop_exit;
9795 
9796   movl(tmp1, 1);
9797   subl(zlen, 2);
9798   addq(Address(z, zlen, Address::times_4, 0), carry);
9799 
9800   bind(L_fourth_loop);
9801   jccb(Assembler::carryClear, L_fourth_loop_exit);
9802   subl(zlen, 2);
9803   jccb(Assembler::negative, L_fourth_loop_exit);
9804   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9805   jmp(L_fourth_loop);
9806   bind(L_fourth_loop_exit);
9807 }
9808 
9809 /**
9810  * Shift z[] left by 1 bit.
9811  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9812  *
9813  */
9814 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9815 
9816   Label L_fifth_loop, L_fifth_loop_exit;
9817 
9818   // Fifth loop
9819   // Perform primitiveLeftShift(z, zlen, 1)
9820 
9821   const Register prev_carry = tmp1;
9822   const Register new_carry = tmp4;
9823   const Register value = tmp2;
9824   const Register zidx = tmp3;
9825 
9826   // int zidx, carry;
9827   // long value;
9828   // carry = 0;
9829   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9830   //    (carry:value)  = (z[i] << 1) | carry ;
9831   //    z[i] = value;
9832   // }
9833 
9834   movl(zidx, zlen);
9835   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9836 
9837   bind(L_fifth_loop);
9838   decl(zidx);  // Use decl to preserve carry flag
9839   decl(zidx);
9840   jccb(Assembler::negative, L_fifth_loop_exit);
9841 
9842   if (UseBMI2Instructions) {
9843      movq(value, Address(z, zidx, Address::times_4, 0));
9844      rclq(value, 1);
9845      rorxq(value, value, 32);
9846      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9847   }
9848   else {
9849     // clear new_carry
9850     xorl(new_carry, new_carry);
9851 
9852     // Shift z[i] by 1, or in previous carry and save new carry
9853     movq(value, Address(z, zidx, Address::times_4, 0));
9854     shlq(value, 1);
9855     adcl(new_carry, 0);
9856 
9857     orq(value, prev_carry);
9858     rorq(value, 0x20);
9859     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9860 
9861     // Set previous carry = new carry
9862     movl(prev_carry, new_carry);
9863   }
9864   jmp(L_fifth_loop);
9865 
9866   bind(L_fifth_loop_exit);
9867 }
9868 
9869 
9870 /**
9871  * Code for BigInteger::squareToLen() intrinsic
9872  *
9873  * rdi: x
9874  * rsi: len
9875  * r8:  z
9876  * rcx: zlen
9877  * r12: tmp1
9878  * r13: tmp2
9879  * r14: tmp3
9880  * r15: tmp4
9881  * rbx: tmp5
9882  *
9883  */
9884 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) {
9885 
9886   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;
9887   push(tmp1);
9888   push(tmp2);
9889   push(tmp3);
9890   push(tmp4);
9891   push(tmp5);
9892 
9893   // First loop
9894   // Store the squares, right shifted one bit (i.e., divided by 2).
9895   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9896 
9897   // Add in off-diagonal sums.
9898   //
9899   // Second, third (nested) and fourth loops.
9900   // zlen +=2;
9901   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9902   //    carry = 0;
9903   //    long op2 = x[xidx:xidx+1];
9904   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9905   //       k -= 2;
9906   //       long op1 = x[j:j+1];
9907   //       long sum = z[k:k+1];
9908   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9909   //       z[k:k+1] = sum;
9910   //    }
9911   //    add_one_64(z, k, carry, tmp_regs);
9912   // }
9913 
9914   const Register carry = tmp5;
9915   const Register sum = tmp3;
9916   const Register op1 = tmp4;
9917   Register op2 = tmp2;
9918 
9919   push(zlen);
9920   push(len);
9921   addl(zlen,2);
9922   bind(L_second_loop);
9923   xorq(carry, carry);
9924   subl(zlen, 4);
9925   subl(len, 2);
9926   push(zlen);
9927   push(len);
9928   cmpl(len, 0);
9929   jccb(Assembler::lessEqual, L_second_loop_exit);
9930 
9931   // Multiply an array by one 64 bit long.
9932   if (UseBMI2Instructions) {
9933     op2 = rdxReg;
9934     movq(op2, Address(x, len, Address::times_4,  0));
9935     rorxq(op2, op2, 32);
9936   }
9937   else {
9938     movq(op2, Address(x, len, Address::times_4,  0));
9939     rorq(op2, 32);
9940   }
9941 
9942   bind(L_third_loop);
9943   decrementl(len);
9944   jccb(Assembler::negative, L_third_loop_exit);
9945   decrementl(len);
9946   jccb(Assembler::negative, L_last_x);
9947 
9948   movq(op1, Address(x, len, Address::times_4,  0));
9949   rorq(op1, 32);
9950 
9951   bind(L_multiply);
9952   subl(zlen, 2);
9953   movq(sum, Address(z, zlen, Address::times_4,  0));
9954 
9955   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9956   if (UseBMI2Instructions) {
9957     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9958   }
9959   else {
9960     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9961   }
9962 
9963   movq(Address(z, zlen, Address::times_4, 0), sum);
9964 
9965   jmp(L_third_loop);
9966   bind(L_third_loop_exit);
9967 
9968   // Fourth loop
9969   // Add 64 bit long carry into z with carry propogation.
9970   // Uses offsetted zlen.
9971   add_one_64(z, zlen, carry, tmp1);
9972 
9973   pop(len);
9974   pop(zlen);
9975   jmp(L_second_loop);
9976 
9977   // Next infrequent code is moved outside loops.
9978   bind(L_last_x);
9979   movl(op1, Address(x, 0));
9980   jmp(L_multiply);
9981 
9982   bind(L_second_loop_exit);
9983   pop(len);
9984   pop(zlen);
9985   pop(len);
9986   pop(zlen);
9987 
9988   // Fifth loop
9989   // Shift z left 1 bit.
9990   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9991 
9992   // z[zlen-1] |= x[len-1] & 1;
9993   movl(tmp3, Address(x, len, Address::times_4, -4));
9994   andl(tmp3, 1);
9995   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9996 
9997   pop(tmp5);
9998   pop(tmp4);
9999   pop(tmp3);
10000   pop(tmp2);
10001   pop(tmp1);
10002 }
10003 
10004 /**
10005  * Helper function for mul_add()
10006  * Multiply the in[] by int k and add to out[] starting at offset offs using
10007  * 128 bit by 32 bit multiply and return the carry in tmp5.
10008  * Only quad int aligned length of in[] is operated on in this function.
10009  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
10010  * This function preserves out, in and k registers.
10011  * len and offset point to the appropriate index in "in" & "out" correspondingly
10012  * tmp5 has the carry.
10013  * other registers are temporary and are modified.
10014  *
10015  */
10016 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
10017   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
10018   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10019 
10020   Label L_first_loop, L_first_loop_exit;
10021 
10022   movl(tmp1, len);
10023   shrl(tmp1, 2);
10024 
10025   bind(L_first_loop);
10026   subl(tmp1, 1);
10027   jccb(Assembler::negative, L_first_loop_exit);
10028 
10029   subl(len, 4);
10030   subl(offset, 4);
10031 
10032   Register op2 = tmp2;
10033   const Register sum = tmp3;
10034   const Register op1 = tmp4;
10035   const Register carry = tmp5;
10036 
10037   if (UseBMI2Instructions) {
10038     op2 = rdxReg;
10039   }
10040 
10041   movq(op1, Address(in, len, Address::times_4,  8));
10042   rorq(op1, 32);
10043   movq(sum, Address(out, offset, Address::times_4,  8));
10044   rorq(sum, 32);
10045   if (UseBMI2Instructions) {
10046     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10047   }
10048   else {
10049     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10050   }
10051   // Store back in big endian from little endian
10052   rorq(sum, 0x20);
10053   movq(Address(out, offset, Address::times_4,  8), sum);
10054 
10055   movq(op1, Address(in, len, Address::times_4,  0));
10056   rorq(op1, 32);
10057   movq(sum, Address(out, offset, Address::times_4,  0));
10058   rorq(sum, 32);
10059   if (UseBMI2Instructions) {
10060     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10061   }
10062   else {
10063     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10064   }
10065   // Store back in big endian from little endian
10066   rorq(sum, 0x20);
10067   movq(Address(out, offset, Address::times_4,  0), sum);
10068 
10069   jmp(L_first_loop);
10070   bind(L_first_loop_exit);
10071 }
10072 
10073 /**
10074  * Code for BigInteger::mulAdd() intrinsic
10075  *
10076  * rdi: out
10077  * rsi: in
10078  * r11: offs (out.length - offset)
10079  * rcx: len
10080  * r8:  k
10081  * r12: tmp1
10082  * r13: tmp2
10083  * r14: tmp3
10084  * r15: tmp4
10085  * rbx: tmp5
10086  * Multiply the in[] by word k and add to out[], return the carry in rax
10087  */
10088 void MacroAssembler::mul_add(Register out, Register in, Register offs,
10089    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
10090    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
10091 
10092   Label L_carry, L_last_in, L_done;
10093 
10094 // carry = 0;
10095 // for (int j=len-1; j >= 0; j--) {
10096 //    long product = (in[j] & LONG_MASK) * kLong +
10097 //                   (out[offs] & LONG_MASK) + carry;
10098 //    out[offs--] = (int)product;
10099 //    carry = product >>> 32;
10100 // }
10101 //
10102   push(tmp1);
10103   push(tmp2);
10104   push(tmp3);
10105   push(tmp4);
10106   push(tmp5);
10107 
10108   Register op2 = tmp2;
10109   const Register sum = tmp3;
10110   const Register op1 = tmp4;
10111   const Register carry =  tmp5;
10112 
10113   if (UseBMI2Instructions) {
10114     op2 = rdxReg;
10115     movl(op2, k);
10116   }
10117   else {
10118     movl(op2, k);
10119   }
10120 
10121   xorq(carry, carry);
10122 
10123   //First loop
10124 
10125   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
10126   //The carry is in tmp5
10127   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
10128 
10129   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
10130   decrementl(len);
10131   jccb(Assembler::negative, L_carry);
10132   decrementl(len);
10133   jccb(Assembler::negative, L_last_in);
10134 
10135   movq(op1, Address(in, len, Address::times_4,  0));
10136   rorq(op1, 32);
10137 
10138   subl(offs, 2);
10139   movq(sum, Address(out, offs, Address::times_4,  0));
10140   rorq(sum, 32);
10141 
10142   if (UseBMI2Instructions) {
10143     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
10144   }
10145   else {
10146     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
10147   }
10148 
10149   // Store back in big endian from little endian
10150   rorq(sum, 0x20);
10151   movq(Address(out, offs, Address::times_4,  0), sum);
10152 
10153   testl(len, len);
10154   jccb(Assembler::zero, L_carry);
10155 
10156   //Multiply the last in[] entry, if any
10157   bind(L_last_in);
10158   movl(op1, Address(in, 0));
10159   movl(sum, Address(out, offs, Address::times_4,  -4));
10160 
10161   movl(raxReg, k);
10162   mull(op1); //tmp4 * eax -> edx:eax
10163   addl(sum, carry);
10164   adcl(rdxReg, 0);
10165   addl(sum, raxReg);
10166   adcl(rdxReg, 0);
10167   movl(carry, rdxReg);
10168 
10169   movl(Address(out, offs, Address::times_4,  -4), sum);
10170 
10171   bind(L_carry);
10172   //return tmp5/carry as carry in rax
10173   movl(rax, carry);
10174 
10175   bind(L_done);
10176   pop(tmp5);
10177   pop(tmp4);
10178   pop(tmp3);
10179   pop(tmp2);
10180   pop(tmp1);
10181 }
10182 #endif
10183 
10184 /**
10185  * Emits code to update CRC-32 with a byte value according to constants in table
10186  *
10187  * @param [in,out]crc   Register containing the crc.
10188  * @param [in]val       Register containing the byte to fold into the CRC.
10189  * @param [in]table     Register containing the table of crc constants.
10190  *
10191  * uint32_t crc;
10192  * val = crc_table[(val ^ crc) & 0xFF];
10193  * crc = val ^ (crc >> 8);
10194  *
10195  */
10196 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
10197   xorl(val, crc);
10198   andl(val, 0xFF);
10199   shrl(crc, 8); // unsigned shift
10200   xorl(crc, Address(table, val, Address::times_4, 0));
10201 }
10202 
10203 /**
10204  * Fold 128-bit data chunk
10205  */
10206 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
10207   if (UseAVX > 0) {
10208     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
10209     vpclmulldq(xcrc, xK, xcrc); // [63:0]
10210     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
10211     pxor(xcrc, xtmp);
10212   } else {
10213     movdqa(xtmp, xcrc);
10214     pclmulhdq(xtmp, xK);   // [123:64]
10215     pclmulldq(xcrc, xK);   // [63:0]
10216     pxor(xcrc, xtmp);
10217     movdqu(xtmp, Address(buf, offset));
10218     pxor(xcrc, xtmp);
10219   }
10220 }
10221 
10222 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
10223   if (UseAVX > 0) {
10224     vpclmulhdq(xtmp, xK, xcrc);
10225     vpclmulldq(xcrc, xK, xcrc);
10226     pxor(xcrc, xbuf);
10227     pxor(xcrc, xtmp);
10228   } else {
10229     movdqa(xtmp, xcrc);
10230     pclmulhdq(xtmp, xK);
10231     pclmulldq(xcrc, xK);
10232     pxor(xcrc, xbuf);
10233     pxor(xcrc, xtmp);
10234   }
10235 }
10236 
10237 /**
10238  * 8-bit folds to compute 32-bit CRC
10239  *
10240  * uint64_t xcrc;
10241  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
10242  */
10243 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
10244   movdl(tmp, xcrc);
10245   andl(tmp, 0xFF);
10246   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
10247   psrldq(xcrc, 1); // unsigned shift one byte
10248   pxor(xcrc, xtmp);
10249 }
10250 
10251 /**
10252  * uint32_t crc;
10253  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
10254  */
10255 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
10256   movl(tmp, crc);
10257   andl(tmp, 0xFF);
10258   shrl(crc, 8);
10259   xorl(crc, Address(table, tmp, Address::times_4, 0));
10260 }
10261 
10262 /**
10263  * @param crc   register containing existing CRC (32-bit)
10264  * @param buf   register pointing to input byte buffer (byte*)
10265  * @param len   register containing number of bytes
10266  * @param table register that will contain address of CRC table
10267  * @param tmp   scratch register
10268  */
10269 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
10270   assert_different_registers(crc, buf, len, table, tmp, rax);
10271 
10272   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
10273   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
10274 
10275   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
10276   // context for the registers used, where all instructions below are using 128-bit mode
10277   // On EVEX without VL and BW, these instructions will all be AVX.
10278   if (VM_Version::supports_avx512vlbw()) {
10279     movl(tmp, 0xffff);
10280     kmovwl(k1, tmp);
10281   }
10282 
10283   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10284   notl(crc); // ~crc
10285   cmpl(len, 16);
10286   jcc(Assembler::less, L_tail);
10287 
10288   // Align buffer to 16 bytes
10289   movl(tmp, buf);
10290   andl(tmp, 0xF);
10291   jccb(Assembler::zero, L_aligned);
10292   subl(tmp,  16);
10293   addl(len, tmp);
10294 
10295   align(4);
10296   BIND(L_align_loop);
10297   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10298   update_byte_crc32(crc, rax, table);
10299   increment(buf);
10300   incrementl(tmp);
10301   jccb(Assembler::less, L_align_loop);
10302 
10303   BIND(L_aligned);
10304   movl(tmp, len); // save
10305   shrl(len, 4);
10306   jcc(Assembler::zero, L_tail_restore);
10307 
10308   // Fold crc into first bytes of vector
10309   movdqa(xmm1, Address(buf, 0));
10310   movdl(rax, xmm1);
10311   xorl(crc, rax);
10312   if (VM_Version::supports_sse4_1()) {
10313     pinsrd(xmm1, crc, 0);
10314   } else {
10315     pinsrw(xmm1, crc, 0);
10316     shrl(crc, 16);
10317     pinsrw(xmm1, crc, 1);
10318   }
10319   addptr(buf, 16);
10320   subl(len, 4); // len > 0
10321   jcc(Assembler::less, L_fold_tail);
10322 
10323   movdqa(xmm2, Address(buf,  0));
10324   movdqa(xmm3, Address(buf, 16));
10325   movdqa(xmm4, Address(buf, 32));
10326   addptr(buf, 48);
10327   subl(len, 3);
10328   jcc(Assembler::lessEqual, L_fold_512b);
10329 
10330   // Fold total 512 bits of polynomial on each iteration,
10331   // 128 bits per each of 4 parallel streams.
10332   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10333 
10334   align(32);
10335   BIND(L_fold_512b_loop);
10336   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10337   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10338   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10339   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10340   addptr(buf, 64);
10341   subl(len, 4);
10342   jcc(Assembler::greater, L_fold_512b_loop);
10343 
10344   // Fold 512 bits to 128 bits.
10345   BIND(L_fold_512b);
10346   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10347   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10348   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10349   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10350 
10351   // Fold the rest of 128 bits data chunks
10352   BIND(L_fold_tail);
10353   addl(len, 3);
10354   jccb(Assembler::lessEqual, L_fold_128b);
10355   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10356 
10357   BIND(L_fold_tail_loop);
10358   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10359   addptr(buf, 16);
10360   decrementl(len);
10361   jccb(Assembler::greater, L_fold_tail_loop);
10362 
10363   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10364   BIND(L_fold_128b);
10365   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10366   if (UseAVX > 0) {
10367     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10368     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10369     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10370   } else {
10371     movdqa(xmm2, xmm0);
10372     pclmulqdq(xmm2, xmm1, 0x1);
10373     movdqa(xmm3, xmm0);
10374     pand(xmm3, xmm2);
10375     pclmulqdq(xmm0, xmm3, 0x1);
10376   }
10377   psrldq(xmm1, 8);
10378   psrldq(xmm2, 4);
10379   pxor(xmm0, xmm1);
10380   pxor(xmm0, xmm2);
10381 
10382   // 8 8-bit folds to compute 32-bit CRC.
10383   for (int j = 0; j < 4; j++) {
10384     fold_8bit_crc32(xmm0, table, xmm1, rax);
10385   }
10386   movdl(crc, xmm0); // mov 32 bits to general register
10387   for (int j = 0; j < 4; j++) {
10388     fold_8bit_crc32(crc, table, rax);
10389   }
10390 
10391   BIND(L_tail_restore);
10392   movl(len, tmp); // restore
10393   BIND(L_tail);
10394   andl(len, 0xf);
10395   jccb(Assembler::zero, L_exit);
10396 
10397   // Fold the rest of bytes
10398   align(4);
10399   BIND(L_tail_loop);
10400   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10401   update_byte_crc32(crc, rax, table);
10402   increment(buf);
10403   decrementl(len);
10404   jccb(Assembler::greater, L_tail_loop);
10405 
10406   BIND(L_exit);
10407   notl(crc); // ~c
10408 }
10409 
10410 #ifdef _LP64
10411 // S. Gueron / Information Processing Letters 112 (2012) 184
10412 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10413 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10414 // Output: the 64-bit carry-less product of B * CONST
10415 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10416                                      Register tmp1, Register tmp2, Register tmp3) {
10417   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10418   if (n > 0) {
10419     addq(tmp3, n * 256 * 8);
10420   }
10421   //    Q1 = TABLEExt[n][B & 0xFF];
10422   movl(tmp1, in);
10423   andl(tmp1, 0x000000FF);
10424   shll(tmp1, 3);
10425   addq(tmp1, tmp3);
10426   movq(tmp1, Address(tmp1, 0));
10427 
10428   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10429   movl(tmp2, in);
10430   shrl(tmp2, 8);
10431   andl(tmp2, 0x000000FF);
10432   shll(tmp2, 3);
10433   addq(tmp2, tmp3);
10434   movq(tmp2, Address(tmp2, 0));
10435 
10436   shlq(tmp2, 8);
10437   xorq(tmp1, tmp2);
10438 
10439   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10440   movl(tmp2, in);
10441   shrl(tmp2, 16);
10442   andl(tmp2, 0x000000FF);
10443   shll(tmp2, 3);
10444   addq(tmp2, tmp3);
10445   movq(tmp2, Address(tmp2, 0));
10446 
10447   shlq(tmp2, 16);
10448   xorq(tmp1, tmp2);
10449 
10450   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10451   shrl(in, 24);
10452   andl(in, 0x000000FF);
10453   shll(in, 3);
10454   addq(in, tmp3);
10455   movq(in, Address(in, 0));
10456 
10457   shlq(in, 24);
10458   xorq(in, tmp1);
10459   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10460 }
10461 
10462 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10463                                       Register in_out,
10464                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10465                                       XMMRegister w_xtmp2,
10466                                       Register tmp1,
10467                                       Register n_tmp2, Register n_tmp3) {
10468   if (is_pclmulqdq_supported) {
10469     movdl(w_xtmp1, in_out); // modified blindly
10470 
10471     movl(tmp1, const_or_pre_comp_const_index);
10472     movdl(w_xtmp2, tmp1);
10473     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10474 
10475     movdq(in_out, w_xtmp1);
10476   } else {
10477     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10478   }
10479 }
10480 
10481 // Recombination Alternative 2: No bit-reflections
10482 // T1 = (CRC_A * U1) << 1
10483 // T2 = (CRC_B * U2) << 1
10484 // C1 = T1 >> 32
10485 // C2 = T2 >> 32
10486 // T1 = T1 & 0xFFFFFFFF
10487 // T2 = T2 & 0xFFFFFFFF
10488 // T1 = CRC32(0, T1)
10489 // T2 = CRC32(0, T2)
10490 // C1 = C1 ^ T1
10491 // C2 = C2 ^ T2
10492 // CRC = C1 ^ C2 ^ CRC_C
10493 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,
10494                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10495                                      Register tmp1, Register tmp2,
10496                                      Register n_tmp3) {
10497   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10498   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10499   shlq(in_out, 1);
10500   movl(tmp1, in_out);
10501   shrq(in_out, 32);
10502   xorl(tmp2, tmp2);
10503   crc32(tmp2, tmp1, 4);
10504   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10505   shlq(in1, 1);
10506   movl(tmp1, in1);
10507   shrq(in1, 32);
10508   xorl(tmp2, tmp2);
10509   crc32(tmp2, tmp1, 4);
10510   xorl(in1, tmp2);
10511   xorl(in_out, in1);
10512   xorl(in_out, in2);
10513 }
10514 
10515 // Set N to predefined value
10516 // Subtract from a lenght of a buffer
10517 // execute in a loop:
10518 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10519 // for i = 1 to N do
10520 //  CRC_A = CRC32(CRC_A, A[i])
10521 //  CRC_B = CRC32(CRC_B, B[i])
10522 //  CRC_C = CRC32(CRC_C, C[i])
10523 // end for
10524 // Recombine
10525 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,
10526                                        Register in_out1, Register in_out2, Register in_out3,
10527                                        Register tmp1, Register tmp2, Register tmp3,
10528                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10529                                        Register tmp4, Register tmp5,
10530                                        Register n_tmp6) {
10531   Label L_processPartitions;
10532   Label L_processPartition;
10533   Label L_exit;
10534 
10535   bind(L_processPartitions);
10536   cmpl(in_out1, 3 * size);
10537   jcc(Assembler::less, L_exit);
10538     xorl(tmp1, tmp1);
10539     xorl(tmp2, tmp2);
10540     movq(tmp3, in_out2);
10541     addq(tmp3, size);
10542 
10543     bind(L_processPartition);
10544       crc32(in_out3, Address(in_out2, 0), 8);
10545       crc32(tmp1, Address(in_out2, size), 8);
10546       crc32(tmp2, Address(in_out2, size * 2), 8);
10547       addq(in_out2, 8);
10548       cmpq(in_out2, tmp3);
10549       jcc(Assembler::less, L_processPartition);
10550     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10551             w_xtmp1, w_xtmp2, w_xtmp3,
10552             tmp4, tmp5,
10553             n_tmp6);
10554     addq(in_out2, 2 * size);
10555     subl(in_out1, 3 * size);
10556     jmp(L_processPartitions);
10557 
10558   bind(L_exit);
10559 }
10560 #else
10561 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10562                                      Register tmp1, Register tmp2, Register tmp3,
10563                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10564   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10565   if (n > 0) {
10566     addl(tmp3, n * 256 * 8);
10567   }
10568   //    Q1 = TABLEExt[n][B & 0xFF];
10569   movl(tmp1, in_out);
10570   andl(tmp1, 0x000000FF);
10571   shll(tmp1, 3);
10572   addl(tmp1, tmp3);
10573   movq(xtmp1, Address(tmp1, 0));
10574 
10575   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10576   movl(tmp2, in_out);
10577   shrl(tmp2, 8);
10578   andl(tmp2, 0x000000FF);
10579   shll(tmp2, 3);
10580   addl(tmp2, tmp3);
10581   movq(xtmp2, Address(tmp2, 0));
10582 
10583   psllq(xtmp2, 8);
10584   pxor(xtmp1, xtmp2);
10585 
10586   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10587   movl(tmp2, in_out);
10588   shrl(tmp2, 16);
10589   andl(tmp2, 0x000000FF);
10590   shll(tmp2, 3);
10591   addl(tmp2, tmp3);
10592   movq(xtmp2, Address(tmp2, 0));
10593 
10594   psllq(xtmp2, 16);
10595   pxor(xtmp1, xtmp2);
10596 
10597   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10598   shrl(in_out, 24);
10599   andl(in_out, 0x000000FF);
10600   shll(in_out, 3);
10601   addl(in_out, tmp3);
10602   movq(xtmp2, Address(in_out, 0));
10603 
10604   psllq(xtmp2, 24);
10605   pxor(xtmp1, xtmp2); // Result in CXMM
10606   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10607 }
10608 
10609 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10610                                       Register in_out,
10611                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10612                                       XMMRegister w_xtmp2,
10613                                       Register tmp1,
10614                                       Register n_tmp2, Register n_tmp3) {
10615   if (is_pclmulqdq_supported) {
10616     movdl(w_xtmp1, in_out);
10617 
10618     movl(tmp1, const_or_pre_comp_const_index);
10619     movdl(w_xtmp2, tmp1);
10620     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10621     // Keep result in XMM since GPR is 32 bit in length
10622   } else {
10623     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10624   }
10625 }
10626 
10627 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,
10628                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10629                                      Register tmp1, Register tmp2,
10630                                      Register n_tmp3) {
10631   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10632   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10633 
10634   psllq(w_xtmp1, 1);
10635   movdl(tmp1, w_xtmp1);
10636   psrlq(w_xtmp1, 32);
10637   movdl(in_out, w_xtmp1);
10638 
10639   xorl(tmp2, tmp2);
10640   crc32(tmp2, tmp1, 4);
10641   xorl(in_out, tmp2);
10642 
10643   psllq(w_xtmp2, 1);
10644   movdl(tmp1, w_xtmp2);
10645   psrlq(w_xtmp2, 32);
10646   movdl(in1, w_xtmp2);
10647 
10648   xorl(tmp2, tmp2);
10649   crc32(tmp2, tmp1, 4);
10650   xorl(in1, tmp2);
10651   xorl(in_out, in1);
10652   xorl(in_out, in2);
10653 }
10654 
10655 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,
10656                                        Register in_out1, Register in_out2, Register in_out3,
10657                                        Register tmp1, Register tmp2, Register tmp3,
10658                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10659                                        Register tmp4, Register tmp5,
10660                                        Register n_tmp6) {
10661   Label L_processPartitions;
10662   Label L_processPartition;
10663   Label L_exit;
10664 
10665   bind(L_processPartitions);
10666   cmpl(in_out1, 3 * size);
10667   jcc(Assembler::less, L_exit);
10668     xorl(tmp1, tmp1);
10669     xorl(tmp2, tmp2);
10670     movl(tmp3, in_out2);
10671     addl(tmp3, size);
10672 
10673     bind(L_processPartition);
10674       crc32(in_out3, Address(in_out2, 0), 4);
10675       crc32(tmp1, Address(in_out2, size), 4);
10676       crc32(tmp2, Address(in_out2, size*2), 4);
10677       crc32(in_out3, Address(in_out2, 0+4), 4);
10678       crc32(tmp1, Address(in_out2, size+4), 4);
10679       crc32(tmp2, Address(in_out2, size*2+4), 4);
10680       addl(in_out2, 8);
10681       cmpl(in_out2, tmp3);
10682       jcc(Assembler::less, L_processPartition);
10683 
10684         push(tmp3);
10685         push(in_out1);
10686         push(in_out2);
10687         tmp4 = tmp3;
10688         tmp5 = in_out1;
10689         n_tmp6 = in_out2;
10690 
10691       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10692             w_xtmp1, w_xtmp2, w_xtmp3,
10693             tmp4, tmp5,
10694             n_tmp6);
10695 
10696         pop(in_out2);
10697         pop(in_out1);
10698         pop(tmp3);
10699 
10700     addl(in_out2, 2 * size);
10701     subl(in_out1, 3 * size);
10702     jmp(L_processPartitions);
10703 
10704   bind(L_exit);
10705 }
10706 #endif //LP64
10707 
10708 #ifdef _LP64
10709 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10710 // Input: A buffer I of L bytes.
10711 // Output: the CRC32C value of the buffer.
10712 // Notations:
10713 // Write L = 24N + r, with N = floor (L/24).
10714 // r = L mod 24 (0 <= r < 24).
10715 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10716 // N quadwords, and R consists of r bytes.
10717 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10718 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10719 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10720 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10721 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10722                                           Register tmp1, Register tmp2, Register tmp3,
10723                                           Register tmp4, Register tmp5, Register tmp6,
10724                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10725                                           bool is_pclmulqdq_supported) {
10726   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10727   Label L_wordByWord;
10728   Label L_byteByByteProlog;
10729   Label L_byteByByte;
10730   Label L_exit;
10731 
10732   if (is_pclmulqdq_supported ) {
10733     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10734     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10735 
10736     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10737     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10738 
10739     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10740     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10741     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10742   } else {
10743     const_or_pre_comp_const_index[0] = 1;
10744     const_or_pre_comp_const_index[1] = 0;
10745 
10746     const_or_pre_comp_const_index[2] = 3;
10747     const_or_pre_comp_const_index[3] = 2;
10748 
10749     const_or_pre_comp_const_index[4] = 5;
10750     const_or_pre_comp_const_index[5] = 4;
10751    }
10752   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10753                     in2, in1, in_out,
10754                     tmp1, tmp2, tmp3,
10755                     w_xtmp1, w_xtmp2, w_xtmp3,
10756                     tmp4, tmp5,
10757                     tmp6);
10758   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10759                     in2, in1, in_out,
10760                     tmp1, tmp2, tmp3,
10761                     w_xtmp1, w_xtmp2, w_xtmp3,
10762                     tmp4, tmp5,
10763                     tmp6);
10764   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10765                     in2, in1, in_out,
10766                     tmp1, tmp2, tmp3,
10767                     w_xtmp1, w_xtmp2, w_xtmp3,
10768                     tmp4, tmp5,
10769                     tmp6);
10770   movl(tmp1, in2);
10771   andl(tmp1, 0x00000007);
10772   negl(tmp1);
10773   addl(tmp1, in2);
10774   addq(tmp1, in1);
10775 
10776   BIND(L_wordByWord);
10777   cmpq(in1, tmp1);
10778   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10779     crc32(in_out, Address(in1, 0), 4);
10780     addq(in1, 4);
10781     jmp(L_wordByWord);
10782 
10783   BIND(L_byteByByteProlog);
10784   andl(in2, 0x00000007);
10785   movl(tmp2, 1);
10786 
10787   BIND(L_byteByByte);
10788   cmpl(tmp2, in2);
10789   jccb(Assembler::greater, L_exit);
10790     crc32(in_out, Address(in1, 0), 1);
10791     incq(in1);
10792     incl(tmp2);
10793     jmp(L_byteByByte);
10794 
10795   BIND(L_exit);
10796 }
10797 #else
10798 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10799                                           Register tmp1, Register  tmp2, Register tmp3,
10800                                           Register tmp4, Register  tmp5, Register tmp6,
10801                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10802                                           bool is_pclmulqdq_supported) {
10803   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10804   Label L_wordByWord;
10805   Label L_byteByByteProlog;
10806   Label L_byteByByte;
10807   Label L_exit;
10808 
10809   if (is_pclmulqdq_supported) {
10810     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10811     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10812 
10813     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10814     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10815 
10816     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10817     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10818   } else {
10819     const_or_pre_comp_const_index[0] = 1;
10820     const_or_pre_comp_const_index[1] = 0;
10821 
10822     const_or_pre_comp_const_index[2] = 3;
10823     const_or_pre_comp_const_index[3] = 2;
10824 
10825     const_or_pre_comp_const_index[4] = 5;
10826     const_or_pre_comp_const_index[5] = 4;
10827   }
10828   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], 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   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10835                     in2, in1, in_out,
10836                     tmp1, tmp2, tmp3,
10837                     w_xtmp1, w_xtmp2, w_xtmp3,
10838                     tmp4, tmp5,
10839                     tmp6);
10840   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10841                     in2, in1, in_out,
10842                     tmp1, tmp2, tmp3,
10843                     w_xtmp1, w_xtmp2, w_xtmp3,
10844                     tmp4, tmp5,
10845                     tmp6);
10846   movl(tmp1, in2);
10847   andl(tmp1, 0x00000007);
10848   negl(tmp1);
10849   addl(tmp1, in2);
10850   addl(tmp1, in1);
10851 
10852   BIND(L_wordByWord);
10853   cmpl(in1, tmp1);
10854   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10855     crc32(in_out, Address(in1,0), 4);
10856     addl(in1, 4);
10857     jmp(L_wordByWord);
10858 
10859   BIND(L_byteByByteProlog);
10860   andl(in2, 0x00000007);
10861   movl(tmp2, 1);
10862 
10863   BIND(L_byteByByte);
10864   cmpl(tmp2, in2);
10865   jccb(Assembler::greater, L_exit);
10866     movb(tmp1, Address(in1, 0));
10867     crc32(in_out, tmp1, 1);
10868     incl(in1);
10869     incl(tmp2);
10870     jmp(L_byteByByte);
10871 
10872   BIND(L_exit);
10873 }
10874 #endif // LP64
10875 #undef BIND
10876 #undef BLOCK_COMMENT
10877 
10878 // Compress char[] array to byte[].
10879 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10880 //   @HotSpotIntrinsicCandidate
10881 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10882 //     for (int i = 0; i < len; i++) {
10883 //       int c = src[srcOff++];
10884 //       if (c >>> 8 != 0) {
10885 //         return 0;
10886 //       }
10887 //       dst[dstOff++] = (byte)c;
10888 //     }
10889 //     return len;
10890 //   }
10891 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10892   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10893   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10894   Register tmp5, Register result) {
10895   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10896 
10897   // rsi: src
10898   // rdi: dst
10899   // rdx: len
10900   // rcx: tmp5
10901   // rax: result
10902 
10903   // rsi holds start addr of source char[] to be compressed
10904   // rdi holds start addr of destination byte[]
10905   // rdx holds length
10906 
10907   assert(len != result, "");
10908 
10909   // save length for return
10910   push(len);
10911 
10912   if ((UseAVX > 2) && // AVX512
10913     VM_Version::supports_avx512vlbw() &&
10914     VM_Version::supports_bmi2()) {
10915 
10916     set_vector_masking();  // opening of the stub context for programming mask registers
10917 
10918     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10919 
10920     // alignement
10921     Label post_alignement;
10922 
10923     // if length of the string is less than 16, handle it in an old fashioned
10924     // way
10925     testl(len, -32);
10926     jcc(Assembler::zero, below_threshold);
10927 
10928     // First check whether a character is compressable ( <= 0xFF).
10929     // Create mask to test for Unicode chars inside zmm vector
10930     movl(result, 0x00FF);
10931     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10932 
10933     // Save k1
10934     kmovql(k3, k1);
10935 
10936     testl(len, -64);
10937     jcc(Assembler::zero, post_alignement);
10938 
10939     movl(tmp5, dst);
10940     andl(tmp5, (32 - 1));
10941     negl(tmp5);
10942     andl(tmp5, (32 - 1));
10943 
10944     // bail out when there is nothing to be done
10945     testl(tmp5, 0xFFFFFFFF);
10946     jcc(Assembler::zero, post_alignement);
10947 
10948     // ~(~0 << len), where len is the # of remaining elements to process
10949     movl(result, 0xFFFFFFFF);
10950     shlxl(result, result, tmp5);
10951     notl(result);
10952     kmovdl(k1, result);
10953 
10954     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10955     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10956     ktestd(k2, k1);
10957     jcc(Assembler::carryClear, restore_k1_return_zero);
10958 
10959     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10960 
10961     addptr(src, tmp5);
10962     addptr(src, tmp5);
10963     addptr(dst, tmp5);
10964     subl(len, tmp5);
10965 
10966     bind(post_alignement);
10967     // end of alignement
10968 
10969     movl(tmp5, len);
10970     andl(tmp5, (32 - 1));    // tail count (in chars)
10971     andl(len, ~(32 - 1));    // vector count (in chars)
10972     jcc(Assembler::zero, copy_loop_tail);
10973 
10974     lea(src, Address(src, len, Address::times_2));
10975     lea(dst, Address(dst, len, Address::times_1));
10976     negptr(len);
10977 
10978     bind(copy_32_loop);
10979     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10980     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10981     kortestdl(k2, k2);
10982     jcc(Assembler::carryClear, restore_k1_return_zero);
10983 
10984     // All elements in current processed chunk are valid candidates for
10985     // compression. Write a truncated byte elements to the memory.
10986     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10987     addptr(len, 32);
10988     jcc(Assembler::notZero, copy_32_loop);
10989 
10990     bind(copy_loop_tail);
10991     // bail out when there is nothing to be done
10992     testl(tmp5, 0xFFFFFFFF);
10993     // Restore k1
10994     kmovql(k1, k3);
10995     jcc(Assembler::zero, return_length);
10996 
10997     movl(len, tmp5);
10998 
10999     // ~(~0 << len), where len is the # of remaining elements to process
11000     movl(result, 0xFFFFFFFF);
11001     shlxl(result, result, len);
11002     notl(result);
11003 
11004     kmovdl(k1, result);
11005 
11006     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
11007     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
11008     ktestd(k2, k1);
11009     jcc(Assembler::carryClear, restore_k1_return_zero);
11010 
11011     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
11012     // Restore k1
11013     kmovql(k1, k3);
11014     jmp(return_length);
11015 
11016     bind(restore_k1_return_zero);
11017     // Restore k1
11018     kmovql(k1, k3);
11019     jmp(return_zero);
11020 
11021     clear_vector_masking();   // closing of the stub context for programming mask registers
11022   }
11023   if (UseSSE42Intrinsics) {
11024     Label copy_32_loop, copy_16, copy_tail;
11025 
11026     bind(below_threshold);
11027 
11028     movl(result, len);
11029 
11030     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
11031 
11032     // vectored compression
11033     andl(len, 0xfffffff0);    // vector count (in chars)
11034     andl(result, 0x0000000f);    // tail count (in chars)
11035     testl(len, len);
11036     jccb(Assembler::zero, copy_16);
11037 
11038     // compress 16 chars per iter
11039     movdl(tmp1Reg, tmp5);
11040     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11041     pxor(tmp4Reg, tmp4Reg);
11042 
11043     lea(src, Address(src, len, Address::times_2));
11044     lea(dst, Address(dst, len, Address::times_1));
11045     negptr(len);
11046 
11047     bind(copy_32_loop);
11048     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
11049     por(tmp4Reg, tmp2Reg);
11050     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
11051     por(tmp4Reg, tmp3Reg);
11052     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
11053     jcc(Assembler::notZero, return_zero);
11054     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
11055     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
11056     addptr(len, 16);
11057     jcc(Assembler::notZero, copy_32_loop);
11058 
11059     // compress next vector of 8 chars (if any)
11060     bind(copy_16);
11061     movl(len, result);
11062     andl(len, 0xfffffff8);    // vector count (in chars)
11063     andl(result, 0x00000007);    // tail count (in chars)
11064     testl(len, len);
11065     jccb(Assembler::zero, copy_tail);
11066 
11067     movdl(tmp1Reg, tmp5);
11068     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
11069     pxor(tmp3Reg, tmp3Reg);
11070 
11071     movdqu(tmp2Reg, Address(src, 0));
11072     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
11073     jccb(Assembler::notZero, return_zero);
11074     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
11075     movq(Address(dst, 0), tmp2Reg);
11076     addptr(src, 16);
11077     addptr(dst, 8);
11078 
11079     bind(copy_tail);
11080     movl(len, result);
11081   }
11082   // compress 1 char per iter
11083   testl(len, len);
11084   jccb(Assembler::zero, return_length);
11085   lea(src, Address(src, len, Address::times_2));
11086   lea(dst, Address(dst, len, Address::times_1));
11087   negptr(len);
11088 
11089   bind(copy_chars_loop);
11090   load_unsigned_short(result, Address(src, len, Address::times_2));
11091   testl(result, 0xff00);      // check if Unicode char
11092   jccb(Assembler::notZero, return_zero);
11093   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
11094   increment(len);
11095   jcc(Assembler::notZero, copy_chars_loop);
11096 
11097   // if compression succeeded, return length
11098   bind(return_length);
11099   pop(result);
11100   jmpb(done);
11101 
11102   // if compression failed, return 0
11103   bind(return_zero);
11104   xorl(result, result);
11105   addptr(rsp, wordSize);
11106 
11107   bind(done);
11108 }
11109 
11110 // Inflate byte[] array to char[].
11111 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
11112 //   @HotSpotIntrinsicCandidate
11113 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
11114 //     for (int i = 0; i < len; i++) {
11115 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
11116 //     }
11117 //   }
11118 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
11119   XMMRegister tmp1, Register tmp2) {
11120   Label copy_chars_loop, done, below_threshold;
11121   // rsi: src
11122   // rdi: dst
11123   // rdx: len
11124   // rcx: tmp2
11125 
11126   // rsi holds start addr of source byte[] to be inflated
11127   // rdi holds start addr of destination char[]
11128   // rdx holds length
11129   assert_different_registers(src, dst, len, tmp2);
11130 
11131   if ((UseAVX > 2) && // AVX512
11132     VM_Version::supports_avx512vlbw() &&
11133     VM_Version::supports_bmi2()) {
11134 
11135     set_vector_masking();  // opening of the stub context for programming mask registers
11136 
11137     Label copy_32_loop, copy_tail;
11138     Register tmp3_aliased = len;
11139 
11140     // if length of the string is less than 16, handle it in an old fashioned
11141     // way
11142     testl(len, -16);
11143     jcc(Assembler::zero, below_threshold);
11144 
11145     // In order to use only one arithmetic operation for the main loop we use
11146     // this pre-calculation
11147     movl(tmp2, len);
11148     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
11149     andl(len, -32);     // vector count
11150     jccb(Assembler::zero, copy_tail);
11151 
11152     lea(src, Address(src, len, Address::times_1));
11153     lea(dst, Address(dst, len, Address::times_2));
11154     negptr(len);
11155 
11156 
11157     // inflate 32 chars per iter
11158     bind(copy_32_loop);
11159     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
11160     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
11161     addptr(len, 32);
11162     jcc(Assembler::notZero, copy_32_loop);
11163 
11164     bind(copy_tail);
11165     // bail out when there is nothing to be done
11166     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
11167     jcc(Assembler::zero, done);
11168 
11169     // Save k1
11170     kmovql(k2, k1);
11171 
11172     // ~(~0 << length), where length is the # of remaining elements to process
11173     movl(tmp3_aliased, -1);
11174     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
11175     notl(tmp3_aliased);
11176     kmovdl(k1, tmp3_aliased);
11177     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
11178     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
11179 
11180     // Restore k1
11181     kmovql(k1, k2);
11182     jmp(done);
11183 
11184     clear_vector_masking();   // closing of the stub context for programming mask registers
11185   }
11186   if (UseSSE42Intrinsics) {
11187     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
11188 
11189     movl(tmp2, len);
11190 
11191     if (UseAVX > 1) {
11192       andl(tmp2, (16 - 1));
11193       andl(len, -16);
11194       jccb(Assembler::zero, copy_new_tail);
11195     } else {
11196       andl(tmp2, 0x00000007);   // tail count (in chars)
11197       andl(len, 0xfffffff8);    // vector count (in chars)
11198       jccb(Assembler::zero, copy_tail);
11199     }
11200 
11201     // vectored inflation
11202     lea(src, Address(src, len, Address::times_1));
11203     lea(dst, Address(dst, len, Address::times_2));
11204     negptr(len);
11205 
11206     if (UseAVX > 1) {
11207       bind(copy_16_loop);
11208       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
11209       vmovdqu(Address(dst, len, Address::times_2), tmp1);
11210       addptr(len, 16);
11211       jcc(Assembler::notZero, copy_16_loop);
11212 
11213       bind(below_threshold);
11214       bind(copy_new_tail);
11215       if ((UseAVX > 2) &&
11216         VM_Version::supports_avx512vlbw() &&
11217         VM_Version::supports_bmi2()) {
11218         movl(tmp2, len);
11219       } else {
11220         movl(len, tmp2);
11221       }
11222       andl(tmp2, 0x00000007);
11223       andl(len, 0xFFFFFFF8);
11224       jccb(Assembler::zero, copy_tail);
11225 
11226       pmovzxbw(tmp1, Address(src, 0));
11227       movdqu(Address(dst, 0), tmp1);
11228       addptr(src, 8);
11229       addptr(dst, 2 * 8);
11230 
11231       jmp(copy_tail, true);
11232     }
11233 
11234     // inflate 8 chars per iter
11235     bind(copy_8_loop);
11236     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
11237     movdqu(Address(dst, len, Address::times_2), tmp1);
11238     addptr(len, 8);
11239     jcc(Assembler::notZero, copy_8_loop);
11240 
11241     bind(copy_tail);
11242     movl(len, tmp2);
11243 
11244     cmpl(len, 4);
11245     jccb(Assembler::less, copy_bytes);
11246 
11247     movdl(tmp1, Address(src, 0));  // load 4 byte chars
11248     pmovzxbw(tmp1, tmp1);
11249     movq(Address(dst, 0), tmp1);
11250     subptr(len, 4);
11251     addptr(src, 4);
11252     addptr(dst, 8);
11253 
11254     bind(copy_bytes);
11255   }
11256   testl(len, len);
11257   jccb(Assembler::zero, done);
11258   lea(src, Address(src, len, Address::times_1));
11259   lea(dst, Address(dst, len, Address::times_2));
11260   negptr(len);
11261 
11262   // inflate 1 char per iter
11263   bind(copy_chars_loop);
11264   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11265   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11266   increment(len);
11267   jcc(Assembler::notZero, copy_chars_loop);
11268 
11269   bind(done);
11270 }
11271 
11272 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11273   switch (cond) {
11274     // Note some conditions are synonyms for others
11275     case Assembler::zero:         return Assembler::notZero;
11276     case Assembler::notZero:      return Assembler::zero;
11277     case Assembler::less:         return Assembler::greaterEqual;
11278     case Assembler::lessEqual:    return Assembler::greater;
11279     case Assembler::greater:      return Assembler::lessEqual;
11280     case Assembler::greaterEqual: return Assembler::less;
11281     case Assembler::below:        return Assembler::aboveEqual;
11282     case Assembler::belowEqual:   return Assembler::above;
11283     case Assembler::above:        return Assembler::belowEqual;
11284     case Assembler::aboveEqual:   return Assembler::below;
11285     case Assembler::overflow:     return Assembler::noOverflow;
11286     case Assembler::noOverflow:   return Assembler::overflow;
11287     case Assembler::negative:     return Assembler::positive;
11288     case Assembler::positive:     return Assembler::negative;
11289     case Assembler::parity:       return Assembler::noParity;
11290     case Assembler::noParity:     return Assembler::parity;
11291   }
11292   ShouldNotReachHere(); return Assembler::overflow;
11293 }
11294 
11295 SkipIfEqual::SkipIfEqual(
11296     MacroAssembler* masm, const bool* flag_addr, bool value) {
11297   _masm = masm;
11298   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11299   _masm->jcc(Assembler::equal, _label);
11300 }
11301 
11302 SkipIfEqual::~SkipIfEqual() {
11303   _masm->bind(_label);
11304 }
11305 
11306 // 32-bit Windows has its own fast-path implementation
11307 // of get_thread
11308 #if !defined(WIN32) || defined(_LP64)
11309 
11310 // This is simply a call to Thread::current()
11311 void MacroAssembler::get_thread(Register thread) {
11312   if (thread != rax) {
11313     push(rax);
11314   }
11315   LP64_ONLY(push(rdi);)
11316   LP64_ONLY(push(rsi);)
11317   push(rdx);
11318   push(rcx);
11319 #ifdef _LP64
11320   push(r8);
11321   push(r9);
11322   push(r10);
11323   push(r11);
11324 #endif
11325 
11326   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11327 
11328 #ifdef _LP64
11329   pop(r11);
11330   pop(r10);
11331   pop(r9);
11332   pop(r8);
11333 #endif
11334   pop(rcx);
11335   pop(rdx);
11336   LP64_ONLY(pop(rsi);)
11337   LP64_ONLY(pop(rdi);)
11338   if (thread != rax) {
11339     mov(thread, rax);
11340     pop(rax);
11341   }
11342 }
11343 
11344 #endif