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/barrierSet.hpp"
  31 #include "gc/shared/barrierSetAssembler.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/accessDecorators.hpp"
  37 #include "oops/klass.inline.hpp"
  38 #include "oops/oop.hpp"
  39 #include "prims/methodHandles.hpp"
  40 #include "runtime/biasedLocking.hpp"
  41 #include "runtime/flags/flagSetting.hpp"
  42 #include "runtime/interfaceSupport.inline.hpp"
  43 #include "runtime/objectMonitor.hpp"
  44 #include "runtime/os.hpp"
  45 #include "runtime/safepoint.hpp"
  46 #include "runtime/safepointMechanism.hpp"
  47 #include "runtime/sharedRuntime.hpp"
  48 #include "runtime/stubRoutines.hpp"
  49 #include "runtime/thread.hpp"
  50 #include "utilities/macros.hpp"
  51 #include "crc32c.h"
  52 #ifdef COMPILER2
  53 #include "opto/intrinsicnode.hpp"
  54 #endif
  55 #if INCLUDE_SHENANDOAHGC
  56 #include "gc/shenandoah/shenandoahBarrierSetAssembler.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, Register arg_0) {
2626   pass_arg0(this, arg_0);
2627   MacroAssembler::call_VM_leaf_base(entry_point, 1);
2628 }
2629 
2630 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1) {
2631 
2632   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2633   pass_arg1(this, arg_1);
2634   pass_arg0(this, arg_0);
2635   MacroAssembler::call_VM_leaf_base(entry_point, 2);
2636 }
2637 
2638 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2) {
2639   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2640   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2641   pass_arg2(this, arg_2);
2642   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2643   pass_arg1(this, arg_1);
2644   pass_arg0(this, arg_0);
2645   MacroAssembler::call_VM_leaf_base(entry_point, 3);
2646 }
2647 
2648 void MacroAssembler::super_call_VM_leaf(address entry_point, Register arg_0, Register arg_1, Register arg_2, Register arg_3) {
2649   LP64_ONLY(assert(arg_0 != c_rarg3, "smashed arg"));
2650   LP64_ONLY(assert(arg_1 != c_rarg3, "smashed arg"));
2651   LP64_ONLY(assert(arg_2 != c_rarg3, "smashed arg"));
2652   pass_arg3(this, arg_3);
2653   LP64_ONLY(assert(arg_0 != c_rarg2, "smashed arg"));
2654   LP64_ONLY(assert(arg_1 != c_rarg2, "smashed arg"));
2655   pass_arg2(this, arg_2);
2656   LP64_ONLY(assert(arg_0 != c_rarg1, "smashed arg"));
2657   pass_arg1(this, arg_1);
2658   pass_arg0(this, arg_0);
2659   MacroAssembler::call_VM_leaf_base(entry_point, 4);
2660 }
2661 
2662 void MacroAssembler::get_vm_result(Register oop_result, Register java_thread) {
2663   movptr(oop_result, Address(java_thread, JavaThread::vm_result_offset()));
2664   movptr(Address(java_thread, JavaThread::vm_result_offset()), NULL_WORD);
2665   verify_oop(oop_result, "broken oop in call_VM_base");
2666 }
2667 
2668 void MacroAssembler::get_vm_result_2(Register metadata_result, Register java_thread) {
2669   movptr(metadata_result, Address(java_thread, JavaThread::vm_result_2_offset()));
2670   movptr(Address(java_thread, JavaThread::vm_result_2_offset()), NULL_WORD);
2671 }
2672 
2673 void MacroAssembler::check_and_handle_earlyret(Register java_thread) {
2674 }
2675 
2676 void MacroAssembler::check_and_handle_popframe(Register java_thread) {
2677 }
2678 
2679 void MacroAssembler::cmp32(AddressLiteral src1, int32_t imm) {
2680   if (reachable(src1)) {
2681     cmpl(as_Address(src1), imm);
2682   } else {
2683     lea(rscratch1, src1);
2684     cmpl(Address(rscratch1, 0), imm);
2685   }
2686 }
2687 
2688 void MacroAssembler::cmp32(Register src1, AddressLiteral src2) {
2689   assert(!src2.is_lval(), "use cmpptr");
2690   if (reachable(src2)) {
2691     cmpl(src1, as_Address(src2));
2692   } else {
2693     lea(rscratch1, src2);
2694     cmpl(src1, Address(rscratch1, 0));
2695   }
2696 }
2697 
2698 void MacroAssembler::cmp32(Register src1, int32_t imm) {
2699   Assembler::cmpl(src1, imm);
2700 }
2701 
2702 void MacroAssembler::cmp32(Register src1, Address src2) {
2703   Assembler::cmpl(src1, src2);
2704 }
2705 
2706 void MacroAssembler::cmpsd2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2707   ucomisd(opr1, opr2);
2708 
2709   Label L;
2710   if (unordered_is_less) {
2711     movl(dst, -1);
2712     jcc(Assembler::parity, L);
2713     jcc(Assembler::below , L);
2714     movl(dst, 0);
2715     jcc(Assembler::equal , L);
2716     increment(dst);
2717   } else { // unordered is greater
2718     movl(dst, 1);
2719     jcc(Assembler::parity, L);
2720     jcc(Assembler::above , L);
2721     movl(dst, 0);
2722     jcc(Assembler::equal , L);
2723     decrementl(dst);
2724   }
2725   bind(L);
2726 }
2727 
2728 void MacroAssembler::cmpss2int(XMMRegister opr1, XMMRegister opr2, Register dst, bool unordered_is_less) {
2729   ucomiss(opr1, opr2);
2730 
2731   Label L;
2732   if (unordered_is_less) {
2733     movl(dst, -1);
2734     jcc(Assembler::parity, L);
2735     jcc(Assembler::below , L);
2736     movl(dst, 0);
2737     jcc(Assembler::equal , L);
2738     increment(dst);
2739   } else { // unordered is greater
2740     movl(dst, 1);
2741     jcc(Assembler::parity, L);
2742     jcc(Assembler::above , L);
2743     movl(dst, 0);
2744     jcc(Assembler::equal , L);
2745     decrementl(dst);
2746   }
2747   bind(L);
2748 }
2749 
2750 
2751 void MacroAssembler::cmp8(AddressLiteral src1, int imm) {
2752   if (reachable(src1)) {
2753     cmpb(as_Address(src1), imm);
2754   } else {
2755     lea(rscratch1, src1);
2756     cmpb(Address(rscratch1, 0), imm);
2757   }
2758 }
2759 
2760 void MacroAssembler::cmpptr(Register src1, AddressLiteral src2) {
2761 #ifdef _LP64
2762   if (src2.is_lval()) {
2763     movptr(rscratch1, src2);
2764     Assembler::cmpq(src1, rscratch1);
2765   } else if (reachable(src2)) {
2766     cmpq(src1, as_Address(src2));
2767   } else {
2768     lea(rscratch1, src2);
2769     Assembler::cmpq(src1, Address(rscratch1, 0));
2770   }
2771 #else
2772   if (src2.is_lval()) {
2773     cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2774   } else {
2775     cmpl(src1, as_Address(src2));
2776   }
2777 #endif // _LP64
2778 }
2779 
2780 void MacroAssembler::cmpptr(Address src1, AddressLiteral src2) {
2781   assert(src2.is_lval(), "not a mem-mem compare");
2782 #ifdef _LP64
2783   // moves src2's literal address
2784   movptr(rscratch1, src2);
2785   Assembler::cmpq(src1, rscratch1);
2786 #else
2787   cmp_literal32(src1, (int32_t) src2.target(), src2.rspec());
2788 #endif // _LP64
2789 }
2790 
2791 void MacroAssembler::cmpoop(Register src1, Register src2) {
2792   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2793   bs->obj_equals(this, IN_HEAP, src1, src2);
2794 }
2795 
2796 void MacroAssembler::cmpoop(Register src1, Address src2) {
2797   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2798   bs->obj_equals_addr(this, IN_HEAP, src1, src2);
2799 }
2800 
2801 #ifdef _LP64
2802 void MacroAssembler::cmpoop(Register src1, jobject src2) {
2803   movoop(rscratch1, src2);
2804   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
2805   bs->obj_equals(this, IN_HEAP, src1, rscratch1);
2806 }
2807 #endif
2808 
2809 void MacroAssembler::locked_cmpxchgptr(Register reg, AddressLiteral adr) {
2810   if (reachable(adr)) {
2811     if (os::is_MP())
2812       lock();
2813     cmpxchgptr(reg, as_Address(adr));
2814   } else {
2815     lea(rscratch1, adr);
2816     if (os::is_MP())
2817       lock();
2818     cmpxchgptr(reg, Address(rscratch1, 0));
2819   }
2820 }
2821 
2822 void MacroAssembler::cmpxchgptr(Register reg, Address adr) {
2823   LP64_ONLY(cmpxchgq(reg, adr)) NOT_LP64(cmpxchgl(reg, adr));
2824 }
2825 
2826 void MacroAssembler::comisd(XMMRegister dst, AddressLiteral src) {
2827   if (reachable(src)) {
2828     Assembler::comisd(dst, as_Address(src));
2829   } else {
2830     lea(rscratch1, src);
2831     Assembler::comisd(dst, Address(rscratch1, 0));
2832   }
2833 }
2834 
2835 void MacroAssembler::comiss(XMMRegister dst, AddressLiteral src) {
2836   if (reachable(src)) {
2837     Assembler::comiss(dst, as_Address(src));
2838   } else {
2839     lea(rscratch1, src);
2840     Assembler::comiss(dst, Address(rscratch1, 0));
2841   }
2842 }
2843 
2844 
2845 void MacroAssembler::cond_inc32(Condition cond, AddressLiteral counter_addr) {
2846   Condition negated_cond = negate_condition(cond);
2847   Label L;
2848   jcc(negated_cond, L);
2849   pushf(); // Preserve flags
2850   atomic_incl(counter_addr);
2851   popf();
2852   bind(L);
2853 }
2854 
2855 int MacroAssembler::corrected_idivl(Register reg) {
2856   // Full implementation of Java idiv and irem; checks for
2857   // special case as described in JVM spec., p.243 & p.271.
2858   // The function returns the (pc) offset of the idivl
2859   // instruction - may be needed for implicit exceptions.
2860   //
2861   //         normal case                           special case
2862   //
2863   // input : rax,: dividend                         min_int
2864   //         reg: divisor   (may not be rax,/rdx)   -1
2865   //
2866   // output: rax,: quotient  (= rax, idiv reg)       min_int
2867   //         rdx: remainder (= rax, irem reg)       0
2868   assert(reg != rax && reg != rdx, "reg cannot be rax, or rdx register");
2869   const int min_int = 0x80000000;
2870   Label normal_case, special_case;
2871 
2872   // check for special case
2873   cmpl(rax, min_int);
2874   jcc(Assembler::notEqual, normal_case);
2875   xorl(rdx, rdx); // prepare rdx for possible special case (where remainder = 0)
2876   cmpl(reg, -1);
2877   jcc(Assembler::equal, special_case);
2878 
2879   // handle normal case
2880   bind(normal_case);
2881   cdql();
2882   int idivl_offset = offset();
2883   idivl(reg);
2884 
2885   // normal and special case exit
2886   bind(special_case);
2887 
2888   return idivl_offset;
2889 }
2890 
2891 
2892 
2893 void MacroAssembler::decrementl(Register reg, int value) {
2894   if (value == min_jint) {subl(reg, value) ; return; }
2895   if (value <  0) { incrementl(reg, -value); return; }
2896   if (value == 0) {                        ; return; }
2897   if (value == 1 && UseIncDec) { decl(reg) ; return; }
2898   /* else */      { subl(reg, value)       ; return; }
2899 }
2900 
2901 void MacroAssembler::decrementl(Address dst, int value) {
2902   if (value == min_jint) {subl(dst, value) ; return; }
2903   if (value <  0) { incrementl(dst, -value); return; }
2904   if (value == 0) {                        ; return; }
2905   if (value == 1 && UseIncDec) { decl(dst) ; return; }
2906   /* else */      { subl(dst, value)       ; return; }
2907 }
2908 
2909 void MacroAssembler::division_with_shift (Register reg, int shift_value) {
2910   assert (shift_value > 0, "illegal shift value");
2911   Label _is_positive;
2912   testl (reg, reg);
2913   jcc (Assembler::positive, _is_positive);
2914   int offset = (1 << shift_value) - 1 ;
2915 
2916   if (offset == 1) {
2917     incrementl(reg);
2918   } else {
2919     addl(reg, offset);
2920   }
2921 
2922   bind (_is_positive);
2923   sarl(reg, shift_value);
2924 }
2925 
2926 void MacroAssembler::divsd(XMMRegister dst, AddressLiteral src) {
2927   if (reachable(src)) {
2928     Assembler::divsd(dst, as_Address(src));
2929   } else {
2930     lea(rscratch1, src);
2931     Assembler::divsd(dst, Address(rscratch1, 0));
2932   }
2933 }
2934 
2935 void MacroAssembler::divss(XMMRegister dst, AddressLiteral src) {
2936   if (reachable(src)) {
2937     Assembler::divss(dst, as_Address(src));
2938   } else {
2939     lea(rscratch1, src);
2940     Assembler::divss(dst, Address(rscratch1, 0));
2941   }
2942 }
2943 
2944 // !defined(COMPILER2) is because of stupid core builds
2945 #if !defined(_LP64) || defined(COMPILER1) || !defined(COMPILER2) || INCLUDE_JVMCI
2946 void MacroAssembler::empty_FPU_stack() {
2947   if (VM_Version::supports_mmx()) {
2948     emms();
2949   } else {
2950     for (int i = 8; i-- > 0; ) ffree(i);
2951   }
2952 }
2953 #endif // !LP64 || C1 || !C2 || INCLUDE_JVMCI
2954 
2955 
2956 // Defines obj, preserves var_size_in_bytes
2957 void MacroAssembler::eden_allocate(Register obj,
2958                                    Register var_size_in_bytes,
2959                                    int con_size_in_bytes,
2960                                    Register t1,
2961                                    Label& slow_case) {
2962   assert(obj == rax, "obj must be in rax, for cmpxchg");
2963   assert_different_registers(obj, var_size_in_bytes, t1);
2964   if (!Universe::heap()->supports_inline_contig_alloc()) {
2965     jmp(slow_case);
2966   } else {
2967     Register end = t1;
2968     Label retry;
2969     bind(retry);
2970     ExternalAddress heap_top((address) Universe::heap()->top_addr());
2971     movptr(obj, heap_top);
2972     if (var_size_in_bytes == noreg) {
2973       lea(end, Address(obj, con_size_in_bytes));
2974     } else {
2975       lea(end, Address(obj, var_size_in_bytes, Address::times_1));
2976     }
2977     // if end < obj then we wrapped around => object too long => slow case
2978     cmpptr(end, obj);
2979     jcc(Assembler::below, slow_case);
2980     cmpptr(end, ExternalAddress((address) Universe::heap()->end_addr()));
2981     jcc(Assembler::above, slow_case);
2982     // Compare obj with the top addr, and if still equal, store the new top addr in
2983     // end at the address of the top addr pointer. Sets ZF if was equal, and clears
2984     // it otherwise. Use lock prefix for atomicity on MPs.
2985     locked_cmpxchgptr(end, heap_top);
2986     jcc(Assembler::notEqual, retry);
2987   }
2988 }
2989 
2990 void MacroAssembler::enter() {
2991   push(rbp);
2992   mov(rbp, rsp);
2993 }
2994 
2995 // A 5 byte nop that is safe for patching (see patch_verified_entry)
2996 void MacroAssembler::fat_nop() {
2997   if (UseAddressNop) {
2998     addr_nop_5();
2999   } else {
3000     emit_int8(0x26); // es:
3001     emit_int8(0x2e); // cs:
3002     emit_int8(0x64); // fs:
3003     emit_int8(0x65); // gs:
3004     emit_int8((unsigned char)0x90);
3005   }
3006 }
3007 
3008 void MacroAssembler::fcmp(Register tmp) {
3009   fcmp(tmp, 1, true, true);
3010 }
3011 
3012 void MacroAssembler::fcmp(Register tmp, int index, bool pop_left, bool pop_right) {
3013   assert(!pop_right || pop_left, "usage error");
3014   if (VM_Version::supports_cmov()) {
3015     assert(tmp == noreg, "unneeded temp");
3016     if (pop_left) {
3017       fucomip(index);
3018     } else {
3019       fucomi(index);
3020     }
3021     if (pop_right) {
3022       fpop();
3023     }
3024   } else {
3025     assert(tmp != noreg, "need temp");
3026     if (pop_left) {
3027       if (pop_right) {
3028         fcompp();
3029       } else {
3030         fcomp(index);
3031       }
3032     } else {
3033       fcom(index);
3034     }
3035     // convert FPU condition into eflags condition via rax,
3036     save_rax(tmp);
3037     fwait(); fnstsw_ax();
3038     sahf();
3039     restore_rax(tmp);
3040   }
3041   // condition codes set as follows:
3042   //
3043   // CF (corresponds to C0) if x < y
3044   // PF (corresponds to C2) if unordered
3045   // ZF (corresponds to C3) if x = y
3046 }
3047 
3048 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less) {
3049   fcmp2int(dst, unordered_is_less, 1, true, true);
3050 }
3051 
3052 void MacroAssembler::fcmp2int(Register dst, bool unordered_is_less, int index, bool pop_left, bool pop_right) {
3053   fcmp(VM_Version::supports_cmov() ? noreg : dst, index, pop_left, pop_right);
3054   Label L;
3055   if (unordered_is_less) {
3056     movl(dst, -1);
3057     jcc(Assembler::parity, L);
3058     jcc(Assembler::below , L);
3059     movl(dst, 0);
3060     jcc(Assembler::equal , L);
3061     increment(dst);
3062   } else { // unordered is greater
3063     movl(dst, 1);
3064     jcc(Assembler::parity, L);
3065     jcc(Assembler::above , L);
3066     movl(dst, 0);
3067     jcc(Assembler::equal , L);
3068     decrementl(dst);
3069   }
3070   bind(L);
3071 }
3072 
3073 void MacroAssembler::fld_d(AddressLiteral src) {
3074   fld_d(as_Address(src));
3075 }
3076 
3077 void MacroAssembler::fld_s(AddressLiteral src) {
3078   fld_s(as_Address(src));
3079 }
3080 
3081 void MacroAssembler::fld_x(AddressLiteral src) {
3082   Assembler::fld_x(as_Address(src));
3083 }
3084 
3085 void MacroAssembler::fldcw(AddressLiteral src) {
3086   Assembler::fldcw(as_Address(src));
3087 }
3088 
3089 void MacroAssembler::mulpd(XMMRegister dst, AddressLiteral src) {
3090   if (reachable(src)) {
3091     Assembler::mulpd(dst, as_Address(src));
3092   } else {
3093     lea(rscratch1, src);
3094     Assembler::mulpd(dst, Address(rscratch1, 0));
3095   }
3096 }
3097 
3098 void MacroAssembler::increase_precision() {
3099   subptr(rsp, BytesPerWord);
3100   fnstcw(Address(rsp, 0));
3101   movl(rax, Address(rsp, 0));
3102   orl(rax, 0x300);
3103   push(rax);
3104   fldcw(Address(rsp, 0));
3105   pop(rax);
3106 }
3107 
3108 void MacroAssembler::restore_precision() {
3109   fldcw(Address(rsp, 0));
3110   addptr(rsp, BytesPerWord);
3111 }
3112 
3113 void MacroAssembler::fpop() {
3114   ffree();
3115   fincstp();
3116 }
3117 
3118 void MacroAssembler::load_float(Address src) {
3119   if (UseSSE >= 1) {
3120     movflt(xmm0, src);
3121   } else {
3122     LP64_ONLY(ShouldNotReachHere());
3123     NOT_LP64(fld_s(src));
3124   }
3125 }
3126 
3127 void MacroAssembler::store_float(Address dst) {
3128   if (UseSSE >= 1) {
3129     movflt(dst, xmm0);
3130   } else {
3131     LP64_ONLY(ShouldNotReachHere());
3132     NOT_LP64(fstp_s(dst));
3133   }
3134 }
3135 
3136 void MacroAssembler::load_double(Address src) {
3137   if (UseSSE >= 2) {
3138     movdbl(xmm0, src);
3139   } else {
3140     LP64_ONLY(ShouldNotReachHere());
3141     NOT_LP64(fld_d(src));
3142   }
3143 }
3144 
3145 void MacroAssembler::store_double(Address dst) {
3146   if (UseSSE >= 2) {
3147     movdbl(dst, xmm0);
3148   } else {
3149     LP64_ONLY(ShouldNotReachHere());
3150     NOT_LP64(fstp_d(dst));
3151   }
3152 }
3153 
3154 void MacroAssembler::fremr(Register tmp) {
3155   save_rax(tmp);
3156   { Label L;
3157     bind(L);
3158     fprem();
3159     fwait(); fnstsw_ax();
3160 #ifdef _LP64
3161     testl(rax, 0x400);
3162     jcc(Assembler::notEqual, L);
3163 #else
3164     sahf();
3165     jcc(Assembler::parity, L);
3166 #endif // _LP64
3167   }
3168   restore_rax(tmp);
3169   // Result is in ST0.
3170   // Note: fxch & fpop to get rid of ST1
3171   // (otherwise FPU stack could overflow eventually)
3172   fxch(1);
3173   fpop();
3174 }
3175 
3176 // dst = c = a * b + c
3177 void MacroAssembler::fmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3178   Assembler::vfmadd231sd(c, a, b);
3179   if (dst != c) {
3180     movdbl(dst, c);
3181   }
3182 }
3183 
3184 // dst = c = a * b + c
3185 void MacroAssembler::fmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c) {
3186   Assembler::vfmadd231ss(c, a, b);
3187   if (dst != c) {
3188     movflt(dst, c);
3189   }
3190 }
3191 
3192 // dst = c = a * b + c
3193 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3194   Assembler::vfmadd231pd(c, a, b, vector_len);
3195   if (dst != c) {
3196     vmovdqu(dst, c);
3197   }
3198 }
3199 
3200 // dst = c = a * b + c
3201 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, XMMRegister b, XMMRegister c, int vector_len) {
3202   Assembler::vfmadd231ps(c, a, b, vector_len);
3203   if (dst != c) {
3204     vmovdqu(dst, c);
3205   }
3206 }
3207 
3208 // dst = c = a * b + c
3209 void MacroAssembler::vfmad(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3210   Assembler::vfmadd231pd(c, a, b, vector_len);
3211   if (dst != c) {
3212     vmovdqu(dst, c);
3213   }
3214 }
3215 
3216 // dst = c = a * b + c
3217 void MacroAssembler::vfmaf(XMMRegister dst, XMMRegister a, Address b, XMMRegister c, int vector_len) {
3218   Assembler::vfmadd231ps(c, a, b, vector_len);
3219   if (dst != c) {
3220     vmovdqu(dst, c);
3221   }
3222 }
3223 
3224 void MacroAssembler::incrementl(AddressLiteral dst) {
3225   if (reachable(dst)) {
3226     incrementl(as_Address(dst));
3227   } else {
3228     lea(rscratch1, dst);
3229     incrementl(Address(rscratch1, 0));
3230   }
3231 }
3232 
3233 void MacroAssembler::incrementl(ArrayAddress dst) {
3234   incrementl(as_Address(dst));
3235 }
3236 
3237 void MacroAssembler::incrementl(Register reg, int value) {
3238   if (value == min_jint) {addl(reg, value) ; return; }
3239   if (value <  0) { decrementl(reg, -value); return; }
3240   if (value == 0) {                        ; return; }
3241   if (value == 1 && UseIncDec) { incl(reg) ; return; }
3242   /* else */      { addl(reg, value)       ; return; }
3243 }
3244 
3245 void MacroAssembler::incrementl(Address dst, int value) {
3246   if (value == min_jint) {addl(dst, value) ; return; }
3247   if (value <  0) { decrementl(dst, -value); return; }
3248   if (value == 0) {                        ; return; }
3249   if (value == 1 && UseIncDec) { incl(dst) ; return; }
3250   /* else */      { addl(dst, value)       ; return; }
3251 }
3252 
3253 void MacroAssembler::jump(AddressLiteral dst) {
3254   if (reachable(dst)) {
3255     jmp_literal(dst.target(), dst.rspec());
3256   } else {
3257     lea(rscratch1, dst);
3258     jmp(rscratch1);
3259   }
3260 }
3261 
3262 void MacroAssembler::jump_cc(Condition cc, AddressLiteral dst) {
3263   if (reachable(dst)) {
3264     InstructionMark im(this);
3265     relocate(dst.reloc());
3266     const int short_size = 2;
3267     const int long_size = 6;
3268     int offs = (intptr_t)dst.target() - ((intptr_t)pc());
3269     if (dst.reloc() == relocInfo::none && is8bit(offs - short_size)) {
3270       // 0111 tttn #8-bit disp
3271       emit_int8(0x70 | cc);
3272       emit_int8((offs - short_size) & 0xFF);
3273     } else {
3274       // 0000 1111 1000 tttn #32-bit disp
3275       emit_int8(0x0F);
3276       emit_int8((unsigned char)(0x80 | cc));
3277       emit_int32(offs - long_size);
3278     }
3279   } else {
3280 #ifdef ASSERT
3281     warning("reversing conditional branch");
3282 #endif /* ASSERT */
3283     Label skip;
3284     jccb(reverse[cc], skip);
3285     lea(rscratch1, dst);
3286     Assembler::jmp(rscratch1);
3287     bind(skip);
3288   }
3289 }
3290 
3291 void MacroAssembler::ldmxcsr(AddressLiteral src) {
3292   if (reachable(src)) {
3293     Assembler::ldmxcsr(as_Address(src));
3294   } else {
3295     lea(rscratch1, src);
3296     Assembler::ldmxcsr(Address(rscratch1, 0));
3297   }
3298 }
3299 
3300 int MacroAssembler::load_signed_byte(Register dst, Address src) {
3301   int off;
3302   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3303     off = offset();
3304     movsbl(dst, src); // movsxb
3305   } else {
3306     off = load_unsigned_byte(dst, src);
3307     shll(dst, 24);
3308     sarl(dst, 24);
3309   }
3310   return off;
3311 }
3312 
3313 // Note: load_signed_short used to be called load_signed_word.
3314 // Although the 'w' in x86 opcodes refers to the term "word" in the assembler
3315 // manual, which means 16 bits, that usage is found nowhere in HotSpot code.
3316 // The term "word" in HotSpot means a 32- or 64-bit machine word.
3317 int MacroAssembler::load_signed_short(Register dst, Address src) {
3318   int off;
3319   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3320     // This is dubious to me since it seems safe to do a signed 16 => 64 bit
3321     // version but this is what 64bit has always done. This seems to imply
3322     // that users are only using 32bits worth.
3323     off = offset();
3324     movswl(dst, src); // movsxw
3325   } else {
3326     off = load_unsigned_short(dst, src);
3327     shll(dst, 16);
3328     sarl(dst, 16);
3329   }
3330   return off;
3331 }
3332 
3333 int MacroAssembler::load_unsigned_byte(Register dst, Address src) {
3334   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3335   // and "3.9 Partial Register Penalties", p. 22).
3336   int off;
3337   if (LP64_ONLY(true || ) VM_Version::is_P6() || src.uses(dst)) {
3338     off = offset();
3339     movzbl(dst, src); // movzxb
3340   } else {
3341     xorl(dst, dst);
3342     off = offset();
3343     movb(dst, src);
3344   }
3345   return off;
3346 }
3347 
3348 // Note: load_unsigned_short used to be called load_unsigned_word.
3349 int MacroAssembler::load_unsigned_short(Register dst, Address src) {
3350   // According to Intel Doc. AP-526, "Zero-Extension of Short", p.16,
3351   // and "3.9 Partial Register Penalties", p. 22).
3352   int off;
3353   if (LP64_ONLY(true ||) VM_Version::is_P6() || src.uses(dst)) {
3354     off = offset();
3355     movzwl(dst, src); // movzxw
3356   } else {
3357     xorl(dst, dst);
3358     off = offset();
3359     movw(dst, src);
3360   }
3361   return off;
3362 }
3363 
3364 void MacroAssembler::load_sized_value(Register dst, Address src, size_t size_in_bytes, bool is_signed, Register dst2) {
3365   switch (size_in_bytes) {
3366 #ifndef _LP64
3367   case  8:
3368     assert(dst2 != noreg, "second dest register required");
3369     movl(dst,  src);
3370     movl(dst2, src.plus_disp(BytesPerInt));
3371     break;
3372 #else
3373   case  8:  movq(dst, src); break;
3374 #endif
3375   case  4:  movl(dst, src); break;
3376   case  2:  is_signed ? load_signed_short(dst, src) : load_unsigned_short(dst, src); break;
3377   case  1:  is_signed ? load_signed_byte( dst, src) : load_unsigned_byte( dst, src); break;
3378   default:  ShouldNotReachHere();
3379   }
3380 }
3381 
3382 void MacroAssembler::store_sized_value(Address dst, Register src, size_t size_in_bytes, Register src2) {
3383   switch (size_in_bytes) {
3384 #ifndef _LP64
3385   case  8:
3386     assert(src2 != noreg, "second source register required");
3387     movl(dst,                        src);
3388     movl(dst.plus_disp(BytesPerInt), src2);
3389     break;
3390 #else
3391   case  8:  movq(dst, src); break;
3392 #endif
3393   case  4:  movl(dst, src); break;
3394   case  2:  movw(dst, src); break;
3395   case  1:  movb(dst, src); break;
3396   default:  ShouldNotReachHere();
3397   }
3398 }
3399 
3400 void MacroAssembler::mov32(AddressLiteral dst, Register src) {
3401   if (reachable(dst)) {
3402     movl(as_Address(dst), src);
3403   } else {
3404     lea(rscratch1, dst);
3405     movl(Address(rscratch1, 0), src);
3406   }
3407 }
3408 
3409 void MacroAssembler::mov32(Register dst, AddressLiteral src) {
3410   if (reachable(src)) {
3411     movl(dst, as_Address(src));
3412   } else {
3413     lea(rscratch1, src);
3414     movl(dst, Address(rscratch1, 0));
3415   }
3416 }
3417 
3418 // C++ bool manipulation
3419 
3420 void MacroAssembler::movbool(Register dst, Address src) {
3421   if(sizeof(bool) == 1)
3422     movb(dst, src);
3423   else if(sizeof(bool) == 2)
3424     movw(dst, src);
3425   else if(sizeof(bool) == 4)
3426     movl(dst, src);
3427   else
3428     // unsupported
3429     ShouldNotReachHere();
3430 }
3431 
3432 void MacroAssembler::movbool(Address dst, bool boolconst) {
3433   if(sizeof(bool) == 1)
3434     movb(dst, (int) boolconst);
3435   else if(sizeof(bool) == 2)
3436     movw(dst, (int) boolconst);
3437   else if(sizeof(bool) == 4)
3438     movl(dst, (int) boolconst);
3439   else
3440     // unsupported
3441     ShouldNotReachHere();
3442 }
3443 
3444 void MacroAssembler::movbool(Address dst, Register src) {
3445   if(sizeof(bool) == 1)
3446     movb(dst, src);
3447   else if(sizeof(bool) == 2)
3448     movw(dst, src);
3449   else if(sizeof(bool) == 4)
3450     movl(dst, src);
3451   else
3452     // unsupported
3453     ShouldNotReachHere();
3454 }
3455 
3456 void MacroAssembler::movbyte(ArrayAddress dst, int src) {
3457   movb(as_Address(dst), src);
3458 }
3459 
3460 void MacroAssembler::movdl(XMMRegister dst, AddressLiteral src) {
3461   if (reachable(src)) {
3462     movdl(dst, as_Address(src));
3463   } else {
3464     lea(rscratch1, src);
3465     movdl(dst, Address(rscratch1, 0));
3466   }
3467 }
3468 
3469 void MacroAssembler::movq(XMMRegister dst, AddressLiteral src) {
3470   if (reachable(src)) {
3471     movq(dst, as_Address(src));
3472   } else {
3473     lea(rscratch1, src);
3474     movq(dst, Address(rscratch1, 0));
3475   }
3476 }
3477 
3478 void MacroAssembler::setvectmask(Register dst, Register src) {
3479   Assembler::movl(dst, 1);
3480   Assembler::shlxl(dst, dst, src);
3481   Assembler::decl(dst);
3482   Assembler::kmovdl(k1, dst);
3483   Assembler::movl(dst, src);
3484 }
3485 
3486 void MacroAssembler::restorevectmask() {
3487   Assembler::knotwl(k1, k0);
3488 }
3489 
3490 void MacroAssembler::movdbl(XMMRegister dst, AddressLiteral src) {
3491   if (reachable(src)) {
3492     if (UseXmmLoadAndClearUpper) {
3493       movsd (dst, as_Address(src));
3494     } else {
3495       movlpd(dst, as_Address(src));
3496     }
3497   } else {
3498     lea(rscratch1, src);
3499     if (UseXmmLoadAndClearUpper) {
3500       movsd (dst, Address(rscratch1, 0));
3501     } else {
3502       movlpd(dst, Address(rscratch1, 0));
3503     }
3504   }
3505 }
3506 
3507 void MacroAssembler::movflt(XMMRegister dst, AddressLiteral src) {
3508   if (reachable(src)) {
3509     movss(dst, as_Address(src));
3510   } else {
3511     lea(rscratch1, src);
3512     movss(dst, Address(rscratch1, 0));
3513   }
3514 }
3515 
3516 void MacroAssembler::movptr(Register dst, Register src) {
3517   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3518 }
3519 
3520 void MacroAssembler::movptr(Register dst, Address src) {
3521   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3522 }
3523 
3524 // src should NEVER be a real pointer. Use AddressLiteral for true pointers
3525 void MacroAssembler::movptr(Register dst, intptr_t src) {
3526   LP64_ONLY(mov64(dst, src)) NOT_LP64(movl(dst, src));
3527 }
3528 
3529 void MacroAssembler::movptr(Address dst, Register src) {
3530   LP64_ONLY(movq(dst, src)) NOT_LP64(movl(dst, src));
3531 }
3532 
3533 void MacroAssembler::movdqu(Address dst, XMMRegister src) {
3534   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3535     Assembler::vextractf32x4(dst, src, 0);
3536   } else {
3537     Assembler::movdqu(dst, src);
3538   }
3539 }
3540 
3541 void MacroAssembler::movdqu(XMMRegister dst, Address src) {
3542   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3543     Assembler::vinsertf32x4(dst, dst, src, 0);
3544   } else {
3545     Assembler::movdqu(dst, src);
3546   }
3547 }
3548 
3549 void MacroAssembler::movdqu(XMMRegister dst, XMMRegister src) {
3550   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3551     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3552   } else {
3553     Assembler::movdqu(dst, src);
3554   }
3555 }
3556 
3557 void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src, Register scratchReg) {
3558   if (reachable(src)) {
3559     movdqu(dst, as_Address(src));
3560   } else {
3561     lea(scratchReg, src);
3562     movdqu(dst, Address(scratchReg, 0));
3563   }
3564 }
3565 
3566 void MacroAssembler::vmovdqu(Address dst, XMMRegister src) {
3567   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (src->encoding() > 15)) {
3568     vextractf64x4_low(dst, src);
3569   } else {
3570     Assembler::vmovdqu(dst, src);
3571   }
3572 }
3573 
3574 void MacroAssembler::vmovdqu(XMMRegister dst, Address src) {
3575   if (UseAVX > 2 && !VM_Version::supports_avx512vl() && (dst->encoding() > 15)) {
3576     vinsertf64x4_low(dst, src);
3577   } else {
3578     Assembler::vmovdqu(dst, src);
3579   }
3580 }
3581 
3582 void MacroAssembler::vmovdqu(XMMRegister dst, XMMRegister src) {
3583   if (UseAVX > 2 && !VM_Version::supports_avx512vl()) {
3584     Assembler::evmovdqul(dst, src, Assembler::AVX_512bit);
3585   }
3586   else {
3587     Assembler::vmovdqu(dst, src);
3588   }
3589 }
3590 
3591 void MacroAssembler::vmovdqu(XMMRegister dst, AddressLiteral src) {
3592   if (reachable(src)) {
3593     vmovdqu(dst, as_Address(src));
3594   }
3595   else {
3596     lea(rscratch1, src);
3597     vmovdqu(dst, Address(rscratch1, 0));
3598   }
3599 }
3600 
3601 void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) {
3602   if (reachable(src)) {
3603     Assembler::movdqa(dst, as_Address(src));
3604   } else {
3605     lea(rscratch1, src);
3606     Assembler::movdqa(dst, Address(rscratch1, 0));
3607   }
3608 }
3609 
3610 void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) {
3611   if (reachable(src)) {
3612     Assembler::movsd(dst, as_Address(src));
3613   } else {
3614     lea(rscratch1, src);
3615     Assembler::movsd(dst, Address(rscratch1, 0));
3616   }
3617 }
3618 
3619 void MacroAssembler::movss(XMMRegister dst, AddressLiteral src) {
3620   if (reachable(src)) {
3621     Assembler::movss(dst, as_Address(src));
3622   } else {
3623     lea(rscratch1, src);
3624     Assembler::movss(dst, Address(rscratch1, 0));
3625   }
3626 }
3627 
3628 void MacroAssembler::mulsd(XMMRegister dst, AddressLiteral src) {
3629   if (reachable(src)) {
3630     Assembler::mulsd(dst, as_Address(src));
3631   } else {
3632     lea(rscratch1, src);
3633     Assembler::mulsd(dst, Address(rscratch1, 0));
3634   }
3635 }
3636 
3637 void MacroAssembler::mulss(XMMRegister dst, AddressLiteral src) {
3638   if (reachable(src)) {
3639     Assembler::mulss(dst, as_Address(src));
3640   } else {
3641     lea(rscratch1, src);
3642     Assembler::mulss(dst, Address(rscratch1, 0));
3643   }
3644 }
3645 
3646 void MacroAssembler::null_check(Register reg, int offset) {
3647   if (needs_explicit_null_check(offset)) {
3648     // provoke OS NULL exception if reg = NULL by
3649     // accessing M[reg] w/o changing any (non-CC) registers
3650     // NOTE: cmpl is plenty here to provoke a segv
3651     cmpptr(rax, Address(reg, 0));
3652     // Note: should probably use testl(rax, Address(reg, 0));
3653     //       may be shorter code (however, this version of
3654     //       testl needs to be implemented first)
3655   } else {
3656     // nothing to do, (later) access of M[reg + offset]
3657     // will provoke OS NULL exception if reg = NULL
3658   }
3659 }
3660 
3661 void MacroAssembler::os_breakpoint() {
3662   // instead of directly emitting a breakpoint, call os:breakpoint for better debugability
3663   // (e.g., MSVC can't call ps() otherwise)
3664   call(RuntimeAddress(CAST_FROM_FN_PTR(address, os::breakpoint)));
3665 }
3666 
3667 void MacroAssembler::unimplemented(const char* what) {
3668   const char* buf = NULL;
3669   {
3670     ResourceMark rm;
3671     stringStream ss;
3672     ss.print("unimplemented: %s", what);
3673     buf = code_string(ss.as_string());
3674   }
3675   stop(buf);
3676 }
3677 
3678 #ifdef _LP64
3679 #define XSTATE_BV 0x200
3680 #endif
3681 
3682 void MacroAssembler::pop_CPU_state() {
3683   pop_FPU_state();
3684   pop_IU_state();
3685 }
3686 
3687 void MacroAssembler::pop_FPU_state() {
3688 #ifndef _LP64
3689   frstor(Address(rsp, 0));
3690 #else
3691   fxrstor(Address(rsp, 0));
3692 #endif
3693   addptr(rsp, FPUStateSizeInWords * wordSize);
3694 }
3695 
3696 void MacroAssembler::pop_IU_state() {
3697   popa();
3698   LP64_ONLY(addq(rsp, 8));
3699   popf();
3700 }
3701 
3702 // Save Integer and Float state
3703 // Warning: Stack must be 16 byte aligned (64bit)
3704 void MacroAssembler::push_CPU_state() {
3705   push_IU_state();
3706   push_FPU_state();
3707 }
3708 
3709 void MacroAssembler::push_FPU_state() {
3710   subptr(rsp, FPUStateSizeInWords * wordSize);
3711 #ifndef _LP64
3712   fnsave(Address(rsp, 0));
3713   fwait();
3714 #else
3715   fxsave(Address(rsp, 0));
3716 #endif // LP64
3717 }
3718 
3719 void MacroAssembler::push_IU_state() {
3720   // Push flags first because pusha kills them
3721   pushf();
3722   // Make sure rsp stays 16-byte aligned
3723   LP64_ONLY(subq(rsp, 8));
3724   pusha();
3725 }
3726 
3727 void MacroAssembler::reset_last_Java_frame(Register java_thread, bool clear_fp) { // determine java_thread register
3728   if (!java_thread->is_valid()) {
3729     java_thread = rdi;
3730     get_thread(java_thread);
3731   }
3732   // we must set sp to zero to clear frame
3733   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), NULL_WORD);
3734   if (clear_fp) {
3735     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), NULL_WORD);
3736   }
3737 
3738   // Always clear the pc because it could have been set by make_walkable()
3739   movptr(Address(java_thread, JavaThread::last_Java_pc_offset()), NULL_WORD);
3740 
3741   vzeroupper();
3742 }
3743 
3744 void MacroAssembler::restore_rax(Register tmp) {
3745   if (tmp == noreg) pop(rax);
3746   else if (tmp != rax) mov(rax, tmp);
3747 }
3748 
3749 void MacroAssembler::round_to(Register reg, int modulus) {
3750   addptr(reg, modulus - 1);
3751   andptr(reg, -modulus);
3752 }
3753 
3754 void MacroAssembler::save_rax(Register tmp) {
3755   if (tmp == noreg) push(rax);
3756   else if (tmp != rax) mov(tmp, rax);
3757 }
3758 
3759 // Write serialization page so VM thread can do a pseudo remote membar.
3760 // We use the current thread pointer to calculate a thread specific
3761 // offset to write to within the page. This minimizes bus traffic
3762 // due to cache line collision.
3763 void MacroAssembler::serialize_memory(Register thread, Register tmp) {
3764   movl(tmp, thread);
3765   shrl(tmp, os::get_serialize_page_shift_count());
3766   andl(tmp, (os::vm_page_size() - sizeof(int)));
3767 
3768   Address index(noreg, tmp, Address::times_1);
3769   ExternalAddress page(os::get_memory_serialize_page());
3770 
3771   // Size of store must match masking code above
3772   movl(as_Address(ArrayAddress(page, index)), tmp);
3773 }
3774 
3775 void MacroAssembler::cmpxchg_oop(Register res, Address addr, Register cmpval, Register newval,
3776                                  bool exchange, bool encode, Register tmp1, Register tmp2) {
3777   BarrierSetAssembler* bsa = BarrierSet::barrier_set()->barrier_set_assembler();
3778   bsa->cmpxchg_oop(this, IN_HEAP, res, addr, cmpval, newval, exchange, encode, tmp1, tmp2);
3779 }
3780 
3781 void MacroAssembler::xchg_oop(Register obj, Address addr, Register tmp) {
3782   BarrierSetAssembler* bsa = BarrierSet::barrier_set()->barrier_set_assembler();
3783   bsa->xchg_oop(this, IN_HEAP, obj, addr, tmp);
3784 }
3785 
3786 void MacroAssembler::safepoint_poll(Label& slow_path, Register thread_reg, Register temp_reg) {
3787   if (SafepointMechanism::uses_thread_local_poll()) {
3788 #ifdef _LP64
3789     assert(thread_reg == r15_thread, "should be");
3790 #else
3791     if (thread_reg == noreg) {
3792       thread_reg = temp_reg;
3793       get_thread(thread_reg);
3794     }
3795 #endif
3796     testb(Address(thread_reg, Thread::polling_page_offset()), SafepointMechanism::poll_bit());
3797     jcc(Assembler::notZero, slow_path); // handshake bit set implies poll
3798   } else {
3799     cmp32(ExternalAddress(SafepointSynchronize::address_of_state()),
3800         SafepointSynchronize::_not_synchronized);
3801     jcc(Assembler::notEqual, slow_path);
3802   }
3803 }
3804 
3805 // Calls to C land
3806 //
3807 // When entering C land, the rbp, & rsp of the last Java frame have to be recorded
3808 // in the (thread-local) JavaThread object. When leaving C land, the last Java fp
3809 // has to be reset to 0. This is required to allow proper stack traversal.
3810 void MacroAssembler::set_last_Java_frame(Register java_thread,
3811                                          Register last_java_sp,
3812                                          Register last_java_fp,
3813                                          address  last_java_pc) {
3814   vzeroupper();
3815   // determine java_thread register
3816   if (!java_thread->is_valid()) {
3817     java_thread = rdi;
3818     get_thread(java_thread);
3819   }
3820   // determine last_java_sp register
3821   if (!last_java_sp->is_valid()) {
3822     last_java_sp = rsp;
3823   }
3824 
3825   // last_java_fp is optional
3826 
3827   if (last_java_fp->is_valid()) {
3828     movptr(Address(java_thread, JavaThread::last_Java_fp_offset()), last_java_fp);
3829   }
3830 
3831   // last_java_pc is optional
3832 
3833   if (last_java_pc != NULL) {
3834     lea(Address(java_thread,
3835                  JavaThread::frame_anchor_offset() + JavaFrameAnchor::last_Java_pc_offset()),
3836         InternalAddress(last_java_pc));
3837 
3838   }
3839   movptr(Address(java_thread, JavaThread::last_Java_sp_offset()), last_java_sp);
3840 }
3841 
3842 void MacroAssembler::shlptr(Register dst, int imm8) {
3843   LP64_ONLY(shlq(dst, imm8)) NOT_LP64(shll(dst, imm8));
3844 }
3845 
3846 void MacroAssembler::shrptr(Register dst, int imm8) {
3847   LP64_ONLY(shrq(dst, imm8)) NOT_LP64(shrl(dst, imm8));
3848 }
3849 
3850 void MacroAssembler::sign_extend_byte(Register reg) {
3851   if (LP64_ONLY(true ||) (VM_Version::is_P6() && reg->has_byte_register())) {
3852     movsbl(reg, reg); // movsxb
3853   } else {
3854     shll(reg, 24);
3855     sarl(reg, 24);
3856   }
3857 }
3858 
3859 void MacroAssembler::sign_extend_short(Register reg) {
3860   if (LP64_ONLY(true ||) VM_Version::is_P6()) {
3861     movswl(reg, reg); // movsxw
3862   } else {
3863     shll(reg, 16);
3864     sarl(reg, 16);
3865   }
3866 }
3867 
3868 void MacroAssembler::testl(Register dst, AddressLiteral src) {
3869   assert(reachable(src), "Address should be reachable");
3870   testl(dst, as_Address(src));
3871 }
3872 
3873 void MacroAssembler::pcmpeqb(XMMRegister dst, XMMRegister src) {
3874   int dst_enc = dst->encoding();
3875   int src_enc = src->encoding();
3876   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3877     Assembler::pcmpeqb(dst, src);
3878   } else if ((dst_enc < 16) && (src_enc < 16)) {
3879     Assembler::pcmpeqb(dst, src);
3880   } else if (src_enc < 16) {
3881     subptr(rsp, 64);
3882     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3883     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3884     Assembler::pcmpeqb(xmm0, src);
3885     movdqu(dst, xmm0);
3886     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3887     addptr(rsp, 64);
3888   } else if (dst_enc < 16) {
3889     subptr(rsp, 64);
3890     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3891     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3892     Assembler::pcmpeqb(dst, xmm0);
3893     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3894     addptr(rsp, 64);
3895   } else {
3896     subptr(rsp, 64);
3897     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3898     subptr(rsp, 64);
3899     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3900     movdqu(xmm0, src);
3901     movdqu(xmm1, dst);
3902     Assembler::pcmpeqb(xmm1, xmm0);
3903     movdqu(dst, xmm1);
3904     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3905     addptr(rsp, 64);
3906     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3907     addptr(rsp, 64);
3908   }
3909 }
3910 
3911 void MacroAssembler::pcmpeqw(XMMRegister dst, XMMRegister src) {
3912   int dst_enc = dst->encoding();
3913   int src_enc = src->encoding();
3914   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
3915     Assembler::pcmpeqw(dst, src);
3916   } else if ((dst_enc < 16) && (src_enc < 16)) {
3917     Assembler::pcmpeqw(dst, src);
3918   } else if (src_enc < 16) {
3919     subptr(rsp, 64);
3920     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3921     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3922     Assembler::pcmpeqw(xmm0, src);
3923     movdqu(dst, xmm0);
3924     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3925     addptr(rsp, 64);
3926   } else if (dst_enc < 16) {
3927     subptr(rsp, 64);
3928     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3929     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3930     Assembler::pcmpeqw(dst, xmm0);
3931     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3932     addptr(rsp, 64);
3933   } else {
3934     subptr(rsp, 64);
3935     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3936     subptr(rsp, 64);
3937     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3938     movdqu(xmm0, src);
3939     movdqu(xmm1, dst);
3940     Assembler::pcmpeqw(xmm1, xmm0);
3941     movdqu(dst, xmm1);
3942     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3943     addptr(rsp, 64);
3944     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3945     addptr(rsp, 64);
3946   }
3947 }
3948 
3949 void MacroAssembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
3950   int dst_enc = dst->encoding();
3951   if (dst_enc < 16) {
3952     Assembler::pcmpestri(dst, src, imm8);
3953   } else {
3954     subptr(rsp, 64);
3955     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3956     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3957     Assembler::pcmpestri(xmm0, src, imm8);
3958     movdqu(dst, xmm0);
3959     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3960     addptr(rsp, 64);
3961   }
3962 }
3963 
3964 void MacroAssembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) {
3965   int dst_enc = dst->encoding();
3966   int src_enc = src->encoding();
3967   if ((dst_enc < 16) && (src_enc < 16)) {
3968     Assembler::pcmpestri(dst, src, imm8);
3969   } else if (src_enc < 16) {
3970     subptr(rsp, 64);
3971     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3972     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
3973     Assembler::pcmpestri(xmm0, src, imm8);
3974     movdqu(dst, xmm0);
3975     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3976     addptr(rsp, 64);
3977   } else if (dst_enc < 16) {
3978     subptr(rsp, 64);
3979     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3980     evmovdqul(xmm0, src, Assembler::AVX_512bit);
3981     Assembler::pcmpestri(dst, xmm0, imm8);
3982     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3983     addptr(rsp, 64);
3984   } else {
3985     subptr(rsp, 64);
3986     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
3987     subptr(rsp, 64);
3988     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
3989     movdqu(xmm0, src);
3990     movdqu(xmm1, dst);
3991     Assembler::pcmpestri(xmm1, xmm0, imm8);
3992     movdqu(dst, xmm1);
3993     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
3994     addptr(rsp, 64);
3995     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
3996     addptr(rsp, 64);
3997   }
3998 }
3999 
4000 void MacroAssembler::pmovzxbw(XMMRegister dst, XMMRegister src) {
4001   int dst_enc = dst->encoding();
4002   int src_enc = src->encoding();
4003   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4004     Assembler::pmovzxbw(dst, src);
4005   } else if ((dst_enc < 16) && (src_enc < 16)) {
4006     Assembler::pmovzxbw(dst, src);
4007   } else if (src_enc < 16) {
4008     subptr(rsp, 64);
4009     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4010     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4011     Assembler::pmovzxbw(xmm0, src);
4012     movdqu(dst, xmm0);
4013     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4014     addptr(rsp, 64);
4015   } else if (dst_enc < 16) {
4016     subptr(rsp, 64);
4017     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4018     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4019     Assembler::pmovzxbw(dst, xmm0);
4020     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4021     addptr(rsp, 64);
4022   } else {
4023     subptr(rsp, 64);
4024     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4025     subptr(rsp, 64);
4026     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4027     movdqu(xmm0, src);
4028     movdqu(xmm1, dst);
4029     Assembler::pmovzxbw(xmm1, xmm0);
4030     movdqu(dst, xmm1);
4031     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4032     addptr(rsp, 64);
4033     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4034     addptr(rsp, 64);
4035   }
4036 }
4037 
4038 void MacroAssembler::pmovzxbw(XMMRegister dst, Address src) {
4039   int dst_enc = dst->encoding();
4040   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4041     Assembler::pmovzxbw(dst, src);
4042   } else if (dst_enc < 16) {
4043     Assembler::pmovzxbw(dst, src);
4044   } else {
4045     subptr(rsp, 64);
4046     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4047     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4048     Assembler::pmovzxbw(xmm0, src);
4049     movdqu(dst, xmm0);
4050     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4051     addptr(rsp, 64);
4052   }
4053 }
4054 
4055 void MacroAssembler::pmovmskb(Register dst, XMMRegister src) {
4056   int src_enc = src->encoding();
4057   if (src_enc < 16) {
4058     Assembler::pmovmskb(dst, src);
4059   } else {
4060     subptr(rsp, 64);
4061     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4062     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4063     Assembler::pmovmskb(dst, xmm0);
4064     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4065     addptr(rsp, 64);
4066   }
4067 }
4068 
4069 void MacroAssembler::ptest(XMMRegister dst, XMMRegister src) {
4070   int dst_enc = dst->encoding();
4071   int src_enc = src->encoding();
4072   if ((dst_enc < 16) && (src_enc < 16)) {
4073     Assembler::ptest(dst, src);
4074   } else if (src_enc < 16) {
4075     subptr(rsp, 64);
4076     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4077     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4078     Assembler::ptest(xmm0, src);
4079     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4080     addptr(rsp, 64);
4081   } else if (dst_enc < 16) {
4082     subptr(rsp, 64);
4083     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4084     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4085     Assembler::ptest(dst, xmm0);
4086     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4087     addptr(rsp, 64);
4088   } else {
4089     subptr(rsp, 64);
4090     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4091     subptr(rsp, 64);
4092     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4093     movdqu(xmm0, src);
4094     movdqu(xmm1, dst);
4095     Assembler::ptest(xmm1, xmm0);
4096     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4097     addptr(rsp, 64);
4098     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4099     addptr(rsp, 64);
4100   }
4101 }
4102 
4103 void MacroAssembler::sqrtsd(XMMRegister dst, AddressLiteral src) {
4104   if (reachable(src)) {
4105     Assembler::sqrtsd(dst, as_Address(src));
4106   } else {
4107     lea(rscratch1, src);
4108     Assembler::sqrtsd(dst, Address(rscratch1, 0));
4109   }
4110 }
4111 
4112 void MacroAssembler::sqrtss(XMMRegister dst, AddressLiteral src) {
4113   if (reachable(src)) {
4114     Assembler::sqrtss(dst, as_Address(src));
4115   } else {
4116     lea(rscratch1, src);
4117     Assembler::sqrtss(dst, Address(rscratch1, 0));
4118   }
4119 }
4120 
4121 void MacroAssembler::subsd(XMMRegister dst, AddressLiteral src) {
4122   if (reachable(src)) {
4123     Assembler::subsd(dst, as_Address(src));
4124   } else {
4125     lea(rscratch1, src);
4126     Assembler::subsd(dst, Address(rscratch1, 0));
4127   }
4128 }
4129 
4130 void MacroAssembler::subss(XMMRegister dst, AddressLiteral src) {
4131   if (reachable(src)) {
4132     Assembler::subss(dst, as_Address(src));
4133   } else {
4134     lea(rscratch1, src);
4135     Assembler::subss(dst, Address(rscratch1, 0));
4136   }
4137 }
4138 
4139 void MacroAssembler::ucomisd(XMMRegister dst, AddressLiteral src) {
4140   if (reachable(src)) {
4141     Assembler::ucomisd(dst, as_Address(src));
4142   } else {
4143     lea(rscratch1, src);
4144     Assembler::ucomisd(dst, Address(rscratch1, 0));
4145   }
4146 }
4147 
4148 void MacroAssembler::ucomiss(XMMRegister dst, AddressLiteral src) {
4149   if (reachable(src)) {
4150     Assembler::ucomiss(dst, as_Address(src));
4151   } else {
4152     lea(rscratch1, src);
4153     Assembler::ucomiss(dst, Address(rscratch1, 0));
4154   }
4155 }
4156 
4157 void MacroAssembler::xorpd(XMMRegister dst, AddressLiteral src) {
4158   // Used in sign-bit flipping with aligned address.
4159   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4160   if (reachable(src)) {
4161     Assembler::xorpd(dst, as_Address(src));
4162   } else {
4163     lea(rscratch1, src);
4164     Assembler::xorpd(dst, Address(rscratch1, 0));
4165   }
4166 }
4167 
4168 void MacroAssembler::xorpd(XMMRegister dst, XMMRegister src) {
4169   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4170     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4171   }
4172   else {
4173     Assembler::xorpd(dst, src);
4174   }
4175 }
4176 
4177 void MacroAssembler::xorps(XMMRegister dst, XMMRegister src) {
4178   if (UseAVX > 2 && !VM_Version::supports_avx512dq() && (dst->encoding() == src->encoding())) {
4179     Assembler::vpxor(dst, dst, src, Assembler::AVX_512bit);
4180   } else {
4181     Assembler::xorps(dst, src);
4182   }
4183 }
4184 
4185 void MacroAssembler::xorps(XMMRegister dst, AddressLiteral src) {
4186   // Used in sign-bit flipping with aligned address.
4187   assert((UseAVX > 0) || (((intptr_t)src.target() & 15) == 0), "SSE mode requires address alignment 16 bytes");
4188   if (reachable(src)) {
4189     Assembler::xorps(dst, as_Address(src));
4190   } else {
4191     lea(rscratch1, src);
4192     Assembler::xorps(dst, Address(rscratch1, 0));
4193   }
4194 }
4195 
4196 void MacroAssembler::pshufb(XMMRegister dst, AddressLiteral src) {
4197   // Used in sign-bit flipping with aligned address.
4198   bool aligned_adr = (((intptr_t)src.target() & 15) == 0);
4199   assert((UseAVX > 0) || aligned_adr, "SSE mode requires address alignment 16 bytes");
4200   if (reachable(src)) {
4201     Assembler::pshufb(dst, as_Address(src));
4202   } else {
4203     lea(rscratch1, src);
4204     Assembler::pshufb(dst, Address(rscratch1, 0));
4205   }
4206 }
4207 
4208 // AVX 3-operands instructions
4209 
4210 void MacroAssembler::vaddsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4211   if (reachable(src)) {
4212     vaddsd(dst, nds, as_Address(src));
4213   } else {
4214     lea(rscratch1, src);
4215     vaddsd(dst, nds, Address(rscratch1, 0));
4216   }
4217 }
4218 
4219 void MacroAssembler::vaddss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
4220   if (reachable(src)) {
4221     vaddss(dst, nds, as_Address(src));
4222   } else {
4223     lea(rscratch1, src);
4224     vaddss(dst, nds, Address(rscratch1, 0));
4225   }
4226 }
4227 
4228 void MacroAssembler::vabsss(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4229   int dst_enc = dst->encoding();
4230   int nds_enc = nds->encoding();
4231   int src_enc = src->encoding();
4232   if ((dst_enc < 16) && (nds_enc < 16)) {
4233     vandps(dst, nds, negate_field, vector_len);
4234   } else if ((src_enc < 16) && (dst_enc < 16)) {
4235     evmovdqul(src, nds, Assembler::AVX_512bit);
4236     vandps(dst, src, negate_field, vector_len);
4237   } else if (src_enc < 16) {
4238     evmovdqul(src, nds, Assembler::AVX_512bit);
4239     vandps(src, src, negate_field, vector_len);
4240     evmovdqul(dst, src, Assembler::AVX_512bit);
4241   } else if (dst_enc < 16) {
4242     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4243     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4244     vandps(dst, xmm0, negate_field, vector_len);
4245     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4246   } else {
4247     if (src_enc != dst_enc) {
4248       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4249       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4250       vandps(xmm0, xmm0, negate_field, vector_len);
4251       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4252       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4253     } else {
4254       subptr(rsp, 64);
4255       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4256       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4257       vandps(xmm0, xmm0, negate_field, vector_len);
4258       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4259       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4260       addptr(rsp, 64);
4261     }
4262   }
4263 }
4264 
4265 void MacroAssembler::vabssd(XMMRegister dst, XMMRegister nds, XMMRegister src, AddressLiteral negate_field, int vector_len) {
4266   int dst_enc = dst->encoding();
4267   int nds_enc = nds->encoding();
4268   int src_enc = src->encoding();
4269   if ((dst_enc < 16) && (nds_enc < 16)) {
4270     vandpd(dst, nds, negate_field, vector_len);
4271   } else if ((src_enc < 16) && (dst_enc < 16)) {
4272     evmovdqul(src, nds, Assembler::AVX_512bit);
4273     vandpd(dst, src, negate_field, vector_len);
4274   } else if (src_enc < 16) {
4275     evmovdqul(src, nds, Assembler::AVX_512bit);
4276     vandpd(src, src, negate_field, vector_len);
4277     evmovdqul(dst, src, Assembler::AVX_512bit);
4278   } else if (dst_enc < 16) {
4279     evmovdqul(src, xmm0, Assembler::AVX_512bit);
4280     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4281     vandpd(dst, xmm0, negate_field, vector_len);
4282     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4283   } else {
4284     if (src_enc != dst_enc) {
4285       evmovdqul(src, xmm0, Assembler::AVX_512bit);
4286       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4287       vandpd(xmm0, xmm0, negate_field, vector_len);
4288       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4289       evmovdqul(xmm0, src, Assembler::AVX_512bit);
4290     } else {
4291       subptr(rsp, 64);
4292       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4293       evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4294       vandpd(xmm0, xmm0, negate_field, vector_len);
4295       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4296       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4297       addptr(rsp, 64);
4298     }
4299   }
4300 }
4301 
4302 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4303   int dst_enc = dst->encoding();
4304   int nds_enc = nds->encoding();
4305   int src_enc = src->encoding();
4306   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4307     Assembler::vpaddb(dst, nds, src, vector_len);
4308   } else if ((dst_enc < 16) && (src_enc < 16)) {
4309     Assembler::vpaddb(dst, dst, src, vector_len);
4310   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4311     // use nds as scratch for src
4312     evmovdqul(nds, src, Assembler::AVX_512bit);
4313     Assembler::vpaddb(dst, dst, nds, vector_len);
4314   } else if ((src_enc < 16) && (nds_enc < 16)) {
4315     // use nds as scratch for dst
4316     evmovdqul(nds, dst, Assembler::AVX_512bit);
4317     Assembler::vpaddb(nds, nds, src, vector_len);
4318     evmovdqul(dst, nds, Assembler::AVX_512bit);
4319   } else if (dst_enc < 16) {
4320     // use nds as scatch for xmm0 to hold src
4321     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4322     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4323     Assembler::vpaddb(dst, dst, xmm0, vector_len);
4324     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4325   } else {
4326     // worse case scenario, all regs are in the upper bank
4327     subptr(rsp, 64);
4328     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4329     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4330     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4331     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4332     Assembler::vpaddb(xmm0, xmm0, xmm1, vector_len);
4333     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4334     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4335     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4336     addptr(rsp, 64);
4337   }
4338 }
4339 
4340 void MacroAssembler::vpaddb(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4341   int dst_enc = dst->encoding();
4342   int nds_enc = nds->encoding();
4343   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4344     Assembler::vpaddb(dst, nds, src, vector_len);
4345   } else if (dst_enc < 16) {
4346     Assembler::vpaddb(dst, dst, src, vector_len);
4347   } else if (nds_enc < 16) {
4348     // implies dst_enc in upper bank with src as scratch
4349     evmovdqul(nds, dst, Assembler::AVX_512bit);
4350     Assembler::vpaddb(nds, nds, src, vector_len);
4351     evmovdqul(dst, nds, Assembler::AVX_512bit);
4352   } else {
4353     // worse case scenario, all regs in upper bank
4354     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4355     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4356     Assembler::vpaddb(xmm0, xmm0, src, vector_len);
4357     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4358   }
4359 }
4360 
4361 void MacroAssembler::vpaddw(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::vpaddw(dst, nds, src, vector_len);
4367   } else if ((dst_enc < 16) && (src_enc < 16)) {
4368     Assembler::vpaddw(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::vpaddw(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::vpaddw(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::vpaddw(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::vpaddw(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::vpaddw(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::vpaddw(dst, nds, src, vector_len);
4404   } else if (dst_enc < 16) {
4405     Assembler::vpaddw(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::vpaddw(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::vpaddw(xmm0, xmm0, src, vector_len);
4416     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4417   }
4418 }
4419 
4420 void MacroAssembler::vpand(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
4421   if (reachable(src)) {
4422     Assembler::vpand(dst, nds, as_Address(src), vector_len);
4423   } else {
4424     lea(rscratch1, src);
4425     Assembler::vpand(dst, nds, Address(rscratch1, 0), vector_len);
4426   }
4427 }
4428 
4429 void MacroAssembler::vpbroadcastw(XMMRegister dst, XMMRegister src) {
4430   int dst_enc = dst->encoding();
4431   int src_enc = src->encoding();
4432   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4433     Assembler::vpbroadcastw(dst, src);
4434   } else if ((dst_enc < 16) && (src_enc < 16)) {
4435     Assembler::vpbroadcastw(dst, src);
4436   } else if (src_enc < 16) {
4437     subptr(rsp, 64);
4438     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4439     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4440     Assembler::vpbroadcastw(xmm0, src);
4441     movdqu(dst, xmm0);
4442     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4443     addptr(rsp, 64);
4444   } else if (dst_enc < 16) {
4445     subptr(rsp, 64);
4446     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4447     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4448     Assembler::vpbroadcastw(dst, xmm0);
4449     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4450     addptr(rsp, 64);
4451   } else {
4452     subptr(rsp, 64);
4453     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4454     subptr(rsp, 64);
4455     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4456     movdqu(xmm0, src);
4457     movdqu(xmm1, dst);
4458     Assembler::vpbroadcastw(xmm1, xmm0);
4459     movdqu(dst, xmm1);
4460     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4461     addptr(rsp, 64);
4462     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4463     addptr(rsp, 64);
4464   }
4465 }
4466 
4467 void MacroAssembler::vpcmpeqb(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4468   int dst_enc = dst->encoding();
4469   int nds_enc = nds->encoding();
4470   int src_enc = src->encoding();
4471   assert(dst_enc == nds_enc, "");
4472   if ((dst_enc < 16) && (src_enc < 16)) {
4473     Assembler::vpcmpeqb(dst, nds, src, vector_len);
4474   } else if (src_enc < 16) {
4475     subptr(rsp, 64);
4476     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4477     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4478     Assembler::vpcmpeqb(xmm0, xmm0, src, vector_len);
4479     movdqu(dst, xmm0);
4480     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4481     addptr(rsp, 64);
4482   } else if (dst_enc < 16) {
4483     subptr(rsp, 64);
4484     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4485     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4486     Assembler::vpcmpeqb(dst, dst, xmm0, vector_len);
4487     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4488     addptr(rsp, 64);
4489   } else {
4490     subptr(rsp, 64);
4491     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4492     subptr(rsp, 64);
4493     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4494     movdqu(xmm0, src);
4495     movdqu(xmm1, dst);
4496     Assembler::vpcmpeqb(xmm1, xmm1, xmm0, vector_len);
4497     movdqu(dst, xmm1);
4498     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4499     addptr(rsp, 64);
4500     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4501     addptr(rsp, 64);
4502   }
4503 }
4504 
4505 void MacroAssembler::vpcmpeqw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4506   int dst_enc = dst->encoding();
4507   int nds_enc = nds->encoding();
4508   int src_enc = src->encoding();
4509   assert(dst_enc == nds_enc, "");
4510   if ((dst_enc < 16) && (src_enc < 16)) {
4511     Assembler::vpcmpeqw(dst, nds, src, vector_len);
4512   } else if (src_enc < 16) {
4513     subptr(rsp, 64);
4514     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4515     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4516     Assembler::vpcmpeqw(xmm0, xmm0, src, vector_len);
4517     movdqu(dst, xmm0);
4518     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4519     addptr(rsp, 64);
4520   } else if (dst_enc < 16) {
4521     subptr(rsp, 64);
4522     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4523     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4524     Assembler::vpcmpeqw(dst, dst, xmm0, vector_len);
4525     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4526     addptr(rsp, 64);
4527   } else {
4528     subptr(rsp, 64);
4529     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4530     subptr(rsp, 64);
4531     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4532     movdqu(xmm0, src);
4533     movdqu(xmm1, dst);
4534     Assembler::vpcmpeqw(xmm1, xmm1, xmm0, vector_len);
4535     movdqu(dst, xmm1);
4536     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4537     addptr(rsp, 64);
4538     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4539     addptr(rsp, 64);
4540   }
4541 }
4542 
4543 void MacroAssembler::vpmovzxbw(XMMRegister dst, Address src, int vector_len) {
4544   int dst_enc = dst->encoding();
4545   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4546     Assembler::vpmovzxbw(dst, src, vector_len);
4547   } else if (dst_enc < 16) {
4548     Assembler::vpmovzxbw(dst, src, vector_len);
4549   } else {
4550     subptr(rsp, 64);
4551     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4552     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4553     Assembler::vpmovzxbw(xmm0, src, vector_len);
4554     movdqu(dst, xmm0);
4555     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4556     addptr(rsp, 64);
4557   }
4558 }
4559 
4560 void MacroAssembler::vpmovmskb(Register dst, XMMRegister src) {
4561   int src_enc = src->encoding();
4562   if (src_enc < 16) {
4563     Assembler::vpmovmskb(dst, src);
4564   } else {
4565     subptr(rsp, 64);
4566     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4567     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4568     Assembler::vpmovmskb(dst, xmm0);
4569     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4570     addptr(rsp, 64);
4571   }
4572 }
4573 
4574 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, XMMRegister src, int vector_len) {
4575   int dst_enc = dst->encoding();
4576   int nds_enc = nds->encoding();
4577   int src_enc = src->encoding();
4578   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4579     Assembler::vpmullw(dst, nds, src, vector_len);
4580   } else if ((dst_enc < 16) && (src_enc < 16)) {
4581     Assembler::vpmullw(dst, dst, src, vector_len);
4582   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4583     // use nds as scratch for src
4584     evmovdqul(nds, src, Assembler::AVX_512bit);
4585     Assembler::vpmullw(dst, dst, nds, vector_len);
4586   } else if ((src_enc < 16) && (nds_enc < 16)) {
4587     // use nds as scratch for dst
4588     evmovdqul(nds, dst, Assembler::AVX_512bit);
4589     Assembler::vpmullw(nds, nds, src, vector_len);
4590     evmovdqul(dst, nds, Assembler::AVX_512bit);
4591   } else if (dst_enc < 16) {
4592     // use nds as scatch for xmm0 to hold src
4593     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4594     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4595     Assembler::vpmullw(dst, dst, xmm0, vector_len);
4596     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4597   } else {
4598     // worse case scenario, all regs are in the upper bank
4599     subptr(rsp, 64);
4600     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4601     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4602     evmovdqul(xmm1, src, Assembler::AVX_512bit);
4603     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4604     Assembler::vpmullw(xmm0, xmm0, xmm1, vector_len);
4605     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4606     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4607     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4608     addptr(rsp, 64);
4609   }
4610 }
4611 
4612 void MacroAssembler::vpmullw(XMMRegister dst, XMMRegister nds, Address src, int vector_len) {
4613   int dst_enc = dst->encoding();
4614   int nds_enc = nds->encoding();
4615   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4616     Assembler::vpmullw(dst, nds, src, vector_len);
4617   } else if (dst_enc < 16) {
4618     Assembler::vpmullw(dst, dst, src, vector_len);
4619   } else if (nds_enc < 16) {
4620     // implies dst_enc in upper bank with src as scratch
4621     evmovdqul(nds, dst, Assembler::AVX_512bit);
4622     Assembler::vpmullw(nds, nds, src, vector_len);
4623     evmovdqul(dst, nds, Assembler::AVX_512bit);
4624   } else {
4625     // worse case scenario, all regs in upper bank
4626     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4627     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4628     Assembler::vpmullw(xmm0, xmm0, src, vector_len);
4629     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4630   }
4631 }
4632 
4633 void MacroAssembler::vpsubb(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::vpsubb(dst, nds, src, vector_len);
4639   } else if ((dst_enc < 16) && (src_enc < 16)) {
4640     Assembler::vpsubb(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::vpsubb(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::vpsubb(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::vpsubb(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::vpsubb(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::vpsubb(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::vpsubb(dst, nds, src, vector_len);
4676   } else if (dst_enc < 16) {
4677     Assembler::vpsubb(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::vpsubb(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::vpsubw(xmm0, xmm0, src, vector_len);
4688     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4689   }
4690 }
4691 
4692 void MacroAssembler::vpsubw(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::vpsubw(dst, nds, src, vector_len);
4698   } else if ((dst_enc < 16) && (src_enc < 16)) {
4699     Assembler::vpsubw(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::vpsubw(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::vpsubw(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::vpsubw(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::vpsubw(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::vpsubw(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::vpsubw(dst, nds, src, vector_len);
4735   } else if (dst_enc < 16) {
4736     Assembler::vpsubw(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::vpsubw(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::vpsraw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4752   int dst_enc = dst->encoding();
4753   int nds_enc = nds->encoding();
4754   int shift_enc = shift->encoding();
4755   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4756     Assembler::vpsraw(dst, nds, shift, vector_len);
4757   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4758     Assembler::vpsraw(dst, dst, shift, vector_len);
4759   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4760     // use nds_enc as scratch with shift
4761     evmovdqul(nds, shift, Assembler::AVX_512bit);
4762     Assembler::vpsraw(dst, dst, nds, vector_len);
4763   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4764     // use nds as scratch with dst
4765     evmovdqul(nds, dst, Assembler::AVX_512bit);
4766     Assembler::vpsraw(nds, nds, shift, vector_len);
4767     evmovdqul(dst, nds, Assembler::AVX_512bit);
4768   } else if (dst_enc < 16) {
4769     // use nds to save a copy of xmm0 and hold shift
4770     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4771     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4772     Assembler::vpsraw(dst, dst, xmm0, vector_len);
4773     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4774   } else if (nds_enc < 16) {
4775     // use nds as dest as temps
4776     evmovdqul(nds, dst, Assembler::AVX_512bit);
4777     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4778     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4779     Assembler::vpsraw(nds, nds, xmm0, vector_len);
4780     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4781     evmovdqul(dst, nds, Assembler::AVX_512bit);
4782   } else {
4783     // worse case scenario, all regs are in the upper bank
4784     subptr(rsp, 64);
4785     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4786     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4787     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4788     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4789     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4790     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4791     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4792     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4793     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4794     addptr(rsp, 64);
4795   }
4796 }
4797 
4798 void MacroAssembler::vpsraw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4799   int dst_enc = dst->encoding();
4800   int nds_enc = nds->encoding();
4801   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4802     Assembler::vpsraw(dst, nds, shift, vector_len);
4803   } else if (dst_enc < 16) {
4804     Assembler::vpsraw(dst, dst, shift, vector_len);
4805   } else if (nds_enc < 16) {
4806     // use nds as scratch
4807     evmovdqul(nds, dst, Assembler::AVX_512bit);
4808     Assembler::vpsraw(nds, nds, shift, vector_len);
4809     evmovdqul(dst, nds, Assembler::AVX_512bit);
4810   } else {
4811     // use nds as scratch for xmm0
4812     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4813     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4814     Assembler::vpsraw(xmm0, xmm0, shift, vector_len);
4815     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4816   }
4817 }
4818 
4819 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4820   int dst_enc = dst->encoding();
4821   int nds_enc = nds->encoding();
4822   int shift_enc = shift->encoding();
4823   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4824     Assembler::vpsrlw(dst, nds, shift, vector_len);
4825   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4826     Assembler::vpsrlw(dst, dst, shift, vector_len);
4827   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4828     // use nds_enc as scratch with shift
4829     evmovdqul(nds, shift, Assembler::AVX_512bit);
4830     Assembler::vpsrlw(dst, dst, nds, vector_len);
4831   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4832     // use nds as scratch with dst
4833     evmovdqul(nds, dst, Assembler::AVX_512bit);
4834     Assembler::vpsrlw(nds, nds, shift, vector_len);
4835     evmovdqul(dst, nds, Assembler::AVX_512bit);
4836   } else if (dst_enc < 16) {
4837     // use nds to save a copy of xmm0 and hold shift
4838     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4839     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4840     Assembler::vpsrlw(dst, dst, xmm0, vector_len);
4841     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4842   } else if (nds_enc < 16) {
4843     // use nds as dest as temps
4844     evmovdqul(nds, dst, Assembler::AVX_512bit);
4845     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4846     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4847     Assembler::vpsrlw(nds, nds, xmm0, vector_len);
4848     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4849     evmovdqul(dst, nds, Assembler::AVX_512bit);
4850   } else {
4851     // worse case scenario, all regs are in the upper bank
4852     subptr(rsp, 64);
4853     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4854     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4855     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4856     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4857     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4858     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4859     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4860     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4861     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4862     addptr(rsp, 64);
4863   }
4864 }
4865 
4866 void MacroAssembler::vpsrlw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4867   int dst_enc = dst->encoding();
4868   int nds_enc = nds->encoding();
4869   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4870     Assembler::vpsrlw(dst, nds, shift, vector_len);
4871   } else if (dst_enc < 16) {
4872     Assembler::vpsrlw(dst, dst, shift, vector_len);
4873   } else if (nds_enc < 16) {
4874     // use nds as scratch
4875     evmovdqul(nds, dst, Assembler::AVX_512bit);
4876     Assembler::vpsrlw(nds, nds, shift, vector_len);
4877     evmovdqul(dst, nds, Assembler::AVX_512bit);
4878   } else {
4879     // use nds as scratch for xmm0
4880     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4881     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4882     Assembler::vpsrlw(xmm0, xmm0, shift, vector_len);
4883     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4884   }
4885 }
4886 
4887 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, XMMRegister shift, int vector_len) {
4888   int dst_enc = dst->encoding();
4889   int nds_enc = nds->encoding();
4890   int shift_enc = shift->encoding();
4891   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4892     Assembler::vpsllw(dst, nds, shift, vector_len);
4893   } else if ((dst_enc < 16) && (shift_enc < 16)) {
4894     Assembler::vpsllw(dst, dst, shift, vector_len);
4895   } else if ((dst_enc < 16) && (nds_enc < 16)) {
4896     // use nds_enc as scratch with shift
4897     evmovdqul(nds, shift, Assembler::AVX_512bit);
4898     Assembler::vpsllw(dst, dst, nds, vector_len);
4899   } else if ((shift_enc < 16) && (nds_enc < 16)) {
4900     // use nds as scratch with dst
4901     evmovdqul(nds, dst, Assembler::AVX_512bit);
4902     Assembler::vpsllw(nds, nds, shift, vector_len);
4903     evmovdqul(dst, nds, Assembler::AVX_512bit);
4904   } else if (dst_enc < 16) {
4905     // use nds to save a copy of xmm0 and hold shift
4906     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4907     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4908     Assembler::vpsllw(dst, dst, xmm0, vector_len);
4909     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4910   } else if (nds_enc < 16) {
4911     // use nds as dest as temps
4912     evmovdqul(nds, dst, Assembler::AVX_512bit);
4913     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4914     evmovdqul(xmm0, shift, Assembler::AVX_512bit);
4915     Assembler::vpsllw(nds, nds, xmm0, vector_len);
4916     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4917     evmovdqul(dst, nds, Assembler::AVX_512bit);
4918   } else {
4919     // worse case scenario, all regs are in the upper bank
4920     subptr(rsp, 64);
4921     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4922     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4923     evmovdqul(xmm1, shift, Assembler::AVX_512bit);
4924     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4925     Assembler::vpsllw(xmm0, xmm0, xmm1, vector_len);
4926     evmovdqul(xmm1, dst, Assembler::AVX_512bit);
4927     evmovdqul(dst, xmm0, Assembler::AVX_512bit);
4928     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4929     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4930     addptr(rsp, 64);
4931   }
4932 }
4933 
4934 void MacroAssembler::vpsllw(XMMRegister dst, XMMRegister nds, int shift, int vector_len) {
4935   int dst_enc = dst->encoding();
4936   int nds_enc = nds->encoding();
4937   if (VM_Version::supports_avxonly() || VM_Version::supports_avx512bw()) {
4938     Assembler::vpsllw(dst, nds, shift, vector_len);
4939   } else if (dst_enc < 16) {
4940     Assembler::vpsllw(dst, dst, shift, vector_len);
4941   } else if (nds_enc < 16) {
4942     // use nds as scratch
4943     evmovdqul(nds, dst, Assembler::AVX_512bit);
4944     Assembler::vpsllw(nds, nds, shift, vector_len);
4945     evmovdqul(dst, nds, Assembler::AVX_512bit);
4946   } else {
4947     // use nds as scratch for xmm0
4948     evmovdqul(nds, xmm0, Assembler::AVX_512bit);
4949     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4950     Assembler::vpsllw(xmm0, xmm0, shift, vector_len);
4951     evmovdqul(xmm0, nds, Assembler::AVX_512bit);
4952   }
4953 }
4954 
4955 void MacroAssembler::vptest(XMMRegister dst, XMMRegister src) {
4956   int dst_enc = dst->encoding();
4957   int src_enc = src->encoding();
4958   if ((dst_enc < 16) && (src_enc < 16)) {
4959     Assembler::vptest(dst, src);
4960   } else if (src_enc < 16) {
4961     subptr(rsp, 64);
4962     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4963     evmovdqul(xmm0, dst, Assembler::AVX_512bit);
4964     Assembler::vptest(xmm0, src);
4965     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4966     addptr(rsp, 64);
4967   } else if (dst_enc < 16) {
4968     subptr(rsp, 64);
4969     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4970     evmovdqul(xmm0, src, Assembler::AVX_512bit);
4971     Assembler::vptest(dst, xmm0);
4972     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4973     addptr(rsp, 64);
4974   } else {
4975     subptr(rsp, 64);
4976     evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
4977     subptr(rsp, 64);
4978     evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
4979     movdqu(xmm0, src);
4980     movdqu(xmm1, dst);
4981     Assembler::vptest(xmm1, xmm0);
4982     evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
4983     addptr(rsp, 64);
4984     evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
4985     addptr(rsp, 64);
4986   }
4987 }
4988 
4989 // This instruction exists within macros, ergo we cannot control its input
4990 // when emitted through those patterns.
4991 void MacroAssembler::punpcklbw(XMMRegister dst, XMMRegister src) {
4992   if (VM_Version::supports_avx512nobw()) {
4993     int dst_enc = dst->encoding();
4994     int src_enc = src->encoding();
4995     if (dst_enc == src_enc) {
4996       if (dst_enc < 16) {
4997         Assembler::punpcklbw(dst, src);
4998       } else {
4999         subptr(rsp, 64);
5000         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5001         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5002         Assembler::punpcklbw(xmm0, xmm0);
5003         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5004         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5005         addptr(rsp, 64);
5006       }
5007     } else {
5008       if ((src_enc < 16) && (dst_enc < 16)) {
5009         Assembler::punpcklbw(dst, src);
5010       } else if (src_enc < 16) {
5011         subptr(rsp, 64);
5012         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5013         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5014         Assembler::punpcklbw(xmm0, src);
5015         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5016         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5017         addptr(rsp, 64);
5018       } else if (dst_enc < 16) {
5019         subptr(rsp, 64);
5020         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5021         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5022         Assembler::punpcklbw(dst, xmm0);
5023         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5024         addptr(rsp, 64);
5025       } else {
5026         subptr(rsp, 64);
5027         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5028         subptr(rsp, 64);
5029         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5030         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5031         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5032         Assembler::punpcklbw(xmm0, xmm1);
5033         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5034         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5035         addptr(rsp, 64);
5036         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5037         addptr(rsp, 64);
5038       }
5039     }
5040   } else {
5041     Assembler::punpcklbw(dst, src);
5042   }
5043 }
5044 
5045 void MacroAssembler::pshufd(XMMRegister dst, Address src, int mode) {
5046   if (VM_Version::supports_avx512vl()) {
5047     Assembler::pshufd(dst, src, mode);
5048   } else {
5049     int dst_enc = dst->encoding();
5050     if (dst_enc < 16) {
5051       Assembler::pshufd(dst, src, mode);
5052     } else {
5053       subptr(rsp, 64);
5054       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5055       Assembler::pshufd(xmm0, src, mode);
5056       evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5057       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5058       addptr(rsp, 64);
5059     }
5060   }
5061 }
5062 
5063 // This instruction exists within macros, ergo we cannot control its input
5064 // when emitted through those patterns.
5065 void MacroAssembler::pshuflw(XMMRegister dst, XMMRegister src, int mode) {
5066   if (VM_Version::supports_avx512nobw()) {
5067     int dst_enc = dst->encoding();
5068     int src_enc = src->encoding();
5069     if (dst_enc == src_enc) {
5070       if (dst_enc < 16) {
5071         Assembler::pshuflw(dst, src, mode);
5072       } else {
5073         subptr(rsp, 64);
5074         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5075         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5076         Assembler::pshuflw(xmm0, xmm0, mode);
5077         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5078         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5079         addptr(rsp, 64);
5080       }
5081     } else {
5082       if ((src_enc < 16) && (dst_enc < 16)) {
5083         Assembler::pshuflw(dst, src, mode);
5084       } else if (src_enc < 16) {
5085         subptr(rsp, 64);
5086         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5087         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5088         Assembler::pshuflw(xmm0, src, mode);
5089         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5090         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5091         addptr(rsp, 64);
5092       } else if (dst_enc < 16) {
5093         subptr(rsp, 64);
5094         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5095         evmovdqul(xmm0, src, Assembler::AVX_512bit);
5096         Assembler::pshuflw(dst, xmm0, mode);
5097         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5098         addptr(rsp, 64);
5099       } else {
5100         subptr(rsp, 64);
5101         evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5102         subptr(rsp, 64);
5103         evmovdqul(Address(rsp, 0), xmm1, Assembler::AVX_512bit);
5104         evmovdqul(xmm0, dst, Assembler::AVX_512bit);
5105         evmovdqul(xmm1, src, Assembler::AVX_512bit);
5106         Assembler::pshuflw(xmm0, xmm1, mode);
5107         evmovdqul(dst, xmm0, Assembler::AVX_512bit);
5108         evmovdqul(xmm1, Address(rsp, 0), Assembler::AVX_512bit);
5109         addptr(rsp, 64);
5110         evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5111         addptr(rsp, 64);
5112       }
5113     }
5114   } else {
5115     Assembler::pshuflw(dst, src, mode);
5116   }
5117 }
5118 
5119 void MacroAssembler::vandpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5120   if (reachable(src)) {
5121     vandpd(dst, nds, as_Address(src), vector_len);
5122   } else {
5123     lea(rscratch1, src);
5124     vandpd(dst, nds, Address(rscratch1, 0), vector_len);
5125   }
5126 }
5127 
5128 void MacroAssembler::vandps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5129   if (reachable(src)) {
5130     vandps(dst, nds, as_Address(src), vector_len);
5131   } else {
5132     lea(rscratch1, src);
5133     vandps(dst, nds, Address(rscratch1, 0), vector_len);
5134   }
5135 }
5136 
5137 void MacroAssembler::vdivsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5138   if (reachable(src)) {
5139     vdivsd(dst, nds, as_Address(src));
5140   } else {
5141     lea(rscratch1, src);
5142     vdivsd(dst, nds, Address(rscratch1, 0));
5143   }
5144 }
5145 
5146 void MacroAssembler::vdivss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5147   if (reachable(src)) {
5148     vdivss(dst, nds, as_Address(src));
5149   } else {
5150     lea(rscratch1, src);
5151     vdivss(dst, nds, Address(rscratch1, 0));
5152   }
5153 }
5154 
5155 void MacroAssembler::vmulsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5156   if (reachable(src)) {
5157     vmulsd(dst, nds, as_Address(src));
5158   } else {
5159     lea(rscratch1, src);
5160     vmulsd(dst, nds, Address(rscratch1, 0));
5161   }
5162 }
5163 
5164 void MacroAssembler::vmulss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5165   if (reachable(src)) {
5166     vmulss(dst, nds, as_Address(src));
5167   } else {
5168     lea(rscratch1, src);
5169     vmulss(dst, nds, Address(rscratch1, 0));
5170   }
5171 }
5172 
5173 void MacroAssembler::vsubsd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5174   if (reachable(src)) {
5175     vsubsd(dst, nds, as_Address(src));
5176   } else {
5177     lea(rscratch1, src);
5178     vsubsd(dst, nds, Address(rscratch1, 0));
5179   }
5180 }
5181 
5182 void MacroAssembler::vsubss(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5183   if (reachable(src)) {
5184     vsubss(dst, nds, as_Address(src));
5185   } else {
5186     lea(rscratch1, src);
5187     vsubss(dst, nds, Address(rscratch1, 0));
5188   }
5189 }
5190 
5191 void MacroAssembler::vnegatess(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5192   int nds_enc = nds->encoding();
5193   int dst_enc = dst->encoding();
5194   bool dst_upper_bank = (dst_enc > 15);
5195   bool nds_upper_bank = (nds_enc > 15);
5196   if (VM_Version::supports_avx512novl() &&
5197       (nds_upper_bank || dst_upper_bank)) {
5198     if (dst_upper_bank) {
5199       subptr(rsp, 64);
5200       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5201       movflt(xmm0, nds);
5202       vxorps(xmm0, xmm0, src, Assembler::AVX_128bit);
5203       movflt(dst, xmm0);
5204       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5205       addptr(rsp, 64);
5206     } else {
5207       movflt(dst, nds);
5208       vxorps(dst, dst, src, Assembler::AVX_128bit);
5209     }
5210   } else {
5211     vxorps(dst, nds, src, Assembler::AVX_128bit);
5212   }
5213 }
5214 
5215 void MacroAssembler::vnegatesd(XMMRegister dst, XMMRegister nds, AddressLiteral src) {
5216   int nds_enc = nds->encoding();
5217   int dst_enc = dst->encoding();
5218   bool dst_upper_bank = (dst_enc > 15);
5219   bool nds_upper_bank = (nds_enc > 15);
5220   if (VM_Version::supports_avx512novl() &&
5221       (nds_upper_bank || dst_upper_bank)) {
5222     if (dst_upper_bank) {
5223       subptr(rsp, 64);
5224       evmovdqul(Address(rsp, 0), xmm0, Assembler::AVX_512bit);
5225       movdbl(xmm0, nds);
5226       vxorpd(xmm0, xmm0, src, Assembler::AVX_128bit);
5227       movdbl(dst, xmm0);
5228       evmovdqul(xmm0, Address(rsp, 0), Assembler::AVX_512bit);
5229       addptr(rsp, 64);
5230     } else {
5231       movdbl(dst, nds);
5232       vxorpd(dst, dst, src, Assembler::AVX_128bit);
5233     }
5234   } else {
5235     vxorpd(dst, nds, src, Assembler::AVX_128bit);
5236   }
5237 }
5238 
5239 void MacroAssembler::vxorpd(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5240   if (reachable(src)) {
5241     vxorpd(dst, nds, as_Address(src), vector_len);
5242   } else {
5243     lea(rscratch1, src);
5244     vxorpd(dst, nds, Address(rscratch1, 0), vector_len);
5245   }
5246 }
5247 
5248 void MacroAssembler::vxorps(XMMRegister dst, XMMRegister nds, AddressLiteral src, int vector_len) {
5249   if (reachable(src)) {
5250     vxorps(dst, nds, as_Address(src), vector_len);
5251   } else {
5252     lea(rscratch1, src);
5253     vxorps(dst, nds, Address(rscratch1, 0), vector_len);
5254   }
5255 }
5256 
5257 void MacroAssembler::clear_jweak_tag(Register possibly_jweak) {
5258   const int32_t inverted_jweak_mask = ~static_cast<int32_t>(JNIHandles::weak_tag_mask);
5259   STATIC_ASSERT(inverted_jweak_mask == -2); // otherwise check this code
5260   // The inverted mask is sign-extended
5261   andptr(possibly_jweak, inverted_jweak_mask);
5262 }
5263 
5264 void MacroAssembler::resolve_jobject(Register value,
5265                                      Register thread,
5266                                      Register tmp) {
5267   assert_different_registers(value, thread, tmp);
5268   Label done, not_weak;
5269   testptr(value, value);
5270   jcc(Assembler::zero, done);                // Use NULL as-is.
5271   testptr(value, JNIHandles::weak_tag_mask); // Test for jweak tag.
5272   jcc(Assembler::zero, not_weak);
5273   // Resolve jweak.
5274   access_load_at(T_OBJECT, IN_ROOT | ON_PHANTOM_OOP_REF,
5275                  value, Address(value, -JNIHandles::weak_tag_value), tmp, thread);
5276   verify_oop(value);
5277   jmp(done);
5278   bind(not_weak);
5279   // Resolve (untagged) jobject.
5280   access_load_at(T_OBJECT, IN_CONCURRENT_ROOT,
5281                  value, Address(value, 0), tmp, thread);
5282   verify_oop(value);
5283   bind(done);
5284 }
5285 
5286 #if INCLUDE_SHENANDOAHGC
5287 #ifndef _LP64
5288 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5289   Unimplemented();
5290 }
5291 #else
5292 void MacroAssembler::shenandoah_write_barrier(Register dst) {
5293   assert(UseShenandoahGC && (ShenandoahWriteBarrier || ShenandoahStoreValEnqueueBarrier), "Should be enabled");
5294 
5295   Label done;
5296 
5297   Address gc_state(r15_thread, in_bytes(ShenandoahThreadLocalData::gc_state_offset()));
5298 
5299   // Check for heap stability
5300   cmpb(gc_state, 0);
5301   jccb(Assembler::zero, done);
5302 
5303   // Heap is unstable, need to perform the read-barrier even if WB is inactive
5304   if (ShenandoahWriteBarrierRB) {
5305     movptr(dst, Address(dst, BrooksPointer::byte_offset()));
5306   }
5307 
5308   // Check for evacuation-in-progress and jump to WB slow-path if needed
5309   testb(gc_state, ShenandoahHeap::EVACUATION | ShenandoahHeap::TRAVERSAL);
5310   jccb(Assembler::zero, done);
5311 
5312   if (dst != rax) {
5313     xchgptr(dst, rax); // Move obj into rax and save rax into obj.
5314   }
5315 
5316   assert(StubRoutines::x86::shenandoah_wb() != NULL, "need write barrier stub");
5317   call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::shenandoah_wb())));
5318 
5319   if (dst != rax) {
5320     xchgptr(rax, dst); // Swap back obj with rax.
5321   }
5322 
5323   bind(done);
5324 }
5325 #endif // _LP64
5326 
5327 #endif // INCLUDE_SHENANDOAHGC
5328 
5329 void MacroAssembler::subptr(Register dst, int32_t imm32) {
5330   LP64_ONLY(subq(dst, imm32)) NOT_LP64(subl(dst, imm32));
5331 }
5332 
5333 // Force generation of a 4 byte immediate value even if it fits into 8bit
5334 void MacroAssembler::subptr_imm32(Register dst, int32_t imm32) {
5335   LP64_ONLY(subq_imm32(dst, imm32)) NOT_LP64(subl_imm32(dst, imm32));
5336 }
5337 
5338 void MacroAssembler::subptr(Register dst, Register src) {
5339   LP64_ONLY(subq(dst, src)) NOT_LP64(subl(dst, src));
5340 }
5341 
5342 // C++ bool manipulation
5343 void MacroAssembler::testbool(Register dst) {
5344   if(sizeof(bool) == 1)
5345     testb(dst, 0xff);
5346   else if(sizeof(bool) == 2) {
5347     // testw implementation needed for two byte bools
5348     ShouldNotReachHere();
5349   } else if(sizeof(bool) == 4)
5350     testl(dst, dst);
5351   else
5352     // unsupported
5353     ShouldNotReachHere();
5354 }
5355 
5356 void MacroAssembler::testptr(Register dst, Register src) {
5357   LP64_ONLY(testq(dst, src)) NOT_LP64(testl(dst, src));
5358 }
5359 
5360 // Defines obj, preserves var_size_in_bytes, okay for t2 == var_size_in_bytes.
5361 void MacroAssembler::tlab_allocate(Register obj,
5362                                    Register var_size_in_bytes,
5363                                    int con_size_in_bytes,
5364                                    Register t1,
5365                                    Register t2,
5366                                    Label& slow_case) {
5367   assert_different_registers(obj, t1, t2);
5368   assert_different_registers(obj, var_size_in_bytes, t1);
5369   Register end = t2;
5370   Register thread = NOT_LP64(t1) LP64_ONLY(r15_thread);
5371 
5372   verify_tlab();
5373 
5374   NOT_LP64(get_thread(thread));
5375 
5376   uint oop_extra_words = Universe::heap()->oop_extra_words();
5377 
5378   movptr(obj, Address(thread, JavaThread::tlab_top_offset()));
5379   if (var_size_in_bytes == noreg) {
5380     lea(end, Address(obj, con_size_in_bytes + oop_extra_words * HeapWordSize));
5381   } else {
5382     if (oop_extra_words > 0) {
5383       addptr(var_size_in_bytes, oop_extra_words * HeapWordSize);
5384     }
5385     lea(end, Address(obj, var_size_in_bytes, Address::times_1));
5386   }
5387   cmpptr(end, Address(thread, JavaThread::tlab_end_offset()));
5388   jcc(Assembler::above, slow_case);
5389 
5390   // update the tlab top pointer
5391   movptr(Address(thread, JavaThread::tlab_top_offset()), end);
5392 
5393   Universe::heap()->compile_prepare_oop(this, obj);
5394 
5395   // recover var_size_in_bytes if necessary
5396   if (var_size_in_bytes == end) {
5397     subptr(var_size_in_bytes, obj);
5398   }
5399   verify_tlab();
5400 }
5401 
5402 // Preserves the contents of address, destroys the contents length_in_bytes and temp.
5403 void MacroAssembler::zero_memory(Register address, Register length_in_bytes, int offset_in_bytes, Register temp) {
5404   assert(address != length_in_bytes && address != temp && temp != length_in_bytes, "registers must be different");
5405   assert((offset_in_bytes & (BytesPerWord - 1)) == 0, "offset must be a multiple of BytesPerWord");
5406   Label done;
5407 
5408   testptr(length_in_bytes, length_in_bytes);
5409   jcc(Assembler::zero, done);
5410 
5411   // initialize topmost word, divide index by 2, check if odd and test if zero
5412   // note: for the remaining code to work, index must be a multiple of BytesPerWord
5413 #ifdef ASSERT
5414   {
5415     Label L;
5416     testptr(length_in_bytes, BytesPerWord - 1);
5417     jcc(Assembler::zero, L);
5418     stop("length must be a multiple of BytesPerWord");
5419     bind(L);
5420   }
5421 #endif
5422   Register index = length_in_bytes;
5423   xorptr(temp, temp);    // use _zero reg to clear memory (shorter code)
5424   if (UseIncDec) {
5425     shrptr(index, 3);  // divide by 8/16 and set carry flag if bit 2 was set
5426   } else {
5427     shrptr(index, 2);  // use 2 instructions to avoid partial flag stall
5428     shrptr(index, 1);
5429   }
5430 #ifndef _LP64
5431   // index could have not been a multiple of 8 (i.e., bit 2 was set)
5432   {
5433     Label even;
5434     // note: if index was a multiple of 8, then it cannot
5435     //       be 0 now otherwise it must have been 0 before
5436     //       => if it is even, we don't need to check for 0 again
5437     jcc(Assembler::carryClear, even);
5438     // clear topmost word (no jump would be needed if conditional assignment worked here)
5439     movptr(Address(address, index, Address::times_8, offset_in_bytes - 0*BytesPerWord), temp);
5440     // index could be 0 now, must check again
5441     jcc(Assembler::zero, done);
5442     bind(even);
5443   }
5444 #endif // !_LP64
5445   // initialize remaining object fields: index is a multiple of 2 now
5446   {
5447     Label loop;
5448     bind(loop);
5449     movptr(Address(address, index, Address::times_8, offset_in_bytes - 1*BytesPerWord), temp);
5450     NOT_LP64(movptr(Address(address, index, Address::times_8, offset_in_bytes - 2*BytesPerWord), temp);)
5451     decrement(index);
5452     jcc(Assembler::notZero, loop);
5453   }
5454 
5455   bind(done);
5456 }
5457 
5458 void MacroAssembler::incr_allocated_bytes(Register thread,
5459                                           Register var_size_in_bytes,
5460                                           int con_size_in_bytes,
5461                                           Register t1) {
5462   if (!thread->is_valid()) {
5463 #ifdef _LP64
5464     thread = r15_thread;
5465 #else
5466     assert(t1->is_valid(), "need temp reg");
5467     thread = t1;
5468     get_thread(thread);
5469 #endif
5470   }
5471 
5472 #ifdef _LP64
5473   if (var_size_in_bytes->is_valid()) {
5474     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5475   } else {
5476     addq(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5477   }
5478 #else
5479   if (var_size_in_bytes->is_valid()) {
5480     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), var_size_in_bytes);
5481   } else {
5482     addl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())), con_size_in_bytes);
5483   }
5484   adcl(Address(thread, in_bytes(JavaThread::allocated_bytes_offset())+4), 0);
5485 #endif
5486 }
5487 
5488 // Look up the method for a megamorphic invokeinterface call.
5489 // The target method is determined by <intf_klass, itable_index>.
5490 // The receiver klass is in recv_klass.
5491 // On success, the result will be in method_result, and execution falls through.
5492 // On failure, execution transfers to the given label.
5493 void MacroAssembler::lookup_interface_method(Register recv_klass,
5494                                              Register intf_klass,
5495                                              RegisterOrConstant itable_index,
5496                                              Register method_result,
5497                                              Register scan_temp,
5498                                              Label& L_no_such_interface,
5499                                              bool return_method) {
5500   assert_different_registers(recv_klass, intf_klass, scan_temp);
5501   assert_different_registers(method_result, intf_klass, scan_temp);
5502   assert(recv_klass != method_result || !return_method,
5503          "recv_klass can be destroyed when method isn't needed");
5504 
5505   assert(itable_index.is_constant() || itable_index.as_register() == method_result,
5506          "caller must use same register for non-constant itable index as for method");
5507 
5508   // Compute start of first itableOffsetEntry (which is at the end of the vtable)
5509   int vtable_base = in_bytes(Klass::vtable_start_offset());
5510   int itentry_off = itableMethodEntry::method_offset_in_bytes();
5511   int scan_step   = itableOffsetEntry::size() * wordSize;
5512   int vte_size    = vtableEntry::size_in_bytes();
5513   Address::ScaleFactor times_vte_scale = Address::times_ptr;
5514   assert(vte_size == wordSize, "else adjust times_vte_scale");
5515 
5516   movl(scan_temp, Address(recv_klass, Klass::vtable_length_offset()));
5517 
5518   // %%% Could store the aligned, prescaled offset in the klassoop.
5519   lea(scan_temp, Address(recv_klass, scan_temp, times_vte_scale, vtable_base));
5520 
5521   if (return_method) {
5522     // Adjust recv_klass by scaled itable_index, so we can free itable_index.
5523     assert(itableMethodEntry::size() * wordSize == wordSize, "adjust the scaling in the code below");
5524     lea(recv_klass, Address(recv_klass, itable_index, Address::times_ptr, itentry_off));
5525   }
5526 
5527   // for (scan = klass->itable(); scan->interface() != NULL; scan += scan_step) {
5528   //   if (scan->interface() == intf) {
5529   //     result = (klass + scan->offset() + itable_index);
5530   //   }
5531   // }
5532   Label search, found_method;
5533 
5534   for (int peel = 1; peel >= 0; peel--) {
5535     movptr(method_result, Address(scan_temp, itableOffsetEntry::interface_offset_in_bytes()));
5536     cmpptr(intf_klass, method_result);
5537 
5538     if (peel) {
5539       jccb(Assembler::equal, found_method);
5540     } else {
5541       jccb(Assembler::notEqual, search);
5542       // (invert the test to fall through to found_method...)
5543     }
5544 
5545     if (!peel)  break;
5546 
5547     bind(search);
5548 
5549     // Check that the previous entry is non-null.  A null entry means that
5550     // the receiver class doesn't implement the interface, and wasn't the
5551     // same as when the caller was compiled.
5552     testptr(method_result, method_result);
5553     jcc(Assembler::zero, L_no_such_interface);
5554     addptr(scan_temp, scan_step);
5555   }
5556 
5557   bind(found_method);
5558 
5559   if (return_method) {
5560     // Got a hit.
5561     movl(scan_temp, Address(scan_temp, itableOffsetEntry::offset_offset_in_bytes()));
5562     movptr(method_result, Address(recv_klass, scan_temp, Address::times_1));
5563   }
5564 }
5565 
5566 
5567 // virtual method calling
5568 void MacroAssembler::lookup_virtual_method(Register recv_klass,
5569                                            RegisterOrConstant vtable_index,
5570                                            Register method_result) {
5571   const int base = in_bytes(Klass::vtable_start_offset());
5572   assert(vtableEntry::size() * wordSize == wordSize, "else adjust the scaling in the code below");
5573   Address vtable_entry_addr(recv_klass,
5574                             vtable_index, Address::times_ptr,
5575                             base + vtableEntry::method_offset_in_bytes());
5576   movptr(method_result, vtable_entry_addr);
5577 }
5578 
5579 
5580 void MacroAssembler::check_klass_subtype(Register sub_klass,
5581                            Register super_klass,
5582                            Register temp_reg,
5583                            Label& L_success) {
5584   Label L_failure;
5585   check_klass_subtype_fast_path(sub_klass, super_klass, temp_reg,        &L_success, &L_failure, NULL);
5586   check_klass_subtype_slow_path(sub_klass, super_klass, temp_reg, noreg, &L_success, NULL);
5587   bind(L_failure);
5588 }
5589 
5590 
5591 void MacroAssembler::check_klass_subtype_fast_path(Register sub_klass,
5592                                                    Register super_klass,
5593                                                    Register temp_reg,
5594                                                    Label* L_success,
5595                                                    Label* L_failure,
5596                                                    Label* L_slow_path,
5597                                         RegisterOrConstant super_check_offset) {
5598   assert_different_registers(sub_klass, super_klass, temp_reg);
5599   bool must_load_sco = (super_check_offset.constant_or_zero() == -1);
5600   if (super_check_offset.is_register()) {
5601     assert_different_registers(sub_klass, super_klass,
5602                                super_check_offset.as_register());
5603   } else if (must_load_sco) {
5604     assert(temp_reg != noreg, "supply either a temp or a register offset");
5605   }
5606 
5607   Label L_fallthrough;
5608   int label_nulls = 0;
5609   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5610   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5611   if (L_slow_path == NULL) { L_slow_path = &L_fallthrough; label_nulls++; }
5612   assert(label_nulls <= 1, "at most one NULL in the batch");
5613 
5614   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5615   int sco_offset = in_bytes(Klass::super_check_offset_offset());
5616   Address super_check_offset_addr(super_klass, sco_offset);
5617 
5618   // Hacked jcc, which "knows" that L_fallthrough, at least, is in
5619   // range of a jccb.  If this routine grows larger, reconsider at
5620   // least some of these.
5621 #define local_jcc(assembler_cond, label)                                \
5622   if (&(label) == &L_fallthrough)  jccb(assembler_cond, label);         \
5623   else                             jcc( assembler_cond, label) /*omit semi*/
5624 
5625   // Hacked jmp, which may only be used just before L_fallthrough.
5626 #define final_jmp(label)                                                \
5627   if (&(label) == &L_fallthrough) { /*do nothing*/ }                    \
5628   else                            jmp(label)                /*omit semi*/
5629 
5630   // If the pointers are equal, we are done (e.g., String[] elements).
5631   // This self-check enables sharing of secondary supertype arrays among
5632   // non-primary types such as array-of-interface.  Otherwise, each such
5633   // type would need its own customized SSA.
5634   // We move this check to the front of the fast path because many
5635   // type checks are in fact trivially successful in this manner,
5636   // so we get a nicely predicted branch right at the start of the check.
5637   cmpptr(sub_klass, super_klass);
5638   local_jcc(Assembler::equal, *L_success);
5639 
5640   // Check the supertype display:
5641   if (must_load_sco) {
5642     // Positive movl does right thing on LP64.
5643     movl(temp_reg, super_check_offset_addr);
5644     super_check_offset = RegisterOrConstant(temp_reg);
5645   }
5646   Address super_check_addr(sub_klass, super_check_offset, Address::times_1, 0);
5647   cmpptr(super_klass, super_check_addr); // load displayed supertype
5648 
5649   // This check has worked decisively for primary supers.
5650   // Secondary supers are sought in the super_cache ('super_cache_addr').
5651   // (Secondary supers are interfaces and very deeply nested subtypes.)
5652   // This works in the same check above because of a tricky aliasing
5653   // between the super_cache and the primary super display elements.
5654   // (The 'super_check_addr' can address either, as the case requires.)
5655   // Note that the cache is updated below if it does not help us find
5656   // what we need immediately.
5657   // So if it was a primary super, we can just fail immediately.
5658   // Otherwise, it's the slow path for us (no success at this point).
5659 
5660   if (super_check_offset.is_register()) {
5661     local_jcc(Assembler::equal, *L_success);
5662     cmpl(super_check_offset.as_register(), sc_offset);
5663     if (L_failure == &L_fallthrough) {
5664       local_jcc(Assembler::equal, *L_slow_path);
5665     } else {
5666       local_jcc(Assembler::notEqual, *L_failure);
5667       final_jmp(*L_slow_path);
5668     }
5669   } else if (super_check_offset.as_constant() == sc_offset) {
5670     // Need a slow path; fast failure is impossible.
5671     if (L_slow_path == &L_fallthrough) {
5672       local_jcc(Assembler::equal, *L_success);
5673     } else {
5674       local_jcc(Assembler::notEqual, *L_slow_path);
5675       final_jmp(*L_success);
5676     }
5677   } else {
5678     // No slow path; it's a fast decision.
5679     if (L_failure == &L_fallthrough) {
5680       local_jcc(Assembler::equal, *L_success);
5681     } else {
5682       local_jcc(Assembler::notEqual, *L_failure);
5683       final_jmp(*L_success);
5684     }
5685   }
5686 
5687   bind(L_fallthrough);
5688 
5689 #undef local_jcc
5690 #undef final_jmp
5691 }
5692 
5693 
5694 void MacroAssembler::check_klass_subtype_slow_path(Register sub_klass,
5695                                                    Register super_klass,
5696                                                    Register temp_reg,
5697                                                    Register temp2_reg,
5698                                                    Label* L_success,
5699                                                    Label* L_failure,
5700                                                    bool set_cond_codes) {
5701   assert_different_registers(sub_klass, super_klass, temp_reg);
5702   if (temp2_reg != noreg)
5703     assert_different_registers(sub_klass, super_klass, temp_reg, temp2_reg);
5704 #define IS_A_TEMP(reg) ((reg) == temp_reg || (reg) == temp2_reg)
5705 
5706   Label L_fallthrough;
5707   int label_nulls = 0;
5708   if (L_success == NULL)   { L_success   = &L_fallthrough; label_nulls++; }
5709   if (L_failure == NULL)   { L_failure   = &L_fallthrough; label_nulls++; }
5710   assert(label_nulls <= 1, "at most one NULL in the batch");
5711 
5712   // a couple of useful fields in sub_klass:
5713   int ss_offset = in_bytes(Klass::secondary_supers_offset());
5714   int sc_offset = in_bytes(Klass::secondary_super_cache_offset());
5715   Address secondary_supers_addr(sub_klass, ss_offset);
5716   Address super_cache_addr(     sub_klass, sc_offset);
5717 
5718   // Do a linear scan of the secondary super-klass chain.
5719   // This code is rarely used, so simplicity is a virtue here.
5720   // The repne_scan instruction uses fixed registers, which we must spill.
5721   // Don't worry too much about pre-existing connections with the input regs.
5722 
5723   assert(sub_klass != rax, "killed reg"); // killed by mov(rax, super)
5724   assert(sub_klass != rcx, "killed reg"); // killed by lea(rcx, &pst_counter)
5725 
5726   // Get super_klass value into rax (even if it was in rdi or rcx).
5727   bool pushed_rax = false, pushed_rcx = false, pushed_rdi = false;
5728   if (super_klass != rax || UseCompressedOops) {
5729     if (!IS_A_TEMP(rax)) { push(rax); pushed_rax = true; }
5730     mov(rax, super_klass);
5731   }
5732   if (!IS_A_TEMP(rcx)) { push(rcx); pushed_rcx = true; }
5733   if (!IS_A_TEMP(rdi)) { push(rdi); pushed_rdi = true; }
5734 
5735 #ifndef PRODUCT
5736   int* pst_counter = &SharedRuntime::_partial_subtype_ctr;
5737   ExternalAddress pst_counter_addr((address) pst_counter);
5738   NOT_LP64(  incrementl(pst_counter_addr) );
5739   LP64_ONLY( lea(rcx, pst_counter_addr) );
5740   LP64_ONLY( incrementl(Address(rcx, 0)) );
5741 #endif //PRODUCT
5742 
5743   // We will consult the secondary-super array.
5744   movptr(rdi, secondary_supers_addr);
5745   // Load the array length.  (Positive movl does right thing on LP64.)
5746   movl(rcx, Address(rdi, Array<Klass*>::length_offset_in_bytes()));
5747   // Skip to start of data.
5748   addptr(rdi, Array<Klass*>::base_offset_in_bytes());
5749 
5750   // Scan RCX words at [RDI] for an occurrence of RAX.
5751   // Set NZ/Z based on last compare.
5752   // Z flag value will not be set by 'repne' if RCX == 0 since 'repne' does
5753   // not change flags (only scas instruction which is repeated sets flags).
5754   // Set Z = 0 (not equal) before 'repne' to indicate that class was not found.
5755 
5756     testptr(rax,rax); // Set Z = 0
5757     repne_scan();
5758 
5759   // Unspill the temp. registers:
5760   if (pushed_rdi)  pop(rdi);
5761   if (pushed_rcx)  pop(rcx);
5762   if (pushed_rax)  pop(rax);
5763 
5764   if (set_cond_codes) {
5765     // Special hack for the AD files:  rdi is guaranteed non-zero.
5766     assert(!pushed_rdi, "rdi must be left non-NULL");
5767     // Also, the condition codes are properly set Z/NZ on succeed/failure.
5768   }
5769 
5770   if (L_failure == &L_fallthrough)
5771         jccb(Assembler::notEqual, *L_failure);
5772   else  jcc(Assembler::notEqual, *L_failure);
5773 
5774   // Success.  Cache the super we found and proceed in triumph.
5775   movptr(super_cache_addr, super_klass);
5776 
5777   if (L_success != &L_fallthrough) {
5778     jmp(*L_success);
5779   }
5780 
5781 #undef IS_A_TEMP
5782 
5783   bind(L_fallthrough);
5784 }
5785 
5786 
5787 void MacroAssembler::cmov32(Condition cc, Register dst, Address src) {
5788   if (VM_Version::supports_cmov()) {
5789     cmovl(cc, dst, src);
5790   } else {
5791     Label L;
5792     jccb(negate_condition(cc), L);
5793     movl(dst, src);
5794     bind(L);
5795   }
5796 }
5797 
5798 void MacroAssembler::cmov32(Condition cc, Register dst, Register src) {
5799   if (VM_Version::supports_cmov()) {
5800     cmovl(cc, dst, src);
5801   } else {
5802     Label L;
5803     jccb(negate_condition(cc), L);
5804     movl(dst, src);
5805     bind(L);
5806   }
5807 }
5808 
5809 void MacroAssembler::verify_oop(Register reg, const char* s) {
5810   if (!VerifyOops) return;
5811 
5812   // Pass register number to verify_oop_subroutine
5813   const char* b = NULL;
5814   {
5815     ResourceMark rm;
5816     stringStream ss;
5817     ss.print("verify_oop: %s: %s", reg->name(), s);
5818     b = code_string(ss.as_string());
5819   }
5820   BLOCK_COMMENT("verify_oop {");
5821 #ifdef _LP64
5822   push(rscratch1);                    // save r10, trashed by movptr()
5823 #endif
5824   push(rax);                          // save rax,
5825   push(reg);                          // pass register argument
5826   ExternalAddress buffer((address) b);
5827   // avoid using pushptr, as it modifies scratch registers
5828   // and our contract is not to modify anything
5829   movptr(rax, buffer.addr());
5830   push(rax);
5831   // call indirectly to solve generation ordering problem
5832   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5833   call(rax);
5834   // Caller pops the arguments (oop, message) and restores rax, r10
5835   BLOCK_COMMENT("} verify_oop");
5836 }
5837 
5838 
5839 RegisterOrConstant MacroAssembler::delayed_value_impl(intptr_t* delayed_value_addr,
5840                                                       Register tmp,
5841                                                       int offset) {
5842   intptr_t value = *delayed_value_addr;
5843   if (value != 0)
5844     return RegisterOrConstant(value + offset);
5845 
5846   // load indirectly to solve generation ordering problem
5847   movptr(tmp, ExternalAddress((address) delayed_value_addr));
5848 
5849 #ifdef ASSERT
5850   { Label L;
5851     testptr(tmp, tmp);
5852     if (WizardMode) {
5853       const char* buf = NULL;
5854       {
5855         ResourceMark rm;
5856         stringStream ss;
5857         ss.print("DelayedValue=" INTPTR_FORMAT, delayed_value_addr[1]);
5858         buf = code_string(ss.as_string());
5859       }
5860       jcc(Assembler::notZero, L);
5861       STOP(buf);
5862     } else {
5863       jccb(Assembler::notZero, L);
5864       hlt();
5865     }
5866     bind(L);
5867   }
5868 #endif
5869 
5870   if (offset != 0)
5871     addptr(tmp, offset);
5872 
5873   return RegisterOrConstant(tmp);
5874 }
5875 
5876 
5877 Address MacroAssembler::argument_address(RegisterOrConstant arg_slot,
5878                                          int extra_slot_offset) {
5879   // cf. TemplateTable::prepare_invoke(), if (load_receiver).
5880   int stackElementSize = Interpreter::stackElementSize;
5881   int offset = Interpreter::expr_offset_in_bytes(extra_slot_offset+0);
5882 #ifdef ASSERT
5883   int offset1 = Interpreter::expr_offset_in_bytes(extra_slot_offset+1);
5884   assert(offset1 - offset == stackElementSize, "correct arithmetic");
5885 #endif
5886   Register             scale_reg    = noreg;
5887   Address::ScaleFactor scale_factor = Address::no_scale;
5888   if (arg_slot.is_constant()) {
5889     offset += arg_slot.as_constant() * stackElementSize;
5890   } else {
5891     scale_reg    = arg_slot.as_register();
5892     scale_factor = Address::times(stackElementSize);
5893   }
5894   offset += wordSize;           // return PC is on stack
5895   return Address(rsp, scale_reg, scale_factor, offset);
5896 }
5897 
5898 
5899 void MacroAssembler::verify_oop_addr(Address addr, const char* s) {
5900   if (!VerifyOops) return;
5901 
5902   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
5903   // Pass register number to verify_oop_subroutine
5904   const char* b = NULL;
5905   {
5906     ResourceMark rm;
5907     stringStream ss;
5908     ss.print("verify_oop_addr: %s", s);
5909     b = code_string(ss.as_string());
5910   }
5911 #ifdef _LP64
5912   push(rscratch1);                    // save r10, trashed by movptr()
5913 #endif
5914   push(rax);                          // save rax,
5915   // addr may contain rsp so we will have to adjust it based on the push
5916   // we just did (and on 64 bit we do two pushes)
5917   // NOTE: 64bit seemed to have had a bug in that it did movq(addr, rax); which
5918   // stores rax into addr which is backwards of what was intended.
5919   if (addr.uses(rsp)) {
5920     lea(rax, addr);
5921     pushptr(Address(rax, LP64_ONLY(2 *) BytesPerWord));
5922   } else {
5923     pushptr(addr);
5924   }
5925 
5926   ExternalAddress buffer((address) b);
5927   // pass msg argument
5928   // avoid using pushptr, as it modifies scratch registers
5929   // and our contract is not to modify anything
5930   movptr(rax, buffer.addr());
5931   push(rax);
5932 
5933   // call indirectly to solve generation ordering problem
5934   movptr(rax, ExternalAddress(StubRoutines::verify_oop_subroutine_entry_address()));
5935   call(rax);
5936   // Caller pops the arguments (addr, message) and restores rax, r10.
5937 }
5938 
5939 void MacroAssembler::verify_tlab() {
5940 #ifdef ASSERT
5941   if (UseTLAB && VerifyOops) {
5942     Label next, ok;
5943     Register t1 = rsi;
5944     Register thread_reg = NOT_LP64(rbx) LP64_ONLY(r15_thread);
5945 
5946     push(t1);
5947     NOT_LP64(push(thread_reg));
5948     NOT_LP64(get_thread(thread_reg));
5949 
5950     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5951     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_start_offset())));
5952     jcc(Assembler::aboveEqual, next);
5953     STOP("assert(top >= start)");
5954     should_not_reach_here();
5955 
5956     bind(next);
5957     movptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_end_offset())));
5958     cmpptr(t1, Address(thread_reg, in_bytes(JavaThread::tlab_top_offset())));
5959     jcc(Assembler::aboveEqual, ok);
5960     STOP("assert(top <= end)");
5961     should_not_reach_here();
5962 
5963     bind(ok);
5964     NOT_LP64(pop(thread_reg));
5965     pop(t1);
5966   }
5967 #endif
5968 }
5969 
5970 class ControlWord {
5971  public:
5972   int32_t _value;
5973 
5974   int  rounding_control() const        { return  (_value >> 10) & 3      ; }
5975   int  precision_control() const       { return  (_value >>  8) & 3      ; }
5976   bool precision() const               { return ((_value >>  5) & 1) != 0; }
5977   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
5978   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
5979   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
5980   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
5981   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
5982 
5983   void print() const {
5984     // rounding control
5985     const char* rc;
5986     switch (rounding_control()) {
5987       case 0: rc = "round near"; break;
5988       case 1: rc = "round down"; break;
5989       case 2: rc = "round up  "; break;
5990       case 3: rc = "chop      "; break;
5991     };
5992     // precision control
5993     const char* pc;
5994     switch (precision_control()) {
5995       case 0: pc = "24 bits "; break;
5996       case 1: pc = "reserved"; break;
5997       case 2: pc = "53 bits "; break;
5998       case 3: pc = "64 bits "; break;
5999     };
6000     // flags
6001     char f[9];
6002     f[0] = ' ';
6003     f[1] = ' ';
6004     f[2] = (precision   ()) ? 'P' : 'p';
6005     f[3] = (underflow   ()) ? 'U' : 'u';
6006     f[4] = (overflow    ()) ? 'O' : 'o';
6007     f[5] = (zero_divide ()) ? 'Z' : 'z';
6008     f[6] = (denormalized()) ? 'D' : 'd';
6009     f[7] = (invalid     ()) ? 'I' : 'i';
6010     f[8] = '\x0';
6011     // output
6012     printf("%04x  masks = %s, %s, %s", _value & 0xFFFF, f, rc, pc);
6013   }
6014 
6015 };
6016 
6017 class StatusWord {
6018  public:
6019   int32_t _value;
6020 
6021   bool busy() const                    { return ((_value >> 15) & 1) != 0; }
6022   bool C3() const                      { return ((_value >> 14) & 1) != 0; }
6023   bool C2() const                      { return ((_value >> 10) & 1) != 0; }
6024   bool C1() const                      { return ((_value >>  9) & 1) != 0; }
6025   bool C0() const                      { return ((_value >>  8) & 1) != 0; }
6026   int  top() const                     { return  (_value >> 11) & 7      ; }
6027   bool error_status() const            { return ((_value >>  7) & 1) != 0; }
6028   bool stack_fault() const             { return ((_value >>  6) & 1) != 0; }
6029   bool precision() const               { return ((_value >>  5) & 1) != 0; }
6030   bool underflow() const               { return ((_value >>  4) & 1) != 0; }
6031   bool overflow() const                { return ((_value >>  3) & 1) != 0; }
6032   bool zero_divide() const             { return ((_value >>  2) & 1) != 0; }
6033   bool denormalized() const            { return ((_value >>  1) & 1) != 0; }
6034   bool invalid() const                 { return ((_value >>  0) & 1) != 0; }
6035 
6036   void print() const {
6037     // condition codes
6038     char c[5];
6039     c[0] = (C3()) ? '3' : '-';
6040     c[1] = (C2()) ? '2' : '-';
6041     c[2] = (C1()) ? '1' : '-';
6042     c[3] = (C0()) ? '0' : '-';
6043     c[4] = '\x0';
6044     // flags
6045     char f[9];
6046     f[0] = (error_status()) ? 'E' : '-';
6047     f[1] = (stack_fault ()) ? 'S' : '-';
6048     f[2] = (precision   ()) ? 'P' : '-';
6049     f[3] = (underflow   ()) ? 'U' : '-';
6050     f[4] = (overflow    ()) ? 'O' : '-';
6051     f[5] = (zero_divide ()) ? 'Z' : '-';
6052     f[6] = (denormalized()) ? 'D' : '-';
6053     f[7] = (invalid     ()) ? 'I' : '-';
6054     f[8] = '\x0';
6055     // output
6056     printf("%04x  flags = %s, cc =  %s, top = %d", _value & 0xFFFF, f, c, top());
6057   }
6058 
6059 };
6060 
6061 class TagWord {
6062  public:
6063   int32_t _value;
6064 
6065   int tag_at(int i) const              { return (_value >> (i*2)) & 3; }
6066 
6067   void print() const {
6068     printf("%04x", _value & 0xFFFF);
6069   }
6070 
6071 };
6072 
6073 class FPU_Register {
6074  public:
6075   int32_t _m0;
6076   int32_t _m1;
6077   int16_t _ex;
6078 
6079   bool is_indefinite() const           {
6080     return _ex == -1 && _m1 == (int32_t)0xC0000000 && _m0 == 0;
6081   }
6082 
6083   void print() const {
6084     char  sign = (_ex < 0) ? '-' : '+';
6085     const char* kind = (_ex == 0x7FFF || _ex == (int16_t)-1) ? "NaN" : "   ";
6086     printf("%c%04hx.%08x%08x  %s", sign, _ex, _m1, _m0, kind);
6087   };
6088 
6089 };
6090 
6091 class FPU_State {
6092  public:
6093   enum {
6094     register_size       = 10,
6095     number_of_registers =  8,
6096     register_mask       =  7
6097   };
6098 
6099   ControlWord  _control_word;
6100   StatusWord   _status_word;
6101   TagWord      _tag_word;
6102   int32_t      _error_offset;
6103   int32_t      _error_selector;
6104   int32_t      _data_offset;
6105   int32_t      _data_selector;
6106   int8_t       _register[register_size * number_of_registers];
6107 
6108   int tag_for_st(int i) const          { return _tag_word.tag_at((_status_word.top() + i) & register_mask); }
6109   FPU_Register* st(int i) const        { return (FPU_Register*)&_register[register_size * i]; }
6110 
6111   const char* tag_as_string(int tag) const {
6112     switch (tag) {
6113       case 0: return "valid";
6114       case 1: return "zero";
6115       case 2: return "special";
6116       case 3: return "empty";
6117     }
6118     ShouldNotReachHere();
6119     return NULL;
6120   }
6121 
6122   void print() const {
6123     // print computation registers
6124     { int t = _status_word.top();
6125       for (int i = 0; i < number_of_registers; i++) {
6126         int j = (i - t) & register_mask;
6127         printf("%c r%d = ST%d = ", (j == 0 ? '*' : ' '), i, j);
6128         st(j)->print();
6129         printf(" %s\n", tag_as_string(_tag_word.tag_at(i)));
6130       }
6131     }
6132     printf("\n");
6133     // print control registers
6134     printf("ctrl = "); _control_word.print(); printf("\n");
6135     printf("stat = "); _status_word .print(); printf("\n");
6136     printf("tags = "); _tag_word    .print(); printf("\n");
6137   }
6138 
6139 };
6140 
6141 class Flag_Register {
6142  public:
6143   int32_t _value;
6144 
6145   bool overflow() const                { return ((_value >> 11) & 1) != 0; }
6146   bool direction() const               { return ((_value >> 10) & 1) != 0; }
6147   bool sign() const                    { return ((_value >>  7) & 1) != 0; }
6148   bool zero() const                    { return ((_value >>  6) & 1) != 0; }
6149   bool auxiliary_carry() const         { return ((_value >>  4) & 1) != 0; }
6150   bool parity() const                  { return ((_value >>  2) & 1) != 0; }
6151   bool carry() const                   { return ((_value >>  0) & 1) != 0; }
6152 
6153   void print() const {
6154     // flags
6155     char f[8];
6156     f[0] = (overflow       ()) ? 'O' : '-';
6157     f[1] = (direction      ()) ? 'D' : '-';
6158     f[2] = (sign           ()) ? 'S' : '-';
6159     f[3] = (zero           ()) ? 'Z' : '-';
6160     f[4] = (auxiliary_carry()) ? 'A' : '-';
6161     f[5] = (parity         ()) ? 'P' : '-';
6162     f[6] = (carry          ()) ? 'C' : '-';
6163     f[7] = '\x0';
6164     // output
6165     printf("%08x  flags = %s", _value, f);
6166   }
6167 
6168 };
6169 
6170 class IU_Register {
6171  public:
6172   int32_t _value;
6173 
6174   void print() const {
6175     printf("%08x  %11d", _value, _value);
6176   }
6177 
6178 };
6179 
6180 class IU_State {
6181  public:
6182   Flag_Register _eflags;
6183   IU_Register   _rdi;
6184   IU_Register   _rsi;
6185   IU_Register   _rbp;
6186   IU_Register   _rsp;
6187   IU_Register   _rbx;
6188   IU_Register   _rdx;
6189   IU_Register   _rcx;
6190   IU_Register   _rax;
6191 
6192   void print() const {
6193     // computation registers
6194     printf("rax,  = "); _rax.print(); printf("\n");
6195     printf("rbx,  = "); _rbx.print(); printf("\n");
6196     printf("rcx  = "); _rcx.print(); printf("\n");
6197     printf("rdx  = "); _rdx.print(); printf("\n");
6198     printf("rdi  = "); _rdi.print(); printf("\n");
6199     printf("rsi  = "); _rsi.print(); printf("\n");
6200     printf("rbp,  = "); _rbp.print(); printf("\n");
6201     printf("rsp  = "); _rsp.print(); printf("\n");
6202     printf("\n");
6203     // control registers
6204     printf("flgs = "); _eflags.print(); printf("\n");
6205   }
6206 };
6207 
6208 
6209 class CPU_State {
6210  public:
6211   FPU_State _fpu_state;
6212   IU_State  _iu_state;
6213 
6214   void print() const {
6215     printf("--------------------------------------------------\n");
6216     _iu_state .print();
6217     printf("\n");
6218     _fpu_state.print();
6219     printf("--------------------------------------------------\n");
6220   }
6221 
6222 };
6223 
6224 
6225 static void _print_CPU_state(CPU_State* state) {
6226   state->print();
6227 };
6228 
6229 
6230 void MacroAssembler::print_CPU_state() {
6231   push_CPU_state();
6232   push(rsp);                // pass CPU state
6233   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _print_CPU_state)));
6234   addptr(rsp, wordSize);       // discard argument
6235   pop_CPU_state();
6236 }
6237 
6238 
6239 static bool _verify_FPU(int stack_depth, char* s, CPU_State* state) {
6240   static int counter = 0;
6241   FPU_State* fs = &state->_fpu_state;
6242   counter++;
6243   // For leaf calls, only verify that the top few elements remain empty.
6244   // We only need 1 empty at the top for C2 code.
6245   if( stack_depth < 0 ) {
6246     if( fs->tag_for_st(7) != 3 ) {
6247       printf("FPR7 not empty\n");
6248       state->print();
6249       assert(false, "error");
6250       return false;
6251     }
6252     return true;                // All other stack states do not matter
6253   }
6254 
6255   assert((fs->_control_word._value & 0xffff) == StubRoutines::_fpu_cntrl_wrd_std,
6256          "bad FPU control word");
6257 
6258   // compute stack depth
6259   int i = 0;
6260   while (i < FPU_State::number_of_registers && fs->tag_for_st(i)  < 3) i++;
6261   int d = i;
6262   while (i < FPU_State::number_of_registers && fs->tag_for_st(i) == 3) i++;
6263   // verify findings
6264   if (i != FPU_State::number_of_registers) {
6265     // stack not contiguous
6266     printf("%s: stack not contiguous at ST%d\n", s, i);
6267     state->print();
6268     assert(false, "error");
6269     return false;
6270   }
6271   // check if computed stack depth corresponds to expected stack depth
6272   if (stack_depth < 0) {
6273     // expected stack depth is -stack_depth or less
6274     if (d > -stack_depth) {
6275       // too many elements on the stack
6276       printf("%s: <= %d stack elements expected but found %d\n", s, -stack_depth, d);
6277       state->print();
6278       assert(false, "error");
6279       return false;
6280     }
6281   } else {
6282     // expected stack depth is stack_depth
6283     if (d != stack_depth) {
6284       // wrong stack depth
6285       printf("%s: %d stack elements expected but found %d\n", s, stack_depth, d);
6286       state->print();
6287       assert(false, "error");
6288       return false;
6289     }
6290   }
6291   // everything is cool
6292   return true;
6293 }
6294 
6295 
6296 void MacroAssembler::verify_FPU(int stack_depth, const char* s) {
6297   if (!VerifyFPU) return;
6298   push_CPU_state();
6299   push(rsp);                // pass CPU state
6300   ExternalAddress msg((address) s);
6301   // pass message string s
6302   pushptr(msg.addr());
6303   push(stack_depth);        // pass stack depth
6304   call(RuntimeAddress(CAST_FROM_FN_PTR(address, _verify_FPU)));
6305   addptr(rsp, 3 * wordSize);   // discard arguments
6306   // check for error
6307   { Label L;
6308     testl(rax, rax);
6309     jcc(Assembler::notZero, L);
6310     int3();                  // break if error condition
6311     bind(L);
6312   }
6313   pop_CPU_state();
6314 }
6315 
6316 void MacroAssembler::restore_cpu_control_state_after_jni() {
6317   // Either restore the MXCSR register after returning from the JNI Call
6318   // or verify that it wasn't changed (with -Xcheck:jni flag).
6319   if (VM_Version::supports_sse()) {
6320     if (RestoreMXCSROnJNICalls) {
6321       ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
6322     } else if (CheckJNICalls) {
6323       call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
6324     }
6325   }
6326   // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
6327   vzeroupper();
6328   // Reset k1 to 0xffff.
6329   if (VM_Version::supports_evex()) {
6330     push(rcx);
6331     movl(rcx, 0xffff);
6332     kmovwl(k1, rcx);
6333     pop(rcx);
6334   }
6335 
6336 #ifndef _LP64
6337   // Either restore the x87 floating pointer control word after returning
6338   // from the JNI call or verify that it wasn't changed.
6339   if (CheckJNICalls) {
6340     call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
6341   }
6342 #endif // _LP64
6343 }
6344 
6345 // ((OopHandle)result).resolve();
6346 void MacroAssembler::resolve_oop_handle(Register result, Register tmp) {
6347   assert_different_registers(result, tmp);
6348 
6349   // Only 64 bit platforms support GCs that require a tmp register
6350   // Only IN_HEAP loads require a thread_tmp register
6351   // OopHandle::resolve is an indirection like jobject.
6352   access_load_at(T_OBJECT, IN_CONCURRENT_ROOT,
6353                  result, Address(result, 0), tmp, /*tmp_thread*/noreg);
6354 }
6355 
6356 void MacroAssembler::load_mirror(Register mirror, Register method, Register tmp) {
6357   // get mirror
6358   const int mirror_offset = in_bytes(Klass::java_mirror_offset());
6359   movptr(mirror, Address(method, Method::const_offset()));
6360   movptr(mirror, Address(mirror, ConstMethod::constants_offset()));
6361   movptr(mirror, Address(mirror, ConstantPool::pool_holder_offset_in_bytes()));
6362   movptr(mirror, Address(mirror, mirror_offset));
6363   resolve_oop_handle(mirror, tmp);
6364 }
6365 
6366 void MacroAssembler::load_klass(Register dst, Register src) {
6367 #ifdef _LP64
6368   if (UseCompressedClassPointers) {
6369     movl(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6370     decode_klass_not_null(dst);
6371   } else
6372 #endif
6373     movptr(dst, Address(src, oopDesc::klass_offset_in_bytes()));
6374 }
6375 
6376 void MacroAssembler::load_prototype_header(Register dst, Register src) {
6377   load_klass(dst, src);
6378   movptr(dst, Address(dst, Klass::prototype_header_offset()));
6379 }
6380 
6381 void MacroAssembler::store_klass(Register dst, Register src) {
6382 #ifdef _LP64
6383   if (UseCompressedClassPointers) {
6384     encode_klass_not_null(src);
6385     movl(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6386   } else
6387 #endif
6388     movptr(Address(dst, oopDesc::klass_offset_in_bytes()), src);
6389 }
6390 
6391 void MacroAssembler::resolve_for_read(DecoratorSet decorators, Register obj) {
6392   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6393   bs->resolve_for_read(this, decorators, obj);
6394 }
6395 
6396 void MacroAssembler::resolve_for_write(DecoratorSet decorators, Register obj) {
6397   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6398   bs->resolve_for_write(this, decorators, obj);
6399 }
6400 
6401 void MacroAssembler::access_load_at(BasicType type, DecoratorSet decorators, Register dst, Address src,
6402                                     Register tmp1, Register thread_tmp) {
6403   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6404   decorators = AccessInternal::decorator_fixup(decorators);
6405   bool as_raw = (decorators & AS_RAW) != 0;
6406   if (as_raw) {
6407     bs->BarrierSetAssembler::load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6408   } else {
6409     bs->load_at(this, decorators, type, dst, src, tmp1, thread_tmp);
6410   }
6411 }
6412 
6413 void MacroAssembler::access_store_at(BasicType type, DecoratorSet decorators, Address dst, Register src,
6414                                      Register tmp1, Register tmp2) {
6415   BarrierSetAssembler* bs = BarrierSet::barrier_set()->barrier_set_assembler();
6416   decorators = AccessInternal::decorator_fixup(decorators);
6417   bool as_raw = (decorators & AS_RAW) != 0;
6418   if (as_raw) {
6419     bs->BarrierSetAssembler::store_at(this, decorators, type, dst, src, tmp1, tmp2);
6420   } else {
6421     bs->store_at(this, decorators, type, dst, src, tmp1, tmp2);
6422   }
6423 }
6424 
6425 void MacroAssembler::load_heap_oop(Register dst, Address src, Register tmp1,
6426                                    Register thread_tmp, DecoratorSet decorators) {
6427   access_load_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, thread_tmp);
6428 }
6429 
6430 // Doesn't do verfication, generates fixed size code
6431 void MacroAssembler::load_heap_oop_not_null(Register dst, Address src, Register tmp1,
6432                                             Register thread_tmp, DecoratorSet decorators) {
6433   access_load_at(T_OBJECT, IN_HEAP | OOP_NOT_NULL | decorators, dst, src, tmp1, thread_tmp);
6434 }
6435 
6436 void MacroAssembler::store_heap_oop(Address dst, Register src, Register tmp1,
6437                                     Register tmp2, DecoratorSet decorators) {
6438   access_store_at(T_OBJECT, IN_HEAP | decorators, dst, src, tmp1, tmp2);
6439 }
6440 
6441 // Used for storing NULLs.
6442 void MacroAssembler::store_heap_oop_null(Address dst) {
6443   access_store_at(T_OBJECT, IN_HEAP, dst, noreg, noreg, noreg);
6444 }
6445 
6446 #ifdef _LP64
6447 void MacroAssembler::store_klass_gap(Register dst, Register src) {
6448   if (UseCompressedClassPointers) {
6449     // Store to klass gap in destination
6450     movl(Address(dst, oopDesc::klass_gap_offset_in_bytes()), src);
6451   }
6452 }
6453 
6454 #ifdef ASSERT
6455 void MacroAssembler::verify_heapbase(const char* msg) {
6456   assert (UseCompressedOops, "should be compressed");
6457   assert (Universe::heap() != NULL, "java heap should be initialized");
6458   if (CheckCompressedOops) {
6459     Label ok;
6460     push(rscratch1); // cmpptr trashes rscratch1
6461     cmpptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6462     jcc(Assembler::equal, ok);
6463     STOP(msg);
6464     bind(ok);
6465     pop(rscratch1);
6466   }
6467 }
6468 #endif
6469 
6470 // Algorithm must match oop.inline.hpp encode_heap_oop.
6471 void MacroAssembler::encode_heap_oop(Register r) {
6472 #ifdef ASSERT
6473   verify_heapbase("MacroAssembler::encode_heap_oop: heap base corrupted?");
6474 #endif
6475   verify_oop(r, "broken oop in encode_heap_oop");
6476   if (Universe::narrow_oop_base() == NULL) {
6477     if (Universe::narrow_oop_shift() != 0) {
6478       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6479       shrq(r, LogMinObjAlignmentInBytes);
6480     }
6481     return;
6482   }
6483   testq(r, r);
6484   cmovq(Assembler::equal, r, r12_heapbase);
6485   subq(r, r12_heapbase);
6486   shrq(r, LogMinObjAlignmentInBytes);
6487 }
6488 
6489 void MacroAssembler::encode_heap_oop_not_null(Register r) {
6490 #ifdef ASSERT
6491   verify_heapbase("MacroAssembler::encode_heap_oop_not_null: heap base corrupted?");
6492   if (CheckCompressedOops) {
6493     Label ok;
6494     testq(r, r);
6495     jcc(Assembler::notEqual, ok);
6496     STOP("null oop passed to encode_heap_oop_not_null");
6497     bind(ok);
6498   }
6499 #endif
6500   verify_oop(r, "broken oop in encode_heap_oop_not_null");
6501   if (Universe::narrow_oop_base() != NULL) {
6502     subq(r, r12_heapbase);
6503   }
6504   if (Universe::narrow_oop_shift() != 0) {
6505     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6506     shrq(r, LogMinObjAlignmentInBytes);
6507   }
6508 }
6509 
6510 void MacroAssembler::encode_heap_oop_not_null(Register dst, Register src) {
6511 #ifdef ASSERT
6512   verify_heapbase("MacroAssembler::encode_heap_oop_not_null2: heap base corrupted?");
6513   if (CheckCompressedOops) {
6514     Label ok;
6515     testq(src, src);
6516     jcc(Assembler::notEqual, ok);
6517     STOP("null oop passed to encode_heap_oop_not_null2");
6518     bind(ok);
6519   }
6520 #endif
6521   verify_oop(src, "broken oop in encode_heap_oop_not_null2");
6522   if (dst != src) {
6523     movq(dst, src);
6524   }
6525   if (Universe::narrow_oop_base() != NULL) {
6526     subq(dst, r12_heapbase);
6527   }
6528   if (Universe::narrow_oop_shift() != 0) {
6529     assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6530     shrq(dst, LogMinObjAlignmentInBytes);
6531   }
6532 }
6533 
6534 void  MacroAssembler::decode_heap_oop(Register r) {
6535 #ifdef ASSERT
6536   verify_heapbase("MacroAssembler::decode_heap_oop: heap base corrupted?");
6537 #endif
6538   if (Universe::narrow_oop_base() == NULL) {
6539     if (Universe::narrow_oop_shift() != 0) {
6540       assert (LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6541       shlq(r, LogMinObjAlignmentInBytes);
6542     }
6543   } else {
6544     Label done;
6545     shlq(r, LogMinObjAlignmentInBytes);
6546     jccb(Assembler::equal, done);
6547     addq(r, r12_heapbase);
6548     bind(done);
6549   }
6550   verify_oop(r, "broken oop in decode_heap_oop");
6551 }
6552 
6553 void  MacroAssembler::decode_heap_oop_not_null(Register r) {
6554   // Note: it will change flags
6555   assert (UseCompressedOops, "should only be used for compressed headers");
6556   assert (Universe::heap() != NULL, "java heap should be initialized");
6557   // Cannot assert, unverified entry point counts instructions (see .ad file)
6558   // vtableStubs also counts instructions in pd_code_size_limit.
6559   // Also do not verify_oop as this is called by verify_oop.
6560   if (Universe::narrow_oop_shift() != 0) {
6561     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6562     shlq(r, LogMinObjAlignmentInBytes);
6563     if (Universe::narrow_oop_base() != NULL) {
6564       addq(r, r12_heapbase);
6565     }
6566   } else {
6567     assert (Universe::narrow_oop_base() == NULL, "sanity");
6568   }
6569 }
6570 
6571 void  MacroAssembler::decode_heap_oop_not_null(Register dst, Register src) {
6572   // Note: it will change flags
6573   assert (UseCompressedOops, "should only be used for compressed headers");
6574   assert (Universe::heap() != NULL, "java heap should be initialized");
6575   // Cannot assert, unverified entry point counts instructions (see .ad file)
6576   // vtableStubs also counts instructions in pd_code_size_limit.
6577   // Also do not verify_oop as this is called by verify_oop.
6578   if (Universe::narrow_oop_shift() != 0) {
6579     assert(LogMinObjAlignmentInBytes == Universe::narrow_oop_shift(), "decode alg wrong");
6580     if (LogMinObjAlignmentInBytes == Address::times_8) {
6581       leaq(dst, Address(r12_heapbase, src, Address::times_8, 0));
6582     } else {
6583       if (dst != src) {
6584         movq(dst, src);
6585       }
6586       shlq(dst, LogMinObjAlignmentInBytes);
6587       if (Universe::narrow_oop_base() != NULL) {
6588         addq(dst, r12_heapbase);
6589       }
6590     }
6591   } else {
6592     assert (Universe::narrow_oop_base() == NULL, "sanity");
6593     if (dst != src) {
6594       movq(dst, src);
6595     }
6596   }
6597 }
6598 
6599 void MacroAssembler::encode_klass_not_null(Register r) {
6600   if (Universe::narrow_klass_base() != NULL) {
6601     // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6602     assert(r != r12_heapbase, "Encoding a klass in r12");
6603     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6604     subq(r, r12_heapbase);
6605   }
6606   if (Universe::narrow_klass_shift() != 0) {
6607     assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6608     shrq(r, LogKlassAlignmentInBytes);
6609   }
6610   if (Universe::narrow_klass_base() != NULL) {
6611     reinit_heapbase();
6612   }
6613 }
6614 
6615 void MacroAssembler::encode_klass_not_null(Register dst, Register src) {
6616   if (dst == src) {
6617     encode_klass_not_null(src);
6618   } else {
6619     if (Universe::narrow_klass_base() != NULL) {
6620       mov64(dst, (int64_t)Universe::narrow_klass_base());
6621       negq(dst);
6622       addq(dst, src);
6623     } else {
6624       movptr(dst, src);
6625     }
6626     if (Universe::narrow_klass_shift() != 0) {
6627       assert (LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6628       shrq(dst, LogKlassAlignmentInBytes);
6629     }
6630   }
6631 }
6632 
6633 // Function instr_size_for_decode_klass_not_null() counts the instructions
6634 // generated by decode_klass_not_null(register r) and reinit_heapbase(),
6635 // when (Universe::heap() != NULL).  Hence, if the instructions they
6636 // generate change, then this method needs to be updated.
6637 int MacroAssembler::instr_size_for_decode_klass_not_null() {
6638   assert (UseCompressedClassPointers, "only for compressed klass ptrs");
6639   if (Universe::narrow_klass_base() != NULL) {
6640     // mov64 + addq + shlq? + mov64  (for reinit_heapbase()).
6641     return (Universe::narrow_klass_shift() == 0 ? 20 : 24);
6642   } else {
6643     // longest load decode klass function, mov64, leaq
6644     return 16;
6645   }
6646 }
6647 
6648 // !!! If the instructions that get generated here change then function
6649 // instr_size_for_decode_klass_not_null() needs to get updated.
6650 void  MacroAssembler::decode_klass_not_null(Register r) {
6651   // Note: it will change flags
6652   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6653   assert(r != r12_heapbase, "Decoding a klass in r12");
6654   // Cannot assert, unverified entry point counts instructions (see .ad file)
6655   // vtableStubs also counts instructions in pd_code_size_limit.
6656   // Also do not verify_oop as this is called by verify_oop.
6657   if (Universe::narrow_klass_shift() != 0) {
6658     assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6659     shlq(r, LogKlassAlignmentInBytes);
6660   }
6661   // Use r12 as a scratch register in which to temporarily load the narrow_klass_base.
6662   if (Universe::narrow_klass_base() != NULL) {
6663     mov64(r12_heapbase, (int64_t)Universe::narrow_klass_base());
6664     addq(r, r12_heapbase);
6665     reinit_heapbase();
6666   }
6667 }
6668 
6669 void  MacroAssembler::decode_klass_not_null(Register dst, Register src) {
6670   // Note: it will change flags
6671   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6672   if (dst == src) {
6673     decode_klass_not_null(dst);
6674   } else {
6675     // Cannot assert, unverified entry point counts instructions (see .ad file)
6676     // vtableStubs also counts instructions in pd_code_size_limit.
6677     // Also do not verify_oop as this is called by verify_oop.
6678     mov64(dst, (int64_t)Universe::narrow_klass_base());
6679     if (Universe::narrow_klass_shift() != 0) {
6680       assert(LogKlassAlignmentInBytes == Universe::narrow_klass_shift(), "decode alg wrong");
6681       assert(LogKlassAlignmentInBytes == Address::times_8, "klass not aligned on 64bits?");
6682       leaq(dst, Address(dst, src, Address::times_8, 0));
6683     } else {
6684       addq(dst, src);
6685     }
6686   }
6687 }
6688 
6689 void  MacroAssembler::set_narrow_oop(Register dst, jobject obj) {
6690   assert (UseCompressedOops, "should only be used for compressed headers");
6691   assert (Universe::heap() != NULL, "java heap should be initialized");
6692   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6693   int oop_index = oop_recorder()->find_index(obj);
6694   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6695   mov_narrow_oop(dst, oop_index, rspec);
6696 }
6697 
6698 void  MacroAssembler::set_narrow_oop(Address dst, jobject obj) {
6699   assert (UseCompressedOops, "should only be used for compressed headers");
6700   assert (Universe::heap() != NULL, "java heap should be initialized");
6701   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6702   int oop_index = oop_recorder()->find_index(obj);
6703   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6704   mov_narrow_oop(dst, oop_index, rspec);
6705 }
6706 
6707 void  MacroAssembler::set_narrow_klass(Register dst, Klass* k) {
6708   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6709   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6710   int klass_index = oop_recorder()->find_index(k);
6711   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6712   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6713 }
6714 
6715 void  MacroAssembler::set_narrow_klass(Address dst, Klass* k) {
6716   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6717   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6718   int klass_index = oop_recorder()->find_index(k);
6719   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6720   mov_narrow_oop(dst, Klass::encode_klass(k), rspec);
6721 }
6722 
6723 void  MacroAssembler::cmp_narrow_oop(Register dst, jobject obj) {
6724   assert (UseCompressedOops, "should only be used for compressed headers");
6725   assert (Universe::heap() != NULL, "java heap should be initialized");
6726   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6727   int oop_index = oop_recorder()->find_index(obj);
6728   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6729   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6730 }
6731 
6732 void  MacroAssembler::cmp_narrow_oop(Address dst, jobject obj) {
6733   assert (UseCompressedOops, "should only be used for compressed headers");
6734   assert (Universe::heap() != NULL, "java heap should be initialized");
6735   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6736   int oop_index = oop_recorder()->find_index(obj);
6737   RelocationHolder rspec = oop_Relocation::spec(oop_index);
6738   Assembler::cmp_narrow_oop(dst, oop_index, rspec);
6739 }
6740 
6741 void  MacroAssembler::cmp_narrow_klass(Register dst, Klass* k) {
6742   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6743   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6744   int klass_index = oop_recorder()->find_index(k);
6745   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6746   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6747 }
6748 
6749 void  MacroAssembler::cmp_narrow_klass(Address dst, Klass* k) {
6750   assert (UseCompressedClassPointers, "should only be used for compressed headers");
6751   assert (oop_recorder() != NULL, "this assembler needs an OopRecorder");
6752   int klass_index = oop_recorder()->find_index(k);
6753   RelocationHolder rspec = metadata_Relocation::spec(klass_index);
6754   Assembler::cmp_narrow_oop(dst, Klass::encode_klass(k), rspec);
6755 }
6756 
6757 void MacroAssembler::reinit_heapbase() {
6758   if (UseCompressedOops || UseCompressedClassPointers) {
6759     if (Universe::heap() != NULL) {
6760       if (Universe::narrow_oop_base() == NULL) {
6761         MacroAssembler::xorptr(r12_heapbase, r12_heapbase);
6762       } else {
6763         mov64(r12_heapbase, (int64_t)Universe::narrow_ptrs_base());
6764       }
6765     } else {
6766       movptr(r12_heapbase, ExternalAddress((address)Universe::narrow_ptrs_base_addr()));
6767     }
6768   }
6769 }
6770 
6771 #endif // _LP64
6772 
6773 // C2 compiled method's prolog code.
6774 void MacroAssembler::verified_entry(int framesize, int stack_bang_size, bool fp_mode_24b) {
6775 
6776   // WARNING: Initial instruction MUST be 5 bytes or longer so that
6777   // NativeJump::patch_verified_entry will be able to patch out the entry
6778   // code safely. The push to verify stack depth is ok at 5 bytes,
6779   // the frame allocation can be either 3 or 6 bytes. So if we don't do
6780   // stack bang then we must use the 6 byte frame allocation even if
6781   // we have no frame. :-(
6782   assert(stack_bang_size >= framesize || stack_bang_size <= 0, "stack bang size incorrect");
6783 
6784   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
6785   // Remove word for return addr
6786   framesize -= wordSize;
6787   stack_bang_size -= wordSize;
6788 
6789   // Calls to C2R adapters often do not accept exceptional returns.
6790   // We require that their callers must bang for them.  But be careful, because
6791   // some VM calls (such as call site linkage) can use several kilobytes of
6792   // stack.  But the stack safety zone should account for that.
6793   // See bugs 4446381, 4468289, 4497237.
6794   if (stack_bang_size > 0) {
6795     generate_stack_overflow_check(stack_bang_size);
6796 
6797     // We always push rbp, so that on return to interpreter rbp, will be
6798     // restored correctly and we can correct the stack.
6799     push(rbp);
6800     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6801     if (PreserveFramePointer) {
6802       mov(rbp, rsp);
6803     }
6804     // Remove word for ebp
6805     framesize -= wordSize;
6806 
6807     // Create frame
6808     if (framesize) {
6809       subptr(rsp, framesize);
6810     }
6811   } else {
6812     // Create frame (force generation of a 4 byte immediate value)
6813     subptr_imm32(rsp, framesize);
6814 
6815     // Save RBP register now.
6816     framesize -= wordSize;
6817     movptr(Address(rsp, framesize), rbp);
6818     // Save caller's stack pointer into RBP if the frame pointer is preserved.
6819     if (PreserveFramePointer) {
6820       movptr(rbp, rsp);
6821       if (framesize > 0) {
6822         addptr(rbp, framesize);
6823       }
6824     }
6825   }
6826 
6827   if (VerifyStackAtCalls) { // Majik cookie to verify stack depth
6828     framesize -= wordSize;
6829     movptr(Address(rsp, framesize), (int32_t)0xbadb100d);
6830   }
6831 
6832 #ifndef _LP64
6833   // If method sets FPU control word do it now
6834   if (fp_mode_24b) {
6835     fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
6836   }
6837   if (UseSSE >= 2 && VerifyFPU) {
6838     verify_FPU(0, "FPU stack must be clean on entry");
6839   }
6840 #endif
6841 
6842 #ifdef ASSERT
6843   if (VerifyStackAtCalls) {
6844     Label L;
6845     push(rax);
6846     mov(rax, rsp);
6847     andptr(rax, StackAlignmentInBytes-1);
6848     cmpptr(rax, StackAlignmentInBytes-wordSize);
6849     pop(rax);
6850     jcc(Assembler::equal, L);
6851     STOP("Stack is not properly aligned!");
6852     bind(L);
6853   }
6854 #endif
6855 
6856 }
6857 
6858 void MacroAssembler::clear_mem(Register base, Register cnt, Register tmp, bool is_large) {
6859   // cnt - number of qwords (8-byte words).
6860   // base - start address, qword aligned.
6861   // is_large - if optimizers know cnt is larger than InitArrayShortSize
6862   assert(base==rdi, "base register must be edi for rep stos");
6863   assert(tmp==rax,   "tmp register must be eax for rep stos");
6864   assert(cnt==rcx,   "cnt register must be ecx for rep stos");
6865   assert(InitArrayShortSize % BytesPerLong == 0,
6866     "InitArrayShortSize should be the multiple of BytesPerLong");
6867 
6868   Label DONE;
6869 
6870   xorptr(tmp, tmp);
6871 
6872   if (!is_large) {
6873     Label LOOP, LONG;
6874     cmpptr(cnt, InitArrayShortSize/BytesPerLong);
6875     jccb(Assembler::greater, LONG);
6876 
6877     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6878 
6879     decrement(cnt);
6880     jccb(Assembler::negative, DONE); // Zero length
6881 
6882     // Use individual pointer-sized stores for small counts:
6883     BIND(LOOP);
6884     movptr(Address(base, cnt, Address::times_ptr), tmp);
6885     decrement(cnt);
6886     jccb(Assembler::greaterEqual, LOOP);
6887     jmpb(DONE);
6888 
6889     BIND(LONG);
6890   }
6891 
6892   // Use longer rep-prefixed ops for non-small counts:
6893   if (UseFastStosb) {
6894     shlptr(cnt, 3); // convert to number of bytes
6895     rep_stosb();
6896   } else {
6897     NOT_LP64(shlptr(cnt, 1);) // convert to number of 32-bit words for 32-bit VM
6898     rep_stos();
6899   }
6900 
6901   BIND(DONE);
6902 }
6903 
6904 #ifdef COMPILER2
6905 
6906 // IndexOf for constant substrings with size >= 8 chars
6907 // which don't need to be loaded through stack.
6908 void MacroAssembler::string_indexofC8(Register str1, Register str2,
6909                                       Register cnt1, Register cnt2,
6910                                       int int_cnt2,  Register result,
6911                                       XMMRegister vec, Register tmp,
6912                                       int ae) {
6913   ShortBranchVerifier sbv(this);
6914   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
6915   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
6916 
6917   // This method uses the pcmpestri instruction with bound registers
6918   //   inputs:
6919   //     xmm - substring
6920   //     rax - substring length (elements count)
6921   //     mem - scanned string
6922   //     rdx - string length (elements count)
6923   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
6924   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
6925   //   outputs:
6926   //     rcx - matched index in string
6927   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
6928   int mode   = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
6929   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
6930   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
6931   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
6932 
6933   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR,
6934         RET_FOUND, RET_NOT_FOUND, EXIT, FOUND_SUBSTR,
6935         MATCH_SUBSTR_HEAD, RELOAD_STR, FOUND_CANDIDATE;
6936 
6937   // Note, inline_string_indexOf() generates checks:
6938   // if (substr.count > string.count) return -1;
6939   // if (substr.count == 0) return 0;
6940   assert(int_cnt2 >= stride, "this code is used only for cnt2 >= 8 chars");
6941 
6942   // Load substring.
6943   if (ae == StrIntrinsicNode::UL) {
6944     pmovzxbw(vec, Address(str2, 0));
6945   } else {
6946     movdqu(vec, Address(str2, 0));
6947   }
6948   movl(cnt2, int_cnt2);
6949   movptr(result, str1); // string addr
6950 
6951   if (int_cnt2 > stride) {
6952     jmpb(SCAN_TO_SUBSTR);
6953 
6954     // Reload substr for rescan, this code
6955     // is executed only for large substrings (> 8 chars)
6956     bind(RELOAD_SUBSTR);
6957     if (ae == StrIntrinsicNode::UL) {
6958       pmovzxbw(vec, Address(str2, 0));
6959     } else {
6960       movdqu(vec, Address(str2, 0));
6961     }
6962     negptr(cnt2); // Jumped here with negative cnt2, convert to positive
6963 
6964     bind(RELOAD_STR);
6965     // We came here after the beginning of the substring was
6966     // matched but the rest of it was not so we need to search
6967     // again. Start from the next element after the previous match.
6968 
6969     // cnt2 is number of substring reminding elements and
6970     // cnt1 is number of string reminding elements when cmp failed.
6971     // Restored cnt1 = cnt1 - cnt2 + int_cnt2
6972     subl(cnt1, cnt2);
6973     addl(cnt1, int_cnt2);
6974     movl(cnt2, int_cnt2); // Now restore cnt2
6975 
6976     decrementl(cnt1);     // Shift to next element
6977     cmpl(cnt1, cnt2);
6978     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6979 
6980     addptr(result, (1<<scale1));
6981 
6982   } // (int_cnt2 > 8)
6983 
6984   // Scan string for start of substr in 16-byte vectors
6985   bind(SCAN_TO_SUBSTR);
6986   pcmpestri(vec, Address(result, 0), mode);
6987   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
6988   subl(cnt1, stride);
6989   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
6990   cmpl(cnt1, cnt2);
6991   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
6992   addptr(result, 16);
6993   jmpb(SCAN_TO_SUBSTR);
6994 
6995   // Found a potential substr
6996   bind(FOUND_CANDIDATE);
6997   // Matched whole vector if first element matched (tmp(rcx) == 0).
6998   if (int_cnt2 == stride) {
6999     jccb(Assembler::overflow, RET_FOUND);    // OF == 1
7000   } else { // int_cnt2 > 8
7001     jccb(Assembler::overflow, FOUND_SUBSTR);
7002   }
7003   // After pcmpestri tmp(rcx) contains matched element index
7004   // Compute start addr of substr
7005   lea(result, Address(result, tmp, scale1));
7006 
7007   // Make sure string is still long enough
7008   subl(cnt1, tmp);
7009   cmpl(cnt1, cnt2);
7010   if (int_cnt2 == stride) {
7011     jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7012   } else { // int_cnt2 > 8
7013     jccb(Assembler::greaterEqual, MATCH_SUBSTR_HEAD);
7014   }
7015   // Left less then substring.
7016 
7017   bind(RET_NOT_FOUND);
7018   movl(result, -1);
7019   jmp(EXIT);
7020 
7021   if (int_cnt2 > stride) {
7022     // This code is optimized for the case when whole substring
7023     // is matched if its head is matched.
7024     bind(MATCH_SUBSTR_HEAD);
7025     pcmpestri(vec, Address(result, 0), mode);
7026     // Reload only string if does not match
7027     jcc(Assembler::noOverflow, RELOAD_STR); // OF == 0
7028 
7029     Label CONT_SCAN_SUBSTR;
7030     // Compare the rest of substring (> 8 chars).
7031     bind(FOUND_SUBSTR);
7032     // First 8 chars are already matched.
7033     negptr(cnt2);
7034     addptr(cnt2, stride);
7035 
7036     bind(SCAN_SUBSTR);
7037     subl(cnt1, stride);
7038     cmpl(cnt2, -stride); // Do not read beyond substring
7039     jccb(Assembler::lessEqual, CONT_SCAN_SUBSTR);
7040     // Back-up strings to avoid reading beyond substring:
7041     // cnt1 = cnt1 - cnt2 + 8
7042     addl(cnt1, cnt2); // cnt2 is negative
7043     addl(cnt1, stride);
7044     movl(cnt2, stride); negptr(cnt2);
7045     bind(CONT_SCAN_SUBSTR);
7046     if (int_cnt2 < (int)G) {
7047       int tail_off1 = int_cnt2<<scale1;
7048       int tail_off2 = int_cnt2<<scale2;
7049       if (ae == StrIntrinsicNode::UL) {
7050         pmovzxbw(vec, Address(str2, cnt2, scale2, tail_off2));
7051       } else {
7052         movdqu(vec, Address(str2, cnt2, scale2, tail_off2));
7053       }
7054       pcmpestri(vec, Address(result, cnt2, scale1, tail_off1), mode);
7055     } else {
7056       // calculate index in register to avoid integer overflow (int_cnt2*2)
7057       movl(tmp, int_cnt2);
7058       addptr(tmp, cnt2);
7059       if (ae == StrIntrinsicNode::UL) {
7060         pmovzxbw(vec, Address(str2, tmp, scale2, 0));
7061       } else {
7062         movdqu(vec, Address(str2, tmp, scale2, 0));
7063       }
7064       pcmpestri(vec, Address(result, tmp, scale1, 0), mode);
7065     }
7066     // Need to reload strings pointers if not matched whole vector
7067     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7068     addptr(cnt2, stride);
7069     jcc(Assembler::negative, SCAN_SUBSTR);
7070     // Fall through if found full substring
7071 
7072   } // (int_cnt2 > 8)
7073 
7074   bind(RET_FOUND);
7075   // Found result if we matched full small substring.
7076   // Compute substr offset
7077   subptr(result, str1);
7078   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7079     shrl(result, 1); // index
7080   }
7081   bind(EXIT);
7082 
7083 } // string_indexofC8
7084 
7085 // Small strings are loaded through stack if they cross page boundary.
7086 void MacroAssembler::string_indexof(Register str1, Register str2,
7087                                     Register cnt1, Register cnt2,
7088                                     int int_cnt2,  Register result,
7089                                     XMMRegister vec, Register tmp,
7090                                     int ae) {
7091   ShortBranchVerifier sbv(this);
7092   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7093   assert(ae != StrIntrinsicNode::LU, "Invalid encoding");
7094 
7095   //
7096   // int_cnt2 is length of small (< 8 chars) constant substring
7097   // or (-1) for non constant substring in which case its length
7098   // is in cnt2 register.
7099   //
7100   // Note, inline_string_indexOf() generates checks:
7101   // if (substr.count > string.count) return -1;
7102   // if (substr.count == 0) return 0;
7103   //
7104   int stride = (ae == StrIntrinsicNode::LL) ? 16 : 8; //UU, UL -> 8
7105   assert(int_cnt2 == -1 || (0 < int_cnt2 && int_cnt2 < stride), "should be != 0");
7106   // This method uses the pcmpestri instruction with bound registers
7107   //   inputs:
7108   //     xmm - substring
7109   //     rax - substring length (elements count)
7110   //     mem - scanned string
7111   //     rdx - string length (elements count)
7112   //     0xd - mode: 1100 (substring search) + 01 (unsigned shorts)
7113   //     0xc - mode: 1100 (substring search) + 00 (unsigned bytes)
7114   //   outputs:
7115   //     rcx - matched index in string
7116   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7117   int mode = (ae == StrIntrinsicNode::LL) ? 0x0c : 0x0d; // bytes or shorts
7118   Address::ScaleFactor scale1 = (ae == StrIntrinsicNode::LL) ? Address::times_1 : Address::times_2;
7119   Address::ScaleFactor scale2 = (ae == StrIntrinsicNode::UL) ? Address::times_1 : scale1;
7120 
7121   Label RELOAD_SUBSTR, SCAN_TO_SUBSTR, SCAN_SUBSTR, ADJUST_STR,
7122         RET_FOUND, RET_NOT_FOUND, CLEANUP, FOUND_SUBSTR,
7123         FOUND_CANDIDATE;
7124 
7125   { //========================================================
7126     // We don't know where these strings are located
7127     // and we can't read beyond them. Load them through stack.
7128     Label BIG_STRINGS, CHECK_STR, COPY_SUBSTR, COPY_STR;
7129 
7130     movptr(tmp, rsp); // save old SP
7131 
7132     if (int_cnt2 > 0) {     // small (< 8 chars) constant substring
7133       if (int_cnt2 == (1>>scale2)) { // One byte
7134         assert((ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL), "Only possible for latin1 encoding");
7135         load_unsigned_byte(result, Address(str2, 0));
7136         movdl(vec, result); // move 32 bits
7137       } else if (ae == StrIntrinsicNode::LL && int_cnt2 == 3) {  // Three bytes
7138         // Not enough header space in 32-bit VM: 12+3 = 15.
7139         movl(result, Address(str2, -1));
7140         shrl(result, 8);
7141         movdl(vec, result); // move 32 bits
7142       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (2>>scale2)) {  // One char
7143         load_unsigned_short(result, Address(str2, 0));
7144         movdl(vec, result); // move 32 bits
7145       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (4>>scale2)) { // Two chars
7146         movdl(vec, Address(str2, 0)); // move 32 bits
7147       } else if (ae != StrIntrinsicNode::UL && int_cnt2 == (8>>scale2)) { // Four chars
7148         movq(vec, Address(str2, 0));  // move 64 bits
7149       } else { // cnt2 = { 3, 5, 6, 7 } || (ae == StrIntrinsicNode::UL && cnt2 ={2, ..., 7})
7150         // Array header size is 12 bytes in 32-bit VM
7151         // + 6 bytes for 3 chars == 18 bytes,
7152         // enough space to load vec and shift.
7153         assert(HeapWordSize*TypeArrayKlass::header_size() >= 12,"sanity");
7154         if (ae == StrIntrinsicNode::UL) {
7155           int tail_off = int_cnt2-8;
7156           pmovzxbw(vec, Address(str2, tail_off));
7157           psrldq(vec, -2*tail_off);
7158         }
7159         else {
7160           int tail_off = int_cnt2*(1<<scale2);
7161           movdqu(vec, Address(str2, tail_off-16));
7162           psrldq(vec, 16-tail_off);
7163         }
7164       }
7165     } else { // not constant substring
7166       cmpl(cnt2, stride);
7167       jccb(Assembler::aboveEqual, BIG_STRINGS); // Both strings are big enough
7168 
7169       // We can read beyond string if srt+16 does not cross page boundary
7170       // since heaps are aligned and mapped by pages.
7171       assert(os::vm_page_size() < (int)G, "default page should be small");
7172       movl(result, str2); // We need only low 32 bits
7173       andl(result, (os::vm_page_size()-1));
7174       cmpl(result, (os::vm_page_size()-16));
7175       jccb(Assembler::belowEqual, CHECK_STR);
7176 
7177       // Move small strings to stack to allow load 16 bytes into vec.
7178       subptr(rsp, 16);
7179       int stk_offset = wordSize-(1<<scale2);
7180       push(cnt2);
7181 
7182       bind(COPY_SUBSTR);
7183       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UL) {
7184         load_unsigned_byte(result, Address(str2, cnt2, scale2, -1));
7185         movb(Address(rsp, cnt2, scale2, stk_offset), result);
7186       } else if (ae == StrIntrinsicNode::UU) {
7187         load_unsigned_short(result, Address(str2, cnt2, scale2, -2));
7188         movw(Address(rsp, cnt2, scale2, stk_offset), result);
7189       }
7190       decrement(cnt2);
7191       jccb(Assembler::notZero, COPY_SUBSTR);
7192 
7193       pop(cnt2);
7194       movptr(str2, rsp);  // New substring address
7195     } // non constant
7196 
7197     bind(CHECK_STR);
7198     cmpl(cnt1, stride);
7199     jccb(Assembler::aboveEqual, BIG_STRINGS);
7200 
7201     // Check cross page boundary.
7202     movl(result, str1); // We need only low 32 bits
7203     andl(result, (os::vm_page_size()-1));
7204     cmpl(result, (os::vm_page_size()-16));
7205     jccb(Assembler::belowEqual, BIG_STRINGS);
7206 
7207     subptr(rsp, 16);
7208     int stk_offset = -(1<<scale1);
7209     if (int_cnt2 < 0) { // not constant
7210       push(cnt2);
7211       stk_offset += wordSize;
7212     }
7213     movl(cnt2, cnt1);
7214 
7215     bind(COPY_STR);
7216     if (ae == StrIntrinsicNode::LL) {
7217       load_unsigned_byte(result, Address(str1, cnt2, scale1, -1));
7218       movb(Address(rsp, cnt2, scale1, stk_offset), result);
7219     } else {
7220       load_unsigned_short(result, Address(str1, cnt2, scale1, -2));
7221       movw(Address(rsp, cnt2, scale1, stk_offset), result);
7222     }
7223     decrement(cnt2);
7224     jccb(Assembler::notZero, COPY_STR);
7225 
7226     if (int_cnt2 < 0) { // not constant
7227       pop(cnt2);
7228     }
7229     movptr(str1, rsp);  // New string address
7230 
7231     bind(BIG_STRINGS);
7232     // Load substring.
7233     if (int_cnt2 < 0) { // -1
7234       if (ae == StrIntrinsicNode::UL) {
7235         pmovzxbw(vec, Address(str2, 0));
7236       } else {
7237         movdqu(vec, Address(str2, 0));
7238       }
7239       push(cnt2);       // substr count
7240       push(str2);       // substr addr
7241       push(str1);       // string addr
7242     } else {
7243       // Small (< 8 chars) constant substrings are loaded already.
7244       movl(cnt2, int_cnt2);
7245     }
7246     push(tmp);  // original SP
7247 
7248   } // Finished loading
7249 
7250   //========================================================
7251   // Start search
7252   //
7253 
7254   movptr(result, str1); // string addr
7255 
7256   if (int_cnt2  < 0) {  // Only for non constant substring
7257     jmpb(SCAN_TO_SUBSTR);
7258 
7259     // SP saved at sp+0
7260     // String saved at sp+1*wordSize
7261     // Substr saved at sp+2*wordSize
7262     // Substr count saved at sp+3*wordSize
7263 
7264     // Reload substr for rescan, this code
7265     // is executed only for large substrings (> 8 chars)
7266     bind(RELOAD_SUBSTR);
7267     movptr(str2, Address(rsp, 2*wordSize));
7268     movl(cnt2, Address(rsp, 3*wordSize));
7269     if (ae == StrIntrinsicNode::UL) {
7270       pmovzxbw(vec, Address(str2, 0));
7271     } else {
7272       movdqu(vec, Address(str2, 0));
7273     }
7274     // We came here after the beginning of the substring was
7275     // matched but the rest of it was not so we need to search
7276     // again. Start from the next element after the previous match.
7277     subptr(str1, result); // Restore counter
7278     if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7279       shrl(str1, 1);
7280     }
7281     addl(cnt1, str1);
7282     decrementl(cnt1);   // Shift to next element
7283     cmpl(cnt1, cnt2);
7284     jcc(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7285 
7286     addptr(result, (1<<scale1));
7287   } // non constant
7288 
7289   // Scan string for start of substr in 16-byte vectors
7290   bind(SCAN_TO_SUBSTR);
7291   assert(cnt1 == rdx && cnt2 == rax && tmp == rcx, "pcmpestri");
7292   pcmpestri(vec, Address(result, 0), mode);
7293   jccb(Assembler::below, FOUND_CANDIDATE);   // CF == 1
7294   subl(cnt1, stride);
7295   jccb(Assembler::lessEqual, RET_NOT_FOUND); // Scanned full string
7296   cmpl(cnt1, cnt2);
7297   jccb(Assembler::negative, RET_NOT_FOUND);  // Left less then substring
7298   addptr(result, 16);
7299 
7300   bind(ADJUST_STR);
7301   cmpl(cnt1, stride); // Do not read beyond string
7302   jccb(Assembler::greaterEqual, SCAN_TO_SUBSTR);
7303   // Back-up string to avoid reading beyond string.
7304   lea(result, Address(result, cnt1, scale1, -16));
7305   movl(cnt1, stride);
7306   jmpb(SCAN_TO_SUBSTR);
7307 
7308   // Found a potential substr
7309   bind(FOUND_CANDIDATE);
7310   // After pcmpestri tmp(rcx) contains matched element index
7311 
7312   // Make sure string is still long enough
7313   subl(cnt1, tmp);
7314   cmpl(cnt1, cnt2);
7315   jccb(Assembler::greaterEqual, FOUND_SUBSTR);
7316   // Left less then substring.
7317 
7318   bind(RET_NOT_FOUND);
7319   movl(result, -1);
7320   jmpb(CLEANUP);
7321 
7322   bind(FOUND_SUBSTR);
7323   // Compute start addr of substr
7324   lea(result, Address(result, tmp, scale1));
7325   if (int_cnt2 > 0) { // Constant substring
7326     // Repeat search for small substring (< 8 chars)
7327     // from new point without reloading substring.
7328     // Have to check that we don't read beyond string.
7329     cmpl(tmp, stride-int_cnt2);
7330     jccb(Assembler::greater, ADJUST_STR);
7331     // Fall through if matched whole substring.
7332   } else { // non constant
7333     assert(int_cnt2 == -1, "should be != 0");
7334 
7335     addl(tmp, cnt2);
7336     // Found result if we matched whole substring.
7337     cmpl(tmp, stride);
7338     jccb(Assembler::lessEqual, RET_FOUND);
7339 
7340     // Repeat search for small substring (<= 8 chars)
7341     // from new point 'str1' without reloading substring.
7342     cmpl(cnt2, stride);
7343     // Have to check that we don't read beyond string.
7344     jccb(Assembler::lessEqual, ADJUST_STR);
7345 
7346     Label CHECK_NEXT, CONT_SCAN_SUBSTR, RET_FOUND_LONG;
7347     // Compare the rest of substring (> 8 chars).
7348     movptr(str1, result);
7349 
7350     cmpl(tmp, cnt2);
7351     // First 8 chars are already matched.
7352     jccb(Assembler::equal, CHECK_NEXT);
7353 
7354     bind(SCAN_SUBSTR);
7355     pcmpestri(vec, Address(str1, 0), mode);
7356     // Need to reload strings pointers if not matched whole vector
7357     jcc(Assembler::noOverflow, RELOAD_SUBSTR); // OF == 0
7358 
7359     bind(CHECK_NEXT);
7360     subl(cnt2, stride);
7361     jccb(Assembler::lessEqual, RET_FOUND_LONG); // Found full substring
7362     addptr(str1, 16);
7363     if (ae == StrIntrinsicNode::UL) {
7364       addptr(str2, 8);
7365     } else {
7366       addptr(str2, 16);
7367     }
7368     subl(cnt1, stride);
7369     cmpl(cnt2, stride); // Do not read beyond substring
7370     jccb(Assembler::greaterEqual, CONT_SCAN_SUBSTR);
7371     // Back-up strings to avoid reading beyond substring.
7372 
7373     if (ae == StrIntrinsicNode::UL) {
7374       lea(str2, Address(str2, cnt2, scale2, -8));
7375       lea(str1, Address(str1, cnt2, scale1, -16));
7376     } else {
7377       lea(str2, Address(str2, cnt2, scale2, -16));
7378       lea(str1, Address(str1, cnt2, scale1, -16));
7379     }
7380     subl(cnt1, cnt2);
7381     movl(cnt2, stride);
7382     addl(cnt1, stride);
7383     bind(CONT_SCAN_SUBSTR);
7384     if (ae == StrIntrinsicNode::UL) {
7385       pmovzxbw(vec, Address(str2, 0));
7386     } else {
7387       movdqu(vec, Address(str2, 0));
7388     }
7389     jmp(SCAN_SUBSTR);
7390 
7391     bind(RET_FOUND_LONG);
7392     movptr(str1, Address(rsp, wordSize));
7393   } // non constant
7394 
7395   bind(RET_FOUND);
7396   // Compute substr offset
7397   subptr(result, str1);
7398   if (ae == StrIntrinsicNode::UU || ae == StrIntrinsicNode::UL) {
7399     shrl(result, 1); // index
7400   }
7401   bind(CLEANUP);
7402   pop(rsp); // restore SP
7403 
7404 } // string_indexof
7405 
7406 void MacroAssembler::string_indexof_char(Register str1, Register cnt1, Register ch, Register result,
7407                                          XMMRegister vec1, XMMRegister vec2, XMMRegister vec3, Register tmp) {
7408   ShortBranchVerifier sbv(this);
7409   assert(UseSSE42Intrinsics, "SSE4.2 intrinsics are required");
7410 
7411   int stride = 8;
7412 
7413   Label FOUND_CHAR, SCAN_TO_CHAR, SCAN_TO_CHAR_LOOP,
7414         SCAN_TO_8_CHAR, SCAN_TO_8_CHAR_LOOP, SCAN_TO_16_CHAR_LOOP,
7415         RET_NOT_FOUND, SCAN_TO_8_CHAR_INIT,
7416         FOUND_SEQ_CHAR, DONE_LABEL;
7417 
7418   movptr(result, str1);
7419   if (UseAVX >= 2) {
7420     cmpl(cnt1, stride);
7421     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7422     cmpl(cnt1, 2*stride);
7423     jcc(Assembler::less, SCAN_TO_8_CHAR_INIT);
7424     movdl(vec1, ch);
7425     vpbroadcastw(vec1, vec1);
7426     vpxor(vec2, vec2);
7427     movl(tmp, cnt1);
7428     andl(tmp, 0xFFFFFFF0);  //vector count (in chars)
7429     andl(cnt1,0x0000000F);  //tail count (in chars)
7430 
7431     bind(SCAN_TO_16_CHAR_LOOP);
7432     vmovdqu(vec3, Address(result, 0));
7433     vpcmpeqw(vec3, vec3, vec1, 1);
7434     vptest(vec2, vec3);
7435     jcc(Assembler::carryClear, FOUND_CHAR);
7436     addptr(result, 32);
7437     subl(tmp, 2*stride);
7438     jccb(Assembler::notZero, SCAN_TO_16_CHAR_LOOP);
7439     jmp(SCAN_TO_8_CHAR);
7440     bind(SCAN_TO_8_CHAR_INIT);
7441     movdl(vec1, ch);
7442     pshuflw(vec1, vec1, 0x00);
7443     pshufd(vec1, vec1, 0);
7444     pxor(vec2, vec2);
7445   }
7446   bind(SCAN_TO_8_CHAR);
7447   cmpl(cnt1, stride);
7448   if (UseAVX >= 2) {
7449     jcc(Assembler::less, SCAN_TO_CHAR);
7450   } else {
7451     jcc(Assembler::less, SCAN_TO_CHAR_LOOP);
7452     movdl(vec1, ch);
7453     pshuflw(vec1, vec1, 0x00);
7454     pshufd(vec1, vec1, 0);
7455     pxor(vec2, vec2);
7456   }
7457   movl(tmp, cnt1);
7458   andl(tmp, 0xFFFFFFF8);  //vector count (in chars)
7459   andl(cnt1,0x00000007);  //tail count (in chars)
7460 
7461   bind(SCAN_TO_8_CHAR_LOOP);
7462   movdqu(vec3, Address(result, 0));
7463   pcmpeqw(vec3, vec1);
7464   ptest(vec2, vec3);
7465   jcc(Assembler::carryClear, FOUND_CHAR);
7466   addptr(result, 16);
7467   subl(tmp, stride);
7468   jccb(Assembler::notZero, SCAN_TO_8_CHAR_LOOP);
7469   bind(SCAN_TO_CHAR);
7470   testl(cnt1, cnt1);
7471   jcc(Assembler::zero, RET_NOT_FOUND);
7472   bind(SCAN_TO_CHAR_LOOP);
7473   load_unsigned_short(tmp, Address(result, 0));
7474   cmpl(ch, tmp);
7475   jccb(Assembler::equal, FOUND_SEQ_CHAR);
7476   addptr(result, 2);
7477   subl(cnt1, 1);
7478   jccb(Assembler::zero, RET_NOT_FOUND);
7479   jmp(SCAN_TO_CHAR_LOOP);
7480 
7481   bind(RET_NOT_FOUND);
7482   movl(result, -1);
7483   jmpb(DONE_LABEL);
7484 
7485   bind(FOUND_CHAR);
7486   if (UseAVX >= 2) {
7487     vpmovmskb(tmp, vec3);
7488   } else {
7489     pmovmskb(tmp, vec3);
7490   }
7491   bsfl(ch, tmp);
7492   addl(result, ch);
7493 
7494   bind(FOUND_SEQ_CHAR);
7495   subptr(result, str1);
7496   shrl(result, 1);
7497 
7498   bind(DONE_LABEL);
7499 } // string_indexof_char
7500 
7501 // helper function for string_compare
7502 void MacroAssembler::load_next_elements(Register elem1, Register elem2, Register str1, Register str2,
7503                                         Address::ScaleFactor scale, Address::ScaleFactor scale1,
7504                                         Address::ScaleFactor scale2, Register index, int ae) {
7505   if (ae == StrIntrinsicNode::LL) {
7506     load_unsigned_byte(elem1, Address(str1, index, scale, 0));
7507     load_unsigned_byte(elem2, Address(str2, index, scale, 0));
7508   } else if (ae == StrIntrinsicNode::UU) {
7509     load_unsigned_short(elem1, Address(str1, index, scale, 0));
7510     load_unsigned_short(elem2, Address(str2, index, scale, 0));
7511   } else {
7512     load_unsigned_byte(elem1, Address(str1, index, scale1, 0));
7513     load_unsigned_short(elem2, Address(str2, index, scale2, 0));
7514   }
7515 }
7516 
7517 // Compare strings, used for char[] and byte[].
7518 void MacroAssembler::string_compare(Register str1, Register str2,
7519                                     Register cnt1, Register cnt2, Register result,
7520                                     XMMRegister vec1, int ae) {
7521   ShortBranchVerifier sbv(this);
7522   Label LENGTH_DIFF_LABEL, POP_LABEL, DONE_LABEL, WHILE_HEAD_LABEL;
7523   Label COMPARE_WIDE_VECTORS_LOOP_FAILED;  // used only _LP64 && AVX3
7524   int stride, stride2, adr_stride, adr_stride1, adr_stride2;
7525   int stride2x2 = 0x40;
7526   Address::ScaleFactor scale = Address::no_scale;
7527   Address::ScaleFactor scale1 = Address::no_scale;
7528   Address::ScaleFactor scale2 = Address::no_scale;
7529 
7530   if (ae != StrIntrinsicNode::LL) {
7531     stride2x2 = 0x20;
7532   }
7533 
7534   if (ae == StrIntrinsicNode::LU || ae == StrIntrinsicNode::UL) {
7535     shrl(cnt2, 1);
7536   }
7537   // Compute the minimum of the string lengths and the
7538   // difference of the string lengths (stack).
7539   // Do the conditional move stuff
7540   movl(result, cnt1);
7541   subl(cnt1, cnt2);
7542   push(cnt1);
7543   cmov32(Assembler::lessEqual, cnt2, result);    // cnt2 = min(cnt1, cnt2)
7544 
7545   // Is the minimum length zero?
7546   testl(cnt2, cnt2);
7547   jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7548   if (ae == StrIntrinsicNode::LL) {
7549     // Load first bytes
7550     load_unsigned_byte(result, Address(str1, 0));  // result = str1[0]
7551     load_unsigned_byte(cnt1, Address(str2, 0));    // cnt1   = str2[0]
7552   } else if (ae == StrIntrinsicNode::UU) {
7553     // Load first characters
7554     load_unsigned_short(result, Address(str1, 0));
7555     load_unsigned_short(cnt1, Address(str2, 0));
7556   } else {
7557     load_unsigned_byte(result, Address(str1, 0));
7558     load_unsigned_short(cnt1, Address(str2, 0));
7559   }
7560   subl(result, cnt1);
7561   jcc(Assembler::notZero,  POP_LABEL);
7562 
7563   if (ae == StrIntrinsicNode::UU) {
7564     // Divide length by 2 to get number of chars
7565     shrl(cnt2, 1);
7566   }
7567   cmpl(cnt2, 1);
7568   jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7569 
7570   // Check if the strings start at the same location and setup scale and stride
7571   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7572     cmpptr(str1, str2);
7573     jcc(Assembler::equal, LENGTH_DIFF_LABEL);
7574     if (ae == StrIntrinsicNode::LL) {
7575       scale = Address::times_1;
7576       stride = 16;
7577     } else {
7578       scale = Address::times_2;
7579       stride = 8;
7580     }
7581   } else {
7582     scale1 = Address::times_1;
7583     scale2 = Address::times_2;
7584     // scale not used
7585     stride = 8;
7586   }
7587 
7588   if (UseAVX >= 2 && UseSSE42Intrinsics) {
7589     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
7590     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
7591     Label COMPARE_WIDE_VECTORS_LOOP_AVX2;
7592     Label COMPARE_TAIL_LONG;
7593     Label COMPARE_WIDE_VECTORS_LOOP_AVX3;  // used only _LP64 && AVX3
7594 
7595     int pcmpmask = 0x19;
7596     if (ae == StrIntrinsicNode::LL) {
7597       pcmpmask &= ~0x01;
7598     }
7599 
7600     // Setup to compare 16-chars (32-bytes) vectors,
7601     // start from first character again because it has aligned address.
7602     if (ae == StrIntrinsicNode::LL) {
7603       stride2 = 32;
7604     } else {
7605       stride2 = 16;
7606     }
7607     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7608       adr_stride = stride << scale;
7609     } else {
7610       adr_stride1 = 8;  //stride << scale1;
7611       adr_stride2 = 16; //stride << scale2;
7612     }
7613 
7614     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7615     // rax and rdx are used by pcmpestri as elements counters
7616     movl(result, cnt2);
7617     andl(cnt2, ~(stride2-1));   // cnt2 holds the vector count
7618     jcc(Assembler::zero, COMPARE_TAIL_LONG);
7619 
7620     // fast path : compare first 2 8-char vectors.
7621     bind(COMPARE_16_CHARS);
7622     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7623       movdqu(vec1, Address(str1, 0));
7624     } else {
7625       pmovzxbw(vec1, Address(str1, 0));
7626     }
7627     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7628     jccb(Assembler::below, COMPARE_INDEX_CHAR);
7629 
7630     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7631       movdqu(vec1, Address(str1, adr_stride));
7632       pcmpestri(vec1, Address(str2, adr_stride), pcmpmask);
7633     } else {
7634       pmovzxbw(vec1, Address(str1, adr_stride1));
7635       pcmpestri(vec1, Address(str2, adr_stride2), pcmpmask);
7636     }
7637     jccb(Assembler::aboveEqual, COMPARE_WIDE_VECTORS);
7638     addl(cnt1, stride);
7639 
7640     // Compare the characters at index in cnt1
7641     bind(COMPARE_INDEX_CHAR); // cnt1 has the offset of the mismatching character
7642     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7643     subl(result, cnt2);
7644     jmp(POP_LABEL);
7645 
7646     // Setup the registers to start vector comparison loop
7647     bind(COMPARE_WIDE_VECTORS);
7648     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7649       lea(str1, Address(str1, result, scale));
7650       lea(str2, Address(str2, result, scale));
7651     } else {
7652       lea(str1, Address(str1, result, scale1));
7653       lea(str2, Address(str2, result, scale2));
7654     }
7655     subl(result, stride2);
7656     subl(cnt2, stride2);
7657     jcc(Assembler::zero, COMPARE_WIDE_TAIL);
7658     negptr(result);
7659 
7660     //  In a loop, compare 16-chars (32-bytes) at once using (vpxor+vptest)
7661     bind(COMPARE_WIDE_VECTORS_LOOP);
7662 
7663 #ifdef _LP64
7664     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
7665       cmpl(cnt2, stride2x2);
7666       jccb(Assembler::below, COMPARE_WIDE_VECTORS_LOOP_AVX2);
7667       testl(cnt2, stride2x2-1);   // cnt2 holds the vector count
7668       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX2);   // means we cannot subtract by 0x40
7669 
7670       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
7671       if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7672         evmovdquq(vec1, Address(str1, result, scale), Assembler::AVX_512bit);
7673         evpcmpeqb(k7, vec1, Address(str2, result, scale), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7674       } else {
7675         vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_512bit);
7676         evpcmpeqb(k7, vec1, Address(str2, result, scale2), Assembler::AVX_512bit); // k7 == 11..11, if operands equal, otherwise k7 has some 0
7677       }
7678       kortestql(k7, k7);
7679       jcc(Assembler::aboveEqual, COMPARE_WIDE_VECTORS_LOOP_FAILED);     // miscompare
7680       addptr(result, stride2x2);  // update since we already compared at this addr
7681       subl(cnt2, stride2x2);      // and sub the size too
7682       jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP_AVX3);
7683 
7684       vpxor(vec1, vec1);
7685       jmpb(COMPARE_WIDE_TAIL);
7686     }//if (VM_Version::supports_avx512vlbw())
7687 #endif // _LP64
7688 
7689 
7690     bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7691     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7692       vmovdqu(vec1, Address(str1, result, scale));
7693       vpxor(vec1, Address(str2, result, scale));
7694     } else {
7695       vpmovzxbw(vec1, Address(str1, result, scale1), Assembler::AVX_256bit);
7696       vpxor(vec1, Address(str2, result, scale2));
7697     }
7698     vptest(vec1, vec1);
7699     jcc(Assembler::notZero, VECTOR_NOT_EQUAL);
7700     addptr(result, stride2);
7701     subl(cnt2, stride2);
7702     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
7703     // clean upper bits of YMM registers
7704     vpxor(vec1, vec1);
7705 
7706     // compare wide vectors tail
7707     bind(COMPARE_WIDE_TAIL);
7708     testptr(result, result);
7709     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7710 
7711     movl(result, stride2);
7712     movl(cnt2, result);
7713     negptr(result);
7714     jmp(COMPARE_WIDE_VECTORS_LOOP_AVX2);
7715 
7716     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
7717     bind(VECTOR_NOT_EQUAL);
7718     // clean upper bits of YMM registers
7719     vpxor(vec1, vec1);
7720     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7721       lea(str1, Address(str1, result, scale));
7722       lea(str2, Address(str2, result, scale));
7723     } else {
7724       lea(str1, Address(str1, result, scale1));
7725       lea(str2, Address(str2, result, scale2));
7726     }
7727     jmp(COMPARE_16_CHARS);
7728 
7729     // Compare tail chars, length between 1 to 15 chars
7730     bind(COMPARE_TAIL_LONG);
7731     movl(cnt2, result);
7732     cmpl(cnt2, stride);
7733     jcc(Assembler::less, COMPARE_SMALL_STR);
7734 
7735     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7736       movdqu(vec1, Address(str1, 0));
7737     } else {
7738       pmovzxbw(vec1, Address(str1, 0));
7739     }
7740     pcmpestri(vec1, Address(str2, 0), pcmpmask);
7741     jcc(Assembler::below, COMPARE_INDEX_CHAR);
7742     subptr(cnt2, stride);
7743     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7744     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7745       lea(str1, Address(str1, result, scale));
7746       lea(str2, Address(str2, result, scale));
7747     } else {
7748       lea(str1, Address(str1, result, scale1));
7749       lea(str2, Address(str2, result, scale2));
7750     }
7751     negptr(cnt2);
7752     jmpb(WHILE_HEAD_LABEL);
7753 
7754     bind(COMPARE_SMALL_STR);
7755   } else if (UseSSE42Intrinsics) {
7756     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_TAIL;
7757     int pcmpmask = 0x19;
7758     // Setup to compare 8-char (16-byte) vectors,
7759     // start from first character again because it has aligned address.
7760     movl(result, cnt2);
7761     andl(cnt2, ~(stride - 1));   // cnt2 holds the vector count
7762     if (ae == StrIntrinsicNode::LL) {
7763       pcmpmask &= ~0x01;
7764     }
7765     jcc(Assembler::zero, COMPARE_TAIL);
7766     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7767       lea(str1, Address(str1, result, scale));
7768       lea(str2, Address(str2, result, scale));
7769     } else {
7770       lea(str1, Address(str1, result, scale1));
7771       lea(str2, Address(str2, result, scale2));
7772     }
7773     negptr(result);
7774 
7775     // pcmpestri
7776     //   inputs:
7777     //     vec1- substring
7778     //     rax - negative string length (elements count)
7779     //     mem - scanned string
7780     //     rdx - string length (elements count)
7781     //     pcmpmask - cmp mode: 11000 (string compare with negated result)
7782     //               + 00 (unsigned bytes) or  + 01 (unsigned shorts)
7783     //   outputs:
7784     //     rcx - first mismatched element index
7785     assert(result == rax && cnt2 == rdx && cnt1 == rcx, "pcmpestri");
7786 
7787     bind(COMPARE_WIDE_VECTORS);
7788     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7789       movdqu(vec1, Address(str1, result, scale));
7790       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7791     } else {
7792       pmovzxbw(vec1, Address(str1, result, scale1));
7793       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7794     }
7795     // After pcmpestri cnt1(rcx) contains mismatched element index
7796 
7797     jccb(Assembler::below, VECTOR_NOT_EQUAL);  // CF==1
7798     addptr(result, stride);
7799     subptr(cnt2, stride);
7800     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS);
7801 
7802     // compare wide vectors tail
7803     testptr(result, result);
7804     jcc(Assembler::zero, LENGTH_DIFF_LABEL);
7805 
7806     movl(cnt2, stride);
7807     movl(result, stride);
7808     negptr(result);
7809     if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7810       movdqu(vec1, Address(str1, result, scale));
7811       pcmpestri(vec1, Address(str2, result, scale), pcmpmask);
7812     } else {
7813       pmovzxbw(vec1, Address(str1, result, scale1));
7814       pcmpestri(vec1, Address(str2, result, scale2), pcmpmask);
7815     }
7816     jccb(Assembler::aboveEqual, LENGTH_DIFF_LABEL);
7817 
7818     // Mismatched characters in the vectors
7819     bind(VECTOR_NOT_EQUAL);
7820     addptr(cnt1, result);
7821     load_next_elements(result, cnt2, str1, str2, scale, scale1, scale2, cnt1, ae);
7822     subl(result, cnt2);
7823     jmpb(POP_LABEL);
7824 
7825     bind(COMPARE_TAIL); // limit is zero
7826     movl(cnt2, result);
7827     // Fallthru to tail compare
7828   }
7829   // Shift str2 and str1 to the end of the arrays, negate min
7830   if (ae == StrIntrinsicNode::LL || ae == StrIntrinsicNode::UU) {
7831     lea(str1, Address(str1, cnt2, scale));
7832     lea(str2, Address(str2, cnt2, scale));
7833   } else {
7834     lea(str1, Address(str1, cnt2, scale1));
7835     lea(str2, Address(str2, cnt2, scale2));
7836   }
7837   decrementl(cnt2);  // first character was compared already
7838   negptr(cnt2);
7839 
7840   // Compare the rest of the elements
7841   bind(WHILE_HEAD_LABEL);
7842   load_next_elements(result, cnt1, str1, str2, scale, scale1, scale2, cnt2, ae);
7843   subl(result, cnt1);
7844   jccb(Assembler::notZero, POP_LABEL);
7845   increment(cnt2);
7846   jccb(Assembler::notZero, WHILE_HEAD_LABEL);
7847 
7848   // Strings are equal up to min length.  Return the length difference.
7849   bind(LENGTH_DIFF_LABEL);
7850   pop(result);
7851   if (ae == StrIntrinsicNode::UU) {
7852     // Divide diff by 2 to get number of chars
7853     sarl(result, 1);
7854   }
7855   jmpb(DONE_LABEL);
7856 
7857 #ifdef _LP64
7858   if (VM_Version::supports_avx512vlbw()) {
7859 
7860     bind(COMPARE_WIDE_VECTORS_LOOP_FAILED);
7861 
7862     kmovql(cnt1, k7);
7863     notq(cnt1);
7864     bsfq(cnt2, cnt1);
7865     if (ae != StrIntrinsicNode::LL) {
7866       // Divide diff by 2 to get number of chars
7867       sarl(cnt2, 1);
7868     }
7869     addq(result, cnt2);
7870     if (ae == StrIntrinsicNode::LL) {
7871       load_unsigned_byte(cnt1, Address(str2, result));
7872       load_unsigned_byte(result, Address(str1, result));
7873     } else if (ae == StrIntrinsicNode::UU) {
7874       load_unsigned_short(cnt1, Address(str2, result, scale));
7875       load_unsigned_short(result, Address(str1, result, scale));
7876     } else {
7877       load_unsigned_short(cnt1, Address(str2, result, scale2));
7878       load_unsigned_byte(result, Address(str1, result, scale1));
7879     }
7880     subl(result, cnt1);
7881     jmpb(POP_LABEL);
7882   }//if (VM_Version::supports_avx512vlbw())
7883 #endif // _LP64
7884 
7885   // Discard the stored length difference
7886   bind(POP_LABEL);
7887   pop(cnt1);
7888 
7889   // That's it
7890   bind(DONE_LABEL);
7891   if(ae == StrIntrinsicNode::UL) {
7892     negl(result);
7893   }
7894 
7895 }
7896 
7897 // Search for Non-ASCII character (Negative byte value) in a byte array,
7898 // return true if it has any and false otherwise.
7899 //   ..\jdk\src\java.base\share\classes\java\lang\StringCoding.java
7900 //   @HotSpotIntrinsicCandidate
7901 //   private static boolean hasNegatives(byte[] ba, int off, int len) {
7902 //     for (int i = off; i < off + len; i++) {
7903 //       if (ba[i] < 0) {
7904 //         return true;
7905 //       }
7906 //     }
7907 //     return false;
7908 //   }
7909 void MacroAssembler::has_negatives(Register ary1, Register len,
7910   Register result, Register tmp1,
7911   XMMRegister vec1, XMMRegister vec2) {
7912   // rsi: byte array
7913   // rcx: len
7914   // rax: result
7915   ShortBranchVerifier sbv(this);
7916   assert_different_registers(ary1, len, result, tmp1);
7917   assert_different_registers(vec1, vec2);
7918   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_CHAR, COMPARE_VECTORS, COMPARE_BYTE;
7919 
7920   // len == 0
7921   testl(len, len);
7922   jcc(Assembler::zero, FALSE_LABEL);
7923 
7924   if ((UseAVX > 2) && // AVX512
7925     VM_Version::supports_avx512vlbw() &&
7926     VM_Version::supports_bmi2()) {
7927 
7928     set_vector_masking();  // opening of the stub context for programming mask registers
7929 
7930     Label test_64_loop, test_tail;
7931     Register tmp3_aliased = len;
7932 
7933     movl(tmp1, len);
7934     vpxor(vec2, vec2, vec2, Assembler::AVX_512bit);
7935 
7936     andl(tmp1, 64 - 1);   // tail count (in chars) 0x3F
7937     andl(len, ~(64 - 1));    // vector count (in chars)
7938     jccb(Assembler::zero, test_tail);
7939 
7940     lea(ary1, Address(ary1, len, Address::times_1));
7941     negptr(len);
7942 
7943     bind(test_64_loop);
7944     // Check whether our 64 elements of size byte contain negatives
7945     evpcmpgtb(k2, vec2, Address(ary1, len, Address::times_1), Assembler::AVX_512bit);
7946     kortestql(k2, k2);
7947     jcc(Assembler::notZero, TRUE_LABEL);
7948 
7949     addptr(len, 64);
7950     jccb(Assembler::notZero, test_64_loop);
7951 
7952 
7953     bind(test_tail);
7954     // bail out when there is nothing to be done
7955     testl(tmp1, -1);
7956     jcc(Assembler::zero, FALSE_LABEL);
7957 
7958     // Save k1
7959     kmovql(k3, k1);
7960 
7961     // ~(~0 << len) applied up to two times (for 32-bit scenario)
7962 #ifdef _LP64
7963     mov64(tmp3_aliased, 0xFFFFFFFFFFFFFFFF);
7964     shlxq(tmp3_aliased, tmp3_aliased, tmp1);
7965     notq(tmp3_aliased);
7966     kmovql(k1, tmp3_aliased);
7967 #else
7968     Label k_init;
7969     jmp(k_init);
7970 
7971     // We could not read 64-bits from a general purpose register thus we move
7972     // data required to compose 64 1's to the instruction stream
7973     // We emit 64 byte wide series of elements from 0..63 which later on would
7974     // be used as a compare targets with tail count contained in tmp1 register.
7975     // Result would be a k1 register having tmp1 consecutive number or 1
7976     // counting from least significant bit.
7977     address tmp = pc();
7978     emit_int64(0x0706050403020100);
7979     emit_int64(0x0F0E0D0C0B0A0908);
7980     emit_int64(0x1716151413121110);
7981     emit_int64(0x1F1E1D1C1B1A1918);
7982     emit_int64(0x2726252423222120);
7983     emit_int64(0x2F2E2D2C2B2A2928);
7984     emit_int64(0x3736353433323130);
7985     emit_int64(0x3F3E3D3C3B3A3938);
7986 
7987     bind(k_init);
7988     lea(len, InternalAddress(tmp));
7989     // create mask to test for negative byte inside a vector
7990     evpbroadcastb(vec1, tmp1, Assembler::AVX_512bit);
7991     evpcmpgtb(k1, vec1, Address(len, 0), Assembler::AVX_512bit);
7992 
7993 #endif
7994     evpcmpgtb(k2, k1, vec2, Address(ary1, 0), Assembler::AVX_512bit);
7995     ktestq(k2, k1);
7996     // Restore k1
7997     kmovql(k1, k3);
7998     jcc(Assembler::notZero, TRUE_LABEL);
7999 
8000     jmp(FALSE_LABEL);
8001 
8002     clear_vector_masking();   // closing of the stub context for programming mask registers
8003   } else {
8004     movl(result, len); // copy
8005 
8006     if (UseAVX == 2 && UseSSE >= 2) {
8007       // With AVX2, use 32-byte vector compare
8008       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8009 
8010       // Compare 32-byte vectors
8011       andl(result, 0x0000001f);  //   tail count (in bytes)
8012       andl(len, 0xffffffe0);   // vector count (in bytes)
8013       jccb(Assembler::zero, COMPARE_TAIL);
8014 
8015       lea(ary1, Address(ary1, len, Address::times_1));
8016       negptr(len);
8017 
8018       movl(tmp1, 0x80808080);   // create mask to test for Unicode chars in vector
8019       movdl(vec2, tmp1);
8020       vpbroadcastd(vec2, vec2);
8021 
8022       bind(COMPARE_WIDE_VECTORS);
8023       vmovdqu(vec1, Address(ary1, len, Address::times_1));
8024       vptest(vec1, vec2);
8025       jccb(Assembler::notZero, TRUE_LABEL);
8026       addptr(len, 32);
8027       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8028 
8029       testl(result, result);
8030       jccb(Assembler::zero, FALSE_LABEL);
8031 
8032       vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8033       vptest(vec1, vec2);
8034       jccb(Assembler::notZero, TRUE_LABEL);
8035       jmpb(FALSE_LABEL);
8036 
8037       bind(COMPARE_TAIL); // len is zero
8038       movl(len, result);
8039       // Fallthru to tail compare
8040     } else if (UseSSE42Intrinsics) {
8041       // With SSE4.2, use double quad vector compare
8042       Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8043 
8044       // Compare 16-byte vectors
8045       andl(result, 0x0000000f);  //   tail count (in bytes)
8046       andl(len, 0xfffffff0);   // vector count (in bytes)
8047       jccb(Assembler::zero, COMPARE_TAIL);
8048 
8049       lea(ary1, Address(ary1, len, Address::times_1));
8050       negptr(len);
8051 
8052       movl(tmp1, 0x80808080);
8053       movdl(vec2, tmp1);
8054       pshufd(vec2, vec2, 0);
8055 
8056       bind(COMPARE_WIDE_VECTORS);
8057       movdqu(vec1, Address(ary1, len, Address::times_1));
8058       ptest(vec1, vec2);
8059       jccb(Assembler::notZero, TRUE_LABEL);
8060       addptr(len, 16);
8061       jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8062 
8063       testl(result, result);
8064       jccb(Assembler::zero, FALSE_LABEL);
8065 
8066       movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8067       ptest(vec1, vec2);
8068       jccb(Assembler::notZero, TRUE_LABEL);
8069       jmpb(FALSE_LABEL);
8070 
8071       bind(COMPARE_TAIL); // len is zero
8072       movl(len, result);
8073       // Fallthru to tail compare
8074     }
8075   }
8076   // Compare 4-byte vectors
8077   andl(len, 0xfffffffc); // vector count (in bytes)
8078   jccb(Assembler::zero, COMPARE_CHAR);
8079 
8080   lea(ary1, Address(ary1, len, Address::times_1));
8081   negptr(len);
8082 
8083   bind(COMPARE_VECTORS);
8084   movl(tmp1, Address(ary1, len, Address::times_1));
8085   andl(tmp1, 0x80808080);
8086   jccb(Assembler::notZero, TRUE_LABEL);
8087   addptr(len, 4);
8088   jcc(Assembler::notZero, COMPARE_VECTORS);
8089 
8090   // Compare trailing char (final 2 bytes), if any
8091   bind(COMPARE_CHAR);
8092   testl(result, 0x2);   // tail  char
8093   jccb(Assembler::zero, COMPARE_BYTE);
8094   load_unsigned_short(tmp1, Address(ary1, 0));
8095   andl(tmp1, 0x00008080);
8096   jccb(Assembler::notZero, TRUE_LABEL);
8097   subptr(result, 2);
8098   lea(ary1, Address(ary1, 2));
8099 
8100   bind(COMPARE_BYTE);
8101   testl(result, 0x1);   // tail  byte
8102   jccb(Assembler::zero, FALSE_LABEL);
8103   load_unsigned_byte(tmp1, Address(ary1, 0));
8104   andl(tmp1, 0x00000080);
8105   jccb(Assembler::notEqual, TRUE_LABEL);
8106   jmpb(FALSE_LABEL);
8107 
8108   bind(TRUE_LABEL);
8109   movl(result, 1);   // return true
8110   jmpb(DONE);
8111 
8112   bind(FALSE_LABEL);
8113   xorl(result, result); // return false
8114 
8115   // That's it
8116   bind(DONE);
8117   if (UseAVX >= 2 && UseSSE >= 2) {
8118     // clean upper bits of YMM registers
8119     vpxor(vec1, vec1);
8120     vpxor(vec2, vec2);
8121   }
8122 }
8123 // Compare char[] or byte[] arrays aligned to 4 bytes or substrings.
8124 void MacroAssembler::arrays_equals(bool is_array_equ, Register ary1, Register ary2,
8125                                    Register limit, Register result, Register chr,
8126                                    XMMRegister vec1, XMMRegister vec2, bool is_char) {
8127   ShortBranchVerifier sbv(this);
8128   Label TRUE_LABEL, FALSE_LABEL, DONE, COMPARE_VECTORS, COMPARE_CHAR, COMPARE_BYTE;
8129 
8130   int length_offset  = arrayOopDesc::length_offset_in_bytes();
8131   int base_offset    = arrayOopDesc::base_offset_in_bytes(is_char ? T_CHAR : T_BYTE);
8132 
8133   if (is_array_equ) {
8134     // Check the input args
8135     cmpoop(ary1, ary2);
8136     jcc(Assembler::equal, TRUE_LABEL);
8137 
8138     // Need additional checks for arrays_equals.
8139     testptr(ary1, ary1);
8140     jcc(Assembler::zero, FALSE_LABEL);
8141     testptr(ary2, ary2);
8142     jcc(Assembler::zero, FALSE_LABEL);
8143 
8144     // Check the lengths
8145     movl(limit, Address(ary1, length_offset));
8146     cmpl(limit, Address(ary2, length_offset));
8147     jcc(Assembler::notEqual, FALSE_LABEL);
8148   }
8149 
8150   // count == 0
8151   testl(limit, limit);
8152   jcc(Assembler::zero, TRUE_LABEL);
8153 
8154   if (is_array_equ) {
8155     // Load array address
8156     lea(ary1, Address(ary1, base_offset));
8157     lea(ary2, Address(ary2, base_offset));
8158   }
8159 
8160   if (is_array_equ && is_char) {
8161     // arrays_equals when used for char[].
8162     shll(limit, 1);      // byte count != 0
8163   }
8164   movl(result, limit); // copy
8165 
8166   if (UseAVX >= 2) {
8167     // With AVX2, use 32-byte vector compare
8168     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8169 
8170     // Compare 32-byte vectors
8171     andl(result, 0x0000001f);  //   tail count (in bytes)
8172     andl(limit, 0xffffffe0);   // vector count (in bytes)
8173     jcc(Assembler::zero, COMPARE_TAIL);
8174 
8175     lea(ary1, Address(ary1, limit, Address::times_1));
8176     lea(ary2, Address(ary2, limit, Address::times_1));
8177     negptr(limit);
8178 
8179     bind(COMPARE_WIDE_VECTORS);
8180 
8181 #ifdef _LP64
8182     if (VM_Version::supports_avx512vlbw()) { // trying 64 bytes fast loop
8183       Label COMPARE_WIDE_VECTORS_LOOP_AVX2, COMPARE_WIDE_VECTORS_LOOP_AVX3;
8184 
8185       cmpl(limit, -64);
8186       jccb(Assembler::greater, COMPARE_WIDE_VECTORS_LOOP_AVX2);
8187 
8188       bind(COMPARE_WIDE_VECTORS_LOOP_AVX3); // the hottest loop
8189 
8190       evmovdquq(vec1, Address(ary1, limit, Address::times_1), Assembler::AVX_512bit);
8191       evpcmpeqb(k7, vec1, Address(ary2, limit, Address::times_1), Assembler::AVX_512bit);
8192       kortestql(k7, k7);
8193       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8194       addptr(limit, 64);  // update since we already compared at this addr
8195       cmpl(limit, -64);
8196       jccb(Assembler::lessEqual, COMPARE_WIDE_VECTORS_LOOP_AVX3);
8197 
8198       // At this point we may still need to compare -limit+result bytes.
8199       // We could execute the next two instruction and just continue via non-wide path:
8200       //  cmpl(limit, 0);
8201       //  jcc(Assembler::equal, COMPARE_TAIL);  // true
8202       // But since we stopped at the points ary{1,2}+limit which are
8203       // not farther than 64 bytes from the ends of arrays ary{1,2}+result
8204       // (|limit| <= 32 and result < 32),
8205       // we may just compare the last 64 bytes.
8206       //
8207       addptr(result, -64);   // it is safe, bc we just came from this area
8208       evmovdquq(vec1, Address(ary1, result, Address::times_1), Assembler::AVX_512bit);
8209       evpcmpeqb(k7, vec1, Address(ary2, result, Address::times_1), Assembler::AVX_512bit);
8210       kortestql(k7, k7);
8211       jcc(Assembler::aboveEqual, FALSE_LABEL);     // miscompare
8212 
8213       jmp(TRUE_LABEL);
8214 
8215       bind(COMPARE_WIDE_VECTORS_LOOP_AVX2);
8216 
8217     }//if (VM_Version::supports_avx512vlbw())
8218 #endif //_LP64
8219 
8220     vmovdqu(vec1, Address(ary1, limit, Address::times_1));
8221     vmovdqu(vec2, Address(ary2, limit, Address::times_1));
8222     vpxor(vec1, vec2);
8223 
8224     vptest(vec1, vec1);
8225     jcc(Assembler::notZero, FALSE_LABEL);
8226     addptr(limit, 32);
8227     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8228 
8229     testl(result, result);
8230     jcc(Assembler::zero, TRUE_LABEL);
8231 
8232     vmovdqu(vec1, Address(ary1, result, Address::times_1, -32));
8233     vmovdqu(vec2, Address(ary2, result, Address::times_1, -32));
8234     vpxor(vec1, vec2);
8235 
8236     vptest(vec1, vec1);
8237     jccb(Assembler::notZero, FALSE_LABEL);
8238     jmpb(TRUE_LABEL);
8239 
8240     bind(COMPARE_TAIL); // limit is zero
8241     movl(limit, result);
8242     // Fallthru to tail compare
8243   } else if (UseSSE42Intrinsics) {
8244     // With SSE4.2, use double quad vector compare
8245     Label COMPARE_WIDE_VECTORS, COMPARE_TAIL;
8246 
8247     // Compare 16-byte vectors
8248     andl(result, 0x0000000f);  //   tail count (in bytes)
8249     andl(limit, 0xfffffff0);   // vector count (in bytes)
8250     jcc(Assembler::zero, COMPARE_TAIL);
8251 
8252     lea(ary1, Address(ary1, limit, Address::times_1));
8253     lea(ary2, Address(ary2, limit, Address::times_1));
8254     negptr(limit);
8255 
8256     bind(COMPARE_WIDE_VECTORS);
8257     movdqu(vec1, Address(ary1, limit, Address::times_1));
8258     movdqu(vec2, Address(ary2, limit, Address::times_1));
8259     pxor(vec1, vec2);
8260 
8261     ptest(vec1, vec1);
8262     jcc(Assembler::notZero, FALSE_LABEL);
8263     addptr(limit, 16);
8264     jcc(Assembler::notZero, COMPARE_WIDE_VECTORS);
8265 
8266     testl(result, result);
8267     jcc(Assembler::zero, TRUE_LABEL);
8268 
8269     movdqu(vec1, Address(ary1, result, Address::times_1, -16));
8270     movdqu(vec2, Address(ary2, result, Address::times_1, -16));
8271     pxor(vec1, vec2);
8272 
8273     ptest(vec1, vec1);
8274     jccb(Assembler::notZero, FALSE_LABEL);
8275     jmpb(TRUE_LABEL);
8276 
8277     bind(COMPARE_TAIL); // limit is zero
8278     movl(limit, result);
8279     // Fallthru to tail compare
8280   }
8281 
8282   // Compare 4-byte vectors
8283   andl(limit, 0xfffffffc); // vector count (in bytes)
8284   jccb(Assembler::zero, COMPARE_CHAR);
8285 
8286   lea(ary1, Address(ary1, limit, Address::times_1));
8287   lea(ary2, Address(ary2, limit, Address::times_1));
8288   negptr(limit);
8289 
8290   bind(COMPARE_VECTORS);
8291   movl(chr, Address(ary1, limit, Address::times_1));
8292   cmpl(chr, Address(ary2, limit, Address::times_1));
8293   jccb(Assembler::notEqual, FALSE_LABEL);
8294   addptr(limit, 4);
8295   jcc(Assembler::notZero, COMPARE_VECTORS);
8296 
8297   // Compare trailing char (final 2 bytes), if any
8298   bind(COMPARE_CHAR);
8299   testl(result, 0x2);   // tail  char
8300   jccb(Assembler::zero, COMPARE_BYTE);
8301   load_unsigned_short(chr, Address(ary1, 0));
8302   load_unsigned_short(limit, Address(ary2, 0));
8303   cmpl(chr, limit);
8304   jccb(Assembler::notEqual, FALSE_LABEL);
8305 
8306   if (is_array_equ && is_char) {
8307     bind(COMPARE_BYTE);
8308   } else {
8309     lea(ary1, Address(ary1, 2));
8310     lea(ary2, Address(ary2, 2));
8311 
8312     bind(COMPARE_BYTE);
8313     testl(result, 0x1);   // tail  byte
8314     jccb(Assembler::zero, TRUE_LABEL);
8315     load_unsigned_byte(chr, Address(ary1, 0));
8316     load_unsigned_byte(limit, Address(ary2, 0));
8317     cmpl(chr, limit);
8318     jccb(Assembler::notEqual, FALSE_LABEL);
8319   }
8320   bind(TRUE_LABEL);
8321   movl(result, 1);   // return true
8322   jmpb(DONE);
8323 
8324   bind(FALSE_LABEL);
8325   xorl(result, result); // return false
8326 
8327   // That's it
8328   bind(DONE);
8329   if (UseAVX >= 2) {
8330     // clean upper bits of YMM registers
8331     vpxor(vec1, vec1);
8332     vpxor(vec2, vec2);
8333   }
8334 }
8335 
8336 #endif
8337 
8338 void MacroAssembler::generate_fill(BasicType t, bool aligned,
8339                                    Register to, Register value, Register count,
8340                                    Register rtmp, XMMRegister xtmp) {
8341   ShortBranchVerifier sbv(this);
8342   assert_different_registers(to, value, count, rtmp);
8343   Label L_exit, L_skip_align1, L_skip_align2, L_fill_byte;
8344   Label L_fill_2_bytes, L_fill_4_bytes;
8345 
8346   int shift = -1;
8347   switch (t) {
8348     case T_BYTE:
8349       shift = 2;
8350       break;
8351     case T_SHORT:
8352       shift = 1;
8353       break;
8354     case T_INT:
8355       shift = 0;
8356       break;
8357     default: ShouldNotReachHere();
8358   }
8359 
8360   if (t == T_BYTE) {
8361     andl(value, 0xff);
8362     movl(rtmp, value);
8363     shll(rtmp, 8);
8364     orl(value, rtmp);
8365   }
8366   if (t == T_SHORT) {
8367     andl(value, 0xffff);
8368   }
8369   if (t == T_BYTE || t == T_SHORT) {
8370     movl(rtmp, value);
8371     shll(rtmp, 16);
8372     orl(value, rtmp);
8373   }
8374 
8375   cmpl(count, 2<<shift); // Short arrays (< 8 bytes) fill by element
8376   jcc(Assembler::below, L_fill_4_bytes); // use unsigned cmp
8377   if (!UseUnalignedLoadStores && !aligned && (t == T_BYTE || t == T_SHORT)) {
8378     // align source address at 4 bytes address boundary
8379     if (t == T_BYTE) {
8380       // One byte misalignment happens only for byte arrays
8381       testptr(to, 1);
8382       jccb(Assembler::zero, L_skip_align1);
8383       movb(Address(to, 0), value);
8384       increment(to);
8385       decrement(count);
8386       BIND(L_skip_align1);
8387     }
8388     // Two bytes misalignment happens only for byte and short (char) arrays
8389     testptr(to, 2);
8390     jccb(Assembler::zero, L_skip_align2);
8391     movw(Address(to, 0), value);
8392     addptr(to, 2);
8393     subl(count, 1<<(shift-1));
8394     BIND(L_skip_align2);
8395   }
8396   if (UseSSE < 2) {
8397     Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8398     // Fill 32-byte chunks
8399     subl(count, 8 << shift);
8400     jcc(Assembler::less, L_check_fill_8_bytes);
8401     align(16);
8402 
8403     BIND(L_fill_32_bytes_loop);
8404 
8405     for (int i = 0; i < 32; i += 4) {
8406       movl(Address(to, i), value);
8407     }
8408 
8409     addptr(to, 32);
8410     subl(count, 8 << shift);
8411     jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8412     BIND(L_check_fill_8_bytes);
8413     addl(count, 8 << shift);
8414     jccb(Assembler::zero, L_exit);
8415     jmpb(L_fill_8_bytes);
8416 
8417     //
8418     // length is too short, just fill qwords
8419     //
8420     BIND(L_fill_8_bytes_loop);
8421     movl(Address(to, 0), value);
8422     movl(Address(to, 4), value);
8423     addptr(to, 8);
8424     BIND(L_fill_8_bytes);
8425     subl(count, 1 << (shift + 1));
8426     jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8427     // fall through to fill 4 bytes
8428   } else {
8429     Label L_fill_32_bytes;
8430     if (!UseUnalignedLoadStores) {
8431       // align to 8 bytes, we know we are 4 byte aligned to start
8432       testptr(to, 4);
8433       jccb(Assembler::zero, L_fill_32_bytes);
8434       movl(Address(to, 0), value);
8435       addptr(to, 4);
8436       subl(count, 1<<shift);
8437     }
8438     BIND(L_fill_32_bytes);
8439     {
8440       assert( UseSSE >= 2, "supported cpu only" );
8441       Label L_fill_32_bytes_loop, L_check_fill_8_bytes, L_fill_8_bytes_loop, L_fill_8_bytes;
8442       if (UseAVX > 2) {
8443         movl(rtmp, 0xffff);
8444         kmovwl(k1, rtmp);
8445       }
8446       movdl(xtmp, value);
8447       if (UseAVX > 2 && UseUnalignedLoadStores) {
8448         // Fill 64-byte chunks
8449         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8450         evpbroadcastd(xtmp, xtmp, Assembler::AVX_512bit);
8451 
8452         subl(count, 16 << shift);
8453         jcc(Assembler::less, L_check_fill_32_bytes);
8454         align(16);
8455 
8456         BIND(L_fill_64_bytes_loop);
8457         evmovdqul(Address(to, 0), xtmp, Assembler::AVX_512bit);
8458         addptr(to, 64);
8459         subl(count, 16 << shift);
8460         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8461 
8462         BIND(L_check_fill_32_bytes);
8463         addl(count, 8 << shift);
8464         jccb(Assembler::less, L_check_fill_8_bytes);
8465         vmovdqu(Address(to, 0), xtmp);
8466         addptr(to, 32);
8467         subl(count, 8 << shift);
8468 
8469         BIND(L_check_fill_8_bytes);
8470       } else if (UseAVX == 2 && UseUnalignedLoadStores) {
8471         // Fill 64-byte chunks
8472         Label L_fill_64_bytes_loop, L_check_fill_32_bytes;
8473         vpbroadcastd(xtmp, xtmp);
8474 
8475         subl(count, 16 << shift);
8476         jcc(Assembler::less, L_check_fill_32_bytes);
8477         align(16);
8478 
8479         BIND(L_fill_64_bytes_loop);
8480         vmovdqu(Address(to, 0), xtmp);
8481         vmovdqu(Address(to, 32), xtmp);
8482         addptr(to, 64);
8483         subl(count, 16 << shift);
8484         jcc(Assembler::greaterEqual, L_fill_64_bytes_loop);
8485 
8486         BIND(L_check_fill_32_bytes);
8487         addl(count, 8 << shift);
8488         jccb(Assembler::less, L_check_fill_8_bytes);
8489         vmovdqu(Address(to, 0), xtmp);
8490         addptr(to, 32);
8491         subl(count, 8 << shift);
8492 
8493         BIND(L_check_fill_8_bytes);
8494         // clean upper bits of YMM registers
8495         movdl(xtmp, value);
8496         pshufd(xtmp, xtmp, 0);
8497       } else {
8498         // Fill 32-byte chunks
8499         pshufd(xtmp, xtmp, 0);
8500 
8501         subl(count, 8 << shift);
8502         jcc(Assembler::less, L_check_fill_8_bytes);
8503         align(16);
8504 
8505         BIND(L_fill_32_bytes_loop);
8506 
8507         if (UseUnalignedLoadStores) {
8508           movdqu(Address(to, 0), xtmp);
8509           movdqu(Address(to, 16), xtmp);
8510         } else {
8511           movq(Address(to, 0), xtmp);
8512           movq(Address(to, 8), xtmp);
8513           movq(Address(to, 16), xtmp);
8514           movq(Address(to, 24), xtmp);
8515         }
8516 
8517         addptr(to, 32);
8518         subl(count, 8 << shift);
8519         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
8520 
8521         BIND(L_check_fill_8_bytes);
8522       }
8523       addl(count, 8 << shift);
8524       jccb(Assembler::zero, L_exit);
8525       jmpb(L_fill_8_bytes);
8526 
8527       //
8528       // length is too short, just fill qwords
8529       //
8530       BIND(L_fill_8_bytes_loop);
8531       movq(Address(to, 0), xtmp);
8532       addptr(to, 8);
8533       BIND(L_fill_8_bytes);
8534       subl(count, 1 << (shift + 1));
8535       jcc(Assembler::greaterEqual, L_fill_8_bytes_loop);
8536     }
8537   }
8538   // fill trailing 4 bytes
8539   BIND(L_fill_4_bytes);
8540   testl(count, 1<<shift);
8541   jccb(Assembler::zero, L_fill_2_bytes);
8542   movl(Address(to, 0), value);
8543   if (t == T_BYTE || t == T_SHORT) {
8544     addptr(to, 4);
8545     BIND(L_fill_2_bytes);
8546     // fill trailing 2 bytes
8547     testl(count, 1<<(shift-1));
8548     jccb(Assembler::zero, L_fill_byte);
8549     movw(Address(to, 0), value);
8550     if (t == T_BYTE) {
8551       addptr(to, 2);
8552       BIND(L_fill_byte);
8553       // fill trailing byte
8554       testl(count, 1);
8555       jccb(Assembler::zero, L_exit);
8556       movb(Address(to, 0), value);
8557     } else {
8558       BIND(L_fill_byte);
8559     }
8560   } else {
8561     BIND(L_fill_2_bytes);
8562   }
8563   BIND(L_exit);
8564 }
8565 
8566 // encode char[] to byte[] in ISO_8859_1
8567    //@HotSpotIntrinsicCandidate
8568    //private static int implEncodeISOArray(byte[] sa, int sp,
8569    //byte[] da, int dp, int len) {
8570    //  int i = 0;
8571    //  for (; i < len; i++) {
8572    //    char c = StringUTF16.getChar(sa, sp++);
8573    //    if (c > '\u00FF')
8574    //      break;
8575    //    da[dp++] = (byte)c;
8576    //  }
8577    //  return i;
8578    //}
8579 void MacroAssembler::encode_iso_array(Register src, Register dst, Register len,
8580   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
8581   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
8582   Register tmp5, Register result) {
8583 
8584   // rsi: src
8585   // rdi: dst
8586   // rdx: len
8587   // rcx: tmp5
8588   // rax: result
8589   ShortBranchVerifier sbv(this);
8590   assert_different_registers(src, dst, len, tmp5, result);
8591   Label L_done, L_copy_1_char, L_copy_1_char_exit;
8592 
8593   // set result
8594   xorl(result, result);
8595   // check for zero length
8596   testl(len, len);
8597   jcc(Assembler::zero, L_done);
8598 
8599   movl(result, len);
8600 
8601   // Setup pointers
8602   lea(src, Address(src, len, Address::times_2)); // char[]
8603   lea(dst, Address(dst, len, Address::times_1)); // byte[]
8604   negptr(len);
8605 
8606   if (UseSSE42Intrinsics || UseAVX >= 2) {
8607     Label L_chars_8_check, L_copy_8_chars, L_copy_8_chars_exit;
8608     Label L_chars_16_check, L_copy_16_chars, L_copy_16_chars_exit;
8609 
8610     if (UseAVX >= 2) {
8611       Label L_chars_32_check, L_copy_32_chars, L_copy_32_chars_exit;
8612       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8613       movdl(tmp1Reg, tmp5);
8614       vpbroadcastd(tmp1Reg, tmp1Reg);
8615       jmp(L_chars_32_check);
8616 
8617       bind(L_copy_32_chars);
8618       vmovdqu(tmp3Reg, Address(src, len, Address::times_2, -64));
8619       vmovdqu(tmp4Reg, Address(src, len, Address::times_2, -32));
8620       vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8621       vptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8622       jccb(Assembler::notZero, L_copy_32_chars_exit);
8623       vpackuswb(tmp3Reg, tmp3Reg, tmp4Reg, /* vector_len */ 1);
8624       vpermq(tmp4Reg, tmp3Reg, 0xD8, /* vector_len */ 1);
8625       vmovdqu(Address(dst, len, Address::times_1, -32), tmp4Reg);
8626 
8627       bind(L_chars_32_check);
8628       addptr(len, 32);
8629       jcc(Assembler::lessEqual, L_copy_32_chars);
8630 
8631       bind(L_copy_32_chars_exit);
8632       subptr(len, 16);
8633       jccb(Assembler::greater, L_copy_16_chars_exit);
8634 
8635     } else if (UseSSE42Intrinsics) {
8636       movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vector
8637       movdl(tmp1Reg, tmp5);
8638       pshufd(tmp1Reg, tmp1Reg, 0);
8639       jmpb(L_chars_16_check);
8640     }
8641 
8642     bind(L_copy_16_chars);
8643     if (UseAVX >= 2) {
8644       vmovdqu(tmp2Reg, Address(src, len, Address::times_2, -32));
8645       vptest(tmp2Reg, tmp1Reg);
8646       jcc(Assembler::notZero, L_copy_16_chars_exit);
8647       vpackuswb(tmp2Reg, tmp2Reg, tmp1Reg, /* vector_len */ 1);
8648       vpermq(tmp3Reg, tmp2Reg, 0xD8, /* vector_len */ 1);
8649     } else {
8650       if (UseAVX > 0) {
8651         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8652         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8653         vpor(tmp2Reg, tmp3Reg, tmp4Reg, /* vector_len */ 0);
8654       } else {
8655         movdqu(tmp3Reg, Address(src, len, Address::times_2, -32));
8656         por(tmp2Reg, tmp3Reg);
8657         movdqu(tmp4Reg, Address(src, len, Address::times_2, -16));
8658         por(tmp2Reg, tmp4Reg);
8659       }
8660       ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in  vector
8661       jccb(Assembler::notZero, L_copy_16_chars_exit);
8662       packuswb(tmp3Reg, tmp4Reg);
8663     }
8664     movdqu(Address(dst, len, Address::times_1, -16), tmp3Reg);
8665 
8666     bind(L_chars_16_check);
8667     addptr(len, 16);
8668     jcc(Assembler::lessEqual, L_copy_16_chars);
8669 
8670     bind(L_copy_16_chars_exit);
8671     if (UseAVX >= 2) {
8672       // clean upper bits of YMM registers
8673       vpxor(tmp2Reg, tmp2Reg);
8674       vpxor(tmp3Reg, tmp3Reg);
8675       vpxor(tmp4Reg, tmp4Reg);
8676       movdl(tmp1Reg, tmp5);
8677       pshufd(tmp1Reg, tmp1Reg, 0);
8678     }
8679     subptr(len, 8);
8680     jccb(Assembler::greater, L_copy_8_chars_exit);
8681 
8682     bind(L_copy_8_chars);
8683     movdqu(tmp3Reg, Address(src, len, Address::times_2, -16));
8684     ptest(tmp3Reg, tmp1Reg);
8685     jccb(Assembler::notZero, L_copy_8_chars_exit);
8686     packuswb(tmp3Reg, tmp1Reg);
8687     movq(Address(dst, len, Address::times_1, -8), tmp3Reg);
8688     addptr(len, 8);
8689     jccb(Assembler::lessEqual, L_copy_8_chars);
8690 
8691     bind(L_copy_8_chars_exit);
8692     subptr(len, 8);
8693     jccb(Assembler::zero, L_done);
8694   }
8695 
8696   bind(L_copy_1_char);
8697   load_unsigned_short(tmp5, Address(src, len, Address::times_2, 0));
8698   testl(tmp5, 0xff00);      // check if Unicode char
8699   jccb(Assembler::notZero, L_copy_1_char_exit);
8700   movb(Address(dst, len, Address::times_1, 0), tmp5);
8701   addptr(len, 1);
8702   jccb(Assembler::less, L_copy_1_char);
8703 
8704   bind(L_copy_1_char_exit);
8705   addptr(result, len); // len is negative count of not processed elements
8706 
8707   bind(L_done);
8708 }
8709 
8710 #ifdef _LP64
8711 /**
8712  * Helper for multiply_to_len().
8713  */
8714 void MacroAssembler::add2_with_carry(Register dest_hi, Register dest_lo, Register src1, Register src2) {
8715   addq(dest_lo, src1);
8716   adcq(dest_hi, 0);
8717   addq(dest_lo, src2);
8718   adcq(dest_hi, 0);
8719 }
8720 
8721 /**
8722  * Multiply 64 bit by 64 bit first loop.
8723  */
8724 void MacroAssembler::multiply_64_x_64_loop(Register x, Register xstart, Register x_xstart,
8725                                            Register y, Register y_idx, Register z,
8726                                            Register carry, Register product,
8727                                            Register idx, Register kdx) {
8728   //
8729   //  jlong carry, x[], y[], z[];
8730   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
8731   //    huge_128 product = y[idx] * x[xstart] + carry;
8732   //    z[kdx] = (jlong)product;
8733   //    carry  = (jlong)(product >>> 64);
8734   //  }
8735   //  z[xstart] = carry;
8736   //
8737 
8738   Label L_first_loop, L_first_loop_exit;
8739   Label L_one_x, L_one_y, L_multiply;
8740 
8741   decrementl(xstart);
8742   jcc(Assembler::negative, L_one_x);
8743 
8744   movq(x_xstart, Address(x, xstart, Address::times_4,  0));
8745   rorq(x_xstart, 32); // convert big-endian to little-endian
8746 
8747   bind(L_first_loop);
8748   decrementl(idx);
8749   jcc(Assembler::negative, L_first_loop_exit);
8750   decrementl(idx);
8751   jcc(Assembler::negative, L_one_y);
8752   movq(y_idx, Address(y, idx, Address::times_4,  0));
8753   rorq(y_idx, 32); // convert big-endian to little-endian
8754   bind(L_multiply);
8755   movq(product, x_xstart);
8756   mulq(y_idx); // product(rax) * y_idx -> rdx:rax
8757   addq(product, carry);
8758   adcq(rdx, 0);
8759   subl(kdx, 2);
8760   movl(Address(z, kdx, Address::times_4,  4), product);
8761   shrq(product, 32);
8762   movl(Address(z, kdx, Address::times_4,  0), product);
8763   movq(carry, rdx);
8764   jmp(L_first_loop);
8765 
8766   bind(L_one_y);
8767   movl(y_idx, Address(y,  0));
8768   jmp(L_multiply);
8769 
8770   bind(L_one_x);
8771   movl(x_xstart, Address(x,  0));
8772   jmp(L_first_loop);
8773 
8774   bind(L_first_loop_exit);
8775 }
8776 
8777 /**
8778  * Multiply 64 bit by 64 bit and add 128 bit.
8779  */
8780 void MacroAssembler::multiply_add_128_x_128(Register x_xstart, Register y, Register z,
8781                                             Register yz_idx, Register idx,
8782                                             Register carry, Register product, int offset) {
8783   //     huge_128 product = (y[idx] * x_xstart) + z[kdx] + carry;
8784   //     z[kdx] = (jlong)product;
8785 
8786   movq(yz_idx, Address(y, idx, Address::times_4,  offset));
8787   rorq(yz_idx, 32); // convert big-endian to little-endian
8788   movq(product, x_xstart);
8789   mulq(yz_idx);     // product(rax) * yz_idx -> rdx:product(rax)
8790   movq(yz_idx, Address(z, idx, Address::times_4,  offset));
8791   rorq(yz_idx, 32); // convert big-endian to little-endian
8792 
8793   add2_with_carry(rdx, product, carry, yz_idx);
8794 
8795   movl(Address(z, idx, Address::times_4,  offset+4), product);
8796   shrq(product, 32);
8797   movl(Address(z, idx, Address::times_4,  offset), product);
8798 
8799 }
8800 
8801 /**
8802  * Multiply 128 bit by 128 bit. Unrolled inner loop.
8803  */
8804 void MacroAssembler::multiply_128_x_128_loop(Register x_xstart, Register y, Register z,
8805                                              Register yz_idx, Register idx, Register jdx,
8806                                              Register carry, Register product,
8807                                              Register carry2) {
8808   //   jlong carry, x[], y[], z[];
8809   //   int kdx = ystart+1;
8810   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8811   //     huge_128 product = (y[idx+1] * x_xstart) + z[kdx+idx+1] + carry;
8812   //     z[kdx+idx+1] = (jlong)product;
8813   //     jlong carry2  = (jlong)(product >>> 64);
8814   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry2;
8815   //     z[kdx+idx] = (jlong)product;
8816   //     carry  = (jlong)(product >>> 64);
8817   //   }
8818   //   idx += 2;
8819   //   if (idx > 0) {
8820   //     product = (y[idx] * x_xstart) + z[kdx+idx] + carry;
8821   //     z[kdx+idx] = (jlong)product;
8822   //     carry  = (jlong)(product >>> 64);
8823   //   }
8824   //
8825 
8826   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8827 
8828   movl(jdx, idx);
8829   andl(jdx, 0xFFFFFFFC);
8830   shrl(jdx, 2);
8831 
8832   bind(L_third_loop);
8833   subl(jdx, 1);
8834   jcc(Assembler::negative, L_third_loop_exit);
8835   subl(idx, 4);
8836 
8837   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 8);
8838   movq(carry2, rdx);
8839 
8840   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry2, product, 0);
8841   movq(carry, rdx);
8842   jmp(L_third_loop);
8843 
8844   bind (L_third_loop_exit);
8845 
8846   andl (idx, 0x3);
8847   jcc(Assembler::zero, L_post_third_loop_done);
8848 
8849   Label L_check_1;
8850   subl(idx, 2);
8851   jcc(Assembler::negative, L_check_1);
8852 
8853   multiply_add_128_x_128(x_xstart, y, z, yz_idx, idx, carry, product, 0);
8854   movq(carry, rdx);
8855 
8856   bind (L_check_1);
8857   addl (idx, 0x2);
8858   andl (idx, 0x1);
8859   subl(idx, 1);
8860   jcc(Assembler::negative, L_post_third_loop_done);
8861 
8862   movl(yz_idx, Address(y, idx, Address::times_4,  0));
8863   movq(product, x_xstart);
8864   mulq(yz_idx); // product(rax) * yz_idx -> rdx:product(rax)
8865   movl(yz_idx, Address(z, idx, Address::times_4,  0));
8866 
8867   add2_with_carry(rdx, product, yz_idx, carry);
8868 
8869   movl(Address(z, idx, Address::times_4,  0), product);
8870   shrq(product, 32);
8871 
8872   shlq(rdx, 32);
8873   orq(product, rdx);
8874   movq(carry, product);
8875 
8876   bind(L_post_third_loop_done);
8877 }
8878 
8879 /**
8880  * Multiply 128 bit by 128 bit using BMI2. Unrolled inner loop.
8881  *
8882  */
8883 void MacroAssembler::multiply_128_x_128_bmi2_loop(Register y, Register z,
8884                                                   Register carry, Register carry2,
8885                                                   Register idx, Register jdx,
8886                                                   Register yz_idx1, Register yz_idx2,
8887                                                   Register tmp, Register tmp3, Register tmp4) {
8888   assert(UseBMI2Instructions, "should be used only when BMI2 is available");
8889 
8890   //   jlong carry, x[], y[], z[];
8891   //   int kdx = ystart+1;
8892   //   for (int idx=ystart-2; idx >= 0; idx -= 2) { // Third loop
8893   //     huge_128 tmp3 = (y[idx+1] * rdx) + z[kdx+idx+1] + carry;
8894   //     jlong carry2  = (jlong)(tmp3 >>> 64);
8895   //     huge_128 tmp4 = (y[idx]   * rdx) + z[kdx+idx] + carry2;
8896   //     carry  = (jlong)(tmp4 >>> 64);
8897   //     z[kdx+idx+1] = (jlong)tmp3;
8898   //     z[kdx+idx] = (jlong)tmp4;
8899   //   }
8900   //   idx += 2;
8901   //   if (idx > 0) {
8902   //     yz_idx1 = (y[idx] * rdx) + z[kdx+idx] + carry;
8903   //     z[kdx+idx] = (jlong)yz_idx1;
8904   //     carry  = (jlong)(yz_idx1 >>> 64);
8905   //   }
8906   //
8907 
8908   Label L_third_loop, L_third_loop_exit, L_post_third_loop_done;
8909 
8910   movl(jdx, idx);
8911   andl(jdx, 0xFFFFFFFC);
8912   shrl(jdx, 2);
8913 
8914   bind(L_third_loop);
8915   subl(jdx, 1);
8916   jcc(Assembler::negative, L_third_loop_exit);
8917   subl(idx, 4);
8918 
8919   movq(yz_idx1,  Address(y, idx, Address::times_4,  8));
8920   rorxq(yz_idx1, yz_idx1, 32); // convert big-endian to little-endian
8921   movq(yz_idx2, Address(y, idx, Address::times_4,  0));
8922   rorxq(yz_idx2, yz_idx2, 32);
8923 
8924   mulxq(tmp4, tmp3, yz_idx1);  //  yz_idx1 * rdx -> tmp4:tmp3
8925   mulxq(carry2, tmp, yz_idx2); //  yz_idx2 * rdx -> carry2:tmp
8926 
8927   movq(yz_idx1,  Address(z, idx, Address::times_4,  8));
8928   rorxq(yz_idx1, yz_idx1, 32);
8929   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8930   rorxq(yz_idx2, yz_idx2, 32);
8931 
8932   if (VM_Version::supports_adx()) {
8933     adcxq(tmp3, carry);
8934     adoxq(tmp3, yz_idx1);
8935 
8936     adcxq(tmp4, tmp);
8937     adoxq(tmp4, yz_idx2);
8938 
8939     movl(carry, 0); // does not affect flags
8940     adcxq(carry2, carry);
8941     adoxq(carry2, carry);
8942   } else {
8943     add2_with_carry(tmp4, tmp3, carry, yz_idx1);
8944     add2_with_carry(carry2, tmp4, tmp, yz_idx2);
8945   }
8946   movq(carry, carry2);
8947 
8948   movl(Address(z, idx, Address::times_4, 12), tmp3);
8949   shrq(tmp3, 32);
8950   movl(Address(z, idx, Address::times_4,  8), tmp3);
8951 
8952   movl(Address(z, idx, Address::times_4,  4), tmp4);
8953   shrq(tmp4, 32);
8954   movl(Address(z, idx, Address::times_4,  0), tmp4);
8955 
8956   jmp(L_third_loop);
8957 
8958   bind (L_third_loop_exit);
8959 
8960   andl (idx, 0x3);
8961   jcc(Assembler::zero, L_post_third_loop_done);
8962 
8963   Label L_check_1;
8964   subl(idx, 2);
8965   jcc(Assembler::negative, L_check_1);
8966 
8967   movq(yz_idx1, Address(y, idx, Address::times_4,  0));
8968   rorxq(yz_idx1, yz_idx1, 32);
8969   mulxq(tmp4, tmp3, yz_idx1); //  yz_idx1 * rdx -> tmp4:tmp3
8970   movq(yz_idx2, Address(z, idx, Address::times_4,  0));
8971   rorxq(yz_idx2, yz_idx2, 32);
8972 
8973   add2_with_carry(tmp4, tmp3, carry, yz_idx2);
8974 
8975   movl(Address(z, idx, Address::times_4,  4), tmp3);
8976   shrq(tmp3, 32);
8977   movl(Address(z, idx, Address::times_4,  0), tmp3);
8978   movq(carry, tmp4);
8979 
8980   bind (L_check_1);
8981   addl (idx, 0x2);
8982   andl (idx, 0x1);
8983   subl(idx, 1);
8984   jcc(Assembler::negative, L_post_third_loop_done);
8985   movl(tmp4, Address(y, idx, Address::times_4,  0));
8986   mulxq(carry2, tmp3, tmp4);  //  tmp4 * rdx -> carry2:tmp3
8987   movl(tmp4, Address(z, idx, Address::times_4,  0));
8988 
8989   add2_with_carry(carry2, tmp3, tmp4, carry);
8990 
8991   movl(Address(z, idx, Address::times_4,  0), tmp3);
8992   shrq(tmp3, 32);
8993 
8994   shlq(carry2, 32);
8995   orq(tmp3, carry2);
8996   movq(carry, tmp3);
8997 
8998   bind(L_post_third_loop_done);
8999 }
9000 
9001 /**
9002  * Code for BigInteger::multiplyToLen() instrinsic.
9003  *
9004  * rdi: x
9005  * rax: xlen
9006  * rsi: y
9007  * rcx: ylen
9008  * r8:  z
9009  * r11: zlen
9010  * r12: tmp1
9011  * r13: tmp2
9012  * r14: tmp3
9013  * r15: tmp4
9014  * rbx: tmp5
9015  *
9016  */
9017 void MacroAssembler::multiply_to_len(Register x, Register xlen, Register y, Register ylen, Register z, Register zlen,
9018                                      Register tmp1, Register tmp2, Register tmp3, Register tmp4, Register tmp5) {
9019   ShortBranchVerifier sbv(this);
9020   assert_different_registers(x, xlen, y, ylen, z, zlen, tmp1, tmp2, tmp3, tmp4, tmp5, rdx);
9021 
9022   push(tmp1);
9023   push(tmp2);
9024   push(tmp3);
9025   push(tmp4);
9026   push(tmp5);
9027 
9028   push(xlen);
9029   push(zlen);
9030 
9031   const Register idx = tmp1;
9032   const Register kdx = tmp2;
9033   const Register xstart = tmp3;
9034 
9035   const Register y_idx = tmp4;
9036   const Register carry = tmp5;
9037   const Register product  = xlen;
9038   const Register x_xstart = zlen;  // reuse register
9039 
9040   // First Loop.
9041   //
9042   //  final static long LONG_MASK = 0xffffffffL;
9043   //  int xstart = xlen - 1;
9044   //  int ystart = ylen - 1;
9045   //  long carry = 0;
9046   //  for (int idx=ystart, kdx=ystart+1+xstart; idx >= 0; idx-, kdx--) {
9047   //    long product = (y[idx] & LONG_MASK) * (x[xstart] & LONG_MASK) + carry;
9048   //    z[kdx] = (int)product;
9049   //    carry = product >>> 32;
9050   //  }
9051   //  z[xstart] = (int)carry;
9052   //
9053 
9054   movl(idx, ylen);      // idx = ylen;
9055   movl(kdx, zlen);      // kdx = xlen+ylen;
9056   xorq(carry, carry);   // carry = 0;
9057 
9058   Label L_done;
9059 
9060   movl(xstart, xlen);
9061   decrementl(xstart);
9062   jcc(Assembler::negative, L_done);
9063 
9064   multiply_64_x_64_loop(x, xstart, x_xstart, y, y_idx, z, carry, product, idx, kdx);
9065 
9066   Label L_second_loop;
9067   testl(kdx, kdx);
9068   jcc(Assembler::zero, L_second_loop);
9069 
9070   Label L_carry;
9071   subl(kdx, 1);
9072   jcc(Assembler::zero, L_carry);
9073 
9074   movl(Address(z, kdx, Address::times_4,  0), carry);
9075   shrq(carry, 32);
9076   subl(kdx, 1);
9077 
9078   bind(L_carry);
9079   movl(Address(z, kdx, Address::times_4,  0), carry);
9080 
9081   // Second and third (nested) loops.
9082   //
9083   // for (int i = xstart-1; i >= 0; i--) { // Second loop
9084   //   carry = 0;
9085   //   for (int jdx=ystart, k=ystart+1+i; jdx >= 0; jdx--, k--) { // Third loop
9086   //     long product = (y[jdx] & LONG_MASK) * (x[i] & LONG_MASK) +
9087   //                    (z[k] & LONG_MASK) + carry;
9088   //     z[k] = (int)product;
9089   //     carry = product >>> 32;
9090   //   }
9091   //   z[i] = (int)carry;
9092   // }
9093   //
9094   // i = xlen, j = tmp1, k = tmp2, carry = tmp5, x[i] = rdx
9095 
9096   const Register jdx = tmp1;
9097 
9098   bind(L_second_loop);
9099   xorl(carry, carry);    // carry = 0;
9100   movl(jdx, ylen);       // j = ystart+1
9101 
9102   subl(xstart, 1);       // i = xstart-1;
9103   jcc(Assembler::negative, L_done);
9104 
9105   push (z);
9106 
9107   Label L_last_x;
9108   lea(z, Address(z, xstart, Address::times_4, 4)); // z = z + k - j
9109   subl(xstart, 1);       // i = xstart-1;
9110   jcc(Assembler::negative, L_last_x);
9111 
9112   if (UseBMI2Instructions) {
9113     movq(rdx,  Address(x, xstart, Address::times_4,  0));
9114     rorxq(rdx, rdx, 32); // convert big-endian to little-endian
9115   } else {
9116     movq(x_xstart, Address(x, xstart, Address::times_4,  0));
9117     rorq(x_xstart, 32);  // convert big-endian to little-endian
9118   }
9119 
9120   Label L_third_loop_prologue;
9121   bind(L_third_loop_prologue);
9122 
9123   push (x);
9124   push (xstart);
9125   push (ylen);
9126 
9127 
9128   if (UseBMI2Instructions) {
9129     multiply_128_x_128_bmi2_loop(y, z, carry, x, jdx, ylen, product, tmp2, x_xstart, tmp3, tmp4);
9130   } else { // !UseBMI2Instructions
9131     multiply_128_x_128_loop(x_xstart, y, z, y_idx, jdx, ylen, carry, product, x);
9132   }
9133 
9134   pop(ylen);
9135   pop(xlen);
9136   pop(x);
9137   pop(z);
9138 
9139   movl(tmp3, xlen);
9140   addl(tmp3, 1);
9141   movl(Address(z, tmp3, Address::times_4,  0), carry);
9142   subl(tmp3, 1);
9143   jccb(Assembler::negative, L_done);
9144 
9145   shrq(carry, 32);
9146   movl(Address(z, tmp3, Address::times_4,  0), carry);
9147   jmp(L_second_loop);
9148 
9149   // Next infrequent code is moved outside loops.
9150   bind(L_last_x);
9151   if (UseBMI2Instructions) {
9152     movl(rdx, Address(x,  0));
9153   } else {
9154     movl(x_xstart, Address(x,  0));
9155   }
9156   jmp(L_third_loop_prologue);
9157 
9158   bind(L_done);
9159 
9160   pop(zlen);
9161   pop(xlen);
9162 
9163   pop(tmp5);
9164   pop(tmp4);
9165   pop(tmp3);
9166   pop(tmp2);
9167   pop(tmp1);
9168 }
9169 
9170 void MacroAssembler::vectorized_mismatch(Register obja, Register objb, Register length, Register log2_array_indxscale,
9171   Register result, Register tmp1, Register tmp2, XMMRegister rymm0, XMMRegister rymm1, XMMRegister rymm2){
9172   assert(UseSSE42Intrinsics, "SSE4.2 must be enabled.");
9173   Label VECTOR64_LOOP, VECTOR64_TAIL, VECTOR64_NOT_EQUAL, VECTOR32_TAIL;
9174   Label VECTOR32_LOOP, VECTOR16_LOOP, VECTOR8_LOOP, VECTOR4_LOOP;
9175   Label VECTOR16_TAIL, VECTOR8_TAIL, VECTOR4_TAIL;
9176   Label VECTOR32_NOT_EQUAL, VECTOR16_NOT_EQUAL, VECTOR8_NOT_EQUAL, VECTOR4_NOT_EQUAL;
9177   Label SAME_TILL_END, DONE;
9178   Label BYTES_LOOP, BYTES_TAIL, BYTES_NOT_EQUAL;
9179 
9180   //scale is in rcx in both Win64 and Unix
9181   ShortBranchVerifier sbv(this);
9182 
9183   shlq(length);
9184   xorq(result, result);
9185 
9186   if ((UseAVX > 2) &&
9187       VM_Version::supports_avx512vlbw()) {
9188     set_vector_masking();  // opening of the stub context for programming mask registers
9189     cmpq(length, 64);
9190     jcc(Assembler::less, VECTOR32_TAIL);
9191     movq(tmp1, length);
9192     andq(tmp1, 0x3F);      // tail count
9193     andq(length, ~(0x3F)); //vector count
9194 
9195     bind(VECTOR64_LOOP);
9196     // AVX512 code to compare 64 byte vectors.
9197     evmovdqub(rymm0, Address(obja, result), Assembler::AVX_512bit);
9198     evpcmpeqb(k7, rymm0, Address(objb, result), Assembler::AVX_512bit);
9199     kortestql(k7, k7);
9200     jcc(Assembler::aboveEqual, VECTOR64_NOT_EQUAL);     // mismatch
9201     addq(result, 64);
9202     subq(length, 64);
9203     jccb(Assembler::notZero, VECTOR64_LOOP);
9204 
9205     //bind(VECTOR64_TAIL);
9206     testq(tmp1, tmp1);
9207     jcc(Assembler::zero, SAME_TILL_END);
9208 
9209     bind(VECTOR64_TAIL);
9210     // AVX512 code to compare upto 63 byte vectors.
9211     // Save k1
9212     kmovql(k3, k1);
9213     mov64(tmp2, 0xFFFFFFFFFFFFFFFF);
9214     shlxq(tmp2, tmp2, tmp1);
9215     notq(tmp2);
9216     kmovql(k1, tmp2);
9217 
9218     evmovdqub(rymm0, k1, Address(obja, result), Assembler::AVX_512bit);
9219     evpcmpeqb(k7, k1, rymm0, Address(objb, result), Assembler::AVX_512bit);
9220 
9221     ktestql(k7, k1);
9222     // Restore k1
9223     kmovql(k1, k3);
9224     jcc(Assembler::below, SAME_TILL_END);     // not mismatch
9225 
9226     bind(VECTOR64_NOT_EQUAL);
9227     kmovql(tmp1, k7);
9228     notq(tmp1);
9229     tzcntq(tmp1, tmp1);
9230     addq(result, tmp1);
9231     shrq(result);
9232     jmp(DONE);
9233     bind(VECTOR32_TAIL);
9234     clear_vector_masking();   // closing of the stub context for programming mask registers
9235   }
9236 
9237   cmpq(length, 8);
9238   jcc(Assembler::equal, VECTOR8_LOOP);
9239   jcc(Assembler::less, VECTOR4_TAIL);
9240 
9241   if (UseAVX >= 2) {
9242 
9243     cmpq(length, 16);
9244     jcc(Assembler::equal, VECTOR16_LOOP);
9245     jcc(Assembler::less, VECTOR8_LOOP);
9246 
9247     cmpq(length, 32);
9248     jccb(Assembler::less, VECTOR16_TAIL);
9249 
9250     subq(length, 32);
9251     bind(VECTOR32_LOOP);
9252     vmovdqu(rymm0, Address(obja, result));
9253     vmovdqu(rymm1, Address(objb, result));
9254     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_256bit);
9255     vptest(rymm2, rymm2);
9256     jcc(Assembler::notZero, VECTOR32_NOT_EQUAL);//mismatch found
9257     addq(result, 32);
9258     subq(length, 32);
9259     jccb(Assembler::greaterEqual, VECTOR32_LOOP);
9260     addq(length, 32);
9261     jcc(Assembler::equal, SAME_TILL_END);
9262     //falling through if less than 32 bytes left //close the branch here.
9263 
9264     bind(VECTOR16_TAIL);
9265     cmpq(length, 16);
9266     jccb(Assembler::less, VECTOR8_TAIL);
9267     bind(VECTOR16_LOOP);
9268     movdqu(rymm0, Address(obja, result));
9269     movdqu(rymm1, Address(objb, result));
9270     vpxor(rymm2, rymm0, rymm1, Assembler::AVX_128bit);
9271     ptest(rymm2, rymm2);
9272     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9273     addq(result, 16);
9274     subq(length, 16);
9275     jcc(Assembler::equal, SAME_TILL_END);
9276     //falling through if less than 16 bytes left
9277   } else {//regular intrinsics
9278 
9279     cmpq(length, 16);
9280     jccb(Assembler::less, VECTOR8_TAIL);
9281 
9282     subq(length, 16);
9283     bind(VECTOR16_LOOP);
9284     movdqu(rymm0, Address(obja, result));
9285     movdqu(rymm1, Address(objb, result));
9286     pxor(rymm0, rymm1);
9287     ptest(rymm0, rymm0);
9288     jcc(Assembler::notZero, VECTOR16_NOT_EQUAL);//mismatch found
9289     addq(result, 16);
9290     subq(length, 16);
9291     jccb(Assembler::greaterEqual, VECTOR16_LOOP);
9292     addq(length, 16);
9293     jcc(Assembler::equal, SAME_TILL_END);
9294     //falling through if less than 16 bytes left
9295   }
9296 
9297   bind(VECTOR8_TAIL);
9298   cmpq(length, 8);
9299   jccb(Assembler::less, VECTOR4_TAIL);
9300   bind(VECTOR8_LOOP);
9301   movq(tmp1, Address(obja, result));
9302   movq(tmp2, Address(objb, result));
9303   xorq(tmp1, tmp2);
9304   testq(tmp1, tmp1);
9305   jcc(Assembler::notZero, VECTOR8_NOT_EQUAL);//mismatch found
9306   addq(result, 8);
9307   subq(length, 8);
9308   jcc(Assembler::equal, SAME_TILL_END);
9309   //falling through if less than 8 bytes left
9310 
9311   bind(VECTOR4_TAIL);
9312   cmpq(length, 4);
9313   jccb(Assembler::less, BYTES_TAIL);
9314   bind(VECTOR4_LOOP);
9315   movl(tmp1, Address(obja, result));
9316   xorl(tmp1, Address(objb, result));
9317   testl(tmp1, tmp1);
9318   jcc(Assembler::notZero, VECTOR4_NOT_EQUAL);//mismatch found
9319   addq(result, 4);
9320   subq(length, 4);
9321   jcc(Assembler::equal, SAME_TILL_END);
9322   //falling through if less than 4 bytes left
9323 
9324   bind(BYTES_TAIL);
9325   bind(BYTES_LOOP);
9326   load_unsigned_byte(tmp1, Address(obja, result));
9327   load_unsigned_byte(tmp2, Address(objb, result));
9328   xorl(tmp1, tmp2);
9329   testl(tmp1, tmp1);
9330   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9331   decq(length);
9332   jccb(Assembler::zero, SAME_TILL_END);
9333   incq(result);
9334   load_unsigned_byte(tmp1, Address(obja, result));
9335   load_unsigned_byte(tmp2, Address(objb, result));
9336   xorl(tmp1, tmp2);
9337   testl(tmp1, tmp1);
9338   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9339   decq(length);
9340   jccb(Assembler::zero, SAME_TILL_END);
9341   incq(result);
9342   load_unsigned_byte(tmp1, Address(obja, result));
9343   load_unsigned_byte(tmp2, Address(objb, result));
9344   xorl(tmp1, tmp2);
9345   testl(tmp1, tmp1);
9346   jccb(Assembler::notZero, BYTES_NOT_EQUAL);//mismatch found
9347   jmpb(SAME_TILL_END);
9348 
9349   if (UseAVX >= 2) {
9350     bind(VECTOR32_NOT_EQUAL);
9351     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_256bit);
9352     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_256bit);
9353     vpxor(rymm0, rymm0, rymm2, Assembler::AVX_256bit);
9354     vpmovmskb(tmp1, rymm0);
9355     bsfq(tmp1, tmp1);
9356     addq(result, tmp1);
9357     shrq(result);
9358     jmpb(DONE);
9359   }
9360 
9361   bind(VECTOR16_NOT_EQUAL);
9362   if (UseAVX >= 2) {
9363     vpcmpeqb(rymm2, rymm2, rymm2, Assembler::AVX_128bit);
9364     vpcmpeqb(rymm0, rymm0, rymm1, Assembler::AVX_128bit);
9365     pxor(rymm0, rymm2);
9366   } else {
9367     pcmpeqb(rymm2, rymm2);
9368     pxor(rymm0, rymm1);
9369     pcmpeqb(rymm0, rymm1);
9370     pxor(rymm0, rymm2);
9371   }
9372   pmovmskb(tmp1, rymm0);
9373   bsfq(tmp1, tmp1);
9374   addq(result, tmp1);
9375   shrq(result);
9376   jmpb(DONE);
9377 
9378   bind(VECTOR8_NOT_EQUAL);
9379   bind(VECTOR4_NOT_EQUAL);
9380   bsfq(tmp1, tmp1);
9381   shrq(tmp1, 3);
9382   addq(result, tmp1);
9383   bind(BYTES_NOT_EQUAL);
9384   shrq(result);
9385   jmpb(DONE);
9386 
9387   bind(SAME_TILL_END);
9388   mov64(result, -1);
9389 
9390   bind(DONE);
9391 }
9392 
9393 //Helper functions for square_to_len()
9394 
9395 /**
9396  * Store the squares of x[], right shifted one bit (divided by 2) into z[]
9397  * Preserves x and z and modifies rest of the registers.
9398  */
9399 void MacroAssembler::square_rshift(Register x, Register xlen, Register z, Register tmp1, Register tmp3, Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9400   // Perform square and right shift by 1
9401   // Handle odd xlen case first, then for even xlen do the following
9402   // jlong carry = 0;
9403   // for (int j=0, i=0; j < xlen; j+=2, i+=4) {
9404   //     huge_128 product = x[j:j+1] * x[j:j+1];
9405   //     z[i:i+1] = (carry << 63) | (jlong)(product >>> 65);
9406   //     z[i+2:i+3] = (jlong)(product >>> 1);
9407   //     carry = (jlong)product;
9408   // }
9409 
9410   xorq(tmp5, tmp5);     // carry
9411   xorq(rdxReg, rdxReg);
9412   xorl(tmp1, tmp1);     // index for x
9413   xorl(tmp4, tmp4);     // index for z
9414 
9415   Label L_first_loop, L_first_loop_exit;
9416 
9417   testl(xlen, 1);
9418   jccb(Assembler::zero, L_first_loop); //jump if xlen is even
9419 
9420   // Square and right shift by 1 the odd element using 32 bit multiply
9421   movl(raxReg, Address(x, tmp1, Address::times_4, 0));
9422   imulq(raxReg, raxReg);
9423   shrq(raxReg, 1);
9424   adcq(tmp5, 0);
9425   movq(Address(z, tmp4, Address::times_4, 0), raxReg);
9426   incrementl(tmp1);
9427   addl(tmp4, 2);
9428 
9429   // Square and  right shift by 1 the rest using 64 bit multiply
9430   bind(L_first_loop);
9431   cmpptr(tmp1, xlen);
9432   jccb(Assembler::equal, L_first_loop_exit);
9433 
9434   // Square
9435   movq(raxReg, Address(x, tmp1, Address::times_4,  0));
9436   rorq(raxReg, 32);    // convert big-endian to little-endian
9437   mulq(raxReg);        // 64-bit multiply rax * rax -> rdx:rax
9438 
9439   // Right shift by 1 and save carry
9440   shrq(tmp5, 1);       // rdx:rax:tmp5 = (tmp5:rdx:rax) >>> 1
9441   rcrq(rdxReg, 1);
9442   rcrq(raxReg, 1);
9443   adcq(tmp5, 0);
9444 
9445   // Store result in z
9446   movq(Address(z, tmp4, Address::times_4, 0), rdxReg);
9447   movq(Address(z, tmp4, Address::times_4, 8), raxReg);
9448 
9449   // Update indices for x and z
9450   addl(tmp1, 2);
9451   addl(tmp4, 4);
9452   jmp(L_first_loop);
9453 
9454   bind(L_first_loop_exit);
9455 }
9456 
9457 
9458 /**
9459  * Perform the following multiply add operation using BMI2 instructions
9460  * carry:sum = sum + op1*op2 + carry
9461  * op2 should be in rdx
9462  * op2 is preserved, all other registers are modified
9463  */
9464 void MacroAssembler::multiply_add_64_bmi2(Register sum, Register op1, Register op2, Register carry, Register tmp2) {
9465   // assert op2 is rdx
9466   mulxq(tmp2, op1, op1);  //  op1 * op2 -> tmp2:op1
9467   addq(sum, carry);
9468   adcq(tmp2, 0);
9469   addq(sum, op1);
9470   adcq(tmp2, 0);
9471   movq(carry, tmp2);
9472 }
9473 
9474 /**
9475  * Perform the following multiply add operation:
9476  * carry:sum = sum + op1*op2 + carry
9477  * Preserves op1, op2 and modifies rest of registers
9478  */
9479 void MacroAssembler::multiply_add_64(Register sum, Register op1, Register op2, Register carry, Register rdxReg, Register raxReg) {
9480   // rdx:rax = op1 * op2
9481   movq(raxReg, op2);
9482   mulq(op1);
9483 
9484   //  rdx:rax = sum + carry + rdx:rax
9485   addq(sum, carry);
9486   adcq(rdxReg, 0);
9487   addq(sum, raxReg);
9488   adcq(rdxReg, 0);
9489 
9490   // carry:sum = rdx:sum
9491   movq(carry, rdxReg);
9492 }
9493 
9494 /**
9495  * Add 64 bit long carry into z[] with carry propogation.
9496  * Preserves z and carry register values and modifies rest of registers.
9497  *
9498  */
9499 void MacroAssembler::add_one_64(Register z, Register zlen, Register carry, Register tmp1) {
9500   Label L_fourth_loop, L_fourth_loop_exit;
9501 
9502   movl(tmp1, 1);
9503   subl(zlen, 2);
9504   addq(Address(z, zlen, Address::times_4, 0), carry);
9505 
9506   bind(L_fourth_loop);
9507   jccb(Assembler::carryClear, L_fourth_loop_exit);
9508   subl(zlen, 2);
9509   jccb(Assembler::negative, L_fourth_loop_exit);
9510   addq(Address(z, zlen, Address::times_4, 0), tmp1);
9511   jmp(L_fourth_loop);
9512   bind(L_fourth_loop_exit);
9513 }
9514 
9515 /**
9516  * Shift z[] left by 1 bit.
9517  * Preserves x, len, z and zlen registers and modifies rest of the registers.
9518  *
9519  */
9520 void MacroAssembler::lshift_by_1(Register x, Register len, Register z, Register zlen, Register tmp1, Register tmp2, Register tmp3, Register tmp4) {
9521 
9522   Label L_fifth_loop, L_fifth_loop_exit;
9523 
9524   // Fifth loop
9525   // Perform primitiveLeftShift(z, zlen, 1)
9526 
9527   const Register prev_carry = tmp1;
9528   const Register new_carry = tmp4;
9529   const Register value = tmp2;
9530   const Register zidx = tmp3;
9531 
9532   // int zidx, carry;
9533   // long value;
9534   // carry = 0;
9535   // for (zidx = zlen-2; zidx >=0; zidx -= 2) {
9536   //    (carry:value)  = (z[i] << 1) | carry ;
9537   //    z[i] = value;
9538   // }
9539 
9540   movl(zidx, zlen);
9541   xorl(prev_carry, prev_carry); // clear carry flag and prev_carry register
9542 
9543   bind(L_fifth_loop);
9544   decl(zidx);  // Use decl to preserve carry flag
9545   decl(zidx);
9546   jccb(Assembler::negative, L_fifth_loop_exit);
9547 
9548   if (UseBMI2Instructions) {
9549      movq(value, Address(z, zidx, Address::times_4, 0));
9550      rclq(value, 1);
9551      rorxq(value, value, 32);
9552      movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9553   }
9554   else {
9555     // clear new_carry
9556     xorl(new_carry, new_carry);
9557 
9558     // Shift z[i] by 1, or in previous carry and save new carry
9559     movq(value, Address(z, zidx, Address::times_4, 0));
9560     shlq(value, 1);
9561     adcl(new_carry, 0);
9562 
9563     orq(value, prev_carry);
9564     rorq(value, 0x20);
9565     movq(Address(z, zidx, Address::times_4,  0), value);  // Store back in big endian form
9566 
9567     // Set previous carry = new carry
9568     movl(prev_carry, new_carry);
9569   }
9570   jmp(L_fifth_loop);
9571 
9572   bind(L_fifth_loop_exit);
9573 }
9574 
9575 
9576 /**
9577  * Code for BigInteger::squareToLen() intrinsic
9578  *
9579  * rdi: x
9580  * rsi: len
9581  * r8:  z
9582  * rcx: zlen
9583  * r12: tmp1
9584  * r13: tmp2
9585  * r14: tmp3
9586  * r15: tmp4
9587  * rbx: tmp5
9588  *
9589  */
9590 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) {
9591 
9592   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;
9593   push(tmp1);
9594   push(tmp2);
9595   push(tmp3);
9596   push(tmp4);
9597   push(tmp5);
9598 
9599   // First loop
9600   // Store the squares, right shifted one bit (i.e., divided by 2).
9601   square_rshift(x, len, z, tmp1, tmp3, tmp4, tmp5, rdxReg, raxReg);
9602 
9603   // Add in off-diagonal sums.
9604   //
9605   // Second, third (nested) and fourth loops.
9606   // zlen +=2;
9607   // for (int xidx=len-2,zidx=zlen-4; xidx > 0; xidx-=2,zidx-=4) {
9608   //    carry = 0;
9609   //    long op2 = x[xidx:xidx+1];
9610   //    for (int j=xidx-2,k=zidx; j >= 0; j-=2) {
9611   //       k -= 2;
9612   //       long op1 = x[j:j+1];
9613   //       long sum = z[k:k+1];
9614   //       carry:sum = multiply_add_64(sum, op1, op2, carry, tmp_regs);
9615   //       z[k:k+1] = sum;
9616   //    }
9617   //    add_one_64(z, k, carry, tmp_regs);
9618   // }
9619 
9620   const Register carry = tmp5;
9621   const Register sum = tmp3;
9622   const Register op1 = tmp4;
9623   Register op2 = tmp2;
9624 
9625   push(zlen);
9626   push(len);
9627   addl(zlen,2);
9628   bind(L_second_loop);
9629   xorq(carry, carry);
9630   subl(zlen, 4);
9631   subl(len, 2);
9632   push(zlen);
9633   push(len);
9634   cmpl(len, 0);
9635   jccb(Assembler::lessEqual, L_second_loop_exit);
9636 
9637   // Multiply an array by one 64 bit long.
9638   if (UseBMI2Instructions) {
9639     op2 = rdxReg;
9640     movq(op2, Address(x, len, Address::times_4,  0));
9641     rorxq(op2, op2, 32);
9642   }
9643   else {
9644     movq(op2, Address(x, len, Address::times_4,  0));
9645     rorq(op2, 32);
9646   }
9647 
9648   bind(L_third_loop);
9649   decrementl(len);
9650   jccb(Assembler::negative, L_third_loop_exit);
9651   decrementl(len);
9652   jccb(Assembler::negative, L_last_x);
9653 
9654   movq(op1, Address(x, len, Address::times_4,  0));
9655   rorq(op1, 32);
9656 
9657   bind(L_multiply);
9658   subl(zlen, 2);
9659   movq(sum, Address(z, zlen, Address::times_4,  0));
9660 
9661   // Multiply 64 bit by 64 bit and add 64 bits lower half and upper 64 bits as carry.
9662   if (UseBMI2Instructions) {
9663     multiply_add_64_bmi2(sum, op1, op2, carry, tmp2);
9664   }
9665   else {
9666     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9667   }
9668 
9669   movq(Address(z, zlen, Address::times_4, 0), sum);
9670 
9671   jmp(L_third_loop);
9672   bind(L_third_loop_exit);
9673 
9674   // Fourth loop
9675   // Add 64 bit long carry into z with carry propogation.
9676   // Uses offsetted zlen.
9677   add_one_64(z, zlen, carry, tmp1);
9678 
9679   pop(len);
9680   pop(zlen);
9681   jmp(L_second_loop);
9682 
9683   // Next infrequent code is moved outside loops.
9684   bind(L_last_x);
9685   movl(op1, Address(x, 0));
9686   jmp(L_multiply);
9687 
9688   bind(L_second_loop_exit);
9689   pop(len);
9690   pop(zlen);
9691   pop(len);
9692   pop(zlen);
9693 
9694   // Fifth loop
9695   // Shift z left 1 bit.
9696   lshift_by_1(x, len, z, zlen, tmp1, tmp2, tmp3, tmp4);
9697 
9698   // z[zlen-1] |= x[len-1] & 1;
9699   movl(tmp3, Address(x, len, Address::times_4, -4));
9700   andl(tmp3, 1);
9701   orl(Address(z, zlen, Address::times_4,  -4), tmp3);
9702 
9703   pop(tmp5);
9704   pop(tmp4);
9705   pop(tmp3);
9706   pop(tmp2);
9707   pop(tmp1);
9708 }
9709 
9710 /**
9711  * Helper function for mul_add()
9712  * Multiply the in[] by int k and add to out[] starting at offset offs using
9713  * 128 bit by 32 bit multiply and return the carry in tmp5.
9714  * Only quad int aligned length of in[] is operated on in this function.
9715  * k is in rdxReg for BMI2Instructions, for others it is in tmp2.
9716  * This function preserves out, in and k registers.
9717  * len and offset point to the appropriate index in "in" & "out" correspondingly
9718  * tmp5 has the carry.
9719  * other registers are temporary and are modified.
9720  *
9721  */
9722 void MacroAssembler::mul_add_128_x_32_loop(Register out, Register in,
9723   Register offset, Register len, Register tmp1, Register tmp2, Register tmp3,
9724   Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9725 
9726   Label L_first_loop, L_first_loop_exit;
9727 
9728   movl(tmp1, len);
9729   shrl(tmp1, 2);
9730 
9731   bind(L_first_loop);
9732   subl(tmp1, 1);
9733   jccb(Assembler::negative, L_first_loop_exit);
9734 
9735   subl(len, 4);
9736   subl(offset, 4);
9737 
9738   Register op2 = tmp2;
9739   const Register sum = tmp3;
9740   const Register op1 = tmp4;
9741   const Register carry = tmp5;
9742 
9743   if (UseBMI2Instructions) {
9744     op2 = rdxReg;
9745   }
9746 
9747   movq(op1, Address(in, len, Address::times_4,  8));
9748   rorq(op1, 32);
9749   movq(sum, Address(out, offset, Address::times_4,  8));
9750   rorq(sum, 32);
9751   if (UseBMI2Instructions) {
9752     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9753   }
9754   else {
9755     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9756   }
9757   // Store back in big endian from little endian
9758   rorq(sum, 0x20);
9759   movq(Address(out, offset, Address::times_4,  8), sum);
9760 
9761   movq(op1, Address(in, len, Address::times_4,  0));
9762   rorq(op1, 32);
9763   movq(sum, Address(out, offset, Address::times_4,  0));
9764   rorq(sum, 32);
9765   if (UseBMI2Instructions) {
9766     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9767   }
9768   else {
9769     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9770   }
9771   // Store back in big endian from little endian
9772   rorq(sum, 0x20);
9773   movq(Address(out, offset, Address::times_4,  0), sum);
9774 
9775   jmp(L_first_loop);
9776   bind(L_first_loop_exit);
9777 }
9778 
9779 /**
9780  * Code for BigInteger::mulAdd() intrinsic
9781  *
9782  * rdi: out
9783  * rsi: in
9784  * r11: offs (out.length - offset)
9785  * rcx: len
9786  * r8:  k
9787  * r12: tmp1
9788  * r13: tmp2
9789  * r14: tmp3
9790  * r15: tmp4
9791  * rbx: tmp5
9792  * Multiply the in[] by word k and add to out[], return the carry in rax
9793  */
9794 void MacroAssembler::mul_add(Register out, Register in, Register offs,
9795    Register len, Register k, Register tmp1, Register tmp2, Register tmp3,
9796    Register tmp4, Register tmp5, Register rdxReg, Register raxReg) {
9797 
9798   Label L_carry, L_last_in, L_done;
9799 
9800 // carry = 0;
9801 // for (int j=len-1; j >= 0; j--) {
9802 //    long product = (in[j] & LONG_MASK) * kLong +
9803 //                   (out[offs] & LONG_MASK) + carry;
9804 //    out[offs--] = (int)product;
9805 //    carry = product >>> 32;
9806 // }
9807 //
9808   push(tmp1);
9809   push(tmp2);
9810   push(tmp3);
9811   push(tmp4);
9812   push(tmp5);
9813 
9814   Register op2 = tmp2;
9815   const Register sum = tmp3;
9816   const Register op1 = tmp4;
9817   const Register carry =  tmp5;
9818 
9819   if (UseBMI2Instructions) {
9820     op2 = rdxReg;
9821     movl(op2, k);
9822   }
9823   else {
9824     movl(op2, k);
9825   }
9826 
9827   xorq(carry, carry);
9828 
9829   //First loop
9830 
9831   //Multiply in[] by k in a 4 way unrolled loop using 128 bit by 32 bit multiply
9832   //The carry is in tmp5
9833   mul_add_128_x_32_loop(out, in, offs, len, tmp1, tmp2, tmp3, tmp4, tmp5, rdxReg, raxReg);
9834 
9835   //Multiply the trailing in[] entry using 64 bit by 32 bit, if any
9836   decrementl(len);
9837   jccb(Assembler::negative, L_carry);
9838   decrementl(len);
9839   jccb(Assembler::negative, L_last_in);
9840 
9841   movq(op1, Address(in, len, Address::times_4,  0));
9842   rorq(op1, 32);
9843 
9844   subl(offs, 2);
9845   movq(sum, Address(out, offs, Address::times_4,  0));
9846   rorq(sum, 32);
9847 
9848   if (UseBMI2Instructions) {
9849     multiply_add_64_bmi2(sum, op1, op2, carry, raxReg);
9850   }
9851   else {
9852     multiply_add_64(sum, op1, op2, carry, rdxReg, raxReg);
9853   }
9854 
9855   // Store back in big endian from little endian
9856   rorq(sum, 0x20);
9857   movq(Address(out, offs, Address::times_4,  0), sum);
9858 
9859   testl(len, len);
9860   jccb(Assembler::zero, L_carry);
9861 
9862   //Multiply the last in[] entry, if any
9863   bind(L_last_in);
9864   movl(op1, Address(in, 0));
9865   movl(sum, Address(out, offs, Address::times_4,  -4));
9866 
9867   movl(raxReg, k);
9868   mull(op1); //tmp4 * eax -> edx:eax
9869   addl(sum, carry);
9870   adcl(rdxReg, 0);
9871   addl(sum, raxReg);
9872   adcl(rdxReg, 0);
9873   movl(carry, rdxReg);
9874 
9875   movl(Address(out, offs, Address::times_4,  -4), sum);
9876 
9877   bind(L_carry);
9878   //return tmp5/carry as carry in rax
9879   movl(rax, carry);
9880 
9881   bind(L_done);
9882   pop(tmp5);
9883   pop(tmp4);
9884   pop(tmp3);
9885   pop(tmp2);
9886   pop(tmp1);
9887 }
9888 #endif
9889 
9890 /**
9891  * Emits code to update CRC-32 with a byte value according to constants in table
9892  *
9893  * @param [in,out]crc   Register containing the crc.
9894  * @param [in]val       Register containing the byte to fold into the CRC.
9895  * @param [in]table     Register containing the table of crc constants.
9896  *
9897  * uint32_t crc;
9898  * val = crc_table[(val ^ crc) & 0xFF];
9899  * crc = val ^ (crc >> 8);
9900  *
9901  */
9902 void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) {
9903   xorl(val, crc);
9904   andl(val, 0xFF);
9905   shrl(crc, 8); // unsigned shift
9906   xorl(crc, Address(table, val, Address::times_4, 0));
9907 }
9908 
9909 /**
9910 * Fold four 128-bit data chunks
9911 */
9912 void MacroAssembler::fold_128bit_crc32_avx512(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9913   evpclmulhdq(xtmp, xK, xcrc, Assembler::AVX_512bit); // [123:64]
9914   evpclmulldq(xcrc, xK, xcrc, Assembler::AVX_512bit); // [63:0]
9915   evpxorq(xcrc, xcrc, Address(buf, offset), Assembler::AVX_512bit /* vector_len */);
9916   evpxorq(xcrc, xcrc, xtmp, Assembler::AVX_512bit /* vector_len */);
9917 }
9918 
9919 /**
9920  * Fold 128-bit data chunk
9921  */
9922 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) {
9923   if (UseAVX > 0) {
9924     vpclmulhdq(xtmp, xK, xcrc); // [123:64]
9925     vpclmulldq(xcrc, xK, xcrc); // [63:0]
9926     vpxor(xcrc, xcrc, Address(buf, offset), 0 /* vector_len */);
9927     pxor(xcrc, xtmp);
9928   } else {
9929     movdqa(xtmp, xcrc);
9930     pclmulhdq(xtmp, xK);   // [123:64]
9931     pclmulldq(xcrc, xK);   // [63:0]
9932     pxor(xcrc, xtmp);
9933     movdqu(xtmp, Address(buf, offset));
9934     pxor(xcrc, xtmp);
9935   }
9936 }
9937 
9938 void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) {
9939   if (UseAVX > 0) {
9940     vpclmulhdq(xtmp, xK, xcrc);
9941     vpclmulldq(xcrc, xK, xcrc);
9942     pxor(xcrc, xbuf);
9943     pxor(xcrc, xtmp);
9944   } else {
9945     movdqa(xtmp, xcrc);
9946     pclmulhdq(xtmp, xK);
9947     pclmulldq(xcrc, xK);
9948     pxor(xcrc, xbuf);
9949     pxor(xcrc, xtmp);
9950   }
9951 }
9952 
9953 /**
9954  * 8-bit folds to compute 32-bit CRC
9955  *
9956  * uint64_t xcrc;
9957  * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8);
9958  */
9959 void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) {
9960   movdl(tmp, xcrc);
9961   andl(tmp, 0xFF);
9962   movdl(xtmp, Address(table, tmp, Address::times_4, 0));
9963   psrldq(xcrc, 1); // unsigned shift one byte
9964   pxor(xcrc, xtmp);
9965 }
9966 
9967 /**
9968  * uint32_t crc;
9969  * timesXtoThe32[crc & 0xFF] ^ (crc >> 8);
9970  */
9971 void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) {
9972   movl(tmp, crc);
9973   andl(tmp, 0xFF);
9974   shrl(crc, 8);
9975   xorl(crc, Address(table, tmp, Address::times_4, 0));
9976 }
9977 
9978 /**
9979  * @param crc   register containing existing CRC (32-bit)
9980  * @param buf   register pointing to input byte buffer (byte*)
9981  * @param len   register containing number of bytes
9982  * @param table register that will contain address of CRC table
9983  * @param tmp   scratch register
9984  */
9985 void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) {
9986   assert_different_registers(crc, buf, len, table, tmp, rax);
9987 
9988   Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned;
9989   Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop;
9990 
9991   // For EVEX with VL and BW, provide a standard mask, VL = 128 will guide the merge
9992   // context for the registers used, where all instructions below are using 128-bit mode
9993   // On EVEX without VL and BW, these instructions will all be AVX.
9994   if (VM_Version::supports_avx512vlbw()) {
9995     movl(tmp, 0xffff);
9996     kmovwl(k1, tmp);
9997   }
9998 
9999   lea(table, ExternalAddress(StubRoutines::crc_table_addr()));
10000   notl(crc); // ~crc
10001   cmpl(len, 16);
10002   jcc(Assembler::less, L_tail);
10003 
10004   // Align buffer to 16 bytes
10005   movl(tmp, buf);
10006   andl(tmp, 0xF);
10007   jccb(Assembler::zero, L_aligned);
10008   subl(tmp,  16);
10009   addl(len, tmp);
10010 
10011   align(4);
10012   BIND(L_align_loop);
10013   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10014   update_byte_crc32(crc, rax, table);
10015   increment(buf);
10016   incrementl(tmp);
10017   jccb(Assembler::less, L_align_loop);
10018 
10019   BIND(L_aligned);
10020   movl(tmp, len); // save
10021   shrl(len, 4);
10022   jcc(Assembler::zero, L_tail_restore);
10023 
10024   // Fold total 512 bits of polynomial on each iteration
10025   if (VM_Version::supports_vpclmulqdq()) {
10026     Label Parallel_loop, L_No_Parallel;
10027 
10028     cmpl(len, 8);
10029     jccb(Assembler::less, L_No_Parallel);
10030 
10031     movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10032     evmovdquq(xmm1, Address(buf, 0), Assembler::AVX_512bit);
10033     movdl(xmm5, crc);
10034     evpxorq(xmm1, xmm1, xmm5, Assembler::AVX_512bit);
10035     addptr(buf, 64);
10036     subl(len, 7);
10037     evshufi64x2(xmm0, xmm0, xmm0, 0x00, Assembler::AVX_512bit); //propagate the mask from 128 bits to 512 bits
10038 
10039     BIND(Parallel_loop);
10040     fold_128bit_crc32_avx512(xmm1, xmm0, xmm5, buf, 0);
10041     addptr(buf, 64);
10042     subl(len, 4);
10043     jcc(Assembler::greater, Parallel_loop);
10044 
10045     vextracti64x2(xmm2, xmm1, 0x01);
10046     vextracti64x2(xmm3, xmm1, 0x02);
10047     vextracti64x2(xmm4, xmm1, 0x03);
10048     jmp(L_fold_512b);
10049 
10050     BIND(L_No_Parallel);
10051   }
10052   // Fold crc into first bytes of vector
10053   movdqa(xmm1, Address(buf, 0));
10054   movdl(rax, xmm1);
10055   xorl(crc, rax);
10056   if (VM_Version::supports_sse4_1()) {
10057     pinsrd(xmm1, crc, 0);
10058   } else {
10059     pinsrw(xmm1, crc, 0);
10060     shrl(crc, 16);
10061     pinsrw(xmm1, crc, 1);
10062   }
10063   addptr(buf, 16);
10064   subl(len, 4); // len > 0
10065   jcc(Assembler::less, L_fold_tail);
10066 
10067   movdqa(xmm2, Address(buf,  0));
10068   movdqa(xmm3, Address(buf, 16));
10069   movdqa(xmm4, Address(buf, 32));
10070   addptr(buf, 48);
10071   subl(len, 3);
10072   jcc(Assembler::lessEqual, L_fold_512b);
10073 
10074   // Fold total 512 bits of polynomial on each iteration,
10075   // 128 bits per each of 4 parallel streams.
10076   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32));
10077 
10078   align(32);
10079   BIND(L_fold_512b_loop);
10080   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10081   fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16);
10082   fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32);
10083   fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48);
10084   addptr(buf, 64);
10085   subl(len, 4);
10086   jcc(Assembler::greater, L_fold_512b_loop);
10087 
10088   // Fold 512 bits to 128 bits.
10089   BIND(L_fold_512b);
10090   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10091   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2);
10092   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3);
10093   fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4);
10094 
10095   // Fold the rest of 128 bits data chunks
10096   BIND(L_fold_tail);
10097   addl(len, 3);
10098   jccb(Assembler::lessEqual, L_fold_128b);
10099   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16));
10100 
10101   BIND(L_fold_tail_loop);
10102   fold_128bit_crc32(xmm1, xmm0, xmm5, buf,  0);
10103   addptr(buf, 16);
10104   decrementl(len);
10105   jccb(Assembler::greater, L_fold_tail_loop);
10106 
10107   // Fold 128 bits in xmm1 down into 32 bits in crc register.
10108   BIND(L_fold_128b);
10109   movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr()));
10110   if (UseAVX > 0) {
10111     vpclmulqdq(xmm2, xmm0, xmm1, 0x1);
10112     vpand(xmm3, xmm0, xmm2, 0 /* vector_len */);
10113     vpclmulqdq(xmm0, xmm0, xmm3, 0x1);
10114   } else {
10115     movdqa(xmm2, xmm0);
10116     pclmulqdq(xmm2, xmm1, 0x1);
10117     movdqa(xmm3, xmm0);
10118     pand(xmm3, xmm2);
10119     pclmulqdq(xmm0, xmm3, 0x1);
10120   }
10121   psrldq(xmm1, 8);
10122   psrldq(xmm2, 4);
10123   pxor(xmm0, xmm1);
10124   pxor(xmm0, xmm2);
10125 
10126   // 8 8-bit folds to compute 32-bit CRC.
10127   for (int j = 0; j < 4; j++) {
10128     fold_8bit_crc32(xmm0, table, xmm1, rax);
10129   }
10130   movdl(crc, xmm0); // mov 32 bits to general register
10131   for (int j = 0; j < 4; j++) {
10132     fold_8bit_crc32(crc, table, rax);
10133   }
10134 
10135   BIND(L_tail_restore);
10136   movl(len, tmp); // restore
10137   BIND(L_tail);
10138   andl(len, 0xf);
10139   jccb(Assembler::zero, L_exit);
10140 
10141   // Fold the rest of bytes
10142   align(4);
10143   BIND(L_tail_loop);
10144   movsbl(rax, Address(buf, 0)); // load byte with sign extension
10145   update_byte_crc32(crc, rax, table);
10146   increment(buf);
10147   decrementl(len);
10148   jccb(Assembler::greater, L_tail_loop);
10149 
10150   BIND(L_exit);
10151   notl(crc); // ~c
10152 }
10153 
10154 #ifdef _LP64
10155 // S. Gueron / Information Processing Letters 112 (2012) 184
10156 // Algorithm 4: Computing carry-less multiplication using a precomputed lookup table.
10157 // Input: A 32 bit value B = [byte3, byte2, byte1, byte0].
10158 // Output: the 64-bit carry-less product of B * CONST
10159 void MacroAssembler::crc32c_ipl_alg4(Register in, uint32_t n,
10160                                      Register tmp1, Register tmp2, Register tmp3) {
10161   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10162   if (n > 0) {
10163     addq(tmp3, n * 256 * 8);
10164   }
10165   //    Q1 = TABLEExt[n][B & 0xFF];
10166   movl(tmp1, in);
10167   andl(tmp1, 0x000000FF);
10168   shll(tmp1, 3);
10169   addq(tmp1, tmp3);
10170   movq(tmp1, Address(tmp1, 0));
10171 
10172   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10173   movl(tmp2, in);
10174   shrl(tmp2, 8);
10175   andl(tmp2, 0x000000FF);
10176   shll(tmp2, 3);
10177   addq(tmp2, tmp3);
10178   movq(tmp2, Address(tmp2, 0));
10179 
10180   shlq(tmp2, 8);
10181   xorq(tmp1, tmp2);
10182 
10183   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10184   movl(tmp2, in);
10185   shrl(tmp2, 16);
10186   andl(tmp2, 0x000000FF);
10187   shll(tmp2, 3);
10188   addq(tmp2, tmp3);
10189   movq(tmp2, Address(tmp2, 0));
10190 
10191   shlq(tmp2, 16);
10192   xorq(tmp1, tmp2);
10193 
10194   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10195   shrl(in, 24);
10196   andl(in, 0x000000FF);
10197   shll(in, 3);
10198   addq(in, tmp3);
10199   movq(in, Address(in, 0));
10200 
10201   shlq(in, 24);
10202   xorq(in, tmp1);
10203   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10204 }
10205 
10206 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10207                                       Register in_out,
10208                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10209                                       XMMRegister w_xtmp2,
10210                                       Register tmp1,
10211                                       Register n_tmp2, Register n_tmp3) {
10212   if (is_pclmulqdq_supported) {
10213     movdl(w_xtmp1, in_out); // modified blindly
10214 
10215     movl(tmp1, const_or_pre_comp_const_index);
10216     movdl(w_xtmp2, tmp1);
10217     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10218 
10219     movdq(in_out, w_xtmp1);
10220   } else {
10221     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3);
10222   }
10223 }
10224 
10225 // Recombination Alternative 2: No bit-reflections
10226 // T1 = (CRC_A * U1) << 1
10227 // T2 = (CRC_B * U2) << 1
10228 // C1 = T1 >> 32
10229 // C2 = T2 >> 32
10230 // T1 = T1 & 0xFFFFFFFF
10231 // T2 = T2 & 0xFFFFFFFF
10232 // T1 = CRC32(0, T1)
10233 // T2 = CRC32(0, T2)
10234 // C1 = C1 ^ T1
10235 // C2 = C2 ^ T2
10236 // CRC = C1 ^ C2 ^ CRC_C
10237 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,
10238                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10239                                      Register tmp1, Register tmp2,
10240                                      Register n_tmp3) {
10241   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10242   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10243   shlq(in_out, 1);
10244   movl(tmp1, in_out);
10245   shrq(in_out, 32);
10246   xorl(tmp2, tmp2);
10247   crc32(tmp2, tmp1, 4);
10248   xorl(in_out, tmp2); // we don't care about upper 32 bit contents here
10249   shlq(in1, 1);
10250   movl(tmp1, in1);
10251   shrq(in1, 32);
10252   xorl(tmp2, tmp2);
10253   crc32(tmp2, tmp1, 4);
10254   xorl(in1, tmp2);
10255   xorl(in_out, in1);
10256   xorl(in_out, in2);
10257 }
10258 
10259 // Set N to predefined value
10260 // Subtract from a lenght of a buffer
10261 // execute in a loop:
10262 // CRC_A = 0xFFFFFFFF, CRC_B = 0, CRC_C = 0
10263 // for i = 1 to N do
10264 //  CRC_A = CRC32(CRC_A, A[i])
10265 //  CRC_B = CRC32(CRC_B, B[i])
10266 //  CRC_C = CRC32(CRC_C, C[i])
10267 // end for
10268 // Recombine
10269 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,
10270                                        Register in_out1, Register in_out2, Register in_out3,
10271                                        Register tmp1, Register tmp2, Register tmp3,
10272                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10273                                        Register tmp4, Register tmp5,
10274                                        Register n_tmp6) {
10275   Label L_processPartitions;
10276   Label L_processPartition;
10277   Label L_exit;
10278 
10279   bind(L_processPartitions);
10280   cmpl(in_out1, 3 * size);
10281   jcc(Assembler::less, L_exit);
10282     xorl(tmp1, tmp1);
10283     xorl(tmp2, tmp2);
10284     movq(tmp3, in_out2);
10285     addq(tmp3, size);
10286 
10287     bind(L_processPartition);
10288       crc32(in_out3, Address(in_out2, 0), 8);
10289       crc32(tmp1, Address(in_out2, size), 8);
10290       crc32(tmp2, Address(in_out2, size * 2), 8);
10291       addq(in_out2, 8);
10292       cmpq(in_out2, tmp3);
10293       jcc(Assembler::less, L_processPartition);
10294     crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10295             w_xtmp1, w_xtmp2, w_xtmp3,
10296             tmp4, tmp5,
10297             n_tmp6);
10298     addq(in_out2, 2 * size);
10299     subl(in_out1, 3 * size);
10300     jmp(L_processPartitions);
10301 
10302   bind(L_exit);
10303 }
10304 #else
10305 void MacroAssembler::crc32c_ipl_alg4(Register in_out, uint32_t n,
10306                                      Register tmp1, Register tmp2, Register tmp3,
10307                                      XMMRegister xtmp1, XMMRegister xtmp2) {
10308   lea(tmp3, ExternalAddress(StubRoutines::crc32c_table_addr()));
10309   if (n > 0) {
10310     addl(tmp3, n * 256 * 8);
10311   }
10312   //    Q1 = TABLEExt[n][B & 0xFF];
10313   movl(tmp1, in_out);
10314   andl(tmp1, 0x000000FF);
10315   shll(tmp1, 3);
10316   addl(tmp1, tmp3);
10317   movq(xtmp1, Address(tmp1, 0));
10318 
10319   //    Q2 = TABLEExt[n][B >> 8 & 0xFF];
10320   movl(tmp2, in_out);
10321   shrl(tmp2, 8);
10322   andl(tmp2, 0x000000FF);
10323   shll(tmp2, 3);
10324   addl(tmp2, tmp3);
10325   movq(xtmp2, Address(tmp2, 0));
10326 
10327   psllq(xtmp2, 8);
10328   pxor(xtmp1, xtmp2);
10329 
10330   //    Q3 = TABLEExt[n][B >> 16 & 0xFF];
10331   movl(tmp2, in_out);
10332   shrl(tmp2, 16);
10333   andl(tmp2, 0x000000FF);
10334   shll(tmp2, 3);
10335   addl(tmp2, tmp3);
10336   movq(xtmp2, Address(tmp2, 0));
10337 
10338   psllq(xtmp2, 16);
10339   pxor(xtmp1, xtmp2);
10340 
10341   //    Q4 = TABLEExt[n][B >> 24 & 0xFF];
10342   shrl(in_out, 24);
10343   andl(in_out, 0x000000FF);
10344   shll(in_out, 3);
10345   addl(in_out, tmp3);
10346   movq(xtmp2, Address(in_out, 0));
10347 
10348   psllq(xtmp2, 24);
10349   pxor(xtmp1, xtmp2); // Result in CXMM
10350   //    return Q1 ^ Q2 << 8 ^ Q3 << 16 ^ Q4 << 24;
10351 }
10352 
10353 void MacroAssembler::crc32c_pclmulqdq(XMMRegister w_xtmp1,
10354                                       Register in_out,
10355                                       uint32_t const_or_pre_comp_const_index, bool is_pclmulqdq_supported,
10356                                       XMMRegister w_xtmp2,
10357                                       Register tmp1,
10358                                       Register n_tmp2, Register n_tmp3) {
10359   if (is_pclmulqdq_supported) {
10360     movdl(w_xtmp1, in_out);
10361 
10362     movl(tmp1, const_or_pre_comp_const_index);
10363     movdl(w_xtmp2, tmp1);
10364     pclmulqdq(w_xtmp1, w_xtmp2, 0);
10365     // Keep result in XMM since GPR is 32 bit in length
10366   } else {
10367     crc32c_ipl_alg4(in_out, const_or_pre_comp_const_index, tmp1, n_tmp2, n_tmp3, w_xtmp1, w_xtmp2);
10368   }
10369 }
10370 
10371 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,
10372                                      XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10373                                      Register tmp1, Register tmp2,
10374                                      Register n_tmp3) {
10375   crc32c_pclmulqdq(w_xtmp1, in_out, const_or_pre_comp_const_index_u1, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10376   crc32c_pclmulqdq(w_xtmp2, in1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, w_xtmp3, tmp1, tmp2, n_tmp3);
10377 
10378   psllq(w_xtmp1, 1);
10379   movdl(tmp1, w_xtmp1);
10380   psrlq(w_xtmp1, 32);
10381   movdl(in_out, w_xtmp1);
10382 
10383   xorl(tmp2, tmp2);
10384   crc32(tmp2, tmp1, 4);
10385   xorl(in_out, tmp2);
10386 
10387   psllq(w_xtmp2, 1);
10388   movdl(tmp1, w_xtmp2);
10389   psrlq(w_xtmp2, 32);
10390   movdl(in1, w_xtmp2);
10391 
10392   xorl(tmp2, tmp2);
10393   crc32(tmp2, tmp1, 4);
10394   xorl(in1, tmp2);
10395   xorl(in_out, in1);
10396   xorl(in_out, in2);
10397 }
10398 
10399 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,
10400                                        Register in_out1, Register in_out2, Register in_out3,
10401                                        Register tmp1, Register tmp2, Register tmp3,
10402                                        XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10403                                        Register tmp4, Register tmp5,
10404                                        Register n_tmp6) {
10405   Label L_processPartitions;
10406   Label L_processPartition;
10407   Label L_exit;
10408 
10409   bind(L_processPartitions);
10410   cmpl(in_out1, 3 * size);
10411   jcc(Assembler::less, L_exit);
10412     xorl(tmp1, tmp1);
10413     xorl(tmp2, tmp2);
10414     movl(tmp3, in_out2);
10415     addl(tmp3, size);
10416 
10417     bind(L_processPartition);
10418       crc32(in_out3, Address(in_out2, 0), 4);
10419       crc32(tmp1, Address(in_out2, size), 4);
10420       crc32(tmp2, Address(in_out2, size*2), 4);
10421       crc32(in_out3, Address(in_out2, 0+4), 4);
10422       crc32(tmp1, Address(in_out2, size+4), 4);
10423       crc32(tmp2, Address(in_out2, size*2+4), 4);
10424       addl(in_out2, 8);
10425       cmpl(in_out2, tmp3);
10426       jcc(Assembler::less, L_processPartition);
10427 
10428         push(tmp3);
10429         push(in_out1);
10430         push(in_out2);
10431         tmp4 = tmp3;
10432         tmp5 = in_out1;
10433         n_tmp6 = in_out2;
10434 
10435       crc32c_rec_alt2(const_or_pre_comp_const_index_u1, const_or_pre_comp_const_index_u2, is_pclmulqdq_supported, in_out3, tmp1, tmp2,
10436             w_xtmp1, w_xtmp2, w_xtmp3,
10437             tmp4, tmp5,
10438             n_tmp6);
10439 
10440         pop(in_out2);
10441         pop(in_out1);
10442         pop(tmp3);
10443 
10444     addl(in_out2, 2 * size);
10445     subl(in_out1, 3 * size);
10446     jmp(L_processPartitions);
10447 
10448   bind(L_exit);
10449 }
10450 #endif //LP64
10451 
10452 #ifdef _LP64
10453 // Algorithm 2: Pipelined usage of the CRC32 instruction.
10454 // Input: A buffer I of L bytes.
10455 // Output: the CRC32C value of the buffer.
10456 // Notations:
10457 // Write L = 24N + r, with N = floor (L/24).
10458 // r = L mod 24 (0 <= r < 24).
10459 // Consider I as the concatenation of A|B|C|R, where A, B, C, each,
10460 // N quadwords, and R consists of r bytes.
10461 // A[j] = I [8j+7:8j], j= 0, 1, ..., N-1
10462 // B[j] = I [N + 8j+7:N + 8j], j= 0, 1, ..., N-1
10463 // C[j] = I [2N + 8j+7:2N + 8j], j= 0, 1, ..., N-1
10464 // if r > 0 R[j] = I [3N +j], j= 0, 1, ...,r-1
10465 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10466                                           Register tmp1, Register tmp2, Register tmp3,
10467                                           Register tmp4, Register tmp5, Register tmp6,
10468                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10469                                           bool is_pclmulqdq_supported) {
10470   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10471   Label L_wordByWord;
10472   Label L_byteByByteProlog;
10473   Label L_byteByByte;
10474   Label L_exit;
10475 
10476   if (is_pclmulqdq_supported ) {
10477     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10478     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr+1);
10479 
10480     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10481     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10482 
10483     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10484     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10485     assert((CRC32C_NUM_PRECOMPUTED_CONSTANTS - 1 ) == 5, "Checking whether you declared all of the constants based on the number of \"chunks\"");
10486   } else {
10487     const_or_pre_comp_const_index[0] = 1;
10488     const_or_pre_comp_const_index[1] = 0;
10489 
10490     const_or_pre_comp_const_index[2] = 3;
10491     const_or_pre_comp_const_index[3] = 2;
10492 
10493     const_or_pre_comp_const_index[4] = 5;
10494     const_or_pre_comp_const_index[5] = 4;
10495    }
10496   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10497                     in2, in1, in_out,
10498                     tmp1, tmp2, tmp3,
10499                     w_xtmp1, w_xtmp2, w_xtmp3,
10500                     tmp4, tmp5,
10501                     tmp6);
10502   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10503                     in2, in1, in_out,
10504                     tmp1, tmp2, tmp3,
10505                     w_xtmp1, w_xtmp2, w_xtmp3,
10506                     tmp4, tmp5,
10507                     tmp6);
10508   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10509                     in2, in1, in_out,
10510                     tmp1, tmp2, tmp3,
10511                     w_xtmp1, w_xtmp2, w_xtmp3,
10512                     tmp4, tmp5,
10513                     tmp6);
10514   movl(tmp1, in2);
10515   andl(tmp1, 0x00000007);
10516   negl(tmp1);
10517   addl(tmp1, in2);
10518   addq(tmp1, in1);
10519 
10520   BIND(L_wordByWord);
10521   cmpq(in1, tmp1);
10522   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10523     crc32(in_out, Address(in1, 0), 4);
10524     addq(in1, 4);
10525     jmp(L_wordByWord);
10526 
10527   BIND(L_byteByByteProlog);
10528   andl(in2, 0x00000007);
10529   movl(tmp2, 1);
10530 
10531   BIND(L_byteByByte);
10532   cmpl(tmp2, in2);
10533   jccb(Assembler::greater, L_exit);
10534     crc32(in_out, Address(in1, 0), 1);
10535     incq(in1);
10536     incl(tmp2);
10537     jmp(L_byteByByte);
10538 
10539   BIND(L_exit);
10540 }
10541 #else
10542 void MacroAssembler::crc32c_ipl_alg2_alt2(Register in_out, Register in1, Register in2,
10543                                           Register tmp1, Register  tmp2, Register tmp3,
10544                                           Register tmp4, Register  tmp5, Register tmp6,
10545                                           XMMRegister w_xtmp1, XMMRegister w_xtmp2, XMMRegister w_xtmp3,
10546                                           bool is_pclmulqdq_supported) {
10547   uint32_t const_or_pre_comp_const_index[CRC32C_NUM_PRECOMPUTED_CONSTANTS];
10548   Label L_wordByWord;
10549   Label L_byteByByteProlog;
10550   Label L_byteByByte;
10551   Label L_exit;
10552 
10553   if (is_pclmulqdq_supported) {
10554     const_or_pre_comp_const_index[1] = *(uint32_t *)StubRoutines::_crc32c_table_addr;
10555     const_or_pre_comp_const_index[0] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 1);
10556 
10557     const_or_pre_comp_const_index[3] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 2);
10558     const_or_pre_comp_const_index[2] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 3);
10559 
10560     const_or_pre_comp_const_index[5] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 4);
10561     const_or_pre_comp_const_index[4] = *((uint32_t *)StubRoutines::_crc32c_table_addr + 5);
10562   } else {
10563     const_or_pre_comp_const_index[0] = 1;
10564     const_or_pre_comp_const_index[1] = 0;
10565 
10566     const_or_pre_comp_const_index[2] = 3;
10567     const_or_pre_comp_const_index[3] = 2;
10568 
10569     const_or_pre_comp_const_index[4] = 5;
10570     const_or_pre_comp_const_index[5] = 4;
10571   }
10572   crc32c_proc_chunk(CRC32C_HIGH, const_or_pre_comp_const_index[0], const_or_pre_comp_const_index[1], is_pclmulqdq_supported,
10573                     in2, in1, in_out,
10574                     tmp1, tmp2, tmp3,
10575                     w_xtmp1, w_xtmp2, w_xtmp3,
10576                     tmp4, tmp5,
10577                     tmp6);
10578   crc32c_proc_chunk(CRC32C_MIDDLE, const_or_pre_comp_const_index[2], const_or_pre_comp_const_index[3], is_pclmulqdq_supported,
10579                     in2, in1, in_out,
10580                     tmp1, tmp2, tmp3,
10581                     w_xtmp1, w_xtmp2, w_xtmp3,
10582                     tmp4, tmp5,
10583                     tmp6);
10584   crc32c_proc_chunk(CRC32C_LOW, const_or_pre_comp_const_index[4], const_or_pre_comp_const_index[5], is_pclmulqdq_supported,
10585                     in2, in1, in_out,
10586                     tmp1, tmp2, tmp3,
10587                     w_xtmp1, w_xtmp2, w_xtmp3,
10588                     tmp4, tmp5,
10589                     tmp6);
10590   movl(tmp1, in2);
10591   andl(tmp1, 0x00000007);
10592   negl(tmp1);
10593   addl(tmp1, in2);
10594   addl(tmp1, in1);
10595 
10596   BIND(L_wordByWord);
10597   cmpl(in1, tmp1);
10598   jcc(Assembler::greaterEqual, L_byteByByteProlog);
10599     crc32(in_out, Address(in1,0), 4);
10600     addl(in1, 4);
10601     jmp(L_wordByWord);
10602 
10603   BIND(L_byteByByteProlog);
10604   andl(in2, 0x00000007);
10605   movl(tmp2, 1);
10606 
10607   BIND(L_byteByByte);
10608   cmpl(tmp2, in2);
10609   jccb(Assembler::greater, L_exit);
10610     movb(tmp1, Address(in1, 0));
10611     crc32(in_out, tmp1, 1);
10612     incl(in1);
10613     incl(tmp2);
10614     jmp(L_byteByByte);
10615 
10616   BIND(L_exit);
10617 }
10618 #endif // LP64
10619 #undef BIND
10620 #undef BLOCK_COMMENT
10621 
10622 // Compress char[] array to byte[].
10623 //   ..\jdk\src\java.base\share\classes\java\lang\StringUTF16.java
10624 //   @HotSpotIntrinsicCandidate
10625 //   private static int compress(char[] src, int srcOff, byte[] dst, int dstOff, int len) {
10626 //     for (int i = 0; i < len; i++) {
10627 //       int c = src[srcOff++];
10628 //       if (c >>> 8 != 0) {
10629 //         return 0;
10630 //       }
10631 //       dst[dstOff++] = (byte)c;
10632 //     }
10633 //     return len;
10634 //   }
10635 void MacroAssembler::char_array_compress(Register src, Register dst, Register len,
10636   XMMRegister tmp1Reg, XMMRegister tmp2Reg,
10637   XMMRegister tmp3Reg, XMMRegister tmp4Reg,
10638   Register tmp5, Register result) {
10639   Label copy_chars_loop, return_length, return_zero, done, below_threshold;
10640 
10641   // rsi: src
10642   // rdi: dst
10643   // rdx: len
10644   // rcx: tmp5
10645   // rax: result
10646 
10647   // rsi holds start addr of source char[] to be compressed
10648   // rdi holds start addr of destination byte[]
10649   // rdx holds length
10650 
10651   assert(len != result, "");
10652 
10653   // save length for return
10654   push(len);
10655 
10656   if ((UseAVX > 2) && // AVX512
10657     VM_Version::supports_avx512vlbw() &&
10658     VM_Version::supports_bmi2()) {
10659 
10660     set_vector_masking();  // opening of the stub context for programming mask registers
10661 
10662     Label copy_32_loop, copy_loop_tail, restore_k1_return_zero;
10663 
10664     // alignement
10665     Label post_alignement;
10666 
10667     // if length of the string is less than 16, handle it in an old fashioned
10668     // way
10669     testl(len, -32);
10670     jcc(Assembler::zero, below_threshold);
10671 
10672     // First check whether a character is compressable ( <= 0xFF).
10673     // Create mask to test for Unicode chars inside zmm vector
10674     movl(result, 0x00FF);
10675     evpbroadcastw(tmp2Reg, result, Assembler::AVX_512bit);
10676 
10677     // Save k1
10678     kmovql(k3, k1);
10679 
10680     testl(len, -64);
10681     jcc(Assembler::zero, post_alignement);
10682 
10683     movl(tmp5, dst);
10684     andl(tmp5, (32 - 1));
10685     negl(tmp5);
10686     andl(tmp5, (32 - 1));
10687 
10688     // bail out when there is nothing to be done
10689     testl(tmp5, 0xFFFFFFFF);
10690     jcc(Assembler::zero, post_alignement);
10691 
10692     // ~(~0 << len), where len is the # of remaining elements to process
10693     movl(result, 0xFFFFFFFF);
10694     shlxl(result, result, tmp5);
10695     notl(result);
10696     kmovdl(k1, result);
10697 
10698     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10699     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10700     ktestd(k2, k1);
10701     jcc(Assembler::carryClear, restore_k1_return_zero);
10702 
10703     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10704 
10705     addptr(src, tmp5);
10706     addptr(src, tmp5);
10707     addptr(dst, tmp5);
10708     subl(len, tmp5);
10709 
10710     bind(post_alignement);
10711     // end of alignement
10712 
10713     movl(tmp5, len);
10714     andl(tmp5, (32 - 1));    // tail count (in chars)
10715     andl(len, ~(32 - 1));    // vector count (in chars)
10716     jcc(Assembler::zero, copy_loop_tail);
10717 
10718     lea(src, Address(src, len, Address::times_2));
10719     lea(dst, Address(dst, len, Address::times_1));
10720     negptr(len);
10721 
10722     bind(copy_32_loop);
10723     evmovdquw(tmp1Reg, Address(src, len, Address::times_2), Assembler::AVX_512bit);
10724     evpcmpuw(k2, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10725     kortestdl(k2, k2);
10726     jcc(Assembler::carryClear, restore_k1_return_zero);
10727 
10728     // All elements in current processed chunk are valid candidates for
10729     // compression. Write a truncated byte elements to the memory.
10730     evpmovwb(Address(dst, len, Address::times_1), tmp1Reg, Assembler::AVX_512bit);
10731     addptr(len, 32);
10732     jcc(Assembler::notZero, copy_32_loop);
10733 
10734     bind(copy_loop_tail);
10735     // bail out when there is nothing to be done
10736     testl(tmp5, 0xFFFFFFFF);
10737     // Restore k1
10738     kmovql(k1, k3);
10739     jcc(Assembler::zero, return_length);
10740 
10741     movl(len, tmp5);
10742 
10743     // ~(~0 << len), where len is the # of remaining elements to process
10744     movl(result, 0xFFFFFFFF);
10745     shlxl(result, result, len);
10746     notl(result);
10747 
10748     kmovdl(k1, result);
10749 
10750     evmovdquw(tmp1Reg, k1, Address(src, 0), Assembler::AVX_512bit);
10751     evpcmpuw(k2, k1, tmp1Reg, tmp2Reg, Assembler::le, Assembler::AVX_512bit);
10752     ktestd(k2, k1);
10753     jcc(Assembler::carryClear, restore_k1_return_zero);
10754 
10755     evpmovwb(Address(dst, 0), k1, tmp1Reg, Assembler::AVX_512bit);
10756     // Restore k1
10757     kmovql(k1, k3);
10758     jmp(return_length);
10759 
10760     bind(restore_k1_return_zero);
10761     // Restore k1
10762     kmovql(k1, k3);
10763     jmp(return_zero);
10764 
10765     clear_vector_masking();   // closing of the stub context for programming mask registers
10766   }
10767   if (UseSSE42Intrinsics) {
10768     Label copy_32_loop, copy_16, copy_tail;
10769 
10770     bind(below_threshold);
10771 
10772     movl(result, len);
10773 
10774     movl(tmp5, 0xff00ff00);   // create mask to test for Unicode chars in vectors
10775 
10776     // vectored compression
10777     andl(len, 0xfffffff0);    // vector count (in chars)
10778     andl(result, 0x0000000f);    // tail count (in chars)
10779     testl(len, len);
10780     jccb(Assembler::zero, copy_16);
10781 
10782     // compress 16 chars per iter
10783     movdl(tmp1Reg, tmp5);
10784     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10785     pxor(tmp4Reg, tmp4Reg);
10786 
10787     lea(src, Address(src, len, Address::times_2));
10788     lea(dst, Address(dst, len, Address::times_1));
10789     negptr(len);
10790 
10791     bind(copy_32_loop);
10792     movdqu(tmp2Reg, Address(src, len, Address::times_2));     // load 1st 8 characters
10793     por(tmp4Reg, tmp2Reg);
10794     movdqu(tmp3Reg, Address(src, len, Address::times_2, 16)); // load next 8 characters
10795     por(tmp4Reg, tmp3Reg);
10796     ptest(tmp4Reg, tmp1Reg);       // check for Unicode chars in next vector
10797     jcc(Assembler::notZero, return_zero);
10798     packuswb(tmp2Reg, tmp3Reg);    // only ASCII chars; compress each to 1 byte
10799     movdqu(Address(dst, len, Address::times_1), tmp2Reg);
10800     addptr(len, 16);
10801     jcc(Assembler::notZero, copy_32_loop);
10802 
10803     // compress next vector of 8 chars (if any)
10804     bind(copy_16);
10805     movl(len, result);
10806     andl(len, 0xfffffff8);    // vector count (in chars)
10807     andl(result, 0x00000007);    // tail count (in chars)
10808     testl(len, len);
10809     jccb(Assembler::zero, copy_tail);
10810 
10811     movdl(tmp1Reg, tmp5);
10812     pshufd(tmp1Reg, tmp1Reg, 0);   // store Unicode mask in tmp1Reg
10813     pxor(tmp3Reg, tmp3Reg);
10814 
10815     movdqu(tmp2Reg, Address(src, 0));
10816     ptest(tmp2Reg, tmp1Reg);       // check for Unicode chars in vector
10817     jccb(Assembler::notZero, return_zero);
10818     packuswb(tmp2Reg, tmp3Reg);    // only LATIN1 chars; compress each to 1 byte
10819     movq(Address(dst, 0), tmp2Reg);
10820     addptr(src, 16);
10821     addptr(dst, 8);
10822 
10823     bind(copy_tail);
10824     movl(len, result);
10825   }
10826   // compress 1 char per iter
10827   testl(len, len);
10828   jccb(Assembler::zero, return_length);
10829   lea(src, Address(src, len, Address::times_2));
10830   lea(dst, Address(dst, len, Address::times_1));
10831   negptr(len);
10832 
10833   bind(copy_chars_loop);
10834   load_unsigned_short(result, Address(src, len, Address::times_2));
10835   testl(result, 0xff00);      // check if Unicode char
10836   jccb(Assembler::notZero, return_zero);
10837   movb(Address(dst, len, Address::times_1), result);  // ASCII char; compress to 1 byte
10838   increment(len);
10839   jcc(Assembler::notZero, copy_chars_loop);
10840 
10841   // if compression succeeded, return length
10842   bind(return_length);
10843   pop(result);
10844   jmpb(done);
10845 
10846   // if compression failed, return 0
10847   bind(return_zero);
10848   xorl(result, result);
10849   addptr(rsp, wordSize);
10850 
10851   bind(done);
10852 }
10853 
10854 // Inflate byte[] array to char[].
10855 //   ..\jdk\src\java.base\share\classes\java\lang\StringLatin1.java
10856 //   @HotSpotIntrinsicCandidate
10857 //   private static void inflate(byte[] src, int srcOff, char[] dst, int dstOff, int len) {
10858 //     for (int i = 0; i < len; i++) {
10859 //       dst[dstOff++] = (char)(src[srcOff++] & 0xff);
10860 //     }
10861 //   }
10862 void MacroAssembler::byte_array_inflate(Register src, Register dst, Register len,
10863   XMMRegister tmp1, Register tmp2) {
10864   Label copy_chars_loop, done, below_threshold;
10865   // rsi: src
10866   // rdi: dst
10867   // rdx: len
10868   // rcx: tmp2
10869 
10870   // rsi holds start addr of source byte[] to be inflated
10871   // rdi holds start addr of destination char[]
10872   // rdx holds length
10873   assert_different_registers(src, dst, len, tmp2);
10874 
10875   if ((UseAVX > 2) && // AVX512
10876     VM_Version::supports_avx512vlbw() &&
10877     VM_Version::supports_bmi2()) {
10878 
10879     set_vector_masking();  // opening of the stub context for programming mask registers
10880 
10881     Label copy_32_loop, copy_tail;
10882     Register tmp3_aliased = len;
10883 
10884     // if length of the string is less than 16, handle it in an old fashioned
10885     // way
10886     testl(len, -16);
10887     jcc(Assembler::zero, below_threshold);
10888 
10889     // In order to use only one arithmetic operation for the main loop we use
10890     // this pre-calculation
10891     movl(tmp2, len);
10892     andl(tmp2, (32 - 1)); // tail count (in chars), 32 element wide loop
10893     andl(len, -32);     // vector count
10894     jccb(Assembler::zero, copy_tail);
10895 
10896     lea(src, Address(src, len, Address::times_1));
10897     lea(dst, Address(dst, len, Address::times_2));
10898     negptr(len);
10899 
10900 
10901     // inflate 32 chars per iter
10902     bind(copy_32_loop);
10903     vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_512bit);
10904     evmovdquw(Address(dst, len, Address::times_2), tmp1, Assembler::AVX_512bit);
10905     addptr(len, 32);
10906     jcc(Assembler::notZero, copy_32_loop);
10907 
10908     bind(copy_tail);
10909     // bail out when there is nothing to be done
10910     testl(tmp2, -1); // we don't destroy the contents of tmp2 here
10911     jcc(Assembler::zero, done);
10912 
10913     // Save k1
10914     kmovql(k2, k1);
10915 
10916     // ~(~0 << length), where length is the # of remaining elements to process
10917     movl(tmp3_aliased, -1);
10918     shlxl(tmp3_aliased, tmp3_aliased, tmp2);
10919     notl(tmp3_aliased);
10920     kmovdl(k1, tmp3_aliased);
10921     evpmovzxbw(tmp1, k1, Address(src, 0), Assembler::AVX_512bit);
10922     evmovdquw(Address(dst, 0), k1, tmp1, Assembler::AVX_512bit);
10923 
10924     // Restore k1
10925     kmovql(k1, k2);
10926     jmp(done);
10927 
10928     clear_vector_masking();   // closing of the stub context for programming mask registers
10929   }
10930   if (UseSSE42Intrinsics) {
10931     Label copy_16_loop, copy_8_loop, copy_bytes, copy_new_tail, copy_tail;
10932 
10933     movl(tmp2, len);
10934 
10935     if (UseAVX > 1) {
10936       andl(tmp2, (16 - 1));
10937       andl(len, -16);
10938       jccb(Assembler::zero, copy_new_tail);
10939     } else {
10940       andl(tmp2, 0x00000007);   // tail count (in chars)
10941       andl(len, 0xfffffff8);    // vector count (in chars)
10942       jccb(Assembler::zero, copy_tail);
10943     }
10944 
10945     // vectored inflation
10946     lea(src, Address(src, len, Address::times_1));
10947     lea(dst, Address(dst, len, Address::times_2));
10948     negptr(len);
10949 
10950     if (UseAVX > 1) {
10951       bind(copy_16_loop);
10952       vpmovzxbw(tmp1, Address(src, len, Address::times_1), Assembler::AVX_256bit);
10953       vmovdqu(Address(dst, len, Address::times_2), tmp1);
10954       addptr(len, 16);
10955       jcc(Assembler::notZero, copy_16_loop);
10956 
10957       bind(below_threshold);
10958       bind(copy_new_tail);
10959       if ((UseAVX > 2) &&
10960         VM_Version::supports_avx512vlbw() &&
10961         VM_Version::supports_bmi2()) {
10962         movl(tmp2, len);
10963       } else {
10964         movl(len, tmp2);
10965       }
10966       andl(tmp2, 0x00000007);
10967       andl(len, 0xFFFFFFF8);
10968       jccb(Assembler::zero, copy_tail);
10969 
10970       pmovzxbw(tmp1, Address(src, 0));
10971       movdqu(Address(dst, 0), tmp1);
10972       addptr(src, 8);
10973       addptr(dst, 2 * 8);
10974 
10975       jmp(copy_tail, true);
10976     }
10977 
10978     // inflate 8 chars per iter
10979     bind(copy_8_loop);
10980     pmovzxbw(tmp1, Address(src, len, Address::times_1));  // unpack to 8 words
10981     movdqu(Address(dst, len, Address::times_2), tmp1);
10982     addptr(len, 8);
10983     jcc(Assembler::notZero, copy_8_loop);
10984 
10985     bind(copy_tail);
10986     movl(len, tmp2);
10987 
10988     cmpl(len, 4);
10989     jccb(Assembler::less, copy_bytes);
10990 
10991     movdl(tmp1, Address(src, 0));  // load 4 byte chars
10992     pmovzxbw(tmp1, tmp1);
10993     movq(Address(dst, 0), tmp1);
10994     subptr(len, 4);
10995     addptr(src, 4);
10996     addptr(dst, 8);
10997 
10998     bind(copy_bytes);
10999   }
11000   testl(len, len);
11001   jccb(Assembler::zero, done);
11002   lea(src, Address(src, len, Address::times_1));
11003   lea(dst, Address(dst, len, Address::times_2));
11004   negptr(len);
11005 
11006   // inflate 1 char per iter
11007   bind(copy_chars_loop);
11008   load_unsigned_byte(tmp2, Address(src, len, Address::times_1));  // load byte char
11009   movw(Address(dst, len, Address::times_2), tmp2);  // inflate byte char to word
11010   increment(len);
11011   jcc(Assembler::notZero, copy_chars_loop);
11012 
11013   bind(done);
11014 }
11015 
11016 Assembler::Condition MacroAssembler::negate_condition(Assembler::Condition cond) {
11017   switch (cond) {
11018     // Note some conditions are synonyms for others
11019     case Assembler::zero:         return Assembler::notZero;
11020     case Assembler::notZero:      return Assembler::zero;
11021     case Assembler::less:         return Assembler::greaterEqual;
11022     case Assembler::lessEqual:    return Assembler::greater;
11023     case Assembler::greater:      return Assembler::lessEqual;
11024     case Assembler::greaterEqual: return Assembler::less;
11025     case Assembler::below:        return Assembler::aboveEqual;
11026     case Assembler::belowEqual:   return Assembler::above;
11027     case Assembler::above:        return Assembler::belowEqual;
11028     case Assembler::aboveEqual:   return Assembler::below;
11029     case Assembler::overflow:     return Assembler::noOverflow;
11030     case Assembler::noOverflow:   return Assembler::overflow;
11031     case Assembler::negative:     return Assembler::positive;
11032     case Assembler::positive:     return Assembler::negative;
11033     case Assembler::parity:       return Assembler::noParity;
11034     case Assembler::noParity:     return Assembler::parity;
11035   }
11036   ShouldNotReachHere(); return Assembler::overflow;
11037 }
11038 
11039 SkipIfEqual::SkipIfEqual(
11040     MacroAssembler* masm, const bool* flag_addr, bool value) {
11041   _masm = masm;
11042   _masm->cmp8(ExternalAddress((address)flag_addr), value);
11043   _masm->jcc(Assembler::equal, _label);
11044 }
11045 
11046 SkipIfEqual::~SkipIfEqual() {
11047   _masm->bind(_label);
11048 }
11049 
11050 // 32-bit Windows has its own fast-path implementation
11051 // of get_thread
11052 #if !defined(WIN32) || defined(_LP64)
11053 
11054 // This is simply a call to Thread::current()
11055 void MacroAssembler::get_thread(Register thread) {
11056   if (thread != rax) {
11057     push(rax);
11058   }
11059   LP64_ONLY(push(rdi);)
11060   LP64_ONLY(push(rsi);)
11061   push(rdx);
11062   push(rcx);
11063 #ifdef _LP64
11064   push(r8);
11065   push(r9);
11066   push(r10);
11067   push(r11);
11068 #endif
11069 
11070   MacroAssembler::call_VM_leaf_base(CAST_FROM_FN_PTR(address, Thread::current), 0);
11071 
11072 #ifdef _LP64
11073   pop(r11);
11074   pop(r10);
11075   pop(r9);
11076   pop(r8);
11077 #endif
11078   pop(rcx);
11079   pop(rdx);
11080   LP64_ONLY(pop(rsi);)
11081   LP64_ONLY(pop(rdi);)
11082   if (thread != rax) {
11083     mov(thread, rax);
11084     pop(rax);
11085   }
11086 }
11087 
11088 #endif
11089 
11090 void MacroAssembler::save_vector_registers() {
11091   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11092   if (UseAVX > 2) {
11093     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11094   }
11095 
11096   if (UseSSE == 1)  {
11097     subptr(rsp, sizeof(jdouble)*8);
11098     for (int n = 0; n < 8; n++) {
11099       movflt(Address(rsp, n*sizeof(jdouble)), as_XMMRegister(n));
11100     }
11101   } else if (UseSSE >= 2)  {
11102     if (UseAVX > 2) {
11103       push(rbx);
11104       movl(rbx, 0xffff);
11105       kmovwl(k1, rbx);
11106       pop(rbx);
11107     }
11108 #ifdef COMPILER2
11109     if (MaxVectorSize > 16) {
11110       if(UseAVX > 2) {
11111         // Save upper half of ZMM registers
11112         subptr(rsp, 32*num_xmm_regs);
11113         for (int n = 0; n < num_xmm_regs; n++) {
11114           vextractf64x4_high(Address(rsp, n*32), as_XMMRegister(n));
11115         }
11116       }
11117       assert(UseAVX > 0, "256 bit vectors are supported only with AVX");
11118       // Save upper half of YMM registers
11119       subptr(rsp, 16*num_xmm_regs);
11120       for (int n = 0; n < num_xmm_regs; n++) {
11121         vextractf128_high(Address(rsp, n*16), as_XMMRegister(n));
11122       }
11123     }
11124 #endif
11125     // Save whole 128bit (16 bytes) XMM registers
11126     subptr(rsp, 16*num_xmm_regs);
11127 #ifdef _LP64
11128     if (VM_Version::supports_evex()) {
11129       for (int n = 0; n < num_xmm_regs; n++) {
11130         vextractf32x4(Address(rsp, n*16), as_XMMRegister(n), 0);
11131       }
11132     } else {
11133       for (int n = 0; n < num_xmm_regs; n++) {
11134         movdqu(Address(rsp, n*16), as_XMMRegister(n));
11135       }
11136     }
11137 #else
11138     for (int n = 0; n < num_xmm_regs; n++) {
11139       movdqu(Address(rsp, n*16), as_XMMRegister(n));
11140     }
11141 #endif
11142   }
11143 }
11144 
11145 void MacroAssembler::restore_vector_registers() {
11146   int num_xmm_regs = LP64_ONLY(16) NOT_LP64(8);
11147   if (UseAVX > 2) {
11148     num_xmm_regs = LP64_ONLY(32) NOT_LP64(8);
11149   }
11150   if (UseSSE == 1)  {
11151     for (int n = 0; n < 8; n++) {
11152       movflt(as_XMMRegister(n), Address(rsp, n*sizeof(jdouble)));
11153     }
11154     addptr(rsp, sizeof(jdouble)*8);
11155   } else if (UseSSE >= 2)  {
11156     // Restore whole 128bit (16 bytes) XMM registers
11157 #ifdef _LP64
11158   if (VM_Version::supports_evex()) {
11159     for (int n = 0; n < num_xmm_regs; n++) {
11160       vinsertf32x4(as_XMMRegister(n), as_XMMRegister(n), Address(rsp, n*16), 0);
11161     }
11162   } else {
11163     for (int n = 0; n < num_xmm_regs; n++) {
11164       movdqu(as_XMMRegister(n), Address(rsp, n*16));
11165     }
11166   }
11167 #else
11168   for (int n = 0; n < num_xmm_regs; n++) {
11169     movdqu(as_XMMRegister(n), Address(rsp, n*16));
11170   }
11171 #endif
11172     addptr(rsp, 16*num_xmm_regs);
11173 
11174 #ifdef COMPILER2
11175     if (MaxVectorSize > 16) {
11176       // Restore upper half of YMM registers.
11177       for (int n = 0; n < num_xmm_regs; n++) {
11178         vinsertf128_high(as_XMMRegister(n), Address(rsp, n*16));
11179       }
11180       addptr(rsp, 16*num_xmm_regs);
11181       if(UseAVX > 2) {
11182         for (int n = 0; n < num_xmm_regs; n++) {
11183           vinsertf64x4_high(as_XMMRegister(n), Address(rsp, n*32));
11184         }
11185         addptr(rsp, 32*num_xmm_regs);
11186       }
11187     }
11188 #endif
11189   }
11190 }